@cuongtran001/kanna 0.61.2 → 0.61.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -703,7 +703,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
703
703
  `)!==n.readPathDeny.join(`
704
704
  `)&&(A.readPathDeny=N),R.join(`
705
705
  `)!==n.writePathDeny.join(`
706
- `)&&(A.writePathDeny=R),Object.keys(A).length===0?null:A}function E(){i(C())}function k(){i(null)}return f.jsxs(f.Fragment,{children:[f.jsx(As,{open:e,onOpenChange:N=>{N||s()},children:f.jsxs(es,{className:"max-w-2xl",children:[f.jsxs(Ms,{children:["Permissions — ",t]}),f.jsxs(Oo,{className:"space-y-5",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-sm font-medium",children:"Default action"}),f.jsxs("div",{className:"text-xs text-muted-foreground",children:["Behaviour when a tool call has no explicit allow/deny rule. ",f.jsx("strong",{children:"auto-allow"})," bypasses prompts and runs untrusted shell commands without supervision — use a worktree."]}),f.jsx(Di,{value:o,onValueChange:w,options:[{value:"ask",label:"Ask"},{value:"auto-allow",label:"Auto-allow (unsafe)"},{value:"auto-deny",label:"Auto-deny"}]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-sm font-medium",children:"Read-path deny list"}),f.jsx("div",{className:"text-xs text-muted-foreground",children:"One glob per line. The model cannot read paths matching any entry. Defaults shown below — edit to add or remove."}),f.jsx("textarea",{value:c,onChange:N=>u(N.target.value),rows:8,className:"w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-xs",spellCheck:!1})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-sm font-medium",children:"Write-path deny list"}),f.jsx("div",{className:"text-xs text-muted-foreground",children:"One glob per line. The model cannot edit or write paths matching any entry."}),f.jsx("textarea",{value:m,onChange:N=>h(N.target.value),rows:8,className:"w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-xs",spellCheck:!1})]})]}),f.jsxs(Sa,{className:"justify-between",children:[f.jsx(Ue,{variant:"ghost",onClick:k,children:"Reset to defaults"}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx(Ue,{variant:"ghost",onClick:s,children:"Cancel"}),f.jsx(Ue,{onClick:E,children:"Apply"})]})]})]})}),f.jsx(As,{open:g,onOpenChange:N=>{N||(b(!1),_(null))},children:f.jsxs(es,{className:"max-w-md",children:[f.jsx(Ms,{children:"Enable auto-allow for this chat?"}),f.jsxs(Oo,{className:"space-y-3 text-sm",children:[f.jsx("p",{children:"Auto-allow disables tool-call prompts. The model can run shell commands, write files, and edit code without asking. Read/write deny lists still apply."}),f.jsx("p",{className:"text-warning",children:"Use a worktree for risky tasks."})]}),f.jsxs(Sa,{className:"justify-end gap-2",children:[f.jsx(Ue,{variant:"ghost",onClick:()=>{b(!1),_(null)},children:"Cancel"}),f.jsx(Ue,{variant:"destructive",onClick:()=>{x&&l(x),b(!1),_(null)},children:"Enable auto-allow"})]})]})})]})}function kQ({open:e,shareUrl:t,onOpenChange:n,onOpenLink:r,onCopyLink:i}){const[s,o]=v.useState(!1);v.useEffect(()=>{e||o(!1)},[e,t]);const l=async()=>{await i()&&(o(!0),window.setTimeout(()=>{o(!1)},2e3))};return f.jsx(As,{open:e,onOpenChange:n,children:f.jsxs(es,{size:"md",children:[f.jsxs(MO,{children:[f.jsx(Ms,{children:"Shared Link"}),f.jsx(af,{children:"Shared links are snapshots in time and contain all attachments, tool calls and history. Be mindful of sensitive info."})]}),f.jsx(Oo,{className:"space-y-3",children:f.jsxs("div",{className:"flex w-full items-center gap-2 rounded-2xl border border-border bg-muted/40 pl-4 px-3 py-2.5",children:[f.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-sm text-foreground",children:t}),f.jsx("button",{type:"button",onClick:()=>void l(),title:s?"Copied":"Copy link","aria-label":s?"Copied":"Copy link",className:"flex flex-shrink-0 items-center justify-center rounded-lg text-logo hover:text-logo/60 transition-colors hover:bg-background hover:text-foreground",children:s?f.jsx(_i,{className:"h-4 w-4 text-emerald-400"}):f.jsx(Pl,{className:"h-4 w-4"})})]})}),f.jsx(Sa,{children:f.jsxs(FY,{type:"button",onClick:r,children:[f.jsx(ik,{className:"mr-2 h-4 w-4"}),"Open"]})})]})})}const EQ={defaultAction:"ask",bash:{autoAllowVerbs:["ls","pwd","git status","git diff","git log"]},readPathDeny:["~/.ssh","~/.aws","~/.gcp","~/.config/gh","~/.claude","~/.kanna","~/Library/Keychains","/etc/shadow","/etc/sudoers","~/.gnupg","~/.gitconfig","**/.git/config","~/.npmrc","~/.netrc","~/.docker/config.json","**/.env","**/.env.*","**/credentials*","**/*.pem","**/*.key","**/id_rsa*","**/id_ed25519*"],writePathDeny:["/etc/**","/usr/**","/System/**","~/.ssh/**","~/.aws/**","~/.config/gh/**","~/.claude/**","~/.kanna/**","~/.gnupg/**","~/.gitconfig","**/.git/config"],toolDenyList:[{tool:"mcp__kanna__bash",pattern:"rm\\s+-rf\\s+(/|~|\\$HOME)(?:\\b|$|\\s)"},{tool:"mcp__kanna__bash",pattern:"git\\s+push\\b.*--force"}],toolAllowList:[]},$n=v.forwardRef(({className:e,type:t,...n},r)=>f.jsx("input",{ref:r,type:t,className:he("flex w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",e),...n}));$n.displayName="Input";const m3=v.createContext(null);function TQ({children:e}){const[t,n]=v.useState(null),[r,i]=v.useState(""),s=v.useRef(null);v.useEffect(()=>{(t==null?void 0:t.kind)==="prompt"&&(i(t.options.initialValue??""),setTimeout(()=>{var b,x;(b=s.current)==null||b.focus(),(x=s.current)==null||x.select()},0))},[t]);const o=v.useCallback(()=>{n(null),i("")},[]),l=v.useCallback(()=>{t&&(t.kind==="confirm"?t.resolve(!1):t.kind==="prompt"?t.resolve(null):t.resolve(),o())},[o,t]),c=v.useCallback(()=>{t&&(t.kind==="confirm"?t.resolve(!0):t.kind==="prompt"?t.resolve(r.trim()||null):t.resolve(),o())},[o,t,r]),u=v.useCallback(b=>new Promise(x=>{n({kind:"confirm",options:b,resolve:x})}),[]),m=v.useCallback(b=>new Promise(x=>{n({kind:"prompt",options:b,resolve:x})}),[]),h=v.useCallback(b=>new Promise(x=>{n({kind:"alert",options:b,resolve:x})}),[]),g=v.useMemo(()=>({confirm:u,prompt:m,alert:h}),[h,u,m]);return f.jsxs(m3.Provider,{value:g,children:[e,f.jsx(As,{open:t!==null,onOpenChange:b=>{b||!t||l()},children:f.jsx(es,{size:"sm",onKeyDown:b=>{b.key!=="Enter"||b.shiftKey||!t||t.kind!=="confirm"||(b.preventDefault(),c())},children:t?f.jsxs(f.Fragment,{children:[f.jsxs(Oo,{className:"space-y-4",children:[f.jsx(Ms,{children:t.options.title}),t.options.description?f.jsx(af,{children:t.options.description}):null,t.kind==="prompt"?f.jsx($n,{ref:s,type:"text",value:r,onChange:b=>i(b.target.value),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),c())},placeholder:t.options.placeholder}):null]}),f.jsxs(Sa,{children:[f.jsx(Ue,{variant:"ghost",size:"sm",onClick:l,className:t.kind==="alert"?"hidden":void 0,children:"cancelLabel"in t.options?t.options.cancelLabel??"Cancel":"Cancel"}),f.jsx(Ue,{variant:t.kind==="confirm"?t.options.confirmVariant??"default":"secondary",size:"sm",onClick:c,disabled:t.kind==="prompt"&&!r.trim(),children:t.kind==="alert"?t.options.closeLabel??"OK":"confirmLabel"in t.options?t.options.confirmLabel??"Confirm":"Confirm"})]})]}):null})})]})}function rp(){const e=v.useContext(m3);if(!e)throw new Error("useAppDialog must be used within AppDialogProvider");return e}const Mk=v.forwardRef(({className:e,...t},n)=>f.jsx("div",{ref:n,className:he("bg-card text-card-foreground",e),...t}));Mk.displayName="Card";const Lk=v.forwardRef(({className:e,...t},n)=>f.jsx("div",{ref:n,className:he("flex flex-col space-y-1.5 p-2",e),...t}));Lk.displayName="CardHeader";const p3=v.forwardRef(({className:e,...t},n)=>f.jsx("h3",{ref:n,className:he("text-2xl font-semibold leading-none tracking-tight",e),...t}));p3.displayName="CardTitle";const g3=v.forwardRef(({className:e,...t},n)=>f.jsx("p",{ref:n,className:he("text-sm text-muted-foreground",e),...t}));g3.displayName="CardDescription";const jk=v.forwardRef(({className:e,...t},n)=>f.jsx("div",{ref:n,className:he("p-6 pt-0",e),...t}));jk.displayName="CardContent";const NQ=v.forwardRef(({className:e,...t},n)=>f.jsx("div",{ref:n,className:he("flex items-center p-6 pt-0",e),...t}));NQ.displayName="CardFooter";const RQ="modulepreload",AQ=function(e){return"/"+e},MM={},K=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let o=function(u){return Promise.all(u.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));i=o(n.map(u=>{if(u=AQ(u),u in MM)return;MM[u]=!0;const m=u.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":RQ,m||(g.as="script"),g.crossOrigin="",g.href=u,c&&g.setAttribute("nonce",c),document.head.appendChild(g),m)return new Promise((b,x)=>{g.addEventListener("load",b),g.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${u}`)))})}))}function s(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&s(l.reason);return t().catch(s)})},MQ=v.lazy(()=>K(()=>import("./index-CEDSh4y6.js"),[]).then(e=>({default:e.Toaster})));function LQ(){return f.jsx(v.Suspense,{fallback:null,children:f.jsx(MQ,{position:"bottom-right",theme:"system",closeButton:!0,duration:6e3})})}const jQ="0.61.2",DQ={version:jQ},Jn="Kanna",LM="kanna",IQ=".kanna",PQ=".kanna-dev",OQ="KANNA_RUNTIME_PROFILE",Dk=`kanna/${DQ.version}`,zQ="[kanna]",BQ=`~/${Jn}`;function $y(){var t;return(t=globalThis.process)==null?void 0:t.env}function FQ(e=$y()){var t;return((t=e==null?void 0:e[OQ])==null?void 0:t.trim().toLowerCase())==="dev"?"dev":"prod"}function $Q(e=$y()){return FQ(e)==="dev"?PQ:IQ}function HQ(e=$y()){return`~/${$Q(e)}`}function UQ(e=$y()){return`${HQ(e)}/keybindings.json`}function qg(e){return e?`${LM} ${e}`:LM}const jM=e=>{let t;const n=new Set,r=(u,m)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const g=t;t=m??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(b=>b(t,g))}},i=()=>t,l={setState:r,getState:i,getInitialState:()=>c,subscribe:u=>(n.add(u),()=>n.delete(u))},c=t=e(r,i,l);return l},VQ=(e=>e?jM(e):jM),WQ=e=>e;function GQ(e,t=WQ){const n=Cn.useSyncExternalStore(e.subscribe,Cn.useCallback(()=>t(e.getState()),[e,t]),Cn.useCallback(()=>t(e.getInitialState()),[e,t]));return Cn.useDebugValue(n),n}const qQ=e=>{const t=VQ(e),n=r=>GQ(t,r);return Object.assign(n,t),n},oo=(e=>qQ),v3="always",b3="funk",KQ=[{value:"blow",label:"Blow"},{value:"bottle",label:"Bottle"},{value:"frog",label:"Frog"},{value:"funk",label:"Funk"},{value:"glass",label:"Glass"},{value:"ping",label:"Ping"},{value:"pop",label:"Pop"},{value:"purr",label:"Purr"},{value:"tink",label:"Tink"}];function YQ(e){switch(e){case"never":case"unfocused":case"always":return e;default:return v3}}function XQ(e){switch(e){case"blow":case"bottle":case"frog":case"funk":case"glass":case"ping":case"pop":case"purr":case"tink":return e;default:return b3}}const Mc=oo()(e=>({chatSoundPreference:v3,chatSoundId:b3,setChatSoundPreference:t=>e({chatSoundPreference:YQ(t)}),setChatSoundId:t=>e({chatSoundId:XQ(t)})})),QQ={blow:"/chat-sounds/Blow.mp3",bottle:"/chat-sounds/Bottle.mp3",frog:"/chat-sounds/Frog.mp3",funk:"/chat-sounds/Funk.mp3",glass:"/chat-sounds/Glass.mp3",ping:"/chat-sounds/Ping.mp3",pop:"/chat-sounds/Pop.mp3",purr:"/chat-sounds/Purr.mp3",tink:"/chat-sounds/Tink.mp3"};function ZQ(e=document){return e.visibilityState!=="visible"||!e.hasFocus()}function JQ(e){const t=new Audio(QQ[e]);return t.preload="auto",t.play()}async function US(e,t){if(t<=0)return;const n=Array.from({length:t},(r,i)=>new Promise(s=>{window.setTimeout(()=>{JQ(e).catch(()=>{}).finally(()=>s())},i*90)}));await Promise.all(n)}function eZ(e,t=document){return e==="never"?!1:e==="always"?!0:ZQ(t)}function tZ(e){return e.projectGroups.reduce((t,n)=>t+n.chats.reduce((r,i)=>r+(i.unread?1:0)+(i.status==="waiting_for_user"?1:0),0),0)}function DM(e){let t=0;const n=new Set;for(const r of e.projectGroups)for(const i of r.chats)i.unread&&(t+=1),i.status==="waiting_for_user"&&n.add(i.chatId);return{unreadCount:t,waitingChatIds:n}}function nZ(e,t){if(!e)return 0;const n=DM(e),r=DM(t),i=Math.max(0,r.unreadCount-n.unreadCount);let s=0;for(const o of r.waitingChatIds)n.waitingChatIds.has(o)||(s+=1);return i+s}function VS(e){return e.split(/[\s_-]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}const rZ=[/^(?:\/usr\/bin\/env\s+)?(?:\/bin\/)?(?:bash|zsh|sh)\s+(?:-[a-zA-Z]*c|-c)\s+(['"])([\s\S]*)\1$/,/^(?:\/usr\/bin\/env\s+)?(?:\/bin\/)?(?:bash|zsh|sh)\s+(?:-[a-zA-Z]*c|-c)\s+(.+)$/,/^(?:\/usr\/bin\/env\s+)?(?:cmd(?:\.exe)?)\s+\/c\s+(['"])([\s\S]*)\1$/i,/^(?:\/usr\/bin\/env\s+)?(?:cmd(?:\.exe)?)\s+\/c\s+(.+)$/i,/^(?:\/usr\/bin\/env\s+)?(?:powershell(?:\.exe)?|pwsh)\s+(?:-NoProfile\s+)?-Command\s+(['"])([\s\S]*)\1$/i,/^(?:\/usr\/bin\/env\s+)?(?:powershell(?:\.exe)?|pwsh)\s+(?:-NoProfile\s+)?-Command\s+(.+)$/i];function iZ(e){const t=e.trim();for(const n of rZ){const r=t.match(n);if(!r)continue;const i=(r[2]??r[1]??"").trim();if(i)return i}return t}function Ik(e){return e.split("/").pop()||e}const sZ=1440*6e4;function oZ(e,t){const n=Math.max(0,t-e),r=Math.floor(n/1e3),i=Math.floor(r/3600),s=Math.floor(r%3600/60),o=r%60;return i>0?`${i}h ${s}m`:s>0?`${s}m ${o}s`:`${o}s`}function aZ(e){const t=new Date(e),n=t.getHours().toString().padStart(2,"0"),r=t.getMinutes().toString().padStart(2,"0");return`${n}:${r}`}function lZ(e,t){if(e===void 0)return null;const n=Math.max(0,t-e),r=6e4,i=60*r,s=sZ,o=7*s;return n<r?"now":n<i?`${Math.floor(n/r)}m`:n<s?`${Math.floor(n/i)}h`:n<o?`${Math.floor(n/s)}d`:`${Math.floor(n/o)}w`}function cZ(e){return e.lastMessageAt??e._creationTime}const Pk=1e3,Xv=60*Pk,yd=60*Xv,X_=24*yd;function Sl(e){const t=Math.max(0,e);if(t<Xv)return`${Math.floor(t/Pk)}s`;if(t<yd)return`${Math.floor(t/Xv)}m`;if(t<X_){const i=Math.floor(t/yd),s=Math.floor(t%yd/Xv);return s===0?`${i}h`:`${i}h ${s}m`}const n=Math.floor(t/X_),r=Math.floor(t%X_/yd);return r===0?`${n}d`:`${n}d ${r}h`}function WS(e){const t=Math.max(0,e);if(t>=yd)return Sl(t);const n=Math.floor(t/Pk),r=Math.floor(n/60),i=n%60;return`${r}:${i.toString().padStart(2,"0")}`}function GS(e){switch(e){case"idle":return"Idle";case"starting":return"Starting";case"running":return"Running";case"waiting_for_user":return"Waiting";case"failed":return"Failed"}}function IM(e){switch(e){case"running":return"active";case"waiting_for_user":return"attention";case"failed":return"destructive";case"idle":case"starting":default:return"muted"}}function PM(e){switch(e){case"active":return"text-emerald-500 dark:text-emerald-400";case"attention":return"text-amber-500 dark:text-amber-400";case"destructive":return"text-destructive";case"muted":default:return"text-muted-foreground"}}function Ok(e){const t=e+"CollectionProvider",[n,r]=Aa(t),[i,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),o=_=>{const{scope:w,children:C}=_,E=Cn.useRef(null),k=Cn.useRef(new Map).current;return f.jsx(i,{scope:w,itemMap:k,collectionRef:E,children:C})};o.displayName=t;const l=e+"CollectionSlot",c=$c(l),u=Cn.forwardRef((_,w)=>{const{scope:C,children:E}=_,k=s(l,C),N=wn(w,k.collectionRef);return f.jsx(c,{ref:N,children:E})});u.displayName=l;const m=e+"CollectionItemSlot",h="data-radix-collection-item",g=$c(m),b=Cn.forwardRef((_,w)=>{const{scope:C,children:E,...k}=_,N=Cn.useRef(null),R=wn(w,N),A=s(m,C);return Cn.useEffect(()=>(A.itemMap.set(N,{ref:N,...k}),()=>void A.itemMap.delete(N))),f.jsx(g,{[h]:"",ref:R,children:E})});b.displayName=m;function x(_){const w=s(e+"CollectionConsumer",_);return Cn.useCallback(()=>{const E=w.collectionRef.current;if(!E)return[];const k=Array.from(E.querySelectorAll(`[${h}]`));return Array.from(w.itemMap.values()).sort((A,M)=>k.indexOf(A.ref.current)-k.indexOf(M.ref.current))},[w.collectionRef,w.itemMap])}return[{Provider:o,Slot:u,ItemSlot:b},x,r]}var uZ=v.createContext(void 0);function zk(e){const t=v.useContext(uZ);return e||t||"ltr"}var Q_="rovingFocusGroup.onEntryFocus",dZ={bubbles:!1,cancelable:!0},ip="RovingFocusGroup",[qS,y3,fZ]=Ok(ip),[hZ,x3]=Aa(ip,[fZ]),[mZ,pZ]=hZ(ip),_3=v.forwardRef((e,t)=>f.jsx(qS.Provider,{scope:e.__scopeRovingFocusGroup,children:f.jsx(qS.Slot,{scope:e.__scopeRovingFocusGroup,children:f.jsx(gZ,{...e,ref:t})})}));_3.displayName=ip;var gZ=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:s,currentTabStopId:o,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:c,onEntryFocus:u,preventScrollOnEntryFocus:m=!1,...h}=e,g=v.useRef(null),b=wn(t,g),x=zk(s),[_,w]=Pd({prop:o,defaultProp:l??null,onChange:c,caller:ip}),[C,E]=v.useState(!1),k=Js(u),N=y3(n),R=v.useRef(!1),[A,M]=v.useState(0);return v.useEffect(()=>{const L=g.current;if(L)return L.addEventListener(Q_,k),()=>L.removeEventListener(Q_,k)},[k]),f.jsx(mZ,{scope:n,orientation:r,dir:x,loop:i,currentTabStopId:_,onItemFocus:v.useCallback(L=>w(L),[w]),onItemShiftTab:v.useCallback(()=>E(!0),[]),onFocusableItemAdd:v.useCallback(()=>M(L=>L+1),[]),onFocusableItemRemove:v.useCallback(()=>M(L=>L-1),[]),children:f.jsx(rn.div,{tabIndex:C||A===0?-1:0,"data-orientation":r,...h,ref:b,style:{outline:"none",...e.style},onMouseDown:rt(e.onMouseDown,()=>{R.current=!0}),onFocus:rt(e.onFocus,L=>{const F=!R.current;if(L.target===L.currentTarget&&F&&!C){const D=new CustomEvent(Q_,dZ);if(L.currentTarget.dispatchEvent(D),!D.defaultPrevented){const O=N().filter(B=>B.focusable),z=O.find(B=>B.active),P=O.find(B=>B.id===_),H=[z,P,...O].filter(Boolean).map(B=>B.ref.current);C3(H,m)}}R.current=!1}),onBlur:rt(e.onBlur,()=>E(!1))})})}),w3="RovingFocusGroupItem",S3=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:s,children:o,...l}=e,c=xa(),u=s||c,m=pZ(w3,n),h=m.currentTabStopId===u,g=y3(n),{onFocusableItemAdd:b,onFocusableItemRemove:x,currentTabStopId:_}=m;return v.useEffect(()=>{if(r)return b(),()=>x()},[r,b,x]),f.jsx(qS.ItemSlot,{scope:n,id:u,focusable:r,active:i,children:f.jsx(rn.span,{tabIndex:h?0:-1,"data-orientation":m.orientation,...l,ref:t,onMouseDown:rt(e.onMouseDown,w=>{r?m.onItemFocus(u):w.preventDefault()}),onFocus:rt(e.onFocus,()=>m.onItemFocus(u)),onKeyDown:rt(e.onKeyDown,w=>{if(w.key==="Tab"&&w.shiftKey){m.onItemShiftTab();return}if(w.target!==w.currentTarget)return;const C=yZ(w,m.orientation,m.dir);if(C!==void 0){if(w.metaKey||w.ctrlKey||w.altKey||w.shiftKey)return;w.preventDefault();let k=g().filter(N=>N.focusable).map(N=>N.ref.current);if(C==="last")k.reverse();else if(C==="prev"||C==="next"){C==="prev"&&k.reverse();const N=k.indexOf(w.currentTarget);k=m.loop?xZ(k,N+1):k.slice(N+1)}setTimeout(()=>C3(k))}}),children:typeof o=="function"?o({isCurrentTabStop:h,hasTabStop:_!=null}):o})})});S3.displayName=w3;var vZ={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function bZ(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function yZ(e,t,n){const r=bZ(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return vZ[r]}function C3(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function xZ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var _Z=_3,wZ=S3,KS=["Enter"," "],SZ=["ArrowDown","PageUp","Home"],k3=["ArrowUp","PageDown","End"],CZ=[...SZ,...k3],kZ={ltr:[...KS,"ArrowRight"],rtl:[...KS,"ArrowLeft"]},EZ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},sp="Menu",[gm,TZ,NZ]=Ok(sp),[ru,E3]=Aa(sp,[NZ,Ul,x3]),Hy=Ul(),T3=x3(),[RZ,iu]=ru(sp),[AZ,op]=ru(sp),N3=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:s,modal:o=!0}=e,l=Hy(t),[c,u]=v.useState(null),m=v.useRef(!1),h=Js(s),g=zk(i);return v.useEffect(()=>{const b=()=>{m.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>m.current=!1;return document.addEventListener("keydown",b,{capture:!0}),()=>{document.removeEventListener("keydown",b,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.jsx(Iy,{...l,children:f.jsx(RZ,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:u,children:f.jsx(AZ,{scope:t,onClose:v.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:m,dir:g,modal:o,children:r})})})};N3.displayName=sp;var MZ="MenuAnchor",Bk=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=Hy(n);return f.jsx(tp,{...i,...r,ref:t})});Bk.displayName=MZ;var Fk="MenuPortal",[LZ,R3]=ru(Fk,{forceMount:void 0}),A3=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,s=iu(Fk,t);return f.jsx(LZ,{scope:t,forceMount:n,children:f.jsx(Is,{present:n||s.open,children:f.jsx(of,{asChild:!0,container:i,children:r})})})};A3.displayName=Fk;var Ns="MenuContent",[jZ,$k]=ru(Ns),M3=v.forwardRef((e,t)=>{const n=R3(Ns,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=iu(Ns,e.__scopeMenu),o=op(Ns,e.__scopeMenu);return f.jsx(gm.Provider,{scope:e.__scopeMenu,children:f.jsx(Is,{present:r||s.open,children:f.jsx(gm.Slot,{scope:e.__scopeMenu,children:o.modal?f.jsx(DZ,{...i,ref:t}):f.jsx(IZ,{...i,ref:t})})})})}),DZ=v.forwardRef((e,t)=>{const n=iu(Ns,e.__scopeMenu),r=v.useRef(null),i=wn(t,r);return v.useEffect(()=>{const s=r.current;if(s)return Ry(s)},[]),f.jsx(Hk,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:rt(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),IZ=v.forwardRef((e,t)=>{const n=iu(Ns,e.__scopeMenu);return f.jsx(Hk,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),PZ=$c("MenuContent.ScrollLock"),Hk=v.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:u,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:b,disableOutsideScroll:x,..._}=e,w=iu(Ns,n),C=op(Ns,n),E=Hy(n),k=T3(n),N=TZ(n),[R,A]=v.useState(null),M=v.useRef(null),L=wn(t,M,w.onContentChange),F=v.useRef(0),D=v.useRef(""),O=v.useRef(0),z=v.useRef(null),P=v.useRef("right"),$=v.useRef(0),H=x?Jm:v.Fragment,B=x?{as:PZ,allowPinchZoom:!0}:void 0,V=Q=>{var ne,se;const I=D.current+Q,W=N().filter(le=>!le.disabled),te=document.activeElement,U=(ne=W.find(le=>le.ref.current===te))==null?void 0:ne.textValue,fe=W.map(le=>le.textValue),ae=KZ(fe,I,U),ee=(se=W.find(le=>le.textValue===ae))==null?void 0:se.ref.current;(function le(ue){D.current=ue,window.clearTimeout(F.current),ue!==""&&(F.current=window.setTimeout(()=>le(""),1e3))})(I),ee&&setTimeout(()=>ee.focus())};v.useEffect(()=>()=>window.clearTimeout(F.current),[]),Ty();const G=v.useCallback(Q=>{var W,te;return P.current===((W=z.current)==null?void 0:W.side)&&XZ(Q,(te=z.current)==null?void 0:te.area)},[]);return f.jsx(jZ,{scope:n,searchRef:D,onItemEnter:v.useCallback(Q=>{G(Q)&&Q.preventDefault()},[G]),onItemLeave:v.useCallback(Q=>{var I;G(Q)||((I=M.current)==null||I.focus(),A(null))},[G]),onTriggerLeave:v.useCallback(Q=>{G(Q)&&Q.preventDefault()},[G]),pointerGraceTimerRef:O,onPointerGraceIntentChange:v.useCallback(Q=>{z.current=Q},[]),children:f.jsx(H,{...B,children:f.jsx(Zm,{asChild:!0,trapped:i,onMountAutoFocus:rt(s,Q=>{var I;Q.preventDefault(),(I=M.current)==null||I.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:f.jsx(sf,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:u,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:b,children:f.jsx(_Z,{asChild:!0,...k,dir:C.dir,orientation:"vertical",loop:r,currentTabStopId:R,onCurrentTabStopIdChange:A,onEntryFocus:rt(c,Q=>{C.isUsingKeyboardRef.current||Q.preventDefault()}),preventScrollOnEntryFocus:!0,children:f.jsx(Py,{role:"menu","aria-orientation":"vertical","data-state":q3(w.open),"data-radix-menu-content":"",dir:C.dir,...E,..._,ref:L,style:{outline:"none",..._.style},onKeyDown:rt(_.onKeyDown,Q=>{const W=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,te=Q.ctrlKey||Q.altKey||Q.metaKey,U=Q.key.length===1;W&&(Q.key==="Tab"&&Q.preventDefault(),!te&&U&&V(Q.key));const fe=M.current;if(Q.target!==fe||!CZ.includes(Q.key))return;Q.preventDefault();const ee=N().filter(ne=>!ne.disabled).map(ne=>ne.ref.current);k3.includes(Q.key)&&ee.reverse(),GZ(ee)}),onBlur:rt(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),D.current="")}),onPointerMove:rt(e.onPointerMove,vm(Q=>{const I=Q.target,W=$.current!==Q.clientX;if(Q.currentTarget.contains(I)&&W){const te=Q.clientX>$.current?"right":"left";P.current=te,$.current=Q.clientX}}))})})})})})})});M3.displayName=Ns;var OZ="MenuGroup",Uk=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.jsx(rn.div,{role:"group",...r,ref:t})});Uk.displayName=OZ;var zZ="MenuLabel",L3=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.jsx(rn.div,{...r,ref:t})});L3.displayName=zZ;var jb="MenuItem",OM="menu.itemSelect",Uy=v.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,s=v.useRef(null),o=op(jb,e.__scopeMenu),l=$k(jb,e.__scopeMenu),c=wn(t,s),u=v.useRef(!1),m=()=>{const h=s.current;if(!n&&h){const g=new CustomEvent(OM,{bubbles:!0,cancelable:!0});h.addEventListener(OM,b=>r==null?void 0:r(b),{once:!0}),Z5(h,g),g.defaultPrevented?u.current=!1:o.onClose()}};return f.jsx(j3,{...i,ref:c,disabled:n,onClick:rt(e.onClick,m),onPointerDown:h=>{var g;(g=e.onPointerDown)==null||g.call(e,h),u.current=!0},onPointerUp:rt(e.onPointerUp,h=>{var g;u.current||(g=h.currentTarget)==null||g.click()}),onKeyDown:rt(e.onKeyDown,h=>{const g=l.searchRef.current!=="";n||g&&h.key===" "||KS.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});Uy.displayName=jb;var j3=v.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...s}=e,o=$k(jb,n),l=T3(n),c=v.useRef(null),u=wn(t,c),[m,h]=v.useState(!1),[g,b]=v.useState("");return v.useEffect(()=>{const x=c.current;x&&b((x.textContent??"").trim())},[s.children]),f.jsx(gm.ItemSlot,{scope:n,disabled:r,textValue:i??g,children:f.jsx(wZ,{asChild:!0,...l,focusable:!r,children:f.jsx(rn.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:u,onPointerMove:rt(e.onPointerMove,vm(x=>{r?o.onItemLeave(x):(o.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:rt(e.onPointerLeave,vm(x=>o.onItemLeave(x))),onFocus:rt(e.onFocus,()=>h(!0)),onBlur:rt(e.onBlur,()=>h(!1))})})})}),BZ="MenuCheckboxItem",D3=v.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return f.jsx(B3,{scope:e.__scopeMenu,checked:n,children:f.jsx(Uy,{role:"menuitemcheckbox","aria-checked":Db(n)?"mixed":n,...i,ref:t,"data-state":Wk(n),onSelect:rt(i.onSelect,()=>r==null?void 0:r(Db(n)?!0:!n),{checkForDefaultPrevented:!1})})})});D3.displayName=BZ;var I3="MenuRadioGroup",[FZ,$Z]=ru(I3,{value:void 0,onValueChange:()=>{}}),P3=v.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,s=Js(r);return f.jsx(FZ,{scope:e.__scopeMenu,value:n,onValueChange:s,children:f.jsx(Uk,{...i,ref:t})})});P3.displayName=I3;var O3="MenuRadioItem",z3=v.forwardRef((e,t)=>{const{value:n,...r}=e,i=$Z(O3,e.__scopeMenu),s=n===i.value;return f.jsx(B3,{scope:e.__scopeMenu,checked:s,children:f.jsx(Uy,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":Wk(s),onSelect:rt(r.onSelect,()=>{var o;return(o=i.onValueChange)==null?void 0:o.call(i,n)},{checkForDefaultPrevented:!1})})})});z3.displayName=O3;var Vk="MenuItemIndicator",[B3,HZ]=ru(Vk,{checked:!1}),F3=v.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,s=HZ(Vk,n);return f.jsx(Is,{present:r||Db(s.checked)||s.checked===!0,children:f.jsx(rn.span,{...i,ref:t,"data-state":Wk(s.checked)})})});F3.displayName=Vk;var UZ="MenuSeparator",$3=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.jsx(rn.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});$3.displayName=UZ;var VZ="MenuArrow",H3=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=Hy(n);return f.jsx(Oy,{...i,...r,ref:t})});H3.displayName=VZ;var WZ="MenuSub",[NTe,U3]=ru(WZ),Ph="MenuSubTrigger",V3=v.forwardRef((e,t)=>{const n=iu(Ph,e.__scopeMenu),r=op(Ph,e.__scopeMenu),i=U3(Ph,e.__scopeMenu),s=$k(Ph,e.__scopeMenu),o=v.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=s,u={__scopeMenu:e.__scopeMenu},m=v.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return v.useEffect(()=>m,[m]),v.useEffect(()=>{const h=l.current;return()=>{window.clearTimeout(h),c(null)}},[l,c]),f.jsx(Bk,{asChild:!0,...u,children:f.jsx(j3,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":q3(n.open),...e,ref:hk(t,i.onTriggerChange),onClick:h=>{var g;(g=e.onClick)==null||g.call(e,h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:rt(e.onPointerMove,vm(h=>{s.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!n.open&&!o.current&&(s.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:rt(e.onPointerLeave,vm(h=>{var b,x;m();const g=(b=n.content)==null?void 0:b.getBoundingClientRect();if(g){const _=(x=n.content)==null?void 0:x.dataset.side,w=_==="right",C=w?-5:5,E=g[w?"left":"right"],k=g[w?"right":"left"];s.onPointerGraceIntentChange({area:[{x:h.clientX+C,y:h.clientY},{x:E,y:g.top},{x:k,y:g.top},{x:k,y:g.bottom},{x:E,y:g.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(h),h.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:rt(e.onKeyDown,h=>{var b;const g=s.searchRef.current!=="";e.disabled||g&&h.key===" "||kZ[r.dir].includes(h.key)&&(n.onOpenChange(!0),(b=n.content)==null||b.focus(),h.preventDefault())})})})});V3.displayName=Ph;var W3="MenuSubContent",G3=v.forwardRef((e,t)=>{const n=R3(Ns,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=iu(Ns,e.__scopeMenu),o=op(Ns,e.__scopeMenu),l=U3(W3,e.__scopeMenu),c=v.useRef(null),u=wn(t,c);return f.jsx(gm.Provider,{scope:e.__scopeMenu,children:f.jsx(Is,{present:r||s.open,children:f.jsx(gm.Slot,{scope:e.__scopeMenu,children:f.jsx(Hk,{id:l.contentId,"aria-labelledby":l.triggerId,...i,ref:u,align:"start",side:o.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{var h;o.isUsingKeyboardRef.current&&((h=c.current)==null||h.focus()),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:rt(e.onFocusOutside,m=>{m.target!==l.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:rt(e.onEscapeKeyDown,m=>{o.onClose(),m.preventDefault()}),onKeyDown:rt(e.onKeyDown,m=>{var b;const h=m.currentTarget.contains(m.target),g=EZ[o.dir].includes(m.key);h&&g&&(s.onOpenChange(!1),(b=l.trigger)==null||b.focus(),m.preventDefault())})})})})})});G3.displayName=W3;function q3(e){return e?"open":"closed"}function Db(e){return e==="indeterminate"}function Wk(e){return Db(e)?"indeterminate":e?"checked":"unchecked"}function GZ(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function qZ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function KZ(e,t,n){const i=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let o=qZ(e,Math.max(s,0));i.length===1&&(o=o.filter(u=>u!==n));const c=o.find(u=>u.toLowerCase().startsWith(i.toLowerCase()));return c!==n?c:void 0}function YZ(e,t){const{x:n,y:r}=e;let i=!1;for(let s=0,o=t.length-1;s<t.length;o=s++){const l=t[s],c=t[o],u=l.x,m=l.y,h=c.x,g=c.y;m>r!=g>r&&n<(h-u)*(r-m)/(g-m)+u&&(i=!i)}return i}function XZ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return YZ(n,t)}function vm(e){return t=>t.pointerType==="mouse"?e(t):void 0}var QZ=N3,ZZ=Bk,JZ=A3,eJ=M3,tJ=Uk,nJ=L3,rJ=Uy,iJ=D3,sJ=P3,oJ=z3,aJ=F3,lJ=$3,cJ=H3,uJ=V3,dJ=G3,Gk="ContextMenu",[fJ]=Aa(Gk,[E3]),wi=E3(),[hJ,K3]=fJ(Gk),Y3=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,dir:i,modal:s=!0}=e,[o,l]=v.useState(!1),c=wi(t),u=Js(r),m=v.useCallback(h=>{l(h),u(h)},[u]);return f.jsx(hJ,{scope:t,open:o,onOpenChange:m,modal:s,children:f.jsx(QZ,{...c,dir:i,open:o,onOpenChange:m,modal:s,children:n})})};Y3.displayName=Gk;var X3="ContextMenuTrigger",Q3=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,s=K3(X3,n),o=wi(n),l=v.useRef({x:0,y:0}),c=v.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...l.current})}),u=v.useRef(0),m=v.useCallback(()=>window.clearTimeout(u.current),[]),h=g=>{l.current={x:g.clientX,y:g.clientY},s.onOpenChange(!0)};return v.useEffect(()=>m,[m]),v.useEffect(()=>void(r&&m()),[r,m]),f.jsxs(f.Fragment,{children:[f.jsx(ZZ,{...o,virtualRef:c}),f.jsx(rn.span,{"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:rt(e.onContextMenu,g=>{m(),h(g),g.preventDefault()}),onPointerDown:r?e.onPointerDown:rt(e.onPointerDown,Kg(g=>{m(),u.current=window.setTimeout(()=>h(g),700)})),onPointerMove:r?e.onPointerMove:rt(e.onPointerMove,Kg(m)),onPointerCancel:r?e.onPointerCancel:rt(e.onPointerCancel,Kg(m)),onPointerUp:r?e.onPointerUp:rt(e.onPointerUp,Kg(m))})]})});Q3.displayName=X3;var mJ="ContextMenuPortal",Z3=e=>{const{__scopeContextMenu:t,...n}=e,r=wi(t);return f.jsx(JZ,{...r,...n})};Z3.displayName=mJ;var J3="ContextMenuContent",e4=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=K3(J3,n),s=wi(n),o=v.useRef(!1);return f.jsx(eJ,{...s,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:l=>{var c;(c=e.onCloseAutoFocus)==null||c.call(e,l),!l.defaultPrevented&&o.current&&l.preventDefault(),o.current=!1},onInteractOutside:l=>{var c;(c=e.onInteractOutside)==null||c.call(e,l),!l.defaultPrevented&&!i.modal&&(o.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});e4.displayName=J3;var pJ="ContextMenuGroup",gJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(tJ,{...i,...r,ref:t})});gJ.displayName=pJ;var vJ="ContextMenuLabel",bJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(nJ,{...i,...r,ref:t})});bJ.displayName=vJ;var yJ="ContextMenuItem",t4=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(rJ,{...i,...r,ref:t})});t4.displayName=yJ;var xJ="ContextMenuCheckboxItem",_J=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(iJ,{...i,...r,ref:t})});_J.displayName=xJ;var wJ="ContextMenuRadioGroup",SJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(sJ,{...i,...r,ref:t})});SJ.displayName=wJ;var CJ="ContextMenuRadioItem",kJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(oJ,{...i,...r,ref:t})});kJ.displayName=CJ;var EJ="ContextMenuItemIndicator",TJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(aJ,{...i,...r,ref:t})});TJ.displayName=EJ;var NJ="ContextMenuSeparator",n4=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(lJ,{...i,...r,ref:t})});n4.displayName=NJ;var RJ="ContextMenuArrow",AJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(cJ,{...i,...r,ref:t})});AJ.displayName=RJ;var MJ="ContextMenuSubTrigger",LJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(uJ,{...i,...r,ref:t})});LJ.displayName=MJ;var jJ="ContextMenuSubContent",DJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(dJ,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});DJ.displayName=jJ;function Kg(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var IJ=Y3,PJ=Q3,OJ=Z3,r4=e4,i4=t4,s4=n4;const o4=v.createContext(null);function su({onOpenChange:e,...t}){const[n,r]=v.useState(0),i=v.useCallback(()=>{r(s=>s+1),e==null||e(!1)},[e]);return f.jsx(o4.Provider,{value:i,children:f.jsx(IJ,{onOpenChange:e,...t},n)})}const ou=PJ,Vl=v.forwardRef(({className:e,...t},n)=>f.jsx(OJ,{children:f.jsx(r4,{ref:n,className:he("z-50 min-w-[170px] overflow-hidden rounded-xl border border-border bg-background p-1 shadow-lg outline-hidden animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...t})}));Vl.displayName=r4.displayName;const jn=v.forwardRef(({className:e,onSelect:t,...n},r)=>{const i=v.useContext(o4);return f.jsx(i4,{ref:r,className:he("relative flex cursor-default select-none items-center gap-2.5 rounded-lg px-3 py-2 text-xs font-medium text-foreground outline-hidden transition-colors hover:bg-muted focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),onSelect:s=>{t==null||t(s),i==null||i()},...n})});jn.displayName=i4.displayName;const a4=v.forwardRef(({className:e,...t},n)=>f.jsx(s4,{ref:n,className:he("-mx-1 my-1 h-px bg-border",e),...t}));a4.displayName=s4.displayName;var Vy="Popover",[l4]=Aa(Vy,[Ul]),ap=Ul(),[zJ,Wl]=l4(Vy),c4=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:s,modal:o=!1}=e,l=ap(t),c=v.useRef(null),[u,m]=v.useState(!1),[h,g]=Pd({prop:r,defaultProp:i??!1,onChange:s,caller:Vy});return f.jsx(Iy,{...l,children:f.jsx(zJ,{scope:t,contentId:xa(),triggerRef:c,open:h,onOpenChange:g,onOpenToggle:v.useCallback(()=>g(b=>!b),[g]),hasCustomAnchor:u,onCustomAnchorAdd:v.useCallback(()=>m(!0),[]),onCustomAnchorRemove:v.useCallback(()=>m(!1),[]),modal:o,children:n})})};c4.displayName=Vy;var u4="PopoverAnchor",BJ=v.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Wl(u4,n),s=ap(n),{onCustomAnchorAdd:o,onCustomAnchorRemove:l}=i;return v.useEffect(()=>(o(),()=>l()),[o,l]),f.jsx(tp,{...s,...r,ref:t})});BJ.displayName=u4;var d4="PopoverTrigger",f4=v.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Wl(d4,n),s=ap(n),o=wn(t,i.triggerRef),l=f.jsx(rn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":v4(i.open),...r,ref:o,onClick:rt(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?l:f.jsx(tp,{asChild:!0,...s,children:l})});f4.displayName=d4;var qk="PopoverPortal",[FJ,$J]=l4(qk,{forceMount:void 0}),h4=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,s=Wl(qk,t);return f.jsx(FJ,{scope:t,forceMount:n,children:f.jsx(Is,{present:n||s.open,children:f.jsx(of,{asChild:!0,container:i,children:r})})})};h4.displayName=qk;var Bd="PopoverContent",m4=v.forwardRef((e,t)=>{const n=$J(Bd,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,s=Wl(Bd,e.__scopePopover);return f.jsx(Is,{present:r||s.open,children:s.modal?f.jsx(UJ,{...i,ref:t}):f.jsx(VJ,{...i,ref:t})})});m4.displayName=Bd;var HJ=$c("PopoverContent.RemoveScroll"),UJ=v.forwardRef((e,t)=>{const n=Wl(Bd,e.__scopePopover),r=v.useRef(null),i=wn(t,r),s=v.useRef(!1);return v.useEffect(()=>{const o=r.current;if(o)return Ry(o)},[]),f.jsx(Jm,{as:HJ,allowPinchZoom:!0,children:f.jsx(p4,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:rt(e.onCloseAutoFocus,o=>{var l;o.preventDefault(),s.current||(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:rt(e.onPointerDownOutside,o=>{const l=o.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,u=l.button===2||c;s.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:rt(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),VJ=v.forwardRef((e,t)=>{const n=Wl(Bd,e.__scopePopover),r=v.useRef(!1),i=v.useRef(!1);return f.jsx(p4,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var o,l;(o=e.onCloseAutoFocus)==null||o.call(e,s),s.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),s.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:s=>{var c,u;(c=e.onInteractOutside)==null||c.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=s.target;((u=n.triggerRef.current)==null?void 0:u.contains(o))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&i.current&&s.preventDefault()}})}),p4=v.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:o,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:u,onInteractOutside:m,...h}=e,g=Wl(Bd,n),b=ap(n);return Ty(),f.jsx(Zm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:s,children:f.jsx(sf,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:m,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:u,onDismiss:()=>g.onOpenChange(!1),children:f.jsx(Py,{"data-state":v4(g.open),role:"dialog",id:g.contentId,...b,...h,ref:t,style:{...h.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),g4="PopoverClose",WJ=v.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Wl(g4,n);return f.jsx(rn.button,{type:"button",...r,ref:t,onClick:rt(e.onClick,()=>i.onOpenChange(!1))})});WJ.displayName=g4;var GJ="PopoverArrow",qJ=v.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=ap(n);return f.jsx(Oy,{...i,...r,ref:t})});qJ.displayName=GJ;function v4(e){return e?"open":"closed"}var KJ=c4,YJ=f4,XJ=h4,b4=m4;const Kk=KJ,Yk=YJ,Wy=v.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},i)=>f.jsx(XJ,{children:f.jsx(b4,{ref:i,align:t,sideOffset:n,[fm]:"",onCloseAutoFocus:s=>{var o;s.preventDefault(),window.dispatchEvent(new Event(kb)),(o=r.onCloseAutoFocus)==null||o.call(r,s)},className:he("z-50 w-72 rounded-xl border border-border bg-background p-4 shadow-lg outline-hidden animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));Wy.displayName=b4.displayName;function QJ({editorLabel:e,starred:t,onCopyPath:n,onShowArchived:r,onOpenInFinder:i,onOpenInEditor:s,onToggleStar:o,onHide:l,children:c}){return f.jsxs(su,{children:[f.jsx(ou,{asChild:!0,children:c}),f.jsxs(Vl,{children:[f.jsxs(jn,{onSelect:u=>{u.stopPropagation(),o()},children:[t?f.jsx(QG,{className:"h-3.5 w-3.5"}):f.jsx(j5,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:t?"Unstar project":"Star project"})]}),f.jsxs(jn,{onSelect:u=>{u.stopPropagation(),n()},children:[f.jsx(Pl,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Copy Path"})]}),f.jsxs(jn,{onSelect:u=>{u.stopPropagation(),r()},children:[f.jsx(tk,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Show Archived"})]}),f.jsxs(jn,{onSelect:u=>{u.stopPropagation(),i()},children:[f.jsx(Cy,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Show in Finder"})]}),f.jsxs(jn,{onSelect:u=>{u.stopPropagation(),s()},children:[f.jsx(nk,{className:"h-3.5 w-3.5"}),f.jsxs("span",{className:"text-xs font-medium",children:["Open in ",e]})]}),f.jsxs(jn,{onSelect:u=>{u.stopPropagation(),l()},className:"text-destructive hover:bg-destructive/10 focus:bg-destructive/10",children:[f.jsx(XV,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Hide"})]})]})]})}function ZJ({canFork:e,onRename:t,onShare:n,onOpenInFinder:r,onFork:i,onArchive:s,onDelete:o,onEditPermissions:l,children:c}){return f.jsxs(su,{children:[f.jsx(ou,{asChild:!0,children:c}),f.jsxs(Vl,{children:[f.jsxs(jn,{onSelect:u=>{u.preventDefault(),t()},children:[f.jsx(Qm,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Rename"})]}),f.jsxs(jn,{onSelect:u=>{u.preventDefault(),n()},children:[f.jsx(ck,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Share"})]}),f.jsxs(jn,{onSelect:u=>{u.preventDefault(),r()},children:[f.jsx(Cy,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Open in Finder"})]}),f.jsxs(jn,{disabled:!e,onSelect:u=>{u.preventDefault(),e&&i()},children:[f.jsx(L5,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Fork"})]}),l?f.jsxs(jn,{onSelect:u=>{u.preventDefault(),l()},children:[f.jsx(M5,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Permissions…"})]}):null,f.jsxs(jn,{onSelect:u=>{u.preventDefault(),s()},children:[f.jsx(tk,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Archive"})]}),f.jsxs(jn,{onSelect:u=>{u.preventDefault(),o()},className:"text-destructive dark:text-red-400 hover:bg-destructive/10 focus:bg-destructive/10 dark:hover:bg-red-500/20 dark:focus:bg-red-500/20",children:[f.jsx(rf,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Delete"})]})]})]})}function JJ({stackTitle:e,onRename:t,onEditMembers:n,onDelete:r,children:i}){const[s,o]=v.useState(!1);function l(c){return()=>{o(!1),c()}}return f.jsxs(Kk,{open:s,onOpenChange:o,children:[f.jsx(Yk,{asChild:!0,children:i}),f.jsxs(Wy,{align:"end",sideOffset:4,className:"w-44 p-1",role:"menu","aria-label":`Actions for ${e}`,children:[f.jsxs("button",{type:"button",role:"menuitem",onClick:l(t),className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium hover:bg-muted focus-visible:bg-muted outline-hidden",children:[f.jsx(Qm,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Rename"})]}),f.jsxs("button",{type:"button",role:"menuitem",onClick:l(n),className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium hover:bg-muted focus-visible:bg-muted outline-hidden",children:[f.jsx(D5,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Edit members"})]}),f.jsxs("button",{type:"button",role:"menuitem",onClick:l(r),className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium text-destructive dark:text-red-400 hover:bg-destructive/10 focus-visible:bg-destructive/10 dark:hover:bg-red-500/20 dark:focus-visible:bg-red-500/20 outline-hidden",children:[f.jsx(rf,{className:"h-3.5 w-3.5"}),f.jsxs("span",{children:["Delete ",e]})]})]})]})}function eee({stackTitle:e,onRename:t,onEditMembers:n,onDelete:r,children:i}){return f.jsxs(su,{children:[f.jsx(ou,{asChild:!0,children:i}),f.jsxs(Vl,{children:[f.jsxs(jn,{onSelect:s=>{s.preventDefault(),t()},children:[f.jsx(Qm,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Rename"})]}),f.jsxs(jn,{onSelect:s=>{s.preventDefault(),n()},children:[f.jsx(D5,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Edit members"})]}),f.jsxs(jn,{onSelect:s=>{s.preventDefault(),r()},className:"text-destructive dark:text-red-400 hover:bg-destructive/10 focus:bg-destructive/10 dark:hover:bg-red-500/20 dark:focus:bg-red-500/20",children:[f.jsx(rf,{className:"h-3.5 w-3.5"}),f.jsxs("span",{className:"text-xs font-medium",children:["Delete ",e]})]})]})]})}function tee(e){return e.status==="running"||e.status==="starting"?"warning":e.status==="waiting_for_user"?"info":e.status==="failed"?"destructive":e.unread?"success":null}function nee(e){switch(e){case"warning":return"bg-warning";case"info":return"bg-info";case"success":return"bg-success";case"destructive":return"bg-destructive";default:return""}}function ree(e){switch(e){case"warning":return"text-warning";case"info":return"text-info";case"success":return"text-success";case"destructive":return"text-destructive";default:return"text-muted-foreground"}}function iee(e){switch(e){case"active":return{glyph:"●",tone:"text-success",title:"Claude PTY session active"};case"warming":return{glyph:"◐",tone:"text-warning",title:"Claude PTY session warming"};case"idle":return{glyph:"○",tone:"text-muted-foreground",title:"Claude PTY session idle"};case"cooling":return{glyph:"◌",tone:"text-muted-foreground",title:"Claude PTY session cooling down"};case"cold":default:return null}}function see({chat:e,activeChatId:t,nowMs:n,shortcutHint:r=null,showShortcutHint:i=!1,onSelectChat:s,onRenameChat:o,onShareChat:l,onOpenInFinder:c,onForkChat:u,onArchiveChat:m,onDeleteChat:h,onEditPermissions:g}){const b=(e.status==="running"||e.status==="waiting_for_user")&&e.stateEnteredAt!=null,x=b&&e.stateEnteredAt!=null?`${GS(e.status)} ${WS(n-e.stateEnteredAt)}`:Sl(n-(e.lastMessageAt??e._creationTime)),_=i&&r?r:x,w=i&&!!r,C=sK(e.chatId),E=t===C,k=tee(e),N=e.canFork?"w-12":b?"w-12 md:w-20":"w-6 md:w-14",R=f.jsxs("div",{"data-chat-id":C,className:he("group flex items-center gap-2 pl-2 pr-1 py-1.5 rounded-md cursor-pointer transition-colors duration-150",E?"bg-muted":"hover:bg-muted/40"),onClick:()=>s(e.chatId),children:[f.jsx("span",{className:"relative flex h-3.5 w-3.5 shrink-0 items-center justify-center","aria-hidden":!0,children:k?f.jsx("span",{className:he("h-2 w-2 rounded-full",nee(k))}):null}),(()=>{const A=iee(e.sessionState);return A?f.jsx("span",{className:he("shrink-0 text-[10px] leading-none",A.tone),title:A.title,"aria-label":A.title,children:A.glyph}):null})(),e.hasPolicyOverride?f.jsx(M5,{className:"size-3 shrink-0 text-warning","aria-label":"Per-chat permission override active"}):null,f.jsx("span",{className:he("truncate flex-1 text-sm",E?"text-foreground font-medium":"text-foreground/90",e.status==="idle"&&!e.unread&&!E?"text-muted-foreground":""),children:e.title}),f.jsxs("div",{className:he("relative h-6 shrink-0",N),children:[_?w?f.jsx("span",{className:"hidden md:flex absolute inset-0 items-center justify-end pr-0.5 text-[11px] text-foreground transition-opacity duration-150 group-hover:opacity-0",children:f.jsx(f3,{className:"h-4 min-w-4 rounded-sm border-border/50 bg-transparent px-1 text-[10px]",children:r})}):f.jsx("span",{className:he("hidden md:flex absolute inset-0 items-center justify-end pr-1 text-[11px] tabular-nums transition-opacity duration-150 group-hover:opacity-0 whitespace-nowrap",b?ree(k):"text-muted-foreground"),children:_}):null,f.jsxs("div",{className:he("absolute inset-0 flex items-center justify-end gap-0 transition-opacity duration-150",_?"opacity-100 md:opacity-0 md:group-hover:opacity-100":"opacity-100"),children:[e.canFork?f.jsx(Ue,{variant:"ghost",size:"icon",className:"h-6 w-6 cursor-pointer rounded-sm hover:!bg-transparent !border-0",onClick:A=>{A.stopPropagation(),u(e.chatId)},title:"Fork chat",children:f.jsx(L5,{className:"size-3.5"})}):null,f.jsx(Ue,{variant:"ghost",size:"icon",className:"h-6 w-6 cursor-pointer rounded-sm hover:!bg-transparent !border-0",onClick:A=>{A.stopPropagation(),m(e.chatId)},title:"Archive chat",children:f.jsx(tk,{className:"size-3.5"})})]})]})]},e._id);return f.jsx(ZJ,{canFork:e.canFork,onRename:()=>o(e.chatId),onShare:()=>l(e.chatId),onOpenInFinder:()=>c(e.localPath),onFork:()=>u(e.chatId),onArchive:()=>m(e.chatId),onDelete:()=>h(e.chatId),onEditPermissions:g?()=>g(e.chatId):void 0,children:R})}const oee=v.memo(see);function aee(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return v.useMemo(()=>r=>{t.forEach(i=>i(r))},t)}const Gy=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function uf(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Xk(e){return"nodeType"in e}function Oi(e){var t,n;return e?uf(e)?e:Xk(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function Qk(e){const{Document:t}=Oi(e);return e instanceof t}function lp(e){return uf(e)?!1:e instanceof Oi(e).HTMLElement}function y4(e){return e instanceof Oi(e).SVGElement}function df(e){return e?uf(e)?e.document:Xk(e)?Qk(e)?e:lp(e)||y4(e)?e.ownerDocument:document:document:document}const zo=Gy?v.useLayoutEffect:v.useEffect;function Zk(e){const t=v.useRef(e);return zo(()=>{t.current=e}),v.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return t.current==null?void 0:t.current(...r)},[])}function lee(){const e=v.useRef(null),t=v.useCallback((r,i)=>{e.current=setInterval(r,i)},[]),n=v.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function bm(e,t){t===void 0&&(t=[e]);const n=v.useRef(e);return zo(()=>{n.current!==e&&(n.current=e)},t),n}function cp(e,t){const n=v.useRef();return v.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...t])}function Ib(e){const t=Zk(e),n=v.useRef(null),r=v.useCallback(i=>{i!==n.current&&(t==null||t(i,n.current)),n.current=i},[]);return[n,r]}function YS(e){const t=v.useRef();return v.useEffect(()=>{t.current=e},[e]),t.current}let Z_={};function up(e,t){return v.useMemo(()=>{if(t)return t;const n=Z_[e]==null?0:Z_[e]+1;return Z_[e]=n,e+"-"+n},[e,t])}function x4(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r.reduce((s,o)=>{const l=Object.entries(o);for(const[c,u]of l){const m=s[c];m!=null&&(s[c]=m+e*u)}return s},{...t})}}const Ed=x4(1),Pb=x4(-1);function cee(e){return"clientX"in e&&"clientY"in e}function Jk(e){if(!e)return!1;const{KeyboardEvent:t}=Oi(e.target);return t&&e instanceof t}function uee(e){if(!e)return!1;const{TouchEvent:t}=Oi(e.target);return t&&e instanceof t}function XS(e){if(uee(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return cee(e)?{x:e.clientX,y:e.clientY}:null}const ym=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[ym.Translate.toString(e),ym.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+" "+n+"ms "+r}}}),zM="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function dee(e){return e.matches(zM)?e:e.querySelector(zM)}const fee={display:"none"};function hee(e){let{id:t,value:n}=e;return Cn.createElement("div",{id:t,style:fee},n)}function mee(e){let{id:t,announcement:n,ariaLiveType:r="assertive"}=e;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Cn.createElement("div",{id:t,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function pee(){const[e,t]=v.useState("");return{announce:v.useCallback(r=>{r!=null&&t(r)},[]),announcement:e}}const _4=v.createContext(null);function gee(e){const t=v.useContext(_4);v.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function vee(){const[e]=v.useState(()=>new Set),t=v.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[v.useCallback(r=>{let{type:i,event:s}=r;e.forEach(o=>{var l;return(l=o[i])==null?void 0:l.call(o,s)})},[e]),t]}const bee={draggable:`
706
+ `)&&(A.writePathDeny=R),Object.keys(A).length===0?null:A}function E(){i(C())}function k(){i(null)}return f.jsxs(f.Fragment,{children:[f.jsx(As,{open:e,onOpenChange:N=>{N||s()},children:f.jsxs(es,{className:"max-w-2xl",children:[f.jsxs(Ms,{children:["Permissions — ",t]}),f.jsxs(Oo,{className:"space-y-5",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-sm font-medium",children:"Default action"}),f.jsxs("div",{className:"text-xs text-muted-foreground",children:["Behaviour when a tool call has no explicit allow/deny rule. ",f.jsx("strong",{children:"auto-allow"})," bypasses prompts and runs untrusted shell commands without supervision — use a worktree."]}),f.jsx(Di,{value:o,onValueChange:w,options:[{value:"ask",label:"Ask"},{value:"auto-allow",label:"Auto-allow (unsafe)"},{value:"auto-deny",label:"Auto-deny"}]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-sm font-medium",children:"Read-path deny list"}),f.jsx("div",{className:"text-xs text-muted-foreground",children:"One glob per line. The model cannot read paths matching any entry. Defaults shown below — edit to add or remove."}),f.jsx("textarea",{value:c,onChange:N=>u(N.target.value),rows:8,className:"w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-xs",spellCheck:!1})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-sm font-medium",children:"Write-path deny list"}),f.jsx("div",{className:"text-xs text-muted-foreground",children:"One glob per line. The model cannot edit or write paths matching any entry."}),f.jsx("textarea",{value:m,onChange:N=>h(N.target.value),rows:8,className:"w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-xs",spellCheck:!1})]})]}),f.jsxs(Sa,{className:"justify-between",children:[f.jsx(Ue,{variant:"ghost",onClick:k,children:"Reset to defaults"}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx(Ue,{variant:"ghost",onClick:s,children:"Cancel"}),f.jsx(Ue,{onClick:E,children:"Apply"})]})]})]})}),f.jsx(As,{open:g,onOpenChange:N=>{N||(b(!1),_(null))},children:f.jsxs(es,{className:"max-w-md",children:[f.jsx(Ms,{children:"Enable auto-allow for this chat?"}),f.jsxs(Oo,{className:"space-y-3 text-sm",children:[f.jsx("p",{children:"Auto-allow disables tool-call prompts. The model can run shell commands, write files, and edit code without asking. Read/write deny lists still apply."}),f.jsx("p",{className:"text-warning",children:"Use a worktree for risky tasks."})]}),f.jsxs(Sa,{className:"justify-end gap-2",children:[f.jsx(Ue,{variant:"ghost",onClick:()=>{b(!1),_(null)},children:"Cancel"}),f.jsx(Ue,{variant:"destructive",onClick:()=>{x&&l(x),b(!1),_(null)},children:"Enable auto-allow"})]})]})})]})}function kQ({open:e,shareUrl:t,onOpenChange:n,onOpenLink:r,onCopyLink:i}){const[s,o]=v.useState(!1);v.useEffect(()=>{e||o(!1)},[e,t]);const l=async()=>{await i()&&(o(!0),window.setTimeout(()=>{o(!1)},2e3))};return f.jsx(As,{open:e,onOpenChange:n,children:f.jsxs(es,{size:"md",children:[f.jsxs(MO,{children:[f.jsx(Ms,{children:"Shared Link"}),f.jsx(af,{children:"Shared links are snapshots in time and contain all attachments, tool calls and history. Be mindful of sensitive info."})]}),f.jsx(Oo,{className:"space-y-3",children:f.jsxs("div",{className:"flex w-full items-center gap-2 rounded-2xl border border-border bg-muted/40 pl-4 px-3 py-2.5",children:[f.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-sm text-foreground",children:t}),f.jsx("button",{type:"button",onClick:()=>void l(),title:s?"Copied":"Copy link","aria-label":s?"Copied":"Copy link",className:"flex flex-shrink-0 items-center justify-center rounded-lg text-logo hover:text-logo/60 transition-colors hover:bg-background hover:text-foreground",children:s?f.jsx(_i,{className:"h-4 w-4 text-emerald-400"}):f.jsx(Pl,{className:"h-4 w-4"})})]})}),f.jsx(Sa,{children:f.jsxs(FY,{type:"button",onClick:r,children:[f.jsx(ik,{className:"mr-2 h-4 w-4"}),"Open"]})})]})})}const EQ={defaultAction:"ask",bash:{autoAllowVerbs:["ls","pwd","git status","git diff","git log"]},readPathDeny:["~/.ssh","~/.aws","~/.gcp","~/.config/gh","~/.claude","~/.kanna","~/Library/Keychains","/etc/shadow","/etc/sudoers","~/.gnupg","~/.gitconfig","**/.git/config","~/.npmrc","~/.netrc","~/.docker/config.json","**/.env","**/.env.*","**/credentials*","**/*.pem","**/*.key","**/id_rsa*","**/id_ed25519*"],writePathDeny:["/etc/**","/usr/**","/System/**","~/.ssh/**","~/.aws/**","~/.config/gh/**","~/.claude/**","~/.kanna/**","~/.gnupg/**","~/.gitconfig","**/.git/config"],toolDenyList:[{tool:"mcp__kanna__bash",pattern:"rm\\s+-rf\\s+(/|~|\\$HOME)(?:\\b|$|\\s)"},{tool:"mcp__kanna__bash",pattern:"git\\s+push\\b.*--force"}],toolAllowList:[]},$n=v.forwardRef(({className:e,type:t,...n},r)=>f.jsx("input",{ref:r,type:t,className:he("flex w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",e),...n}));$n.displayName="Input";const m3=v.createContext(null);function TQ({children:e}){const[t,n]=v.useState(null),[r,i]=v.useState(""),s=v.useRef(null);v.useEffect(()=>{(t==null?void 0:t.kind)==="prompt"&&(i(t.options.initialValue??""),setTimeout(()=>{var b,x;(b=s.current)==null||b.focus(),(x=s.current)==null||x.select()},0))},[t]);const o=v.useCallback(()=>{n(null),i("")},[]),l=v.useCallback(()=>{t&&(t.kind==="confirm"?t.resolve(!1):t.kind==="prompt"?t.resolve(null):t.resolve(),o())},[o,t]),c=v.useCallback(()=>{t&&(t.kind==="confirm"?t.resolve(!0):t.kind==="prompt"?t.resolve(r.trim()||null):t.resolve(),o())},[o,t,r]),u=v.useCallback(b=>new Promise(x=>{n({kind:"confirm",options:b,resolve:x})}),[]),m=v.useCallback(b=>new Promise(x=>{n({kind:"prompt",options:b,resolve:x})}),[]),h=v.useCallback(b=>new Promise(x=>{n({kind:"alert",options:b,resolve:x})}),[]),g=v.useMemo(()=>({confirm:u,prompt:m,alert:h}),[h,u,m]);return f.jsxs(m3.Provider,{value:g,children:[e,f.jsx(As,{open:t!==null,onOpenChange:b=>{b||!t||l()},children:f.jsx(es,{size:"sm",onKeyDown:b=>{b.key!=="Enter"||b.shiftKey||!t||t.kind!=="confirm"||(b.preventDefault(),c())},children:t?f.jsxs(f.Fragment,{children:[f.jsxs(Oo,{className:"space-y-4",children:[f.jsx(Ms,{children:t.options.title}),t.options.description?f.jsx(af,{children:t.options.description}):null,t.kind==="prompt"?f.jsx($n,{ref:s,type:"text",value:r,onChange:b=>i(b.target.value),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),c())},placeholder:t.options.placeholder}):null]}),f.jsxs(Sa,{children:[f.jsx(Ue,{variant:"ghost",size:"sm",onClick:l,className:t.kind==="alert"?"hidden":void 0,children:"cancelLabel"in t.options?t.options.cancelLabel??"Cancel":"Cancel"}),f.jsx(Ue,{variant:t.kind==="confirm"?t.options.confirmVariant??"default":"secondary",size:"sm",onClick:c,disabled:t.kind==="prompt"&&!r.trim(),children:t.kind==="alert"?t.options.closeLabel??"OK":"confirmLabel"in t.options?t.options.confirmLabel??"Confirm":"Confirm"})]})]}):null})})]})}function rp(){const e=v.useContext(m3);if(!e)throw new Error("useAppDialog must be used within AppDialogProvider");return e}const Mk=v.forwardRef(({className:e,...t},n)=>f.jsx("div",{ref:n,className:he("bg-card text-card-foreground",e),...t}));Mk.displayName="Card";const Lk=v.forwardRef(({className:e,...t},n)=>f.jsx("div",{ref:n,className:he("flex flex-col space-y-1.5 p-2",e),...t}));Lk.displayName="CardHeader";const p3=v.forwardRef(({className:e,...t},n)=>f.jsx("h3",{ref:n,className:he("text-2xl font-semibold leading-none tracking-tight",e),...t}));p3.displayName="CardTitle";const g3=v.forwardRef(({className:e,...t},n)=>f.jsx("p",{ref:n,className:he("text-sm text-muted-foreground",e),...t}));g3.displayName="CardDescription";const jk=v.forwardRef(({className:e,...t},n)=>f.jsx("div",{ref:n,className:he("p-6 pt-0",e),...t}));jk.displayName="CardContent";const NQ=v.forwardRef(({className:e,...t},n)=>f.jsx("div",{ref:n,className:he("flex items-center p-6 pt-0",e),...t}));NQ.displayName="CardFooter";const RQ="modulepreload",AQ=function(e){return"/"+e},MM={},K=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let o=function(u){return Promise.all(u.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));i=o(n.map(u=>{if(u=AQ(u),u in MM)return;MM[u]=!0;const m=u.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":RQ,m||(g.as="script"),g.crossOrigin="",g.href=u,c&&g.setAttribute("nonce",c),document.head.appendChild(g),m)return new Promise((b,x)=>{g.addEventListener("load",b),g.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${u}`)))})}))}function s(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&s(l.reason);return t().catch(s)})},MQ=v.lazy(()=>K(()=>import("./index-f0nvAfAu.js"),[]).then(e=>({default:e.Toaster})));function LQ(){return f.jsx(v.Suspense,{fallback:null,children:f.jsx(MQ,{position:"bottom-right",theme:"system",closeButton:!0,duration:6e3})})}const jQ="0.61.4",DQ={version:jQ},Jn="Kanna",LM="kanna",IQ=".kanna",PQ=".kanna-dev",OQ="KANNA_RUNTIME_PROFILE",Dk=`kanna/${DQ.version}`,zQ="[kanna]",BQ=`~/${Jn}`;function $y(){var t;return(t=globalThis.process)==null?void 0:t.env}function FQ(e=$y()){var t;return((t=e==null?void 0:e[OQ])==null?void 0:t.trim().toLowerCase())==="dev"?"dev":"prod"}function $Q(e=$y()){return FQ(e)==="dev"?PQ:IQ}function HQ(e=$y()){return`~/${$Q(e)}`}function UQ(e=$y()){return`${HQ(e)}/keybindings.json`}function qg(e){return e?`${LM} ${e}`:LM}const jM=e=>{let t;const n=new Set,r=(u,m)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const g=t;t=m??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(b=>b(t,g))}},i=()=>t,l={setState:r,getState:i,getInitialState:()=>c,subscribe:u=>(n.add(u),()=>n.delete(u))},c=t=e(r,i,l);return l},VQ=(e=>e?jM(e):jM),WQ=e=>e;function GQ(e,t=WQ){const n=Cn.useSyncExternalStore(e.subscribe,Cn.useCallback(()=>t(e.getState()),[e,t]),Cn.useCallback(()=>t(e.getInitialState()),[e,t]));return Cn.useDebugValue(n),n}const qQ=e=>{const t=VQ(e),n=r=>GQ(t,r);return Object.assign(n,t),n},oo=(e=>qQ),v3="always",b3="funk",KQ=[{value:"blow",label:"Blow"},{value:"bottle",label:"Bottle"},{value:"frog",label:"Frog"},{value:"funk",label:"Funk"},{value:"glass",label:"Glass"},{value:"ping",label:"Ping"},{value:"pop",label:"Pop"},{value:"purr",label:"Purr"},{value:"tink",label:"Tink"}];function YQ(e){switch(e){case"never":case"unfocused":case"always":return e;default:return v3}}function XQ(e){switch(e){case"blow":case"bottle":case"frog":case"funk":case"glass":case"ping":case"pop":case"purr":case"tink":return e;default:return b3}}const Mc=oo()(e=>({chatSoundPreference:v3,chatSoundId:b3,setChatSoundPreference:t=>e({chatSoundPreference:YQ(t)}),setChatSoundId:t=>e({chatSoundId:XQ(t)})})),QQ={blow:"/chat-sounds/Blow.mp3",bottle:"/chat-sounds/Bottle.mp3",frog:"/chat-sounds/Frog.mp3",funk:"/chat-sounds/Funk.mp3",glass:"/chat-sounds/Glass.mp3",ping:"/chat-sounds/Ping.mp3",pop:"/chat-sounds/Pop.mp3",purr:"/chat-sounds/Purr.mp3",tink:"/chat-sounds/Tink.mp3"};function ZQ(e=document){return e.visibilityState!=="visible"||!e.hasFocus()}function JQ(e){const t=new Audio(QQ[e]);return t.preload="auto",t.play()}async function US(e,t){if(t<=0)return;const n=Array.from({length:t},(r,i)=>new Promise(s=>{window.setTimeout(()=>{JQ(e).catch(()=>{}).finally(()=>s())},i*90)}));await Promise.all(n)}function eZ(e,t=document){return e==="never"?!1:e==="always"?!0:ZQ(t)}function tZ(e){return e.projectGroups.reduce((t,n)=>t+n.chats.reduce((r,i)=>r+(i.unread?1:0)+(i.status==="waiting_for_user"?1:0),0),0)}function DM(e){let t=0;const n=new Set;for(const r of e.projectGroups)for(const i of r.chats)i.unread&&(t+=1),i.status==="waiting_for_user"&&n.add(i.chatId);return{unreadCount:t,waitingChatIds:n}}function nZ(e,t){if(!e)return 0;const n=DM(e),r=DM(t),i=Math.max(0,r.unreadCount-n.unreadCount);let s=0;for(const o of r.waitingChatIds)n.waitingChatIds.has(o)||(s+=1);return i+s}function VS(e){return e.split(/[\s_-]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}const rZ=[/^(?:\/usr\/bin\/env\s+)?(?:\/bin\/)?(?:bash|zsh|sh)\s+(?:-[a-zA-Z]*c|-c)\s+(['"])([\s\S]*)\1$/,/^(?:\/usr\/bin\/env\s+)?(?:\/bin\/)?(?:bash|zsh|sh)\s+(?:-[a-zA-Z]*c|-c)\s+(.+)$/,/^(?:\/usr\/bin\/env\s+)?(?:cmd(?:\.exe)?)\s+\/c\s+(['"])([\s\S]*)\1$/i,/^(?:\/usr\/bin\/env\s+)?(?:cmd(?:\.exe)?)\s+\/c\s+(.+)$/i,/^(?:\/usr\/bin\/env\s+)?(?:powershell(?:\.exe)?|pwsh)\s+(?:-NoProfile\s+)?-Command\s+(['"])([\s\S]*)\1$/i,/^(?:\/usr\/bin\/env\s+)?(?:powershell(?:\.exe)?|pwsh)\s+(?:-NoProfile\s+)?-Command\s+(.+)$/i];function iZ(e){const t=e.trim();for(const n of rZ){const r=t.match(n);if(!r)continue;const i=(r[2]??r[1]??"").trim();if(i)return i}return t}function Ik(e){return e.split("/").pop()||e}const sZ=1440*6e4;function oZ(e,t){const n=Math.max(0,t-e),r=Math.floor(n/1e3),i=Math.floor(r/3600),s=Math.floor(r%3600/60),o=r%60;return i>0?`${i}h ${s}m`:s>0?`${s}m ${o}s`:`${o}s`}function aZ(e){const t=new Date(e),n=t.getHours().toString().padStart(2,"0"),r=t.getMinutes().toString().padStart(2,"0");return`${n}:${r}`}function lZ(e,t){if(e===void 0)return null;const n=Math.max(0,t-e),r=6e4,i=60*r,s=sZ,o=7*s;return n<r?"now":n<i?`${Math.floor(n/r)}m`:n<s?`${Math.floor(n/i)}h`:n<o?`${Math.floor(n/s)}d`:`${Math.floor(n/o)}w`}function cZ(e){return e.lastMessageAt??e._creationTime}const Pk=1e3,Xv=60*Pk,yd=60*Xv,X_=24*yd;function Sl(e){const t=Math.max(0,e);if(t<Xv)return`${Math.floor(t/Pk)}s`;if(t<yd)return`${Math.floor(t/Xv)}m`;if(t<X_){const i=Math.floor(t/yd),s=Math.floor(t%yd/Xv);return s===0?`${i}h`:`${i}h ${s}m`}const n=Math.floor(t/X_),r=Math.floor(t%X_/yd);return r===0?`${n}d`:`${n}d ${r}h`}function WS(e){const t=Math.max(0,e);if(t>=yd)return Sl(t);const n=Math.floor(t/Pk),r=Math.floor(n/60),i=n%60;return`${r}:${i.toString().padStart(2,"0")}`}function GS(e){switch(e){case"idle":return"Idle";case"starting":return"Starting";case"running":return"Running";case"waiting_for_user":return"Waiting";case"failed":return"Failed"}}function IM(e){switch(e){case"running":return"active";case"waiting_for_user":return"attention";case"failed":return"destructive";case"idle":case"starting":default:return"muted"}}function PM(e){switch(e){case"active":return"text-emerald-500 dark:text-emerald-400";case"attention":return"text-amber-500 dark:text-amber-400";case"destructive":return"text-destructive";case"muted":default:return"text-muted-foreground"}}function Ok(e){const t=e+"CollectionProvider",[n,r]=Aa(t),[i,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),o=_=>{const{scope:w,children:C}=_,E=Cn.useRef(null),k=Cn.useRef(new Map).current;return f.jsx(i,{scope:w,itemMap:k,collectionRef:E,children:C})};o.displayName=t;const l=e+"CollectionSlot",c=$c(l),u=Cn.forwardRef((_,w)=>{const{scope:C,children:E}=_,k=s(l,C),N=wn(w,k.collectionRef);return f.jsx(c,{ref:N,children:E})});u.displayName=l;const m=e+"CollectionItemSlot",h="data-radix-collection-item",g=$c(m),b=Cn.forwardRef((_,w)=>{const{scope:C,children:E,...k}=_,N=Cn.useRef(null),R=wn(w,N),A=s(m,C);return Cn.useEffect(()=>(A.itemMap.set(N,{ref:N,...k}),()=>void A.itemMap.delete(N))),f.jsx(g,{[h]:"",ref:R,children:E})});b.displayName=m;function x(_){const w=s(e+"CollectionConsumer",_);return Cn.useCallback(()=>{const E=w.collectionRef.current;if(!E)return[];const k=Array.from(E.querySelectorAll(`[${h}]`));return Array.from(w.itemMap.values()).sort((A,M)=>k.indexOf(A.ref.current)-k.indexOf(M.ref.current))},[w.collectionRef,w.itemMap])}return[{Provider:o,Slot:u,ItemSlot:b},x,r]}var uZ=v.createContext(void 0);function zk(e){const t=v.useContext(uZ);return e||t||"ltr"}var Q_="rovingFocusGroup.onEntryFocus",dZ={bubbles:!1,cancelable:!0},ip="RovingFocusGroup",[qS,y3,fZ]=Ok(ip),[hZ,x3]=Aa(ip,[fZ]),[mZ,pZ]=hZ(ip),_3=v.forwardRef((e,t)=>f.jsx(qS.Provider,{scope:e.__scopeRovingFocusGroup,children:f.jsx(qS.Slot,{scope:e.__scopeRovingFocusGroup,children:f.jsx(gZ,{...e,ref:t})})}));_3.displayName=ip;var gZ=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:s,currentTabStopId:o,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:c,onEntryFocus:u,preventScrollOnEntryFocus:m=!1,...h}=e,g=v.useRef(null),b=wn(t,g),x=zk(s),[_,w]=Pd({prop:o,defaultProp:l??null,onChange:c,caller:ip}),[C,E]=v.useState(!1),k=Js(u),N=y3(n),R=v.useRef(!1),[A,M]=v.useState(0);return v.useEffect(()=>{const L=g.current;if(L)return L.addEventListener(Q_,k),()=>L.removeEventListener(Q_,k)},[k]),f.jsx(mZ,{scope:n,orientation:r,dir:x,loop:i,currentTabStopId:_,onItemFocus:v.useCallback(L=>w(L),[w]),onItemShiftTab:v.useCallback(()=>E(!0),[]),onFocusableItemAdd:v.useCallback(()=>M(L=>L+1),[]),onFocusableItemRemove:v.useCallback(()=>M(L=>L-1),[]),children:f.jsx(rn.div,{tabIndex:C||A===0?-1:0,"data-orientation":r,...h,ref:b,style:{outline:"none",...e.style},onMouseDown:rt(e.onMouseDown,()=>{R.current=!0}),onFocus:rt(e.onFocus,L=>{const F=!R.current;if(L.target===L.currentTarget&&F&&!C){const D=new CustomEvent(Q_,dZ);if(L.currentTarget.dispatchEvent(D),!D.defaultPrevented){const O=N().filter(B=>B.focusable),z=O.find(B=>B.active),P=O.find(B=>B.id===_),H=[z,P,...O].filter(Boolean).map(B=>B.ref.current);C3(H,m)}}R.current=!1}),onBlur:rt(e.onBlur,()=>E(!1))})})}),w3="RovingFocusGroupItem",S3=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:s,children:o,...l}=e,c=xa(),u=s||c,m=pZ(w3,n),h=m.currentTabStopId===u,g=y3(n),{onFocusableItemAdd:b,onFocusableItemRemove:x,currentTabStopId:_}=m;return v.useEffect(()=>{if(r)return b(),()=>x()},[r,b,x]),f.jsx(qS.ItemSlot,{scope:n,id:u,focusable:r,active:i,children:f.jsx(rn.span,{tabIndex:h?0:-1,"data-orientation":m.orientation,...l,ref:t,onMouseDown:rt(e.onMouseDown,w=>{r?m.onItemFocus(u):w.preventDefault()}),onFocus:rt(e.onFocus,()=>m.onItemFocus(u)),onKeyDown:rt(e.onKeyDown,w=>{if(w.key==="Tab"&&w.shiftKey){m.onItemShiftTab();return}if(w.target!==w.currentTarget)return;const C=yZ(w,m.orientation,m.dir);if(C!==void 0){if(w.metaKey||w.ctrlKey||w.altKey||w.shiftKey)return;w.preventDefault();let k=g().filter(N=>N.focusable).map(N=>N.ref.current);if(C==="last")k.reverse();else if(C==="prev"||C==="next"){C==="prev"&&k.reverse();const N=k.indexOf(w.currentTarget);k=m.loop?xZ(k,N+1):k.slice(N+1)}setTimeout(()=>C3(k))}}),children:typeof o=="function"?o({isCurrentTabStop:h,hasTabStop:_!=null}):o})})});S3.displayName=w3;var vZ={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function bZ(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function yZ(e,t,n){const r=bZ(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return vZ[r]}function C3(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function xZ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var _Z=_3,wZ=S3,KS=["Enter"," "],SZ=["ArrowDown","PageUp","Home"],k3=["ArrowUp","PageDown","End"],CZ=[...SZ,...k3],kZ={ltr:[...KS,"ArrowRight"],rtl:[...KS,"ArrowLeft"]},EZ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},sp="Menu",[gm,TZ,NZ]=Ok(sp),[ru,E3]=Aa(sp,[NZ,Ul,x3]),Hy=Ul(),T3=x3(),[RZ,iu]=ru(sp),[AZ,op]=ru(sp),N3=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:s,modal:o=!0}=e,l=Hy(t),[c,u]=v.useState(null),m=v.useRef(!1),h=Js(s),g=zk(i);return v.useEffect(()=>{const b=()=>{m.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>m.current=!1;return document.addEventListener("keydown",b,{capture:!0}),()=>{document.removeEventListener("keydown",b,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.jsx(Iy,{...l,children:f.jsx(RZ,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:u,children:f.jsx(AZ,{scope:t,onClose:v.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:m,dir:g,modal:o,children:r})})})};N3.displayName=sp;var MZ="MenuAnchor",Bk=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=Hy(n);return f.jsx(tp,{...i,...r,ref:t})});Bk.displayName=MZ;var Fk="MenuPortal",[LZ,R3]=ru(Fk,{forceMount:void 0}),A3=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,s=iu(Fk,t);return f.jsx(LZ,{scope:t,forceMount:n,children:f.jsx(Is,{present:n||s.open,children:f.jsx(of,{asChild:!0,container:i,children:r})})})};A3.displayName=Fk;var Ns="MenuContent",[jZ,$k]=ru(Ns),M3=v.forwardRef((e,t)=>{const n=R3(Ns,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=iu(Ns,e.__scopeMenu),o=op(Ns,e.__scopeMenu);return f.jsx(gm.Provider,{scope:e.__scopeMenu,children:f.jsx(Is,{present:r||s.open,children:f.jsx(gm.Slot,{scope:e.__scopeMenu,children:o.modal?f.jsx(DZ,{...i,ref:t}):f.jsx(IZ,{...i,ref:t})})})})}),DZ=v.forwardRef((e,t)=>{const n=iu(Ns,e.__scopeMenu),r=v.useRef(null),i=wn(t,r);return v.useEffect(()=>{const s=r.current;if(s)return Ry(s)},[]),f.jsx(Hk,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:rt(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),IZ=v.forwardRef((e,t)=>{const n=iu(Ns,e.__scopeMenu);return f.jsx(Hk,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),PZ=$c("MenuContent.ScrollLock"),Hk=v.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:u,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:b,disableOutsideScroll:x,..._}=e,w=iu(Ns,n),C=op(Ns,n),E=Hy(n),k=T3(n),N=TZ(n),[R,A]=v.useState(null),M=v.useRef(null),L=wn(t,M,w.onContentChange),F=v.useRef(0),D=v.useRef(""),O=v.useRef(0),z=v.useRef(null),P=v.useRef("right"),$=v.useRef(0),H=x?Jm:v.Fragment,B=x?{as:PZ,allowPinchZoom:!0}:void 0,V=Q=>{var ne,se;const I=D.current+Q,W=N().filter(le=>!le.disabled),te=document.activeElement,U=(ne=W.find(le=>le.ref.current===te))==null?void 0:ne.textValue,fe=W.map(le=>le.textValue),ae=KZ(fe,I,U),ee=(se=W.find(le=>le.textValue===ae))==null?void 0:se.ref.current;(function le(ue){D.current=ue,window.clearTimeout(F.current),ue!==""&&(F.current=window.setTimeout(()=>le(""),1e3))})(I),ee&&setTimeout(()=>ee.focus())};v.useEffect(()=>()=>window.clearTimeout(F.current),[]),Ty();const G=v.useCallback(Q=>{var W,te;return P.current===((W=z.current)==null?void 0:W.side)&&XZ(Q,(te=z.current)==null?void 0:te.area)},[]);return f.jsx(jZ,{scope:n,searchRef:D,onItemEnter:v.useCallback(Q=>{G(Q)&&Q.preventDefault()},[G]),onItemLeave:v.useCallback(Q=>{var I;G(Q)||((I=M.current)==null||I.focus(),A(null))},[G]),onTriggerLeave:v.useCallback(Q=>{G(Q)&&Q.preventDefault()},[G]),pointerGraceTimerRef:O,onPointerGraceIntentChange:v.useCallback(Q=>{z.current=Q},[]),children:f.jsx(H,{...B,children:f.jsx(Zm,{asChild:!0,trapped:i,onMountAutoFocus:rt(s,Q=>{var I;Q.preventDefault(),(I=M.current)==null||I.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:f.jsx(sf,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:u,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:b,children:f.jsx(_Z,{asChild:!0,...k,dir:C.dir,orientation:"vertical",loop:r,currentTabStopId:R,onCurrentTabStopIdChange:A,onEntryFocus:rt(c,Q=>{C.isUsingKeyboardRef.current||Q.preventDefault()}),preventScrollOnEntryFocus:!0,children:f.jsx(Py,{role:"menu","aria-orientation":"vertical","data-state":q3(w.open),"data-radix-menu-content":"",dir:C.dir,...E,..._,ref:L,style:{outline:"none",..._.style},onKeyDown:rt(_.onKeyDown,Q=>{const W=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,te=Q.ctrlKey||Q.altKey||Q.metaKey,U=Q.key.length===1;W&&(Q.key==="Tab"&&Q.preventDefault(),!te&&U&&V(Q.key));const fe=M.current;if(Q.target!==fe||!CZ.includes(Q.key))return;Q.preventDefault();const ee=N().filter(ne=>!ne.disabled).map(ne=>ne.ref.current);k3.includes(Q.key)&&ee.reverse(),GZ(ee)}),onBlur:rt(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),D.current="")}),onPointerMove:rt(e.onPointerMove,vm(Q=>{const I=Q.target,W=$.current!==Q.clientX;if(Q.currentTarget.contains(I)&&W){const te=Q.clientX>$.current?"right":"left";P.current=te,$.current=Q.clientX}}))})})})})})})});M3.displayName=Ns;var OZ="MenuGroup",Uk=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.jsx(rn.div,{role:"group",...r,ref:t})});Uk.displayName=OZ;var zZ="MenuLabel",L3=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.jsx(rn.div,{...r,ref:t})});L3.displayName=zZ;var jb="MenuItem",OM="menu.itemSelect",Uy=v.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,s=v.useRef(null),o=op(jb,e.__scopeMenu),l=$k(jb,e.__scopeMenu),c=wn(t,s),u=v.useRef(!1),m=()=>{const h=s.current;if(!n&&h){const g=new CustomEvent(OM,{bubbles:!0,cancelable:!0});h.addEventListener(OM,b=>r==null?void 0:r(b),{once:!0}),Z5(h,g),g.defaultPrevented?u.current=!1:o.onClose()}};return f.jsx(j3,{...i,ref:c,disabled:n,onClick:rt(e.onClick,m),onPointerDown:h=>{var g;(g=e.onPointerDown)==null||g.call(e,h),u.current=!0},onPointerUp:rt(e.onPointerUp,h=>{var g;u.current||(g=h.currentTarget)==null||g.click()}),onKeyDown:rt(e.onKeyDown,h=>{const g=l.searchRef.current!=="";n||g&&h.key===" "||KS.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});Uy.displayName=jb;var j3=v.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...s}=e,o=$k(jb,n),l=T3(n),c=v.useRef(null),u=wn(t,c),[m,h]=v.useState(!1),[g,b]=v.useState("");return v.useEffect(()=>{const x=c.current;x&&b((x.textContent??"").trim())},[s.children]),f.jsx(gm.ItemSlot,{scope:n,disabled:r,textValue:i??g,children:f.jsx(wZ,{asChild:!0,...l,focusable:!r,children:f.jsx(rn.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:u,onPointerMove:rt(e.onPointerMove,vm(x=>{r?o.onItemLeave(x):(o.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:rt(e.onPointerLeave,vm(x=>o.onItemLeave(x))),onFocus:rt(e.onFocus,()=>h(!0)),onBlur:rt(e.onBlur,()=>h(!1))})})})}),BZ="MenuCheckboxItem",D3=v.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return f.jsx(B3,{scope:e.__scopeMenu,checked:n,children:f.jsx(Uy,{role:"menuitemcheckbox","aria-checked":Db(n)?"mixed":n,...i,ref:t,"data-state":Wk(n),onSelect:rt(i.onSelect,()=>r==null?void 0:r(Db(n)?!0:!n),{checkForDefaultPrevented:!1})})})});D3.displayName=BZ;var I3="MenuRadioGroup",[FZ,$Z]=ru(I3,{value:void 0,onValueChange:()=>{}}),P3=v.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,s=Js(r);return f.jsx(FZ,{scope:e.__scopeMenu,value:n,onValueChange:s,children:f.jsx(Uk,{...i,ref:t})})});P3.displayName=I3;var O3="MenuRadioItem",z3=v.forwardRef((e,t)=>{const{value:n,...r}=e,i=$Z(O3,e.__scopeMenu),s=n===i.value;return f.jsx(B3,{scope:e.__scopeMenu,checked:s,children:f.jsx(Uy,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":Wk(s),onSelect:rt(r.onSelect,()=>{var o;return(o=i.onValueChange)==null?void 0:o.call(i,n)},{checkForDefaultPrevented:!1})})})});z3.displayName=O3;var Vk="MenuItemIndicator",[B3,HZ]=ru(Vk,{checked:!1}),F3=v.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,s=HZ(Vk,n);return f.jsx(Is,{present:r||Db(s.checked)||s.checked===!0,children:f.jsx(rn.span,{...i,ref:t,"data-state":Wk(s.checked)})})});F3.displayName=Vk;var UZ="MenuSeparator",$3=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.jsx(rn.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});$3.displayName=UZ;var VZ="MenuArrow",H3=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=Hy(n);return f.jsx(Oy,{...i,...r,ref:t})});H3.displayName=VZ;var WZ="MenuSub",[NTe,U3]=ru(WZ),Ph="MenuSubTrigger",V3=v.forwardRef((e,t)=>{const n=iu(Ph,e.__scopeMenu),r=op(Ph,e.__scopeMenu),i=U3(Ph,e.__scopeMenu),s=$k(Ph,e.__scopeMenu),o=v.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=s,u={__scopeMenu:e.__scopeMenu},m=v.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return v.useEffect(()=>m,[m]),v.useEffect(()=>{const h=l.current;return()=>{window.clearTimeout(h),c(null)}},[l,c]),f.jsx(Bk,{asChild:!0,...u,children:f.jsx(j3,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":q3(n.open),...e,ref:hk(t,i.onTriggerChange),onClick:h=>{var g;(g=e.onClick)==null||g.call(e,h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:rt(e.onPointerMove,vm(h=>{s.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!n.open&&!o.current&&(s.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:rt(e.onPointerLeave,vm(h=>{var b,x;m();const g=(b=n.content)==null?void 0:b.getBoundingClientRect();if(g){const _=(x=n.content)==null?void 0:x.dataset.side,w=_==="right",C=w?-5:5,E=g[w?"left":"right"],k=g[w?"right":"left"];s.onPointerGraceIntentChange({area:[{x:h.clientX+C,y:h.clientY},{x:E,y:g.top},{x:k,y:g.top},{x:k,y:g.bottom},{x:E,y:g.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(h),h.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:rt(e.onKeyDown,h=>{var b;const g=s.searchRef.current!=="";e.disabled||g&&h.key===" "||kZ[r.dir].includes(h.key)&&(n.onOpenChange(!0),(b=n.content)==null||b.focus(),h.preventDefault())})})})});V3.displayName=Ph;var W3="MenuSubContent",G3=v.forwardRef((e,t)=>{const n=R3(Ns,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=iu(Ns,e.__scopeMenu),o=op(Ns,e.__scopeMenu),l=U3(W3,e.__scopeMenu),c=v.useRef(null),u=wn(t,c);return f.jsx(gm.Provider,{scope:e.__scopeMenu,children:f.jsx(Is,{present:r||s.open,children:f.jsx(gm.Slot,{scope:e.__scopeMenu,children:f.jsx(Hk,{id:l.contentId,"aria-labelledby":l.triggerId,...i,ref:u,align:"start",side:o.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{var h;o.isUsingKeyboardRef.current&&((h=c.current)==null||h.focus()),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:rt(e.onFocusOutside,m=>{m.target!==l.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:rt(e.onEscapeKeyDown,m=>{o.onClose(),m.preventDefault()}),onKeyDown:rt(e.onKeyDown,m=>{var b;const h=m.currentTarget.contains(m.target),g=EZ[o.dir].includes(m.key);h&&g&&(s.onOpenChange(!1),(b=l.trigger)==null||b.focus(),m.preventDefault())})})})})})});G3.displayName=W3;function q3(e){return e?"open":"closed"}function Db(e){return e==="indeterminate"}function Wk(e){return Db(e)?"indeterminate":e?"checked":"unchecked"}function GZ(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function qZ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function KZ(e,t,n){const i=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let o=qZ(e,Math.max(s,0));i.length===1&&(o=o.filter(u=>u!==n));const c=o.find(u=>u.toLowerCase().startsWith(i.toLowerCase()));return c!==n?c:void 0}function YZ(e,t){const{x:n,y:r}=e;let i=!1;for(let s=0,o=t.length-1;s<t.length;o=s++){const l=t[s],c=t[o],u=l.x,m=l.y,h=c.x,g=c.y;m>r!=g>r&&n<(h-u)*(r-m)/(g-m)+u&&(i=!i)}return i}function XZ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return YZ(n,t)}function vm(e){return t=>t.pointerType==="mouse"?e(t):void 0}var QZ=N3,ZZ=Bk,JZ=A3,eJ=M3,tJ=Uk,nJ=L3,rJ=Uy,iJ=D3,sJ=P3,oJ=z3,aJ=F3,lJ=$3,cJ=H3,uJ=V3,dJ=G3,Gk="ContextMenu",[fJ]=Aa(Gk,[E3]),wi=E3(),[hJ,K3]=fJ(Gk),Y3=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,dir:i,modal:s=!0}=e,[o,l]=v.useState(!1),c=wi(t),u=Js(r),m=v.useCallback(h=>{l(h),u(h)},[u]);return f.jsx(hJ,{scope:t,open:o,onOpenChange:m,modal:s,children:f.jsx(QZ,{...c,dir:i,open:o,onOpenChange:m,modal:s,children:n})})};Y3.displayName=Gk;var X3="ContextMenuTrigger",Q3=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,s=K3(X3,n),o=wi(n),l=v.useRef({x:0,y:0}),c=v.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...l.current})}),u=v.useRef(0),m=v.useCallback(()=>window.clearTimeout(u.current),[]),h=g=>{l.current={x:g.clientX,y:g.clientY},s.onOpenChange(!0)};return v.useEffect(()=>m,[m]),v.useEffect(()=>void(r&&m()),[r,m]),f.jsxs(f.Fragment,{children:[f.jsx(ZZ,{...o,virtualRef:c}),f.jsx(rn.span,{"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:rt(e.onContextMenu,g=>{m(),h(g),g.preventDefault()}),onPointerDown:r?e.onPointerDown:rt(e.onPointerDown,Kg(g=>{m(),u.current=window.setTimeout(()=>h(g),700)})),onPointerMove:r?e.onPointerMove:rt(e.onPointerMove,Kg(m)),onPointerCancel:r?e.onPointerCancel:rt(e.onPointerCancel,Kg(m)),onPointerUp:r?e.onPointerUp:rt(e.onPointerUp,Kg(m))})]})});Q3.displayName=X3;var mJ="ContextMenuPortal",Z3=e=>{const{__scopeContextMenu:t,...n}=e,r=wi(t);return f.jsx(JZ,{...r,...n})};Z3.displayName=mJ;var J3="ContextMenuContent",e4=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=K3(J3,n),s=wi(n),o=v.useRef(!1);return f.jsx(eJ,{...s,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:l=>{var c;(c=e.onCloseAutoFocus)==null||c.call(e,l),!l.defaultPrevented&&o.current&&l.preventDefault(),o.current=!1},onInteractOutside:l=>{var c;(c=e.onInteractOutside)==null||c.call(e,l),!l.defaultPrevented&&!i.modal&&(o.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});e4.displayName=J3;var pJ="ContextMenuGroup",gJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(tJ,{...i,...r,ref:t})});gJ.displayName=pJ;var vJ="ContextMenuLabel",bJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(nJ,{...i,...r,ref:t})});bJ.displayName=vJ;var yJ="ContextMenuItem",t4=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(rJ,{...i,...r,ref:t})});t4.displayName=yJ;var xJ="ContextMenuCheckboxItem",_J=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(iJ,{...i,...r,ref:t})});_J.displayName=xJ;var wJ="ContextMenuRadioGroup",SJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(sJ,{...i,...r,ref:t})});SJ.displayName=wJ;var CJ="ContextMenuRadioItem",kJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(oJ,{...i,...r,ref:t})});kJ.displayName=CJ;var EJ="ContextMenuItemIndicator",TJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(aJ,{...i,...r,ref:t})});TJ.displayName=EJ;var NJ="ContextMenuSeparator",n4=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(lJ,{...i,...r,ref:t})});n4.displayName=NJ;var RJ="ContextMenuArrow",AJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(cJ,{...i,...r,ref:t})});AJ.displayName=RJ;var MJ="ContextMenuSubTrigger",LJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(uJ,{...i,...r,ref:t})});LJ.displayName=MJ;var jJ="ContextMenuSubContent",DJ=v.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=wi(n);return f.jsx(dJ,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});DJ.displayName=jJ;function Kg(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var IJ=Y3,PJ=Q3,OJ=Z3,r4=e4,i4=t4,s4=n4;const o4=v.createContext(null);function su({onOpenChange:e,...t}){const[n,r]=v.useState(0),i=v.useCallback(()=>{r(s=>s+1),e==null||e(!1)},[e]);return f.jsx(o4.Provider,{value:i,children:f.jsx(IJ,{onOpenChange:e,...t},n)})}const ou=PJ,Vl=v.forwardRef(({className:e,...t},n)=>f.jsx(OJ,{children:f.jsx(r4,{ref:n,className:he("z-50 min-w-[170px] overflow-hidden rounded-xl border border-border bg-background p-1 shadow-lg outline-hidden animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...t})}));Vl.displayName=r4.displayName;const jn=v.forwardRef(({className:e,onSelect:t,...n},r)=>{const i=v.useContext(o4);return f.jsx(i4,{ref:r,className:he("relative flex cursor-default select-none items-center gap-2.5 rounded-lg px-3 py-2 text-xs font-medium text-foreground outline-hidden transition-colors hover:bg-muted focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),onSelect:s=>{t==null||t(s),i==null||i()},...n})});jn.displayName=i4.displayName;const a4=v.forwardRef(({className:e,...t},n)=>f.jsx(s4,{ref:n,className:he("-mx-1 my-1 h-px bg-border",e),...t}));a4.displayName=s4.displayName;var Vy="Popover",[l4]=Aa(Vy,[Ul]),ap=Ul(),[zJ,Wl]=l4(Vy),c4=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:s,modal:o=!1}=e,l=ap(t),c=v.useRef(null),[u,m]=v.useState(!1),[h,g]=Pd({prop:r,defaultProp:i??!1,onChange:s,caller:Vy});return f.jsx(Iy,{...l,children:f.jsx(zJ,{scope:t,contentId:xa(),triggerRef:c,open:h,onOpenChange:g,onOpenToggle:v.useCallback(()=>g(b=>!b),[g]),hasCustomAnchor:u,onCustomAnchorAdd:v.useCallback(()=>m(!0),[]),onCustomAnchorRemove:v.useCallback(()=>m(!1),[]),modal:o,children:n})})};c4.displayName=Vy;var u4="PopoverAnchor",BJ=v.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Wl(u4,n),s=ap(n),{onCustomAnchorAdd:o,onCustomAnchorRemove:l}=i;return v.useEffect(()=>(o(),()=>l()),[o,l]),f.jsx(tp,{...s,...r,ref:t})});BJ.displayName=u4;var d4="PopoverTrigger",f4=v.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Wl(d4,n),s=ap(n),o=wn(t,i.triggerRef),l=f.jsx(rn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":v4(i.open),...r,ref:o,onClick:rt(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?l:f.jsx(tp,{asChild:!0,...s,children:l})});f4.displayName=d4;var qk="PopoverPortal",[FJ,$J]=l4(qk,{forceMount:void 0}),h4=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,s=Wl(qk,t);return f.jsx(FJ,{scope:t,forceMount:n,children:f.jsx(Is,{present:n||s.open,children:f.jsx(of,{asChild:!0,container:i,children:r})})})};h4.displayName=qk;var Bd="PopoverContent",m4=v.forwardRef((e,t)=>{const n=$J(Bd,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,s=Wl(Bd,e.__scopePopover);return f.jsx(Is,{present:r||s.open,children:s.modal?f.jsx(UJ,{...i,ref:t}):f.jsx(VJ,{...i,ref:t})})});m4.displayName=Bd;var HJ=$c("PopoverContent.RemoveScroll"),UJ=v.forwardRef((e,t)=>{const n=Wl(Bd,e.__scopePopover),r=v.useRef(null),i=wn(t,r),s=v.useRef(!1);return v.useEffect(()=>{const o=r.current;if(o)return Ry(o)},[]),f.jsx(Jm,{as:HJ,allowPinchZoom:!0,children:f.jsx(p4,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:rt(e.onCloseAutoFocus,o=>{var l;o.preventDefault(),s.current||(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:rt(e.onPointerDownOutside,o=>{const l=o.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,u=l.button===2||c;s.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:rt(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),VJ=v.forwardRef((e,t)=>{const n=Wl(Bd,e.__scopePopover),r=v.useRef(!1),i=v.useRef(!1);return f.jsx(p4,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var o,l;(o=e.onCloseAutoFocus)==null||o.call(e,s),s.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),s.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:s=>{var c,u;(c=e.onInteractOutside)==null||c.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=s.target;((u=n.triggerRef.current)==null?void 0:u.contains(o))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&i.current&&s.preventDefault()}})}),p4=v.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:o,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:u,onInteractOutside:m,...h}=e,g=Wl(Bd,n),b=ap(n);return Ty(),f.jsx(Zm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:s,children:f.jsx(sf,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:m,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:u,onDismiss:()=>g.onOpenChange(!1),children:f.jsx(Py,{"data-state":v4(g.open),role:"dialog",id:g.contentId,...b,...h,ref:t,style:{...h.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),g4="PopoverClose",WJ=v.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Wl(g4,n);return f.jsx(rn.button,{type:"button",...r,ref:t,onClick:rt(e.onClick,()=>i.onOpenChange(!1))})});WJ.displayName=g4;var GJ="PopoverArrow",qJ=v.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=ap(n);return f.jsx(Oy,{...i,...r,ref:t})});qJ.displayName=GJ;function v4(e){return e?"open":"closed"}var KJ=c4,YJ=f4,XJ=h4,b4=m4;const Kk=KJ,Yk=YJ,Wy=v.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},i)=>f.jsx(XJ,{children:f.jsx(b4,{ref:i,align:t,sideOffset:n,[fm]:"",onCloseAutoFocus:s=>{var o;s.preventDefault(),window.dispatchEvent(new Event(kb)),(o=r.onCloseAutoFocus)==null||o.call(r,s)},className:he("z-50 w-72 rounded-xl border border-border bg-background p-4 shadow-lg outline-hidden animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));Wy.displayName=b4.displayName;function QJ({editorLabel:e,starred:t,onCopyPath:n,onShowArchived:r,onOpenInFinder:i,onOpenInEditor:s,onToggleStar:o,onHide:l,children:c}){return f.jsxs(su,{children:[f.jsx(ou,{asChild:!0,children:c}),f.jsxs(Vl,{children:[f.jsxs(jn,{onSelect:u=>{u.stopPropagation(),o()},children:[t?f.jsx(QG,{className:"h-3.5 w-3.5"}):f.jsx(j5,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:t?"Unstar project":"Star project"})]}),f.jsxs(jn,{onSelect:u=>{u.stopPropagation(),n()},children:[f.jsx(Pl,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Copy Path"})]}),f.jsxs(jn,{onSelect:u=>{u.stopPropagation(),r()},children:[f.jsx(tk,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Show Archived"})]}),f.jsxs(jn,{onSelect:u=>{u.stopPropagation(),i()},children:[f.jsx(Cy,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Show in Finder"})]}),f.jsxs(jn,{onSelect:u=>{u.stopPropagation(),s()},children:[f.jsx(nk,{className:"h-3.5 w-3.5"}),f.jsxs("span",{className:"text-xs font-medium",children:["Open in ",e]})]}),f.jsxs(jn,{onSelect:u=>{u.stopPropagation(),l()},className:"text-destructive hover:bg-destructive/10 focus:bg-destructive/10",children:[f.jsx(XV,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Hide"})]})]})]})}function ZJ({canFork:e,onRename:t,onShare:n,onOpenInFinder:r,onFork:i,onArchive:s,onDelete:o,onEditPermissions:l,children:c}){return f.jsxs(su,{children:[f.jsx(ou,{asChild:!0,children:c}),f.jsxs(Vl,{children:[f.jsxs(jn,{onSelect:u=>{u.preventDefault(),t()},children:[f.jsx(Qm,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Rename"})]}),f.jsxs(jn,{onSelect:u=>{u.preventDefault(),n()},children:[f.jsx(ck,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Share"})]}),f.jsxs(jn,{onSelect:u=>{u.preventDefault(),r()},children:[f.jsx(Cy,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Open in Finder"})]}),f.jsxs(jn,{disabled:!e,onSelect:u=>{u.preventDefault(),e&&i()},children:[f.jsx(L5,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Fork"})]}),l?f.jsxs(jn,{onSelect:u=>{u.preventDefault(),l()},children:[f.jsx(M5,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Permissions…"})]}):null,f.jsxs(jn,{onSelect:u=>{u.preventDefault(),s()},children:[f.jsx(tk,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Archive"})]}),f.jsxs(jn,{onSelect:u=>{u.preventDefault(),o()},className:"text-destructive dark:text-red-400 hover:bg-destructive/10 focus:bg-destructive/10 dark:hover:bg-red-500/20 dark:focus:bg-red-500/20",children:[f.jsx(rf,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Delete"})]})]})]})}function JJ({stackTitle:e,onRename:t,onEditMembers:n,onDelete:r,children:i}){const[s,o]=v.useState(!1);function l(c){return()=>{o(!1),c()}}return f.jsxs(Kk,{open:s,onOpenChange:o,children:[f.jsx(Yk,{asChild:!0,children:i}),f.jsxs(Wy,{align:"end",sideOffset:4,className:"w-44 p-1",role:"menu","aria-label":`Actions for ${e}`,children:[f.jsxs("button",{type:"button",role:"menuitem",onClick:l(t),className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium hover:bg-muted focus-visible:bg-muted outline-hidden",children:[f.jsx(Qm,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Rename"})]}),f.jsxs("button",{type:"button",role:"menuitem",onClick:l(n),className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium hover:bg-muted focus-visible:bg-muted outline-hidden",children:[f.jsx(D5,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Edit members"})]}),f.jsxs("button",{type:"button",role:"menuitem",onClick:l(r),className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium text-destructive dark:text-red-400 hover:bg-destructive/10 focus-visible:bg-destructive/10 dark:hover:bg-red-500/20 dark:focus-visible:bg-red-500/20 outline-hidden",children:[f.jsx(rf,{className:"h-3.5 w-3.5"}),f.jsxs("span",{children:["Delete ",e]})]})]})]})}function eee({stackTitle:e,onRename:t,onEditMembers:n,onDelete:r,children:i}){return f.jsxs(su,{children:[f.jsx(ou,{asChild:!0,children:i}),f.jsxs(Vl,{children:[f.jsxs(jn,{onSelect:s=>{s.preventDefault(),t()},children:[f.jsx(Qm,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Rename"})]}),f.jsxs(jn,{onSelect:s=>{s.preventDefault(),n()},children:[f.jsx(D5,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Edit members"})]}),f.jsxs(jn,{onSelect:s=>{s.preventDefault(),r()},className:"text-destructive dark:text-red-400 hover:bg-destructive/10 focus:bg-destructive/10 dark:hover:bg-red-500/20 dark:focus:bg-red-500/20",children:[f.jsx(rf,{className:"h-3.5 w-3.5"}),f.jsxs("span",{className:"text-xs font-medium",children:["Delete ",e]})]})]})]})}function tee(e){return e.status==="running"||e.status==="starting"?"warning":e.status==="waiting_for_user"?"info":e.status==="failed"?"destructive":e.unread?"success":null}function nee(e){switch(e){case"warning":return"bg-warning";case"info":return"bg-info";case"success":return"bg-success";case"destructive":return"bg-destructive";default:return""}}function ree(e){switch(e){case"warning":return"text-warning";case"info":return"text-info";case"success":return"text-success";case"destructive":return"text-destructive";default:return"text-muted-foreground"}}function iee(e){switch(e){case"active":return{glyph:"●",tone:"text-success",title:"Claude PTY session active"};case"warming":return{glyph:"◐",tone:"text-warning",title:"Claude PTY session warming"};case"idle":return{glyph:"○",tone:"text-muted-foreground",title:"Claude PTY session idle"};case"cooling":return{glyph:"◌",tone:"text-muted-foreground",title:"Claude PTY session cooling down"};case"cold":default:return null}}function see({chat:e,activeChatId:t,nowMs:n,shortcutHint:r=null,showShortcutHint:i=!1,onSelectChat:s,onRenameChat:o,onShareChat:l,onOpenInFinder:c,onForkChat:u,onArchiveChat:m,onDeleteChat:h,onEditPermissions:g}){const b=(e.status==="running"||e.status==="waiting_for_user")&&e.stateEnteredAt!=null,x=b&&e.stateEnteredAt!=null?`${GS(e.status)} ${WS(n-e.stateEnteredAt)}`:Sl(n-(e.lastMessageAt??e._creationTime)),_=i&&r?r:x,w=i&&!!r,C=sK(e.chatId),E=t===C,k=tee(e),N=e.canFork?"w-12":b?"w-12 md:w-20":"w-6 md:w-14",R=f.jsxs("div",{"data-chat-id":C,className:he("group flex items-center gap-2 pl-2 pr-1 py-1.5 rounded-md cursor-pointer transition-colors duration-150",E?"bg-muted":"hover:bg-muted/40"),onClick:()=>s(e.chatId),children:[f.jsx("span",{className:"relative flex h-3.5 w-3.5 shrink-0 items-center justify-center","aria-hidden":!0,children:k?f.jsx("span",{className:he("h-2 w-2 rounded-full",nee(k))}):null}),(()=>{const A=iee(e.sessionState);return A?f.jsx("span",{className:he("shrink-0 text-[10px] leading-none",A.tone),title:A.title,"aria-label":A.title,children:A.glyph}):null})(),e.hasPolicyOverride?f.jsx(M5,{className:"size-3 shrink-0 text-warning","aria-label":"Per-chat permission override active"}):null,f.jsx("span",{className:he("truncate flex-1 text-sm",E?"text-foreground font-medium":"text-foreground/90",e.status==="idle"&&!e.unread&&!E?"text-muted-foreground":""),children:e.title}),f.jsxs("div",{className:he("relative h-6 shrink-0",N),children:[_?w?f.jsx("span",{className:"hidden md:flex absolute inset-0 items-center justify-end pr-0.5 text-[11px] text-foreground transition-opacity duration-150 group-hover:opacity-0",children:f.jsx(f3,{className:"h-4 min-w-4 rounded-sm border-border/50 bg-transparent px-1 text-[10px]",children:r})}):f.jsx("span",{className:he("hidden md:flex absolute inset-0 items-center justify-end pr-1 text-[11px] tabular-nums transition-opacity duration-150 group-hover:opacity-0 whitespace-nowrap",b?ree(k):"text-muted-foreground"),children:_}):null,f.jsxs("div",{className:he("absolute inset-0 flex items-center justify-end gap-0 transition-opacity duration-150",_?"opacity-100 md:opacity-0 md:group-hover:opacity-100":"opacity-100"),children:[e.canFork?f.jsx(Ue,{variant:"ghost",size:"icon",className:"h-6 w-6 cursor-pointer rounded-sm hover:!bg-transparent !border-0",onClick:A=>{A.stopPropagation(),u(e.chatId)},title:"Fork chat",children:f.jsx(L5,{className:"size-3.5"})}):null,f.jsx(Ue,{variant:"ghost",size:"icon",className:"h-6 w-6 cursor-pointer rounded-sm hover:!bg-transparent !border-0",onClick:A=>{A.stopPropagation(),m(e.chatId)},title:"Archive chat",children:f.jsx(tk,{className:"size-3.5"})})]})]})]},e._id);return f.jsx(ZJ,{canFork:e.canFork,onRename:()=>o(e.chatId),onShare:()=>l(e.chatId),onOpenInFinder:()=>c(e.localPath),onFork:()=>u(e.chatId),onArchive:()=>m(e.chatId),onDelete:()=>h(e.chatId),onEditPermissions:g?()=>g(e.chatId):void 0,children:R})}const oee=v.memo(see);function aee(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return v.useMemo(()=>r=>{t.forEach(i=>i(r))},t)}const Gy=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function uf(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Xk(e){return"nodeType"in e}function Oi(e){var t,n;return e?uf(e)?e:Xk(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function Qk(e){const{Document:t}=Oi(e);return e instanceof t}function lp(e){return uf(e)?!1:e instanceof Oi(e).HTMLElement}function y4(e){return e instanceof Oi(e).SVGElement}function df(e){return e?uf(e)?e.document:Xk(e)?Qk(e)?e:lp(e)||y4(e)?e.ownerDocument:document:document:document}const zo=Gy?v.useLayoutEffect:v.useEffect;function Zk(e){const t=v.useRef(e);return zo(()=>{t.current=e}),v.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return t.current==null?void 0:t.current(...r)},[])}function lee(){const e=v.useRef(null),t=v.useCallback((r,i)=>{e.current=setInterval(r,i)},[]),n=v.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function bm(e,t){t===void 0&&(t=[e]);const n=v.useRef(e);return zo(()=>{n.current!==e&&(n.current=e)},t),n}function cp(e,t){const n=v.useRef();return v.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...t])}function Ib(e){const t=Zk(e),n=v.useRef(null),r=v.useCallback(i=>{i!==n.current&&(t==null||t(i,n.current)),n.current=i},[]);return[n,r]}function YS(e){const t=v.useRef();return v.useEffect(()=>{t.current=e},[e]),t.current}let Z_={};function up(e,t){return v.useMemo(()=>{if(t)return t;const n=Z_[e]==null?0:Z_[e]+1;return Z_[e]=n,e+"-"+n},[e,t])}function x4(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r.reduce((s,o)=>{const l=Object.entries(o);for(const[c,u]of l){const m=s[c];m!=null&&(s[c]=m+e*u)}return s},{...t})}}const Ed=x4(1),Pb=x4(-1);function cee(e){return"clientX"in e&&"clientY"in e}function Jk(e){if(!e)return!1;const{KeyboardEvent:t}=Oi(e.target);return t&&e instanceof t}function uee(e){if(!e)return!1;const{TouchEvent:t}=Oi(e.target);return t&&e instanceof t}function XS(e){if(uee(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return cee(e)?{x:e.clientX,y:e.clientY}:null}const ym=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[ym.Translate.toString(e),ym.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+" "+n+"ms "+r}}}),zM="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function dee(e){return e.matches(zM)?e:e.querySelector(zM)}const fee={display:"none"};function hee(e){let{id:t,value:n}=e;return Cn.createElement("div",{id:t,style:fee},n)}function mee(e){let{id:t,announcement:n,ariaLiveType:r="assertive"}=e;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Cn.createElement("div",{id:t,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function pee(){const[e,t]=v.useState("");return{announce:v.useCallback(r=>{r!=null&&t(r)},[]),announcement:e}}const _4=v.createContext(null);function gee(e){const t=v.useContext(_4);v.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function vee(){const[e]=v.useState(()=>new Set),t=v.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[v.useCallback(r=>{let{type:i,event:s}=r;e.forEach(o=>{var l;return(l=o[i])==null?void 0:l.call(o,s)})},[e]),t]}const bee={draggable:`
707
707
  To pick up a draggable item, press the space bar.
708
708
  While dragging, use the arrow keys to move the item.
709
709
  Press space again to drop the item in its new position, or press escape to cancel.
@@ -2602,10 +2602,10 @@ XID_Start XIDS`.split(/\s/).map(e=>[a0(e),e])),$ae=new Map([["s",Er(383)],[Er(38
2602
2602
  `});++r<e.length;)r&&n.push({type:"text",value:`
2603
2603
  `}),n.push(e[r]);return t&&e.length>0&&n.push({type:"text",value:`
2604
2604
  `}),n}function eD(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function tD(e,t){const n=hge(e,t),r=n.one(e,void 0),i=dge(n),s=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return i&&s.children.push({type:"text",value:`
2605
- `},i),s}function bge(e,t){return e&&"run"in e?async function(n,r){const i=tD(n,{file:r,...t});await e.run(i,r)}:function(n,r){return tD(n,{file:r,...e||t})}}function nD(e){if(e)throw e}var Vw,rD;function yge(){if(rD)return Vw;rD=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},s=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var m=e.call(u,"constructor"),h=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!m&&!h)return!1;var g;for(g in u);return typeof g>"u"||e.call(u,g)},o=function(u,m){n&&m.name==="__proto__"?n(u,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):u[m.name]=m.newValue},l=function(u,m){if(m==="__proto__")if(e.call(u,m)){if(r)return r(u,m).value}else return;return u[m]};return Vw=function c(){var u,m,h,g,b,x,_=arguments[0],w=1,C=arguments.length,E=!1;for(typeof _=="boolean"&&(E=_,_=arguments[1]||{},w=2),(_==null||typeof _!="object"&&typeof _!="function")&&(_={});w<C;++w)if(u=arguments[w],u!=null)for(m in u)h=l(_,m),g=l(u,m),_!==g&&(E&&g&&(s(g)||(b=i(g)))?(b?(b=!1,x=h&&i(h)?h:[]):x=h&&s(h)?h:{},o(_,{name:m,newValue:c(E,x,g)})):typeof g<"u"&&o(_,{name:m,newValue:g}));return _},Vw}var xge=yge();const Ww=yy(xge);function G1(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function _ge(){const e=[],t={run:n,use:r};return t;function n(...i){let s=-1;const o=i.pop();if(typeof o!="function")throw new TypeError("Expected function as last argument, not "+o);l(null,...i);function l(c,...u){const m=e[++s];let h=-1;if(c){o(c);return}for(;++h<i.length;)(u[h]===null||u[h]===void 0)&&(u[h]=i[h]);i=u,m?wge(m,l)(...u):o(null,...u)}}function r(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return e.push(i),t}}function wge(e,t){let n;return r;function r(...o){const l=e.length>o.length;let c;l&&o.push(i);try{c=e.apply(this,o)}catch(u){const m=u;if(l&&n)throw m;return i(m)}l||(c&&c.then&&typeof c.then=="function"?c.then(s,i):c instanceof Error?i(c):s(c))}function i(o,...l){n||(n=!0,t(o,...l))}function s(o){i(null,o)}}const wo={basename:Sge,dirname:Cge,extname:kge,join:Ege,sep:"/"};function Sge(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');bp(e);let n=0,r=-1,i=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else r<0&&(s=!0,r=i+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let o=-1,l=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else o<0&&(s=!0,o=i+1),l>-1&&(e.codePointAt(i)===t.codePointAt(l--)?l<0&&(r=i):(l=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function Cge(e){if(bp(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function kge(e){bp(e);let t=e.length,n=-1,r=0,i=-1,s=0,o;for(;t--;){const l=e.codePointAt(t);if(l===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),l===46?i<0?i=t:s!==1&&(s=1):i>-1&&(s=-1)}return i<0||n<0||s===0||s===1&&i===n-1&&i===r+1?"":e.slice(i,n)}function Ege(...e){let t=-1,n;for(;++t<e.length;)bp(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":Tge(n)}function Tge(e){bp(e);const t=e.codePointAt(0)===47;let n=Nge(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function Nge(e,t){let n="",r=0,i=-1,s=0,o=-1,l,c;for(;++o<=e.length;){if(o<e.length)l=e.codePointAt(o);else{if(l===47)break;l=47}if(l===47){if(!(i===o-1||s===1))if(i!==o-1&&s===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),i=o,s=0;continue}}else if(n.length>0){n="",r=0,i=o,s=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(i+1,o):n=e.slice(i+1,o),r=o-i-1;i=o,s=0}else l===46&&s>-1?s++:s=-1}return n}function bp(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Rge={cwd:Age};function Age(){return"/"}function q1(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Mge(e){if(typeof e=="string")e=new URL(e);else if(!q1(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return Lge(e)}function Lge(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(t)}const Gw=["history","path","basename","stem","extname","dirname"];class DB{constructor(t){let n;t?q1(t)?n={path:t}:typeof t=="string"||jge(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":Rge.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Gw.length;){const s=Gw[r];s in n&&n[s]!==void 0&&n[s]!==null&&(this[s]=s==="history"?[...n[s]]:n[s])}let i;for(i in n)Gw.includes(i)||(this[i]=n[i])}get basename(){return typeof this.path=="string"?wo.basename(this.path):void 0}set basename(t){Kw(t,"basename"),qw(t,"basename"),this.path=wo.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?wo.dirname(this.path):void 0}set dirname(t){iD(this.basename,"dirname"),this.path=wo.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?wo.extname(this.path):void 0}set extname(t){if(qw(t,"extname"),iD(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=wo.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){q1(t)&&(t=Mge(t)),Kw(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?wo.basename(this.path,this.extname):void 0}set stem(t){Kw(t,"stem"),qw(t,"stem"),this.path=wo.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const i=this.message(t,n,r);throw i.fatal=!0,i}info(t,n,r){const i=this.message(t,n,r);return i.fatal=void 0,i}message(t,n,r){const i=new li(t,n,r);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function qw(e,t){if(e&&e.includes(wo.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+wo.sep+"`")}function Kw(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function iD(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function jge(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Dge=(function(e){const r=this.constructor.prototype,i=r[e],s=function(){return i.apply(s,arguments)};return Object.setPrototypeOf(s,r),s}),Ige={}.hasOwnProperty;class n2 extends Dge{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=_ge()}copy(){const t=new n2;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(Ww(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Qw("data",this.frozen),this.namespace[t]=n,this):Ige.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Qw("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const i=n.call(t,...r);typeof i=="function"&&this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=_v(t),r=this.parser||this.Parser;return Yw("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),Yw("process",this.parser||this.Parser),Xw("process",this.compiler||this.Compiler),n?i(void 0,n):new Promise(i);function i(s,o){const l=_v(t),c=r.parse(l);r.run(c,l,function(m,h,g){if(m||!h||!g)return u(m);const b=h,x=r.stringify(b,g);zge(x)?g.value=x:g.result=x,u(m,g)});function u(m,h){m||!h?o(m):s?s(h):n(void 0,h)}}}processSync(t){let n=!1,r;return this.freeze(),Yw("processSync",this.parser||this.Parser),Xw("processSync",this.compiler||this.Compiler),this.process(t,i),oD("processSync","process",n),r;function i(s,o){n=!0,nD(s),r=o}}run(t,n,r){sD(t),this.freeze();const i=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?s(void 0,r):new Promise(s);function s(o,l){const c=_v(n);i.run(t,c,u);function u(m,h,g){const b=h||t;m?l(m):o?o(b):r(void 0,b,g)}}}runSync(t,n){let r=!1,i;return this.run(t,n,s),oD("runSync","run",r),i;function s(o,l){nD(o),i=l,r=!0}}stringify(t,n){this.freeze();const r=_v(n),i=this.compiler||this.Compiler;return Xw("stringify",i),sD(t),i(t,r)}use(t,...n){const r=this.attachers,i=this.namespace;if(Qw("use",this.frozen),t!=null)if(typeof t=="function")c(t,n);else if(typeof t=="object")Array.isArray(t)?l(t):o(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function s(u){if(typeof u=="function")c(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[m,...h]=u;c(m,h)}else o(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function o(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");l(u.plugins),u.settings&&(i.settings=Ww(!0,i.settings,u.settings))}function l(u){let m=-1;if(u!=null)if(Array.isArray(u))for(;++m<u.length;){const h=u[m];s(h)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function c(u,m){let h=-1,g=-1;for(;++h<r.length;)if(r[h][0]===u){g=h;break}if(g===-1)r.push([u,...m]);else if(m.length>0){let[b,...x]=m;const _=r[g][1];G1(_)&&G1(b)&&(b=Ww(!0,_,b)),r[g]=[u,b,...x]}}}}const Pge=new n2().freeze();function Yw(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Xw(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Qw(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function sD(e){if(!G1(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function oD(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function _v(e){return Oge(e)?e:new DB(e)}function Oge(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function zge(e){return typeof e=="string"||Bge(e)}function Bge(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Fge="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",aD=[],lD={allowDangerousHtml:!0},$ge=/^(https?|ircs?|mailto|xmpp)$/i,Hge=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function lu(e){const t=Uge(e),n=Vge(e);return Wge(t.runSync(t.parse(n),n),e)}function Uge(e){const t=e.rehypePlugins||aD,n=e.remarkPlugins||aD,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...lD}:lD;return Pge().use(Lpe).use(n).use(bge,r).use(t)}function Vge(e){const t=e.children||"",n=new DB;return typeof t=="string"&&(n.value=t),n}function Wge(e,t){const n=t.allowedElements,r=t.allowElement,i=t.components,s=t.disallowedElements,o=t.skipHtml,l=t.unwrapDisallowed,c=t.urlTransform||Gge;for(const m of Hge)Object.hasOwn(t,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+Fge+m.id,void 0);return $E(e,u),Fme(e,{Fragment:f.Fragment,components:i,ignoreInvalidStyle:!0,jsx:f.jsx,jsxs:f.jsxs,passKeys:!0,passNode:!0});function u(m,h,g){if(m.type==="raw"&&g&&typeof h=="number")return o?g.children.splice(h,1):g.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let b;for(b in Uw)if(Object.hasOwn(Uw,b)&&Object.hasOwn(m.properties,b)){const x=m.properties[b],_=Uw[b];(_===null||_.includes(m.tagName))&&(m.properties[b]=c(String(x||""),b,m))}}if(m.type==="element"){let b=n?!n.includes(m.tagName):s?s.includes(m.tagName):!1;if(!b&&r&&typeof h=="number"&&(b=!r(m,h,g)),b&&g&&typeof h=="number")return l&&m.children?g.children.splice(h,1,...m.children):g.children.splice(h,1),h}}}function Gge(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),i=e.indexOf("/");return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||$ge.test(e.slice(0,t))?e:""}const wv=new Map;function qge(e){return`${e.id}|${e.contentUrl}|${e.size??0}`}function g0(e){const t=qge(e),n=wv.get(t),[r,i]=v.useState(n??{status:"loading"}),[s,o]=v.useState(t),l=v.useRef(t);return l.current=t,s!==t&&(o(t),i(wv.get(t)??{status:"loading"})),v.useEffect(()=>{if(n&&n.status!=="loading")return;let c=!1;const u=t;return BE(e.contentUrl,A8).then(m=>{if(c||l.current!==u)return;const h={status:"ready",content:m.content,truncated:m.truncated};wv.set(u,h),i(h)}).catch(m=>{if(c||l.current!==u)return;const g={status:"error",message:m instanceof Error?m.message:"Unable to load preview."};wv.set(u,g),i(g)}),()=>{c=!0}},[n,t,e.contentUrl]),r}function Kge({source:e}){const t=g0(e);return t.status==="loading"?f.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[f.jsx("div",{className:"prose hidden"})," Loading…"]}):t.status==="error"?f.jsx("div",{className:"p-4 text-sm text-destructive",children:t.message}):f.jsxs("div",{className:"space-y-2 overflow-auto p-3",children:[t.truncated?f.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:"Preview truncated to 1024 KB."}):null,f.jsx("div",{className:"prose prose-sm prose-invert max-w-none rounded-xl border border-border bg-background p-4",children:f.jsx(lu,{remarkPlugins:Sf,components:Cf,children:t.content})})]})}const Sv=new Map;function Yge(e){return`${e.id}|${e.contentUrl}|${e.size??0}|${e.mimeType}`}function Xge({source:e}){const t=Yge(e),n=Sv.get(t),[r,i]=v.useState(n??{status:"loading"}),[s,o]=v.useState(t),l=v.useRef(t);if(l.current=t,s!==t&&(o(t),i(Sv.get(t)??{status:"loading"})),v.useEffect(()=>{if(n&&n.status!=="loading")return;const g=e.mimeType==="text/tab-separated-values"?" ":",";let b=!1;const x=t;return BE(e.contentUrl,A8).then(_=>{if(b||l.current!==x)return;const w={status:"ready",table:Nue(_.content,g),truncated:_.truncated};Sv.set(x,w),i(w)}).catch(_=>{if(b||l.current!==x)return;const w={status:"error",message:_ instanceof Error?_.message:"Unable to load preview."};Sv.set(x,w),i(w)}),()=>{b=!0}},[n,t,e.contentUrl,e.mimeType]),r.status==="loading")return f.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[f.jsx("table",{className:"sr-only"})," Loading…"]});if(r.status==="error")return f.jsxs("div",{className:"p-4 text-sm text-destructive",children:[f.jsx("table",{className:"sr-only"})," ",r.message]});const{table:c}=r,[u,...m]=c.rows,h=[r.truncated?"Preview truncated to 1024 KB.":null,c.truncatedRows?`Showing first ${c.rows.length} of ${c.rowCount} rows.`:null,c.truncatedColumns?`Showing first ${z1} of ${c.columnCount} columns.`:null].filter(Boolean);return f.jsxs("div",{className:"space-y-2 overflow-auto p-3",children:[h.length?f.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:h.join(" ")}):null,f.jsx("div",{className:"max-h-[70dvh] overflow-auto rounded-xl border border-border bg-background",children:f.jsxs("table",{className:"min-w-full border-collapse text-xs",children:[u?f.jsx("thead",{className:"sticky top-0 bg-muted",children:f.jsx("tr",{children:u.map((g,b)=>f.jsx("th",{className:"border-b border-border px-3 py-2 text-left font-medium",children:g||" "},b))})}):null,f.jsx("tbody",{children:m.map((g,b)=>f.jsx("tr",{className:"odd:bg-background even:bg-muted/20",children:g.map((x,_)=>f.jsx("td",{className:"max-w-[320px] border-b border-border px-3 py-2 align-top",children:f.jsx("div",{className:"whitespace-pre-wrap break-words",children:x||" "})},_))},b))})]})})]})}function Qge({source:e}){const t=g0(e);return t.status==="loading"?f.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[f.jsx("pre",{className:"sr-only"})," Loading…"]}):t.status==="error"?f.jsxs("div",{className:"p-4 text-sm text-destructive",children:[f.jsx("pre",{className:"sr-only"})," ",t.message]}):f.jsxs("div",{className:"space-y-2 overflow-auto p-3",children:[t.truncated?f.jsx(Zge,{children:"Preview truncated to 1024 KB."}):null,f.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-xl border border-border bg-background p-3 text-xs",children:t.content})]})}function Zge({children:e}){return f.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:e})}function Jge({source:e}){const t=g0(e),n=v.useMemo(()=>t.status==="ready"?Tue(t.content):"",[t]);return t.status==="loading"?f.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[f.jsx("pre",{className:"sr-only"})," Loading…"]}):t.status==="error"?f.jsxs("div",{className:"p-4 text-sm text-destructive",children:[f.jsx("pre",{className:"sr-only"})," ",t.message]}):f.jsxs("div",{className:"space-y-2 overflow-auto p-3",children:[t.truncated?f.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:"Preview truncated to 1024 KB."}):null,f.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-xl border border-border bg-background p-3 text-xs",children:n})]})}function eve({source:e}){return f.jsxs("div",{className:"flex h-full flex-col items-stretch justify-center gap-3 p-4",children:[f.jsx("div",{className:"text-sm font-medium text-foreground",children:e.displayName}),f.jsx("audio",{src:e.contentUrl,controls:!0,preload:"metadata",className:"w-full"})]})}function tve({source:e}){return f.jsx("div",{className:"flex h-full items-center justify-center bg-black/40 p-2",children:f.jsx("video",{src:e.contentUrl,controls:!0,playsInline:!0,preload:"metadata",className:"max-h-[60dvh] w-full rounded-xl"})})}const nve=200*1024;function rve(e){const t=e.lastIndexOf(".");if(t<0)return"text";const n=e.slice(t+1).toLowerCase();return{ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",go:"go",rs:"rust",java:"java",rb:"ruby",sh:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",css:"css",scss:"scss",html:"html",json:"json",md:"markdown",sql:"sql",cpp:"cpp",c:"c",h:"c",swift:"swift",kt:"kotlin",php:"php",toml:"toml"}[n]??"text"}function ive({source:e}){const t=g0(e),n=t.status==="ready"&&t.content.length<=nve,r=n?`${e.id}|${e.contentUrl}|${e.size??0}|${t.content.length}`:null,[i,s]=v.useState(null);return v.useEffect(()=>{if(!n||t.status!=="ready"||r===null)return;let o=!1;const l=r;return K(()=>Promise.resolve().then(()=>_le),void 0).then(async c=>{if(o)return;const u=await c.codeToHtml(t.content,{lang:rve(e.fileName),theme:"github-dark"});o||s({key:l,html:u})}).catch(()=>{typeof console<"u"&&console.warn("[file-preview] Shiki unavailable; falling back to plain text")}),()=>{o=!0}},[n,r,t,e.fileName]),t.status==="loading"?f.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[f.jsx("pre",{className:"sr-only"})," Loading…"]}):t.status==="error"?f.jsxs("div",{className:"p-4 text-sm text-destructive",children:[f.jsx("pre",{className:"sr-only"})," ",t.message]}):i&&i.key===r?f.jsx("div",{className:"overflow-auto p-3 text-xs",dangerouslySetInnerHTML:{__html:i.html}}):f.jsxs("div",{className:"space-y-2 overflow-auto p-3",children:[t.truncated?f.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:"Preview truncated to 1024 KB."}):null,f.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-xl border border-border bg-background p-3 text-xs",children:t.content})]})}async function sve(e){var r;const t=ave(e.contentUrl),n=navigator.share;if(typeof n=="function")try{return await n.call(navigator,{title:e.displayName,url:t}),"shared"}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return"shared"}if((r=navigator.clipboard)!=null&&r.writeText)try{return await navigator.clipboard.writeText(t),"copied"}catch{return"failed"}return"failed"}function ove(e){const t=document.createElement("a");t.href=e.contentUrl,t.download=e.fileName,t.rel="noopener",document.body.appendChild(t),t.click(),t.remove()}function ave(e){return typeof window>"u"?e:new URL(e,document.baseURI||window.location.href).toString()}function wf({source:e,open:t,onOpenChange:n}){const r=v.useCallback(()=>n(!1),[n]);return f.jsx(As,{open:t&&e!==null,onOpenChange:n,children:f.jsx(es,{size:"lg",className:"inset-0 h-[100dvh] max-h-none w-full max-w-none translate-x-0 translate-y-0 rounded-none p-0 md:inset-auto md:left-1/2 md:top-1/2 md:h-auto md:max-h-[90dvh] md:w-auto md:max-w-3xl md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-2xl",children:e?f.jsx(lve,{source:e,onClose:r}):null})})}function lve({source:e,onClose:t}){const n=uve(e),[r,i]=v.useState(0),s=v.useRef(null),o=v.useCallback(h=>{s.current={y:h.clientY,lastY:h.clientY,lastT:Date.now()};try{h.currentTarget.setPointerCapture(h.pointerId)}catch{}},[]),l=v.useCallback(h=>{if(!s.current)return;const g=h.clientY-s.current.y;g<0||(s.current.lastY=h.clientY,s.current.lastT=Date.now(),i(g))},[]),c=v.useCallback(h=>{const g=s.current;s.current=null;try{h.currentTarget.releasePointerCapture(h.pointerId)}catch{}if(!g)return;const b=h.clientY-g.y,x=Math.max(1,Date.now()-g.lastT),_=(h.clientY-g.lastY)/x;b>120||_>.5?t():i(0)},[t]),u=v.useCallback(()=>{sve(e)},[e]),m=v.useCallback(()=>ove(e),[e]);return f.jsxs("div",{className:"flex h-full max-h-full flex-col",style:r>0?{transform:`translateY(${r}px)`,transition:"none"}:void 0,children:[f.jsxs("div",{onPointerDown:o,onPointerMove:l,onPointerUp:c,onPointerCancel:c,className:"border-b border-border px-4 py-3 touch-none",children:[f.jsx("div",{className:"mx-auto mb-2 h-1 w-12 rounded-full bg-muted md:hidden",role:"button","aria-label":"Drag down to close"}),f.jsx(Ms,{className:"truncate text-base",children:e.displayName}),f.jsx(af,{className:"truncate text-xs",children:n})]}),f.jsx("div",{className:"min-h-0 flex-1 overflow-auto",role:"region","aria-label":"File preview",children:v.createElement(cve(e),{source:e})},e.id),f.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border px-4 py-3",children:[f.jsxs(Ue,{type:"button",variant:"outline",onClick:u,children:[f.jsx(OG,{className:"mr-2 h-4 w-4"}),"Share"]}),e.origin==="offer_download"?f.jsxs(Ue,{type:"button",onClick:m,children:[f.jsx(rk,{className:"mr-2 h-4 w-4"}),"Download"]}):null]})]})}function cve(e){const t={id:e.id,displayName:e.displayName,mimeType:e.mimeType,size:e.size??0,contentUrl:e.contentUrl,relativePath:e.relativePath??""},n=xf(t);return n==="image"?kme:n==="pdf"?Oj:n==="audio"?eve:n==="video"?tve:n==="table"?Xge:n==="markdown"?Kge:n==="json"?Jge:n==="code"?ive:yf(t).kind==="external"?Oj:Qge}function uve(e){const t={id:e.id,displayName:e.displayName,mimeType:e.mimeType,size:e.size??0,contentUrl:e.contentUrl,relativePath:e.relativePath??""},n=xf(t),r=u0(n,e.mimeType),i=e.size?` · ${kf(e.size)}`:"";return`${r}${i}`}function yp(e,t){return{id:e.id,contentUrl:e.contentUrl,displayName:e.displayName,fileName:e.displayName,relativePath:e.relativePath,mimeType:e.mimeType,size:e.size,origin:t}}function dve(e){const t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function fve({path:e,linkText:t}){const n=v.useMemo(()=>qE(e),[e]),[r,i]=v.useState({kind:"loading"}),[s,o]=v.useState(!1);v.useEffect(()=>{const A=new AbortController;return fetch(n,{method:"HEAD",signal:A.signal}).then(M=>{var D,O;if(A.signal.aborted)return;if(!M.ok){i({kind:M.status===404?"missing":"error"});return}const L=((O=(D=M.headers.get("Content-Type"))==null?void 0:D.split(";")[0])==null?void 0:O.trim())||"application/octet-stream",F=Number.parseInt(M.headers.get("Content-Length")??"0",10)||0;i({kind:"ready",mimeType:L,size:F})}).catch(()=>{A.signal.aborted||i({kind:"error"})}),()=>A.abort()},[n]);const l=dve(e),c=t||l,u=Cme(c,28),m=r.kind==="ready"?r.mimeType:"application/octet-stream",h=r.kind==="ready"?r.size:0,g={id:`local-file-${n}`,kind:"file",displayName:u,absolutePath:e,relativePath:e,contentUrl:n,mimeType:m,size:h};if(r.kind==="missing")return f.jsx("span",{className:"inline-flex align-bottom","data-testid":"local-file-link",children:f.jsx(Do,{attachment:g,disabledReason:"File no longer available"})});const b=xf(g),x=u0(b,m),_=h>0?kf(h):null,w=r.kind==="loading",C=r.kind==="error",E=w?f.jsx("span",{className:"text-muted-foreground",children:"Fetching…"}):C?f.jsx("span",{className:"text-muted-foreground",children:"Unable to load"}):f.jsxs(f.Fragment,{children:[x,_?f.jsxs(f.Fragment,{children:[" · ",f.jsx("span",{className:"tabular-nums",children:_})]}):null]}),k=r.kind==="ready"?yf(g):null,N=k!==null&&!k.openInNewTab,R=[N?"Preview":"Download",c,x,_].filter(Boolean);return N?f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"inline-flex align-bottom","data-testid":"local-file-link",children:f.jsx(Do,{attachment:g,onClick:()=>o(!0),meta:E,ariaLabel:R.join(", ")})}),f.jsx(wf,{source:s?yp(g,"local_file_link"):null,open:s,onOpenChange:o})]}):f.jsx("span",{className:"inline-flex align-bottom","data-testid":"local-file-link",children:f.jsx(Do,{attachment:g,href:n,download:l,meta:E,ariaLabel:R.join(", ")})})}const hve={readonly:!1,localLinkMode:"open",attachmentMode:"live"},mve=v.createContext(hve);function v0(){return v.useContext(mve)}const sy=()=>{},IB=v.createContext(sy);function PB({children:e,onOpenLocalLink:t}){return f.jsx(IB.Provider,{value:t??sy,children:e})}const K1={Task:_b,TaskOutput:_b,Bash:ky,Glob:Gh,Grep:Gh,ExitPlanMode:WA,Read:k5,Edit:aW,Write:cW,Delete:gW,NotebookEdit:Qm,WebFetch:iV,TodoWrite:wV,WebSearch:Gh,KillShell:KG,AskUserQuestion:R5,Skill:HG,EnterPlanMode:WA},OB=sq;function zB(e){return K1[e]?K1[e]:OB}function BB({icon:e,className:t}){return f.jsx(e,{className:t})}function ja({children:e,className:t}){return f.jsx("div",{className:he("flex gap-3 justify-start items-center",t),children:e})}function FB({children:e,className:t}){return f.jsx("div",{className:he("flex items-center gap-1.5 text-xs",t),children:e})}function Fl({children:e,className:t}){return f.jsx("span",{className:he("font-medium text-foreground/80",t),children:e})}function pve({children:e}){return f.jsx("span",{className:"text-muted-foreground",children:e})}function gve({children:e,className:t}){return f.jsxs(ja,{className:he("px-0.5 text-xs tracking-wide",t),children:[f.jsx("div",{className:"w-full h-[1px] bg-border"}),f.jsx(Fl,{className:"whitespace-nowrap text-[11px] tracking-widest text-muted-foreground/60 uppercase flex-shrink-0",children:e}),f.jsx("div",{className:"w-full h-[1px] bg-border"})]})}function b0({children:e,expandedContent:t,defaultExpanded:n=!1}){const[r,i]=v.useState(n);return f.jsxs("div",{className:"flex flex-col w-full",children:[f.jsxs("button",{onClick:()=>i(!r),className:`group/expandable-row cursor-pointer grid grid-cols-[auto_1fr] items-center gap-1 text-sm ${r?"":"hover:opacity-60 transition-opacity"}`,children:[f.jsx("div",{className:"grid grid-cols-[auto_1fr] items-center gap-1.5",children:e}),f.jsx(Po,{className:`h-4.5 w-4.5 text-muted-icon translate-y-[0.5px] transition-all duration-200 opacity-0 group-hover/expandable-row:opacity-100 ${r?"rotate-90 opacity-100":""}`})]}),r&&t]})}function cD({label:e,children:t,copyText:n}){const[r,i]=v.useState(!1),s=n??oy(t),o=v.useCallback(async()=>{await navigator.clipboard.writeText(s),i(!0),setTimeout(()=>i(!1),2e3)},[s]);return f.jsxs("div",{children:[f.jsx("span",{className:"font-medium text-muted-foreground",children:e}),f.jsxs("div",{className:"relative group/codeblock",children:[f.jsx("pre",{className:"my-1 text-xs font-mono whitespace-no-wrap break-all bg-muted border border-border rounded-lg p-2 max-h-64 overflow-auto w-full",children:t}),f.jsx(Ue,{variant:"ghost",size:"icon","aria-label":r?"Copied":"Copy code",className:he("absolute top-[4px] right-[4px] z-10 h-11 w-11 md:h-6.5 md:w-6.5 rounded-sm text-muted-foreground opacity-100 md:opacity-0 md:group-hover/codeblock:opacity-100 transition-opacity [@media(hover:none)]:!opacity-100",!r&&"hover:text-foreground",r&&"hover:!bg-transparent hover:!border-transparent"),onClick:o,children:r?f.jsx(_i,{className:"h-3.5 w-3.5 text-success"}):f.jsx(Pl,{className:"h-4 w-4"})})]})]})}function $B({children:e,icon:t,className:n}){return f.jsxs("span",{className:he("inline-flex items-center gap-1 px-2 py-1 bg-muted border border-border rounded-full",n),children:[t&&f.jsx(t,{className:"h-3 w-3 text-muted-foreground"}),e]})}function y0({children:e,className:t}){return f.jsxs("div",{className:he("grid grid-cols-[auto_1fr] gap-2 min-w-0",t),children:[f.jsx("div",{className:" min-w-5 flex flex-col relative items-center justify-center",children:f.jsx("div",{className:"min-h-full w-[1px] bg-muted-foreground/20"})}),f.jsx("div",{className:"-ml-[1px] min-w-0 overflow-hidden",children:e})]})}function oy(e){if(typeof e=="string")return e;if(typeof e=="number")return String(e);if(Array.isArray(e))return e.map(oy).join("");if(e&&typeof e=="object"&&"props"in e){const t=e.props;return oy(t.children)}return""}function uD(e,t){return v.isValidElement(e)?v.cloneElement(e,{className:he(e.props.className,t)}):e}function vve({children:e,...t}){const[n,r]=v.useState(!1),i=oy(e),s=async()=>{await navigator.clipboard.writeText(i),r(!0),setTimeout(()=>r(!1),2e3)};return f.jsxs("div",{className:"relative overflow-x-auto max-w-full min-w-0 no-code-highlight group/pre",children:[f.jsx("pre",{className:"min-w-0 rounded-xl py-2.5 px-3.5 [.no-pre-highlight_&]:bg-background",...t,children:e}),f.jsx(Ue,{variant:"ghost",size:"icon","aria-label":n?"Copied":"Copy code",className:he("absolute top-[35px] -translate-y-[50%] -translate-x-[1px] rounded-md right-1.5 h-11 w-11 md:h-8 md:w-8 text-muted-foreground opacity-100 md:opacity-0 md:group-hover/pre:opacity-100 transition-opacity [@media(hover:none)]:!opacity-100",!n&&"hover:text-foreground",n&&"hover:!bg-transparent hover:!border-transparent"),onClick:s,children:n?f.jsx(_i,{className:"h-4 w-4 text-success"}):f.jsx(Pl,{className:"h-4 w-4"})})]})}const r2={h1:({children:e})=>f.jsx("h1",{className:"text-[20px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",children:e}),h2:({children:e})=>f.jsx("h2",{className:"text-[18px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",children:e}),h3:({children:e})=>f.jsx("h3",{className:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",children:e}),h4:({children:e})=>f.jsx("h4",{className:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",children:e}),h5:({children:e})=>f.jsx("h5",{className:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",children:e}),h6:({children:e})=>f.jsx("h6",{className:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",children:e}),pre:vve,code:({children:e,className:t,...n})=>t?f.jsx("code",{className:"block text-xs whitespace-pre",...n,children:e}):f.jsx("code",{className:"break-all px-1 bg-border/60 dark:[.no-pre-highlight_&]:bg-background dark:[.text-pretty_&]:bg-neutral [.no-code-highlight_&]:!bg-transparent py-0.5 rounded text-sm whitespace-wrap",...n,children:e}),table:({children:e,...t})=>f.jsx("div",{className:"border border-border rounded-xl overflow-x-auto",children:f.jsx("table",{className:"table-auto min-w-full divide-y divide-border bg-background",...t,children:e})}),tbody:({children:e,...t})=>f.jsx("tbody",{className:"divide-y divide-border",...t,children:e}),th:({children:e,...t})=>f.jsx("th",{className:"text-left text-xs uppercase text-muted-foreground tracking-wider p-2 pl-0 first:pl-3 bg-muted dark:bg-card [&_*]:font-semibold",...t,children:e}),td:({children:e,...t})=>f.jsx("td",{className:"text-left p-2 pl-0 first:pl-3 [&_*]:font-normal ",...t,children:e}),p:({children:e,...t})=>f.jsx("p",{className:"break-words mt-5 mb-3 first:mt-0 last:mb-0",...t,children:e}),blockquote:({children:e,...t})=>(()=>{const n=v.Children.toArray(e),r=n[0];r!==void 0&&(n[0]=uD(r,"mt-0"));const i=n.length-1,s=n[i];return s!==void 0&&(n[i]=uD(s,"mb-0")),f.jsx("blockquote",{className:"my-2 mt-5 mb-3 first:mt-0 last:mb-0 border-l-2 border-border/80 pl-2 text-muted-foreground",...t,children:n})})(),a:({children:e,...t})=>f.jsx("a",{className:"transition-all underline decoration-2 text-logo decoration-logo/50 hover:text-logo/70 dark:text-logo dark:decoration-logo/70 dark:hover:text-logo/60 dark:hover:decoration-logo/40 ",target:"_blank",rel:"noopener noreferrer",...t,children:e}),img:({src:e,...t})=>{const n=typeof e=="string"&&Sme(e)?qE(e):e;return f.jsx("img",{src:n,...t})}};function bve({children:e,href:t,onClick:n,overrideOpenLocalLink:r,...i}){const s=v.useContext(IB),o=r??s,l=v0(),c=_me(t);if(c&&l.localLinkMode==="text")return f.jsx("span",{className:"transition-all underline decoration-2 text-logo decoration-logo/50",children:e});if(c&&!bB(c.path)){const u=Y1(e).trim();return f.jsx(fve,{path:c.path,linkText:u||void 0})}return f.jsx("a",{className:"transition-all underline decoration-2 text-logo decoration-logo/50 hover:text-logo/70 dark:text-logo dark:decoration-logo/70 dark:hover:text-logo/60 dark:hover:decoration-logo/40 ",href:t,target:c?void 0:"_blank",rel:c?void 0:"noopener noreferrer",onClick:u=>{n==null||n(u),!(u.defaultPrevented||!c||o===sy)&&(u.preventDefault(),o({...c,clientX:u.clientX,clientY:u.clientY,trigger:"click"}))},onContextMenu:u=>{!c||o===sy||(u.preventDefault(),o({...c,clientX:u.clientX,clientY:u.clientY,trigger:"contextmenu"}))},...i,children:e})}function yve(e){return{...r2,a:t=>f.jsx(bve,{...t,overrideOpenLocalLink:e==null?void 0:e.onOpenLocalLink})}}const Sf=[vB],Cf=yve();function Y1(e){return e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(Y1).join(""):v.isValidElement(e)?Y1(e.props.children):""}({...r2});function i2({attachment:e,previewUrl:t,onClick:n,onRemove:r,className:i,size:s="transcript",uploadProgress:o,onCancelUpload:l}){const c=e.contentUrl||t,u=s==="composer",m=o!==void 0;return f.jsxs("div",{className:he("group relative flex flex-row items-end",i),children:[f.jsxs("button",{type:"button",onClick:n,className:he("group/image relative overflow-hidden rounded-xl border border-border/80 bg-background shadow-sm",u?"min-w-[80px]":"min-w-[200px]"),children:[c?f.jsx("img",{src:c,alt:e.displayName,className:he("rounded-xl object-contain bg-muted",u?"min-h-[50px] min-w-[80px] max-h-[120px] max-w-[200px]":"min-h-[100px] min-w-[200px] max-h-[300px] max-w-[300px]")}):f.jsx("div",{className:he("flex items-center justify-center rounded-xl bg-muted text-muted-foreground",u?"min-h-[64px] min-w-[80px]":"min-h-[160px] min-w-[200px]"),children:f.jsx(C5,{className:he(u?"size-6":"size-8")})}),f.jsxs("div",{className:he("pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/75 via-black/30 to-transparent text-left opacity-0 transition-opacity duration-200 group-hover/image:opacity-100",u?"px-2.5 pb-2 pt-6":"px-4 pb-3 pt-10"),children:[f.jsx("div",{className:he("truncate font-medium text-white",u?"text-xs":"text-sm"),children:e.displayName}),f.jsxs("div",{className:"truncate text-xs text-white/80",children:[e.mimeType," · ",kf(e.size)]})]})]}),m?f.jsx(I8,{progress:o??null,onCancel:l,size:u?"sm":"md",cancelLabel:`Cancel upload of ${e.displayName}`}):null,r&&!m?f.jsx(HB,{displayName:e.displayName,onRemove:r}):null]})}function Do({attachment:e,onClick:t,onRemove:n,className:r,uploadProgress:i,onCancelUpload:s,href:o,download:l,meta:c,ariaLabel:u,disabledReason:m}){const h=e.kind==="mention"?"text":xf(e),g=wve(h),b=e.kind==="mention",x=b?xve(e.displayName):e.displayName,_=b?_ve(e.displayName):"",w=i!==void 0,C=!!m,E=he("flex w-[200px] items-center gap-2 rounded-xl border border-border bg-background p-1 pr-3 text-left transition-colors",C?"cursor-not-allowed opacity-60":"hover:bg-accent/50"),k=b?f.jsx("div",{className:"max-w-[150px] truncate text-[11px] text-muted-foreground",children:_?`@${_}`:"@mention"}):m?f.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:m}):c!==void 0?f.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:c}):f.jsxs("div",{className:"truncate text-[11px] text-muted-foreground",children:[e.mimeType," · ",kf(e.size)]}),N=f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"flex min-h-10 min-w-10 items-center justify-center rounded-lg border border-border bg-muted text-muted-foreground",children:f.jsx(BB,{icon:g,className:"size-5"})}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:he("max-w-[150px] truncate text-[13px] font-medium",C?"text-muted-foreground line-through":"text-foreground"),children:x}),k]})]});return f.jsxs("div",{className:he("group relative",r),children:[o&&!C?f.jsx("a",{href:o,download:l,rel:"noopener","aria-label":u,className:E,children:N}):f.jsx("button",{type:"button",onClick:C?void 0:t,title:b?e.displayName:void 0,"aria-label":u,"aria-disabled":C||void 0,disabled:C,className:E,children:N}),w?f.jsx(I8,{progress:i??null,onCancel:s,size:"sm",cancelLabel:`Cancel upload of ${e.displayName}`}):null,n&&!w?f.jsx(HB,{displayName:e.displayName,onRemove:n}):null]})}function xve(e){const t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function _ve(e){const t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function HB({displayName:e,onRemove:t}){return f.jsx("button",{type:"button",className:"absolute right-2 top-2 rounded-full bg-background/90 p-1 text-muted-foreground shadow-sm transition hover:bg-muted hover:text-foreground",onClick:n=>{n.preventDefault(),n.stopPropagation(),t()},"aria-label":`Remove ${e}`,children:f.jsx(io,{className:"h-3.5 w-3.5"})})}function wve(e){switch(e){case"image":return C5;case"pdf":return xG;case"markdown":return NG;case"json":return eW;case"table":return dW;case"code":return nW;case"text":return sk;case"archive":return ZV;case"audio":return iW;case"video":return mW;default:return k5}}function kf(e){return e<1024?`${e} B`:e<1024*1024?`${Math.max(1,Math.round(e/1024))} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}const xp=v.forwardRef(({className:e,...t},n)=>f.jsx("textarea",{"data-gramm":"false","data-gramm_editor":"false","data-enable-grammarly":"false","data-1p-ignore":!0,autoComplete:"off",className:he("flex w-full rounded-lg border border-border bg-background px-2.5 py-2 text-sm placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));xp.displayName="Textarea";const Cv={};function dD(e){return!e.isCollapsed&&!e.hasPreviewAttachment&&e.patch===void 0&&e.patchError===void 0&&!e.isPatchLoading}function Sve(e,t){return!e||!t.mimeType||typeof t.size!="number"||t.changeType==="deleted"||!t.mimeType.startsWith("image/")&&t.mimeType!=="application/pdf"?null:{id:`diff:${t.path}`,kind:t.mimeType.startsWith("image/")?"image":"file",displayName:t.path.split("/").pop()??t.path,absolutePath:t.path,relativePath:t.path,contentUrl:`/api/projects/${e}/files/${encodeURIComponent(t.path)}/content`,mimeType:t.mimeType,size:t.size}}function UB(e){return e.isUntracked}function Cve(e){return UB(e)?e.path.includes("/"):!1}function Zw(e){return f.jsxs(Qr,{delayDuration:0,children:[f.jsx(Zr,{asChild:!0,children:f.jsx("button",{type:"button","aria-label":e.label,title:e.label,onClick:e.onClick,className:he("flex h-11 w-11 md:h-7 md:w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",e.active&&"bg-accent text-foreground"),children:e.children})}),f.jsx(Hr,{children:e.label})]})}function VB({checked:e,mixed:t=!1,label:n,className:r,onClick:i}){return f.jsx("button",{type:"button","aria-label":n??(e?"Exclude file from commit":"Include file in commit"),"aria-checked":t?"mixed":e,"aria-pressed":t?"mixed":e,onClick:s=>{s.stopPropagation(),i()},className:he("flex size-4.5 shrink-0 items-center justify-center rounded border transition-colors",e||t?"border-foreground bg-foreground text-background":"border-border bg-background text-transparent",r),children:t?f.jsx(eG,{className:"h-3 w-3",strokeWidth:3}):e?f.jsx(_i,{className:"h-3 w-3",strokeWidth:3}):null})}function s2(e){const t=Date.parse(e);if(!Number.isFinite(t))return"";const n=Date.now()-t,r=6e4,i=60*r,s=24*i,o=7*s,l=30*s,c=365*s;return n<r?"just now":n<i?`${Math.round(n/r)}m ago`:n<s?`${Math.round(n/i)}hr ago`:n<o?`${Math.round(n/s)}d ago`:n<l?`${Math.round(n/o)}wk ago`:n<c?`${Math.round(n/l)}mo ago`:`${Math.round(n/c)}yr ago`}function kve(e){return e?`Last fetched ${s2(e)}`:"No local fetch recorded"}function Eve({entry:e,isPendingPush:t=!1}){const n=s2(e.authoredAt),r=!!e.githubUrl;return f.jsxs("button",{type:"button",disabled:!r,onClick:()=>{!e.githubUrl||typeof window>"u"||window.open(e.githubUrl,"_blank","noopener,noreferrer")},className:he("flex w-full items-start gap-3 rounded-lg border border-border bg-background pl-3 pr-2 py-2 text-left transition-colors",r?"hover:bg-accent":"cursor-default opacity-60"),children:[f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:e.summary}),e.description?f.jsx("div",{className:"mt-1 line-clamp-2 whitespace-pre-wrap text-xs text-muted-foreground",children:e.description}):null,f.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-xs text-muted-foreground",children:[e.authorName?f.jsx("span",{className:"truncate",children:e.authorName}):null,e.authorName&&n?f.jsx("span",{"aria-hidden":"true",children:"•"}):null,n?f.jsx("span",{children:n}):null]})]}),e.tags.length>0?f.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-1",children:[e.tags.map(i=>f.jsx("span",{className:"inline-flex items-center rounded-full bg-muted border border-border px-2 py-0.5 text-[11px]",children:i},i)),t?f.jsx("span",{className:"inline-flex items-center rounded-full bg-muted border border-border px-2 py-0.5 text-[11px]",children:f.jsx(um,{className:"size-3"})}):null]}):t?f.jsx("div",{className:"flex shrink-0 flex-wrap justify-end gap-1",children:f.jsx("span",{className:"inline-flex items-center rounded-full bg-muted border border-border px-2 py-0.5 text-[11px]",children:f.jsx(um,{className:"size-3"})})}):null]})}function fD(e){switch(e.kind){case"local":return 0;case"pull_request":return 1;case"remote":default:return 2}}function Tve(e){const t=new Map;for(const n of e){const r=t.get(n.name);(!r||fD(n)<fD(r))&&t.set(n.name,n)}return t}function Nve(e,t){const n=Tve([...e.local,...e.pullRequests,...e.remote]);t&&n.delete(t);const r=new Set,i=e.defaultBranchName?n.get(e.defaultBranchName):void 0;i&&r.add(i.name);const s=e.recent.map(l=>n.get(l.name)??l).filter(l=>!!l&&!r.has(l.name));for(const l of s)r.add(l.name);const o=[...n.values()].filter(l=>!r.has(l.name)).sort((l,c)=>l.displayName.localeCompare(c.displayName));return{defaultBranch:i,recent:s,other:o}}function Rve({open:e,onOpenChange:t,onGetGitHubPublishInfo:n,onCheckGitHubRepoAvailability:r,onPublish:i}){const[s,o]=v.useState(null),[l,c]=v.useState(!1),[u,m]=v.useState(""),[h,g]=v.useState(""),[b,x]=v.useState("private"),[_,w]=v.useState(""),[C,E]=v.useState(null),[k,N]=v.useState(!1),[R,A]=v.useState(!1);v.useEffect(()=>{if(!e)return;let F=!1;return c(!0),E(null),n().then(D=>{F||(o(D),m(D.owners[0]??D.activeAccountLogin??""),g(D.suggestedRepoName),x("private"),w(""))}).finally(()=>{F||c(!1)}),()=>{F=!0}},[n,e]),v.useEffect(()=>{if(!e||!(s!=null&&s.ghInstalled)||!s.authenticated)return;const F=u.trim(),D=h.trim();if(!F||!D){E(null);return}let O=!1;N(!0);const z=window.setTimeout(()=>{r({owner:F,name:D}).then(P=>{O||E(P)}).finally(()=>{O||N(!1)})},250);return()=>{O=!0,window.clearTimeout(z)}},[s==null?void 0:s.authenticated,s==null?void 0:s.ghInstalled,h,r,e,u]);async function M(){if(!(!u.trim()||!h.trim())){A(!0);try{const F=await i({owner:u.trim(),name:h.trim(),visibility:b,description:_});F!=null&&F.ok&&t(!1)}finally{A(!1)}}}const L=!!(s!=null&&s.ghInstalled&&s.authenticated&&u.trim()&&h.trim()&&(C!=null&&C.available)&&!k&&!R);return f.jsx(As,{open:e,onOpenChange:t,children:f.jsxs(es,{size:"sm",className:"max-w-[min(92vw,475px)]",children:[f.jsxs(Oo,{className:"space-y-2 px-4 pb-4 pt-4",children:[f.jsxs("div",{className:"space-y-1",children:[f.jsx(Ms,{children:"Push to GitHub"}),f.jsx(af,{children:"Create a GitHub repository from this local project using GitHub CLI."})]}),l?f.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[f.jsx(bn,{className:"size-4 animate-spin"}),f.jsx("span",{children:"Checking GitHub CLI…"})]}):s&&!s.ghInstalled?f.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[f.jsx("p",{children:"GitHub CLI is not installed."}),f.jsx("div",{className:"rounded-lg border border-border px-3 py-2 font-mono text-xs text-foreground",children:"brew install gh"}),f.jsx("p",{children:"Then run:"}),f.jsx("div",{className:"rounded-lg border border-border px-3 py-2 font-mono text-xs text-foreground",children:"gh auth login"})]}):s&&!s.authenticated?f.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[f.jsx("p",{children:"GitHub CLI is installed but not signed in."}),f.jsx("div",{className:"rounded-lg border border-border px-3 py-2 font-mono text-xs text-foreground",children:"gh auth login"})]}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"space-y-2",children:f.jsxs(pa,{value:u,onValueChange:m,children:[f.jsx(Eo,{className:"pl-[11px] [&>span]:flex [&>span]:items-center [&>span]:gap-2",children:f.jsx(El,{placeholder:"Select owner"})}),f.jsx(To,{children:((s==null?void 0:s.owners)??[]).map(F=>f.jsx(ws,{value:F,children:f.jsxs("span",{className:"flex items-center gap-2",children:[F===(s==null?void 0:s.activeAccountLogin)?f.jsx(Ey,{className:"size-4 text-muted-foreground"}):f.jsx(bV,{className:"size-4 text-muted-foreground"}),f.jsx("span",{className:"pl-[1px]",children:F})]})},F))})]})}),f.jsx("div",{className:"space-y-2",children:f.jsxs("div",{className:"relative",children:[f.jsx($n,{value:h,onChange:F=>g(F.target.value),placeholder:"my-repo",className:"pl-9 pr-10"}),f.jsx(fG,{className:"pointer-events-none absolute inset-y-0 left-3 my-auto size-4 text-muted-foreground"}),k?f.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-3 flex items-center text-muted-foreground",children:f.jsx(bn,{className:"size-4 animate-spin"})}):C?f.jsx("div",{className:"absolute inset-y-0 right-2 flex items-center",children:f.jsxs(Qr,{delayDuration:0,children:[f.jsx(Zr,{asChild:!0,children:f.jsx("button",{type:"button",tabIndex:-1,"aria-label":C.message,className:he("flex size-6 items-center justify-center rounded-md",C.available?"text-success":"text-destructive"),children:C.available?f.jsx(_i,{className:"size-4"}):f.jsx(wb,{className:"size-4"})})}),f.jsx(Hr,{children:C.message})]})}):null]})}),f.jsx("div",{className:"space-y-2",children:f.jsxs("div",{className:"relative",children:[f.jsx(sk,{className:"pointer-events-none absolute left-3 top-3 size-4 text-muted-foreground"}),f.jsx(xp,{value:_,onChange:F=>w(F.target.value),rows:3,placeholder:"Optional description",className:"pl-9 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"})]})}),f.jsx("div",{className:"space-y-2",children:f.jsxs(pa,{value:b,onValueChange:F=>x(F),children:[f.jsx(Eo,{className:"pl-[11px] [&>span]:flex [&>span]:items-center [&>span]:gap-2",children:f.jsx(El,{placeholder:"Select visibility"})}),f.jsxs(To,{children:[f.jsx(ws,{value:"private",children:f.jsxs("span",{className:"flex items-center gap-2",children:[f.jsx(WW,{className:"size-4 text-muted-foreground"}),f.jsx("span",{className:"pl-[1px]",children:"Private"})]})}),f.jsx(ws,{value:"public",children:f.jsxs("span",{className:"flex items-center gap-2",children:[f.jsx(LW,{className:"size-4 text-muted-foreground"}),f.jsx("span",{className:"pl-[1px]",children:"Public"})]})})]})]})})]})]}),f.jsxs(Sa,{children:[f.jsx(Ue,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Cancel"}),f.jsx(Ue,{size:"sm",disabled:!L,onClick:()=>void M(),children:R?f.jsxs(f.Fragment,{children:[f.jsx(bn,{className:"mr-1.5 size-3.5 animate-spin"}),"Publishing…"]}):"Push to GitHub"})]})]})})}function WB({value:e,onChange:t,placeholder:n,disabled:r,trailingAction:i}){return f.jsxs("div",{className:"relative",children:[f.jsx(Gh,{className:"pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),f.jsx($n,{value:e,onChange:s=>t(s.target.value),placeholder:n,className:he("h-9 pl-7 text-sm",i?"pr-14":void 0),disabled:r}),i?f.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2",children:i}):null]})}function Dc({title:e,entries:t,emptyLabel:n,selectedName:r,disabled:i,stickyTitle:s=!1,onSelect:o}){return t.length===0&&!n?null:f.jsxs("div",{className:"space-y-1",children:[f.jsx("div",{className:he("px-1 py-1 text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground",s&&"sticky top-0 z-10 bg-background"),children:e}),t.length===0?f.jsx("div",{className:"px-1 py-1 text-xs text-muted-foreground",children:n}):t.map(l=>{const c=r===l.name;return f.jsxs("button",{type:"button",disabled:i,onClick:()=>o(l),className:he("flex w-full items-start gap-2 rounded-lg px-2 py-2 text-left transition-colors disabled:opacity-60",c?"bg-accent text-foreground":"hover:bg-accent"),children:[l.kind==="pull_request"?f.jsx(N5,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):f.jsx(Ac,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsxs("div",{className:"flex w-full items-center gap-3",children:[f.jsx("div",{className:"min-w-0 flex-1 overflow-hidden whitespace-nowrap text-sm text-foreground",children:l.displayName}),l.updatedAt?f.jsx("div",{className:"ml-auto shrink-0 text-right text-[11px] text-muted-foreground",children:s2(l.updatedAt)}):null]}),l.kind==="pull_request"&&l.description||l.headLabel?f.jsx("div",{className:"truncate text-xs text-muted-foreground",children:l.kind==="pull_request"?l.description??l.headLabel??l.name:l.headLabel??void 0}):null]})]},l.id)})]})}function Ave({open:e,onOpenChange:t,branchList:n,currentBranchName:r,onPreviewMergeBranch:i,onMergeBranch:s}){const[o,l]=v.useState(""),[c,u]=v.useState(null),[m,h]=v.useState(null),[g,b]=v.useState(null),[x,_]=v.useState(!1),[w,C]=v.useState(!1),E=v.useMemo(()=>n?Nve(n,r):{defaultBranch:void 0,recent:[],other:[]},[n,r]),k=o.trim().toLowerCase(),N=v.useCallback(O=>k?[O.displayName,O.name,O.description,O.prTitle,O.headLabel].some(z=>z==null?void 0:z.toLowerCase().includes(k)):!0,[k]),R=E.defaultBranch&&N(E.defaultBranch)?E.defaultBranch:void 0,A=E.recent.filter(N),M=E.other.filter(N),L=v.useMemo(()=>c?[E.defaultBranch,...E.recent,...E.other].find(O=>O!==void 0&&O.name===c)??null:null,[E.defaultBranch,E.other,E.recent,c]);v.useEffect(()=>{e||(l(""),u(null),h(null),b(null),_(!1),C(!1))},[e]),v.useEffect(()=>{if(!e||!L){h(null),b(null),_(!1);return}let O=!1;return h(null),b(null),_(!0),i(L).then(z=>{O||h(z)}).catch(z=>{O||b(z instanceof Error?z.message:String(z))}).finally(()=>{O||_(!1)}),()=>{O=!0}},[i,e,L]);const F=!L||!m||x||w||m.status!=="mergeable";async function D(){if(!(!L||F)){C(!0);try{const O=await s(L);O!=null&&O.ok&&t(!1)}finally{C(!1)}}}return f.jsx(As,{open:e,onOpenChange:t,children:f.jsxs(es,{size:"sm",className:"max-w-[min(92vw,475px)]",children:[f.jsxs(Oo,{className:"flex min-h-0 flex-col gap-3 px-4 pb-4 pt-4",children:[f.jsxs("div",{className:"space-y-1",children:[f.jsxs(Ms,{children:["Merge into ",r??"current branch"]}),f.jsx(af,{children:"Choose a branch to continue."})]}),f.jsx(WB,{value:o,onChange:l,placeholder:"Search branches"}),f.jsxs("div",{className:"max-h-[375px] space-y-3 overflow-y-auto pr-1",children:[f.jsx(Dc,{title:"Default Branch",entries:R?[R]:[],emptyLabel:"No default branch available.",selectedName:c,onSelect:O=>u(O.name)}),f.jsx(Dc,{title:"Recent Branches",entries:A,emptyLabel:"No recent branches.",selectedName:c,onSelect:O=>u(O.name)}),f.jsx(Dc,{title:"Other Branches",entries:M,emptyLabel:"No other branches match this search.",selectedName:c,onSelect:O=>u(O.name)})]}),f.jsx("div",{className:"px-2",children:L?x?f.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[f.jsx(bn,{className:"size-3.5 animate-spin"}),f.jsx("span",{children:"Checking merge preview…"})]}):g?f.jsx("div",{className:"text-sm text-destructive",children:g}):m?f.jsxs("div",{className:"flex items-start gap-2",children:[m.status==="up_to_date"?f.jsx(_i,{className:"mt-1 size-3.5 shrink-0 text-success"}):m.status==="conflicts"?f.jsx(wb,{className:"mt-1 size-3.5 shrink-0 text-warning"}):m.status==="mergeable"?f.jsx(T5,{className:"mt-1 size-3.5 shrink-0 text-muted-foreground"}):f.jsx(wb,{className:"mt-1 size-3.5 shrink-0 text-destructive"}),f.jsxs("div",{className:"min-w-0 space-y-1",children:[f.jsx("div",{className:"text-sm font-medium text-foreground",children:m.message}),m.detail?f.jsx("div",{className:"line-clamp-2 whitespace-pre-wrap text-xs text-muted-foreground",children:m.detail}):null]})]}):f.jsx("div",{className:"text-sm text-muted-foreground",children:"Preview unavailable."}):f.jsx("div",{className:"text-sm text-muted-foreground",children:"Select a branch to preview the merge."})})]}),f.jsx(Sa,{children:f.jsxs("div",{className:"flex min-w-0 w-full items-center justify-end gap-2",children:[f.jsx(Ue,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Cancel"}),f.jsx(Ue,{className:"max-w-full min-w-0",size:"sm",disabled:F,onClick:()=>void D(),children:w?f.jsxs(f.Fragment,{children:[f.jsx(bn,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}),"Merging…"]}):f.jsx("span",{className:"block max-w-full truncate",children:"Merge"})})]})})]})})}function Mve({currentBranchName:e,onListBranches:t,onPreviewMergeBranch:n,onMergeBranch:r,onCheckoutBranch:i,onCreateBranch:s}){const[o,l]=v.useState(!1),[c,u]=v.useState(!1),[m,h]=v.useState(!1),[g,b]=v.useState(!1),[x,_]=v.useState(""),[w,C]=v.useState("branches"),[E,k]=v.useState(null),[N,R]=v.useState(null);v.useEffect(()=>{o&&(h(!0),R(null),t().then(G=>k(G)).catch(G=>{R(G instanceof Error?G.message:String(G))}).finally(()=>{h(!1)}))},[t,o]);const A=x.trim().toLowerCase(),M=G=>G.filter(Q=>A?[Q.displayName,Q.name,Q.description,Q.prTitle,Q.headLabel].some(I=>I==null?void 0:I.toLowerCase().includes(A)):!0),L=(E==null?void 0:E.currentBranchName)??e,F=new Set(((E==null?void 0:E.pullRequests)??[]).map(G=>G.headRefName??G.name)),D=M((E==null?void 0:E.recent)??[]).filter(G=>G.name!==L),O=M((E==null?void 0:E.local)??[]).filter(G=>G.name!==L),z=M((E==null?void 0:E.remote)??[]).filter(G=>G.name!==L&&!F.has(G.name)),P=M((E==null?void 0:E.pullRequests)??[]).filter(G=>G.name!==L),$=(E==null?void 0:E.pullRequests.length)??0;async function H(G){b(!0);try{await i(G),l(!1),_(""),C("branches")}finally{b(!1)}}async function B(){b(!0);try{await s(),l(!1),_(""),C("branches")}finally{b(!1)}}function V(){l(!1),u(!0)}return f.jsxs(Kk,{open:o,onOpenChange:l,children:[f.jsx(Yk,{asChild:!0,children:f.jsxs("button",{type:"button",className:"flex min-w-0 max-w-full items-center gap-1 rounded-md px-1.5 py-1 text-sm transition-colors hover:bg-accent hover:text-foreground","aria-label":"Open branch switcher",children:[f.jsx(Ac,{className:"h-3.5 w-3.5 shrink-0"}),f.jsx("span",{className:"truncate",children:e??"Detached HEAD"}),f.jsx(nf,{className:"h-3.5 w-3.5 shrink-0"})]})}),f.jsx(Wy,{align:"start",className:"w-[320px] p-2",children:f.jsxs("div",{className:"space-y-2",children:[f.jsx(WB,{value:x,onChange:_,placeholder:w==="pull_requests"?"Search pull requests":"Search branches",disabled:m||g,trailingAction:f.jsx(Ue,{variant:"ghost",size:"sm",onClick:()=>void B(),disabled:m||g,className:"h-7 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:"+ New"})}),f.jsx(Di,{value:w,onValueChange:G=>C(G),size:"sm",className:"w-full",optionClassName:"flex-1 justify-center",options:[{value:"branches",label:"Branches"},{value:"pull_requests",label:`Open PRs ${$}`}]}),f.jsx("div",{className:"max-h-[420px] overflow-y-auto pr-1.5 -mr-[8px]",children:m?f.jsxs("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[f.jsx(bn,{className:"h-4 w-4 animate-spin"}),f.jsx("span",{children:"Loading branches…"})]}):N?f.jsx("div",{className:"rounded-lg border border-border px-3 py-2 text-sm text-muted-foreground",children:N}):w==="pull_requests"?f.jsx(Dc,{title:"Open PRs",entries:P,emptyLabel:(E==null?void 0:E.pullRequestsStatus)==="error"?E.pullRequestsError??"Could not load pull requests.":(E==null?void 0:E.pullRequestsStatus)==="unavailable"?"Pull requests unavailable for this repository.":"No open pull requests.",disabled:g,stickyTitle:!0,onSelect:G=>{H(G)}}):f.jsxs("div",{className:"space-y-3",children:[f.jsx(Dc,{title:"Recent",entries:D,emptyLabel:"No recent branches.",disabled:g,stickyTitle:!0,onSelect:G=>{H(G)}}),f.jsx(Dc,{title:"Local",entries:O,emptyLabel:"No local branches.",disabled:g,stickyTitle:!0,onSelect:G=>{H(G)}}),f.jsx(Dc,{title:"Remote",entries:z,emptyLabel:"No remote branches.",disabled:g,stickyTitle:!0,onSelect:G=>{H(G)}})]})}),L?f.jsx(Ue,{variant:"default",size:"sm",disabled:m||g||!!N,onClick:V,className:"h-9 w-full justify-center rounded-lg px-3 text-sm",children:f.jsxs("span",{className:"block max-w-full truncate",children:[f.jsx(TW,{className:"mr-1.5 inline h-3.5 w-3.5 shrink-0"}),"Merge branch into ",L,"..."]})}):null]})}),f.jsx(Ave,{open:c,onOpenChange:u,branchList:E,currentBranchName:L,onPreviewMergeBranch:n,onMergeBranch:r})]})}function Lve({file:e,rootRef:t,projectId:n,isCollapsed:r,isChecked:i,editorLabel:s,diffRenderMode:o,wrapLines:l,onToggleCollapsed:c,onToggleChecked:u,fileActions:m,patch:h,patchError:g,isPatchLoading:b,onLoadPatch:x}){const _=UB(e),w=Cve(e),[C,E]=v.useState(null),k=v.useRef(null),N=v.useRef(null),{sentinelRef:R,isStuck:A}=vue({rootRef:t,disabled:r}),M=v.useMemo(()=>Sve(n,e),[e,n]),L=M!==null,F=dD({isCollapsed:r,hasPreviewAttachment:L,patch:h,patchError:g,isPatchLoading:b});v.useEffect(()=>{if(!F)return;const P=`${e.path}\0${e.patchDigest}`;N.current!==P&&(N.current=P,x(e.path).catch(()=>{}))},[e.patchDigest,e.path,x,F]);function D(P){if(yf(P).openInNewTab){typeof window<"u"&&window.open(new URL(P.contentUrl,window.location.origin).toString(),"_blank","noopener,noreferrer");return}E(P.id)}function O(P){var H;P.preventDefault(),P.stopPropagation();const $=P.currentTarget.getBoundingClientRect();(H=k.current)==null||H.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:$.left+$.width/2,clientY:$.bottom,view:window}))}function z(){if(!r){c();return}if(L||h!==void 0){c();return}if(b)return;if(!(g!==void 0||dD({isCollapsed:!1,hasPreviewAttachment:L,patch:h,patchError:g,isPatchLoading:b}))){c();return}x(e.path).then(()=>{c()}).catch(()=>{})}return f.jsxs(su,{children:[f.jsx(ou,{asChild:!0,children:f.jsxs("div",{ref:k,className:"relative rounded-lg border border-border bg-background",children:[r?null:f.jsx("div",{ref:R,className:"pointer-events-none absolute inset-x-0 top-0 h-px","aria-hidden":"true"}),f.jsxs("div",{role:"button",tabIndex:0,onClick:z,onKeyDown:P=>{P.key!=="Enter"&&P.key!==" "||(P.preventDefault(),z())},className:he("group/header sticky top-0 z-20 flex cursor-pointer items-center justify-between gap-3 bg-background pl-[7px] pr-2.5 py-1.5 text-[13px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",!r&&!A&&"rounded-t-[calc(theme(borderRadius.lg)-1px)]",r&&"rounded-[calc(theme(borderRadius.lg)-1px)]",!r&&"border-b border-border/50"),children:[f.jsxs("div",{className:"flex min-w-0 items-center",children:[f.jsx(VB,{checked:i,onClick:u}),f.jsx("div",{className:"min-w-0 truncate select-none ml-2 mr-1",children:e.path})]}),f.jsxs("div",{className:"flex shrink-0 items-center gap-2 select-none",children:[f.jsxs("span",{className:"whitespace-nowrap text-xs font-mono",children:[e.additions>0?f.jsxs("span",{className:"text-success",children:["+",e.additions]}):null,e.deletions>0?f.jsxs("span",{className:e.additions>0?"ml-2 text-destructive":"text-destructive",children:["-",e.deletions]}):null]}),f.jsx("button",{type:"button","aria-label":`Open actions for ${e.path}`,onClick:O,className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:f.jsx(dm,{className:"h-3.5 w-3.5 shrink-0"})}),b&&r&&!M?f.jsx(bn,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):r?f.jsx(nf,{className:"h-3.5 w-3.5 shrink-0"}):f.jsx(S5,{className:"h-3.5 w-3.5 shrink-0"})]})]}),r?null:f.jsx("div",{className:"kanna-diff-patch overflow-hidden rounded-b-[calc(theme(borderRadius.lg)-1px)] pb-[1px]",children:M?f.jsx("div",{className:"flex justify-center p-3",children:M.kind==="image"?f.jsx(i2,{attachment:M,onClick:()=>D(M)}):f.jsx(Do,{attachment:M,onClick:()=>D(M)})}):b?f.jsxs("div",{className:"flex items-center justify-center px-3 py-8 text-sm text-muted-foreground",children:[f.jsx(bn,{className:"mr-2 h-4 w-4 animate-spin"}),"Loading diff..."]}):g?f.jsx("div",{className:"px-3 py-4 text-sm text-destructive",children:g}):h!==void 0?f.jsx(pue,{patch:h,options:{diffStyle:o,disableFileHeader:!0,disableBackground:!1,overflow:l?"wrap":"scroll",lineDiffType:"word",diffIndicators:"classic"}}):f.jsx("div",{className:"px-3 py-4 text-sm text-muted-foreground",children:"Diff unavailable."})}),f.jsx(wf,{source:M&&C===M.id?yp(M,"user_attachment"):null,open:M!==null&&C===M.id,onOpenChange:P=>!P&&E(null)})]},e.path)}),f.jsxs(Vl,{children:[f.jsxs(jn,{onSelect:P=>{P.stopPropagation(),m.onOpenFile(e.path)},children:[f.jsx(nk,{className:"h-3.5 w-3.5"}),f.jsxs("span",{className:"text-xs font-medium",children:["Open in ",s]})]}),f.jsxs(jn,{onSelect:P=>{P.stopPropagation(),m.onOpenInFinder(e.path)},children:[f.jsx(Cy,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Open in Finder"})]}),f.jsxs(jn,{onSelect:P=>{P.stopPropagation(),m.onDiscardFile(e.path)},className:"text-destructive hover:bg-destructive/10 focus:bg-destructive/10",children:[f.jsx(rf,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Discard Changes"})]}),f.jsxs(jn,{disabled:!_,onSelect:P=>{P.stopPropagation(),_&&m.onIgnoreFile(e.path)},children:[f.jsx(BA,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Ignore File"})]}),f.jsxs(jn,{disabled:!w,onSelect:P=>{P.stopPropagation(),w&&m.onIgnoreFolder(e.path)},children:[f.jsx(BA,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Ignore folder..."})]}),f.jsx(a4,{}),f.jsxs(jn,{onSelect:P=>{P.stopPropagation(),m.onCopyFilePath(e.path)},children:[f.jsx(Pl,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Copy File Path"})]}),f.jsxs(jn,{onSelect:P=>{P.stopPropagation(),m.onCopyRelativePath(e.path)},children:[f.jsx(Pl,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Copy Relative Path"})]})]})]})}function jve({projectId:e,diffs:t,editorLabel:n,diffRenderMode:r,wrapLines:i,onOpenFile:s,onOpenInFinder:o,onDiscardFile:l,onIgnoreFile:c,onIgnoreFolder:u,onCopyFilePath:m,onCopyRelativePath:h,onListBranches:g,onPreviewMergeBranch:b,onMergeBranch:x,onCheckoutBranch:_,onCreateBranch:w,onGenerateCommitMessage:C,onInitializeGit:E,onGetGitHubPublishInfo:k,onCheckGitHubRepoAvailability:N,onSetupGitHub:R,onCommit:A,onSyncWithRemote:M,onLoadPatch:L,onDiffRenderModeChange:F,onWrapLinesChange:D}){var Qe;const O=v.useMemo(()=>({onOpenFile:s,onOpenInFinder:o,onDiscardFile:l,onIgnoreFile:c,onIgnoreFolder:u,onCopyFilePath:m,onCopyRelativePath:h}),[s,o,l,c,u,m,h]),z=t.files.length>0,[P,$]=v.useState(!1),[H,B]=v.useState(null),[V,G]=v.useState(!1),[Q,I]=v.useState(!1),[W,te]=v.useState({}),[U,fe]=v.useState({}),[ae,ee]=v.useState({}),ne=v.useRef(null),se=v.useRef({}),le=v.useMemo(()=>t.files.map(_e=>_e.path),[t.files]),ue=v.useMemo(()=>le.join("\0"),[le]),Ae=ji(_e=>{var Fe;return e?((Fe=_e.projectUi[e])==null?void 0:Fe.viewMode)??(z?"changes":"history"):z?"changes":"history"}),ce=ji(_e=>{var Fe;return e?((Fe=_e.projectUi[e])==null?void 0:Fe.collapsedPaths)??Cv:Cv}),De=ji(_e=>{var Fe;return e?((Fe=_e.projectUi[e])==null?void 0:Fe.summary)??"":""}),Ke=ji(_e=>{var Fe;return e?((Fe=_e.projectUi[e])==null?void 0:Fe.description)??"":""}),ht=ji(_e=>_e.reconcileCollapsedPaths),Tt=ji(_e=>_e.toggleCollapsedPath),qt=ji(_e=>_e.setViewMode),Se=ji(_e=>_e.setCommitDraft),Rt=ji(_e=>_e.clearCommitDraft),Et=pv(_e=>e?_e.checkedPathsByProjectId[e]??Cv:Cv),dt=pv(_e=>_e.reconcileProject),Bt=pv(_e=>_e.setChecked),Ut=pv(_e=>_e.setAllChecked),pt=v.useRef(z);v.useEffect(()=>{e&&ht(e,le)},[le,ue,e,ht]),v.useEffect(()=>{const _e=Object.fromEntries(t.files.map(qe=>[qe.path,qe.patchDigest])),Fe=qe=>se.current[qe]===_e[qe];te(qe=>Object.fromEntries(Object.entries(qe).filter(([Ve])=>le.includes(Ve)&&Fe(Ve)))),fe(qe=>Object.fromEntries(Object.entries(qe).filter(([Ve])=>le.includes(Ve)&&Fe(Ve)))),ee(qe=>Object.fromEntries(Object.entries(qe).filter(([Ve])=>le.includes(Ve)&&Fe(Ve)))),se.current=_e},[t.files,le,ue]),v.useEffect(()=>{e&&dt(e,le)},[le,ue,e,dt]),v.useEffect(()=>{if(!e)return;if(pt.current!==z){qt(e,z?"changes":"history"),pt.current=z;return}pt.current=z},[z,e,qt]);const ln=v.useMemo(()=>t.files.filter(_e=>Et[_e.path]??!0).map(_e=>_e.path),[Et,t.files]),me=ln.length,Ce=t.files.length>0&&me===t.files.length,$e=me>0&&me<t.files.length,et=De.trim(),Ee=et.length>0,Pe=H!==null,Ze=P||Pe,Ye=((Qe=t.branchHistory)==null?void 0:Qe.entries)??[],Ge=t.behindCount??0,ft=t.aheadCount??0,st=t.hasUpstream===!0,Vt=t.hasUpstream===!1&&!!t.branchName,sn=t.hasOriginRemote===!0,pn=t.branchName?t.branchName.split("/").map(_e=>encodeURIComponent(_e)).join("/"):null,dn=Vt?"publish":Ge>0?"pull":"fetch",At=t.originRepoSlug&&pn?`https://github.com/${t.originRepoSlug}/compare/${pn}?expand=1`:null,Je=!!(st&&At&&t.branchName&&t.branchName!==t.defaultBranchName),St=t.status==="ready"&&me>0&&!Ze,xt=t.status==="ready"&&me>0&&Ee&&!Ze,gt=sn?"commit_and_push":"commit_only",bt=t.branchName??"current branch";async function Lt(_e){if(xt){B(_e);try{const Fe=await A({paths:ln,summary:et,description:Ke.trim(),mode:_e});(Fe!=null&&Fe.ok||Fe!=null&&Fe.localCommitCreated)&&e&&Rt(e)}finally{B(null)}}}async function Wt(){if(St){$(!0);try{const _e=await C({paths:ln});e&&Se(e,{summary:_e.subject,description:_e.body})}finally{$(!1)}}}function Te(_e){if(!(!(_e.metaKey||_e.ctrlKey)||_e.key!=="Enter")){if(_e.preventDefault(),Ee){Lt(gt);return}Wt()}}async function nt(_e=dn){if(!(t.status!=="ready"||V)){G(!0);try{await M(_e)}finally{G(!1)}}}const Ie=v.useCallback(async _e=>{var Fe;if(W[_e]!==void 0||ae[_e])return W[_e]??"";ee(qe=>({...qe,[_e]:!0})),fe(qe=>{if(!(_e in qe))return qe;const{[_e]:Ve,...Dt}=qe;return Dt});try{const qe=await L(_e);te(Dt=>({...Dt,[_e]:qe}));const Ve=(Fe=t.files.find(Dt=>Dt.path===_e))==null?void 0:Fe.patchDigest;return Ve&&(se.current={...se.current,[_e]:Ve}),qe}catch(qe){const Ve=qe instanceof Error?qe.message:String(qe);throw fe(Dt=>({...Dt,[_e]:Ve})),qe}finally{ee(qe=>{const{[_e]:Ve,...Dt}=qe;return Dt})}},[t.files,ae,L,W]);return f.jsx("div",{className:"h-full min-h-0 border-l border-border bg-background md:min-w-[370px]",children:f.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[f.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border pl-2.5 pr-2 py-2",children:[f.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:f.jsx(Mve,{currentBranchName:t.branchName,onListBranches:g,onPreviewMergeBranch:b,onMergeBranch:x,onCheckoutBranch:_,onCreateBranch:w})}),t.status==="ready"?sn?dn==="publish"?f.jsxs(Ue,{variant:"ghost",size:"sm",onClick:()=>void nt(),disabled:V,className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[V?f.jsx(bn,{className:"h-3.5 w-3.5 animate-spin"}):f.jsx(Gv,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Publish Branch"})]}):f.jsxs("div",{className:"flex items-center gap-1",children:[dn==="fetch"?f.jsxs(Qr,{delayDuration:0,children:[f.jsx(Zr,{asChild:!0,children:f.jsxs(Ue,{variant:"ghost",size:"sm",onClick:()=>void nt(),disabled:V,className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[V?f.jsx(bn,{className:"h-3.5 w-3.5 animate-spin"}):f.jsx(wG,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Fetch"})]})}),f.jsx(Hr,{children:kve(t.lastFetchedAt)})]}):f.jsxs(Ue,{variant:"ghost",size:"sm",onClick:()=>void nt(),disabled:V,className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[V?f.jsx(bn,{className:"h-3.5 w-3.5 animate-spin"}):f.jsx(rk,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Pull"}),f.jsx("span",{className:"inline-flex min-w-4 items-center justify-center rounded-full bg-muted px-1 text-[10px] text-muted-foreground",children:Ge})]}),st&&ft>0?f.jsxs(Ue,{variant:"default",size:"sm",onClick:()=>void nt("push"),disabled:V,className:"h-7 gap-1.5 px-2 text-xs",children:[V?f.jsx(bn,{className:"h-3.5 w-3.5 animate-spin"}):f.jsx(Gv,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Push"}),f.jsx("span",{className:"inline-flex min-w-4 items-center justify-center rounded-full bg-primary-foreground/15 px-1 text-[10px] text-primary-foreground",children:ft})]}):null,Je&&At?f.jsxs(Ue,{variant:"ghost",size:"sm",onClick:()=>{typeof window>"u"||window.open(At,"_blank","noopener,noreferrer")},className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[f.jsx(N5,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"PR"})]}):null]}):f.jsxs(Ue,{variant:"default",size:"sm",onClick:()=>I(!0),className:"h-7 gap-1.5 px-3 text-xs",children:[f.jsx(AW,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Push to GitHub"})]}):null]}),f.jsxs("div",{className:"relative min-h-0 flex-1",children:[f.jsx("div",{className:"sticky top-0 z-30 pl-[14px] pr-[12px] pt-[6px] bg-gradient-to-b from-background to-transparent",children:f.jsx("div",{className:"relative h-[40px] flex min-w-0 items-center justify-center gap-[13px]",children:f.jsxs("div",{className:"flex min-w-0 flex-1 items-center justify-between gap-[13px] relative",children:[Ae==="changes"?f.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground/70",children:[f.jsx(VB,{checked:Ce,mixed:$e,label:$e?"Select all files for commit":Ce?"Unselect all files from commit":"Select all files for commit",onClick:()=>{!e||t.files.length===0||Ut(e,le,$e?!0:!Ce)}}),f.jsxs("span",{children:[me," files"]})]}):f.jsx("div",{}),f.jsx("div",{className:"pointer-events-none absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2",children:f.jsx("div",{className:"pointer-events-auto",children:f.jsx(Di,{value:Ae,onValueChange:_e=>{e&&qt(e,_e)},size:"sm",optionClassName:"flex-1 justify-center",options:[{value:"changes",label:"Changes"},{value:"history",label:"History"}]})})}),Ae==="changes"?f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(Zw,{label:"Unified diff",active:r==="unified",onClick:()=>F("unified"),children:f.jsx(EG,{className:"h-4 w-4"})}),f.jsx(Zw,{label:"Side-by-side diff",active:r==="split",onClick:()=>F("split"),children:f.jsx(zV,{className:"h-4 w-4"})}),f.jsx(Zw,{label:i?"Disable word wrap":"Enable word wrap",active:i,onClick:()=>D(!i),children:f.jsx(rq,{className:"h-4 w-4"})})]}):f.jsx("div",{})]})})}),f.jsx("div",{ref:ne,className:"h-full overflow-y-auto [scrollbar-gutter:stable]",children:t.status==="no_repo"?f.jsx("div",{className:"flex h-full items-center justify-center px-6 py-3 text-center",children:f.jsxs("div",{className:"flex max-w-[280px] flex-col items-center gap-3",children:[f.jsx("p",{className:"text-sm text-muted-foreground",children:"Initialize git here to start tracking branches, diffs, and history."}),f.jsx(Ue,{size:"sm",onClick:()=>void E(),children:"Init Git"})]})}):Ae==="history"?Ye.length===0?f.jsx("div",{className:"flex h-full items-center justify-center px-6 py-3 text-center",children:f.jsxs("p",{className:"text-sm text-muted-foreground",children:["No recent commits on ",t.branchName??"this branch","."]})}):f.jsx("div",{className:"space-y-1.5 p-1.5",children:Ye.map((_e,Fe)=>f.jsx(Eve,{entry:_e,isPendingPush:Fe<ft},_e.sha))}):t.files.length===0?f.jsx("div",{className:"flex h-full items-center justify-center px-6 py-3 text-center",children:f.jsx("p",{className:"text-sm text-muted-foreground",children:"No file changes."})}):f.jsxs("div",{className:"space-y-1.5 p-1.5 pb-10",children:[t.files.map(_e=>{const Fe=ce[_e.path]??!0,qe=Et[_e.path]??!0;return f.jsx(Lve,{file:_e,rootRef:ne,projectId:e,isCollapsed:Fe,isChecked:qe,editorLabel:n,diffRenderMode:r,wrapLines:i,onToggleCollapsed:()=>{e&&Tt(e,_e.path)},onToggleChecked:()=>{e&&Bt(e,_e.path,!qe)},fileActions:O,patch:W[_e.path],patchError:U[_e.path],isPatchLoading:!!ae[_e.path],onLoadPatch:Ie},_e.path)}),Ae==="changes"?f.jsxs("div",{className:"pointer-events-none sticky inset-x-0 bottom-11 py-1 pb-6 z-30 overflow-y-auto",children:[f.jsx("div",{className:"absolute inset-x-0 bottom-0 top-0 bg-gradient-to-t from-background to-transparent"}),f.jsx("div",{className:"pointer-events-auto relative",children:f.jsxs("div",{className:"space-y-0 rounded-xl mx-auto max-w-[700px]",children:[f.jsx($n,{value:De,onChange:_e=>{e&&Se(e,{summary:_e.target.value,description:Ke})},onKeyDown:Te,placeholder:"Commit message (override)",className:"rounded-t-xl rounded-b-none px-3",disabled:Ze||t.status!=="ready"}),f.jsx(xp,{value:Ke,onChange:_e=>{e&&Se(e,{summary:De,description:_e.target.value})},onKeyDown:Te,placeholder:"Description",rows:5,className:"-mt-px rounded-t-none rounded-b-xl px-3 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background mb-2",disabled:Ze||t.status!=="ready"}),f.jsx("div",{className:"w-full flex flex-row",children:f.jsxs(su,{children:[f.jsx(ou,{asChild:!0,children:f.jsx(Ue,{type:"button",className:"-mt-px w-full rounded-xl",disabled:Ee?!xt:!St,onClick:()=>{if(Ee){Lt(gt);return}Wt()},children:f.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[Ee?Pe?f.jsx(bn,{strokeWidth:2.5,className:"size-3 shrink-0 animate-spin"}):gt==="commit_and_push"?t.hasUpstream?f.jsx(Gv,{strokeWidth:2.5,className:"size-3 shrink-0"}):f.jsx(T5,{strokeWidth:2.5,className:"size-3 shrink-0"}):f.jsx(_i,{strokeWidth:2.5,className:"size-3 shrink-0"}):P?f.jsx(bn,{strokeWidth:2.5,className:"size-3 shrink-0 animate-spin"}):f.jsx(uG,{strokeWidth:2.5,className:"size-3 shrink-0"}),f.jsx("span",{className:"min-w-0 truncate text-left",children:Ee?Pe?H==="commit_only"?"Committing...":"Committing & Pushing...":gt==="commit_only"?f.jsxs(f.Fragment,{children:["Commit to ",f.jsx(Ac,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),bt]}):t.hasUpstream?f.jsxs(f.Fragment,{children:["Commit & push to ",f.jsx(Ac,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),bt]}):f.jsxs(f.Fragment,{children:["Commit & publish ",f.jsx(Ac,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),bt]}):P?"Generating...":f.jsxs(f.Fragment,{children:["Generate message for ",f.jsx(Ac,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),bt]})})]})})}),t.hasUpstream?f.jsx(Vl,{children:f.jsx(jn,{disabled:!Ee||!xt,onSelect:_e=>{_e.stopPropagation(),Lt("commit_only")},children:"Commit Only"})}):null]})})]})})]}):null]})})]}),f.jsx(Rve,{open:Q,onOpenChange:I,onGetGitHubPublishInfo:k,onCheckGitHubRepoAvailability:N,onPublish:R})]})})}const Dve=v.memo(jve);function Ive(e,t){const n=getComputedStyle(e),r=parseFloat(n.fontSize);return t*r}function Pve(e,t){const n=getComputedStyle(e.ownerDocument.body),r=parseFloat(n.fontSize);return t*r}function Ove(e){return e/100*window.innerHeight}function zve(e){return e/100*window.innerWidth}function Bve(e){switch(typeof e){case"number":return[e,"px"];case"string":{const t=parseFloat(e);return e.endsWith("%")?[t,"%"]:e.endsWith("px")?[t,"px"]:e.endsWith("rem")?[t,"rem"]:e.endsWith("em")?[t,"em"]:e.endsWith("vh")?[t,"vh"]:e.endsWith("vw")?[t,"vw"]:[t,"%"]}}}function Bh({groupSize:e,panelElement:t,styleProp:n}){let r;const[i,s]=Bve(n);switch(s){case"%":{r=i/100*e;break}case"px":{r=i;break}case"rem":{r=Pve(t,i);break}case"em":{r=Ive(t,i);break}case"vh":{r=Ove(i);break}case"vw":{r=zve(i);break}}return r}function Ii(e){return parseFloat(e.toFixed(3))}function Wd({group:e}){const{orientation:t,panels:n}=e;return n.reduce((r,i)=>(r+=t==="horizontal"?i.element.offsetWidth:i.element.offsetHeight,r),0)}function X1(e){const{panels:t}=e,n=Wd({group:e});return n===0?t.map(r=>({groupResizeBehavior:r.panelConstraints.groupResizeBehavior,collapsedSize:0,collapsible:r.panelConstraints.collapsible===!0,defaultSize:void 0,disabled:r.panelConstraints.disabled,minSize:0,maxSize:100,panelId:r.id})):t.map(r=>{const{element:i,panelConstraints:s}=r;let o=0;if(s.collapsedSize!==void 0){const m=Bh({groupSize:n,panelElement:i,styleProp:s.collapsedSize});o=Ii(m/n*100)}let l;if(s.defaultSize!==void 0){const m=Bh({groupSize:n,panelElement:i,styleProp:s.defaultSize});l=Ii(m/n*100)}let c=0;if(s.minSize!==void 0){const m=Bh({groupSize:n,panelElement:i,styleProp:s.minSize});c=Ii(m/n*100)}let u=100;if(s.maxSize!==void 0){const m=Bh({groupSize:n,panelElement:i,styleProp:s.maxSize});u=Ii(m/n*100)}return{groupResizeBehavior:s.groupResizeBehavior,collapsedSize:o,collapsible:s.collapsible===!0,defaultSize:l,disabled:s.disabled,minSize:c,maxSize:u,panelId:r.id}})}function Ln(e,t="Assertion error"){if(!e)throw Error(t)}function Q1(e,t){return Array.from(t).sort(e==="horizontal"?Fve:$ve)}function Fve(e,t){const n=e.element.offsetLeft-t.element.offsetLeft;return n!==0?n:e.element.offsetWidth-t.element.offsetWidth}function $ve(e,t){const n=e.element.offsetTop-t.element.offsetTop;return n!==0?n:e.element.offsetHeight-t.element.offsetHeight}function GB(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.ELEMENT_NODE}function qB(e,t){return{x:e.x>=t.left&&e.x<=t.right?0:Math.min(Math.abs(e.x-t.left),Math.abs(e.x-t.right)),y:e.y>=t.top&&e.y<=t.bottom?0:Math.min(Math.abs(e.y-t.top),Math.abs(e.y-t.bottom))}}function Hve({orientation:e,rects:t,targetRect:n}){const r={x:n.x+n.width/2,y:n.y+n.height/2};let i,s=Number.MAX_VALUE;for(const o of t){const{x:l,y:c}=qB(r,o),u=e==="horizontal"?l:c;u<s&&(s=u,i=o)}return Ln(i,"No rect found"),i}let kv;function Uve(){return kv===void 0&&(typeof matchMedia=="function"?kv=!!matchMedia("(pointer:coarse)").matches:kv=!1),kv}function KB(e){const{element:t,orientation:n,panels:r,separators:i}=e,s=Q1(n,Array.from(t.children).filter(GB).map(x=>({element:x}))).map(({element:x})=>x),o=[];let l=!1,c=!1,u=-1,m=-1,h=0,g,b=[];{let x=-1;for(const _ of s)_.hasAttribute("data-panel")&&(x++,_.ariaDisabled===null&&(h++,u===-1&&(u=x),m=x))}if(h>1){let x=-1;for(const _ of s)if(_.hasAttribute("data-panel")){x++;const w=r.find(C=>C.element===_);if(w){if(g){const C=g.element.getBoundingClientRect(),E=_.getBoundingClientRect();let k;if(c){const N=n==="horizontal"?new DOMRect(C.right,C.top,0,C.height):new DOMRect(C.left,C.bottom,C.width,0),R=n==="horizontal"?new DOMRect(E.left,E.top,0,E.height):new DOMRect(E.left,E.top,E.width,0);switch(b.length){case 0:{k=[N,R];break}case 1:{const A=b[0],M=Hve({orientation:n,rects:[C,E],targetRect:A.element.getBoundingClientRect()});k=[A,M===C?R:N];break}default:{k=b;break}}}else b.length?k=b:k=[n==="horizontal"?new DOMRect(C.right,E.top,E.left-C.right,E.height):new DOMRect(E.left,C.bottom,E.width,E.top-C.bottom)];for(const N of k){let R="width"in N?N:N.element.getBoundingClientRect();const A=Uve()?e.resizeTargetMinimumSize.coarse:e.resizeTargetMinimumSize.fine;if(R.width<A){const L=A-R.width;R=new DOMRect(R.x-L/2,R.y,R.width+L,R.height)}if(R.height<A){const L=A-R.height;R=new DOMRect(R.x,R.y-L/2,R.width,R.height+L)}const M=x<=u||x>m;!l&&!M&&o.push({group:e,groupSize:Wd({group:e}),panels:[g,w],separator:"width"in N?void 0:N,rect:R}),l=!1}}c=!1,g=w,b=[]}}else if(_.hasAttribute("data-separator")){_.ariaDisabled!==null&&(l=!0);const w=i.find(C=>C.element===_);w?b.push(w):(g=void 0,b=[])}else c=!0}return o}var Rl,XP;let YB=(XP=class{constructor(){dl(this,Rl,{})}addListener(t,n){const r=_r(this,Rl)[t];return r===void 0?_r(this,Rl)[t]=[n]:r.includes(n)||r.push(n),()=>{this.removeListener(t,n)}}emit(t,n){const r=_r(this,Rl)[t];if(r!==void 0)if(r.length===1)r[0].call(null,n);else{let i=!1,s=null;const o=Array.from(r);for(let l=0;l<o.length;l++){const c=o[l];try{c.call(null,n)}catch(u){s===null&&(i=!0,s=u)}}if(i)throw s}}removeAllListeners(){ms(this,Rl,{})}removeListener(t,n){const r=_r(this,Rl)[t];if(r!==void 0){const i=r.indexOf(n);i>=0&&r.splice(i,1)}}},Rl=new WeakMap,XP),Ao=new Map;const XB=new YB;function Vve(e){Ao=new Map(Ao),Ao.delete(e)}function hD(e,t){for(const[n]of Ao)if(n.id===e)return n}function jl(e,t){for(const[n,r]of Ao)if(n.id===e)return r;if(t)throw Error(`Could not find data for Group with id ${e}`)}function cu(){return Ao}function o2(e,t){return XB.addListener("groupChange",n=>{n.group.id===e&&t(n)})}function Na(e,t){const n=Ao.get(e);Ao=new Map(Ao),Ao.set(e,t),XB.emit("groupChange",{group:e,prev:n,next:t})}function Wve(e,t,n){let r,i={x:1/0,y:1/0};for(const s of t){const o=qB(n,s.rect);switch(e){case"horizontal":{o.x<=i.x&&(r=s,i=o);break}case"vertical":{o.y<=i.y&&(r=s,i=o);break}}}return r?{distance:i,hitRegion:r}:void 0}function Gve(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function qve(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:gD(e),b:gD(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)r=n.a.pop(),n.b.pop();Ln(r,"Stacking order can only be calculated for elements with a common ancestor");const i={a:pD(mD(n.a)),b:pD(mD(n.b))};if(i.a===i.b){const s=r.childNodes,o={a:n.a.at(-1),b:n.b.at(-1)};let l=s.length;for(;l--;){const c=s[l];if(c===o.a)return 1;if(c===o.b)return-1}}return Math.sign(i.a-i.b)}const Kve=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function Yve(e){const t=getComputedStyle(QB(e)??e).display;return t==="flex"||t==="inline-flex"}function Xve(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||Yve(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||Kve.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function mD(e){let t=e.length;for(;t--;){const n=e[t];if(Ln(n,"Missing node"),Xve(n))return n}return null}function pD(e){return e&&Number(getComputedStyle(e).zIndex)||0}function gD(e){const t=[];for(;e;)t.push(e),e=QB(e);return t}function QB(e){const{parentNode:t}=e;return Gve(t)?t.host:t}function Qve(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function Zve({groupElement:e,hitRegion:t,pointerEventTarget:n}){if(!GB(n)||n.contains(e)||e.contains(n))return!0;if(qve(n,e)>0){let r=n;for(;r;){if(r.contains(e))return!0;if(Qve(r.getBoundingClientRect(),t))return!1;r=r.parentElement}}return!0}function a2(e,t){const n=[];return t.forEach((r,i)=>{if(i.disabled)return;const s=KB(i),o=Wve(i.orientation,s,{x:e.clientX,y:e.clientY});o&&o.distance.x<=0&&o.distance.y<=0&&Zve({groupElement:i.element,hitRegion:o.hitRegion.rect,pointerEventTarget:e.target})&&n.push(o.hitRegion)}),n}function Jve(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function gi(e,t,n=0){return Math.abs(Ii(e)-Ii(t))<=n}function So(e,t){return gi(e,t)?0:e>t?1:-1}function _d({overrideDisabledPanels:e,panelConstraints:t,prevSize:n,size:r}){const{collapsedSize:i=0,collapsible:s,disabled:o,maxSize:l=100,minSize:c=0}=t;if(o&&!e)return n;if(So(r,c)<0)if(s){const u=(i+c)/2;So(r,u)<0?r=i:r=c}else r=c;return r=Math.min(l,r),r=Ii(r),r}function zm({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:r,prevLayout:i,trigger:s}){if(gi(e,0))return t;const o=s==="imperative-api",l=Object.values(t),c=Object.values(i),u=[...l],[m,h]=r;Ln(m!=null,"Invalid first pivot index"),Ln(h!=null,"Invalid second pivot index");let g=0;switch(s){case"keyboard":{{const _=e<0?h:m,w=n[_];Ln(w,`Panel constraints not found for index ${_}`);const{collapsedSize:C=0,collapsible:E,minSize:k=0}=w;if(E){const N=l[_];if(Ln(N!=null,`Previous layout not found for panel index ${_}`),gi(N,C)){const R=k-N;So(R,Math.abs(e))>0&&(e=e<0?0-R:R)}}}{const _=e<0?m:h,w=n[_];Ln(w,`No panel constraints found for index ${_}`);const{collapsedSize:C=0,collapsible:E,minSize:k=0}=w;if(E){const N=l[_];if(Ln(N!=null,`Previous layout not found for panel index ${_}`),gi(N,k)){const R=N-C;So(R,Math.abs(e))>0&&(e=e<0?0-R:R)}}}break}default:{const _=e<0?h:m,w=n[_];Ln(w,`Panel constraints not found for index ${_}`);const C=l[_],{collapsible:E,collapsedSize:k,minSize:N}=w;if(E&&So(C,N)<0)if(e>0){const R=N-k,A=R/2,M=C+e;So(M,N)<0&&(e=So(e,A)<=0?0:R)}else{const R=N-k,A=100-R/2,M=C-e;So(M,N)<0&&(e=So(100+e,A)>0?0:-R)}break}}{const _=e<0?1:-1;let w=e<0?h:m,C=0;for(;;){const k=l[w];Ln(k!=null,`Previous layout not found for panel index ${w}`);const N=_d({overrideDisabledPanels:o,panelConstraints:n[w],prevSize:k,size:100})-k;if(C+=N,w+=_,w<0||w>=n.length)break}const E=Math.min(Math.abs(e),Math.abs(C));e=e<0?0-E:E}{let _=e<0?m:h;for(;_>=0&&_<n.length;){const w=Math.abs(e)-Math.abs(g),C=l[_];Ln(C!=null,`Previous layout not found for panel index ${_}`);const E=C-w,k=_d({overrideDisabledPanels:o,panelConstraints:n[_],prevSize:C,size:E});if(!gi(C,k)&&(g+=C-k,u[_]=k,g.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?_--:_++}}if(Jve(c,u))return i;{const _=e<0?h:m,w=l[_];Ln(w!=null,`Previous layout not found for panel index ${_}`);const C=w+g,E=_d({overrideDisabledPanels:o,panelConstraints:n[_],prevSize:w,size:C});if(u[_]=E,!gi(E,C)){let k=C-E,N=e<0?h:m;for(;N>=0&&N<n.length;){const R=u[N];Ln(R!=null,`Previous layout not found for panel index ${N}`);const A=R+k,M=_d({overrideDisabledPanels:o,panelConstraints:n[N],prevSize:R,size:A});if(gi(R,M)||(k-=M-R,u[N]=M),gi(k,0))break;e>0?N--:N++}}}const b=Object.values(u).reduce((_,w)=>w+_,0);if(!gi(b,100,.1))return i;const x=Object.keys(i);return u.reduce((_,w,C)=>(_[x[C]]=w,_),{})}function Yc(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(t[n]===void 0||So(e[n],t[n])!==0)return!1;return!0}function Xc({layout:e,panelConstraints:t}){const n=Object.values(e),r=[...n],i=r.reduce((l,c)=>l+c,0);if(r.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${r.map(l=>`${l}%`).join(", ")}`);if(!gi(i,100)&&r.length>0)for(let l=0;l<t.length;l++){const c=r[l];Ln(c!=null,`No layout data found for index ${l}`);const u=100/i*c;r[l]=u}let s=0;for(let l=0;l<t.length;l++){const c=n[l];Ln(c!=null,`No layout data found for index ${l}`);const u=r[l];Ln(u!=null,`No layout data found for index ${l}`);const m=_d({overrideDisabledPanels:!0,panelConstraints:t[l],prevSize:c,size:u});u!=m&&(s+=u-m,r[l]=m)}if(!gi(s,0))for(let l=0;l<t.length;l++){const c=r[l];Ln(c!=null,`No layout data found for index ${l}`);const u=c+s,m=_d({overrideDisabledPanels:!0,panelConstraints:t[l],prevSize:c,size:u});if(c!==m&&(s-=m-c,r[l]=m,gi(s,0)))break}const o=Object.keys(e);return r.reduce((l,c,u)=>(l[o[u]]=c,l),{})}function ZB({groupId:e,panelId:t}){const n=()=>{const l=cu();for(const[c,{defaultLayoutDeferred:u,derivedPanelConstraints:m,layout:h,groupSize:g,separatorToPanels:b}]of l)if(c.id===e)return{defaultLayoutDeferred:u,derivedPanelConstraints:m,group:c,groupSize:g,layout:h,separatorToPanels:b};throw Error(`Group ${e} not found`)},r=()=>{const l=n().derivedPanelConstraints.find(c=>c.panelId===t);if(l!==void 0)return l;throw Error(`Panel constraints not found for Panel ${t}`)},i=()=>{const l=n().group.panels.find(c=>c.id===t);if(l!==void 0)return l;throw Error(`Layout not found for Panel ${t}`)},s=()=>{const l=n().layout[t];if(l!==void 0)return l;throw Error(`Layout not found for Panel ${t}`)},o=l=>{const c=s();if(l===c)return;const{defaultLayoutDeferred:u,derivedPanelConstraints:m,group:h,groupSize:g,layout:b,separatorToPanels:x}=n(),_=h.panels.findIndex(k=>k.id===t),w=_===h.panels.length-1,C=zm({delta:w?c-l:l-c,initialLayout:b,panelConstraints:m,pivotIndices:w?[_-1,_]:[_,_+1],prevLayout:b,trigger:"imperative-api"}),E=Xc({layout:C,panelConstraints:m});Yc(b,E)||Na(h,{defaultLayoutDeferred:u,derivedPanelConstraints:m,groupSize:g,layout:E,separatorToPanels:x})};return{collapse:()=>{const{collapsible:l,collapsedSize:c}=r(),{mutableValues:u}=i(),m=s();l&&m!==c&&(u.expandToSize=m,o(c))},expand:()=>{const{collapsible:l,collapsedSize:c,minSize:u}=r(),{mutableValues:m}=i(),h=s();if(l&&h===c){let g=m.expandToSize??u;g===0&&(g=1),o(g)}},getSize:()=>{const{group:l}=n(),c=s(),{element:u}=i(),m=l.orientation==="horizontal"?u.offsetWidth:u.offsetHeight;return{asPercentage:c,inPixels:m}},isCollapsed:()=>{const{collapsible:l,collapsedSize:c}=r(),u=s();return l&&gi(c,u)},resize:l=>{const{group:c}=n(),{element:u}=i(),m=Wd({group:c}),h=Bh({groupSize:m,panelElement:u,styleProp:l}),g=Ii(h/m*100);o(g)}}}function vD(e){if(e.defaultPrevented)return;const t=cu();a2(e,t).forEach(n=>{if(n.separator){const r=n.panels.find(i=>i.panelConstraints.defaultSize!==void 0);if(r){const i=r.panelConstraints.defaultSize,s=ZB({groupId:n.group.id,panelId:r.id});s&&i!==void 0&&(s.resize(i),e.preventDefault())}}})}function ab(e){const t=cu();for(const[n]of t)if(n.separators.some(r=>r.element===e))return n;throw Error("Could not find parent Group for separator element")}function JB({groupId:e}){const t=()=>{const n=cu();for(const[r,i]of n)if(r.id===e)return{group:r,...i};throw Error(`Could not find Group with id "${e}"`)};return{getLayout(){const{defaultLayoutDeferred:n,layout:r}=t();return n?{}:r},setLayout(n){const{defaultLayoutDeferred:r,derivedPanelConstraints:i,group:s,groupSize:o,layout:l,separatorToPanels:c}=t(),u=Xc({layout:n,panelConstraints:i});return r?l:(Yc(l,u)||Na(s,{defaultLayoutDeferred:r,derivedPanelConstraints:i,groupSize:o,layout:u,separatorToPanels:c}),u)}}}function _c(e,t){const n=ab(e),r=jl(n.id,!0),i=n.separators.find(m=>m.element===e);Ln(i,"Matching separator not found");const s=r.separatorToPanels.get(i);Ln(s,"Matching panels not found");const o=s.map(m=>n.panels.indexOf(m)),l=JB({groupId:n.id}).getLayout(),c=zm({delta:t,initialLayout:l,panelConstraints:r.derivedPanelConstraints,pivotIndices:o,prevLayout:l,trigger:"keyboard"}),u=Xc({layout:c,panelConstraints:r.derivedPanelConstraints});Yc(l,u)||Na(n,{defaultLayoutDeferred:r.defaultLayoutDeferred,derivedPanelConstraints:r.derivedPanelConstraints,groupSize:r.groupSize,layout:u,separatorToPanels:r.separatorToPanels})}function bD(e){if(e.defaultPrevented)return;const t=e.currentTarget,n=ab(t);if(!n.disabled)switch(e.key){case"ArrowDown":{e.preventDefault(),n.orientation==="vertical"&&_c(t,5);break}case"ArrowLeft":{e.preventDefault(),n.orientation==="horizontal"&&_c(t,-5);break}case"ArrowRight":{e.preventDefault(),n.orientation==="horizontal"&&_c(t,5);break}case"ArrowUp":{e.preventDefault(),n.orientation==="vertical"&&_c(t,-5);break}case"End":{e.preventDefault(),_c(t,100);break}case"Enter":{e.preventDefault();const r=ab(t),i=jl(r.id,!0),{derivedPanelConstraints:s,layout:o,separatorToPanels:l}=i,c=r.separators.find(g=>g.element===t);Ln(c,"Matching separator not found");const u=l.get(c);Ln(u,"Matching panels not found");const m=u[0],h=s.find(g=>g.panelId===m.id);if(Ln(h,"Panel metadata not found"),h.collapsible){const g=o[m.id],b=h.collapsedSize===g?r.mutableState.expandedPanelSizes[m.id]??h.minSize:h.collapsedSize;_c(t,b-g)}break}case"F6":{e.preventDefault();const r=ab(t).separators.map(o=>o.element),i=Array.from(r).findIndex(o=>o===e.currentTarget);Ln(i!==null,"Index not found");const s=e.shiftKey?i>0?i-1:r.length-1:i+1<r.length?i+1:0;r[s].focus({preventScroll:!0});break}case"Home":{e.preventDefault(),_c(t,-100);break}}}let jd={cursorFlags:0,state:"inactive"};const l2=new YB;function Qc(){return jd}function ebe(e){return l2.addListener("change",e)}function tbe(e){const t=jd,n={...jd};n.cursorFlags=e,jd=n,l2.emit("change",{prev:t,next:n})}function Dd(e){const t=jd;jd=e,l2.emit("change",{prev:t,next:e})}function yD(e){if(e.defaultPrevented||e.pointerType==="mouse"&&e.button>0)return;const t=cu(),n=a2(e,t),r=new Map;let i=!1;n.forEach(s=>{s.separator&&(i||(i=!0,s.separator.element.focus({preventScroll:!0})));const o=t.get(s.group);o&&r.set(s.group,o.layout)}),Dd({cursorFlags:0,hitRegions:n,initialLayoutMap:r,pointerDownAtPoint:{x:e.clientX,y:e.clientY},state:"active"}),n.length&&e.preventDefault()}const nbe=e=>e,Jw=()=>{},eF=1,tF=2,nF=4,rF=8,xD=3,_D=12;let Ev;function wD(){return Ev===void 0&&(Ev=!1,typeof window<"u"&&(window.navigator.userAgent.includes("Chrome")||window.navigator.userAgent.includes("Firefox"))&&(Ev=!0)),Ev}function rbe({cursorFlags:e,groups:t,state:n}){let r=0,i=0;switch(n){case"active":case"hover":t.forEach(s=>{if(!s.mutableState.disableCursor)switch(s.orientation){case"horizontal":{r++;break}case"vertical":{i++;break}}})}if(!(r===0&&i===0)){switch(n){case"active":{if(e&&wD()){const s=(e&eF)!==0,o=(e&tF)!==0,l=(e&nF)!==0,c=(e&rF)!==0;if(s)return l?"se-resize":c?"ne-resize":"e-resize";if(o)return l?"sw-resize":c?"nw-resize":"w-resize";if(l)return"s-resize";if(c)return"n-resize"}break}}return wD()?r>0&&i>0?"move":r>0?"ew-resize":"ns-resize":r>0&&i>0?"grab":r>0?"col-resize":"row-resize"}}const SD=new WeakMap;function c2(e){if(e.defaultView===null||e.defaultView===void 0)return;let{prevStyle:t,styleSheet:n}=SD.get(e)??{};n===void 0&&(n=new e.defaultView.CSSStyleSheet,e.adoptedStyleSheets&&e.adoptedStyleSheets.push(n));const r=Qc();switch(r.state){case"active":case"hover":{const i=rbe({cursorFlags:r.cursorFlags,groups:r.hitRegions.map(o=>o.group),state:r.state}),s=`*, *:hover {cursor: ${i} !important; }`;if(t===s)return;t=s,i?n.cssRules.length===0?n.insertRule(s):n.replaceSync(s):n.cssRules.length===1&&n.deleteRule(0);break}case"inactive":{t=void 0,n.cssRules.length===1&&n.deleteRule(0);break}}SD.set(e,{prevStyle:t,styleSheet:n})}function iF({document:e,event:t,hitRegions:n,initialLayoutMap:r,mountedGroups:i,pointerDownAtPoint:s,prevCursorFlags:o}){let l=0;n.forEach(u=>{const{group:m,groupSize:h}=u,{orientation:g,panels:b}=m,{disableCursor:x}=m.mutableState;let _=0;s?g==="horizontal"?_=(t.clientX-s.x)/h*100:_=(t.clientY-s.y)/h*100:g==="horizontal"?_=t.clientX<0?-100:100:_=t.clientY<0?-100:100;const w=r.get(m),C=i.get(m);if(!w||!C)return;const{defaultLayoutDeferred:E,derivedPanelConstraints:k,groupSize:N,layout:R,separatorToPanels:A}=C;if(k&&R&&A){const M=zm({delta:_,initialLayout:w,panelConstraints:k,pivotIndices:u.panels.map(L=>b.indexOf(L)),prevLayout:R,trigger:"mouse-or-touch"});if(Yc(M,R)){if(_!==0&&!x)switch(g){case"horizontal":{l|=_<0?eF:tF;break}case"vertical":{l|=_<0?nF:rF;break}}}else Na(u.group,{defaultLayoutDeferred:E,derivedPanelConstraints:k,groupSize:N,layout:M,separatorToPanels:A})}});let c=0;t.movementX===0?c|=o&xD:c|=l&xD,t.movementY===0?c|=o&_D:c|=l&_D,tbe(c),c2(e)}function CD(e){const t=cu(),n=Qc();switch(n.state){case"active":iF({document:e.currentTarget,event:e,hitRegions:n.hitRegions,initialLayoutMap:n.initialLayoutMap,mountedGroups:t,prevCursorFlags:n.cursorFlags})}}function kD(e){if(e.defaultPrevented)return;const t=Qc(),n=cu();switch(t.state){case"active":{if(e.buttons===0){Dd({cursorFlags:0,state:"inactive"}),t.hitRegions.forEach(r=>{const i=jl(r.group.id,!0);Na(r.group,i)});return}iF({document:e.currentTarget,event:e,hitRegions:t.hitRegions,initialLayoutMap:t.initialLayoutMap,mountedGroups:n,pointerDownAtPoint:t.pointerDownAtPoint,prevCursorFlags:t.cursorFlags});break}default:{const r=a2(e,n);r.length===0?t.state!=="inactive"&&Dd({cursorFlags:0,state:"inactive"}):Dd({cursorFlags:0,hitRegions:r,state:"hover"}),c2(e.currentTarget);break}}}function ED(e){if(e.relatedTarget instanceof HTMLIFrameElement)switch(Qc().state){case"hover":Dd({cursorFlags:0,state:"inactive"})}}function TD(e){if(e.defaultPrevented||e.pointerType==="mouse"&&e.button>0)return;const t=Qc();switch(t.state){case"active":Dd({cursorFlags:0,state:"inactive"}),t.hitRegions.length>0&&(c2(e.currentTarget),t.hitRegions.forEach(n=>{const r=jl(n.group.id,!0);Na(n.group,r)}),e.preventDefault())}}function ND(e){let t=0,n=0;const r={};for(const s of e)if(s.defaultSize!==void 0){t++;const o=Ii(s.defaultSize);n+=o,r[s.panelId]=o}else r[s.panelId]=void 0;const i=e.length-t;if(i!==0){const s=Ii((100-n)/i);for(const o of e)o.defaultSize===void 0&&(r[o.panelId]=s)}return r}function ibe(e,t,n){if(!n[0])return;const r=e.panels.find(c=>c.element===t);if(!r||!r.onResize)return;const i=Wd({group:e}),s=e.orientation==="horizontal"?r.element.offsetWidth:r.element.offsetHeight,o=r.mutableValues.prevSize,l={asPercentage:Ii(s/i*100),inPixels:s};r.mutableValues.prevSize=l,r.onResize(l,r.id,o)}function sbe(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function obe({group:e,nextGroupSize:t,prevGroupSize:n,prevLayout:r}){if(n<=0||t<=0||n===t)return r;let i=0,s=0,o=!1;const l=new Map,c=[];for(const h of e.panels){const g=r[h.id]??0;switch(h.panelConstraints.groupResizeBehavior){case"preserve-pixel-size":{o=!0;const b=g/100*n,x=Ii(b/t*100);l.set(h.id,x),i+=x;break}case"preserve-relative-size":default:{c.push(h.id),s+=g;break}}}if(!o||c.length===0)return r;const u=100-i,m={...r};if(l.forEach((h,g)=>{m[g]=h}),s>0)for(const h of c){const g=r[h]??0;m[h]=Ii(g/s*u)}else{const h=Ii(u/c.length);for(const g of c)m[g]=h}return m}function abe(e,t){const n=e.map(i=>i.id),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n)if(!r.includes(i))return!1;return!0}const ad=new Map;function lbe(e){let t=!0;Ln(e.element.ownerDocument.defaultView,"Cannot register an unmounted Group");const n=e.element.ownerDocument.defaultView.ResizeObserver,r=new Set,i=new Set,s=new n(x=>{for(const _ of x){const{borderBoxSize:w,target:C}=_;if(C===e.element){if(t){const E=Wd({group:e});if(E===0)return;const k=jl(e.id);if(!k)return;const N=X1(e),R=k.defaultLayoutDeferred?ND(N):k.layout,A=obe({group:e,nextGroupSize:E,prevGroupSize:k.groupSize,prevLayout:R}),M=Xc({layout:A,panelConstraints:N});if(!k.defaultLayoutDeferred&&Yc(k.layout,M)&&sbe(k.derivedPanelConstraints,N)&&k.groupSize===E)return;Na(e,{defaultLayoutDeferred:!1,derivedPanelConstraints:N,groupSize:E,layout:M,separatorToPanels:k.separatorToPanels})}}else ibe(e,C,w)}});s.observe(e.element),e.panels.forEach(x=>{Ln(!r.has(x.id),`Panel ids must be unique; id "${x.id}" was used more than once`),r.add(x.id),x.onResize&&s.observe(x.element)});const o=Wd({group:e}),l=X1(e),c=e.panels.map(({id:x})=>x).join(",");let u=e.mutableState.defaultLayout;u&&(abe(e.panels,u)||(u=void 0));const m=e.mutableState.layouts[c]??u??ND(l),h=Xc({layout:m,panelConstraints:l}),g=e.element.ownerDocument;ad.set(g,(ad.get(g)??0)+1);const b=new Map;return KB(e).forEach(x=>{x.separator&&b.set(x.separator,x.panels)}),Na(e,{defaultLayoutDeferred:o===0,derivedPanelConstraints:l,groupSize:o,layout:h,separatorToPanels:b}),e.separators.forEach(x=>{Ln(!i.has(x.id),`Separator ids must be unique; id "${x.id}" was used more than once`),i.add(x.id),x.element.addEventListener("keydown",bD)}),ad.get(g)===1&&(g.addEventListener("dblclick",vD,!0),g.addEventListener("pointerdown",yD,!0),g.addEventListener("pointerleave",CD),g.addEventListener("pointermove",kD),g.addEventListener("pointerout",ED),g.addEventListener("pointerup",TD,!0)),function(){t=!1,ad.set(g,Math.max(0,(ad.get(g)??0)-1)),Vve(e),e.separators.forEach(x=>{x.element.removeEventListener("keydown",bD)}),ad.get(g)||(g.removeEventListener("dblclick",vD,!0),g.removeEventListener("pointerdown",yD,!0),g.removeEventListener("pointerleave",CD),g.removeEventListener("pointermove",kD),g.removeEventListener("pointerout",ED),g.removeEventListener("pointerup",TD,!0)),s.disconnect()}}function cbe(){const[e,t]=v.useState({}),n=v.useCallback(()=>t({}),[]);return[e,n]}function u2(e){const t=v.useId();return`${e??t}`}const uu=typeof window<"u"?v.useLayoutEffect:v.useEffect;function rm(e){const t=v.useRef(e);return uu(()=>{t.current=e},[e]),v.useCallback((...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[t])}function d2(...e){return rm(t=>{e.forEach(n=>{if(n)switch(typeof n){case"function":{n(t);break}case"object":{n.current=t;break}}})})}function f2(e){const t=v.useRef({...e});return uu(()=>{for(const n in e)t.current[n]=e[n]},[e]),t.current}const sF=v.createContext(null);function ube(e,t){const n=v.useRef({getLayout:()=>({}),setLayout:nbe});v.useImperativeHandle(t,()=>n.current,[]),uu(()=>{Object.assign(n.current,JB({groupId:e}))})}function oF({children:e,className:t,defaultLayout:n,disableCursor:r,disabled:i,elementRef:s,groupRef:o,id:l,onLayoutChange:c,onLayoutChanged:u,orientation:m="horizontal",resizeTargetMinimumSize:h={coarse:20,fine:10},style:g,...b}){const x=v.useRef({onLayoutChange:{},onLayoutChanged:{}}),_=rm(O=>{Yc(x.current.onLayoutChange,O)||(x.current.onLayoutChange=O,c==null||c(O))}),w=rm(O=>{Yc(x.current.onLayoutChanged,O)||(x.current.onLayoutChanged=O,u==null||u(O))}),C=u2(l),E=v.useRef(null),[k,N]=cbe(),R=v.useRef({lastExpandedPanelSizes:{},layouts:{},panels:[],resizeTargetMinimumSize:h,separators:[]}),A=d2(E,s);ube(C,o);const M=rm((O,z)=>{const P=Qc(),$=hD(O),H=jl(O);if(H){let B=!1;switch(P.state){case"active":{B=P.hitRegions.some(V=>V.group===$);break}}return{flexGrow:H.layout[z]??1,pointerEvents:B?"none":void 0}}return{flexGrow:(n==null?void 0:n[z])??1}}),L=f2({defaultLayout:n,disableCursor:r}),F=v.useMemo(()=>({get disableCursor(){return!!L.disableCursor},getPanelStyles:M,id:C,orientation:m,registerPanel:O=>{const z=R.current;return z.panels=Q1(m,[...z.panels,O]),N(),()=>{z.panels=z.panels.filter(P=>P!==O),N()}},registerSeparator:O=>{const z=R.current;return z.separators=Q1(m,[...z.separators,O]),N(),()=>{z.separators=z.separators.filter(P=>P!==O),N()}},togglePanelDisabled:(O,z)=>{const P=R.current.panels.find(B=>B.id===O);P&&(P.panelConstraints.disabled=z);const $=hD(C),H=jl(C);$&&H&&Na($,{...H,derivedPanelConstraints:X1($)})},toggleSeparatorDisabled:(O,z)=>{const P=R.current.separators.find($=>$.id===O);P&&(P.disabled=z)}}),[M,C,N,m,L]),D=v.useRef(null);return uu(()=>{const O=E.current;if(O===null)return;const z=R.current;let P;if(L.defaultLayout!==void 0&&Object.keys(L.defaultLayout).length===z.panels.length){P={};for(const I of z.panels){const W=L.defaultLayout[I.id];W!==void 0&&(P[I.id]=W)}}const $={disabled:!!i,element:O,id:C,mutableState:{defaultLayout:P,disableCursor:!!L.disableCursor,expandedPanelSizes:R.current.lastExpandedPanelSizes,layouts:R.current.layouts},orientation:m,panels:z.panels,resizeTargetMinimumSize:z.resizeTargetMinimumSize,separators:z.separators};D.current=$;const H=lbe($),{defaultLayoutDeferred:B,derivedPanelConstraints:V,layout:G}=jl($.id,!0);!B&&V.length>0&&(_(G),w(G));const Q=o2(C,I=>{const{defaultLayoutDeferred:W,derivedPanelConstraints:te,layout:U}=I.next;if(W||te.length===0)return;const fe=$.panels.map(({id:ee})=>ee).join(",");$.mutableState.layouts[fe]=U,te.forEach(ee=>{if(ee.collapsible){const{layout:ne}=I.prev??{};if(ne){const se=gi(ee.collapsedSize,U[ee.panelId]),le=gi(ee.collapsedSize,ne[ee.panelId]);se&&!le&&($.mutableState.expandedPanelSizes[ee.panelId]=ne[ee.panelId])}}});const ae=Qc().state!=="active";_(U),ae&&w(U)});return()=>{D.current=null,H(),Q()}},[i,C,w,_,m,k,L]),v.useEffect(()=>{const O=D.current;O&&(O.mutableState.defaultLayout=n,O.mutableState.disableCursor=!!r)}),f.jsx(sF.Provider,{value:F,children:f.jsx("div",{...b,className:t,"data-group":!0,"data-testid":C,id:C,ref:A,style:{height:"100%",width:"100%",overflow:"hidden",...g,display:"flex",flexDirection:m==="horizontal"?"row":"column",flexWrap:"nowrap",touchAction:m==="horizontal"?"pan-y":"pan-x"},children:e})})}oF.displayName="Group";function h2(){const e=v.useContext(sF);return Ln(e,"Group Context not found; did you render a Panel or Separator outside of a Group?"),e}function dbe(e,t){const{id:n}=h2(),r=v.useRef({collapse:Jw,expand:Jw,getSize:()=>({asPercentage:0,inPixels:0}),isCollapsed:()=>!1,resize:Jw});v.useImperativeHandle(t,()=>r.current,[]),uu(()=>{Object.assign(r.current,ZB({groupId:n,panelId:e}))})}function aF({children:e,className:t,collapsedSize:n="0%",collapsible:r=!1,defaultSize:i,disabled:s,elementRef:o,groupResizeBehavior:l="preserve-relative-size",id:c,maxSize:u="100%",minSize:m="0%",onResize:h,panelRef:g,style:b,...x}){const _=!!c,w=u2(c),C=f2({disabled:s}),E=v.useRef(null),k=d2(E,o),{getPanelStyles:N,id:R,orientation:A,registerPanel:M,togglePanelDisabled:L}=h2(),F=h!==null,D=rm((z,P,$)=>{h==null||h(z,c,$)});uu(()=>{const z=E.current;if(z!==null){const P={element:z,id:w,idIsStable:_,mutableValues:{expandToSize:void 0,prevSize:void 0},onResize:F?D:void 0,panelConstraints:{groupResizeBehavior:l,collapsedSize:n,collapsible:r,defaultSize:i,disabled:C.disabled,maxSize:u,minSize:m}};return M(P)}},[l,n,r,i,F,w,_,u,m,D,M,C]),v.useEffect(()=>{L(w,!!s)},[s,w,L]),dbe(w,g);const O=v.useSyncExternalStore(z=>o2(R,z),()=>JSON.stringify(N(R,w)),()=>JSON.stringify(N(R,w)));return f.jsx("div",{...x,"aria-disabled":s||void 0,"data-panel":!0,"data-testid":w,id:w,ref:k,style:{...fbe,display:"flex",flexBasis:0,flexShrink:1,overflow:"visible",...JSON.parse(O)},children:f.jsx("div",{className:t,style:{maxHeight:"100%",maxWidth:"100%",flexGrow:1,overflow:"auto",...b,touchAction:A==="horizontal"?"pan-y":"pan-x"},children:e})})}aF.displayName="Panel";const fbe={minHeight:0,maxHeight:"100%",height:"auto",minWidth:0,maxWidth:"100%",width:"auto",border:"none",borderWidth:0,padding:0,margin:0};function hbe({layout:e,panelConstraints:t,panelId:n,panelIndex:r}){let i,s;const o=e[n],l=t.find(c=>c.panelId===n);if(l){const c=l.maxSize,u=l.collapsible?l.collapsedSize:l.minSize,m=[r,r+1];s=Xc({layout:zm({delta:u-o,initialLayout:e,panelConstraints:t,pivotIndices:m,prevLayout:e}),panelConstraints:t})[n],i=Xc({layout:zm({delta:c-o,initialLayout:e,panelConstraints:t,pivotIndices:m,prevLayout:e}),panelConstraints:t})[n]}return{valueControls:n,valueMax:i,valueMin:s,valueNow:o}}function lF({children:e,className:t,disabled:n,elementRef:r,id:i,style:s,...o}){const l=u2(i),c=f2({disabled:n}),[u,m]=v.useState({}),[h,g]=v.useState("inactive"),b=v.useRef(null),x=d2(b,r),{disableCursor:_,id:w,orientation:C,registerSeparator:E,toggleSeparatorDisabled:k}=h2(),N=C==="horizontal"?"vertical":"horizontal";uu(()=>{const A=b.current;if(A!==null){const M={disabled:c.disabled,element:A,id:l},L=E(M),F=ebe(O=>{g(O.next.state!=="inactive"&&O.next.hitRegions.some(z=>z.separator===M)?O.next.state:"inactive")}),D=o2(w,O=>{const{derivedPanelConstraints:z,layout:P,separatorToPanels:$}=O.next,H=$.get(M);if(H){const B=H[0],V=H.indexOf(B);m(hbe({layout:P,panelConstraints:z,panelId:B.id,panelIndex:V}))}});return()=>{F(),D(),L()}}},[w,l,E,c]),v.useEffect(()=>{k(l,!!n)},[n,l,k]);let R;return n&&!_&&(R="not-allowed"),f.jsx("div",{...o,"aria-controls":u.valueControls,"aria-disabled":n||void 0,"aria-orientation":N,"aria-valuemax":u.valueMax,"aria-valuemin":u.valueMin,"aria-valuenow":u.valueNow,children:e,className:t,"data-separator":n?"disabled":h,"data-testid":l,id:l,ref:x,role:"separator",style:{flexBasis:"auto",cursor:R,...s,flexGrow:0,flexShrink:0,touchAction:"none"},tabIndex:n?void 0:0})}lF.displayName="Separator";const m2=({className:e,...t})=>f.jsx(oF,{className:he("flex h-full w-full",e),...t}),Bm=e=>f.jsx(aF,{...e}),p2=({withHandle:e,orientation:t,disabled:n,className:r,...i})=>f.jsx(lF,{disabled:n,className:he("relative flex items-center justify-center bg-transparent focus-visible:outline-none",t==="vertical"?"h-2 w-full -my-1 cursor-row-resize":"h-full w-2 -mx-1 cursor-col-resize",e&&(t==="vertical"?"before:absolute before:inset-x-0 before:top-1/2 before:h-0.5 before:-translate-y-1/2 before:bg-border":"before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-border"),r),...i,children:f.jsx("span",{className:"sr-only",children:t==="vertical"?"Resize rows":"Resize columns"})});function cF(e,t,n){const r=typeof e.maxTokens=="number"&&Number.isFinite(e.maxTokens)?e.maxTokens:null,i=r&&r>0?Math.min(100,e.usedTokens/r*100):null,s=r!==null?Math.max(0,Math.round(r-e.usedTokens)):null,o=i!==null?Math.max(0,100-i):null;return{...e,compactsAutomatically:e.compactsAutomatically||n,maxTokens:r??void 0,remainingTokens:s,usedPercentage:i,remainingPercentage:o,updatedAt:t}}function mbe(e){const t=e.some(n=>n.kind==="compact_boundary"||n.kind==="compact_summary"||n.kind==="context_cleared");for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&!(r.kind!=="context_window_updated"||r.usage.usedTokens<=0))return cF(r.usage,new Date(r.createdAt).toISOString(),t)}return null}function pbe(e,t){return!e||t===null||!Number.isFinite(t)||t<=0?e:cF({...e,maxTokens:t},e.updatedAt,e.compactsAutomatically)}function Nh(e){return e==null||!Number.isFinite(e)?"0":e<1e3?`${Math.round(e)}`:e<1e4?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:e<1e6?`${Math.round(e/1e3)}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}m`}const g2=[68,32];function gbe(){return{isVisible:!1,mainSizes:[...g2],terminals:[],nextTerminalIndex:0}}function vbe(e,t){return e[t]??gbe()}function eS(e){if(e.length===0)return[];const t=e.reduce((n,r)=>n+Math.max(r,0),0);return!Number.isFinite(t)||t<=0?Array.from({length:e.length},()=>100/e.length):e.map(n=>Math.max(n,0)/t*100)}function bbe(e){let t=e,n="";do n=String.fromCharCode(65+t%26)+n,t=Math.floor(t/26)-1;while(t>=0);return`Terminal ${n}`}function ybe(e){if(e.length===0)return e;const t=e.length+1;return e.map(n=>({...n,size:n.size*e.length/t}))}function ld(e,t,n){return{...e,[t]:n(vbe(e,t))}}const wl=oo()(bf(e=>({projects:{},addTerminal:(t,n)=>e(r=>({projects:ld(r.projects,t,i=>{var c,u;const s=ybe(i.terminals),o={id:((u=(c=globalThis.crypto)==null?void 0:c.randomUUID)==null?void 0:u.call(c))??`terminal-${Date.now()}-${i.nextTerminalIndex}`,title:bbe(i.nextTerminalIndex),size:100/(s.length+1)},l=n?Math.max(s.findIndex(m=>m.id===n)+1,0):s.length;return{...i,isVisible:!0,nextTerminalIndex:i.nextTerminalIndex+1,terminals:[...s.slice(0,l),o,...s.slice(l)]}})})),removeTerminal:(t,n)=>e(r=>({projects:ld(r.projects,t,i=>{const s=i.terminals.filter(l=>l.id!==n);if(s.length===0)return{...i,isVisible:!1,terminals:[]};const o=eS(s.map(l=>l.size));return{...i,terminals:s.map((l,c)=>({...l,size:o[c]??100/s.length}))}})})),toggleVisibility:t=>e(n=>({projects:ld(n.projects,t,r=>({...r,isVisible:r.terminals.length>0?!r.isVisible:!1}))})),resetMainSizes:t=>e(n=>({projects:ld(n.projects,t,r=>({...r,mainSizes:[...g2]}))})),setMainSizes:(t,n)=>e(r=>{if(n.length!==2)return r;const i=eS(n);return{projects:ld(r.projects,t,s=>({...s,mainSizes:i}))}}),setTerminalSizes:(t,n)=>e(r=>({projects:ld(r.projects,t,i=>{if(n.length!==i.terminals.length)return i;const s=eS(n);return{...i,terminals:i.terminals.map((o,l)=>({...o,size:s[l]??o.size}))}})})),clearProject:t=>e(n=>{const{[t]:r,...i}=n.projects;return{projects:i}})}),{name:"terminal-layouts",version:1})),xbe={isVisible:!1,mainSizes:[...g2],terminals:[],nextTerminalIndex:0},_be=35;function wbe(e,t){return!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0?0:e*(t/100)}function Sbe(e,t){const n=wbe(e,t);return n>=0&&n<_be}const x0=350,Cbe=[.4,0,.2,1],kbe=8,RD=1e-6;function Ebe(e,t,n){const r=1-e;return 3*r*r*e*t+3*r*e*e*n+e*e*e}function Tbe(e,t,n){const r=1-e;return 3*r*r*e*t+3*r*e*e*n+e*e*e}function Nbe(e,t,n){const r=1-e;return 3*r*r*t+6*r*e*(n-t)+3*e*e*(1-n)}function Rbe(e,t,n){let r=e;for(let i=0;i<kbe;i+=1){const s=Ebe(r,t,n)-e;if(Math.abs(s)<RD)return r;const o=Nbe(r,t,n);if(Math.abs(o)<RD)break;r-=s/o}return r}function Abe(e){if(e<=0)return 0;if(e>=1)return 1;const[t,n,r,i]=Cbe,s=Rbe(e,t,r);return Tbe(s,n,i)}function uF(e,t,n){const r=Abe(n);return[e[0]+(t[0]-e[0])*r,e[1]+(t[1]-e[1])*r]}function Mbe({projectId:e,shouldRenderRightSidebarLayout:t,showRightSidebar:n,rightSidebarSize:r}){const i=v.useRef(null),s=v.useRef(null),o=v.useRef(null),l=v.useRef(null),c=v.useRef(null),u=v.useRef(!1),m=v.useRef(null),h=v.useRef(!1),g=v.useRef(!1);return v.useEffect(()=>()=>{l.current!==null&&window.cancelAnimationFrame(l.current),c.current!==null&&window.clearTimeout(c.current)},[]),v.useLayoutEffect(()=>{var M,L,F,D,O,z;if(!t){l.current!==null&&(window.cancelAnimationFrame(l.current),l.current=null),c.current!==null&&(window.clearTimeout(c.current),c.current=null),u.current=!1;return}const b=i.current;if(!b)return;l.current!==null&&(window.cancelAnimationFrame(l.current),l.current=null),c.current!==null&&(window.clearTimeout(c.current),c.current=null);const x=m.current,_=x!==null&&x!==e,w=n&&!g.current,C=!h.current,E=n?[100-r,r]:[100,0],k=_||C&&n,N=w||C?[100,0]:[b.getLayout().workspace??E[0],b.getLayout().rightSidebar??E[1]];if(m.current=e,h.current=t,g.current=n,k||Math.abs(N[0]-E[0])<.1&&Math.abs(N[1]-E[1])<.1){b.setLayout({workspace:E[0],rightSidebar:E[1]}),(M=s.current)==null||M.setAttribute("data-right-sidebar-open",n?"true":"false"),(L=o.current)==null||L.setAttribute("data-right-sidebar-open",n?"true":"false"),(F=o.current)==null||F.setAttribute("data-right-sidebar-animated","false");return}u.current=!0,(D=s.current)==null||D.setAttribute("data-right-sidebar-open",n?"true":"false"),(O=o.current)==null||O.setAttribute("data-right-sidebar-open",n?"true":"false"),(z=o.current)==null||z.setAttribute("data-right-sidebar-animated","true"),b.setLayout({workspace:N[0],rightSidebar:N[1]});const R=performance.now(),A=P=>{const $=Math.min(1,(P-R)/x0),H=uF(N,E,$);if(b.setLayout({workspace:H[0],rightSidebar:H[1]}),$<1){l.current=window.requestAnimationFrame(A);return}b.setLayout({workspace:E[0],rightSidebar:E[1]}),l.current=null,c.current=window.setTimeout(()=>{u.current=!1,c.current=null},0)};l.current=window.requestAnimationFrame(A)},[e,r,t,n]),v.useEffect(()=>{t||(h.current=!1,g.current=!1)},[t]),{isAnimating:u,panelGroupRef:i,sidebarPanelRef:s,sidebarVisualRef:o}}function Lbe(e){return e.visibilityState==="visible"?e.activeChatId:null}function jbe(e){e.socket.setFocusedChat(Lbe({activeChatId:e.activeChatId,visibilityState:e.visibilityState}))}function Dbe({socket:e,activeChatId:t}){v.useEffect(()=>{if(typeof document>"u")return;const n=()=>{jbe({socket:e,activeChatId:t,visibilityState:document.visibilityState})};return n(),document.addEventListener("visibilitychange",n),window.addEventListener("pagehide",n),window.addEventListener("pageshow",n),()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("pagehide",n),window.removeEventListener("pageshow",n),e.setFocusedChat(null)}},[e,t])}function Ibe({rootRef:e,fallbackRef:t,enabled:n,canCancel:r}){v.useEffect(()=>{if(!n)return;let i=0,s=null;const o=h=>{const g=h instanceof Element?h:null,b=e.current,x=t.current;if(vM({trigger:"pointer",activeElement:document.activeElement,pointerStartTarget:s,pointerEndTarget:g,root:b,fallback:x,hasActiveOverlay:gM(document),hasActiveSelection:PY(window.getSelection())})!=="restore"){s=null;return}x==null||x.focus({preventScroll:!0}),s=null},l=h=>{cancelAnimationFrame(i),s=h.target instanceof Element?h.target:null},c=h=>{cancelAnimationFrame(i),i=window.requestAnimationFrame(()=>{o(h.target)})},u=()=>{s=null;const h=t.current;!h||h.disabled||h.focus({preventScroll:!0})},m=h=>{if(h.key!=="Escape")return;const g=t.current;vM({trigger:"escape",activeElement:document.activeElement,fallback:g,hasActiveOverlay:gM(document),canCancel:r,defaultPrevented:h.defaultPrevented})==="escape-focus"&&(h.preventDefault(),g==null||g.focus({preventScroll:!0}))};return window.addEventListener("pointerdown",l,!0),window.addEventListener("pointerup",c,!0),window.addEventListener("keydown",m,!0),window.addEventListener(kb,u),()=>{cancelAnimationFrame(i),window.removeEventListener("pointerdown",l,!0),window.removeEventListener("pointerup",c,!0),window.removeEventListener("keydown",m,!0),window.removeEventListener(kb,u)}},[r,n,t,e])}function Pbe(e){const t=e.previousProjectId!==null&&e.previousProjectId!==e.projectId,n=e.previousProjectId===null&&e.projectId!==null;return!t&&!n&&e.showTerminalPane&&!e.wasTerminalVisible}function Obe({previousProjectId:e,projectId:t,previousShouldRenderTerminalLayout:n,previousShowTerminalPane:r,showTerminalPane:i,terminalLayout:s,liveLayout:o}){const l=e!==null&&e!==t,c=i&&!r,u=!n,m=e===null&&t!==null,h=i?s.mainSizes:[100,0];return{currentLayout:c||u?[100,0]:o,shouldSkipAnimation:l||m&&u,targetLayout:h}}function zbe({chatInputRef:e,projectId:t,shouldRenderTerminalLayout:n,showTerminalPane:r,terminalLayout:i}){const s=v.useRef(null),o=v.useRef(null),l=v.useRef(null),c=v.useRef(null),u=v.useRef(null),m=v.useRef(!1),h=v.useRef(null),g=v.useRef(!1),b=v.useRef(!1),x=v.useRef(!1),[_,w]=v.useState(0);return v.useEffect(()=>{var k;const C=h.current,E=x.current;Pbe({previousProjectId:C,projectId:t,showTerminalPane:r,wasTerminalVisible:E})&&w(N=>N+1),C!==null&&C===t&&!r&&E&&((k=e.current)==null||k.focus({preventScroll:!0})),x.current=r,h.current=t},[e,t,r]),v.useEffect(()=>()=>{c.current!==null&&window.cancelAnimationFrame(c.current),u.current!==null&&window.clearTimeout(u.current)},[]),v.useLayoutEffect(()=>{var L,F,D,O,z,P;if(!n){c.current!==null&&(window.cancelAnimationFrame(c.current),c.current=null),u.current!==null&&(window.clearTimeout(u.current),u.current=null),m.current=!1;return}const C=s.current;if(!C)return;c.current!==null&&(window.cancelAnimationFrame(c.current),c.current=null),u.current!==null&&(window.clearTimeout(u.current),u.current=null);const E=h.current,{currentLayout:k,shouldSkipAnimation:N,targetLayout:R}=Obe({previousProjectId:E,projectId:t,previousShouldRenderTerminalLayout:g.current,previousShowTerminalPane:b.current,showTerminalPane:r,terminalLayout:i,liveLayout:[C.getLayout().chat??i.mainSizes[0],C.getLayout().terminal??i.mainSizes[1]]});if(g.current=n,b.current=r,N||Math.abs(k[0]-R[0])<.1&&Math.abs(k[1]-R[1])<.1){C.setLayout({chat:R[0],terminal:R[1]}),(L=o.current)==null||L.setAttribute("data-terminal-open",r?"true":"false"),(F=l.current)==null||F.setAttribute("data-terminal-open",r?"true":"false"),(D=l.current)==null||D.setAttribute("data-terminal-animated","false");return}m.current=!0,(O=o.current)==null||O.setAttribute("data-terminal-open",r?"true":"false"),(z=l.current)==null||z.setAttribute("data-terminal-open",r?"true":"false"),(P=l.current)==null||P.setAttribute("data-terminal-animated","true"),C.setLayout({chat:k[0],terminal:k[1]});const A=performance.now(),M=$=>{const H=Math.min(1,($-A)/x0),B=uF(k,R,H);if(C.setLayout({chat:B[0],terminal:B[1]}),H<1){c.current=window.requestAnimationFrame(M);return}C.setLayout({chat:R[0],terminal:R[1]}),c.current=null,u.current=window.setTimeout(()=>{m.current=!1,u.current=null},0)};c.current=window.requestAnimationFrame(M)},[t,n,r,i]),v.useEffect(()=>{n||(g.current=!1,b.current=!1)},[n]),{isAnimating:m,mainPanelGroupRef:s,terminalFocusRequestVersion:_,terminalPanelRef:o,terminalVisualRef:l}}const AD=e=>Symbol.iterator in e,MD=e=>"entries"in e,LD=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[i,s]of n)if(!r.has(i)||!Object.is(s,r.get(i)))return!1;return!0},Bbe=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let i=n.next(),s=r.next();for(;!i.done&&!s.done;){if(!Object.is(i.value,s.value))return!1;i=n.next(),s=r.next()}return!!i.done&&!!s.done};function Fbe(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:AD(e)&&AD(t)?MD(e)&&MD(t)?LD(e,t):Bbe(e,t):LD({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function jD(e){const t=Cn.useRef(void 0);return n=>{const r=e(n);return Fbe(t.current,r)?t.current:t.current=r}}const im="__new__";function wc(e){var s,o;const t=(s=e==null?void 0:e.modelOptions)==null?void 0:s.reasoningEffort,n=e1(t)?t:e1(e==null?void 0:e.effort)?e.effort:Vc.reasoningEffort,r=rne(e==null?void 0:e.model),i=oE(r,(o=e==null?void 0:e.modelOptions)==null?void 0:o.contextWindow);return{model:r,modelOptions:{reasoningEffort:!U4(r)&&n==="max"?"high":n,contextWindow:i},planMode:!!(e!=null&&e.planMode)}}function Tv(e){var n,r;const t=(n=e==null?void 0:e.modelOptions)==null?void 0:n.reasoningEffort;return{model:ine(e==null?void 0:e.model),modelOptions:{reasoningEffort:t1(t)?t:t1(e==null?void 0:e.effort)?e.effort:wm.reasoningEffort,fastMode:typeof((r=e==null?void 0:e.modelOptions)==null?void 0:r.fastMode)=="boolean"?e.modelOptions.fastMode:wm.fastMode},planMode:!!(e!=null&&e.planMode)}}function $be(){return{claude:{model:"claude-opus-4-7",modelOptions:{...Vc},planMode:!1},codex:{model:"gpt-5.5",modelOptions:{...wm},planMode:!1}}}function Hbe(e,t){return e.reasoningEffort===t.reasoningEffort&&e.contextWindow===t.contextWindow}function Ube(e,t){return e.reasoningEffort===t.reasoningEffort&&e.fastMode===t.fastMode}function Vbe(e,t){return e.claude.model===t.claude.model&&e.claude.planMode===t.claude.planMode&&Hbe(e.claude.modelOptions,t.claude.modelOptions)&&e.codex.model===t.codex.model&&e.codex.planMode===t.codex.planMode&&Ube(e.codex.modelOptions,t.codex.modelOptions)}function Wbe(e,t){if(t===void 0){console.info(`[chat-preferences] ${e}`);return}console.info(`[chat-preferences] ${e}`,t)}function sm(e,t){if(e==="claude"){const r=t.claude;return{provider:"claude",model:r.model,modelOptions:{...r.modelOptions},planMode:r.planMode}}const n=t.codex;return{provider:"codex",model:n.model,modelOptions:{...n.modelOptions},planMode:n.planMode}}function Z1(e){return e.provider==="claude"?{provider:"claude",model:e.model,modelOptions:{...e.modelOptions},planMode:e.planMode}:{provider:"codex",model:e.model,modelOptions:{...e.modelOptions},planMode:e.planMode}}function dF(e){return e.providerHint?sm(e.providerHint,e.providerDefaults):e.defaultProvider==="last_used"?e.sourceState?Z1(e.sourceState):sm("claude",e.providerDefaults):sm(e.defaultProvider,e.providerDefaults)}function fF(e,t){const n=e.chatStates[t];return n||dF({defaultProvider:e.defaultProvider,providerDefaults:e.providerDefaults,legacyComposerState:e.legacyComposerState})}function Nv(e,t,n){const r=fF(e,t);return{chatStates:{...e.chatStates,[t]:n(r)}}}const bi=oo()(bf((e,t)=>({defaultProvider:"last_used",providerDefaults:$be(),chatStates:{},legacyComposerState:{provider:"claude",model:"claude-opus-4-7",modelOptions:{...Vc},planMode:!1},setDefaultProvider:n=>e({defaultProvider:n}),applyServerDefaults:(n,r)=>e(i=>{if(i.defaultProvider===n&&Vbe(i.providerDefaults,r))return{defaultProvider:n,providerDefaults:r};const{[im]:o,...l}=i.chatStates;return{defaultProvider:n,providerDefaults:r,chatStates:l}}),setProviderDefaultModel:(n,r)=>e(i=>({providerDefaults:{...i.providerDefaults,[n]:n==="claude"?wc({...i.providerDefaults.claude,model:r}):Tv({...i.providerDefaults.codex,model:r})}})),setProviderDefaultModelOptions:(n,r)=>e(i=>({providerDefaults:{...i.providerDefaults,[n]:n==="claude"?wc({...i.providerDefaults.claude,modelOptions:{...i.providerDefaults.claude.modelOptions,...r}}):Tv({...i.providerDefaults.codex,modelOptions:{...i.providerDefaults.codex.modelOptions,...r}})}})),setProviderDefaultPlanMode:(n,r)=>e(i=>({providerDefaults:{...i.providerDefaults,[n]:{...i.providerDefaults[n],planMode:r}}})),getComposerState:n=>Z1(fF(t(),n)),initializeComposerForChat:(n,r)=>e(i=>{if(i.chatStates[n])return i;const s=dF({defaultProvider:i.defaultProvider,providerDefaults:i.providerDefaults,sourceState:r==null?void 0:r.sourceState,legacyComposerState:i.legacyComposerState,providerHint:r==null?void 0:r.providerHint});return Wbe("initializeComposerForChat",{chatId:n,composerState:s}),{chatStates:{...i.chatStates,[n]:s}}}),setComposerState:(n,r)=>e(i=>({chatStates:{...i.chatStates,[n]:r.provider==="claude"?{provider:"claude",model:wc(r).model,modelOptions:wc(r).modelOptions,planMode:r.planMode}:Z1(r)}})),setChatComposerProvider:(n,r)=>e(i=>Nv(i,n,()=>sm(r,i.providerDefaults))),setChatComposerModel:(n,r)=>e(i=>Nv(i,n,s=>s.provider==="claude"?{provider:"claude",model:wc({...s,model:r}).model,modelOptions:wc({...s,model:r}).modelOptions,planMode:s.planMode}:{provider:"codex",model:r,modelOptions:Tv({...s,model:r}).modelOptions,planMode:s.planMode})),setChatComposerModelOptions:(n,r)=>e(i=>Nv(i,n,s=>s.provider==="claude"?{provider:"claude",model:s.model,modelOptions:wc({...s,modelOptions:{...s.modelOptions,...r}}).modelOptions,planMode:s.planMode}:{provider:"codex",model:s.model,modelOptions:Tv({...s,modelOptions:{...s.modelOptions,...r}}).modelOptions,planMode:s.planMode})),setChatComposerPlanMode:(n,r)=>e(i=>Nv(i,n,s=>({...s,planMode:r}))),resetChatComposerFromProvider:(n,r)=>e(i=>({chatStates:{...i.chatStates,[n]:sm(r,i.providerDefaults)}}))}),{name:"chat-preferences-state",version:1,partialize:e=>({chatStates:e.chatStates,legacyComposerState:e.legacyComposerState})})),J1=oo()(bf((e,t)=>({drafts:{},attachmentDrafts:{},setDraft:(n,r)=>e(i=>{if(!r){const{[n]:s,...o}=i.drafts;return{drafts:o}}return{drafts:{...i.drafts,[n]:r}}}),clearDraft:n=>e(r=>{const{[n]:i,...s}=r.drafts;return{drafts:s}}),getDraft:n=>t().drafts[n]??"",setAttachmentDrafts:(n,r)=>e(i=>{if(r.length===0){const{[n]:s,...o}=i.attachmentDrafts;return{attachmentDrafts:o}}return{attachmentDrafts:{...i.attachmentDrafts,[n]:r}}}),clearAttachmentDrafts:n=>e(r=>{const{[n]:i,...s}=r.attachmentDrafts;return{attachmentDrafts:s}}),getAttachmentDrafts:n=>t().attachmentDrafts[n]??[]}),{name:"chat-input-drafts"})),v2=oo()(e=>({byChatId:{},loadingByChatId:{},setForChat:(t,n)=>e(r=>({byChatId:{...r.byChatId,[t]:n}})),setLoadingForChat:(t,n)=>e(r=>(r.loadingByChatId[t]??!1)===n?r:{loadingByChatId:{...r.loadingByChatId,[t]:n}}),clear:t=>e(n=>{const r=t in n.byChatId,i=t in n.loadingByChatId;if(!r&&!i)return n;const{[t]:s,...o}=n.byChatId,{[t]:l,...c}=n.loadingByChatId;return{byChatId:o,loadingByChatId:c}})}));function Gbe(e){return{autoResumeOnRateLimit:!!(e!=null&&e.autoResumeOnRateLimit)}}const eC=oo()(bf(e=>({autoResumeOnRateLimit:!1,setAutoResumeOnRateLimit:t=>e({autoResumeOnRateLimit:t})}),{name:"kanna-preferences",version:1,migrate:e=>Gbe(e)}));function qbe(e,t){var n,r,i,s,o,l,c,u,m;return{...e,...t,terminal:{...e.terminal,...t.terminal},editor:{...e.editor,...t.editor},providerDefaults:{claude:{...e.providerDefaults.claude,...(n=t.providerDefaults)==null?void 0:n.claude,modelOptions:{...e.providerDefaults.claude.modelOptions,...(i=(r=t.providerDefaults)==null?void 0:r.claude)==null?void 0:i.modelOptions}},codex:{...e.providerDefaults.codex,...(s=t.providerDefaults)==null?void 0:s.codex,modelOptions:{...e.providerDefaults.codex.modelOptions,...(l=(o=t.providerDefaults)==null?void 0:o.codex)==null?void 0:l.modelOptions}}},cloudflareTunnel:{...e.cloudflareTunnel,...t.cloudflareTunnel},claudeAuth:{tokens:((c=t.claudeAuth)==null?void 0:c.tokens)??e.claudeAuth.tokens},auth:{...e.auth,...t.auth},uploads:{...e.uploads,...t.uploads},subagents:e.subagents,claudeDriver:{preference:((u=t.claudeDriver)==null?void 0:u.preference)??e.claudeDriver.preference,lifecycle:{...e.claudeDriver.lifecycle,...(m=t.claudeDriver)==null?void 0:m.lifecycle}}}}const Qi=oo()(e=>({settings:null,hydrationStatus:"idle",setHydrationStatus:t=>e({hydrationStatus:t}),setFromServer:t=>e({settings:t,hydrationStatus:"ready"}),applyOptimisticPatch:t=>e(n=>({settings:n.settings?qbe(n.settings,t):n.settings}))})),hF=v.createContext(void 0),Kbe=e=>e==="light"||e==="dark"||e==="system";function Ybe(e){return e==="dark"?"black-translucent":"default"}function DD(e,t){if(typeof document>"u")return;let n=document.head.querySelector(`meta[name="${e}"]`);n||(n=document.createElement("meta"),n.setAttribute("name",e),document.head.appendChild(n)),n.setAttribute("content",t)}function ID(e){if(typeof document>"u"||typeof window>"u")return;const t=getComputedStyle(document.body).backgroundColor||getComputedStyle(document.documentElement).backgroundColor;t&&DD("theme-color",t),DD("apple-mobile-web-app-status-bar-style",Ybe(e)),document.documentElement.style.colorScheme=e}const lb=()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",PD=e=>{if(typeof document>"u")return;const t=e==="system"?lb():e;document.documentElement.classList.toggle("dark",t==="dark")},Xbe=()=>{var t;const e=(t=Qi.getState().settings)==null?void 0:t.theme;return e&&Kbe(e)?e:"system"};function Qbe({children:e}){const t=Qi(o=>{var l;return(l=o.settings)==null?void 0:l.theme}),n=Qi(o=>o.applyOptimisticPatch),[r,i]=v.useState(Xbe);v.useEffect(()=>{!t||t===r||i(t)},[t,r]),v.useEffect(()=>{PD(r)},[r]),v.useEffect(()=>{const o=r==="system"?lb():r;ID(o)},[r]),v.useEffect(()=>{if(r!=="system")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),l=()=>{PD("system"),ID(lb())};return o.addEventListener?(o.addEventListener("change",l),()=>o.removeEventListener("change",l)):(o.addListener(l),()=>o.removeListener(l))},[r]);const s=v.useMemo(()=>{const o=r==="system"?lb():r;return{theme:r,resolvedTheme:o,setTheme:l=>{i(l),n({theme:l})}}},[n,r]);return f.jsx(hF.Provider,{value:s,children:e})}function b2(){const e=v.useContext(hF);if(!e)throw new Error("useTheme must be used within ThemeProvider");return e}function cd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function OD(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function Zbe(e){const t=e&&typeof e=="object"&&"content"in e&&Array.isArray(e.content)?e.content:Array.isArray(e)?e:[],n=[];for(const r of t)if(!(!r||typeof r!="object"||!("type"in r))){if(r.type==="text"&&typeof r.text=="string"){n.push({type:"text",text:r.text});continue}if(r.type==="image"){if("data"in r&&typeof r.data=="string"){n.push({type:"image",data:r.data,mimeType:typeof r.mimeType=="string"?r.mimeType:void 0});continue}"source"in r&&r.source&&typeof r.source=="object"&&"type"in r.source&&r.source.type==="base64"&&"data"in r.source&&typeof r.source.data=="string"&&n.push({type:"image",data:r.source.data,mimeType:typeof r.source.media_type=="string"?r.source.media_type:void 0})}}return n}function Jbe(e){const t=e&&typeof e=="object"&&"content"in e&&Array.isArray(e.content)?e.content:Array.isArray(e)?e:null;if(!t)return null;const n=[];for(const r of t)r&&typeof r=="object"&&"type"in r&&r.type==="text"&&typeof r.text=="string"&&n.push(r.text);return n.length>0?n.join(""):null}function eye(e,t){const n=OD(t);switch(e.toolKind){case"ask_user_question":{const s=cd(n),o=cd(s==null?void 0:s.answers)??(s||{});return{answers:Object.fromEntries(Object.entries(o).map(([l,c])=>Array.isArray(c)?[l,c.map(u=>String(u))]:c&&typeof c=="object"&&Array.isArray(c.answers)?[l,c.answers.map(u=>String(u))]:c==null||c===""?[l,[]]:[l,[String(c)]])),...(s==null?void 0:s.discarded)===!0?{discarded:!0}:{}}}case"exit_plan_mode":{const s=cd(n);return{confirmed:typeof(s==null?void 0:s.confirmed)=="boolean"?s.confirmed:void 0,clearContext:typeof(s==null?void 0:s.clearContext)=="boolean"?s.clearContext:void 0,message:typeof(s==null?void 0:s.message)=="string"?s.message:void 0,...(s==null?void 0:s.discarded)===!0?{discarded:!0}:{}}}case"offer_download":{const s=Jbe(n),o=s?OD(s):n,l=cd(o);return{contentUrl:typeof(l==null?void 0:l.contentUrl)=="string"?l.contentUrl:"",relativePath:typeof(l==null?void 0:l.relativePath)=="string"?l.relativePath:"",fileName:typeof(l==null?void 0:l.fileName)=="string"?l.fileName:"",displayName:typeof(l==null?void 0:l.displayName)=="string"?l.displayName:typeof(l==null?void 0:l.fileName)=="string"?l.fileName:"",size:typeof(l==null?void 0:l.size)=="number"?l.size:0,...typeof(l==null?void 0:l.mimeType)=="string"?{mimeType:l.mimeType}:{}}}case"image_generation":{const s=cd(n);return{contentUrl:typeof(s==null?void 0:s.contentUrl)=="string"?s.contentUrl:"",relativePath:typeof(s==null?void 0:s.relativePath)=="string"?s.relativePath:"",fileName:typeof(s==null?void 0:s.fileName)=="string"?s.fileName:""}}case"read_file":if(typeof n=="string")return n;const r=Zbe(n);if(r.length>0)return{content:r.flatMap(s=>s.type==="text"?[s.text]:[]).join(""),blocks:r};const i=cd(n);return{content:typeof(i==null?void 0:i.content)=="string"?i.content:JSON.stringify(n,null,2)};default:return n}}function mF(e){return new Date(e).toISOString()}function Ai(e){return{id:e._id,messageId:e.messageId,timestamp:mF(e.createdAt),hidden:e.hidden}}function tye(e){return{id:e._id,messageId:e.messageId,hidden:e.hidden,kind:"tool",toolKind:e.tool.toolKind,toolName:e.tool.toolName,toolId:e.tool.toolId,input:e.tool.input,timestamp:mF(e.createdAt)}}function nye(e){if(e.debugRaw)try{return JSON.parse(e.debugRaw).tool_use_result}catch{return}}function pF(e){const t=new Map,n=[];for(const r of e)switch(r.kind){case"user_prompt":n.push({...Ai(r),kind:"user_prompt",content:r.content,attachments:r.attachments??[],steered:r.steered,autoContinue:r.autoContinue});break;case"system_init":n.push({...Ai(r),kind:"system_init",provider:r.provider,model:r.model,tools:r.tools,agents:r.agents,slashCommands:r.slashCommands,mcpServers:r.mcpServers,debugRaw:r.debugRaw});break;case"account_info":n.push({...Ai(r),kind:"account_info",accountInfo:r.accountInfo});break;case"assistant_text":n.push({...Ai(r),kind:"assistant_text",text:r.text});break;case"tool_call":{const i=tye(r);t.set(r.tool.toolId,{hydrated:i,normalized:r.tool}),n.push(i);break}case"tool_result":{const i=t.get(r.toolId);if(i){const s=i.normalized.toolKind==="ask_user_question"||i.normalized.toolKind==="exit_plan_mode"?nye(r)??r.content:r.content;i.hydrated.result=eye(i.normalized,s),i.hydrated.rawResult=s,i.hydrated.isError=r.isError,r.persisted&&(i.hydrated.persisted=r.persisted)}break}case"result":n.push({...Ai(r),kind:"result",success:!r.isError,cancelled:r.subtype==="cancelled",result:r.result,durationMs:r.durationMs,costUsd:r.costUsd});break;case"status":n.push({...Ai(r),kind:"status",status:r.status});break;case"context_window_updated":n.push({...Ai(r),kind:"context_window_updated",usage:r.usage});break;case"compact_boundary":n.push({...Ai(r),kind:"compact_boundary"});break;case"compact_summary":n.push({...Ai(r),kind:"compact_summary",summary:r.summary});break;case"context_cleared":n.push({...Ai(r),kind:"context_cleared"});break;case"interrupted":n.push({...Ai(r),kind:"interrupted"});break;case"auto_continue_prompt":n.push({...Ai(r),kind:"auto_continue_prompt",scheduleId:r.scheduleId});break;case"pending_tool_request":n.push({...Ai(r),kind:"pending_tool_request",toolRequestId:r.toolRequestId,toolName:r.toolName,arguments:r.arguments});break;case"tool_request_resolved":break;default:n.push({...Ai(r),kind:"unknown",json:JSON.stringify(r,null,2)});break}return n}const rye=["AskUserQuestion","ExitPlanMode","TodoWrite"],iye=new Set(["TodoWrite"]);function sye(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r.kind!=="tool")continue;const i=r;if(i.toolName===t&&!i.result)return i.id}return null}function oye(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r.kind!=="tool")continue;const i=r;if(i.toolName===t)return i.id}return null}function aye(e){const t={};for(const n of rye)t[n]=iye.has(n)?oye(e,n):sye(e,n);return t}function lye(e){return e==="starting"||e==="running"||e==="waiting_for_user"}function cye(e){return e==="starting"||e==="running"||e==="waiting_for_user"}const y2="pushDeviceId";function gF(){return typeof localStorage>"u"?null:localStorage.getItem(y2)}function uye(e){typeof localStorage>"u"||localStorage.setItem(y2,e)}function dye(){typeof localStorage>"u"||localStorage.removeItem(y2)}function fye(){return!(typeof window>"u"||typeof Notification>"u"||!("serviceWorker"in navigator)||typeof globalThis.PushManager>"u")}function hye(){var t;if(typeof window>"u")return!1;if(window.isSecureContext)return!0;const e=((t=window.location)==null?void 0:t.hostname)??"";return e==="localhost"||e==="127.0.0.1"||e==="::1"}function tC(){if(!fye())return{state:"unsupported"};if(!hye())return{state:"insecure-context"};switch(Notification.permission){case"granted":return{state:"granted"};case"denied":return{state:"denied"};default:return{state:"default"}}}function mye(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64url"));const t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/-/g,"+").replace(/_/g,"/"),r=atob(n),i=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)i[s]=r.charCodeAt(s);return i}function pye(e){const t=e||"";return/iPhone|iPad/i.test(t)?"iPhone / iPad":/Android/i.test(t)?"Android":/Macintosh/i.test(t)?"Mac":/Windows/i.test(t)?"Windows PC":t||"Browser"}async function gye(e){const t=tC();if(t.state==="unsupported")throw new Error("Push not supported in this browser");if(t.state==="insecure-context")throw new Error("Push requires a secure context (HTTPS)");if(t.state==="denied")throw new Error("Notification permission previously denied");if(await Notification.requestPermission()!=="granted")throw new Error("Notification permission was not granted");const r=await navigator.serviceWorker.register("/sw.js");await navigator.serviceWorker.ready;const i=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:mye(e.vapidPublicKey)}),s=i.toJSON(),o=s.endpoint??i.endpoint,l=s.keys??{};if(!o||!l.p256dh||!l.auth)throw new Error("Subscription returned without endpoint or keys");const c=navigator.userAgent??"",{id:u}=await e.sendToServer({subscription:{endpoint:o,keys:{p256dh:l.p256dh,auth:l.auth}},label:pye(c),userAgent:c});return u}async function vye(e){const n=await(await navigator.serviceWorker.ready).pushManager.getSubscription();n&&await n.unsubscribe(),await e.sendToServer(e.pushDeviceId)}typeof navigator<"u"&&"serviceWorker"in navigator&&navigator.serviceWorker.addEventListener("message",e=>{const t=e.data;(t==null?void 0:t.type)==="kanna.navigate"&&typeof t.url=="string"&&(window.location.href=t.url)});const bye=25e3,yye=15e3,xye=4e3,zD="kanna:profile-send-to-starting";function BD(){try{return window.sessionStorage.getItem(zD)==="1"||window.localStorage.getItem(zD)==="1"}catch{return!1}}class _ye{constructor(t){re(this,"url");re(this,"ws",null);re(this,"started",!1);re(this,"reconnectTimer",null);re(this,"reconnectDelayMs",750);re(this,"subscriptions",new Map);re(this,"pending",new Map);re(this,"outboundQueue",[]);re(this,"statusListeners",new Set);re(this,"heartbeatTimer",null);re(this,"pingTimeoutTimer",null);re(this,"pingPromise",null);re(this,"lastOpenAt",0);re(this,"lastMessageAt",0);re(this,"reconnectImmediatelyOnClose",!1);re(this,"handleWindowFocus",()=>{this.ensureHealthyConnection()});re(this,"handleVisibilityChange",()=>{if(document.visibilityState==="visible"){this.startHeartbeat(),this.ensureHealthyConnection();return}this.stopHeartbeat()});re(this,"handleOnline",()=>{this.ensureHealthyConnection()});this.url=t}start(){this.started||(this.started=!0,window.addEventListener("focus",this.handleWindowFocus),window.addEventListener("online",this.handleOnline),document.addEventListener("visibilitychange",this.handleVisibilityChange),this.connect())}dispose(){var t;this.started=!1,this.reconnectTimer&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopHeartbeat(),this.clearPingState(),window.removeEventListener("focus",this.handleWindowFocus),window.removeEventListener("online",this.handleOnline),document.removeEventListener("visibilitychange",this.handleVisibilityChange),(t=this.ws)==null||t.close(),this.ws=null;for(const n of this.pending.values())n.reject(new Error("Socket disposed"));this.pending.clear()}onStatus(t){return this.statusListeners.add(t),t(this.getStatus()),()=>{this.statusListeners.delete(t)}}subscribe(t,n,r){const i=Tc();return this.subscriptions.set(i,{topic:t,listener:n,eventListener:r}),this.enqueue({v:1,type:"subscribe",id:i,topic:t}),()=>{this.subscriptions.delete(i),this.enqueue({v:1,type:"unsubscribe",id:i})}}subscribeTerminal(t,n){const r=Tc(),i={type:"terminal",terminalId:t};return this.subscriptions.set(r,{topic:i,listener:n.onSnapshot,eventListener:n.onEvent}),this.enqueue({v:1,type:"subscribe",id:r,topic:i}),()=>{this.subscriptions.delete(r),this.enqueue({v:1,type:"unsubscribe",id:r})}}command(t){const n=Tc(),r={v:1,type:"command",id:n,command:t};return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),this.enqueue(r)})}setFocusedChat(t){const n=Tc();this.enqueue({v:1,type:"command",id:n,command:{type:"push.setFocusedChat",chatId:t}})}ensureHealthyConnection(){return!this.ws||this.ws.readyState===WebSocket.CLOSED||this.ws.readyState===WebSocket.CLOSING?(this.reconnectNow(),Promise.resolve()):this.ws.readyState===WebSocket.CONNECTING||!this.isConnectionStale()?Promise.resolve():this.sendPing()}connect(){this.started&&(this.emitStatus("connecting"),this.ws=new WebSocket(this.url),this.ws.addEventListener("open",()=>{this.reconnectDelayMs=750,this.reconnectImmediatelyOnClose=!1,this.lastOpenAt=Date.now(),this.lastMessageAt=this.lastOpenAt,this.emitStatus("connected"),this.startHeartbeat();for(const[n,r]of this.subscriptions.entries())this.sendNow({v:1,type:"subscribe",id:n,topic:r.topic});for(;this.outboundQueue.length>0;){const n=this.outboundQueue.shift();n&&this.sendNow(n)}const t=gF();t&&this.sendNow({v:1,type:"command",id:Tc(),command:{type:"push.identifyDevice",pushDeviceId:t}})}),this.ws.addEventListener("message",t=>{var s,o;this.lastMessageAt=Date.now();const n=performance.now(),r=String(t.data);let i;try{i=JSON.parse(r)}catch{return}if(BD()&&i.type==="snapshot"&&i.snapshot.type==="chat"&&((s=i.snapshot.data)==null?void 0:s.runtime.status)==="starting"&&console.debug("[kanna/send->starting][client-ws]",{stage:"socket_message_received",receivedAt:n,payloadBytes:r.length,chatId:i.snapshot.data.runtime.chatId,status:i.snapshot.data.runtime.status,messageCount:i.snapshot.data.messages.length}),BD()&&i.type==="ack"&&console.debug("[kanna/send->starting][client-ws]",{stage:"socket_ack_received",receivedAt:n,payloadBytes:r.length,commandId:i.id}),i.type==="snapshot"){const l=this.subscriptions.get(i.id);l==null||l.listener(i.snapshot.data);return}if(i.type==="event"){const l=this.subscriptions.get(i.id);(o=l==null?void 0:l.eventListener)==null||o.call(l,i.event);return}if(i.type==="ack"){const l=this.pending.get(i.id);if(!l)return;this.pending.delete(i.id),l.resolve(i.result);return}if(i.type==="error"){if(!i.id){console.error(zQ,i.message);return}const l=this.pending.get(i.id);if(!l)return;this.pending.delete(i.id),l.reject(new Error(i.message))}}),this.ws.addEventListener("close",()=>{if(!this.started)return;const t=this.reconnectImmediatelyOnClose;this.reconnectImmediatelyOnClose=!1,this.stopHeartbeat(),this.clearPingState(),this.emitStatus("disconnected");for(const n of this.pending.values())n.reject(new Error("Disconnected"));if(this.pending.clear(),t){this.connect();return}this.scheduleReconnect()}))}scheduleReconnect(){this.reconnectTimer===null&&(this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.connect(),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,5e3)},this.reconnectDelayMs))}getStatus(){var t,n;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?"connected":((n=this.ws)==null?void 0:n.readyState)===WebSocket.CONNECTING?"connecting":"disconnected"}emitStatus(t){for(const n of this.statusListeners)n(t)}isConnectionStale(){const t=Math.max(this.lastMessageAt,this.lastOpenAt);return t>0&&Date.now()-t>=bye}sendPing(){if(this.pingPromise)return this.pingPromise;const t=this.command({type:"system.ping"}).then(()=>{this.clearPingState()}).catch(n=>{throw this.clearPingState(),this.reconnectNow(),n});return this.pingTimeoutTimer=window.setTimeout(()=>{this.clearPingState(),this.reconnectNow()},xye),this.pingPromise=t,t}reconnectNow(){if(this.reconnectTimer!==null&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),!this.ws||this.ws.readyState===WebSocket.CLOSED){this.connect();return}this.ws.readyState!==WebSocket.CONNECTING&&(this.reconnectImmediatelyOnClose=!0,this.ws.close())}startHeartbeat(){document.visibilityState==="visible"&&this.heartbeatTimer===null&&(this.heartbeatTimer=window.setInterval(()=>{var t;if(document.visibilityState!=="visible"){this.stopHeartbeat();return}((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ensureHealthyConnection()},yye))}stopHeartbeat(){this.heartbeatTimer!==null&&(window.clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}clearPingState(){this.pingTimeoutTimer!==null&&(window.clearTimeout(this.pingTimeoutTimer),this.pingTimeoutTimer=null),this.pingPromise=null}enqueue(t){var n;if(((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN){this.sendNow(t);return}this.outboundQueue.push(t)}sendNow(t){var n;(n=this.ws)==null||n.send(JSON.stringify(t))}}async function wye(e){const{toast:t}=await K(async()=>{const{toast:r}=await import("./index-CEDSh4y6.js");return{toast:r}},[]);t(`${e} ${e===1?"process":"processes"} survived restart`,{description:"Review and stop them in Background tasks (⌘⇧B).",action:{label:"Review",onClick:()=>Ys.getState().openDialog()}})}function Sye(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const r of n)if(e[r]!==t[r])return!1;return!0}function Cye(e,t){return e===t?!0:!e||!t?!1:e.chatId===t.chatId&&e.projectId===t.projectId&&e.localPath===t.localPath&&e.title===t.title&&e.status===t.status&&e.isDraining===t.isDraining&&e.provider===t.provider&&e.planMode===t.planMode&&Sye(e.sessionTokensByProvider,t.sessionTokensByProvider)}function kye(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>{var i;return n._id===((i=t[r])==null?void 0:i._id)})}function Eye(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>{var i;return n.id===((i=t[r])==null?void 0:i.id)})}function Tye(e,t){return e===t?!0:!e||!t?!1:e.hasOlder===t.hasOlder&&e.olderCursor===t.olderCursor&&e.recentLimit===t.recentLimit}function Nye(e,t){return e.id===t.id&&e.content===t.content&&e.createdAt===t.createdAt&&e.provider===t.provider&&e.model===t.model&&e.planMode===t.planMode&&JSON.stringify(e.modelOptions)===JSON.stringify(t.modelOptions)&&Rye(e.attachments,t.attachments)}function Rye(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return!!i&&n.id===i.id&&n.kind===i.kind&&n.displayName===i.displayName&&n.absolutePath===i.absolutePath&&n.relativePath===i.relativePath&&n.contentUrl===i.contentUrl&&n.mimeType===i.mimeType&&n.size===i.size})}function Aye(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>Nye(n,t[r]))}function Mye(e,t){var s,o;if(e===t)return!0;if(!e||!t||e.status!==t.status||e.branchName!==t.branchName||e.defaultBranchName!==t.defaultBranchName||e.hasOriginRemote!==t.hasOriginRemote||e.originRepoSlug!==t.originRepoSlug||e.hasUpstream!==t.hasUpstream||e.aheadCount!==t.aheadCount||e.behindCount!==t.behindCount||e.lastFetchedAt!==t.lastFetchedAt)return!1;const n=((s=e.branchHistory)==null?void 0:s.entries)??[],r=((o=t.branchHistory)==null?void 0:o.entries)??[];return n.length!==r.length||!n.every((l,c)=>{const u=r[c];return!!u&&l.sha===u.sha&&l.summary===u.summary&&l.description===u.description&&l.authorName===u.authorName&&l.authoredAt===u.authoredAt&&l.githubUrl===u.githubUrl&&l.tags.length===u.tags.length&&l.tags.every((m,h)=>m===u.tags[h])})||e.files.length!==t.files.length?!1:e.files.every((l,c)=>{const u=t.files[c];return!!u&&l.path===u.path&&l.changeType===u.changeType&&l.isUntracked===u.isUntracked&&l.additions===u.additions&&l.deletions===u.deletions&&l.patchDigest===u.patchDigest&&l.mimeType===u.mimeType&&l.size===u.size})}function Lye(e,t){return!!(e&&e.status!=="unknown"&&t&&t.status==="unknown"&&t.files.length===0)}function jye(e,t){if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(i=>{const s=e[i],o=t[i];return!s||!o?!1:s.state===o.state&&s.scheduledAt===o.scheduledAt&&s.resetAt===o.resetAt&&s.detectedAt===o.detectedAt&&s.tz===o.tz})}function Dye(e,t){if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(i=>{const s=e[i],o=t[i];return!s||!o?!1:s.state===o.state&&s.url===o.url&&s.error===o.error&&s.port===o.port&&s.activatedAt===o.activatedAt&&s.stoppedAt===o.stoppedAt})}function Iye(e,t){return e===t?!0:!e||!t?!1:Cye(e.runtime,t.runtime)&&Aye(e.queuedMessages,t.queuedMessages)&&kye(e.messages,t.messages)&&Tye(e.history,t.history)&&Eye(e.availableProviders,t.availableProviders)&&jye(e.schedules,t.schedules)&&e.liveScheduleId===t.liveScheduleId&&Dye(e.tunnels,t.tunnels)&&e.liveTunnelId===t.liveTunnelId}function FD(e,t){const n=new Map;for(const r of e)n.set(r._id,r);for(const r of t)n.set(r._id,r);return[...n.values()]}function Pye(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if((n==null?void 0:n.kind)==="user_prompt"&&n.content.trim().length>0)return n.content}return null}const $D="__new_chat__",vF="lever-theme",bF="chat-sound-preferences",yF="terminal-preferences",xF="chat-preferences";function tS(e){if(typeof window>"u")return null;const t=window.localStorage.getItem(e);if(!t)return null;try{const n=JSON.parse(t);return n.state&&typeof n.state=="object"&&!Array.isArray(n.state)?n.state:null}catch{return null}}function Oye(){if(typeof window>"u")return null;const e={},t=window.localStorage.getItem(vF);(t==="light"||t==="dark"||t==="system")&&(e.theme=t);const n=tS(bF);((n==null?void 0:n.chatSoundPreference)==="never"||(n==null?void 0:n.chatSoundPreference)==="unfocused"||(n==null?void 0:n.chatSoundPreference)==="always")&&(e.chatSoundPreference=n.chatSoundPreference),((n==null?void 0:n.chatSoundId)==="blow"||(n==null?void 0:n.chatSoundId)==="bottle"||(n==null?void 0:n.chatSoundId)==="frog"||(n==null?void 0:n.chatSoundId)==="funk"||(n==null?void 0:n.chatSoundId)==="glass"||(n==null?void 0:n.chatSoundId)==="ping"||(n==null?void 0:n.chatSoundId)==="pop"||(n==null?void 0:n.chatSoundId)==="purr"||(n==null?void 0:n.chatSoundId)==="tink")&&(e.chatSoundId=n.chatSoundId);const r=tS(yF);if(r){e.terminal={},typeof r.scrollbackLines=="number"&&(e.terminal.scrollbackLines=r.scrollbackLines),typeof r.minColumnWidth=="number"&&(e.terminal.minColumnWidth=r.minColumnWidth);const s={};(r.editorPreset==="cursor"||r.editorPreset==="vscode"||r.editorPreset==="xcode"||r.editorPreset==="windsurf"||r.editorPreset==="custom")&&(s.preset=r.editorPreset),typeof r.editorCommandTemplate=="string"&&(s.commandTemplate=r.editorCommandTemplate),Object.keys(s).length>0&&(e.editor=s)}const i=tS(xF);return((i==null?void 0:i.defaultProvider)==="last_used"||(i==null?void 0:i.defaultProvider)==="claude"||(i==null?void 0:i.defaultProvider)==="codex")&&(e.defaultProvider=i.defaultProvider),i!=null&&i.providerDefaults&&typeof i.providerDefaults=="object"&&(e.providerDefaults=i.providerDefaults),e.browserSettingsMigrated=!0,Object.keys(e).length>1?e:null}function zye(){typeof window>"u"||(window.localStorage.removeItem(vF),window.localStorage.removeItem(bF),window.localStorage.removeItem(yF),window.localStorage.removeItem(xF))}function Rh(e){Qi.getState().setFromServer(e);const t=pi.getState();t.setScrollbackLines(e.terminal.scrollbackLines),t.setMinColumnWidth(e.terminal.minColumnWidth),t.setEditorPreset(e.editor.preset),t.setEditorCommandTemplate(e.editor.commandTemplate);const n=Mc.getState();n.setChatSoundPreference(e.chatSoundPreference),n.setChatSoundId(e.chatSoundId),bi.getState().applyServerDefaults(e.defaultProvider,e.providerDefaults)}function Bye(e){return JSON.stringify({id:e.id,kind:e.kind,displayName:e.displayName,relativePath:e.relativePath,mimeType:e.mimeType,size:e.size,contentUrl:e.contentUrl})}function x2(e,t=[]){return JSON.stringify({content:e,attachments:t.map(Bye)})}function Fye(e,t){return e.reduce((n,r)=>r.kind!=="user_prompt"?n:n+(x2(r.content,r.attachments??[])===t?1:0),0)}function $ye(e,t,n){const r=new Map;for(const i of n){if(i.kind!=="user_prompt")continue;const s=x2(i.content,i.attachments??[]);r.set(s,(r.get(s)??0)+1)}return e.filter(i=>i.scopeId!==t?!0:(r.get(i.signature)??0)<i.requiredMatchCount)}function Hye(e,t,n){return e.some(r=>r.id===t)?e.filter(r=>r.id!==t):e}const Uye=200,Vye=500;function HD(e,t){var r;const n=e.find(i=>i.chats.some(s=>s.chatId===t));return n?((r=n.chats.find(i=>i.chatId!==t))==null?void 0:r.chatId)??null:null}function UD(e,t){if(!(t!=null&&t.length)||e.length<=1)return e;const n=new Map(e.map((o,l)=>[o.groupKey,l])),r=new Set,i=t.map(o=>{if(r.has(o))return null;r.add(o);const l=n.get(o);return l===void 0?null:e[l]}).filter(o=>!!o);if(i.length===0)return e;const s=[...i,...e.filter(o=>!r.has(o.groupKey))];return s.every((o,l)=>o===e[l])?e:s}function Wye(e=document){return e.visibilityState==="visible"&&e.hasFocus()}function Gye(){return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`}function qye(){const[e]=v.useState(()=>new _ye(Gye()));return v.useEffect(()=>(e.start(),()=>{e.dispose()}),[e]),e}const VD="kanna:profile-send-to-starting";function Kye(){try{return window.sessionStorage.getItem(VD)==="1"||window.localStorage.getItem(VD)==="1"}catch{return!1}}function _F(e){return Number((performance.now()-e).toFixed(1))}function pl(e,t,n){!e||!Kye()||console.debug("[kanna/send->starting][client]",{traceId:e.traceId,stage:t,elapsedMs:_F(e.startedAt),serverChatId:e.serverChatId,routeChatIdAtSend:e.routeChatIdAtSend,...n})}function Yye(e){var t,n;return(e==null?void 0:e.provider)==="claude"&&e.model&&((t=e.modelOptions)!=null&&t.claude)?{provider:"claude",model:e.model,modelOptions:{reasoningEffort:e.modelOptions.claude.reasoningEffort??"high",contextWindow:e.modelOptions.claude.contextWindow??"200k"},planMode:!!e.planMode}:(e==null?void 0:e.provider)==="codex"&&e.model&&((n=e.modelOptions)!=null&&n.codex)?{provider:"codex",model:e.model,modelOptions:{reasoningEffort:e.modelOptions.codex.reasoningEffort??"high",fastMode:e.modelOptions.codex.fastMode??!1},planMode:!!e.planMode}:null}function Xye(e,t){var n;return t?((n=e.find(r=>r.chats.some(i=>i.chatId===t)))==null?void 0:n.groupKey)??null:null}function Qye(e,t){return e==="awaiting_disconnect"&&t==="disconnected"?"awaiting_server_ready":"none"}function Zye(e,t){return t==="updating"||t==="restart_pending"?{active:!0,label:"Installing update"}:e==="awaiting_disconnect"||e==="awaiting_server_ready"?{active:!0,label:"Re-deploying Kanna"}:{active:!1,label:""}}const Jye=30,_2="kanna:ui-update-restart",wF="kanna:last-update-reload-request";function e0e(e){return e+Jye}function t0e(e,t){return t>0?t:e}function nS(){return window.sessionStorage.getItem(_2)}function n0e(e){window.sessionStorage.setItem(_2,e)}function r0e(){window.sessionStorage.removeItem(_2)}function i0e(e,t){return e?String(e)!==t:!1}function s0e(){return window.sessionStorage.getItem(wF)}function o0e(e){window.sessionStorage.setItem(wF,String(e))}function a0e(){return"/auth/status"}function l0e(e,t,n="application/json"){const r=new Blob([t],{type:`${n}; charset=utf-8`}),i=URL.createObjectURL(r),s=document.createElement("a");s.href=i,s.download=e,s.style.display="none",document.body.append(s),s.click(),s.remove(),URL.revokeObjectURL(i)}async function c0e(e=fetch){return(await e(a0e(),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}})).ok}function u0e(e){const t=e.selectedProjectId??e.sidebarProjectId??null;return t?{kind:"project_id",projectId:t}:e.fallbackLocalProjectPath?{kind:"local_path",localPath:e.fallbackLocalProjectPath}:null}function d0e(e,t){return!e||!t?null:e.runtime.chatId!==t?(e.runtime.chatId,e.runtime.provider,null):e}function f0e(e){var yu,xu,Ha;const t=ef(),n=qye(),r=rp(),{resolvedTheme:i}=b2(),[s,o]=v.useState({starredProjectGroups:[],projectGroups:[],stacks:[]}),[l,c]=v.useState(null),[u,m]=v.useState(null),[h,g]=v.useState(null),[b,x]=v.useState(()=>nS()),_=v.useCallback(Y=>{n0e(Y),x(Y)},[]),w=v.useCallback(()=>{r0e(),x(null)},[]),[C,E]=v.useState(null),[k,N]=v.useState([]),[R,A]=v.useState(!1),[M,L]=v.useState(null),[F,D]=v.useState(!1),[O,z]=v.useState({}),[P,$]=v.useState(null),[H,B]=v.useState(null),[V,G]=v.useState(null),[Q,I]=v.useState(null),[W,te]=v.useState("connecting"),[U,fe]=v.useState(!1),[ae,ee]=v.useState(!1),[ne,se]=v.useState(!1),[le,ue]=v.useState(null),[Ae,ce]=v.useState(!1),[De,Ke]=v.useState(!1),[ht,Tt]=v.useState(!1),[qt,Se]=v.useState(null),[Rt,Et]=v.useState(!1),[dt,Bt]=v.useState(null),[Ut,pt]=v.useState(!1),[ln,me]=v.useState(null),[Ce,$e]=v.useState(null),[et,Ee]=v.useState([]),[Pe,Ze]=v.useState(null),[Ye,Ge]=v.useState(0),ft=v.useRef(new Map),st=J1(jD(Y=>Object.keys(Y.drafts).sort())),Vt=J1(jD(Y=>Object.keys(Y.attachmentDrafts).sort())),sn=v.useRef(0),pn=v.useRef(null),dn=v.useRef({projectId:null,diffs:null}),At=Sne(pi(Y=>Y.editorPreset)),Je=v.useMemo(()=>UD(s.projectGroups,l),[l,s.projectGroups]),St=v.useRef(Je);v.useLayoutEffect(()=>{St.current=Je});const xt=v.useMemo(()=>Je===s.projectGroups?s:{...s,projectGroups:Je},[s,Je]);v.useEffect(()=>n.onStatus(te),[n]),v.useEffect(()=>n.subscribe({type:"sidebar"},Y=>{o(Y),c(X=>X&&UD(Y.projectGroups,X)===Y.projectGroups?null:X),fe(!0),Se(null)}),[n]),v.useEffect(()=>{if(W!=="connected")return;const Y=[...new Set([...st,...Vt])].sort();n.command({type:"chat.setDraftProtection",chatIds:Y}).catch(X=>{Se(X instanceof Error?X.message:String(X))})},[Vt,W,st,n]),v.useEffect(()=>n.subscribe({type:"local-projects"},Y=>{m(Y),ee(!0),Se(null)}),[n]),v.useEffect(()=>n.subscribe({type:"update"},Y=>{g(Y),Se(null)}),[n]),v.useEffect(()=>{W==="connected"&&n.command({type:"update.check",force:!0}).catch(Y=>{Se(Y instanceof Error?Y.message:String(Y))})},[W,n]),v.useEffect(()=>{const Y=h==null?void 0:h.reloadRequestedAt;i0e(Y,s0e())&&Y&&(o0e(Y),_("awaiting_disconnect"))},[_,h==null?void 0:h.reloadRequestedAt]),v.useEffect(()=>{const Y=nS();if(Qye(Y,W)==="awaiting_server_ready"){_("awaiting_server_ready");return}},[W,_]),v.useEffect(()=>{if(nS()!=="awaiting_server_ready")return;let Y=!1,X=null;const je=async()=>{try{if(await c0e()){if(Y)return;w(),window.location.reload();return}}catch{}Y||(X=window.setTimeout(()=>{je()},500))};return je(),()=>{Y=!0,X!==null&&window.clearTimeout(X)}},[W,w]),v.useEffect(()=>{function Y(){h!=null&&h.lastCheckedAt&&(Date.now()-h.lastCheckedAt<=3600*1e3||n.command({type:"update.check"}).catch(X=>{Se(X instanceof Error?X.message:String(X))}))}return window.addEventListener("focus",Y),()=>{window.removeEventListener("focus",Y)}},[n,h==null?void 0:h.lastCheckedAt]),v.useEffect(()=>n.subscribe({type:"keybindings"},Y=>{$(Y),Se(null)}),[n]),v.useEffect(()=>n.subscribe({type:"app-settings"},Y=>{B(Y),Rh(Y),Se(null)}),[n]),v.useEffect(()=>n.subscribe({type:"push-config"},Y=>{G(Y)}),[n]),v.useEffect(()=>{let Y=!1;return n.subscribe({type:"bg-tasks"},X=>{Ys.getState().applySnapshot(X.tasks),!Y&&X.orphanRecoveryCount!=null&&X.orphanRecoveryCount>0&&(Y=!0,wye(X.orphanRecoveryCount))},X=>{X.type==="bg-tasks.added"?Ys.getState().applyDiff({op:"added",task:X.task}):X.type==="bg-tasks.updated"?Ys.getState().applyDiff({op:"updated",task:X.task}):X.type==="bg-tasks.removed"&&Ys.getState().applyDiff({op:"removed",task:X.task})})},[n]);const gt=v.useCallback(async()=>{try{Qi.getState().setHydrationStatus("loading");const Y=await n.command({type:"settings.readAppSettings"});B(Y),Rh(Y),Se(null)}catch(Y){Qi.getState().setHydrationStatus("error"),Se(Y instanceof Error?Y.message:String(Y))}},[n]),bt=v.useCallback(async(Y,X)=>{try{await n.command({type:"chat.setPolicyOverride",chatId:Y,policyOverride:X}),Se(null)}catch(je){throw Se(je instanceof Error?je.message:String(je)),je}},[n]),Lt=v.useCallback(async Y=>{try{Qi.getState().applyOptimisticPatch(Y);const X=await n.command({type:"settings.writeAppSettingsPatch",patch:Y});B(X),Rh(X),Se(null)}catch(X){throw Se(X instanceof Error?X.message:String(X)),await gt(),X}},[gt,n]),Wt=v.useCallback(async Y=>{try{Qi.getState().applyOptimisticPatch({cloudflareTunnel:Y});const X=await n.command({type:"appSettings.setCloudflareTunnel",patch:Y});B(X),Rh(X),Se(null)}catch(X){throw Se(X instanceof Error?X.message:String(X)),await gt(),X}},[gt,n]),Te=v.useCallback(async Y=>{try{Qi.getState().applyOptimisticPatch({claudeAuth:Y});const X=await n.command({type:"appSettings.setClaudeAuth",patch:Y});B(X),Rh(X),Se(null)}catch(X){throw Se(X instanceof Error?X.message:String(X)),await gt(),X}},[gt,n]),nt=v.useCallback(async Y=>await n.command({type:"appSettings.testOAuthToken",token:Y}),[n]),Ie=v.useCallback(async()=>{try{const Y=await n.command({type:"settings.readLlmProvider"});I(Y),Se(null)}catch(Y){Se(Y instanceof Error?Y.message:String(Y))}},[n]),Qe=v.useCallback(async Y=>{try{const X=await n.command({type:"settings.writeLlmProvider",provider:Y.provider,apiKey:Y.apiKey,model:Y.model,baseUrl:Y.baseUrl});I(X),Se(null)}catch(X){throw Se(X instanceof Error?X.message:String(X)),X}},[n]),_e=v.useCallback(async Y=>await n.command({type:"settings.validateLlmProvider",provider:Y.provider,apiKey:Y.apiKey,model:Y.model,baseUrl:Y.baseUrl}),[n]);v.useEffect(()=>{W==="connected"&&gt()},[W,gt]),v.useEffect(()=>{if(W!=="connected"||(H==null?void 0:H.browserSettingsMigrated)!==!1)return;const Y=Oye();Y&&Lt(Y).then(zye).catch(()=>{})},[H==null?void 0:H.browserSettingsMigrated,W,Lt]),v.useEffect(()=>{W==="connected"&&Ie()},[W,Ie]),v.useEffect(()=>{function Y(){Ge(X=>X+1)}return window.addEventListener("focus",Y),document.addEventListener("visibilitychange",Y),()=>{window.removeEventListener("focus",Y),document.removeEventListener("visibilitychange",Y)}},[]),v.useEffect(()=>{if(!e){E(null),se(!0);return}++sn.current,St.current.length,St.current.reduce((X,je)=>X+je.chats.length,0),E(null),se(!1);const Y=n.subscribe({type:"chat",chatId:e,recentLimit:Uye},X=>{if(X!=null&&X.runtime.chatId){const je=[...ft.current.values()].filter(_t=>_t.serverChatId===X.runtime.chatId).sort((_t,ir)=>ir.startedAt-_t.startedAt)[0];je&&je.snapshotAt===void 0&&(je.snapshotAt=performance.now(),pl(je,"chat_snapshot_received",{status:X.runtime.status,messageCount:X.messages.length}))}if(E(je=>{const _t=Iye(je,X);return X==null||X.runtime.chatId,X==null||X.runtime.provider,X==null||X.runtime.status,X==null||X.messages.length,_t?je:X}),L((X==null?void 0:X.history.olderCursor)??null),D((X==null?void 0:X.history.hasOlder)??!1),se(!0),Se(null),X){const je=v2.getState();je.setForChat(X.runtime.chatId,X.slashCommands??[]),je.setLoadingForChat(X.runtime.chatId,X.slashCommandsLoading??!1)}});return()=>{St.current.length,St.current.reduce((X,je)=>X+je.chats.length,0),Y()}},[e,n]),v.useEffect(()=>{if(le)return;const Y=Je[0];Y&&ue(Y.groupKey)},[le,Je]),v.useEffect(()=>{if(!e||!U||!ne)return;if(Je.some(X=>X.chats.some(je=>je.chatId===e))){Ce===e&&$e(null);return}Ce!==e&&t("/")},[e,ne,t,Ce,Je,U]),v.useEffect(()=>{C&&(ue(C.runtime.projectId),Ce===C.runtime.chatId&&$e(null))},[C,Ce]),v.useEffect(()=>{if(!e||!U||!Wye())return;const Y=Je.flatMap(X=>X.chats).find(X=>X.chatId===e);Y!=null&&Y.unread&&n.command({type:"chat.markRead",chatId:e}).catch(X=>{Se(X instanceof Error?X.message:String(X))})},[e,Ye,Je,U,n]),v.useEffect(()=>{N([]),A(!1),L(null),D(!1)},[e]);const Fe=v.useMemo(()=>d0e(C,e),[e,C]),qe=v.useMemo(()=>(Fe==null?void 0:Fe.runtime.projectId)??Xye(Je,e)??le,[e,Fe==null?void 0:Fe.runtime.projectId,le,Je]),Ve=v.useMemo(()=>{const Y=qe?O[qe]??null:null;return qe&&Y?(dn.current={projectId:qe,diffs:Y},Y):qe&&dn.current.projectId===qe?dn.current.diffs:Y},[qe,O]);v.useEffect(()=>qe?n.subscribe({type:"project-git",projectId:qe},X=>{z(je=>{const _t=X??null;return Lye(je[qe]??null,_t)||Mye(je[qe]??null,_t)?je:{...je,[qe]:_t}}),Se(null)}):void 0,[qe,n]),v.useEffect(()=>{C==null||C.runtime.chatId,C==null||C.runtime.provider,Fe==null||Fe.runtime.chatId,Fe==null||Fe.runtime.provider},[e,Fe,C,Ce]);const Dt=v.useMemo(()=>FD(k,(Fe==null?void 0:Fe.messages)??[]),[Fe==null?void 0:Fe.messages,k]),Mt=e??$D,Ft=v.useMemo(()=>et.filter(Y=>Y.scopeId===Mt).map(Y=>Y.entry),[Mt,et]),It=v.useMemo(()=>[...Dt,...Ft],[Ft,Dt]),hn=v.useMemo(()=>pF(It),[It]),ur=v.useMemo(()=>Pye(hn),[hn]),xe=v.useMemo(()=>aye(hn),[hn]),ye=(Fe==null?void 0:Fe.runtime)??null,it=(Fe==null?void 0:Fe.queuedMessages)??[],Oe=((Pe==null?void 0:Pe.scopeId)===Mt&&(!ye||ye.status==="idle")?"starting":null)??(ye==null?void 0:ye.status)??null,Be=(Fe==null?void 0:Fe.availableProviders)??Xh,Gt=cye(Oe??void 0),Kt=lye(Oe??void 0),Jt=(ye==null?void 0:ye.isDraining)??!1,ct=((yu=u==null?void 0:u.projects[0])==null?void 0:yu.localPath)??null,mn=(ye==null?void 0:ye.localPath)??ct??((xu=Je[0])==null?void 0:xu.localPath),Pn=!!(le??(ye==null?void 0:ye.projectId)??((Ha=Je[0])==null?void 0:Ha.groupKey)??ct);v.useEffect(()=>{(Pe==null?void 0:Pe.scopeId)===Mt&&ye!=null&&ye.status&&ye.status!=="idle"&&Ze(null)},[Pe,Mt,ye==null?void 0:ye.status]),v.useEffect(()=>{if(!(Pe!=null&&Pe.ackedAt)||Pe.scopeId!==Mt||ye!=null&&ye.status&&ye.status!=="idle")return;const Y=window.setTimeout(()=>{Ze(X=>(X==null?void 0:X.scopeId)===Mt&&X.ackedAt===Pe.ackedAt?null:X)},300);return()=>window.clearTimeout(Y)},[Pe,Mt,ye==null?void 0:ye.status]),v.useEffect(()=>{if(!e||(ye==null?void 0:ye.status)!=="starting")return;const Y=[...ft.current.values()].filter(X=>X.serverChatId===e).sort((X,je)=>je.startedAt-X.startedAt)[0];!Y||Y.startingStatusAt!==void 0||(Y.startingStatusAt=performance.now(),pl(Y,"runtime_status_starting",{status:ye.status}))},[e,ye==null?void 0:ye.status]),v.useEffect(()=>{if(!e||!ye||ye.status==="starting")return;const Y=[...ft.current.values()].filter(X=>X.serverChatId===e).sort((X,je)=>je.startedAt-X.startedAt)[0];!Y||Y.startingRenderedAt!==void 0||(pl(Y,"starting_not_observed",{status:ye.status}),ft.current.delete(Y.traceId))},[e,ye]),v.useLayoutEffect(()=>{if(!e||(ye==null?void 0:ye.status)!=="starting"){pn.current=null;return}const Y=[...ft.current.values()].filter(X=>X.serverChatId===e).sort((X,je)=>je.startedAt-X.startedAt)[0];Y&&pn.current!==Y.traceId&&(pn.current=Y.traceId,Y.startingRenderedAt=performance.now(),pl(Y,"starting_render_committed",{totalMs:_F(Y.startedAt)}),ft.current.delete(Y.traceId))},[e,ye==null?void 0:ye.status]),v.useEffect(()=>{Ee(Y=>{const X=$ye(Y,Mt,Dt);return X.length===Y.length&&X.every((je,_t)=>je===Y[_t])?Y:X})},[Mt,Dt]);const Gn=v.useCallback(async()=>{if(!(!e||!M||R||!F)){A(!0);try{const Y=await n.command({type:"chat.loadHistory",chatId:e,beforeCursor:M,limit:Vye});N(X=>FD(Y.messages,X)),L(Y.olderCursor),D(Y.hasOlder),Se(null)}catch(Y){const X=Y instanceof Error?Y.message:String(Y);Se(X)}finally{A(!1)}}},[e,F,M,R,n]),Ar=v.useCallback(async Y=>{const X=bi.getState(),je=e?X.getComposerState(e):X.getComposerState(im),_t=await n.command({type:"chat.create",projectId:Y});X.initializeComposerForChat(_t.chatId,{sourceState:je}),ue(Y),$e(_t.chatId),t(`/chat/${_t.chatId}`),ce(!1),Se(null)},[e,t,n]),Jr=v.useCallback(async Y=>Y.kind==="project_id"?{projectId:Y.projectId}:Y.kind==="local_path"?{projectId:(await n.command({type:"project.open",localPath:Y.localPath})).projectId,localPath:Y.localPath}:{projectId:(await n.command(Y.project.mode==="new"?{type:"project.create",localPath:Y.project.localPath,title:Y.project.title}:{type:"project.open",localPath:Y.project.localPath})).projectId,localPath:Y.project.localPath},[n]),Xn=v.useCallback(async Y=>{try{const X=Y.kind==="project_id"?null:Y.kind==="local_path"?Y.localPath:Y.project.localPath;X&&me(X);const{projectId:je}=await Jr(Y);await Ar(je)}catch(X){Se(X instanceof Error?X.message:String(X))}finally{me(null)}},[Ar,Jr]),rs=v.useCallback(async Y=>{await Xn({kind:"project_id",projectId:Y})},[Xn]),Bi=v.useCallback(async Y=>{try{const X=await n.command({type:"chat.fork",chatId:Y.chatId}),je=bi.getState();je.initializeComposerForChat(X.chatId,{sourceState:je.getComposerState(Y.chatId)}),$e(X.chatId),t(`/chat/${X.chatId}`),ce(!1),Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[t,n]),yt=v.useCallback(async Y=>{await Xn({kind:"local_path",localPath:Y})},[Xn]),cn=v.useCallback(async Y=>{await Xn({kind:"project_request",project:Y})},[Xn]),Tn=v.useCallback(async Y=>{try{await n.command({type:"update.check",force:Y==null?void 0:Y.force}),Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[n]),yn=v.useCallback(async Y=>{_("awaiting_disconnect");try{const X=await n.command({type:"update.install",version:Y});if(!X.ok){w(),Se(null),await r.alert({title:X.userTitle??"Update failed",description:X.userMessage??"Kanna could not install the update. Try again later.",closeLabel:"OK"});return}if(X.ok&&X.action==="reload"){window.location.reload();return}Se(null)}catch(X){w(),Se(X instanceof Error?X.message:String(X))}},[w,r,_,n]),ao=v.useCallback(async()=>{_("awaiting_disconnect");try{const Y=await n.command({type:"update.reload"});if(!Y.ok){w(),Se(null),await r.alert({title:Y.userTitle??"Re-deploy failed",description:Y.userMessage??"Kanna could not re-deploy. Try again later.",closeLabel:"OK"});return}if(Y.action==="reload"){window.location.reload();return}Se(null)}catch(Y){w(),Se(Y instanceof Error?Y.message:String(Y))}},[w,r,_,n]),Oa=v.useCallback(async()=>{try{const Y=await fetch("/auth/logout",{method:"POST",headers:{Accept:"application/json"}});if(!Y.ok)throw new Error(`Sign out failed with status ${Y.status}`);Se(null),window.location.reload()}catch(Y){Se(Y instanceof Error?Y.message:String(Y))}},[]),is=v.useCallback(async(Y,X)=>{var Lp;const je=(X==null?void 0:X.attachments)??[],_t=Tc(),ir=Tc(),ui=x2(Y,je),tc=e??$D;Ze({scopeId:tc,ackedAt:null});const zs={traceId:ir,optimisticId:_t,startedAt:performance.now(),serverChatId:e,routeChatIdAtSend:e,contentPreview:Y.slice(0,80)};ft.current.set(ir,zs),pl(zs,"handle_send_called",{optimisticScopeId:tc,attachments:je.length,contentLength:Y.length,contentPreview:zs.contentPreview});const M0=Fye(Dt,ui)+et.filter(fr=>fr.scopeId===tc&&fr.signature===ui).length+1;Ee(fr=>[...fr,{id:_t,scopeId:tc,signature:ui,requiredMatchCount:M0,entry:{_id:`optimistic:${_t}`,kind:"user_prompt",content:Y,attachments:je,createdAt:Date.now()}}]),pl(zs,"optimistic_prompt_added",{optimisticId:_t,optimisticScopeId:tc});try{let fr=le??((Lp=Je[0])==null?void 0:Lp.groupKey)??null;if(!e&&!fr&&ct&&(fr=(await n.command({type:"project.open",localPath:ct})).projectId,ue(fr)),!e&&!fr)throw new Error("Open a project first");const _u=eC.getState().autoResumeOnRateLimit,di=await n.command({type:"chat.send",chatId:e??void 0,projectId:e?void 0:fr??void 0,clientTraceId:ir,provider:X==null?void 0:X.provider,content:Y,attachments:je,model:X==null?void 0:X.model,modelOptions:X==null?void 0:X.modelOptions,planMode:X==null?void 0:X.planMode,autoResumeOnRateLimit:_u});if(zs.ackAt=performance.now(),zs.serverChatId=di.chatId??zs.serverChatId,di.queued?(Ee(Bs=>Hye(Bs,_t,{queued:!0})),Ze(null)):Ze(Bs=>Bs&&{scopeId:!e&&di.chatId?di.chatId:Bs.scopeId,ackedAt:performance.now()}),pl(zs,"chat_send_ack_received",{resultChatId:di.chatId??null,queued:di.queued??!1}),!e&&di.chatId){Ee(jp=>jp.map(Lf=>Lf.id===_t?{...Lf,scopeId:di.chatId}:Lf));const Bs=bi.getState();Bs.setComposerState(di.chatId,Yye(X)??Bs.getComposerState(im)),$e(di.chatId),t(`/chat/${di.chatId}`)}Se(null)}catch(fr){throw Ee(_u=>_u.filter(di=>di.id!==_t)),Ze(null),pl(zs,"handle_send_failed",{error:fr instanceof Error?fr.message:String(fr)}),ft.current.delete(ir),Se(fr instanceof Error?fr.message:String(fr)),fr}},[e,ct,t,et,le,Dt,Je,n]),Ho=v.useCallback(async Y=>{if(e)try{await n.command({type:"message.steer",chatId:e,queuedMessageId:Y}),Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[e,n]),ss=v.useCallback(async Y=>{if(e)try{await n.command({type:"message.dequeue",chatId:e,queuedMessageId:Y}),Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[e,n]),za=v.useCallback(async()=>{if(e)try{await n.command({type:"chat.cancel",chatId:e})}catch(Y){Se(Y instanceof Error?Y.message:String(Y))}},[e,n]),dr=v.useCallback(async()=>{if(e)try{await n.command({type:"chat.stopDraining",chatId:e})}catch(Y){Se(Y instanceof Error?Y.message:String(Y))}},[e,n]),Le=v.useCallback(async Y=>{const X=await r.prompt({title:"Rename Chat",initialValue:Y.title,confirmLabel:"Rename"});if(!(!X||X===Y.title))try{await n.command({type:"chat.rename",chatId:Y.chatId,title:X}),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[r,n]),Xe=v.useCallback(async Y=>{if(await r.confirm({title:"Delete Chat",description:`Delete "${Y.title}"? This cannot be undone.`,confirmLabel:"Delete",confirmVariant:"destructive"}))try{if(await n.command({type:"chat.delete",chatId:Y.chatId}),Y.chatId===e){const je=HD(Je,Y.chatId);t(je?`/chat/${je}`:"/")}}catch(je){Se(je instanceof Error?je.message:String(je))}},[e,r,t,Je,n]),Ot=v.useCallback(async Y=>{try{if(await n.command({type:"chat.archive",chatId:Y.chatId}),Y.chatId===e){const X=HD(Je,Y.chatId);t(X?`/chat/${X}`:"/")}Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[e,t,Je,n]),rr=v.useCallback(async Y=>{try{$e(Y),await n.command({type:"chat.unarchive",chatId:Y}),t(`/chat/${Y}`),Se(null)}catch(X){$e(null),Se(X instanceof Error?X.message:String(X))}},[t,n]),ci=v.useCallback(async Y=>{try{await n.command({type:"project.remove",projectId:Y}),wl.getState().clearProject(Y),ji.getState().clearProject(Y),(ye==null?void 0:ye.projectId)===Y&&t("/"),Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[t,ye,n]),lo=v.useCallback(async(Y,X)=>{try{await n.command({type:"project.setStar",projectId:Y,starred:X}),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[n]),Z=v.useCallback(async Y=>{c(Y);try{await n.command({type:"sidebar.reorderProjectGroups",projectIds:Y}),Se(null)}catch(X){c(null),Se(X instanceof Error?X.message:String(X))}},[n]),ze=v.useCallback(async(Y,X)=>{try{await n.command({type:"stack.create",title:Y,projectIds:X}),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[n]),Sn=v.useCallback(async(Y,X)=>{try{await n.command({type:"stack.rename",stackId:Y,title:X}),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[n]),co=v.useCallback(async Y=>{try{await n.command({type:"stack.remove",stackId:Y}),Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[n]),Yl=v.useCallback(async(Y,X)=>{try{await n.command({type:"stack.addProject",stackId:Y,projectId:X}),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[n]),Xl=v.useCallback(async(Y,X)=>{try{await n.command({type:"stack.removeProject",stackId:Y,projectId:X}),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[n]),Nf=v.useCallback(async(Y,X,je)=>{try{const _t=bi.getState(),ir=e?_t.getComposerState(e):_t.getComposerState(im),ui=await n.command({type:"chat.create",projectId:Y,stackId:X,stackBindings:je});_t.initializeComposerForChat(ui.chatId,{sourceState:ir}),ue(Y),$e(ui.chatId),t(`/chat/${ui.chatId}`),ce(!1),Se(null)}catch(_t){Se(_t instanceof Error?_t.message:String(_t))}},[e,t,n]),Ba=v.useCallback(async Y=>{try{const X=await n.command({type:"stack.listWorktrees",projectId:Y});return Se(null),X.worktrees}catch(X){return Se(X instanceof Error?X.message:String(X)),[]}},[n]),Ps=v.useCallback(async()=>await n.command({type:"sessions.importClaude"}),[n]),uo=v.useCallback(async Y=>{const X=pi.getState();Se(null),await n.command({type:"system.openExternal",...Y,editor:Y.action==="open_editor"?Y.editor??{preset:X.editorPreset,commandTemplate:X.editorCommandTemplate}:void 0})},[n]),Rf=v.useCallback(async(Y,X)=>{var _t,ir;const je=(ye==null?void 0:ye.localPath)??((_t=u==null?void 0:u.projects[0])==null?void 0:_t.localPath)??((ir=Je[0])==null?void 0:ir.localPath);if(je)try{await uo({action:Y,localPath:je,editor:X})}catch(ui){Se(ui instanceof Error?ui.message:String(ui))}},[u==null?void 0:u.projects,uo,ye==null?void 0:ye.localPath,Je]),Fa=v.useCallback(async Y=>{var X;try{if(typeof navigator>"u"||!((X=navigator.clipboard)!=null&&X.writeText))throw new Error("Clipboard is not available");await navigator.clipboard.writeText(Y),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[]),$a=v.useCallback(async(Y,X="open_editor",je)=>{try{await uo({action:X,localPath:Y.path,line:Y.line,column:Y.column,editor:je})}catch(_t){Se(_t instanceof Error?_t.message:String(_t))}},[uo]),Tp=v.useCallback(async(Y,X)=>{try{await uo({action:Y,localPath:X})}catch(je){Se(je instanceof Error?je.message:String(je))}},[uo]),Ql=v.useCallback(async(Y=e)=>{if(!Y||Rt)return null;Et(!0);try{const X=await n.command({type:"chat.exportStandalone",chatId:Y,theme:i,attachmentMode:"bundle"});return Se(null),X}catch(X){return Se(X instanceof Error?X.message:String(X)),null}finally{Et(!1)}},[e,Rt,i,n]),Np=v.useCallback(async(Y=e)=>{if(!Y||Rt)return;pt(!1);const X=await Ql(Y);if(X!=null&&X.ok&&X.shareUrl){Bt(X.shareUrl),pt(!0);return}X&&!X.ok&&await r.confirm({title:"Share failed",description:X.error,confirmLabel:"Download transcript JSON",cancelLabel:"Close",confirmVariant:"secondary"})&&l0e(X.transcriptFileName,X.transcriptJson)},[e,r,Ql,Rt]),Zl=v.useCallback(()=>{Bt(null),pt(!1)},[]),Os=v.useCallback(async()=>{var Y;if(!dt)return!1;try{if(typeof navigator>"u"||!((Y=navigator.clipboard)!=null&&Y.writeText))throw new Error("Clipboard is not available");return await navigator.clipboard.writeText(dt),!0}catch(X){return await r.alert({title:"Copy failed",description:X instanceof Error?X.message:String(X),closeLabel:"Close"}),!1}},[r,dt]),Af=v.useCallback(()=>{dt&&(window.open(dt,"_blank","noopener,noreferrer"),Bt(null))},[dt]),Jl=v.useCallback(()=>{var X;const Y=u0e({selectedProjectId:le,sidebarProjectId:(X=Je[0])==null?void 0:X.groupKey,fallbackLocalProjectPath:ct});if(Y){Xn(Y);return}t("/")},[ct,t,le,Je,Xn]),fo=v.useCallback(()=>ce(!0),[]),Mf=v.useCallback(()=>ce(!1),[]),pu=v.useCallback(()=>Ke(!0),[]),Rp=v.useCallback(()=>Ke(!1),[]),gu=v.useCallback(()=>Tt(!0),[]),vu=v.useCallback(()=>Tt(!1),[]),Ap=v.useCallback(async(Y,X,je)=>{if(e)try{await n.command({type:"chat.respondTool",chatId:e,toolUseId:Y,result:{questions:X,answers:je}})}catch(_t){Se(_t instanceof Error?_t.message:String(_t))}},[e,n]),ei=v.useCallback(async(Y,X,je,_t)=>{if(e){X&&bi.getState().setChatComposerPlanMode(e,!1);try{await n.command({type:"chat.respondTool",chatId:e,toolUseId:Y,result:{confirmed:X,...je?{clearContext:!0}:{},..._t?{message:_t}:{}}})}catch(ir){Se(ir instanceof Error?ir.message:String(ir))}}},[e,n]),Uo=v.useCallback(async(Y,X,je,_t)=>{if(e)try{await n.command({type:"chat.respondSubagentTool",chatId:e,runId:Y,toolUseId:X,result:{questions:je,answers:_t}})}catch(ir){Se(ir instanceof Error?ir.message:String(ir))}},[e,n]),bu=v.useCallback(async(Y,X,je)=>{if(e)try{await n.command({type:"chat.respondSubagentTool",chatId:e,runId:Y,toolUseId:X,result:je})}catch(_t){Se(_t instanceof Error?_t.message:String(_t))}},[e,n]),ec=v.useCallback(async(Y,X)=>{if(e)try{await n.command({type:"chat.toolRequestAnswer",chatId:e,toolRequestId:Y,decision:X})}catch(je){Se(je instanceof Error?je.message:String(je))}},[e,n]),Mp=Zye(b,h==null?void 0:h.status);return{socket:n,activeChatId:e,activeProjectId:qe,sidebarData:xt,localProjects:u,updateSnapshot:h,chatSnapshot:C,chatDiffSnapshot:Ve,keybindings:P,appSettings:H,pushConfig:V,llmProvider:Q,connectionStatus:W,sidebarReady:U,uiRestartActive:Mp.active,uiRestartLabel:Mp.label,localProjectsReady:ae,commandError:qt,startingLocalPath:ln,sidebarOpen:Ae,sidebarCollapsed:De,messages:hn,queuedMessages:it,previousPrompt:ur,latestToolIds:xe,runtime:ye,runtimeStatus:Oe,isHistoryLoading:R,hasOlderHistory:F,availableProviders:Be,isProcessing:Gt,canCancel:Kt,isDraining:Jt,isExportingStandalone:Rt,standaloneShareUrl:dt,standaloneShareComplete:Ut,navbarLocalPath:mn,editorLabel:At,hasSelectedProject:Pn,addProjectModalOpen:ht,openSidebar:fo,closeSidebar:Mf,collapseSidebar:pu,expandSidebar:Rp,openAddProjectModal:gu,closeAddProjectModal:vu,loadOlderHistory:Gn,handleCreateChat:rs,handleForkChat:Bi,handleOpenLocalProject:yt,handleCreateProject:cn,handleCheckForUpdates:Tn,handleInstallUpdate:yn,handleForceReload:ao,handleReadAppSettings:gt,handleWriteAppSettings:Lt,handleSetChatPolicyOverride:bt,handleWriteCloudflareTunnel:Wt,handleWriteClaudeAuth:Te,handleTestOAuthToken:nt,handleReadLlmProvider:Ie,handleWriteLlmProvider:Qe,handleValidateLlmProvider:_e,handleSignOut:Oa,handleSend:is,handleSteerQueuedMessage:Ho,handleRemoveQueuedMessage:ss,handleCancel:za,handleStopDraining:dr,handleRenameChat:Le,handleShareChat:Np,handleArchiveChat:Ot,handleOpenArchivedChat:rr,handleDeleteChat:Xe,handleHideProject:ci,handleToggleProjectStar:lo,handleReorderProjectGroups:Z,stacks:xt.stacks,handleCreateStack:ze,handleRenameStack:Sn,handleRemoveStack:co,handleAddProjectToStack:Yl,handleRemoveProjectFromStack:Xl,handleCreateStackChat:Nf,handleListStackWorktrees:Ba,importClaudeSessions:Ps,handleCopyPath:Fa,handleOpenExternal:Rf,handleOpenExternalPath:Tp,handleOpenLocalLink:$a,handleCompose:Jl,handleAskUserQuestion:Ap,handleExitPlanMode:ei,handleSubagentAskUserQuestion:Uo,handleSubagentExitPlanMode:bu,handleExportStandalone:Ql,handleCloseStandaloneShareDialog:Zl,handleOpenStandaloneShareLink:Af,handleCopyStandaloneShareLink:Os,handleToolRequestAnswer:ec}}const SF=v.memo(function({message:t}){return f.jsx("div",{className:"text-pretty prose prose-sm dark:prose-invert px-0.5 w-full max-w-[70ch] space-y-4",children:f.jsx(lu,{remarkPlugins:Sf,components:Cf,children:t.text})})}),_p=({children:e,className:t,animate:n=!0,shimmerWidth:r,...i})=>f.jsx("span",{className:he("mx-auto max-w-md text-foreground/60",n&&"animate-shiny-pulse",t),...i,children:e});function h0e(e){const t=e.split(`
2605
+ `},i),s}function bge(e,t){return e&&"run"in e?async function(n,r){const i=tD(n,{file:r,...t});await e.run(i,r)}:function(n,r){return tD(n,{file:r,...e||t})}}function nD(e){if(e)throw e}var Vw,rD;function yge(){if(rD)return Vw;rD=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},s=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var m=e.call(u,"constructor"),h=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!m&&!h)return!1;var g;for(g in u);return typeof g>"u"||e.call(u,g)},o=function(u,m){n&&m.name==="__proto__"?n(u,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):u[m.name]=m.newValue},l=function(u,m){if(m==="__proto__")if(e.call(u,m)){if(r)return r(u,m).value}else return;return u[m]};return Vw=function c(){var u,m,h,g,b,x,_=arguments[0],w=1,C=arguments.length,E=!1;for(typeof _=="boolean"&&(E=_,_=arguments[1]||{},w=2),(_==null||typeof _!="object"&&typeof _!="function")&&(_={});w<C;++w)if(u=arguments[w],u!=null)for(m in u)h=l(_,m),g=l(u,m),_!==g&&(E&&g&&(s(g)||(b=i(g)))?(b?(b=!1,x=h&&i(h)?h:[]):x=h&&s(h)?h:{},o(_,{name:m,newValue:c(E,x,g)})):typeof g<"u"&&o(_,{name:m,newValue:g}));return _},Vw}var xge=yge();const Ww=yy(xge);function G1(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function _ge(){const e=[],t={run:n,use:r};return t;function n(...i){let s=-1;const o=i.pop();if(typeof o!="function")throw new TypeError("Expected function as last argument, not "+o);l(null,...i);function l(c,...u){const m=e[++s];let h=-1;if(c){o(c);return}for(;++h<i.length;)(u[h]===null||u[h]===void 0)&&(u[h]=i[h]);i=u,m?wge(m,l)(...u):o(null,...u)}}function r(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return e.push(i),t}}function wge(e,t){let n;return r;function r(...o){const l=e.length>o.length;let c;l&&o.push(i);try{c=e.apply(this,o)}catch(u){const m=u;if(l&&n)throw m;return i(m)}l||(c&&c.then&&typeof c.then=="function"?c.then(s,i):c instanceof Error?i(c):s(c))}function i(o,...l){n||(n=!0,t(o,...l))}function s(o){i(null,o)}}const wo={basename:Sge,dirname:Cge,extname:kge,join:Ege,sep:"/"};function Sge(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');bp(e);let n=0,r=-1,i=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else r<0&&(s=!0,r=i+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let o=-1,l=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else o<0&&(s=!0,o=i+1),l>-1&&(e.codePointAt(i)===t.codePointAt(l--)?l<0&&(r=i):(l=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function Cge(e){if(bp(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function kge(e){bp(e);let t=e.length,n=-1,r=0,i=-1,s=0,o;for(;t--;){const l=e.codePointAt(t);if(l===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),l===46?i<0?i=t:s!==1&&(s=1):i>-1&&(s=-1)}return i<0||n<0||s===0||s===1&&i===n-1&&i===r+1?"":e.slice(i,n)}function Ege(...e){let t=-1,n;for(;++t<e.length;)bp(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":Tge(n)}function Tge(e){bp(e);const t=e.codePointAt(0)===47;let n=Nge(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function Nge(e,t){let n="",r=0,i=-1,s=0,o=-1,l,c;for(;++o<=e.length;){if(o<e.length)l=e.codePointAt(o);else{if(l===47)break;l=47}if(l===47){if(!(i===o-1||s===1))if(i!==o-1&&s===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),i=o,s=0;continue}}else if(n.length>0){n="",r=0,i=o,s=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(i+1,o):n=e.slice(i+1,o),r=o-i-1;i=o,s=0}else l===46&&s>-1?s++:s=-1}return n}function bp(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Rge={cwd:Age};function Age(){return"/"}function q1(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Mge(e){if(typeof e=="string")e=new URL(e);else if(!q1(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return Lge(e)}function Lge(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(t)}const Gw=["history","path","basename","stem","extname","dirname"];class DB{constructor(t){let n;t?q1(t)?n={path:t}:typeof t=="string"||jge(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":Rge.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Gw.length;){const s=Gw[r];s in n&&n[s]!==void 0&&n[s]!==null&&(this[s]=s==="history"?[...n[s]]:n[s])}let i;for(i in n)Gw.includes(i)||(this[i]=n[i])}get basename(){return typeof this.path=="string"?wo.basename(this.path):void 0}set basename(t){Kw(t,"basename"),qw(t,"basename"),this.path=wo.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?wo.dirname(this.path):void 0}set dirname(t){iD(this.basename,"dirname"),this.path=wo.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?wo.extname(this.path):void 0}set extname(t){if(qw(t,"extname"),iD(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=wo.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){q1(t)&&(t=Mge(t)),Kw(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?wo.basename(this.path,this.extname):void 0}set stem(t){Kw(t,"stem"),qw(t,"stem"),this.path=wo.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const i=this.message(t,n,r);throw i.fatal=!0,i}info(t,n,r){const i=this.message(t,n,r);return i.fatal=void 0,i}message(t,n,r){const i=new li(t,n,r);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function qw(e,t){if(e&&e.includes(wo.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+wo.sep+"`")}function Kw(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function iD(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function jge(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Dge=(function(e){const r=this.constructor.prototype,i=r[e],s=function(){return i.apply(s,arguments)};return Object.setPrototypeOf(s,r),s}),Ige={}.hasOwnProperty;class n2 extends Dge{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=_ge()}copy(){const t=new n2;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(Ww(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Qw("data",this.frozen),this.namespace[t]=n,this):Ige.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Qw("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const i=n.call(t,...r);typeof i=="function"&&this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=_v(t),r=this.parser||this.Parser;return Yw("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),Yw("process",this.parser||this.Parser),Xw("process",this.compiler||this.Compiler),n?i(void 0,n):new Promise(i);function i(s,o){const l=_v(t),c=r.parse(l);r.run(c,l,function(m,h,g){if(m||!h||!g)return u(m);const b=h,x=r.stringify(b,g);zge(x)?g.value=x:g.result=x,u(m,g)});function u(m,h){m||!h?o(m):s?s(h):n(void 0,h)}}}processSync(t){let n=!1,r;return this.freeze(),Yw("processSync",this.parser||this.Parser),Xw("processSync",this.compiler||this.Compiler),this.process(t,i),oD("processSync","process",n),r;function i(s,o){n=!0,nD(s),r=o}}run(t,n,r){sD(t),this.freeze();const i=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?s(void 0,r):new Promise(s);function s(o,l){const c=_v(n);i.run(t,c,u);function u(m,h,g){const b=h||t;m?l(m):o?o(b):r(void 0,b,g)}}}runSync(t,n){let r=!1,i;return this.run(t,n,s),oD("runSync","run",r),i;function s(o,l){nD(o),i=l,r=!0}}stringify(t,n){this.freeze();const r=_v(n),i=this.compiler||this.Compiler;return Xw("stringify",i),sD(t),i(t,r)}use(t,...n){const r=this.attachers,i=this.namespace;if(Qw("use",this.frozen),t!=null)if(typeof t=="function")c(t,n);else if(typeof t=="object")Array.isArray(t)?l(t):o(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function s(u){if(typeof u=="function")c(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[m,...h]=u;c(m,h)}else o(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function o(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");l(u.plugins),u.settings&&(i.settings=Ww(!0,i.settings,u.settings))}function l(u){let m=-1;if(u!=null)if(Array.isArray(u))for(;++m<u.length;){const h=u[m];s(h)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function c(u,m){let h=-1,g=-1;for(;++h<r.length;)if(r[h][0]===u){g=h;break}if(g===-1)r.push([u,...m]);else if(m.length>0){let[b,...x]=m;const _=r[g][1];G1(_)&&G1(b)&&(b=Ww(!0,_,b)),r[g]=[u,b,...x]}}}}const Pge=new n2().freeze();function Yw(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Xw(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Qw(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function sD(e){if(!G1(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function oD(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function _v(e){return Oge(e)?e:new DB(e)}function Oge(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function zge(e){return typeof e=="string"||Bge(e)}function Bge(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Fge="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",aD=[],lD={allowDangerousHtml:!0},$ge=/^(https?|ircs?|mailto|xmpp)$/i,Hge=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function lu(e){const t=Uge(e),n=Vge(e);return Wge(t.runSync(t.parse(n),n),e)}function Uge(e){const t=e.rehypePlugins||aD,n=e.remarkPlugins||aD,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...lD}:lD;return Pge().use(Lpe).use(n).use(bge,r).use(t)}function Vge(e){const t=e.children||"",n=new DB;return typeof t=="string"&&(n.value=t),n}function Wge(e,t){const n=t.allowedElements,r=t.allowElement,i=t.components,s=t.disallowedElements,o=t.skipHtml,l=t.unwrapDisallowed,c=t.urlTransform||Gge;for(const m of Hge)Object.hasOwn(t,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+Fge+m.id,void 0);return $E(e,u),Fme(e,{Fragment:f.Fragment,components:i,ignoreInvalidStyle:!0,jsx:f.jsx,jsxs:f.jsxs,passKeys:!0,passNode:!0});function u(m,h,g){if(m.type==="raw"&&g&&typeof h=="number")return o?g.children.splice(h,1):g.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let b;for(b in Uw)if(Object.hasOwn(Uw,b)&&Object.hasOwn(m.properties,b)){const x=m.properties[b],_=Uw[b];(_===null||_.includes(m.tagName))&&(m.properties[b]=c(String(x||""),b,m))}}if(m.type==="element"){let b=n?!n.includes(m.tagName):s?s.includes(m.tagName):!1;if(!b&&r&&typeof h=="number"&&(b=!r(m,h,g)),b&&g&&typeof h=="number")return l&&m.children?g.children.splice(h,1,...m.children):g.children.splice(h,1),h}}}function Gge(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),i=e.indexOf("/");return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||$ge.test(e.slice(0,t))?e:""}const wv=new Map;function qge(e){return`${e.id}|${e.contentUrl}|${e.size??0}`}function g0(e){const t=qge(e),n=wv.get(t),[r,i]=v.useState(n??{status:"loading"}),[s,o]=v.useState(t),l=v.useRef(t);return l.current=t,s!==t&&(o(t),i(wv.get(t)??{status:"loading"})),v.useEffect(()=>{if(n&&n.status!=="loading")return;let c=!1;const u=t;return BE(e.contentUrl,A8).then(m=>{if(c||l.current!==u)return;const h={status:"ready",content:m.content,truncated:m.truncated};wv.set(u,h),i(h)}).catch(m=>{if(c||l.current!==u)return;const g={status:"error",message:m instanceof Error?m.message:"Unable to load preview."};wv.set(u,g),i(g)}),()=>{c=!0}},[n,t,e.contentUrl]),r}function Kge({source:e}){const t=g0(e);return t.status==="loading"?f.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[f.jsx("div",{className:"prose hidden"})," Loading…"]}):t.status==="error"?f.jsx("div",{className:"p-4 text-sm text-destructive",children:t.message}):f.jsxs("div",{className:"space-y-2 overflow-auto p-3",children:[t.truncated?f.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:"Preview truncated to 1024 KB."}):null,f.jsx("div",{className:"prose prose-sm prose-invert max-w-none rounded-xl border border-border bg-background p-4",children:f.jsx(lu,{remarkPlugins:Sf,components:Cf,children:t.content})})]})}const Sv=new Map;function Yge(e){return`${e.id}|${e.contentUrl}|${e.size??0}|${e.mimeType}`}function Xge({source:e}){const t=Yge(e),n=Sv.get(t),[r,i]=v.useState(n??{status:"loading"}),[s,o]=v.useState(t),l=v.useRef(t);if(l.current=t,s!==t&&(o(t),i(Sv.get(t)??{status:"loading"})),v.useEffect(()=>{if(n&&n.status!=="loading")return;const g=e.mimeType==="text/tab-separated-values"?" ":",";let b=!1;const x=t;return BE(e.contentUrl,A8).then(_=>{if(b||l.current!==x)return;const w={status:"ready",table:Nue(_.content,g),truncated:_.truncated};Sv.set(x,w),i(w)}).catch(_=>{if(b||l.current!==x)return;const w={status:"error",message:_ instanceof Error?_.message:"Unable to load preview."};Sv.set(x,w),i(w)}),()=>{b=!0}},[n,t,e.contentUrl,e.mimeType]),r.status==="loading")return f.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[f.jsx("table",{className:"sr-only"})," Loading…"]});if(r.status==="error")return f.jsxs("div",{className:"p-4 text-sm text-destructive",children:[f.jsx("table",{className:"sr-only"})," ",r.message]});const{table:c}=r,[u,...m]=c.rows,h=[r.truncated?"Preview truncated to 1024 KB.":null,c.truncatedRows?`Showing first ${c.rows.length} of ${c.rowCount} rows.`:null,c.truncatedColumns?`Showing first ${z1} of ${c.columnCount} columns.`:null].filter(Boolean);return f.jsxs("div",{className:"space-y-2 overflow-auto p-3",children:[h.length?f.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:h.join(" ")}):null,f.jsx("div",{className:"max-h-[70dvh] overflow-auto rounded-xl border border-border bg-background",children:f.jsxs("table",{className:"min-w-full border-collapse text-xs",children:[u?f.jsx("thead",{className:"sticky top-0 bg-muted",children:f.jsx("tr",{children:u.map((g,b)=>f.jsx("th",{className:"border-b border-border px-3 py-2 text-left font-medium",children:g||" "},b))})}):null,f.jsx("tbody",{children:m.map((g,b)=>f.jsx("tr",{className:"odd:bg-background even:bg-muted/20",children:g.map((x,_)=>f.jsx("td",{className:"max-w-[320px] border-b border-border px-3 py-2 align-top",children:f.jsx("div",{className:"whitespace-pre-wrap break-words",children:x||" "})},_))},b))})]})})]})}function Qge({source:e}){const t=g0(e);return t.status==="loading"?f.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[f.jsx("pre",{className:"sr-only"})," Loading…"]}):t.status==="error"?f.jsxs("div",{className:"p-4 text-sm text-destructive",children:[f.jsx("pre",{className:"sr-only"})," ",t.message]}):f.jsxs("div",{className:"space-y-2 overflow-auto p-3",children:[t.truncated?f.jsx(Zge,{children:"Preview truncated to 1024 KB."}):null,f.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-xl border border-border bg-background p-3 text-xs",children:t.content})]})}function Zge({children:e}){return f.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:e})}function Jge({source:e}){const t=g0(e),n=v.useMemo(()=>t.status==="ready"?Tue(t.content):"",[t]);return t.status==="loading"?f.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[f.jsx("pre",{className:"sr-only"})," Loading…"]}):t.status==="error"?f.jsxs("div",{className:"p-4 text-sm text-destructive",children:[f.jsx("pre",{className:"sr-only"})," ",t.message]}):f.jsxs("div",{className:"space-y-2 overflow-auto p-3",children:[t.truncated?f.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:"Preview truncated to 1024 KB."}):null,f.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-xl border border-border bg-background p-3 text-xs",children:n})]})}function eve({source:e}){return f.jsxs("div",{className:"flex h-full flex-col items-stretch justify-center gap-3 p-4",children:[f.jsx("div",{className:"text-sm font-medium text-foreground",children:e.displayName}),f.jsx("audio",{src:e.contentUrl,controls:!0,preload:"metadata",className:"w-full"})]})}function tve({source:e}){return f.jsx("div",{className:"flex h-full items-center justify-center bg-black/40 p-2",children:f.jsx("video",{src:e.contentUrl,controls:!0,playsInline:!0,preload:"metadata",className:"max-h-[60dvh] w-full rounded-xl"})})}const nve=200*1024;function rve(e){const t=e.lastIndexOf(".");if(t<0)return"text";const n=e.slice(t+1).toLowerCase();return{ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",go:"go",rs:"rust",java:"java",rb:"ruby",sh:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",css:"css",scss:"scss",html:"html",json:"json",md:"markdown",sql:"sql",cpp:"cpp",c:"c",h:"c",swift:"swift",kt:"kotlin",php:"php",toml:"toml"}[n]??"text"}function ive({source:e}){const t=g0(e),n=t.status==="ready"&&t.content.length<=nve,r=n?`${e.id}|${e.contentUrl}|${e.size??0}|${t.content.length}`:null,[i,s]=v.useState(null);return v.useEffect(()=>{if(!n||t.status!=="ready"||r===null)return;let o=!1;const l=r;return K(()=>Promise.resolve().then(()=>_le),void 0).then(async c=>{if(o)return;const u=await c.codeToHtml(t.content,{lang:rve(e.fileName),theme:"github-dark"});o||s({key:l,html:u})}).catch(()=>{typeof console<"u"&&console.warn("[file-preview] Shiki unavailable; falling back to plain text")}),()=>{o=!0}},[n,r,t,e.fileName]),t.status==="loading"?f.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[f.jsx("pre",{className:"sr-only"})," Loading…"]}):t.status==="error"?f.jsxs("div",{className:"p-4 text-sm text-destructive",children:[f.jsx("pre",{className:"sr-only"})," ",t.message]}):i&&i.key===r?f.jsx("div",{className:"overflow-auto p-3 text-xs",dangerouslySetInnerHTML:{__html:i.html}}):f.jsxs("div",{className:"space-y-2 overflow-auto p-3",children:[t.truncated?f.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:"Preview truncated to 1024 KB."}):null,f.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-xl border border-border bg-background p-3 text-xs",children:t.content})]})}async function sve(e){var r;const t=ave(e.contentUrl),n=navigator.share;if(typeof n=="function")try{return await n.call(navigator,{title:e.displayName,url:t}),"shared"}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return"shared"}if((r=navigator.clipboard)!=null&&r.writeText)try{return await navigator.clipboard.writeText(t),"copied"}catch{return"failed"}return"failed"}function ove(e){const t=document.createElement("a");t.href=e.contentUrl,t.download=e.fileName,t.rel="noopener",document.body.appendChild(t),t.click(),t.remove()}function ave(e){return typeof window>"u"?e:new URL(e,document.baseURI||window.location.href).toString()}function wf({source:e,open:t,onOpenChange:n}){const r=v.useCallback(()=>n(!1),[n]);return f.jsx(As,{open:t&&e!==null,onOpenChange:n,children:f.jsx(es,{size:"lg",className:"inset-0 h-[100dvh] max-h-none w-full max-w-none translate-x-0 translate-y-0 rounded-none p-0 md:inset-auto md:left-1/2 md:top-1/2 md:h-auto md:max-h-[90dvh] md:w-auto md:max-w-3xl md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-2xl",children:e?f.jsx(lve,{source:e,onClose:r}):null})})}function lve({source:e,onClose:t}){const n=uve(e),[r,i]=v.useState(0),s=v.useRef(null),o=v.useCallback(h=>{s.current={y:h.clientY,lastY:h.clientY,lastT:Date.now()};try{h.currentTarget.setPointerCapture(h.pointerId)}catch{}},[]),l=v.useCallback(h=>{if(!s.current)return;const g=h.clientY-s.current.y;g<0||(s.current.lastY=h.clientY,s.current.lastT=Date.now(),i(g))},[]),c=v.useCallback(h=>{const g=s.current;s.current=null;try{h.currentTarget.releasePointerCapture(h.pointerId)}catch{}if(!g)return;const b=h.clientY-g.y,x=Math.max(1,Date.now()-g.lastT),_=(h.clientY-g.lastY)/x;b>120||_>.5?t():i(0)},[t]),u=v.useCallback(()=>{sve(e)},[e]),m=v.useCallback(()=>ove(e),[e]);return f.jsxs("div",{className:"flex h-full max-h-full flex-col",style:r>0?{transform:`translateY(${r}px)`,transition:"none"}:void 0,children:[f.jsxs("div",{onPointerDown:o,onPointerMove:l,onPointerUp:c,onPointerCancel:c,className:"border-b border-border px-4 py-3 touch-none",children:[f.jsx("div",{className:"mx-auto mb-2 h-1 w-12 rounded-full bg-muted md:hidden",role:"button","aria-label":"Drag down to close"}),f.jsx(Ms,{className:"truncate text-base",children:e.displayName}),f.jsx(af,{className:"truncate text-xs",children:n})]}),f.jsx("div",{className:"min-h-0 flex-1 overflow-auto",role:"region","aria-label":"File preview",children:v.createElement(cve(e),{source:e})},e.id),f.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border px-4 py-3",children:[f.jsxs(Ue,{type:"button",variant:"outline",onClick:u,children:[f.jsx(OG,{className:"mr-2 h-4 w-4"}),"Share"]}),e.origin==="offer_download"?f.jsxs(Ue,{type:"button",onClick:m,children:[f.jsx(rk,{className:"mr-2 h-4 w-4"}),"Download"]}):null]})]})}function cve(e){const t={id:e.id,displayName:e.displayName,mimeType:e.mimeType,size:e.size??0,contentUrl:e.contentUrl,relativePath:e.relativePath??""},n=xf(t);return n==="image"?kme:n==="pdf"?Oj:n==="audio"?eve:n==="video"?tve:n==="table"?Xge:n==="markdown"?Kge:n==="json"?Jge:n==="code"?ive:yf(t).kind==="external"?Oj:Qge}function uve(e){const t={id:e.id,displayName:e.displayName,mimeType:e.mimeType,size:e.size??0,contentUrl:e.contentUrl,relativePath:e.relativePath??""},n=xf(t),r=u0(n,e.mimeType),i=e.size?` · ${kf(e.size)}`:"";return`${r}${i}`}function yp(e,t){return{id:e.id,contentUrl:e.contentUrl,displayName:e.displayName,fileName:e.displayName,relativePath:e.relativePath,mimeType:e.mimeType,size:e.size,origin:t}}function dve(e){const t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function fve({path:e,linkText:t}){const n=v.useMemo(()=>qE(e),[e]),[r,i]=v.useState({kind:"loading"}),[s,o]=v.useState(!1);v.useEffect(()=>{const A=new AbortController;return fetch(n,{method:"HEAD",signal:A.signal}).then(M=>{var D,O;if(A.signal.aborted)return;if(!M.ok){i({kind:M.status===404?"missing":"error"});return}const L=((O=(D=M.headers.get("Content-Type"))==null?void 0:D.split(";")[0])==null?void 0:O.trim())||"application/octet-stream",F=Number.parseInt(M.headers.get("Content-Length")??"0",10)||0;i({kind:"ready",mimeType:L,size:F})}).catch(()=>{A.signal.aborted||i({kind:"error"})}),()=>A.abort()},[n]);const l=dve(e),c=t||l,u=Cme(c,28),m=r.kind==="ready"?r.mimeType:"application/octet-stream",h=r.kind==="ready"?r.size:0,g={id:`local-file-${n}`,kind:"file",displayName:u,absolutePath:e,relativePath:e,contentUrl:n,mimeType:m,size:h};if(r.kind==="missing")return f.jsx("span",{className:"inline-flex align-bottom","data-testid":"local-file-link",children:f.jsx(Do,{attachment:g,disabledReason:"File no longer available"})});const b=xf(g),x=u0(b,m),_=h>0?kf(h):null,w=r.kind==="loading",C=r.kind==="error",E=w?f.jsx("span",{className:"text-muted-foreground",children:"Fetching…"}):C?f.jsx("span",{className:"text-muted-foreground",children:"Unable to load"}):f.jsxs(f.Fragment,{children:[x,_?f.jsxs(f.Fragment,{children:[" · ",f.jsx("span",{className:"tabular-nums",children:_})]}):null]}),k=r.kind==="ready"?yf(g):null,N=k!==null&&!k.openInNewTab,R=[N?"Preview":"Download",c,x,_].filter(Boolean);return N?f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"inline-flex align-bottom","data-testid":"local-file-link",children:f.jsx(Do,{attachment:g,onClick:()=>o(!0),meta:E,ariaLabel:R.join(", ")})}),f.jsx(wf,{source:s?yp(g,"local_file_link"):null,open:s,onOpenChange:o})]}):f.jsx("span",{className:"inline-flex align-bottom","data-testid":"local-file-link",children:f.jsx(Do,{attachment:g,href:n,download:l,meta:E,ariaLabel:R.join(", ")})})}const hve={readonly:!1,localLinkMode:"open",attachmentMode:"live"},mve=v.createContext(hve);function v0(){return v.useContext(mve)}const sy=()=>{},IB=v.createContext(sy);function PB({children:e,onOpenLocalLink:t}){return f.jsx(IB.Provider,{value:t??sy,children:e})}const K1={Task:_b,TaskOutput:_b,Bash:ky,Glob:Gh,Grep:Gh,ExitPlanMode:WA,Read:k5,Edit:aW,Write:cW,Delete:gW,NotebookEdit:Qm,WebFetch:iV,TodoWrite:wV,WebSearch:Gh,KillShell:KG,AskUserQuestion:R5,Skill:HG,EnterPlanMode:WA},OB=sq;function zB(e){return K1[e]?K1[e]:OB}function BB({icon:e,className:t}){return f.jsx(e,{className:t})}function ja({children:e,className:t}){return f.jsx("div",{className:he("flex gap-3 justify-start items-center",t),children:e})}function FB({children:e,className:t}){return f.jsx("div",{className:he("flex items-center gap-1.5 text-xs",t),children:e})}function Fl({children:e,className:t}){return f.jsx("span",{className:he("font-medium text-foreground/80",t),children:e})}function pve({children:e}){return f.jsx("span",{className:"text-muted-foreground",children:e})}function gve({children:e,className:t}){return f.jsxs(ja,{className:he("px-0.5 text-xs tracking-wide",t),children:[f.jsx("div",{className:"w-full h-[1px] bg-border"}),f.jsx(Fl,{className:"whitespace-nowrap text-[11px] tracking-widest text-muted-foreground/60 uppercase flex-shrink-0",children:e}),f.jsx("div",{className:"w-full h-[1px] bg-border"})]})}function b0({children:e,expandedContent:t,defaultExpanded:n=!1}){const[r,i]=v.useState(n);return f.jsxs("div",{className:"flex flex-col w-full",children:[f.jsxs("button",{onClick:()=>i(!r),className:`group/expandable-row cursor-pointer grid grid-cols-[auto_1fr] items-center gap-1 text-sm ${r?"":"hover:opacity-60 transition-opacity"}`,children:[f.jsx("div",{className:"grid grid-cols-[auto_1fr] items-center gap-1.5",children:e}),f.jsx(Po,{className:`h-4.5 w-4.5 text-muted-icon translate-y-[0.5px] transition-all duration-200 opacity-0 group-hover/expandable-row:opacity-100 ${r?"rotate-90 opacity-100":""}`})]}),r&&t]})}function cD({label:e,children:t,copyText:n}){const[r,i]=v.useState(!1),s=n??oy(t),o=v.useCallback(async()=>{await navigator.clipboard.writeText(s),i(!0),setTimeout(()=>i(!1),2e3)},[s]);return f.jsxs("div",{children:[f.jsx("span",{className:"font-medium text-muted-foreground",children:e}),f.jsxs("div",{className:"relative group/codeblock",children:[f.jsx("pre",{className:"my-1 text-xs font-mono whitespace-no-wrap break-all bg-muted border border-border rounded-lg p-2 max-h-64 overflow-auto w-full",children:t}),f.jsx(Ue,{variant:"ghost",size:"icon","aria-label":r?"Copied":"Copy code",className:he("absolute top-[4px] right-[4px] z-10 h-11 w-11 md:h-6.5 md:w-6.5 rounded-sm text-muted-foreground opacity-100 md:opacity-0 md:group-hover/codeblock:opacity-100 transition-opacity [@media(hover:none)]:!opacity-100",!r&&"hover:text-foreground",r&&"hover:!bg-transparent hover:!border-transparent"),onClick:o,children:r?f.jsx(_i,{className:"h-3.5 w-3.5 text-success"}):f.jsx(Pl,{className:"h-4 w-4"})})]})]})}function $B({children:e,icon:t,className:n}){return f.jsxs("span",{className:he("inline-flex items-center gap-1 px-2 py-1 bg-muted border border-border rounded-full",n),children:[t&&f.jsx(t,{className:"h-3 w-3 text-muted-foreground"}),e]})}function y0({children:e,className:t}){return f.jsxs("div",{className:he("grid grid-cols-[auto_1fr] gap-2 min-w-0",t),children:[f.jsx("div",{className:" min-w-5 flex flex-col relative items-center justify-center",children:f.jsx("div",{className:"min-h-full w-[1px] bg-muted-foreground/20"})}),f.jsx("div",{className:"-ml-[1px] min-w-0 overflow-hidden",children:e})]})}function oy(e){if(typeof e=="string")return e;if(typeof e=="number")return String(e);if(Array.isArray(e))return e.map(oy).join("");if(e&&typeof e=="object"&&"props"in e){const t=e.props;return oy(t.children)}return""}function uD(e,t){return v.isValidElement(e)?v.cloneElement(e,{className:he(e.props.className,t)}):e}function vve({children:e,...t}){const[n,r]=v.useState(!1),i=oy(e),s=async()=>{await navigator.clipboard.writeText(i),r(!0),setTimeout(()=>r(!1),2e3)};return f.jsxs("div",{className:"relative overflow-x-auto max-w-full min-w-0 no-code-highlight group/pre",children:[f.jsx("pre",{className:"min-w-0 rounded-xl py-2.5 px-3.5 [.no-pre-highlight_&]:bg-background",...t,children:e}),f.jsx(Ue,{variant:"ghost",size:"icon","aria-label":n?"Copied":"Copy code",className:he("absolute top-[35px] -translate-y-[50%] -translate-x-[1px] rounded-md right-1.5 h-11 w-11 md:h-8 md:w-8 text-muted-foreground opacity-100 md:opacity-0 md:group-hover/pre:opacity-100 transition-opacity [@media(hover:none)]:!opacity-100",!n&&"hover:text-foreground",n&&"hover:!bg-transparent hover:!border-transparent"),onClick:s,children:n?f.jsx(_i,{className:"h-4 w-4 text-success"}):f.jsx(Pl,{className:"h-4 w-4"})})]})}const r2={h1:({children:e})=>f.jsx("h1",{className:"text-[20px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",children:e}),h2:({children:e})=>f.jsx("h2",{className:"text-[18px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",children:e}),h3:({children:e})=>f.jsx("h3",{className:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",children:e}),h4:({children:e})=>f.jsx("h4",{className:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",children:e}),h5:({children:e})=>f.jsx("h5",{className:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",children:e}),h6:({children:e})=>f.jsx("h6",{className:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",children:e}),pre:vve,code:({children:e,className:t,...n})=>t?f.jsx("code",{className:"block text-xs whitespace-pre",...n,children:e}):f.jsx("code",{className:"break-all px-1 bg-border/60 dark:[.no-pre-highlight_&]:bg-background dark:[.text-pretty_&]:bg-neutral [.no-code-highlight_&]:!bg-transparent py-0.5 rounded text-sm whitespace-wrap",...n,children:e}),table:({children:e,...t})=>f.jsx("div",{className:"border border-border rounded-xl overflow-x-auto",children:f.jsx("table",{className:"table-auto min-w-full divide-y divide-border bg-background",...t,children:e})}),tbody:({children:e,...t})=>f.jsx("tbody",{className:"divide-y divide-border",...t,children:e}),th:({children:e,...t})=>f.jsx("th",{className:"text-left text-xs uppercase text-muted-foreground tracking-wider p-2 pl-0 first:pl-3 bg-muted dark:bg-card [&_*]:font-semibold",...t,children:e}),td:({children:e,...t})=>f.jsx("td",{className:"text-left p-2 pl-0 first:pl-3 [&_*]:font-normal ",...t,children:e}),p:({children:e,...t})=>f.jsx("p",{className:"break-words mt-5 mb-3 first:mt-0 last:mb-0",...t,children:e}),blockquote:({children:e,...t})=>(()=>{const n=v.Children.toArray(e),r=n[0];r!==void 0&&(n[0]=uD(r,"mt-0"));const i=n.length-1,s=n[i];return s!==void 0&&(n[i]=uD(s,"mb-0")),f.jsx("blockquote",{className:"my-2 mt-5 mb-3 first:mt-0 last:mb-0 border-l-2 border-border/80 pl-2 text-muted-foreground",...t,children:n})})(),a:({children:e,...t})=>f.jsx("a",{className:"transition-all underline decoration-2 text-logo decoration-logo/50 hover:text-logo/70 dark:text-logo dark:decoration-logo/70 dark:hover:text-logo/60 dark:hover:decoration-logo/40 ",target:"_blank",rel:"noopener noreferrer",...t,children:e}),img:({src:e,...t})=>{const n=typeof e=="string"&&Sme(e)?qE(e):e;return f.jsx("img",{src:n,...t})}};function bve({children:e,href:t,onClick:n,overrideOpenLocalLink:r,...i}){const s=v.useContext(IB),o=r??s,l=v0(),c=_me(t);if(c&&l.localLinkMode==="text")return f.jsx("span",{className:"transition-all underline decoration-2 text-logo decoration-logo/50",children:e});if(c&&!bB(c.path)){const u=Y1(e).trim();return f.jsx(fve,{path:c.path,linkText:u||void 0})}return f.jsx("a",{className:"transition-all underline decoration-2 text-logo decoration-logo/50 hover:text-logo/70 dark:text-logo dark:decoration-logo/70 dark:hover:text-logo/60 dark:hover:decoration-logo/40 ",href:t,target:c?void 0:"_blank",rel:c?void 0:"noopener noreferrer",onClick:u=>{n==null||n(u),!(u.defaultPrevented||!c||o===sy)&&(u.preventDefault(),o({...c,clientX:u.clientX,clientY:u.clientY,trigger:"click"}))},onContextMenu:u=>{!c||o===sy||(u.preventDefault(),o({...c,clientX:u.clientX,clientY:u.clientY,trigger:"contextmenu"}))},...i,children:e})}function yve(e){return{...r2,a:t=>f.jsx(bve,{...t,overrideOpenLocalLink:e==null?void 0:e.onOpenLocalLink})}}const Sf=[vB],Cf=yve();function Y1(e){return e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(Y1).join(""):v.isValidElement(e)?Y1(e.props.children):""}({...r2});function i2({attachment:e,previewUrl:t,onClick:n,onRemove:r,className:i,size:s="transcript",uploadProgress:o,onCancelUpload:l}){const c=e.contentUrl||t,u=s==="composer",m=o!==void 0;return f.jsxs("div",{className:he("group relative flex flex-row items-end",i),children:[f.jsxs("button",{type:"button",onClick:n,className:he("group/image relative overflow-hidden rounded-xl border border-border/80 bg-background shadow-sm",u?"min-w-[80px]":"min-w-[200px]"),children:[c?f.jsx("img",{src:c,alt:e.displayName,className:he("rounded-xl object-contain bg-muted",u?"min-h-[50px] min-w-[80px] max-h-[120px] max-w-[200px]":"min-h-[100px] min-w-[200px] max-h-[300px] max-w-[300px]")}):f.jsx("div",{className:he("flex items-center justify-center rounded-xl bg-muted text-muted-foreground",u?"min-h-[64px] min-w-[80px]":"min-h-[160px] min-w-[200px]"),children:f.jsx(C5,{className:he(u?"size-6":"size-8")})}),f.jsxs("div",{className:he("pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/75 via-black/30 to-transparent text-left opacity-0 transition-opacity duration-200 group-hover/image:opacity-100",u?"px-2.5 pb-2 pt-6":"px-4 pb-3 pt-10"),children:[f.jsx("div",{className:he("truncate font-medium text-white",u?"text-xs":"text-sm"),children:e.displayName}),f.jsxs("div",{className:"truncate text-xs text-white/80",children:[e.mimeType," · ",kf(e.size)]})]})]}),m?f.jsx(I8,{progress:o??null,onCancel:l,size:u?"sm":"md",cancelLabel:`Cancel upload of ${e.displayName}`}):null,r&&!m?f.jsx(HB,{displayName:e.displayName,onRemove:r}):null]})}function Do({attachment:e,onClick:t,onRemove:n,className:r,uploadProgress:i,onCancelUpload:s,href:o,download:l,meta:c,ariaLabel:u,disabledReason:m}){const h=e.kind==="mention"?"text":xf(e),g=wve(h),b=e.kind==="mention",x=b?xve(e.displayName):e.displayName,_=b?_ve(e.displayName):"",w=i!==void 0,C=!!m,E=he("flex w-[200px] items-center gap-2 rounded-xl border border-border bg-background p-1 pr-3 text-left transition-colors",C?"cursor-not-allowed opacity-60":"hover:bg-accent/50"),k=b?f.jsx("div",{className:"max-w-[150px] truncate text-[11px] text-muted-foreground",children:_?`@${_}`:"@mention"}):m?f.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:m}):c!==void 0?f.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:c}):f.jsxs("div",{className:"truncate text-[11px] text-muted-foreground",children:[e.mimeType," · ",kf(e.size)]}),N=f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"flex min-h-10 min-w-10 items-center justify-center rounded-lg border border-border bg-muted text-muted-foreground",children:f.jsx(BB,{icon:g,className:"size-5"})}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:he("max-w-[150px] truncate text-[13px] font-medium",C?"text-muted-foreground line-through":"text-foreground"),children:x}),k]})]});return f.jsxs("div",{className:he("group relative",r),children:[o&&!C?f.jsx("a",{href:o,download:l,rel:"noopener","aria-label":u,className:E,children:N}):f.jsx("button",{type:"button",onClick:C?void 0:t,title:b?e.displayName:void 0,"aria-label":u,"aria-disabled":C||void 0,disabled:C,className:E,children:N}),w?f.jsx(I8,{progress:i??null,onCancel:s,size:"sm",cancelLabel:`Cancel upload of ${e.displayName}`}):null,n&&!w?f.jsx(HB,{displayName:e.displayName,onRemove:n}):null]})}function xve(e){const t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function _ve(e){const t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function HB({displayName:e,onRemove:t}){return f.jsx("button",{type:"button",className:"absolute right-2 top-2 rounded-full bg-background/90 p-1 text-muted-foreground shadow-sm transition hover:bg-muted hover:text-foreground",onClick:n=>{n.preventDefault(),n.stopPropagation(),t()},"aria-label":`Remove ${e}`,children:f.jsx(io,{className:"h-3.5 w-3.5"})})}function wve(e){switch(e){case"image":return C5;case"pdf":return xG;case"markdown":return NG;case"json":return eW;case"table":return dW;case"code":return nW;case"text":return sk;case"archive":return ZV;case"audio":return iW;case"video":return mW;default:return k5}}function kf(e){return e<1024?`${e} B`:e<1024*1024?`${Math.max(1,Math.round(e/1024))} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}const xp=v.forwardRef(({className:e,...t},n)=>f.jsx("textarea",{"data-gramm":"false","data-gramm_editor":"false","data-enable-grammarly":"false","data-1p-ignore":!0,autoComplete:"off",className:he("flex w-full rounded-lg border border-border bg-background px-2.5 py-2 text-sm placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));xp.displayName="Textarea";const Cv={};function dD(e){return!e.isCollapsed&&!e.hasPreviewAttachment&&e.patch===void 0&&e.patchError===void 0&&!e.isPatchLoading}function Sve(e,t){return!e||!t.mimeType||typeof t.size!="number"||t.changeType==="deleted"||!t.mimeType.startsWith("image/")&&t.mimeType!=="application/pdf"?null:{id:`diff:${t.path}`,kind:t.mimeType.startsWith("image/")?"image":"file",displayName:t.path.split("/").pop()??t.path,absolutePath:t.path,relativePath:t.path,contentUrl:`/api/projects/${e}/files/${encodeURIComponent(t.path)}/content`,mimeType:t.mimeType,size:t.size}}function UB(e){return e.isUntracked}function Cve(e){return UB(e)?e.path.includes("/"):!1}function Zw(e){return f.jsxs(Qr,{delayDuration:0,children:[f.jsx(Zr,{asChild:!0,children:f.jsx("button",{type:"button","aria-label":e.label,title:e.label,onClick:e.onClick,className:he("flex h-11 w-11 md:h-7 md:w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",e.active&&"bg-accent text-foreground"),children:e.children})}),f.jsx(Hr,{children:e.label})]})}function VB({checked:e,mixed:t=!1,label:n,className:r,onClick:i}){return f.jsx("button",{type:"button","aria-label":n??(e?"Exclude file from commit":"Include file in commit"),"aria-checked":t?"mixed":e,"aria-pressed":t?"mixed":e,onClick:s=>{s.stopPropagation(),i()},className:he("flex size-4.5 shrink-0 items-center justify-center rounded border transition-colors",e||t?"border-foreground bg-foreground text-background":"border-border bg-background text-transparent",r),children:t?f.jsx(eG,{className:"h-3 w-3",strokeWidth:3}):e?f.jsx(_i,{className:"h-3 w-3",strokeWidth:3}):null})}function s2(e){const t=Date.parse(e);if(!Number.isFinite(t))return"";const n=Date.now()-t,r=6e4,i=60*r,s=24*i,o=7*s,l=30*s,c=365*s;return n<r?"just now":n<i?`${Math.round(n/r)}m ago`:n<s?`${Math.round(n/i)}hr ago`:n<o?`${Math.round(n/s)}d ago`:n<l?`${Math.round(n/o)}wk ago`:n<c?`${Math.round(n/l)}mo ago`:`${Math.round(n/c)}yr ago`}function kve(e){return e?`Last fetched ${s2(e)}`:"No local fetch recorded"}function Eve({entry:e,isPendingPush:t=!1}){const n=s2(e.authoredAt),r=!!e.githubUrl;return f.jsxs("button",{type:"button",disabled:!r,onClick:()=>{!e.githubUrl||typeof window>"u"||window.open(e.githubUrl,"_blank","noopener,noreferrer")},className:he("flex w-full items-start gap-3 rounded-lg border border-border bg-background pl-3 pr-2 py-2 text-left transition-colors",r?"hover:bg-accent":"cursor-default opacity-60"),children:[f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:e.summary}),e.description?f.jsx("div",{className:"mt-1 line-clamp-2 whitespace-pre-wrap text-xs text-muted-foreground",children:e.description}):null,f.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-xs text-muted-foreground",children:[e.authorName?f.jsx("span",{className:"truncate",children:e.authorName}):null,e.authorName&&n?f.jsx("span",{"aria-hidden":"true",children:"•"}):null,n?f.jsx("span",{children:n}):null]})]}),e.tags.length>0?f.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-1",children:[e.tags.map(i=>f.jsx("span",{className:"inline-flex items-center rounded-full bg-muted border border-border px-2 py-0.5 text-[11px]",children:i},i)),t?f.jsx("span",{className:"inline-flex items-center rounded-full bg-muted border border-border px-2 py-0.5 text-[11px]",children:f.jsx(um,{className:"size-3"})}):null]}):t?f.jsx("div",{className:"flex shrink-0 flex-wrap justify-end gap-1",children:f.jsx("span",{className:"inline-flex items-center rounded-full bg-muted border border-border px-2 py-0.5 text-[11px]",children:f.jsx(um,{className:"size-3"})})}):null]})}function fD(e){switch(e.kind){case"local":return 0;case"pull_request":return 1;case"remote":default:return 2}}function Tve(e){const t=new Map;for(const n of e){const r=t.get(n.name);(!r||fD(n)<fD(r))&&t.set(n.name,n)}return t}function Nve(e,t){const n=Tve([...e.local,...e.pullRequests,...e.remote]);t&&n.delete(t);const r=new Set,i=e.defaultBranchName?n.get(e.defaultBranchName):void 0;i&&r.add(i.name);const s=e.recent.map(l=>n.get(l.name)??l).filter(l=>!!l&&!r.has(l.name));for(const l of s)r.add(l.name);const o=[...n.values()].filter(l=>!r.has(l.name)).sort((l,c)=>l.displayName.localeCompare(c.displayName));return{defaultBranch:i,recent:s,other:o}}function Rve({open:e,onOpenChange:t,onGetGitHubPublishInfo:n,onCheckGitHubRepoAvailability:r,onPublish:i}){const[s,o]=v.useState(null),[l,c]=v.useState(!1),[u,m]=v.useState(""),[h,g]=v.useState(""),[b,x]=v.useState("private"),[_,w]=v.useState(""),[C,E]=v.useState(null),[k,N]=v.useState(!1),[R,A]=v.useState(!1);v.useEffect(()=>{if(!e)return;let F=!1;return c(!0),E(null),n().then(D=>{F||(o(D),m(D.owners[0]??D.activeAccountLogin??""),g(D.suggestedRepoName),x("private"),w(""))}).finally(()=>{F||c(!1)}),()=>{F=!0}},[n,e]),v.useEffect(()=>{if(!e||!(s!=null&&s.ghInstalled)||!s.authenticated)return;const F=u.trim(),D=h.trim();if(!F||!D){E(null);return}let O=!1;N(!0);const z=window.setTimeout(()=>{r({owner:F,name:D}).then(P=>{O||E(P)}).finally(()=>{O||N(!1)})},250);return()=>{O=!0,window.clearTimeout(z)}},[s==null?void 0:s.authenticated,s==null?void 0:s.ghInstalled,h,r,e,u]);async function M(){if(!(!u.trim()||!h.trim())){A(!0);try{const F=await i({owner:u.trim(),name:h.trim(),visibility:b,description:_});F!=null&&F.ok&&t(!1)}finally{A(!1)}}}const L=!!(s!=null&&s.ghInstalled&&s.authenticated&&u.trim()&&h.trim()&&(C!=null&&C.available)&&!k&&!R);return f.jsx(As,{open:e,onOpenChange:t,children:f.jsxs(es,{size:"sm",className:"max-w-[min(92vw,475px)]",children:[f.jsxs(Oo,{className:"space-y-2 px-4 pb-4 pt-4",children:[f.jsxs("div",{className:"space-y-1",children:[f.jsx(Ms,{children:"Push to GitHub"}),f.jsx(af,{children:"Create a GitHub repository from this local project using GitHub CLI."})]}),l?f.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[f.jsx(bn,{className:"size-4 animate-spin"}),f.jsx("span",{children:"Checking GitHub CLI…"})]}):s&&!s.ghInstalled?f.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[f.jsx("p",{children:"GitHub CLI is not installed."}),f.jsx("div",{className:"rounded-lg border border-border px-3 py-2 font-mono text-xs text-foreground",children:"brew install gh"}),f.jsx("p",{children:"Then run:"}),f.jsx("div",{className:"rounded-lg border border-border px-3 py-2 font-mono text-xs text-foreground",children:"gh auth login"})]}):s&&!s.authenticated?f.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[f.jsx("p",{children:"GitHub CLI is installed but not signed in."}),f.jsx("div",{className:"rounded-lg border border-border px-3 py-2 font-mono text-xs text-foreground",children:"gh auth login"})]}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"space-y-2",children:f.jsxs(pa,{value:u,onValueChange:m,children:[f.jsx(Eo,{className:"pl-[11px] [&>span]:flex [&>span]:items-center [&>span]:gap-2",children:f.jsx(El,{placeholder:"Select owner"})}),f.jsx(To,{children:((s==null?void 0:s.owners)??[]).map(F=>f.jsx(ws,{value:F,children:f.jsxs("span",{className:"flex items-center gap-2",children:[F===(s==null?void 0:s.activeAccountLogin)?f.jsx(Ey,{className:"size-4 text-muted-foreground"}):f.jsx(bV,{className:"size-4 text-muted-foreground"}),f.jsx("span",{className:"pl-[1px]",children:F})]})},F))})]})}),f.jsx("div",{className:"space-y-2",children:f.jsxs("div",{className:"relative",children:[f.jsx($n,{value:h,onChange:F=>g(F.target.value),placeholder:"my-repo",className:"pl-9 pr-10"}),f.jsx(fG,{className:"pointer-events-none absolute inset-y-0 left-3 my-auto size-4 text-muted-foreground"}),k?f.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-3 flex items-center text-muted-foreground",children:f.jsx(bn,{className:"size-4 animate-spin"})}):C?f.jsx("div",{className:"absolute inset-y-0 right-2 flex items-center",children:f.jsxs(Qr,{delayDuration:0,children:[f.jsx(Zr,{asChild:!0,children:f.jsx("button",{type:"button",tabIndex:-1,"aria-label":C.message,className:he("flex size-6 items-center justify-center rounded-md",C.available?"text-success":"text-destructive"),children:C.available?f.jsx(_i,{className:"size-4"}):f.jsx(wb,{className:"size-4"})})}),f.jsx(Hr,{children:C.message})]})}):null]})}),f.jsx("div",{className:"space-y-2",children:f.jsxs("div",{className:"relative",children:[f.jsx(sk,{className:"pointer-events-none absolute left-3 top-3 size-4 text-muted-foreground"}),f.jsx(xp,{value:_,onChange:F=>w(F.target.value),rows:3,placeholder:"Optional description",className:"pl-9 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"})]})}),f.jsx("div",{className:"space-y-2",children:f.jsxs(pa,{value:b,onValueChange:F=>x(F),children:[f.jsx(Eo,{className:"pl-[11px] [&>span]:flex [&>span]:items-center [&>span]:gap-2",children:f.jsx(El,{placeholder:"Select visibility"})}),f.jsxs(To,{children:[f.jsx(ws,{value:"private",children:f.jsxs("span",{className:"flex items-center gap-2",children:[f.jsx(WW,{className:"size-4 text-muted-foreground"}),f.jsx("span",{className:"pl-[1px]",children:"Private"})]})}),f.jsx(ws,{value:"public",children:f.jsxs("span",{className:"flex items-center gap-2",children:[f.jsx(LW,{className:"size-4 text-muted-foreground"}),f.jsx("span",{className:"pl-[1px]",children:"Public"})]})})]})]})})]})]}),f.jsxs(Sa,{children:[f.jsx(Ue,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Cancel"}),f.jsx(Ue,{size:"sm",disabled:!L,onClick:()=>void M(),children:R?f.jsxs(f.Fragment,{children:[f.jsx(bn,{className:"mr-1.5 size-3.5 animate-spin"}),"Publishing…"]}):"Push to GitHub"})]})]})})}function WB({value:e,onChange:t,placeholder:n,disabled:r,trailingAction:i}){return f.jsxs("div",{className:"relative",children:[f.jsx(Gh,{className:"pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),f.jsx($n,{value:e,onChange:s=>t(s.target.value),placeholder:n,className:he("h-9 pl-7 text-sm",i?"pr-14":void 0),disabled:r}),i?f.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2",children:i}):null]})}function Dc({title:e,entries:t,emptyLabel:n,selectedName:r,disabled:i,stickyTitle:s=!1,onSelect:o}){return t.length===0&&!n?null:f.jsxs("div",{className:"space-y-1",children:[f.jsx("div",{className:he("px-1 py-1 text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground",s&&"sticky top-0 z-10 bg-background"),children:e}),t.length===0?f.jsx("div",{className:"px-1 py-1 text-xs text-muted-foreground",children:n}):t.map(l=>{const c=r===l.name;return f.jsxs("button",{type:"button",disabled:i,onClick:()=>o(l),className:he("flex w-full items-start gap-2 rounded-lg px-2 py-2 text-left transition-colors disabled:opacity-60",c?"bg-accent text-foreground":"hover:bg-accent"),children:[l.kind==="pull_request"?f.jsx(N5,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):f.jsx(Ac,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsxs("div",{className:"flex w-full items-center gap-3",children:[f.jsx("div",{className:"min-w-0 flex-1 overflow-hidden whitespace-nowrap text-sm text-foreground",children:l.displayName}),l.updatedAt?f.jsx("div",{className:"ml-auto shrink-0 text-right text-[11px] text-muted-foreground",children:s2(l.updatedAt)}):null]}),l.kind==="pull_request"&&l.description||l.headLabel?f.jsx("div",{className:"truncate text-xs text-muted-foreground",children:l.kind==="pull_request"?l.description??l.headLabel??l.name:l.headLabel??void 0}):null]})]},l.id)})]})}function Ave({open:e,onOpenChange:t,branchList:n,currentBranchName:r,onPreviewMergeBranch:i,onMergeBranch:s}){const[o,l]=v.useState(""),[c,u]=v.useState(null),[m,h]=v.useState(null),[g,b]=v.useState(null),[x,_]=v.useState(!1),[w,C]=v.useState(!1),E=v.useMemo(()=>n?Nve(n,r):{defaultBranch:void 0,recent:[],other:[]},[n,r]),k=o.trim().toLowerCase(),N=v.useCallback(O=>k?[O.displayName,O.name,O.description,O.prTitle,O.headLabel].some(z=>z==null?void 0:z.toLowerCase().includes(k)):!0,[k]),R=E.defaultBranch&&N(E.defaultBranch)?E.defaultBranch:void 0,A=E.recent.filter(N),M=E.other.filter(N),L=v.useMemo(()=>c?[E.defaultBranch,...E.recent,...E.other].find(O=>O!==void 0&&O.name===c)??null:null,[E.defaultBranch,E.other,E.recent,c]);v.useEffect(()=>{e||(l(""),u(null),h(null),b(null),_(!1),C(!1))},[e]),v.useEffect(()=>{if(!e||!L){h(null),b(null),_(!1);return}let O=!1;return h(null),b(null),_(!0),i(L).then(z=>{O||h(z)}).catch(z=>{O||b(z instanceof Error?z.message:String(z))}).finally(()=>{O||_(!1)}),()=>{O=!0}},[i,e,L]);const F=!L||!m||x||w||m.status!=="mergeable";async function D(){if(!(!L||F)){C(!0);try{const O=await s(L);O!=null&&O.ok&&t(!1)}finally{C(!1)}}}return f.jsx(As,{open:e,onOpenChange:t,children:f.jsxs(es,{size:"sm",className:"max-w-[min(92vw,475px)]",children:[f.jsxs(Oo,{className:"flex min-h-0 flex-col gap-3 px-4 pb-4 pt-4",children:[f.jsxs("div",{className:"space-y-1",children:[f.jsxs(Ms,{children:["Merge into ",r??"current branch"]}),f.jsx(af,{children:"Choose a branch to continue."})]}),f.jsx(WB,{value:o,onChange:l,placeholder:"Search branches"}),f.jsxs("div",{className:"max-h-[375px] space-y-3 overflow-y-auto pr-1",children:[f.jsx(Dc,{title:"Default Branch",entries:R?[R]:[],emptyLabel:"No default branch available.",selectedName:c,onSelect:O=>u(O.name)}),f.jsx(Dc,{title:"Recent Branches",entries:A,emptyLabel:"No recent branches.",selectedName:c,onSelect:O=>u(O.name)}),f.jsx(Dc,{title:"Other Branches",entries:M,emptyLabel:"No other branches match this search.",selectedName:c,onSelect:O=>u(O.name)})]}),f.jsx("div",{className:"px-2",children:L?x?f.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[f.jsx(bn,{className:"size-3.5 animate-spin"}),f.jsx("span",{children:"Checking merge preview…"})]}):g?f.jsx("div",{className:"text-sm text-destructive",children:g}):m?f.jsxs("div",{className:"flex items-start gap-2",children:[m.status==="up_to_date"?f.jsx(_i,{className:"mt-1 size-3.5 shrink-0 text-success"}):m.status==="conflicts"?f.jsx(wb,{className:"mt-1 size-3.5 shrink-0 text-warning"}):m.status==="mergeable"?f.jsx(T5,{className:"mt-1 size-3.5 shrink-0 text-muted-foreground"}):f.jsx(wb,{className:"mt-1 size-3.5 shrink-0 text-destructive"}),f.jsxs("div",{className:"min-w-0 space-y-1",children:[f.jsx("div",{className:"text-sm font-medium text-foreground",children:m.message}),m.detail?f.jsx("div",{className:"line-clamp-2 whitespace-pre-wrap text-xs text-muted-foreground",children:m.detail}):null]})]}):f.jsx("div",{className:"text-sm text-muted-foreground",children:"Preview unavailable."}):f.jsx("div",{className:"text-sm text-muted-foreground",children:"Select a branch to preview the merge."})})]}),f.jsx(Sa,{children:f.jsxs("div",{className:"flex min-w-0 w-full items-center justify-end gap-2",children:[f.jsx(Ue,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Cancel"}),f.jsx(Ue,{className:"max-w-full min-w-0",size:"sm",disabled:F,onClick:()=>void D(),children:w?f.jsxs(f.Fragment,{children:[f.jsx(bn,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}),"Merging…"]}):f.jsx("span",{className:"block max-w-full truncate",children:"Merge"})})]})})]})})}function Mve({currentBranchName:e,onListBranches:t,onPreviewMergeBranch:n,onMergeBranch:r,onCheckoutBranch:i,onCreateBranch:s}){const[o,l]=v.useState(!1),[c,u]=v.useState(!1),[m,h]=v.useState(!1),[g,b]=v.useState(!1),[x,_]=v.useState(""),[w,C]=v.useState("branches"),[E,k]=v.useState(null),[N,R]=v.useState(null);v.useEffect(()=>{o&&(h(!0),R(null),t().then(G=>k(G)).catch(G=>{R(G instanceof Error?G.message:String(G))}).finally(()=>{h(!1)}))},[t,o]);const A=x.trim().toLowerCase(),M=G=>G.filter(Q=>A?[Q.displayName,Q.name,Q.description,Q.prTitle,Q.headLabel].some(I=>I==null?void 0:I.toLowerCase().includes(A)):!0),L=(E==null?void 0:E.currentBranchName)??e,F=new Set(((E==null?void 0:E.pullRequests)??[]).map(G=>G.headRefName??G.name)),D=M((E==null?void 0:E.recent)??[]).filter(G=>G.name!==L),O=M((E==null?void 0:E.local)??[]).filter(G=>G.name!==L),z=M((E==null?void 0:E.remote)??[]).filter(G=>G.name!==L&&!F.has(G.name)),P=M((E==null?void 0:E.pullRequests)??[]).filter(G=>G.name!==L),$=(E==null?void 0:E.pullRequests.length)??0;async function H(G){b(!0);try{await i(G),l(!1),_(""),C("branches")}finally{b(!1)}}async function B(){b(!0);try{await s(),l(!1),_(""),C("branches")}finally{b(!1)}}function V(){l(!1),u(!0)}return f.jsxs(Kk,{open:o,onOpenChange:l,children:[f.jsx(Yk,{asChild:!0,children:f.jsxs("button",{type:"button",className:"flex min-w-0 max-w-full items-center gap-1 rounded-md px-1.5 py-1 text-sm transition-colors hover:bg-accent hover:text-foreground","aria-label":"Open branch switcher",children:[f.jsx(Ac,{className:"h-3.5 w-3.5 shrink-0"}),f.jsx("span",{className:"truncate",children:e??"Detached HEAD"}),f.jsx(nf,{className:"h-3.5 w-3.5 shrink-0"})]})}),f.jsx(Wy,{align:"start",className:"w-[320px] p-2",children:f.jsxs("div",{className:"space-y-2",children:[f.jsx(WB,{value:x,onChange:_,placeholder:w==="pull_requests"?"Search pull requests":"Search branches",disabled:m||g,trailingAction:f.jsx(Ue,{variant:"ghost",size:"sm",onClick:()=>void B(),disabled:m||g,className:"h-7 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:"+ New"})}),f.jsx(Di,{value:w,onValueChange:G=>C(G),size:"sm",className:"w-full",optionClassName:"flex-1 justify-center",options:[{value:"branches",label:"Branches"},{value:"pull_requests",label:`Open PRs ${$}`}]}),f.jsx("div",{className:"max-h-[420px] overflow-y-auto pr-1.5 -mr-[8px]",children:m?f.jsxs("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[f.jsx(bn,{className:"h-4 w-4 animate-spin"}),f.jsx("span",{children:"Loading branches…"})]}):N?f.jsx("div",{className:"rounded-lg border border-border px-3 py-2 text-sm text-muted-foreground",children:N}):w==="pull_requests"?f.jsx(Dc,{title:"Open PRs",entries:P,emptyLabel:(E==null?void 0:E.pullRequestsStatus)==="error"?E.pullRequestsError??"Could not load pull requests.":(E==null?void 0:E.pullRequestsStatus)==="unavailable"?"Pull requests unavailable for this repository.":"No open pull requests.",disabled:g,stickyTitle:!0,onSelect:G=>{H(G)}}):f.jsxs("div",{className:"space-y-3",children:[f.jsx(Dc,{title:"Recent",entries:D,emptyLabel:"No recent branches.",disabled:g,stickyTitle:!0,onSelect:G=>{H(G)}}),f.jsx(Dc,{title:"Local",entries:O,emptyLabel:"No local branches.",disabled:g,stickyTitle:!0,onSelect:G=>{H(G)}}),f.jsx(Dc,{title:"Remote",entries:z,emptyLabel:"No remote branches.",disabled:g,stickyTitle:!0,onSelect:G=>{H(G)}})]})}),L?f.jsx(Ue,{variant:"default",size:"sm",disabled:m||g||!!N,onClick:V,className:"h-9 w-full justify-center rounded-lg px-3 text-sm",children:f.jsxs("span",{className:"block max-w-full truncate",children:[f.jsx(TW,{className:"mr-1.5 inline h-3.5 w-3.5 shrink-0"}),"Merge branch into ",L,"..."]})}):null]})}),f.jsx(Ave,{open:c,onOpenChange:u,branchList:E,currentBranchName:L,onPreviewMergeBranch:n,onMergeBranch:r})]})}function Lve({file:e,rootRef:t,projectId:n,isCollapsed:r,isChecked:i,editorLabel:s,diffRenderMode:o,wrapLines:l,onToggleCollapsed:c,onToggleChecked:u,fileActions:m,patch:h,patchError:g,isPatchLoading:b,onLoadPatch:x}){const _=UB(e),w=Cve(e),[C,E]=v.useState(null),k=v.useRef(null),N=v.useRef(null),{sentinelRef:R,isStuck:A}=vue({rootRef:t,disabled:r}),M=v.useMemo(()=>Sve(n,e),[e,n]),L=M!==null,F=dD({isCollapsed:r,hasPreviewAttachment:L,patch:h,patchError:g,isPatchLoading:b});v.useEffect(()=>{if(!F)return;const P=`${e.path}\0${e.patchDigest}`;N.current!==P&&(N.current=P,x(e.path).catch(()=>{}))},[e.patchDigest,e.path,x,F]);function D(P){if(yf(P).openInNewTab){typeof window<"u"&&window.open(new URL(P.contentUrl,window.location.origin).toString(),"_blank","noopener,noreferrer");return}E(P.id)}function O(P){var H;P.preventDefault(),P.stopPropagation();const $=P.currentTarget.getBoundingClientRect();(H=k.current)==null||H.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:$.left+$.width/2,clientY:$.bottom,view:window}))}function z(){if(!r){c();return}if(L||h!==void 0){c();return}if(b)return;if(!(g!==void 0||dD({isCollapsed:!1,hasPreviewAttachment:L,patch:h,patchError:g,isPatchLoading:b}))){c();return}x(e.path).then(()=>{c()}).catch(()=>{})}return f.jsxs(su,{children:[f.jsx(ou,{asChild:!0,children:f.jsxs("div",{ref:k,className:"relative rounded-lg border border-border bg-background",children:[r?null:f.jsx("div",{ref:R,className:"pointer-events-none absolute inset-x-0 top-0 h-px","aria-hidden":"true"}),f.jsxs("div",{role:"button",tabIndex:0,onClick:z,onKeyDown:P=>{P.key!=="Enter"&&P.key!==" "||(P.preventDefault(),z())},className:he("group/header sticky top-0 z-20 flex cursor-pointer items-center justify-between gap-3 bg-background pl-[7px] pr-2.5 py-1.5 text-[13px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",!r&&!A&&"rounded-t-[calc(theme(borderRadius.lg)-1px)]",r&&"rounded-[calc(theme(borderRadius.lg)-1px)]",!r&&"border-b border-border/50"),children:[f.jsxs("div",{className:"flex min-w-0 items-center",children:[f.jsx(VB,{checked:i,onClick:u}),f.jsx("div",{className:"min-w-0 truncate select-none ml-2 mr-1",children:e.path})]}),f.jsxs("div",{className:"flex shrink-0 items-center gap-2 select-none",children:[f.jsxs("span",{className:"whitespace-nowrap text-xs font-mono",children:[e.additions>0?f.jsxs("span",{className:"text-success",children:["+",e.additions]}):null,e.deletions>0?f.jsxs("span",{className:e.additions>0?"ml-2 text-destructive":"text-destructive",children:["-",e.deletions]}):null]}),f.jsx("button",{type:"button","aria-label":`Open actions for ${e.path}`,onClick:O,className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:f.jsx(dm,{className:"h-3.5 w-3.5 shrink-0"})}),b&&r&&!M?f.jsx(bn,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):r?f.jsx(nf,{className:"h-3.5 w-3.5 shrink-0"}):f.jsx(S5,{className:"h-3.5 w-3.5 shrink-0"})]})]}),r?null:f.jsx("div",{className:"kanna-diff-patch overflow-hidden rounded-b-[calc(theme(borderRadius.lg)-1px)] pb-[1px]",children:M?f.jsx("div",{className:"flex justify-center p-3",children:M.kind==="image"?f.jsx(i2,{attachment:M,onClick:()=>D(M)}):f.jsx(Do,{attachment:M,onClick:()=>D(M)})}):b?f.jsxs("div",{className:"flex items-center justify-center px-3 py-8 text-sm text-muted-foreground",children:[f.jsx(bn,{className:"mr-2 h-4 w-4 animate-spin"}),"Loading diff..."]}):g?f.jsx("div",{className:"px-3 py-4 text-sm text-destructive",children:g}):h!==void 0?f.jsx(pue,{patch:h,options:{diffStyle:o,disableFileHeader:!0,disableBackground:!1,overflow:l?"wrap":"scroll",lineDiffType:"word",diffIndicators:"classic"}}):f.jsx("div",{className:"px-3 py-4 text-sm text-muted-foreground",children:"Diff unavailable."})}),f.jsx(wf,{source:M&&C===M.id?yp(M,"user_attachment"):null,open:M!==null&&C===M.id,onOpenChange:P=>!P&&E(null)})]},e.path)}),f.jsxs(Vl,{children:[f.jsxs(jn,{onSelect:P=>{P.stopPropagation(),m.onOpenFile(e.path)},children:[f.jsx(nk,{className:"h-3.5 w-3.5"}),f.jsxs("span",{className:"text-xs font-medium",children:["Open in ",s]})]}),f.jsxs(jn,{onSelect:P=>{P.stopPropagation(),m.onOpenInFinder(e.path)},children:[f.jsx(Cy,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Open in Finder"})]}),f.jsxs(jn,{onSelect:P=>{P.stopPropagation(),m.onDiscardFile(e.path)},className:"text-destructive hover:bg-destructive/10 focus:bg-destructive/10",children:[f.jsx(rf,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Discard Changes"})]}),f.jsxs(jn,{disabled:!_,onSelect:P=>{P.stopPropagation(),_&&m.onIgnoreFile(e.path)},children:[f.jsx(BA,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Ignore File"})]}),f.jsxs(jn,{disabled:!w,onSelect:P=>{P.stopPropagation(),w&&m.onIgnoreFolder(e.path)},children:[f.jsx(BA,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Ignore folder..."})]}),f.jsx(a4,{}),f.jsxs(jn,{onSelect:P=>{P.stopPropagation(),m.onCopyFilePath(e.path)},children:[f.jsx(Pl,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Copy File Path"})]}),f.jsxs(jn,{onSelect:P=>{P.stopPropagation(),m.onCopyRelativePath(e.path)},children:[f.jsx(Pl,{className:"h-3.5 w-3.5"}),f.jsx("span",{className:"text-xs font-medium",children:"Copy Relative Path"})]})]})]})}function jve({projectId:e,diffs:t,editorLabel:n,diffRenderMode:r,wrapLines:i,onOpenFile:s,onOpenInFinder:o,onDiscardFile:l,onIgnoreFile:c,onIgnoreFolder:u,onCopyFilePath:m,onCopyRelativePath:h,onListBranches:g,onPreviewMergeBranch:b,onMergeBranch:x,onCheckoutBranch:_,onCreateBranch:w,onGenerateCommitMessage:C,onInitializeGit:E,onGetGitHubPublishInfo:k,onCheckGitHubRepoAvailability:N,onSetupGitHub:R,onCommit:A,onSyncWithRemote:M,onLoadPatch:L,onDiffRenderModeChange:F,onWrapLinesChange:D}){var Qe;const O=v.useMemo(()=>({onOpenFile:s,onOpenInFinder:o,onDiscardFile:l,onIgnoreFile:c,onIgnoreFolder:u,onCopyFilePath:m,onCopyRelativePath:h}),[s,o,l,c,u,m,h]),z=t.files.length>0,[P,$]=v.useState(!1),[H,B]=v.useState(null),[V,G]=v.useState(!1),[Q,I]=v.useState(!1),[W,te]=v.useState({}),[U,fe]=v.useState({}),[ae,ee]=v.useState({}),ne=v.useRef(null),se=v.useRef({}),le=v.useMemo(()=>t.files.map(_e=>_e.path),[t.files]),ue=v.useMemo(()=>le.join("\0"),[le]),Ae=ji(_e=>{var Fe;return e?((Fe=_e.projectUi[e])==null?void 0:Fe.viewMode)??(z?"changes":"history"):z?"changes":"history"}),ce=ji(_e=>{var Fe;return e?((Fe=_e.projectUi[e])==null?void 0:Fe.collapsedPaths)??Cv:Cv}),De=ji(_e=>{var Fe;return e?((Fe=_e.projectUi[e])==null?void 0:Fe.summary)??"":""}),Ke=ji(_e=>{var Fe;return e?((Fe=_e.projectUi[e])==null?void 0:Fe.description)??"":""}),ht=ji(_e=>_e.reconcileCollapsedPaths),Tt=ji(_e=>_e.toggleCollapsedPath),qt=ji(_e=>_e.setViewMode),Se=ji(_e=>_e.setCommitDraft),Rt=ji(_e=>_e.clearCommitDraft),Et=pv(_e=>e?_e.checkedPathsByProjectId[e]??Cv:Cv),dt=pv(_e=>_e.reconcileProject),Bt=pv(_e=>_e.setChecked),Ut=pv(_e=>_e.setAllChecked),pt=v.useRef(z);v.useEffect(()=>{e&&ht(e,le)},[le,ue,e,ht]),v.useEffect(()=>{const _e=Object.fromEntries(t.files.map(qe=>[qe.path,qe.patchDigest])),Fe=qe=>se.current[qe]===_e[qe];te(qe=>Object.fromEntries(Object.entries(qe).filter(([Ve])=>le.includes(Ve)&&Fe(Ve)))),fe(qe=>Object.fromEntries(Object.entries(qe).filter(([Ve])=>le.includes(Ve)&&Fe(Ve)))),ee(qe=>Object.fromEntries(Object.entries(qe).filter(([Ve])=>le.includes(Ve)&&Fe(Ve)))),se.current=_e},[t.files,le,ue]),v.useEffect(()=>{e&&dt(e,le)},[le,ue,e,dt]),v.useEffect(()=>{if(!e)return;if(pt.current!==z){qt(e,z?"changes":"history"),pt.current=z;return}pt.current=z},[z,e,qt]);const ln=v.useMemo(()=>t.files.filter(_e=>Et[_e.path]??!0).map(_e=>_e.path),[Et,t.files]),me=ln.length,Ce=t.files.length>0&&me===t.files.length,$e=me>0&&me<t.files.length,et=De.trim(),Ee=et.length>0,Pe=H!==null,Ze=P||Pe,Ye=((Qe=t.branchHistory)==null?void 0:Qe.entries)??[],Ge=t.behindCount??0,ft=t.aheadCount??0,st=t.hasUpstream===!0,Vt=t.hasUpstream===!1&&!!t.branchName,sn=t.hasOriginRemote===!0,pn=t.branchName?t.branchName.split("/").map(_e=>encodeURIComponent(_e)).join("/"):null,dn=Vt?"publish":Ge>0?"pull":"fetch",At=t.originRepoSlug&&pn?`https://github.com/${t.originRepoSlug}/compare/${pn}?expand=1`:null,Je=!!(st&&At&&t.branchName&&t.branchName!==t.defaultBranchName),St=t.status==="ready"&&me>0&&!Ze,xt=t.status==="ready"&&me>0&&Ee&&!Ze,gt=sn?"commit_and_push":"commit_only",bt=t.branchName??"current branch";async function Lt(_e){if(xt){B(_e);try{const Fe=await A({paths:ln,summary:et,description:Ke.trim(),mode:_e});(Fe!=null&&Fe.ok||Fe!=null&&Fe.localCommitCreated)&&e&&Rt(e)}finally{B(null)}}}async function Wt(){if(St){$(!0);try{const _e=await C({paths:ln});e&&Se(e,{summary:_e.subject,description:_e.body})}finally{$(!1)}}}function Te(_e){if(!(!(_e.metaKey||_e.ctrlKey)||_e.key!=="Enter")){if(_e.preventDefault(),Ee){Lt(gt);return}Wt()}}async function nt(_e=dn){if(!(t.status!=="ready"||V)){G(!0);try{await M(_e)}finally{G(!1)}}}const Ie=v.useCallback(async _e=>{var Fe;if(W[_e]!==void 0||ae[_e])return W[_e]??"";ee(qe=>({...qe,[_e]:!0})),fe(qe=>{if(!(_e in qe))return qe;const{[_e]:Ve,...Dt}=qe;return Dt});try{const qe=await L(_e);te(Dt=>({...Dt,[_e]:qe}));const Ve=(Fe=t.files.find(Dt=>Dt.path===_e))==null?void 0:Fe.patchDigest;return Ve&&(se.current={...se.current,[_e]:Ve}),qe}catch(qe){const Ve=qe instanceof Error?qe.message:String(qe);throw fe(Dt=>({...Dt,[_e]:Ve})),qe}finally{ee(qe=>{const{[_e]:Ve,...Dt}=qe;return Dt})}},[t.files,ae,L,W]);return f.jsx("div",{className:"h-full min-h-0 border-l border-border bg-background md:min-w-[370px]",children:f.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[f.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border pl-2.5 pr-2 py-2",children:[f.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:f.jsx(Mve,{currentBranchName:t.branchName,onListBranches:g,onPreviewMergeBranch:b,onMergeBranch:x,onCheckoutBranch:_,onCreateBranch:w})}),t.status==="ready"?sn?dn==="publish"?f.jsxs(Ue,{variant:"ghost",size:"sm",onClick:()=>void nt(),disabled:V,className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[V?f.jsx(bn,{className:"h-3.5 w-3.5 animate-spin"}):f.jsx(Gv,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Publish Branch"})]}):f.jsxs("div",{className:"flex items-center gap-1",children:[dn==="fetch"?f.jsxs(Qr,{delayDuration:0,children:[f.jsx(Zr,{asChild:!0,children:f.jsxs(Ue,{variant:"ghost",size:"sm",onClick:()=>void nt(),disabled:V,className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[V?f.jsx(bn,{className:"h-3.5 w-3.5 animate-spin"}):f.jsx(wG,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Fetch"})]})}),f.jsx(Hr,{children:kve(t.lastFetchedAt)})]}):f.jsxs(Ue,{variant:"ghost",size:"sm",onClick:()=>void nt(),disabled:V,className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[V?f.jsx(bn,{className:"h-3.5 w-3.5 animate-spin"}):f.jsx(rk,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Pull"}),f.jsx("span",{className:"inline-flex min-w-4 items-center justify-center rounded-full bg-muted px-1 text-[10px] text-muted-foreground",children:Ge})]}),st&&ft>0?f.jsxs(Ue,{variant:"default",size:"sm",onClick:()=>void nt("push"),disabled:V,className:"h-7 gap-1.5 px-2 text-xs",children:[V?f.jsx(bn,{className:"h-3.5 w-3.5 animate-spin"}):f.jsx(Gv,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Push"}),f.jsx("span",{className:"inline-flex min-w-4 items-center justify-center rounded-full bg-primary-foreground/15 px-1 text-[10px] text-primary-foreground",children:ft})]}):null,Je&&At?f.jsxs(Ue,{variant:"ghost",size:"sm",onClick:()=>{typeof window>"u"||window.open(At,"_blank","noopener,noreferrer")},className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[f.jsx(N5,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"PR"})]}):null]}):f.jsxs(Ue,{variant:"default",size:"sm",onClick:()=>I(!0),className:"h-7 gap-1.5 px-3 text-xs",children:[f.jsx(AW,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:"Push to GitHub"})]}):null]}),f.jsxs("div",{className:"relative min-h-0 flex-1",children:[f.jsx("div",{className:"sticky top-0 z-30 pl-[14px] pr-[12px] pt-[6px] bg-gradient-to-b from-background to-transparent",children:f.jsx("div",{className:"relative h-[40px] flex min-w-0 items-center justify-center gap-[13px]",children:f.jsxs("div",{className:"flex min-w-0 flex-1 items-center justify-between gap-[13px] relative",children:[Ae==="changes"?f.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground/70",children:[f.jsx(VB,{checked:Ce,mixed:$e,label:$e?"Select all files for commit":Ce?"Unselect all files from commit":"Select all files for commit",onClick:()=>{!e||t.files.length===0||Ut(e,le,$e?!0:!Ce)}}),f.jsxs("span",{children:[me," files"]})]}):f.jsx("div",{}),f.jsx("div",{className:"pointer-events-none absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2",children:f.jsx("div",{className:"pointer-events-auto",children:f.jsx(Di,{value:Ae,onValueChange:_e=>{e&&qt(e,_e)},size:"sm",optionClassName:"flex-1 justify-center",options:[{value:"changes",label:"Changes"},{value:"history",label:"History"}]})})}),Ae==="changes"?f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(Zw,{label:"Unified diff",active:r==="unified",onClick:()=>F("unified"),children:f.jsx(EG,{className:"h-4 w-4"})}),f.jsx(Zw,{label:"Side-by-side diff",active:r==="split",onClick:()=>F("split"),children:f.jsx(zV,{className:"h-4 w-4"})}),f.jsx(Zw,{label:i?"Disable word wrap":"Enable word wrap",active:i,onClick:()=>D(!i),children:f.jsx(rq,{className:"h-4 w-4"})})]}):f.jsx("div",{})]})})}),f.jsx("div",{ref:ne,className:"h-full overflow-y-auto [scrollbar-gutter:stable]",children:t.status==="no_repo"?f.jsx("div",{className:"flex h-full items-center justify-center px-6 py-3 text-center",children:f.jsxs("div",{className:"flex max-w-[280px] flex-col items-center gap-3",children:[f.jsx("p",{className:"text-sm text-muted-foreground",children:"Initialize git here to start tracking branches, diffs, and history."}),f.jsx(Ue,{size:"sm",onClick:()=>void E(),children:"Init Git"})]})}):Ae==="history"?Ye.length===0?f.jsx("div",{className:"flex h-full items-center justify-center px-6 py-3 text-center",children:f.jsxs("p",{className:"text-sm text-muted-foreground",children:["No recent commits on ",t.branchName??"this branch","."]})}):f.jsx("div",{className:"space-y-1.5 p-1.5",children:Ye.map((_e,Fe)=>f.jsx(Eve,{entry:_e,isPendingPush:Fe<ft},_e.sha))}):t.files.length===0?f.jsx("div",{className:"flex h-full items-center justify-center px-6 py-3 text-center",children:f.jsx("p",{className:"text-sm text-muted-foreground",children:"No file changes."})}):f.jsxs("div",{className:"space-y-1.5 p-1.5 pb-10",children:[t.files.map(_e=>{const Fe=ce[_e.path]??!0,qe=Et[_e.path]??!0;return f.jsx(Lve,{file:_e,rootRef:ne,projectId:e,isCollapsed:Fe,isChecked:qe,editorLabel:n,diffRenderMode:r,wrapLines:i,onToggleCollapsed:()=>{e&&Tt(e,_e.path)},onToggleChecked:()=>{e&&Bt(e,_e.path,!qe)},fileActions:O,patch:W[_e.path],patchError:U[_e.path],isPatchLoading:!!ae[_e.path],onLoadPatch:Ie},_e.path)}),Ae==="changes"?f.jsxs("div",{className:"pointer-events-none sticky inset-x-0 bottom-11 py-1 pb-6 z-30 overflow-y-auto",children:[f.jsx("div",{className:"absolute inset-x-0 bottom-0 top-0 bg-gradient-to-t from-background to-transparent"}),f.jsx("div",{className:"pointer-events-auto relative",children:f.jsxs("div",{className:"space-y-0 rounded-xl mx-auto max-w-[700px]",children:[f.jsx($n,{value:De,onChange:_e=>{e&&Se(e,{summary:_e.target.value,description:Ke})},onKeyDown:Te,placeholder:"Commit message (override)",className:"rounded-t-xl rounded-b-none px-3",disabled:Ze||t.status!=="ready"}),f.jsx(xp,{value:Ke,onChange:_e=>{e&&Se(e,{summary:De,description:_e.target.value})},onKeyDown:Te,placeholder:"Description",rows:5,className:"-mt-px rounded-t-none rounded-b-xl px-3 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background mb-2",disabled:Ze||t.status!=="ready"}),f.jsx("div",{className:"w-full flex flex-row",children:f.jsxs(su,{children:[f.jsx(ou,{asChild:!0,children:f.jsx(Ue,{type:"button",className:"-mt-px w-full rounded-xl",disabled:Ee?!xt:!St,onClick:()=>{if(Ee){Lt(gt);return}Wt()},children:f.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[Ee?Pe?f.jsx(bn,{strokeWidth:2.5,className:"size-3 shrink-0 animate-spin"}):gt==="commit_and_push"?t.hasUpstream?f.jsx(Gv,{strokeWidth:2.5,className:"size-3 shrink-0"}):f.jsx(T5,{strokeWidth:2.5,className:"size-3 shrink-0"}):f.jsx(_i,{strokeWidth:2.5,className:"size-3 shrink-0"}):P?f.jsx(bn,{strokeWidth:2.5,className:"size-3 shrink-0 animate-spin"}):f.jsx(uG,{strokeWidth:2.5,className:"size-3 shrink-0"}),f.jsx("span",{className:"min-w-0 truncate text-left",children:Ee?Pe?H==="commit_only"?"Committing...":"Committing & Pushing...":gt==="commit_only"?f.jsxs(f.Fragment,{children:["Commit to ",f.jsx(Ac,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),bt]}):t.hasUpstream?f.jsxs(f.Fragment,{children:["Commit & push to ",f.jsx(Ac,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),bt]}):f.jsxs(f.Fragment,{children:["Commit & publish ",f.jsx(Ac,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),bt]}):P?"Generating...":f.jsxs(f.Fragment,{children:["Generate message for ",f.jsx(Ac,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),bt]})})]})})}),t.hasUpstream?f.jsx(Vl,{children:f.jsx(jn,{disabled:!Ee||!xt,onSelect:_e=>{_e.stopPropagation(),Lt("commit_only")},children:"Commit Only"})}):null]})})]})})]}):null]})})]}),f.jsx(Rve,{open:Q,onOpenChange:I,onGetGitHubPublishInfo:k,onCheckGitHubRepoAvailability:N,onPublish:R})]})})}const Dve=v.memo(jve);function Ive(e,t){const n=getComputedStyle(e),r=parseFloat(n.fontSize);return t*r}function Pve(e,t){const n=getComputedStyle(e.ownerDocument.body),r=parseFloat(n.fontSize);return t*r}function Ove(e){return e/100*window.innerHeight}function zve(e){return e/100*window.innerWidth}function Bve(e){switch(typeof e){case"number":return[e,"px"];case"string":{const t=parseFloat(e);return e.endsWith("%")?[t,"%"]:e.endsWith("px")?[t,"px"]:e.endsWith("rem")?[t,"rem"]:e.endsWith("em")?[t,"em"]:e.endsWith("vh")?[t,"vh"]:e.endsWith("vw")?[t,"vw"]:[t,"%"]}}}function Bh({groupSize:e,panelElement:t,styleProp:n}){let r;const[i,s]=Bve(n);switch(s){case"%":{r=i/100*e;break}case"px":{r=i;break}case"rem":{r=Pve(t,i);break}case"em":{r=Ive(t,i);break}case"vh":{r=Ove(i);break}case"vw":{r=zve(i);break}}return r}function Ii(e){return parseFloat(e.toFixed(3))}function Wd({group:e}){const{orientation:t,panels:n}=e;return n.reduce((r,i)=>(r+=t==="horizontal"?i.element.offsetWidth:i.element.offsetHeight,r),0)}function X1(e){const{panels:t}=e,n=Wd({group:e});return n===0?t.map(r=>({groupResizeBehavior:r.panelConstraints.groupResizeBehavior,collapsedSize:0,collapsible:r.panelConstraints.collapsible===!0,defaultSize:void 0,disabled:r.panelConstraints.disabled,minSize:0,maxSize:100,panelId:r.id})):t.map(r=>{const{element:i,panelConstraints:s}=r;let o=0;if(s.collapsedSize!==void 0){const m=Bh({groupSize:n,panelElement:i,styleProp:s.collapsedSize});o=Ii(m/n*100)}let l;if(s.defaultSize!==void 0){const m=Bh({groupSize:n,panelElement:i,styleProp:s.defaultSize});l=Ii(m/n*100)}let c=0;if(s.minSize!==void 0){const m=Bh({groupSize:n,panelElement:i,styleProp:s.minSize});c=Ii(m/n*100)}let u=100;if(s.maxSize!==void 0){const m=Bh({groupSize:n,panelElement:i,styleProp:s.maxSize});u=Ii(m/n*100)}return{groupResizeBehavior:s.groupResizeBehavior,collapsedSize:o,collapsible:s.collapsible===!0,defaultSize:l,disabled:s.disabled,minSize:c,maxSize:u,panelId:r.id}})}function Ln(e,t="Assertion error"){if(!e)throw Error(t)}function Q1(e,t){return Array.from(t).sort(e==="horizontal"?Fve:$ve)}function Fve(e,t){const n=e.element.offsetLeft-t.element.offsetLeft;return n!==0?n:e.element.offsetWidth-t.element.offsetWidth}function $ve(e,t){const n=e.element.offsetTop-t.element.offsetTop;return n!==0?n:e.element.offsetHeight-t.element.offsetHeight}function GB(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.ELEMENT_NODE}function qB(e,t){return{x:e.x>=t.left&&e.x<=t.right?0:Math.min(Math.abs(e.x-t.left),Math.abs(e.x-t.right)),y:e.y>=t.top&&e.y<=t.bottom?0:Math.min(Math.abs(e.y-t.top),Math.abs(e.y-t.bottom))}}function Hve({orientation:e,rects:t,targetRect:n}){const r={x:n.x+n.width/2,y:n.y+n.height/2};let i,s=Number.MAX_VALUE;for(const o of t){const{x:l,y:c}=qB(r,o),u=e==="horizontal"?l:c;u<s&&(s=u,i=o)}return Ln(i,"No rect found"),i}let kv;function Uve(){return kv===void 0&&(typeof matchMedia=="function"?kv=!!matchMedia("(pointer:coarse)").matches:kv=!1),kv}function KB(e){const{element:t,orientation:n,panels:r,separators:i}=e,s=Q1(n,Array.from(t.children).filter(GB).map(x=>({element:x}))).map(({element:x})=>x),o=[];let l=!1,c=!1,u=-1,m=-1,h=0,g,b=[];{let x=-1;for(const _ of s)_.hasAttribute("data-panel")&&(x++,_.ariaDisabled===null&&(h++,u===-1&&(u=x),m=x))}if(h>1){let x=-1;for(const _ of s)if(_.hasAttribute("data-panel")){x++;const w=r.find(C=>C.element===_);if(w){if(g){const C=g.element.getBoundingClientRect(),E=_.getBoundingClientRect();let k;if(c){const N=n==="horizontal"?new DOMRect(C.right,C.top,0,C.height):new DOMRect(C.left,C.bottom,C.width,0),R=n==="horizontal"?new DOMRect(E.left,E.top,0,E.height):new DOMRect(E.left,E.top,E.width,0);switch(b.length){case 0:{k=[N,R];break}case 1:{const A=b[0],M=Hve({orientation:n,rects:[C,E],targetRect:A.element.getBoundingClientRect()});k=[A,M===C?R:N];break}default:{k=b;break}}}else b.length?k=b:k=[n==="horizontal"?new DOMRect(C.right,E.top,E.left-C.right,E.height):new DOMRect(E.left,C.bottom,E.width,E.top-C.bottom)];for(const N of k){let R="width"in N?N:N.element.getBoundingClientRect();const A=Uve()?e.resizeTargetMinimumSize.coarse:e.resizeTargetMinimumSize.fine;if(R.width<A){const L=A-R.width;R=new DOMRect(R.x-L/2,R.y,R.width+L,R.height)}if(R.height<A){const L=A-R.height;R=new DOMRect(R.x,R.y-L/2,R.width,R.height+L)}const M=x<=u||x>m;!l&&!M&&o.push({group:e,groupSize:Wd({group:e}),panels:[g,w],separator:"width"in N?void 0:N,rect:R}),l=!1}}c=!1,g=w,b=[]}}else if(_.hasAttribute("data-separator")){_.ariaDisabled!==null&&(l=!0);const w=i.find(C=>C.element===_);w?b.push(w):(g=void 0,b=[])}else c=!0}return o}var Rl,XP;let YB=(XP=class{constructor(){dl(this,Rl,{})}addListener(t,n){const r=_r(this,Rl)[t];return r===void 0?_r(this,Rl)[t]=[n]:r.includes(n)||r.push(n),()=>{this.removeListener(t,n)}}emit(t,n){const r=_r(this,Rl)[t];if(r!==void 0)if(r.length===1)r[0].call(null,n);else{let i=!1,s=null;const o=Array.from(r);for(let l=0;l<o.length;l++){const c=o[l];try{c.call(null,n)}catch(u){s===null&&(i=!0,s=u)}}if(i)throw s}}removeAllListeners(){ms(this,Rl,{})}removeListener(t,n){const r=_r(this,Rl)[t];if(r!==void 0){const i=r.indexOf(n);i>=0&&r.splice(i,1)}}},Rl=new WeakMap,XP),Ao=new Map;const XB=new YB;function Vve(e){Ao=new Map(Ao),Ao.delete(e)}function hD(e,t){for(const[n]of Ao)if(n.id===e)return n}function jl(e,t){for(const[n,r]of Ao)if(n.id===e)return r;if(t)throw Error(`Could not find data for Group with id ${e}`)}function cu(){return Ao}function o2(e,t){return XB.addListener("groupChange",n=>{n.group.id===e&&t(n)})}function Na(e,t){const n=Ao.get(e);Ao=new Map(Ao),Ao.set(e,t),XB.emit("groupChange",{group:e,prev:n,next:t})}function Wve(e,t,n){let r,i={x:1/0,y:1/0};for(const s of t){const o=qB(n,s.rect);switch(e){case"horizontal":{o.x<=i.x&&(r=s,i=o);break}case"vertical":{o.y<=i.y&&(r=s,i=o);break}}}return r?{distance:i,hitRegion:r}:void 0}function Gve(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function qve(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:gD(e),b:gD(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)r=n.a.pop(),n.b.pop();Ln(r,"Stacking order can only be calculated for elements with a common ancestor");const i={a:pD(mD(n.a)),b:pD(mD(n.b))};if(i.a===i.b){const s=r.childNodes,o={a:n.a.at(-1),b:n.b.at(-1)};let l=s.length;for(;l--;){const c=s[l];if(c===o.a)return 1;if(c===o.b)return-1}}return Math.sign(i.a-i.b)}const Kve=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function Yve(e){const t=getComputedStyle(QB(e)??e).display;return t==="flex"||t==="inline-flex"}function Xve(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||Yve(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||Kve.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function mD(e){let t=e.length;for(;t--;){const n=e[t];if(Ln(n,"Missing node"),Xve(n))return n}return null}function pD(e){return e&&Number(getComputedStyle(e).zIndex)||0}function gD(e){const t=[];for(;e;)t.push(e),e=QB(e);return t}function QB(e){const{parentNode:t}=e;return Gve(t)?t.host:t}function Qve(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function Zve({groupElement:e,hitRegion:t,pointerEventTarget:n}){if(!GB(n)||n.contains(e)||e.contains(n))return!0;if(qve(n,e)>0){let r=n;for(;r;){if(r.contains(e))return!0;if(Qve(r.getBoundingClientRect(),t))return!1;r=r.parentElement}}return!0}function a2(e,t){const n=[];return t.forEach((r,i)=>{if(i.disabled)return;const s=KB(i),o=Wve(i.orientation,s,{x:e.clientX,y:e.clientY});o&&o.distance.x<=0&&o.distance.y<=0&&Zve({groupElement:i.element,hitRegion:o.hitRegion.rect,pointerEventTarget:e.target})&&n.push(o.hitRegion)}),n}function Jve(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function gi(e,t,n=0){return Math.abs(Ii(e)-Ii(t))<=n}function So(e,t){return gi(e,t)?0:e>t?1:-1}function _d({overrideDisabledPanels:e,panelConstraints:t,prevSize:n,size:r}){const{collapsedSize:i=0,collapsible:s,disabled:o,maxSize:l=100,minSize:c=0}=t;if(o&&!e)return n;if(So(r,c)<0)if(s){const u=(i+c)/2;So(r,u)<0?r=i:r=c}else r=c;return r=Math.min(l,r),r=Ii(r),r}function zm({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:r,prevLayout:i,trigger:s}){if(gi(e,0))return t;const o=s==="imperative-api",l=Object.values(t),c=Object.values(i),u=[...l],[m,h]=r;Ln(m!=null,"Invalid first pivot index"),Ln(h!=null,"Invalid second pivot index");let g=0;switch(s){case"keyboard":{{const _=e<0?h:m,w=n[_];Ln(w,`Panel constraints not found for index ${_}`);const{collapsedSize:C=0,collapsible:E,minSize:k=0}=w;if(E){const N=l[_];if(Ln(N!=null,`Previous layout not found for panel index ${_}`),gi(N,C)){const R=k-N;So(R,Math.abs(e))>0&&(e=e<0?0-R:R)}}}{const _=e<0?m:h,w=n[_];Ln(w,`No panel constraints found for index ${_}`);const{collapsedSize:C=0,collapsible:E,minSize:k=0}=w;if(E){const N=l[_];if(Ln(N!=null,`Previous layout not found for panel index ${_}`),gi(N,k)){const R=N-C;So(R,Math.abs(e))>0&&(e=e<0?0-R:R)}}}break}default:{const _=e<0?h:m,w=n[_];Ln(w,`Panel constraints not found for index ${_}`);const C=l[_],{collapsible:E,collapsedSize:k,minSize:N}=w;if(E&&So(C,N)<0)if(e>0){const R=N-k,A=R/2,M=C+e;So(M,N)<0&&(e=So(e,A)<=0?0:R)}else{const R=N-k,A=100-R/2,M=C-e;So(M,N)<0&&(e=So(100+e,A)>0?0:-R)}break}}{const _=e<0?1:-1;let w=e<0?h:m,C=0;for(;;){const k=l[w];Ln(k!=null,`Previous layout not found for panel index ${w}`);const N=_d({overrideDisabledPanels:o,panelConstraints:n[w],prevSize:k,size:100})-k;if(C+=N,w+=_,w<0||w>=n.length)break}const E=Math.min(Math.abs(e),Math.abs(C));e=e<0?0-E:E}{let _=e<0?m:h;for(;_>=0&&_<n.length;){const w=Math.abs(e)-Math.abs(g),C=l[_];Ln(C!=null,`Previous layout not found for panel index ${_}`);const E=C-w,k=_d({overrideDisabledPanels:o,panelConstraints:n[_],prevSize:C,size:E});if(!gi(C,k)&&(g+=C-k,u[_]=k,g.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?_--:_++}}if(Jve(c,u))return i;{const _=e<0?h:m,w=l[_];Ln(w!=null,`Previous layout not found for panel index ${_}`);const C=w+g,E=_d({overrideDisabledPanels:o,panelConstraints:n[_],prevSize:w,size:C});if(u[_]=E,!gi(E,C)){let k=C-E,N=e<0?h:m;for(;N>=0&&N<n.length;){const R=u[N];Ln(R!=null,`Previous layout not found for panel index ${N}`);const A=R+k,M=_d({overrideDisabledPanels:o,panelConstraints:n[N],prevSize:R,size:A});if(gi(R,M)||(k-=M-R,u[N]=M),gi(k,0))break;e>0?N--:N++}}}const b=Object.values(u).reduce((_,w)=>w+_,0);if(!gi(b,100,.1))return i;const x=Object.keys(i);return u.reduce((_,w,C)=>(_[x[C]]=w,_),{})}function Yc(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(t[n]===void 0||So(e[n],t[n])!==0)return!1;return!0}function Xc({layout:e,panelConstraints:t}){const n=Object.values(e),r=[...n],i=r.reduce((l,c)=>l+c,0);if(r.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${r.map(l=>`${l}%`).join(", ")}`);if(!gi(i,100)&&r.length>0)for(let l=0;l<t.length;l++){const c=r[l];Ln(c!=null,`No layout data found for index ${l}`);const u=100/i*c;r[l]=u}let s=0;for(let l=0;l<t.length;l++){const c=n[l];Ln(c!=null,`No layout data found for index ${l}`);const u=r[l];Ln(u!=null,`No layout data found for index ${l}`);const m=_d({overrideDisabledPanels:!0,panelConstraints:t[l],prevSize:c,size:u});u!=m&&(s+=u-m,r[l]=m)}if(!gi(s,0))for(let l=0;l<t.length;l++){const c=r[l];Ln(c!=null,`No layout data found for index ${l}`);const u=c+s,m=_d({overrideDisabledPanels:!0,panelConstraints:t[l],prevSize:c,size:u});if(c!==m&&(s-=m-c,r[l]=m,gi(s,0)))break}const o=Object.keys(e);return r.reduce((l,c,u)=>(l[o[u]]=c,l),{})}function ZB({groupId:e,panelId:t}){const n=()=>{const l=cu();for(const[c,{defaultLayoutDeferred:u,derivedPanelConstraints:m,layout:h,groupSize:g,separatorToPanels:b}]of l)if(c.id===e)return{defaultLayoutDeferred:u,derivedPanelConstraints:m,group:c,groupSize:g,layout:h,separatorToPanels:b};throw Error(`Group ${e} not found`)},r=()=>{const l=n().derivedPanelConstraints.find(c=>c.panelId===t);if(l!==void 0)return l;throw Error(`Panel constraints not found for Panel ${t}`)},i=()=>{const l=n().group.panels.find(c=>c.id===t);if(l!==void 0)return l;throw Error(`Layout not found for Panel ${t}`)},s=()=>{const l=n().layout[t];if(l!==void 0)return l;throw Error(`Layout not found for Panel ${t}`)},o=l=>{const c=s();if(l===c)return;const{defaultLayoutDeferred:u,derivedPanelConstraints:m,group:h,groupSize:g,layout:b,separatorToPanels:x}=n(),_=h.panels.findIndex(k=>k.id===t),w=_===h.panels.length-1,C=zm({delta:w?c-l:l-c,initialLayout:b,panelConstraints:m,pivotIndices:w?[_-1,_]:[_,_+1],prevLayout:b,trigger:"imperative-api"}),E=Xc({layout:C,panelConstraints:m});Yc(b,E)||Na(h,{defaultLayoutDeferred:u,derivedPanelConstraints:m,groupSize:g,layout:E,separatorToPanels:x})};return{collapse:()=>{const{collapsible:l,collapsedSize:c}=r(),{mutableValues:u}=i(),m=s();l&&m!==c&&(u.expandToSize=m,o(c))},expand:()=>{const{collapsible:l,collapsedSize:c,minSize:u}=r(),{mutableValues:m}=i(),h=s();if(l&&h===c){let g=m.expandToSize??u;g===0&&(g=1),o(g)}},getSize:()=>{const{group:l}=n(),c=s(),{element:u}=i(),m=l.orientation==="horizontal"?u.offsetWidth:u.offsetHeight;return{asPercentage:c,inPixels:m}},isCollapsed:()=>{const{collapsible:l,collapsedSize:c}=r(),u=s();return l&&gi(c,u)},resize:l=>{const{group:c}=n(),{element:u}=i(),m=Wd({group:c}),h=Bh({groupSize:m,panelElement:u,styleProp:l}),g=Ii(h/m*100);o(g)}}}function vD(e){if(e.defaultPrevented)return;const t=cu();a2(e,t).forEach(n=>{if(n.separator){const r=n.panels.find(i=>i.panelConstraints.defaultSize!==void 0);if(r){const i=r.panelConstraints.defaultSize,s=ZB({groupId:n.group.id,panelId:r.id});s&&i!==void 0&&(s.resize(i),e.preventDefault())}}})}function ab(e){const t=cu();for(const[n]of t)if(n.separators.some(r=>r.element===e))return n;throw Error("Could not find parent Group for separator element")}function JB({groupId:e}){const t=()=>{const n=cu();for(const[r,i]of n)if(r.id===e)return{group:r,...i};throw Error(`Could not find Group with id "${e}"`)};return{getLayout(){const{defaultLayoutDeferred:n,layout:r}=t();return n?{}:r},setLayout(n){const{defaultLayoutDeferred:r,derivedPanelConstraints:i,group:s,groupSize:o,layout:l,separatorToPanels:c}=t(),u=Xc({layout:n,panelConstraints:i});return r?l:(Yc(l,u)||Na(s,{defaultLayoutDeferred:r,derivedPanelConstraints:i,groupSize:o,layout:u,separatorToPanels:c}),u)}}}function _c(e,t){const n=ab(e),r=jl(n.id,!0),i=n.separators.find(m=>m.element===e);Ln(i,"Matching separator not found");const s=r.separatorToPanels.get(i);Ln(s,"Matching panels not found");const o=s.map(m=>n.panels.indexOf(m)),l=JB({groupId:n.id}).getLayout(),c=zm({delta:t,initialLayout:l,panelConstraints:r.derivedPanelConstraints,pivotIndices:o,prevLayout:l,trigger:"keyboard"}),u=Xc({layout:c,panelConstraints:r.derivedPanelConstraints});Yc(l,u)||Na(n,{defaultLayoutDeferred:r.defaultLayoutDeferred,derivedPanelConstraints:r.derivedPanelConstraints,groupSize:r.groupSize,layout:u,separatorToPanels:r.separatorToPanels})}function bD(e){if(e.defaultPrevented)return;const t=e.currentTarget,n=ab(t);if(!n.disabled)switch(e.key){case"ArrowDown":{e.preventDefault(),n.orientation==="vertical"&&_c(t,5);break}case"ArrowLeft":{e.preventDefault(),n.orientation==="horizontal"&&_c(t,-5);break}case"ArrowRight":{e.preventDefault(),n.orientation==="horizontal"&&_c(t,5);break}case"ArrowUp":{e.preventDefault(),n.orientation==="vertical"&&_c(t,-5);break}case"End":{e.preventDefault(),_c(t,100);break}case"Enter":{e.preventDefault();const r=ab(t),i=jl(r.id,!0),{derivedPanelConstraints:s,layout:o,separatorToPanels:l}=i,c=r.separators.find(g=>g.element===t);Ln(c,"Matching separator not found");const u=l.get(c);Ln(u,"Matching panels not found");const m=u[0],h=s.find(g=>g.panelId===m.id);if(Ln(h,"Panel metadata not found"),h.collapsible){const g=o[m.id],b=h.collapsedSize===g?r.mutableState.expandedPanelSizes[m.id]??h.minSize:h.collapsedSize;_c(t,b-g)}break}case"F6":{e.preventDefault();const r=ab(t).separators.map(o=>o.element),i=Array.from(r).findIndex(o=>o===e.currentTarget);Ln(i!==null,"Index not found");const s=e.shiftKey?i>0?i-1:r.length-1:i+1<r.length?i+1:0;r[s].focus({preventScroll:!0});break}case"Home":{e.preventDefault(),_c(t,-100);break}}}let jd={cursorFlags:0,state:"inactive"};const l2=new YB;function Qc(){return jd}function ebe(e){return l2.addListener("change",e)}function tbe(e){const t=jd,n={...jd};n.cursorFlags=e,jd=n,l2.emit("change",{prev:t,next:n})}function Dd(e){const t=jd;jd=e,l2.emit("change",{prev:t,next:e})}function yD(e){if(e.defaultPrevented||e.pointerType==="mouse"&&e.button>0)return;const t=cu(),n=a2(e,t),r=new Map;let i=!1;n.forEach(s=>{s.separator&&(i||(i=!0,s.separator.element.focus({preventScroll:!0})));const o=t.get(s.group);o&&r.set(s.group,o.layout)}),Dd({cursorFlags:0,hitRegions:n,initialLayoutMap:r,pointerDownAtPoint:{x:e.clientX,y:e.clientY},state:"active"}),n.length&&e.preventDefault()}const nbe=e=>e,Jw=()=>{},eF=1,tF=2,nF=4,rF=8,xD=3,_D=12;let Ev;function wD(){return Ev===void 0&&(Ev=!1,typeof window<"u"&&(window.navigator.userAgent.includes("Chrome")||window.navigator.userAgent.includes("Firefox"))&&(Ev=!0)),Ev}function rbe({cursorFlags:e,groups:t,state:n}){let r=0,i=0;switch(n){case"active":case"hover":t.forEach(s=>{if(!s.mutableState.disableCursor)switch(s.orientation){case"horizontal":{r++;break}case"vertical":{i++;break}}})}if(!(r===0&&i===0)){switch(n){case"active":{if(e&&wD()){const s=(e&eF)!==0,o=(e&tF)!==0,l=(e&nF)!==0,c=(e&rF)!==0;if(s)return l?"se-resize":c?"ne-resize":"e-resize";if(o)return l?"sw-resize":c?"nw-resize":"w-resize";if(l)return"s-resize";if(c)return"n-resize"}break}}return wD()?r>0&&i>0?"move":r>0?"ew-resize":"ns-resize":r>0&&i>0?"grab":r>0?"col-resize":"row-resize"}}const SD=new WeakMap;function c2(e){if(e.defaultView===null||e.defaultView===void 0)return;let{prevStyle:t,styleSheet:n}=SD.get(e)??{};n===void 0&&(n=new e.defaultView.CSSStyleSheet,e.adoptedStyleSheets&&e.adoptedStyleSheets.push(n));const r=Qc();switch(r.state){case"active":case"hover":{const i=rbe({cursorFlags:r.cursorFlags,groups:r.hitRegions.map(o=>o.group),state:r.state}),s=`*, *:hover {cursor: ${i} !important; }`;if(t===s)return;t=s,i?n.cssRules.length===0?n.insertRule(s):n.replaceSync(s):n.cssRules.length===1&&n.deleteRule(0);break}case"inactive":{t=void 0,n.cssRules.length===1&&n.deleteRule(0);break}}SD.set(e,{prevStyle:t,styleSheet:n})}function iF({document:e,event:t,hitRegions:n,initialLayoutMap:r,mountedGroups:i,pointerDownAtPoint:s,prevCursorFlags:o}){let l=0;n.forEach(u=>{const{group:m,groupSize:h}=u,{orientation:g,panels:b}=m,{disableCursor:x}=m.mutableState;let _=0;s?g==="horizontal"?_=(t.clientX-s.x)/h*100:_=(t.clientY-s.y)/h*100:g==="horizontal"?_=t.clientX<0?-100:100:_=t.clientY<0?-100:100;const w=r.get(m),C=i.get(m);if(!w||!C)return;const{defaultLayoutDeferred:E,derivedPanelConstraints:k,groupSize:N,layout:R,separatorToPanels:A}=C;if(k&&R&&A){const M=zm({delta:_,initialLayout:w,panelConstraints:k,pivotIndices:u.panels.map(L=>b.indexOf(L)),prevLayout:R,trigger:"mouse-or-touch"});if(Yc(M,R)){if(_!==0&&!x)switch(g){case"horizontal":{l|=_<0?eF:tF;break}case"vertical":{l|=_<0?nF:rF;break}}}else Na(u.group,{defaultLayoutDeferred:E,derivedPanelConstraints:k,groupSize:N,layout:M,separatorToPanels:A})}});let c=0;t.movementX===0?c|=o&xD:c|=l&xD,t.movementY===0?c|=o&_D:c|=l&_D,tbe(c),c2(e)}function CD(e){const t=cu(),n=Qc();switch(n.state){case"active":iF({document:e.currentTarget,event:e,hitRegions:n.hitRegions,initialLayoutMap:n.initialLayoutMap,mountedGroups:t,prevCursorFlags:n.cursorFlags})}}function kD(e){if(e.defaultPrevented)return;const t=Qc(),n=cu();switch(t.state){case"active":{if(e.buttons===0){Dd({cursorFlags:0,state:"inactive"}),t.hitRegions.forEach(r=>{const i=jl(r.group.id,!0);Na(r.group,i)});return}iF({document:e.currentTarget,event:e,hitRegions:t.hitRegions,initialLayoutMap:t.initialLayoutMap,mountedGroups:n,pointerDownAtPoint:t.pointerDownAtPoint,prevCursorFlags:t.cursorFlags});break}default:{const r=a2(e,n);r.length===0?t.state!=="inactive"&&Dd({cursorFlags:0,state:"inactive"}):Dd({cursorFlags:0,hitRegions:r,state:"hover"}),c2(e.currentTarget);break}}}function ED(e){if(e.relatedTarget instanceof HTMLIFrameElement)switch(Qc().state){case"hover":Dd({cursorFlags:0,state:"inactive"})}}function TD(e){if(e.defaultPrevented||e.pointerType==="mouse"&&e.button>0)return;const t=Qc();switch(t.state){case"active":Dd({cursorFlags:0,state:"inactive"}),t.hitRegions.length>0&&(c2(e.currentTarget),t.hitRegions.forEach(n=>{const r=jl(n.group.id,!0);Na(n.group,r)}),e.preventDefault())}}function ND(e){let t=0,n=0;const r={};for(const s of e)if(s.defaultSize!==void 0){t++;const o=Ii(s.defaultSize);n+=o,r[s.panelId]=o}else r[s.panelId]=void 0;const i=e.length-t;if(i!==0){const s=Ii((100-n)/i);for(const o of e)o.defaultSize===void 0&&(r[o.panelId]=s)}return r}function ibe(e,t,n){if(!n[0])return;const r=e.panels.find(c=>c.element===t);if(!r||!r.onResize)return;const i=Wd({group:e}),s=e.orientation==="horizontal"?r.element.offsetWidth:r.element.offsetHeight,o=r.mutableValues.prevSize,l={asPercentage:Ii(s/i*100),inPixels:s};r.mutableValues.prevSize=l,r.onResize(l,r.id,o)}function sbe(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function obe({group:e,nextGroupSize:t,prevGroupSize:n,prevLayout:r}){if(n<=0||t<=0||n===t)return r;let i=0,s=0,o=!1;const l=new Map,c=[];for(const h of e.panels){const g=r[h.id]??0;switch(h.panelConstraints.groupResizeBehavior){case"preserve-pixel-size":{o=!0;const b=g/100*n,x=Ii(b/t*100);l.set(h.id,x),i+=x;break}case"preserve-relative-size":default:{c.push(h.id),s+=g;break}}}if(!o||c.length===0)return r;const u=100-i,m={...r};if(l.forEach((h,g)=>{m[g]=h}),s>0)for(const h of c){const g=r[h]??0;m[h]=Ii(g/s*u)}else{const h=Ii(u/c.length);for(const g of c)m[g]=h}return m}function abe(e,t){const n=e.map(i=>i.id),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n)if(!r.includes(i))return!1;return!0}const ad=new Map;function lbe(e){let t=!0;Ln(e.element.ownerDocument.defaultView,"Cannot register an unmounted Group");const n=e.element.ownerDocument.defaultView.ResizeObserver,r=new Set,i=new Set,s=new n(x=>{for(const _ of x){const{borderBoxSize:w,target:C}=_;if(C===e.element){if(t){const E=Wd({group:e});if(E===0)return;const k=jl(e.id);if(!k)return;const N=X1(e),R=k.defaultLayoutDeferred?ND(N):k.layout,A=obe({group:e,nextGroupSize:E,prevGroupSize:k.groupSize,prevLayout:R}),M=Xc({layout:A,panelConstraints:N});if(!k.defaultLayoutDeferred&&Yc(k.layout,M)&&sbe(k.derivedPanelConstraints,N)&&k.groupSize===E)return;Na(e,{defaultLayoutDeferred:!1,derivedPanelConstraints:N,groupSize:E,layout:M,separatorToPanels:k.separatorToPanels})}}else ibe(e,C,w)}});s.observe(e.element),e.panels.forEach(x=>{Ln(!r.has(x.id),`Panel ids must be unique; id "${x.id}" was used more than once`),r.add(x.id),x.onResize&&s.observe(x.element)});const o=Wd({group:e}),l=X1(e),c=e.panels.map(({id:x})=>x).join(",");let u=e.mutableState.defaultLayout;u&&(abe(e.panels,u)||(u=void 0));const m=e.mutableState.layouts[c]??u??ND(l),h=Xc({layout:m,panelConstraints:l}),g=e.element.ownerDocument;ad.set(g,(ad.get(g)??0)+1);const b=new Map;return KB(e).forEach(x=>{x.separator&&b.set(x.separator,x.panels)}),Na(e,{defaultLayoutDeferred:o===0,derivedPanelConstraints:l,groupSize:o,layout:h,separatorToPanels:b}),e.separators.forEach(x=>{Ln(!i.has(x.id),`Separator ids must be unique; id "${x.id}" was used more than once`),i.add(x.id),x.element.addEventListener("keydown",bD)}),ad.get(g)===1&&(g.addEventListener("dblclick",vD,!0),g.addEventListener("pointerdown",yD,!0),g.addEventListener("pointerleave",CD),g.addEventListener("pointermove",kD),g.addEventListener("pointerout",ED),g.addEventListener("pointerup",TD,!0)),function(){t=!1,ad.set(g,Math.max(0,(ad.get(g)??0)-1)),Vve(e),e.separators.forEach(x=>{x.element.removeEventListener("keydown",bD)}),ad.get(g)||(g.removeEventListener("dblclick",vD,!0),g.removeEventListener("pointerdown",yD,!0),g.removeEventListener("pointerleave",CD),g.removeEventListener("pointermove",kD),g.removeEventListener("pointerout",ED),g.removeEventListener("pointerup",TD,!0)),s.disconnect()}}function cbe(){const[e,t]=v.useState({}),n=v.useCallback(()=>t({}),[]);return[e,n]}function u2(e){const t=v.useId();return`${e??t}`}const uu=typeof window<"u"?v.useLayoutEffect:v.useEffect;function rm(e){const t=v.useRef(e);return uu(()=>{t.current=e},[e]),v.useCallback((...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[t])}function d2(...e){return rm(t=>{e.forEach(n=>{if(n)switch(typeof n){case"function":{n(t);break}case"object":{n.current=t;break}}})})}function f2(e){const t=v.useRef({...e});return uu(()=>{for(const n in e)t.current[n]=e[n]},[e]),t.current}const sF=v.createContext(null);function ube(e,t){const n=v.useRef({getLayout:()=>({}),setLayout:nbe});v.useImperativeHandle(t,()=>n.current,[]),uu(()=>{Object.assign(n.current,JB({groupId:e}))})}function oF({children:e,className:t,defaultLayout:n,disableCursor:r,disabled:i,elementRef:s,groupRef:o,id:l,onLayoutChange:c,onLayoutChanged:u,orientation:m="horizontal",resizeTargetMinimumSize:h={coarse:20,fine:10},style:g,...b}){const x=v.useRef({onLayoutChange:{},onLayoutChanged:{}}),_=rm(O=>{Yc(x.current.onLayoutChange,O)||(x.current.onLayoutChange=O,c==null||c(O))}),w=rm(O=>{Yc(x.current.onLayoutChanged,O)||(x.current.onLayoutChanged=O,u==null||u(O))}),C=u2(l),E=v.useRef(null),[k,N]=cbe(),R=v.useRef({lastExpandedPanelSizes:{},layouts:{},panels:[],resizeTargetMinimumSize:h,separators:[]}),A=d2(E,s);ube(C,o);const M=rm((O,z)=>{const P=Qc(),$=hD(O),H=jl(O);if(H){let B=!1;switch(P.state){case"active":{B=P.hitRegions.some(V=>V.group===$);break}}return{flexGrow:H.layout[z]??1,pointerEvents:B?"none":void 0}}return{flexGrow:(n==null?void 0:n[z])??1}}),L=f2({defaultLayout:n,disableCursor:r}),F=v.useMemo(()=>({get disableCursor(){return!!L.disableCursor},getPanelStyles:M,id:C,orientation:m,registerPanel:O=>{const z=R.current;return z.panels=Q1(m,[...z.panels,O]),N(),()=>{z.panels=z.panels.filter(P=>P!==O),N()}},registerSeparator:O=>{const z=R.current;return z.separators=Q1(m,[...z.separators,O]),N(),()=>{z.separators=z.separators.filter(P=>P!==O),N()}},togglePanelDisabled:(O,z)=>{const P=R.current.panels.find(B=>B.id===O);P&&(P.panelConstraints.disabled=z);const $=hD(C),H=jl(C);$&&H&&Na($,{...H,derivedPanelConstraints:X1($)})},toggleSeparatorDisabled:(O,z)=>{const P=R.current.separators.find($=>$.id===O);P&&(P.disabled=z)}}),[M,C,N,m,L]),D=v.useRef(null);return uu(()=>{const O=E.current;if(O===null)return;const z=R.current;let P;if(L.defaultLayout!==void 0&&Object.keys(L.defaultLayout).length===z.panels.length){P={};for(const I of z.panels){const W=L.defaultLayout[I.id];W!==void 0&&(P[I.id]=W)}}const $={disabled:!!i,element:O,id:C,mutableState:{defaultLayout:P,disableCursor:!!L.disableCursor,expandedPanelSizes:R.current.lastExpandedPanelSizes,layouts:R.current.layouts},orientation:m,panels:z.panels,resizeTargetMinimumSize:z.resizeTargetMinimumSize,separators:z.separators};D.current=$;const H=lbe($),{defaultLayoutDeferred:B,derivedPanelConstraints:V,layout:G}=jl($.id,!0);!B&&V.length>0&&(_(G),w(G));const Q=o2(C,I=>{const{defaultLayoutDeferred:W,derivedPanelConstraints:te,layout:U}=I.next;if(W||te.length===0)return;const fe=$.panels.map(({id:ee})=>ee).join(",");$.mutableState.layouts[fe]=U,te.forEach(ee=>{if(ee.collapsible){const{layout:ne}=I.prev??{};if(ne){const se=gi(ee.collapsedSize,U[ee.panelId]),le=gi(ee.collapsedSize,ne[ee.panelId]);se&&!le&&($.mutableState.expandedPanelSizes[ee.panelId]=ne[ee.panelId])}}});const ae=Qc().state!=="active";_(U),ae&&w(U)});return()=>{D.current=null,H(),Q()}},[i,C,w,_,m,k,L]),v.useEffect(()=>{const O=D.current;O&&(O.mutableState.defaultLayout=n,O.mutableState.disableCursor=!!r)}),f.jsx(sF.Provider,{value:F,children:f.jsx("div",{...b,className:t,"data-group":!0,"data-testid":C,id:C,ref:A,style:{height:"100%",width:"100%",overflow:"hidden",...g,display:"flex",flexDirection:m==="horizontal"?"row":"column",flexWrap:"nowrap",touchAction:m==="horizontal"?"pan-y":"pan-x"},children:e})})}oF.displayName="Group";function h2(){const e=v.useContext(sF);return Ln(e,"Group Context not found; did you render a Panel or Separator outside of a Group?"),e}function dbe(e,t){const{id:n}=h2(),r=v.useRef({collapse:Jw,expand:Jw,getSize:()=>({asPercentage:0,inPixels:0}),isCollapsed:()=>!1,resize:Jw});v.useImperativeHandle(t,()=>r.current,[]),uu(()=>{Object.assign(r.current,ZB({groupId:n,panelId:e}))})}function aF({children:e,className:t,collapsedSize:n="0%",collapsible:r=!1,defaultSize:i,disabled:s,elementRef:o,groupResizeBehavior:l="preserve-relative-size",id:c,maxSize:u="100%",minSize:m="0%",onResize:h,panelRef:g,style:b,...x}){const _=!!c,w=u2(c),C=f2({disabled:s}),E=v.useRef(null),k=d2(E,o),{getPanelStyles:N,id:R,orientation:A,registerPanel:M,togglePanelDisabled:L}=h2(),F=h!==null,D=rm((z,P,$)=>{h==null||h(z,c,$)});uu(()=>{const z=E.current;if(z!==null){const P={element:z,id:w,idIsStable:_,mutableValues:{expandToSize:void 0,prevSize:void 0},onResize:F?D:void 0,panelConstraints:{groupResizeBehavior:l,collapsedSize:n,collapsible:r,defaultSize:i,disabled:C.disabled,maxSize:u,minSize:m}};return M(P)}},[l,n,r,i,F,w,_,u,m,D,M,C]),v.useEffect(()=>{L(w,!!s)},[s,w,L]),dbe(w,g);const O=v.useSyncExternalStore(z=>o2(R,z),()=>JSON.stringify(N(R,w)),()=>JSON.stringify(N(R,w)));return f.jsx("div",{...x,"aria-disabled":s||void 0,"data-panel":!0,"data-testid":w,id:w,ref:k,style:{...fbe,display:"flex",flexBasis:0,flexShrink:1,overflow:"visible",...JSON.parse(O)},children:f.jsx("div",{className:t,style:{maxHeight:"100%",maxWidth:"100%",flexGrow:1,overflow:"auto",...b,touchAction:A==="horizontal"?"pan-y":"pan-x"},children:e})})}aF.displayName="Panel";const fbe={minHeight:0,maxHeight:"100%",height:"auto",minWidth:0,maxWidth:"100%",width:"auto",border:"none",borderWidth:0,padding:0,margin:0};function hbe({layout:e,panelConstraints:t,panelId:n,panelIndex:r}){let i,s;const o=e[n],l=t.find(c=>c.panelId===n);if(l){const c=l.maxSize,u=l.collapsible?l.collapsedSize:l.minSize,m=[r,r+1];s=Xc({layout:zm({delta:u-o,initialLayout:e,panelConstraints:t,pivotIndices:m,prevLayout:e}),panelConstraints:t})[n],i=Xc({layout:zm({delta:c-o,initialLayout:e,panelConstraints:t,pivotIndices:m,prevLayout:e}),panelConstraints:t})[n]}return{valueControls:n,valueMax:i,valueMin:s,valueNow:o}}function lF({children:e,className:t,disabled:n,elementRef:r,id:i,style:s,...o}){const l=u2(i),c=f2({disabled:n}),[u,m]=v.useState({}),[h,g]=v.useState("inactive"),b=v.useRef(null),x=d2(b,r),{disableCursor:_,id:w,orientation:C,registerSeparator:E,toggleSeparatorDisabled:k}=h2(),N=C==="horizontal"?"vertical":"horizontal";uu(()=>{const A=b.current;if(A!==null){const M={disabled:c.disabled,element:A,id:l},L=E(M),F=ebe(O=>{g(O.next.state!=="inactive"&&O.next.hitRegions.some(z=>z.separator===M)?O.next.state:"inactive")}),D=o2(w,O=>{const{derivedPanelConstraints:z,layout:P,separatorToPanels:$}=O.next,H=$.get(M);if(H){const B=H[0],V=H.indexOf(B);m(hbe({layout:P,panelConstraints:z,panelId:B.id,panelIndex:V}))}});return()=>{F(),D(),L()}}},[w,l,E,c]),v.useEffect(()=>{k(l,!!n)},[n,l,k]);let R;return n&&!_&&(R="not-allowed"),f.jsx("div",{...o,"aria-controls":u.valueControls,"aria-disabled":n||void 0,"aria-orientation":N,"aria-valuemax":u.valueMax,"aria-valuemin":u.valueMin,"aria-valuenow":u.valueNow,children:e,className:t,"data-separator":n?"disabled":h,"data-testid":l,id:l,ref:x,role:"separator",style:{flexBasis:"auto",cursor:R,...s,flexGrow:0,flexShrink:0,touchAction:"none"},tabIndex:n?void 0:0})}lF.displayName="Separator";const m2=({className:e,...t})=>f.jsx(oF,{className:he("flex h-full w-full",e),...t}),Bm=e=>f.jsx(aF,{...e}),p2=({withHandle:e,orientation:t,disabled:n,className:r,...i})=>f.jsx(lF,{disabled:n,className:he("relative flex items-center justify-center bg-transparent focus-visible:outline-none",t==="vertical"?"h-2 w-full -my-1 cursor-row-resize":"h-full w-2 -mx-1 cursor-col-resize",e&&(t==="vertical"?"before:absolute before:inset-x-0 before:top-1/2 before:h-0.5 before:-translate-y-1/2 before:bg-border":"before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-border"),r),...i,children:f.jsx("span",{className:"sr-only",children:t==="vertical"?"Resize rows":"Resize columns"})});function cF(e,t,n){const r=typeof e.maxTokens=="number"&&Number.isFinite(e.maxTokens)?e.maxTokens:null,i=r&&r>0?Math.min(100,e.usedTokens/r*100):null,s=r!==null?Math.max(0,Math.round(r-e.usedTokens)):null,o=i!==null?Math.max(0,100-i):null;return{...e,compactsAutomatically:e.compactsAutomatically||n,maxTokens:r??void 0,remainingTokens:s,usedPercentage:i,remainingPercentage:o,updatedAt:t}}function mbe(e){const t=e.some(n=>n.kind==="compact_boundary"||n.kind==="compact_summary"||n.kind==="context_cleared");for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&!(r.kind!=="context_window_updated"||r.usage.usedTokens<=0))return cF(r.usage,new Date(r.createdAt).toISOString(),t)}return null}function pbe(e,t){return!e||t===null||!Number.isFinite(t)||t<=0?e:cF({...e,maxTokens:t},e.updatedAt,e.compactsAutomatically)}function Nh(e){return e==null||!Number.isFinite(e)?"0":e<1e3?`${Math.round(e)}`:e<1e4?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:e<1e6?`${Math.round(e/1e3)}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}m`}const g2=[68,32];function gbe(){return{isVisible:!1,mainSizes:[...g2],terminals:[],nextTerminalIndex:0}}function vbe(e,t){return e[t]??gbe()}function eS(e){if(e.length===0)return[];const t=e.reduce((n,r)=>n+Math.max(r,0),0);return!Number.isFinite(t)||t<=0?Array.from({length:e.length},()=>100/e.length):e.map(n=>Math.max(n,0)/t*100)}function bbe(e){let t=e,n="";do n=String.fromCharCode(65+t%26)+n,t=Math.floor(t/26)-1;while(t>=0);return`Terminal ${n}`}function ybe(e){if(e.length===0)return e;const t=e.length+1;return e.map(n=>({...n,size:n.size*e.length/t}))}function ld(e,t,n){return{...e,[t]:n(vbe(e,t))}}const wl=oo()(bf(e=>({projects:{},addTerminal:(t,n)=>e(r=>({projects:ld(r.projects,t,i=>{var c,u;const s=ybe(i.terminals),o={id:((u=(c=globalThis.crypto)==null?void 0:c.randomUUID)==null?void 0:u.call(c))??`terminal-${Date.now()}-${i.nextTerminalIndex}`,title:bbe(i.nextTerminalIndex),size:100/(s.length+1)},l=n?Math.max(s.findIndex(m=>m.id===n)+1,0):s.length;return{...i,isVisible:!0,nextTerminalIndex:i.nextTerminalIndex+1,terminals:[...s.slice(0,l),o,...s.slice(l)]}})})),removeTerminal:(t,n)=>e(r=>({projects:ld(r.projects,t,i=>{const s=i.terminals.filter(l=>l.id!==n);if(s.length===0)return{...i,isVisible:!1,terminals:[]};const o=eS(s.map(l=>l.size));return{...i,terminals:s.map((l,c)=>({...l,size:o[c]??100/s.length}))}})})),toggleVisibility:t=>e(n=>({projects:ld(n.projects,t,r=>({...r,isVisible:r.terminals.length>0?!r.isVisible:!1}))})),resetMainSizes:t=>e(n=>({projects:ld(n.projects,t,r=>({...r,mainSizes:[...g2]}))})),setMainSizes:(t,n)=>e(r=>{if(n.length!==2)return r;const i=eS(n);return{projects:ld(r.projects,t,s=>({...s,mainSizes:i}))}}),setTerminalSizes:(t,n)=>e(r=>({projects:ld(r.projects,t,i=>{if(n.length!==i.terminals.length)return i;const s=eS(n);return{...i,terminals:i.terminals.map((o,l)=>({...o,size:s[l]??o.size}))}})})),clearProject:t=>e(n=>{const{[t]:r,...i}=n.projects;return{projects:i}})}),{name:"terminal-layouts",version:1})),xbe={isVisible:!1,mainSizes:[...g2],terminals:[],nextTerminalIndex:0},_be=35;function wbe(e,t){return!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0?0:e*(t/100)}function Sbe(e,t){const n=wbe(e,t);return n>=0&&n<_be}const x0=350,Cbe=[.4,0,.2,1],kbe=8,RD=1e-6;function Ebe(e,t,n){const r=1-e;return 3*r*r*e*t+3*r*e*e*n+e*e*e}function Tbe(e,t,n){const r=1-e;return 3*r*r*e*t+3*r*e*e*n+e*e*e}function Nbe(e,t,n){const r=1-e;return 3*r*r*t+6*r*e*(n-t)+3*e*e*(1-n)}function Rbe(e,t,n){let r=e;for(let i=0;i<kbe;i+=1){const s=Ebe(r,t,n)-e;if(Math.abs(s)<RD)return r;const o=Nbe(r,t,n);if(Math.abs(o)<RD)break;r-=s/o}return r}function Abe(e){if(e<=0)return 0;if(e>=1)return 1;const[t,n,r,i]=Cbe,s=Rbe(e,t,r);return Tbe(s,n,i)}function uF(e,t,n){const r=Abe(n);return[e[0]+(t[0]-e[0])*r,e[1]+(t[1]-e[1])*r]}function Mbe({projectId:e,shouldRenderRightSidebarLayout:t,showRightSidebar:n,rightSidebarSize:r}){const i=v.useRef(null),s=v.useRef(null),o=v.useRef(null),l=v.useRef(null),c=v.useRef(null),u=v.useRef(!1),m=v.useRef(null),h=v.useRef(!1),g=v.useRef(!1);return v.useEffect(()=>()=>{l.current!==null&&window.cancelAnimationFrame(l.current),c.current!==null&&window.clearTimeout(c.current)},[]),v.useLayoutEffect(()=>{var M,L,F,D,O,z;if(!t){l.current!==null&&(window.cancelAnimationFrame(l.current),l.current=null),c.current!==null&&(window.clearTimeout(c.current),c.current=null),u.current=!1;return}const b=i.current;if(!b)return;l.current!==null&&(window.cancelAnimationFrame(l.current),l.current=null),c.current!==null&&(window.clearTimeout(c.current),c.current=null);const x=m.current,_=x!==null&&x!==e,w=n&&!g.current,C=!h.current,E=n?[100-r,r]:[100,0],k=_||C&&n,N=w||C?[100,0]:[b.getLayout().workspace??E[0],b.getLayout().rightSidebar??E[1]];if(m.current=e,h.current=t,g.current=n,k||Math.abs(N[0]-E[0])<.1&&Math.abs(N[1]-E[1])<.1){b.setLayout({workspace:E[0],rightSidebar:E[1]}),(M=s.current)==null||M.setAttribute("data-right-sidebar-open",n?"true":"false"),(L=o.current)==null||L.setAttribute("data-right-sidebar-open",n?"true":"false"),(F=o.current)==null||F.setAttribute("data-right-sidebar-animated","false");return}u.current=!0,(D=s.current)==null||D.setAttribute("data-right-sidebar-open",n?"true":"false"),(O=o.current)==null||O.setAttribute("data-right-sidebar-open",n?"true":"false"),(z=o.current)==null||z.setAttribute("data-right-sidebar-animated","true"),b.setLayout({workspace:N[0],rightSidebar:N[1]});const R=performance.now(),A=P=>{const $=Math.min(1,(P-R)/x0),H=uF(N,E,$);if(b.setLayout({workspace:H[0],rightSidebar:H[1]}),$<1){l.current=window.requestAnimationFrame(A);return}b.setLayout({workspace:E[0],rightSidebar:E[1]}),l.current=null,c.current=window.setTimeout(()=>{u.current=!1,c.current=null},0)};l.current=window.requestAnimationFrame(A)},[e,r,t,n]),v.useEffect(()=>{t||(h.current=!1,g.current=!1)},[t]),{isAnimating:u,panelGroupRef:i,sidebarPanelRef:s,sidebarVisualRef:o}}function Lbe(e){return e.visibilityState==="visible"?e.activeChatId:null}function jbe(e){e.socket.setFocusedChat(Lbe({activeChatId:e.activeChatId,visibilityState:e.visibilityState}))}function Dbe({socket:e,activeChatId:t}){v.useEffect(()=>{if(typeof document>"u")return;const n=()=>{jbe({socket:e,activeChatId:t,visibilityState:document.visibilityState})};return n(),document.addEventListener("visibilitychange",n),window.addEventListener("pagehide",n),window.addEventListener("pageshow",n),()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("pagehide",n),window.removeEventListener("pageshow",n),e.setFocusedChat(null)}},[e,t])}function Ibe({rootRef:e,fallbackRef:t,enabled:n,canCancel:r}){v.useEffect(()=>{if(!n)return;let i=0,s=null;const o=h=>{const g=h instanceof Element?h:null,b=e.current,x=t.current;if(vM({trigger:"pointer",activeElement:document.activeElement,pointerStartTarget:s,pointerEndTarget:g,root:b,fallback:x,hasActiveOverlay:gM(document),hasActiveSelection:PY(window.getSelection())})!=="restore"){s=null;return}x==null||x.focus({preventScroll:!0}),s=null},l=h=>{cancelAnimationFrame(i),s=h.target instanceof Element?h.target:null},c=h=>{cancelAnimationFrame(i),i=window.requestAnimationFrame(()=>{o(h.target)})},u=()=>{s=null;const h=t.current;!h||h.disabled||h.focus({preventScroll:!0})},m=h=>{if(h.key!=="Escape")return;const g=t.current;vM({trigger:"escape",activeElement:document.activeElement,fallback:g,hasActiveOverlay:gM(document),canCancel:r,defaultPrevented:h.defaultPrevented})==="escape-focus"&&(h.preventDefault(),g==null||g.focus({preventScroll:!0}))};return window.addEventListener("pointerdown",l,!0),window.addEventListener("pointerup",c,!0),window.addEventListener("keydown",m,!0),window.addEventListener(kb,u),()=>{cancelAnimationFrame(i),window.removeEventListener("pointerdown",l,!0),window.removeEventListener("pointerup",c,!0),window.removeEventListener("keydown",m,!0),window.removeEventListener(kb,u)}},[r,n,t,e])}function Pbe(e){const t=e.previousProjectId!==null&&e.previousProjectId!==e.projectId,n=e.previousProjectId===null&&e.projectId!==null;return!t&&!n&&e.showTerminalPane&&!e.wasTerminalVisible}function Obe({previousProjectId:e,projectId:t,previousShouldRenderTerminalLayout:n,previousShowTerminalPane:r,showTerminalPane:i,terminalLayout:s,liveLayout:o}){const l=e!==null&&e!==t,c=i&&!r,u=!n,m=e===null&&t!==null,h=i?s.mainSizes:[100,0];return{currentLayout:c||u?[100,0]:o,shouldSkipAnimation:l||m&&u,targetLayout:h}}function zbe({chatInputRef:e,projectId:t,shouldRenderTerminalLayout:n,showTerminalPane:r,terminalLayout:i}){const s=v.useRef(null),o=v.useRef(null),l=v.useRef(null),c=v.useRef(null),u=v.useRef(null),m=v.useRef(!1),h=v.useRef(null),g=v.useRef(!1),b=v.useRef(!1),x=v.useRef(!1),[_,w]=v.useState(0);return v.useEffect(()=>{var k;const C=h.current,E=x.current;Pbe({previousProjectId:C,projectId:t,showTerminalPane:r,wasTerminalVisible:E})&&w(N=>N+1),C!==null&&C===t&&!r&&E&&((k=e.current)==null||k.focus({preventScroll:!0})),x.current=r,h.current=t},[e,t,r]),v.useEffect(()=>()=>{c.current!==null&&window.cancelAnimationFrame(c.current),u.current!==null&&window.clearTimeout(u.current)},[]),v.useLayoutEffect(()=>{var L,F,D,O,z,P;if(!n){c.current!==null&&(window.cancelAnimationFrame(c.current),c.current=null),u.current!==null&&(window.clearTimeout(u.current),u.current=null),m.current=!1;return}const C=s.current;if(!C)return;c.current!==null&&(window.cancelAnimationFrame(c.current),c.current=null),u.current!==null&&(window.clearTimeout(u.current),u.current=null);const E=h.current,{currentLayout:k,shouldSkipAnimation:N,targetLayout:R}=Obe({previousProjectId:E,projectId:t,previousShouldRenderTerminalLayout:g.current,previousShowTerminalPane:b.current,showTerminalPane:r,terminalLayout:i,liveLayout:[C.getLayout().chat??i.mainSizes[0],C.getLayout().terminal??i.mainSizes[1]]});if(g.current=n,b.current=r,N||Math.abs(k[0]-R[0])<.1&&Math.abs(k[1]-R[1])<.1){C.setLayout({chat:R[0],terminal:R[1]}),(L=o.current)==null||L.setAttribute("data-terminal-open",r?"true":"false"),(F=l.current)==null||F.setAttribute("data-terminal-open",r?"true":"false"),(D=l.current)==null||D.setAttribute("data-terminal-animated","false");return}m.current=!0,(O=o.current)==null||O.setAttribute("data-terminal-open",r?"true":"false"),(z=l.current)==null||z.setAttribute("data-terminal-open",r?"true":"false"),(P=l.current)==null||P.setAttribute("data-terminal-animated","true"),C.setLayout({chat:k[0],terminal:k[1]});const A=performance.now(),M=$=>{const H=Math.min(1,($-A)/x0),B=uF(k,R,H);if(C.setLayout({chat:B[0],terminal:B[1]}),H<1){c.current=window.requestAnimationFrame(M);return}C.setLayout({chat:R[0],terminal:R[1]}),c.current=null,u.current=window.setTimeout(()=>{m.current=!1,u.current=null},0)};c.current=window.requestAnimationFrame(M)},[t,n,r,i]),v.useEffect(()=>{n||(g.current=!1,b.current=!1)},[n]),{isAnimating:m,mainPanelGroupRef:s,terminalFocusRequestVersion:_,terminalPanelRef:o,terminalVisualRef:l}}const AD=e=>Symbol.iterator in e,MD=e=>"entries"in e,LD=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[i,s]of n)if(!r.has(i)||!Object.is(s,r.get(i)))return!1;return!0},Bbe=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let i=n.next(),s=r.next();for(;!i.done&&!s.done;){if(!Object.is(i.value,s.value))return!1;i=n.next(),s=r.next()}return!!i.done&&!!s.done};function Fbe(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:AD(e)&&AD(t)?MD(e)&&MD(t)?LD(e,t):Bbe(e,t):LD({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function jD(e){const t=Cn.useRef(void 0);return n=>{const r=e(n);return Fbe(t.current,r)?t.current:t.current=r}}const im="__new__";function wc(e){var s,o;const t=(s=e==null?void 0:e.modelOptions)==null?void 0:s.reasoningEffort,n=e1(t)?t:e1(e==null?void 0:e.effort)?e.effort:Vc.reasoningEffort,r=rne(e==null?void 0:e.model),i=oE(r,(o=e==null?void 0:e.modelOptions)==null?void 0:o.contextWindow);return{model:r,modelOptions:{reasoningEffort:!U4(r)&&n==="max"?"high":n,contextWindow:i},planMode:!!(e!=null&&e.planMode)}}function Tv(e){var n,r;const t=(n=e==null?void 0:e.modelOptions)==null?void 0:n.reasoningEffort;return{model:ine(e==null?void 0:e.model),modelOptions:{reasoningEffort:t1(t)?t:t1(e==null?void 0:e.effort)?e.effort:wm.reasoningEffort,fastMode:typeof((r=e==null?void 0:e.modelOptions)==null?void 0:r.fastMode)=="boolean"?e.modelOptions.fastMode:wm.fastMode},planMode:!!(e!=null&&e.planMode)}}function $be(){return{claude:{model:"claude-opus-4-7",modelOptions:{...Vc},planMode:!1},codex:{model:"gpt-5.5",modelOptions:{...wm},planMode:!1}}}function Hbe(e,t){return e.reasoningEffort===t.reasoningEffort&&e.contextWindow===t.contextWindow}function Ube(e,t){return e.reasoningEffort===t.reasoningEffort&&e.fastMode===t.fastMode}function Vbe(e,t){return e.claude.model===t.claude.model&&e.claude.planMode===t.claude.planMode&&Hbe(e.claude.modelOptions,t.claude.modelOptions)&&e.codex.model===t.codex.model&&e.codex.planMode===t.codex.planMode&&Ube(e.codex.modelOptions,t.codex.modelOptions)}function Wbe(e,t){if(t===void 0){console.info(`[chat-preferences] ${e}`);return}console.info(`[chat-preferences] ${e}`,t)}function sm(e,t){if(e==="claude"){const r=t.claude;return{provider:"claude",model:r.model,modelOptions:{...r.modelOptions},planMode:r.planMode}}const n=t.codex;return{provider:"codex",model:n.model,modelOptions:{...n.modelOptions},planMode:n.planMode}}function Z1(e){return e.provider==="claude"?{provider:"claude",model:e.model,modelOptions:{...e.modelOptions},planMode:e.planMode}:{provider:"codex",model:e.model,modelOptions:{...e.modelOptions},planMode:e.planMode}}function dF(e){return e.providerHint?sm(e.providerHint,e.providerDefaults):e.defaultProvider==="last_used"?e.sourceState?Z1(e.sourceState):sm("claude",e.providerDefaults):sm(e.defaultProvider,e.providerDefaults)}function fF(e,t){const n=e.chatStates[t];return n||dF({defaultProvider:e.defaultProvider,providerDefaults:e.providerDefaults,legacyComposerState:e.legacyComposerState})}function Nv(e,t,n){const r=fF(e,t);return{chatStates:{...e.chatStates,[t]:n(r)}}}const bi=oo()(bf((e,t)=>({defaultProvider:"last_used",providerDefaults:$be(),chatStates:{},legacyComposerState:{provider:"claude",model:"claude-opus-4-7",modelOptions:{...Vc},planMode:!1},setDefaultProvider:n=>e({defaultProvider:n}),applyServerDefaults:(n,r)=>e(i=>{if(i.defaultProvider===n&&Vbe(i.providerDefaults,r))return{defaultProvider:n,providerDefaults:r};const{[im]:o,...l}=i.chatStates;return{defaultProvider:n,providerDefaults:r,chatStates:l}}),setProviderDefaultModel:(n,r)=>e(i=>({providerDefaults:{...i.providerDefaults,[n]:n==="claude"?wc({...i.providerDefaults.claude,model:r}):Tv({...i.providerDefaults.codex,model:r})}})),setProviderDefaultModelOptions:(n,r)=>e(i=>({providerDefaults:{...i.providerDefaults,[n]:n==="claude"?wc({...i.providerDefaults.claude,modelOptions:{...i.providerDefaults.claude.modelOptions,...r}}):Tv({...i.providerDefaults.codex,modelOptions:{...i.providerDefaults.codex.modelOptions,...r}})}})),setProviderDefaultPlanMode:(n,r)=>e(i=>({providerDefaults:{...i.providerDefaults,[n]:{...i.providerDefaults[n],planMode:r}}})),getComposerState:n=>Z1(fF(t(),n)),initializeComposerForChat:(n,r)=>e(i=>{if(i.chatStates[n])return i;const s=dF({defaultProvider:i.defaultProvider,providerDefaults:i.providerDefaults,sourceState:r==null?void 0:r.sourceState,legacyComposerState:i.legacyComposerState,providerHint:r==null?void 0:r.providerHint});return Wbe("initializeComposerForChat",{chatId:n,composerState:s}),{chatStates:{...i.chatStates,[n]:s}}}),setComposerState:(n,r)=>e(i=>({chatStates:{...i.chatStates,[n]:r.provider==="claude"?{provider:"claude",model:wc(r).model,modelOptions:wc(r).modelOptions,planMode:r.planMode}:Z1(r)}})),setChatComposerProvider:(n,r)=>e(i=>Nv(i,n,()=>sm(r,i.providerDefaults))),setChatComposerModel:(n,r)=>e(i=>Nv(i,n,s=>s.provider==="claude"?{provider:"claude",model:wc({...s,model:r}).model,modelOptions:wc({...s,model:r}).modelOptions,planMode:s.planMode}:{provider:"codex",model:r,modelOptions:Tv({...s,model:r}).modelOptions,planMode:s.planMode})),setChatComposerModelOptions:(n,r)=>e(i=>Nv(i,n,s=>s.provider==="claude"?{provider:"claude",model:s.model,modelOptions:wc({...s,modelOptions:{...s.modelOptions,...r}}).modelOptions,planMode:s.planMode}:{provider:"codex",model:s.model,modelOptions:Tv({...s,modelOptions:{...s.modelOptions,...r}}).modelOptions,planMode:s.planMode})),setChatComposerPlanMode:(n,r)=>e(i=>Nv(i,n,s=>({...s,planMode:r}))),resetChatComposerFromProvider:(n,r)=>e(i=>({chatStates:{...i.chatStates,[n]:sm(r,i.providerDefaults)}}))}),{name:"chat-preferences-state",version:1,partialize:e=>({chatStates:e.chatStates,legacyComposerState:e.legacyComposerState})})),J1=oo()(bf((e,t)=>({drafts:{},attachmentDrafts:{},setDraft:(n,r)=>e(i=>{if(!r){const{[n]:s,...o}=i.drafts;return{drafts:o}}return{drafts:{...i.drafts,[n]:r}}}),clearDraft:n=>e(r=>{const{[n]:i,...s}=r.drafts;return{drafts:s}}),getDraft:n=>t().drafts[n]??"",setAttachmentDrafts:(n,r)=>e(i=>{if(r.length===0){const{[n]:s,...o}=i.attachmentDrafts;return{attachmentDrafts:o}}return{attachmentDrafts:{...i.attachmentDrafts,[n]:r}}}),clearAttachmentDrafts:n=>e(r=>{const{[n]:i,...s}=r.attachmentDrafts;return{attachmentDrafts:s}}),getAttachmentDrafts:n=>t().attachmentDrafts[n]??[]}),{name:"chat-input-drafts"})),v2=oo()(e=>({byChatId:{},loadingByChatId:{},setForChat:(t,n)=>e(r=>({byChatId:{...r.byChatId,[t]:n}})),setLoadingForChat:(t,n)=>e(r=>(r.loadingByChatId[t]??!1)===n?r:{loadingByChatId:{...r.loadingByChatId,[t]:n}}),clear:t=>e(n=>{const r=t in n.byChatId,i=t in n.loadingByChatId;if(!r&&!i)return n;const{[t]:s,...o}=n.byChatId,{[t]:l,...c}=n.loadingByChatId;return{byChatId:o,loadingByChatId:c}})}));function Gbe(e){return{autoResumeOnRateLimit:!!(e!=null&&e.autoResumeOnRateLimit)}}const eC=oo()(bf(e=>({autoResumeOnRateLimit:!1,setAutoResumeOnRateLimit:t=>e({autoResumeOnRateLimit:t})}),{name:"kanna-preferences",version:1,migrate:e=>Gbe(e)}));function qbe(e,t){var n,r,i,s,o,l,c,u,m;return{...e,...t,terminal:{...e.terminal,...t.terminal},editor:{...e.editor,...t.editor},providerDefaults:{claude:{...e.providerDefaults.claude,...(n=t.providerDefaults)==null?void 0:n.claude,modelOptions:{...e.providerDefaults.claude.modelOptions,...(i=(r=t.providerDefaults)==null?void 0:r.claude)==null?void 0:i.modelOptions}},codex:{...e.providerDefaults.codex,...(s=t.providerDefaults)==null?void 0:s.codex,modelOptions:{...e.providerDefaults.codex.modelOptions,...(l=(o=t.providerDefaults)==null?void 0:o.codex)==null?void 0:l.modelOptions}}},cloudflareTunnel:{...e.cloudflareTunnel,...t.cloudflareTunnel},claudeAuth:{tokens:((c=t.claudeAuth)==null?void 0:c.tokens)??e.claudeAuth.tokens},auth:{...e.auth,...t.auth},uploads:{...e.uploads,...t.uploads},subagents:e.subagents,claudeDriver:{preference:((u=t.claudeDriver)==null?void 0:u.preference)??e.claudeDriver.preference,lifecycle:{...e.claudeDriver.lifecycle,...(m=t.claudeDriver)==null?void 0:m.lifecycle}}}}const Qi=oo()(e=>({settings:null,hydrationStatus:"idle",setHydrationStatus:t=>e({hydrationStatus:t}),setFromServer:t=>e({settings:t,hydrationStatus:"ready"}),applyOptimisticPatch:t=>e(n=>({settings:n.settings?qbe(n.settings,t):n.settings}))})),hF=v.createContext(void 0),Kbe=e=>e==="light"||e==="dark"||e==="system";function Ybe(e){return e==="dark"?"black-translucent":"default"}function DD(e,t){if(typeof document>"u")return;let n=document.head.querySelector(`meta[name="${e}"]`);n||(n=document.createElement("meta"),n.setAttribute("name",e),document.head.appendChild(n)),n.setAttribute("content",t)}function ID(e){if(typeof document>"u"||typeof window>"u")return;const t=getComputedStyle(document.body).backgroundColor||getComputedStyle(document.documentElement).backgroundColor;t&&DD("theme-color",t),DD("apple-mobile-web-app-status-bar-style",Ybe(e)),document.documentElement.style.colorScheme=e}const lb=()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",PD=e=>{if(typeof document>"u")return;const t=e==="system"?lb():e;document.documentElement.classList.toggle("dark",t==="dark")},Xbe=()=>{var t;const e=(t=Qi.getState().settings)==null?void 0:t.theme;return e&&Kbe(e)?e:"system"};function Qbe({children:e}){const t=Qi(o=>{var l;return(l=o.settings)==null?void 0:l.theme}),n=Qi(o=>o.applyOptimisticPatch),[r,i]=v.useState(Xbe);v.useEffect(()=>{!t||t===r||i(t)},[t,r]),v.useEffect(()=>{PD(r)},[r]),v.useEffect(()=>{const o=r==="system"?lb():r;ID(o)},[r]),v.useEffect(()=>{if(r!=="system")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),l=()=>{PD("system"),ID(lb())};return o.addEventListener?(o.addEventListener("change",l),()=>o.removeEventListener("change",l)):(o.addListener(l),()=>o.removeListener(l))},[r]);const s=v.useMemo(()=>{const o=r==="system"?lb():r;return{theme:r,resolvedTheme:o,setTheme:l=>{i(l),n({theme:l})}}},[n,r]);return f.jsx(hF.Provider,{value:s,children:e})}function b2(){const e=v.useContext(hF);if(!e)throw new Error("useTheme must be used within ThemeProvider");return e}function cd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function OD(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function Zbe(e){const t=e&&typeof e=="object"&&"content"in e&&Array.isArray(e.content)?e.content:Array.isArray(e)?e:[],n=[];for(const r of t)if(!(!r||typeof r!="object"||!("type"in r))){if(r.type==="text"&&typeof r.text=="string"){n.push({type:"text",text:r.text});continue}if(r.type==="image"){if("data"in r&&typeof r.data=="string"){n.push({type:"image",data:r.data,mimeType:typeof r.mimeType=="string"?r.mimeType:void 0});continue}"source"in r&&r.source&&typeof r.source=="object"&&"type"in r.source&&r.source.type==="base64"&&"data"in r.source&&typeof r.source.data=="string"&&n.push({type:"image",data:r.source.data,mimeType:typeof r.source.media_type=="string"?r.source.media_type:void 0})}}return n}function Jbe(e){const t=e&&typeof e=="object"&&"content"in e&&Array.isArray(e.content)?e.content:Array.isArray(e)?e:null;if(!t)return null;const n=[];for(const r of t)r&&typeof r=="object"&&"type"in r&&r.type==="text"&&typeof r.text=="string"&&n.push(r.text);return n.length>0?n.join(""):null}function eye(e,t){const n=OD(t);switch(e.toolKind){case"ask_user_question":{const s=cd(n),o=cd(s==null?void 0:s.answers)??(s||{});return{answers:Object.fromEntries(Object.entries(o).map(([l,c])=>Array.isArray(c)?[l,c.map(u=>String(u))]:c&&typeof c=="object"&&Array.isArray(c.answers)?[l,c.answers.map(u=>String(u))]:c==null||c===""?[l,[]]:[l,[String(c)]])),...(s==null?void 0:s.discarded)===!0?{discarded:!0}:{}}}case"exit_plan_mode":{const s=cd(n);return{confirmed:typeof(s==null?void 0:s.confirmed)=="boolean"?s.confirmed:void 0,clearContext:typeof(s==null?void 0:s.clearContext)=="boolean"?s.clearContext:void 0,message:typeof(s==null?void 0:s.message)=="string"?s.message:void 0,...(s==null?void 0:s.discarded)===!0?{discarded:!0}:{}}}case"offer_download":{const s=Jbe(n),o=s?OD(s):n,l=cd(o);return{contentUrl:typeof(l==null?void 0:l.contentUrl)=="string"?l.contentUrl:"",relativePath:typeof(l==null?void 0:l.relativePath)=="string"?l.relativePath:"",fileName:typeof(l==null?void 0:l.fileName)=="string"?l.fileName:"",displayName:typeof(l==null?void 0:l.displayName)=="string"?l.displayName:typeof(l==null?void 0:l.fileName)=="string"?l.fileName:"",size:typeof(l==null?void 0:l.size)=="number"?l.size:0,...typeof(l==null?void 0:l.mimeType)=="string"?{mimeType:l.mimeType}:{}}}case"image_generation":{const s=cd(n);return{contentUrl:typeof(s==null?void 0:s.contentUrl)=="string"?s.contentUrl:"",relativePath:typeof(s==null?void 0:s.relativePath)=="string"?s.relativePath:"",fileName:typeof(s==null?void 0:s.fileName)=="string"?s.fileName:""}}case"read_file":if(typeof n=="string")return n;const r=Zbe(n);if(r.length>0)return{content:r.flatMap(s=>s.type==="text"?[s.text]:[]).join(""),blocks:r};const i=cd(n);return{content:typeof(i==null?void 0:i.content)=="string"?i.content:JSON.stringify(n,null,2)};default:return n}}function mF(e){return new Date(e).toISOString()}function Ai(e){return{id:e._id,messageId:e.messageId,timestamp:mF(e.createdAt),hidden:e.hidden}}function tye(e){return{id:e._id,messageId:e.messageId,hidden:e.hidden,kind:"tool",toolKind:e.tool.toolKind,toolName:e.tool.toolName,toolId:e.tool.toolId,input:e.tool.input,timestamp:mF(e.createdAt)}}function nye(e){if(e.debugRaw)try{return JSON.parse(e.debugRaw).tool_use_result}catch{return}}function pF(e){const t=new Map,n=[];for(const r of e)switch(r.kind){case"user_prompt":n.push({...Ai(r),kind:"user_prompt",content:r.content,attachments:r.attachments??[],steered:r.steered,autoContinue:r.autoContinue});break;case"system_init":n.push({...Ai(r),kind:"system_init",provider:r.provider,model:r.model,tools:r.tools,agents:r.agents,slashCommands:r.slashCommands,mcpServers:r.mcpServers,debugRaw:r.debugRaw});break;case"account_info":n.push({...Ai(r),kind:"account_info",accountInfo:r.accountInfo});break;case"assistant_text":n.push({...Ai(r),kind:"assistant_text",text:r.text});break;case"tool_call":{const i=tye(r);t.set(r.tool.toolId,{hydrated:i,normalized:r.tool}),n.push(i);break}case"tool_result":{const i=t.get(r.toolId);if(i){const s=i.normalized.toolKind==="ask_user_question"||i.normalized.toolKind==="exit_plan_mode"?nye(r)??r.content:r.content;i.hydrated.result=eye(i.normalized,s),i.hydrated.rawResult=s,i.hydrated.isError=r.isError,r.persisted&&(i.hydrated.persisted=r.persisted)}break}case"result":n.push({...Ai(r),kind:"result",success:!r.isError,cancelled:r.subtype==="cancelled",result:r.result,durationMs:r.durationMs,costUsd:r.costUsd});break;case"status":n.push({...Ai(r),kind:"status",status:r.status});break;case"context_window_updated":n.push({...Ai(r),kind:"context_window_updated",usage:r.usage});break;case"compact_boundary":n.push({...Ai(r),kind:"compact_boundary"});break;case"compact_summary":n.push({...Ai(r),kind:"compact_summary",summary:r.summary});break;case"context_cleared":n.push({...Ai(r),kind:"context_cleared"});break;case"interrupted":n.push({...Ai(r),kind:"interrupted"});break;case"auto_continue_prompt":n.push({...Ai(r),kind:"auto_continue_prompt",scheduleId:r.scheduleId});break;case"pending_tool_request":n.push({...Ai(r),kind:"pending_tool_request",toolRequestId:r.toolRequestId,toolName:r.toolName,arguments:r.arguments});break;case"tool_request_resolved":break;default:n.push({...Ai(r),kind:"unknown",json:JSON.stringify(r,null,2)});break}return n}const rye=["AskUserQuestion","ExitPlanMode","TodoWrite"],iye=new Set(["TodoWrite"]);function sye(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r.kind!=="tool")continue;const i=r;if(i.toolName===t&&!i.result)return i.id}return null}function oye(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r.kind!=="tool")continue;const i=r;if(i.toolName===t)return i.id}return null}function aye(e){const t={};for(const n of rye)t[n]=iye.has(n)?oye(e,n):sye(e,n);return t}function lye(e){return e==="starting"||e==="running"||e==="waiting_for_user"}function cye(e){return e==="starting"||e==="running"||e==="waiting_for_user"}const y2="pushDeviceId";function gF(){return typeof localStorage>"u"?null:localStorage.getItem(y2)}function uye(e){typeof localStorage>"u"||localStorage.setItem(y2,e)}function dye(){typeof localStorage>"u"||localStorage.removeItem(y2)}function fye(){return!(typeof window>"u"||typeof Notification>"u"||!("serviceWorker"in navigator)||typeof globalThis.PushManager>"u")}function hye(){var t;if(typeof window>"u")return!1;if(window.isSecureContext)return!0;const e=((t=window.location)==null?void 0:t.hostname)??"";return e==="localhost"||e==="127.0.0.1"||e==="::1"}function tC(){if(!fye())return{state:"unsupported"};if(!hye())return{state:"insecure-context"};switch(Notification.permission){case"granted":return{state:"granted"};case"denied":return{state:"denied"};default:return{state:"default"}}}function mye(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64url"));const t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/-/g,"+").replace(/_/g,"/"),r=atob(n),i=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)i[s]=r.charCodeAt(s);return i}function pye(e){const t=e||"";return/iPhone|iPad/i.test(t)?"iPhone / iPad":/Android/i.test(t)?"Android":/Macintosh/i.test(t)?"Mac":/Windows/i.test(t)?"Windows PC":t||"Browser"}async function gye(e){const t=tC();if(t.state==="unsupported")throw new Error("Push not supported in this browser");if(t.state==="insecure-context")throw new Error("Push requires a secure context (HTTPS)");if(t.state==="denied")throw new Error("Notification permission previously denied");if(await Notification.requestPermission()!=="granted")throw new Error("Notification permission was not granted");const r=await navigator.serviceWorker.register("/sw.js");await navigator.serviceWorker.ready;const i=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:mye(e.vapidPublicKey)}),s=i.toJSON(),o=s.endpoint??i.endpoint,l=s.keys??{};if(!o||!l.p256dh||!l.auth)throw new Error("Subscription returned without endpoint or keys");const c=navigator.userAgent??"",{id:u}=await e.sendToServer({subscription:{endpoint:o,keys:{p256dh:l.p256dh,auth:l.auth}},label:pye(c),userAgent:c});return u}async function vye(e){const n=await(await navigator.serviceWorker.ready).pushManager.getSubscription();n&&await n.unsubscribe(),await e.sendToServer(e.pushDeviceId)}typeof navigator<"u"&&"serviceWorker"in navigator&&navigator.serviceWorker.addEventListener("message",e=>{const t=e.data;(t==null?void 0:t.type)==="kanna.navigate"&&typeof t.url=="string"&&(window.location.href=t.url)});const bye=25e3,yye=15e3,xye=4e3,zD="kanna:profile-send-to-starting";function BD(){try{return window.sessionStorage.getItem(zD)==="1"||window.localStorage.getItem(zD)==="1"}catch{return!1}}class _ye{constructor(t){re(this,"url");re(this,"ws",null);re(this,"started",!1);re(this,"reconnectTimer",null);re(this,"reconnectDelayMs",750);re(this,"subscriptions",new Map);re(this,"pending",new Map);re(this,"outboundQueue",[]);re(this,"statusListeners",new Set);re(this,"heartbeatTimer",null);re(this,"pingTimeoutTimer",null);re(this,"pingPromise",null);re(this,"lastOpenAt",0);re(this,"lastMessageAt",0);re(this,"reconnectImmediatelyOnClose",!1);re(this,"handleWindowFocus",()=>{this.ensureHealthyConnection()});re(this,"handleVisibilityChange",()=>{if(document.visibilityState==="visible"){this.startHeartbeat(),this.ensureHealthyConnection();return}this.stopHeartbeat()});re(this,"handleOnline",()=>{this.ensureHealthyConnection()});this.url=t}start(){this.started||(this.started=!0,window.addEventListener("focus",this.handleWindowFocus),window.addEventListener("online",this.handleOnline),document.addEventListener("visibilitychange",this.handleVisibilityChange),this.connect())}dispose(){var t;this.started=!1,this.reconnectTimer&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopHeartbeat(),this.clearPingState(),window.removeEventListener("focus",this.handleWindowFocus),window.removeEventListener("online",this.handleOnline),document.removeEventListener("visibilitychange",this.handleVisibilityChange),(t=this.ws)==null||t.close(),this.ws=null;for(const n of this.pending.values())n.reject(new Error("Socket disposed"));this.pending.clear()}onStatus(t){return this.statusListeners.add(t),t(this.getStatus()),()=>{this.statusListeners.delete(t)}}subscribe(t,n,r){const i=Tc();return this.subscriptions.set(i,{topic:t,listener:n,eventListener:r}),this.enqueue({v:1,type:"subscribe",id:i,topic:t}),()=>{this.subscriptions.delete(i),this.enqueue({v:1,type:"unsubscribe",id:i})}}subscribeTerminal(t,n){const r=Tc(),i={type:"terminal",terminalId:t};return this.subscriptions.set(r,{topic:i,listener:n.onSnapshot,eventListener:n.onEvent}),this.enqueue({v:1,type:"subscribe",id:r,topic:i}),()=>{this.subscriptions.delete(r),this.enqueue({v:1,type:"unsubscribe",id:r})}}command(t){const n=Tc(),r={v:1,type:"command",id:n,command:t};return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),this.enqueue(r)})}setFocusedChat(t){const n=Tc();this.enqueue({v:1,type:"command",id:n,command:{type:"push.setFocusedChat",chatId:t}})}ensureHealthyConnection(){return!this.ws||this.ws.readyState===WebSocket.CLOSED||this.ws.readyState===WebSocket.CLOSING?(this.reconnectNow(),Promise.resolve()):this.ws.readyState===WebSocket.CONNECTING||!this.isConnectionStale()?Promise.resolve():this.sendPing()}connect(){this.started&&(this.emitStatus("connecting"),this.ws=new WebSocket(this.url),this.ws.addEventListener("open",()=>{this.reconnectDelayMs=750,this.reconnectImmediatelyOnClose=!1,this.lastOpenAt=Date.now(),this.lastMessageAt=this.lastOpenAt,this.emitStatus("connected"),this.startHeartbeat();for(const[n,r]of this.subscriptions.entries())this.sendNow({v:1,type:"subscribe",id:n,topic:r.topic});for(;this.outboundQueue.length>0;){const n=this.outboundQueue.shift();n&&this.sendNow(n)}const t=gF();t&&this.sendNow({v:1,type:"command",id:Tc(),command:{type:"push.identifyDevice",pushDeviceId:t}})}),this.ws.addEventListener("message",t=>{var s,o;this.lastMessageAt=Date.now();const n=performance.now(),r=String(t.data);let i;try{i=JSON.parse(r)}catch{return}if(BD()&&i.type==="snapshot"&&i.snapshot.type==="chat"&&((s=i.snapshot.data)==null?void 0:s.runtime.status)==="starting"&&console.debug("[kanna/send->starting][client-ws]",{stage:"socket_message_received",receivedAt:n,payloadBytes:r.length,chatId:i.snapshot.data.runtime.chatId,status:i.snapshot.data.runtime.status,messageCount:i.snapshot.data.messages.length}),BD()&&i.type==="ack"&&console.debug("[kanna/send->starting][client-ws]",{stage:"socket_ack_received",receivedAt:n,payloadBytes:r.length,commandId:i.id}),i.type==="snapshot"){const l=this.subscriptions.get(i.id);l==null||l.listener(i.snapshot.data);return}if(i.type==="event"){const l=this.subscriptions.get(i.id);(o=l==null?void 0:l.eventListener)==null||o.call(l,i.event);return}if(i.type==="ack"){const l=this.pending.get(i.id);if(!l)return;this.pending.delete(i.id),l.resolve(i.result);return}if(i.type==="error"){if(!i.id){console.error(zQ,i.message);return}const l=this.pending.get(i.id);if(!l)return;this.pending.delete(i.id),l.reject(new Error(i.message))}}),this.ws.addEventListener("close",()=>{if(!this.started)return;const t=this.reconnectImmediatelyOnClose;this.reconnectImmediatelyOnClose=!1,this.stopHeartbeat(),this.clearPingState(),this.emitStatus("disconnected");for(const n of this.pending.values())n.reject(new Error("Disconnected"));if(this.pending.clear(),t){this.connect();return}this.scheduleReconnect()}))}scheduleReconnect(){this.reconnectTimer===null&&(this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.connect(),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,5e3)},this.reconnectDelayMs))}getStatus(){var t,n;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?"connected":((n=this.ws)==null?void 0:n.readyState)===WebSocket.CONNECTING?"connecting":"disconnected"}emitStatus(t){for(const n of this.statusListeners)n(t)}isConnectionStale(){const t=Math.max(this.lastMessageAt,this.lastOpenAt);return t>0&&Date.now()-t>=bye}sendPing(){if(this.pingPromise)return this.pingPromise;const t=this.command({type:"system.ping"}).then(()=>{this.clearPingState()}).catch(n=>{throw this.clearPingState(),this.reconnectNow(),n});return this.pingTimeoutTimer=window.setTimeout(()=>{this.clearPingState(),this.reconnectNow()},xye),this.pingPromise=t,t}reconnectNow(){if(this.reconnectTimer!==null&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),!this.ws||this.ws.readyState===WebSocket.CLOSED){this.connect();return}this.ws.readyState!==WebSocket.CONNECTING&&(this.reconnectImmediatelyOnClose=!0,this.ws.close())}startHeartbeat(){document.visibilityState==="visible"&&this.heartbeatTimer===null&&(this.heartbeatTimer=window.setInterval(()=>{var t;if(document.visibilityState!=="visible"){this.stopHeartbeat();return}((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ensureHealthyConnection()},yye))}stopHeartbeat(){this.heartbeatTimer!==null&&(window.clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}clearPingState(){this.pingTimeoutTimer!==null&&(window.clearTimeout(this.pingTimeoutTimer),this.pingTimeoutTimer=null),this.pingPromise=null}enqueue(t){var n;if(((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN){this.sendNow(t);return}this.outboundQueue.push(t)}sendNow(t){var n;(n=this.ws)==null||n.send(JSON.stringify(t))}}async function wye(e){const{toast:t}=await K(async()=>{const{toast:r}=await import("./index-f0nvAfAu.js");return{toast:r}},[]);t(`${e} ${e===1?"process":"processes"} survived restart`,{description:"Review and stop them in Background tasks (⌘⇧B).",action:{label:"Review",onClick:()=>Ys.getState().openDialog()}})}function Sye(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const r of n)if(e[r]!==t[r])return!1;return!0}function Cye(e,t){return e===t?!0:!e||!t?!1:e.chatId===t.chatId&&e.projectId===t.projectId&&e.localPath===t.localPath&&e.title===t.title&&e.status===t.status&&e.isDraining===t.isDraining&&e.provider===t.provider&&e.planMode===t.planMode&&Sye(e.sessionTokensByProvider,t.sessionTokensByProvider)}function kye(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>{var i;return n._id===((i=t[r])==null?void 0:i._id)})}function Eye(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>{var i;return n.id===((i=t[r])==null?void 0:i.id)})}function Tye(e,t){return e===t?!0:!e||!t?!1:e.hasOlder===t.hasOlder&&e.olderCursor===t.olderCursor&&e.recentLimit===t.recentLimit}function Nye(e,t){return e.id===t.id&&e.content===t.content&&e.createdAt===t.createdAt&&e.provider===t.provider&&e.model===t.model&&e.planMode===t.planMode&&JSON.stringify(e.modelOptions)===JSON.stringify(t.modelOptions)&&Rye(e.attachments,t.attachments)}function Rye(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return!!i&&n.id===i.id&&n.kind===i.kind&&n.displayName===i.displayName&&n.absolutePath===i.absolutePath&&n.relativePath===i.relativePath&&n.contentUrl===i.contentUrl&&n.mimeType===i.mimeType&&n.size===i.size})}function Aye(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>Nye(n,t[r]))}function Mye(e,t){var s,o;if(e===t)return!0;if(!e||!t||e.status!==t.status||e.branchName!==t.branchName||e.defaultBranchName!==t.defaultBranchName||e.hasOriginRemote!==t.hasOriginRemote||e.originRepoSlug!==t.originRepoSlug||e.hasUpstream!==t.hasUpstream||e.aheadCount!==t.aheadCount||e.behindCount!==t.behindCount||e.lastFetchedAt!==t.lastFetchedAt)return!1;const n=((s=e.branchHistory)==null?void 0:s.entries)??[],r=((o=t.branchHistory)==null?void 0:o.entries)??[];return n.length!==r.length||!n.every((l,c)=>{const u=r[c];return!!u&&l.sha===u.sha&&l.summary===u.summary&&l.description===u.description&&l.authorName===u.authorName&&l.authoredAt===u.authoredAt&&l.githubUrl===u.githubUrl&&l.tags.length===u.tags.length&&l.tags.every((m,h)=>m===u.tags[h])})||e.files.length!==t.files.length?!1:e.files.every((l,c)=>{const u=t.files[c];return!!u&&l.path===u.path&&l.changeType===u.changeType&&l.isUntracked===u.isUntracked&&l.additions===u.additions&&l.deletions===u.deletions&&l.patchDigest===u.patchDigest&&l.mimeType===u.mimeType&&l.size===u.size})}function Lye(e,t){return!!(e&&e.status!=="unknown"&&t&&t.status==="unknown"&&t.files.length===0)}function jye(e,t){if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(i=>{const s=e[i],o=t[i];return!s||!o?!1:s.state===o.state&&s.scheduledAt===o.scheduledAt&&s.resetAt===o.resetAt&&s.detectedAt===o.detectedAt&&s.tz===o.tz})}function Dye(e,t){if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(i=>{const s=e[i],o=t[i];return!s||!o?!1:s.state===o.state&&s.url===o.url&&s.error===o.error&&s.port===o.port&&s.activatedAt===o.activatedAt&&s.stoppedAt===o.stoppedAt})}function Iye(e,t){return e===t?!0:!e||!t?!1:Cye(e.runtime,t.runtime)&&Aye(e.queuedMessages,t.queuedMessages)&&kye(e.messages,t.messages)&&Tye(e.history,t.history)&&Eye(e.availableProviders,t.availableProviders)&&jye(e.schedules,t.schedules)&&e.liveScheduleId===t.liveScheduleId&&Dye(e.tunnels,t.tunnels)&&e.liveTunnelId===t.liveTunnelId}function FD(e,t){const n=new Map;for(const r of e)n.set(r._id,r);for(const r of t)n.set(r._id,r);return[...n.values()]}function Pye(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if((n==null?void 0:n.kind)==="user_prompt"&&n.content.trim().length>0)return n.content}return null}const $D="__new_chat__",vF="lever-theme",bF="chat-sound-preferences",yF="terminal-preferences",xF="chat-preferences";function tS(e){if(typeof window>"u")return null;const t=window.localStorage.getItem(e);if(!t)return null;try{const n=JSON.parse(t);return n.state&&typeof n.state=="object"&&!Array.isArray(n.state)?n.state:null}catch{return null}}function Oye(){if(typeof window>"u")return null;const e={},t=window.localStorage.getItem(vF);(t==="light"||t==="dark"||t==="system")&&(e.theme=t);const n=tS(bF);((n==null?void 0:n.chatSoundPreference)==="never"||(n==null?void 0:n.chatSoundPreference)==="unfocused"||(n==null?void 0:n.chatSoundPreference)==="always")&&(e.chatSoundPreference=n.chatSoundPreference),((n==null?void 0:n.chatSoundId)==="blow"||(n==null?void 0:n.chatSoundId)==="bottle"||(n==null?void 0:n.chatSoundId)==="frog"||(n==null?void 0:n.chatSoundId)==="funk"||(n==null?void 0:n.chatSoundId)==="glass"||(n==null?void 0:n.chatSoundId)==="ping"||(n==null?void 0:n.chatSoundId)==="pop"||(n==null?void 0:n.chatSoundId)==="purr"||(n==null?void 0:n.chatSoundId)==="tink")&&(e.chatSoundId=n.chatSoundId);const r=tS(yF);if(r){e.terminal={},typeof r.scrollbackLines=="number"&&(e.terminal.scrollbackLines=r.scrollbackLines),typeof r.minColumnWidth=="number"&&(e.terminal.minColumnWidth=r.minColumnWidth);const s={};(r.editorPreset==="cursor"||r.editorPreset==="vscode"||r.editorPreset==="xcode"||r.editorPreset==="windsurf"||r.editorPreset==="custom")&&(s.preset=r.editorPreset),typeof r.editorCommandTemplate=="string"&&(s.commandTemplate=r.editorCommandTemplate),Object.keys(s).length>0&&(e.editor=s)}const i=tS(xF);return((i==null?void 0:i.defaultProvider)==="last_used"||(i==null?void 0:i.defaultProvider)==="claude"||(i==null?void 0:i.defaultProvider)==="codex")&&(e.defaultProvider=i.defaultProvider),i!=null&&i.providerDefaults&&typeof i.providerDefaults=="object"&&(e.providerDefaults=i.providerDefaults),e.browserSettingsMigrated=!0,Object.keys(e).length>1?e:null}function zye(){typeof window>"u"||(window.localStorage.removeItem(vF),window.localStorage.removeItem(bF),window.localStorage.removeItem(yF),window.localStorage.removeItem(xF))}function Rh(e){Qi.getState().setFromServer(e);const t=pi.getState();t.setScrollbackLines(e.terminal.scrollbackLines),t.setMinColumnWidth(e.terminal.minColumnWidth),t.setEditorPreset(e.editor.preset),t.setEditorCommandTemplate(e.editor.commandTemplate);const n=Mc.getState();n.setChatSoundPreference(e.chatSoundPreference),n.setChatSoundId(e.chatSoundId),bi.getState().applyServerDefaults(e.defaultProvider,e.providerDefaults)}function Bye(e){return JSON.stringify({id:e.id,kind:e.kind,displayName:e.displayName,relativePath:e.relativePath,mimeType:e.mimeType,size:e.size,contentUrl:e.contentUrl})}function x2(e,t=[]){return JSON.stringify({content:e,attachments:t.map(Bye)})}function Fye(e,t){return e.reduce((n,r)=>r.kind!=="user_prompt"?n:n+(x2(r.content,r.attachments??[])===t?1:0),0)}function $ye(e,t,n){const r=new Map;for(const i of n){if(i.kind!=="user_prompt")continue;const s=x2(i.content,i.attachments??[]);r.set(s,(r.get(s)??0)+1)}return e.filter(i=>i.scopeId!==t?!0:(r.get(i.signature)??0)<i.requiredMatchCount)}function Hye(e,t,n){return e.some(r=>r.id===t)?e.filter(r=>r.id!==t):e}const Uye=200,Vye=500;function HD(e,t){var r;const n=e.find(i=>i.chats.some(s=>s.chatId===t));return n?((r=n.chats.find(i=>i.chatId!==t))==null?void 0:r.chatId)??null:null}function UD(e,t){if(!(t!=null&&t.length)||e.length<=1)return e;const n=new Map(e.map((o,l)=>[o.groupKey,l])),r=new Set,i=t.map(o=>{if(r.has(o))return null;r.add(o);const l=n.get(o);return l===void 0?null:e[l]}).filter(o=>!!o);if(i.length===0)return e;const s=[...i,...e.filter(o=>!r.has(o.groupKey))];return s.every((o,l)=>o===e[l])?e:s}function Wye(e=document){return e.visibilityState==="visible"&&e.hasFocus()}function Gye(){return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`}function qye(){const[e]=v.useState(()=>new _ye(Gye()));return v.useEffect(()=>(e.start(),()=>{e.dispose()}),[e]),e}const VD="kanna:profile-send-to-starting";function Kye(){try{return window.sessionStorage.getItem(VD)==="1"||window.localStorage.getItem(VD)==="1"}catch{return!1}}function _F(e){return Number((performance.now()-e).toFixed(1))}function pl(e,t,n){!e||!Kye()||console.debug("[kanna/send->starting][client]",{traceId:e.traceId,stage:t,elapsedMs:_F(e.startedAt),serverChatId:e.serverChatId,routeChatIdAtSend:e.routeChatIdAtSend,...n})}function Yye(e){var t,n;return(e==null?void 0:e.provider)==="claude"&&e.model&&((t=e.modelOptions)!=null&&t.claude)?{provider:"claude",model:e.model,modelOptions:{reasoningEffort:e.modelOptions.claude.reasoningEffort??"high",contextWindow:e.modelOptions.claude.contextWindow??"200k"},planMode:!!e.planMode}:(e==null?void 0:e.provider)==="codex"&&e.model&&((n=e.modelOptions)!=null&&n.codex)?{provider:"codex",model:e.model,modelOptions:{reasoningEffort:e.modelOptions.codex.reasoningEffort??"high",fastMode:e.modelOptions.codex.fastMode??!1},planMode:!!e.planMode}:null}function Xye(e,t){var n;return t?((n=e.find(r=>r.chats.some(i=>i.chatId===t)))==null?void 0:n.groupKey)??null:null}function Qye(e,t){return e==="awaiting_disconnect"&&t==="disconnected"?"awaiting_server_ready":"none"}function Zye(e,t){return t==="updating"||t==="restart_pending"?{active:!0,label:"Installing update"}:e==="awaiting_disconnect"||e==="awaiting_server_ready"?{active:!0,label:"Re-deploying Kanna"}:{active:!1,label:""}}const Jye=30,_2="kanna:ui-update-restart",wF="kanna:last-update-reload-request";function e0e(e){return e+Jye}function t0e(e,t){return t>0?t:e}function nS(){return window.sessionStorage.getItem(_2)}function n0e(e){window.sessionStorage.setItem(_2,e)}function r0e(){window.sessionStorage.removeItem(_2)}function i0e(e,t){return e?String(e)!==t:!1}function s0e(){return window.sessionStorage.getItem(wF)}function o0e(e){window.sessionStorage.setItem(wF,String(e))}function a0e(){return"/auth/status"}function l0e(e,t,n="application/json"){const r=new Blob([t],{type:`${n}; charset=utf-8`}),i=URL.createObjectURL(r),s=document.createElement("a");s.href=i,s.download=e,s.style.display="none",document.body.append(s),s.click(),s.remove(),URL.revokeObjectURL(i)}async function c0e(e=fetch){return(await e(a0e(),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}})).ok}function u0e(e){const t=e.selectedProjectId??e.sidebarProjectId??null;return t?{kind:"project_id",projectId:t}:e.fallbackLocalProjectPath?{kind:"local_path",localPath:e.fallbackLocalProjectPath}:null}function d0e(e,t){return!e||!t?null:e.runtime.chatId!==t?(e.runtime.chatId,e.runtime.provider,null):e}function f0e(e){var yu,xu,Ha;const t=ef(),n=qye(),r=rp(),{resolvedTheme:i}=b2(),[s,o]=v.useState({starredProjectGroups:[],projectGroups:[],stacks:[]}),[l,c]=v.useState(null),[u,m]=v.useState(null),[h,g]=v.useState(null),[b,x]=v.useState(()=>nS()),_=v.useCallback(Y=>{n0e(Y),x(Y)},[]),w=v.useCallback(()=>{r0e(),x(null)},[]),[C,E]=v.useState(null),[k,N]=v.useState([]),[R,A]=v.useState(!1),[M,L]=v.useState(null),[F,D]=v.useState(!1),[O,z]=v.useState({}),[P,$]=v.useState(null),[H,B]=v.useState(null),[V,G]=v.useState(null),[Q,I]=v.useState(null),[W,te]=v.useState("connecting"),[U,fe]=v.useState(!1),[ae,ee]=v.useState(!1),[ne,se]=v.useState(!1),[le,ue]=v.useState(null),[Ae,ce]=v.useState(!1),[De,Ke]=v.useState(!1),[ht,Tt]=v.useState(!1),[qt,Se]=v.useState(null),[Rt,Et]=v.useState(!1),[dt,Bt]=v.useState(null),[Ut,pt]=v.useState(!1),[ln,me]=v.useState(null),[Ce,$e]=v.useState(null),[et,Ee]=v.useState([]),[Pe,Ze]=v.useState(null),[Ye,Ge]=v.useState(0),ft=v.useRef(new Map),st=J1(jD(Y=>Object.keys(Y.drafts).sort())),Vt=J1(jD(Y=>Object.keys(Y.attachmentDrafts).sort())),sn=v.useRef(0),pn=v.useRef(null),dn=v.useRef({projectId:null,diffs:null}),At=Sne(pi(Y=>Y.editorPreset)),Je=v.useMemo(()=>UD(s.projectGroups,l),[l,s.projectGroups]),St=v.useRef(Je);v.useLayoutEffect(()=>{St.current=Je});const xt=v.useMemo(()=>Je===s.projectGroups?s:{...s,projectGroups:Je},[s,Je]);v.useEffect(()=>n.onStatus(te),[n]),v.useEffect(()=>n.subscribe({type:"sidebar"},Y=>{o(Y),c(X=>X&&UD(Y.projectGroups,X)===Y.projectGroups?null:X),fe(!0),Se(null)}),[n]),v.useEffect(()=>{if(W!=="connected")return;const Y=[...new Set([...st,...Vt])].sort();n.command({type:"chat.setDraftProtection",chatIds:Y}).catch(X=>{Se(X instanceof Error?X.message:String(X))})},[Vt,W,st,n]),v.useEffect(()=>n.subscribe({type:"local-projects"},Y=>{m(Y),ee(!0),Se(null)}),[n]),v.useEffect(()=>n.subscribe({type:"update"},Y=>{g(Y),Se(null)}),[n]),v.useEffect(()=>{W==="connected"&&n.command({type:"update.check",force:!0}).catch(Y=>{Se(Y instanceof Error?Y.message:String(Y))})},[W,n]),v.useEffect(()=>{const Y=h==null?void 0:h.reloadRequestedAt;i0e(Y,s0e())&&Y&&(o0e(Y),_("awaiting_disconnect"))},[_,h==null?void 0:h.reloadRequestedAt]),v.useEffect(()=>{const Y=nS();if(Qye(Y,W)==="awaiting_server_ready"){_("awaiting_server_ready");return}},[W,_]),v.useEffect(()=>{if(nS()!=="awaiting_server_ready")return;let Y=!1,X=null;const je=async()=>{try{if(await c0e()){if(Y)return;w(),window.location.reload();return}}catch{}Y||(X=window.setTimeout(()=>{je()},500))};return je(),()=>{Y=!0,X!==null&&window.clearTimeout(X)}},[W,w]),v.useEffect(()=>{function Y(){h!=null&&h.lastCheckedAt&&(Date.now()-h.lastCheckedAt<=3600*1e3||n.command({type:"update.check"}).catch(X=>{Se(X instanceof Error?X.message:String(X))}))}return window.addEventListener("focus",Y),()=>{window.removeEventListener("focus",Y)}},[n,h==null?void 0:h.lastCheckedAt]),v.useEffect(()=>n.subscribe({type:"keybindings"},Y=>{$(Y),Se(null)}),[n]),v.useEffect(()=>n.subscribe({type:"app-settings"},Y=>{B(Y),Rh(Y),Se(null)}),[n]),v.useEffect(()=>n.subscribe({type:"push-config"},Y=>{G(Y)}),[n]),v.useEffect(()=>{let Y=!1;return n.subscribe({type:"bg-tasks"},X=>{Ys.getState().applySnapshot(X.tasks),!Y&&X.orphanRecoveryCount!=null&&X.orphanRecoveryCount>0&&(Y=!0,wye(X.orphanRecoveryCount))},X=>{X.type==="bg-tasks.added"?Ys.getState().applyDiff({op:"added",task:X.task}):X.type==="bg-tasks.updated"?Ys.getState().applyDiff({op:"updated",task:X.task}):X.type==="bg-tasks.removed"&&Ys.getState().applyDiff({op:"removed",task:X.task})})},[n]);const gt=v.useCallback(async()=>{try{Qi.getState().setHydrationStatus("loading");const Y=await n.command({type:"settings.readAppSettings"});B(Y),Rh(Y),Se(null)}catch(Y){Qi.getState().setHydrationStatus("error"),Se(Y instanceof Error?Y.message:String(Y))}},[n]),bt=v.useCallback(async(Y,X)=>{try{await n.command({type:"chat.setPolicyOverride",chatId:Y,policyOverride:X}),Se(null)}catch(je){throw Se(je instanceof Error?je.message:String(je)),je}},[n]),Lt=v.useCallback(async Y=>{try{Qi.getState().applyOptimisticPatch(Y);const X=await n.command({type:"settings.writeAppSettingsPatch",patch:Y});B(X),Rh(X),Se(null)}catch(X){throw Se(X instanceof Error?X.message:String(X)),await gt(),X}},[gt,n]),Wt=v.useCallback(async Y=>{try{Qi.getState().applyOptimisticPatch({cloudflareTunnel:Y});const X=await n.command({type:"appSettings.setCloudflareTunnel",patch:Y});B(X),Rh(X),Se(null)}catch(X){throw Se(X instanceof Error?X.message:String(X)),await gt(),X}},[gt,n]),Te=v.useCallback(async Y=>{try{Qi.getState().applyOptimisticPatch({claudeAuth:Y});const X=await n.command({type:"appSettings.setClaudeAuth",patch:Y});B(X),Rh(X),Se(null)}catch(X){throw Se(X instanceof Error?X.message:String(X)),await gt(),X}},[gt,n]),nt=v.useCallback(async Y=>await n.command({type:"appSettings.testOAuthToken",token:Y}),[n]),Ie=v.useCallback(async()=>{try{const Y=await n.command({type:"settings.readLlmProvider"});I(Y),Se(null)}catch(Y){Se(Y instanceof Error?Y.message:String(Y))}},[n]),Qe=v.useCallback(async Y=>{try{const X=await n.command({type:"settings.writeLlmProvider",provider:Y.provider,apiKey:Y.apiKey,model:Y.model,baseUrl:Y.baseUrl});I(X),Se(null)}catch(X){throw Se(X instanceof Error?X.message:String(X)),X}},[n]),_e=v.useCallback(async Y=>await n.command({type:"settings.validateLlmProvider",provider:Y.provider,apiKey:Y.apiKey,model:Y.model,baseUrl:Y.baseUrl}),[n]);v.useEffect(()=>{W==="connected"&&gt()},[W,gt]),v.useEffect(()=>{if(W!=="connected"||(H==null?void 0:H.browserSettingsMigrated)!==!1)return;const Y=Oye();Y&&Lt(Y).then(zye).catch(()=>{})},[H==null?void 0:H.browserSettingsMigrated,W,Lt]),v.useEffect(()=>{W==="connected"&&Ie()},[W,Ie]),v.useEffect(()=>{function Y(){Ge(X=>X+1)}return window.addEventListener("focus",Y),document.addEventListener("visibilitychange",Y),()=>{window.removeEventListener("focus",Y),document.removeEventListener("visibilitychange",Y)}},[]),v.useEffect(()=>{if(!e){E(null),se(!0);return}++sn.current,St.current.length,St.current.reduce((X,je)=>X+je.chats.length,0),E(null),se(!1);const Y=n.subscribe({type:"chat",chatId:e,recentLimit:Uye},X=>{if(X!=null&&X.runtime.chatId){const je=[...ft.current.values()].filter(_t=>_t.serverChatId===X.runtime.chatId).sort((_t,ir)=>ir.startedAt-_t.startedAt)[0];je&&je.snapshotAt===void 0&&(je.snapshotAt=performance.now(),pl(je,"chat_snapshot_received",{status:X.runtime.status,messageCount:X.messages.length}))}if(E(je=>{const _t=Iye(je,X);return X==null||X.runtime.chatId,X==null||X.runtime.provider,X==null||X.runtime.status,X==null||X.messages.length,_t?je:X}),L((X==null?void 0:X.history.olderCursor)??null),D((X==null?void 0:X.history.hasOlder)??!1),se(!0),Se(null),X){const je=v2.getState();je.setForChat(X.runtime.chatId,X.slashCommands??[]),je.setLoadingForChat(X.runtime.chatId,X.slashCommandsLoading??!1)}});return()=>{St.current.length,St.current.reduce((X,je)=>X+je.chats.length,0),Y()}},[e,n]),v.useEffect(()=>{if(le)return;const Y=Je[0];Y&&ue(Y.groupKey)},[le,Je]),v.useEffect(()=>{if(!e||!U||!ne)return;if(Je.some(X=>X.chats.some(je=>je.chatId===e))){Ce===e&&$e(null);return}Ce!==e&&t("/")},[e,ne,t,Ce,Je,U]),v.useEffect(()=>{C&&(ue(C.runtime.projectId),Ce===C.runtime.chatId&&$e(null))},[C,Ce]),v.useEffect(()=>{if(!e||!U||!Wye())return;const Y=Je.flatMap(X=>X.chats).find(X=>X.chatId===e);Y!=null&&Y.unread&&n.command({type:"chat.markRead",chatId:e}).catch(X=>{Se(X instanceof Error?X.message:String(X))})},[e,Ye,Je,U,n]),v.useEffect(()=>{N([]),A(!1),L(null),D(!1)},[e]);const Fe=v.useMemo(()=>d0e(C,e),[e,C]),qe=v.useMemo(()=>(Fe==null?void 0:Fe.runtime.projectId)??Xye(Je,e)??le,[e,Fe==null?void 0:Fe.runtime.projectId,le,Je]),Ve=v.useMemo(()=>{const Y=qe?O[qe]??null:null;return qe&&Y?(dn.current={projectId:qe,diffs:Y},Y):qe&&dn.current.projectId===qe?dn.current.diffs:Y},[qe,O]);v.useEffect(()=>qe?n.subscribe({type:"project-git",projectId:qe},X=>{z(je=>{const _t=X??null;return Lye(je[qe]??null,_t)||Mye(je[qe]??null,_t)?je:{...je,[qe]:_t}}),Se(null)}):void 0,[qe,n]),v.useEffect(()=>{C==null||C.runtime.chatId,C==null||C.runtime.provider,Fe==null||Fe.runtime.chatId,Fe==null||Fe.runtime.provider},[e,Fe,C,Ce]);const Dt=v.useMemo(()=>FD(k,(Fe==null?void 0:Fe.messages)??[]),[Fe==null?void 0:Fe.messages,k]),Mt=e??$D,Ft=v.useMemo(()=>et.filter(Y=>Y.scopeId===Mt).map(Y=>Y.entry),[Mt,et]),It=v.useMemo(()=>[...Dt,...Ft],[Ft,Dt]),hn=v.useMemo(()=>pF(It),[It]),ur=v.useMemo(()=>Pye(hn),[hn]),xe=v.useMemo(()=>aye(hn),[hn]),ye=(Fe==null?void 0:Fe.runtime)??null,it=(Fe==null?void 0:Fe.queuedMessages)??[],Oe=((Pe==null?void 0:Pe.scopeId)===Mt&&(!ye||ye.status==="idle")?"starting":null)??(ye==null?void 0:ye.status)??null,Be=(Fe==null?void 0:Fe.availableProviders)??Xh,Gt=cye(Oe??void 0),Kt=lye(Oe??void 0),Jt=(ye==null?void 0:ye.isDraining)??!1,ct=((yu=u==null?void 0:u.projects[0])==null?void 0:yu.localPath)??null,mn=(ye==null?void 0:ye.localPath)??ct??((xu=Je[0])==null?void 0:xu.localPath),Pn=!!(le??(ye==null?void 0:ye.projectId)??((Ha=Je[0])==null?void 0:Ha.groupKey)??ct);v.useEffect(()=>{(Pe==null?void 0:Pe.scopeId)===Mt&&ye!=null&&ye.status&&ye.status!=="idle"&&Ze(null)},[Pe,Mt,ye==null?void 0:ye.status]),v.useEffect(()=>{if(!(Pe!=null&&Pe.ackedAt)||Pe.scopeId!==Mt||ye!=null&&ye.status&&ye.status!=="idle")return;const Y=window.setTimeout(()=>{Ze(X=>(X==null?void 0:X.scopeId)===Mt&&X.ackedAt===Pe.ackedAt?null:X)},300);return()=>window.clearTimeout(Y)},[Pe,Mt,ye==null?void 0:ye.status]),v.useEffect(()=>{if(!e||(ye==null?void 0:ye.status)!=="starting")return;const Y=[...ft.current.values()].filter(X=>X.serverChatId===e).sort((X,je)=>je.startedAt-X.startedAt)[0];!Y||Y.startingStatusAt!==void 0||(Y.startingStatusAt=performance.now(),pl(Y,"runtime_status_starting",{status:ye.status}))},[e,ye==null?void 0:ye.status]),v.useEffect(()=>{if(!e||!ye||ye.status==="starting")return;const Y=[...ft.current.values()].filter(X=>X.serverChatId===e).sort((X,je)=>je.startedAt-X.startedAt)[0];!Y||Y.startingRenderedAt!==void 0||(pl(Y,"starting_not_observed",{status:ye.status}),ft.current.delete(Y.traceId))},[e,ye]),v.useLayoutEffect(()=>{if(!e||(ye==null?void 0:ye.status)!=="starting"){pn.current=null;return}const Y=[...ft.current.values()].filter(X=>X.serverChatId===e).sort((X,je)=>je.startedAt-X.startedAt)[0];Y&&pn.current!==Y.traceId&&(pn.current=Y.traceId,Y.startingRenderedAt=performance.now(),pl(Y,"starting_render_committed",{totalMs:_F(Y.startedAt)}),ft.current.delete(Y.traceId))},[e,ye==null?void 0:ye.status]),v.useEffect(()=>{Ee(Y=>{const X=$ye(Y,Mt,Dt);return X.length===Y.length&&X.every((je,_t)=>je===Y[_t])?Y:X})},[Mt,Dt]);const Gn=v.useCallback(async()=>{if(!(!e||!M||R||!F)){A(!0);try{const Y=await n.command({type:"chat.loadHistory",chatId:e,beforeCursor:M,limit:Vye});N(X=>FD(Y.messages,X)),L(Y.olderCursor),D(Y.hasOlder),Se(null)}catch(Y){const X=Y instanceof Error?Y.message:String(Y);Se(X)}finally{A(!1)}}},[e,F,M,R,n]),Ar=v.useCallback(async Y=>{const X=bi.getState(),je=e?X.getComposerState(e):X.getComposerState(im),_t=await n.command({type:"chat.create",projectId:Y});X.initializeComposerForChat(_t.chatId,{sourceState:je}),ue(Y),$e(_t.chatId),t(`/chat/${_t.chatId}`),ce(!1),Se(null)},[e,t,n]),Jr=v.useCallback(async Y=>Y.kind==="project_id"?{projectId:Y.projectId}:Y.kind==="local_path"?{projectId:(await n.command({type:"project.open",localPath:Y.localPath})).projectId,localPath:Y.localPath}:{projectId:(await n.command(Y.project.mode==="new"?{type:"project.create",localPath:Y.project.localPath,title:Y.project.title}:{type:"project.open",localPath:Y.project.localPath})).projectId,localPath:Y.project.localPath},[n]),Xn=v.useCallback(async Y=>{try{const X=Y.kind==="project_id"?null:Y.kind==="local_path"?Y.localPath:Y.project.localPath;X&&me(X);const{projectId:je}=await Jr(Y);await Ar(je)}catch(X){Se(X instanceof Error?X.message:String(X))}finally{me(null)}},[Ar,Jr]),rs=v.useCallback(async Y=>{await Xn({kind:"project_id",projectId:Y})},[Xn]),Bi=v.useCallback(async Y=>{try{const X=await n.command({type:"chat.fork",chatId:Y.chatId}),je=bi.getState();je.initializeComposerForChat(X.chatId,{sourceState:je.getComposerState(Y.chatId)}),$e(X.chatId),t(`/chat/${X.chatId}`),ce(!1),Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[t,n]),yt=v.useCallback(async Y=>{await Xn({kind:"local_path",localPath:Y})},[Xn]),cn=v.useCallback(async Y=>{await Xn({kind:"project_request",project:Y})},[Xn]),Tn=v.useCallback(async Y=>{try{await n.command({type:"update.check",force:Y==null?void 0:Y.force}),Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[n]),yn=v.useCallback(async Y=>{_("awaiting_disconnect");try{const X=await n.command({type:"update.install",version:Y});if(!X.ok){w(),Se(null),await r.alert({title:X.userTitle??"Update failed",description:X.userMessage??"Kanna could not install the update. Try again later.",closeLabel:"OK"});return}if(X.ok&&X.action==="reload"){window.location.reload();return}Se(null)}catch(X){w(),Se(X instanceof Error?X.message:String(X))}},[w,r,_,n]),ao=v.useCallback(async()=>{_("awaiting_disconnect");try{const Y=await n.command({type:"update.reload"});if(!Y.ok){w(),Se(null),await r.alert({title:Y.userTitle??"Re-deploy failed",description:Y.userMessage??"Kanna could not re-deploy. Try again later.",closeLabel:"OK"});return}if(Y.action==="reload"){window.location.reload();return}Se(null)}catch(Y){w(),Se(Y instanceof Error?Y.message:String(Y))}},[w,r,_,n]),Oa=v.useCallback(async()=>{try{const Y=await fetch("/auth/logout",{method:"POST",headers:{Accept:"application/json"}});if(!Y.ok)throw new Error(`Sign out failed with status ${Y.status}`);Se(null),window.location.reload()}catch(Y){Se(Y instanceof Error?Y.message:String(Y))}},[]),is=v.useCallback(async(Y,X)=>{var Lp;const je=(X==null?void 0:X.attachments)??[],_t=Tc(),ir=Tc(),ui=x2(Y,je),tc=e??$D;Ze({scopeId:tc,ackedAt:null});const zs={traceId:ir,optimisticId:_t,startedAt:performance.now(),serverChatId:e,routeChatIdAtSend:e,contentPreview:Y.slice(0,80)};ft.current.set(ir,zs),pl(zs,"handle_send_called",{optimisticScopeId:tc,attachments:je.length,contentLength:Y.length,contentPreview:zs.contentPreview});const M0=Fye(Dt,ui)+et.filter(fr=>fr.scopeId===tc&&fr.signature===ui).length+1;Ee(fr=>[...fr,{id:_t,scopeId:tc,signature:ui,requiredMatchCount:M0,entry:{_id:`optimistic:${_t}`,kind:"user_prompt",content:Y,attachments:je,createdAt:Date.now()}}]),pl(zs,"optimistic_prompt_added",{optimisticId:_t,optimisticScopeId:tc});try{let fr=le??((Lp=Je[0])==null?void 0:Lp.groupKey)??null;if(!e&&!fr&&ct&&(fr=(await n.command({type:"project.open",localPath:ct})).projectId,ue(fr)),!e&&!fr)throw new Error("Open a project first");const _u=eC.getState().autoResumeOnRateLimit,di=await n.command({type:"chat.send",chatId:e??void 0,projectId:e?void 0:fr??void 0,clientTraceId:ir,provider:X==null?void 0:X.provider,content:Y,attachments:je,model:X==null?void 0:X.model,modelOptions:X==null?void 0:X.modelOptions,planMode:X==null?void 0:X.planMode,autoResumeOnRateLimit:_u});if(zs.ackAt=performance.now(),zs.serverChatId=di.chatId??zs.serverChatId,di.queued?(Ee(Bs=>Hye(Bs,_t,{queued:!0})),Ze(null)):Ze(Bs=>Bs&&{scopeId:!e&&di.chatId?di.chatId:Bs.scopeId,ackedAt:performance.now()}),pl(zs,"chat_send_ack_received",{resultChatId:di.chatId??null,queued:di.queued??!1}),!e&&di.chatId){Ee(jp=>jp.map(Lf=>Lf.id===_t?{...Lf,scopeId:di.chatId}:Lf));const Bs=bi.getState();Bs.setComposerState(di.chatId,Yye(X)??Bs.getComposerState(im)),$e(di.chatId),t(`/chat/${di.chatId}`)}Se(null)}catch(fr){throw Ee(_u=>_u.filter(di=>di.id!==_t)),Ze(null),pl(zs,"handle_send_failed",{error:fr instanceof Error?fr.message:String(fr)}),ft.current.delete(ir),Se(fr instanceof Error?fr.message:String(fr)),fr}},[e,ct,t,et,le,Dt,Je,n]),Ho=v.useCallback(async Y=>{if(e)try{await n.command({type:"message.steer",chatId:e,queuedMessageId:Y}),Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[e,n]),ss=v.useCallback(async Y=>{if(e)try{await n.command({type:"message.dequeue",chatId:e,queuedMessageId:Y}),Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[e,n]),za=v.useCallback(async()=>{if(e)try{await n.command({type:"chat.cancel",chatId:e})}catch(Y){Se(Y instanceof Error?Y.message:String(Y))}},[e,n]),dr=v.useCallback(async()=>{if(e)try{await n.command({type:"chat.stopDraining",chatId:e})}catch(Y){Se(Y instanceof Error?Y.message:String(Y))}},[e,n]),Le=v.useCallback(async Y=>{const X=await r.prompt({title:"Rename Chat",initialValue:Y.title,confirmLabel:"Rename"});if(!(!X||X===Y.title))try{await n.command({type:"chat.rename",chatId:Y.chatId,title:X}),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[r,n]),Xe=v.useCallback(async Y=>{if(await r.confirm({title:"Delete Chat",description:`Delete "${Y.title}"? This cannot be undone.`,confirmLabel:"Delete",confirmVariant:"destructive"}))try{if(await n.command({type:"chat.delete",chatId:Y.chatId}),Y.chatId===e){const je=HD(Je,Y.chatId);t(je?`/chat/${je}`:"/")}}catch(je){Se(je instanceof Error?je.message:String(je))}},[e,r,t,Je,n]),Ot=v.useCallback(async Y=>{try{if(await n.command({type:"chat.archive",chatId:Y.chatId}),Y.chatId===e){const X=HD(Je,Y.chatId);t(X?`/chat/${X}`:"/")}Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[e,t,Je,n]),rr=v.useCallback(async Y=>{try{$e(Y),await n.command({type:"chat.unarchive",chatId:Y}),t(`/chat/${Y}`),Se(null)}catch(X){$e(null),Se(X instanceof Error?X.message:String(X))}},[t,n]),ci=v.useCallback(async Y=>{try{await n.command({type:"project.remove",projectId:Y}),wl.getState().clearProject(Y),ji.getState().clearProject(Y),(ye==null?void 0:ye.projectId)===Y&&t("/"),Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[t,ye,n]),lo=v.useCallback(async(Y,X)=>{try{await n.command({type:"project.setStar",projectId:Y,starred:X}),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[n]),Z=v.useCallback(async Y=>{c(Y);try{await n.command({type:"sidebar.reorderProjectGroups",projectIds:Y}),Se(null)}catch(X){c(null),Se(X instanceof Error?X.message:String(X))}},[n]),ze=v.useCallback(async(Y,X)=>{try{await n.command({type:"stack.create",title:Y,projectIds:X}),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[n]),Sn=v.useCallback(async(Y,X)=>{try{await n.command({type:"stack.rename",stackId:Y,title:X}),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[n]),co=v.useCallback(async Y=>{try{await n.command({type:"stack.remove",stackId:Y}),Se(null)}catch(X){Se(X instanceof Error?X.message:String(X))}},[n]),Yl=v.useCallback(async(Y,X)=>{try{await n.command({type:"stack.addProject",stackId:Y,projectId:X}),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[n]),Xl=v.useCallback(async(Y,X)=>{try{await n.command({type:"stack.removeProject",stackId:Y,projectId:X}),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[n]),Nf=v.useCallback(async(Y,X,je)=>{try{const _t=bi.getState(),ir=e?_t.getComposerState(e):_t.getComposerState(im),ui=await n.command({type:"chat.create",projectId:Y,stackId:X,stackBindings:je});_t.initializeComposerForChat(ui.chatId,{sourceState:ir}),ue(Y),$e(ui.chatId),t(`/chat/${ui.chatId}`),ce(!1),Se(null)}catch(_t){Se(_t instanceof Error?_t.message:String(_t))}},[e,t,n]),Ba=v.useCallback(async Y=>{try{const X=await n.command({type:"stack.listWorktrees",projectId:Y});return Se(null),X.worktrees}catch(X){return Se(X instanceof Error?X.message:String(X)),[]}},[n]),Ps=v.useCallback(async()=>await n.command({type:"sessions.importClaude"}),[n]),uo=v.useCallback(async Y=>{const X=pi.getState();Se(null),await n.command({type:"system.openExternal",...Y,editor:Y.action==="open_editor"?Y.editor??{preset:X.editorPreset,commandTemplate:X.editorCommandTemplate}:void 0})},[n]),Rf=v.useCallback(async(Y,X)=>{var _t,ir;const je=(ye==null?void 0:ye.localPath)??((_t=u==null?void 0:u.projects[0])==null?void 0:_t.localPath)??((ir=Je[0])==null?void 0:ir.localPath);if(je)try{await uo({action:Y,localPath:je,editor:X})}catch(ui){Se(ui instanceof Error?ui.message:String(ui))}},[u==null?void 0:u.projects,uo,ye==null?void 0:ye.localPath,Je]),Fa=v.useCallback(async Y=>{var X;try{if(typeof navigator>"u"||!((X=navigator.clipboard)!=null&&X.writeText))throw new Error("Clipboard is not available");await navigator.clipboard.writeText(Y),Se(null)}catch(je){Se(je instanceof Error?je.message:String(je))}},[]),$a=v.useCallback(async(Y,X="open_editor",je)=>{try{await uo({action:X,localPath:Y.path,line:Y.line,column:Y.column,editor:je})}catch(_t){Se(_t instanceof Error?_t.message:String(_t))}},[uo]),Tp=v.useCallback(async(Y,X)=>{try{await uo({action:Y,localPath:X})}catch(je){Se(je instanceof Error?je.message:String(je))}},[uo]),Ql=v.useCallback(async(Y=e)=>{if(!Y||Rt)return null;Et(!0);try{const X=await n.command({type:"chat.exportStandalone",chatId:Y,theme:i,attachmentMode:"bundle"});return Se(null),X}catch(X){return Se(X instanceof Error?X.message:String(X)),null}finally{Et(!1)}},[e,Rt,i,n]),Np=v.useCallback(async(Y=e)=>{if(!Y||Rt)return;pt(!1);const X=await Ql(Y);if(X!=null&&X.ok&&X.shareUrl){Bt(X.shareUrl),pt(!0);return}X&&!X.ok&&await r.confirm({title:"Share failed",description:X.error,confirmLabel:"Download transcript JSON",cancelLabel:"Close",confirmVariant:"secondary"})&&l0e(X.transcriptFileName,X.transcriptJson)},[e,r,Ql,Rt]),Zl=v.useCallback(()=>{Bt(null),pt(!1)},[]),Os=v.useCallback(async()=>{var Y;if(!dt)return!1;try{if(typeof navigator>"u"||!((Y=navigator.clipboard)!=null&&Y.writeText))throw new Error("Clipboard is not available");return await navigator.clipboard.writeText(dt),!0}catch(X){return await r.alert({title:"Copy failed",description:X instanceof Error?X.message:String(X),closeLabel:"Close"}),!1}},[r,dt]),Af=v.useCallback(()=>{dt&&(window.open(dt,"_blank","noopener,noreferrer"),Bt(null))},[dt]),Jl=v.useCallback(()=>{var X;const Y=u0e({selectedProjectId:le,sidebarProjectId:(X=Je[0])==null?void 0:X.groupKey,fallbackLocalProjectPath:ct});if(Y){Xn(Y);return}t("/")},[ct,t,le,Je,Xn]),fo=v.useCallback(()=>ce(!0),[]),Mf=v.useCallback(()=>ce(!1),[]),pu=v.useCallback(()=>Ke(!0),[]),Rp=v.useCallback(()=>Ke(!1),[]),gu=v.useCallback(()=>Tt(!0),[]),vu=v.useCallback(()=>Tt(!1),[]),Ap=v.useCallback(async(Y,X,je)=>{if(e)try{await n.command({type:"chat.respondTool",chatId:e,toolUseId:Y,result:{questions:X,answers:je}})}catch(_t){Se(_t instanceof Error?_t.message:String(_t))}},[e,n]),ei=v.useCallback(async(Y,X,je,_t)=>{if(e){X&&bi.getState().setChatComposerPlanMode(e,!1);try{await n.command({type:"chat.respondTool",chatId:e,toolUseId:Y,result:{confirmed:X,...je?{clearContext:!0}:{},..._t?{message:_t}:{}}})}catch(ir){Se(ir instanceof Error?ir.message:String(ir))}}},[e,n]),Uo=v.useCallback(async(Y,X,je,_t)=>{if(e)try{await n.command({type:"chat.respondSubagentTool",chatId:e,runId:Y,toolUseId:X,result:{questions:je,answers:_t}})}catch(ir){Se(ir instanceof Error?ir.message:String(ir))}},[e,n]),bu=v.useCallback(async(Y,X,je)=>{if(e)try{await n.command({type:"chat.respondSubagentTool",chatId:e,runId:Y,toolUseId:X,result:je})}catch(_t){Se(_t instanceof Error?_t.message:String(_t))}},[e,n]),ec=v.useCallback(async(Y,X)=>{if(e)try{await n.command({type:"chat.toolRequestAnswer",chatId:e,toolRequestId:Y,decision:X})}catch(je){Se(je instanceof Error?je.message:String(je))}},[e,n]),Mp=Zye(b,h==null?void 0:h.status);return{socket:n,activeChatId:e,activeProjectId:qe,sidebarData:xt,localProjects:u,updateSnapshot:h,chatSnapshot:C,chatDiffSnapshot:Ve,keybindings:P,appSettings:H,pushConfig:V,llmProvider:Q,connectionStatus:W,sidebarReady:U,uiRestartActive:Mp.active,uiRestartLabel:Mp.label,localProjectsReady:ae,commandError:qt,startingLocalPath:ln,sidebarOpen:Ae,sidebarCollapsed:De,messages:hn,queuedMessages:it,previousPrompt:ur,latestToolIds:xe,runtime:ye,runtimeStatus:Oe,isHistoryLoading:R,hasOlderHistory:F,availableProviders:Be,isProcessing:Gt,canCancel:Kt,isDraining:Jt,isExportingStandalone:Rt,standaloneShareUrl:dt,standaloneShareComplete:Ut,navbarLocalPath:mn,editorLabel:At,hasSelectedProject:Pn,addProjectModalOpen:ht,openSidebar:fo,closeSidebar:Mf,collapseSidebar:pu,expandSidebar:Rp,openAddProjectModal:gu,closeAddProjectModal:vu,loadOlderHistory:Gn,handleCreateChat:rs,handleForkChat:Bi,handleOpenLocalProject:yt,handleCreateProject:cn,handleCheckForUpdates:Tn,handleInstallUpdate:yn,handleForceReload:ao,handleReadAppSettings:gt,handleWriteAppSettings:Lt,handleSetChatPolicyOverride:bt,handleWriteCloudflareTunnel:Wt,handleWriteClaudeAuth:Te,handleTestOAuthToken:nt,handleReadLlmProvider:Ie,handleWriteLlmProvider:Qe,handleValidateLlmProvider:_e,handleSignOut:Oa,handleSend:is,handleSteerQueuedMessage:Ho,handleRemoveQueuedMessage:ss,handleCancel:za,handleStopDraining:dr,handleRenameChat:Le,handleShareChat:Np,handleArchiveChat:Ot,handleOpenArchivedChat:rr,handleDeleteChat:Xe,handleHideProject:ci,handleToggleProjectStar:lo,handleReorderProjectGroups:Z,stacks:xt.stacks,handleCreateStack:ze,handleRenameStack:Sn,handleRemoveStack:co,handleAddProjectToStack:Yl,handleRemoveProjectFromStack:Xl,handleCreateStackChat:Nf,handleListStackWorktrees:Ba,importClaudeSessions:Ps,handleCopyPath:Fa,handleOpenExternal:Rf,handleOpenExternalPath:Tp,handleOpenLocalLink:$a,handleCompose:Jl,handleAskUserQuestion:Ap,handleExitPlanMode:ei,handleSubagentAskUserQuestion:Uo,handleSubagentExitPlanMode:bu,handleExportStandalone:Ql,handleCloseStandaloneShareDialog:Zl,handleOpenStandaloneShareLink:Af,handleCopyStandaloneShareLink:Os,handleToolRequestAnswer:ec}}const SF=v.memo(function({message:t}){return f.jsx("div",{className:"text-pretty prose prose-sm dark:prose-invert px-0.5 w-full max-w-[70ch] space-y-4",children:f.jsx(lu,{remarkPlugins:Sf,components:Cf,children:t.text})})}),_p=({children:e,className:t,animate:n=!0,shimmerWidth:r,...i})=>f.jsx("span",{className:he("mx-auto max-w-md text-foreground/60",n&&"animate-shiny-pulse",t),...i,children:e});function h0e(e){const t=e.split(`
2606
2606
  `),n=/^\s*(\d+)→(.*)$/;return t.map(r=>{const i=r.match(n);return i?{lineNumber:parseInt(i[1],10),content:i[2]}:{lineNumber:null,content:r}})}function m0e(e){return e.replace(/<[^>]+>/g,"")}function p0e(e,t){const n=e.split(`
2607
2607
  `),r=t.split(`
2608
- `),i=g0e(n,r),s=v0e(n,r,i);return b0e(s)}function g0e(e,t){const n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let s=1;s<=n;s++)for(let o=1;o<=r;o++)i[s][o]=e[s-1]===t[o-1]?i[s-1][o-1]+1:Math.max(i[s-1][o],i[s][o-1]);return i}function v0e(e,t,n){const r=[];let i=e.length,s=t.length;for(;i>0||s>0;)i>0&&s>0&&e[i-1]===t[s-1]?(r.push({type:"context",text:e[i-1],oldIdx:i,newIdx:s}),i--,s--):s>0&&(i===0||n[i][s-1]>=n[i-1][s])?(r.push({type:"added",text:t[s-1],oldIdx:i,newIdx:s}),s--):(r.push({type:"removed",text:e[i-1],oldIdx:i,newIdx:s}),i--);return r.reverse()}function b0e(e){return e.map(t=>{const n=t.type==="removed"?"-":t.type==="added"?"+":" ";return{type:t.type,content:`${n}${t.text}`}})}function Rv({content:e,isDiff:t=!1,oldString:n,newString:r}){const i=v.useMemo(()=>t&&n!==void 0&&r!==void 0?p0e(n,r):[],[t,n,r]),s=v.useMemo(()=>t?[]:h0e(e),[e,t]),o=v.useMemo(()=>s.some(l=>l.lineNumber!==null),[s]);return t&&i.length>0?f.jsx("div",{className:"my-1 rounded-lg border border-border overflow-hidden",children:f.jsx("div",{className:"overflow-auto max-h-64 md:max-h-[50vh]",children:f.jsx("table",{className:"w-full border-collapse text-xs font-mono",children:f.jsx("tbody",{children:i.map((l,c)=>{const u=l.type==="removed"?"bg-destructive/10 dark:bg-destructive/15":l.type==="added"?"bg-success/10 dark:bg-success/15":"",m=l.type==="removed"?"text-destructive":l.type==="added"?"text-success":"text-foreground";return f.jsxs("tr",{className:u,children:[f.jsx("td",{className:`px-2 py-0 select-none w-0 whitespace-nowrap ${l.type==="removed"?"text-destructive/50":l.type==="added"?"text-success/50":"text-muted-foreground/50"}`,children:l.type==="removed"?"-":l.type==="added"?"+":" "}),f.jsx("td",{className:`px-2 py-0 whitespace-pre select-all ${m}`,children:l.content.slice(1)})]},c)})})})})}):f.jsx("div",{className:"my-1 rounded-lg border border-border overflow-hidden",children:f.jsx("div",{className:"overflow-auto max-h-64 md:max-h-[50vh]",children:f.jsx("table",{className:"w-full border-collapse text-xs font-mono",children:f.jsx("tbody",{children:s.map((l,c)=>f.jsxs("tr",{children:[o&&f.jsx("td",{className:"px-2 py-0 select-none w-0 whitespace-nowrap text-muted-foreground/50 text-right",children:l.lineNumber!==null?l.lineNumber:""}),f.jsx("td",{className:"px-2 py-0 whitespace-pre select-all text-foreground",children:m0e(l.content)})]},c))})})})})}function WD(e){return(e&&typeof e=="object"&&"content"in e&&Array.isArray(e.content)?e.content:Array.isArray(e)?e:[]).flatMap(n=>!n||typeof n!="object"||!("type"in n)||n.type!=="image"?[]:"data"in n&&typeof n.data=="string"?[{type:"image",data:n.data,mimeType:typeof n.mimeType=="string"?n.mimeType:void 0}]:"source"in n&&n.source&&typeof n.source=="object"&&"type"in n.source&&n.source.type==="base64"&&"data"in n.source&&typeof n.source.data=="string"?[{type:"image",data:n.source.data,mimeType:typeof n.source.media_type=="string"?n.source.media_type:void 0}]:[])}function y0e({images:e}){return f.jsx("div",{className:"flex flex-col gap-3",children:e.map((t,n)=>{const r=t.mimeType||"image/png";return f.jsx("div",{className:"overflow-hidden rounded-lg border border-border bg-muted/20",children:f.jsx("img",{src:`data:${r};base64,${t.data}`,alt:`Read result ${n+1}`,className:"max-h-[50vh] w-full object-contain bg-background"})},`${r}:${n}`)})})}function ay({message:e,isLoading:t=!1,localPath:n}){var w;const r=e.result!==void 0,i=!r&&t,s=v.useMemo(()=>{if(e.toolKind==="skill")return e.input.skill;if(e.toolKind==="glob")return`Search files ${e.input.pattern==="**/*"?"in all directories":`matching ${e.input.pattern}`}`;if(e.toolKind==="grep"){const C=e.input.pattern,E=e.input.outputMode;return E==="count"?`Count \`${C}\` occurrences`:E==="content"?`Find \`${C}\` in text`:`Find \`${C}\` in files`}return e.toolKind==="bash"?e.input.description||(e.input.command?iZ(e.input.command):"Bash"):e.toolKind==="web_search"?e.input.query||"Web Search":e.toolKind==="read_file"?`Read ${bv(e.input.filePath,n)}`:e.toolKind==="write_file"?`Write ${bv(e.input.filePath,n)}`:e.toolKind==="edit_file"?`Edit ${bv(e.input.filePath,n)}`:e.toolKind==="delete_file"?`Delete ${bv(e.input.filePath,n)}`:e.toolKind==="mcp_generic"?`${VS(e.input.tool)} from ${VS(e.input.server)}`:e.toolKind==="subagent_task"&&e.input.subagentType||e.toolName},[e.input,e.toolKind,e.toolName,n]),o=v.useMemo(()=>e.toolKind==="subagent_task",[e.toolKind]),l=v.useMemo(()=>{if(e.toolKind==="skill")return e.input.skill},[e.input,e.toolKind]),c=e.toolKind==="bash",u=e.toolKind==="write_file",m=e.toolKind==="edit_file",h=e.toolKind==="delete_file",g=e.toolKind==="read_file",b=v.useMemo(()=>{if(typeof e.result=="string")return e.result;if(!e.result)return"";if(typeof e.result=="object"&&e.result!==null&&"content"in e.result){const C=e.result.content;if(typeof C=="string")return C}return JSON.stringify(e.result,null,2)},[e.result]),x=v.useMemo(()=>{if(!g)return[];if(e.result&&typeof e.result=="object"&&"blocks"in e.result){const C=e.result.blocks;if(Array.isArray(C)){const E=WD(C);if(E.length>0)return E}}return WD(e.rawResult)},[g,e.rawResult,e.result]),_=v.useMemo(()=>{switch(e.toolKind){case"bash":return e.input.command;case"write_file":case"delete_file":return e.input.content;default:return JSON.stringify(e.input,null,2)}},[e]);return f.jsx(ja,{className:"w-full",children:f.jsxs(b0,{expandedContent:f.jsx(y0,{className:"my-4 text-sm",children:f.jsxs("div",{className:"flex flex-col gap-2",children:[m?f.jsx(Rv,{content:"",isDiff:!0,oldString:e.input.oldString,newString:e.input.newString}):h?f.jsx(Rv,{content:e.input.content}):!g&&!u&&f.jsx(cD,{label:c?f.jsxs("span",{className:"flex items-center gap-2 w-full",children:[f.jsx("span",{children:"Command"}),!!e.input.timeoutMs&&f.jsxs("span",{className:"text-muted-foreground",children:["timeout: ",String(e.input.timeoutMs),"ms"]}),!!e.input.runInBackground&&f.jsx("span",{className:"text-muted-foreground",children:"background"})]}):u?"Contents":"Input",copyText:_,children:_}),r&&g&&!e.isError&&(x.length>0?f.jsxs("div",{children:[f.jsx("span",{className:"font-medium text-muted-foreground",children:"Image"}),f.jsx("div",{className:"mt-1",children:f.jsx(y0e,{images:x})})]}):f.jsx(Rv,{content:b})),u&&!e.isError&&f.jsx(Rv,{content:e.input.content}),r&&!g&&!(u&&!e.isError)&&!(m&&!e.isError)&&!(h&&!e.isError)&&f.jsx(cD,{label:e.isError?"Error":"Result",copyText:b,children:b})]})}),children:[f.jsx("div",{className:"w-5 h-5 relative flex items-center justify-center",children:e.isError?f.jsx(io,{className:"size-4 text-destructive"}):o?f.jsx(Ey,{className:"size-4 text-muted-icon"}):f.jsx(BB,{icon:zB(e.toolName),className:"size-4 text-muted-icon"})}),f.jsx(Fl,{className:"text-left transition-opacity duration-200 truncate",children:f.jsx(_p,{animate:i,shimmerWidth:Math.max(20,(((w=l||s)==null?void 0:w.length)??33)*3),children:l||s})})]})})}function x0e(e){if(e<1e3)return`${e}ms`;const t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h${r>0?` ${r}m`:""}`:r>0?`${r}m${i>0?` ${i}s`:""}`:`${i}s`}function GD({durationMs:e,prefix:t="Worked for"}){return e<=0?null:f.jsxs(gve,{children:[t," ",x0e(e)]})}function CF({message:e}){return e.success?f.jsx(GD,{durationMs:e.durationMs}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"px-4 py-3 mx-2 my-1 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm",children:e.result||"An unknown error occurred."}),f.jsx(GD,{durationMs:e.durationMs,prefix:"Failed after"})]})}function _0e(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function w0e(e){return typeof e=="string"?e:JSON.stringify(e,null,2)}function S0e(e){return e.replace(/<persisted-output>\n?/g,"").replace(/\n?<\/persisted-output>/g,"")}function C0e({message:e,localPath:t}){if(e.kind==="tool"&&e.persisted){const n=S0e(w0e(e.rawResult??""));return f.jsxs("div",{className:"rounded-md border border-border bg-muted/30 p-2 space-y-1 text-xs",children:[f.jsxs("div",{className:"font-medium",children:[e.toolName,": output too large (",_0e(e.persisted.originalSize),") — saved to disk"]}),f.jsx("pre",{className:"text-[11px] whitespace-pre-wrap overflow-hidden max-h-48",children:n}),f.jsxs("a",{href:qE(e.persisted.filePath),className:"text-blue-500 hover:underline break-all",target:"_blank",rel:"noreferrer",children:["View full output (",e.persisted.filePath,")"]})]})}switch(e.kind){case"assistant_text":return f.jsx(SF,{message:e});case"tool":return f.jsx(ay,{message:e,isLoading:!1,localPath:t});case"result":return f.jsx(CF,{message:e});default:return null}}function k0e(e){switch(e){case"AUTH_REQUIRED":return"Auth required";case"UNKNOWN_SUBAGENT":return"Unknown subagent";case"LOOP_DETECTED":return"Loop detected";case"DEPTH_EXCEEDED":return"Depth exceeded";case"TIMEOUT":return"Timeout";case"PROVIDER_ERROR":return"Provider error";case"INTERRUPTED":return"Interrupted";case"USER_CANCELLED":return"Cancelled by you";default:return"Error"}}function E0e({error:e,runId:t,onRetry:n,onOpenSettings:r}){const i=e.code==="TIMEOUT"||e.code==="PROVIDER_ERROR",s=e.code==="AUTH_REQUIRED";return f.jsxs("div",{"data-testid":`subagent-error:${t}`,className:"rounded-md border border-destructive/40 bg-destructive/5 p-3 text-sm",children:[f.jsxs("div",{className:"flex items-center gap-2 font-medium text-destructive",children:[f.jsx(wb,{className:"h-4 w-4"}),f.jsx("span",{children:k0e(e.code)})]}),f.jsx("p",{className:"mt-1 text-foreground",children:e.message}),f.jsxs("div",{className:"mt-2 flex gap-2",children:[s&&r&&f.jsxs("button",{type:"button",onClick:r,className:"inline-flex items-center gap-1 text-xs underline",children:[f.jsx(zW,{className:"h-3 w-3"})," Open settings"]}),i&&n&&f.jsxs("button",{type:"button",onClick:n,className:"inline-flex items-center gap-1 text-xs underline",children:[f.jsx(CG,{className:"h-3 w-3"})," Retry"]})]})]})}function T0e({question:e,currentIndex:t,totalQuestions:n,onBack:r,children:i}){const s=r&&t>0;return f.jsxs("div",{className:"rounded-2xl border border-border overflow-hidden",children:[f.jsxs("div",{className:"relative",children:[f.jsxs("h3",{className:"font-medium text-foreground text-sm p-3 px-4 bg-card border-b border-border text-foreground flex flex-row items-center gap-2",children:[s?f.jsx("button",{onClick:r,className:" text-muted-foreground hover:opacity-60 transition-all flex items-center",children:f.jsx(EV,{className:"h-4 w-4 -ml-0.5",strokeWidth:3})}):n>1?f.jsxs("span",{className:"font-bold text-muted-foreground whitespace-nowrap",children:[t+1," of ",n]}):null,e]}),n>1&&f.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-border",children:f.jsx("div",{className:"h-full bg-muted-foreground/40 transition-all duration-300",style:{width:`${t/n*100}%`}})})]}),i]})}function qD({label:e,description:t}){return f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"text-foreground text-sm",children:e}),t&&f.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:t})]})}function kF({selected:e,multiSelect:t,onClick:n}){return f.jsx("button",{type:"button",onClick:n,className:he("flex-shrink-0 w-5 h-5 border-1 flex items-center justify-center",t?"rounded":"rounded-full",e?"border-transparent bg-foreground":"border-muted-foreground/50 bg-background",n&&e&&"cursor-pointer"),children:e&&f.jsx(_i,{strokeWidth:3,className:"translate-y-[0.5px] h-3 w-3 text-white dark:text-background"})})}function N0e({option:e,selected:t,multiSelect:n,onClick:r,isLast:i}){const s="w-full text-left p-3 pt-2.5 pl-4 pr-5 bg-background",o=i?"":"border-b border-border";return r?f.jsx("button",{onClick:r,className:he(s,o,"transition-all cursor-pointer"),children:f.jsxs("div",{className:"flex items-center justify-between gap-3",children:[f.jsx("div",{className:"flex-1 min-w-0",children:f.jsx(qD,{label:e.label,description:e.description})}),f.jsx(kF,{selected:t,multiSelect:n})]})}):f.jsx("div",{className:he(s,o),children:f.jsx(qD,{label:e.label,description:e.description})})}function R0e(e){return e==null?void 0:e.answers}function ps(e){return e.id||e.question}function EF({message:e,onSubmit:t,isLatest:n}){var V,G;const r=v0(),i=e.input.questions,s=!!e.result,o=R0e(e.result),l=((V=e.result)==null?void 0:V.discarded)===!0,[c,u]=v.useState(0),[m,h]=v.useState({}),[g,b]=v.useState({}),[x,_]=v.useState(o??null),[w,C]=v.useState(s),E=(Q,I)=>{var ae;const W=(ae=g[Q])==null?void 0:ae.trim(),te=m[Q]||"",U=I||i.find(ee=>ps(ee)===Q);if(U!=null&&U.multiSelect)return[te,W].filter(Boolean).flatMap(ee=>ee.split(", ").filter(Boolean));const fe=W||te;return fe?[fe]:[]},k=Q=>{const I=m[ps(Q)]||"";return Q.multiSelect?I.split(", ").filter(Boolean):[I]},N=(Q,I)=>{const W=ps(Q);if(Q.multiSelect){const te=m[W]?m[W].split(", ").filter(Boolean):[],U=te.includes(I)?te.filter(fe=>fe!==I):[...te,I];h({...m,[W]:U.join(", ")})}else h({...m,[W]:I}),b({...g,[W]:""}),c<i.length-1&&setTimeout(()=>u(c+1),150)},R=(Q,I)=>{const W=ps(Q);b({...g,[W]:I}),I&&!Q.multiSelect&&h({...m,[W]:""})},A=Q=>{const I=ps(Q);Q.multiSelect&&g[I]&&b({...g,[I]:""})},M=i.every(Q=>E(ps(Q),Q).length>0),L=i[c],F=c===i.length-1,D=L&&E(ps(L),L).length>0,O=()=>{c<i.length-1&&u(c+1)},z=()=>{c>0&&u(c-1)},P=()=>{if(!M)return;const Q={};for(const I of i){const W=ps(I);Q[W]=E(W,I)}_(Q),C(!0),t(e.toolId,i,Q)},$=Q=>{if(Q.key==="Enter"&&!(!L||!D)){if(Q.preventDefault(),F){P();return}O()}};if(w||s){const Q=o||x||{};return f.jsx("div",{className:"w-full",children:f.jsxs("div",{className:"rounded-2xl border border-border overflow-hidden",children:[f.jsxs("div",{className:"font-medium text-sm p-3 px-4 pr-5 bg-muted border-b border-border flex flex-row items-center justify-between",children:[f.jsxs("p",{children:["Question",i.length!==1?"s":""]}),f.jsx("p",{className:"",children:l?"Discarded":"Answers"})]}),i.map((I,W)=>{const te=Q[ps(I)]||Q[I.question]||[],U=W===i.length-1;return f.jsxs("div",{className:he("w-full p-3 pt-2.5 pl-4 pr-5 bg-background flex items-center justify-between gap-3",!U&&"border-b border-border"),children:[f.jsx("div",{className:"text-sm text-pretty",children:I.question}),te.length>0&&f.jsx("div",{className:"text-sm font-medium text-right max-w-[50%] text-pretty",children:te.join(", ")}),te.length===0&&f.jsx("div",{className:"text-sm font-medium text-right italic",children:l?"Discarded":"No Response"})]},ps(I))})]})})}if(r.readonly)return f.jsx("div",{className:"w-full",children:f.jsxs("div",{className:"rounded-2xl border border-border overflow-hidden",children:[f.jsxs("div",{className:"font-medium text-sm p-3 px-4 pr-5 bg-muted border-b border-border flex flex-row items-center justify-between gap-3",children:[f.jsxs("p",{children:["Question",i.length!==1?"s":""]}),f.jsx("p",{className:"text-muted-foreground",children:"Awaiting response"})]}),i.map((Q,I)=>{var W;return f.jsxs("div",{className:he("w-full p-3 pt-2.5 pl-4 pr-5 bg-background flex items-center justify-between gap-3",I<i.length-1&&"border-b border-border"),children:[f.jsx("div",{className:"text-sm text-pretty",children:Q.question}),f.jsx("div",{className:"max-w-[50%] text-right text-xs text-muted-foreground text-pretty",children:((W=Q.options)==null?void 0:W.map(te=>te.label).join(", "))||"Freeform response"})]},ps(Q))})]})});if(!n)return f.jsx("div",{className:"w-full py-2",children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(R5,{className:"h-4 w-4 text-muted-foreground"}),f.jsx("span",{className:"text-sm text-muted-foreground",children:"Questions pending (newer question active)"})]})});if(!L)return null;const H=k(L),B=g[ps(L)]||"";return f.jsxs("div",{className:"w-full space-y-3",children:[f.jsxs(T0e,{question:L.question,currentIndex:c,totalQuestions:i.length,onBack:c>0?z:void 0,children:[(G=L.options)==null?void 0:G.map(Q=>f.jsx(N0e,{option:Q,selected:H.includes(Q.label),multiSelect:L.multiSelect,onClick:()=>N(L,Q.label)},Q.label)),f.jsx("div",{className:"transition-all bg-background",children:f.jsxs("div",{className:"flex pr-5 items-center justify-between gap-3",children:[f.jsx("input",{type:"text",value:B,onChange:Q=>R(L,Q.target.value),onKeyDown:$,placeholder:"Other...",className:"flex-1 px-3 !py-1 pl-4 min-h-[55px] min-w-0 text-sm bg-transparent outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background rounded-md text-foreground placeholder:text-muted-foreground"}),f.jsx(kF,{selected:!!B,multiSelect:L.multiSelect,onClick:L.multiSelect&&B?()=>A(L):void 0})]})})]}),f.jsxs("div",{className:"flex justify-end gap-2 mx-2",children:[!F&&D&&(L.multiSelect||!!B)&&f.jsx(Ue,{size:"sm",onClick:O,children:"Next"}),F&&f.jsx(Ue,{size:"sm",onClick:P,disabled:!M,className:he(!M&&"opacity-50 cursor-not-allowed","rounded-full"),children:"Submit"})]})]})}function TF({message:e,onConfirm:t,isLatest:n}){const r=v0(),i=!!e.result,[s,o]=v.useState(!1),[l,c]=v.useState(!1),[u,m]=v.useState(!1),[h,g]=v.useState(""),b=v.useRef(null),x=e.input;v.useEffect(()=>{u&&b.current&&b.current.focus()},[u]);const _=async()=>{x!=null&&x.plan&&(await navigator.clipboard.writeText(x.plan),c(!0),setTimeout(()=>c(!1),2e3))},w=i?e.result:null,C=(w==null?void 0:w.discarded)===!0;return f.jsxs("div",{className:"flex flex-col gap-3",children:[f.jsxs("div",{className:"relative rounded-2xl border border-border overflow-hidden group/plan",children:[(x==null?void 0:x.plan)&&f.jsx(Ue,{variant:"ghost",size:"icon","aria-label":l?"Copied":"Copy plan",className:he("absolute top-2 right-2 z-10 h-11 w-11 md:h-8 md:w-8 rounded-md text-muted-foreground opacity-100 md:opacity-0 md:group-hover/plan:opacity-100 transition-opacity [@media(hover:none)]:!opacity-100",!l&&"hover:text-foreground",l&&"hover:!bg-transparent hover:!border-transparent"),onClick:_,children:l?f.jsx(_i,{className:"h-4 w-4 text-success"}):f.jsx(Pl,{className:"h-4 w-4"})}),f.jsxs("div",{className:he("!pt-5 !pb-0 px-4 md:py-4.5 md:px-5.5 bg-muted dark:bg-card overflow-scroll no-pre-highlight transition-all",i&&!s?"max-h-[min(400px,40vh)] ":"",i?"hover:!pb-[32px]":""),children:[i&&f.jsxs(Ue,{variant:"ghost",className:"absolute z-10 bottom-2 pr-2.5 !pl-3.5 h-[34px] inline-flex gap-1 text-sm left-[50%] -translate-x-[50%] text-muted-foreground backdrop-blur-sm hover:text-foreground opacity-0 group-hover/plan:opacity-100 transition-all rounded-full border border-border",onClick:()=>o(!s),children:[s?"Show Less":"Show More",f.jsx(nf,{className:`size-3.5 transition-transform ${s?"rotate-180":""}`})]}),x!=null&&x.plan?f.jsxs("div",{className:"prose prose-sm dark:prose-invert max-w-none",children:[f.jsx(lu,{remarkPlugins:Sf,components:Cf,children:x.plan}),f.jsx("div",{className:"mt-5"})]}):f.jsx("p",{className:"text-sm text-muted-foreground",children:"No plan provided"})]})]}),i?f.jsx("div",{className:"flex justify-end mx-2",children:f.jsxs("span",{className:"pl-4 inline text-sm font-medium bg-background text-foreground/60 border border-border py-1.5 px-3 rounded-[20px] leading-relaxed max-w-[85%] sm:max-w-[80%]",children:[f.jsx("em",{children:C?"Discarded":w!=null&&w.clearContext?"Approved & Cleared Context":w!=null&&w.confirmed?"Approved":w!=null&&w.message?`Adjusted: "${w.message}"`:"Adjusted Plan"}),f.jsx(UV,{className:"inline h-4 w-4 ml-1.5 -mt-0.5"})]})}):n?r.readonly?f.jsx("div",{className:"flex justify-end mx-2",children:f.jsx("span",{className:"inline text-sm text-muted-foreground italic",children:"Plan pending in original session"})}):f.jsxs("div",{className:"flex flex-col gap-3",children:[!u&&f.jsxs("div",{className:"flex flex-col md:flex-row items-stretch md:items-center justify-end gap-2 mx-2",children:[f.jsxs(Ue,{size:"sm",onClick:()=>t(e.toolId,!0,!0),className:"rounded-full bg-primary text-background pr-4 md:order-last",children:[f.jsx(xV,{className:"h-4 w-4 mr-1.5"}),"Approve & Clear"]}),f.jsxs("div",{className:"flex items-stretch md:items-center gap-2 md:contents",children:[f.jsxs(Ue,{size:"sm",variant:"outline",onClick:()=>m(!0),className:"rounded-full border-border flex-1 md:flex-initial md:order-first",children:[f.jsx(Qm,{className:"h-4 w-4 mr-1.5"}),"Suggest Edits"]}),f.jsxs(Ue,{size:"sm",variant:"outline",onClick:()=>t(e.toolId,!0),className:"rounded-full border-border flex-1 md:flex-initial",children:[f.jsx(_i,{className:"h-4 w-4 mr-1.5"}),"Approve"]})]})]}),u&&f.jsxs("div",{className:"flex flex-col gap-2",children:[f.jsx("textarea",{ref:b,value:h,onChange:E=>g(E.target.value),onKeyDown:E=>{E.key==="Enter"&&!E.shiftKey&&h.trim()&&(E.preventDefault(),t(e.toolId,!1,void 0,h.trim())),E.key==="Escape"&&(m(!1),g(""))},placeholder:"Describe what you'd like to change...",rows:3,className:"w-full rounded-2xl border border-border bg-muted dark:bg-card px-4 py-3 text-sm text-foreground placeholder:text-muted-foreground resize-none outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"}),f.jsxs("div",{className:"flex items-center justify-end gap-2 mx-2",children:[f.jsx(Ue,{size:"sm",variant:"ghost",onClick:()=>{m(!1),g("")},className:"rounded-full text-muted-foreground",children:"Cancel"}),f.jsxs(Ue,{size:"sm",disabled:!h.trim(),onClick:()=>t(e.toolId,!1,void 0,h.trim()),className:"rounded-full bg-primary text-background disabled:opacity-50 disabled:pointer-events-none",children:[f.jsx(MG,{className:"h-4 w-4 mr-1.5"}),"Adjust Plan"]})]})]})]}):f.jsx("div",{className:"flex justify-end mx-2",children:f.jsx("span",{className:"inline text-sm text-muted-foreground italic",children:"Plan pending (newer prompt active)"})})]})}function A0e({pendingTool:e,onAskUserQuestionSubmit:t,onExitPlanModeSubmit:n}){if(e.toolKind==="ask_user_question"){const r=e.input,i={id:e.toolUseId,kind:"tool",toolKind:"ask_user_question",toolName:"AskUserQuestion",toolId:e.toolUseId,input:{questions:r.questions??[]},timestamp:new Date(e.requestedAt).toISOString()};return f.jsxs("div",{"data-testid":`subagent-pending-tool:${e.toolUseId}`,children:[f.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-1",children:"awaiting your response"}),f.jsx(EF,{message:i,onSubmit:t,isLatest:!0})]})}if(e.toolKind==="exit_plan_mode"){const r=e.input,i={id:e.toolUseId,kind:"tool",toolKind:"exit_plan_mode",toolName:"ExitPlanMode",toolId:e.toolUseId,input:{plan:r.plan,summary:r.summary},timestamp:new Date(e.requestedAt).toISOString()};return f.jsxs("div",{"data-testid":`subagent-pending-tool:${e.toolUseId}`,children:[f.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-1",children:"awaiting your response"}),f.jsx(TF,{message:i,onConfirm:(s,o,l,c)=>n(s,{confirmed:o,clearContext:l,message:c}),isLatest:!0})]})}return null}function NF({run:e,indentDepth:t,localPath:n,onOpenSettings:r,onRetry:i,onSubagentAskUserQuestionSubmit:s,onSubagentExitPlanModeSubmit:o,onCancelSubagentRun:l}){var h;const c=pF(e.entries),u=c.some(g=>g.kind==="assistant_text"),m=e.status==="running"&&u;return f.jsxs("div",{"data-testid":`subagent-message:${e.runId}`,className:he("border-l-2 border-accent pl-3 py-2 space-y-2"),style:{marginLeft:`${t*24}px`},children:[f.jsxs("header",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[f.jsx(tf,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:e.subagentName}),f.jsxs("span",{className:"opacity-60",children:[e.provider,e.model?`/${e.model}`:""]}),((h=e.usage)==null?void 0:h.outputTokens)!=null&&f.jsxs("span",{className:"opacity-60",children:["· ",e.usage.inputTokens??0,"↑ ",e.usage.outputTokens,"↓"]}),e.status==="running"&&f.jsx("span",{className:"ml-auto inline-block animate-pulse",children:m?"streaming...":"running..."}),l&&e.status==="running"&&f.jsx("button",{type:"button","data-testid":`subagent-cancel:${e.runId}`,"aria-label":"Cancel subagent",onClick:()=>l(e.chatId,e.runId),className:"text-muted-foreground hover:text-foreground",children:f.jsx(io,{className:"h-3.5 w-3.5"})})]}),c.map(g=>f.jsx(C0e,{message:g,localPath:n},g.id)),e.pendingTool&&f.jsx(A0e,{pendingTool:e.pendingTool,onAskUserQuestionSubmit:(g,b,x)=>s==null?void 0:s(e.runId,g,b,x),onExitPlanModeSubmit:(g,b)=>o==null?void 0:o(e.runId,g,b)}),c.length===0&&e.finalText&&f.jsxs("div",{className:he("whitespace-pre-wrap text-sm",m&&"text-foreground/80"),children:[e.finalText,m&&f.jsx("span",{className:"ml-0.5 inline-block w-2 animate-pulse",children:"▍"})]}),e.status==="failed"&&e.error&&f.jsx("div",{children:f.jsx(E0e,{error:e.error,runId:e.runId,subagentId:e.subagentId,onOpenSettings:r,onRetry:i})})]})}function M0e(e){var n;const t=e.match(/^<system-message>\s*([\s\S]*?)\s*<\/system-message>\s*([\s\S]*)$/);return t?{systemMessage:((n=t[1])==null?void 0:n.trim())||null,body:t[2]??""}:{systemMessage:null,body:e}}const L0e=v.memo(function({content:t,attachments:n=[],steered:r=!1,autoContinue:i}){const[s,o]=v.useState(null),l=v0(),c=v.useMemo(()=>M0e(t),[t]),u=l.attachmentMode==="metadata",m=!l.readonly||l.attachmentMode==="bundle",h=v.useMemo(()=>n.filter(w=>w.kind==="image"&&(w.contentUrl||u)),[n,u]),g=v.useMemo(()=>n.filter(w=>w.kind!=="image"||!w.contentUrl&&!u),[n,u]),b=n.find(w=>w.id===s)??null,x=b?yp(b,"user_attachment"):null;function _(w){if(!m||!w.contentUrl)return;if(yf(w).openInNewTab){typeof window<"u"&&window.open(new URL(w.contentUrl,document.baseURI||window.location.href).toString(),"_blank","noopener,noreferrer");return}o(w.id)}return f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"flex flex-col items-end gap-2",children:[h.length>0?f.jsx("div",{className:"flex max-w-[85%] sm:max-w-[80%] flex-wrap justify-end gap-3",children:h.map(w=>f.jsx(i2,{attachment:w,onClick:m?()=>_(w):void 0},w.id))}):null,g.length>0?f.jsx("div",{className:"flex max-w-[85%] sm:max-w-[80%] flex-wrap justify-end gap-2",children:g.map(w=>f.jsx(Do,{attachment:w,onClick:m?()=>_(w):void 0},w.id))}):null,c.body||!c.body&&n.length===0&&t&&!c.systemMessage?f.jsxs("div",{className:"flex max-w-[85%] items-center gap-2 sm:max-w-[80%]",children:[r?f.jsx(mq,{"aria-label":"Sent mid-turn",className:"size-3.5 shrink-0 text-muted-foreground"}):null,f.jsx("div",{className:"min-w-0 flex-1 rounded-[20px] border border-border bg-muted px-3.5 py-1.5 text-primary prose prose-sm prose-invert [&_p]:whitespace-pre-line",children:f.jsx(lu,{remarkPlugins:Sf,components:Cf,children:c.body})})]}):null,i?f.jsx("span",{className:"text-xs text-muted-foreground opacity-70",children:"auto-sent"}):null]}),f.jsx(wf,{source:x,open:x!==null,onOpenChange:w=>!w&&o(null)})]})});function j0e({json:e}){return f.jsx("div",{className:"flex gap-3 justify-start",children:f.jsx("div",{className:"flex-1 max-w-[90%]",children:f.jsx("pre",{className:"text-xs font-mono whitespace-pre-wrap break-words bg-muted rounded-lg p-3 overflow-auto max-h-96",children:e})})})}function RF({title:e,count:t,children:n,badge:r}){const[i,s]=v.useState(!1);return t===0?null:f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsxs("button",{onClick:()=>s(!i),className:"flex items-center gap-1 cursor-pointer group/section hover:opacity-60 transition-opacity",children:[f.jsx(Po,{className:he("h-3.5 w-3.5 text-muted-foreground transition-transform duration-200",i&&"rotate-90")}),f.jsx("span",{className:"text-muted-foreground font-medium",children:e}),f.jsx("span",{className:"text-muted-foreground/60",children:t}),r]}),i&&f.jsx("div",{className:"ml-5",children:n})]})}function rS({title:e,items:t,icon:n,getIcon:r}){return t.length===0?null:f.jsx(RF,{title:e,count:t.length,children:f.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.map(i=>f.jsx($B,{icon:r?r(i):n,children:i},i))})})}function D0e(e){const t=e.match(/^mcp__([^_]+)__(.+)$/);return t?{server:t[1],tool:t[2]}:null}function AF({status:e}){const t=e==="connected"?"bg-success":e==="pending"?"bg-warning":"bg-destructive";return f.jsx("span",{className:he("inline-block h-2 w-2 rounded-full shrink-0",t)})}function I0e(e){switch(e){case"connected":return"Connected";case"failed":return"Failed";case"needs-auth":return"Needs auth";case"pending":return"Connecting...";case"disabled":return"Disabled";default:return e}}function KD({server:e}){const[t,n]=v.useState(!1),r=e.status==="connected";return f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsxs("button",{onClick:()=>r&&e.tools.length>0&&n(!t),className:he("flex items-center gap-1.5",r&&e.tools.length>0&&"cursor-pointer hover:opacity-60 transition-opacity"),children:[r&&e.tools.length>0&&f.jsx(Po,{className:he("h-3 w-3 text-muted-foreground transition-transform duration-200",t&&"rotate-90")}),f.jsx(AF,{status:e.status}),f.jsx("span",{className:"text-muted-foreground font-medium",children:VS(e.name)}),r?f.jsxs("span",{className:"text-muted-foreground/50",children:[e.tools.length," tools"]}):f.jsx("span",{className:"text-muted-foreground/50",children:I0e(e.status)})]}),!r&&e.error&&f.jsx("span",{className:"text-destructive ml-5",children:e.error}),t&&e.tools.length>0&&f.jsx("div",{className:"flex flex-wrap gap-1.5 ml-5",children:e.tools.map(i=>f.jsx($B,{icon:zB(`mcp__${e.name}__${i}`),children:i},i))})]})}function P0e({servers:e}){if(e.length===0)return null;const t=e.filter(i=>i.status==="connected"),n=e.filter(i=>i.status!=="connected"),r=n.length>0?f.jsxs("span",{className:"flex items-center gap-1 ml-1",children:[f.jsx(AF,{status:"failed"}),f.jsxs("span",{className:"text-muted-foreground/60",children:[n.length," disconnected"]})]}):null;return f.jsx(RF,{title:"MCP Servers",count:e.length,badge:r,children:f.jsxs("div",{className:"flex flex-col gap-2",children:[t.map(i=>f.jsx(KD,{server:i},i.name)),n.map(i=>f.jsx(KD,{server:i},i.name))]})})}function O0e({rawJson:e}){const[t,n]=v.useState(!1);return f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsxs("button",{onClick:()=>n(!t),className:"flex items-center gap-1 cursor-pointer group/section hover:opacity-60 transition-opacity",children:[f.jsx(Po,{className:he("h-3.5 w-3.5 text-muted-foreground transition-transform duration-200",t&&"rotate-90")}),f.jsx("span",{className:"text-muted-foreground font-medium",children:"Raw Message"})]}),t&&f.jsx("pre",{className:"ml-5 text-xs whitespace-pre-wrap break-all border border-border rounded-md p-3 overflow-x-auto max-h-96 overflow-y-auto",children:e})]})}function z0e({message:e,rawJson:t}){const{coreTools:n,mcpServersWithTools:r}=v.useMemo(()=>{const i=new Map,s=[];for(const l of e.tools){const c=D0e(l);if(c){const u=i.get(c.server)||[];u.push(c.tool),i.set(c.server,u)}else s.push(l)}const o=e.mcpServers.map(l=>({name:l.name,status:l.status,error:l.error,tools:i.get(l.name)||[]}));return{coreTools:s,mcpServersWithTools:o}},[e.tools,e.mcpServers]);return f.jsx(ja,{children:f.jsxs(b0,{expandedContent:f.jsx(y0,{className:"my-4 text-xs",children:f.jsxs("div",{className:"flex flex-col gap-3",children:[f.jsx(pve,{children:e.model}),f.jsx(rS,{title:"Tools",items:n,getIcon:i=>K1[i]??OB}),f.jsx(rS,{title:"Agents",items:e.agents,icon:Ey}),f.jsx(rS,{title:"Commands",items:e.slashCommands,icon:FG}),f.jsx(P0e,{servers:r}),t&&f.jsx(O0e,{rawJson:t})]})}),children:[f.jsx(cV,{className:"h-5 w-5 text-logo"}),f.jsx(Fl,{children:"Session Started"})]})})}function B0e({message:e}){return f.jsx(ja,{className:"hidden",children:f.jsxs(b0,{expandedContent:f.jsx(y0,{className:"my-4 text-xs",children:f.jsx("pre",{className:"font-mono whitespace-pre-wrap break-all bg-muted border border-border rounded-lg p-2 max-h-64 overflow-auto",children:JSON.stringify(e.accountInfo,null,2)})}),children:[f.jsx("div",{className:"size-5 flex justify-center items-center ",children:f.jsx(Ey,{className:"h-4 w-4 text-muted-foreground"})}),f.jsx(Fl,{children:"Account"})]})})}const F0e={completed:{Icon:_i,iconClass:"text-success",textClass:"text-muted-foreground"},in_progress:{Icon:bn,iconClass:"text-foreground animate-spin",textClass:"text-foreground font-medium"},pending:{Icon:LV,iconClass:"text-muted-foreground",textClass:"text-muted-foreground"}};function $0e({message:e}){const t=e.input.todos;return t.length?f.jsx("div",{className:"w-full",children:f.jsxs("div",{className:"rounded-2xl border border-border overflow-hidden",children:[f.jsxs("h3",{className:"font-medium text-foreground text-sm p-3 px-4 bg-card border-b border-border flex items-center gap-2",children:[f.jsx(FW,{className:"h-4 w-4 text-muted-foreground"}),"Progress"]}),f.jsx("div",{children:t.map((n,r)=>{const i=r===t.length-1,{Icon:s,iconClass:o,textClass:l}=F0e[n.status];return f.jsxs("div",{className:he("flex items-center gap-3 px-4 py-2.5 bg-background",!i&&"border-b border-border"),children:[f.jsx(s,{className:he("h-4 w-4 flex-shrink-0",o)}),f.jsx("span",{className:he("text-sm",l),children:n.status==="in_progress"?n.activeForm:n.content})]},r)})})]})}):null}function H0e({message:e}){const t=e.result,n=t==null?void 0:t.contentUrl,[r,i]=v.useState("idle"),[s,o]=v.useState(!1);if(v.useEffect(()=>{if(!n)return;const _=new AbortController;return fetch(n,{method:"HEAD",signal:_.signal}).then(w=>{_.signal.aborted||i(w.ok?"ready":"missing")}).catch(()=>{}),()=>_.abort()},[n]),!t||!n)return null;const l={id:`offer-download-${e.toolId}`,kind:"file",displayName:t.displayName||t.fileName,absolutePath:t.relativePath,relativePath:t.relativePath,contentUrl:n,mimeType:t.mimeType??"application/octet-stream",size:t.size},c=xf(l),u=u0(c,t.mimeType),m=t.size>0?kf(t.size):null,h=f.jsxs(f.Fragment,{children:[u,m?f.jsxs(f.Fragment,{children:[" · ",f.jsx("span",{className:"tabular-nums",children:m})]}):null]});if(r==="missing")return f.jsx("div",{className:"flex","data-testid":"offer-download-link",children:f.jsx(Do,{attachment:l,disabledReason:"File no longer available"})});if(!yf(l).openInNewTab){const _=`Preview ${l.displayName}, ${u}${m?`, ${m}`:""}`;return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"flex","data-testid":"offer-download-link",children:f.jsx(Do,{attachment:l,onClick:()=>o(!0),meta:h,ariaLabel:_})}),f.jsx(wf,{source:s?yp(l,"offer_download"):null,open:s,onOpenChange:o})]})}const x=["Download",l.displayName,u,m].filter(Boolean);return f.jsx("div",{className:"flex","data-testid":"offer-download-link",children:f.jsx(Do,{attachment:l,href:n,download:t.fileName||void 0,meta:h,ariaLabel:x.join(", ")})})}const iS=new Map;function U0e(e){const{cacheKey:t,enabled:n,ref:r,fetcher:i,rootMargin:s}=e,o=iS.get(t),[l,c]=v.useState(o!==void 0?"ready":"idle"),[u,m]=v.useState(o!==void 0?o:null),[h,g]=v.useState(null),[b,x]=v.useState(t),_=v.useRef(null),w=v.useRef(t);if(w.current=t,b!==t){x(t);const C=iS.get(t);c(C!==void 0?"ready":"idle"),m(C!==void 0?C:null),g(null)}return v.useEffect(()=>{if(!n||o!==void 0)return;const C=r.current;if(!C||typeof IntersectionObserver>"u")return;let E=!1;const k=t,N=new IntersectionObserver(R=>{for(const A of R){if(!A.isIntersecting)continue;if(N.disconnect(),E)return;const M=new AbortController;_.current=M,c("loading"),i(M.signal).then(L=>{E||w.current!==k||(iS.set(k,L),m(L),c("ready"))}).catch(L=>{E||M.signal.aborted||w.current!==k||(g(L instanceof Error?L:new Error(String(L))),c("error"))});break}},{rootMargin:s??"200px"});return N.observe(C),()=>{var R;E=!0,N.disconnect(),(R=_.current)==null||R.abort(),_.current=null}},[o,t,n,r,i,s]),v.useMemo(()=>({state:l,data:u,error:h}),[l,u,h])}function V0e({source:e,onOpen:t,variant:n}){const r={id:e.id,kind:"file",displayName:e.displayName,mimeType:e.mimeType,size:e.size??0,contentUrl:e.contentUrl,relativePath:e.relativePath??"",absolutePath:""},i=xf(r),s=u0(i,e.mimeType),o=e.size&&e.size>0?kf(e.size):null;return i==="image"?f.jsx("button",{type:"button",onClick:t,"aria-label":`Preview ${e.displayName}`,className:"overflow-hidden rounded-xl border border-border bg-background",children:f.jsx("img",{src:e.contentUrl,alt:e.altText??e.displayName,loading:"lazy",className:"max-h-64 w-auto max-w-full object-contain"})}):n==="expanded"&&(i==="text"||i==="code"||i==="markdown"||i==="json"||i==="table")?f.jsx(W0e,{source:e,onOpen:t,friendlyType:s,sizeLabel:o}):f.jsx(Do,{attachment:r,onClick:t,meta:f.jsxs(f.Fragment,{children:[s,o?f.jsxs(f.Fragment,{children:[" · ",f.jsx("span",{className:"tabular-nums",children:o})]}):null]}),ariaLabel:`Preview ${e.displayName}, ${s}${o?`, ${o}`:""}`})}const W0e=function({source:t,onOpen:n,friendlyType:r,sizeLabel:i}){const s=v.useRef(null),o=t.contentUrl,l=v.useCallback(async m=>{const h=await BE(o,4096);if(m.aborted)throw new Error("aborted");return h.content.slice(0,200)},[o]),c=U0e({ref:s,enabled:!0,cacheKey:`snippet:${t.id}|${t.contentUrl}|${t.size??0}`,fetcher:l}),u=c.state==="ready"&&typeof c.data=="string"?c.data:"";return f.jsxs("button",{ref:s,type:"button",onClick:n,"aria-label":`Preview ${t.displayName}`,className:"flex w-full max-w-md flex-col items-start gap-1 rounded-xl border border-border bg-background p-3 text-left hover:bg-accent/40",children:[f.jsx("div",{className:"text-sm font-medium text-foreground",children:t.displayName}),f.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[r,i?` · ${i}`:""]}),u?f.jsx("pre",{className:"line-clamp-3 max-h-16 w-full whitespace-pre-wrap break-words text-[11px] text-muted-foreground",children:u}):null]})};function G0e({message:e}){const{status:t,revisedPrompt:n}=e.input,r=e.result,i=r==null?void 0:r.contentUrl,s=e.isError||t==="failed",[o,l]=v.useState(!1);if(!s&&!r&&t==="in_progress")return f.jsxs("div",{className:"flex flex-col gap-1 rounded-md border border-border/40 bg-muted/30 px-3 py-2 text-sm text-muted-foreground","data-testid":"image-generation-pending",children:[f.jsx("span",{children:"Generating image…"}),n?f.jsx("span",{className:"italic",children:n}):null]});if(s||!r||!i)return f.jsxs("div",{className:"flex flex-col gap-1 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm","data-testid":"image-generation-error",children:[f.jsx("span",{children:"Image generation failed."}),r!=null&&r.relativePath?f.jsx("span",{className:"text-muted-foreground",children:r.relativePath}):null]});const c={id:`image-gen-${e.toolId}`,contentUrl:i,displayName:r.fileName,fileName:r.fileName,relativePath:r.relativePath,mimeType:"image/png",origin:"image_generation",altText:n??void 0};return f.jsxs("figure",{className:"flex flex-col gap-2","data-testid":"image-generation",children:[f.jsx(V0e,{source:c,onOpen:()=>l(!0),variant:"expanded"}),n?f.jsx("figcaption",{className:"text-xs text-muted-foreground italic",children:n}):null,f.jsx(wf,{source:o?c:null,open:o,onOpenChange:l})]})}function q0e({message:e}){return f.jsx("div",{className:"flex items-center justify-end gap-2 text-sm text-muted-foreground",children:f.jsxs("div",{className:"inline-flex gap-1.5 items-center justify-center whitespace-nowrap text-sm font-medium bg-background text-foreground/60 border border-border h-9 pl-1 pr-4 rounded-full",children:[f.jsx(AV,{className:"h-4 w-4 ml-1.5"}),f.jsx("em",{children:"Interrupted"})]})})}function ly({size:e=4}){return f.jsxs("svg",{className:"flex-1",viewBox:`0 0 100 ${e}`,preserveAspectRatio:"none",style:{height:`${e}px`},children:[f.jsx("pattern",{id:"zigzag",width:e,height:e,patternUnits:"userSpaceOnUse",children:f.jsx("path",{d:`M0 ${e} L${e/2} 0 L${e} ${e}`,fill:"none",stroke:"currentColor",strokeWidth:"0.5",className:"text-muted-foreground/30",style:{stroke:"currentColor"}})}),f.jsx("rect",{width:"100%",height:e,fill:"url(#zigzag)",className:"text-muted-foreground/30"})]})}function K0e(){return f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx(ly,{}),f.jsx("span",{className:"text-[11px] tracking-widest text-muted-foreground uppercase flex-shrink-0",children:"Compacted"}),f.jsx(ly,{})]})}function Y0e(){return f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx(ly,{}),f.jsx("span",{className:"text-[11px] tracking-widest text-muted-foreground uppercase flex-shrink-0",children:"Context Cleared"}),f.jsx(ly,{})]})}function X0e({message:e}){return f.jsx(ja,{children:f.jsxs(b0,{expandedContent:f.jsx(y0,{className:"my-4 text-xs",children:f.jsx("div",{className:"prose prose-sm dark:prose-invert max-w-none",children:f.jsx(lu,{remarkPlugins:Sf,components:Cf,children:e.summary})})}),children:[f.jsx("div",{className:"w-5 h-5 relative flex items-center justify-center",children:f.jsx(A5,{className:"h-4.5 w-4.5 text-muted-foreground"})}),f.jsx(Fl,{children:"Summarized"})]})})}const Q0e={compacting:"Compacting..."};function Z0e({message:e}){const t=Q0e[e.status]||e.status;return f.jsxs(ja,{className:"grid grid-cols-[auto_1fr] items-center gap-1.5 text-sm animate-pulse",children:[f.jsx("div",{className:"w-5 h-5 relative flex items-center justify-center",children:f.jsx(A5,{className:"h-4.5 w-4.5 text-muted-foreground"})}),f.jsx(Fl,{className:"text-left transition-opacity duration-200 truncate",children:t})]})}const J0e={read_file:{key:"read",singular:"read",plural:"reads"},edit_file:{key:"edit",singular:"edit",plural:"edits"},write_file:{key:"write",singular:"write",plural:"writes"},delete_file:{key:"delete",singular:"delete",plural:"deletes"},bash:{key:"bash",singular:"command",plural:"commands"},grep:{key:"grep",singular:"search",plural:"searches"},glob:{key:"glob",singular:"glob",plural:"globs"},subagent_task:{key:"task",singular:"agent",plural:"agents"},web_search:{key:"websearch",singular:"web search",plural:"web searches"},skill:{key:"skill",singular:"skill",plural:"skills"},todo_write:{key:"todo",singular:"todo update",plural:"todo updates"}},exe={key:"other",singular:"tool call",plural:"tool calls"};function txe(e){return J0e[e]??exe}function nxe(e){const t=new Map,n=[];for(const r of e){const i=r.toolKind,s=txe(i),o=t.get(s.key);o?o.count++:(t.set(s.key,{category:s,count:1}),n.push(s.key))}return n.map(r=>{const{category:i,count:s}=t.get(r);return`${s} ${s===1?i.singular:i.plural}`}).join(", ")}function rxe({messages:e,isLoading:t,localPath:n,expanded:r,onExpandedChange:i}){const s=v.useMemo(()=>nxe(e),[e]),l=e.some(c=>c.result===void 0)&&t;return f.jsx(ja,{className:"w-full",children:f.jsxs("div",{className:"flex flex-col w-full",children:[f.jsx("button",{onClick:()=>i(!r),className:`group cursor-pointer grid grid-cols-[auto_1fr] items-center gap-1 text-sm ${!r&&!l?"hover:opacity-60 transition-opacity":""}`,children:f.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-1.5",children:[f.jsx("div",{className:"w-5 h-5 relative flex items-center justify-center",children:f.jsx(Po,{className:`h-4.5 w-4.5 text-muted-icon transition-all duration-200 ${r?"rotate-90":""}`})}),f.jsx(Fl,{className:"text-left",children:f.jsx(_p,{animate:l,children:s})})]})}),r&&f.jsxs("div",{className:"my-4 flex flex-col gap-3",children:[e.map(c=>f.jsx(ay,{message:c,isLoading:t,localPath:n},c.id)),e.length>5&&f.jsx("button",{onClick:()=>i(!1),className:"cursor-pointer grid grid-cols-[auto_1fr] items-center gap-1 text-xs hover:opacity-80 transition-opacity",children:f.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-1.5",children:[f.jsx("div",{className:"w-5 h-5 relative flex items-center justify-center",children:f.jsx(Po,{className:"h-4.5 w-4.5 text-muted-icon -rotate-90"})}),f.jsx(Fl,{className:"text-left",children:"Collapse"})]})})]})]})})}function ixe(e){if(e!=="system")return e}function sS(e,t){const n=ixe(t),r=new Intl.DateTimeFormat("en-GB",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(new Date(e)),i=o=>{var l;return((l=r.find(c=>c.type===o))==null?void 0:l.value)??"00"};let s=i("hour");return s==="24"&&(s="00"),`${i("day")}/${i("month")}/${i("year")} ${s}:${i("minute")}`}const sxe=/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})$/;function YD(e,t){if(e==="system")return-new Date(t).getTimezoneOffset();const n=new Intl.DateTimeFormat("en-US",{timeZone:e,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(new Date(t)),r=o=>{var l;return Number(((l=n.find(c=>c.type===o))==null?void 0:l.value)??0)};let i=r("hour");i===24&&(i=0);const s=Date.UTC(r("year"),r("month")-1,r("day"),i,r("minute"),r("second"));return Math.round((s-t)/6e4)}function oxe(e,t){const n=sxe.exec(e.trim());if(!n)return null;const[,r,i,s,o,l]=n,c=Number(r),u=Number(i),m=Number(s),h=Number(o),g=Number(l);if(u<1||u>12||c<1||c>31||h>23||g>59)return null;const b=Date.UTC(m,u-1,c,h,g),x=YD(t,b),_=b-x*6e4,w=YD(t,_);return _-(w-x)*6e4}const axe={neutral:"border-border bg-card",muted:"border-border/50 bg-card/50 opacity-75",success:"border-emerald-500/30 bg-emerald-500/5",error:"border-destructive/40 bg-destructive/5"},lxe={primary:"default",secondary:"secondary",ghost:"ghost",destructive:"destructive"};function ga({title:e,description:t,body:n,errorMessage:r,tone:i="neutral",actions:s=[]}){const[o,l]=v.useState(null),[c,u]=v.useState(null),m=v.useCallback(async g=>{if(o)return;u(null);let b;try{b=g.onClick()}catch(x){console.error("[transcript-action-card] sync click threw",x),u(x instanceof Error?x.message:String(x));return}if(b instanceof Promise){l(g.id);try{await b}catch(x){console.error("[transcript-action-card] async click rejected",x),u(x instanceof Error?x.message:String(x))}finally{l(null)}}},[o]),h=o!==null;return f.jsxs("div",{"data-focus-fallback-ignore":!0,className:he("rounded-lg border px-4 py-3 text-sm space-y-2 transition-colors",axe[i]),children:[f.jsx("div",{className:"flex items-start justify-between gap-3",children:f.jsxs("div",{className:"space-y-1 min-w-0 flex-1",children:[f.jsx("div",{className:"font-medium leading-tight",children:e}),t?f.jsx("div",{className:"text-muted-foreground text-xs leading-snug",children:t}):null]})}),n?f.jsx("div",{className:"text-xs leading-snug",children:n}):null,r?f.jsx("div",{className:"text-destructive text-xs leading-snug",children:r}):null,c?f.jsx("div",{className:"text-destructive text-xs leading-snug",role:"alert",children:c}):null,s.length>0?f.jsx("div",{className:"flex flex-wrap gap-2 pt-1",children:s.map(g=>{const b=o===g.id;return f.jsxs(Ue,{type:"button",size:"sm",variant:lxe[g.variant??"ghost"],disabled:g.disabled||h&&!b,onClick:()=>{m(g)},className:"gap-1.5",children:[b?f.jsx(bn,{className:"size-3.5 animate-spin"}):null,g.label]},g.id)})}):null]})}function cxe({schedule:e,onAccept:t,onReschedule:n,onCancel:r}){const[i,s]=v.useState(()=>sS(e.scheduledAt??e.resetAt,e.tz)),[o,l]=v.useState(!1),c=v.useMemo(()=>oxe(i,e.tz),[i,e.tz]),u=c!==null&&c>Date.now(),m=c===null?"Use format dd/mm/yyyy hh:mm":u?null:"Time must be in the future";if(e.state==="fired"){const x=sS(e.scheduledAt??e.resetAt,e.tz);return f.jsx(ga,{title:`Auto-continued at ${x}`,tone:"success"})}if(e.state==="cancelled")return f.jsx(ga,{title:"Auto-continue cancelled",tone:"muted"});if(e.state==="proposed"){const x=e.resetAt<=Date.now(),_=[{id:"schedule",label:"Schedule",variant:"primary",disabled:!u,onClick:()=>{c!==null&&t(c)}},{id:"dismiss",label:"Dismiss",variant:"ghost",onClick:()=>r()}];return f.jsx(ga,{title:"Rate limit hit — schedule auto-continue?",description:x?"Reset time has passed — accept to continue now.":void 0,body:f.jsxs("div",{className:"space-y-1",children:[f.jsx($n,{value:i,onChange:w=>s(w.target.value),placeholder:"dd/mm/yyyy hh:mm"}),m&&f.jsx("div",{className:"text-destructive text-xs",children:m})]}),actions:_})}const h=sS(e.scheduledAt??e.resetAt,e.tz),g=e.tz==="system"?"local":e.tz;if(!o){const x=[{id:"change",label:"Change time",variant:"secondary",onClick:()=>l(!0)},{id:"cancel",label:"Cancel",variant:"ghost",onClick:()=>r()}];return f.jsx(ga,{title:`Auto-continue at ${h} (${g})`,actions:x})}const b=[{id:"save",label:"Save",variant:"primary",disabled:!u,onClick:()=>{c!==null&&(n(c),l(!1))}},{id:"back",label:"Back",variant:"ghost",onClick:()=>l(!1)}];return f.jsx(ga,{title:`Auto-continue at ${h} (${g})`,body:f.jsxs("div",{className:"space-y-1",children:[f.jsx($n,{value:i,onChange:x=>s(x.target.value),placeholder:"dd/mm/yyyy hh:mm"}),m&&f.jsx("div",{className:"text-destructive text-xs",children:m})]}),actions:b})}function uxe({toolRequestId:e,questions:t,onAnswer:n}){const[r,i]=v.useState({});function s(u){return u.id??u.question}function o(u,m){const h=s(u);u.multiSelect?i(g=>{const b=g[h]??[],x=b.includes(m)?b.filter(_=>_!==m):[...b,m];return{...g,[h]:x}}):i(g=>({...g,[h]:[m]}))}function l(){const u={};for(const m of t){const h=s(m);u[h]=r[h]??[]}n(e,{kind:"answer",payload:{questions:t,answers:u}})}const c=t.every(u=>{var h;const m=s(u);return(((h=r[m])==null?void 0:h.length)??0)>0});return f.jsxs("div",{className:"rounded-2xl border border-border overflow-hidden",children:[f.jsxs("div",{className:"font-medium text-sm p-3 px-4 bg-muted border-b border-border flex items-center justify-between",children:[f.jsxs("span",{children:["Question",t.length!==1?"s":""]}),f.jsx("span",{className:"text-xs text-muted-foreground",children:"Reconnected — awaiting your response"})]}),t.map((u,m)=>{var x;const h=s(u),g=r[h]??[],b=m===t.length-1;return f.jsxs("div",{className:`bg-background px-4 py-3 ${b?"":"border-b border-border"}`,children:[f.jsx("p",{className:"text-sm font-medium mb-2",children:u.question}),u.options&&u.options.length>0?f.jsx("div",{className:"flex flex-wrap gap-2",children:u.options.map(_=>f.jsx("button",{onClick:()=>o(u,_.label),className:`rounded-full border px-3 py-1 text-xs transition-colors ${g.includes(_.label)?"border-foreground bg-foreground text-background":"border-border bg-background text-foreground hover:bg-muted"}`,children:_.label},_.label))}):f.jsx("input",{type:"text",className:"w-full rounded-md border border-border bg-muted px-3 py-1.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Type your answer...",value:((x=r[h])==null?void 0:x[0])??"",onChange:_=>{const w=_.target.value;i(C=>({...C,[h]:w?[w]:[]}))}})]},h)}),f.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3 bg-background border-t border-border",children:[f.jsx(Ue,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>n(e,{kind:"deny",reason:"user_canceled"}),children:"Cancel"}),f.jsx(Ue,{size:"sm",className:"rounded-full",disabled:!c,onClick:l,children:"Submit"})]})]})}function dxe({toolRequestId:e,plan:t,onAnswer:n}){return f.jsxs("div",{className:"rounded-2xl border border-border overflow-hidden",children:[f.jsxs("div",{className:"font-medium text-sm p-3 px-4 bg-muted border-b border-border flex items-center justify-between",children:[f.jsx("span",{children:"Plan"}),f.jsx("span",{className:"text-xs text-muted-foreground",children:"Reconnected — awaiting your response"})]}),f.jsx("div",{className:"bg-background px-4 py-3",children:f.jsx("p",{className:"text-sm whitespace-pre-wrap",children:t})}),f.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3 bg-background border-t border-border",children:[f.jsx(Ue,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>n(e,{kind:"deny",reason:"user_canceled"}),children:"Edit"}),f.jsx(Ue,{size:"sm",className:"rounded-full",onClick:()=>n(e,{kind:"answer",payload:{confirmed:!0}}),children:"Confirm"})]})]})}function fxe({toolRequestId:e,toolName:t,args:n,onAnswer:r}){const i=["command","path","url","pattern","query"].find(o=>typeof n[o]=="string"&&n[o].length>0),s=i?n[i]:JSON.stringify(n);return f.jsxs("div",{className:"rounded-2xl border border-border bg-background px-4 py-3 text-sm",children:[f.jsxs("div",{className:"flex items-baseline gap-2",children:[f.jsx("span",{className:"text-muted-foreground shrink-0",children:"Pending tool:"}),f.jsx("span",{className:"font-mono text-foreground",children:t})]}),s?f.jsx("pre",{className:"mt-1 max-h-32 overflow-auto whitespace-pre-wrap break-all font-mono text-xs text-muted-foreground",children:s}):null,f.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[f.jsx(Ue,{variant:"ghost",size:"sm",onClick:()=>r(e,{kind:"deny",reason:"user_canceled"}),children:"Deny"}),f.jsx(Ue,{variant:"default",size:"sm",onClick:()=>r(e,{kind:"allow"}),children:"Allow"})]})]})}function hxe({entry:e,onAnswer:t}){const{toolRequestId:n,toolName:r,arguments:i}=e;if(r==="mcp__kanna__ask_user_question"){const s=i.questions??[];return f.jsx(uxe,{toolRequestId:n,questions:s,onAnswer:t})}if(r==="mcp__kanna__exit_plan_mode"){const s=typeof i.plan=="string"?i.plan:"";return f.jsx(dxe,{toolRequestId:n,plan:s,onAnswer:t})}return f.jsx(fxe,{toolRequestId:n,toolName:r,args:i,onAnswer:t})}const mxe=new Set(["AskUserQuestion","ExitPlanMode","TodoWrite"]);function XD(e){if(e.kind!=="tool")return!1;const t=e.toolName;return!mxe.has(t)}function pxe(e,{isFirstSystem:t,isFirstAccount:n,isLatestTodoWrite:r,hideResult:i,isFinalStatus:s}){let o=!e.hidden;if(o)switch(e.kind){case"system_init":o=t;break;case"account_info":o=n;break;case"tool":o=e.toolKind!=="todo_write"||r;break;case"result":o=!i&&(!e.success||e.durationMs>6e4);break;case"context_window_updated":o=!1;break;case"status":o=s;break;default:o=!0;break}return{isFirstSystem:t,isFirstAccount:n,isLatestTodoWrite:r,hideResult:i,isFinalStatus:s,shouldRender:o}}function gxe(e,t){const n=e.findIndex(i=>i.kind==="system_init"),r=e.findIndex(i=>i.kind==="account_info");return e.map((i,s)=>{const o=e[s-1],l=e[s+1];return pxe(i,{isFirstSystem:n===s,isFirstAccount:r===s,isLatestTodoWrite:i.id===t.TodoWrite,hideResult:(l==null?void 0:l.kind)==="context_cleared"||(o==null?void 0:o.kind)==="context_cleared",isFinalStatus:s===e.length-1})})}function vxe(e,t){const n=[];let r=0;for(;r<e.length;){const i=e[r],s=t[r];if(s!=null&&s.shouldRender&&XD(i)){const o=[i],l=r;for(r+=1;r<e.length;){const c=e[r],u=t[r];if(!(u!=null&&u.shouldRender)){r+=1;continue}if(!XD(c))break;o.push(c),r+=1}o.length>=2?n.push({type:"tool-group",messages:o,startIndex:l}):n.push({type:"single",message:i,index:l});continue}n.push({type:"single",message:i,index:r}),r+=1}return n}function QD(e){var n;return e.type==="single"?e.message.id:`tool-group:${((n=e.messages[0])==null?void 0:n.id)??e.startIndex}`}function oS(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function bxe(e,t){return e.id===t.id&&e.kind===t.kind&&e.displayName===t.displayName&&e.absolutePath===t.absolutePath&&e.relativePath===t.relativePath&&e.contentUrl===t.contentUrl&&e.mimeType===t.mimeType&&e.size===t.size}function yxe(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>bxe(n,t[r]))}function Gd(e,t){var n,r;if(e===t)return!0;if(e.kind!==t.kind||e.id!==t.id||e.hidden!==t.hidden)return!1;switch(e.kind){case"user_prompt":return e.content===(t.kind==="user_prompt"?t.content:null)&&t.kind==="user_prompt"&&e.steered===t.steered&&((n=e.autoContinue)==null?void 0:n.scheduleId)===((r=t.autoContinue)==null?void 0:r.scheduleId)&&yxe(e.attachments,t.attachments);case"system_init":return t.kind==="system_init"&&e.provider===t.provider&&e.model===t.model&&oS(e.tools,t.tools)&&oS(e.agents,t.agents)&&oS(e.slashCommands,t.slashCommands)&&e.debugRaw===t.debugRaw;case"account_info":return t.kind==="account_info"&&JSON.stringify(e.accountInfo)===JSON.stringify(t.accountInfo);case"assistant_text":return t.kind==="assistant_text"&&e.text===t.text;case"tool":return t.kind==="tool"&&e.toolKind===t.toolKind&&e.toolName===t.toolName&&e.toolId===t.toolId&&e.isError===t.isError&&JSON.stringify(e.input)===JSON.stringify(t.input)&&JSON.stringify(e.result)===JSON.stringify(t.result)&&JSON.stringify(e.rawResult)===JSON.stringify(t.rawResult);case"result":return t.kind==="result"&&e.success===t.success&&e.cancelled===t.cancelled&&e.result===t.result&&e.durationMs===t.durationMs&&e.costUsd===t.costUsd;case"status":return t.kind==="status"&&e.status===t.status;case"compact_summary":return t.kind==="compact_summary"&&e.summary===t.summary;case"context_window_updated":return t.kind==="context_window_updated"&&JSON.stringify(e.usage)===JSON.stringify(t.usage);case"compact_boundary":case"context_cleared":case"interrupted":return!0;case"unknown":return t.kind==="unknown"&&e.json===t.json;case"auto_continue_prompt":return t.kind==="auto_continue_prompt"&&e.scheduleId===t.scheduleId;case"pending_tool_request":return t.kind==="pending_tool_request"&&e.toolRequestId===t.toolRequestId&&e.toolName===t.toolName}}function xxe(e,t){return e.kind!==t.kind||e.id!==t.id?!1:e.kind==="single"&&t.kind==="single"?e.index===t.index&&e.isLoading===t.isLoading&&e.localPath===t.localPath&&e.isFirstSystem===t.isFirstSystem&&e.isFirstAccount===t.isFirstAccount&&e.isLatestAskUserQuestion===t.isLatestAskUserQuestion&&e.isLatestExitPlanMode===t.isLatestExitPlanMode&&e.isLatestTodoWrite===t.isLatestTodoWrite&&e.hideResult===t.hideResult&&e.isFinalStatus===t.isFinalStatus&&Gd(e.message,t.message):e.kind==="tool-group"&&t.kind==="tool-group"?e.startIndex===t.startIndex&&e.isLoading===t.isLoading&&e.localPath===t.localPath&&e.messages.length===t.messages.length&&e.messages.every((n,r)=>Gd(n,t.messages[r])):!1}function _xe(e,t){const n=new Map;let r=e.length!==t.byId.size;const i=e.map((s,o)=>{const l=t.byId.get(s.id),c=l&&xxe(l,s)?l:s;return n.set(s.id,c),!r&&t.result[o]!==c&&(r=!0),c});return r?{byId:n,result:i}:t}function wxe(e){const t=v.useRef({byId:new Map,result:[]}),n=v.useMemo(()=>_xe(e,t.current),[e]);return v.useLayoutEffect(()=>{t.current=n}),n.result}const MF=(e,t)=>{},Sxe=v.memo(function({message:t,index:n,isLoading:r,localPath:i,isFirstSystem:s,isFirstAccount:o,isLatestAskUserQuestion:l,isLatestExitPlanMode:c,isLatestTodoWrite:u,hideResult:m,isFinalStatus:h,onAskUserQuestionSubmit:g,onExitPlanModeConfirm:b,onToolRequestAnswer:x=MF,schedules:_,onAutoContinueAccept:w,onAutoContinueReschedule:C,onAutoContinueCancel:E}){let k=null;if(t.kind==="user_prompt")k=f.jsx(L0e,{content:t.content,attachments:t.attachments,steered:t.steered,autoContinue:t.autoContinue},t.id);else switch(t.kind){case"auto_continue_prompt":{const N=_[t.scheduleId];if(!N){k=f.jsx("div",{className:"rounded border px-3 py-2 text-sm opacity-70",children:"Auto-continue expired"},t.id);break}k=f.jsx(cxe,{schedule:N,onAccept:R=>w(t.scheduleId,R),onReschedule:R=>C(t.scheduleId,R),onCancel:()=>E(t.scheduleId)},t.id);break}case"unknown":k=f.jsx(j0e,{json:t.json},t.id);break;case"system_init":k=s?f.jsx(z0e,{message:t,rawJson:t.debugRaw},t.id):null;break;case"account_info":k=o?f.jsx(B0e,{message:t},t.id):null;break;case"assistant_text":k=f.jsx(SF,{message:t},t.id);break;case"tool":if(t.isError){k=f.jsx(ay,{message:t,isLoading:r,localPath:i},t.id);break}if(t.toolKind==="ask_user_question"){k=f.jsx(EF,{message:t,onSubmit:g,isLatest:l},t.id);break}if(t.toolKind==="exit_plan_mode"){k=f.jsx(TF,{message:t,onConfirm:b,isLatest:c},t.id);break}if(t.toolKind==="todo_write"){k=u?f.jsx($0e,{message:t},t.id):null;break}if(t.toolKind==="offer_download"&&t.result){k=f.jsx(H0e,{message:t},t.id);break}if(t.toolKind==="image_generation"){k=f.jsx(G0e,{message:t},t.id);break}k=f.jsx(ay,{message:t,isLoading:r,localPath:i},t.id);break;case"result":k=m?null:f.jsx(CF,{message:t},t.id);break;case"context_window_updated":k=null;break;case"interrupted":k=f.jsx(q0e,{message:t},t.id);break;case"compact_boundary":k=f.jsx(K0e,{},t.id);break;case"context_cleared":k=f.jsx(Y0e,{},t.id);break;case"compact_summary":k=f.jsx(X0e,{message:t},t.id);break;case"status":k=h?f.jsx(Z0e,{message:t},t.id):null;break;case"pending_tool_request":k=f.jsx(hxe,{entry:t,onAnswer:x},t.id);break}return k?f.jsx("div",{id:`msg-${t.id}`,className:"group relative","data-index":n,[Eb]:"",children:k}):null},(e,t)=>e.index===t.index&&e.isLoading===t.isLoading&&e.localPath===t.localPath&&e.isFirstSystem===t.isFirstSystem&&e.isFirstAccount===t.isFirstAccount&&e.isLatestAskUserQuestion===t.isLatestAskUserQuestion&&e.isLatestExitPlanMode===t.isLatestExitPlanMode&&e.isLatestTodoWrite===t.isLatestTodoWrite&&e.hideResult===t.hideResult&&e.isFinalStatus===t.isFinalStatus&&e.onAskUserQuestionSubmit===t.onAskUserQuestionSubmit&&e.onExitPlanModeConfirm===t.onExitPlanModeConfirm&&e.onToolRequestAnswer===t.onToolRequestAnswer&&e.schedules===t.schedules&&e.onAutoContinueAccept===t.onAutoContinueAccept&&e.onAutoContinueReschedule===t.onAutoContinueReschedule&&e.onAutoContinueCancel===t.onAutoContinueCancel&&Gd(e.message,t.message)),Cxe=v.memo(function({id:t,messages:n,isLoading:r,localPath:i,expanded:s,onExpandedChange:o}){return f.jsx("div",{className:"group relative",[Eb]:"",children:f.jsx(rxe,{messages:n,isLoading:r,localPath:i,expanded:s,onExpandedChange:l=>o(t,l)})})},(e,t)=>e.id===t.id&&e.startIndex===t.startIndex&&e.isLoading===t.isLoading&&e.localPath===t.localPath&&e.expanded===t.expanded&&e.onExpandedChange===t.onExpandedChange&&e.messages.length===t.messages.length&&e.messages.every((n,r)=>Gd(n,t.messages[r])));function LF(e,{isLoading:t,localPath:n,latestToolIds:r}){const i=gxe(e,r),s=vxe(e,i),o=[];for(const l of s){if(l.type==="tool-group"){o.push({kind:"tool-group",id:QD(l),startIndex:l.startIndex,messages:l.messages,isLoading:t&&l.messages.some(m=>m.kind==="tool"&&m.result===void 0),localPath:n});continue}const c=i[l.index];if(!c)continue;const u={kind:"single",id:QD(l),message:l.message,index:l.index,isLoading:l.message.kind==="tool"&&l.message.result===void 0&&t,localPath:n,isFirstSystem:c.isFirstSystem,isFirstAccount:c.isFirstAccount,isLatestAskUserQuestion:l.message.id===r.AskUserQuestion,isLatestExitPlanMode:l.message.id===r.ExitPlanMode,isLatestTodoWrite:c.isLatestTodoWrite,hideResult:c.hideResult,isFinalStatus:c.isFinalStatus};c.shouldRender&&o.push(u)}return o}const kxe={};function jF(e,t,n,r,i,s,o){const l=n.get(e.runId)??[];return f.jsxs(Cn.Fragment,{children:[f.jsx(NF,{run:e,indentDepth:t,localPath:r,onSubagentAskUserQuestionSubmit:i,onSubagentExitPlanModeSubmit:s,onCancelSubagentRun:o}),l.map(c=>jF(c,t+1,n,r,i,s,o))]},e.runId)}const DF=v.memo(function({row:t,toolGroupExpanded:n,onToolGroupExpandedChange:r,onAskUserQuestionSubmit:i,onExitPlanModeConfirm:s,onToolRequestAnswer:o,schedules:l,onAutoContinueAccept:c,onAutoContinueReschedule:u,onAutoContinueCancel:m}){return t.kind==="tool-group"?f.jsx(Cxe,{id:t.id,startIndex:t.startIndex,messages:t.messages,isLoading:t.isLoading,localPath:t.localPath,expanded:n??!1,onExpandedChange:r}):f.jsx(Sxe,{message:t.message,index:t.index,isLoading:t.isLoading,localPath:t.localPath,isFirstSystem:t.isFirstSystem,isFirstAccount:t.isFirstAccount,isLatestAskUserQuestion:t.isLatestAskUserQuestion,isLatestExitPlanMode:t.isLatestExitPlanMode,isLatestTodoWrite:t.isLatestTodoWrite,hideResult:t.hideResult,isFinalStatus:t.isFinalStatus,onAskUserQuestionSubmit:i,onExitPlanModeConfirm:s,onToolRequestAnswer:o,schedules:l,onAutoContinueAccept:c,onAutoContinueReschedule:u,onAutoContinueCancel:m})},(e,t)=>{if(e.toolGroupExpanded!==t.toolGroupExpanded||e.onToolGroupExpandedChange!==t.onToolGroupExpandedChange||e.onAskUserQuestionSubmit!==t.onAskUserQuestionSubmit||e.onExitPlanModeConfirm!==t.onExitPlanModeConfirm||e.onToolRequestAnswer!==t.onToolRequestAnswer||e.schedules!==t.schedules||e.onAutoContinueAccept!==t.onAutoContinueAccept||e.onAutoContinueReschedule!==t.onAutoContinueReschedule||e.onAutoContinueCancel!==t.onAutoContinueCancel||e.row.kind!==t.row.kind||e.row.id!==t.row.id)return!1;if(e.row.kind==="tool-group"&&t.row.kind==="tool-group"){const n=e.row,r=t.row;return n.startIndex===r.startIndex&&n.isLoading===r.isLoading&&n.localPath===r.localPath&&n.messages.length===r.messages.length&&n.messages.every((i,s)=>Gd(i,r.messages[s]))}return e.row.kind==="single"&&t.row.kind==="single"?e.row.index===t.row.index&&e.row.isLoading===t.row.isLoading&&e.row.localPath===t.row.localPath&&e.row.isFirstSystem===t.row.isFirstSystem&&e.row.isFirstAccount===t.row.isFirstAccount&&e.row.isLatestAskUserQuestion===t.row.isLatestAskUserQuestion&&e.row.isLatestExitPlanMode===t.row.isLatestExitPlanMode&&e.row.isLatestTodoWrite===t.row.isLatestTodoWrite&&e.row.hideResult===t.row.hideResult&&e.row.isFinalStatus===t.row.isFinalStatus&&Gd(e.row.message,t.row.message):!1}),IF={},Exe=(e,t)=>{},Txe=(e,t)=>{},Nxe=e=>{};function Rxe({messages:e,isLoading:t,localPath:n,latestToolIds:r,onOpenLocalLink:i,onAskUserQuestionSubmit:s,onExitPlanModeConfirm:o,onToolRequestAnswer:l=MF,schedules:c=IF,onAutoContinueAccept:u=Exe,onAutoContinueReschedule:m=Txe,onAutoContinueCancel:h=Nxe,onTunnelAccept:g,onTunnelStop:b,onTunnelRetry:x,subagentRuns:_=kxe,onSubagentAskUserQuestionSubmit:w,onSubagentExitPlanModeSubmit:C,onCancelSubagentRun:E}){const[k,N]=v.useState({}),R=v.useMemo(()=>LF(e,{isLoading:t,localPath:n,latestToolIds:r}),[t,r,n,e]),{runsByUserMessageId:A,childrenByParentRunId:M}=v.useMemo(()=>{const F=new Map,D=new Map;for(const z of Object.values(_))if(z.parentRunId===null){const P=F.get(z.parentUserMessageId)??[];P.push(z),F.set(z.parentUserMessageId,P)}else{const P=D.get(z.parentRunId)??[];P.push(z),D.set(z.parentRunId,P)}const O=(z,P)=>z.startedAt-P.startedAt||z.runId.localeCompare(P.runId);for(const z of F.values())z.sort(O);for(const z of D.values())z.sort(O);return{runsByUserMessageId:F,childrenByParentRunId:D}},[_]),L=v.useCallback((F,D)=>{N(O=>O[F]===D?O:{...O,[F]:D})},[]);return f.jsx(PB,{onOpenLocalLink:i,children:R.map(F=>{const D=F.kind==="single"&&F.message.kind==="user_prompt"?F.message.id:null,O=D?A.get(D)??[]:[];return f.jsxs("div",{className:"mx-auto max-w-[800px] pb-5",children:[f.jsx(DF,{row:F,toolGroupExpanded:F.kind==="tool-group"?k[F.id]??!1:void 0,onToolGroupExpandedChange:L,onAskUserQuestionSubmit:s,onExitPlanModeConfirm:o,onToolRequestAnswer:l,schedules:c,onAutoContinueAccept:u,onAutoContinueReschedule:m,onAutoContinueCancel:h}),O.map(z=>jF(z,0,M,n??"",w,C,E))]},F.id)})})}v.memo(Rxe);function Axe(e=1e3){const[t,n]=v.useState(()=>Date.now()),r=v.useRef(e);return v.useLayoutEffect(()=>{r.current=e}),v.useEffect(()=>{const i=window.setInterval(()=>{n(Date.now())},r.current);return()=>window.clearInterval(i)},[]),t}function Mxe(e){switch(e.kind){case"bash_shell":return e.command;case"terminal_pty":return`PTY: ${e.cwd}`;case"codex_session":return"Codex session";case"draining_stream":return"Draining stream"}}function Lxe(e){switch(e.kind){case"bash_shell":return"bash";case"terminal_pty":return"terminal";case"codex_session":return"codex";case"draining_stream":return"stream"}}function jxe(e){return"chatId"in e?e.chatId??null:null}function Dxe(e){return e.kind==="bash_shell"?e.status==="stopping"?"stopping":"running":"active"}function Ixe(e){return(e.lastOutput??"").split(`
2608
+ `),i=g0e(n,r),s=v0e(n,r,i);return b0e(s)}function g0e(e,t){const n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let s=1;s<=n;s++)for(let o=1;o<=r;o++)i[s][o]=e[s-1]===t[o-1]?i[s-1][o-1]+1:Math.max(i[s-1][o],i[s][o-1]);return i}function v0e(e,t,n){const r=[];let i=e.length,s=t.length;for(;i>0||s>0;)i>0&&s>0&&e[i-1]===t[s-1]?(r.push({type:"context",text:e[i-1],oldIdx:i,newIdx:s}),i--,s--):s>0&&(i===0||n[i][s-1]>=n[i-1][s])?(r.push({type:"added",text:t[s-1],oldIdx:i,newIdx:s}),s--):(r.push({type:"removed",text:e[i-1],oldIdx:i,newIdx:s}),i--);return r.reverse()}function b0e(e){return e.map(t=>{const n=t.type==="removed"?"-":t.type==="added"?"+":" ";return{type:t.type,content:`${n}${t.text}`}})}function Rv({content:e,isDiff:t=!1,oldString:n,newString:r}){const i=v.useMemo(()=>t&&n!==void 0&&r!==void 0?p0e(n,r):[],[t,n,r]),s=v.useMemo(()=>t?[]:h0e(e),[e,t]),o=v.useMemo(()=>s.some(l=>l.lineNumber!==null),[s]);return t&&i.length>0?f.jsx("div",{className:"my-1 rounded-lg border border-border overflow-hidden",children:f.jsx("div",{className:"overflow-auto max-h-64 md:max-h-[50vh]",children:f.jsx("table",{className:"w-full border-collapse text-xs font-mono",children:f.jsx("tbody",{children:i.map((l,c)=>{const u=l.type==="removed"?"bg-destructive/10 dark:bg-destructive/15":l.type==="added"?"bg-success/10 dark:bg-success/15":"",m=l.type==="removed"?"text-destructive":l.type==="added"?"text-success":"text-foreground";return f.jsxs("tr",{className:u,children:[f.jsx("td",{className:`px-2 py-0 select-none w-0 whitespace-nowrap ${l.type==="removed"?"text-destructive/50":l.type==="added"?"text-success/50":"text-muted-foreground/50"}`,children:l.type==="removed"?"-":l.type==="added"?"+":" "}),f.jsx("td",{className:`px-2 py-0 whitespace-pre select-all ${m}`,children:l.content.slice(1)})]},c)})})})})}):f.jsx("div",{className:"my-1 rounded-lg border border-border overflow-hidden",children:f.jsx("div",{className:"overflow-auto max-h-64 md:max-h-[50vh]",children:f.jsx("table",{className:"w-full border-collapse text-xs font-mono",children:f.jsx("tbody",{children:s.map((l,c)=>f.jsxs("tr",{children:[o&&f.jsx("td",{className:"px-2 py-0 select-none w-0 whitespace-nowrap text-muted-foreground/50 text-right",children:l.lineNumber!==null?l.lineNumber:""}),f.jsx("td",{className:"px-2 py-0 whitespace-pre select-all text-foreground",children:m0e(l.content)})]},c))})})})})}function WD(e){return(e&&typeof e=="object"&&"content"in e&&Array.isArray(e.content)?e.content:Array.isArray(e)?e:[]).flatMap(n=>!n||typeof n!="object"||!("type"in n)||n.type!=="image"?[]:"data"in n&&typeof n.data=="string"?[{type:"image",data:n.data,mimeType:typeof n.mimeType=="string"?n.mimeType:void 0}]:"source"in n&&n.source&&typeof n.source=="object"&&"type"in n.source&&n.source.type==="base64"&&"data"in n.source&&typeof n.source.data=="string"?[{type:"image",data:n.source.data,mimeType:typeof n.source.media_type=="string"?n.source.media_type:void 0}]:[])}function y0e({images:e}){return f.jsx("div",{className:"flex flex-col gap-3",children:e.map((t,n)=>{const r=t.mimeType||"image/png";return f.jsx("div",{className:"overflow-hidden rounded-lg border border-border bg-muted/20",children:f.jsx("img",{src:`data:${r};base64,${t.data}`,alt:`Read result ${n+1}`,className:"max-h-[50vh] w-full object-contain bg-background"})},`${r}:${n}`)})})}function ay({message:e,isLoading:t=!1,localPath:n}){var w;const r=e.result!==void 0,i=!r&&t,s=v.useMemo(()=>{if(e.toolKind==="skill")return e.input.skill;if(e.toolKind==="glob")return`Search files ${e.input.pattern==="**/*"?"in all directories":`matching ${e.input.pattern}`}`;if(e.toolKind==="grep"){const C=e.input.pattern,E=e.input.outputMode;return E==="count"?`Count \`${C}\` occurrences`:E==="content"?`Find \`${C}\` in text`:`Find \`${C}\` in files`}return e.toolKind==="bash"?e.input.description||(e.input.command?iZ(e.input.command):"Bash"):e.toolKind==="web_search"?e.input.query||"Web Search":e.toolKind==="read_file"?`Read ${bv(e.input.filePath,n)}`:e.toolKind==="write_file"?`Write ${bv(e.input.filePath,n)}`:e.toolKind==="edit_file"?`Edit ${bv(e.input.filePath,n)}`:e.toolKind==="delete_file"?`Delete ${bv(e.input.filePath,n)}`:e.toolKind==="mcp_generic"?`${VS(e.input.tool)} from ${VS(e.input.server)}`:e.toolKind==="subagent_task"&&e.input.subagentType||e.toolName},[e.input,e.toolKind,e.toolName,n]),o=v.useMemo(()=>e.toolKind==="subagent_task",[e.toolKind]),l=v.useMemo(()=>{if(e.toolKind==="skill")return e.input.skill},[e.input,e.toolKind]),c=e.toolKind==="bash",u=e.toolKind==="write_file",m=e.toolKind==="edit_file",h=e.toolKind==="delete_file",g=e.toolKind==="read_file",b=v.useMemo(()=>{if(typeof e.result=="string")return e.result;if(!e.result)return"";if(typeof e.result=="object"&&e.result!==null&&"content"in e.result){const C=e.result.content;if(typeof C=="string")return C}return JSON.stringify(e.result,null,2)},[e.result]),x=v.useMemo(()=>{if(!g)return[];if(e.result&&typeof e.result=="object"&&"blocks"in e.result){const C=e.result.blocks;if(Array.isArray(C)){const E=WD(C);if(E.length>0)return E}}return WD(e.rawResult)},[g,e.rawResult,e.result]),_=v.useMemo(()=>{switch(e.toolKind){case"bash":return e.input.command;case"write_file":case"delete_file":return e.input.content;default:return JSON.stringify(e.input,null,2)}},[e]);return f.jsx(ja,{className:"w-full",children:f.jsxs(b0,{expandedContent:f.jsx(y0,{className:"my-4 text-sm",children:f.jsxs("div",{className:"flex flex-col gap-2",children:[m?f.jsx(Rv,{content:"",isDiff:!0,oldString:e.input.oldString,newString:e.input.newString}):h?f.jsx(Rv,{content:e.input.content}):!g&&!u&&f.jsx(cD,{label:c?f.jsxs("span",{className:"flex items-center gap-2 w-full",children:[f.jsx("span",{children:"Command"}),!!e.input.timeoutMs&&f.jsxs("span",{className:"text-muted-foreground",children:["timeout: ",String(e.input.timeoutMs),"ms"]}),!!e.input.runInBackground&&f.jsx("span",{className:"text-muted-foreground",children:"background"})]}):u?"Contents":"Input",copyText:_,children:_}),r&&g&&!e.isError&&(x.length>0?f.jsxs("div",{children:[f.jsx("span",{className:"font-medium text-muted-foreground",children:"Image"}),f.jsx("div",{className:"mt-1",children:f.jsx(y0e,{images:x})})]}):f.jsx(Rv,{content:b})),u&&!e.isError&&f.jsx(Rv,{content:e.input.content}),r&&!g&&!(u&&!e.isError)&&!(m&&!e.isError)&&!(h&&!e.isError)&&f.jsx(cD,{label:e.isError?"Error":"Result",copyText:b,children:b})]})}),children:[f.jsx("div",{className:"w-5 h-5 relative flex items-center justify-center",children:e.isError?f.jsx(io,{className:"size-4 text-destructive"}):o?f.jsx(Ey,{className:"size-4 text-muted-icon"}):f.jsx(BB,{icon:zB(e.toolName),className:"size-4 text-muted-icon"})}),f.jsx(Fl,{className:"text-left transition-opacity duration-200 truncate",children:f.jsx(_p,{animate:i,shimmerWidth:Math.max(20,(((w=l||s)==null?void 0:w.length)??33)*3),children:l||s})})]})})}function x0e(e){if(e<1e3)return`${e}ms`;const t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h${r>0?` ${r}m`:""}`:r>0?`${r}m${i>0?` ${i}s`:""}`:`${i}s`}function GD({durationMs:e,prefix:t="Worked for"}){return e<=0?null:f.jsxs(gve,{children:[t," ",x0e(e)]})}function CF({message:e}){return e.success?f.jsx(GD,{durationMs:e.durationMs}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"px-4 py-3 mx-2 my-1 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm",children:e.result||"An unknown error occurred."}),f.jsx(GD,{durationMs:e.durationMs,prefix:"Failed after"})]})}function _0e(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function w0e(e){return typeof e=="string"?e:JSON.stringify(e,null,2)}function S0e(e){return e.replace(/<persisted-output>\n?/g,"").replace(/\n?<\/persisted-output>/g,"")}function C0e({message:e,localPath:t}){if(e.kind==="tool"&&e.persisted){const n=S0e(w0e(e.rawResult??""));return f.jsxs("div",{className:"rounded-md border border-border bg-muted/30 p-2 space-y-1 text-xs",children:[f.jsxs("div",{className:"font-medium",children:[e.toolName,": output too large (",_0e(e.persisted.originalSize),") — saved to disk"]}),f.jsx("pre",{className:"text-[11px] whitespace-pre-wrap overflow-hidden max-h-48",children:n}),f.jsxs("a",{href:qE(e.persisted.filePath),className:"text-blue-500 hover:underline break-all",target:"_blank",rel:"noreferrer",children:["View full output (",e.persisted.filePath,")"]})]})}switch(e.kind){case"assistant_text":return f.jsx(SF,{message:e});case"tool":return f.jsx(ay,{message:e,isLoading:!1,localPath:t});case"result":return f.jsx(CF,{message:e});default:return null}}function k0e(e){switch(e){case"AUTH_REQUIRED":return"Auth required";case"UNKNOWN_SUBAGENT":return"Unknown subagent";case"LOOP_DETECTED":return"Loop detected";case"DEPTH_EXCEEDED":return"Depth exceeded";case"TIMEOUT":return"Timeout";case"PROVIDER_ERROR":return"Provider error";case"INTERRUPTED":return"Interrupted";case"USER_CANCELLED":return"Cancelled by you";default:return"Error"}}function E0e({error:e,runId:t,onRetry:n,onOpenSettings:r}){const i=e.code==="TIMEOUT"||e.code==="PROVIDER_ERROR",s=e.code==="AUTH_REQUIRED";return f.jsxs("div",{"data-testid":`subagent-error:${t}`,className:"rounded-md border border-destructive/40 bg-destructive/5 p-3 text-sm",children:[f.jsxs("div",{className:"flex items-center gap-2 font-medium text-destructive",children:[f.jsx(wb,{className:"h-4 w-4"}),f.jsx("span",{children:k0e(e.code)})]}),f.jsx("p",{className:"mt-1 text-foreground",children:e.message}),f.jsxs("div",{className:"mt-2 flex gap-2",children:[s&&r&&f.jsxs("button",{type:"button",onClick:r,className:"inline-flex items-center gap-1 text-xs underline",children:[f.jsx(zW,{className:"h-3 w-3"})," Open settings"]}),i&&n&&f.jsxs("button",{type:"button",onClick:n,className:"inline-flex items-center gap-1 text-xs underline",children:[f.jsx(CG,{className:"h-3 w-3"})," Retry"]})]})]})}function T0e({question:e,currentIndex:t,totalQuestions:n,onBack:r,children:i}){const s=r&&t>0;return f.jsxs("div",{className:"rounded-2xl border border-border overflow-hidden",children:[f.jsxs("div",{className:"relative",children:[f.jsxs("h3",{className:"font-medium text-foreground text-sm p-3 px-4 bg-card border-b border-border text-foreground flex flex-row items-center gap-2",children:[s?f.jsx("button",{onClick:r,className:" text-muted-foreground hover:opacity-60 transition-all flex items-center",children:f.jsx(EV,{className:"h-4 w-4 -ml-0.5",strokeWidth:3})}):n>1?f.jsxs("span",{className:"font-bold text-muted-foreground whitespace-nowrap",children:[t+1," of ",n]}):null,e]}),n>1&&f.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-border",children:f.jsx("div",{className:"h-full bg-muted-foreground/40 transition-all duration-300",style:{width:`${t/n*100}%`}})})]}),i]})}function qD({label:e,description:t}){return f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"text-foreground text-sm",children:e}),t&&f.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:t})]})}function kF({selected:e,multiSelect:t,onClick:n}){return f.jsx("button",{type:"button",onClick:n,className:he("flex-shrink-0 w-5 h-5 border-1 flex items-center justify-center",t?"rounded":"rounded-full",e?"border-transparent bg-foreground":"border-muted-foreground/50 bg-background",n&&e&&"cursor-pointer"),children:e&&f.jsx(_i,{strokeWidth:3,className:"translate-y-[0.5px] h-3 w-3 text-white dark:text-background"})})}function N0e({option:e,selected:t,multiSelect:n,onClick:r,isLast:i}){const s="w-full text-left p-3 pt-2.5 pl-4 pr-5 bg-background",o=i?"":"border-b border-border";return r?f.jsx("button",{onClick:r,className:he(s,o,"transition-all cursor-pointer"),children:f.jsxs("div",{className:"flex items-center justify-between gap-3",children:[f.jsx("div",{className:"flex-1 min-w-0",children:f.jsx(qD,{label:e.label,description:e.description})}),f.jsx(kF,{selected:t,multiSelect:n})]})}):f.jsx("div",{className:he(s,o),children:f.jsx(qD,{label:e.label,description:e.description})})}function R0e(e){return e==null?void 0:e.answers}function ps(e){return e.id||e.question}function EF({message:e,onSubmit:t,isLatest:n}){var V,G;const r=v0(),i=e.input.questions,s=!!e.result,o=R0e(e.result),l=((V=e.result)==null?void 0:V.discarded)===!0,[c,u]=v.useState(0),[m,h]=v.useState({}),[g,b]=v.useState({}),[x,_]=v.useState(o??null),[w,C]=v.useState(s),E=(Q,I)=>{var ae;const W=(ae=g[Q])==null?void 0:ae.trim(),te=m[Q]||"",U=I||i.find(ee=>ps(ee)===Q);if(U!=null&&U.multiSelect)return[te,W].filter(Boolean).flatMap(ee=>ee.split(", ").filter(Boolean));const fe=W||te;return fe?[fe]:[]},k=Q=>{const I=m[ps(Q)]||"";return Q.multiSelect?I.split(", ").filter(Boolean):[I]},N=(Q,I)=>{const W=ps(Q);if(Q.multiSelect){const te=m[W]?m[W].split(", ").filter(Boolean):[],U=te.includes(I)?te.filter(fe=>fe!==I):[...te,I];h({...m,[W]:U.join(", ")})}else h({...m,[W]:I}),b({...g,[W]:""}),c<i.length-1&&setTimeout(()=>u(c+1),150)},R=(Q,I)=>{const W=ps(Q);b({...g,[W]:I}),I&&!Q.multiSelect&&h({...m,[W]:""})},A=Q=>{const I=ps(Q);Q.multiSelect&&g[I]&&b({...g,[I]:""})},M=i.every(Q=>E(ps(Q),Q).length>0),L=i[c],F=c===i.length-1,D=L&&E(ps(L),L).length>0,O=()=>{c<i.length-1&&u(c+1)},z=()=>{c>0&&u(c-1)},P=()=>{if(!M)return;const Q={};for(const I of i){const W=ps(I);Q[W]=E(W,I)}_(Q),C(!0),t(e.toolId,i,Q)},$=Q=>{if(Q.key==="Enter"&&!(!L||!D)){if(Q.preventDefault(),F){P();return}O()}};if(w||s){const Q=o||x||{};return f.jsx("div",{className:"w-full",children:f.jsxs("div",{className:"rounded-2xl border border-border overflow-hidden",children:[f.jsxs("div",{className:"font-medium text-sm p-3 px-4 pr-5 bg-muted border-b border-border flex flex-row items-center justify-between",children:[f.jsxs("p",{children:["Question",i.length!==1?"s":""]}),f.jsx("p",{className:"",children:l?"Discarded":"Answers"})]}),i.map((I,W)=>{const te=Q[ps(I)]||Q[I.question]||[],U=W===i.length-1;return f.jsxs("div",{className:he("w-full p-3 pt-2.5 pl-4 pr-5 bg-background flex items-center justify-between gap-3",!U&&"border-b border-border"),children:[f.jsx("div",{className:"text-sm text-pretty",children:I.question}),te.length>0&&f.jsx("div",{className:"text-sm font-medium text-right max-w-[50%] text-pretty",children:te.join(", ")}),te.length===0&&f.jsx("div",{className:"text-sm font-medium text-right italic",children:l?"Discarded":"No Response"})]},ps(I))})]})})}if(r.readonly)return f.jsx("div",{className:"w-full",children:f.jsxs("div",{className:"rounded-2xl border border-border overflow-hidden",children:[f.jsxs("div",{className:"font-medium text-sm p-3 px-4 pr-5 bg-muted border-b border-border flex flex-row items-center justify-between gap-3",children:[f.jsxs("p",{children:["Question",i.length!==1?"s":""]}),f.jsx("p",{className:"text-muted-foreground",children:"Awaiting response"})]}),i.map((Q,I)=>{var W;return f.jsxs("div",{className:he("w-full p-3 pt-2.5 pl-4 pr-5 bg-background flex items-center justify-between gap-3",I<i.length-1&&"border-b border-border"),children:[f.jsx("div",{className:"text-sm text-pretty",children:Q.question}),f.jsx("div",{className:"max-w-[50%] text-right text-xs text-muted-foreground text-pretty",children:((W=Q.options)==null?void 0:W.map(te=>te.label).join(", "))||"Freeform response"})]},ps(Q))})]})});if(!n)return f.jsx("div",{className:"w-full py-2",children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(R5,{className:"h-4 w-4 text-muted-foreground"}),f.jsx("span",{className:"text-sm text-muted-foreground",children:"Questions pending (newer question active)"})]})});if(!L)return null;const H=k(L),B=g[ps(L)]||"";return f.jsxs("div",{className:"w-full space-y-3",children:[f.jsxs(T0e,{question:L.question,currentIndex:c,totalQuestions:i.length,onBack:c>0?z:void 0,children:[(G=L.options)==null?void 0:G.map(Q=>f.jsx(N0e,{option:Q,selected:H.includes(Q.label),multiSelect:L.multiSelect,onClick:()=>N(L,Q.label)},Q.label)),f.jsx("div",{className:"transition-all bg-background",children:f.jsxs("div",{className:"flex pr-5 items-center justify-between gap-3",children:[f.jsx("input",{type:"text",value:B,onChange:Q=>R(L,Q.target.value),onKeyDown:$,placeholder:"Other...",className:"flex-1 px-3 !py-1 pl-4 min-h-[55px] min-w-0 text-sm bg-transparent outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background rounded-md text-foreground placeholder:text-muted-foreground"}),f.jsx(kF,{selected:!!B,multiSelect:L.multiSelect,onClick:L.multiSelect&&B?()=>A(L):void 0})]})})]}),f.jsxs("div",{className:"flex justify-end gap-2 mx-2",children:[!F&&D&&(L.multiSelect||!!B)&&f.jsx(Ue,{size:"sm",onClick:O,children:"Next"}),F&&f.jsx(Ue,{size:"sm",onClick:P,disabled:!M,className:he(!M&&"opacity-50 cursor-not-allowed","rounded-full"),children:"Submit"})]})]})}function TF({message:e,onConfirm:t,isLatest:n}){const r=v0(),i=!!e.result,[s,o]=v.useState(!1),[l,c]=v.useState(!1),[u,m]=v.useState(!1),[h,g]=v.useState(""),b=v.useRef(null),x=e.input;v.useEffect(()=>{u&&b.current&&b.current.focus()},[u]);const _=async()=>{x!=null&&x.plan&&(await navigator.clipboard.writeText(x.plan),c(!0),setTimeout(()=>c(!1),2e3))},w=i?e.result:null,C=(w==null?void 0:w.discarded)===!0;return f.jsxs("div",{className:"flex flex-col gap-3",children:[f.jsxs("div",{className:"relative rounded-2xl border border-border overflow-hidden group/plan",children:[(x==null?void 0:x.plan)&&f.jsx(Ue,{variant:"ghost",size:"icon","aria-label":l?"Copied":"Copy plan",className:he("absolute top-2 right-2 z-10 h-11 w-11 md:h-8 md:w-8 rounded-md text-muted-foreground opacity-100 md:opacity-0 md:group-hover/plan:opacity-100 transition-opacity [@media(hover:none)]:!opacity-100",!l&&"hover:text-foreground",l&&"hover:!bg-transparent hover:!border-transparent"),onClick:_,children:l?f.jsx(_i,{className:"h-4 w-4 text-success"}):f.jsx(Pl,{className:"h-4 w-4"})}),f.jsxs("div",{className:he("!pt-5 !pb-0 px-4 md:py-4.5 md:px-5.5 bg-muted dark:bg-card overflow-scroll no-pre-highlight transition-all",i&&!s?"max-h-[min(400px,40vh)] ":"",i?"hover:!pb-[32px]":""),children:[i&&f.jsxs(Ue,{variant:"ghost",className:"absolute z-10 bottom-2 pr-2.5 !pl-3.5 h-[34px] inline-flex gap-1 text-sm left-[50%] -translate-x-[50%] text-muted-foreground backdrop-blur-sm hover:text-foreground opacity-0 group-hover/plan:opacity-100 transition-all rounded-full border border-border",onClick:()=>o(!s),children:[s?"Show Less":"Show More",f.jsx(nf,{className:`size-3.5 transition-transform ${s?"rotate-180":""}`})]}),x!=null&&x.plan?f.jsxs("div",{className:"prose prose-sm dark:prose-invert max-w-none",children:[f.jsx(lu,{remarkPlugins:Sf,components:Cf,children:x.plan}),f.jsx("div",{className:"mt-5"})]}):f.jsx("p",{className:"text-sm text-muted-foreground",children:"No plan provided"})]})]}),i?f.jsx("div",{className:"flex justify-end mx-2",children:f.jsxs("span",{className:"pl-4 inline text-sm font-medium bg-background text-foreground/60 border border-border py-1.5 px-3 rounded-[20px] leading-relaxed max-w-[85%] sm:max-w-[80%]",children:[f.jsx("em",{children:C?"Discarded":w!=null&&w.clearContext?"Approved & Cleared Context":w!=null&&w.confirmed?"Approved":w!=null&&w.message?`Adjusted: "${w.message}"`:"Adjusted Plan"}),f.jsx(UV,{className:"inline h-4 w-4 ml-1.5 -mt-0.5"})]})}):n?r.readonly?f.jsx("div",{className:"flex justify-end mx-2",children:f.jsx("span",{className:"inline text-sm text-muted-foreground italic",children:"Plan pending in original session"})}):f.jsxs("div",{className:"flex flex-col gap-3",children:[!u&&f.jsxs("div",{className:"flex flex-col md:flex-row items-stretch md:items-center justify-end gap-2 mx-2",children:[f.jsxs(Ue,{size:"sm",onClick:()=>t(e.toolId,!0,!0),className:"rounded-full bg-primary text-background pr-4 md:order-last",children:[f.jsx(xV,{className:"h-4 w-4 mr-1.5"}),"Approve & Clear"]}),f.jsxs("div",{className:"flex items-stretch md:items-center gap-2 md:contents",children:[f.jsxs(Ue,{size:"sm",variant:"outline",onClick:()=>m(!0),className:"rounded-full border-border flex-1 md:flex-initial md:order-first",children:[f.jsx(Qm,{className:"h-4 w-4 mr-1.5"}),"Suggest Edits"]}),f.jsxs(Ue,{size:"sm",variant:"outline",onClick:()=>t(e.toolId,!0),className:"rounded-full border-border flex-1 md:flex-initial",children:[f.jsx(_i,{className:"h-4 w-4 mr-1.5"}),"Approve"]})]})]}),u&&f.jsxs("div",{className:"flex flex-col gap-2",children:[f.jsx("textarea",{ref:b,value:h,onChange:E=>g(E.target.value),onKeyDown:E=>{E.key==="Enter"&&!E.shiftKey&&h.trim()&&(E.preventDefault(),t(e.toolId,!1,void 0,h.trim())),E.key==="Escape"&&(m(!1),g(""))},placeholder:"Describe what you'd like to change...",rows:3,className:"w-full rounded-2xl border border-border bg-muted dark:bg-card px-4 py-3 text-sm text-foreground placeholder:text-muted-foreground resize-none outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"}),f.jsxs("div",{className:"flex items-center justify-end gap-2 mx-2",children:[f.jsx(Ue,{size:"sm",variant:"ghost",onClick:()=>{m(!1),g("")},className:"rounded-full text-muted-foreground",children:"Cancel"}),f.jsxs(Ue,{size:"sm",disabled:!h.trim(),onClick:()=>t(e.toolId,!1,void 0,h.trim()),className:"rounded-full bg-primary text-background disabled:opacity-50 disabled:pointer-events-none",children:[f.jsx(MG,{className:"h-4 w-4 mr-1.5"}),"Adjust Plan"]})]})]})]}):f.jsx("div",{className:"flex justify-end mx-2",children:f.jsx("span",{className:"inline text-sm text-muted-foreground italic",children:"Plan pending (newer prompt active)"})})]})}function A0e({pendingTool:e,onAskUserQuestionSubmit:t,onExitPlanModeSubmit:n}){if(e.toolKind==="ask_user_question"){const r=e.input,i={id:e.toolUseId,kind:"tool",toolKind:"ask_user_question",toolName:"AskUserQuestion",toolId:e.toolUseId,input:{questions:r.questions??[]},timestamp:new Date(e.requestedAt).toISOString()};return f.jsxs("div",{"data-testid":`subagent-pending-tool:${e.toolUseId}`,children:[f.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-1",children:"awaiting your response"}),f.jsx(EF,{message:i,onSubmit:t,isLatest:!0})]})}if(e.toolKind==="exit_plan_mode"){const r=e.input,i={id:e.toolUseId,kind:"tool",toolKind:"exit_plan_mode",toolName:"ExitPlanMode",toolId:e.toolUseId,input:{plan:r.plan,summary:r.summary},timestamp:new Date(e.requestedAt).toISOString()};return f.jsxs("div",{"data-testid":`subagent-pending-tool:${e.toolUseId}`,children:[f.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-1",children:"awaiting your response"}),f.jsx(TF,{message:i,onConfirm:(s,o,l,c)=>n(s,{confirmed:o,clearContext:l,message:c}),isLatest:!0})]})}return null}function NF({run:e,indentDepth:t,localPath:n,onOpenSettings:r,onRetry:i,onSubagentAskUserQuestionSubmit:s,onSubagentExitPlanModeSubmit:o,onCancelSubagentRun:l}){var h;const c=pF(e.entries),u=c.some(g=>g.kind==="assistant_text"),m=e.status==="running"&&u;return f.jsxs("div",{"data-testid":`subagent-message:${e.runId}`,className:he("border-l-2 border-accent pl-3 py-2 space-y-2"),style:{marginLeft:`${t*24}px`},children:[f.jsxs("header",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[f.jsx(tf,{className:"h-3.5 w-3.5"}),f.jsx("span",{children:e.subagentName}),f.jsxs("span",{className:"opacity-60",children:[e.provider,e.model?`/${e.model}`:""]}),((h=e.usage)==null?void 0:h.outputTokens)!=null&&f.jsxs("span",{className:"opacity-60",children:["· ",e.usage.inputTokens??0,"↑ ",e.usage.outputTokens,"↓"]}),e.status==="running"&&f.jsx("span",{className:"ml-auto inline-block animate-pulse",children:m?"streaming...":"running..."}),l&&e.status==="running"&&f.jsx("button",{type:"button","data-testid":`subagent-cancel:${e.runId}`,"aria-label":"Cancel subagent",onClick:()=>l(e.chatId,e.runId),className:"text-muted-foreground hover:text-foreground",children:f.jsx(io,{className:"h-3.5 w-3.5"})})]}),c.map(g=>f.jsx(C0e,{message:g,localPath:n},g.id)),e.pendingTool&&f.jsx(A0e,{pendingTool:e.pendingTool,onAskUserQuestionSubmit:(g,b,x)=>s==null?void 0:s(e.runId,g,b,x),onExitPlanModeSubmit:(g,b)=>o==null?void 0:o(e.runId,g,b)}),c.length===0&&e.finalText&&f.jsxs("div",{className:he("whitespace-pre-wrap text-sm",m&&"text-foreground/80"),children:[e.finalText,m&&f.jsx("span",{className:"ml-0.5 inline-block w-2 animate-pulse",children:"▍"})]}),e.status==="failed"&&e.error&&f.jsx("div",{children:f.jsx(E0e,{error:e.error,runId:e.runId,subagentId:e.subagentId,onOpenSettings:r,onRetry:i})})]})}function M0e(e){var n;const t=e.match(/^<system-message>\s*([\s\S]*?)\s*<\/system-message>\s*([\s\S]*)$/);return t?{systemMessage:((n=t[1])==null?void 0:n.trim())||null,body:t[2]??""}:{systemMessage:null,body:e}}const L0e=v.memo(function({content:t,attachments:n=[],steered:r=!1,autoContinue:i}){const[s,o]=v.useState(null),l=v0(),c=v.useMemo(()=>M0e(t),[t]),u=l.attachmentMode==="metadata",m=!l.readonly||l.attachmentMode==="bundle",h=v.useMemo(()=>n.filter(w=>w.kind==="image"&&(w.contentUrl||u)),[n,u]),g=v.useMemo(()=>n.filter(w=>w.kind!=="image"||!w.contentUrl&&!u),[n,u]),b=n.find(w=>w.id===s)??null,x=b?yp(b,"user_attachment"):null;function _(w){if(!m||!w.contentUrl)return;if(yf(w).openInNewTab){typeof window<"u"&&window.open(new URL(w.contentUrl,document.baseURI||window.location.href).toString(),"_blank","noopener,noreferrer");return}o(w.id)}return f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"flex flex-col items-end gap-2",children:[h.length>0?f.jsx("div",{className:"flex max-w-[85%] sm:max-w-[80%] flex-wrap justify-end gap-3",children:h.map(w=>f.jsx(i2,{attachment:w,onClick:m?()=>_(w):void 0},w.id))}):null,g.length>0?f.jsx("div",{className:"flex max-w-[85%] sm:max-w-[80%] flex-wrap justify-end gap-2",children:g.map(w=>f.jsx(Do,{attachment:w,onClick:m?()=>_(w):void 0},w.id))}):null,c.body||!c.body&&n.length===0&&t&&!c.systemMessage?f.jsxs("div",{className:"flex max-w-[85%] items-center gap-2 sm:max-w-[80%]",children:[r?f.jsx(mq,{"aria-label":"Sent mid-turn",className:"size-3.5 shrink-0 text-muted-foreground"}):null,f.jsx("div",{className:"min-w-0 flex-1 rounded-[20px] border border-border bg-muted px-3.5 py-1.5 text-primary prose prose-sm prose-invert [&_p]:whitespace-pre-line",children:f.jsx(lu,{remarkPlugins:Sf,components:Cf,children:c.body})})]}):null,i?f.jsx("span",{className:"text-xs text-muted-foreground opacity-70",children:"auto-sent"}):null]}),f.jsx(wf,{source:x,open:x!==null,onOpenChange:w=>!w&&o(null)})]})});function j0e({json:e}){return f.jsx("div",{className:"flex gap-3 justify-start",children:f.jsx("div",{className:"flex-1 max-w-[90%]",children:f.jsx("pre",{className:"text-xs font-mono whitespace-pre-wrap break-words bg-muted rounded-lg p-3 overflow-auto max-h-96",children:e})})})}function RF({title:e,count:t,children:n,badge:r}){const[i,s]=v.useState(!1);return t===0?null:f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsxs("button",{onClick:()=>s(!i),className:"flex items-center gap-1 cursor-pointer group/section hover:opacity-60 transition-opacity",children:[f.jsx(Po,{className:he("h-3.5 w-3.5 text-muted-foreground transition-transform duration-200",i&&"rotate-90")}),f.jsx("span",{className:"text-muted-foreground font-medium",children:e}),f.jsx("span",{className:"text-muted-foreground/60",children:t}),r]}),i&&f.jsx("div",{className:"ml-5",children:n})]})}function rS({title:e,items:t,icon:n,getIcon:r}){return t.length===0?null:f.jsx(RF,{title:e,count:t.length,children:f.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.map(i=>f.jsx($B,{icon:r?r(i):n,children:i},i))})})}function D0e(e){const t=e.match(/^mcp__([^_]+)__(.+)$/);return t?{server:t[1],tool:t[2]}:null}function AF({status:e}){const t=e==="connected"?"bg-success":e==="pending"?"bg-warning":"bg-destructive";return f.jsx("span",{className:he("inline-block h-2 w-2 rounded-full shrink-0",t)})}function I0e(e){switch(e){case"connected":return"Connected";case"failed":return"Failed";case"needs-auth":return"Needs auth";case"pending":return"Connecting...";case"disabled":return"Disabled";default:return e}}function KD({server:e}){const[t,n]=v.useState(!1),r=e.status==="connected";return f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsxs("button",{onClick:()=>r&&e.tools.length>0&&n(!t),className:he("flex items-center gap-1.5",r&&e.tools.length>0&&"cursor-pointer hover:opacity-60 transition-opacity"),children:[r&&e.tools.length>0&&f.jsx(Po,{className:he("h-3 w-3 text-muted-foreground transition-transform duration-200",t&&"rotate-90")}),f.jsx(AF,{status:e.status}),f.jsx("span",{className:"text-muted-foreground font-medium",children:VS(e.name)}),r?f.jsxs("span",{className:"text-muted-foreground/50",children:[e.tools.length," tools"]}):f.jsx("span",{className:"text-muted-foreground/50",children:I0e(e.status)})]}),!r&&e.error&&f.jsx("span",{className:"text-destructive ml-5",children:e.error}),t&&e.tools.length>0&&f.jsx("div",{className:"flex flex-wrap gap-1.5 ml-5",children:e.tools.map(i=>f.jsx($B,{icon:zB(`mcp__${e.name}__${i}`),children:i},i))})]})}function P0e({servers:e}){if(e.length===0)return null;const t=e.filter(i=>i.status==="connected"),n=e.filter(i=>i.status!=="connected"),r=n.length>0?f.jsxs("span",{className:"flex items-center gap-1 ml-1",children:[f.jsx(AF,{status:"failed"}),f.jsxs("span",{className:"text-muted-foreground/60",children:[n.length," disconnected"]})]}):null;return f.jsx(RF,{title:"MCP Servers",count:e.length,badge:r,children:f.jsxs("div",{className:"flex flex-col gap-2",children:[t.map(i=>f.jsx(KD,{server:i},i.name)),n.map(i=>f.jsx(KD,{server:i},i.name))]})})}function O0e({rawJson:e}){const[t,n]=v.useState(!1);return f.jsxs("div",{className:"flex flex-col gap-1.5",children:[f.jsxs("button",{onClick:()=>n(!t),className:"flex items-center gap-1 cursor-pointer group/section hover:opacity-60 transition-opacity",children:[f.jsx(Po,{className:he("h-3.5 w-3.5 text-muted-foreground transition-transform duration-200",t&&"rotate-90")}),f.jsx("span",{className:"text-muted-foreground font-medium",children:"Raw Message"})]}),t&&f.jsx("pre",{className:"ml-5 text-xs whitespace-pre-wrap break-all border border-border rounded-md p-3 overflow-x-auto max-h-96 overflow-y-auto",children:e})]})}function z0e({message:e,rawJson:t}){const{coreTools:n,mcpServersWithTools:r}=v.useMemo(()=>{const i=new Map,s=[];for(const l of e.tools){const c=D0e(l);if(c){const u=i.get(c.server)||[];u.push(c.tool),i.set(c.server,u)}else s.push(l)}const o=e.mcpServers.map(l=>({name:l.name,status:l.status,error:l.error,tools:i.get(l.name)||[]}));return{coreTools:s,mcpServersWithTools:o}},[e.tools,e.mcpServers]);return f.jsx(ja,{children:f.jsxs(b0,{expandedContent:f.jsx(y0,{className:"my-4 text-xs",children:f.jsxs("div",{className:"flex flex-col gap-3",children:[f.jsx(pve,{children:e.model}),f.jsx(rS,{title:"Tools",items:n,getIcon:i=>K1[i]??OB}),f.jsx(rS,{title:"Agents",items:e.agents,icon:Ey}),f.jsx(rS,{title:"Commands",items:e.slashCommands,icon:FG}),f.jsx(P0e,{servers:r}),t&&f.jsx(O0e,{rawJson:t})]})}),children:[f.jsx(cV,{className:"h-5 w-5 text-logo"}),f.jsx(Fl,{children:"Session Started"})]})})}function B0e({message:e}){return f.jsx(ja,{className:"hidden",children:f.jsxs(b0,{expandedContent:f.jsx(y0,{className:"my-4 text-xs",children:f.jsx("pre",{className:"font-mono whitespace-pre-wrap break-all bg-muted border border-border rounded-lg p-2 max-h-64 overflow-auto",children:JSON.stringify(e.accountInfo,null,2)})}),children:[f.jsx("div",{className:"size-5 flex justify-center items-center ",children:f.jsx(Ey,{className:"h-4 w-4 text-muted-foreground"})}),f.jsx(Fl,{children:"Account"})]})})}const F0e={completed:{Icon:_i,iconClass:"text-success",textClass:"text-muted-foreground"},in_progress:{Icon:bn,iconClass:"text-foreground animate-spin",textClass:"text-foreground font-medium"},pending:{Icon:LV,iconClass:"text-muted-foreground",textClass:"text-muted-foreground"}};function $0e({message:e}){const t=e.input.todos;return t.length?f.jsx("div",{className:"w-full",children:f.jsxs("div",{className:"rounded-2xl border border-border overflow-hidden",children:[f.jsxs("h3",{className:"font-medium text-foreground text-sm p-3 px-4 bg-card border-b border-border flex items-center gap-2",children:[f.jsx(FW,{className:"h-4 w-4 text-muted-foreground"}),"Progress"]}),f.jsx("div",{children:t.map((n,r)=>{const i=r===t.length-1,{Icon:s,iconClass:o,textClass:l}=F0e[n.status];return f.jsxs("div",{className:he("flex items-center gap-3 px-4 py-2.5 bg-background",!i&&"border-b border-border"),children:[f.jsx(s,{className:he("h-4 w-4 flex-shrink-0",o)}),f.jsx("span",{className:he("text-sm",l),children:n.status==="in_progress"?n.activeForm:n.content})]},r)})})]})}):null}function H0e({message:e}){const t=e.result,n=t==null?void 0:t.contentUrl,[r,i]=v.useState("idle"),[s,o]=v.useState(!1);if(v.useEffect(()=>{if(!n)return;const _=new AbortController;return fetch(n,{method:"HEAD",signal:_.signal}).then(w=>{_.signal.aborted||i(w.ok?"ready":"missing")}).catch(()=>{}),()=>_.abort()},[n]),!t||!n)return null;const l={id:`offer-download-${e.toolId}`,kind:"file",displayName:t.displayName||t.fileName,absolutePath:t.relativePath,relativePath:t.relativePath,contentUrl:n,mimeType:t.mimeType??"application/octet-stream",size:t.size},c=xf(l),u=u0(c,t.mimeType),m=t.size>0?kf(t.size):null,h=f.jsxs(f.Fragment,{children:[u,m?f.jsxs(f.Fragment,{children:[" · ",f.jsx("span",{className:"tabular-nums",children:m})]}):null]});if(r==="missing")return f.jsx("div",{className:"flex","data-testid":"offer-download-link",children:f.jsx(Do,{attachment:l,disabledReason:"File no longer available"})});if(!yf(l).openInNewTab){const _=`Preview ${l.displayName}, ${u}${m?`, ${m}`:""}`;return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"flex","data-testid":"offer-download-link",children:f.jsx(Do,{attachment:l,onClick:()=>o(!0),meta:h,ariaLabel:_})}),f.jsx(wf,{source:s?yp(l,"offer_download"):null,open:s,onOpenChange:o})]})}const x=["Download",l.displayName,u,m].filter(Boolean);return f.jsx("div",{className:"flex","data-testid":"offer-download-link",children:f.jsx(Do,{attachment:l,href:n,download:t.fileName||void 0,meta:h,ariaLabel:x.join(", ")})})}const iS=new Map;function U0e(e){const{cacheKey:t,enabled:n,ref:r,fetcher:i,rootMargin:s}=e,o=iS.get(t),[l,c]=v.useState(o!==void 0?"ready":"idle"),[u,m]=v.useState(o!==void 0?o:null),[h,g]=v.useState(null),[b,x]=v.useState(t),_=v.useRef(null),w=v.useRef(t);if(w.current=t,b!==t){x(t);const C=iS.get(t);c(C!==void 0?"ready":"idle"),m(C!==void 0?C:null),g(null)}return v.useEffect(()=>{if(!n||o!==void 0)return;const C=r.current;if(!C||typeof IntersectionObserver>"u")return;let E=!1;const k=t,N=new IntersectionObserver(R=>{for(const A of R){if(!A.isIntersecting)continue;if(N.disconnect(),E)return;const M=new AbortController;_.current=M,c("loading"),i(M.signal).then(L=>{E||w.current!==k||(iS.set(k,L),m(L),c("ready"))}).catch(L=>{E||M.signal.aborted||w.current!==k||(g(L instanceof Error?L:new Error(String(L))),c("error"))});break}},{rootMargin:s??"200px"});return N.observe(C),()=>{var R;E=!0,N.disconnect(),(R=_.current)==null||R.abort(),_.current=null}},[o,t,n,r,i,s]),v.useMemo(()=>({state:l,data:u,error:h}),[l,u,h])}function V0e({source:e,onOpen:t,variant:n}){const r={id:e.id,kind:"file",displayName:e.displayName,mimeType:e.mimeType,size:e.size??0,contentUrl:e.contentUrl,relativePath:e.relativePath??"",absolutePath:""},i=xf(r),s=u0(i,e.mimeType),o=e.size&&e.size>0?kf(e.size):null;return i==="image"?f.jsx("button",{type:"button",onClick:t,"aria-label":`Preview ${e.displayName}`,className:"overflow-hidden rounded-xl border border-border bg-background",children:f.jsx("img",{src:e.contentUrl,alt:e.altText??e.displayName,loading:"lazy",className:"max-h-64 w-auto max-w-full object-contain"})}):n==="expanded"&&(i==="text"||i==="code"||i==="markdown"||i==="json"||i==="table")?f.jsx(W0e,{source:e,onOpen:t,friendlyType:s,sizeLabel:o}):f.jsx(Do,{attachment:r,onClick:t,meta:f.jsxs(f.Fragment,{children:[s,o?f.jsxs(f.Fragment,{children:[" · ",f.jsx("span",{className:"tabular-nums",children:o})]}):null]}),ariaLabel:`Preview ${e.displayName}, ${s}${o?`, ${o}`:""}`})}const W0e=function({source:t,onOpen:n,friendlyType:r,sizeLabel:i}){const s=v.useRef(null),o=t.contentUrl,l=v.useCallback(async m=>{const h=await BE(o,4096);if(m.aborted)throw new Error("aborted");return h.content.slice(0,200)},[o]),c=U0e({ref:s,enabled:!0,cacheKey:`snippet:${t.id}|${t.contentUrl}|${t.size??0}`,fetcher:l}),u=c.state==="ready"&&typeof c.data=="string"?c.data:"";return f.jsxs("button",{ref:s,type:"button",onClick:n,"aria-label":`Preview ${t.displayName}`,className:"flex w-full max-w-md flex-col items-start gap-1 rounded-xl border border-border bg-background p-3 text-left hover:bg-accent/40",children:[f.jsx("div",{className:"text-sm font-medium text-foreground",children:t.displayName}),f.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[r,i?` · ${i}`:""]}),u?f.jsx("pre",{className:"line-clamp-3 max-h-16 w-full whitespace-pre-wrap break-words text-[11px] text-muted-foreground",children:u}):null]})};function G0e({message:e}){const{status:t,revisedPrompt:n}=e.input,r=e.result,i=r==null?void 0:r.contentUrl,s=e.isError||t==="failed",[o,l]=v.useState(!1);if(!s&&!r&&t==="in_progress")return f.jsxs("div",{className:"flex flex-col gap-1 rounded-md border border-border/40 bg-muted/30 px-3 py-2 text-sm text-muted-foreground","data-testid":"image-generation-pending",children:[f.jsx("span",{children:"Generating image…"}),n?f.jsx("span",{className:"italic",children:n}):null]});if(s||!r||!i)return f.jsxs("div",{className:"flex flex-col gap-1 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm","data-testid":"image-generation-error",children:[f.jsx("span",{children:"Image generation failed."}),r!=null&&r.relativePath?f.jsx("span",{className:"text-muted-foreground",children:r.relativePath}):null]});const c={id:`image-gen-${e.toolId}`,contentUrl:i,displayName:r.fileName,fileName:r.fileName,relativePath:r.relativePath,mimeType:"image/png",origin:"image_generation",altText:n??void 0};return f.jsxs("figure",{className:"flex flex-col gap-2","data-testid":"image-generation",children:[f.jsx(V0e,{source:c,onOpen:()=>l(!0),variant:"expanded"}),n?f.jsx("figcaption",{className:"text-xs text-muted-foreground italic",children:n}):null,f.jsx(wf,{source:o?c:null,open:o,onOpenChange:l})]})}function q0e({message:e}){return f.jsx("div",{className:"flex items-center justify-end gap-2 text-sm text-muted-foreground",children:f.jsxs("div",{className:"inline-flex gap-1.5 items-center justify-center whitespace-nowrap text-sm font-medium bg-background text-foreground/60 border border-border h-9 pl-1 pr-4 rounded-full",children:[f.jsx(AV,{className:"h-4 w-4 ml-1.5"}),f.jsx("em",{children:"Interrupted"})]})})}function ly({size:e=4}){return f.jsxs("svg",{className:"flex-1",viewBox:`0 0 100 ${e}`,preserveAspectRatio:"none",style:{height:`${e}px`},children:[f.jsx("pattern",{id:"zigzag",width:e,height:e,patternUnits:"userSpaceOnUse",children:f.jsx("path",{d:`M0 ${e} L${e/2} 0 L${e} ${e}`,fill:"none",stroke:"currentColor",strokeWidth:"0.5",className:"text-muted-foreground/30",style:{stroke:"currentColor"}})}),f.jsx("rect",{width:"100%",height:e,fill:"url(#zigzag)",className:"text-muted-foreground/30"})]})}function K0e(){return f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx(ly,{}),f.jsx("span",{className:"text-[11px] tracking-widest text-muted-foreground uppercase flex-shrink-0",children:"Compacted"}),f.jsx(ly,{})]})}function Y0e(){return f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx(ly,{}),f.jsx("span",{className:"text-[11px] tracking-widest text-muted-foreground uppercase flex-shrink-0",children:"Context Cleared"}),f.jsx(ly,{})]})}function X0e({message:e}){return f.jsx(ja,{children:f.jsxs(b0,{expandedContent:f.jsx(y0,{className:"my-4 text-xs",children:f.jsx("div",{className:"prose prose-sm dark:prose-invert max-w-none",children:f.jsx(lu,{remarkPlugins:Sf,components:Cf,children:e.summary})})}),children:[f.jsx("div",{className:"w-5 h-5 relative flex items-center justify-center",children:f.jsx(A5,{className:"h-4.5 w-4.5 text-muted-foreground"})}),f.jsx(Fl,{children:"Summarized"})]})})}const Q0e={compacting:"Compacting..."};function Z0e({message:e}){const t=Q0e[e.status]||e.status;return f.jsxs(ja,{className:"grid grid-cols-[auto_1fr] items-center gap-1.5 text-sm animate-pulse",children:[f.jsx("div",{className:"w-5 h-5 relative flex items-center justify-center",children:f.jsx(A5,{className:"h-4.5 w-4.5 text-muted-foreground"})}),f.jsx(Fl,{className:"text-left transition-opacity duration-200 truncate",children:t})]})}const J0e={read_file:{key:"read",singular:"read",plural:"reads"},edit_file:{key:"edit",singular:"edit",plural:"edits"},write_file:{key:"write",singular:"write",plural:"writes"},delete_file:{key:"delete",singular:"delete",plural:"deletes"},bash:{key:"bash",singular:"command",plural:"commands"},grep:{key:"grep",singular:"search",plural:"searches"},glob:{key:"glob",singular:"glob",plural:"globs"},subagent_task:{key:"task",singular:"agent",plural:"agents"},web_search:{key:"websearch",singular:"web search",plural:"web searches"},skill:{key:"skill",singular:"skill",plural:"skills"},todo_write:{key:"todo",singular:"todo update",plural:"todo updates"}},exe={key:"other",singular:"tool call",plural:"tool calls"};function txe(e){return J0e[e]??exe}function nxe(e){const t=new Map,n=[];for(const r of e){const i=r.toolKind,s=txe(i),o=t.get(s.key);o?o.count++:(t.set(s.key,{category:s,count:1}),n.push(s.key))}return n.map(r=>{const{category:i,count:s}=t.get(r);return`${s} ${s===1?i.singular:i.plural}`}).join(", ")}function rxe({messages:e,isLoading:t,localPath:n,expanded:r,onExpandedChange:i}){const s=v.useMemo(()=>nxe(e),[e]),l=e.some(c=>c.result===void 0)&&t;return f.jsx(ja,{className:"w-full",children:f.jsxs("div",{className:"flex flex-col w-full",children:[f.jsx("button",{onClick:()=>i(!r),className:`group cursor-pointer grid grid-cols-[auto_1fr] items-center gap-1 text-sm ${!r&&!l?"hover:opacity-60 transition-opacity":""}`,children:f.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-1.5",children:[f.jsx("div",{className:"w-5 h-5 relative flex items-center justify-center",children:f.jsx(Po,{className:`h-4.5 w-4.5 text-muted-icon transition-all duration-200 ${r?"rotate-90":""}`})}),f.jsx(Fl,{className:"text-left",children:f.jsx(_p,{animate:l,children:s})})]})}),r&&f.jsxs("div",{className:"my-4 flex flex-col gap-3",children:[e.map(c=>f.jsx(ay,{message:c,isLoading:t,localPath:n},c.id)),e.length>5&&f.jsx("button",{onClick:()=>i(!1),className:"cursor-pointer grid grid-cols-[auto_1fr] items-center gap-1 text-xs hover:opacity-80 transition-opacity",children:f.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-1.5",children:[f.jsx("div",{className:"w-5 h-5 relative flex items-center justify-center",children:f.jsx(Po,{className:"h-4.5 w-4.5 text-muted-icon -rotate-90"})}),f.jsx(Fl,{className:"text-left",children:"Collapse"})]})})]})]})})}function ixe(e){if(e!=="system")return e}function sS(e,t){const n=ixe(t),r=new Intl.DateTimeFormat("en-GB",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(new Date(e)),i=o=>{var l;return((l=r.find(c=>c.type===o))==null?void 0:l.value)??"00"};let s=i("hour");return s==="24"&&(s="00"),`${i("day")}/${i("month")}/${i("year")} ${s}:${i("minute")}`}const sxe=/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})$/;function YD(e,t){if(e==="system")return-new Date(t).getTimezoneOffset();const n=new Intl.DateTimeFormat("en-US",{timeZone:e,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(new Date(t)),r=o=>{var l;return Number(((l=n.find(c=>c.type===o))==null?void 0:l.value)??0)};let i=r("hour");i===24&&(i=0);const s=Date.UTC(r("year"),r("month")-1,r("day"),i,r("minute"),r("second"));return Math.round((s-t)/6e4)}function oxe(e,t){const n=sxe.exec(e.trim());if(!n)return null;const[,r,i,s,o,l]=n,c=Number(r),u=Number(i),m=Number(s),h=Number(o),g=Number(l);if(u<1||u>12||c<1||c>31||h>23||g>59)return null;const b=Date.UTC(m,u-1,c,h,g),x=YD(t,b),_=b-x*6e4,w=YD(t,_);return _-(w-x)*6e4}const axe={neutral:"border-border bg-card",muted:"border-border/50 bg-card/50 opacity-75",success:"border-emerald-500/30 bg-emerald-500/5",error:"border-destructive/40 bg-destructive/5"},lxe={primary:"default",secondary:"secondary",ghost:"ghost",destructive:"destructive"};function ga({title:e,description:t,body:n,errorMessage:r,tone:i="neutral",actions:s=[]}){const[o,l]=v.useState(null),[c,u]=v.useState(null),m=v.useCallback(async g=>{if(o)return;u(null);let b;try{b=g.onClick()}catch(x){console.error("[transcript-action-card] sync click threw",x),u(x instanceof Error?x.message:String(x));return}if(b instanceof Promise){l(g.id);try{await b}catch(x){console.error("[transcript-action-card] async click rejected",x),u(x instanceof Error?x.message:String(x))}finally{l(null)}}},[o]),h=o!==null;return f.jsxs("div",{"data-focus-fallback-ignore":!0,className:he("rounded-lg border px-4 py-3 text-sm space-y-2 transition-colors",axe[i]),children:[f.jsx("div",{className:"flex items-start justify-between gap-3",children:f.jsxs("div",{className:"space-y-1 min-w-0 flex-1",children:[f.jsx("div",{className:"font-medium leading-tight",children:e}),t?f.jsx("div",{className:"text-muted-foreground text-xs leading-snug",children:t}):null]})}),n?f.jsx("div",{className:"text-xs leading-snug",children:n}):null,r?f.jsx("div",{className:"text-destructive text-xs leading-snug",children:r}):null,c?f.jsx("div",{className:"text-destructive text-xs leading-snug",role:"alert",children:c}):null,s.length>0?f.jsx("div",{className:"flex flex-wrap gap-2 pt-1",children:s.map(g=>{const b=o===g.id;return f.jsxs(Ue,{type:"button",size:"sm",variant:lxe[g.variant??"ghost"],disabled:g.disabled||h&&!b,onClick:()=>{m(g)},className:"gap-1.5",children:[b?f.jsx(bn,{className:"size-3.5 animate-spin"}):null,g.label]},g.id)})}):null]})}function cxe({schedule:e,onAccept:t,onReschedule:n,onCancel:r}){const[i,s]=v.useState(()=>sS(e.scheduledAt??e.resetAt,e.tz)),[o,l]=v.useState(!1),c=v.useMemo(()=>oxe(i,e.tz),[i,e.tz]),u=c!==null&&c>Date.now(),m=c===null?"Use format dd/mm/yyyy hh:mm":u?null:"Time must be in the future";if(e.state==="fired"){const x=sS(e.scheduledAt??e.resetAt,e.tz);return f.jsx(ga,{title:`Auto-continued at ${x}`,tone:"success"})}if(e.state==="cancelled")return f.jsx(ga,{title:"Auto-continue cancelled",tone:"muted"});if(e.state==="proposed"){const x=e.resetAt<=Date.now(),_=[{id:"schedule",label:"Schedule",variant:"primary",disabled:!u,onClick:()=>{c!==null&&t(c)}},{id:"dismiss",label:"Dismiss",variant:"ghost",onClick:()=>r()}];return f.jsx(ga,{title:"Rate limit hit — schedule auto-continue?",description:x?"Reset time has passed — accept to continue now.":void 0,body:f.jsxs("div",{className:"space-y-1",children:[f.jsx($n,{value:i,onChange:w=>s(w.target.value),placeholder:"dd/mm/yyyy hh:mm"}),m&&f.jsx("div",{className:"text-destructive text-xs",children:m})]}),actions:_})}const h=sS(e.scheduledAt??e.resetAt,e.tz),g=e.tz==="system"?"local":e.tz;if(!o){const x=[{id:"change",label:"Change time",variant:"secondary",onClick:()=>l(!0)},{id:"cancel",label:"Cancel",variant:"ghost",onClick:()=>r()}];return f.jsx(ga,{title:`Auto-continue at ${h} (${g})`,actions:x})}const b=[{id:"save",label:"Save",variant:"primary",disabled:!u,onClick:()=>{c!==null&&(n(c),l(!1))}},{id:"back",label:"Back",variant:"ghost",onClick:()=>l(!1)}];return f.jsx(ga,{title:`Auto-continue at ${h} (${g})`,body:f.jsxs("div",{className:"space-y-1",children:[f.jsx($n,{value:i,onChange:x=>s(x.target.value),placeholder:"dd/mm/yyyy hh:mm"}),m&&f.jsx("div",{className:"text-destructive text-xs",children:m})]}),actions:b})}function uxe({toolRequestId:e,questions:t,onAnswer:n}){const[r,i]=v.useState({});function s(u){return u.id??u.question}function o(u,m){const h=s(u);u.multiSelect?i(g=>{const b=g[h]??[],x=b.includes(m)?b.filter(_=>_!==m):[...b,m];return{...g,[h]:x}}):i(g=>({...g,[h]:[m]}))}function l(){const u={};for(const m of t){const h=s(m);u[h]=r[h]??[]}n(e,{kind:"answer",payload:{questions:t,answers:u}})}const c=t.every(u=>{var h;const m=s(u);return(((h=r[m])==null?void 0:h.length)??0)>0});return f.jsxs("div",{className:"rounded-2xl border border-border overflow-hidden",children:[f.jsxs("div",{className:"font-medium text-sm p-3 px-4 bg-muted border-b border-border flex items-center justify-between",children:[f.jsxs("span",{children:["Question",t.length!==1?"s":""]}),f.jsx("span",{className:"text-xs text-muted-foreground",children:"Reconnected — awaiting your response"})]}),t.map((u,m)=>{var x;const h=s(u),g=r[h]??[],b=m===t.length-1;return f.jsxs("div",{className:`bg-background px-4 py-3 ${b?"":"border-b border-border"}`,children:[f.jsx("p",{className:"text-sm font-medium mb-2",children:u.question}),u.options&&u.options.length>0?f.jsx("div",{className:"flex flex-wrap gap-2",children:u.options.map(_=>f.jsx("button",{onClick:()=>o(u,_.label),className:`rounded-full border px-3 py-1 text-xs transition-colors ${g.includes(_.label)?"border-foreground bg-foreground text-background":"border-border bg-background text-foreground hover:bg-muted"}`,children:_.label},_.label))}):f.jsx("input",{type:"text",className:"w-full rounded-md border border-border bg-muted px-3 py-1.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Type your answer...",value:((x=r[h])==null?void 0:x[0])??"",onChange:_=>{const w=_.target.value;i(C=>({...C,[h]:w?[w]:[]}))}})]},h)}),f.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3 bg-background border-t border-border",children:[f.jsx(Ue,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>n(e,{kind:"deny",reason:"user_canceled"}),children:"Cancel"}),f.jsx(Ue,{size:"sm",className:"rounded-full",disabled:!c,onClick:l,children:"Submit"})]})]})}function dxe({toolRequestId:e,plan:t,onAnswer:n}){return f.jsxs("div",{className:"rounded-2xl border border-border overflow-hidden",children:[f.jsxs("div",{className:"font-medium text-sm p-3 px-4 bg-muted border-b border-border flex items-center justify-between",children:[f.jsx("span",{children:"Plan"}),f.jsx("span",{className:"text-xs text-muted-foreground",children:"Reconnected — awaiting your response"})]}),f.jsx("div",{className:"bg-background px-4 py-3",children:f.jsx("p",{className:"text-sm whitespace-pre-wrap",children:t})}),f.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3 bg-background border-t border-border",children:[f.jsx(Ue,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>n(e,{kind:"deny",reason:"user_canceled"}),children:"Edit"}),f.jsx(Ue,{size:"sm",className:"rounded-full",onClick:()=>n(e,{kind:"answer",payload:{confirmed:!0}}),children:"Confirm"})]})]})}function fxe({toolRequestId:e,toolName:t,args:n,onAnswer:r}){const i=["command","path","url","pattern","query"].find(o=>typeof n[o]=="string"&&n[o].length>0),s=i?n[i]:JSON.stringify(n);return f.jsxs("div",{className:"rounded-2xl border border-border bg-background px-4 py-3 text-sm",children:[f.jsxs("div",{className:"flex items-baseline gap-2",children:[f.jsx("span",{className:"text-muted-foreground shrink-0",children:"Pending tool:"}),f.jsx("span",{className:"font-mono text-foreground",children:t})]}),s?f.jsx("pre",{className:"mt-1 max-h-32 overflow-auto whitespace-pre-wrap break-all font-mono text-xs text-muted-foreground",children:s}):null,f.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[f.jsx(Ue,{variant:"ghost",size:"sm",onClick:()=>r(e,{kind:"deny",reason:"user_canceled"}),children:"Deny"}),f.jsx(Ue,{variant:"default",size:"sm",onClick:()=>r(e,{kind:"allow"}),children:"Allow"})]})]})}function hxe({entry:e,onAnswer:t}){const{toolRequestId:n,toolName:r,arguments:i}=e;if(r==="mcp__kanna__ask_user_question"){const o=(Array.isArray(i.questions)?i.questions:[]).map(l=>({id:typeof l.id=="string"?l.id:void 0,question:typeof l.question=="string"?l.question:typeof l.text=="string"?l.text:"",header:typeof l.header=="string"?l.header:void 0,options:Array.isArray(l.options)?l.options:void 0,multiSelect:typeof l.multiSelect=="boolean"?l.multiSelect:!1}));return f.jsx(uxe,{toolRequestId:n,questions:o,onAnswer:t})}if(r==="mcp__kanna__exit_plan_mode"){const s=typeof i.plan=="string"?i.plan:"";return f.jsx(dxe,{toolRequestId:n,plan:s,onAnswer:t})}return f.jsx(fxe,{toolRequestId:n,toolName:r,args:i,onAnswer:t})}const mxe=new Set(["AskUserQuestion","ExitPlanMode","TodoWrite"]);function XD(e){if(e.kind!=="tool")return!1;const t=e.toolName;return!mxe.has(t)}function pxe(e,{isFirstSystem:t,isFirstAccount:n,isLatestTodoWrite:r,hideResult:i,isFinalStatus:s}){let o=!e.hidden;if(o)switch(e.kind){case"system_init":o=t;break;case"account_info":o=n;break;case"tool":o=e.toolKind!=="todo_write"||r;break;case"result":o=!i&&(!e.success||e.durationMs>6e4);break;case"context_window_updated":o=!1;break;case"status":o=s;break;default:o=!0;break}return{isFirstSystem:t,isFirstAccount:n,isLatestTodoWrite:r,hideResult:i,isFinalStatus:s,shouldRender:o}}function gxe(e,t){const n=e.findIndex(i=>i.kind==="system_init"),r=e.findIndex(i=>i.kind==="account_info");return e.map((i,s)=>{const o=e[s-1],l=e[s+1];return pxe(i,{isFirstSystem:n===s,isFirstAccount:r===s,isLatestTodoWrite:i.id===t.TodoWrite,hideResult:(l==null?void 0:l.kind)==="context_cleared"||(o==null?void 0:o.kind)==="context_cleared",isFinalStatus:s===e.length-1})})}function vxe(e,t){const n=[];let r=0;for(;r<e.length;){const i=e[r],s=t[r];if(s!=null&&s.shouldRender&&XD(i)){const o=[i],l=r;for(r+=1;r<e.length;){const c=e[r],u=t[r];if(!(u!=null&&u.shouldRender)){r+=1;continue}if(!XD(c))break;o.push(c),r+=1}o.length>=2?n.push({type:"tool-group",messages:o,startIndex:l}):n.push({type:"single",message:i,index:l});continue}n.push({type:"single",message:i,index:r}),r+=1}return n}function QD(e){var n;return e.type==="single"?e.message.id:`tool-group:${((n=e.messages[0])==null?void 0:n.id)??e.startIndex}`}function oS(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function bxe(e,t){return e.id===t.id&&e.kind===t.kind&&e.displayName===t.displayName&&e.absolutePath===t.absolutePath&&e.relativePath===t.relativePath&&e.contentUrl===t.contentUrl&&e.mimeType===t.mimeType&&e.size===t.size}function yxe(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>bxe(n,t[r]))}function Gd(e,t){var n,r;if(e===t)return!0;if(e.kind!==t.kind||e.id!==t.id||e.hidden!==t.hidden)return!1;switch(e.kind){case"user_prompt":return e.content===(t.kind==="user_prompt"?t.content:null)&&t.kind==="user_prompt"&&e.steered===t.steered&&((n=e.autoContinue)==null?void 0:n.scheduleId)===((r=t.autoContinue)==null?void 0:r.scheduleId)&&yxe(e.attachments,t.attachments);case"system_init":return t.kind==="system_init"&&e.provider===t.provider&&e.model===t.model&&oS(e.tools,t.tools)&&oS(e.agents,t.agents)&&oS(e.slashCommands,t.slashCommands)&&e.debugRaw===t.debugRaw;case"account_info":return t.kind==="account_info"&&JSON.stringify(e.accountInfo)===JSON.stringify(t.accountInfo);case"assistant_text":return t.kind==="assistant_text"&&e.text===t.text;case"tool":return t.kind==="tool"&&e.toolKind===t.toolKind&&e.toolName===t.toolName&&e.toolId===t.toolId&&e.isError===t.isError&&JSON.stringify(e.input)===JSON.stringify(t.input)&&JSON.stringify(e.result)===JSON.stringify(t.result)&&JSON.stringify(e.rawResult)===JSON.stringify(t.rawResult);case"result":return t.kind==="result"&&e.success===t.success&&e.cancelled===t.cancelled&&e.result===t.result&&e.durationMs===t.durationMs&&e.costUsd===t.costUsd;case"status":return t.kind==="status"&&e.status===t.status;case"compact_summary":return t.kind==="compact_summary"&&e.summary===t.summary;case"context_window_updated":return t.kind==="context_window_updated"&&JSON.stringify(e.usage)===JSON.stringify(t.usage);case"compact_boundary":case"context_cleared":case"interrupted":return!0;case"unknown":return t.kind==="unknown"&&e.json===t.json;case"auto_continue_prompt":return t.kind==="auto_continue_prompt"&&e.scheduleId===t.scheduleId;case"pending_tool_request":return t.kind==="pending_tool_request"&&e.toolRequestId===t.toolRequestId&&e.toolName===t.toolName}}function xxe(e,t){return e.kind!==t.kind||e.id!==t.id?!1:e.kind==="single"&&t.kind==="single"?e.index===t.index&&e.isLoading===t.isLoading&&e.localPath===t.localPath&&e.isFirstSystem===t.isFirstSystem&&e.isFirstAccount===t.isFirstAccount&&e.isLatestAskUserQuestion===t.isLatestAskUserQuestion&&e.isLatestExitPlanMode===t.isLatestExitPlanMode&&e.isLatestTodoWrite===t.isLatestTodoWrite&&e.hideResult===t.hideResult&&e.isFinalStatus===t.isFinalStatus&&Gd(e.message,t.message):e.kind==="tool-group"&&t.kind==="tool-group"?e.startIndex===t.startIndex&&e.isLoading===t.isLoading&&e.localPath===t.localPath&&e.messages.length===t.messages.length&&e.messages.every((n,r)=>Gd(n,t.messages[r])):!1}function _xe(e,t){const n=new Map;let r=e.length!==t.byId.size;const i=e.map((s,o)=>{const l=t.byId.get(s.id),c=l&&xxe(l,s)?l:s;return n.set(s.id,c),!r&&t.result[o]!==c&&(r=!0),c});return r?{byId:n,result:i}:t}function wxe(e){const t=v.useRef({byId:new Map,result:[]}),n=v.useMemo(()=>_xe(e,t.current),[e]);return v.useLayoutEffect(()=>{t.current=n}),n.result}const MF=(e,t)=>{},Sxe=v.memo(function({message:t,index:n,isLoading:r,localPath:i,isFirstSystem:s,isFirstAccount:o,isLatestAskUserQuestion:l,isLatestExitPlanMode:c,isLatestTodoWrite:u,hideResult:m,isFinalStatus:h,onAskUserQuestionSubmit:g,onExitPlanModeConfirm:b,onToolRequestAnswer:x=MF,schedules:_,onAutoContinueAccept:w,onAutoContinueReschedule:C,onAutoContinueCancel:E}){let k=null;if(t.kind==="user_prompt")k=f.jsx(L0e,{content:t.content,attachments:t.attachments,steered:t.steered,autoContinue:t.autoContinue},t.id);else switch(t.kind){case"auto_continue_prompt":{const N=_[t.scheduleId];if(!N){k=f.jsx("div",{className:"rounded border px-3 py-2 text-sm opacity-70",children:"Auto-continue expired"},t.id);break}k=f.jsx(cxe,{schedule:N,onAccept:R=>w(t.scheduleId,R),onReschedule:R=>C(t.scheduleId,R),onCancel:()=>E(t.scheduleId)},t.id);break}case"unknown":k=f.jsx(j0e,{json:t.json},t.id);break;case"system_init":k=s?f.jsx(z0e,{message:t,rawJson:t.debugRaw},t.id):null;break;case"account_info":k=o?f.jsx(B0e,{message:t},t.id):null;break;case"assistant_text":k=f.jsx(SF,{message:t},t.id);break;case"tool":if(t.isError){k=f.jsx(ay,{message:t,isLoading:r,localPath:i},t.id);break}if(t.toolKind==="ask_user_question"){k=f.jsx(EF,{message:t,onSubmit:g,isLatest:l},t.id);break}if(t.toolKind==="exit_plan_mode"){k=f.jsx(TF,{message:t,onConfirm:b,isLatest:c},t.id);break}if(t.toolKind==="todo_write"){k=u?f.jsx($0e,{message:t},t.id):null;break}if(t.toolKind==="offer_download"&&t.result){k=f.jsx(H0e,{message:t},t.id);break}if(t.toolKind==="image_generation"){k=f.jsx(G0e,{message:t},t.id);break}k=f.jsx(ay,{message:t,isLoading:r,localPath:i},t.id);break;case"result":k=m?null:f.jsx(CF,{message:t},t.id);break;case"context_window_updated":k=null;break;case"interrupted":k=f.jsx(q0e,{message:t},t.id);break;case"compact_boundary":k=f.jsx(K0e,{},t.id);break;case"context_cleared":k=f.jsx(Y0e,{},t.id);break;case"compact_summary":k=f.jsx(X0e,{message:t},t.id);break;case"status":k=h?f.jsx(Z0e,{message:t},t.id):null;break;case"pending_tool_request":k=f.jsx(hxe,{entry:t,onAnswer:x},t.id);break}return k?f.jsx("div",{id:`msg-${t.id}`,className:"group relative","data-index":n,[Eb]:"",children:k}):null},(e,t)=>e.index===t.index&&e.isLoading===t.isLoading&&e.localPath===t.localPath&&e.isFirstSystem===t.isFirstSystem&&e.isFirstAccount===t.isFirstAccount&&e.isLatestAskUserQuestion===t.isLatestAskUserQuestion&&e.isLatestExitPlanMode===t.isLatestExitPlanMode&&e.isLatestTodoWrite===t.isLatestTodoWrite&&e.hideResult===t.hideResult&&e.isFinalStatus===t.isFinalStatus&&e.onAskUserQuestionSubmit===t.onAskUserQuestionSubmit&&e.onExitPlanModeConfirm===t.onExitPlanModeConfirm&&e.onToolRequestAnswer===t.onToolRequestAnswer&&e.schedules===t.schedules&&e.onAutoContinueAccept===t.onAutoContinueAccept&&e.onAutoContinueReschedule===t.onAutoContinueReschedule&&e.onAutoContinueCancel===t.onAutoContinueCancel&&Gd(e.message,t.message)),Cxe=v.memo(function({id:t,messages:n,isLoading:r,localPath:i,expanded:s,onExpandedChange:o}){return f.jsx("div",{className:"group relative",[Eb]:"",children:f.jsx(rxe,{messages:n,isLoading:r,localPath:i,expanded:s,onExpandedChange:l=>o(t,l)})})},(e,t)=>e.id===t.id&&e.startIndex===t.startIndex&&e.isLoading===t.isLoading&&e.localPath===t.localPath&&e.expanded===t.expanded&&e.onExpandedChange===t.onExpandedChange&&e.messages.length===t.messages.length&&e.messages.every((n,r)=>Gd(n,t.messages[r])));function LF(e,{isLoading:t,localPath:n,latestToolIds:r}){const i=gxe(e,r),s=vxe(e,i),o=[];for(const l of s){if(l.type==="tool-group"){o.push({kind:"tool-group",id:QD(l),startIndex:l.startIndex,messages:l.messages,isLoading:t&&l.messages.some(m=>m.kind==="tool"&&m.result===void 0),localPath:n});continue}const c=i[l.index];if(!c)continue;const u={kind:"single",id:QD(l),message:l.message,index:l.index,isLoading:l.message.kind==="tool"&&l.message.result===void 0&&t,localPath:n,isFirstSystem:c.isFirstSystem,isFirstAccount:c.isFirstAccount,isLatestAskUserQuestion:l.message.id===r.AskUserQuestion,isLatestExitPlanMode:l.message.id===r.ExitPlanMode,isLatestTodoWrite:c.isLatestTodoWrite,hideResult:c.hideResult,isFinalStatus:c.isFinalStatus};c.shouldRender&&o.push(u)}return o}const kxe={};function jF(e,t,n,r,i,s,o){const l=n.get(e.runId)??[];return f.jsxs(Cn.Fragment,{children:[f.jsx(NF,{run:e,indentDepth:t,localPath:r,onSubagentAskUserQuestionSubmit:i,onSubagentExitPlanModeSubmit:s,onCancelSubagentRun:o}),l.map(c=>jF(c,t+1,n,r,i,s,o))]},e.runId)}const DF=v.memo(function({row:t,toolGroupExpanded:n,onToolGroupExpandedChange:r,onAskUserQuestionSubmit:i,onExitPlanModeConfirm:s,onToolRequestAnswer:o,schedules:l,onAutoContinueAccept:c,onAutoContinueReschedule:u,onAutoContinueCancel:m}){return t.kind==="tool-group"?f.jsx(Cxe,{id:t.id,startIndex:t.startIndex,messages:t.messages,isLoading:t.isLoading,localPath:t.localPath,expanded:n??!1,onExpandedChange:r}):f.jsx(Sxe,{message:t.message,index:t.index,isLoading:t.isLoading,localPath:t.localPath,isFirstSystem:t.isFirstSystem,isFirstAccount:t.isFirstAccount,isLatestAskUserQuestion:t.isLatestAskUserQuestion,isLatestExitPlanMode:t.isLatestExitPlanMode,isLatestTodoWrite:t.isLatestTodoWrite,hideResult:t.hideResult,isFinalStatus:t.isFinalStatus,onAskUserQuestionSubmit:i,onExitPlanModeConfirm:s,onToolRequestAnswer:o,schedules:l,onAutoContinueAccept:c,onAutoContinueReschedule:u,onAutoContinueCancel:m})},(e,t)=>{if(e.toolGroupExpanded!==t.toolGroupExpanded||e.onToolGroupExpandedChange!==t.onToolGroupExpandedChange||e.onAskUserQuestionSubmit!==t.onAskUserQuestionSubmit||e.onExitPlanModeConfirm!==t.onExitPlanModeConfirm||e.onToolRequestAnswer!==t.onToolRequestAnswer||e.schedules!==t.schedules||e.onAutoContinueAccept!==t.onAutoContinueAccept||e.onAutoContinueReschedule!==t.onAutoContinueReschedule||e.onAutoContinueCancel!==t.onAutoContinueCancel||e.row.kind!==t.row.kind||e.row.id!==t.row.id)return!1;if(e.row.kind==="tool-group"&&t.row.kind==="tool-group"){const n=e.row,r=t.row;return n.startIndex===r.startIndex&&n.isLoading===r.isLoading&&n.localPath===r.localPath&&n.messages.length===r.messages.length&&n.messages.every((i,s)=>Gd(i,r.messages[s]))}return e.row.kind==="single"&&t.row.kind==="single"?e.row.index===t.row.index&&e.row.isLoading===t.row.isLoading&&e.row.localPath===t.row.localPath&&e.row.isFirstSystem===t.row.isFirstSystem&&e.row.isFirstAccount===t.row.isFirstAccount&&e.row.isLatestAskUserQuestion===t.row.isLatestAskUserQuestion&&e.row.isLatestExitPlanMode===t.row.isLatestExitPlanMode&&e.row.isLatestTodoWrite===t.row.isLatestTodoWrite&&e.row.hideResult===t.row.hideResult&&e.row.isFinalStatus===t.row.isFinalStatus&&Gd(e.row.message,t.row.message):!1}),IF={},Exe=(e,t)=>{},Txe=(e,t)=>{},Nxe=e=>{};function Rxe({messages:e,isLoading:t,localPath:n,latestToolIds:r,onOpenLocalLink:i,onAskUserQuestionSubmit:s,onExitPlanModeConfirm:o,onToolRequestAnswer:l=MF,schedules:c=IF,onAutoContinueAccept:u=Exe,onAutoContinueReschedule:m=Txe,onAutoContinueCancel:h=Nxe,onTunnelAccept:g,onTunnelStop:b,onTunnelRetry:x,subagentRuns:_=kxe,onSubagentAskUserQuestionSubmit:w,onSubagentExitPlanModeSubmit:C,onCancelSubagentRun:E}){const[k,N]=v.useState({}),R=v.useMemo(()=>LF(e,{isLoading:t,localPath:n,latestToolIds:r}),[t,r,n,e]),{runsByUserMessageId:A,childrenByParentRunId:M}=v.useMemo(()=>{const F=new Map,D=new Map;for(const z of Object.values(_))if(z.parentRunId===null){const P=F.get(z.parentUserMessageId)??[];P.push(z),F.set(z.parentUserMessageId,P)}else{const P=D.get(z.parentRunId)??[];P.push(z),D.set(z.parentRunId,P)}const O=(z,P)=>z.startedAt-P.startedAt||z.runId.localeCompare(P.runId);for(const z of F.values())z.sort(O);for(const z of D.values())z.sort(O);return{runsByUserMessageId:F,childrenByParentRunId:D}},[_]),L=v.useCallback((F,D)=>{N(O=>O[F]===D?O:{...O,[F]:D})},[]);return f.jsx(PB,{onOpenLocalLink:i,children:R.map(F=>{const D=F.kind==="single"&&F.message.kind==="user_prompt"?F.message.id:null,O=D?A.get(D)??[]:[];return f.jsxs("div",{className:"mx-auto max-w-[800px] pb-5",children:[f.jsx(DF,{row:F,toolGroupExpanded:F.kind==="tool-group"?k[F.id]??!1:void 0,onToolGroupExpandedChange:L,onAskUserQuestionSubmit:s,onExitPlanModeConfirm:o,onToolRequestAnswer:l,schedules:c,onAutoContinueAccept:u,onAutoContinueReschedule:m,onAutoContinueCancel:h}),O.map(z=>jF(z,0,M,n??"",w,C,E))]},F.id)})})}v.memo(Rxe);function Axe(e=1e3){const[t,n]=v.useState(()=>Date.now()),r=v.useRef(e);return v.useLayoutEffect(()=>{r.current=e}),v.useEffect(()=>{const i=window.setInterval(()=>{n(Date.now())},r.current);return()=>window.clearInterval(i)},[]),t}function Mxe(e){switch(e.kind){case"bash_shell":return e.command;case"terminal_pty":return`PTY: ${e.cwd}`;case"codex_session":return"Codex session";case"draining_stream":return"Draining stream"}}function Lxe(e){switch(e.kind){case"bash_shell":return"bash";case"terminal_pty":return"terminal";case"codex_session":return"codex";case"draining_stream":return"stream"}}function jxe(e){return"chatId"in e?e.chatId??null:null}function Dxe(e){return e.kind==="bash_shell"?e.status==="stopping"?"stopping":"running":"active"}function Ixe(e){return(e.lastOutput??"").split(`
2609
2609
  `).slice(-12)}function Pxe(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}const PF=v.memo(function({task:t,index:n,now:r,isFocused:i,isExpanded:s,isDimmed:o,graceMs:l,variant:c="desktop",onFocus:u,onToggleExpand:m,onStopConfirmed:h,onForceKill:g,onConfirmStart:b,onConfirmEnd:x,stopButtonRef:_,_testInitialPhase:w}){const C=v.useRef(null),E=v.useRef(null),k=_??E,N=v.useRef(null),[R,A]=v.useState(()=>w==="confirm"?{phase:"confirm"}:w==="stopping"?{phase:"stopping",startedAt:0}:w==="forceAvailable"?{phase:"forceAvailable"}:{phase:"idle"}),M=Mxe(t),L=Lxe(t),F=jxe(t),D=Dxe(t),O=R.phase==="stopping"||R.phase==="forceAvailable"?null:oZ(t.startedAt,r),z=aZ(t.startedAt),P=Ixe(t),$=Pxe(),H=$||n>=8?0:n*24,B=$?{}:{animationName:"bg-task-row-enter",animationDuration:"180ms",animationTimingFunction:"cubic-bezier(0.25, 0.46, 0.45, 0.94)",animationFillMode:"both",animationDelay:`${H}ms`};v.useEffect(()=>{if(R.phase!=="stopping")return;const ae=setTimeout(()=>{A({phase:"forceAvailable"})},l);return()=>clearTimeout(ae)},[R.phase,l]),v.useEffect(()=>{var ae;R.phase==="confirm"&&((ae=N.current)==null||ae.focus())},[R.phase]);const V=v.useCallback(()=>{A({phase:"confirm"}),b(t.id)},[t.id,b]),G=v.useCallback(()=>{var ae;A({phase:"idle"}),x(),(ae=k.current)==null||ae.focus()},[x]),Q=v.useCallback(()=>{A({phase:"stopping",startedAt:Date.now()}),x(),h(t.id)},[t.id,x,h]),I=v.useCallback(()=>{g(t.id)},[t.id,g]),W=v.useCallback(ae=>{if(ae.key==="Escape"&&R.phase==="confirm"){ae.preventDefault(),ae.stopPropagation(),G();return}ae.key==="Enter"&&(ae.preventDefault(),m(t.id)),(ae.metaKey||ae.ctrlKey)&&ae.key==="."&&(ae.preventDefault(),R.phase==="idle"?V():R.phase==="confirm"?Q():R.phase==="forceAvailable"&&I())},[t.id,m,R.phase,V,Q,G,I]),te=v.useCallback(ae=>{ae.stopPropagation(),m(t.id)},[t.id,m]),U=$?{}:{animationName:"bg-task-confirm-slide-in",animationDuration:"180ms",animationTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)",animationFillMode:"both"},fe=()=>R.phase==="idle"?c==="mobile"?f.jsxs("button",{ref:k,type:"button","aria-label":"Stop task",onClick:ae=>{ae.stopPropagation(),V()},disabled:D==="stopping",className:he("w-full flex items-center justify-center gap-1.5 px-3 py-2 rounded-md","text-sm text-muted-foreground hover:text-destructive-text border border-border/60 hover:border-destructive-text/40","focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring","disabled:opacity-40 disabled:pointer-events-none","transition-colors"),"data-mobile-stop-line":!0,children:[f.jsx(KA,{className:"w-3 h-3 fill-current","aria-hidden":!0}),"Stop"]}):f.jsxs(Qr,{children:[f.jsx(Zr,{asChild:!0,children:f.jsx("button",{ref:k,type:"button","aria-label":"Stop task",onClick:ae=>{ae.stopPropagation(),V()},disabled:D==="stopping",className:he("flex-shrink-0 inline-flex items-center justify-center w-5 h-5 rounded-sm","text-muted-foreground hover:text-destructive-text","focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring","disabled:opacity-40 disabled:pointer-events-none","transition-colors"),children:f.jsx(KA,{className:"w-3 h-3 fill-current","aria-hidden":!0})})}),f.jsx(Hr,{side:"top",children:"Stop (⌘.)"})]}):R.phase==="confirm"?c==="mobile"?f.jsxs("span",{className:"grid grid-cols-2 gap-2 w-full",style:U,"data-confirm-area":!0,"data-mobile-stop-line":!0,children:[f.jsx("button",{ref:N,type:"button","aria-label":"Confirm stop",onClick:ae=>{ae.stopPropagation(),Q()},className:he("flex items-center justify-center rounded-md px-3 py-2 text-sm font-medium border","focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring","transition-colors"),style:{color:"var(--destructive-text)",borderColor:"var(--destructive-text)"},children:"Confirm stop?"}),f.jsx("button",{type:"button","aria-label":"Cancel stop",onClick:ae=>{ae.stopPropagation(),G()},className:he("flex items-center justify-center rounded-md px-3 py-2 text-sm","text-muted-foreground hover:text-foreground","border border-border/60 hover:border-border","focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring","transition-colors"),children:"Cancel"})]}):f.jsxs("span",{className:"flex items-center gap-1.5 flex-shrink-0",style:U,"data-confirm-area":!0,children:[f.jsx("button",{ref:N,type:"button","aria-label":"Confirm stop",onClick:ae=>{ae.stopPropagation(),Q()},className:he("inline-flex items-center rounded-sm px-1.5 py-0.5 text-xs font-medium","focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring","transition-colors"),style:{color:"var(--destructive-text)"},children:"Confirm stop?"}),f.jsx("button",{type:"button","aria-label":"Cancel stop",onClick:ae=>{ae.stopPropagation(),G()},className:he("inline-flex items-center rounded-sm px-1.5 py-0.5 text-xs","text-muted-foreground hover:text-foreground","border border-border/60 hover:border-border","focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring","transition-colors"),children:"Cancel"})]}):R.phase==="forceAvailable"?c==="mobile"?f.jsx("button",{type:"button","aria-label":"Force kill task",onClick:ae=>{ae.stopPropagation(),I()},className:he("w-full flex items-center justify-center rounded-md px-3 py-2 text-sm font-medium border","focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring","transition-colors"),style:{color:"var(--destructive-text)",borderColor:"var(--destructive-text)"},"data-mobile-stop-line":!0,children:"Force kill"}):f.jsxs(Qr,{children:[f.jsx(Zr,{asChild:!0,children:f.jsx("button",{type:"button","aria-label":"Force kill task",onClick:ae=>{ae.stopPropagation(),I()},className:he("flex-shrink-0 inline-flex items-center rounded-sm px-1.5 py-0.5 text-xs font-medium","focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring","transition-colors"),style:{color:"var(--destructive-text)"},children:"Force kill"})}),f.jsx(Hr,{side:"top",children:"Send SIGKILL immediately"})]}):null;return c==="mobile"?f.jsxs("div",{ref:C,role:"option","aria-selected":i,tabIndex:i?0:-1,"data-task-id":t.id,"data-row-enter":!0,"data-mobile-row":!0,onFocus:()=>u(t.id),onKeyDown:W,className:he("group relative flex flex-col px-3 py-3 rounded-md transition-all cursor-default gap-1.5","hover:bg-secondary focus-visible:bg-secondary","focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-ring",i&&"bg-secondary"),style:{...B,...o?{opacity:.6,pointerEvents:"none"}:{}},children:[f.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[f.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full flex-shrink-0 mt-px",style:{backgroundColor:R.phase==="stopping"||D==="stopping"?"var(--muted-foreground)":"var(--warning)"},"aria-hidden":!0}),f.jsx("span",{className:"flex-1 min-w-0 truncate font-mono text-sm font-semibold leading-snug",children:M}),O!==null?f.jsx("span",{className:"flex-shrink-0 font-mono text-[13px] font-medium tabular-nums text-muted-foreground leading-snug",children:O}):f.jsx("span",{className:"flex-shrink-0 font-mono text-[13px] italic text-muted-foreground leading-snug",children:"stopping…"})]}),f.jsxs("div",{className:"flex items-center gap-1.5 pl-[14px] min-w-0 flex-wrap",children:[f.jsx("span",{className:"text-xs text-muted-foreground font-sans leading-none flex-shrink-0",children:L}),F&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"text-xs text-muted-foreground leading-none flex-shrink-0","aria-hidden":!0,children:"·"}),f.jsx("a",{href:`/chat/${F}`,className:"text-xs text-muted-foreground hover:text-foreground underline underline-offset-2 leading-none truncate max-w-[160px] focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring rounded-sm",onClick:ae=>ae.stopPropagation(),children:"chat"})]}),f.jsx("span",{className:"text-xs text-muted-foreground leading-none flex-shrink-0","aria-hidden":!0,children:"·"}),f.jsxs("span",{className:"text-xs text-muted-foreground font-sans tabular-nums leading-none flex-shrink-0",children:["started ",z]}),f.jsx("span",{className:"text-xs font-sans leading-none flex-shrink-0",style:R.phase==="stopping"||R.phase==="forceAvailable"?{color:"var(--muted-foreground)"}:D!=="stopping"?{color:"var(--warning)"}:void 0,children:R.phase==="stopping"||R.phase==="forceAvailable"||D==="stopping"?"stopping":"running"})]}),t.kind==="bash_shell"&&M.length>40&&f.jsxs("details",{className:"pl-[14px]","data-full-command":!0,children:[f.jsx("summary",{className:"text-xs text-muted-foreground cursor-pointer select-none list-none underline underline-offset-2",children:"full command"}),f.jsx("pre",{className:"mt-1 text-xs font-mono text-muted-foreground whitespace-pre-wrap break-all leading-relaxed",children:M})]}),f.jsx("div",{className:"pl-[14px]","data-mobile-stop-line-wrapper":!0,children:fe()}),s&&f.jsx("pre",{className:"mt-1 pl-[14px] text-xs font-mono leading-[1.55] text-muted-foreground max-h-[240px] overflow-y-auto whitespace-pre-wrap break-all","aria-label":"Last output",children:P.join(`
2610
2610
  `)||"(no output)"})]}):f.jsxs("div",{ref:C,role:"option","aria-selected":i,tabIndex:i?0:-1,"data-task-id":t.id,"data-row-enter":!0,onFocus:()=>u(t.id),onKeyDown:W,className:he("group relative flex flex-col px-3 py-2.5 rounded-md transition-all cursor-default","hover:bg-secondary focus-visible:bg-secondary","focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-ring",i&&"bg-secondary"),style:{...B,...o?{opacity:.6,pointerEvents:"none"}:{}},children:[f.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[f.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full flex-shrink-0 mt-px",style:{backgroundColor:R.phase==="stopping"||D==="stopping"?"var(--muted-foreground)":"var(--warning)"},"aria-hidden":!0}),f.jsx("span",{className:"flex-1 min-w-0 truncate font-mono text-sm font-semibold leading-snug",children:M}),O!==null?f.jsx("span",{className:"flex-shrink-0 font-mono text-[13px] font-medium tabular-nums text-muted-foreground leading-snug",children:O}):f.jsx("span",{className:"flex-shrink-0 font-mono text-[13px] italic text-muted-foreground leading-snug",children:(R.phase==="forceAvailable","stopping…")}),f.jsxs(Qr,{children:[f.jsx(Zr,{asChild:!0,children:f.jsx("button",{type:"button","aria-label":s?"Collapse output":"Expand output",onClick:te,className:he("flex-shrink-0 inline-flex items-center justify-center w-5 h-5 rounded-sm","text-muted-foreground hover:text-foreground","focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring","transition-transform duration-150",s&&"rotate-90"),children:f.jsx(Po,{className:"w-3.5 h-3.5","aria-hidden":!0})})}),f.jsxs(Hr,{side:"top",children:[s?"Collapse output":"Expand output"," (Enter)"]})]})]}),f.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 pl-[14px] min-w-0",children:[f.jsx("span",{className:"text-xs text-muted-foreground font-sans leading-none flex-shrink-0",children:L}),F&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"text-xs text-muted-foreground leading-none flex-shrink-0","aria-hidden":!0,children:"·"}),f.jsx("a",{href:`/chat/${F}`,className:"text-xs text-muted-foreground hover:text-foreground underline underline-offset-2 leading-none truncate max-w-[200px] focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring rounded-sm",onClick:ae=>ae.stopPropagation(),children:"chat"})]}),f.jsx("span",{className:"text-xs text-muted-foreground leading-none flex-shrink-0","aria-hidden":!0,children:"·"}),f.jsxs("span",{className:"text-xs text-muted-foreground font-sans tabular-nums leading-none flex-shrink-0",children:["started ",z]}),f.jsx("span",{className:"text-xs font-sans leading-none flex-shrink-0",style:R.phase==="stopping"||R.phase==="forceAvailable"?{color:"var(--muted-foreground)"}:D!=="stopping"?{color:"var(--warning)"}:void 0,children:R.phase==="stopping"||R.phase==="forceAvailable"||D==="stopping"?"stopping":"running"}),f.jsx("span",{className:"flex-1"}),fe()]}),s&&f.jsx("pre",{className:"mt-2 pl-[14px] text-xs font-mono leading-[1.55] text-muted-foreground max-h-[240px] overflow-y-auto whitespace-pre-wrap break-all","aria-label":"Last output",children:P.join(`
2611
2611
  `)||"(no output)"})]})});function Oxe({orphans:e,now:t,variant:n,onStop:r,graceMs:i}){const[s,o]=v.useState("idle"),[l,c]=v.useState(null),[u,m]=v.useState(null),h=v.useId(),g=v.useCallback(()=>{o("confirm")},[]),b=v.useCallback(()=>{o("idle")},[]),x=v.useCallback(()=>{o("idle");for(const E of e)r(E.id,!1)},[e,r]),_=v.useCallback(E=>{c(E)},[]),w=v.useCallback(()=>{c(null)},[]),C=v.useCallback(E=>{m(k=>k===E?null:E)},[]);return e.length===0?null:f.jsxs("div",{className:"mb-3","data-orphan-section":!0,children:[f.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 mb-1",children:[f.jsx("span",{id:h,className:"text-xs text-muted-foreground font-sans","data-orphan-header":!0,children:"Found from previous session"}),s==="idle"?f.jsx("button",{type:"button",onClick:g,className:he("text-xs text-muted-foreground hover:text-foreground","focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring rounded-sm","transition-colors"),"data-kill-all-btn":!0,children:"Kill all"}):f.jsxs("span",{className:"flex items-center gap-2","data-kill-all-confirm":!0,children:[f.jsxs("button",{type:"button",onClick:x,className:he("text-xs font-medium","focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring rounded-sm","transition-colors"),style:{color:"var(--destructive-text)"},children:["Kill ",e.length," orphan",e.length!==1?"s":"","?"]}),f.jsx("button",{type:"button",onClick:b,className:he("text-xs text-muted-foreground hover:text-foreground","focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring rounded-sm","transition-colors"),children:"Cancel"})]})]}),f.jsx("div",{role:"listbox","aria-labelledby":h,"aria-label":"Orphan tasks from previous session",className:"flex flex-col gap-0.5",style:{opacity:.85},children:e.map((E,k)=>f.jsx(PF,{task:E,index:k,now:t,isFocused:!1,isExpanded:E.id===u,isDimmed:l!==null&&l!==E.id,graceMs:i,variant:n,onFocus:()=>{},onToggleExpand:C,onStopConfirmed:N=>r(N,!1),onForceKill:N=>r(N,!0),onConfirmStart:_,onConfirmEnd:w},E.id))})]})}function zxe({tasks:e,onStop:t,graceMs:n=3e3,variant:r="desktop"}){var F;const i=Axe(1e3),s=v.useRef(null),o=v.useId(),[l,c]=v.useState(null),[u,m]=v.useState(null),[h,g]=v.useState(null),b=e.filter(D=>D.kind==="bash_shell"&&D.orphan===!0),x=e.filter(D=>!(D.kind==="bash_shell"&&D.orphan===!0)),w=x.findIndex(D=>D.id===l)>=0?l:((F=x[0])==null?void 0:F.id)??null,C=v.useCallback(D=>{c(D)},[]),E=v.useCallback(D=>{m(O=>O===D?null:D)},[]),k=v.useCallback(D=>{t(D,!1)},[t]),N=v.useCallback(D=>{t(D,!0)},[t]),R=v.useCallback(D=>{g(D)},[]),A=v.useCallback(()=>{g(null)},[]),M=v.useCallback(D=>{var z,P,$,H;if(x.length===0)return;const O=x.findIndex(B=>B.id===w);if(D.key==="ArrowDown"){D.preventDefault();const B=Math.min(O+1,x.length-1),V=(z=x[B])==null?void 0:z.id;if(V){c(V);const G=(P=s.current)==null?void 0:P.querySelector(`[data-task-id="${V}"]`);G==null||G.focus()}}else if(D.key==="ArrowUp"){D.preventDefault();const B=Math.max(O-1,0),V=($=x[B])==null?void 0:$.id;if(V){c(V);const G=(H=s.current)==null?void 0:H.querySelector(`[data-task-id="${V}"]`);G==null||G.focus()}}},[x,w]),L=e.length;return f.jsx(Fy,{children:f.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[f.jsxs("div",{className:"flex flex-row items-center justify-between gap-4 shrink-0 p-4 border-b border-border",children:[f.jsx("h2",{id:o,className:"text-[18px] font-medium leading-none",children:"Background tasks"}),L>0&&f.jsxs("span",{className:"text-xs text-muted-foreground font-sans tabular-nums flex-shrink-0 mr-6",children:[L," running"]})]}),f.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 pb-4 pt-3.5",children:[b.length>0&&f.jsx(Oxe,{orphans:b,now:i,variant:r,onStop:t,graceMs:n}),e.length===0?f.jsx("p",{className:"text-sm text-muted-foreground py-4",children:"No background tasks. Anything an agent leaves running here will appear so you can stop it."}):x.length===0?null:f.jsx("div",{ref:s,role:"listbox","aria-label":"Background tasks","aria-labelledby":o,onKeyDown:M,className:"flex flex-col gap-0.5",children:x.map((D,O)=>f.jsx(PF,{task:D,index:O,now:i,isFocused:D.id===w,isExpanded:D.id===u,isDimmed:h!==null&&h!==D.id,graceMs:n,variant:r,onFocus:C,onToggleExpand:E,onStopConfirmed:k,onForceKill:N,onConfirmStart:R,onConfirmEnd:A},D.id))})]})]})})}function Bxe({open:e,onOpenChange:t,tasks:n,onStop:r,graceMs:i,variant:s="desktop"}){const o=v.useId(),l=s==="mobile"?"max-w-none w-full rounded-t-xl rounded-b-none left-0 right-0 bottom-0 top-auto translate-x-0 translate-y-0 max-h-[80vh]":"";return f.jsx(As,{open:e,onOpenChange:t,children:f.jsxs(es,{className:he("w-[min(720px,calc(100vw-2rem))] p-0",l,s==="mobile"&&"data-[state=open]:slide-in-from-bottom data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-left-0 data-[state=closed]:slide-out-to-left-0 data-[state=open]:slide-in-from-top-[0%] data-[state=closed]:slide-out-to-top-[0%]"),size:"lg","aria-labelledby":o,"data-variant":s,children:[f.jsx(Ms,{id:o,className:"sr-only",children:"Background tasks"}),f.jsx(zxe,{tasks:n,onStop:r,graceMs:i,variant:s})]})})}function Fxe({open:e,onOpenChange:t,socket:n,variant:r}){const i=Ys(c=>c.tasks),s=$4(),o=r??(s?"mobile":"desktop"),l=v.useCallback((c,u)=>{if(!n)return;const m={type:"bg-tasks.stop",id:c,force:u};n.command(m).catch(()=>{})},[n]);return f.jsx(Bxe,{open:e,onOpenChange:t,tasks:i,onStop:l,variant:o})}const $xe=`