@vibedeckx/ui-dist 0.3.11 → 0.3.12

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.
@@ -8,7 +8,7 @@ You can add a description to the \`${lC}\` by passing a \`${lT}\` component as a
8
8
 
9
9
  Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${lC}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component.
10
10
 
11
- For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return $.useEffect(()=>{document.getElementById(e.current?.getAttribute("aria-describedby"))||console.warn(r)},[r,e]),null};function lL({...e}){return(0,O.jsx)(lw,{"data-slot":"alert-dialog",...e})}function lz({...e}){return(0,O.jsx)(lS,{"data-slot":"alert-dialog-portal",...e})}function lO({className:e,...r}){return(0,O.jsx)(lj,{"data-slot":"alert-dialog-overlay",className:(0,ey.cn)("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...r})}function l$({className:e,...r}){return(0,O.jsxs)(lz,{children:[(0,O.jsx)(lO,{}),(0,O.jsx)(lD,{"data-slot":"alert-dialog-content",className:(0,ey.cn)("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...r})]})}function lW({className:e,...r}){return(0,O.jsx)("div",{"data-slot":"alert-dialog-header",className:(0,ey.cn)("flex flex-col gap-2 text-center sm:text-left",e),...r})}function lH({className:e,...r}){return(0,O.jsx)("div",{"data-slot":"alert-dialog-footer",className:(0,ey.cn)("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...r})}function lU({className:e,...r}){return(0,O.jsx)(lA,{"data-slot":"alert-dialog-title",className:(0,ey.cn)("text-lg font-semibold",e),...r})}function lq({className:e,...r}){return(0,O.jsx)(lM,{"data-slot":"alert-dialog-description",className:(0,ey.cn)("text-muted-foreground text-sm",e),...r})}function lK({className:e,...r}){return(0,O.jsx)(lF,{className:(0,ey.cn)((0,W.buttonVariants)(),e),...r})}function lV({className:e,...r}){return(0,O.jsx)(lI,{className:(0,ey.cn)((0,W.buttonVariants)({variant:"outline"}),e),...r})}let lY={task:"Task",workspace:"Workspace",agent_session:"Agent session",schedule:"Schedule",schedule_run:"Schedule run"};function lG({projectId:e,currentThreadId:r,threads:s,contextRefs:n,onNewThread:i,onSelectThread:a,onRenameThread:o,onArchiveThread:l,onDeleteThread:c,onOpenContext:d,newThreadPending:u=!1,className:h}){let[f,p]=(0,$.useState)(!0),[m,g]=(0,$.useState)(!0),[x,v]=(0,$.useState)(!1),[_,y]=(0,$.useState)(null),[b,w]=(0,$.useState)(null),[S,j]=(0,$.useState)(""),[C,k]=(0,$.useState)(null),[N,E]=(0,$.useState)(null),[D,R]=(0,$.useState)(new Set),[A,T]=(0,$.useState)(null),M=(0,$.useRef)(new Set),F=(0,$.useRef)(null),P=s.filter(e=>null===e.archived_at),I=!!b&&D.has(`rename:${b.id}`),B=!!N&&D.has(`delete:${N.id}`),L=!!C&&D.has(`archive:${C.id}`);(0,$.useEffect)(()=>{if(!_)return;F.current?.querySelector('[role="menuitem"]')?.focus();let e=e=>{"Escape"===e.key&&y(null)},r=e=>{F.current?.contains(e.target)||y(null)};return document.addEventListener("keydown",e),document.addEventListener("pointerdown",r),()=>{document.removeEventListener("keydown",e),document.removeEventListener("pointerdown",r)}},[_]);let z=async(e,r,s)=>{if(!M.current.has(e)){M.current.add(e),R(r=>new Set(r).add(e)),T(null);try{await r(),s()}catch(e){T(e instanceof Error?e.message:"Project Chat action failed")}finally{M.current.delete(e),R(r=>{let s=new Set(r);return s.delete(e),s})}}};return(0,O.jsxs)("aside",{"data-testid":"project-chat-rail","data-project-chat-column":!0,className:(0,ey.cn)("flex h-full w-[300px] shrink-0 flex-col overflow-hidden border-l border-border bg-muted/10",h),"aria-label":"Project Chat threads and context",children:[(0,O.jsxs)("section",{className:"flex min-h-0 flex-col border-b border-border/70",children:[(0,O.jsxs)("div",{className:"flex h-11 shrink-0 items-center gap-1 px-3",children:[(0,O.jsxs)("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-1.5 rounded px-1 py-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>p(e=>!e),"aria-expanded":f,children:[f?(0,O.jsx)(ns,{className:"size-4"}):(0,O.jsx)(a3,{className:"size-4"}),(0,O.jsx)("h2",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Chat Threads"})]}),(0,O.jsx)(W.Button,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"New thread",disabled:u,onClick:()=>void i(),children:(0,O.jsx)(eS,{className:"size-4","aria-hidden":"true"})})]}),f?(0,O.jsxs)("div",{className:"space-y-1 px-2 pb-3",children:[P.slice(0,5).map(e=>{let s=sM(e),n=e.id===r;return(0,O.jsxs)("div",{"data-testid":"thread-row",className:(0,ey.cn)("relative flex items-center rounded-md",n?"bg-accent":"hover:bg-muted"),children:[(0,O.jsx)("button",{type:"button","aria-label":`Open thread: ${s}`,"aria-current":n?"page":void 0,onClick:()=>a(e.id),className:"min-w-0 flex-1 truncate px-2 py-2 text-left text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:s}),(0,O.jsx)(W.Button,{type:"button",variant:"ghost",size:"icon-sm","aria-label":`Thread actions: ${s}`,"aria-expanded":_===e.id,"aria-haspopup":"menu","aria-controls":_===e.id?`thread-actions-${e.id}`:void 0,onClick:()=>y(r=>r===e.id?null:e.id),children:(0,O.jsx)(lx,{className:"size-4","aria-hidden":"true"})}),_===e.id?(0,O.jsxs)("div",{ref:F,id:`thread-actions-${e.id}`,role:"menu","aria-label":`Actions for ${s}`,className:"absolute right-1 top-9 z-20 w-40 rounded-md border bg-popover p-1 text-popover-foreground shadow-md",children:[(0,O.jsxs)("button",{type:"button",role:"menuitem",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted",onClick:()=>{y(null),T(null),w(e),j(s)},children:[(0,O.jsx)(rg,{className:"size-3.5"})," Rename thread"]}),(0,O.jsxs)("button",{type:"button",role:"menuitem",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted",onClick:()=>{y(null),T(null),k(e)},children:[(0,O.jsx)(sN,{className:"size-3.5"})," Archive thread"]}),(0,O.jsxs)("button",{type:"button",role:"menuitem",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm text-destructive hover:bg-destructive/10",onClick:()=>{y(null),T(null),E(e)},children:[(0,O.jsx)(rc,{className:"size-3.5"})," Delete thread"]})]}):null]},e.id)}),(0,O.jsx)(W.Button,{type:"button",variant:"ghost",size:"sm","aria-label":"View all threads",className:"w-full",onClick:()=>v(!0),children:"View all"})]}):null]}),(0,O.jsxs)("section",{className:"flex min-h-0 flex-1 flex-col",children:[(0,O.jsxs)("button",{type:"button",className:"flex h-11 shrink-0 items-center gap-1.5 px-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",onClick:()=>g(e=>!e),"aria-expanded":m,children:[m?(0,O.jsx)(ns,{className:"size-4"}):(0,O.jsx)(a3,{className:"size-4"}),(0,O.jsx)("h2",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Context"})]}),m?(0,O.jsx)("div",{className:"min-h-0 flex-1 space-y-1 overflow-y-auto px-2 pb-3",children:0===n.length?(0,O.jsx)("p",{className:"px-2 py-4 text-xs text-muted-foreground",children:"Referenced project items appear here."}):n.map(e=>{let r=lY[e.entity_type],s=!e.deleted&&(!e.navigation||!d),n=e.deleted||s,i=e.navigation?"Navigation is unavailable in this view.":"Navigation details are unavailable; refresh the thread and try again.";return(0,O.jsxs)("button",{type:"button",disabled:n,"aria-label":e.deleted?`Deleted ${r.toLocaleLowerCase()}`:s?`Unavailable ${r.toLocaleLowerCase()}`:`Open ${r}: ${e.navigation.label}`,title:s?i:void 0,onClick:()=>d?.(e),className:"flex w-full flex-col rounded-md px-2 py-2 text-left hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-55",children:[(0,O.jsx)("span",{className:"text-sm",children:e.deleted?`Deleted ${r.toLocaleLowerCase()}`:s?`Unavailable ${r.toLocaleLowerCase()}`:`${r} \xb7 ${e.navigation.label}`}),e.deleted?(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:"Deleted"}):null,s?(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:i}):null]},`${e.entity_type}:${e.entity_id}`)})}):null]}),(0,O.jsx)(sF,{open:x,onOpenChange:v,projectId:e,onSelectThread:a}),(0,O.jsx)(t8,{open:null!==b,onOpenChange:e=>{e||I||(w(null),T(null))},children:(0,O.jsxs)(rr,{children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:"Rename Project Chat thread"}),(0,O.jsx)(ra,{children:"Give this conversation a concise project-level title."})]}),(0,O.jsx)(ro,{autoFocus:!0,"aria-label":"Thread title",value:S,onChange:e=>j(e.target.value),onKeyDown:e=>{"Enter"===e.key&&b&&S.trim()&&z(`rename:${b.id}`,()=>o(b.id,S.trim()),()=>w(null))}}),A?(0,O.jsx)("div",{role:"alert",className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:A}):null,(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{type:"button",variant:"outline",disabled:I,onClick:()=>{w(null),T(null)},children:"Cancel"}),(0,O.jsx)(W.Button,{type:"button",disabled:!S.trim()||I,onClick:()=>{b&&z(`rename:${b.id}`,()=>o(b.id,S.trim()),()=>w(null))},children:"Save title"})]})]})}),(0,O.jsx)(lL,{open:null!==N,onOpenChange:e=>{e||B||(E(null),T(null))},children:(0,O.jsxs)(l$,{children:[(0,O.jsxs)(lW,{children:[(0,O.jsx)(lU,{children:"Delete this Project Chat thread?"}),(0,O.jsx)(lq,{children:"This permanently removes the thread and its persisted conversation."})]}),A?(0,O.jsx)("div",{role:"alert",className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:A}):null,(0,O.jsxs)(lH,{children:[(0,O.jsx)(lV,{disabled:B,children:"Cancel"}),(0,O.jsx)(lK,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:B,onClick:e=>{e.preventDefault(),N&&z(`delete:${N.id}`,()=>c(N.id),()=>E(null))},children:"Confirm delete"})]})]})}),(0,O.jsx)(lL,{open:null!==C,onOpenChange:e=>{e||L||(k(null),T(null))},children:(0,O.jsxs)(l$,{children:[(0,O.jsxs)(lW,{children:[(0,O.jsx)(lU,{children:"Archive this Project Chat thread?"}),(0,O.jsx)(lq,{children:"The conversation leaves recent selectors but remains available in thread history."})]}),A?(0,O.jsx)("div",{role:"alert",className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:A}):null,(0,O.jsxs)(lH,{children:[(0,O.jsx)(lV,{disabled:L,children:"Cancel"}),(0,O.jsx)(lK,{disabled:L,onClick:e=>{e.preventDefault(),C&&z(`archive:${C.id}`,()=>l(C.id),()=>k(null))},children:"Confirm archive"})]})]})})]})}var lX=e.i(113862);let lJ=(0,ew.default)("square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);var lZ="horizontal",lQ=["horizontal","vertical"],l0=$.forwardRef((e,r)=>{var s;let{decorative:n,orientation:i=lZ,...a}=e,o=(s=i,lQ.includes(s))?i:lZ;return(0,O.jsx)(er.div,{"data-orientation":o,...n?{role:"none"}:{"aria-orientation":"vertical"===o?o:void 0,role:"separator"},...a,ref:r})});l0.displayName="Separator",e.s(["Root",()=>l0,"Separator",()=>l0],691102),e.i(691102),(0,sn.cva)("flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",{variants:{orientation:{horizontal:"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}});var l1=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),l2=$.forwardRef((e,r)=>(0,O.jsx)(er.span,{...e,ref:r,style:{...l1,...e.style}}));l2.displayName="VisuallyHidden";var[l5,l3]=q("Tooltip",[iw]),l4=iw(),l6="TooltipProvider",l7="tooltip.open",[l8,l9]=l5(l6),ce=e=>{let{__scopeTooltip:r,delayDuration:s=700,skipDelayDuration:n=300,disableHoverableContent:i=!1,children:a}=e,o=$.useRef(!0),l=$.useRef(!1),c=$.useRef(0);return $.useEffect(()=>{let e=c.current;return()=>window.clearTimeout(e)},[]),(0,O.jsx)(l8,{scope:r,isOpenDelayedRef:o,delayDuration:s,onOpen:$.useCallback(()=>{window.clearTimeout(c.current),o.current=!1},[]),onClose:$.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.current=!0,n)},[n]),isPointerInTransitRef:l,onPointerInTransitChange:$.useCallback(e=>{l.current=e},[]),disableHoverableContent:i,children:a})};ce.displayName=l6;var ct="Tooltip",[cr,cs]=l5(ct),cn=e=>{let{__scopeTooltip:r,children:s,open:n,defaultOpen:i,onOpenChange:a,disableHoverableContent:o,delayDuration:l}=e,c=l9(ct,e.__scopeTooltip),d=l4(r),[u,h]=$.useState(null),f=ek(),p=$.useRef(0),m=o??c.disableHoverableContent,g=l??c.delayDuration,x=$.useRef(!1),[v,_]=G({prop:n,defaultProp:i??!1,onChange:e=>{e?(c.onOpen(),document.dispatchEvent(new CustomEvent(l7))):c.onClose(),a?.(e)},caller:ct}),y=$.useMemo(()=>v?x.current?"delayed-open":"instant-open":"closed",[v]),b=$.useCallback(()=>{window.clearTimeout(p.current),p.current=0,x.current=!1,_(!0)},[_]),w=$.useCallback(()=>{window.clearTimeout(p.current),p.current=0,_(!1)},[_]),S=$.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{x.current=!0,_(!0),p.current=0},g)},[g,_]);return $.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),(0,O.jsx)(iC,{...d,children:(0,O.jsx)(cr,{scope:r,contentId:f,open:v,stateAttribute:y,trigger:u,onTriggerChange:h,onTriggerEnter:$.useCallback(()=>{c.isOpenDelayedRef.current?S():b()},[c.isOpenDelayedRef,S,b]),onTriggerLeave:$.useCallback(()=>{m?w():(window.clearTimeout(p.current),p.current=0)},[w,m]),onOpen:b,onClose:w,disableHoverableContent:m,children:s})})};cn.displayName=ct;var ci="TooltipTrigger",ca=$.forwardRef((e,r)=>{let{__scopeTooltip:s,...n}=e,i=cs(ci,s),a=l9(ci,s),o=l4(s),l=$.useRef(null),c=(0,U.useComposedRefs)(r,l,i.onTriggerChange),d=$.useRef(!1),u=$.useRef(!1),h=$.useCallback(()=>d.current=!1,[]);return $.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),(0,O.jsx)(iN,{asChild:!0,...o,children:(0,O.jsx)(er.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...n,ref:c,onPointerMove:K(e.onPointerMove,e=>{"touch"!==e.pointerType&&(u.current||a.isPointerInTransitRef.current||(i.onTriggerEnter(),u.current=!0))}),onPointerLeave:K(e.onPointerLeave,()=>{i.onTriggerLeave(),u.current=!1}),onPointerDown:K(e.onPointerDown,()=>{i.open&&i.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:K(e.onFocus,()=>{d.current||i.onOpen()}),onBlur:K(e.onBlur,i.onClose),onClick:K(e.onClick,i.onClose)})})});ca.displayName=ci;var co="TooltipPortal",[cl,cc]=l5(co,{forceMount:void 0}),cd=e=>{let{__scopeTooltip:r,forceMount:s,children:n,container:i}=e,a=cs(co,r);return(0,O.jsx)(cl,{scope:r,forceMount:s,children:(0,O.jsx)(Z,{present:s||a.open,children:(0,O.jsx)(eW,{asChild:!0,container:i,children:n})})})};cd.displayName=co;var cu="TooltipContent",ch=$.forwardRef((e,r)=>{let s=cc(cu,e.__scopeTooltip),{forceMount:n=s.forceMount,side:i="top",...a}=e,o=cs(cu,e.__scopeTooltip);return(0,O.jsx)(Z,{present:n||o.open,children:o.disableHoverableContent?(0,O.jsx)(cx,{side:i,...a,ref:r}):(0,O.jsx)(cf,{side:i,...a,ref:r})})}),cf=$.forwardRef((e,r)=>{let s=cs(cu,e.__scopeTooltip),n=l9(cu,e.__scopeTooltip),i=$.useRef(null),a=(0,U.useComposedRefs)(r,i),[o,l]=$.useState(null),{trigger:c,onClose:d}=s,u=i.current,{onPointerInTransitChange:h}=n,f=$.useCallback(()=>{l(null),h(!1)},[h]),p=$.useCallback((e,r)=>{let s,n=e.currentTarget,i={x:e.clientX,y:e.clientY},a=function(e,r){let s=Math.abs(r.top-e.y),n=Math.abs(r.bottom-e.y),i=Math.abs(r.right-e.x),a=Math.abs(r.left-e.x);switch(Math.min(s,n,i,a)){case a:return"left";case i:return"right";case s:return"top";case n:return"bottom";default:throw Error("unreachable")}}(i,n.getBoundingClientRect());l(((s=[...function(e,r,s=5){let n=[];switch(r){case"top":n.push({x:e.x-s,y:e.y+s},{x:e.x+s,y:e.y+s});break;case"bottom":n.push({x:e.x-s,y:e.y-s},{x:e.x+s,y:e.y-s});break;case"left":n.push({x:e.x+s,y:e.y-s},{x:e.x+s,y:e.y+s});break;case"right":n.push({x:e.x-s,y:e.y-s},{x:e.x-s,y:e.y+s})}return n}(i,a),...function(e){let{top:r,right:s,bottom:n,left:i}=e;return[{x:i,y:r},{x:s,y:r},{x:s,y:n},{x:i,y:n}]}(r.getBoundingClientRect())].slice()).sort((e,r)=>e.x<r.x?-1:e.x>r.x?1:e.y<r.y?-1:1*!!(e.y>r.y)),function(e){if(e.length<=1)return e.slice();let r=[];for(let s=0;s<e.length;s++){let n=e[s];for(;r.length>=2;){let e=r[r.length-1],s=r[r.length-2];if((e.x-s.x)*(n.y-s.y)>=(e.y-s.y)*(n.x-s.x))r.pop();else break}r.push(n)}r.pop();let s=[];for(let r=e.length-1;r>=0;r--){let n=e[r];for(;s.length>=2;){let e=s[s.length-1],r=s[s.length-2];if((e.x-r.x)*(n.y-r.y)>=(e.y-r.y)*(n.x-r.x))s.pop();else break}s.push(n)}return(s.pop(),1===r.length&&1===s.length&&r[0].x===s[0].x&&r[0].y===s[0].y)?r:r.concat(s)}(s))),h(!0)},[h]);return $.useEffect(()=>()=>f(),[f]),$.useEffect(()=>{if(c&&u){let e=e=>p(e,u),r=e=>p(e,c);return c.addEventListener("pointerleave",e),u.addEventListener("pointerleave",r),()=>{c.removeEventListener("pointerleave",e),u.removeEventListener("pointerleave",r)}}},[c,u,p,f]),$.useEffect(()=>{if(o){let e=e=>{let r=e.target,s={x:e.clientX,y:e.clientY},n=c?.contains(r)||u?.contains(r),i=!function(e,r){let{x:s,y:n}=e,i=!1;for(let e=0,a=r.length-1;e<r.length;a=e++){let o=r[e],l=r[a],c=o.x,d=o.y,u=l.x,h=l.y;d>n!=h>n&&s<(u-c)*(n-d)/(h-d)+c&&(i=!i)}return i}(s,o);n?f():i&&(f(),d())};return document.addEventListener("pointermove",e),()=>document.removeEventListener("pointermove",e)}},[c,u,o,d,f]),(0,O.jsx)(cx,{...e,ref:a})}),[cp,cm]=l5(ct,{isInside:!1}),cg=(0,et.createSlottable)("TooltipContent"),cx=$.forwardRef((e,r)=>{let{__scopeTooltip:s,children:n,"aria-label":i,onEscapeKeyDown:a,onPointerDownOutside:o,...l}=e,c=cs(cu,s),d=l4(s),{onClose:u}=c;return $.useEffect(()=>(document.addEventListener(l7,u),()=>document.removeEventListener(l7,u)),[u]),$.useEffect(()=>{if(c.trigger){let e=e=>{let r=e.target;r?.contains(c.trigger)&&u()};return window.addEventListener("scroll",e,{capture:!0}),()=>window.removeEventListener("scroll",e,{capture:!0})}},[c.trigger,u]),(0,O.jsx)(eR,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:e=>e.preventDefault(),onDismiss:u,children:(0,O.jsxs)(iA,{"data-state":c.stateAttribute,...d,...l,ref:r,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[(0,O.jsx)(cg,{children:n}),(0,O.jsx)(cp,{scope:s,isInside:!0,children:(0,O.jsx)(l2,{id:c.contentId,role:"tooltip",children:i||n})})]})})});ch.displayName=cu;var cv="TooltipArrow",c_=$.forwardRef((e,r)=>{let{__scopeTooltip:s,...n}=e,i=l4(s);return cm(cv,s).isInside?null:(0,O.jsx)(iF,{...i,...n,ref:r})});c_.displayName=cv,e.s(["Arrow",()=>c_,"Content",()=>ch,"Portal",()=>cd,"Provider",()=>ce,"Root",()=>cn,"Tooltip",()=>cn,"TooltipArrow",()=>c_,"TooltipContent",()=>ch,"TooltipPortal",()=>cd,"TooltipProvider",()=>ce,"TooltipTrigger",()=>ca,"Trigger",()=>ca,"createTooltipScope",()=>l3],517964);var cy=e.i(517964),cy=cy;function cb({delayDuration:e=0,...r}){return(0,O.jsx)(cy.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...r})}function cw({...e}){return(0,O.jsx)(cy.Root,{"data-slot":"tooltip",...e})}function cS({...e}){return(0,O.jsx)(cy.Trigger,{"data-slot":"tooltip-trigger",...e})}function cj({className:e,sideOffset:r=0,children:s,...n}){return(0,O.jsx)(cy.Portal,{children:(0,O.jsxs)(cy.Content,{"data-slot":"tooltip-content",sideOffset:r,className:(0,ey.cn)("bg-foreground text-background 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 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...n,children:[s,(0,O.jsx)(cy.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}(0,ew.default)("chevron-left",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);var cC=e.i(94265),ck=cC;let cN=({className:e,from:r,...s})=>(0,O.jsx)("div",{className:(0,ey.cn)("group flex w-full max-w-[95%] flex-col gap-2","user"===r?"is-user ml-auto justify-end":"is-assistant",e),...s}),cE=({children:e,className:r,...s})=>(0,O.jsx)("div",{className:(0,ey.cn)("is-user:dark flex w-fit max-w-full min-w-0 flex-col gap-2 overflow-hidden text-sm","group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground","group-[.is-assistant]:text-foreground",r),...s,children:e}),cD=(0,$.memo)(({className:e,...r})=>(0,O.jsx)(ck.i,{className:(0,ey.cn)("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...r}),(e,r)=>e.children===r.children);cD.displayName="MessageResponse";let cR=(0,ew.default)("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]),cA={damping:.7,stiffness:.05,mass:1.25},cT=1e3/60,cM=!1;function cF(e,r){let s=(0,$.useCallback)(r=>(s.current=r,e(r)),r);return s}globalThis.document?.addEventListener("mousedown",()=>{cM=!0}),globalThis.document?.addEventListener("mouseup",()=>{cM=!1}),globalThis.document?.addEventListener("click",()=>{cM=!1});let cP=new Map;function cI(...e){let r={...cA},s=!1;for(let n of e){if("instant"===n){s=!0;continue}"object"==typeof n&&(s=!1,r.damping=n.damping??r.damping,r.stiffness=n.stiffness??r.stiffness,r.mass=n.mass??r.mass)}let n=JSON.stringify(r);return cP.has(n)||cP.set(n,Object.freeze(r)),s?"instant":cP.get(n)}let cB=(0,$.createContext)(null),cL="undefined"!=typeof window?$.useLayoutEffect:$.useEffect;function cz({instance:e,children:r,resize:s,initial:n,mass:i,damping:a,stiffness:o,targetScrollTop:l,contextRef:c,...d}){let u=(0,$.useRef)(null),h=((e={})=>{let[r,s]=(0,$.useState)(!1),[n,i]=(0,$.useState)(!1!==e.initial),[a,o]=(0,$.useState)(!1),l=(0,$.useRef)(null);l.current=e;let c=(0,$.useCallback)(()=>{if(!cM)return!1;let e=window.getSelection();if(!e||!e.rangeCount)return!1;let r=e.getRangeAt(0);return r.commonAncestorContainer.contains(x.current)||x.current?.contains(r.commonAncestorContainer)},[]),d=(0,$.useCallback)(e=>{h.isAtBottom=e,i(e)},[]),u=(0,$.useCallback)(e=>{h.escapedFromLock=e,s(e)},[]),h=(0,$.useMemo)(()=>{let s;return{escapedFromLock:r,isAtBottom:n,resizeDifference:0,accumulated:0,velocity:0,listeners:new Set,get scrollTop(){return x.current?.scrollTop??0},set scrollTop(scrollTop){x.current&&(x.current.scrollTop=scrollTop,h.ignoreScrollToTop=x.current.scrollTop)},get targetScrollTop(){if(!x.current||!v.current)return 0;return x.current.scrollHeight-1-x.current.clientHeight},get calculatedTargetScrollTop(){if(!x.current||!v.current)return 0;let{targetScrollTop:r}=this;if(!e.targetScrollTop)return r;if(s?.targetScrollTop===r)return s.calculatedScrollTop;let n=Math.max(Math.min(e.targetScrollTop(r,{scrollElement:x.current,contentElement:v.current}),r),0);return s={targetScrollTop:r,calculatedScrollTop:n},requestAnimationFrame(()=>{s=void 0}),n},get scrollDifference(){return this.calculatedTargetScrollTop-this.scrollTop},get isNearBottom(){return this.scrollDifference<=70}}},[]),f=(0,$.useCallback)((e={})=>{let r;"string"==typeof e&&(e={animation:e}),e.preserveScrollPosition||d(!0);let s=Date.now()+(Number(e.wait)||0),n=cI(l.current,e.animation),{ignoreEscapes:i=!1}=e,a=h.calculatedTargetScrollTop;e.duration instanceof Promise?e.duration.finally(()=>{r=Date.now()}):r=s+(e.duration??0);let o=async()=>{let e=new Promise(requestAnimationFrame).then(()=>{if(!h.isAtBottom)return h.animation=void 0,!1;let{scrollTop:d}=h,u=performance.now(),p=(u-(h.lastTick??u))/cT;if(h.animation||(h.animation={behavior:n,promise:e,ignoreEscapes:i}),h.animation.behavior===n&&(h.lastTick=u),c()||s>Date.now())return o();if(d<Math.min(a,h.calculatedTargetScrollTop)){if(h.animation?.behavior===n){if("instant"===n)return h.scrollTop=h.calculatedTargetScrollTop,o();h.velocity=(n.damping*h.velocity+n.stiffness*h.scrollDifference)/n.mass,h.accumulated+=h.velocity*p,h.scrollTop+=h.accumulated,h.scrollTop!==d&&(h.accumulated=0)}return o()}return r>Date.now()?(a=h.calculatedTargetScrollTop,o()):(h.animation=void 0,h.scrollTop<h.calculatedTargetScrollTop)?f({animation:cI(l.current,l.current.resize),ignoreEscapes:i,duration:Math.max(0,r-Date.now())||void 0}):h.isAtBottom});return e.then(e=>(requestAnimationFrame(()=>{h.animation||(h.lastTick=void 0,h.velocity=0)}),e))};return(!0!==e.wait&&(h.animation=void 0),h.animation?.behavior===n)?h.animation.promise:o()},[d,c,h]),p=(0,$.useCallback)(()=>{u(!0),d(!1)},[u,d]),m=(0,$.useCallback)(({target:e})=>{if(e!==x.current)return;let{scrollTop:r,ignoreScrollToTop:s}=h,{lastScrollTop:n=r}=h;h.lastScrollTop=r,h.ignoreScrollToTop=void 0,s&&s>r&&(n=s),o(h.isNearBottom),setTimeout(()=>{if(h.resizeDifference||r===s)return;if(c()){u(!0),d(!1);return}let e=r>n,i=r<n;if(h.animation?.ignoreEscapes){h.scrollTop=n;return}i&&(u(!0),d(!1)),e&&u(!1),!h.escapedFromLock&&h.isNearBottom&&d(!0)},1)},[u,d,c,h]),g=(0,$.useCallback)(({target:e,deltaY:r})=>{let s=e;for(;!["scroll","auto"].includes(getComputedStyle(s).overflow);){if(!s.parentElement)return;s=s.parentElement}s===x.current&&r<0&&x.current.scrollHeight>x.current.clientHeight&&!h.animation?.ignoreEscapes&&(u(!0),d(!1))},[u,d,h]),x=cF(e=>{x.current?.removeEventListener("scroll",m),x.current?.removeEventListener("wheel",g),e?.addEventListener("scroll",m,{passive:!0}),e?.addEventListener("wheel",g,{passive:!0})},[]),v=cF(e=>{let r;h.resizeObserver?.disconnect(),e&&(h.resizeObserver=new ResizeObserver(([e])=>{let{height:s}=e.contentRect,n=s-(r??s);if(h.resizeDifference=n,h.scrollTop>h.targetScrollTop&&(h.scrollTop=h.targetScrollTop),o(h.isNearBottom),n>=0){let e=cI(l.current,r?l.current.resize:l.current.initial);f({animation:e,wait:!0,preserveScrollPosition:!0,duration:"instant"===e?void 0:350})}else h.isNearBottom&&(u(!1),d(!0));r=s,requestAnimationFrame(()=>{setTimeout(()=>{h.resizeDifference===n&&(h.resizeDifference=0)},1)})}),h.resizeObserver?.observe(e))},[]);return{contentRef:v,scrollRef:x,scrollToBottom:f,stopScroll:p,isAtBottom:n||a,isNearBottom:a,escapedFromLock:r,state:h}})({mass:i,damping:a,stiffness:o,resize:s,initial:n,targetScrollTop:$.useCallback((e,r)=>{let s=y?.targetScrollTop??l;return s?.(e,r)??e},[l])}),{scrollRef:f,contentRef:p,scrollToBottom:m,stopScroll:g,isAtBottom:x,escapedFromLock:v,state:_}=e??h,y=(0,$.useMemo)(()=>({scrollToBottom:m,stopScroll:g,scrollRef:f,isAtBottom:x,escapedFromLock:v,contentRef:p,state:_,get targetScrollTop(){return u.current},set targetScrollTop(targetScrollTop){u.current=targetScrollTop}}),[m,x,p,f,g,v,_]);return(0,$.useImperativeHandle)(c,()=>y,[y]),cL(()=>{f.current&&"visible"===getComputedStyle(f.current).overflow&&(f.current.style.overflow="auto")},[]),$.createElement(cB.Provider,{value:y},$.createElement("div",{...d},"function"==typeof r?r(y):r))}function cO(){let e=(0,$.useContext)(cB);if(!e)throw Error("use-stick-to-bottom component context must be used within a StickToBottom component");return e}(cz||(cz={})).Content=function({children:e,scrollClassName:r,...s}){let n=cO();return $.createElement("div",{ref:n.scrollRef,style:{height:"100%",width:"100%",scrollbarGutter:"stable both-edges"},className:r},$.createElement("div",{...s,ref:n.contentRef},"function"==typeof e?e(n):e))};let c$=({className:e,...r})=>(0,O.jsx)(cz,{className:(0,ey.cn)("relative flex-1 overflow-y-hidden",e),initial:"smooth",resize:"smooth",role:"log",...r}),cW=({className:e,...r})=>(0,O.jsx)(cz.Content,{className:(0,ey.cn)("flex flex-col gap-8 p-4",e),...r}),cH=({className:e,...r})=>{let{isAtBottom:s,scrollToBottom:n}=cO(),i=(0,$.useCallback)(()=>{n()},[n]);return!s&&(0,O.jsx)(W.Button,{className:(0,ey.cn)("absolute bottom-4 left-[50%] translate-x-[-50%] rounded-full",e),onClick:i,size:"icon",type:"button",variant:"outline",...r,children:(0,O.jsx)(cR,{className:"size-4"})})},cU=(0,ew.default)("circle-dot",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]),cq=(0,ew.default)("clock-3",[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),cK=(0,ew.default)("message-square-more",[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 11h.01",key:"z322tv"}],["path",{d:"M16 11h.01",key:"xkw8gn"}],["path",{d:"M8 11h.01",key:"1dfujw"}]]);function cV({operation:e,onOpenSession:r,onViewOutput:s,onRunAgain:n,pendingAction:i,actionError:a}){let{label:o,detail:l}=function(e){switch(e.kind){case"task_create":return{label:"Task created",detail:e.title??e.taskId};case"task_update":return{label:"Task updated",detail:e.title??e.taskId};case"agent_session_create":return{label:"Agent session",detail:e.branch?`${e.target??"workspace"} / ${e.branch}`:e.target??"main workspace"};case"agent_instruction":return{label:"Agent instruction",detail:e.instruction??e.sessionId};case"schedule_run":return{label:"Schedule run",detail:e.runId}}}(e),c=e.failure?.code==="timeout"?{label:"Timed out",Icon:cq,className:"text-amber-600"}:e.failure?.code==="remote_offline"?{label:"Remote offline",Icon:sy,className:"text-destructive"}:e.failure?.code==="deleted_target"?{label:"Deleted target",Icon:sy,className:"text-muted-foreground"}:"completed"===e.status?{label:"Completed",Icon:sJ,className:"text-emerald-600"}:"failed"===e.status?{label:"Failed",Icon:sy,className:"text-destructive"}:"running"===e.status||"resolving"===e.status?{label:"Running",Icon:sj,className:"text-blue-600"}:{label:"Queued",Icon:cU,className:"text-muted-foreground"},d=e.failure?.code==="deleted_target",u="agent_session_create"===e.kind&&e.sessionAvailable&&("running"===e.status||"completed"===e.status)&&!d,h="schedule_run"===e.kind&&e.runAvailable&&("running"===e.status||"completed"===e.status||"failed"===e.status)&&!d,f="schedule_run"===e.kind&&e.runAvailable&&("completed"===e.status||"failed"===e.status)&&!d,p=c.Icon;return(0,O.jsxs)("section",{className:"rounded-lg border bg-card p-3 text-card-foreground","aria-label":`${o}: ${c.label}`,children:[(0,O.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("div",{className:"text-sm font-medium",children:o}),l?(0,O.jsx)("div",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:l}):null]}),(0,O.jsxs)("div",{"data-operation-status":e.status,className:(0,ey.cn)("flex shrink-0 items-center gap-1.5 text-xs font-medium",c.className),children:[(0,O.jsx)(p,{className:(0,ey.cn)("size-3.5",("running"===e.status||"resolving"===e.status)&&"animate-spin"),"aria-hidden":"true"}),c.label]})]}),e.failure?.message?(0,O.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:e.failure.message}):null,"agent_session_create"===e.kind&&u&&r?(0,O.jsx)("div",{className:"mt-3",children:(0,O.jsxs)(W.Button,{type:"button",size:"sm",variant:"outline","aria-busy":"open_session"===i,disabled:null!=i,onClick:()=>r(e),children:["open_session"===i?(0,O.jsx)(sj,{className:"size-3.5 animate-spin"}):(0,O.jsx)(s7,{className:"size-3.5"}),"Open Session"]})}):null,"schedule_run"===e.kind&&(h&&s||f&&n)?(0,O.jsxs)("div",{className:"mt-3 flex flex-wrap gap-2",children:[h&&s?(0,O.jsxs)(W.Button,{type:"button",size:"sm",variant:"outline","aria-busy":"view_output"===i,disabled:null!=i,onClick:()=>s(e),children:["view_output"===i?(0,O.jsx)(sj,{className:"size-3.5 animate-spin"}):(0,O.jsx)(cK,{className:"size-3.5"}),"View Output"]}):null,f&&n?(0,O.jsxs)(W.Button,{type:"button",size:"sm",variant:"outline","aria-busy":"run_again"===i,disabled:null!=i,onClick:()=>n(e),children:["run_again"===i?(0,O.jsx)(sj,{className:"size-3.5 animate-spin"}):(0,O.jsx)(s8,{className:"size-3.5"}),"run_again"===i?"Running again…":"Run Again"]}):null]}):null,a?(0,O.jsx)("p",{role:"alert",className:"mt-2 text-xs text-destructive",children:a}):null]})}let cY=(0,ew.default)("map-pin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);function cG({operation:e,onSelect:r,pendingWorkspaceId:s,actionError:n}){let i="pending"!==e.status;return(0,O.jsxs)("section",{className:"rounded-lg border bg-card p-3 text-card-foreground","aria-label":"Select a workspace for the agent session",children:[(0,O.jsx)("div",{className:"text-sm font-medium",children:"Choose a workspace"}),(0,O.jsx)("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"This agent session needs one of the project's offered workspaces."}),(0,O.jsx)("div",{className:"mt-3 grid gap-2",children:e.candidates.map(n=>{let a=s===n.id,o=`${n.target} / ${n.branch??"main"}`;return(0,O.jsxs)(W.Button,{type:"button",variant:"outline",className:"h-auto min-h-9 justify-start whitespace-normal text-left","aria-label":`Select workspace: ${o}`,"aria-busy":a,disabled:i||null!=s,onClick:()=>r({requestId:e.requestId,workspaceId:n.id}),children:[a?(0,O.jsx)(sj,{className:"size-3.5 animate-spin"}):(0,O.jsx)(cY,{className:"size-3.5"}),o,a?" · Selecting…":""]},n.id)})}),i?(0,O.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Workspace selection resolved."}):null,n?(0,O.jsx)("p",{role:"alert",className:"mt-2 text-xs text-destructive",children:n}):null]})}function cX(e){try{let r=JSON.parse(e);return"object"!=typeof r||null===r||Array.isArray(r)?null:r}catch{return null}}function cJ(e){if("workspace_selection"===e.kind)switch(e.status){case"pending":return"Waiting for workspace selection";case"resolving":return"Creating agent session";case"running":return"Agent session running";case"completed":return"Agent session completed";case"failed":return"Workspace selection failed"}if("agent_session_create"===e.kind){if("resolving"===e.status)return"Creating agent session";if("running"===e.status)return"Agent session running";if("completed"===e.status)return"Agent session completed"}switch(e.status){case"pending":return"Queued";case"resolving":case"running":return"Running";case"completed":return"Completed";case"failed":return"Failed"}}function cZ({messages:e,contextRefs:r,status:s,activeTurnId:n,pendingApprovalIds:i,queueLength:a,loading:o,hasEarlierMessages:l,loadingEarlierMessages:c,connected:d,error:u,initialDraft:h="",onDraftChange:f,onDraftSent:p,onSend:m,onLoadEarlierMessages:g,onStop:x,onResolveApproval:v,onSelectWorkspace:_,onOpenAgentSession:y,onOpenScheduleRun:b,onRunScheduleAgain:w}){let[S,j]=(0,$.useState)(h),[C,k]=(0,$.useState)(!1),[N,E]=(0,$.useState)(null),[D,R]=(0,$.useState)(new Set),[A,T]=(0,$.useState)(new Set),[M,F]=(0,$.useState)(null),P=(0,$.useRef)(!1),I=(0,$.useRef)(null),B=(0,$.useRef)(new Set),L=(0,$.useRef)(new Set),[z,H]=(0,$.useState)(new Map),[U,q]=(0,$.useState)(new Map),K=(0,$.useMemo)(()=>{let r=new Map,s=new Map;for(let n of e){if("operation"!==n.type)continue;let e=(0,rv.parseProjectChatOperationMessage)(n.content);e&&(r.set(n.id,e),s.set(e.operationId,n.id))}return{byMessageId:r,latestMessageIdByOperation:s}},[e]),V=async(e,r,s)=>{if(!L.current.has(e)){L.current.add(e),H(s=>new Map(s).set(e,r)),q(r=>{let s=new Map(r);return s.delete(e),s});try{await s()}catch(r){q(s=>new Map(s).set(e,r instanceof Error?r.message:"Project operation failed"))}finally{L.current.delete(e),H(r=>{let s=new Map(r);return s.delete(e),s})}}},Y=async e=>{e.preventDefault();let r=S.trim();if(r&&!P.current){P.current=!0,k(!0),F(null);try{await m(r),j(""),p?.(S)}catch(e){F(e instanceof Error?e.message:"Failed to send message")}finally{P.current=!1,k(!1)}}};(0,$.useEffect)(()=>{let e=I.current;e&&("running"!==s||n!==e)&&(I.current=null,E(null))},[n,s]);let G=async()=>{if(n&&!I.current){I.current=n,E(n),F(null);try{await x(n)}catch(e){I.current===n&&F(e instanceof Error?e.message:"Failed to stop generation")}}},X=async(e,r)=>{if(!B.current.has(e)){B.current.add(e),R(r=>new Set(r).add(e)),F(null);try{await v(e,r),T(r=>new Set(r).add(e))}catch(e){F(e instanceof Error?e.message:"Failed to resolve approval")}finally{B.current.delete(e),R(r=>{let s=new Set(r);return s.delete(e),s})}}};return(0,$.useEffect)(()=>{T(e=>{let r=new Set([...e].filter(e=>i.includes(e)));return r.size===e.size?e:r})},[i]),(0,O.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,O.jsxs)(c$,{className:"min-h-0",initial:"instant",resize:"smooth","data-testid":"project-chat-scroll",children:[(0,O.jsxs)(cW,{className:"mx-auto w-full max-w-3xl gap-4 px-4 py-5 sm:px-6",children:[l?(0,O.jsx)("div",{className:"flex justify-center",children:(0,O.jsxs)(W.Button,{type:"button",size:"sm",variant:"outline",disabled:c,onClick:()=>void g(),children:[c?(0,O.jsx)(sj,{className:"size-3.5 animate-spin"}):null,"Load earlier messages"]})}):null,o&&0===e.length?(0,O.jsx)("div",{className:"flex justify-center py-12",children:(0,O.jsx)(sj,{className:"size-5 animate-spin text-muted-foreground"})}):null,o||0!==e.length?null:(0,O.jsxs)("div",{className:"mx-auto max-w-md py-20 text-center",children:[(0,O.jsx)("h2",{className:"text-base font-semibold",children:"Start a project conversation"}),(0,O.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Discuss tasks, schedules, sessions, and work across the whole project."})]}),(0,O.jsxs)("div",{className:"flex w-full flex-col gap-4",children:[e.map(e=>{var s;if("turn_end"===e.type)return(0,O.jsxs)("div",{"data-testid":"turn-boundary",className:"my-2 flex items-center gap-2","aria-label":"Turn complete",children:[(0,O.jsx)("span",{className:"h-px flex-1 bg-border"}),(0,O.jsx)("span",{className:"size-1 rounded-full bg-border"}),(0,O.jsx)("span",{className:"h-px flex-1 bg-border"})]},e.id);if("user"===e.type||"assistant"===e.type)return(0,O.jsx)(cN,{from:e.type,children:(0,O.jsx)(cE,{children:"assistant"===e.type?(0,O.jsx)(cD,{children:e.content}):e.content})},e.id);if("tool_use"===e.type){let r;return(0,O.jsxs)("div",{className:"flex items-center gap-2 rounded-md bg-muted/50 px-3 py-2 text-xs text-muted-foreground",children:[(0,O.jsx)(sA,{className:"size-3.5"}),"Running ",(r=cX(e.content),("string"==typeof r?.toolName?r.toolName:"string"==typeof r?.tool?r.tool:"project tool").replaceAll("_"," ")),"…"]},e.id)}if("tool_result"===e.type){let r;return(0,O.jsxs)("details",{className:"rounded-md border px-3 py-2 text-xs",children:[(0,O.jsx)("summary",{className:"cursor-pointer text-muted-foreground",children:"Tool result"}),(0,O.jsx)("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap",children:(r=cX(s=e.content),"string"==typeof r?.output?r.output:"string"==typeof r?.error?r.error:s)})]},e.id)}if("tool_approval_request"===e.type){let r=cX(e.content);if(!r||"string"!=typeof r.approvalId)return null;let s="string"==typeof r.tool?r.tool:"project tool",n=i.includes(r.approvalId)&&!A.has(r.approvalId);return(0,O.jsxs)("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-sm",children:[(0,O.jsxs)("div",{className:"font-medium",children:["Approve ",s.replaceAll("_"," "),"?"]}),(0,O.jsx)("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap text-xs text-muted-foreground",children:JSON.stringify(r.input??{},null,2)}),n?(0,O.jsxs)("div",{className:"mt-3 flex gap-2",children:[(0,O.jsxs)(W.Button,{size:"sm","aria-label":`Approve ${s}`,disabled:D.has(r.approvalId),onClick:()=>void X(r.approvalId,!0),children:[(0,O.jsx)(rf.Check,{className:"size-3.5"}),"Approve"]}),(0,O.jsxs)(W.Button,{size:"sm",variant:"outline","aria-label":`Deny ${s}`,disabled:D.has(r.approvalId),onClick:()=>void X(r.approvalId,!1),children:[(0,O.jsx)(t7,{className:"size-3.5"}),"Deny"]})]}):(0,O.jsx)("div",{className:"mt-3 text-xs text-muted-foreground",children:"Approval expired or resolved"})]},e.id)}if("operation"===e.type){let s,n=K.byMessageId.get(e.id);if(!n)return(0,O.jsx)("div",{className:"rounded-md border bg-card px-3 py-2 text-sm text-muted-foreground",children:"Project operation unavailable"},e.id);if(K.latestMessageIdByOperation.get(n.operationId)!==e.id)return null;let i=(s=(e,s)=>r.some(r=>r.entity_type===e&&r.entity_id===s&&r.deleted),"task_create"===n.kind||"task_update"===n.kind?s("task",n.taskId):"agent_session_create"===n.kind||"agent_instruction"===n.kind?s("agent_session",n.sessionId):"schedule_run"===n.kind&&(s("schedule",n.scheduleId)||s("schedule_run",n.runId)))?{...n,failure:{code:"deleted_target",message:"The target no longer exists or is unavailable."}}:n,a=z.get(i.operationId),o=U.get(i.operationId);if("workspace_selection"===i.kind){let e=a?.startsWith("workspace:")?a.slice(10):null;return(0,O.jsxs)("div",{"data-operation-id":i.operationId,"data-operation-kind":i.kind,children:[(0,O.jsx)("p",{role:"status","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:cJ(i)}),(0,O.jsx)(cG,{operation:i,pendingWorkspaceId:e,actionError:o,onSelect:({requestId:e,workspaceId:r})=>{V(i.operationId,"select_workspace",async()=>{H(e=>new Map(e).set(i.operationId,`workspace:${r}`)),await _(e,r)})}})]},`operation:${i.operationId}`)}return(0,O.jsxs)("div",{"data-operation-id":i.operationId,"data-operation-kind":i.kind,children:[(0,O.jsx)("p",{role:"status","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:cJ(i)}),(0,O.jsx)(cV,{operation:i,pendingAction:a,actionError:o,onOpenSession:"agent_session_create"===i.kind&&y?e=>{V(e.operationId,"open_session",()=>y(e.sessionId,e.target??"local",e.branch??null))}:void 0,onViewOutput:"schedule_run"===i.kind&&b?e=>{V(e.operationId,"view_output",()=>b(e.runId,e.scheduleId))}:void 0,onRunAgain:"schedule_run"===i.kind&&w?e=>{V(e.operationId,"run_again",()=>w(e.runId))}:void 0})]},`operation:${i.operationId}`)}if("error"===e.type){let r=cX(e.content),s="string"==typeof r?.message?r.message:e.content;return(0,O.jsxs)("div",{role:"alert",className:"flex gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[(0,O.jsx)(s6,{className:"mt-0.5 size-4 shrink-0"}),s]},e.id)}return(0,O.jsx)("div",{className:"rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:e.content},e.id)}),u?(0,O.jsx)("div",{role:"alert",className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:u}):null,M?(0,O.jsx)("div",{role:"alert",className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:M}):null]})]}),(0,O.jsx)(cH,{"aria-label":"Jump to latest message"})]}),(0,O.jsx)("div",{className:"shrink-0 border-t bg-background p-3 sm:px-6",children:(0,O.jsxs)("form",{onSubmit:e=>void Y(e),className:"mx-auto max-w-3xl",children:["running"===s?(0,O.jsxs)("div",{className:"mb-2 flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[(0,O.jsx)("span",{children:a>0?`${a} queued`:"Project Chat is working"}),(0,O.jsxs)(W.Button,{type:"button",variant:"outline",size:"sm","aria-label":"Stop generating",disabled:!n||null!==N,onClick:()=>void G(),children:[(0,O.jsx)(lJ,{className:"size-3"}),N?"Stopping…":"Stop generating"]})]}):null,"queued"===s?(0,O.jsxs)("div",{className:"mb-2 flex items-center gap-2 text-xs text-muted-foreground",role:"status",children:[(0,O.jsx)(lX.Clock,{className:"size-3.5"}),(0,O.jsx)("span",{children:"Waiting to start…"})]}):null,(0,O.jsxs)("div",{className:"relative",children:[(0,O.jsx)(rl,{"aria-label":"Message Project Chat",value:S,onChange:e=>{j(e.target.value),f?.(e.target.value)},onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),e.currentTarget.form?.requestSubmit())},placeholder:d?"Message Project Chat…":"Reconnecting to Project Chat…",disabled:!d||C,rows:2,className:"min-h-20 resize-none pr-16"}),(0,O.jsx)(W.Button,{type:"submit",size:"sm","aria-label":"Send message",disabled:!d||C||!S.trim(),className:"absolute bottom-2 right-2",children:"Send"})]})]})})]})}function cQ({projectId:e,threadId:r,projectName:s,onBack:n,onSelectThread:i,onOpenContext:a,onOpenAgentSession:o,onOpenScheduleRun:l,onRunScheduleAgain:c}){let d=function(e,r){let s=sf(e),[n,i]=(0,$.useState)([]),[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(!1),[d,u]=(0,$.useState)(!1),[h,f]=(0,$.useState)(ld),[p,m]=(0,$.useState)(!1),[g,x]=(0,$.useState)(null),[v,_]=(0,$.useState)(null),[y,b]=(0,$.useState)(null),w=(0,$.useRef)(ld()),S=(0,$.useRef)(e),j=(0,$.useRef)(r),C=(0,$.useRef)(0),k=(0,$.useRef)(0),N=(0,$.useRef)(null),E=(0,$.useRef)(!1),D=(0,$.useRef)(new Map),R=(0,$.useRef)(0),A=(0,$.useRef)(null),T=(0,$.useRef)(new Map);(0,$.useEffect)(()=>(E.current=!0,()=>{E.current=!1}),[]),(0,$.useEffect)(()=>{for(let[s,n]of(S.current=e,j.current=r,T.current))e&&n.identity.projectId===e||T.current.delete(s)},[e,r]);let M=(0,$.useCallback)(async(e,r,s)=>{N.current?.abort();let n=new AbortController;N.current=n;let a=++k.current;try{let o=await rv.api.listProjectChatThreads(e,s,{signal:n.signal});if(C.current!==r||S.current!==e||k.current!==a)return;i(o),x(null)}catch(s){if(n.signal.aborted||C.current!==r||S.current!==e||k.current!==a)return;x(s instanceof Error?s.message:"Failed to list Project Chat threads")}finally{N.current===n&&(N.current=null),C.current===r&&S.current===e&&k.current===a&&o(!1)}},[]);(0,$.useEffect)(()=>{C.current+=1,k.current+=1;let r=C.current;if(N.current?.abort(),N.current=null,!e){i([]),o(!1),x(null);return}return i([]),o(!0),x(null),M(e,r,!1),()=>{k.current+=1,N.current?.abort(),N.current=null}},[M,e]);let F=(0,$.useCallback)(async(e=!1)=>{let r=S.current;r&&await M(r,C.current,e)},[M]),P=(0,$.useCallback)((e,r)=>!!E.current&&S.current===e&&C.current===r&&(k.current+=1,N.current?.abort(),N.current=null,o(!1),!0),[]);(0,$.useEffect)(()=>{R.current+=1;let s=R.current,n=!1,i=!1,a=null,o=0,l=null,d=null,h=e=>{w.current=e,f(e)};if(A.current?.close(),A.current=null,m(!1),u(!1),_(null),b(null),!e||!r){h(ld()),c(!1);return}let p=T.current.get(r);p?.identity.projectId===e?(lu(T.current,p),h({thread:p.thread,messages:p.messages,hasEarlierMessages:p.hasEarlierMessages,earliestSequence:p.earliestSequence,status:p.status,activeTurnId:p.activeTurnId,pendingApprovalIds:p.pendingApprovalIds,queueLength:p.queueLength,contextRefs:p.contextRefs})):(T.current.delete(r),h(ld())),c(!0);let g=()=>!n&&!i&&R.current===s&&S.current===e&&j.current===r,x=()=>{null!==a&&clearTimeout(a),a=null},v=e=>g()&&d===e,y=e=>{null!==e.timeout&&clearTimeout(e.timeout),e.timeout=null,d===e&&(d=null)},C=e=>{y(e),e.controller.abort();let r=e.socket;e.socket=null,r&&A.current===r&&(A.current=null),r?.close()},k=e=>{i=!0,x(),d&&C(d),e&&A.current===e&&(A.current=null,e.close()),m(!1),c(!1),_("Thread not found"),b("thread_not_found")},N=(e=!1)=>{if(!g()||(e&&x(),null!==a))return;let r=e?0:Math.min(1e3*2**o,3e4);e||(o+=1),a=setTimeout(()=>{a=null,D(!0)},r)},E=(e,r)=>{g()&&A.current===e&&(d?.socket===e?C(d):(A.current=null,e.close()),m(!1),c(!1),r&&_(r),N())};async function D(s){if(!g()||d)return;let n={controller:new AbortController,timeout:null,socket:null};d=n,n.timeout=setTimeout(()=>{v(n)&&(C(n),m(!1),c(!1),_("Project Chat connection timed out"),N())},1e4);try{let[a,u]=await Promise.all([rv.api.getProjectChatThread(r,{signal:n.controller.signal}),(0,rv.getFreshToken)(s?{skipCache:!0}:void 0)]);if(!v(n))return;let{thread:f,contextRefs:p}=a;if(f.project_id!==e||f.id!==r){i=!0,C(n),_("Project Chat stream identity mismatch"),c(!1);return}if(!Array.isArray(p)||!p.every(lm)||p.some(e=>e.thread_id!==r))throw Error("Invalid Project Chat thread context");h({...w.current,thread:f,contextRefs:p});let x=new WebSocket((0,rv.getWebSocketUrl)(`/api/project-chat/threads/${r}/stream`,u));n.socket=x,A.current=x;let S=!1;l=null,x.onopen=()=>{g()&&A.current===x&&m(!0)},x.onmessage=s=>{if(g()&&A.current===x)try{let a=JSON.parse(s.data);if(!lf(a))throw Error("invalid frame");if("type"in a&&"project_chat_snapshot"===a.type){let s=a.snapshot;if(!function(e){if(!lf(e)||!lf(e.identity)||!lf(e.thread)||!Array.isArray(e.messages)||!Array.isArray(e.contextRefs))return!1;let r=e.thread.id,s=e.thread.project_id,n=e.thread.user_id;return"string"==typeof r&&"string"==typeof s&&"string"==typeof n&&"string"==typeof e.identity.projectId&&"string"==typeof e.identity.threadId&&"string"==typeof e.identity.userId&&e.identity.threadId===r&&e.identity.projectId===s&&e.identity.userId===n&&e.messages.every(e=>lp(e)&&e.thread_id===r)&&"boolean"==typeof e.hasEarlierMessages&&(null===e.earliestSequence||Number.isSafeInteger(e.earliestSequence))&&e.contextRefs.every(e=>lm(e)&&e.thread_id===r)&&lg(e.status)&&(null===e.activeTurnId||"string"==typeof e.activeTurnId)&&Array.isArray(e.pendingApprovalIds)&&e.pendingApprovalIds.every(e=>"string"==typeof e&&e.length>0)&&Number.isSafeInteger(e.queueLength)&&e.queueLength>=0}(s))throw Error("invalid snapshot");if(s.identity.threadId!==r||s.identity.projectId!==e||s.identity.userId!==f.user_id||s.thread.id!==r||s.thread.project_id!==e||s.thread.user_id!==f.user_id){i=!0,_("Project Chat stream identity mismatch"),c(!1),d===n?C(n):(A.current=null,x.close());return}S=!0,l=Date.now(),y(n),o=0,b(null),_(null),lu(T.current,s),h({thread:s.thread,messages:w.current.thread?.id===r&&null!==w.current.earliestSequence&&null!==s.earliestSequence&&w.current.earliestSequence<s.earliestSequence?lh(w.current.messages,s.messages):s.messages,hasEarlierMessages:w.current.thread?.id===r&&null!==w.current.earliestSequence&&null!==s.earliestSequence&&w.current.earliestSequence<s.earliestSequence?w.current.hasEarlierMessages:s.hasEarlierMessages,earliestSequence:w.current.thread?.id===r&&null!==w.current.earliestSequence&&null!==s.earliestSequence&&w.current.earliestSequence<s.earliestSequence?w.current.earliestSequence:s.earliestSequence,status:s.status,activeTurnId:s.activeTurnId,pendingApprovalIds:s.pendingApprovalIds,queueLength:s.queueLength,contextRefs:s.contextRefs}),c(!1)}else if("JsonPatch"in a){if(!S||!Array.isArray(a.JsonPatch))throw Error("invalid patch frame");let s=function(e,r){let s=e;for(let e of r){if(!lf(e)||"add"!==e.op&&"replace"!==e.op||"string"!=typeof e.path||!lf(e.value))return null;let r=/^\/messages\/(0|[1-9]\d*)$/.exec(e.path);if(r&&"ENTRY"===e.value.type&&lp(e.value.content)){let n=e.value.content,i=Number(r[1]);if(!Number.isSafeInteger(i)||null!==s.thread&&n.thread_id!==s.thread.id)return null;let a=[...s.messages];if("add"===e.op){if(i>a.length||a.some(e=>e.id===n.id))return null;a.push(n),a.sort((e,r)=>e.sequence-r.sequence)}else{let e=a.findIndex(e=>e.id===n.id);if(e<0)return null;a[e]=n}s={...s,messages:a,earliestSequence:a[0]?.sequence??null}}else if("/messages"===e.path&&"MESSAGES"===e.value.type&&Array.isArray(e.value.content)&&e.value.content.every(lp)&&"boolean"==typeof e.value.hasEarlierMessages&&(null===e.value.earliestSequence||Number.isSafeInteger(e.value.earliestSequence))&&e.value.content.every(e=>null===s.thread||e.thread_id===s.thread.id)){let r=null!==s.earliestSequence&&null!==e.value.earliestSequence&&s.earliestSequence<e.value.earliestSequence,n=r?lh(s.messages,e.value.content):e.value.content;s={...s,messages:n,earliestSequence:n[0]?.sequence??null,hasEarlierMessages:r?s.hasEarlierMessages:e.value.hasEarlierMessages}}else if("/status"===e.path&&"STATUS"===e.value.type&&lg(e.value.content))s={...s,status:e.value.content};else if("/activeTurnId"===e.path&&"ACTIVE_TURN"===e.value.type&&(null===e.value.content||"string"==typeof e.value.content))s={...s,activeTurnId:e.value.content};else if("/pendingApprovalIds"===e.path&&"APPROVALS"===e.value.type&&Array.isArray(e.value.content)&&e.value.content.every(e=>"string"==typeof e&&e.length>0))s={...s,pendingApprovalIds:[...new Set(e.value.content)].sort()};else if("/queueLength"===e.path&&"QUEUE"===e.value.type&&Number.isSafeInteger(e.value.content)&&e.value.content>=0)s={...s,queueLength:e.value.content};else{if(!("/contextRefs"===e.path&&"CONTEXT"===e.value.type&&Array.isArray(e.value.content)&&e.value.content.every(lm)&&e.value.content.every(e=>null===s.thread||e.thread_id===s.thread.id)))return null;s={...s,contextRefs:e.value.content}}}return s}(w.current,a.JsonPatch);if(!s)throw Error("invalid patch frame");l=Date.now(),s.thread&&lu(T.current,{identity:{projectId:e,threadId:r,userId:s.thread.user_id},thread:s.thread,messages:s.messages,hasEarlierMessages:s.hasEarlierMessages,earliestSequence:s.earliestSequence,status:s.status,activeTurnId:s.activeTurnId,pendingApprovalIds:s.pendingApprovalIds,queueLength:s.queueLength,contextRefs:s.contextRefs}),h(s)}else if("error"in a){if("Thread not found"===a.error)return void k(x);E(x,"string"==typeof a.error?a.error:"Project Chat stream failed")}else throw Error("unknown frame")}catch{E(x,"Invalid Project Chat stream message")}},x.onerror=()=>{E(x)},x.onclose=()=>{g()&&A.current===x&&(d?.socket===x&&C(d),A.current=null,m(!1),N())}}catch(e){if(!v(n))return;if(C(n),lf(e)&&(404===e.status||e instanceof Error&&"Thread not found"===e.message))return void k();c(!1),_(e instanceof Error?e.message:"Failed to open Project Chat thread"),N()}}let M=()=>{if(!g())return;x(),d&&C(d);let e=A.current;e&&(A.current=null,e.close()),m(!1),D(!0)},F=()=>M(),P=()=>{"visible"===document.visibilityState&&(d||null!==l&&Date.now()-l>4e4)&&M()};return window.addEventListener("online",F),document.addEventListener("visibilitychange",P),D(!1),()=>{n=!0,x(),d&&C(d),window.removeEventListener("online",F),document.removeEventListener("visibilitychange",P);let e=A.current;A.current=null,e?.close()}},[e,r]);let I=(0,$.useCallback)(async e=>{let r=S.current,n=C.current;if(!r)throw Error("No project selected");let a=await s(e);return a.project_id===r&&P(r,n)&&i(e=>[a,...e.filter(e=>e.id!==a.id)]),a},[s,P]),B=(0,$.useCallback)(e=>{if(i(r=>null===e.archived_at?[e,...r.filter(r=>r.id!==e.id)]:r.filter(r=>r.id!==e.id)),w.current.thread?.id===e.id){let r={...w.current,thread:e};w.current=r,f(r)}let r=T.current.get(e.id);r&&lu(T.current,{...r,thread:e})},[]),L=(0,$.useCallback)(async(e,r)=>{let s=S.current,n=C.current,i=r.trim();if(!i)throw Error("Title is required");let a=(D.current.get(e)??0)+1;D.current.set(e,a);let o=await rv.api.updateProjectChatThread(e,{title:i});return s&&o.project_id===s&&D.current.get(e)===a&&P(s,n)&&B(o),o},[P,B]),z=(0,$.useCallback)(async(e,r=!0)=>{let s=S.current,n=C.current,i=(D.current.get(e)??0)+1;D.current.set(e,i);let a=await rv.api.updateProjectChatThread(e,{archived:r});return s&&a.project_id===s&&D.current.get(e)===i&&P(s,n)&&B(a),a},[P,B]),O=(0,$.useCallback)(async e=>{let r=S.current,s=C.current,n=(D.current.get(e)??0)+1;if(D.current.set(e,n),await rv.api.deleteProjectChatThread(e),r&&D.current.get(e)===n&&P(r,s)&&(T.current.delete(e),i(r=>r.filter(r=>r.id!==e)),j.current===e)){R.current+=1,A.current?.close(),A.current=null,m(!1),c(!1);let e=ld();w.current=e,f(e)}},[P]),W=(0,$.useCallback)(async e=>{let r=j.current;if(!r)throw Error("No Project Chat thread selected");let s=e.trim();if(!s)throw Error("Message is required");await rv.api.sendProjectChatMessage(r,s)},[]),H=(0,$.useCallback)(async e=>{let r=j.current;return!!r&&rv.api.stopProjectChatTurn(r,e)},[]),U=(0,$.useCallback)(async(e,r)=>{let s=j.current;if(!s)throw Error("No Project Chat thread selected");await rv.api.approveProjectChatTool(s,e,r)},[]),q=(0,$.useCallback)(async(e,r)=>{let s=j.current;if(!s)throw Error("No Project Chat thread selected");await rv.api.selectProjectChatWorkspace(s,e,r)},[]),K=(0,$.useCallback)(async()=>{let e=j.current,r=w.current;if(e&&r.hasEarlierMessages&&null!==r.earliestSequence){u(!0);try{let s=await rv.api.listProjectChatMessages(e,{beforeSequence:r.earliestSequence});if(j.current!==e||w.current.thread?.id!==e)return;let n=lh(w.current.messages,s.messages),i={...w.current,messages:n,hasEarlierMessages:s.hasMore,earliestSequence:n[0]?.sequence??null};w.current=i,f(i),_(null)}catch(r){j.current===e&&_(r instanceof Error?r.message:"Failed to load earlier messages")}finally{j.current===e&&u(!1)}}},[]);return{...h,threads:n,loading:a||l,threadsLoading:a,threadLoading:l,loadingEarlierMessages:d,isConnected:p,error:v??g,terminalError:y,refetchThreads:F,createThread:I,renameThread:L,archiveThread:z,deleteThread:O,sendMessage:W,stopTurn:H,resolveToolApproval:U,selectWorkspace:q,loadEarlierMessages:K}}(e,r),[u,h]=(0,$.useState)(!0),[f,p]=(0,$.useState)(!1),[m,g]=(0,$.useState)(!1),[x,v]=(0,$.useState)(!1),[_,y]=(0,$.useState)(null),b=(0,$.useRef)(!1),w=(0,$.useRef)(new Map),S=(0,$.useRef)(null),j=(0,$.useRef)(0),C=sM(d.thread),k=d.threads.filter(e=>null===e.archived_at),N=`${e}:${r}`,E=function(){let[e,r]=$.useState(void 0);return $.useEffect(()=>{let e=window.matchMedia("(max-width: 767px)"),s=()=>{r(window.innerWidth<768)};return e.addEventListener("change",s),r(window.innerWidth<768),()=>e.removeEventListener("change",s)},[]),!!e}(),D=e=>{p(e),e||requestAnimationFrame(()=>S.current?.focus())};(0,$.useEffect)(()=>{j.current+=1,b.current=!1,v(!1),y(null),g(!1),p(!1)},[N]);let R=async()=>{if(b.current)return;let r=j.current;b.current=!0,v(!0),y(null);try{let s=await d.createThread();r===j.current&&s.project_id===e&&i(s.id)}catch(e){r===j.current&&y(e instanceof Error?e.message:"Failed to create thread")}finally{r===j.current&&(b.current=!1,v(!1))}},A=e=>{if(e!==r)return;let s=k.find(r=>r.id!==e);s?i(s.id):n()},T=async e=>{let r=j.current;await d.archiveThread(e,!0),r===j.current&&A(e)},M=async e=>{let r=j.current;await d.deleteThread(e),r===j.current&&A(e)};return(0,O.jsxs)("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[(0,O.jsxs)("header",{className:"flex h-12 shrink-0 items-center justify-between gap-3 border-b px-3 sm:px-4",children:[(0,O.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,O.jsx)(W.Button,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"Back to Overview",onClick:n,children:(0,O.jsx)(o9.ArrowLeft,{className:"size-4"})}),(0,O.jsx)(sD,{className:"size-4 shrink-0 text-primary","aria-hidden":"true"}),(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsxs)("div",{className:"truncate text-[11px] text-muted-foreground",children:[s," / Project Chat"]}),(0,O.jsxs)(a4,{open:m,onOpenChange:g,children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsxs)("button",{type:"button","aria-label":`Current thread: ${C}`,className:"flex max-w-[50vw] items-center gap-1 truncate text-sm font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,O.jsx)("span",{className:"truncate",children:C}),(0,O.jsx)(ns,{className:"size-3.5 shrink-0"})]})}),(0,O.jsxs)(a7,{align:"start",className:"w-64",children:[k.slice(0,5).map(e=>{let r=sM(e);return(0,O.jsx)(a8,{asChild:!0,children:(0,O.jsx)("button",{type:"button","aria-label":`Switch to thread: ${r}`,onClick:()=>i(e.id),className:"w-full truncate text-left",children:r})},e.id)}),(0,O.jsx)(a8,{asChild:!0,children:(0,O.jsxs)("button",{type:"button",disabled:x,onClick:()=>void R(),className:"w-full border-t",children:[(0,O.jsx)(eS,{className:"size-3.5"}),"New thread"]})})]})]})]})]}),(0,O.jsx)(W.Button,{ref:S,type:"button",variant:"ghost",size:"icon-sm","aria-label":E?"Open threads and context":u?"Hide threads and context":"Show threads and context",onClick:()=>E?p(!0):h(e=>!e),children:E?(0,O.jsx)(lt,{className:"size-4"}):u?(0,O.jsx)(le,{className:"size-4"}):(0,O.jsx)(lt,{className:"size-4"})})]}),_?(0,O.jsx)("div",{role:"alert",className:"border-b border-destructive/40 bg-destructive/10 px-4 py-2 text-sm text-destructive",children:_}):null,(0,O.jsxs)("div",{className:"flex min-h-0 flex-1","data-testid":"project-chat-workbench-columns",children:[(0,O.jsx)("main",{"data-testid":"project-chat-main","data-project-chat-column":!0,className:"min-w-0 flex-1",children:"thread_not_found"===d.terminalError?(0,O.jsx)("div",{className:"flex h-full items-center justify-center p-6 text-center",children:(0,O.jsxs)("div",{children:[(0,O.jsx)("h2",{className:"font-semibold",children:"Thread not found"}),(0,O.jsx)(W.Button,{className:"mt-3",variant:"outline",onClick:n,children:"Back to Overview"})]})}):(0,O.jsx)(cZ,{messages:d.messages,contextRefs:d.contextRefs,status:d.status,activeTurnId:d.activeTurnId,pendingApprovalIds:d.pendingApprovalIds,queueLength:d.queueLength,loading:d.threadLoading,hasEarlierMessages:d.hasEarlierMessages,loadingEarlierMessages:d.loadingEarlierMessages,connected:d.isConnected,error:d.error,initialDraft:w.current.get(N)??"",onDraftChange:e=>{e?w.current.set(N,e):w.current.delete(N)},onDraftSent:e=>{w.current.get(N)===e&&w.current.delete(N)},onSend:d.sendMessage,onLoadEarlierMessages:d.loadEarlierMessages,onStop:d.stopTurn,onResolveApproval:d.resolveToolApproval,onSelectWorkspace:d.selectWorkspace,onOpenAgentSession:o,onOpenScheduleRun:l,onRunScheduleAgain:c},N)}),!E&&u?(0,O.jsx)(lG,{projectId:e,currentThreadId:r,threads:d.threads,contextRefs:d.contextRefs,onNewThread:R,onSelectThread:i,onRenameThread:async(e,r)=>{await d.renameThread(e,r)},onArchiveThread:T,onDeleteThread:M,onOpenContext:a,newThreadPending:x},N):null]}),E?(0,O.jsx)(ls,{open:f,onOpenChange:D,children:(0,O.jsxs)(la,{side:"right","data-testid":"project-chat-mobile-drawer",className:"w-[min(90vw,360px)] gap-0 p-0","aria-label":"Project Chat threads and context",onCloseAutoFocus:e=>{e.preventDefault(),S.current?.focus()},children:[(0,O.jsxs)(lo,{className:"shrink-0 border-b px-4 py-3 pr-14 text-left",children:[(0,O.jsx)(ll,{className:"text-sm",children:"Threads and context"}),(0,O.jsx)(lc,{className:"text-xs",children:"Switch conversations and open referenced project items."})]}),(0,O.jsx)(lG,{projectId:e,className:"min-h-0 w-full flex-1 border-l-0",currentThreadId:r,threads:d.threads,contextRefs:d.contextRefs,onNewThread:R,onSelectThread:e=>{D(!1),i(e)},onRenameThread:async(e,r)=>{await d.renameThread(e,r)},onArchiveThread:T,onDeleteThread:M,onOpenContext:a?e=>{D(!1),a(e)}:void 0,newThreadPending:x},N)]})}):null]})}function c0(e){return e?"target-not-found"===e.error?e.requestedTarget:e.target:null}function c1(e){let r=[],s=`vibedeckx:mergeTarget:${e}:`;try{for(let e=0;e<localStorage.length;e+=1){let n=localStorage.key(e);if(!n?.startsWith(s))continue;let i=localStorage.getItem(n);i&&r.push({key:n,branch:n.slice(s.length),target:i})}}catch{}return r}let c2=new Map,c5=new Set(["working","main-running"]);function c3(e,r){return`vibedeckx:schedule-rerun:v2:${encodeURIComponent(e)}:${encodeURIComponent(r)}`}function c4(e){try{window.sessionStorage.removeItem(e)}catch{}}var ck=cC;let c6=(0,ew.default)("columns-3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]),c7=(0,ew.default)("settings",[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),c8={sm:{box:"size-4 rounded",text:"text-[9.5px]",icon:"size-2.5",letters:1},md:{box:"size-5 rounded-[5px]",text:"text-[9px]",icon:"size-3",letters:2}};function c9({name:e,size:r="sm",className:s}){let n=c8[r],i=s_(e,n.letters);return(0,O.jsx)("span",{"aria-hidden":"true",className:(0,ey.cn)("grid shrink-0 place-items-center bg-primary/14 font-mono font-semibold leading-none tracking-[-0.02em] text-primary",n.box,n.text,s),children:i||(0,O.jsx)(oY,{className:(0,ey.cn)(n.icon,"text-primary")})})}let de=(0,ew.default)("check-check",[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]]);function dt({info:e,repositoryLabel:r,onClick:s}){let n=function(e,r){if("target-not-found"===e.error){let s=`Target branch '${e.requestedTarget}' not found — pick a new target or reset to default`;return r?`${s} \xb7 ${r}`:s}let s=["merged"===e.status?`Merged into ${e.target}`:"no-unique-commits"===e.status?`In sync with ${e.target}`:`${e.unmergedCount} commit${1!==e.unmergedCount?"s":""} not in ${e.target}`];return e.dirty&&s.push("uncommitted changes"),r&&s.push(r),s.join(" · ")}(e,r);return(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsxs)("button",{onClick:e=>{e.stopPropagation(),s()},"aria-label":n,className:"relative shrink-0 flex items-center justify-center h-4 min-w-4 px-0.5 rounded hover:bg-muted",children:["target-not-found"===e.error?(0,O.jsx)(s6,{className:"h-3 w-3 text-amber-500"}):"merged"===e.status?(0,O.jsx)(rf.Check,{className:"h-3 w-3 text-muted-foreground/70"}):"no-unique-commits"===e.status?(0,O.jsx)(de,{className:"h-3 w-3 text-emerald-500"}):(0,O.jsx)("span",{className:"text-[10px] font-mono leading-none text-amber-500",children:e.unmergedCount}),!e.error&&e.dirty&&(0,O.jsx)("span",{className:"absolute -top-0.5 -right-0.5 h-1.5 w-1.5 rounded-full bg-orange-400"})]})}),(0,O.jsx)(cj,{side:"right",children:n})]})}let dr=(0,ew.default)("git-merge",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]]);function ds({projectId:e,branch:r,currentTarget:s,onTargetChange:n,onTargetReset:i,onDelete:a}){let[o,l]=(0,$.useState)(null),c=async()=>{null!==o||l((await rv.api.getProjectBranches(e)).filter(e=>e!==r))};return(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)("button",{onClick:e=>e.stopPropagation(),className:"shrink-0 p-0.5 rounded opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 hover:bg-muted transition-all",title:"Workspace menu",children:(0,O.jsx)(lx,{className:"h-3 w-3"})})}),(0,O.jsxs)(a7,{side:"right",align:"start",children:[(0,O.jsxs)(on,{children:[(0,O.jsxs)(oi,{onPointerEnter:c,onFocus:c,children:[(0,O.jsx)(dr,{className:"h-3.5 w-3.5 mr-1.5"}),"Compare against"]}),(0,O.jsxs)(oa,{children:[null===o?(0,O.jsx)(a8,{disabled:!0,children:"Loading…"}):0===o.length?(0,O.jsx)(a8,{disabled:!0,children:"No other branches"}):o.map(e=>(0,O.jsx)(a9,{checked:e===s,onCheckedChange:()=>n(e),children:(0,O.jsx)("span",{className:"font-mono text-xs",children:e})},e)),(0,O.jsx)(os,{}),(0,O.jsx)(a8,{onClick:i,children:(0,O.jsx)("span",{className:"text-xs",children:"Default branch (auto)"})})]})]}),(0,O.jsxs)(a8,{onClick:a,className:"text-destructive focus:text-destructive",children:[(0,O.jsx)(rc,{className:"h-3.5 w-3.5 mr-1.5"}),"Delete worktree"]})]})]})}function dn({status:e}){let r="relative h-[7px] w-[7px] rounded-full shrink-0";return e&&"idle"!==e?"working"===e?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-blue-500"),children:(0,O.jsx)("span",{className:"absolute inset-[-2px] rounded-full bg-blue-500",style:{animation:"status-dot-pulse 1.6s ease-out infinite",opacity:.5}})}):"main-running"===e?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-violet-500"),children:(0,O.jsx)("span",{className:"absolute inset-[-2px] rounded-full bg-violet-500",style:{animation:"status-dot-pulse 1.6s ease-out infinite",opacity:.5}})}):"main-completed"===e?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-emerald-500")}):"stopped"===e?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-amber-500")}):(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-lime-400")}):(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-muted-foreground/40")})}function di({status:e}){let r="relative h-[7px] w-[7px] rounded-full shrink-0";return"running"===e?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-blue-500"),children:(0,O.jsx)("span",{className:"absolute inset-[-2px] rounded-full bg-blue-500",style:{animation:"status-dot-pulse 1.6s ease-out infinite",opacity:.5}})}):"error"===e?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-red-500")}):(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-lime-400")})}function da({schedule:e}){let r="relative h-[7px] w-[7px] rounded-full shrink-0";if(e.running)return(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-blue-500"),children:(0,O.jsx)("span",{className:"absolute inset-[-2px] rounded-full bg-blue-500",style:{animation:"status-dot-pulse 1.6s ease-out infinite",opacity:.5}})});let s=e.last_run;return s&&"skipped"!==s.status?"completed"===s.status?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-emerald-500")}):"failed"===s.status||"timeout"===s.status||"killed"===s.status?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-red-500")}):(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-blue-500")}):(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-muted-foreground/40")})}function dl({children:e,className:r}){return(0,O.jsx)("div",{className:(0,ey.cn)("px-2 pt-2.5 pb-1.5 border-t border-border/50 first:border-t-0",r),children:e})}function dc({children:e,action:r}){return(0,O.jsxs)("div",{className:"flex items-center justify-between px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.06em] text-muted-foreground/80",children:[(0,O.jsx)("span",{children:e}),r]})}function dd({icon:e,label:r,active:s,disabled:n,onClick:i}){return(0,O.jsxs)("button",{onClick:i,disabled:n,className:(0,ey.cn)("relative w-full flex items-center gap-[9px] rounded-md px-2 py-[5px] text-[12.5px] font-normal transition-colors",n&&"text-muted-foreground/40 cursor-not-allowed",!n&&!s&&"text-foreground/75 hover:bg-muted hover:text-foreground",s&&"bg-card text-foreground font-medium shadow-sm"),children:[s&&(0,O.jsx)("span",{className:"absolute -left-2 top-1.5 bottom-1.5 w-[2px] rounded-full bg-primary"}),(0,O.jsx)("span",{className:(0,ey.cn)("shrink-0 flex items-center justify-center",s?"text-foreground":"text-muted-foreground"),children:e}),(0,O.jsx)("span",{className:"truncate text-left",children:r})]})}function du({activeView:e,onViewChange:r,worktrees:s,selectedBranch:n,onBranchChange:i,currentProject:a,onCreateWorktreeOpen:o,onDeleteWorktree:l,mergeStatuses:c,mergeDefaultTarget:d,mergeRepositoryLabel:u,onMergeTargetChange:h,onMergeBadgeClick:f,workspaceStatuses:p,residentSessions:m,selectedSessionId:g,onResidentSessionSelect:x,hasProject:v=!0,projects:_,onSelectProject:y,onCreateProjectOpen:b,schedules:w,selectedScheduleId:S,onScheduleSelect:j,onCreateScheduleOpen:C}){let k=(0,$.useRef)(null);return(0,$.useEffect)(()=>{k.current?.scrollIntoView({block:"nearest"})},[a?.id,_]),(0,O.jsxs)("nav",{className:"w-[220px] border-r border-border bg-sidebar flex flex-col overflow-hidden",children:[(0,O.jsxs)(dl,{children:[(0,O.jsx)(dc,{action:(0,O.jsx)("button",{onClick:b,className:"p-0.5 rounded hover:bg-muted hover:text-foreground transition-colors text-muted-foreground",title:"Create new project",children:(0,O.jsx)(eS,{className:"h-3 w-3"})}),children:"Projects"}),_&&_.length>0?(0,O.jsx)(cb,{delayDuration:300,children:(0,O.jsx)("div",{className:"flex flex-col gap-0.5 max-h-40 overflow-y-auto mt-0.5",children:_.map(s=>{let n=a?.id===s.id,i=n&&("project-info"===e||"project-chat"===e);return(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsxs)("button",{ref:n?k:void 0,onClick:()=>{y?.(s),r("project-info")},className:(0,ey.cn)("relative w-full flex items-center gap-1.5 rounded-md px-2 py-[5px] text-[12.5px] transition-colors min-w-0","hover:bg-muted hover:text-foreground",n?"text-foreground font-medium":"text-foreground/75"),children:[i&&(0,O.jsx)("span",{className:"absolute -left-2 top-1.5 bottom-1.5 w-[2px] rounded-full bg-primary"}),(0,O.jsx)(c9,{name:s.name}),(0,O.jsx)("span",{className:"truncate flex-1 text-left",children:s.name}),n&&(0,O.jsx)(r_,{className:"h-3 w-3 shrink-0 text-muted-foreground ml-auto"})]})}),(0,O.jsx)(cj,{side:"right",children:s.name})]},s.id)})})}):(0,O.jsx)("span",{className:"block px-2 mt-1 text-[11.5px] text-muted-foreground/60",children:"No projects yet"})]}),(0,O.jsxs)(dl,{children:[(0,O.jsx)(dc,{children:"Navigation"}),(0,O.jsx)("div",{className:"flex flex-col gap-0.5 mt-0.5",children:(0,O.jsx)(dd,{icon:(0,O.jsx)(sQ,{className:"h-3.5 w-3.5"}),label:"Tasks",active:"tasks"===e&&v,disabled:!v,onClick:()=>{v&&(i?.(null),r("tasks"))}})})]}),(0,O.jsxs)(dl,{children:[(0,O.jsx)(dc,{action:a?(0,O.jsx)("button",{onClick:C,className:"p-0.5 rounded hover:bg-muted hover:text-foreground transition-colors text-muted-foreground",title:"Create scheduled task",children:(0,O.jsx)(eS,{className:"h-3 w-3"})}):void 0,children:"Schedule"}),a&&w&&w.length>0&&(0,O.jsx)("div",{className:"flex flex-col gap-px",children:w.map(r=>{let s="schedules"===e&&S===r.id;return(0,O.jsxs)("button",{onClick:()=>j?.(r.id),className:(0,ey.cn)("w-full min-w-0 flex items-center gap-2 rounded-[5px] px-2 py-1 text-[11.5px] transition-colors overflow-hidden",!s&&"text-foreground/80 hover:bg-muted",s&&"bg-accent text-accent-foreground font-medium",!r.enabled&&"opacity-50"),children:[(0,O.jsx)(da,{schedule:r}),(0,O.jsx)("span",{className:"truncate text-left flex-1",children:r.name}),"local"!==r.target&&(0,O.jsx)(ry,{className:"h-2.5 w-2.5 shrink-0 text-violet-500","aria-label":"remote"})]},r.id)})}),a&&w&&0===w.length&&(0,O.jsx)("span",{className:"block px-2 mt-1 text-[11.5px] text-muted-foreground/60",children:"No scheduled tasks"})]}),(0,O.jsxs)(dl,{className:"flex-1 overflow-y-auto",children:[(0,O.jsx)(dc,{action:a?(0,O.jsx)("button",{onClick:o,className:"p-0.5 rounded hover:bg-muted hover:text-foreground transition-colors text-muted-foreground",title:"Create new worktree",children:(0,O.jsx)(eS,{className:"h-3 w-3"})}):void 0,children:"Workspace"}),a&&s&&s.length>0&&(0,O.jsx)(O.Fragment,{children:(0,O.jsx)(cb,{delayDuration:300,children:(0,O.jsx)("div",{className:"flex flex-col gap-px",children:s.map(s=>{var o;let v="workspace"===e&&n===s.branch,_=null===s.branch?"":s.branch,y=void 0!==s.currentBranch,b=s.currentBranch??"detached HEAD",w=m?.get(_)??[],S=(o=p?.get(_),w.length>0&&"main-running"!==o&&"main-completed"!==o?"idle":o);return(0,O.jsxs)("div",{className:(0,ey.cn)("min-w-0 rounded-[3px]",v&&"bg-accent"),children:[(0,O.jsxs)("div",{className:"group relative flex items-center min-w-0 gap-0.5 pr-1",children:[(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsxs)("button",{onClick:()=>{i?.(s.branch),r("workspace")},className:(0,ey.cn)("flex-1 min-w-0 flex items-center gap-2 rounded-[3px] pl-2 pr-1 py-1 font-mono text-[11.5px] transition-colors overflow-hidden",!v&&"text-foreground/80 hover:bg-muted",v&&"text-accent-foreground font-medium"),children:[(0,O.jsx)(dn,{status:S}),(0,O.jsxs)("span",{className:"truncate text-left",children:[s.branch??"main",y&&(0,O.jsxs)("span",{className:"text-amber-600 dark:text-amber-400",children:[" → ",b]})]})]})}),(0,O.jsx)(cj,{side:"right",children:y?`Workspace branch: ${s.branch??"main"}; currently checked out: ${b}`:s.branch??"main"})]}),null!==s.branch&&c?.get(s.branch)&&(0,O.jsx)(dt,{info:c.get(s.branch),repositoryLabel:u,onClick:()=>f?.(s.branch)}),null!==s.branch&&a&&(0,O.jsx)(ds,{projectId:a.id,branch:s.branch,currentTarget:c0(c?.get(s.branch))??d??null,onTargetChange:e=>h?.(s.branch,e),onTargetReset:()=>h?.(s.branch,null),onDelete:()=>l?.(s)})]}),w.length>0&&(0,O.jsx)("div",{className:"ml-4 mt-px flex flex-col gap-px",children:w.map(r=>{let s="workspace"===e&&g===r.id;return(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsxs)("button",{onClick:()=>x?.(r),className:(0,ey.cn)("min-w-0 flex items-center gap-1.5 rounded-[3px] py-0.5 pl-1.5 pr-2 font-mono text-[11px] transition-colors",!s&&"text-foreground/70 hover:text-foreground",s&&"text-accent-foreground font-medium"),children:[(0,O.jsx)("span",{className:"shrink-0 text-muted-foreground/70",children:"└"}),(0,O.jsx)(di,{status:r.status}),(0,O.jsx)("span",{className:"truncate text-left",children:r.title})]})}),(0,O.jsx)(cj,{side:"right",children:r.title})]},r.id)})})]},s.branch??"__main__")})})})}),(!s||0===s.length)&&(0,O.jsx)("div",{className:"mt-0.5",children:(0,O.jsx)(dd,{icon:(0,O.jsx)(c6,{className:"h-3.5 w-3.5"}),label:"Workspace",active:"workspace"===e,onClick:()=>r("workspace")})})]}),(0,O.jsx)(dl,{children:(0,O.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,O.jsx)(dd,{icon:(0,O.jsx)(ry,{className:"h-3.5 w-3.5"}),label:"Remote Servers",active:"remote-servers"===e,onClick:()=>r("remote-servers")}),(0,O.jsx)(dd,{icon:(0,O.jsx)(c7,{className:"h-3.5 w-3.5"}),label:"Settings",active:"settings"===e,onClick:()=>r("settings")})]})})]})}function dh({title:e,count:r,description:s,actions:n,className:i}){return(0,O.jsxs)("div",{className:(0,ey.cn)("flex items-center justify-between gap-4 px-5 pt-[14px] pb-3 border-b border-border bg-background flex-shrink-0",i),children:[(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsxs)("h1",{className:"flex items-baseline gap-2.5 m-0 text-[17px] font-semibold tracking-[-0.018em] text-foreground",children:[(0,O.jsx)("span",{className:"truncate",children:e}),void 0!==r&&(0,O.jsx)("span",{className:"font-mono text-[11.5px] font-medium text-muted-foreground/80 tracking-normal",children:r})]}),s&&(0,O.jsx)("p",{className:"text-[11.5px] text-muted-foreground mt-0.5",children:s})]}),n&&(0,O.jsx)("div",{className:"flex items-center gap-2",children:n})]})}function df({children:e,className:r}){return(0,O.jsx)("div",{className:(0,ey.cn)("flex items-center gap-1.5 px-5 py-2 border-b border-border bg-background flex-shrink-0 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",r),children:e})}function dp({active:e,count:r,onClick:s,children:n}){return(0,O.jsxs)("button",{onClick:s,className:(0,ey.cn)("inline-flex items-center gap-1.5 px-2.5 py-[3px] rounded-full text-[11.5px] font-normal transition-colors whitespace-nowrap flex-shrink-0 border",e?"bg-card text-foreground font-medium border-border shadow-sm":"bg-transparent text-muted-foreground border-transparent hover:bg-muted hover:text-foreground"),children:[n,void 0!==r&&(0,O.jsx)("span",{className:(0,ey.cn)("font-mono text-[10.5px] pl-0.5",e?"text-muted-foreground":"text-muted-foreground/70"),children:r})]})}let dm=(0,ew.default)("grip-vertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]),dg=(0,$.createContext)(null);dg.displayName="PanelGroupContext";let dx="data-panel-group-direction",dv="data-panel-group-id",d_="data-resize-handle",dy="data-panel-resize-handle-id",db=$.useLayoutEffect,dw=$["useId".toString()],dS="function"==typeof dw?dw:()=>null,dj=0;function dC(e=null){let r=dS(),s=(0,$.useRef)(e||r||null);return null===s.current&&(s.current=""+dj++),null!=e?e:s.current}function dk({children:e,className:r="",collapsedSize:s,collapsible:n,defaultSize:i,forwardedRef:a,id:o,maxSize:l,minSize:c,onCollapse:d,onExpand:u,onResize:h,order:f,style:p,tagName:m="div",...g}){let x=(0,$.useContext)(dg);if(null===x)throw Error("Panel components must be rendered within a PanelGroup container");let{collapsePanel:v,expandPanel:_,getPanelSize:y,getPanelStyle:b,groupId:w,isPanelCollapsed:S,reevaluatePanelConstraints:j,registerPanel:C,resizePanel:k,unregisterPanel:N}=x,E=dC(o),D=(0,$.useRef)({callbacks:{onCollapse:d,onExpand:u,onResize:h},constraints:{collapsedSize:s,collapsible:n,defaultSize:i,maxSize:l,minSize:c},id:E,idIsFromProps:void 0!==o,order:f});(0,$.useRef)({didLogMissingDefaultSizeWarning:!1}),db(()=>{let{callbacks:e,constraints:r}=D.current,a={...r};D.current.id=E,D.current.idIsFromProps=void 0!==o,D.current.order=f,e.onCollapse=d,e.onExpand=u,e.onResize=h,r.collapsedSize=s,r.collapsible=n,r.defaultSize=i,r.maxSize=l,r.minSize=c,(a.collapsedSize!==r.collapsedSize||a.collapsible!==r.collapsible||a.maxSize!==r.maxSize||a.minSize!==r.minSize)&&j(D.current,a)}),db(()=>{let e=D.current;return C(e),()=>{N(e)}},[f,E,C,N]),(0,$.useImperativeHandle)(a,()=>({collapse:()=>{v(D.current)},expand:e=>{_(D.current,e)},getId:()=>E,getSize:()=>y(D.current),isCollapsed:()=>S(D.current),isExpanded:()=>!S(D.current),resize:e=>{k(D.current,e)}}),[v,_,y,S,E,k]);let R=b(D.current,i);return(0,$.createElement)(m,{...g,children:e,className:r,id:E,style:{...R,...p},[dv]:w,"data-panel":"","data-panel-collapsible":n||void 0,"data-panel-id":E,"data-panel-size":parseFloat(""+R.flexGrow).toFixed(1)})}let dN=(0,$.forwardRef)((e,r)=>(0,$.createElement)(dk,{...e,forwardedRef:r}));dk.displayName="Panel",dN.displayName="forwardRef(Panel)";let dE=null,dD=-1,dR=null;function dA(e,s){var n,i,a;let o=function(e,r){if(r){let e=(r&d$)!=0,s=(r&dW)!=0,n=(r&dH)!=0,i=(r&dU)!=0;if(e)if(n)return"se-resize";else if(i)return"ne-resize";else return"e-resize";if(s)if(n)return"sw-resize";else if(i)return"nw-resize";else return"w-resize";if(n)return"s-resize";else if(i)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}(e,s);dE!==o&&(dE=o,null===dR&&(dR=document.createElement("style"),r&&dR.setAttribute("nonce",r),document.head.appendChild(dR)),dD>=0&&(null==(a=dR.sheet)||a.removeRule(dD)),dD=null!=(n=null==(i=dR.sheet)?void 0:i.insertRule(`*{cursor: ${o} !important;}`))?n:-1)}function dT(e){return"keydown"===e.type}function dM(e){return e.type.startsWith("pointer")}function dF(e){return e.type.startsWith("mouse")}function dP(e){if(dM(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(dF(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}let dI=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function dB(e){let r=e.length;for(;r--;){let s=e[r];if(d6(s,"Missing node"),function(e){var r;let s,n=getComputedStyle(e);return"fixed"===n.position||!!("auto"!==n.zIndex&&("static"!==n.position||"flex"===(s=getComputedStyle(null!=(r=dO(e))?r:e).display)||"inline-flex"===s)||1>+n.opacity||"transform"in n&&"none"!==n.transform||"webkitTransform"in n&&"none"!==n.webkitTransform||"mixBlendMode"in n&&"normal"!==n.mixBlendMode||"filter"in n&&"none"!==n.filter||"webkitFilter"in n&&"none"!==n.webkitFilter||"isolation"in n&&"isolate"===n.isolation||dI.test(n.willChange))||"touch"===n.webkitOverflowScrolling}(s))return s}return null}function dL(e){return e&&Number(getComputedStyle(e).zIndex)||0}function dz(e){let r=[];for(;e;)r.push(e),e=dO(e);return r}function dO(e){let{parentNode:r}=e;return r&&r instanceof ShadowRoot?r.host:r}let d$=1,dW=2,dH=4,dU=8,dq="coarse"===function(){if("function"==typeof matchMedia)return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}(),dK=[],dV=!1,dY=new Map,dG=new Map,dX=new Set;function dJ(e){let{target:r}=e,{x:s,y:n}=dP(e);dV=!0,d1({target:r,x:s,y:n}),d3(),dK.length>0&&(d4("down",e),e.preventDefault(),d0(r)||e.stopImmediatePropagation())}function dZ(e){let{x:r,y:s}=dP(e);if(dV&&0===e.buttons&&(dV=!1,d4("up",e)),!dV){let{target:n}=e;d1({target:n,x:r,y:s})}d4("move",e),d2(),dK.length>0&&e.preventDefault()}function dQ(e){let{target:r}=e,{x:s,y:n}=dP(e);dG.clear(),dV=!1,dK.length>0&&(e.preventDefault(),d0(r)||e.stopImmediatePropagation()),d4("up",e),d1({target:r,x:s,y:n}),d2(),d3()}function d0(e){let r=e;for(;r;){if(r.hasAttribute(d_))return!0;r=r.parentElement}return!1}function d1({target:e,x:r,y:s}){dK.splice(0);let n=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(n=e),dX.forEach(e=>{let{element:i,hitAreaMargins:a}=e,o=i.getBoundingClientRect(),{bottom:l,left:c,right:d,top:u}=o,h=dq?a.coarse:a.fine;if(r>=c-h&&r<=d+h&&s>=u-h&&s<=l+h){if(null!==n&&document.contains(n)&&i!==n&&!i.contains(n)&&!n.contains(i)&&function(e,r){let s;if(e===r)throw Error("Cannot compare node with itself");let n={a:dz(e),b:dz(r)};for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),r=n.b.pop(),s=e;d6(s,"Stacking order can only be calculated for elements with a common ancestor");let i={a:dL(dB(n.a)),b:dL(dB(n.b))};if(i.a===i.b){let e=s.childNodes,r={a:n.a.at(-1),b:n.b.at(-1)},i=e.length;for(;i--;){let s=e[i];if(s===r.a)return 1;if(s===r.b)return -1}}return Math.sign(i.a-i.b)}(n,i)>0){let e=n,r=!1;for(;e;){var f;if(e.contains(i))break;if(f=e.getBoundingClientRect(),f.x<o.x+o.width&&f.x+f.width>o.x&&f.y<o.y+o.height&&f.y+f.height>o.y){r=!0;break}e=e.parentElement}if(r)return}dK.push(e)}})}function d2(){let e=!1,r=!1;dK.forEach(s=>{let{direction:n}=s;"horizontal"===n?e=!0:r=!0});let s=0;dG.forEach(e=>{s|=e}),e&&r?dA("intersection",s):e?dA("horizontal",s):r?dA("vertical",s):null!==dR&&(document.head.removeChild(dR),dE=null,dR=null,dD=-1)}let d5=new AbortController;function d3(){d5.abort();let e={capture:!0,signal:(d5=new AbortController).signal};dX.size&&(dV?(dK.length>0&&dY.forEach((r,s)=>{let{body:n}=s;r>0&&(n.addEventListener("contextmenu",dQ,e),n.addEventListener("pointerleave",dZ,e),n.addEventListener("pointermove",dZ,e))}),window.addEventListener("pointerup",dQ,e),window.addEventListener("pointercancel",dQ,e)):dY.forEach((r,s)=>{let{body:n}=s;r>0&&(n.addEventListener("pointerdown",dJ,e),n.addEventListener("pointermove",dZ,e))}))}function d4(e,r){dX.forEach(s=>{let{setResizeHandlerState:n}=s;n(e,dK.includes(s),r)})}function d6(e,r){if(!e)throw console.error(r),Error(r)}function d7(e,r,s=10){return e.toFixed(s)===r.toFixed(s)?0:e>r?1:-1}function d8(e,r,s=10){return 0===d7(e,r,s)}function d9(e,r,s){return 0===d7(e,r,s)}function ue({panelConstraints:e,panelIndex:r,size:s}){let n=e[r];d6(null!=n,`Panel constraints not found for index ${r}`);let{collapsedSize:i=0,collapsible:a,maxSize:o=100,minSize:l=0}=n;return 0>d7(s,l)&&(s=a&&0>d7(s,(i+l)/2)?i:l),s=parseFloat((s=Math.min(o,s)).toFixed(10))}function ut({delta:e,initialLayout:r,panelConstraints:s,pivotIndices:n,prevLayout:i,trigger:a}){if(d9(e,0))return r;let o=[...r],[l,c]=n;d6(null!=l,"Invalid first pivot index"),d6(null!=c,"Invalid second pivot index");let d=0;if("keyboard"===a){{let n=e<0?c:l,i=s[n];d6(i,`Panel constraints not found for index ${n}`);let{collapsedSize:a=0,collapsible:o,minSize:d=0}=i;if(o){let s=r[n];if(d6(null!=s,`Previous layout not found for panel index ${n}`),d9(s,a)){let r=d-s;d7(r,Math.abs(e))>0&&(e=e<0?0-r:r)}}}{let n=e<0?l:c,i=s[n];d6(i,`No panel constraints found for index ${n}`);let{collapsedSize:a=0,collapsible:o,minSize:d=0}=i;if(o){let s=r[n];if(d6(null!=s,`Previous layout not found for panel index ${n}`),d9(s,d)){let r=s-a;d7(r,Math.abs(e))>0&&(e=e<0?0-r:r)}}}}{let n=e<0?1:-1,i=e<0?c:l,a=0;for(;;){let e=r[i];if(d6(null!=e,`Previous layout not found for panel index ${i}`),a+=ue({panelConstraints:s,panelIndex:i,size:100})-e,(i+=n)<0||i>=s.length)break}let o=Math.min(Math.abs(e),Math.abs(a));e=e<0?0-o:o}{let n=e<0?l:c;for(;n>=0&&n<s.length;){let i=Math.abs(e)-Math.abs(d),a=r[n];d6(null!=a,`Previous layout not found for panel index ${n}`);let l=ue({panelConstraints:s,panelIndex:n,size:a-i});if(!d9(a,l)&&(d+=a-l,o[n]=l,d.toPrecision(3).localeCompare(Math.abs(e).toPrecision(3),void 0,{numeric:!0})>=0))break;e<0?n--:n++}}if(function(e,r,s){if(e.length!==r.length)return!1;for(let s=0;s<e.length;s++)if(!d9(e[s],r[s],void 0))return!1;return!0}(i,o))return i;{let n=e<0?c:l,i=r[n];d6(null!=i,`Previous layout not found for panel index ${n}`);let a=i+d,u=ue({panelConstraints:s,panelIndex:n,size:a});if(o[n]=u,!d9(u,a)){let r=a-u,n=e<0?c:l;for(;n>=0&&n<s.length;){let i=o[n];d6(null!=i,`Previous layout not found for panel index ${n}`);let a=ue({panelConstraints:s,panelIndex:n,size:i+r});if(d9(i,a)||(r-=a-i,o[n]=a),d9(r,0))break;e>0?n--:n++}}}return d9(o.reduce((e,r)=>r+e,0),100)?o:i}function ur(e,r=document){return Array.from(r.querySelectorAll(`[${dy}][data-panel-group-id="${e}"]`))}function us(e,r,s=document){let n=ur(e,s).findIndex(e=>e.getAttribute(dy)===r);return null!=n?n:null}function un(e,r,s){let n=us(e,r,s);return null!=n?[n,n+1]:[-1,-1]}function ui(e,r=document){var s;if(r instanceof HTMLElement&&(null==r||null==(s=r.dataset)?void 0:s.panelGroupId)==e)return r;let n=r.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return n||null}function ua(e,r=document){let s=r.querySelector(`[${dy}="${e}"]`);return s||null}function uo(e,r){if(e.length!==r.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==r[s])return!1;return!0}function ul(e,r){let{x:s,y:n}=dP(r);return"horizontal"===e?s:n}function uc(e,r,s){r.forEach((r,n)=>{let i=e[n];d6(i,`Panel data not found for index ${n}`);let{callbacks:a,constraints:o,id:l}=i,{collapsedSize:c=0,collapsible:d}=o,u=s[l];if(null==u||r!==u){s[l]=r;let{onCollapse:e,onExpand:n,onResize:i}=a;i&&i(r,u),d&&(e||n)&&(n&&(null==u||d8(u,c))&&!d8(r,c)&&n(),e&&(null==u||!d8(u,c))&&d8(r,c)&&e())}})}function ud(e,r){if(e.length!==r.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!=r[s])return!1;return!0}function uu(e){try{if("undefined"!=typeof localStorage)e.getItem=e=>localStorage.getItem(e),e.setItem=(e,r)=>{localStorage.setItem(e,r)};else throw Error("localStorage not supported in this environment")}catch(r){console.error(r),e.getItem=()=>null,e.setItem=()=>{}}}function uh(e){return`react-resizable-panels:${e}`}function uf(e){return e.map(e=>{let{constraints:r,id:s,idIsFromProps:n,order:i}=e;return n?s:i?`${i}:${JSON.stringify(r)}`:JSON.stringify(r)}).sort((e,r)=>e.localeCompare(r)).join(",")}function up(e,r){try{let s=uh(e),n=r.getItem(s);if(n){let e=JSON.parse(n);if("object"==typeof e&&null!=e)return e}}catch(e){}return null}function um(e,r,s,n,i){var a;let o=uh(e),l=uf(r),c=null!=(a=up(e,i))?a:{};c[l]={expandToSizes:Object.fromEntries(s.entries()),layout:n};try{i.setItem(o,JSON.stringify(c))}catch(e){console.error(e)}}function ug({layout:e,panelConstraints:r}){let s=[...e],n=s.reduce((e,r)=>e+r,0);if(s.length!==r.length)throw Error(`Invalid ${r.length} panel layout: ${s.map(e=>`${e}%`).join(", ")}`);if(!d9(n,100)&&s.length>0)for(let e=0;e<r.length;e++){let r=s[e];d6(null!=r,`No layout data found for index ${e}`);let i=100/n*r;s[e]=i}let i=0;for(let e=0;e<r.length;e++){let n=s[e];d6(null!=n,`No layout data found for index ${e}`);let a=ue({panelConstraints:r,panelIndex:e,size:n});n!=a&&(i+=n-a,s[e]=a)}if(!d9(i,0))for(let e=0;e<r.length;e++){let n=s[e];d6(null!=n,`No layout data found for index ${e}`);let a=ue({panelConstraints:r,panelIndex:e,size:n+i});if(n!==a&&(i-=a-n,s[e]=a,d9(i,0)))break}return s}let ux={getItem:e=>(uu(ux),ux.getItem(e)),setItem:(e,r)=>{uu(ux),ux.setItem(e,r)}},uv={};function u_({autoSaveId:e=null,children:r,className:s="",direction:n,forwardedRef:i,id:a=null,onLayout:o=null,keyboardResizeBy:l=null,storage:c=ux,style:d,tagName:u="div",...h}){let f=dC(a),p=(0,$.useRef)(null),[m,g]=(0,$.useState)(null),[x,v]=(0,$.useState)([]),_=function(){let[e,r]=(0,$.useState)(0);return(0,$.useCallback)(()=>r(e=>e+1),[])}(),y=(0,$.useRef)({}),b=(0,$.useRef)(new Map),w=(0,$.useRef)(0),S=(0,$.useRef)({autoSaveId:e,direction:n,dragState:m,id:f,keyboardResizeBy:l,onLayout:o,storage:c}),j=(0,$.useRef)({layout:x,panelDataArray:[],panelDataArrayChanged:!1});(0,$.useRef)({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),(0,$.useImperativeHandle)(i,()=>({getId:()=>S.current.id,getLayout:()=>{let{layout:e}=j.current;return e},setLayout:e=>{let{onLayout:r}=S.current,{layout:s,panelDataArray:n}=j.current,i=ug({layout:e,panelConstraints:n.map(e=>e.constraints)});uo(s,i)||(v(i),j.current.layout=i,r&&r(i),uc(n,i,y.current))}}),[]),db(()=>{S.current.autoSaveId=e,S.current.direction=n,S.current.dragState=m,S.current.id=f,S.current.onLayout=o,S.current.storage=c}),function({committedValuesRef:e,eagerValuesRef:r,groupId:s,layout:n,panelDataArray:i,panelGroupElement:a,setLayout:o}){(0,$.useRef)({didWarnAboutMissingResizeHandle:!1}),db(()=>{if(!a)return;let e=ur(s,a);for(let r=0;r<i.length-1;r++){let{valueMax:s,valueMin:a,valueNow:o}=function({layout:e,panelsArray:r,pivotIndices:s}){let n=0,i=100,a=0,o=0,l=s[0];return d6(null!=l,"No pivot index found"),r.forEach((e,r)=>{let{constraints:s}=e,{maxSize:c=100,minSize:d=0}=s;r===l?(n=d,i=c):(a+=d,o+=c)}),{valueMax:Math.min(i,100-a),valueMin:Math.max(n,100-o),valueNow:e[l]}}({layout:n,panelsArray:i,pivotIndices:[r,r+1]}),l=e[r];if(null==l);else{let e=i[r];d6(e,`No panel data found for index "${r}"`),l.setAttribute("aria-controls",e.id),l.setAttribute("aria-valuemax",""+Math.round(s)),l.setAttribute("aria-valuemin",""+Math.round(a)),l.setAttribute("aria-valuenow",null!=o?""+Math.round(o):"")}}return()=>{e.forEach((e,r)=>{e.removeAttribute("aria-controls"),e.removeAttribute("aria-valuemax"),e.removeAttribute("aria-valuemin"),e.removeAttribute("aria-valuenow")})}},[s,n,i,a]),(0,$.useEffect)(()=>{if(!a)return;let e=r.current;d6(e,"Eager values not found");let{panelDataArray:i}=e;d6(null!=ui(s,a),`No group found for id "${s}"`);let l=ur(s,a);d6(l,`No resize handles found for group id "${s}"`);let c=l.map(e=>{let r=e.getAttribute(dy);d6(r,"Resize handle element has no handle id attribute");let[l,c]=function(e,r,s,n=document){var i,a,o,l;let c=ua(r,n),d=ur(e,n),u=c?d.indexOf(c):-1;return[null!=(i=null==(a=s[u])?void 0:a.id)?i:null,null!=(o=null==(l=s[u+1])?void 0:l.id)?o:null]}(s,r,i,a);if(null==l||null==c)return()=>{};let d=e=>{if(!e.defaultPrevented&&"Enter"===e.key){e.preventDefault();let c=i.findIndex(e=>e.id===l);if(c>=0){let e=i[c];d6(e,`No panel data found for index ${c}`);let l=n[c],{collapsedSize:d=0,collapsible:u,minSize:h=0}=e.constraints;if(null!=l&&u){let e=ut({delta:d9(l,d)?h-d:d-l,initialLayout:n,panelConstraints:i.map(e=>e.constraints),pivotIndices:un(s,r,a),prevLayout:n,trigger:"keyboard"});n!==e&&o(e)}}}};return e.addEventListener("keydown",d),()=>{e.removeEventListener("keydown",d)}});return()=>{c.forEach(e=>e())}},[a,e,r,s,n,i,o])}({committedValuesRef:S,eagerValuesRef:j,groupId:f,layout:x,panelDataArray:j.current.panelDataArray,setLayout:v,panelGroupElement:p.current}),(0,$.useEffect)(()=>{let{panelDataArray:r}=j.current;if(e){if(0===x.length||x.length!==r.length)return;let s=uv[e];null==s&&(s=function(e,r=10){let s=null;return(...n)=>{null!==s&&clearTimeout(s),s=setTimeout(()=>{e(...n)},r)}}(um,100),uv[e]=s),s(e,[...r],new Map(b.current),x,c)}},[e,x,c]),(0,$.useEffect)(()=>{});let C=(0,$.useCallback)(e=>{let{onLayout:r}=S.current,{layout:s,panelDataArray:n}=j.current;if(e.constraints.collapsible){let i=n.map(e=>e.constraints),{collapsedSize:a=0,panelSize:o,pivotIndices:l}=uw(n,e,s);if(d6(null!=o,`Panel size not found for panel "${e.id}"`),!d8(o,a)){b.current.set(e.id,o);let c=ut({delta:ub(n,e)===n.length-1?o-a:a-o,initialLayout:s,panelConstraints:i,pivotIndices:l,prevLayout:s,trigger:"imperative-api"});ud(s,c)||(v(c),j.current.layout=c,r&&r(c),uc(n,c,y.current))}}},[]),k=(0,$.useCallback)((e,r)=>{let{onLayout:s}=S.current,{layout:n,panelDataArray:i}=j.current;if(e.constraints.collapsible){let a=i.map(e=>e.constraints),{collapsedSize:o=0,panelSize:l=0,minSize:c=0,pivotIndices:d}=uw(i,e,n),u=null!=r?r:c;if(d8(l,o)){let r=b.current.get(e.id),o=null!=r&&r>=u?r:u,c=ut({delta:ub(i,e)===i.length-1?l-o:o-l,initialLayout:n,panelConstraints:a,pivotIndices:d,prevLayout:n,trigger:"imperative-api"});ud(n,c)||(v(c),j.current.layout=c,s&&s(c),uc(i,c,y.current))}}},[]),N=(0,$.useCallback)(e=>{let{layout:r,panelDataArray:s}=j.current,{panelSize:n}=uw(s,e,r);return d6(null!=n,`Panel size not found for panel "${e.id}"`),n},[]),E=(0,$.useCallback)((e,r)=>{let{panelDataArray:s}=j.current,n=ub(s,e);return function({defaultSize:e,dragState:r,layout:s,panelData:n,panelIndex:i,precision:a=3}){let o=s[i];return{flexBasis:0,flexGrow:null==o?void 0!=e?e.toPrecision(a):"1":1===n.length?"1":o.toPrecision(a),flexShrink:1,overflow:"hidden",pointerEvents:null!==r?"none":void 0}}({defaultSize:r,dragState:m,layout:x,panelData:s,panelIndex:n})},[m,x]),D=(0,$.useCallback)(e=>{let{layout:r,panelDataArray:s}=j.current,{collapsedSize:n=0,collapsible:i,panelSize:a}=uw(s,e,r);return d6(null!=a,`Panel size not found for panel "${e.id}"`),!0===i&&d8(a,n)},[]),R=(0,$.useCallback)(e=>{let{layout:r,panelDataArray:s}=j.current,{collapsedSize:n=0,collapsible:i,panelSize:a}=uw(s,e,r);return d6(null!=a,`Panel size not found for panel "${e.id}"`),!i||d7(a,n)>0},[]),A=(0,$.useCallback)(e=>{let{panelDataArray:r}=j.current;r.push(e),r.sort((e,r)=>{let s=e.order,n=r.order;return null==s&&null==n?0:null==s?-1:null==n?1:s-n}),j.current.panelDataArrayChanged=!0,_()},[_]);db(()=>{if(j.current.panelDataArrayChanged){j.current.panelDataArrayChanged=!1;let{autoSaveId:s,onLayout:n,storage:i}=S.current,{layout:a,panelDataArray:o}=j.current,l=null;if(s){var e,r;let n=null!=(r=(null!=(e=up(s,i))?e:{})[uf(o)])?r:null;n&&(b.current=new Map(Object.entries(n.expandToSizes)),l=n.layout)}null==l&&(l=function({panelDataArray:e}){let r=Array(e.length),s=e.map(e=>e.constraints),n=0,i=100;for(let a=0;a<e.length;a++){let e=s[a];d6(e,`Panel constraints not found for index ${a}`);let{defaultSize:o}=e;null!=o&&(n++,r[a]=o,i-=o)}for(let a=0;a<e.length;a++){let o=s[a];d6(o,`Panel constraints not found for index ${a}`);let{defaultSize:l}=o;if(null!=l)continue;let c=i/(e.length-n);n++,r[a]=c,i-=c}return r}({panelDataArray:o}));let c=ug({layout:l,panelConstraints:o.map(e=>e.constraints)});uo(a,c)||(v(c),j.current.layout=c,n&&n(c),uc(o,c,y.current))}}),db(()=>{let e=j.current;return()=>{e.layout=[]}},[]);let T=(0,$.useCallback)(e=>{let r=!1,s=p.current;return s&&"rtl"===window.getComputedStyle(s,null).getPropertyValue("direction")&&(r=!0),function(s){var n,i;s.preventDefault();let a=p.current;if(!a)return()=>null;let{direction:o,dragState:l,id:c,keyboardResizeBy:d,onLayout:u}=S.current,{layout:h,panelDataArray:f}=j.current,{initialLayout:m}=null!=l?l:{},g=un(c,e,a),x=function(e,r,s,n,i,a){if(dT(e)){let r="horizontal"===s,n=0;n=e.shiftKey?100:null!=i?i:10;let a=0;switch(e.key){case"ArrowDown":a=r?0:n;break;case"ArrowLeft":a=r?-n:0;break;case"ArrowRight":a=r?n:0;break;case"ArrowUp":a=r?0:-n;break;case"End":a=100;break;case"Home":a=-100}return a}return null==n?0:function(e,r,s,n,i){let a="horizontal"===s,o=ua(r,i);d6(o,`No resize handle element found for id "${r}"`);let l=o.getAttribute(dv);d6(l,"Resize handle element has no group id attribute");let{initialCursorPosition:c}=n,d=ul(s,e),u=ui(l,i);d6(u,`No group element found for id "${l}"`);let h=u.getBoundingClientRect();return(d-c)/(a?h.width:h.height)*100}(e,r,s,n,a)}(s,e,o,l,d,a),_="horizontal"===o;_&&r&&(x=-x);let b=ut({delta:x,initialLayout:null!=m?m:h,panelConstraints:f.map(e=>e.constraints),pivotIndices:g,prevLayout:h,trigger:dT(s)?"keyboard":"mouse-or-touch"}),C=!ud(h,b);(dM(s)||dF(s))&&w.current!=x&&((w.current=x,C||0===x)?dG.set(e,0):_?(n=x<0?d$:dW,dG.set(e,n)):(i=x<0?dH:dU,dG.set(e,i))),C&&(v(b),j.current.layout=b,u&&u(b),uc(f,b,y.current))}},[]),M=(0,$.useCallback)((e,r)=>{let{onLayout:s}=S.current,{layout:n,panelDataArray:i}=j.current,a=i.map(e=>e.constraints),{panelSize:o,pivotIndices:l}=uw(i,e,n);d6(null!=o,`Panel size not found for panel "${e.id}"`);let c=ut({delta:ub(i,e)===i.length-1?o-r:r-o,initialLayout:n,panelConstraints:a,pivotIndices:l,prevLayout:n,trigger:"imperative-api"});ud(n,c)||(v(c),j.current.layout=c,s&&s(c),uc(i,c,y.current))},[]),F=(0,$.useCallback)((e,r)=>{let{layout:s,panelDataArray:n}=j.current,{collapsedSize:i=0,collapsible:a}=r,{collapsedSize:o=0,collapsible:l,maxSize:c=100,minSize:d=0}=e.constraints,{panelSize:u}=uw(n,e,s);null!=u&&(a&&l&&d8(u,i)?d8(i,o)||M(e,o):u<d?M(e,d):u>c&&M(e,c))},[M]),P=(0,$.useCallback)((e,r)=>{let{direction:s}=S.current,{layout:n}=j.current;if(!p.current)return;let i=ua(e,p.current);d6(i,`Drag handle element not found for id "${e}"`);let a=ul(s,r);g({dragHandleId:e,dragHandleRect:i.getBoundingClientRect(),initialCursorPosition:a,initialLayout:n})},[]),I=(0,$.useCallback)(()=>{g(null)},[]),B=(0,$.useCallback)(e=>{let{panelDataArray:r}=j.current,s=ub(r,e);s>=0&&(r.splice(s,1),delete y.current[e.id],j.current.panelDataArrayChanged=!0,_())},[_]),L=(0,$.useMemo)(()=>({collapsePanel:C,direction:n,dragState:m,expandPanel:k,getPanelSize:N,getPanelStyle:E,groupId:f,isPanelCollapsed:D,isPanelExpanded:R,reevaluatePanelConstraints:F,registerPanel:A,registerResizeHandle:T,resizePanel:M,startDragging:P,stopDragging:I,unregisterPanel:B,panelGroupElement:p.current}),[C,m,n,k,N,E,f,D,R,F,A,T,M,P,I,B]);return(0,$.createElement)(dg.Provider,{value:L},(0,$.createElement)(u,{...h,children:r,className:s,id:a,ref:p,style:{display:"flex",flexDirection:"horizontal"===n?"row":"column",height:"100%",overflow:"hidden",width:"100%",...d},"data-panel-group":"",[dx]:n,[dv]:f}))}let uy=(0,$.forwardRef)((e,r)=>(0,$.createElement)(u_,{...e,forwardedRef:r}));function ub(e,r){return e.findIndex(e=>e===r||e.id===r.id)}function uw(e,r,s){let n=ub(e,r),i=n===e.length-1,a=s[n];return{...r.constraints,panelSize:a,pivotIndices:i?[n-1,n]:[n,n+1]}}function uS({children:e=null,className:r="",disabled:s=!1,hitAreaMargins:n,id:i,onBlur:a,onClick:o,onDragging:l,onFocus:c,onPointerDown:d,onPointerUp:u,style:h={},tabIndex:f=0,tagName:p="div",...m}){var g,x;let v=(0,$.useRef)(null),_=(0,$.useRef)({onClick:o,onDragging:l,onPointerDown:d,onPointerUp:u});(0,$.useEffect)(()=>{_.current.onClick=o,_.current.onDragging=l,_.current.onPointerDown=d,_.current.onPointerUp=u});let y=(0,$.useContext)(dg);if(null===y)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");let{direction:b,groupId:w,registerResizeHandle:S,startDragging:j,stopDragging:C,panelGroupElement:k}=y,N=dC(i),[E,D]=(0,$.useState)("inactive"),[R,A]=(0,$.useState)(!1),[T,M]=(0,$.useState)(null),F=(0,$.useRef)({state:E});db(()=>{F.current.state=E}),(0,$.useEffect)(()=>{if(s)M(null);else{let e=S(N);M(()=>e)}},[s,N,S]);let P=null!=(g=null==n?void 0:n.coarse)?g:15,I=null!=(x=null==n?void 0:n.fine)?x:5;return(0,$.useEffect)(()=>{if(s||null==T)return;let e=v.current;d6(e,"Element ref not attached");let r=!1;return function(e,r,s,n,i){var a;let{ownerDocument:o}=r,l={direction:s,element:r,hitAreaMargins:n,setResizeHandlerState:i},c=null!=(a=dY.get(o))?a:0;return dY.set(o,c+1),dX.add(l),d3(),function(){var r;dG.delete(e),dX.delete(l);let s=null!=(r=dY.get(o))?r:1;if(dY.set(o,s-1),d3(),1===s&&dY.delete(o),dK.includes(l)){let e=dK.indexOf(l);e>=0&&dK.splice(e,1),d2(),i("up",!0,null)}}}(N,e,b,{coarse:P,fine:I},(e,s,n)=>{if(!s)return void D("inactive");switch(e){case"down":{D("drag"),r=!1,d6(n,'Expected event to be defined for "down" action'),j(N,n);let{onDragging:e,onPointerDown:s}=_.current;null==e||e(!0),null==s||s();break}case"move":{let{state:e}=F.current;r=!0,"drag"!==e&&D("hover"),d6(n,'Expected event to be defined for "move" action'),T(n);break}case"up":{D("hover"),C();let{onClick:e,onDragging:s,onPointerUp:n}=_.current;null==s||s(!1),null==n||n(),r||null==e||e()}}})},[P,b,s,I,S,N,T,j,C]),!function({disabled:e,handleId:r,resizeHandler:s,panelGroupElement:n}){(0,$.useEffect)(()=>{if(e||null==s||null==n)return;let i=ua(r,n);if(null==i)return;let a=e=>{if(!e.defaultPrevented)switch(e.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":e.preventDefault(),s(e);break;case"F6":{e.preventDefault();let s=i.getAttribute(dv);d6(s,`No group element found for id "${s}"`);let a=ur(s,n),o=us(s,r,n);d6(null!==o,`No resize element found for id "${r}"`);let l=e.shiftKey?o>0?o-1:a.length-1:o+1<a.length?o+1:0;a[l].focus()}}};return i.addEventListener("keydown",a),()=>{i.removeEventListener("keydown",a)}},[n,e,r,s])}({disabled:s,handleId:N,resizeHandler:T,panelGroupElement:k}),(0,$.createElement)(p,{...m,children:e,className:r,id:i,onBlur:()=>{A(!1),null==a||a()},onFocus:()=>{A(!0),null==c||c()},ref:v,role:"separator",style:{touchAction:"none",userSelect:"none",...h},tabIndex:f,[dx]:b,[dv]:w,[d_]:"","data-resize-handle-active":"drag"===E?"pointer":R?"keyboard":void 0,"data-panel-resize-handle-enabled":!s,[dy]:N,"data-resize-handle-state":E})}u_.displayName="PanelGroup",uy.displayName="forwardRef(PanelGroup)",uS.displayName="PanelResizeHandle";let uj=({className:e,...r})=>(0,O.jsx)(uy,{className:(0,ey.cn)("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...r}),uC=({withHandle:e,className:r,...s})=>(0,O.jsx)(uS,{className:(0,ey.cn)("relative flex w-px items-center justify-center bg-border/60 after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-[''] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:inset-x-0 data-[panel-group-direction=vertical]:after:-top-1 data-[panel-group-direction=vertical]:after:-bottom-1 data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:right-0 [&[data-resize-handle-active]]:bg-ring",r),...s,children:e&&(0,O.jsx)("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:(0,O.jsx)(dm,{className:"h-2.5 w-2.5"})})});function uk({className:e,...r}){return(0,O.jsx)("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:(0,O.jsx)("table",{"data-slot":"table",className:(0,ey.cn)("w-full caption-bottom text-sm",e),...r})})}function uN({className:e,...r}){return(0,O.jsx)("thead",{"data-slot":"table-header",className:(0,ey.cn)("[&_tr]:border-b",e),...r})}function uE({className:e,...r}){return(0,O.jsx)("tbody",{"data-slot":"table-body",className:(0,ey.cn)("[&_tr:last-child]:border-0",e),...r})}function uD({className:e,...r}){return(0,O.jsx)("tr",{"data-slot":"table-row",className:(0,ey.cn)("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",e),...r})}function uR({className:e,...r}){return(0,O.jsx)("th",{"data-slot":"table-head",className:(0,ey.cn)("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...r})}function uA({className:e,...r}){return(0,O.jsx)("td",{"data-slot":"table-cell",className:(0,ey.cn)("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...r})}var uT=[" ","Enter","ArrowUp","ArrowDown"],uM=[" ","Enter"],uF="Select",[uP,uI,uB]=rb(uF),[uL,uz]=q(uF,[uB,iw]),uO=iw(),[u$,uW]=uL(uF),[uH,uU]=uL(uF),uq=e=>{let{__scopeSelect:r,children:s,open:n,defaultOpen:i,onOpenChange:a,value:o,defaultValue:l,onValueChange:c,dir:d,name:u,autoComplete:h,disabled:f,required:p,form:m}=e,g=uO(r),[x,v]=$.useState(null),[_,y]=$.useState(null),[b,w]=$.useState(!1),S=rk(d),[j,C]=G({prop:n,defaultProp:i??!1,onChange:a,caller:uF}),[k,N]=G({prop:o,defaultProp:l,onChange:c,caller:uF}),E=$.useRef(null),D=!x||m||!!x.closest("form"),[R,A]=$.useState(new Set),T=Array.from(R).map(e=>e.props.value).join(";");return(0,O.jsx)(iC,{...g,children:(0,O.jsxs)(u$,{required:p,scope:r,trigger:x,onTriggerChange:v,valueNode:_,onValueNodeChange:y,valueNodeHasChildren:b,onValueNodeHasChildrenChange:w,contentId:ek(),value:k,onValueChange:N,open:j,onOpenChange:C,dir:S,triggerPointerDownPosRef:E,disabled:f,children:[(0,O.jsx)(uP.Provider,{scope:r,children:(0,O.jsx)(uH,{scope:e.__scopeSelect,onNativeOptionAdd:$.useCallback(e=>{A(r=>new Set(r).add(e))},[]),onNativeOptionRemove:$.useCallback(e=>{A(r=>{let s=new Set(r);return s.delete(e),s})},[]),children:s})}),D?(0,O.jsxs)(hv,{"aria-hidden":!0,required:p,tabIndex:-1,name:u,autoComplete:h,value:k,onChange:e=>N(e.target.value),disabled:f,form:m,children:[void 0===k?(0,O.jsx)("option",{value:""}):null,Array.from(R)]},T):null]})})};uq.displayName=uF;var uK="SelectTrigger",uV=$.forwardRef((e,r)=>{let{__scopeSelect:s,disabled:n=!1,...i}=e,a=uO(s),o=uW(uK,s),l=o.disabled||n,c=(0,U.useComposedRefs)(r,o.onTriggerChange),d=uI(s),u=$.useRef("touch"),[h,f,p]=hy(e=>{let r=d().filter(e=>!e.disabled),s=r.find(e=>e.value===o.value),n=hb(r,e,s);void 0!==n&&o.onValueChange(n.value)}),m=e=>{l||(o.onOpenChange(!0),p()),e&&(o.triggerPointerDownPosRef.current={x:Math.round(e.pageX),y:Math.round(e.pageY)})};return(0,O.jsx)(iN,{asChild:!0,...a,children:(0,O.jsx)(er.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":h_(o.value)?"":void 0,...i,ref:c,onClick:K(i.onClick,e=>{e.currentTarget.focus(),"mouse"!==u.current&&m(e)}),onPointerDown:K(i.onPointerDown,e=>{u.current=e.pointerType;let r=e.target;r.hasPointerCapture(e.pointerId)&&r.releasePointerCapture(e.pointerId),0===e.button&&!1===e.ctrlKey&&"mouse"===e.pointerType&&(m(e),e.preventDefault())}),onKeyDown:K(i.onKeyDown,e=>{let r=""!==h.current;e.ctrlKey||e.altKey||e.metaKey||1!==e.key.length||f(e.key),(!r||" "!==e.key)&&uT.includes(e.key)&&(m(),e.preventDefault())})})})});uV.displayName=uK;var uY="SelectValue",uG=$.forwardRef((e,r)=>{let{__scopeSelect:s,className:n,style:i,children:a,placeholder:o="",...l}=e,c=uW(uY,s),{onValueNodeHasChildrenChange:d}=c,u=void 0!==a,h=(0,U.useComposedRefs)(r,c.onValueNodeChange);return V(()=>{d(u)},[d,u]),(0,O.jsx)(er.span,{...l,ref:h,style:{pointerEvents:"none"},children:h_(c.value)?(0,O.jsx)(O.Fragment,{children:o}):a})});uG.displayName=uY;var uX=$.forwardRef((e,r)=>{let{__scopeSelect:s,children:n,...i}=e;return(0,O.jsx)(er.span,{"aria-hidden":!0,...i,ref:r,children:n||"▼"})});uX.displayName="SelectIcon";var uJ=e=>(0,O.jsx)(eW,{asChild:!0,...e});uJ.displayName="SelectPortal";var uZ="SelectContent",uQ=$.forwardRef((e,r)=>{let s=uW(uZ,e.__scopeSelect),[n,i]=$.useState();return(V(()=>{i(new DocumentFragment)},[]),s.open)?(0,O.jsx)(u5,{...e,ref:r}):n?ee.createPortal((0,O.jsx)(u0,{scope:e.__scopeSelect,children:(0,O.jsx)(uP.Slot,{scope:e.__scopeSelect,children:(0,O.jsx)("div",{children:e.children})})}),n):null});uQ.displayName=uZ;var[u0,u1]=uL(uZ),u2=(0,et.createSlot)("SelectContent.RemoveScroll"),u5=$.forwardRef((e,r)=>{let{__scopeSelect:s,position:n="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:a,onPointerDownOutside:o,side:l,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:f,collisionPadding:p,sticky:m,hideWhenDetached:g,avoidCollisions:x,...v}=e,_=uW(uZ,s),[y,b]=$.useState(null),[w,S]=$.useState(null),j=(0,U.useComposedRefs)(r,e=>b(e)),[C,k]=$.useState(null),[N,E]=$.useState(null),D=uI(s),[R,A]=$.useState(!1),T=$.useRef(!1);$.useEffect(()=>{if(y)return tN(y)},[y]),eU();let M=$.useCallback(e=>{let[r,...s]=D().map(e=>e.ref.current),[n]=s.slice(-1),i=document.activeElement;for(let s of e)if(s===i||(s?.scrollIntoView({block:"nearest"}),s===r&&w&&(w.scrollTop=0),s===n&&w&&(w.scrollTop=w.scrollHeight),s?.focus(),document.activeElement!==i))return},[D,w]),F=$.useCallback(()=>M([C,y]),[M,C,y]);$.useEffect(()=>{R&&F()},[R,F]);let{onOpenChange:P,triggerPointerDownPosRef:I}=_;$.useEffect(()=>{if(y){let e={x:0,y:0},r=r=>{e={x:Math.abs(Math.round(r.pageX)-(I.current?.x??0)),y:Math.abs(Math.round(r.pageY)-(I.current?.y??0))}},s=s=>{e.x<=10&&e.y<=10?s.preventDefault():y.contains(s.target)||P(!1),document.removeEventListener("pointermove",r),I.current=null};return null!==I.current&&(document.addEventListener("pointermove",r),document.addEventListener("pointerup",s,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",r),document.removeEventListener("pointerup",s,{capture:!0})}}},[y,P,I]),$.useEffect(()=>{let e=()=>P(!1);return window.addEventListener("blur",e),window.addEventListener("resize",e),()=>{window.removeEventListener("blur",e),window.removeEventListener("resize",e)}},[P]);let[B,L]=hy(e=>{let r=D().filter(e=>!e.disabled),s=r.find(e=>e.ref.current===document.activeElement),n=hb(r,e,s);n&&setTimeout(()=>n.ref.current.focus())}),z=$.useCallback((e,r,s)=>{let n=!T.current&&!s;(void 0!==_.value&&_.value===r||n)&&(k(e),n&&(T.current=!0))},[_.value]),W=$.useCallback(()=>y?.focus(),[y]),H=$.useCallback((e,r,s)=>{let n=!T.current&&!s;(void 0!==_.value&&_.value===r||n)&&E(e)},[_.value]),q="popper"===n?u4:u3,V=q===u4?{side:l,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:f,collisionPadding:p,sticky:m,hideWhenDetached:g,avoidCollisions:x}:{};return(0,O.jsx)(u0,{scope:s,content:y,viewport:w,onViewportChange:S,itemRefCallback:z,selectedItem:C,onItemLeave:W,itemTextRefCallback:H,focusSelectedItem:F,selectedItemText:N,position:n,isPositioned:R,searchRef:B,children:(0,O.jsx)(ty,{as:u2,allowPinchZoom:!0,children:(0,O.jsx)(eI,{asChild:!0,trapped:_.open,onMountAutoFocus:e=>{e.preventDefault()},onUnmountAutoFocus:K(i,e=>{_.trigger?.focus({preventScroll:!0}),e.preventDefault()}),children:(0,O.jsx)(eR,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:e=>e.preventDefault(),onDismiss:()=>_.onOpenChange(!1),children:(0,O.jsx)(q,{role:"listbox",id:_.contentId,"data-state":_.open?"open":"closed",dir:_.dir,onContextMenu:e=>e.preventDefault(),...v,...V,onPlaced:()=>A(!0),ref:j,style:{display:"flex",flexDirection:"column",outline:"none",...v.style},onKeyDown:K(v.onKeyDown,e=>{let r=e.ctrlKey||e.altKey||e.metaKey;if("Tab"===e.key&&e.preventDefault(),r||1!==e.key.length||L(e.key),["ArrowUp","ArrowDown","Home","End"].includes(e.key)){let r=D().filter(e=>!e.disabled).map(e=>e.ref.current);if(["ArrowUp","End"].includes(e.key)&&(r=r.slice().reverse()),["ArrowUp","ArrowDown"].includes(e.key)){let s=e.target,n=r.indexOf(s);r=r.slice(n+1)}setTimeout(()=>M(r)),e.preventDefault()}})})})})})})});u5.displayName="SelectContentImpl";var u3=$.forwardRef((e,r)=>{let{__scopeSelect:s,onPlaced:n,...i}=e,a=uW(uZ,s),o=u1(uZ,s),[l,c]=$.useState(null),[d,u]=$.useState(null),h=(0,U.useComposedRefs)(r,e=>u(e)),f=uI(s),p=$.useRef(!1),m=$.useRef(!0),{viewport:g,selectedItem:x,selectedItemText:v,focusSelectedItem:_}=o,y=$.useCallback(()=>{if(a.trigger&&a.valueNode&&l&&d&&g&&x&&v){let e=a.trigger.getBoundingClientRect(),r=d.getBoundingClientRect(),s=a.valueNode.getBoundingClientRect(),i=v.getBoundingClientRect();if("rtl"!==a.dir){let n=i.left-r.left,a=s.left-n,o=e.left-a,c=e.width+o,d=Math.max(c,r.width),u=oh(a,[10,Math.max(10,window.innerWidth-10-d)]);l.style.minWidth=c+"px",l.style.left=u+"px"}else{let n=r.right-i.right,a=window.innerWidth-s.right-n,o=window.innerWidth-e.right-a,c=e.width+o,d=Math.max(c,r.width),u=oh(a,[10,Math.max(10,window.innerWidth-10-d)]);l.style.minWidth=c+"px",l.style.right=u+"px"}let o=f(),c=window.innerHeight-20,u=g.scrollHeight,h=window.getComputedStyle(d),m=parseInt(h.borderTopWidth,10),_=parseInt(h.paddingTop,10),y=parseInt(h.borderBottomWidth,10),b=m+_+u+parseInt(h.paddingBottom,10)+y,w=Math.min(5*x.offsetHeight,b),S=window.getComputedStyle(g),j=parseInt(S.paddingTop,10),C=parseInt(S.paddingBottom,10),k=e.top+e.height/2-10,N=x.offsetHeight/2,E=m+_+(x.offsetTop+N);if(E<=k){let e=o.length>0&&x===o[o.length-1].ref.current;l.style.bottom="0px";let r=Math.max(c-k,N+(e?C:0)+(d.clientHeight-g.offsetTop-g.offsetHeight)+y);l.style.height=E+r+"px"}else{let e=o.length>0&&x===o[0].ref.current;l.style.top="0px";let r=Math.max(k,m+g.offsetTop+(e?j:0)+N);l.style.height=r+(b-E)+"px",g.scrollTop=E-k+g.offsetTop}l.style.margin="10px 0",l.style.minHeight=w+"px",l.style.maxHeight=c+"px",n?.(),requestAnimationFrame(()=>p.current=!0)}},[f,a.trigger,a.valueNode,l,d,g,x,v,a.dir,n]);V(()=>y(),[y]);let[b,w]=$.useState();V(()=>{d&&w(window.getComputedStyle(d).zIndex)},[d]);let S=$.useCallback(e=>{e&&!0===m.current&&(y(),_?.(),m.current=!1)},[y,_]);return(0,O.jsx)(u6,{scope:s,contentWrapper:l,shouldExpandOnScrollRef:p,onScrollButtonChange:S,children:(0,O.jsx)("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:b},children:(0,O.jsx)(er.div,{...i,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});u3.displayName="SelectItemAlignedPosition";var u4=$.forwardRef((e,r)=>{let{__scopeSelect:s,align:n="start",collisionPadding:i=10,...a}=e,o=uO(s);return(0,O.jsx)(iA,{...o,...a,ref:r,align:n,collisionPadding:i,style:{boxSizing:"border-box",...a.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});u4.displayName="SelectPopperPosition";var[u6,u7]=uL(uZ,{}),u8="SelectViewport",u9=$.forwardRef((e,r)=>{let{__scopeSelect:s,nonce:n,...i}=e,a=u1(u8,s),o=u7(u8,s),l=(0,U.useComposedRefs)(r,a.onViewportChange),c=$.useRef(0);return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:n}),(0,O.jsx)(uP.Slot,{scope:s,children:(0,O.jsx)(er.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:K(i.onScroll,e=>{let r=e.currentTarget,{contentWrapper:s,shouldExpandOnScrollRef:n}=o;if(n?.current&&s){let e=Math.abs(c.current-r.scrollTop);if(e>0){let n=window.innerHeight-20,i=Math.max(parseFloat(s.style.minHeight),parseFloat(s.style.height));if(i<n){let a=i+e,o=Math.min(n,a),l=a-o;s.style.height=o+"px","0px"===s.style.bottom&&(r.scrollTop=l>0?l:0,s.style.justifyContent="flex-end")}}}c.current=r.scrollTop})})})]})});u9.displayName=u8;var he="SelectGroup",[ht,hr]=uL(he);$.forwardRef((e,r)=>{let{__scopeSelect:s,...n}=e,i=ek();return(0,O.jsx)(ht,{scope:s,id:i,children:(0,O.jsx)(er.div,{role:"group","aria-labelledby":i,...n,ref:r})})}).displayName=he;var hs="SelectLabel";$.forwardRef((e,r)=>{let{__scopeSelect:s,...n}=e,i=hr(hs,s);return(0,O.jsx)(er.div,{id:i.id,...n,ref:r})}).displayName=hs;var hn="SelectItem",[hi,ha]=uL(hn),ho=$.forwardRef((e,r)=>{let{__scopeSelect:s,value:n,disabled:i=!1,textValue:a,...o}=e,l=uW(hn,s),c=u1(hn,s),d=l.value===n,[u,h]=$.useState(a??""),[f,p]=$.useState(!1),m=(0,U.useComposedRefs)(r,e=>c.itemRefCallback?.(e,n,i)),g=ek(),x=$.useRef("touch"),v=()=>{i||(l.onValueChange(n),l.onOpenChange(!1))};if(""===n)throw Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return(0,O.jsx)(hi,{scope:s,value:n,disabled:i,textId:g,isSelected:d,onItemTextChange:$.useCallback(e=>{h(r=>r||(e?.textContent??"").trim())},[]),children:(0,O.jsx)(uP.ItemSlot,{scope:s,value:n,disabled:i,textValue:u,children:(0,O.jsx)(er.div,{role:"option","aria-labelledby":g,"data-highlighted":f?"":void 0,"aria-selected":d&&f,"data-state":d?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...o,ref:m,onFocus:K(o.onFocus,()=>p(!0)),onBlur:K(o.onBlur,()=>p(!1)),onClick:K(o.onClick,()=>{"mouse"!==x.current&&v()}),onPointerUp:K(o.onPointerUp,()=>{"mouse"===x.current&&v()}),onPointerDown:K(o.onPointerDown,e=>{x.current=e.pointerType}),onPointerMove:K(o.onPointerMove,e=>{x.current=e.pointerType,i?c.onItemLeave?.():"mouse"===x.current&&e.currentTarget.focus({preventScroll:!0})}),onPointerLeave:K(o.onPointerLeave,e=>{e.currentTarget===document.activeElement&&c.onItemLeave?.()}),onKeyDown:K(o.onKeyDown,e=>{(c.searchRef?.current===""||" "!==e.key)&&(uM.includes(e.key)&&v()," "===e.key&&e.preventDefault())})})})})});ho.displayName=hn;var hl="SelectItemText",hc=$.forwardRef((e,r)=>{let{__scopeSelect:s,className:n,style:i,...a}=e,o=uW(hl,s),l=u1(hl,s),c=ha(hl,s),d=uU(hl,s),[u,h]=$.useState(null),f=(0,U.useComposedRefs)(r,e=>h(e),c.onItemTextChange,e=>l.itemTextRefCallback?.(e,c.value,c.disabled)),p=u?.textContent,m=$.useMemo(()=>(0,O.jsx)("option",{value:c.value,disabled:c.disabled,children:p},c.value),[c.disabled,c.value,p]),{onNativeOptionAdd:g,onNativeOptionRemove:x}=d;return V(()=>(g(m),()=>x(m)),[g,x,m]),(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(er.span,{id:c.textId,...a,ref:f}),c.isSelected&&o.valueNode&&!o.valueNodeHasChildren?ee.createPortal(a.children,o.valueNode):null]})});hc.displayName=hl;var hd="SelectItemIndicator",hu=$.forwardRef((e,r)=>{let{__scopeSelect:s,...n}=e;return ha(hd,s).isSelected?(0,O.jsx)(er.span,{"aria-hidden":!0,...n,ref:r}):null});hu.displayName=hd;var hh="SelectScrollUpButton",hf=$.forwardRef((e,r)=>{let s=u1(hh,e.__scopeSelect),n=u7(hh,e.__scopeSelect),[i,a]=$.useState(!1),o=(0,U.useComposedRefs)(r,n.onScrollButtonChange);return V(()=>{if(s.viewport&&s.isPositioned){let e=function(){a(r.scrollTop>0)},r=s.viewport;return e(),r.addEventListener("scroll",e),()=>r.removeEventListener("scroll",e)}},[s.viewport,s.isPositioned]),i?(0,O.jsx)(hg,{...e,ref:o,onAutoScroll:()=>{let{viewport:e,selectedItem:r}=s;e&&r&&(e.scrollTop=e.scrollTop-r.offsetHeight)}}):null});hf.displayName=hh;var hp="SelectScrollDownButton",hm=$.forwardRef((e,r)=>{let s=u1(hp,e.__scopeSelect),n=u7(hp,e.__scopeSelect),[i,a]=$.useState(!1),o=(0,U.useComposedRefs)(r,n.onScrollButtonChange);return V(()=>{if(s.viewport&&s.isPositioned){let e=function(){let e=r.scrollHeight-r.clientHeight;a(Math.ceil(r.scrollTop)<e)},r=s.viewport;return e(),r.addEventListener("scroll",e),()=>r.removeEventListener("scroll",e)}},[s.viewport,s.isPositioned]),i?(0,O.jsx)(hg,{...e,ref:o,onAutoScroll:()=>{let{viewport:e,selectedItem:r}=s;e&&r&&(e.scrollTop=e.scrollTop+r.offsetHeight)}}):null});hm.displayName=hp;var hg=$.forwardRef((e,r)=>{let{__scopeSelect:s,onAutoScroll:n,...i}=e,a=u1("SelectScrollButton",s),o=$.useRef(null),l=uI(s),c=$.useCallback(()=>{null!==o.current&&(window.clearInterval(o.current),o.current=null)},[]);return $.useEffect(()=>()=>c(),[c]),V(()=>{let e=l().find(e=>e.ref.current===document.activeElement);e?.ref.current?.scrollIntoView({block:"nearest"})},[l]),(0,O.jsx)(er.div,{"aria-hidden":!0,...i,ref:r,style:{flexShrink:0,...i.style},onPointerDown:K(i.onPointerDown,()=>{null===o.current&&(o.current=window.setInterval(n,50))}),onPointerMove:K(i.onPointerMove,()=>{a.onItemLeave?.(),null===o.current&&(o.current=window.setInterval(n,50))}),onPointerLeave:K(i.onPointerLeave,()=>{c()})})});$.forwardRef((e,r)=>{let{__scopeSelect:s,...n}=e;return(0,O.jsx)(er.div,{"aria-hidden":!0,...n,ref:r})}).displayName="SelectSeparator";var hx="SelectArrow";$.forwardRef((e,r)=>{let{__scopeSelect:s,...n}=e,i=uO(s),a=uW(hx,s),o=u1(hx,s);return a.open&&"popper"===o.position?(0,O.jsx)(iF,{...i,...n,ref:r}):null}).displayName=hx;var hv=$.forwardRef(({__scopeSelect:e,value:r,...s},n)=>{let i=$.useRef(null),a=(0,U.useComposedRefs)(n,i),o=X(r);return $.useEffect(()=>{let e=i.current;if(!e)return;let s=Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype,"value").set;if(o!==r&&s){let n=new Event("change",{bubbles:!0});s.call(e,r),e.dispatchEvent(n)}},[o,r]),(0,O.jsx)(er.select,{...s,style:{...l1,...s.style},ref:a,defaultValue:r})});function h_(e){return""===e||void 0===e}function hy(e){let r=eN(e),s=$.useRef(""),n=$.useRef(0),i=$.useCallback(e=>{let i=s.current+e;r(i),function e(r){s.current=r,window.clearTimeout(n.current),""!==r&&(n.current=window.setTimeout(()=>e(""),1e3))}(i)},[r]),a=$.useCallback(()=>{s.current="",window.clearTimeout(n.current)},[]);return $.useEffect(()=>()=>window.clearTimeout(n.current),[]),[s,i,a]}function hb(e,r,s){var n,i;let a=r.length>1&&Array.from(r).every(e=>e===r[0])?r[0]:r,o=s?e.indexOf(s):-1,l=(n=e,i=Math.max(o,0),n.map((e,r)=>n[(i+r)%n.length]));1===a.length&&(l=l.filter(e=>e!==s));let c=l.find(e=>e.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==s?c:void 0}hv.displayName="SelectBubbleInput";var H=H;function hw({...e}){return(0,O.jsx)(uq,{"data-slot":"select",...e})}function hS({...e}){return(0,O.jsx)(uG,{"data-slot":"select-value",...e})}function hj({className:e,size:r="default",children:s,...n}){return(0,O.jsxs)(uV,{"data-slot":"select-trigger","data-size":r,className:(0,ey.cn)("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[s,(0,O.jsx)(uX,{asChild:!0,children:(0,O.jsx)(ns,{className:"size-4 opacity-50"})})]})}function hC({className:e,children:r,position:s="item-aligned",align:n="center",...i}){return(0,O.jsx)(uJ,{children:(0,O.jsxs)(uQ,{"data-slot":"select-content",className:(0,ey.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:s,align:n,...i,children:[(0,O.jsx)(hN,{}),(0,O.jsx)(u9,{className:(0,ey.cn)("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:r}),(0,O.jsx)(hE,{})]})})}function hk({className:e,children:r,...s}){return(0,O.jsxs)(ho,{"data-slot":"select-item",className:(0,ey.cn)("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...s,children:[(0,O.jsx)("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:(0,O.jsx)(hu,{children:(0,O.jsx)(H.default,{className:"size-4"})})}),(0,O.jsx)(hc,{children:r})]})}function hN({className:e,...r}){return(0,O.jsx)(hf,{"data-slot":"select-scroll-up-button",className:(0,ey.cn)("flex cursor-default items-center justify-center py-1",e),...r,children:(0,O.jsx)(oX,{className:"size-4"})})}function hE({className:e,...r}){return(0,O.jsx)(hm,{"data-slot":"select-scroll-down-button",className:(0,ey.cn)("flex cursor-default items-center justify-center py-1",e),...r,children:(0,O.jsx)(ns,{className:"size-4"})})}let hD="__main__";function hR({open:e,onOpenChange:r,onSubmit:s,initial:n,worktrees:i,projectId:a}){let[o,l]=(0,$.useState)(""),[c,d]=(0,$.useState)("0 9 * * *"),[u,h]=(0,$.useState)(""),[f,p]=(0,$.useState)("local"),[m,g]=(0,$.useState)([]),[x,v]=(0,$.useState)("command"),[_,y]=(0,$.useState)("claude"),[b,w]=(0,$.useState)(""),[S,j]=(0,$.useState)("branch"),[C,k]=(0,$.useState)(hD),[N,E]=(0,$.useState)(i),[D,R]=(0,$.useState)(""),[A,T]=(0,$.useState)("30"),[M,F]=(0,$.useState)(!1),[P,I]=(0,$.useState)(null);(0,$.useEffect)(()=>{e&&(I(null),l(n?.name??""),d(n?.cron_expr??"0 9 * * *"),h(n?.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone),p(n?.target??"local"),v(n?.run_type??"command"),y(n?.prompt_provider??"claude"),w(n?.content??""),j(n?.cwd_mode??"branch"),k(n?.branch??hD),R(n?.directory??""),T(String(Math.round((n?.timeout_seconds??1800)/60))))},[e,n]),(0,$.useEffect)(()=>{"local"===f&&E(i)},[f,i]),(0,$.useEffect)(()=>{let r=!1;return e&&a&&rv.api.getProjectRemotes(a).then(e=>{r||g(e)}).catch(e=>console.error("Failed to load project remotes:",e)),()=>{r=!0}},[e,a]),(0,$.useEffect)(()=>{let r=!1;if(e&&a&&"local"!==f)return rv.api.getProjectWorktrees(a,f).then(e=>{r||E(e)}).catch(e=>{console.error("Failed to load target worktrees:",e),r||E([{branch:null}])}),()=>{r=!0}},[e,a,f]);let B=async()=>{if(!o.trim()||!b.trim())return void I("Name and content are required");let e=parseInt(A,10);if(!Number.isInteger(e)||e<=0)return void I("Timeout must be a positive number of minutes");if("directory"===S&&!D.trim())return void I("Directory is required");F(!0),I(null);try{await s({name:o.trim(),cron_expr:c.trim(),timezone:u.trim()||"UTC",target:f,run_type:x,prompt_provider:"prompt"===x?_:null,content:b,cwd_mode:S,branch:"branch"===S?C===hD?null:C:null,directory:"directory"===S?D.trim():null,timeout_seconds:60*e}),r(!1)}catch(e){I(e instanceof Error?e.message:"Failed to save schedule")}finally{F(!1)}};return(0,O.jsx)(t8,{open:e,onOpenChange:r,children:(0,O.jsxs)(rr,{className:"max-w-lg",children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:n?"Edit Scheduled Task":"New Scheduled Task"}),(0,O.jsx)(ra,{children:"Run a command or a Claude prompt on a cron schedule"})]}),(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Name"}),(0,O.jsx)(ro,{value:o,onChange:e=>l(e.target.value),placeholder:"Daily log analysis",disabled:M})]}),(0,O.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Cron"}),(0,O.jsx)(ro,{value:c,onChange:e=>d(e.target.value),placeholder:"0 9 * * *",className:"font-mono",disabled:M}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"5-field cron — “0 9 * * *” = every day at 09:00"})]}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Timezone"}),(0,O.jsx)(ro,{value:u,onChange:e=>h(e.target.value),placeholder:"Asia/Shanghai",disabled:M})]})]}),(0,O.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Type"}),(0,O.jsxs)(hw,{value:x,onValueChange:e=>v(e),disabled:M,children:[(0,O.jsx)(hj,{size:"sm",children:(0,O.jsx)(hS,{})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"command",children:"Command (shell)"}),(0,O.jsx)(hk,{value:"prompt",children:"Prompt"})]})]})]}),"prompt"===x&&(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Agent"}),(0,O.jsxs)(hw,{value:_,onValueChange:e=>y(e),disabled:M,children:[(0,O.jsx)(hj,{size:"sm",children:(0,O.jsx)(hS,{})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"claude",children:"Claude"}),(0,O.jsx)(hk,{value:"codex",children:"Codex"})]})]})]})]}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"command"===x?"Command":"Prompt"}),(0,O.jsx)(rl,{value:b,onChange:e=>w(e.target.value),placeholder:"command"===x?"./scripts/scan.sh --daily":"Analyze today's server logs under ./logs and summarize anomalies",className:"font-mono text-sm min-h-[80px]",disabled:M})]}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Target"}),(0,O.jsxs)(hw,{value:f,onValueChange:e=>{p(e),k(hD)},disabled:M,children:[(0,O.jsx)(hj,{size:"sm",children:(0,O.jsx)(hS,{placeholder:"Local"})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"local",children:"Local"}),m.map(e=>(0,O.jsx)(hk,{value:e.remote_server_id,children:e.server_name??e.remote_server_id},e.remote_server_id))]})]})]}),(0,O.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Runs in"}),(0,O.jsxs)(hw,{value:S,onValueChange:e=>j(e),disabled:M,children:[(0,O.jsx)(hj,{size:"sm",children:(0,O.jsx)(hS,{})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"branch",children:"Workspace (branch)"}),(0,O.jsx)(hk,{value:"directory",children:"Directory"})]})]})]}),(0,O.jsx)("div",{className:"space-y-2",children:"branch"===S?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Workspace"}),(0,O.jsxs)(hw,{value:C,onValueChange:k,disabled:M,children:[(0,O.jsx)(hj,{size:"sm",children:(0,O.jsx)(hS,{placeholder:"Select workspace"})}),(0,O.jsx)(hC,{children:N.map(e=>(0,O.jsx)(hk,{value:e.branch??hD,children:e.branch??"main"},e.branch??hD))})]})]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Directory"}),(0,O.jsx)(ro,{value:D,onChange:e=>R(e.target.value),placeholder:"/var/log/myapp",className:"font-mono",disabled:M})]})})]}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Timeout (minutes)"}),(0,O.jsx)(ro,{value:A,onChange:e=>T(e.target.value),className:"w-24",disabled:M})]}),P&&(0,O.jsx)("div",{className:"text-sm text-destructive bg-destructive/10 px-3 py-2 rounded-md",children:P})]}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>r(!1),disabled:M,children:"Cancel"}),(0,O.jsx)(W.Button,{onClick:B,disabled:M||!o.trim()||!b.trim(),children:M?"Saving...":n?"Save":"Create"})]})]})})}let hA={running:"bg-blue-500/15 text-blue-600",completed:"bg-emerald-500/15 text-emerald-600",failed:"bg-red-500/15 text-red-600",timeout:"bg-amber-500/15 text-amber-600",killed:"bg-amber-500/15 text-amber-600",skipped:"bg-muted text-muted-foreground"},hT=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;function hM(e){return e.replace(hT,"").replace(/\r\n/g,"\n").replace(/\r/g,"\n")}function hF(e){return new Date(e.includes("T")?e:e.replace(" ","T")+"Z")}function hP(e){return e?hF(e).toLocaleString():"—"}function hI(e){if(!e.finished_at)return"…";let r=Math.max(0,Math.round((hF(e.finished_at).getTime()-hF(e.started_at).getTime())/1e3));return r<60?`${r}s`:`${Math.floor(r/60)}m ${r%60}s`}function hB({projectId:e,schedules:r,loading:s,selectedId:n,onSelect:i,worktrees:a,onCreate:o,onUpdate:l,onDelete:c,onRunNow:d,createOpen:u,onCreateOpenChange:h,openRunId:f,onOpenRunHandled:p}){let m=r.find(e=>e.id===n)??r[0]??null,[g,x]=(0,$.useState)([]),[v,_]=(0,$.useState)(!1),[y,b]=(0,$.useState)(null),[w,S]=(0,$.useState)(null),[j,C]=(0,$.useState)(0),[k,N]=(0,$.useState)(null),[E,D]=(0,$.useState)(null),[R,A]=(0,$.useState)(null),T=(0,$.useCallback)(async e=>{try{return await rv.api.getScheduleRuns(e)}catch(e){return console.error("Failed to fetch schedule runs:",e),null}},[]);(0,$.useEffect)(()=>{let e=m?.id,r=!1;return(e?T(e):Promise.resolve([])).then(e=>{if(r)return;let s=e??[];x(s),b(e=>e&&(e===w||s.some(r=>r.id===e&&"skipped"!==r.status))?e:s.find(e=>"skipped"!==e.status)?.id??null)}),()=>{r=!0}},[m?.id,r,T,w]);let M=g.find(e=>e.id===y&&e.schedule_id===m?.id),F=M?`${M.status}:${M.finished_at??""}`:null;(0,$.useEffect)(()=>{if(!y)return;let e=!1;return rv.api.getScheduleRun(y).then(r=>{e||N({runId:y,nonce:j,run:r,error:null})},r=>{e||N({runId:y,nonce:j,run:null,error:r instanceof Error?r.message:"Failed to load run output"})}),()=>{e=!0}},[y,j,F]);let P=async()=>{if(m){D(null);try{await d(m.id)}catch(e){D(e instanceof Error?e.message:"Failed to start run")}}};(0,$.useEffect)(()=>{f&&(S(f),b(f),p?.(f))},[f,p]);let I=m?g.filter(e=>e.schedule_id===m.id):[],B=y===w||I.some(e=>e.id===y&&"skipped"!==e.status),L=B&&k?.runId===y&&k.nonce===j?k:null;return s||0!==r.length?(0,O.jsxs)("div",{className:"flex flex-col h-full",children:[m&&(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(dh,{title:m.name,description:`${m.cron_expr} \xb7 ${m.timezone} \xb7 next: ${hP(m.next_run_at)}`,actions:(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsxs)(W.Button,{size:"sm",onClick:P,disabled:!!m.running,children:[(0,O.jsx)(rh,{className:"h-3.5 w-3.5 mr-1.5"}),m.running?"Running…":"Run now"]}),(0,O.jsxs)("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[(0,O.jsx)("input",{type:"checkbox",checked:m.enabled,onChange:e=>void l(m.id,{enabled:e.target.checked}),className:"h-4 w-4 rounded border-input accent-primary"}),(0,O.jsx)("span",{children:"Enabled"})]}),(0,O.jsx)(W.Button,{size:"sm",variant:"outline",onClick:()=>_(!0),children:(0,O.jsx)(rg,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{size:"sm",variant:"outline",onClick:()=>{m&&A(m)},className:"hover:bg-destructive/15 hover:text-destructive",children:(0,O.jsx)(rc,{className:"h-3.5 w-3.5"})})]})}),(0,O.jsxs)("div",{className:"px-5 py-3 grid grid-cols-2 gap-x-8 gap-y-1 text-sm border-b border-border/50",children:[(0,O.jsxs)("div",{children:[(0,O.jsx)("span",{className:"text-muted-foreground",children:"Type: "}),"command"===m.run_type?"Command":`Prompt (${"codex"===m.prompt_provider?"Codex":"Claude"})`]}),(0,O.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,O.jsx)("span",{className:"text-muted-foreground",children:"Runs in: "}),"branch"===m.cwd_mode?`workspace ${m.branch??"main"}`:m.directory,"local"!==m.target&&(0,O.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-violet-500/15 text-violet-600",children:"remote"})]}),(0,O.jsx)("div",{className:"col-span-2 font-mono text-xs text-muted-foreground truncate",title:m.content,children:m.content}),(0,O.jsxs)("div",{children:[(0,O.jsx)("span",{className:"text-muted-foreground",children:"Timeout: "}),Math.round(m.timeout_seconds/60),"m"]})]}),E&&(0,O.jsx)("div",{className:"mx-5 mt-3 text-sm text-destructive bg-destructive/10 px-3 py-2 rounded-md",children:E}),(0,O.jsx)("div",{className:"flex-1 min-h-0",children:(0,O.jsxs)(uj,{direction:"horizontal",autoSaveId:"schedule-run-panels",children:[(0,O.jsx)(dN,{defaultSize:33,minSize:25,children:(0,O.jsx)("div",{className:"h-full overflow-auto px-5 py-3",children:(0,O.jsxs)(uk,{children:[(0,O.jsx)(uN,{children:(0,O.jsxs)(uD,{children:[(0,O.jsx)(uR,{children:"Started"}),(0,O.jsx)(uR,{children:"Duration"}),(0,O.jsx)(uR,{children:"Status"}),(0,O.jsx)(uR,{children:"Exit code"})]})}),(0,O.jsxs)(uE,{children:[I.map(e=>(0,O.jsxs)(uD,{onClick:()=>{"skipped"!==e.status&&(S(null),b(e.id))},"aria-disabled":"skipped"===e.status,className:(0,ey.cn)("skipped"!==e.status&&"cursor-pointer",e.id===y&&"bg-muted/50"),children:[(0,O.jsx)(uA,{children:hP(e.started_at)}),(0,O.jsx)(uA,{children:"skipped"===e.status?"—":hI(e)}),(0,O.jsx)(uA,{children:(0,O.jsx)("span",{className:(0,ey.cn)("px-1.5 py-0.5 rounded text-[11px] font-medium",hA[e.status]),children:e.status})}),(0,O.jsx)(uA,{children:e.exit_code??"—"})]},e.id)),0===I.length&&(0,O.jsx)(uD,{children:(0,O.jsx)(uA,{colSpan:4,className:"text-center text-muted-foreground",children:"No runs yet — click “Run now” to try it"})})]})]})})}),(0,O.jsx)(uC,{withHandle:!0}),(0,O.jsx)(dN,{defaultSize:67,minSize:25,children:(0,O.jsx)("div",{className:"h-full overflow-auto px-5 py-4",children:B&&!L?(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-sm text-muted-foreground",children:"Loading run output…"}):L?.error?(0,O.jsxs)("div",{className:"h-full flex flex-col items-center justify-center gap-3 text-sm",children:[(0,O.jsx)("div",{className:"text-destructive",children:L.error}),(0,O.jsx)(W.Button,{size:"sm",variant:"outline",onClick:()=>C(e=>e+1),children:"Retry"})]}):L?.run?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{className:"mb-4 pb-3 border-b border-border/60",children:[(0,O.jsxs)("div",{className:"text-sm font-medium",children:[L.run.report?"Run report":"Run output"," — ",hP(L.run.started_at)]}),(0,O.jsxs)("div",{className:"mt-2 flex items-center gap-3 text-xs text-muted-foreground",children:[(0,O.jsx)("span",{className:(0,ey.cn)("px-1.5 py-0.5 rounded text-[11px] font-medium",hA[L.run.status]),children:L.run.status}),(0,O.jsx)("span",{children:hI(L.run)}),(0,O.jsxs)("span",{children:["Exit code: ",L.run.exit_code??"—"]})]})]}),L.run.report?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("div",{className:"rounded-md border border-border/50 p-3 text-sm",children:(0,O.jsx)(ck.i,{className:"[&>*:first-child]:mt-0 [&>*:last-child]:mb-0",children:L.run.report})}),(0,O.jsxs)("details",{className:"mt-3",children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer select-none",children:"Raw output"}),(0,O.jsx)("pre",{className:"mt-2 overflow-auto rounded-md bg-muted/50 p-3 font-mono text-xs whitespace-pre-wrap",children:L.run.output?hM(L.run.output):"(no output captured)"})]})]}):(0,O.jsx)("pre",{className:"overflow-auto rounded-md bg-muted/50 p-3 font-mono text-xs whitespace-pre-wrap",children:L.run.output?hM(L.run.output):"(no output captured)"})]}):(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-sm text-muted-foreground",children:"Select a run to view its output"})})})]})}),(0,O.jsx)(hR,{open:v,onOpenChange:_,initial:m,onSubmit:async e=>{await l(m.id,e)},worktrees:a,projectId:e})]}),(0,O.jsx)(hR,{open:u,onOpenChange:h,onSubmit:async e=>{i((await o(e)).id)},worktrees:a,projectId:e}),(0,O.jsx)(lL,{open:null!==R,onOpenChange:e=>{e||A(null)},children:(0,O.jsxs)(l$,{children:[(0,O.jsxs)(lW,{children:[(0,O.jsx)(lU,{children:"Delete scheduled task?"}),(0,O.jsx)(lq,{children:R?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("span",{className:"font-medium text-foreground",children:R.name})," ","and its run history will be permanently deleted. This cannot be undone."]}):null})]}),(0,O.jsxs)(lH,{children:[(0,O.jsx)(lV,{children:"Cancel"}),(0,O.jsx)(lK,{className:(0,ey.cn)((0,W.buttonVariants)({variant:"destructive"}),"border-transparent"),onClick:()=>{A(null),R&&(D(null),c(R.id).catch(e=>{D(e instanceof Error?e.message:"Failed to delete")}))},children:"Delete"})]})]})})]}):(0,O.jsxs)("div",{className:"flex flex-col h-full items-center justify-center gap-3 text-center",children:[(0,O.jsx)(sw,{className:"h-8 w-8 text-muted-foreground/50"}),(0,O.jsx)("p",{className:"text-sm text-muted-foreground",children:"No scheduled tasks yet"}),(0,O.jsx)(W.Button,{size:"sm",onClick:()=>h(!0),children:"New Scheduled Task"}),(0,O.jsx)(hR,{open:u,onOpenChange:h,onSubmit:async e=>{await o(e)},worktrees:a,projectId:e})]})}var hL=e.i(423917);function hz({className:e}){return(0,O.jsx)("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:(0,ey.cn)("h-4 w-4",e),"aria-hidden":"true",children:(0,O.jsx)("path",{d:"M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189z"})})}function hO({inviteUrl:e}){return e?(0,O.jsx)(W.Button,{asChild:!0,variant:"ghost",size:"icon-sm",title:"Join our Discord",children:(0,O.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer","aria-label":"Join our Discord",children:(0,O.jsx)(hz,{})})}):null}function h$({open:e,onOpenChange:r,onProjectCreated:s}){let{config:n}=(0,hL.useAppConfig)(),i=n?.localProjectsEnabled!==!1,[a,o]=(0,$.useState)(""),[l,c]=(0,$.useState)(""),[d,u]=(0,$.useState)([]),[h,f]=(0,$.useState)("closed"),[p,m]=(0,$.useState)([]),[g,x]=(0,$.useState)(null),[v,_]=(0,$.useState)(""),[y,b]=(0,$.useState)(!1),[w,S]=(0,$.useState)(""),j=()=>{o(""),c(""),u([]),C(),S("")},C=()=>{f("closed"),x(null),_("")},k=e=>{e||j(),r(e)},N=async()=>{let e=await rv.api.selectFolder();e.path&&(c(e.path),a||o(e.path.split("/").pop()||""))},E=async()=>{f("pick-server");try{let e=await rv.api.getRemoteServers();m(e)}catch{m([])}},D=l.trim().length>0,R=d.length>0,A=async()=>{if(!a.trim())return void S("Project name is required");if(!D&&!R)return void S(i?"Please provide a local folder, remote server, or both":"Please add a remote server");b(!0),S("");try{let e=await rv.api.createProject({name:a.trim(),...D?{path:l.trim()}:{},...R&&!D?{agentMode:d[0].serverId}:{}});for(let r of d)await rv.api.addProjectRemote(e.id,{remoteServerId:r.serverId,remotePath:r.remotePath});s(e),j(),r(!1)}catch(e){S(e instanceof Error?e.message:"Failed to create project")}finally{b(!1)}};return(0,O.jsx)(t8,{open:e,onOpenChange:k,children:(0,O.jsxs)(rr,{className:"max-w-lg h-[620px] max-h-[calc(100vh-4rem)] grid-rows-[auto_minmax(0,1fr)_auto]",children:[(0,O.jsx)(rs,{children:(0,O.jsx)(ri,{children:"Create New Project"})}),(0,O.jsx)("div",{className:"overflow-y-auto -mx-1 px-1",children:(0,O.jsxs)("div",{className:"space-y-5 py-2",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Project Name"}),(0,O.jsx)(ro,{value:a,onChange:e=>o(e.target.value),placeholder:"My Project"})]}),i&&(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Local Folder"}),(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsx)(ro,{value:l,onChange:e=>c(e.target.value),placeholder:"/path/to/project (optional)",className:"flex-1"}),(0,O.jsx)(W.Button,{variant:"outline",onClick:N,children:(0,O.jsx)(r_,{className:"h-4 w-4"})})]})]}),(0,O.jsxs)("div",{className:"space-y-3",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Remote Servers"}),d.length>0&&(0,O.jsx)("div",{className:"space-y-2",children:d.map((e,r)=>(0,O.jsxs)("div",{className:"flex items-center gap-2 rounded-md border p-2 text-sm",children:[(0,O.jsx)(ry,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),(0,O.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,O.jsx)("p",{className:"font-medium truncate",children:e.serverName}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground font-mono truncate",children:e.remotePath})]}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon-sm",className:"h-7 w-7 shrink-0",onClick:()=>{u(e=>e.filter((e,s)=>s!==r))},children:(0,O.jsx)(rc,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},`${e.serverId}-${e.remotePath}`))}),"closed"===h&&(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:E,className:"w-full",children:[(0,O.jsx)(eS,{className:"h-4 w-4 mr-1"}),"Add Remote"]}),"pick-server"===h&&(0,O.jsxs)("div",{className:"rounded-md border p-3 space-y-3",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between",children:[(0,O.jsx)("label",{className:"text-xs font-medium",children:"Select a Remote Server"}),(0,O.jsx)(W.Button,{variant:"ghost",size:"sm",onClick:C,children:(0,O.jsx)(t7,{className:"h-3.5 w-3.5"})})]}),p.length>0&&(0,O.jsx)("div",{className:"space-y-1",children:p.map(e=>(0,O.jsxs)("button",{className:"flex items-center gap-2 w-full rounded-md p-2 text-sm text-left hover:bg-muted",onClick:()=>{x(e),_(""),f("pick-path")},children:[(0,O.jsx)(od,{className:"h-4 w-4 text-muted-foreground"}),(0,O.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,O.jsx)("p",{className:"truncate",children:e.name}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground truncate",children:"online"===e.status?"Connected":"Not connected"})]})]},e.id))}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"Add new servers in Settings → Remote Servers, then connect the remote machine with a connect token."})]}),"pick-path"===h&&g&&(0,O.jsxs)("div",{className:"rounded-md border p-3 space-y-3",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between",children:[(0,O.jsxs)("label",{className:"text-xs font-medium",children:["Select Directory on ",g.name]}),(0,O.jsx)(W.Button,{variant:"ghost",size:"sm",onClick:C,children:(0,O.jsx)(t7,{className:"h-3.5 w-3.5"})})]}),(0,O.jsx)(oJ,{serverId:g.id,onSelect:e=>{_(e)},selectedPath:v}),v&&(0,O.jsxs)("div",{className:"flex items-center justify-between",children:[(0,O.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Selected: ",(0,O.jsx)("span",{className:"font-mono",children:v})]}),(0,O.jsx)(W.Button,{size:"sm",onClick:()=>{g&&v&&(d.some(e=>e.serverId===g.id&&e.remotePath===v)||(u(e=>[...e,{serverId:g.id,serverName:g.name,remotePath:v}]),a||o(v.split("/").pop()||"")),C())},children:"Add"})]})]})]}),w&&(0,O.jsx)("p",{className:"text-sm text-red-500 pt-3",children:w})]})}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>k(!1),children:"Cancel"}),(0,O.jsx)(W.Button,{onClick:A,disabled:y,children:y?"Creating...":"Create Project"})]})]})})}let hW=(0,ew.default)("network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]),hH=(0,ew.default)("palette",[["path",{d:"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z",key:"e79jfc"}],["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}]]),hU=(0,ew.default)("sparkles",[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]]),hq=(0,ew.default)("square-terminal",[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]]),hK=(0,ew.default)("moon",[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]]),hV=(0,ew.default)("sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);var hY=e.i(371263),hG=e.i(909596),hX=["PageUp","PageDown"],hJ=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],hZ={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},hQ="Slider",[h0,h1,h2]=rb(hQ),[h5,h3]=q(hQ,[h2]),[h4,h6]=h5(hQ),h7=$.forwardRef((e,r)=>{let{name:s,min:n=0,max:i=100,step:a=1,orientation:o="horizontal",disabled:l=!1,minStepsBetweenThumbs:c=0,defaultValue:d=[n],value:u,onValueChange:h=()=>{},onValueCommit:f=()=>{},inverted:p=!1,form:m,...g}=e,x=$.useRef(new Set),v=$.useRef(0),_="horizontal"===o,[y=[],b]=G({prop:u,defaultProp:d,onChange:e=>{let r=[...x.current];r[v.current]?.focus(),h(e)}}),w=$.useRef(y);function S(e,r,{commit:s}={commit:!1}){let o,l=(String(a).split(".")[1]||"").length,d=oh(Math.round((Math.round((e-n)/a)*a+n)*(o=Math.pow(10,l)))/o,[n,i]);b((e=[])=>{let n=function(e=[],r,s){let n=[...e];return n[s]=r,n.sort((e,r)=>e-r)}(e,d,r);if(!function(e,r){if(r>0)return Math.min(...e.slice(0,-1).map((r,s)=>e[s+1]-r))>=r;return!0}(n,c*a))return e;{v.current=n.indexOf(d);let r=String(n)!==String(e);return r&&s&&f(n),r?n:e}})}return(0,O.jsx)(h4,{scope:e.__scopeSlider,name:s,disabled:l,min:n,max:i,valueIndexToChangeRef:v,thumbs:x.current,values:y,orientation:o,form:m,children:(0,O.jsx)(h0.Provider,{scope:e.__scopeSlider,children:(0,O.jsx)(h0.Slot,{scope:e.__scopeSlider,children:(0,O.jsx)(_?fe:ft,{"aria-disabled":l,"data-disabled":l?"":void 0,...g,ref:r,onPointerDown:K(g.onPointerDown,()=>{l||(w.current=y)}),min:n,max:i,inverted:p,onSlideStart:l?void 0:function(e){let r=function(e,r){if(1===e.length)return 0;let s=e.map(e=>Math.abs(e-r)),n=Math.min(...s);return s.indexOf(n)}(y,e);S(e,r)},onSlideMove:l?void 0:function(e){S(e,v.current)},onSlideEnd:l?void 0:function(){let e=w.current[v.current];y[v.current]!==e&&f(y)},onHomeKeyDown:()=>!l&&S(n,0,{commit:!0}),onEndKeyDown:()=>!l&&S(i,y.length-1,{commit:!0}),onStepKeyDown:({event:e,direction:r})=>{if(!l){let s=hX.includes(e.key)||e.shiftKey&&hJ.includes(e.key),n=v.current;S(y[n]+a*(s?10:1)*r,n,{commit:!0})}}})})})})});h7.displayName=hQ;var[h8,h9]=h5(hQ,{startEdge:"left",endEdge:"right",size:"width",direction:1}),fe=$.forwardRef((e,r)=>{let{min:s,max:n,dir:i,inverted:a,onSlideStart:o,onSlideMove:l,onSlideEnd:c,onStepKeyDown:d,...u}=e,[h,f]=$.useState(null),p=(0,U.useComposedRefs)(r,e=>f(e)),m=$.useRef(void 0),g=rk(i),x="ltr"===g,v=x&&!a||!x&&a;function _(e){let r=m.current||h.getBoundingClientRect(),i=fh([0,r.width],v?[s,n]:[n,s]);return m.current=r,i(e-r.left)}return(0,O.jsx)(h8,{scope:e.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?1:-1,size:"width",children:(0,O.jsx)(fr,{dir:g,"data-orientation":"horizontal",...u,ref:p,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:e=>{let r=_(e.clientX);o?.(r)},onSlideMove:e=>{let r=_(e.clientX);l?.(r)},onSlideEnd:()=>{m.current=void 0,c?.()},onStepKeyDown:e=>{let r=hZ[v?"from-left":"from-right"].includes(e.key);d?.({event:e,direction:r?-1:1})}})})}),ft=$.forwardRef((e,r)=>{let{min:s,max:n,inverted:i,onSlideStart:a,onSlideMove:o,onSlideEnd:l,onStepKeyDown:c,...d}=e,u=$.useRef(null),h=(0,U.useComposedRefs)(r,u),f=$.useRef(void 0),p=!i;function m(e){let r=f.current||u.current.getBoundingClientRect(),i=fh([0,r.height],p?[n,s]:[s,n]);return f.current=r,i(e-r.top)}return(0,O.jsx)(h8,{scope:e.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:(0,O.jsx)(fr,{"data-orientation":"vertical",...d,ref:h,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:e=>{let r=m(e.clientY);a?.(r)},onSlideMove:e=>{let r=m(e.clientY);o?.(r)},onSlideEnd:()=>{f.current=void 0,l?.()},onStepKeyDown:e=>{let r=hZ[p?"from-bottom":"from-top"].includes(e.key);c?.({event:e,direction:r?-1:1})}})})}),fr=$.forwardRef((e,r)=>{let{__scopeSlider:s,onSlideStart:n,onSlideMove:i,onSlideEnd:a,onHomeKeyDown:o,onEndKeyDown:l,onStepKeyDown:c,...d}=e,u=h6(hQ,s);return(0,O.jsx)(er.span,{...d,ref:r,onKeyDown:K(e.onKeyDown,e=>{"Home"===e.key?(o(e),e.preventDefault()):"End"===e.key?(l(e),e.preventDefault()):hX.concat(hJ).includes(e.key)&&(c(e),e.preventDefault())}),onPointerDown:K(e.onPointerDown,e=>{let r=e.target;r.setPointerCapture(e.pointerId),e.preventDefault(),u.thumbs.has(r)?r.focus():n(e)}),onPointerMove:K(e.onPointerMove,e=>{e.target.hasPointerCapture(e.pointerId)&&i(e)}),onPointerUp:K(e.onPointerUp,e=>{let r=e.target;r.hasPointerCapture(e.pointerId)&&(r.releasePointerCapture(e.pointerId),a(e))})})}),fs="SliderTrack",fn=$.forwardRef((e,r)=>{let{__scopeSlider:s,...n}=e,i=h6(fs,s);return(0,O.jsx)(er.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...n,ref:r})});fn.displayName=fs;var fi="SliderRange",fa=$.forwardRef((e,r)=>{let{__scopeSlider:s,...n}=e,i=h6(fi,s),a=h9(fi,s),o=$.useRef(null),l=(0,U.useComposedRefs)(r,o),c=i.values.length,d=i.values.map(e=>fu(e,i.min,i.max)),u=c>1?Math.min(...d):0,h=100-Math.max(...d);return(0,O.jsx)(er.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...n,ref:l,style:{...e.style,[a.startEdge]:u+"%",[a.endEdge]:h+"%"}})});fa.displayName=fi;var fo="SliderThumb",fl=$.forwardRef((e,r)=>{let s=h1(e.__scopeSlider),[n,i]=$.useState(null),a=(0,U.useComposedRefs)(r,e=>i(e)),o=$.useMemo(()=>n?s().findIndex(e=>e.ref.current===n):-1,[s,n]);return(0,O.jsx)(fc,{...e,ref:a,index:o})}),fc=$.forwardRef((e,r)=>{var s,n,i,a,o;let l,c,{__scopeSlider:d,index:u,name:h,...f}=e,p=h6(fo,d),m=h9(fo,d),[g,x]=$.useState(null),v=(0,U.useComposedRefs)(r,e=>x(e)),_=!g||p.form||!!g.closest("form"),y=J(g),b=p.values[u],w=void 0===b?0:fu(b,p.min,p.max),S=(s=u,(n=p.values.length)>2?`Value ${s+1} of ${n}`:2===n?["Minimum","Maximum"][s]:void 0),j=y?.[m.size],C=j?(i=j,a=w,o=m.direction,c=fh([0,50],[0,l=i/2]),(l-c(a)*o)*o):0;return $.useEffect(()=>{if(g)return p.thumbs.add(g),()=>{p.thumbs.delete(g)}},[g,p.thumbs]),(0,O.jsxs)("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[m.startEdge]:`calc(${w}% + ${C}px)`},children:[(0,O.jsx)(h0.ItemSlot,{scope:e.__scopeSlider,children:(0,O.jsx)(er.span,{role:"slider","aria-label":e["aria-label"]||S,"aria-valuemin":p.min,"aria-valuenow":b,"aria-valuemax":p.max,"aria-orientation":p.orientation,"data-orientation":p.orientation,"data-disabled":p.disabled?"":void 0,tabIndex:p.disabled?void 0:0,...f,ref:v,style:void 0===b?{display:"none"}:e.style,onFocus:K(e.onFocus,()=>{p.valueIndexToChangeRef.current=u})})}),_&&(0,O.jsx)(fd,{name:h??(p.name?p.name+(p.values.length>1?"[]":""):void 0),form:p.form,value:b},u)]})});fl.displayName=fo;var fd=$.forwardRef(({__scopeSlider:e,value:r,...s},n)=>{let i=$.useRef(null),a=(0,U.useComposedRefs)(i,n),o=X(r);return $.useEffect(()=>{let e=i.current;if(!e)return;let s=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value").set;if(o!==r&&s){let n=new Event("input",{bubbles:!0});s.call(e,r),e.dispatchEvent(n)}},[o,r]),(0,O.jsx)(er.input,{style:{display:"none"},...s,ref:a,defaultValue:r})});function fu(e,r,s){return oh(100/(s-r)*(e-r),[0,100])}function fh(e,r){return s=>{if(e[0]===e[1]||r[0]===r[1])return r[0];let n=(r[1]-r[0])/(e[1]-e[0]);return r[0]+n*(s-e[0])}}fd.displayName="RadioBubbleInput";let ff=$.forwardRef(({className:e,...r},s)=>(0,O.jsxs)(h7,{ref:s,className:(0,ey.cn)("relative flex w-full touch-none select-none items-center","data-[disabled]:opacity-50",e),...r,children:[(0,O.jsx)(fn,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-muted",children:(0,O.jsx)(fa,{className:"absolute h-full bg-primary"})}),(0,O.jsx)(fl,{className:(0,ey.cn)("block h-4 w-4 rounded-full border border-primary/60 bg-card shadow-[var(--shadow-sm-app)]","transition-colors hover:border-primary","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 focus-visible:ring-offset-1 focus-visible:ring-offset-background"),"aria-label":"Value"})]}));function fp({id:e,label:r,description:s,rightSlot:n,children:i}){return(0,O.jsxs)("section",{id:e,className:"scroll-mt-6 rounded-[10px] border border-border bg-card p-5 shadow-[var(--shadow-sm-app)]",children:[(0,O.jsxs)("header",{className:"flex items-end justify-between gap-3 pb-3 mb-4 border-b border-border/70",children:[(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("h2",{className:"text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/80 leading-none",children:r}),s&&(0,O.jsx)("p",{className:"mt-2 text-[12px] text-muted-foreground/90 leading-snug",children:s})]}),n&&(0,O.jsx)("div",{className:"shrink-0",children:n})]}),(0,O.jsx)("div",{className:"space-y-4",children:i})]})}function fm({label:e,hint:r,htmlFor:s,mono:n,children:i}){return(0,O.jsxs)("div",{children:[(0,O.jsx)("label",{htmlFor:s,className:(0,ey.cn)("block text-[12px] font-medium text-foreground/90 mb-1.5",n&&"font-mono tracking-tight"),children:e}),i,r&&(0,O.jsx)("p",{className:"mt-1.5 text-[11px] text-muted-foreground/85 leading-relaxed",children:r})]})}function fg({name:e,value:r,options:s,onChange:n,columns:i=1}){return(0,O.jsx)("div",{className:(0,ey.cn)("grid gap-2",1===i&&"grid-cols-1",2===i&&"grid-cols-1 sm:grid-cols-2",3===i&&"grid-cols-1 sm:grid-cols-3"),role:"radiogroup",children:s.map(s=>{let i=r===s.value,a=s.Icon;return(0,O.jsxs)("label",{className:(0,ey.cn)("group relative flex items-start gap-3 px-3 py-2.5 rounded-[8px] border cursor-pointer","transition-[border-color,background-color,box-shadow] duration-150","focus-within:ring-2 focus-within:ring-ring/40 focus-within:ring-offset-1 focus-within:ring-offset-background",i?"border-primary/40 bg-[color-mix(in_oklch,var(--primary)_8%,var(--card))] shadow-[var(--shadow-sm-app)]":"border-border/70 bg-card hover:border-border hover:bg-muted/40"),children:[(0,O.jsx)("input",{type:"radio",name:e,value:s.value,checked:i,onChange:()=>n(s.value),className:"sr-only"}),(0,O.jsx)("span",{"aria-hidden":!0,className:(0,ey.cn)("mt-0.5 inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full border transition-colors",i?"border-primary bg-primary":"border-border bg-card group-hover:border-foreground/40"),children:i&&(0,O.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-primary-foreground"})}),a&&(0,O.jsx)(a,{className:(0,ey.cn)("h-4 w-4 mt-0.5 shrink-0 transition-colors",i?"text-primary":"text-muted-foreground")}),(0,O.jsxs)("span",{className:"flex-1 min-w-0",children:[(0,O.jsx)("span",{className:(0,ey.cn)("block text-[12.5px] font-medium leading-tight",i?"text-foreground":"text-foreground/90"),children:s.label}),s.description&&(0,O.jsx)("span",{className:"mt-0.5 block text-[11.5px] text-muted-foreground leading-snug",children:s.description})]}),s.meta&&(0,O.jsx)("span",{className:"ml-2 mt-0.5 shrink-0 font-mono text-[10.5px] text-muted-foreground/80",children:s.meta})]},s.value)})})}function fx({variant:e="default",icon:r,children:s}){return(0,O.jsxs)("div",{className:(0,ey.cn)("flex items-center gap-2 rounded-[6px] px-2.5 py-1.5 text-[12px]","default"===e&&"text-muted-foreground bg-muted/40","success"===e&&"text-[color:var(--chart-2)] bg-[color-mix(in_oklch,var(--chart-2)_10%,var(--card))] border border-[color-mix(in_oklch,var(--chart-2)_25%,transparent)]","error"===e&&"text-destructive bg-[color-mix(in_oklch,var(--destructive)_8%,var(--card))] border border-[color-mix(in_oklch,var(--destructive)_25%,transparent)]"),children:[r&&(0,O.jsx)("span",{className:"shrink-0",children:r}),(0,O.jsx)("span",{className:"truncate",children:s})]})}function fv({children:e}){return(0,O.jsx)("div",{className:"flex items-center justify-end gap-2 pt-1",children:e})}function f_({nav:e,children:r}){let[s,n]=(0,$.useState)(e[0]?.id??""),i=(0,$.useRef)(null);return(0,$.useEffect)(()=>{let r=i.current;if(!r)return;let s=()=>{let s=r.getBoundingClientRect(),i=s.top+.25*s.height,a=e[0]?.id??"";for(let s of e){let e=r.querySelector(`#${CSS.escape(s.id)}`);e&&e.getBoundingClientRect().top<=i&&(a=s.id)}n(a)};return s(),r.addEventListener("scroll",s,{passive:!0}),()=>r.removeEventListener("scroll",s)},[e]),(0,O.jsxs)("div",{className:"flex-1 min-h-0 grid grid-cols-[200px_minmax(0,1fr)] overflow-hidden",children:[(0,O.jsx)("aside",{className:"border-r border-border bg-[color:var(--sidebar)] overflow-y-auto",children:(0,O.jsx)("nav",{className:"p-3 flex flex-col gap-0.5",children:e.map(e=>{let r=e.Icon,a=s===e.id;return(0,O.jsxs)("button",{type:"button",onClick:()=>(e=>{let r=i.current;if(!r)return;let s=r.querySelector(`#${CSS.escape(e)}`);if(!s)return;let a=s.offsetTop-12;r.scrollTo({top:a,behavior:"smooth"}),n(e)})(e.id),className:(0,ey.cn)("group relative flex items-center gap-2.5 w-full px-2.5 py-1.5 rounded-[6px] text-[12.5px] text-left","transition-colors duration-100",a?"bg-card text-foreground font-medium shadow-[var(--shadow-sm-app)]":"text-muted-foreground hover:bg-muted/50 hover:text-foreground"),children:[a&&(0,O.jsx)("span",{"aria-hidden":!0,className:"absolute -left-3 top-1.5 bottom-1.5 w-[2px] rounded-full bg-primary"}),r&&(0,O.jsx)(r,{className:(0,ey.cn)("h-3.5 w-3.5 shrink-0",a?"text-foreground":"text-muted-foreground/80")}),(0,O.jsx)("span",{className:"truncate",children:e.label}),e.badge&&(0,O.jsx)("span",{className:"ml-auto font-mono text-[10px] text-muted-foreground/80",children:e.badge})]},e.id)})})}),(0,O.jsx)("div",{ref:i,className:"overflow-y-auto",children:(0,O.jsx)("div",{className:"mx-auto max-w-2xl px-8 py-7 space-y-6",children:r})})]})}ff.displayName="Slider";let fy=[{value:"light",label:"Light",description:"Bright surface, true-white cards",Icon:hV},{value:"dark",label:"Dark",description:"Low-light surfaces with deep neutrals",Icon:hK},{value:"system",label:"System",description:"Match your OS preference",Icon:oc}],{fontSizeMin:fb,fontSizeMax:fw}=rv.CONVERSATION_SETTINGS_LIMITS;function fS(){let{theme:e,setTheme:r}=(0,hY.useTheme)(),{settings:s,setAgentFontSize:n,setChatFontSize:i,setFilesTreeFontSize:a,setFilesContentFontSize:o}=(0,hG.useConversationSettings)();return(0,O.jsxs)("div",{className:"space-y-6",children:[(0,O.jsx)(fm,{label:"Theme",hint:"Sets the surface palette across the app. Switching is instant.",children:(0,O.jsx)(fg,{name:"theme",value:e,options:fy,onChange:r,columns:3})}),(0,O.jsx)(fm,{label:"Conversation font size",hint:"Independent typography for agent and chat views. Affects message body and tool output; chrome elements stay fixed.",children:(0,O.jsxs)("div",{className:"space-y-5",children:[(0,O.jsx)(fj,{label:"Agent conversation",value:s.agentFontSize,onChange:n}),(0,O.jsx)(fj,{label:"Chat session",value:s.chatFontSize,onChange:i})]})}),(0,O.jsx)(fm,{label:"Files font size",hint:"Independent typography for the Files tab. File tree controls the file list and search results; file content controls the preview and code.",children:(0,O.jsxs)("div",{className:"space-y-5",children:[(0,O.jsx)(fj,{label:"File tree, File search",value:s.filesTreeFontSize,onChange:a}),(0,O.jsx)(fj,{label:"File content",value:s.filesContentFontSize,onChange:o})]})}),(0,O.jsx)(fv,{children:(0,O.jsx)(W.Button,{variant:"ghost",size:"sm",onClick:()=>{n(rv.DEFAULT_CONVERSATION_SETTINGS.agentFontSize),i(rv.DEFAULT_CONVERSATION_SETTINGS.chatFontSize),a(rv.DEFAULT_CONVERSATION_SETTINGS.filesTreeFontSize),o(rv.DEFAULT_CONVERSATION_SETTINGS.filesContentFontSize)},children:"Reset"})})]})}function fj({label:e,value:r,onChange:s}){return(0,O.jsxs)("div",{children:[(0,O.jsxs)("div",{className:"flex items-baseline justify-between mb-1.5",children:[(0,O.jsx)("span",{className:"text-[12px] font-medium text-foreground/90",children:e}),(0,O.jsxs)("span",{className:"font-mono text-[11.5px] text-foreground/80 tabular-nums",children:[r," px"]})]}),(0,O.jsx)(ff,{min:fb,max:fw,step:1,value:[r],onValueChange:e=>s(e[0])}),(0,O.jsxs)("div",{className:"flex justify-between mt-1 text-[10.5px] text-muted-foreground/80 font-mono",children:[(0,O.jsx)("span",{children:fb}),(0,O.jsx)("span",{children:fw})]})]})}let fC=(0,ew.default)("waypoints",[["circle",{cx:"12",cy:"4.5",r:"2.5",key:"r5ysbb"}],["path",{d:"m10.2 6.3-3.9 3.9",key:"1nzqf6"}],["circle",{cx:"4.5",cy:"12",r:"2.5",key:"jydg6v"}],["path",{d:"M7 12h10",key:"b7w52i"}],["circle",{cx:"19.5",cy:"12",r:"2.5",key:"1piiel"}],["path",{d:"m13.8 17.7 3.9-3.9",key:"1wyg1y"}],["circle",{cx:"12",cy:"19.5",r:"2.5",key:"13o1pw"}]]),fk={deepseek:hU,openrouter:fC},fN=rv.PROVIDER_IDS.map(e=>({value:e,label:rv.PROVIDERS[e].label,description:"deepseek"===e?"Direct API access — lowest latency":"Aggregator routing — many models available",Icon:fk[e]}));function fE({name:e,value:r,onChange:s}){let n=rv.PROVIDERS[r.provider];return(0,O.jsxs)("div",{className:"space-y-3",children:[(0,O.jsx)(fg,{name:e,value:r.provider,options:fN,onChange:e=>s((0,rv.defaultModelChoice)(e)),columns:2}),n.models?(0,O.jsxs)(hw,{value:r.model,onValueChange:e=>s({...r,model:e}),children:[(0,O.jsx)(hj,{className:"w-full font-mono text-[12.5px]",children:(0,O.jsx)(hS,{})}),(0,O.jsx)(hC,{children:n.models.map(e=>(0,O.jsx)(hk,{value:e,className:"font-mono text-[12.5px]",children:n.modelLabels?.[e]??e},e))})]}):(0,O.jsx)(ro,{className:"font-mono text-[12.5px]",placeholder:n.placeholder,value:r.model,onChange:e=>s({...r,model:e.target.value})})]})}function fD(){let[e,r]=(0,$.useState)(()=>(0,rv.defaultChatProviderConfig)().apiKeys),[s,n]=(0,$.useState)(()=>({deepseek:!1,openrouter:!1})),[i,a]=(0,$.useState)(()=>(0,rv.defaultModelChoice)()),[o,l]=(0,$.useState)(()=>(0,rv.defaultModelChoice)()),[c,d]=(0,$.useState)(!0),[u,h]=(0,$.useState)(!1),[f,p]=(0,$.useState)(null);(0,$.useEffect)(()=>{d(!0),rv.api.getChatProviderSettings().then(e=>{r(e.apiKeys),a(e.main),l(e.fast),n({deepseek:!1,openrouter:!1})}).finally(()=>d(!1))},[]);let m=async()=>{h(!0),p(null);try{let c={};for(let r of rv.PROVIDER_IDS)s[r]&&(c[r]=e[r]);let d={main:i,fast:o};Object.keys(c).length>0&&(d.apiKeys=c);let u=await rv.api.updateChatProviderSettings(d);r(u.apiKeys),a(u.main),l(u.fast),n({deepseek:!1,openrouter:!1}),p("Settings saved"),setTimeout(()=>p(null),2e3)}catch(e){p(e instanceof Error?e.message:"Failed to save")}finally{h(!1)}};return c?(0,O.jsx)("div",{className:"flex items-center justify-center py-6",children:(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):(0,O.jsxs)("div",{className:"space-y-6",children:[(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsx)("p",{className:"text-[12px] font-medium text-foreground/70",children:"API keys"}),rv.PROVIDER_IDS.map(i=>{let a=rv.PROVIDERS[i],o=s[i],l=e[i];return(0,O.jsx)(fm,{label:`${a.label} API key`,mono:!0,hint:(0,O.jsxs)(O.Fragment,{children:["Leave empty to fall back to the"," ",(0,O.jsx)("code",{className:"font-mono text-[10.5px] bg-muted/60 border border-border/60 rounded px-1 py-px",children:a.envKey})," ","environment variable."]}),children:(0,O.jsx)(ro,{type:"password",className:"font-mono text-[12px]",placeholder:l&&!o?l:"sk-...",value:o?l:"",onChange:e=>{var s;return s=e.target.value,void(r(e=>({...e,[i]:s})),n(e=>({...e,[i]:!0})),p(null))}})},i)})]}),(0,O.jsx)(fm,{label:"Main model",hint:"Powers the chat session.",children:(0,O.jsx)(fE,{name:"main-provider",value:i,onChange:e=>{a(e),p(null)}})}),(0,O.jsx)(fm,{label:"Fast model",hint:"Powers translate and agent session titles. Can use a different provider than the main model.",children:(0,O.jsx)(fE,{name:"fast-provider",value:o,onChange:e=>{l(e),p(null)}})}),f&&(0,O.jsx)(fx,{variant:"Settings saved"===f?"success":"error",icon:"Settings saved"===f?(0,O.jsx)(sJ,{className:"h-3.5 w-3.5"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5"}),children:f}),(0,O.jsx)(fv,{children:(0,O.jsxs)(W.Button,{size:"sm",onClick:m,disabled:u,children:[u&&(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save"]})})]})}let fR=[{value:"none",label:"Direct",description:"No proxy — connect directly to the internet",Icon:(0,ew.default)("shield-off",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]])},{value:"http",label:"HTTP / HTTPS",description:"Route through an HTTP CONNECT proxy",Icon:hW},{value:"socks5",label:"SOCKS5",description:"Route through a SOCKS5 proxy server",Icon:fC}];function fA(){let[e,r]=(0,$.useState)("none"),[s,n]=(0,$.useState)(""),[i,a]=(0,$.useState)(""),[o,l]=(0,$.useState)(!0),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(!1),[f,p]=(0,$.useState)(null),[m,g]=(0,$.useState)(null);(0,$.useEffect)(()=>{l(!0),p(null),g(null),rv.api.getProxySettings().then(e=>{r(e.type),n(e.host),a(e.port?String(e.port):"")}).finally(()=>l(!1))},[]);let x=()=>({type:e,host:"none"===e?"":s.trim(),port:"none"===e?0:parseInt(i,10)||0}),v=async()=>{h(!0),p(null);try{p(await rv.api.testProxyConnection(x()))}catch(e){p({success:!1,message:e instanceof Error?e.message:"Test failed"})}finally{h(!1)}},_=async()=>{d(!0),g(null);try{await rv.api.updateProxySettings(x()),g("Settings saved"),setTimeout(()=>g(null),2e3)}catch(e){g(e instanceof Error?e.message:"Failed to save")}finally{d(!1)}},y="none"!==e;return o?(0,O.jsx)("div",{className:"flex items-center justify-center py-6",children:(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsx)(fm,{label:"Connection mode",children:(0,O.jsx)(fg,{name:"proxyType",value:e,options:fR,onChange:e=>{r(e),p(null),g(null)}})}),y&&(0,O.jsxs)("div",{className:"grid grid-cols-[1fr_120px] gap-3",children:[(0,O.jsx)(fm,{label:"Host",mono:!0,children:(0,O.jsx)(ro,{placeholder:"127.0.0.1",value:s,className:"font-mono text-[12.5px]",onChange:e=>{n(e.target.value),p(null),g(null)}})}),(0,O.jsx)(fm,{label:"Port",mono:!0,children:(0,O.jsx)(ro,{type:"number",placeholder:"1080",value:i,className:"font-mono text-[12.5px]",onChange:e=>{a(e.target.value),p(null),g(null)},min:1,max:65535})})]}),f&&(0,O.jsx)(fx,{variant:f.success?"success":"error",icon:f.success?(0,O.jsx)(sJ,{className:"h-3.5 w-3.5"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5"}),children:f.message??(f.success?"Connection succeeded":"Connection failed")}),m&&!f&&(0,O.jsx)(fx,{variant:"Settings saved"===m?"success":"error",icon:"Settings saved"===m?(0,O.jsx)(sJ,{className:"h-3.5 w-3.5"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5"}),children:m}),(0,O.jsxs)(fv,{children:[y&&(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:v,disabled:u||!s.trim()||!i,children:[u&&(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Test connection"]}),(0,O.jsxs)(W.Button,{size:"sm",onClick:_,disabled:c,children:[c&&(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save"]})]})]})}var fT=e.i(276949);let{scrollbackMin:fM,scrollbackMax:fF,fontSizeMin:fP,fontSizeMax:fI}=rv.TERMINAL_SETTINGS_LIMITS;function fB(){let{settings:e,loaded:r,refresh:s}=(0,fT.useTerminalSettings)(),[n,i]=(0,$.useState)(String(rv.DEFAULT_TERMINAL_SETTINGS.scrollback)),[a,o]=(0,$.useState)(String(rv.DEFAULT_TERMINAL_SETTINGS.fontSize)),[l,c]=(0,$.useState)(rv.DEFAULT_TERMINAL_SETTINGS.fontFamily),[d,u]=(0,$.useState)(!1),[h,f]=(0,$.useState)(null);(0,$.useEffect)(()=>{r&&(i(String(e.scrollback)),o(String(e.fontSize)),c(e.fontFamily))},[r,e.scrollback,e.fontSize,e.fontFamily]);let p=parseInt(n,10),m=parseInt(a,10),g=Number.isFinite(p)&&p>=fM&&p<=fF,x=Number.isFinite(m)&&m>=fP&&m<=fI,v=""!==l.trim(),_=g&&x&&v,y=async()=>{if(_){u(!0),f(null);try{let e={scrollback:p,fontSize:m,fontFamily:l.trim()};await rv.api.updateTerminalSettings(e),await s(),f("Settings saved"),setTimeout(()=>f(null),2e3)}catch(e){f(e instanceof Error?e.message:"Failed to save")}finally{u(!1)}}};return r?(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,O.jsx)(fm,{label:"Scrollback",mono:!0,hint:(0,O.jsxs)("span",{children:["Lines kept in buffer."," ",(0,O.jsxs)("span",{className:"font-mono text-foreground/70",children:[fM,"–",fF]})," · default ",(0,O.jsx)("span",{className:"font-mono text-foreground/70",children:rv.DEFAULT_TERMINAL_SETTINGS.scrollback})]}),children:(0,O.jsx)(ro,{type:"number",min:fM,max:fF,value:n,className:"font-mono text-[12.5px]",onChange:e=>{i(e.target.value),f(null)}})}),(0,O.jsx)(fm,{label:"Font size",mono:!0,hint:(0,O.jsxs)("span",{children:["Pixels."," ",(0,O.jsxs)("span",{className:"font-mono text-foreground/70",children:[fP,"–",fI]})," · default ",(0,O.jsx)("span",{className:"font-mono text-foreground/70",children:rv.DEFAULT_TERMINAL_SETTINGS.fontSize})]}),children:(0,O.jsx)(ro,{type:"number",min:fP,max:fI,value:a,className:"font-mono text-[12.5px]",onChange:e=>{o(e.target.value),f(null)}})})]}),(0,O.jsx)(fm,{label:"Font family",mono:!0,hint:"CSS font-family list. Use monospace fonts for column alignment.",children:(0,O.jsx)(ro,{value:l,className:"font-mono text-[12px]",onChange:e=>{c(e.target.value),f(null)},placeholder:rv.DEFAULT_TERMINAL_SETTINGS.fontFamily})}),h&&(0,O.jsx)(fx,{variant:"Settings saved"===h?"success":"error",icon:"Settings saved"===h?(0,O.jsx)(sJ,{className:"h-3.5 w-3.5"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5"}),children:h}),(0,O.jsxs)(fv,{children:[(0,O.jsx)(W.Button,{variant:"outline",size:"sm",onClick:()=>{i(String(rv.DEFAULT_TERMINAL_SETTINGS.scrollback)),o(String(rv.DEFAULT_TERMINAL_SETTINGS.fontSize)),c(rv.DEFAULT_TERMINAL_SETTINGS.fontFamily),f(null)},disabled:d,children:"Reset"}),(0,O.jsxs)(W.Button,{size:"sm",onClick:y,disabled:d||!_,children:[d&&(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save"]})]})]}):(0,O.jsx)("div",{className:"flex items-center justify-center py-6",children:(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin text-muted-foreground"})})}let{min:fL,max:fz}=rv.AGENT_PROCESS_SETTINGS_LIMITS;function fO(){let[e,r]=(0,$.useState)(String(rv.DEFAULT_AGENT_PROCESS_SETTINGS.maxResidentAgentProcesses)),[s,n]=(0,$.useState)(!1),[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=!1;return(0,rv.getAgentProcessSettings)().then(s=>{e||(r(String(s.maxResidentAgentProcesses)),n(!0))}).catch(r=>{e||(l(r instanceof Error?r.message:"Failed to load settings"),n(!0))}),()=>{e=!0}},[]);let c=parseInt(e,10),d=Number.isInteger(c)&&c>=fL&&c<=fz,u=async()=>{if(d){a(!0),l(null);try{let e=await (0,rv.updateAgentProcessSettings)({maxResidentAgentProcesses:c});r(String(e.maxResidentAgentProcesses)),l("Settings saved"),setTimeout(()=>l(null),2e3)}catch(e){l(e instanceof Error?e.message:"Failed to save")}finally{a(!1)}}};return s?(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsx)(fm,{label:"Resident agent processes",mono:!0,hint:(0,O.jsxs)("span",{children:["Live local or remote agent processes per server."," ",(0,O.jsxs)("span",{className:"font-mono text-foreground/70",children:[fL,"–",fz]})," · default ",(0,O.jsx)("span",{className:"font-mono text-foreground/70",children:rv.DEFAULT_AGENT_PROCESS_SETTINGS.maxResidentAgentProcesses})]}),children:(0,O.jsxs)("div",{className:"flex items-center gap-2 max-w-[220px]",children:[(0,O.jsx)(sb,{className:"h-4 w-4 text-muted-foreground"}),(0,O.jsx)(ro,{type:"number",min:fL,max:fz,value:e,className:"font-mono text-[12.5px]",onChange:e=>{r(e.target.value),l(null)}})]})}),o&&(0,O.jsx)(fx,{variant:"Settings saved"===o?"success":"error",icon:"Settings saved"===o?(0,O.jsx)(sJ,{className:"h-3.5 w-3.5"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5"}),children:o}),(0,O.jsxs)(fv,{children:[(0,O.jsx)(W.Button,{variant:"outline",size:"sm",onClick:()=>{r(String(rv.DEFAULT_AGENT_PROCESS_SETTINGS.maxResidentAgentProcesses)),l(null)},disabled:i,children:"Reset"}),(0,O.jsxs)(W.Button,{size:"sm",onClick:u,disabled:i||!d,children:[i&&(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save"]})]})]}):(0,O.jsx)("div",{className:"flex items-center justify-center py-6",children:(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin text-muted-foreground"})})}let f$=[{id:"appearance",label:"Appearance",Icon:hH},{id:"ai-chat",label:"AI Chat",Icon:hU},{id:"agents",label:"Agents",Icon:sb},{id:"terminal",label:"Terminal",Icon:hq},{id:"proxy",label:"Proxy",Icon:hW}];function fW(){let{config:e}=(0,hL.useAppConfig)(),[r]=(0,$.useState)(rv.getPersistedConfig),s=(e??r)?.authEnabled!==!1,n=s?f$.filter(e=>"proxy"!==e.id):f$;return(0,O.jsxs)("div",{className:"h-full flex flex-col overflow-hidden",children:[(0,O.jsx)(dh,{title:"Settings",description:"Theme, intelligence, terminal, and network preferences."}),(0,O.jsxs)(f_,{nav:n,children:[(0,O.jsx)(fp,{id:"appearance",label:"Appearance",description:"Visual surface for the workspace. Affects every view.",children:(0,O.jsx)(fS,{})}),(0,O.jsx)(fp,{id:"ai-chat",label:"AI Chat",description:"Provider, credentials, and default model used for the orchestrator chat.",children:(0,O.jsx)(fD,{})}),(0,O.jsx)(fp,{id:"agents",label:"Agents",description:"Resident coding-agent process limits per workspace branch.",children:(0,O.jsx)(fO,{})}),(0,O.jsx)(fp,{id:"terminal",label:"Terminal",description:"Buffer size and typography for the executor terminal.",children:(0,O.jsx)(fB,{})}),!s&&(0,O.jsx)(fp,{id:"proxy",label:"Proxy",description:"Outbound network routing for AI providers and remote servers.",children:(0,O.jsx)(fA,{})})]})]})}let fH=(0,ew.default)("plug-zap",[["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m18 3-4 4h6l-4 4",key:"16psg9"}]]),fU=(0,ew.default)("key-round",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);var fq=e.i(710307);let fK=(0,ew.default)("refresh-cw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]),fV={name:""};function fY(){let[e,r]=(0,$.useState)([]),[s,n]=(0,$.useState)(!0),[i,a]=(0,$.useState)(""),[o,l]=(0,$.useState)(!1),[c,d]=(0,$.useState)(null),[u,h]=(0,$.useState)(fV),[f,p]=(0,$.useState)(""),[m,g]=(0,$.useState)(!1),[x,v]=(0,$.useState)(null),[_,y]=(0,$.useState)(!1),[b,w]=(0,$.useState)({}),[S,j]=(0,$.useState)({}),[C,k]=(0,$.useState)(null),[N,E]=(0,$.useState)(null),[D,R]=(0,$.useState)(null),[A,T]=(0,$.useState)(!1),[M,F]=(0,$.useState)(!1),[P,I]=(0,$.useState)(!1),[B,L]=(0,$.useState)(!1),z=(0,$.useRef)(null),H=(0,$.useCallback)(async()=>{try{let e=await rv.api.getRemoteServers();r(e),a("")}catch(e){a(e instanceof Error?e.message:"Failed to load servers")}finally{n(!1)}},[]);(0,$.useEffect)(()=>{H()},[H]),(0,$.useEffect)(()=>{let e=setInterval(H,15e3),r=()=>H();return window.addEventListener("focus",r),()=>{clearInterval(e),window.removeEventListener("focus",r)}},[H]);let U=async()=>{if(!u.name.trim())return void p("Name is required");g(!0),p("");try{c?u.name.trim()!==c.name&&await rv.api.updateRemoteServer(c.id,{name:u.name.trim()}):await rv.api.createRemoteServer({name:u.name.trim()}),l(!1),await H()}catch(e){p(e instanceof Error?e.message:"Failed to save server")}finally{g(!1)}},q=async()=>{if(x){y(!0);try{await rv.api.deleteRemoteServer(x.id),v(null),await H()}catch(e){p(e instanceof Error?e.message:"Failed to delete server")}finally{y(!1)}}},K=async e=>{w(r=>({...r,[e.id]:"testing"})),j(r=>{let s={...r};return delete s[e.id],s});try{let r=await rv.api.testRemoteServer(e.id);w(s=>({...s,[e.id]:r.success?"success":"error"})),r.success||j(r=>({...r,[e.id]:"Connection failed"}))}catch(r){w(r=>({...r,[e.id]:"error"})),j(s=>({...s,[e.id]:r instanceof Error?r.message:"Test failed"}))}},V=async e=>{z.current=e.id,k(e),E(null),R(null),F(!1),L(!1),I(!1),T(!0);try{let r=await rv.api.getRemoteServerConnectToken(e.id);if(z.current!==e.id)return;E(r.token),R(r.connectCommand)}catch(r){if(z.current!==e.id)return;z.current=null,p(r instanceof Error?r.message:"Failed to load token"),k(null)}finally{z.current===e.id&&T(!1)}},Y=async e=>{I(!0),F(!1);try{let r=await rv.api.rotateRemoteServerConnectToken(e.id);z.current===e.id&&(E(r.token),R(r.connectCommand),L(!1)),await H()}catch(e){a(e instanceof Error?e.message:"Failed to rotate token")}finally{z.current===e.id&&I(!1)}},G=async e=>{try{await rv.api.revokeRemoteServerConnectToken(e.id),await H()}catch(e){a(e instanceof Error?e.message:"Failed to revoke token")}},X=async(e,s)=>{try{let n=await rv.api.updateRemoteServer(e.id,{crossRemoteAccess:s});r(e=>e.map(e=>e.id===n.id?n:e))}catch(e){a(e instanceof Error?e.message:"Failed to update access")}},J="Update the vibedeckx package on the worker machine, then restart `vibedeckx connect`.";return s?(0,O.jsx)("div",{className:"flex items-center justify-center py-8",children:(0,O.jsx)(sj,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between",children:[(0,O.jsxs)("div",{children:[(0,O.jsx)("h3",{className:"text-sm font-medium",children:"Remote Servers"}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"Manage globally available remote servers"})]}),(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:()=>{d(null),h(fV),p(""),l(!0)},children:[(0,O.jsx)(eS,{className:"h-4 w-4 mr-1.5"}),"Add Server"]})]}),i&&(0,O.jsx)("p",{className:"text-sm text-red-500",children:i}),0===e.length?(0,O.jsxs)("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[(0,O.jsx)(ry,{className:"h-8 w-8 mx-auto mb-2 opacity-40"}),"No remote servers configured"]}):(0,O.jsxs)(uk,{children:[(0,O.jsx)(uN,{children:(0,O.jsxs)(uD,{children:[(0,O.jsx)(uR,{children:"Name"}),(0,O.jsx)(uR,{children:"Status"}),(0,O.jsx)(uR,{children:"Cross-remote access"}),(0,O.jsx)(uR,{className:"w-[180px] text-right",children:"Actions"})]})}),(0,O.jsx)(uE,{children:e.map(e=>{let r,s;return(0,O.jsxs)(uD,{children:[(0,O.jsx)(uA,{className:"font-medium",children:(0,O.jsxs)("div",{className:"flex items-center",children:[(r="online"===e.status,(0,O.jsx)("span",{className:`inline-block h-2.5 w-2.5 rounded-full mr-2 ${r?"bg-green-500":"bg-gray-400"}`,title:r?"Online":"Offline"})),e.name]})}),(0,O.jsxs)(uA,{className:"font-mono text-xs text-muted-foreground",children:[(0,O.jsx)("div",{children:"online"===e.status?"Connected":"Waiting for connection..."}),(e=>{if(!e.worker_version)return e.last_connected_at?(0,O.jsx)("div",{className:"mt-0.5 text-[11px] text-muted-foreground",title:J,children:"version unknown · upgrade recommended"}):null;let r="behind-min"===e.worker_update_status?(0,O.jsx)("span",{className:"text-red-500",title:J,children:"upgrade required"}):"behind-latest"===e.worker_update_status?(0,O.jsxs)("span",{className:"text-amber-500",title:J,children:["update available → v",e.latest_worker_version]}):null;return(0,O.jsxs)("div",{className:"mt-0.5 text-[11px]",children:[(0,O.jsxs)("span",{className:"text-muted-foreground",children:["v",e.worker_version]}),r&&(0,O.jsx)("span",{className:"ml-1.5",children:r})]})})(e)]}),(0,O.jsx)(uA,{children:(0,O.jsxs)(hw,{value:e.cross_remote_access,onValueChange:r=>X(e,r),children:[(0,O.jsx)(hj,{className:"w-[190px] text-[12.5px]",children:(0,O.jsx)(hS,{})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"off",className:"text-[12.5px]",children:"Off"}),(0,O.jsx)(hk,{value:"read",className:"text-[12.5px]",children:"Diagnostic read"}),(0,O.jsx)(hk,{value:"exec",className:"text-[12.5px]",children:"Command execution"})]})]})}),(0,O.jsxs)(uA,{className:"text-right",children:[(0,O.jsxs)("div",{className:"flex items-center justify-end gap-1",children:[(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:()=>V(e),title:"Connect token",className:"h-8 w-8",children:(0,O.jsx)(fU,{className:"h-4 w-4"})}),(s=b[e.id]||"idle",(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:()=>K(e),disabled:"testing"===s,title:"Test connection",className:"h-8 w-8",children:"testing"===s?(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"}):"success"===s?(0,O.jsx)(rf.Check,{className:"h-4 w-4 text-green-500"}):"error"===s?(0,O.jsx)(t7,{className:"h-4 w-4 text-red-500"}):(0,O.jsx)(fH,{className:"h-4 w-4"})})),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:()=>{d(e),h({name:e.name}),p(""),l(!0)},title:"Edit server",className:"h-8 w-8",children:(0,O.jsx)(rg,{className:"h-4 w-4"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:()=>v(e),title:"Delete server",className:"h-8 w-8 text-destructive hover:text-destructive",children:(0,O.jsx)(rc,{className:"h-4 w-4"})})]}),S[e.id]&&(0,O.jsx)("p",{className:"text-xs text-red-500 mt-1 text-right",children:S[e.id]})]})]},e.id)})})]}),(0,O.jsxs)("p",{className:"text-xs text-muted-foreground",children:["When enabled, agents running on your other machines can reach this one.",(0,O.jsx)("strong",{children:" Diagnostic read"})," exposes files, directories and the process list — including any secrets in logs and config files.",(0,O.jsx)("strong",{children:" Command execution"})," additionally allows arbitrary shell commands. Off by default."]}),(0,O.jsx)(t8,{open:o,onOpenChange:l,children:(0,O.jsxs)(rr,{className:"sm:max-w-md",children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:c?"Edit Server":"Add Remote Server"}),(0,O.jsx)(ra,{children:c?"Update the server name.":"Add a new remote server, then generate a connect token and run the connect command on the remote machine."})]}),(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Name"}),(0,O.jsx)(ro,{value:u.name,onChange:e=>{h(r=>({...r,name:e.target.value})),p("")},placeholder:"My Remote Server"})]}),f&&(0,O.jsx)("p",{className:"text-sm text-red-500",children:f})]}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),(0,O.jsxs)(W.Button,{onClick:U,disabled:m,children:[m&&(0,O.jsx)(sj,{className:"h-4 w-4 mr-1.5 animate-spin"}),c?"Save Changes":"Add Server"]})]})]})}),(0,O.jsx)(t8,{open:null!==C,onOpenChange:e=>{e||(z.current=null,k(null),E(null),R(null),L(!1))},children:(0,O.jsxs)(rr,{className:"sm:max-w-lg",children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:"Connect Token"}),(0,O.jsxs)(ra,{children:["Use this token to connect a remote node to"," ",(0,O.jsx)("span",{className:"font-semibold",children:C?.name}),". It stays the same every time you open this dialog — rotate it to issue a replacement."]})]}),A?(0,O.jsx)("div",{className:"flex items-center justify-center py-4",children:(0,O.jsx)(sj,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):N?(0,O.jsx)("div",{className:"space-y-4",children:(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Connect Command"}),(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsx)(ro,{readOnly:!0,value:D||"",className:"font-mono text-xs"}),(0,O.jsx)(W.Button,{variant:"outline",size:"icon",className:"shrink-0",onClick:()=>{var e;return e=D||"",void(navigator.clipboard.writeText(e),F(!0),setTimeout(()=>F(!1),2e3))},title:"Copy command",children:M?(0,O.jsx)(rf.Check,{className:"h-4 w-4 text-green-500"}):(0,O.jsx)(fq.Copy,{className:"h-4 w-4"})})]}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"Run this command on the remote machine to establish the reverse connection."}),B&&(0,O.jsx)("p",{className:"text-xs text-destructive",children:"Rotating invalidates the current token immediately. Any worker still using it will fail to reconnect until you re-run the new command."})]})}):null,(0,O.jsxs)(rn,{children:[N&&C&&(0,O.jsxs)("div",{className:"mr-auto flex items-center gap-2",children:[(0,O.jsxs)(W.Button,{variant:"outline",disabled:P,onClick:()=>{B?Y(C):L(!0)},children:[P?(0,O.jsx)(sj,{className:"mr-2 h-4 w-4 animate-spin"}):(0,O.jsx)(fK,{className:"mr-2 h-4 w-4"}),B?"Confirm rotate":"Rotate Token"]}),(0,O.jsx)(W.Button,{variant:"outline",className:"text-destructive hover:text-destructive",onClick:()=>{G(C),z.current=null,k(null),E(null)},children:"Revoke Token"})]}),(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>{z.current=null,k(null),E(null),R(null),L(!1)},children:"Close"})]})]})}),(0,O.jsx)(t8,{open:null!==x,onOpenChange:e=>{e||v(null)},children:(0,O.jsxs)(rr,{className:"sm:max-w-sm",children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:"Delete Server"}),(0,O.jsxs)(ra,{children:["Are you sure you want to delete"," ",(0,O.jsx)("span",{className:"font-semibold",children:x?.name}),"? This will also remove it from any projects that reference it."]})]}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>v(null),children:"Cancel"}),(0,O.jsxs)(W.Button,{variant:"destructive",onClick:q,disabled:_,children:[_&&(0,O.jsx)(sj,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Delete"]})]})]})})]})}function fG({projectId:e,project:r,open:s,onOpenChange:n,onWorktreeCreated:i}){let[a,o]=(0,$.useState)(""),[l,c]=(0,$.useState)(!1),[d,u]=(0,$.useState)(null),[h,f]=(0,$.useState)(null),[p,m]=(0,$.useState)(!0),[g,x]=(0,$.useState)(!0),[v,_]=(0,$.useState)([]),[y,b]=(0,$.useState)([]),[w,S]=(0,$.useState)("main"),[j,C]=(0,$.useState)("main"),[k,N]=(0,$.useState)(!1),E=!!(r.path&&r.remote_path);(0,$.useEffect)(()=>{s&&(N(!0),E?Promise.all([rv.api.getProjectBranches(e,"local"),rv.api.getProjectBranches(e,"remote")]).then(([e,r])=>{_(e),b(r),S(e.includes("main")?"main":e[0]||"main"),C(r.includes("main")?"main":r[0]||"main"),N(!1)}):rv.api.getProjectBranches(e).then(e=>{_(e),S(e.includes("main")?"main":e[0]||"main"),N(!1)}))},[s,e,E]);let D=async()=>{if(a.trim()){c(!0),u(null),f(null);try{let r;E&&(r=[],p&&r.push("local"),g&&r.push("remote"));let s=await rv.api.createWorktree(e,a.trim(),r,w,E?j:void 0);if(s.partialSuccess){let e,r=s.results?.remote?.success===!1?"remote":"local",n=s.results?.[r],i=n?.error||"Unknown error",a=n?.errorCode,o=n?.requestId;switch(a){case"timeout":e="Connection to remote server timed out. The remote server may be slow or unreachable.";break;case"network_error":e="Remote server is not connected. Run the connect command on the remote machine (Settings → Remote Servers → connect token).";break;case"auth_error":e="Authentication failed with remote server. Copy the current connect command (Settings → Remote Servers → connect token) and re-run it on the remote machine; rotate the token only if you need to replace it.";break;case"server_error":e=`Remote server returned an error: ${i}`;break;default:e=`Worktree created locally, but ${r} creation failed: ${i}`}o&&(e+=` (Request ID: ${o})`),f(e)}i(s.worktree.branch),s.partialSuccess||(n(!1),o(""))}catch(e){u(e instanceof Error?e.message:"Failed to create worktree")}finally{c(!1)}}},R=e=>{e||(o(""),u(null),f(null),m(!0),x(!0),_([]),b([]),S("main"),C("main")),n(e)},A=(e,r,s,n)=>(0,O.jsxs)(hw,{value:r,onValueChange:s,disabled:n||k,children:[(0,O.jsx)(hj,{size:"sm",children:(0,O.jsx)(hS,{placeholder:k?"Loading...":"Select branch"})}),(0,O.jsx)(hC,{children:e.map(e=>(0,O.jsx)(hk,{value:e,children:e},e))})]});return(0,O.jsx)(t8,{open:s,onOpenChange:R,children:(0,O.jsxs)(rr,{children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:"Create New Worktree"}),(0,O.jsx)(ra,{children:"Create a new branch based on an existing branch"})]}),(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{htmlFor:"branch-name",className:"text-sm font-medium",children:"Branch Name"}),(0,O.jsx)(ro,{id:"branch-name",placeholder:"feature/my-feature",value:a,onChange:e=>o(e.target.value),disabled:l,onKeyDown:e=>{"Enter"===e.key&&a.trim()&&(!E||p||g)&&D()}})]}),E?(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Create On"}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsxs)("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[(0,O.jsx)("input",{type:"checkbox",checked:p,onChange:e=>{(e.target.checked||g)&&m(e.target.checked)},disabled:l,className:"h-4 w-4 rounded border-input accent-primary"}),(0,O.jsx)("span",{children:"Local"}),(0,O.jsx)("span",{className:"text-muted-foreground truncate text-xs",children:r.path})]}),p&&v.length>0&&(0,O.jsxs)("div",{className:"ml-6",children:[(0,O.jsx)("label",{className:"text-xs text-muted-foreground",children:"Base Branch"}),A(v,w,S,l)]}),(0,O.jsxs)("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[(0,O.jsx)("input",{type:"checkbox",checked:g,onChange:e=>{(e.target.checked||p)&&x(e.target.checked)},disabled:l,className:"h-4 w-4 rounded border-input accent-primary"}),(0,O.jsx)("span",{children:"Remote"}),(0,O.jsx)("span",{className:"text-muted-foreground truncate text-xs",children:r.remote_path})]}),g&&y.length>0&&(0,O.jsxs)("div",{className:"ml-6",children:[(0,O.jsx)("label",{className:"text-xs text-muted-foreground",children:"Base Branch"}),A(y,j,C,l)]})]})]}):v.length>0&&(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Base Branch"}),A(v,w,S,l)]}),h&&(0,O.jsx)("div",{className:"text-sm text-yellow-600 dark:text-yellow-500 bg-yellow-500/10 px-3 py-2 rounded-md",children:h}),d&&(0,O.jsx)("div",{className:"text-sm text-destructive bg-destructive/10 px-3 py-2 rounded-md",children:d})]}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>R(!1),disabled:l,children:"Cancel"}),(0,O.jsx)(W.Button,{onClick:D,disabled:!a.trim()||l||E&&!p&&!g,children:l?"Creating...":"Create"})]})]})})}function fX({projectId:e,worktree:r,open:s,onOpenChange:n,onWorktreeDeleted:i}){let[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(null),[d,u]=(0,$.useState)(null),h=async()=>{if(r){o(!0),c(null),u(null);try{let s=await rv.api.deleteWorktree(e,r.branch);if(s.partialSuccess){let e=s.results?.remote?.error||"Unknown error";u(`Local worktree deleted, but remote deletion failed: ${e}`)}i(),s.partialSuccess||n(!1)}catch(e){c(e instanceof Error?e.message:"Failed to delete worktree")}finally{o(!1)}}},f=e=>{e||(c(null),u(null)),n(e)};return(0,O.jsx)(t8,{open:s,onOpenChange:f,children:(0,O.jsxs)(rr,{children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:"Delete Worktree"}),(0,O.jsx)(ra,{children:"Are you sure you want to delete this worktree?"})]}),r&&(0,O.jsx)("div",{className:"space-y-2",children:(0,O.jsxs)("div",{className:"text-sm",children:[(0,O.jsx)("span",{className:"font-medium",children:"Branch:"})," ",(0,O.jsx)("span",{className:"text-muted-foreground",children:r.branch})]})}),d&&(0,O.jsx)("div",{className:"text-sm text-yellow-600 dark:text-yellow-500 bg-yellow-500/10 px-3 py-2 rounded-md",children:d}),l&&(0,O.jsx)("div",{className:"text-sm text-destructive bg-destructive/10 px-3 py-2 rounded-md",children:l}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>f(!1),disabled:a,children:"Cancel"}),(0,O.jsx)(W.Button,{variant:"destructive",onClick:h,disabled:a,children:a?"Deleting...":"Delete"})]})]})})}e.i(247755);var fJ=e.i(642098);function fZ(){let{config:e}=(0,hL.useAppConfig)();return e?.authEnabled?(0,O.jsx)("div",{className:"flex items-center",children:(0,O.jsx)(fJ.UserButton,{appearance:{elements:{avatarBox:"h-7 w-7 ring-1 ring-border/60"}}})}):null}var fQ=e.i(183663),f0="Collapsible",[f1,f2]=q(f0),[f5,f3]=f1(f0),f4=$.forwardRef((e,r)=>{let{__scopeCollapsible:s,open:n,defaultOpen:i,disabled:a,onOpenChange:o,...l}=e,[c,d]=G({prop:n,defaultProp:i??!1,onChange:o,caller:f0});return(0,O.jsx)(f5,{scope:s,disabled:a,contentId:ek(),open:c,onOpenToggle:$.useCallback(()=>d(e=>!e),[d]),children:(0,O.jsx)(er.div,{"data-state":pt(c),"data-disabled":a?"":void 0,...l,ref:r})})});f4.displayName=f0;var f6="CollapsibleTrigger",f7=$.forwardRef((e,r)=>{let{__scopeCollapsible:s,...n}=e,i=f3(f6,s);return(0,O.jsx)(er.button,{type:"button","aria-controls":i.contentId,"aria-expanded":i.open||!1,"data-state":pt(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...n,ref:r,onClick:K(e.onClick,i.onOpenToggle)})});f7.displayName=f6;var f8="CollapsibleContent",f9=$.forwardRef((e,r)=>{let{forceMount:s,...n}=e,i=f3(f8,e.__scopeCollapsible);return(0,O.jsx)(Z,{present:s||i.open,children:({present:e})=>(0,O.jsx)(pe,{...n,ref:r,present:e})})});f9.displayName=f8;var pe=$.forwardRef((e,r)=>{let{__scopeCollapsible:s,present:n,children:i,...a}=e,o=f3(f8,s),[l,c]=$.useState(n),d=$.useRef(null),u=(0,U.useComposedRefs)(r,d),h=$.useRef(0),f=h.current,p=$.useRef(0),m=p.current,g=o.open||l,x=$.useRef(g),v=$.useRef(void 0);return $.useEffect(()=>{let e=requestAnimationFrame(()=>x.current=!1);return()=>cancelAnimationFrame(e)},[]),V(()=>{let e=d.current;if(e){v.current=v.current||{transitionDuration:e.style.transitionDuration,animationName:e.style.animationName},e.style.transitionDuration="0s",e.style.animationName="none";let r=e.getBoundingClientRect();h.current=r.height,p.current=r.width,x.current||(e.style.transitionDuration=v.current.transitionDuration,e.style.animationName=v.current.animationName),c(n)}},[o.open,n]),(0,O.jsx)(er.div,{"data-state":pt(o.open),"data-disabled":o.disabled?"":void 0,id:o.contentId,hidden:!g,...a,ref:u,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":m?`${m}px`:void 0,...e.style},children:g&&i})});function pt(e){return e?"open":"closed"}function pr({...e}){return(0,O.jsx)(f4,{"data-slot":"collapsible",...e})}function ps({...e}){return(0,O.jsx)(f7,{"data-slot":"collapsible-trigger",...e})}function pn({...e}){return(0,O.jsx)(f9,{"data-slot":"collapsible-content",...e})}let pi=(0,ew.default)("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]),pa=(0,ew.default)("ban",[["path",{d:"M4.929 4.929 19.07 19.071",key:"196cmz"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);var po=e.i(885101),pl=Object.defineProperty,pc=Object.getOwnPropertyDescriptor,pd=(e,r,s,n)=>{for(var i,a=n>1?void 0:n?pc(r,s):r,o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n?i(r,s,a):i(a))||a);return n&&a&&pl(r,s,a),a},pu=(e,r)=>(s,n)=>r(s,n,e),ph="Terminal input",pf="Too much output to announce, navigate to rows manually to read";function pp(e,r,s,n){var i;i=e=e.replace(/\r?\n/g,"\r"),e=s.decPrivateModes.bracketedPasteMode&&!0!==n.rawOptions.ignoreBracketedPasteMode?"\x1b[200~"+i+"\x1b[201~":i,s.triggerDataEvent(e,!0),r.value=""}function pm(e,r,s){let n=s.getBoundingClientRect(),i=e.clientX-n.left-10,a=e.clientY-n.top-10;r.style.width="20px",r.style.height="20px",r.style.left=`${i}px`,r.style.top=`${a}px`,r.style.zIndex="1000",r.focus()}function pg(e,r,s,n,i){pm(e,r,s),i&&n.rightClickSelect(e),r.value=n.selectionText,r.select()}function px(e){return e>65535?String.fromCharCode(((e-=65536)>>10)+55296)+String.fromCharCode(e%1024+56320):String.fromCharCode(e)}function pv(e,r=0,s=e.length){let n="";for(let i=r;i<s;++i){let r=e[i];r>65535?(r-=65536,n+=String.fromCharCode((r>>10)+55296)+String.fromCharCode(r%1024+56320)):n+=String.fromCharCode(r)}return n}var p_=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,r){let s=e.length;if(!s)return 0;let n=0,i=0;if(this._interim){let s=e.charCodeAt(i++);56320<=s&&s<=57343?r[n++]=(this._interim-55296)*1024+s-56320+65536:(r[n++]=this._interim,r[n++]=s),this._interim=0}for(let a=i;a<s;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=s)return this._interim=i,n;let o=e.charCodeAt(a);56320<=o&&o<=57343?r[n++]=(i-55296)*1024+o-56320+65536:(r[n++]=i,r[n++]=o);continue}65279!==i&&(r[n++]=i)}return n}},py=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,r){let s=e.length;if(!s)return 0;let n=0,i,a,o,l,c=0,d=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(224&a)==192?31:(240&a)==224?15:7;let o=0,l;for(;(l=63&this.interim[++o])&&o<4;)a<<=6,a|=l;let c=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,u=c-o;for(;d<u;){if(d>=s)return 0;if((192&(l=e[d++]))!=128){d--,i=!0;break}this.interim[o++]=l,a<<=6,a|=63&l}i||(2===c?a<128?d--:r[n++]=a:3===c?a<2048||a>=55296&&a<=57343||65279===a||(r[n++]=a):a<65536||a>1114111||(r[n++]=a)),this.interim.fill(0)}let u=s-4,h=d;for(;h<s;){for(;h<u&&!(128&(i=e[h]))&&!(128&(a=e[h+1]))&&!(128&(o=e[h+2]))&&!(128&(l=e[h+3]));)r[n++]=i,r[n++]=a,r[n++]=o,r[n++]=l,h+=4;if((i=e[h++])<128)r[n++]=i;else if((224&i)==192){if(h>=s)return this.interim[0]=i,n;if((192&(a=e[h++]))!=128||(c=(31&i)<<6|63&a)<128){h--;continue}r[n++]=c}else if((240&i)==224){if(h>=s)return this.interim[0]=i,n;if((192&(a=e[h++]))!=128){h--;continue}if(h>=s)return this.interim[0]=i,this.interim[1]=a,n;if((192&(o=e[h++]))!=128){h--;continue}if((c=(15&i)<<12|(63&a)<<6|63&o)<2048||c>=55296&&c<=57343||65279===c)continue;r[n++]=c}else if((248&i)==240){if(h>=s)return this.interim[0]=i,n;if((192&(a=e[h++]))!=128){h--;continue}if(h>=s)return this.interim[0]=i,this.interim[1]=a,n;if((192&(o=e[h++]))!=128){h--;continue}if(h>=s)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,n;if((192&(l=e[h++]))!=128){h--;continue}if((c=(7&i)<<18|(63&a)<<12|(63&o)<<6|63&l)<65536||c>1114111)continue;r[n++]=c}}return n}},pb=class e{constructor(){this.fg=0,this.bg=0,this.extended=new pw}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){let r=new e;return r.fg=this.fg,r.bg=this.bg,r.extended=this.extended.clone(),r}isInverse(){return 0x4000000&this.fg}isBold(){return 0x8000000&this.fg}isUnderline(){return this.hasExtendedAttrs()&&0!==this.extended.underlineStyle?1:0x10000000&this.fg}isBlink(){return 0x20000000&this.fg}isInvisible(){return 0x40000000&this.fg}isItalic(){return 0x4000000&this.bg}isDim(){return 0x8000000&this.bg}isStrikethrough(){return 0x80000000&this.fg}isProtected(){return 0x20000000&this.bg}isOverline(){return 0x40000000&this.bg}getFgColorMode(){return 0x3000000&this.fg}getBgColorMode(){return 0x3000000&this.bg}isFgRGB(){return(0x3000000&this.fg)==0x3000000}isBgRGB(){return(0x3000000&this.bg)==0x3000000}isFgPalette(){return(0x3000000&this.fg)==0x1000000||(0x3000000&this.fg)==0x2000000}isBgPalette(){return(0x3000000&this.bg)==0x1000000||(0x3000000&this.bg)==0x2000000}isFgDefault(){return(0x3000000&this.fg)==0}isBgDefault(){return(0x3000000&this.bg)==0}isAttributeDefault(){return 0===this.fg&&0===this.bg}getFgColor(){switch(0x3000000&this.fg){case 0x1000000:case 0x2000000:return 255&this.fg;case 0x3000000:return 0xffffff&this.fg;default:return -1}}getBgColor(){switch(0x3000000&this.bg){case 0x1000000:case 0x2000000:return 255&this.bg;case 0x3000000:return 0xffffff&this.bg;default:return -1}}hasExtendedAttrs(){return 0x10000000&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-0x10000001:this.bg|=0x10000000}getUnderlineColor(){if(0x10000000&this.bg&&~this.extended.underlineColor)switch(0x3000000&this.extended.underlineColor){case 0x1000000:case 0x2000000:return 255&this.extended.underlineColor;case 0x3000000:return 0xffffff&this.extended.underlineColor}return this.getFgColor()}getUnderlineColorMode(){return 0x10000000&this.bg&&~this.extended.underlineColor?0x3000000&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 0x10000000&this.bg&&~this.extended.underlineColor?(0x3000000&this.extended.underlineColor)==0x3000000:this.isFgRGB()}isUnderlineColorPalette(){return 0x10000000&this.bg&&~this.extended.underlineColor?(0x3000000&this.extended.underlineColor)==0x1000000||(0x3000000&this.extended.underlineColor)==0x2000000:this.isFgPalette()}isUnderlineColorDefault(){return 0x10000000&this.bg&&~this.extended.underlineColor?(0x3000000&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 0x10000000&this.fg?0x10000000&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},pw=class e{constructor(e=0,r=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=r}get ext(){return this._urlId?-0x1c000001&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(0x1c000000&this._ext)>>26}set underlineStyle(e){this._ext&=-0x1c000001,this._ext|=e<<26&0x1c000000}get underlineColor(){return 0x3ffffff&this._ext}set underlineColor(e){this._ext&=-0x4000000,this._ext|=0x3ffffff&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(0xe0000000&this._ext)>>29;return e<0?0xfffffff8^e:e}set underlineVariantOffset(e){this._ext&=0x1fffffff,this._ext|=e<<29&0xe0000000}clone(){return new e(this._ext,this._urlId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId}},pS=class e extends pb{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new pw,this.combinedData=""}static fromCharData(r){let s=new e;return s.setFromCharData(r),s}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?px(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[0],this.bg=0;let r=!1;if(e[1].length>2)r=!0;else if(2===e[1].length){let s=e[1].charCodeAt(0);if(55296<=s&&s<=56319){let n=e[1].charCodeAt(1);56320<=n&&n<=57343?this.content=(s-55296)*1024+n-56320+65536|e[2]<<22:r=!0}else r=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;r&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},pj="di$target",pC="di$dependencies",pk=new Map;function pN(e){if(pk.has(e))return pk.get(e);let r=function(e,s,n){var i,a,o;if(3!=arguments.length)throw Error("@IServiceName-decorator can only be used to decorate a parameter");i=r,a=e,o=n,a[pj]===a?a[pC].push({id:i,index:o}):(a[pC]=[{id:i,index:o}],a[pj]=a)};return r._id=e,pk.set(e,r),r}var pE=pN("BufferService"),pD=pN("CoreMouseService"),pR=pN("CoreService"),pA=pN("CharsetService"),pT=pN("InstantiationService"),pM=pN("LogService"),pF=pN("OptionsService"),pP=pN("OscLinkService"),pI=pN("UnicodeService"),pB=pN("DecorationService"),pL=class{constructor(e,r,s){this._bufferService=e,this._optionsService=r,this._oscLinkService=s}provideLinks(e,r){let s=this._bufferService.buffer.lines.get(e-1);if(!s)return void r(void 0);let n=[],i=this._optionsService.rawOptions.linkHandler,a=new pS,o=s.getTrimmedLength(),l=-1,c=-1,d=!1;for(let r=0;r<o;r++)if(!(-1===c&&!s.hasContent(r))){if(s.loadCell(r,a),a.hasExtendedAttrs()&&a.extended.urlId)if(-1===c){c=r,l=a.extended.urlId;continue}else d=a.extended.urlId!==l;else -1!==c&&(d=!0);if(d||-1!==c&&r===o-1){let s=this._oscLinkService.getLinkData(l)?.uri;if(s){let a={start:{x:c+1,y:e},end:{x:r+ +(!d&&r===o-1),y:e}},l=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(s);["http:","https:"].includes(e.protocol)||(l=!0)}catch{l=!0}l||n.push({text:s,range:a,activate:(e,r)=>i?i.activate(e,r,a):function(e,r){if(confirm(`Do you want to navigate to ${r}?
11
+ For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return $.useEffect(()=>{document.getElementById(e.current?.getAttribute("aria-describedby"))||console.warn(r)},[r,e]),null};function lL({...e}){return(0,O.jsx)(lw,{"data-slot":"alert-dialog",...e})}function lz({...e}){return(0,O.jsx)(lS,{"data-slot":"alert-dialog-portal",...e})}function lO({className:e,...r}){return(0,O.jsx)(lj,{"data-slot":"alert-dialog-overlay",className:(0,ey.cn)("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...r})}function l$({className:e,...r}){return(0,O.jsxs)(lz,{children:[(0,O.jsx)(lO,{}),(0,O.jsx)(lD,{"data-slot":"alert-dialog-content",className:(0,ey.cn)("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...r})]})}function lW({className:e,...r}){return(0,O.jsx)("div",{"data-slot":"alert-dialog-header",className:(0,ey.cn)("flex flex-col gap-2 text-center sm:text-left",e),...r})}function lH({className:e,...r}){return(0,O.jsx)("div",{"data-slot":"alert-dialog-footer",className:(0,ey.cn)("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...r})}function lU({className:e,...r}){return(0,O.jsx)(lA,{"data-slot":"alert-dialog-title",className:(0,ey.cn)("text-lg font-semibold",e),...r})}function lq({className:e,...r}){return(0,O.jsx)(lM,{"data-slot":"alert-dialog-description",className:(0,ey.cn)("text-muted-foreground text-sm",e),...r})}function lK({className:e,...r}){return(0,O.jsx)(lF,{className:(0,ey.cn)((0,W.buttonVariants)(),e),...r})}function lV({className:e,...r}){return(0,O.jsx)(lI,{className:(0,ey.cn)((0,W.buttonVariants)({variant:"outline"}),e),...r})}let lY={task:"Task",workspace:"Workspace",agent_session:"Agent session",schedule:"Schedule",schedule_run:"Schedule run"};function lG({projectId:e,currentThreadId:r,threads:s,contextRefs:n,onNewThread:i,onSelectThread:a,onRenameThread:o,onArchiveThread:l,onDeleteThread:c,onOpenContext:d,newThreadPending:u=!1,className:h}){let[f,p]=(0,$.useState)(!0),[m,g]=(0,$.useState)(!0),[x,v]=(0,$.useState)(!1),[_,y]=(0,$.useState)(null),[b,w]=(0,$.useState)(null),[S,j]=(0,$.useState)(""),[C,k]=(0,$.useState)(null),[N,E]=(0,$.useState)(null),[D,R]=(0,$.useState)(new Set),[A,T]=(0,$.useState)(null),M=(0,$.useRef)(new Set),F=(0,$.useRef)(null),P=s.filter(e=>null===e.archived_at),I=!!b&&D.has(`rename:${b.id}`),B=!!N&&D.has(`delete:${N.id}`),L=!!C&&D.has(`archive:${C.id}`);(0,$.useEffect)(()=>{if(!_)return;F.current?.querySelector('[role="menuitem"]')?.focus();let e=e=>{"Escape"===e.key&&y(null)},r=e=>{F.current?.contains(e.target)||y(null)};return document.addEventListener("keydown",e),document.addEventListener("pointerdown",r),()=>{document.removeEventListener("keydown",e),document.removeEventListener("pointerdown",r)}},[_]);let z=async(e,r,s)=>{if(!M.current.has(e)){M.current.add(e),R(r=>new Set(r).add(e)),T(null);try{await r(),s()}catch(e){T(e instanceof Error?e.message:"Project Chat action failed")}finally{M.current.delete(e),R(r=>{let s=new Set(r);return s.delete(e),s})}}};return(0,O.jsxs)("aside",{"data-testid":"project-chat-rail","data-project-chat-column":!0,className:(0,ey.cn)("flex h-full w-[300px] shrink-0 flex-col overflow-hidden border-l border-border bg-muted/10",h),"aria-label":"Project Chat threads and context",children:[(0,O.jsxs)("section",{className:"flex min-h-0 flex-col border-b border-border/70",children:[(0,O.jsxs)("div",{className:"flex h-11 shrink-0 items-center gap-1 px-3",children:[(0,O.jsxs)("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-1.5 rounded px-1 py-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>p(e=>!e),"aria-expanded":f,children:[f?(0,O.jsx)(ns,{className:"size-4"}):(0,O.jsx)(a3,{className:"size-4"}),(0,O.jsx)("h2",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Chat Threads"})]}),(0,O.jsx)(W.Button,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"New thread",disabled:u,onClick:()=>void i(),children:(0,O.jsx)(eS,{className:"size-4","aria-hidden":"true"})})]}),f?(0,O.jsxs)("div",{className:"space-y-1 px-2 pb-3",children:[P.slice(0,5).map(e=>{let s=sM(e),n=e.id===r;return(0,O.jsxs)("div",{"data-testid":"thread-row",className:(0,ey.cn)("relative flex items-center rounded-md",n?"bg-accent":"hover:bg-muted"),children:[(0,O.jsx)("button",{type:"button","aria-label":`Open thread: ${s}`,"aria-current":n?"page":void 0,onClick:()=>a(e.id),className:"min-w-0 flex-1 truncate px-2 py-2 text-left text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:s}),(0,O.jsx)(W.Button,{type:"button",variant:"ghost",size:"icon-sm","aria-label":`Thread actions: ${s}`,"aria-expanded":_===e.id,"aria-haspopup":"menu","aria-controls":_===e.id?`thread-actions-${e.id}`:void 0,onClick:()=>y(r=>r===e.id?null:e.id),children:(0,O.jsx)(lx,{className:"size-4","aria-hidden":"true"})}),_===e.id?(0,O.jsxs)("div",{ref:F,id:`thread-actions-${e.id}`,role:"menu","aria-label":`Actions for ${s}`,className:"absolute right-1 top-9 z-20 w-40 rounded-md border bg-popover p-1 text-popover-foreground shadow-md",children:[(0,O.jsxs)("button",{type:"button",role:"menuitem",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted",onClick:()=>{y(null),T(null),w(e),j(s)},children:[(0,O.jsx)(rg,{className:"size-3.5"})," Rename thread"]}),(0,O.jsxs)("button",{type:"button",role:"menuitem",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted",onClick:()=>{y(null),T(null),k(e)},children:[(0,O.jsx)(sN,{className:"size-3.5"})," Archive thread"]}),(0,O.jsxs)("button",{type:"button",role:"menuitem",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm text-destructive hover:bg-destructive/10",onClick:()=>{y(null),T(null),E(e)},children:[(0,O.jsx)(rc,{className:"size-3.5"})," Delete thread"]})]}):null]},e.id)}),(0,O.jsx)(W.Button,{type:"button",variant:"ghost",size:"sm","aria-label":"View all threads",className:"w-full",onClick:()=>v(!0),children:"View all"})]}):null]}),(0,O.jsxs)("section",{className:"flex min-h-0 flex-1 flex-col",children:[(0,O.jsxs)("button",{type:"button",className:"flex h-11 shrink-0 items-center gap-1.5 px-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",onClick:()=>g(e=>!e),"aria-expanded":m,children:[m?(0,O.jsx)(ns,{className:"size-4"}):(0,O.jsx)(a3,{className:"size-4"}),(0,O.jsx)("h2",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Context"})]}),m?(0,O.jsx)("div",{className:"min-h-0 flex-1 space-y-1 overflow-y-auto px-2 pb-3",children:0===n.length?(0,O.jsx)("p",{className:"px-2 py-4 text-xs text-muted-foreground",children:"Referenced project items appear here."}):n.map(e=>{let r=lY[e.entity_type],s=!e.deleted&&(!e.navigation||!d),n=e.deleted||s,i=e.navigation?"Navigation is unavailable in this view.":"Navigation details are unavailable; refresh the thread and try again.";return(0,O.jsxs)("button",{type:"button",disabled:n,"aria-label":e.deleted?`Deleted ${r.toLocaleLowerCase()}`:s?`Unavailable ${r.toLocaleLowerCase()}`:`Open ${r}: ${e.navigation.label}`,title:s?i:void 0,onClick:()=>d?.(e),className:"flex w-full flex-col rounded-md px-2 py-2 text-left hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-55",children:[(0,O.jsx)("span",{className:"text-sm",children:e.deleted?`Deleted ${r.toLocaleLowerCase()}`:s?`Unavailable ${r.toLocaleLowerCase()}`:`${r} \xb7 ${e.navigation.label}`}),e.deleted?(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:"Deleted"}):null,s?(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:i}):null]},`${e.entity_type}:${e.entity_id}`)})}):null]}),(0,O.jsx)(sF,{open:x,onOpenChange:v,projectId:e,onSelectThread:a}),(0,O.jsx)(t8,{open:null!==b,onOpenChange:e=>{e||I||(w(null),T(null))},children:(0,O.jsxs)(rr,{children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:"Rename Project Chat thread"}),(0,O.jsx)(ra,{children:"Give this conversation a concise project-level title."})]}),(0,O.jsx)(ro,{autoFocus:!0,"aria-label":"Thread title",value:S,onChange:e=>j(e.target.value),onKeyDown:e=>{"Enter"===e.key&&b&&S.trim()&&z(`rename:${b.id}`,()=>o(b.id,S.trim()),()=>w(null))}}),A?(0,O.jsx)("div",{role:"alert",className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:A}):null,(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{type:"button",variant:"outline",disabled:I,onClick:()=>{w(null),T(null)},children:"Cancel"}),(0,O.jsx)(W.Button,{type:"button",disabled:!S.trim()||I,onClick:()=>{b&&z(`rename:${b.id}`,()=>o(b.id,S.trim()),()=>w(null))},children:"Save title"})]})]})}),(0,O.jsx)(lL,{open:null!==N,onOpenChange:e=>{e||B||(E(null),T(null))},children:(0,O.jsxs)(l$,{children:[(0,O.jsxs)(lW,{children:[(0,O.jsx)(lU,{children:"Delete this Project Chat thread?"}),(0,O.jsx)(lq,{children:"This permanently removes the thread and its persisted conversation."})]}),A?(0,O.jsx)("div",{role:"alert",className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:A}):null,(0,O.jsxs)(lH,{children:[(0,O.jsx)(lV,{disabled:B,children:"Cancel"}),(0,O.jsx)(lK,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:B,onClick:e=>{e.preventDefault(),N&&z(`delete:${N.id}`,()=>c(N.id),()=>E(null))},children:"Confirm delete"})]})]})}),(0,O.jsx)(lL,{open:null!==C,onOpenChange:e=>{e||L||(k(null),T(null))},children:(0,O.jsxs)(l$,{children:[(0,O.jsxs)(lW,{children:[(0,O.jsx)(lU,{children:"Archive this Project Chat thread?"}),(0,O.jsx)(lq,{children:"The conversation leaves recent selectors but remains available in thread history."})]}),A?(0,O.jsx)("div",{role:"alert",className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:A}):null,(0,O.jsxs)(lH,{children:[(0,O.jsx)(lV,{disabled:L,children:"Cancel"}),(0,O.jsx)(lK,{disabled:L,onClick:e=>{e.preventDefault(),C&&z(`archive:${C.id}`,()=>l(C.id),()=>k(null))},children:"Confirm archive"})]})]})})]})}var lX=e.i(113862);let lJ=(0,ew.default)("square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);var lZ="horizontal",lQ=["horizontal","vertical"],l0=$.forwardRef((e,r)=>{var s;let{decorative:n,orientation:i=lZ,...a}=e,o=(s=i,lQ.includes(s))?i:lZ;return(0,O.jsx)(er.div,{"data-orientation":o,...n?{role:"none"}:{"aria-orientation":"vertical"===o?o:void 0,role:"separator"},...a,ref:r})});l0.displayName="Separator",e.s(["Root",()=>l0,"Separator",()=>l0],691102),e.i(691102),(0,sn.cva)("flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",{variants:{orientation:{horizontal:"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}});var l1=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),l2=$.forwardRef((e,r)=>(0,O.jsx)(er.span,{...e,ref:r,style:{...l1,...e.style}}));l2.displayName="VisuallyHidden";var[l5,l3]=q("Tooltip",[iw]),l4=iw(),l6="TooltipProvider",l7="tooltip.open",[l8,l9]=l5(l6),ce=e=>{let{__scopeTooltip:r,delayDuration:s=700,skipDelayDuration:n=300,disableHoverableContent:i=!1,children:a}=e,o=$.useRef(!0),l=$.useRef(!1),c=$.useRef(0);return $.useEffect(()=>{let e=c.current;return()=>window.clearTimeout(e)},[]),(0,O.jsx)(l8,{scope:r,isOpenDelayedRef:o,delayDuration:s,onOpen:$.useCallback(()=>{window.clearTimeout(c.current),o.current=!1},[]),onClose:$.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.current=!0,n)},[n]),isPointerInTransitRef:l,onPointerInTransitChange:$.useCallback(e=>{l.current=e},[]),disableHoverableContent:i,children:a})};ce.displayName=l6;var ct="Tooltip",[cr,cs]=l5(ct),cn=e=>{let{__scopeTooltip:r,children:s,open:n,defaultOpen:i,onOpenChange:a,disableHoverableContent:o,delayDuration:l}=e,c=l9(ct,e.__scopeTooltip),d=l4(r),[u,h]=$.useState(null),f=ek(),p=$.useRef(0),m=o??c.disableHoverableContent,g=l??c.delayDuration,x=$.useRef(!1),[v,_]=G({prop:n,defaultProp:i??!1,onChange:e=>{e?(c.onOpen(),document.dispatchEvent(new CustomEvent(l7))):c.onClose(),a?.(e)},caller:ct}),y=$.useMemo(()=>v?x.current?"delayed-open":"instant-open":"closed",[v]),b=$.useCallback(()=>{window.clearTimeout(p.current),p.current=0,x.current=!1,_(!0)},[_]),w=$.useCallback(()=>{window.clearTimeout(p.current),p.current=0,_(!1)},[_]),S=$.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{x.current=!0,_(!0),p.current=0},g)},[g,_]);return $.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),(0,O.jsx)(iC,{...d,children:(0,O.jsx)(cr,{scope:r,contentId:f,open:v,stateAttribute:y,trigger:u,onTriggerChange:h,onTriggerEnter:$.useCallback(()=>{c.isOpenDelayedRef.current?S():b()},[c.isOpenDelayedRef,S,b]),onTriggerLeave:$.useCallback(()=>{m?w():(window.clearTimeout(p.current),p.current=0)},[w,m]),onOpen:b,onClose:w,disableHoverableContent:m,children:s})})};cn.displayName=ct;var ci="TooltipTrigger",ca=$.forwardRef((e,r)=>{let{__scopeTooltip:s,...n}=e,i=cs(ci,s),a=l9(ci,s),o=l4(s),l=$.useRef(null),c=(0,U.useComposedRefs)(r,l,i.onTriggerChange),d=$.useRef(!1),u=$.useRef(!1),h=$.useCallback(()=>d.current=!1,[]);return $.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),(0,O.jsx)(iN,{asChild:!0,...o,children:(0,O.jsx)(er.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...n,ref:c,onPointerMove:K(e.onPointerMove,e=>{"touch"!==e.pointerType&&(u.current||a.isPointerInTransitRef.current||(i.onTriggerEnter(),u.current=!0))}),onPointerLeave:K(e.onPointerLeave,()=>{i.onTriggerLeave(),u.current=!1}),onPointerDown:K(e.onPointerDown,()=>{i.open&&i.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:K(e.onFocus,()=>{d.current||i.onOpen()}),onBlur:K(e.onBlur,i.onClose),onClick:K(e.onClick,i.onClose)})})});ca.displayName=ci;var co="TooltipPortal",[cl,cc]=l5(co,{forceMount:void 0}),cd=e=>{let{__scopeTooltip:r,forceMount:s,children:n,container:i}=e,a=cs(co,r);return(0,O.jsx)(cl,{scope:r,forceMount:s,children:(0,O.jsx)(Z,{present:s||a.open,children:(0,O.jsx)(eW,{asChild:!0,container:i,children:n})})})};cd.displayName=co;var cu="TooltipContent",ch=$.forwardRef((e,r)=>{let s=cc(cu,e.__scopeTooltip),{forceMount:n=s.forceMount,side:i="top",...a}=e,o=cs(cu,e.__scopeTooltip);return(0,O.jsx)(Z,{present:n||o.open,children:o.disableHoverableContent?(0,O.jsx)(cx,{side:i,...a,ref:r}):(0,O.jsx)(cf,{side:i,...a,ref:r})})}),cf=$.forwardRef((e,r)=>{let s=cs(cu,e.__scopeTooltip),n=l9(cu,e.__scopeTooltip),i=$.useRef(null),a=(0,U.useComposedRefs)(r,i),[o,l]=$.useState(null),{trigger:c,onClose:d}=s,u=i.current,{onPointerInTransitChange:h}=n,f=$.useCallback(()=>{l(null),h(!1)},[h]),p=$.useCallback((e,r)=>{let s,n=e.currentTarget,i={x:e.clientX,y:e.clientY},a=function(e,r){let s=Math.abs(r.top-e.y),n=Math.abs(r.bottom-e.y),i=Math.abs(r.right-e.x),a=Math.abs(r.left-e.x);switch(Math.min(s,n,i,a)){case a:return"left";case i:return"right";case s:return"top";case n:return"bottom";default:throw Error("unreachable")}}(i,n.getBoundingClientRect());l(((s=[...function(e,r,s=5){let n=[];switch(r){case"top":n.push({x:e.x-s,y:e.y+s},{x:e.x+s,y:e.y+s});break;case"bottom":n.push({x:e.x-s,y:e.y-s},{x:e.x+s,y:e.y-s});break;case"left":n.push({x:e.x+s,y:e.y-s},{x:e.x+s,y:e.y+s});break;case"right":n.push({x:e.x-s,y:e.y-s},{x:e.x-s,y:e.y+s})}return n}(i,a),...function(e){let{top:r,right:s,bottom:n,left:i}=e;return[{x:i,y:r},{x:s,y:r},{x:s,y:n},{x:i,y:n}]}(r.getBoundingClientRect())].slice()).sort((e,r)=>e.x<r.x?-1:e.x>r.x?1:e.y<r.y?-1:1*!!(e.y>r.y)),function(e){if(e.length<=1)return e.slice();let r=[];for(let s=0;s<e.length;s++){let n=e[s];for(;r.length>=2;){let e=r[r.length-1],s=r[r.length-2];if((e.x-s.x)*(n.y-s.y)>=(e.y-s.y)*(n.x-s.x))r.pop();else break}r.push(n)}r.pop();let s=[];for(let r=e.length-1;r>=0;r--){let n=e[r];for(;s.length>=2;){let e=s[s.length-1],r=s[s.length-2];if((e.x-r.x)*(n.y-r.y)>=(e.y-r.y)*(n.x-r.x))s.pop();else break}s.push(n)}return(s.pop(),1===r.length&&1===s.length&&r[0].x===s[0].x&&r[0].y===s[0].y)?r:r.concat(s)}(s))),h(!0)},[h]);return $.useEffect(()=>()=>f(),[f]),$.useEffect(()=>{if(c&&u){let e=e=>p(e,u),r=e=>p(e,c);return c.addEventListener("pointerleave",e),u.addEventListener("pointerleave",r),()=>{c.removeEventListener("pointerleave",e),u.removeEventListener("pointerleave",r)}}},[c,u,p,f]),$.useEffect(()=>{if(o){let e=e=>{let r=e.target,s={x:e.clientX,y:e.clientY},n=c?.contains(r)||u?.contains(r),i=!function(e,r){let{x:s,y:n}=e,i=!1;for(let e=0,a=r.length-1;e<r.length;a=e++){let o=r[e],l=r[a],c=o.x,d=o.y,u=l.x,h=l.y;d>n!=h>n&&s<(u-c)*(n-d)/(h-d)+c&&(i=!i)}return i}(s,o);n?f():i&&(f(),d())};return document.addEventListener("pointermove",e),()=>document.removeEventListener("pointermove",e)}},[c,u,o,d,f]),(0,O.jsx)(cx,{...e,ref:a})}),[cp,cm]=l5(ct,{isInside:!1}),cg=(0,et.createSlottable)("TooltipContent"),cx=$.forwardRef((e,r)=>{let{__scopeTooltip:s,children:n,"aria-label":i,onEscapeKeyDown:a,onPointerDownOutside:o,...l}=e,c=cs(cu,s),d=l4(s),{onClose:u}=c;return $.useEffect(()=>(document.addEventListener(l7,u),()=>document.removeEventListener(l7,u)),[u]),$.useEffect(()=>{if(c.trigger){let e=e=>{let r=e.target;r?.contains(c.trigger)&&u()};return window.addEventListener("scroll",e,{capture:!0}),()=>window.removeEventListener("scroll",e,{capture:!0})}},[c.trigger,u]),(0,O.jsx)(eR,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:e=>e.preventDefault(),onDismiss:u,children:(0,O.jsxs)(iA,{"data-state":c.stateAttribute,...d,...l,ref:r,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[(0,O.jsx)(cg,{children:n}),(0,O.jsx)(cp,{scope:s,isInside:!0,children:(0,O.jsx)(l2,{id:c.contentId,role:"tooltip",children:i||n})})]})})});ch.displayName=cu;var cv="TooltipArrow",c_=$.forwardRef((e,r)=>{let{__scopeTooltip:s,...n}=e,i=l4(s);return cm(cv,s).isInside?null:(0,O.jsx)(iF,{...i,...n,ref:r})});c_.displayName=cv,e.s(["Arrow",()=>c_,"Content",()=>ch,"Portal",()=>cd,"Provider",()=>ce,"Root",()=>cn,"Tooltip",()=>cn,"TooltipArrow",()=>c_,"TooltipContent",()=>ch,"TooltipPortal",()=>cd,"TooltipProvider",()=>ce,"TooltipTrigger",()=>ca,"Trigger",()=>ca,"createTooltipScope",()=>l3],517964);var cy=e.i(517964),cy=cy;function cb({delayDuration:e=0,...r}){return(0,O.jsx)(cy.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...r})}function cw({...e}){return(0,O.jsx)(cy.Root,{"data-slot":"tooltip",...e})}function cS({...e}){return(0,O.jsx)(cy.Trigger,{"data-slot":"tooltip-trigger",...e})}function cj({className:e,sideOffset:r=0,children:s,...n}){return(0,O.jsx)(cy.Portal,{children:(0,O.jsxs)(cy.Content,{"data-slot":"tooltip-content",sideOffset:r,className:(0,ey.cn)("bg-foreground text-background 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 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...n,children:[s,(0,O.jsx)(cy.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}(0,ew.default)("chevron-left",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);var cC=e.i(94265),ck=cC;let cN=({className:e,from:r,...s})=>(0,O.jsx)("div",{className:(0,ey.cn)("group flex w-full max-w-[95%] flex-col gap-2","user"===r?"is-user ml-auto justify-end":"is-assistant",e),...s}),cE=({children:e,className:r,...s})=>(0,O.jsx)("div",{className:(0,ey.cn)("is-user:dark flex w-fit max-w-full min-w-0 flex-col gap-2 overflow-hidden text-sm","group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground","group-[.is-assistant]:text-foreground",r),...s,children:e}),cD=(0,$.memo)(({className:e,...r})=>(0,O.jsx)(ck.i,{className:(0,ey.cn)("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...r}),(e,r)=>e.children===r.children);cD.displayName="MessageResponse";let cR=(0,ew.default)("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]),cA={damping:.7,stiffness:.05,mass:1.25},cT=1e3/60,cM=!1;function cF(e,r){let s=(0,$.useCallback)(r=>(s.current=r,e(r)),r);return s}globalThis.document?.addEventListener("mousedown",()=>{cM=!0}),globalThis.document?.addEventListener("mouseup",()=>{cM=!1}),globalThis.document?.addEventListener("click",()=>{cM=!1});let cP=new Map;function cI(...e){let r={...cA},s=!1;for(let n of e){if("instant"===n){s=!0;continue}"object"==typeof n&&(s=!1,r.damping=n.damping??r.damping,r.stiffness=n.stiffness??r.stiffness,r.mass=n.mass??r.mass)}let n=JSON.stringify(r);return cP.has(n)||cP.set(n,Object.freeze(r)),s?"instant":cP.get(n)}let cB=(0,$.createContext)(null),cL="undefined"!=typeof window?$.useLayoutEffect:$.useEffect;function cz({instance:e,children:r,resize:s,initial:n,mass:i,damping:a,stiffness:o,targetScrollTop:l,contextRef:c,...d}){let u=(0,$.useRef)(null),h=((e={})=>{let[r,s]=(0,$.useState)(!1),[n,i]=(0,$.useState)(!1!==e.initial),[a,o]=(0,$.useState)(!1),l=(0,$.useRef)(null);l.current=e;let c=(0,$.useCallback)(()=>{if(!cM)return!1;let e=window.getSelection();if(!e||!e.rangeCount)return!1;let r=e.getRangeAt(0);return r.commonAncestorContainer.contains(x.current)||x.current?.contains(r.commonAncestorContainer)},[]),d=(0,$.useCallback)(e=>{h.isAtBottom=e,i(e)},[]),u=(0,$.useCallback)(e=>{h.escapedFromLock=e,s(e)},[]),h=(0,$.useMemo)(()=>{let s;return{escapedFromLock:r,isAtBottom:n,resizeDifference:0,accumulated:0,velocity:0,listeners:new Set,get scrollTop(){return x.current?.scrollTop??0},set scrollTop(scrollTop){x.current&&(x.current.scrollTop=scrollTop,h.ignoreScrollToTop=x.current.scrollTop)},get targetScrollTop(){if(!x.current||!v.current)return 0;return x.current.scrollHeight-1-x.current.clientHeight},get calculatedTargetScrollTop(){if(!x.current||!v.current)return 0;let{targetScrollTop:r}=this;if(!e.targetScrollTop)return r;if(s?.targetScrollTop===r)return s.calculatedScrollTop;let n=Math.max(Math.min(e.targetScrollTop(r,{scrollElement:x.current,contentElement:v.current}),r),0);return s={targetScrollTop:r,calculatedScrollTop:n},requestAnimationFrame(()=>{s=void 0}),n},get scrollDifference(){return this.calculatedTargetScrollTop-this.scrollTop},get isNearBottom(){return this.scrollDifference<=70}}},[]),f=(0,$.useCallback)((e={})=>{let r;"string"==typeof e&&(e={animation:e}),e.preserveScrollPosition||d(!0);let s=Date.now()+(Number(e.wait)||0),n=cI(l.current,e.animation),{ignoreEscapes:i=!1}=e,a=h.calculatedTargetScrollTop;e.duration instanceof Promise?e.duration.finally(()=>{r=Date.now()}):r=s+(e.duration??0);let o=async()=>{let e=new Promise(requestAnimationFrame).then(()=>{if(!h.isAtBottom)return h.animation=void 0,!1;let{scrollTop:d}=h,u=performance.now(),p=(u-(h.lastTick??u))/cT;if(h.animation||(h.animation={behavior:n,promise:e,ignoreEscapes:i}),h.animation.behavior===n&&(h.lastTick=u),c()||s>Date.now())return o();if(d<Math.min(a,h.calculatedTargetScrollTop)){if(h.animation?.behavior===n){if("instant"===n)return h.scrollTop=h.calculatedTargetScrollTop,o();h.velocity=(n.damping*h.velocity+n.stiffness*h.scrollDifference)/n.mass,h.accumulated+=h.velocity*p,h.scrollTop+=h.accumulated,h.scrollTop!==d&&(h.accumulated=0)}return o()}return r>Date.now()?(a=h.calculatedTargetScrollTop,o()):(h.animation=void 0,h.scrollTop<h.calculatedTargetScrollTop)?f({animation:cI(l.current,l.current.resize),ignoreEscapes:i,duration:Math.max(0,r-Date.now())||void 0}):h.isAtBottom});return e.then(e=>(requestAnimationFrame(()=>{h.animation||(h.lastTick=void 0,h.velocity=0)}),e))};return(!0!==e.wait&&(h.animation=void 0),h.animation?.behavior===n)?h.animation.promise:o()},[d,c,h]),p=(0,$.useCallback)(()=>{u(!0),d(!1)},[u,d]),m=(0,$.useCallback)(({target:e})=>{if(e!==x.current)return;let{scrollTop:r,ignoreScrollToTop:s}=h,{lastScrollTop:n=r}=h;h.lastScrollTop=r,h.ignoreScrollToTop=void 0,s&&s>r&&(n=s),o(h.isNearBottom),setTimeout(()=>{if(h.resizeDifference||r===s)return;if(c()){u(!0),d(!1);return}let e=r>n,i=r<n;if(h.animation?.ignoreEscapes){h.scrollTop=n;return}i&&(u(!0),d(!1)),e&&u(!1),!h.escapedFromLock&&h.isNearBottom&&d(!0)},1)},[u,d,c,h]),g=(0,$.useCallback)(({target:e,deltaY:r})=>{let s=e;for(;!["scroll","auto"].includes(getComputedStyle(s).overflow);){if(!s.parentElement)return;s=s.parentElement}s===x.current&&r<0&&x.current.scrollHeight>x.current.clientHeight&&!h.animation?.ignoreEscapes&&(u(!0),d(!1))},[u,d,h]),x=cF(e=>{x.current?.removeEventListener("scroll",m),x.current?.removeEventListener("wheel",g),e?.addEventListener("scroll",m,{passive:!0}),e?.addEventListener("wheel",g,{passive:!0})},[]),v=cF(e=>{let r;h.resizeObserver?.disconnect(),e&&(h.resizeObserver=new ResizeObserver(([e])=>{let{height:s}=e.contentRect,n=s-(r??s);if(h.resizeDifference=n,h.scrollTop>h.targetScrollTop&&(h.scrollTop=h.targetScrollTop),o(h.isNearBottom),n>=0){let e=cI(l.current,r?l.current.resize:l.current.initial);f({animation:e,wait:!0,preserveScrollPosition:!0,duration:"instant"===e?void 0:350})}else h.isNearBottom&&(u(!1),d(!0));r=s,requestAnimationFrame(()=>{setTimeout(()=>{h.resizeDifference===n&&(h.resizeDifference=0)},1)})}),h.resizeObserver?.observe(e))},[]);return{contentRef:v,scrollRef:x,scrollToBottom:f,stopScroll:p,isAtBottom:n||a,isNearBottom:a,escapedFromLock:r,state:h}})({mass:i,damping:a,stiffness:o,resize:s,initial:n,targetScrollTop:$.useCallback((e,r)=>{let s=y?.targetScrollTop??l;return s?.(e,r)??e},[l])}),{scrollRef:f,contentRef:p,scrollToBottom:m,stopScroll:g,isAtBottom:x,escapedFromLock:v,state:_}=e??h,y=(0,$.useMemo)(()=>({scrollToBottom:m,stopScroll:g,scrollRef:f,isAtBottom:x,escapedFromLock:v,contentRef:p,state:_,get targetScrollTop(){return u.current},set targetScrollTop(targetScrollTop){u.current=targetScrollTop}}),[m,x,p,f,g,v,_]);return(0,$.useImperativeHandle)(c,()=>y,[y]),cL(()=>{f.current&&"visible"===getComputedStyle(f.current).overflow&&(f.current.style.overflow="auto")},[]),$.createElement(cB.Provider,{value:y},$.createElement("div",{...d},"function"==typeof r?r(y):r))}function cO(){let e=(0,$.useContext)(cB);if(!e)throw Error("use-stick-to-bottom component context must be used within a StickToBottom component");return e}(cz||(cz={})).Content=function({children:e,scrollClassName:r,...s}){let n=cO();return $.createElement("div",{ref:n.scrollRef,style:{height:"100%",width:"100%",scrollbarGutter:"stable both-edges"},className:r},$.createElement("div",{...s,ref:n.contentRef},"function"==typeof e?e(n):e))};let c$=({className:e,...r})=>(0,O.jsx)(cz,{className:(0,ey.cn)("relative flex-1 overflow-y-hidden",e),initial:"smooth",resize:"smooth",role:"log",...r}),cW=({className:e,...r})=>(0,O.jsx)(cz.Content,{className:(0,ey.cn)("flex flex-col gap-8 p-4",e),...r}),cH=({className:e,...r})=>{let{isAtBottom:s,scrollToBottom:n}=cO(),i=(0,$.useCallback)(()=>{n()},[n]);return!s&&(0,O.jsx)(W.Button,{className:(0,ey.cn)("absolute bottom-4 left-[50%] translate-x-[-50%] rounded-full",e),onClick:i,size:"icon",type:"button",variant:"outline",...r,children:(0,O.jsx)(cR,{className:"size-4"})})},cU=(0,ew.default)("circle-dot",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]),cq=(0,ew.default)("clock-3",[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),cK=(0,ew.default)("message-square-more",[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 11h.01",key:"z322tv"}],["path",{d:"M16 11h.01",key:"xkw8gn"}],["path",{d:"M8 11h.01",key:"1dfujw"}]]);function cV({operation:e,onOpenSession:r,onViewOutput:s,onRunAgain:n,pendingAction:i,actionError:a}){let{label:o,detail:l}=function(e){switch(e.kind){case"task_create":return{label:"Task created",detail:e.title??e.taskId};case"task_update":return{label:"Task updated",detail:e.title??e.taskId};case"agent_session_create":return{label:"Agent session",detail:e.branch?`${e.target??"workspace"} / ${e.branch}`:e.target??"main workspace"};case"agent_instruction":return{label:"Agent instruction",detail:e.instruction??e.sessionId};case"schedule_run":return{label:"Schedule run",detail:e.runId}}}(e),c=e.failure?.code==="timeout"?{label:"Timed out",Icon:cq,className:"text-amber-600"}:e.failure?.code==="remote_offline"?{label:"Remote offline",Icon:sy,className:"text-destructive"}:e.failure?.code==="deleted_target"?{label:"Deleted target",Icon:sy,className:"text-muted-foreground"}:"completed"===e.status?{label:"Completed",Icon:sJ,className:"text-emerald-600"}:"failed"===e.status?{label:"Failed",Icon:sy,className:"text-destructive"}:"running"===e.status||"resolving"===e.status?{label:"Running",Icon:sj,className:"text-blue-600"}:{label:"Queued",Icon:cU,className:"text-muted-foreground"},d=e.failure?.code==="deleted_target",u="agent_session_create"===e.kind&&e.sessionAvailable&&("running"===e.status||"completed"===e.status)&&!d,h="schedule_run"===e.kind&&e.runAvailable&&("running"===e.status||"completed"===e.status||"failed"===e.status)&&!d,f="schedule_run"===e.kind&&e.runAvailable&&("completed"===e.status||"failed"===e.status)&&!d,p=c.Icon;return(0,O.jsxs)("section",{className:"rounded-lg border bg-card p-3 text-card-foreground","aria-label":`${o}: ${c.label}`,children:[(0,O.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("div",{className:"text-sm font-medium",children:o}),l?(0,O.jsx)("div",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:l}):null]}),(0,O.jsxs)("div",{"data-operation-status":e.status,className:(0,ey.cn)("flex shrink-0 items-center gap-1.5 text-xs font-medium",c.className),children:[(0,O.jsx)(p,{className:(0,ey.cn)("size-3.5",("running"===e.status||"resolving"===e.status)&&"animate-spin"),"aria-hidden":"true"}),c.label]})]}),e.failure?.message?(0,O.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:e.failure.message}):null,"agent_session_create"===e.kind&&u&&r?(0,O.jsx)("div",{className:"mt-3",children:(0,O.jsxs)(W.Button,{type:"button",size:"sm",variant:"outline","aria-busy":"open_session"===i,disabled:null!=i,onClick:()=>r(e),children:["open_session"===i?(0,O.jsx)(sj,{className:"size-3.5 animate-spin"}):(0,O.jsx)(s7,{className:"size-3.5"}),"Open Session"]})}):null,"schedule_run"===e.kind&&(h&&s||f&&n)?(0,O.jsxs)("div",{className:"mt-3 flex flex-wrap gap-2",children:[h&&s?(0,O.jsxs)(W.Button,{type:"button",size:"sm",variant:"outline","aria-busy":"view_output"===i,disabled:null!=i,onClick:()=>s(e),children:["view_output"===i?(0,O.jsx)(sj,{className:"size-3.5 animate-spin"}):(0,O.jsx)(cK,{className:"size-3.5"}),"View Output"]}):null,f&&n?(0,O.jsxs)(W.Button,{type:"button",size:"sm",variant:"outline","aria-busy":"run_again"===i,disabled:null!=i,onClick:()=>n(e),children:["run_again"===i?(0,O.jsx)(sj,{className:"size-3.5 animate-spin"}):(0,O.jsx)(s8,{className:"size-3.5"}),"run_again"===i?"Running again…":"Run Again"]}):null]}):null,a?(0,O.jsx)("p",{role:"alert",className:"mt-2 text-xs text-destructive",children:a}):null]})}let cY=(0,ew.default)("map-pin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);function cG({operation:e,onSelect:r,pendingWorkspaceId:s,actionError:n}){let i="pending"!==e.status;return(0,O.jsxs)("section",{className:"rounded-lg border bg-card p-3 text-card-foreground","aria-label":"Select a workspace for the agent session",children:[(0,O.jsx)("div",{className:"text-sm font-medium",children:"Choose a workspace"}),(0,O.jsx)("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"This agent session needs one of the project's offered workspaces."}),(0,O.jsx)("div",{className:"mt-3 grid gap-2",children:e.candidates.map(n=>{let a=s===n.id,o=`${n.target} / ${n.branch??"main"}`;return(0,O.jsxs)(W.Button,{type:"button",variant:"outline",className:"h-auto min-h-9 justify-start whitespace-normal text-left","aria-label":`Select workspace: ${o}`,"aria-busy":a,disabled:i||null!=s,onClick:()=>r({requestId:e.requestId,workspaceId:n.id}),children:[a?(0,O.jsx)(sj,{className:"size-3.5 animate-spin"}):(0,O.jsx)(cY,{className:"size-3.5"}),o,a?" · Selecting…":""]},n.id)})}),i?(0,O.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Workspace selection resolved."}):null,n?(0,O.jsx)("p",{role:"alert",className:"mt-2 text-xs text-destructive",children:n}):null]})}function cX(e){try{let r=JSON.parse(e);return"object"!=typeof r||null===r||Array.isArray(r)?null:r}catch{return null}}function cJ(e){if("workspace_selection"===e.kind)switch(e.status){case"pending":return"Waiting for workspace selection";case"resolving":return"Creating agent session";case"running":return"Agent session running";case"completed":return"Agent session completed";case"failed":return"Workspace selection failed"}if("agent_session_create"===e.kind){if("resolving"===e.status)return"Creating agent session";if("running"===e.status)return"Agent session running";if("completed"===e.status)return"Agent session completed"}switch(e.status){case"pending":return"Queued";case"resolving":case"running":return"Running";case"completed":return"Completed";case"failed":return"Failed"}}function cZ({messages:e,contextRefs:r,status:s,activeTurnId:n,pendingApprovalIds:i,queueLength:a,loading:o,hasEarlierMessages:l,loadingEarlierMessages:c,connected:d,error:u,initialDraft:h="",onDraftChange:f,onDraftSent:p,onSend:m,onLoadEarlierMessages:g,onStop:x,onResolveApproval:v,onSelectWorkspace:_,onOpenAgentSession:y,onOpenScheduleRun:b,onRunScheduleAgain:w}){let[S,j]=(0,$.useState)(h),[C,k]=(0,$.useState)(!1),[N,E]=(0,$.useState)(null),[D,R]=(0,$.useState)(new Set),[A,T]=(0,$.useState)(new Set),[M,F]=(0,$.useState)(null),P=(0,$.useRef)(!1),I=(0,$.useRef)(null),B=(0,$.useRef)(new Set),L=(0,$.useRef)(new Set),[z,H]=(0,$.useState)(new Map),[U,q]=(0,$.useState)(new Map),K=(0,$.useMemo)(()=>{let r=new Map,s=new Map;for(let n of e){if("operation"!==n.type)continue;let e=(0,rv.parseProjectChatOperationMessage)(n.content);e&&(r.set(n.id,e),s.set(e.operationId,n.id))}return{byMessageId:r,latestMessageIdByOperation:s}},[e]),V=async(e,r,s)=>{if(!L.current.has(e)){L.current.add(e),H(s=>new Map(s).set(e,r)),q(r=>{let s=new Map(r);return s.delete(e),s});try{await s()}catch(r){q(s=>new Map(s).set(e,r instanceof Error?r.message:"Project operation failed"))}finally{L.current.delete(e),H(r=>{let s=new Map(r);return s.delete(e),s})}}},Y=async e=>{e.preventDefault();let r=S.trim();if(r&&!P.current){P.current=!0,k(!0),F(null);try{await m(r),j(""),p?.(S)}catch(e){F(e instanceof Error?e.message:"Failed to send message")}finally{P.current=!1,k(!1)}}};(0,$.useEffect)(()=>{let e=I.current;e&&("running"!==s||n!==e)&&(I.current=null,E(null))},[n,s]);let G=async()=>{if(n&&!I.current){I.current=n,E(n),F(null);try{await x(n)}catch(e){I.current===n&&F(e instanceof Error?e.message:"Failed to stop generation")}}},X=async(e,r)=>{if(!B.current.has(e)){B.current.add(e),R(r=>new Set(r).add(e)),F(null);try{await v(e,r),T(r=>new Set(r).add(e))}catch(e){F(e instanceof Error?e.message:"Failed to resolve approval")}finally{B.current.delete(e),R(r=>{let s=new Set(r);return s.delete(e),s})}}};return(0,$.useEffect)(()=>{T(e=>{let r=new Set([...e].filter(e=>i.includes(e)));return r.size===e.size?e:r})},[i]),(0,O.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,O.jsxs)(c$,{className:"min-h-0",initial:"instant",resize:"smooth","data-testid":"project-chat-scroll",children:[(0,O.jsxs)(cW,{className:"mx-auto w-full max-w-3xl gap-4 px-4 py-5 sm:px-6",children:[l?(0,O.jsx)("div",{className:"flex justify-center",children:(0,O.jsxs)(W.Button,{type:"button",size:"sm",variant:"outline",disabled:c,onClick:()=>void g(),children:[c?(0,O.jsx)(sj,{className:"size-3.5 animate-spin"}):null,"Load earlier messages"]})}):null,o&&0===e.length?(0,O.jsx)("div",{className:"flex justify-center py-12",children:(0,O.jsx)(sj,{className:"size-5 animate-spin text-muted-foreground"})}):null,o||0!==e.length?null:(0,O.jsxs)("div",{className:"mx-auto max-w-md py-20 text-center",children:[(0,O.jsx)("h2",{className:"text-base font-semibold",children:"Start a project conversation"}),(0,O.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Discuss tasks, schedules, sessions, and work across the whole project."})]}),(0,O.jsxs)("div",{className:"flex w-full flex-col gap-4",children:[e.map(e=>{var s;if("turn_end"===e.type)return(0,O.jsxs)("div",{"data-testid":"turn-boundary",className:"my-2 flex items-center gap-2","aria-label":"Turn complete",children:[(0,O.jsx)("span",{className:"h-px flex-1 bg-border"}),(0,O.jsx)("span",{className:"size-1 rounded-full bg-border"}),(0,O.jsx)("span",{className:"h-px flex-1 bg-border"})]},e.id);if("user"===e.type||"assistant"===e.type)return(0,O.jsx)(cN,{from:e.type,children:(0,O.jsx)(cE,{children:"assistant"===e.type?(0,O.jsx)(cD,{children:e.content}):e.content})},e.id);if("tool_use"===e.type){let r;return(0,O.jsxs)("div",{className:"flex items-center gap-2 rounded-md bg-muted/50 px-3 py-2 text-xs text-muted-foreground",children:[(0,O.jsx)(sA,{className:"size-3.5"}),"Running ",(r=cX(e.content),("string"==typeof r?.toolName?r.toolName:"string"==typeof r?.tool?r.tool:"project tool").replaceAll("_"," ")),"…"]},e.id)}if("tool_result"===e.type){let r;return(0,O.jsxs)("details",{className:"rounded-md border px-3 py-2 text-xs",children:[(0,O.jsx)("summary",{className:"cursor-pointer text-muted-foreground",children:"Tool result"}),(0,O.jsx)("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap",children:(r=cX(s=e.content),"string"==typeof r?.output?r.output:"string"==typeof r?.error?r.error:s)})]},e.id)}if("tool_approval_request"===e.type){let r=cX(e.content);if(!r||"string"!=typeof r.approvalId)return null;let s="string"==typeof r.tool?r.tool:"project tool",n=i.includes(r.approvalId)&&!A.has(r.approvalId);return(0,O.jsxs)("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-sm",children:[(0,O.jsxs)("div",{className:"font-medium",children:["Approve ",s.replaceAll("_"," "),"?"]}),(0,O.jsx)("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap text-xs text-muted-foreground",children:JSON.stringify(r.input??{},null,2)}),n?(0,O.jsxs)("div",{className:"mt-3 flex gap-2",children:[(0,O.jsxs)(W.Button,{size:"sm","aria-label":`Approve ${s}`,disabled:D.has(r.approvalId),onClick:()=>void X(r.approvalId,!0),children:[(0,O.jsx)(rf.Check,{className:"size-3.5"}),"Approve"]}),(0,O.jsxs)(W.Button,{size:"sm",variant:"outline","aria-label":`Deny ${s}`,disabled:D.has(r.approvalId),onClick:()=>void X(r.approvalId,!1),children:[(0,O.jsx)(t7,{className:"size-3.5"}),"Deny"]})]}):(0,O.jsx)("div",{className:"mt-3 text-xs text-muted-foreground",children:"Approval expired or resolved"})]},e.id)}if("operation"===e.type){let s,n=K.byMessageId.get(e.id);if(!n)return(0,O.jsx)("div",{className:"rounded-md border bg-card px-3 py-2 text-sm text-muted-foreground",children:"Project operation unavailable"},e.id);if(K.latestMessageIdByOperation.get(n.operationId)!==e.id)return null;let i=(s=(e,s)=>r.some(r=>r.entity_type===e&&r.entity_id===s&&r.deleted),"task_create"===n.kind||"task_update"===n.kind?s("task",n.taskId):"agent_session_create"===n.kind||"agent_instruction"===n.kind?s("agent_session",n.sessionId):"schedule_run"===n.kind&&(s("schedule",n.scheduleId)||s("schedule_run",n.runId)))?{...n,failure:{code:"deleted_target",message:"The target no longer exists or is unavailable."}}:n,a=z.get(i.operationId),o=U.get(i.operationId);if("workspace_selection"===i.kind){let e=a?.startsWith("workspace:")?a.slice(10):null;return(0,O.jsxs)("div",{"data-operation-id":i.operationId,"data-operation-kind":i.kind,children:[(0,O.jsx)("p",{role:"status","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:cJ(i)}),(0,O.jsx)(cG,{operation:i,pendingWorkspaceId:e,actionError:o,onSelect:({requestId:e,workspaceId:r})=>{V(i.operationId,"select_workspace",async()=>{H(e=>new Map(e).set(i.operationId,`workspace:${r}`)),await _(e,r)})}})]},`operation:${i.operationId}`)}return(0,O.jsxs)("div",{"data-operation-id":i.operationId,"data-operation-kind":i.kind,children:[(0,O.jsx)("p",{role:"status","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:cJ(i)}),(0,O.jsx)(cV,{operation:i,pendingAction:a,actionError:o,onOpenSession:"agent_session_create"===i.kind&&y?e=>{V(e.operationId,"open_session",()=>y(e.sessionId,e.target??"local",e.branch??null))}:void 0,onViewOutput:"schedule_run"===i.kind&&b?e=>{V(e.operationId,"view_output",()=>b(e.runId,e.scheduleId))}:void 0,onRunAgain:"schedule_run"===i.kind&&w?e=>{V(e.operationId,"run_again",()=>w(e.runId))}:void 0})]},`operation:${i.operationId}`)}if("error"===e.type){let r=cX(e.content),s="string"==typeof r?.message?r.message:e.content;return(0,O.jsxs)("div",{role:"alert",className:"flex gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[(0,O.jsx)(s6,{className:"mt-0.5 size-4 shrink-0"}),s]},e.id)}return(0,O.jsx)("div",{className:"rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:e.content},e.id)}),u?(0,O.jsx)("div",{role:"alert",className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:u}):null,M?(0,O.jsx)("div",{role:"alert",className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:M}):null]})]}),(0,O.jsx)(cH,{"aria-label":"Jump to latest message"})]}),(0,O.jsx)("div",{className:"shrink-0 border-t bg-background p-3 sm:px-6",children:(0,O.jsxs)("form",{onSubmit:e=>void Y(e),className:"mx-auto max-w-3xl",children:["running"===s?(0,O.jsxs)("div",{className:"mb-2 flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[(0,O.jsx)("span",{children:a>0?`${a} queued`:"Project Chat is working"}),(0,O.jsxs)(W.Button,{type:"button",variant:"outline",size:"sm","aria-label":"Stop generating",disabled:!n||null!==N,onClick:()=>void G(),children:[(0,O.jsx)(lJ,{className:"size-3"}),N?"Stopping…":"Stop generating"]})]}):null,"queued"===s?(0,O.jsxs)("div",{className:"mb-2 flex items-center gap-2 text-xs text-muted-foreground",role:"status",children:[(0,O.jsx)(lX.Clock,{className:"size-3.5"}),(0,O.jsx)("span",{children:"Waiting to start…"})]}):null,(0,O.jsxs)("div",{className:"relative",children:[(0,O.jsx)(rl,{"aria-label":"Message Project Chat",value:S,onChange:e=>{j(e.target.value),f?.(e.target.value)},onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),e.currentTarget.form?.requestSubmit())},placeholder:d?"Message Project Chat…":"Reconnecting to Project Chat…",disabled:!d||C,rows:2,className:"min-h-20 resize-none pr-16"}),(0,O.jsx)(W.Button,{type:"submit",size:"sm","aria-label":"Send message",disabled:!d||C||!S.trim(),className:"absolute bottom-2 right-2",children:"Send"})]})]})})]})}function cQ({projectId:e,threadId:r,projectName:s,onBack:n,onSelectThread:i,onOpenContext:a,onOpenAgentSession:o,onOpenScheduleRun:l,onRunScheduleAgain:c}){let d=function(e,r){let s=sf(e),[n,i]=(0,$.useState)([]),[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(!1),[d,u]=(0,$.useState)(!1),[h,f]=(0,$.useState)(ld),[p,m]=(0,$.useState)(!1),[g,x]=(0,$.useState)(null),[v,_]=(0,$.useState)(null),[y,b]=(0,$.useState)(null),w=(0,$.useRef)(ld()),S=(0,$.useRef)(e),j=(0,$.useRef)(r),C=(0,$.useRef)(0),k=(0,$.useRef)(0),N=(0,$.useRef)(null),E=(0,$.useRef)(!1),D=(0,$.useRef)(new Map),R=(0,$.useRef)(0),A=(0,$.useRef)(null),T=(0,$.useRef)(new Map);(0,$.useEffect)(()=>(E.current=!0,()=>{E.current=!1}),[]),(0,$.useEffect)(()=>{for(let[s,n]of(S.current=e,j.current=r,T.current))e&&n.identity.projectId===e||T.current.delete(s)},[e,r]);let M=(0,$.useCallback)(async(e,r,s)=>{N.current?.abort();let n=new AbortController;N.current=n;let a=++k.current;try{let o=await rv.api.listProjectChatThreads(e,s,{signal:n.signal});if(C.current!==r||S.current!==e||k.current!==a)return;i(o),x(null)}catch(s){if(n.signal.aborted||C.current!==r||S.current!==e||k.current!==a)return;x(s instanceof Error?s.message:"Failed to list Project Chat threads")}finally{N.current===n&&(N.current=null),C.current===r&&S.current===e&&k.current===a&&o(!1)}},[]);(0,$.useEffect)(()=>{C.current+=1,k.current+=1;let r=C.current;if(N.current?.abort(),N.current=null,!e){i([]),o(!1),x(null);return}return i([]),o(!0),x(null),M(e,r,!1),()=>{k.current+=1,N.current?.abort(),N.current=null}},[M,e]);let F=(0,$.useCallback)(async(e=!1)=>{let r=S.current;r&&await M(r,C.current,e)},[M]),P=(0,$.useCallback)((e,r)=>!!E.current&&S.current===e&&C.current===r&&(k.current+=1,N.current?.abort(),N.current=null,o(!1),!0),[]);(0,$.useEffect)(()=>{R.current+=1;let s=R.current,n=!1,i=!1,a=null,o=0,l=null,d=null,h=e=>{w.current=e,f(e)};if(A.current?.close(),A.current=null,m(!1),u(!1),_(null),b(null),!e||!r){h(ld()),c(!1);return}let p=T.current.get(r);p?.identity.projectId===e?(lu(T.current,p),h({thread:p.thread,messages:p.messages,hasEarlierMessages:p.hasEarlierMessages,earliestSequence:p.earliestSequence,status:p.status,activeTurnId:p.activeTurnId,pendingApprovalIds:p.pendingApprovalIds,queueLength:p.queueLength,contextRefs:p.contextRefs})):(T.current.delete(r),h(ld())),c(!0);let g=()=>!n&&!i&&R.current===s&&S.current===e&&j.current===r,x=()=>{null!==a&&clearTimeout(a),a=null},v=e=>g()&&d===e,y=e=>{null!==e.timeout&&clearTimeout(e.timeout),e.timeout=null,d===e&&(d=null)},C=e=>{y(e),e.controller.abort();let r=e.socket;e.socket=null,r&&A.current===r&&(A.current=null),r?.close()},k=e=>{i=!0,x(),d&&C(d),e&&A.current===e&&(A.current=null,e.close()),m(!1),c(!1),_("Thread not found"),b("thread_not_found")},N=(e=!1)=>{if(!g()||(e&&x(),null!==a))return;let r=e?0:Math.min(1e3*2**o,3e4);e||(o+=1),a=setTimeout(()=>{a=null,D(!0)},r)},E=(e,r)=>{g()&&A.current===e&&(d?.socket===e?C(d):(A.current=null,e.close()),m(!1),c(!1),r&&_(r),N())};async function D(s){if(!g()||d)return;let n={controller:new AbortController,timeout:null,socket:null};d=n,n.timeout=setTimeout(()=>{v(n)&&(C(n),m(!1),c(!1),_("Project Chat connection timed out"),N())},1e4);try{let[a,u]=await Promise.all([rv.api.getProjectChatThread(r,{signal:n.controller.signal}),(0,rv.getFreshToken)(s?{skipCache:!0}:void 0)]);if(!v(n))return;let{thread:f,contextRefs:p}=a;if(f.project_id!==e||f.id!==r){i=!0,C(n),_("Project Chat stream identity mismatch"),c(!1);return}if(!Array.isArray(p)||!p.every(lm)||p.some(e=>e.thread_id!==r))throw Error("Invalid Project Chat thread context");h({...w.current,thread:f,contextRefs:p});let x=new WebSocket((0,rv.getWebSocketUrl)(`/api/project-chat/threads/${r}/stream`,u));n.socket=x,A.current=x;let S=!1;l=null,x.onopen=()=>{g()&&A.current===x&&m(!0)},x.onmessage=s=>{if(g()&&A.current===x)try{let a=JSON.parse(s.data);if(!lf(a))throw Error("invalid frame");if("type"in a&&"project_chat_snapshot"===a.type){let s=a.snapshot;if(!function(e){if(!lf(e)||!lf(e.identity)||!lf(e.thread)||!Array.isArray(e.messages)||!Array.isArray(e.contextRefs))return!1;let r=e.thread.id,s=e.thread.project_id,n=e.thread.user_id;return"string"==typeof r&&"string"==typeof s&&"string"==typeof n&&"string"==typeof e.identity.projectId&&"string"==typeof e.identity.threadId&&"string"==typeof e.identity.userId&&e.identity.threadId===r&&e.identity.projectId===s&&e.identity.userId===n&&e.messages.every(e=>lp(e)&&e.thread_id===r)&&"boolean"==typeof e.hasEarlierMessages&&(null===e.earliestSequence||Number.isSafeInteger(e.earliestSequence))&&e.contextRefs.every(e=>lm(e)&&e.thread_id===r)&&lg(e.status)&&(null===e.activeTurnId||"string"==typeof e.activeTurnId)&&Array.isArray(e.pendingApprovalIds)&&e.pendingApprovalIds.every(e=>"string"==typeof e&&e.length>0)&&Number.isSafeInteger(e.queueLength)&&e.queueLength>=0}(s))throw Error("invalid snapshot");if(s.identity.threadId!==r||s.identity.projectId!==e||s.identity.userId!==f.user_id||s.thread.id!==r||s.thread.project_id!==e||s.thread.user_id!==f.user_id){i=!0,_("Project Chat stream identity mismatch"),c(!1),d===n?C(n):(A.current=null,x.close());return}S=!0,l=Date.now(),y(n),o=0,b(null),_(null),lu(T.current,s),h({thread:s.thread,messages:w.current.thread?.id===r&&null!==w.current.earliestSequence&&null!==s.earliestSequence&&w.current.earliestSequence<s.earliestSequence?lh(w.current.messages,s.messages):s.messages,hasEarlierMessages:w.current.thread?.id===r&&null!==w.current.earliestSequence&&null!==s.earliestSequence&&w.current.earliestSequence<s.earliestSequence?w.current.hasEarlierMessages:s.hasEarlierMessages,earliestSequence:w.current.thread?.id===r&&null!==w.current.earliestSequence&&null!==s.earliestSequence&&w.current.earliestSequence<s.earliestSequence?w.current.earliestSequence:s.earliestSequence,status:s.status,activeTurnId:s.activeTurnId,pendingApprovalIds:s.pendingApprovalIds,queueLength:s.queueLength,contextRefs:s.contextRefs}),c(!1)}else if("JsonPatch"in a){if(!S||!Array.isArray(a.JsonPatch))throw Error("invalid patch frame");let s=function(e,r){let s=e;for(let e of r){if(!lf(e)||"add"!==e.op&&"replace"!==e.op||"string"!=typeof e.path||!lf(e.value))return null;let r=/^\/messages\/(0|[1-9]\d*)$/.exec(e.path);if(r&&"ENTRY"===e.value.type&&lp(e.value.content)){let n=e.value.content,i=Number(r[1]);if(!Number.isSafeInteger(i)||null!==s.thread&&n.thread_id!==s.thread.id)return null;let a=[...s.messages];if("add"===e.op){if(i>a.length||a.some(e=>e.id===n.id))return null;a.push(n),a.sort((e,r)=>e.sequence-r.sequence)}else{let e=a.findIndex(e=>e.id===n.id);if(e<0)return null;a[e]=n}s={...s,messages:a,earliestSequence:a[0]?.sequence??null}}else if("/messages"===e.path&&"MESSAGES"===e.value.type&&Array.isArray(e.value.content)&&e.value.content.every(lp)&&"boolean"==typeof e.value.hasEarlierMessages&&(null===e.value.earliestSequence||Number.isSafeInteger(e.value.earliestSequence))&&e.value.content.every(e=>null===s.thread||e.thread_id===s.thread.id)){let r=null!==s.earliestSequence&&null!==e.value.earliestSequence&&s.earliestSequence<e.value.earliestSequence,n=r?lh(s.messages,e.value.content):e.value.content;s={...s,messages:n,earliestSequence:n[0]?.sequence??null,hasEarlierMessages:r?s.hasEarlierMessages:e.value.hasEarlierMessages}}else if("/status"===e.path&&"STATUS"===e.value.type&&lg(e.value.content))s={...s,status:e.value.content};else if("/activeTurnId"===e.path&&"ACTIVE_TURN"===e.value.type&&(null===e.value.content||"string"==typeof e.value.content))s={...s,activeTurnId:e.value.content};else if("/pendingApprovalIds"===e.path&&"APPROVALS"===e.value.type&&Array.isArray(e.value.content)&&e.value.content.every(e=>"string"==typeof e&&e.length>0))s={...s,pendingApprovalIds:[...new Set(e.value.content)].sort()};else if("/queueLength"===e.path&&"QUEUE"===e.value.type&&Number.isSafeInteger(e.value.content)&&e.value.content>=0)s={...s,queueLength:e.value.content};else{if(!("/contextRefs"===e.path&&"CONTEXT"===e.value.type&&Array.isArray(e.value.content)&&e.value.content.every(lm)&&e.value.content.every(e=>null===s.thread||e.thread_id===s.thread.id)))return null;s={...s,contextRefs:e.value.content}}}return s}(w.current,a.JsonPatch);if(!s)throw Error("invalid patch frame");l=Date.now(),s.thread&&lu(T.current,{identity:{projectId:e,threadId:r,userId:s.thread.user_id},thread:s.thread,messages:s.messages,hasEarlierMessages:s.hasEarlierMessages,earliestSequence:s.earliestSequence,status:s.status,activeTurnId:s.activeTurnId,pendingApprovalIds:s.pendingApprovalIds,queueLength:s.queueLength,contextRefs:s.contextRefs}),h(s)}else if("error"in a){if("Thread not found"===a.error)return void k(x);E(x,"string"==typeof a.error?a.error:"Project Chat stream failed")}else throw Error("unknown frame")}catch{E(x,"Invalid Project Chat stream message")}},x.onerror=()=>{E(x)},x.onclose=()=>{g()&&A.current===x&&(d?.socket===x&&C(d),A.current=null,m(!1),N())}}catch(e){if(!v(n))return;if(C(n),lf(e)&&(404===e.status||e instanceof Error&&"Thread not found"===e.message))return void k();c(!1),_(e instanceof Error?e.message:"Failed to open Project Chat thread"),N()}}let M=()=>{if(!g())return;x(),d&&C(d);let e=A.current;e&&(A.current=null,e.close()),m(!1),D(!0)},F=()=>M(),P=()=>{"visible"===document.visibilityState&&(d||null!==l&&Date.now()-l>4e4)&&M()};return window.addEventListener("online",F),document.addEventListener("visibilitychange",P),D(!1),()=>{n=!0,x(),d&&C(d),window.removeEventListener("online",F),document.removeEventListener("visibilitychange",P);let e=A.current;A.current=null,e?.close()}},[e,r]);let I=(0,$.useCallback)(async e=>{let r=S.current,n=C.current;if(!r)throw Error("No project selected");let a=await s(e);return a.project_id===r&&P(r,n)&&i(e=>[a,...e.filter(e=>e.id!==a.id)]),a},[s,P]),B=(0,$.useCallback)(e=>{if(i(r=>null===e.archived_at?[e,...r.filter(r=>r.id!==e.id)]:r.filter(r=>r.id!==e.id)),w.current.thread?.id===e.id){let r={...w.current,thread:e};w.current=r,f(r)}let r=T.current.get(e.id);r&&lu(T.current,{...r,thread:e})},[]),L=(0,$.useCallback)(async(e,r)=>{let s=S.current,n=C.current,i=r.trim();if(!i)throw Error("Title is required");let a=(D.current.get(e)??0)+1;D.current.set(e,a);let o=await rv.api.updateProjectChatThread(e,{title:i});return s&&o.project_id===s&&D.current.get(e)===a&&P(s,n)&&B(o),o},[P,B]),z=(0,$.useCallback)(async(e,r=!0)=>{let s=S.current,n=C.current,i=(D.current.get(e)??0)+1;D.current.set(e,i);let a=await rv.api.updateProjectChatThread(e,{archived:r});return s&&a.project_id===s&&D.current.get(e)===i&&P(s,n)&&B(a),a},[P,B]),O=(0,$.useCallback)(async e=>{let r=S.current,s=C.current,n=(D.current.get(e)??0)+1;if(D.current.set(e,n),await rv.api.deleteProjectChatThread(e),r&&D.current.get(e)===n&&P(r,s)&&(T.current.delete(e),i(r=>r.filter(r=>r.id!==e)),j.current===e)){R.current+=1,A.current?.close(),A.current=null,m(!1),c(!1);let e=ld();w.current=e,f(e)}},[P]),W=(0,$.useCallback)(async e=>{let r=j.current;if(!r)throw Error("No Project Chat thread selected");let s=e.trim();if(!s)throw Error("Message is required");await rv.api.sendProjectChatMessage(r,s)},[]),H=(0,$.useCallback)(async e=>{let r=j.current;return!!r&&rv.api.stopProjectChatTurn(r,e)},[]),U=(0,$.useCallback)(async(e,r)=>{let s=j.current;if(!s)throw Error("No Project Chat thread selected");await rv.api.approveProjectChatTool(s,e,r)},[]),q=(0,$.useCallback)(async(e,r)=>{let s=j.current;if(!s)throw Error("No Project Chat thread selected");await rv.api.selectProjectChatWorkspace(s,e,r)},[]),K=(0,$.useCallback)(async()=>{let e=j.current,r=w.current;if(e&&r.hasEarlierMessages&&null!==r.earliestSequence){u(!0);try{let s=await rv.api.listProjectChatMessages(e,{beforeSequence:r.earliestSequence});if(j.current!==e||w.current.thread?.id!==e)return;let n=lh(w.current.messages,s.messages),i={...w.current,messages:n,hasEarlierMessages:s.hasMore,earliestSequence:n[0]?.sequence??null};w.current=i,f(i),_(null)}catch(r){j.current===e&&_(r instanceof Error?r.message:"Failed to load earlier messages")}finally{j.current===e&&u(!1)}}},[]);return{...h,threads:n,loading:a||l,threadsLoading:a,threadLoading:l,loadingEarlierMessages:d,isConnected:p,error:v??g,terminalError:y,refetchThreads:F,createThread:I,renameThread:L,archiveThread:z,deleteThread:O,sendMessage:W,stopTurn:H,resolveToolApproval:U,selectWorkspace:q,loadEarlierMessages:K}}(e,r),[u,h]=(0,$.useState)(!0),[f,p]=(0,$.useState)(!1),[m,g]=(0,$.useState)(!1),[x,v]=(0,$.useState)(!1),[_,y]=(0,$.useState)(null),b=(0,$.useRef)(!1),w=(0,$.useRef)(new Map),S=(0,$.useRef)(null),j=(0,$.useRef)(0),C=sM(d.thread),k=d.threads.filter(e=>null===e.archived_at),N=`${e}:${r}`,E=function(){let[e,r]=$.useState(void 0);return $.useEffect(()=>{let e=window.matchMedia("(max-width: 767px)"),s=()=>{r(window.innerWidth<768)};return e.addEventListener("change",s),r(window.innerWidth<768),()=>e.removeEventListener("change",s)},[]),!!e}(),D=e=>{p(e),e||requestAnimationFrame(()=>S.current?.focus())};(0,$.useEffect)(()=>{j.current+=1,b.current=!1,v(!1),y(null),g(!1),p(!1)},[N]);let R=async()=>{if(b.current)return;let r=j.current;b.current=!0,v(!0),y(null);try{let s=await d.createThread();r===j.current&&s.project_id===e&&i(s.id)}catch(e){r===j.current&&y(e instanceof Error?e.message:"Failed to create thread")}finally{r===j.current&&(b.current=!1,v(!1))}},A=e=>{if(e!==r)return;let s=k.find(r=>r.id!==e);s?i(s.id):n()},T=async e=>{let r=j.current;await d.archiveThread(e,!0),r===j.current&&A(e)},M=async e=>{let r=j.current;await d.deleteThread(e),r===j.current&&A(e)};return(0,O.jsxs)("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[(0,O.jsxs)("header",{className:"flex h-12 shrink-0 items-center justify-between gap-3 border-b px-3 sm:px-4",children:[(0,O.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,O.jsx)(W.Button,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"Back to Overview",onClick:n,children:(0,O.jsx)(o9.ArrowLeft,{className:"size-4"})}),(0,O.jsx)(sD,{className:"size-4 shrink-0 text-primary","aria-hidden":"true"}),(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsxs)("div",{className:"truncate text-[11px] text-muted-foreground",children:[s," / Project Chat"]}),(0,O.jsxs)(a4,{open:m,onOpenChange:g,children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsxs)("button",{type:"button","aria-label":`Current thread: ${C}`,className:"flex max-w-[50vw] items-center gap-1 truncate text-sm font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,O.jsx)("span",{className:"truncate",children:C}),(0,O.jsx)(ns,{className:"size-3.5 shrink-0"})]})}),(0,O.jsxs)(a7,{align:"start",className:"w-64",children:[k.slice(0,5).map(e=>{let r=sM(e);return(0,O.jsx)(a8,{asChild:!0,children:(0,O.jsx)("button",{type:"button","aria-label":`Switch to thread: ${r}`,onClick:()=>i(e.id),className:"w-full truncate text-left",children:r})},e.id)}),(0,O.jsx)(a8,{asChild:!0,children:(0,O.jsxs)("button",{type:"button",disabled:x,onClick:()=>void R(),className:"w-full border-t",children:[(0,O.jsx)(eS,{className:"size-3.5"}),"New thread"]})})]})]})]})]}),(0,O.jsx)(W.Button,{ref:S,type:"button",variant:"ghost",size:"icon-sm","aria-label":E?"Open threads and context":u?"Hide threads and context":"Show threads and context",onClick:()=>E?p(!0):h(e=>!e),children:E?(0,O.jsx)(lt,{className:"size-4"}):u?(0,O.jsx)(le,{className:"size-4"}):(0,O.jsx)(lt,{className:"size-4"})})]}),_?(0,O.jsx)("div",{role:"alert",className:"border-b border-destructive/40 bg-destructive/10 px-4 py-2 text-sm text-destructive",children:_}):null,(0,O.jsxs)("div",{className:"flex min-h-0 flex-1","data-testid":"project-chat-workbench-columns",children:[(0,O.jsx)("main",{"data-testid":"project-chat-main","data-project-chat-column":!0,className:"min-w-0 flex-1",children:"thread_not_found"===d.terminalError?(0,O.jsx)("div",{className:"flex h-full items-center justify-center p-6 text-center",children:(0,O.jsxs)("div",{children:[(0,O.jsx)("h2",{className:"font-semibold",children:"Thread not found"}),(0,O.jsx)(W.Button,{className:"mt-3",variant:"outline",onClick:n,children:"Back to Overview"})]})}):(0,O.jsx)(cZ,{messages:d.messages,contextRefs:d.contextRefs,status:d.status,activeTurnId:d.activeTurnId,pendingApprovalIds:d.pendingApprovalIds,queueLength:d.queueLength,loading:d.threadLoading,hasEarlierMessages:d.hasEarlierMessages,loadingEarlierMessages:d.loadingEarlierMessages,connected:d.isConnected,error:d.error,initialDraft:w.current.get(N)??"",onDraftChange:e=>{e?w.current.set(N,e):w.current.delete(N)},onDraftSent:e=>{w.current.get(N)===e&&w.current.delete(N)},onSend:d.sendMessage,onLoadEarlierMessages:d.loadEarlierMessages,onStop:d.stopTurn,onResolveApproval:d.resolveToolApproval,onSelectWorkspace:d.selectWorkspace,onOpenAgentSession:o,onOpenScheduleRun:l,onRunScheduleAgain:c},N)}),!E&&u?(0,O.jsx)(lG,{projectId:e,currentThreadId:r,threads:d.threads,contextRefs:d.contextRefs,onNewThread:R,onSelectThread:i,onRenameThread:async(e,r)=>{await d.renameThread(e,r)},onArchiveThread:T,onDeleteThread:M,onOpenContext:a,newThreadPending:x},N):null]}),E?(0,O.jsx)(ls,{open:f,onOpenChange:D,children:(0,O.jsxs)(la,{side:"right","data-testid":"project-chat-mobile-drawer",className:"w-[min(90vw,360px)] gap-0 p-0","aria-label":"Project Chat threads and context",onCloseAutoFocus:e=>{e.preventDefault(),S.current?.focus()},children:[(0,O.jsxs)(lo,{className:"shrink-0 border-b px-4 py-3 pr-14 text-left",children:[(0,O.jsx)(ll,{className:"text-sm",children:"Threads and context"}),(0,O.jsx)(lc,{className:"text-xs",children:"Switch conversations and open referenced project items."})]}),(0,O.jsx)(lG,{projectId:e,className:"min-h-0 w-full flex-1 border-l-0",currentThreadId:r,threads:d.threads,contextRefs:d.contextRefs,onNewThread:R,onSelectThread:e=>{D(!1),i(e)},onRenameThread:async(e,r)=>{await d.renameThread(e,r)},onArchiveThread:T,onDeleteThread:M,onOpenContext:a?e=>{D(!1),a(e)}:void 0,newThreadPending:x},N)]})}):null]})}function c0(e){return e?"target-not-found"===e.error?e.requestedTarget:e.target:null}function c1(e){let r=[],s=`vibedeckx:mergeTarget:${e}:`;try{for(let e=0;e<localStorage.length;e+=1){let n=localStorage.key(e);if(!n?.startsWith(s))continue;let i=localStorage.getItem(n);i&&r.push({key:n,branch:n.slice(s.length),target:i})}}catch{}return r}let c2=new Map,c5=new Set(["working","main-running"]);function c3(e,r){return`vibedeckx:schedule-rerun:v2:${encodeURIComponent(e)}:${encodeURIComponent(r)}`}function c4(e){try{window.sessionStorage.removeItem(e)}catch{}}var ck=cC;let c6=(0,ew.default)("columns-3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]),c7=(0,ew.default)("settings",[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),c8={sm:{box:"size-4 rounded",text:"text-[9.5px]",icon:"size-2.5",letters:1},md:{box:"size-5 rounded-[5px]",text:"text-[9px]",icon:"size-3",letters:2}};function c9({name:e,size:r="sm",className:s}){let n=c8[r],i=s_(e,n.letters);return(0,O.jsx)("span",{"aria-hidden":"true",className:(0,ey.cn)("grid shrink-0 place-items-center bg-primary/14 font-mono font-semibold leading-none tracking-[-0.02em] text-primary",n.box,n.text,s),children:i||(0,O.jsx)(oY,{className:(0,ey.cn)(n.icon,"text-primary")})})}let de=(0,ew.default)("check-check",[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]]);function dt({info:e,repositoryLabel:r,onClick:s}){let n=function(e,r){if("target-not-found"===e.error){let s=`Target branch '${e.requestedTarget}' not found — pick a new target or reset to default`;return r?`${s} \xb7 ${r}`:s}let s=["merged"===e.status?`Merged into ${e.target}`:"no-unique-commits"===e.status?`In sync with ${e.target}`:`${e.unmergedCount} commit${1!==e.unmergedCount?"s":""} not in ${e.target}`];return e.dirty&&s.push("uncommitted changes"),r&&s.push(r),s.join(" · ")}(e,r);return(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsxs)("button",{onClick:e=>{e.stopPropagation(),s()},"aria-label":n,className:"relative shrink-0 flex items-center justify-center h-4 min-w-4 px-0.5 rounded hover:bg-muted",children:["target-not-found"===e.error?(0,O.jsx)(s6,{className:"h-3 w-3 text-amber-500"}):"merged"===e.status?(0,O.jsx)(rf.Check,{className:"h-3 w-3 text-muted-foreground/70"}):"no-unique-commits"===e.status?(0,O.jsx)(de,{className:"h-3 w-3 text-emerald-500"}):(0,O.jsx)("span",{className:"text-[10px] font-mono leading-none text-amber-500",children:e.unmergedCount}),!e.error&&e.dirty&&(0,O.jsx)("span",{className:"absolute -top-0.5 -right-0.5 h-1.5 w-1.5 rounded-full bg-orange-400"})]})}),(0,O.jsx)(cj,{side:"right",children:n})]})}let dr=(0,ew.default)("git-merge",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]]);function ds({projectId:e,branch:r,currentTarget:s,onTargetChange:n,onTargetReset:i,onDelete:a}){let[o,l]=(0,$.useState)(null),c=async()=>{null!==o||l((await rv.api.getProjectBranches(e)).filter(e=>e!==r))};return(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)("button",{onClick:e=>e.stopPropagation(),className:"shrink-0 p-0.5 rounded opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 hover:bg-muted transition-all",title:"Workspace menu",children:(0,O.jsx)(lx,{className:"h-3 w-3"})})}),(0,O.jsxs)(a7,{side:"right",align:"start",children:[(0,O.jsxs)(on,{children:[(0,O.jsxs)(oi,{onPointerEnter:c,onFocus:c,children:[(0,O.jsx)(dr,{className:"h-3.5 w-3.5 mr-1.5"}),"Compare against"]}),(0,O.jsxs)(oa,{children:[null===o?(0,O.jsx)(a8,{disabled:!0,children:"Loading…"}):0===o.length?(0,O.jsx)(a8,{disabled:!0,children:"No other branches"}):o.map(e=>(0,O.jsx)(a9,{checked:e===s,onCheckedChange:()=>n(e),children:(0,O.jsx)("span",{className:"font-mono text-xs",children:e})},e)),(0,O.jsx)(os,{}),(0,O.jsx)(a8,{onClick:i,children:(0,O.jsx)("span",{className:"text-xs",children:"Default branch (auto)"})})]})]}),(0,O.jsxs)(a8,{onClick:a,className:"text-destructive focus:text-destructive",children:[(0,O.jsx)(rc,{className:"h-3.5 w-3.5 mr-1.5"}),"Delete worktree"]})]})]})}function dn({status:e}){let r="relative h-[7px] w-[7px] rounded-full shrink-0";return e&&"idle"!==e?"working"===e?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-blue-500"),children:(0,O.jsx)("span",{className:"absolute inset-[-2px] rounded-full bg-blue-500",style:{animation:"status-dot-pulse 1.6s ease-out infinite",opacity:.5}})}):"main-running"===e?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-violet-500"),children:(0,O.jsx)("span",{className:"absolute inset-[-2px] rounded-full bg-violet-500",style:{animation:"status-dot-pulse 1.6s ease-out infinite",opacity:.5}})}):"main-completed"===e?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-emerald-500")}):"stopped"===e?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-amber-500")}):(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-lime-400")}):(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-muted-foreground/40")})}function di({status:e}){let r="relative h-[7px] w-[7px] rounded-full shrink-0";return"running"===e?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-blue-500"),children:(0,O.jsx)("span",{className:"absolute inset-[-2px] rounded-full bg-blue-500",style:{animation:"status-dot-pulse 1.6s ease-out infinite",opacity:.5}})}):"error"===e?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-red-500")}):(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-lime-400")})}function da({schedule:e}){let r="relative h-[7px] w-[7px] rounded-full shrink-0";if(e.running)return(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-blue-500"),children:(0,O.jsx)("span",{className:"absolute inset-[-2px] rounded-full bg-blue-500",style:{animation:"status-dot-pulse 1.6s ease-out infinite",opacity:.5}})});let s=e.last_run;return s&&"skipped"!==s.status?"completed"===s.status?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-emerald-500")}):"failed"===s.status||"timeout"===s.status||"killed"===s.status?(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-red-500")}):(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-blue-500")}):(0,O.jsx)("span",{className:(0,ey.cn)(r,"bg-muted-foreground/40")})}function dl({children:e,className:r}){return(0,O.jsx)("div",{className:(0,ey.cn)("px-2 pt-2.5 pb-1.5 border-t border-border/50 first:border-t-0",r),children:e})}function dc({children:e,action:r}){return(0,O.jsxs)("div",{className:"flex items-center justify-between px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.06em] text-muted-foreground/80",children:[(0,O.jsx)("span",{children:e}),r]})}function dd({icon:e,label:r,active:s,disabled:n,onClick:i}){return(0,O.jsxs)("button",{onClick:i,disabled:n,className:(0,ey.cn)("relative w-full flex items-center gap-[9px] rounded-md px-2 py-[5px] text-[12.5px] font-normal transition-colors",n&&"text-muted-foreground/40 cursor-not-allowed",!n&&!s&&"text-foreground/75 hover:bg-muted hover:text-foreground",s&&"bg-card text-foreground font-medium shadow-sm"),children:[s&&(0,O.jsx)("span",{className:"absolute -left-2 top-1.5 bottom-1.5 w-[2px] rounded-full bg-primary"}),(0,O.jsx)("span",{className:(0,ey.cn)("shrink-0 flex items-center justify-center",s?"text-foreground":"text-muted-foreground"),children:e}),(0,O.jsx)("span",{className:"truncate text-left",children:r})]})}function du({activeView:e,onViewChange:r,worktrees:s,selectedBranch:n,onBranchChange:i,currentProject:a,onCreateWorktreeOpen:o,onDeleteWorktree:l,mergeStatuses:c,mergeDefaultTarget:d,mergeRepositoryLabel:u,onMergeTargetChange:h,onMergeBadgeClick:f,workspaceStatuses:p,residentSessions:m,selectedSessionId:g,onResidentSessionSelect:x,hasProject:v=!0,projects:_,onSelectProject:y,onCreateProjectOpen:b,schedules:w,selectedScheduleId:S,onScheduleSelect:j,onCreateScheduleOpen:C}){let k=(0,$.useRef)(null);return(0,$.useEffect)(()=>{k.current?.scrollIntoView({block:"nearest"})},[a?.id,_]),(0,O.jsxs)("nav",{className:"w-[220px] border-r border-border bg-sidebar flex flex-col overflow-hidden",children:[(0,O.jsxs)(dl,{children:[(0,O.jsx)(dc,{action:(0,O.jsx)("button",{onClick:b,className:"p-0.5 rounded hover:bg-muted hover:text-foreground transition-colors text-muted-foreground",title:"Create new project",children:(0,O.jsx)(eS,{className:"h-3 w-3"})}),children:"Projects"}),_&&_.length>0?(0,O.jsx)(cb,{delayDuration:300,children:(0,O.jsx)("div",{className:"flex flex-col gap-0.5 max-h-40 overflow-y-auto mt-0.5",children:_.map(s=>{let n=a?.id===s.id,i=n&&("project-info"===e||"project-chat"===e);return(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsxs)("button",{ref:n?k:void 0,onClick:()=>{y?.(s),r("project-info")},className:(0,ey.cn)("relative w-full flex items-center gap-1.5 rounded-md px-2 py-[5px] text-[12.5px] transition-colors min-w-0","hover:bg-muted hover:text-foreground",n?"text-foreground font-medium":"text-foreground/75"),children:[i&&(0,O.jsx)("span",{className:"absolute -left-2 top-1.5 bottom-1.5 w-[2px] rounded-full bg-primary"}),(0,O.jsx)(c9,{name:s.name}),(0,O.jsx)("span",{className:"truncate flex-1 text-left",children:s.name}),n&&(0,O.jsx)(r_,{className:"h-3 w-3 shrink-0 text-muted-foreground ml-auto"})]})}),(0,O.jsx)(cj,{side:"right",children:s.name})]},s.id)})})}):(0,O.jsx)("span",{className:"block px-2 mt-1 text-[11.5px] text-muted-foreground/60",children:"No projects yet"})]}),(0,O.jsxs)(dl,{children:[(0,O.jsx)(dc,{children:"Navigation"}),(0,O.jsx)("div",{className:"flex flex-col gap-0.5 mt-0.5",children:(0,O.jsx)(dd,{icon:(0,O.jsx)(sQ,{className:"h-3.5 w-3.5"}),label:"Tasks",active:"tasks"===e&&v,disabled:!v,onClick:()=>{v&&(i?.(null),r("tasks"))}})})]}),(0,O.jsxs)(dl,{children:[(0,O.jsx)(dc,{action:a?(0,O.jsx)("button",{onClick:C,className:"p-0.5 rounded hover:bg-muted hover:text-foreground transition-colors text-muted-foreground",title:"Create scheduled task",children:(0,O.jsx)(eS,{className:"h-3 w-3"})}):void 0,children:"Schedule"}),a&&w&&w.length>0&&(0,O.jsx)("div",{className:"flex flex-col gap-px",children:w.map(r=>{let s="schedules"===e&&S===r.id;return(0,O.jsxs)("button",{onClick:()=>j?.(r.id),className:(0,ey.cn)("w-full min-w-0 flex items-center gap-2 rounded-[5px] px-2 py-1 text-[11.5px] transition-colors overflow-hidden",!s&&"text-foreground/80 hover:bg-muted",s&&"bg-accent text-accent-foreground font-medium",!r.enabled&&"opacity-50"),children:[(0,O.jsx)(da,{schedule:r}),(0,O.jsx)("span",{className:"truncate text-left flex-1",children:r.name}),"local"!==r.target&&(0,O.jsx)(ry,{className:"h-2.5 w-2.5 shrink-0 text-violet-500","aria-label":"remote"})]},r.id)})}),a&&w&&0===w.length&&(0,O.jsx)("span",{className:"block px-2 mt-1 text-[11.5px] text-muted-foreground/60",children:"No scheduled tasks"})]}),(0,O.jsxs)(dl,{className:"flex-1 overflow-y-auto",children:[(0,O.jsx)(dc,{action:a?(0,O.jsx)("button",{onClick:o,className:"p-0.5 rounded hover:bg-muted hover:text-foreground transition-colors text-muted-foreground",title:"Create new worktree",children:(0,O.jsx)(eS,{className:"h-3 w-3"})}):void 0,children:"Workspace"}),a&&s&&s.length>0&&(0,O.jsx)(O.Fragment,{children:(0,O.jsx)(cb,{delayDuration:300,children:(0,O.jsx)("div",{className:"flex flex-col gap-px",children:s.map(s=>{var o;let v="workspace"===e&&n===s.branch,_=null===s.branch?"":s.branch,y=void 0!==s.currentBranch,b=s.currentBranch??"detached HEAD",w=s.branch??s.expectedBranch??"main",S=m?.get(_)??[],j=(o=p?.get(_),S.length>0&&"main-running"!==o&&"main-completed"!==o?"idle":o);return(0,O.jsxs)("div",{className:(0,ey.cn)("min-w-0 rounded-[3px]",v&&"bg-accent"),children:[(0,O.jsxs)("div",{className:"group relative flex items-center min-w-0 gap-0.5 pr-1",children:[(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsxs)("button",{onClick:()=>{i?.(s.branch),r("workspace")},className:(0,ey.cn)("flex-1 min-w-0 flex items-center gap-2 rounded-[3px] pl-2 pr-1 py-1 font-mono text-[11.5px] transition-colors overflow-hidden",!v&&"text-foreground/80 hover:bg-muted",v&&"text-accent-foreground font-medium"),children:[(0,O.jsx)(dn,{status:j}),(0,O.jsxs)("span",{className:"truncate text-left",children:[w,y&&(0,O.jsxs)("span",{className:"text-amber-600 dark:text-amber-400",children:[" → ",b]})]})]})}),(0,O.jsx)(cj,{side:"right",children:y?`Workspace branch: ${w}; currently checked out: ${b}`:w})]}),null!==s.branch&&c?.get(s.branch)&&(0,O.jsx)(dt,{info:c.get(s.branch),repositoryLabel:u,onClick:()=>f?.(s.branch)}),null!==s.branch&&a&&(0,O.jsx)(ds,{projectId:a.id,branch:s.branch,currentTarget:c0(c?.get(s.branch))??d??null,onTargetChange:e=>h?.(s.branch,e),onTargetReset:()=>h?.(s.branch,null),onDelete:()=>l?.(s)})]}),S.length>0&&(0,O.jsx)("div",{className:"ml-4 mt-px flex flex-col gap-px",children:S.map(r=>{let s="workspace"===e&&g===r.id;return(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsxs)("button",{onClick:()=>x?.(r),className:(0,ey.cn)("min-w-0 flex items-center gap-1.5 rounded-[3px] py-0.5 pl-1.5 pr-2 font-mono text-[11px] transition-colors",!s&&"text-foreground/70 hover:text-foreground",s&&"text-accent-foreground font-medium"),children:[(0,O.jsx)("span",{className:"shrink-0 text-muted-foreground/70",children:"└"}),(0,O.jsx)(di,{status:r.status}),(0,O.jsx)("span",{className:"truncate text-left",children:r.title})]})}),(0,O.jsx)(cj,{side:"right",children:r.title})]},r.id)})})]},s.branch??"__main__")})})})}),(!s||0===s.length)&&(0,O.jsx)("div",{className:"mt-0.5",children:(0,O.jsx)(dd,{icon:(0,O.jsx)(c6,{className:"h-3.5 w-3.5"}),label:"Workspace",active:"workspace"===e,onClick:()=>r("workspace")})})]}),(0,O.jsx)(dl,{children:(0,O.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,O.jsx)(dd,{icon:(0,O.jsx)(ry,{className:"h-3.5 w-3.5"}),label:"Remote Servers",active:"remote-servers"===e,onClick:()=>r("remote-servers")}),(0,O.jsx)(dd,{icon:(0,O.jsx)(c7,{className:"h-3.5 w-3.5"}),label:"Settings",active:"settings"===e,onClick:()=>r("settings")})]})})]})}function dh({title:e,count:r,description:s,actions:n,className:i}){return(0,O.jsxs)("div",{className:(0,ey.cn)("flex items-center justify-between gap-4 px-5 pt-[14px] pb-3 border-b border-border bg-background flex-shrink-0",i),children:[(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsxs)("h1",{className:"flex items-baseline gap-2.5 m-0 text-[17px] font-semibold tracking-[-0.018em] text-foreground",children:[(0,O.jsx)("span",{className:"truncate",children:e}),void 0!==r&&(0,O.jsx)("span",{className:"font-mono text-[11.5px] font-medium text-muted-foreground/80 tracking-normal",children:r})]}),s&&(0,O.jsx)("p",{className:"text-[11.5px] text-muted-foreground mt-0.5",children:s})]}),n&&(0,O.jsx)("div",{className:"flex items-center gap-2",children:n})]})}function df({children:e,className:r}){return(0,O.jsx)("div",{className:(0,ey.cn)("flex items-center gap-1.5 px-5 py-2 border-b border-border bg-background flex-shrink-0 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",r),children:e})}function dp({active:e,count:r,onClick:s,children:n}){return(0,O.jsxs)("button",{onClick:s,className:(0,ey.cn)("inline-flex items-center gap-1.5 px-2.5 py-[3px] rounded-full text-[11.5px] font-normal transition-colors whitespace-nowrap flex-shrink-0 border",e?"bg-card text-foreground font-medium border-border shadow-sm":"bg-transparent text-muted-foreground border-transparent hover:bg-muted hover:text-foreground"),children:[n,void 0!==r&&(0,O.jsx)("span",{className:(0,ey.cn)("font-mono text-[10.5px] pl-0.5",e?"text-muted-foreground":"text-muted-foreground/70"),children:r})]})}let dm=(0,ew.default)("grip-vertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]),dg=(0,$.createContext)(null);dg.displayName="PanelGroupContext";let dx="data-panel-group-direction",dv="data-panel-group-id",d_="data-resize-handle",dy="data-panel-resize-handle-id",db=$.useLayoutEffect,dw=$["useId".toString()],dS="function"==typeof dw?dw:()=>null,dj=0;function dC(e=null){let r=dS(),s=(0,$.useRef)(e||r||null);return null===s.current&&(s.current=""+dj++),null!=e?e:s.current}function dk({children:e,className:r="",collapsedSize:s,collapsible:n,defaultSize:i,forwardedRef:a,id:o,maxSize:l,minSize:c,onCollapse:d,onExpand:u,onResize:h,order:f,style:p,tagName:m="div",...g}){let x=(0,$.useContext)(dg);if(null===x)throw Error("Panel components must be rendered within a PanelGroup container");let{collapsePanel:v,expandPanel:_,getPanelSize:y,getPanelStyle:b,groupId:w,isPanelCollapsed:S,reevaluatePanelConstraints:j,registerPanel:C,resizePanel:k,unregisterPanel:N}=x,E=dC(o),D=(0,$.useRef)({callbacks:{onCollapse:d,onExpand:u,onResize:h},constraints:{collapsedSize:s,collapsible:n,defaultSize:i,maxSize:l,minSize:c},id:E,idIsFromProps:void 0!==o,order:f});(0,$.useRef)({didLogMissingDefaultSizeWarning:!1}),db(()=>{let{callbacks:e,constraints:r}=D.current,a={...r};D.current.id=E,D.current.idIsFromProps=void 0!==o,D.current.order=f,e.onCollapse=d,e.onExpand=u,e.onResize=h,r.collapsedSize=s,r.collapsible=n,r.defaultSize=i,r.maxSize=l,r.minSize=c,(a.collapsedSize!==r.collapsedSize||a.collapsible!==r.collapsible||a.maxSize!==r.maxSize||a.minSize!==r.minSize)&&j(D.current,a)}),db(()=>{let e=D.current;return C(e),()=>{N(e)}},[f,E,C,N]),(0,$.useImperativeHandle)(a,()=>({collapse:()=>{v(D.current)},expand:e=>{_(D.current,e)},getId:()=>E,getSize:()=>y(D.current),isCollapsed:()=>S(D.current),isExpanded:()=>!S(D.current),resize:e=>{k(D.current,e)}}),[v,_,y,S,E,k]);let R=b(D.current,i);return(0,$.createElement)(m,{...g,children:e,className:r,id:E,style:{...R,...p},[dv]:w,"data-panel":"","data-panel-collapsible":n||void 0,"data-panel-id":E,"data-panel-size":parseFloat(""+R.flexGrow).toFixed(1)})}let dN=(0,$.forwardRef)((e,r)=>(0,$.createElement)(dk,{...e,forwardedRef:r}));dk.displayName="Panel",dN.displayName="forwardRef(Panel)";let dE=null,dD=-1,dR=null;function dA(e,s){var n,i,a;let o=function(e,r){if(r){let e=(r&d$)!=0,s=(r&dW)!=0,n=(r&dH)!=0,i=(r&dU)!=0;if(e)if(n)return"se-resize";else if(i)return"ne-resize";else return"e-resize";if(s)if(n)return"sw-resize";else if(i)return"nw-resize";else return"w-resize";if(n)return"s-resize";else if(i)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}(e,s);dE!==o&&(dE=o,null===dR&&(dR=document.createElement("style"),r&&dR.setAttribute("nonce",r),document.head.appendChild(dR)),dD>=0&&(null==(a=dR.sheet)||a.removeRule(dD)),dD=null!=(n=null==(i=dR.sheet)?void 0:i.insertRule(`*{cursor: ${o} !important;}`))?n:-1)}function dT(e){return"keydown"===e.type}function dM(e){return e.type.startsWith("pointer")}function dF(e){return e.type.startsWith("mouse")}function dP(e){if(dM(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(dF(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}let dI=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function dB(e){let r=e.length;for(;r--;){let s=e[r];if(d6(s,"Missing node"),function(e){var r;let s,n=getComputedStyle(e);return"fixed"===n.position||!!("auto"!==n.zIndex&&("static"!==n.position||"flex"===(s=getComputedStyle(null!=(r=dO(e))?r:e).display)||"inline-flex"===s)||1>+n.opacity||"transform"in n&&"none"!==n.transform||"webkitTransform"in n&&"none"!==n.webkitTransform||"mixBlendMode"in n&&"normal"!==n.mixBlendMode||"filter"in n&&"none"!==n.filter||"webkitFilter"in n&&"none"!==n.webkitFilter||"isolation"in n&&"isolate"===n.isolation||dI.test(n.willChange))||"touch"===n.webkitOverflowScrolling}(s))return s}return null}function dL(e){return e&&Number(getComputedStyle(e).zIndex)||0}function dz(e){let r=[];for(;e;)r.push(e),e=dO(e);return r}function dO(e){let{parentNode:r}=e;return r&&r instanceof ShadowRoot?r.host:r}let d$=1,dW=2,dH=4,dU=8,dq="coarse"===function(){if("function"==typeof matchMedia)return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}(),dK=[],dV=!1,dY=new Map,dG=new Map,dX=new Set;function dJ(e){let{target:r}=e,{x:s,y:n}=dP(e);dV=!0,d1({target:r,x:s,y:n}),d3(),dK.length>0&&(d4("down",e),e.preventDefault(),d0(r)||e.stopImmediatePropagation())}function dZ(e){let{x:r,y:s}=dP(e);if(dV&&0===e.buttons&&(dV=!1,d4("up",e)),!dV){let{target:n}=e;d1({target:n,x:r,y:s})}d4("move",e),d2(),dK.length>0&&e.preventDefault()}function dQ(e){let{target:r}=e,{x:s,y:n}=dP(e);dG.clear(),dV=!1,dK.length>0&&(e.preventDefault(),d0(r)||e.stopImmediatePropagation()),d4("up",e),d1({target:r,x:s,y:n}),d2(),d3()}function d0(e){let r=e;for(;r;){if(r.hasAttribute(d_))return!0;r=r.parentElement}return!1}function d1({target:e,x:r,y:s}){dK.splice(0);let n=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(n=e),dX.forEach(e=>{let{element:i,hitAreaMargins:a}=e,o=i.getBoundingClientRect(),{bottom:l,left:c,right:d,top:u}=o,h=dq?a.coarse:a.fine;if(r>=c-h&&r<=d+h&&s>=u-h&&s<=l+h){if(null!==n&&document.contains(n)&&i!==n&&!i.contains(n)&&!n.contains(i)&&function(e,r){let s;if(e===r)throw Error("Cannot compare node with itself");let n={a:dz(e),b:dz(r)};for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),r=n.b.pop(),s=e;d6(s,"Stacking order can only be calculated for elements with a common ancestor");let i={a:dL(dB(n.a)),b:dL(dB(n.b))};if(i.a===i.b){let e=s.childNodes,r={a:n.a.at(-1),b:n.b.at(-1)},i=e.length;for(;i--;){let s=e[i];if(s===r.a)return 1;if(s===r.b)return -1}}return Math.sign(i.a-i.b)}(n,i)>0){let e=n,r=!1;for(;e;){var f;if(e.contains(i))break;if(f=e.getBoundingClientRect(),f.x<o.x+o.width&&f.x+f.width>o.x&&f.y<o.y+o.height&&f.y+f.height>o.y){r=!0;break}e=e.parentElement}if(r)return}dK.push(e)}})}function d2(){let e=!1,r=!1;dK.forEach(s=>{let{direction:n}=s;"horizontal"===n?e=!0:r=!0});let s=0;dG.forEach(e=>{s|=e}),e&&r?dA("intersection",s):e?dA("horizontal",s):r?dA("vertical",s):null!==dR&&(document.head.removeChild(dR),dE=null,dR=null,dD=-1)}let d5=new AbortController;function d3(){d5.abort();let e={capture:!0,signal:(d5=new AbortController).signal};dX.size&&(dV?(dK.length>0&&dY.forEach((r,s)=>{let{body:n}=s;r>0&&(n.addEventListener("contextmenu",dQ,e),n.addEventListener("pointerleave",dZ,e),n.addEventListener("pointermove",dZ,e))}),window.addEventListener("pointerup",dQ,e),window.addEventListener("pointercancel",dQ,e)):dY.forEach((r,s)=>{let{body:n}=s;r>0&&(n.addEventListener("pointerdown",dJ,e),n.addEventListener("pointermove",dZ,e))}))}function d4(e,r){dX.forEach(s=>{let{setResizeHandlerState:n}=s;n(e,dK.includes(s),r)})}function d6(e,r){if(!e)throw console.error(r),Error(r)}function d7(e,r,s=10){return e.toFixed(s)===r.toFixed(s)?0:e>r?1:-1}function d8(e,r,s=10){return 0===d7(e,r,s)}function d9(e,r,s){return 0===d7(e,r,s)}function ue({panelConstraints:e,panelIndex:r,size:s}){let n=e[r];d6(null!=n,`Panel constraints not found for index ${r}`);let{collapsedSize:i=0,collapsible:a,maxSize:o=100,minSize:l=0}=n;return 0>d7(s,l)&&(s=a&&0>d7(s,(i+l)/2)?i:l),s=parseFloat((s=Math.min(o,s)).toFixed(10))}function ut({delta:e,initialLayout:r,panelConstraints:s,pivotIndices:n,prevLayout:i,trigger:a}){if(d9(e,0))return r;let o=[...r],[l,c]=n;d6(null!=l,"Invalid first pivot index"),d6(null!=c,"Invalid second pivot index");let d=0;if("keyboard"===a){{let n=e<0?c:l,i=s[n];d6(i,`Panel constraints not found for index ${n}`);let{collapsedSize:a=0,collapsible:o,minSize:d=0}=i;if(o){let s=r[n];if(d6(null!=s,`Previous layout not found for panel index ${n}`),d9(s,a)){let r=d-s;d7(r,Math.abs(e))>0&&(e=e<0?0-r:r)}}}{let n=e<0?l:c,i=s[n];d6(i,`No panel constraints found for index ${n}`);let{collapsedSize:a=0,collapsible:o,minSize:d=0}=i;if(o){let s=r[n];if(d6(null!=s,`Previous layout not found for panel index ${n}`),d9(s,d)){let r=s-a;d7(r,Math.abs(e))>0&&(e=e<0?0-r:r)}}}}{let n=e<0?1:-1,i=e<0?c:l,a=0;for(;;){let e=r[i];if(d6(null!=e,`Previous layout not found for panel index ${i}`),a+=ue({panelConstraints:s,panelIndex:i,size:100})-e,(i+=n)<0||i>=s.length)break}let o=Math.min(Math.abs(e),Math.abs(a));e=e<0?0-o:o}{let n=e<0?l:c;for(;n>=0&&n<s.length;){let i=Math.abs(e)-Math.abs(d),a=r[n];d6(null!=a,`Previous layout not found for panel index ${n}`);let l=ue({panelConstraints:s,panelIndex:n,size:a-i});if(!d9(a,l)&&(d+=a-l,o[n]=l,d.toPrecision(3).localeCompare(Math.abs(e).toPrecision(3),void 0,{numeric:!0})>=0))break;e<0?n--:n++}}if(function(e,r,s){if(e.length!==r.length)return!1;for(let s=0;s<e.length;s++)if(!d9(e[s],r[s],void 0))return!1;return!0}(i,o))return i;{let n=e<0?c:l,i=r[n];d6(null!=i,`Previous layout not found for panel index ${n}`);let a=i+d,u=ue({panelConstraints:s,panelIndex:n,size:a});if(o[n]=u,!d9(u,a)){let r=a-u,n=e<0?c:l;for(;n>=0&&n<s.length;){let i=o[n];d6(null!=i,`Previous layout not found for panel index ${n}`);let a=ue({panelConstraints:s,panelIndex:n,size:i+r});if(d9(i,a)||(r-=a-i,o[n]=a),d9(r,0))break;e>0?n--:n++}}}return d9(o.reduce((e,r)=>r+e,0),100)?o:i}function ur(e,r=document){return Array.from(r.querySelectorAll(`[${dy}][data-panel-group-id="${e}"]`))}function us(e,r,s=document){let n=ur(e,s).findIndex(e=>e.getAttribute(dy)===r);return null!=n?n:null}function un(e,r,s){let n=us(e,r,s);return null!=n?[n,n+1]:[-1,-1]}function ui(e,r=document){var s;if(r instanceof HTMLElement&&(null==r||null==(s=r.dataset)?void 0:s.panelGroupId)==e)return r;let n=r.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return n||null}function ua(e,r=document){let s=r.querySelector(`[${dy}="${e}"]`);return s||null}function uo(e,r){if(e.length!==r.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==r[s])return!1;return!0}function ul(e,r){let{x:s,y:n}=dP(r);return"horizontal"===e?s:n}function uc(e,r,s){r.forEach((r,n)=>{let i=e[n];d6(i,`Panel data not found for index ${n}`);let{callbacks:a,constraints:o,id:l}=i,{collapsedSize:c=0,collapsible:d}=o,u=s[l];if(null==u||r!==u){s[l]=r;let{onCollapse:e,onExpand:n,onResize:i}=a;i&&i(r,u),d&&(e||n)&&(n&&(null==u||d8(u,c))&&!d8(r,c)&&n(),e&&(null==u||!d8(u,c))&&d8(r,c)&&e())}})}function ud(e,r){if(e.length!==r.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!=r[s])return!1;return!0}function uu(e){try{if("undefined"!=typeof localStorage)e.getItem=e=>localStorage.getItem(e),e.setItem=(e,r)=>{localStorage.setItem(e,r)};else throw Error("localStorage not supported in this environment")}catch(r){console.error(r),e.getItem=()=>null,e.setItem=()=>{}}}function uh(e){return`react-resizable-panels:${e}`}function uf(e){return e.map(e=>{let{constraints:r,id:s,idIsFromProps:n,order:i}=e;return n?s:i?`${i}:${JSON.stringify(r)}`:JSON.stringify(r)}).sort((e,r)=>e.localeCompare(r)).join(",")}function up(e,r){try{let s=uh(e),n=r.getItem(s);if(n){let e=JSON.parse(n);if("object"==typeof e&&null!=e)return e}}catch(e){}return null}function um(e,r,s,n,i){var a;let o=uh(e),l=uf(r),c=null!=(a=up(e,i))?a:{};c[l]={expandToSizes:Object.fromEntries(s.entries()),layout:n};try{i.setItem(o,JSON.stringify(c))}catch(e){console.error(e)}}function ug({layout:e,panelConstraints:r}){let s=[...e],n=s.reduce((e,r)=>e+r,0);if(s.length!==r.length)throw Error(`Invalid ${r.length} panel layout: ${s.map(e=>`${e}%`).join(", ")}`);if(!d9(n,100)&&s.length>0)for(let e=0;e<r.length;e++){let r=s[e];d6(null!=r,`No layout data found for index ${e}`);let i=100/n*r;s[e]=i}let i=0;for(let e=0;e<r.length;e++){let n=s[e];d6(null!=n,`No layout data found for index ${e}`);let a=ue({panelConstraints:r,panelIndex:e,size:n});n!=a&&(i+=n-a,s[e]=a)}if(!d9(i,0))for(let e=0;e<r.length;e++){let n=s[e];d6(null!=n,`No layout data found for index ${e}`);let a=ue({panelConstraints:r,panelIndex:e,size:n+i});if(n!==a&&(i-=a-n,s[e]=a,d9(i,0)))break}return s}let ux={getItem:e=>(uu(ux),ux.getItem(e)),setItem:(e,r)=>{uu(ux),ux.setItem(e,r)}},uv={};function u_({autoSaveId:e=null,children:r,className:s="",direction:n,forwardedRef:i,id:a=null,onLayout:o=null,keyboardResizeBy:l=null,storage:c=ux,style:d,tagName:u="div",...h}){let f=dC(a),p=(0,$.useRef)(null),[m,g]=(0,$.useState)(null),[x,v]=(0,$.useState)([]),_=function(){let[e,r]=(0,$.useState)(0);return(0,$.useCallback)(()=>r(e=>e+1),[])}(),y=(0,$.useRef)({}),b=(0,$.useRef)(new Map),w=(0,$.useRef)(0),S=(0,$.useRef)({autoSaveId:e,direction:n,dragState:m,id:f,keyboardResizeBy:l,onLayout:o,storage:c}),j=(0,$.useRef)({layout:x,panelDataArray:[],panelDataArrayChanged:!1});(0,$.useRef)({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),(0,$.useImperativeHandle)(i,()=>({getId:()=>S.current.id,getLayout:()=>{let{layout:e}=j.current;return e},setLayout:e=>{let{onLayout:r}=S.current,{layout:s,panelDataArray:n}=j.current,i=ug({layout:e,panelConstraints:n.map(e=>e.constraints)});uo(s,i)||(v(i),j.current.layout=i,r&&r(i),uc(n,i,y.current))}}),[]),db(()=>{S.current.autoSaveId=e,S.current.direction=n,S.current.dragState=m,S.current.id=f,S.current.onLayout=o,S.current.storage=c}),function({committedValuesRef:e,eagerValuesRef:r,groupId:s,layout:n,panelDataArray:i,panelGroupElement:a,setLayout:o}){(0,$.useRef)({didWarnAboutMissingResizeHandle:!1}),db(()=>{if(!a)return;let e=ur(s,a);for(let r=0;r<i.length-1;r++){let{valueMax:s,valueMin:a,valueNow:o}=function({layout:e,panelsArray:r,pivotIndices:s}){let n=0,i=100,a=0,o=0,l=s[0];return d6(null!=l,"No pivot index found"),r.forEach((e,r)=>{let{constraints:s}=e,{maxSize:c=100,minSize:d=0}=s;r===l?(n=d,i=c):(a+=d,o+=c)}),{valueMax:Math.min(i,100-a),valueMin:Math.max(n,100-o),valueNow:e[l]}}({layout:n,panelsArray:i,pivotIndices:[r,r+1]}),l=e[r];if(null==l);else{let e=i[r];d6(e,`No panel data found for index "${r}"`),l.setAttribute("aria-controls",e.id),l.setAttribute("aria-valuemax",""+Math.round(s)),l.setAttribute("aria-valuemin",""+Math.round(a)),l.setAttribute("aria-valuenow",null!=o?""+Math.round(o):"")}}return()=>{e.forEach((e,r)=>{e.removeAttribute("aria-controls"),e.removeAttribute("aria-valuemax"),e.removeAttribute("aria-valuemin"),e.removeAttribute("aria-valuenow")})}},[s,n,i,a]),(0,$.useEffect)(()=>{if(!a)return;let e=r.current;d6(e,"Eager values not found");let{panelDataArray:i}=e;d6(null!=ui(s,a),`No group found for id "${s}"`);let l=ur(s,a);d6(l,`No resize handles found for group id "${s}"`);let c=l.map(e=>{let r=e.getAttribute(dy);d6(r,"Resize handle element has no handle id attribute");let[l,c]=function(e,r,s,n=document){var i,a,o,l;let c=ua(r,n),d=ur(e,n),u=c?d.indexOf(c):-1;return[null!=(i=null==(a=s[u])?void 0:a.id)?i:null,null!=(o=null==(l=s[u+1])?void 0:l.id)?o:null]}(s,r,i,a);if(null==l||null==c)return()=>{};let d=e=>{if(!e.defaultPrevented&&"Enter"===e.key){e.preventDefault();let c=i.findIndex(e=>e.id===l);if(c>=0){let e=i[c];d6(e,`No panel data found for index ${c}`);let l=n[c],{collapsedSize:d=0,collapsible:u,minSize:h=0}=e.constraints;if(null!=l&&u){let e=ut({delta:d9(l,d)?h-d:d-l,initialLayout:n,panelConstraints:i.map(e=>e.constraints),pivotIndices:un(s,r,a),prevLayout:n,trigger:"keyboard"});n!==e&&o(e)}}}};return e.addEventListener("keydown",d),()=>{e.removeEventListener("keydown",d)}});return()=>{c.forEach(e=>e())}},[a,e,r,s,n,i,o])}({committedValuesRef:S,eagerValuesRef:j,groupId:f,layout:x,panelDataArray:j.current.panelDataArray,setLayout:v,panelGroupElement:p.current}),(0,$.useEffect)(()=>{let{panelDataArray:r}=j.current;if(e){if(0===x.length||x.length!==r.length)return;let s=uv[e];null==s&&(s=function(e,r=10){let s=null;return(...n)=>{null!==s&&clearTimeout(s),s=setTimeout(()=>{e(...n)},r)}}(um,100),uv[e]=s),s(e,[...r],new Map(b.current),x,c)}},[e,x,c]),(0,$.useEffect)(()=>{});let C=(0,$.useCallback)(e=>{let{onLayout:r}=S.current,{layout:s,panelDataArray:n}=j.current;if(e.constraints.collapsible){let i=n.map(e=>e.constraints),{collapsedSize:a=0,panelSize:o,pivotIndices:l}=uw(n,e,s);if(d6(null!=o,`Panel size not found for panel "${e.id}"`),!d8(o,a)){b.current.set(e.id,o);let c=ut({delta:ub(n,e)===n.length-1?o-a:a-o,initialLayout:s,panelConstraints:i,pivotIndices:l,prevLayout:s,trigger:"imperative-api"});ud(s,c)||(v(c),j.current.layout=c,r&&r(c),uc(n,c,y.current))}}},[]),k=(0,$.useCallback)((e,r)=>{let{onLayout:s}=S.current,{layout:n,panelDataArray:i}=j.current;if(e.constraints.collapsible){let a=i.map(e=>e.constraints),{collapsedSize:o=0,panelSize:l=0,minSize:c=0,pivotIndices:d}=uw(i,e,n),u=null!=r?r:c;if(d8(l,o)){let r=b.current.get(e.id),o=null!=r&&r>=u?r:u,c=ut({delta:ub(i,e)===i.length-1?l-o:o-l,initialLayout:n,panelConstraints:a,pivotIndices:d,prevLayout:n,trigger:"imperative-api"});ud(n,c)||(v(c),j.current.layout=c,s&&s(c),uc(i,c,y.current))}}},[]),N=(0,$.useCallback)(e=>{let{layout:r,panelDataArray:s}=j.current,{panelSize:n}=uw(s,e,r);return d6(null!=n,`Panel size not found for panel "${e.id}"`),n},[]),E=(0,$.useCallback)((e,r)=>{let{panelDataArray:s}=j.current,n=ub(s,e);return function({defaultSize:e,dragState:r,layout:s,panelData:n,panelIndex:i,precision:a=3}){let o=s[i];return{flexBasis:0,flexGrow:null==o?void 0!=e?e.toPrecision(a):"1":1===n.length?"1":o.toPrecision(a),flexShrink:1,overflow:"hidden",pointerEvents:null!==r?"none":void 0}}({defaultSize:r,dragState:m,layout:x,panelData:s,panelIndex:n})},[m,x]),D=(0,$.useCallback)(e=>{let{layout:r,panelDataArray:s}=j.current,{collapsedSize:n=0,collapsible:i,panelSize:a}=uw(s,e,r);return d6(null!=a,`Panel size not found for panel "${e.id}"`),!0===i&&d8(a,n)},[]),R=(0,$.useCallback)(e=>{let{layout:r,panelDataArray:s}=j.current,{collapsedSize:n=0,collapsible:i,panelSize:a}=uw(s,e,r);return d6(null!=a,`Panel size not found for panel "${e.id}"`),!i||d7(a,n)>0},[]),A=(0,$.useCallback)(e=>{let{panelDataArray:r}=j.current;r.push(e),r.sort((e,r)=>{let s=e.order,n=r.order;return null==s&&null==n?0:null==s?-1:null==n?1:s-n}),j.current.panelDataArrayChanged=!0,_()},[_]);db(()=>{if(j.current.panelDataArrayChanged){j.current.panelDataArrayChanged=!1;let{autoSaveId:s,onLayout:n,storage:i}=S.current,{layout:a,panelDataArray:o}=j.current,l=null;if(s){var e,r;let n=null!=(r=(null!=(e=up(s,i))?e:{})[uf(o)])?r:null;n&&(b.current=new Map(Object.entries(n.expandToSizes)),l=n.layout)}null==l&&(l=function({panelDataArray:e}){let r=Array(e.length),s=e.map(e=>e.constraints),n=0,i=100;for(let a=0;a<e.length;a++){let e=s[a];d6(e,`Panel constraints not found for index ${a}`);let{defaultSize:o}=e;null!=o&&(n++,r[a]=o,i-=o)}for(let a=0;a<e.length;a++){let o=s[a];d6(o,`Panel constraints not found for index ${a}`);let{defaultSize:l}=o;if(null!=l)continue;let c=i/(e.length-n);n++,r[a]=c,i-=c}return r}({panelDataArray:o}));let c=ug({layout:l,panelConstraints:o.map(e=>e.constraints)});uo(a,c)||(v(c),j.current.layout=c,n&&n(c),uc(o,c,y.current))}}),db(()=>{let e=j.current;return()=>{e.layout=[]}},[]);let T=(0,$.useCallback)(e=>{let r=!1,s=p.current;return s&&"rtl"===window.getComputedStyle(s,null).getPropertyValue("direction")&&(r=!0),function(s){var n,i;s.preventDefault();let a=p.current;if(!a)return()=>null;let{direction:o,dragState:l,id:c,keyboardResizeBy:d,onLayout:u}=S.current,{layout:h,panelDataArray:f}=j.current,{initialLayout:m}=null!=l?l:{},g=un(c,e,a),x=function(e,r,s,n,i,a){if(dT(e)){let r="horizontal"===s,n=0;n=e.shiftKey?100:null!=i?i:10;let a=0;switch(e.key){case"ArrowDown":a=r?0:n;break;case"ArrowLeft":a=r?-n:0;break;case"ArrowRight":a=r?n:0;break;case"ArrowUp":a=r?0:-n;break;case"End":a=100;break;case"Home":a=-100}return a}return null==n?0:function(e,r,s,n,i){let a="horizontal"===s,o=ua(r,i);d6(o,`No resize handle element found for id "${r}"`);let l=o.getAttribute(dv);d6(l,"Resize handle element has no group id attribute");let{initialCursorPosition:c}=n,d=ul(s,e),u=ui(l,i);d6(u,`No group element found for id "${l}"`);let h=u.getBoundingClientRect();return(d-c)/(a?h.width:h.height)*100}(e,r,s,n,a)}(s,e,o,l,d,a),_="horizontal"===o;_&&r&&(x=-x);let b=ut({delta:x,initialLayout:null!=m?m:h,panelConstraints:f.map(e=>e.constraints),pivotIndices:g,prevLayout:h,trigger:dT(s)?"keyboard":"mouse-or-touch"}),C=!ud(h,b);(dM(s)||dF(s))&&w.current!=x&&((w.current=x,C||0===x)?dG.set(e,0):_?(n=x<0?d$:dW,dG.set(e,n)):(i=x<0?dH:dU,dG.set(e,i))),C&&(v(b),j.current.layout=b,u&&u(b),uc(f,b,y.current))}},[]),M=(0,$.useCallback)((e,r)=>{let{onLayout:s}=S.current,{layout:n,panelDataArray:i}=j.current,a=i.map(e=>e.constraints),{panelSize:o,pivotIndices:l}=uw(i,e,n);d6(null!=o,`Panel size not found for panel "${e.id}"`);let c=ut({delta:ub(i,e)===i.length-1?o-r:r-o,initialLayout:n,panelConstraints:a,pivotIndices:l,prevLayout:n,trigger:"imperative-api"});ud(n,c)||(v(c),j.current.layout=c,s&&s(c),uc(i,c,y.current))},[]),F=(0,$.useCallback)((e,r)=>{let{layout:s,panelDataArray:n}=j.current,{collapsedSize:i=0,collapsible:a}=r,{collapsedSize:o=0,collapsible:l,maxSize:c=100,minSize:d=0}=e.constraints,{panelSize:u}=uw(n,e,s);null!=u&&(a&&l&&d8(u,i)?d8(i,o)||M(e,o):u<d?M(e,d):u>c&&M(e,c))},[M]),P=(0,$.useCallback)((e,r)=>{let{direction:s}=S.current,{layout:n}=j.current;if(!p.current)return;let i=ua(e,p.current);d6(i,`Drag handle element not found for id "${e}"`);let a=ul(s,r);g({dragHandleId:e,dragHandleRect:i.getBoundingClientRect(),initialCursorPosition:a,initialLayout:n})},[]),I=(0,$.useCallback)(()=>{g(null)},[]),B=(0,$.useCallback)(e=>{let{panelDataArray:r}=j.current,s=ub(r,e);s>=0&&(r.splice(s,1),delete y.current[e.id],j.current.panelDataArrayChanged=!0,_())},[_]),L=(0,$.useMemo)(()=>({collapsePanel:C,direction:n,dragState:m,expandPanel:k,getPanelSize:N,getPanelStyle:E,groupId:f,isPanelCollapsed:D,isPanelExpanded:R,reevaluatePanelConstraints:F,registerPanel:A,registerResizeHandle:T,resizePanel:M,startDragging:P,stopDragging:I,unregisterPanel:B,panelGroupElement:p.current}),[C,m,n,k,N,E,f,D,R,F,A,T,M,P,I,B]);return(0,$.createElement)(dg.Provider,{value:L},(0,$.createElement)(u,{...h,children:r,className:s,id:a,ref:p,style:{display:"flex",flexDirection:"horizontal"===n?"row":"column",height:"100%",overflow:"hidden",width:"100%",...d},"data-panel-group":"",[dx]:n,[dv]:f}))}let uy=(0,$.forwardRef)((e,r)=>(0,$.createElement)(u_,{...e,forwardedRef:r}));function ub(e,r){return e.findIndex(e=>e===r||e.id===r.id)}function uw(e,r,s){let n=ub(e,r),i=n===e.length-1,a=s[n];return{...r.constraints,panelSize:a,pivotIndices:i?[n-1,n]:[n,n+1]}}function uS({children:e=null,className:r="",disabled:s=!1,hitAreaMargins:n,id:i,onBlur:a,onClick:o,onDragging:l,onFocus:c,onPointerDown:d,onPointerUp:u,style:h={},tabIndex:f=0,tagName:p="div",...m}){var g,x;let v=(0,$.useRef)(null),_=(0,$.useRef)({onClick:o,onDragging:l,onPointerDown:d,onPointerUp:u});(0,$.useEffect)(()=>{_.current.onClick=o,_.current.onDragging=l,_.current.onPointerDown=d,_.current.onPointerUp=u});let y=(0,$.useContext)(dg);if(null===y)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");let{direction:b,groupId:w,registerResizeHandle:S,startDragging:j,stopDragging:C,panelGroupElement:k}=y,N=dC(i),[E,D]=(0,$.useState)("inactive"),[R,A]=(0,$.useState)(!1),[T,M]=(0,$.useState)(null),F=(0,$.useRef)({state:E});db(()=>{F.current.state=E}),(0,$.useEffect)(()=>{if(s)M(null);else{let e=S(N);M(()=>e)}},[s,N,S]);let P=null!=(g=null==n?void 0:n.coarse)?g:15,I=null!=(x=null==n?void 0:n.fine)?x:5;return(0,$.useEffect)(()=>{if(s||null==T)return;let e=v.current;d6(e,"Element ref not attached");let r=!1;return function(e,r,s,n,i){var a;let{ownerDocument:o}=r,l={direction:s,element:r,hitAreaMargins:n,setResizeHandlerState:i},c=null!=(a=dY.get(o))?a:0;return dY.set(o,c+1),dX.add(l),d3(),function(){var r;dG.delete(e),dX.delete(l);let s=null!=(r=dY.get(o))?r:1;if(dY.set(o,s-1),d3(),1===s&&dY.delete(o),dK.includes(l)){let e=dK.indexOf(l);e>=0&&dK.splice(e,1),d2(),i("up",!0,null)}}}(N,e,b,{coarse:P,fine:I},(e,s,n)=>{if(!s)return void D("inactive");switch(e){case"down":{D("drag"),r=!1,d6(n,'Expected event to be defined for "down" action'),j(N,n);let{onDragging:e,onPointerDown:s}=_.current;null==e||e(!0),null==s||s();break}case"move":{let{state:e}=F.current;r=!0,"drag"!==e&&D("hover"),d6(n,'Expected event to be defined for "move" action'),T(n);break}case"up":{D("hover"),C();let{onClick:e,onDragging:s,onPointerUp:n}=_.current;null==s||s(!1),null==n||n(),r||null==e||e()}}})},[P,b,s,I,S,N,T,j,C]),!function({disabled:e,handleId:r,resizeHandler:s,panelGroupElement:n}){(0,$.useEffect)(()=>{if(e||null==s||null==n)return;let i=ua(r,n);if(null==i)return;let a=e=>{if(!e.defaultPrevented)switch(e.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":e.preventDefault(),s(e);break;case"F6":{e.preventDefault();let s=i.getAttribute(dv);d6(s,`No group element found for id "${s}"`);let a=ur(s,n),o=us(s,r,n);d6(null!==o,`No resize element found for id "${r}"`);let l=e.shiftKey?o>0?o-1:a.length-1:o+1<a.length?o+1:0;a[l].focus()}}};return i.addEventListener("keydown",a),()=>{i.removeEventListener("keydown",a)}},[n,e,r,s])}({disabled:s,handleId:N,resizeHandler:T,panelGroupElement:k}),(0,$.createElement)(p,{...m,children:e,className:r,id:i,onBlur:()=>{A(!1),null==a||a()},onFocus:()=>{A(!0),null==c||c()},ref:v,role:"separator",style:{touchAction:"none",userSelect:"none",...h},tabIndex:f,[dx]:b,[dv]:w,[d_]:"","data-resize-handle-active":"drag"===E?"pointer":R?"keyboard":void 0,"data-panel-resize-handle-enabled":!s,[dy]:N,"data-resize-handle-state":E})}u_.displayName="PanelGroup",uy.displayName="forwardRef(PanelGroup)",uS.displayName="PanelResizeHandle";let uj=({className:e,...r})=>(0,O.jsx)(uy,{className:(0,ey.cn)("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...r}),uC=({withHandle:e,className:r,...s})=>(0,O.jsx)(uS,{className:(0,ey.cn)("relative flex w-px items-center justify-center bg-border/60 after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-[''] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:inset-x-0 data-[panel-group-direction=vertical]:after:-top-1 data-[panel-group-direction=vertical]:after:-bottom-1 data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:right-0 [&[data-resize-handle-active]]:bg-ring",r),...s,children:e&&(0,O.jsx)("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:(0,O.jsx)(dm,{className:"h-2.5 w-2.5"})})});function uk({className:e,...r}){return(0,O.jsx)("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:(0,O.jsx)("table",{"data-slot":"table",className:(0,ey.cn)("w-full caption-bottom text-sm",e),...r})})}function uN({className:e,...r}){return(0,O.jsx)("thead",{"data-slot":"table-header",className:(0,ey.cn)("[&_tr]:border-b",e),...r})}function uE({className:e,...r}){return(0,O.jsx)("tbody",{"data-slot":"table-body",className:(0,ey.cn)("[&_tr:last-child]:border-0",e),...r})}function uD({className:e,...r}){return(0,O.jsx)("tr",{"data-slot":"table-row",className:(0,ey.cn)("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",e),...r})}function uR({className:e,...r}){return(0,O.jsx)("th",{"data-slot":"table-head",className:(0,ey.cn)("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...r})}function uA({className:e,...r}){return(0,O.jsx)("td",{"data-slot":"table-cell",className:(0,ey.cn)("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...r})}var uT=[" ","Enter","ArrowUp","ArrowDown"],uM=[" ","Enter"],uF="Select",[uP,uI,uB]=rb(uF),[uL,uz]=q(uF,[uB,iw]),uO=iw(),[u$,uW]=uL(uF),[uH,uU]=uL(uF),uq=e=>{let{__scopeSelect:r,children:s,open:n,defaultOpen:i,onOpenChange:a,value:o,defaultValue:l,onValueChange:c,dir:d,name:u,autoComplete:h,disabled:f,required:p,form:m}=e,g=uO(r),[x,v]=$.useState(null),[_,y]=$.useState(null),[b,w]=$.useState(!1),S=rk(d),[j,C]=G({prop:n,defaultProp:i??!1,onChange:a,caller:uF}),[k,N]=G({prop:o,defaultProp:l,onChange:c,caller:uF}),E=$.useRef(null),D=!x||m||!!x.closest("form"),[R,A]=$.useState(new Set),T=Array.from(R).map(e=>e.props.value).join(";");return(0,O.jsx)(iC,{...g,children:(0,O.jsxs)(u$,{required:p,scope:r,trigger:x,onTriggerChange:v,valueNode:_,onValueNodeChange:y,valueNodeHasChildren:b,onValueNodeHasChildrenChange:w,contentId:ek(),value:k,onValueChange:N,open:j,onOpenChange:C,dir:S,triggerPointerDownPosRef:E,disabled:f,children:[(0,O.jsx)(uP.Provider,{scope:r,children:(0,O.jsx)(uH,{scope:e.__scopeSelect,onNativeOptionAdd:$.useCallback(e=>{A(r=>new Set(r).add(e))},[]),onNativeOptionRemove:$.useCallback(e=>{A(r=>{let s=new Set(r);return s.delete(e),s})},[]),children:s})}),D?(0,O.jsxs)(hv,{"aria-hidden":!0,required:p,tabIndex:-1,name:u,autoComplete:h,value:k,onChange:e=>N(e.target.value),disabled:f,form:m,children:[void 0===k?(0,O.jsx)("option",{value:""}):null,Array.from(R)]},T):null]})})};uq.displayName=uF;var uK="SelectTrigger",uV=$.forwardRef((e,r)=>{let{__scopeSelect:s,disabled:n=!1,...i}=e,a=uO(s),o=uW(uK,s),l=o.disabled||n,c=(0,U.useComposedRefs)(r,o.onTriggerChange),d=uI(s),u=$.useRef("touch"),[h,f,p]=hy(e=>{let r=d().filter(e=>!e.disabled),s=r.find(e=>e.value===o.value),n=hb(r,e,s);void 0!==n&&o.onValueChange(n.value)}),m=e=>{l||(o.onOpenChange(!0),p()),e&&(o.triggerPointerDownPosRef.current={x:Math.round(e.pageX),y:Math.round(e.pageY)})};return(0,O.jsx)(iN,{asChild:!0,...a,children:(0,O.jsx)(er.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":h_(o.value)?"":void 0,...i,ref:c,onClick:K(i.onClick,e=>{e.currentTarget.focus(),"mouse"!==u.current&&m(e)}),onPointerDown:K(i.onPointerDown,e=>{u.current=e.pointerType;let r=e.target;r.hasPointerCapture(e.pointerId)&&r.releasePointerCapture(e.pointerId),0===e.button&&!1===e.ctrlKey&&"mouse"===e.pointerType&&(m(e),e.preventDefault())}),onKeyDown:K(i.onKeyDown,e=>{let r=""!==h.current;e.ctrlKey||e.altKey||e.metaKey||1!==e.key.length||f(e.key),(!r||" "!==e.key)&&uT.includes(e.key)&&(m(),e.preventDefault())})})})});uV.displayName=uK;var uY="SelectValue",uG=$.forwardRef((e,r)=>{let{__scopeSelect:s,className:n,style:i,children:a,placeholder:o="",...l}=e,c=uW(uY,s),{onValueNodeHasChildrenChange:d}=c,u=void 0!==a,h=(0,U.useComposedRefs)(r,c.onValueNodeChange);return V(()=>{d(u)},[d,u]),(0,O.jsx)(er.span,{...l,ref:h,style:{pointerEvents:"none"},children:h_(c.value)?(0,O.jsx)(O.Fragment,{children:o}):a})});uG.displayName=uY;var uX=$.forwardRef((e,r)=>{let{__scopeSelect:s,children:n,...i}=e;return(0,O.jsx)(er.span,{"aria-hidden":!0,...i,ref:r,children:n||"▼"})});uX.displayName="SelectIcon";var uJ=e=>(0,O.jsx)(eW,{asChild:!0,...e});uJ.displayName="SelectPortal";var uZ="SelectContent",uQ=$.forwardRef((e,r)=>{let s=uW(uZ,e.__scopeSelect),[n,i]=$.useState();return(V(()=>{i(new DocumentFragment)},[]),s.open)?(0,O.jsx)(u5,{...e,ref:r}):n?ee.createPortal((0,O.jsx)(u0,{scope:e.__scopeSelect,children:(0,O.jsx)(uP.Slot,{scope:e.__scopeSelect,children:(0,O.jsx)("div",{children:e.children})})}),n):null});uQ.displayName=uZ;var[u0,u1]=uL(uZ),u2=(0,et.createSlot)("SelectContent.RemoveScroll"),u5=$.forwardRef((e,r)=>{let{__scopeSelect:s,position:n="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:a,onPointerDownOutside:o,side:l,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:f,collisionPadding:p,sticky:m,hideWhenDetached:g,avoidCollisions:x,...v}=e,_=uW(uZ,s),[y,b]=$.useState(null),[w,S]=$.useState(null),j=(0,U.useComposedRefs)(r,e=>b(e)),[C,k]=$.useState(null),[N,E]=$.useState(null),D=uI(s),[R,A]=$.useState(!1),T=$.useRef(!1);$.useEffect(()=>{if(y)return tN(y)},[y]),eU();let M=$.useCallback(e=>{let[r,...s]=D().map(e=>e.ref.current),[n]=s.slice(-1),i=document.activeElement;for(let s of e)if(s===i||(s?.scrollIntoView({block:"nearest"}),s===r&&w&&(w.scrollTop=0),s===n&&w&&(w.scrollTop=w.scrollHeight),s?.focus(),document.activeElement!==i))return},[D,w]),F=$.useCallback(()=>M([C,y]),[M,C,y]);$.useEffect(()=>{R&&F()},[R,F]);let{onOpenChange:P,triggerPointerDownPosRef:I}=_;$.useEffect(()=>{if(y){let e={x:0,y:0},r=r=>{e={x:Math.abs(Math.round(r.pageX)-(I.current?.x??0)),y:Math.abs(Math.round(r.pageY)-(I.current?.y??0))}},s=s=>{e.x<=10&&e.y<=10?s.preventDefault():y.contains(s.target)||P(!1),document.removeEventListener("pointermove",r),I.current=null};return null!==I.current&&(document.addEventListener("pointermove",r),document.addEventListener("pointerup",s,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",r),document.removeEventListener("pointerup",s,{capture:!0})}}},[y,P,I]),$.useEffect(()=>{let e=()=>P(!1);return window.addEventListener("blur",e),window.addEventListener("resize",e),()=>{window.removeEventListener("blur",e),window.removeEventListener("resize",e)}},[P]);let[B,L]=hy(e=>{let r=D().filter(e=>!e.disabled),s=r.find(e=>e.ref.current===document.activeElement),n=hb(r,e,s);n&&setTimeout(()=>n.ref.current.focus())}),z=$.useCallback((e,r,s)=>{let n=!T.current&&!s;(void 0!==_.value&&_.value===r||n)&&(k(e),n&&(T.current=!0))},[_.value]),W=$.useCallback(()=>y?.focus(),[y]),H=$.useCallback((e,r,s)=>{let n=!T.current&&!s;(void 0!==_.value&&_.value===r||n)&&E(e)},[_.value]),q="popper"===n?u4:u3,V=q===u4?{side:l,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:f,collisionPadding:p,sticky:m,hideWhenDetached:g,avoidCollisions:x}:{};return(0,O.jsx)(u0,{scope:s,content:y,viewport:w,onViewportChange:S,itemRefCallback:z,selectedItem:C,onItemLeave:W,itemTextRefCallback:H,focusSelectedItem:F,selectedItemText:N,position:n,isPositioned:R,searchRef:B,children:(0,O.jsx)(ty,{as:u2,allowPinchZoom:!0,children:(0,O.jsx)(eI,{asChild:!0,trapped:_.open,onMountAutoFocus:e=>{e.preventDefault()},onUnmountAutoFocus:K(i,e=>{_.trigger?.focus({preventScroll:!0}),e.preventDefault()}),children:(0,O.jsx)(eR,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:e=>e.preventDefault(),onDismiss:()=>_.onOpenChange(!1),children:(0,O.jsx)(q,{role:"listbox",id:_.contentId,"data-state":_.open?"open":"closed",dir:_.dir,onContextMenu:e=>e.preventDefault(),...v,...V,onPlaced:()=>A(!0),ref:j,style:{display:"flex",flexDirection:"column",outline:"none",...v.style},onKeyDown:K(v.onKeyDown,e=>{let r=e.ctrlKey||e.altKey||e.metaKey;if("Tab"===e.key&&e.preventDefault(),r||1!==e.key.length||L(e.key),["ArrowUp","ArrowDown","Home","End"].includes(e.key)){let r=D().filter(e=>!e.disabled).map(e=>e.ref.current);if(["ArrowUp","End"].includes(e.key)&&(r=r.slice().reverse()),["ArrowUp","ArrowDown"].includes(e.key)){let s=e.target,n=r.indexOf(s);r=r.slice(n+1)}setTimeout(()=>M(r)),e.preventDefault()}})})})})})})});u5.displayName="SelectContentImpl";var u3=$.forwardRef((e,r)=>{let{__scopeSelect:s,onPlaced:n,...i}=e,a=uW(uZ,s),o=u1(uZ,s),[l,c]=$.useState(null),[d,u]=$.useState(null),h=(0,U.useComposedRefs)(r,e=>u(e)),f=uI(s),p=$.useRef(!1),m=$.useRef(!0),{viewport:g,selectedItem:x,selectedItemText:v,focusSelectedItem:_}=o,y=$.useCallback(()=>{if(a.trigger&&a.valueNode&&l&&d&&g&&x&&v){let e=a.trigger.getBoundingClientRect(),r=d.getBoundingClientRect(),s=a.valueNode.getBoundingClientRect(),i=v.getBoundingClientRect();if("rtl"!==a.dir){let n=i.left-r.left,a=s.left-n,o=e.left-a,c=e.width+o,d=Math.max(c,r.width),u=oh(a,[10,Math.max(10,window.innerWidth-10-d)]);l.style.minWidth=c+"px",l.style.left=u+"px"}else{let n=r.right-i.right,a=window.innerWidth-s.right-n,o=window.innerWidth-e.right-a,c=e.width+o,d=Math.max(c,r.width),u=oh(a,[10,Math.max(10,window.innerWidth-10-d)]);l.style.minWidth=c+"px",l.style.right=u+"px"}let o=f(),c=window.innerHeight-20,u=g.scrollHeight,h=window.getComputedStyle(d),m=parseInt(h.borderTopWidth,10),_=parseInt(h.paddingTop,10),y=parseInt(h.borderBottomWidth,10),b=m+_+u+parseInt(h.paddingBottom,10)+y,w=Math.min(5*x.offsetHeight,b),S=window.getComputedStyle(g),j=parseInt(S.paddingTop,10),C=parseInt(S.paddingBottom,10),k=e.top+e.height/2-10,N=x.offsetHeight/2,E=m+_+(x.offsetTop+N);if(E<=k){let e=o.length>0&&x===o[o.length-1].ref.current;l.style.bottom="0px";let r=Math.max(c-k,N+(e?C:0)+(d.clientHeight-g.offsetTop-g.offsetHeight)+y);l.style.height=E+r+"px"}else{let e=o.length>0&&x===o[0].ref.current;l.style.top="0px";let r=Math.max(k,m+g.offsetTop+(e?j:0)+N);l.style.height=r+(b-E)+"px",g.scrollTop=E-k+g.offsetTop}l.style.margin="10px 0",l.style.minHeight=w+"px",l.style.maxHeight=c+"px",n?.(),requestAnimationFrame(()=>p.current=!0)}},[f,a.trigger,a.valueNode,l,d,g,x,v,a.dir,n]);V(()=>y(),[y]);let[b,w]=$.useState();V(()=>{d&&w(window.getComputedStyle(d).zIndex)},[d]);let S=$.useCallback(e=>{e&&!0===m.current&&(y(),_?.(),m.current=!1)},[y,_]);return(0,O.jsx)(u6,{scope:s,contentWrapper:l,shouldExpandOnScrollRef:p,onScrollButtonChange:S,children:(0,O.jsx)("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:b},children:(0,O.jsx)(er.div,{...i,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});u3.displayName="SelectItemAlignedPosition";var u4=$.forwardRef((e,r)=>{let{__scopeSelect:s,align:n="start",collisionPadding:i=10,...a}=e,o=uO(s);return(0,O.jsx)(iA,{...o,...a,ref:r,align:n,collisionPadding:i,style:{boxSizing:"border-box",...a.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});u4.displayName="SelectPopperPosition";var[u6,u7]=uL(uZ,{}),u8="SelectViewport",u9=$.forwardRef((e,r)=>{let{__scopeSelect:s,nonce:n,...i}=e,a=u1(u8,s),o=u7(u8,s),l=(0,U.useComposedRefs)(r,a.onViewportChange),c=$.useRef(0);return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:n}),(0,O.jsx)(uP.Slot,{scope:s,children:(0,O.jsx)(er.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:K(i.onScroll,e=>{let r=e.currentTarget,{contentWrapper:s,shouldExpandOnScrollRef:n}=o;if(n?.current&&s){let e=Math.abs(c.current-r.scrollTop);if(e>0){let n=window.innerHeight-20,i=Math.max(parseFloat(s.style.minHeight),parseFloat(s.style.height));if(i<n){let a=i+e,o=Math.min(n,a),l=a-o;s.style.height=o+"px","0px"===s.style.bottom&&(r.scrollTop=l>0?l:0,s.style.justifyContent="flex-end")}}}c.current=r.scrollTop})})})]})});u9.displayName=u8;var he="SelectGroup",[ht,hr]=uL(he);$.forwardRef((e,r)=>{let{__scopeSelect:s,...n}=e,i=ek();return(0,O.jsx)(ht,{scope:s,id:i,children:(0,O.jsx)(er.div,{role:"group","aria-labelledby":i,...n,ref:r})})}).displayName=he;var hs="SelectLabel";$.forwardRef((e,r)=>{let{__scopeSelect:s,...n}=e,i=hr(hs,s);return(0,O.jsx)(er.div,{id:i.id,...n,ref:r})}).displayName=hs;var hn="SelectItem",[hi,ha]=uL(hn),ho=$.forwardRef((e,r)=>{let{__scopeSelect:s,value:n,disabled:i=!1,textValue:a,...o}=e,l=uW(hn,s),c=u1(hn,s),d=l.value===n,[u,h]=$.useState(a??""),[f,p]=$.useState(!1),m=(0,U.useComposedRefs)(r,e=>c.itemRefCallback?.(e,n,i)),g=ek(),x=$.useRef("touch"),v=()=>{i||(l.onValueChange(n),l.onOpenChange(!1))};if(""===n)throw Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return(0,O.jsx)(hi,{scope:s,value:n,disabled:i,textId:g,isSelected:d,onItemTextChange:$.useCallback(e=>{h(r=>r||(e?.textContent??"").trim())},[]),children:(0,O.jsx)(uP.ItemSlot,{scope:s,value:n,disabled:i,textValue:u,children:(0,O.jsx)(er.div,{role:"option","aria-labelledby":g,"data-highlighted":f?"":void 0,"aria-selected":d&&f,"data-state":d?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...o,ref:m,onFocus:K(o.onFocus,()=>p(!0)),onBlur:K(o.onBlur,()=>p(!1)),onClick:K(o.onClick,()=>{"mouse"!==x.current&&v()}),onPointerUp:K(o.onPointerUp,()=>{"mouse"===x.current&&v()}),onPointerDown:K(o.onPointerDown,e=>{x.current=e.pointerType}),onPointerMove:K(o.onPointerMove,e=>{x.current=e.pointerType,i?c.onItemLeave?.():"mouse"===x.current&&e.currentTarget.focus({preventScroll:!0})}),onPointerLeave:K(o.onPointerLeave,e=>{e.currentTarget===document.activeElement&&c.onItemLeave?.()}),onKeyDown:K(o.onKeyDown,e=>{(c.searchRef?.current===""||" "!==e.key)&&(uM.includes(e.key)&&v()," "===e.key&&e.preventDefault())})})})})});ho.displayName=hn;var hl="SelectItemText",hc=$.forwardRef((e,r)=>{let{__scopeSelect:s,className:n,style:i,...a}=e,o=uW(hl,s),l=u1(hl,s),c=ha(hl,s),d=uU(hl,s),[u,h]=$.useState(null),f=(0,U.useComposedRefs)(r,e=>h(e),c.onItemTextChange,e=>l.itemTextRefCallback?.(e,c.value,c.disabled)),p=u?.textContent,m=$.useMemo(()=>(0,O.jsx)("option",{value:c.value,disabled:c.disabled,children:p},c.value),[c.disabled,c.value,p]),{onNativeOptionAdd:g,onNativeOptionRemove:x}=d;return V(()=>(g(m),()=>x(m)),[g,x,m]),(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(er.span,{id:c.textId,...a,ref:f}),c.isSelected&&o.valueNode&&!o.valueNodeHasChildren?ee.createPortal(a.children,o.valueNode):null]})});hc.displayName=hl;var hd="SelectItemIndicator",hu=$.forwardRef((e,r)=>{let{__scopeSelect:s,...n}=e;return ha(hd,s).isSelected?(0,O.jsx)(er.span,{"aria-hidden":!0,...n,ref:r}):null});hu.displayName=hd;var hh="SelectScrollUpButton",hf=$.forwardRef((e,r)=>{let s=u1(hh,e.__scopeSelect),n=u7(hh,e.__scopeSelect),[i,a]=$.useState(!1),o=(0,U.useComposedRefs)(r,n.onScrollButtonChange);return V(()=>{if(s.viewport&&s.isPositioned){let e=function(){a(r.scrollTop>0)},r=s.viewport;return e(),r.addEventListener("scroll",e),()=>r.removeEventListener("scroll",e)}},[s.viewport,s.isPositioned]),i?(0,O.jsx)(hg,{...e,ref:o,onAutoScroll:()=>{let{viewport:e,selectedItem:r}=s;e&&r&&(e.scrollTop=e.scrollTop-r.offsetHeight)}}):null});hf.displayName=hh;var hp="SelectScrollDownButton",hm=$.forwardRef((e,r)=>{let s=u1(hp,e.__scopeSelect),n=u7(hp,e.__scopeSelect),[i,a]=$.useState(!1),o=(0,U.useComposedRefs)(r,n.onScrollButtonChange);return V(()=>{if(s.viewport&&s.isPositioned){let e=function(){let e=r.scrollHeight-r.clientHeight;a(Math.ceil(r.scrollTop)<e)},r=s.viewport;return e(),r.addEventListener("scroll",e),()=>r.removeEventListener("scroll",e)}},[s.viewport,s.isPositioned]),i?(0,O.jsx)(hg,{...e,ref:o,onAutoScroll:()=>{let{viewport:e,selectedItem:r}=s;e&&r&&(e.scrollTop=e.scrollTop+r.offsetHeight)}}):null});hm.displayName=hp;var hg=$.forwardRef((e,r)=>{let{__scopeSelect:s,onAutoScroll:n,...i}=e,a=u1("SelectScrollButton",s),o=$.useRef(null),l=uI(s),c=$.useCallback(()=>{null!==o.current&&(window.clearInterval(o.current),o.current=null)},[]);return $.useEffect(()=>()=>c(),[c]),V(()=>{let e=l().find(e=>e.ref.current===document.activeElement);e?.ref.current?.scrollIntoView({block:"nearest"})},[l]),(0,O.jsx)(er.div,{"aria-hidden":!0,...i,ref:r,style:{flexShrink:0,...i.style},onPointerDown:K(i.onPointerDown,()=>{null===o.current&&(o.current=window.setInterval(n,50))}),onPointerMove:K(i.onPointerMove,()=>{a.onItemLeave?.(),null===o.current&&(o.current=window.setInterval(n,50))}),onPointerLeave:K(i.onPointerLeave,()=>{c()})})});$.forwardRef((e,r)=>{let{__scopeSelect:s,...n}=e;return(0,O.jsx)(er.div,{"aria-hidden":!0,...n,ref:r})}).displayName="SelectSeparator";var hx="SelectArrow";$.forwardRef((e,r)=>{let{__scopeSelect:s,...n}=e,i=uO(s),a=uW(hx,s),o=u1(hx,s);return a.open&&"popper"===o.position?(0,O.jsx)(iF,{...i,...n,ref:r}):null}).displayName=hx;var hv=$.forwardRef(({__scopeSelect:e,value:r,...s},n)=>{let i=$.useRef(null),a=(0,U.useComposedRefs)(n,i),o=X(r);return $.useEffect(()=>{let e=i.current;if(!e)return;let s=Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype,"value").set;if(o!==r&&s){let n=new Event("change",{bubbles:!0});s.call(e,r),e.dispatchEvent(n)}},[o,r]),(0,O.jsx)(er.select,{...s,style:{...l1,...s.style},ref:a,defaultValue:r})});function h_(e){return""===e||void 0===e}function hy(e){let r=eN(e),s=$.useRef(""),n=$.useRef(0),i=$.useCallback(e=>{let i=s.current+e;r(i),function e(r){s.current=r,window.clearTimeout(n.current),""!==r&&(n.current=window.setTimeout(()=>e(""),1e3))}(i)},[r]),a=$.useCallback(()=>{s.current="",window.clearTimeout(n.current)},[]);return $.useEffect(()=>()=>window.clearTimeout(n.current),[]),[s,i,a]}function hb(e,r,s){var n,i;let a=r.length>1&&Array.from(r).every(e=>e===r[0])?r[0]:r,o=s?e.indexOf(s):-1,l=(n=e,i=Math.max(o,0),n.map((e,r)=>n[(i+r)%n.length]));1===a.length&&(l=l.filter(e=>e!==s));let c=l.find(e=>e.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==s?c:void 0}hv.displayName="SelectBubbleInput";var H=H;function hw({...e}){return(0,O.jsx)(uq,{"data-slot":"select",...e})}function hS({...e}){return(0,O.jsx)(uG,{"data-slot":"select-value",...e})}function hj({className:e,size:r="default",children:s,...n}){return(0,O.jsxs)(uV,{"data-slot":"select-trigger","data-size":r,className:(0,ey.cn)("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[s,(0,O.jsx)(uX,{asChild:!0,children:(0,O.jsx)(ns,{className:"size-4 opacity-50"})})]})}function hC({className:e,children:r,position:s="item-aligned",align:n="center",...i}){return(0,O.jsx)(uJ,{children:(0,O.jsxs)(uQ,{"data-slot":"select-content",className:(0,ey.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:s,align:n,...i,children:[(0,O.jsx)(hN,{}),(0,O.jsx)(u9,{className:(0,ey.cn)("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:r}),(0,O.jsx)(hE,{})]})})}function hk({className:e,children:r,...s}){return(0,O.jsxs)(ho,{"data-slot":"select-item",className:(0,ey.cn)("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...s,children:[(0,O.jsx)("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:(0,O.jsx)(hu,{children:(0,O.jsx)(H.default,{className:"size-4"})})}),(0,O.jsx)(hc,{children:r})]})}function hN({className:e,...r}){return(0,O.jsx)(hf,{"data-slot":"select-scroll-up-button",className:(0,ey.cn)("flex cursor-default items-center justify-center py-1",e),...r,children:(0,O.jsx)(oX,{className:"size-4"})})}function hE({className:e,...r}){return(0,O.jsx)(hm,{"data-slot":"select-scroll-down-button",className:(0,ey.cn)("flex cursor-default items-center justify-center py-1",e),...r,children:(0,O.jsx)(ns,{className:"size-4"})})}let hD="__main__";function hR({open:e,onOpenChange:r,onSubmit:s,initial:n,worktrees:i,projectId:a}){let[o,l]=(0,$.useState)(""),[c,d]=(0,$.useState)("0 9 * * *"),[u,h]=(0,$.useState)(""),[f,p]=(0,$.useState)("local"),[m,g]=(0,$.useState)([]),[x,v]=(0,$.useState)("command"),[_,y]=(0,$.useState)("claude"),[b,w]=(0,$.useState)(""),[S,j]=(0,$.useState)("branch"),[C,k]=(0,$.useState)(hD),[N,E]=(0,$.useState)(i),[D,R]=(0,$.useState)(""),[A,T]=(0,$.useState)("30"),[M,F]=(0,$.useState)(!1),[P,I]=(0,$.useState)(null);(0,$.useEffect)(()=>{e&&(I(null),l(n?.name??""),d(n?.cron_expr??"0 9 * * *"),h(n?.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone),p(n?.target??"local"),v(n?.run_type??"command"),y(n?.prompt_provider??"claude"),w(n?.content??""),j(n?.cwd_mode??"branch"),k(n?.branch??hD),R(n?.directory??""),T(String(Math.round((n?.timeout_seconds??1800)/60))))},[e,n]),(0,$.useEffect)(()=>{"local"===f&&E(i)},[f,i]),(0,$.useEffect)(()=>{let r=!1;return e&&a&&rv.api.getProjectRemotes(a).then(e=>{r||g(e)}).catch(e=>console.error("Failed to load project remotes:",e)),()=>{r=!0}},[e,a]),(0,$.useEffect)(()=>{let r=!1;if(e&&a&&"local"!==f)return rv.api.getProjectWorktrees(a,f).then(e=>{r||E(e)}).catch(e=>{console.error("Failed to load target worktrees:",e),r||E([{branch:null}])}),()=>{r=!0}},[e,a,f]);let B=async()=>{if(!o.trim()||!b.trim())return void I("Name and content are required");let e=parseInt(A,10);if(!Number.isInteger(e)||e<=0)return void I("Timeout must be a positive number of minutes");if("directory"===S&&!D.trim())return void I("Directory is required");F(!0),I(null);try{await s({name:o.trim(),cron_expr:c.trim(),timezone:u.trim()||"UTC",target:f,run_type:x,prompt_provider:"prompt"===x?_:null,content:b,cwd_mode:S,branch:"branch"===S?C===hD?null:C:null,directory:"directory"===S?D.trim():null,timeout_seconds:60*e}),r(!1)}catch(e){I(e instanceof Error?e.message:"Failed to save schedule")}finally{F(!1)}};return(0,O.jsx)(t8,{open:e,onOpenChange:r,children:(0,O.jsxs)(rr,{className:"max-w-lg",children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:n?"Edit Scheduled Task":"New Scheduled Task"}),(0,O.jsx)(ra,{children:"Run a command or a Claude prompt on a cron schedule"})]}),(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Name"}),(0,O.jsx)(ro,{value:o,onChange:e=>l(e.target.value),placeholder:"Daily log analysis",disabled:M})]}),(0,O.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Cron"}),(0,O.jsx)(ro,{value:c,onChange:e=>d(e.target.value),placeholder:"0 9 * * *",className:"font-mono",disabled:M}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"5-field cron — “0 9 * * *” = every day at 09:00"})]}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Timezone"}),(0,O.jsx)(ro,{value:u,onChange:e=>h(e.target.value),placeholder:"Asia/Shanghai",disabled:M})]})]}),(0,O.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Type"}),(0,O.jsxs)(hw,{value:x,onValueChange:e=>v(e),disabled:M,children:[(0,O.jsx)(hj,{size:"sm",children:(0,O.jsx)(hS,{})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"command",children:"Command (shell)"}),(0,O.jsx)(hk,{value:"prompt",children:"Prompt"})]})]})]}),"prompt"===x&&(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Agent"}),(0,O.jsxs)(hw,{value:_,onValueChange:e=>y(e),disabled:M,children:[(0,O.jsx)(hj,{size:"sm",children:(0,O.jsx)(hS,{})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"claude",children:"Claude"}),(0,O.jsx)(hk,{value:"codex",children:"Codex"})]})]})]})]}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"command"===x?"Command":"Prompt"}),(0,O.jsx)(rl,{value:b,onChange:e=>w(e.target.value),placeholder:"command"===x?"./scripts/scan.sh --daily":"Analyze today's server logs under ./logs and summarize anomalies",className:"font-mono text-sm min-h-[80px]",disabled:M})]}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Target"}),(0,O.jsxs)(hw,{value:f,onValueChange:e=>{p(e),k(hD)},disabled:M,children:[(0,O.jsx)(hj,{size:"sm",children:(0,O.jsx)(hS,{placeholder:"Local"})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"local",children:"Local"}),m.map(e=>(0,O.jsx)(hk,{value:e.remote_server_id,children:e.server_name??e.remote_server_id},e.remote_server_id))]})]})]}),(0,O.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Runs in"}),(0,O.jsxs)(hw,{value:S,onValueChange:e=>j(e),disabled:M,children:[(0,O.jsx)(hj,{size:"sm",children:(0,O.jsx)(hS,{})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"branch",children:"Workspace (branch)"}),(0,O.jsx)(hk,{value:"directory",children:"Directory"})]})]})]}),(0,O.jsx)("div",{className:"space-y-2",children:"branch"===S?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Workspace"}),(0,O.jsxs)(hw,{value:C,onValueChange:k,disabled:M,children:[(0,O.jsx)(hj,{size:"sm",children:(0,O.jsx)(hS,{placeholder:"Select workspace"})}),(0,O.jsx)(hC,{children:N.map(e=>(0,O.jsx)(hk,{value:e.branch??hD,children:e.branch??"main"},e.branch??hD))})]})]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Directory"}),(0,O.jsx)(ro,{value:D,onChange:e=>R(e.target.value),placeholder:"/var/log/myapp",className:"font-mono",disabled:M})]})})]}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Timeout (minutes)"}),(0,O.jsx)(ro,{value:A,onChange:e=>T(e.target.value),className:"w-24",disabled:M})]}),P&&(0,O.jsx)("div",{className:"text-sm text-destructive bg-destructive/10 px-3 py-2 rounded-md",children:P})]}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>r(!1),disabled:M,children:"Cancel"}),(0,O.jsx)(W.Button,{onClick:B,disabled:M||!o.trim()||!b.trim(),children:M?"Saving...":n?"Save":"Create"})]})]})})}let hA={running:"bg-blue-500/15 text-blue-600",completed:"bg-emerald-500/15 text-emerald-600",failed:"bg-red-500/15 text-red-600",timeout:"bg-amber-500/15 text-amber-600",killed:"bg-amber-500/15 text-amber-600",skipped:"bg-muted text-muted-foreground"},hT=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;function hM(e){return e.replace(hT,"").replace(/\r\n/g,"\n").replace(/\r/g,"\n")}function hF(e){return new Date(e.includes("T")?e:e.replace(" ","T")+"Z")}function hP(e){return e?hF(e).toLocaleString():"—"}function hI(e){if(!e.finished_at)return"…";let r=Math.max(0,Math.round((hF(e.finished_at).getTime()-hF(e.started_at).getTime())/1e3));return r<60?`${r}s`:`${Math.floor(r/60)}m ${r%60}s`}function hB({projectId:e,schedules:r,loading:s,selectedId:n,onSelect:i,worktrees:a,onCreate:o,onUpdate:l,onDelete:c,onRunNow:d,createOpen:u,onCreateOpenChange:h,openRunId:f,onOpenRunHandled:p}){let m=r.find(e=>e.id===n)??r[0]??null,[g,x]=(0,$.useState)([]),[v,_]=(0,$.useState)(!1),[y,b]=(0,$.useState)(null),[w,S]=(0,$.useState)(null),[j,C]=(0,$.useState)(0),[k,N]=(0,$.useState)(null),[E,D]=(0,$.useState)(null),[R,A]=(0,$.useState)(null),T=(0,$.useCallback)(async e=>{try{return await rv.api.getScheduleRuns(e)}catch(e){return console.error("Failed to fetch schedule runs:",e),null}},[]);(0,$.useEffect)(()=>{let e=m?.id,r=!1;return(e?T(e):Promise.resolve([])).then(e=>{if(r)return;let s=e??[];x(s),b(e=>e&&(e===w||s.some(r=>r.id===e&&"skipped"!==r.status))?e:s.find(e=>"skipped"!==e.status)?.id??null)}),()=>{r=!0}},[m?.id,r,T,w]);let M=g.find(e=>e.id===y&&e.schedule_id===m?.id),F=M?`${M.status}:${M.finished_at??""}`:null;(0,$.useEffect)(()=>{if(!y)return;let e=!1;return rv.api.getScheduleRun(y).then(r=>{e||N({runId:y,nonce:j,run:r,error:null})},r=>{e||N({runId:y,nonce:j,run:null,error:r instanceof Error?r.message:"Failed to load run output"})}),()=>{e=!0}},[y,j,F]);let P=async()=>{if(m){D(null);try{await d(m.id)}catch(e){D(e instanceof Error?e.message:"Failed to start run")}}};(0,$.useEffect)(()=>{f&&(S(f),b(f),p?.(f))},[f,p]);let I=m?g.filter(e=>e.schedule_id===m.id):[],B=y===w||I.some(e=>e.id===y&&"skipped"!==e.status),L=B&&k?.runId===y&&k.nonce===j?k:null;return s||0!==r.length?(0,O.jsxs)("div",{className:"flex flex-col h-full",children:[m&&(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(dh,{title:m.name,description:`${m.cron_expr} \xb7 ${m.timezone} \xb7 next: ${hP(m.next_run_at)}`,actions:(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsxs)(W.Button,{size:"sm",onClick:P,disabled:!!m.running,children:[(0,O.jsx)(rh,{className:"h-3.5 w-3.5 mr-1.5"}),m.running?"Running…":"Run now"]}),(0,O.jsxs)("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[(0,O.jsx)("input",{type:"checkbox",checked:m.enabled,onChange:e=>void l(m.id,{enabled:e.target.checked}),className:"h-4 w-4 rounded border-input accent-primary"}),(0,O.jsx)("span",{children:"Enabled"})]}),(0,O.jsx)(W.Button,{size:"sm",variant:"outline",onClick:()=>_(!0),children:(0,O.jsx)(rg,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{size:"sm",variant:"outline",onClick:()=>{m&&A(m)},className:"hover:bg-destructive/15 hover:text-destructive",children:(0,O.jsx)(rc,{className:"h-3.5 w-3.5"})})]})}),(0,O.jsxs)("div",{className:"px-5 py-3 grid grid-cols-2 gap-x-8 gap-y-1 text-sm border-b border-border/50",children:[(0,O.jsxs)("div",{children:[(0,O.jsx)("span",{className:"text-muted-foreground",children:"Type: "}),"command"===m.run_type?"Command":`Prompt (${"codex"===m.prompt_provider?"Codex":"Claude"})`]}),(0,O.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,O.jsx)("span",{className:"text-muted-foreground",children:"Runs in: "}),"branch"===m.cwd_mode?`workspace ${m.branch??"main"}`:m.directory,"local"!==m.target&&(0,O.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-violet-500/15 text-violet-600",children:"remote"})]}),(0,O.jsx)("div",{className:"col-span-2 font-mono text-xs text-muted-foreground truncate",title:m.content,children:m.content}),(0,O.jsxs)("div",{children:[(0,O.jsx)("span",{className:"text-muted-foreground",children:"Timeout: "}),Math.round(m.timeout_seconds/60),"m"]})]}),E&&(0,O.jsx)("div",{className:"mx-5 mt-3 text-sm text-destructive bg-destructive/10 px-3 py-2 rounded-md",children:E}),(0,O.jsx)("div",{className:"flex-1 min-h-0",children:(0,O.jsxs)(uj,{direction:"horizontal",autoSaveId:"schedule-run-panels",children:[(0,O.jsx)(dN,{defaultSize:33,minSize:25,children:(0,O.jsx)("div",{className:"h-full overflow-auto px-5 py-3",children:(0,O.jsxs)(uk,{children:[(0,O.jsx)(uN,{children:(0,O.jsxs)(uD,{children:[(0,O.jsx)(uR,{children:"Started"}),(0,O.jsx)(uR,{children:"Duration"}),(0,O.jsx)(uR,{children:"Status"}),(0,O.jsx)(uR,{children:"Exit code"})]})}),(0,O.jsxs)(uE,{children:[I.map(e=>(0,O.jsxs)(uD,{onClick:()=>{"skipped"!==e.status&&(S(null),b(e.id))},"aria-disabled":"skipped"===e.status,className:(0,ey.cn)("skipped"!==e.status&&"cursor-pointer",e.id===y&&"bg-muted/50"),children:[(0,O.jsx)(uA,{children:hP(e.started_at)}),(0,O.jsx)(uA,{children:"skipped"===e.status?"—":hI(e)}),(0,O.jsx)(uA,{children:(0,O.jsx)("span",{className:(0,ey.cn)("px-1.5 py-0.5 rounded text-[11px] font-medium",hA[e.status]),children:e.status})}),(0,O.jsx)(uA,{children:e.exit_code??"—"})]},e.id)),0===I.length&&(0,O.jsx)(uD,{children:(0,O.jsx)(uA,{colSpan:4,className:"text-center text-muted-foreground",children:"No runs yet — click “Run now” to try it"})})]})]})})}),(0,O.jsx)(uC,{withHandle:!0}),(0,O.jsx)(dN,{defaultSize:67,minSize:25,children:(0,O.jsx)("div",{className:"h-full overflow-auto px-5 py-4",children:B&&!L?(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-sm text-muted-foreground",children:"Loading run output…"}):L?.error?(0,O.jsxs)("div",{className:"h-full flex flex-col items-center justify-center gap-3 text-sm",children:[(0,O.jsx)("div",{className:"text-destructive",children:L.error}),(0,O.jsx)(W.Button,{size:"sm",variant:"outline",onClick:()=>C(e=>e+1),children:"Retry"})]}):L?.run?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{className:"mb-4 pb-3 border-b border-border/60",children:[(0,O.jsxs)("div",{className:"text-sm font-medium",children:[L.run.report?"Run report":"Run output"," — ",hP(L.run.started_at)]}),(0,O.jsxs)("div",{className:"mt-2 flex items-center gap-3 text-xs text-muted-foreground",children:[(0,O.jsx)("span",{className:(0,ey.cn)("px-1.5 py-0.5 rounded text-[11px] font-medium",hA[L.run.status]),children:L.run.status}),(0,O.jsx)("span",{children:hI(L.run)}),(0,O.jsxs)("span",{children:["Exit code: ",L.run.exit_code??"—"]})]})]}),L.run.report?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("div",{className:"rounded-md border border-border/50 p-3 text-sm",children:(0,O.jsx)(ck.i,{className:"[&>*:first-child]:mt-0 [&>*:last-child]:mb-0",children:L.run.report})}),(0,O.jsxs)("details",{className:"mt-3",children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer select-none",children:"Raw output"}),(0,O.jsx)("pre",{className:"mt-2 overflow-auto rounded-md bg-muted/50 p-3 font-mono text-xs whitespace-pre-wrap",children:L.run.output?hM(L.run.output):"(no output captured)"})]})]}):(0,O.jsx)("pre",{className:"overflow-auto rounded-md bg-muted/50 p-3 font-mono text-xs whitespace-pre-wrap",children:L.run.output?hM(L.run.output):"(no output captured)"})]}):(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-sm text-muted-foreground",children:"Select a run to view its output"})})})]})}),(0,O.jsx)(hR,{open:v,onOpenChange:_,initial:m,onSubmit:async e=>{await l(m.id,e)},worktrees:a,projectId:e})]}),(0,O.jsx)(hR,{open:u,onOpenChange:h,onSubmit:async e=>{i((await o(e)).id)},worktrees:a,projectId:e}),(0,O.jsx)(lL,{open:null!==R,onOpenChange:e=>{e||A(null)},children:(0,O.jsxs)(l$,{children:[(0,O.jsxs)(lW,{children:[(0,O.jsx)(lU,{children:"Delete scheduled task?"}),(0,O.jsx)(lq,{children:R?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("span",{className:"font-medium text-foreground",children:R.name})," ","and its run history will be permanently deleted. This cannot be undone."]}):null})]}),(0,O.jsxs)(lH,{children:[(0,O.jsx)(lV,{children:"Cancel"}),(0,O.jsx)(lK,{className:(0,ey.cn)((0,W.buttonVariants)({variant:"destructive"}),"border-transparent"),onClick:()=>{A(null),R&&(D(null),c(R.id).catch(e=>{D(e instanceof Error?e.message:"Failed to delete")}))},children:"Delete"})]})]})})]}):(0,O.jsxs)("div",{className:"flex flex-col h-full items-center justify-center gap-3 text-center",children:[(0,O.jsx)(sw,{className:"h-8 w-8 text-muted-foreground/50"}),(0,O.jsx)("p",{className:"text-sm text-muted-foreground",children:"No scheduled tasks yet"}),(0,O.jsx)(W.Button,{size:"sm",onClick:()=>h(!0),children:"New Scheduled Task"}),(0,O.jsx)(hR,{open:u,onOpenChange:h,onSubmit:async e=>{await o(e)},worktrees:a,projectId:e})]})}var hL=e.i(423917);function hz({className:e}){return(0,O.jsx)("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:(0,ey.cn)("h-4 w-4",e),"aria-hidden":"true",children:(0,O.jsx)("path",{d:"M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189z"})})}function hO({inviteUrl:e}){return e?(0,O.jsx)(W.Button,{asChild:!0,variant:"ghost",size:"icon-sm",title:"Join our Discord",children:(0,O.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer","aria-label":"Join our Discord",children:(0,O.jsx)(hz,{})})}):null}function h$({open:e,onOpenChange:r,onProjectCreated:s}){let{config:n}=(0,hL.useAppConfig)(),i=n?.localProjectsEnabled!==!1,[a,o]=(0,$.useState)(""),[l,c]=(0,$.useState)(""),[d,u]=(0,$.useState)([]),[h,f]=(0,$.useState)("closed"),[p,m]=(0,$.useState)([]),[g,x]=(0,$.useState)(null),[v,_]=(0,$.useState)(""),[y,b]=(0,$.useState)(!1),[w,S]=(0,$.useState)(""),j=()=>{o(""),c(""),u([]),C(),S("")},C=()=>{f("closed"),x(null),_("")},k=e=>{e||j(),r(e)},N=async()=>{let e=await rv.api.selectFolder();e.path&&(c(e.path),a||o(e.path.split("/").pop()||""))},E=async()=>{f("pick-server");try{let e=await rv.api.getRemoteServers();m(e)}catch{m([])}},D=l.trim().length>0,R=d.length>0,A=async()=>{if(!a.trim())return void S("Project name is required");if(!D&&!R)return void S(i?"Please provide a local folder, remote server, or both":"Please add a remote server");b(!0),S("");try{let e=await rv.api.createProject({name:a.trim(),...D?{path:l.trim()}:{},...R&&!D?{agentMode:d[0].serverId}:{}});for(let r of d)await rv.api.addProjectRemote(e.id,{remoteServerId:r.serverId,remotePath:r.remotePath});s(e),j(),r(!1)}catch(e){S(e instanceof Error?e.message:"Failed to create project")}finally{b(!1)}};return(0,O.jsx)(t8,{open:e,onOpenChange:k,children:(0,O.jsxs)(rr,{className:"max-w-lg h-[620px] max-h-[calc(100vh-4rem)] grid-rows-[auto_minmax(0,1fr)_auto]",children:[(0,O.jsx)(rs,{children:(0,O.jsx)(ri,{children:"Create New Project"})}),(0,O.jsx)("div",{className:"overflow-y-auto -mx-1 px-1",children:(0,O.jsxs)("div",{className:"space-y-5 py-2",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Project Name"}),(0,O.jsx)(ro,{value:a,onChange:e=>o(e.target.value),placeholder:"My Project"})]}),i&&(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Local Folder"}),(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsx)(ro,{value:l,onChange:e=>c(e.target.value),placeholder:"/path/to/project (optional)",className:"flex-1"}),(0,O.jsx)(W.Button,{variant:"outline",onClick:N,children:(0,O.jsx)(r_,{className:"h-4 w-4"})})]})]}),(0,O.jsxs)("div",{className:"space-y-3",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Remote Servers"}),d.length>0&&(0,O.jsx)("div",{className:"space-y-2",children:d.map((e,r)=>(0,O.jsxs)("div",{className:"flex items-center gap-2 rounded-md border p-2 text-sm",children:[(0,O.jsx)(ry,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),(0,O.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,O.jsx)("p",{className:"font-medium truncate",children:e.serverName}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground font-mono truncate",children:e.remotePath})]}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon-sm",className:"h-7 w-7 shrink-0",onClick:()=>{u(e=>e.filter((e,s)=>s!==r))},children:(0,O.jsx)(rc,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},`${e.serverId}-${e.remotePath}`))}),"closed"===h&&(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:E,className:"w-full",children:[(0,O.jsx)(eS,{className:"h-4 w-4 mr-1"}),"Add Remote"]}),"pick-server"===h&&(0,O.jsxs)("div",{className:"rounded-md border p-3 space-y-3",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between",children:[(0,O.jsx)("label",{className:"text-xs font-medium",children:"Select a Remote Server"}),(0,O.jsx)(W.Button,{variant:"ghost",size:"sm",onClick:C,children:(0,O.jsx)(t7,{className:"h-3.5 w-3.5"})})]}),p.length>0&&(0,O.jsx)("div",{className:"space-y-1",children:p.map(e=>(0,O.jsxs)("button",{className:"flex items-center gap-2 w-full rounded-md p-2 text-sm text-left hover:bg-muted",onClick:()=>{x(e),_(""),f("pick-path")},children:[(0,O.jsx)(od,{className:"h-4 w-4 text-muted-foreground"}),(0,O.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,O.jsx)("p",{className:"truncate",children:e.name}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground truncate",children:"online"===e.status?"Connected":"Not connected"})]})]},e.id))}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"Add new servers in Settings → Remote Servers, then connect the remote machine with a connect token."})]}),"pick-path"===h&&g&&(0,O.jsxs)("div",{className:"rounded-md border p-3 space-y-3",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between",children:[(0,O.jsxs)("label",{className:"text-xs font-medium",children:["Select Directory on ",g.name]}),(0,O.jsx)(W.Button,{variant:"ghost",size:"sm",onClick:C,children:(0,O.jsx)(t7,{className:"h-3.5 w-3.5"})})]}),(0,O.jsx)(oJ,{serverId:g.id,onSelect:e=>{_(e)},selectedPath:v}),v&&(0,O.jsxs)("div",{className:"flex items-center justify-between",children:[(0,O.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Selected: ",(0,O.jsx)("span",{className:"font-mono",children:v})]}),(0,O.jsx)(W.Button,{size:"sm",onClick:()=>{g&&v&&(d.some(e=>e.serverId===g.id&&e.remotePath===v)||(u(e=>[...e,{serverId:g.id,serverName:g.name,remotePath:v}]),a||o(v.split("/").pop()||"")),C())},children:"Add"})]})]})]}),w&&(0,O.jsx)("p",{className:"text-sm text-red-500 pt-3",children:w})]})}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>k(!1),children:"Cancel"}),(0,O.jsx)(W.Button,{onClick:A,disabled:y,children:y?"Creating...":"Create Project"})]})]})})}let hW=(0,ew.default)("network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]),hH=(0,ew.default)("palette",[["path",{d:"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z",key:"e79jfc"}],["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}]]),hU=(0,ew.default)("sparkles",[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]]),hq=(0,ew.default)("square-terminal",[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]]),hK=(0,ew.default)("moon",[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]]),hV=(0,ew.default)("sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);var hY=e.i(371263),hG=e.i(909596),hX=["PageUp","PageDown"],hJ=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],hZ={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},hQ="Slider",[h0,h1,h2]=rb(hQ),[h5,h3]=q(hQ,[h2]),[h4,h6]=h5(hQ),h7=$.forwardRef((e,r)=>{let{name:s,min:n=0,max:i=100,step:a=1,orientation:o="horizontal",disabled:l=!1,minStepsBetweenThumbs:c=0,defaultValue:d=[n],value:u,onValueChange:h=()=>{},onValueCommit:f=()=>{},inverted:p=!1,form:m,...g}=e,x=$.useRef(new Set),v=$.useRef(0),_="horizontal"===o,[y=[],b]=G({prop:u,defaultProp:d,onChange:e=>{let r=[...x.current];r[v.current]?.focus(),h(e)}}),w=$.useRef(y);function S(e,r,{commit:s}={commit:!1}){let o,l=(String(a).split(".")[1]||"").length,d=oh(Math.round((Math.round((e-n)/a)*a+n)*(o=Math.pow(10,l)))/o,[n,i]);b((e=[])=>{let n=function(e=[],r,s){let n=[...e];return n[s]=r,n.sort((e,r)=>e-r)}(e,d,r);if(!function(e,r){if(r>0)return Math.min(...e.slice(0,-1).map((r,s)=>e[s+1]-r))>=r;return!0}(n,c*a))return e;{v.current=n.indexOf(d);let r=String(n)!==String(e);return r&&s&&f(n),r?n:e}})}return(0,O.jsx)(h4,{scope:e.__scopeSlider,name:s,disabled:l,min:n,max:i,valueIndexToChangeRef:v,thumbs:x.current,values:y,orientation:o,form:m,children:(0,O.jsx)(h0.Provider,{scope:e.__scopeSlider,children:(0,O.jsx)(h0.Slot,{scope:e.__scopeSlider,children:(0,O.jsx)(_?fe:ft,{"aria-disabled":l,"data-disabled":l?"":void 0,...g,ref:r,onPointerDown:K(g.onPointerDown,()=>{l||(w.current=y)}),min:n,max:i,inverted:p,onSlideStart:l?void 0:function(e){let r=function(e,r){if(1===e.length)return 0;let s=e.map(e=>Math.abs(e-r)),n=Math.min(...s);return s.indexOf(n)}(y,e);S(e,r)},onSlideMove:l?void 0:function(e){S(e,v.current)},onSlideEnd:l?void 0:function(){let e=w.current[v.current];y[v.current]!==e&&f(y)},onHomeKeyDown:()=>!l&&S(n,0,{commit:!0}),onEndKeyDown:()=>!l&&S(i,y.length-1,{commit:!0}),onStepKeyDown:({event:e,direction:r})=>{if(!l){let s=hX.includes(e.key)||e.shiftKey&&hJ.includes(e.key),n=v.current;S(y[n]+a*(s?10:1)*r,n,{commit:!0})}}})})})})});h7.displayName=hQ;var[h8,h9]=h5(hQ,{startEdge:"left",endEdge:"right",size:"width",direction:1}),fe=$.forwardRef((e,r)=>{let{min:s,max:n,dir:i,inverted:a,onSlideStart:o,onSlideMove:l,onSlideEnd:c,onStepKeyDown:d,...u}=e,[h,f]=$.useState(null),p=(0,U.useComposedRefs)(r,e=>f(e)),m=$.useRef(void 0),g=rk(i),x="ltr"===g,v=x&&!a||!x&&a;function _(e){let r=m.current||h.getBoundingClientRect(),i=fh([0,r.width],v?[s,n]:[n,s]);return m.current=r,i(e-r.left)}return(0,O.jsx)(h8,{scope:e.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?1:-1,size:"width",children:(0,O.jsx)(fr,{dir:g,"data-orientation":"horizontal",...u,ref:p,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:e=>{let r=_(e.clientX);o?.(r)},onSlideMove:e=>{let r=_(e.clientX);l?.(r)},onSlideEnd:()=>{m.current=void 0,c?.()},onStepKeyDown:e=>{let r=hZ[v?"from-left":"from-right"].includes(e.key);d?.({event:e,direction:r?-1:1})}})})}),ft=$.forwardRef((e,r)=>{let{min:s,max:n,inverted:i,onSlideStart:a,onSlideMove:o,onSlideEnd:l,onStepKeyDown:c,...d}=e,u=$.useRef(null),h=(0,U.useComposedRefs)(r,u),f=$.useRef(void 0),p=!i;function m(e){let r=f.current||u.current.getBoundingClientRect(),i=fh([0,r.height],p?[n,s]:[s,n]);return f.current=r,i(e-r.top)}return(0,O.jsx)(h8,{scope:e.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:(0,O.jsx)(fr,{"data-orientation":"vertical",...d,ref:h,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:e=>{let r=m(e.clientY);a?.(r)},onSlideMove:e=>{let r=m(e.clientY);o?.(r)},onSlideEnd:()=>{f.current=void 0,l?.()},onStepKeyDown:e=>{let r=hZ[p?"from-bottom":"from-top"].includes(e.key);c?.({event:e,direction:r?-1:1})}})})}),fr=$.forwardRef((e,r)=>{let{__scopeSlider:s,onSlideStart:n,onSlideMove:i,onSlideEnd:a,onHomeKeyDown:o,onEndKeyDown:l,onStepKeyDown:c,...d}=e,u=h6(hQ,s);return(0,O.jsx)(er.span,{...d,ref:r,onKeyDown:K(e.onKeyDown,e=>{"Home"===e.key?(o(e),e.preventDefault()):"End"===e.key?(l(e),e.preventDefault()):hX.concat(hJ).includes(e.key)&&(c(e),e.preventDefault())}),onPointerDown:K(e.onPointerDown,e=>{let r=e.target;r.setPointerCapture(e.pointerId),e.preventDefault(),u.thumbs.has(r)?r.focus():n(e)}),onPointerMove:K(e.onPointerMove,e=>{e.target.hasPointerCapture(e.pointerId)&&i(e)}),onPointerUp:K(e.onPointerUp,e=>{let r=e.target;r.hasPointerCapture(e.pointerId)&&(r.releasePointerCapture(e.pointerId),a(e))})})}),fs="SliderTrack",fn=$.forwardRef((e,r)=>{let{__scopeSlider:s,...n}=e,i=h6(fs,s);return(0,O.jsx)(er.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...n,ref:r})});fn.displayName=fs;var fi="SliderRange",fa=$.forwardRef((e,r)=>{let{__scopeSlider:s,...n}=e,i=h6(fi,s),a=h9(fi,s),o=$.useRef(null),l=(0,U.useComposedRefs)(r,o),c=i.values.length,d=i.values.map(e=>fu(e,i.min,i.max)),u=c>1?Math.min(...d):0,h=100-Math.max(...d);return(0,O.jsx)(er.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...n,ref:l,style:{...e.style,[a.startEdge]:u+"%",[a.endEdge]:h+"%"}})});fa.displayName=fi;var fo="SliderThumb",fl=$.forwardRef((e,r)=>{let s=h1(e.__scopeSlider),[n,i]=$.useState(null),a=(0,U.useComposedRefs)(r,e=>i(e)),o=$.useMemo(()=>n?s().findIndex(e=>e.ref.current===n):-1,[s,n]);return(0,O.jsx)(fc,{...e,ref:a,index:o})}),fc=$.forwardRef((e,r)=>{var s,n,i,a,o;let l,c,{__scopeSlider:d,index:u,name:h,...f}=e,p=h6(fo,d),m=h9(fo,d),[g,x]=$.useState(null),v=(0,U.useComposedRefs)(r,e=>x(e)),_=!g||p.form||!!g.closest("form"),y=J(g),b=p.values[u],w=void 0===b?0:fu(b,p.min,p.max),S=(s=u,(n=p.values.length)>2?`Value ${s+1} of ${n}`:2===n?["Minimum","Maximum"][s]:void 0),j=y?.[m.size],C=j?(i=j,a=w,o=m.direction,c=fh([0,50],[0,l=i/2]),(l-c(a)*o)*o):0;return $.useEffect(()=>{if(g)return p.thumbs.add(g),()=>{p.thumbs.delete(g)}},[g,p.thumbs]),(0,O.jsxs)("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[m.startEdge]:`calc(${w}% + ${C}px)`},children:[(0,O.jsx)(h0.ItemSlot,{scope:e.__scopeSlider,children:(0,O.jsx)(er.span,{role:"slider","aria-label":e["aria-label"]||S,"aria-valuemin":p.min,"aria-valuenow":b,"aria-valuemax":p.max,"aria-orientation":p.orientation,"data-orientation":p.orientation,"data-disabled":p.disabled?"":void 0,tabIndex:p.disabled?void 0:0,...f,ref:v,style:void 0===b?{display:"none"}:e.style,onFocus:K(e.onFocus,()=>{p.valueIndexToChangeRef.current=u})})}),_&&(0,O.jsx)(fd,{name:h??(p.name?p.name+(p.values.length>1?"[]":""):void 0),form:p.form,value:b},u)]})});fl.displayName=fo;var fd=$.forwardRef(({__scopeSlider:e,value:r,...s},n)=>{let i=$.useRef(null),a=(0,U.useComposedRefs)(i,n),o=X(r);return $.useEffect(()=>{let e=i.current;if(!e)return;let s=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value").set;if(o!==r&&s){let n=new Event("input",{bubbles:!0});s.call(e,r),e.dispatchEvent(n)}},[o,r]),(0,O.jsx)(er.input,{style:{display:"none"},...s,ref:a,defaultValue:r})});function fu(e,r,s){return oh(100/(s-r)*(e-r),[0,100])}function fh(e,r){return s=>{if(e[0]===e[1]||r[0]===r[1])return r[0];let n=(r[1]-r[0])/(e[1]-e[0]);return r[0]+n*(s-e[0])}}fd.displayName="RadioBubbleInput";let ff=$.forwardRef(({className:e,...r},s)=>(0,O.jsxs)(h7,{ref:s,className:(0,ey.cn)("relative flex w-full touch-none select-none items-center","data-[disabled]:opacity-50",e),...r,children:[(0,O.jsx)(fn,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-muted",children:(0,O.jsx)(fa,{className:"absolute h-full bg-primary"})}),(0,O.jsx)(fl,{className:(0,ey.cn)("block h-4 w-4 rounded-full border border-primary/60 bg-card shadow-[var(--shadow-sm-app)]","transition-colors hover:border-primary","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 focus-visible:ring-offset-1 focus-visible:ring-offset-background"),"aria-label":"Value"})]}));function fp({id:e,label:r,description:s,rightSlot:n,children:i}){return(0,O.jsxs)("section",{id:e,className:"scroll-mt-6 rounded-[10px] border border-border bg-card p-5 shadow-[var(--shadow-sm-app)]",children:[(0,O.jsxs)("header",{className:"flex items-end justify-between gap-3 pb-3 mb-4 border-b border-border/70",children:[(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("h2",{className:"text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/80 leading-none",children:r}),s&&(0,O.jsx)("p",{className:"mt-2 text-[12px] text-muted-foreground/90 leading-snug",children:s})]}),n&&(0,O.jsx)("div",{className:"shrink-0",children:n})]}),(0,O.jsx)("div",{className:"space-y-4",children:i})]})}function fm({label:e,hint:r,htmlFor:s,mono:n,children:i}){return(0,O.jsxs)("div",{children:[(0,O.jsx)("label",{htmlFor:s,className:(0,ey.cn)("block text-[12px] font-medium text-foreground/90 mb-1.5",n&&"font-mono tracking-tight"),children:e}),i,r&&(0,O.jsx)("p",{className:"mt-1.5 text-[11px] text-muted-foreground/85 leading-relaxed",children:r})]})}function fg({name:e,value:r,options:s,onChange:n,columns:i=1}){return(0,O.jsx)("div",{className:(0,ey.cn)("grid gap-2",1===i&&"grid-cols-1",2===i&&"grid-cols-1 sm:grid-cols-2",3===i&&"grid-cols-1 sm:grid-cols-3"),role:"radiogroup",children:s.map(s=>{let i=r===s.value,a=s.Icon;return(0,O.jsxs)("label",{className:(0,ey.cn)("group relative flex items-start gap-3 px-3 py-2.5 rounded-[8px] border cursor-pointer","transition-[border-color,background-color,box-shadow] duration-150","focus-within:ring-2 focus-within:ring-ring/40 focus-within:ring-offset-1 focus-within:ring-offset-background",i?"border-primary/40 bg-[color-mix(in_oklch,var(--primary)_8%,var(--card))] shadow-[var(--shadow-sm-app)]":"border-border/70 bg-card hover:border-border hover:bg-muted/40"),children:[(0,O.jsx)("input",{type:"radio",name:e,value:s.value,checked:i,onChange:()=>n(s.value),className:"sr-only"}),(0,O.jsx)("span",{"aria-hidden":!0,className:(0,ey.cn)("mt-0.5 inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full border transition-colors",i?"border-primary bg-primary":"border-border bg-card group-hover:border-foreground/40"),children:i&&(0,O.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-primary-foreground"})}),a&&(0,O.jsx)(a,{className:(0,ey.cn)("h-4 w-4 mt-0.5 shrink-0 transition-colors",i?"text-primary":"text-muted-foreground")}),(0,O.jsxs)("span",{className:"flex-1 min-w-0",children:[(0,O.jsx)("span",{className:(0,ey.cn)("block text-[12.5px] font-medium leading-tight",i?"text-foreground":"text-foreground/90"),children:s.label}),s.description&&(0,O.jsx)("span",{className:"mt-0.5 block text-[11.5px] text-muted-foreground leading-snug",children:s.description})]}),s.meta&&(0,O.jsx)("span",{className:"ml-2 mt-0.5 shrink-0 font-mono text-[10.5px] text-muted-foreground/80",children:s.meta})]},s.value)})})}function fx({variant:e="default",icon:r,children:s}){return(0,O.jsxs)("div",{className:(0,ey.cn)("flex items-center gap-2 rounded-[6px] px-2.5 py-1.5 text-[12px]","default"===e&&"text-muted-foreground bg-muted/40","success"===e&&"text-[color:var(--chart-2)] bg-[color-mix(in_oklch,var(--chart-2)_10%,var(--card))] border border-[color-mix(in_oklch,var(--chart-2)_25%,transparent)]","error"===e&&"text-destructive bg-[color-mix(in_oklch,var(--destructive)_8%,var(--card))] border border-[color-mix(in_oklch,var(--destructive)_25%,transparent)]"),children:[r&&(0,O.jsx)("span",{className:"shrink-0",children:r}),(0,O.jsx)("span",{className:"truncate",children:s})]})}function fv({children:e}){return(0,O.jsx)("div",{className:"flex items-center justify-end gap-2 pt-1",children:e})}function f_({nav:e,children:r}){let[s,n]=(0,$.useState)(e[0]?.id??""),i=(0,$.useRef)(null);return(0,$.useEffect)(()=>{let r=i.current;if(!r)return;let s=()=>{let s=r.getBoundingClientRect(),i=s.top+.25*s.height,a=e[0]?.id??"";for(let s of e){let e=r.querySelector(`#${CSS.escape(s.id)}`);e&&e.getBoundingClientRect().top<=i&&(a=s.id)}n(a)};return s(),r.addEventListener("scroll",s,{passive:!0}),()=>r.removeEventListener("scroll",s)},[e]),(0,O.jsxs)("div",{className:"flex-1 min-h-0 grid grid-cols-[200px_minmax(0,1fr)] overflow-hidden",children:[(0,O.jsx)("aside",{className:"border-r border-border bg-[color:var(--sidebar)] overflow-y-auto",children:(0,O.jsx)("nav",{className:"p-3 flex flex-col gap-0.5",children:e.map(e=>{let r=e.Icon,a=s===e.id;return(0,O.jsxs)("button",{type:"button",onClick:()=>(e=>{let r=i.current;if(!r)return;let s=r.querySelector(`#${CSS.escape(e)}`);if(!s)return;let a=s.offsetTop-12;r.scrollTo({top:a,behavior:"smooth"}),n(e)})(e.id),className:(0,ey.cn)("group relative flex items-center gap-2.5 w-full px-2.5 py-1.5 rounded-[6px] text-[12.5px] text-left","transition-colors duration-100",a?"bg-card text-foreground font-medium shadow-[var(--shadow-sm-app)]":"text-muted-foreground hover:bg-muted/50 hover:text-foreground"),children:[a&&(0,O.jsx)("span",{"aria-hidden":!0,className:"absolute -left-3 top-1.5 bottom-1.5 w-[2px] rounded-full bg-primary"}),r&&(0,O.jsx)(r,{className:(0,ey.cn)("h-3.5 w-3.5 shrink-0",a?"text-foreground":"text-muted-foreground/80")}),(0,O.jsx)("span",{className:"truncate",children:e.label}),e.badge&&(0,O.jsx)("span",{className:"ml-auto font-mono text-[10px] text-muted-foreground/80",children:e.badge})]},e.id)})})}),(0,O.jsx)("div",{ref:i,className:"overflow-y-auto",children:(0,O.jsx)("div",{className:"mx-auto max-w-2xl px-8 py-7 space-y-6",children:r})})]})}ff.displayName="Slider";let fy=[{value:"light",label:"Light",description:"Bright surface, true-white cards",Icon:hV},{value:"dark",label:"Dark",description:"Low-light surfaces with deep neutrals",Icon:hK},{value:"system",label:"System",description:"Match your OS preference",Icon:oc}],{fontSizeMin:fb,fontSizeMax:fw}=rv.CONVERSATION_SETTINGS_LIMITS;function fS(){let{theme:e,setTheme:r}=(0,hY.useTheme)(),{settings:s,setAgentFontSize:n,setChatFontSize:i,setFilesTreeFontSize:a,setFilesContentFontSize:o}=(0,hG.useConversationSettings)();return(0,O.jsxs)("div",{className:"space-y-6",children:[(0,O.jsx)(fm,{label:"Theme",hint:"Sets the surface palette across the app. Switching is instant.",children:(0,O.jsx)(fg,{name:"theme",value:e,options:fy,onChange:r,columns:3})}),(0,O.jsx)(fm,{label:"Conversation font size",hint:"Independent typography for agent and chat views. Affects message body and tool output; chrome elements stay fixed.",children:(0,O.jsxs)("div",{className:"space-y-5",children:[(0,O.jsx)(fj,{label:"Agent conversation",value:s.agentFontSize,onChange:n}),(0,O.jsx)(fj,{label:"Chat session",value:s.chatFontSize,onChange:i})]})}),(0,O.jsx)(fm,{label:"Files font size",hint:"Independent typography for the Files tab. File tree controls the file list and search results; file content controls the preview and code.",children:(0,O.jsxs)("div",{className:"space-y-5",children:[(0,O.jsx)(fj,{label:"File tree, File search",value:s.filesTreeFontSize,onChange:a}),(0,O.jsx)(fj,{label:"File content",value:s.filesContentFontSize,onChange:o})]})}),(0,O.jsx)(fv,{children:(0,O.jsx)(W.Button,{variant:"ghost",size:"sm",onClick:()=>{n(rv.DEFAULT_CONVERSATION_SETTINGS.agentFontSize),i(rv.DEFAULT_CONVERSATION_SETTINGS.chatFontSize),a(rv.DEFAULT_CONVERSATION_SETTINGS.filesTreeFontSize),o(rv.DEFAULT_CONVERSATION_SETTINGS.filesContentFontSize)},children:"Reset"})})]})}function fj({label:e,value:r,onChange:s}){return(0,O.jsxs)("div",{children:[(0,O.jsxs)("div",{className:"flex items-baseline justify-between mb-1.5",children:[(0,O.jsx)("span",{className:"text-[12px] font-medium text-foreground/90",children:e}),(0,O.jsxs)("span",{className:"font-mono text-[11.5px] text-foreground/80 tabular-nums",children:[r," px"]})]}),(0,O.jsx)(ff,{min:fb,max:fw,step:1,value:[r],onValueChange:e=>s(e[0])}),(0,O.jsxs)("div",{className:"flex justify-between mt-1 text-[10.5px] text-muted-foreground/80 font-mono",children:[(0,O.jsx)("span",{children:fb}),(0,O.jsx)("span",{children:fw})]})]})}let fC=(0,ew.default)("waypoints",[["circle",{cx:"12",cy:"4.5",r:"2.5",key:"r5ysbb"}],["path",{d:"m10.2 6.3-3.9 3.9",key:"1nzqf6"}],["circle",{cx:"4.5",cy:"12",r:"2.5",key:"jydg6v"}],["path",{d:"M7 12h10",key:"b7w52i"}],["circle",{cx:"19.5",cy:"12",r:"2.5",key:"1piiel"}],["path",{d:"m13.8 17.7 3.9-3.9",key:"1wyg1y"}],["circle",{cx:"12",cy:"19.5",r:"2.5",key:"13o1pw"}]]),fk={deepseek:hU,openrouter:fC},fN=rv.PROVIDER_IDS.map(e=>({value:e,label:rv.PROVIDERS[e].label,description:"deepseek"===e?"Direct API access — lowest latency":"Aggregator routing — many models available",Icon:fk[e]}));function fE({name:e,value:r,onChange:s}){let n=rv.PROVIDERS[r.provider];return(0,O.jsxs)("div",{className:"space-y-3",children:[(0,O.jsx)(fg,{name:e,value:r.provider,options:fN,onChange:e=>s((0,rv.defaultModelChoice)(e)),columns:2}),n.models?(0,O.jsxs)(hw,{value:r.model,onValueChange:e=>s({...r,model:e}),children:[(0,O.jsx)(hj,{className:"w-full font-mono text-[12.5px]",children:(0,O.jsx)(hS,{})}),(0,O.jsx)(hC,{children:n.models.map(e=>(0,O.jsx)(hk,{value:e,className:"font-mono text-[12.5px]",children:n.modelLabels?.[e]??e},e))})]}):(0,O.jsx)(ro,{className:"font-mono text-[12.5px]",placeholder:n.placeholder,value:r.model,onChange:e=>s({...r,model:e.target.value})})]})}function fD(){let[e,r]=(0,$.useState)(()=>(0,rv.defaultChatProviderConfig)().apiKeys),[s,n]=(0,$.useState)(()=>({deepseek:!1,openrouter:!1})),[i,a]=(0,$.useState)(()=>(0,rv.defaultModelChoice)()),[o,l]=(0,$.useState)(()=>(0,rv.defaultModelChoice)()),[c,d]=(0,$.useState)(!0),[u,h]=(0,$.useState)(!1),[f,p]=(0,$.useState)(null);(0,$.useEffect)(()=>{d(!0),rv.api.getChatProviderSettings().then(e=>{r(e.apiKeys),a(e.main),l(e.fast),n({deepseek:!1,openrouter:!1})}).finally(()=>d(!1))},[]);let m=async()=>{h(!0),p(null);try{let c={};for(let r of rv.PROVIDER_IDS)s[r]&&(c[r]=e[r]);let d={main:i,fast:o};Object.keys(c).length>0&&(d.apiKeys=c);let u=await rv.api.updateChatProviderSettings(d);r(u.apiKeys),a(u.main),l(u.fast),n({deepseek:!1,openrouter:!1}),p("Settings saved"),setTimeout(()=>p(null),2e3)}catch(e){p(e instanceof Error?e.message:"Failed to save")}finally{h(!1)}};return c?(0,O.jsx)("div",{className:"flex items-center justify-center py-6",children:(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):(0,O.jsxs)("div",{className:"space-y-6",children:[(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsx)("p",{className:"text-[12px] font-medium text-foreground/70",children:"API keys"}),rv.PROVIDER_IDS.map(i=>{let a=rv.PROVIDERS[i],o=s[i],l=e[i];return(0,O.jsx)(fm,{label:`${a.label} API key`,mono:!0,hint:(0,O.jsxs)(O.Fragment,{children:["Leave empty to fall back to the"," ",(0,O.jsx)("code",{className:"font-mono text-[10.5px] bg-muted/60 border border-border/60 rounded px-1 py-px",children:a.envKey})," ","environment variable."]}),children:(0,O.jsx)(ro,{type:"password",className:"font-mono text-[12px]",placeholder:l&&!o?l:"sk-...",value:o?l:"",onChange:e=>{var s;return s=e.target.value,void(r(e=>({...e,[i]:s})),n(e=>({...e,[i]:!0})),p(null))}})},i)})]}),(0,O.jsx)(fm,{label:"Main model",hint:"Powers the chat session.",children:(0,O.jsx)(fE,{name:"main-provider",value:i,onChange:e=>{a(e),p(null)}})}),(0,O.jsx)(fm,{label:"Fast model",hint:"Powers translate and agent session titles. Can use a different provider than the main model.",children:(0,O.jsx)(fE,{name:"fast-provider",value:o,onChange:e=>{l(e),p(null)}})}),f&&(0,O.jsx)(fx,{variant:"Settings saved"===f?"success":"error",icon:"Settings saved"===f?(0,O.jsx)(sJ,{className:"h-3.5 w-3.5"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5"}),children:f}),(0,O.jsx)(fv,{children:(0,O.jsxs)(W.Button,{size:"sm",onClick:m,disabled:u,children:[u&&(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save"]})})]})}let fR=[{value:"none",label:"Direct",description:"No proxy — connect directly to the internet",Icon:(0,ew.default)("shield-off",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]])},{value:"http",label:"HTTP / HTTPS",description:"Route through an HTTP CONNECT proxy",Icon:hW},{value:"socks5",label:"SOCKS5",description:"Route through a SOCKS5 proxy server",Icon:fC}];function fA(){let[e,r]=(0,$.useState)("none"),[s,n]=(0,$.useState)(""),[i,a]=(0,$.useState)(""),[o,l]=(0,$.useState)(!0),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(!1),[f,p]=(0,$.useState)(null),[m,g]=(0,$.useState)(null);(0,$.useEffect)(()=>{l(!0),p(null),g(null),rv.api.getProxySettings().then(e=>{r(e.type),n(e.host),a(e.port?String(e.port):"")}).finally(()=>l(!1))},[]);let x=()=>({type:e,host:"none"===e?"":s.trim(),port:"none"===e?0:parseInt(i,10)||0}),v=async()=>{h(!0),p(null);try{p(await rv.api.testProxyConnection(x()))}catch(e){p({success:!1,message:e instanceof Error?e.message:"Test failed"})}finally{h(!1)}},_=async()=>{d(!0),g(null);try{await rv.api.updateProxySettings(x()),g("Settings saved"),setTimeout(()=>g(null),2e3)}catch(e){g(e instanceof Error?e.message:"Failed to save")}finally{d(!1)}},y="none"!==e;return o?(0,O.jsx)("div",{className:"flex items-center justify-center py-6",children:(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsx)(fm,{label:"Connection mode",children:(0,O.jsx)(fg,{name:"proxyType",value:e,options:fR,onChange:e=>{r(e),p(null),g(null)}})}),y&&(0,O.jsxs)("div",{className:"grid grid-cols-[1fr_120px] gap-3",children:[(0,O.jsx)(fm,{label:"Host",mono:!0,children:(0,O.jsx)(ro,{placeholder:"127.0.0.1",value:s,className:"font-mono text-[12.5px]",onChange:e=>{n(e.target.value),p(null),g(null)}})}),(0,O.jsx)(fm,{label:"Port",mono:!0,children:(0,O.jsx)(ro,{type:"number",placeholder:"1080",value:i,className:"font-mono text-[12.5px]",onChange:e=>{a(e.target.value),p(null),g(null)},min:1,max:65535})})]}),f&&(0,O.jsx)(fx,{variant:f.success?"success":"error",icon:f.success?(0,O.jsx)(sJ,{className:"h-3.5 w-3.5"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5"}),children:f.message??(f.success?"Connection succeeded":"Connection failed")}),m&&!f&&(0,O.jsx)(fx,{variant:"Settings saved"===m?"success":"error",icon:"Settings saved"===m?(0,O.jsx)(sJ,{className:"h-3.5 w-3.5"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5"}),children:m}),(0,O.jsxs)(fv,{children:[y&&(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:v,disabled:u||!s.trim()||!i,children:[u&&(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Test connection"]}),(0,O.jsxs)(W.Button,{size:"sm",onClick:_,disabled:c,children:[c&&(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save"]})]})]})}var fT=e.i(276949);let{scrollbackMin:fM,scrollbackMax:fF,fontSizeMin:fP,fontSizeMax:fI}=rv.TERMINAL_SETTINGS_LIMITS;function fB(){let{settings:e,loaded:r,refresh:s}=(0,fT.useTerminalSettings)(),[n,i]=(0,$.useState)(String(rv.DEFAULT_TERMINAL_SETTINGS.scrollback)),[a,o]=(0,$.useState)(String(rv.DEFAULT_TERMINAL_SETTINGS.fontSize)),[l,c]=(0,$.useState)(rv.DEFAULT_TERMINAL_SETTINGS.fontFamily),[d,u]=(0,$.useState)(!1),[h,f]=(0,$.useState)(null);(0,$.useEffect)(()=>{r&&(i(String(e.scrollback)),o(String(e.fontSize)),c(e.fontFamily))},[r,e.scrollback,e.fontSize,e.fontFamily]);let p=parseInt(n,10),m=parseInt(a,10),g=Number.isFinite(p)&&p>=fM&&p<=fF,x=Number.isFinite(m)&&m>=fP&&m<=fI,v=""!==l.trim(),_=g&&x&&v,y=async()=>{if(_){u(!0),f(null);try{let e={scrollback:p,fontSize:m,fontFamily:l.trim()};await rv.api.updateTerminalSettings(e),await s(),f("Settings saved"),setTimeout(()=>f(null),2e3)}catch(e){f(e instanceof Error?e.message:"Failed to save")}finally{u(!1)}}};return r?(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,O.jsx)(fm,{label:"Scrollback",mono:!0,hint:(0,O.jsxs)("span",{children:["Lines kept in buffer."," ",(0,O.jsxs)("span",{className:"font-mono text-foreground/70",children:[fM,"–",fF]})," · default ",(0,O.jsx)("span",{className:"font-mono text-foreground/70",children:rv.DEFAULT_TERMINAL_SETTINGS.scrollback})]}),children:(0,O.jsx)(ro,{type:"number",min:fM,max:fF,value:n,className:"font-mono text-[12.5px]",onChange:e=>{i(e.target.value),f(null)}})}),(0,O.jsx)(fm,{label:"Font size",mono:!0,hint:(0,O.jsxs)("span",{children:["Pixels."," ",(0,O.jsxs)("span",{className:"font-mono text-foreground/70",children:[fP,"–",fI]})," · default ",(0,O.jsx)("span",{className:"font-mono text-foreground/70",children:rv.DEFAULT_TERMINAL_SETTINGS.fontSize})]}),children:(0,O.jsx)(ro,{type:"number",min:fP,max:fI,value:a,className:"font-mono text-[12.5px]",onChange:e=>{o(e.target.value),f(null)}})})]}),(0,O.jsx)(fm,{label:"Font family",mono:!0,hint:"CSS font-family list. Use monospace fonts for column alignment.",children:(0,O.jsx)(ro,{value:l,className:"font-mono text-[12px]",onChange:e=>{c(e.target.value),f(null)},placeholder:rv.DEFAULT_TERMINAL_SETTINGS.fontFamily})}),h&&(0,O.jsx)(fx,{variant:"Settings saved"===h?"success":"error",icon:"Settings saved"===h?(0,O.jsx)(sJ,{className:"h-3.5 w-3.5"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5"}),children:h}),(0,O.jsxs)(fv,{children:[(0,O.jsx)(W.Button,{variant:"outline",size:"sm",onClick:()=>{i(String(rv.DEFAULT_TERMINAL_SETTINGS.scrollback)),o(String(rv.DEFAULT_TERMINAL_SETTINGS.fontSize)),c(rv.DEFAULT_TERMINAL_SETTINGS.fontFamily),f(null)},disabled:d,children:"Reset"}),(0,O.jsxs)(W.Button,{size:"sm",onClick:y,disabled:d||!_,children:[d&&(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save"]})]})]}):(0,O.jsx)("div",{className:"flex items-center justify-center py-6",children:(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin text-muted-foreground"})})}let{min:fL,max:fz}=rv.AGENT_PROCESS_SETTINGS_LIMITS;function fO(){let[e,r]=(0,$.useState)(String(rv.DEFAULT_AGENT_PROCESS_SETTINGS.maxResidentAgentProcesses)),[s,n]=(0,$.useState)(!1),[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=!1;return(0,rv.getAgentProcessSettings)().then(s=>{e||(r(String(s.maxResidentAgentProcesses)),n(!0))}).catch(r=>{e||(l(r instanceof Error?r.message:"Failed to load settings"),n(!0))}),()=>{e=!0}},[]);let c=parseInt(e,10),d=Number.isInteger(c)&&c>=fL&&c<=fz,u=async()=>{if(d){a(!0),l(null);try{let e=await (0,rv.updateAgentProcessSettings)({maxResidentAgentProcesses:c});r(String(e.maxResidentAgentProcesses)),l("Settings saved"),setTimeout(()=>l(null),2e3)}catch(e){l(e instanceof Error?e.message:"Failed to save")}finally{a(!1)}}};return s?(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsx)(fm,{label:"Resident agent processes",mono:!0,hint:(0,O.jsxs)("span",{children:["Live local or remote agent processes per server."," ",(0,O.jsxs)("span",{className:"font-mono text-foreground/70",children:[fL,"–",fz]})," · default ",(0,O.jsx)("span",{className:"font-mono text-foreground/70",children:rv.DEFAULT_AGENT_PROCESS_SETTINGS.maxResidentAgentProcesses})]}),children:(0,O.jsxs)("div",{className:"flex items-center gap-2 max-w-[220px]",children:[(0,O.jsx)(sb,{className:"h-4 w-4 text-muted-foreground"}),(0,O.jsx)(ro,{type:"number",min:fL,max:fz,value:e,className:"font-mono text-[12.5px]",onChange:e=>{r(e.target.value),l(null)}})]})}),o&&(0,O.jsx)(fx,{variant:"Settings saved"===o?"success":"error",icon:"Settings saved"===o?(0,O.jsx)(sJ,{className:"h-3.5 w-3.5"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5"}),children:o}),(0,O.jsxs)(fv,{children:[(0,O.jsx)(W.Button,{variant:"outline",size:"sm",onClick:()=>{r(String(rv.DEFAULT_AGENT_PROCESS_SETTINGS.maxResidentAgentProcesses)),l(null)},disabled:i,children:"Reset"}),(0,O.jsxs)(W.Button,{size:"sm",onClick:u,disabled:i||!d,children:[i&&(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save"]})]})]}):(0,O.jsx)("div",{className:"flex items-center justify-center py-6",children:(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin text-muted-foreground"})})}let f$=[{id:"appearance",label:"Appearance",Icon:hH},{id:"ai-chat",label:"AI Chat",Icon:hU},{id:"agents",label:"Agents",Icon:sb},{id:"terminal",label:"Terminal",Icon:hq},{id:"proxy",label:"Proxy",Icon:hW}];function fW(){let{config:e}=(0,hL.useAppConfig)(),[r]=(0,$.useState)(rv.getPersistedConfig),s=(e??r)?.authEnabled!==!1,n=s?f$.filter(e=>"proxy"!==e.id):f$;return(0,O.jsxs)("div",{className:"h-full flex flex-col overflow-hidden",children:[(0,O.jsx)(dh,{title:"Settings",description:"Theme, intelligence, terminal, and network preferences."}),(0,O.jsxs)(f_,{nav:n,children:[(0,O.jsx)(fp,{id:"appearance",label:"Appearance",description:"Visual surface for the workspace. Affects every view.",children:(0,O.jsx)(fS,{})}),(0,O.jsx)(fp,{id:"ai-chat",label:"AI Chat",description:"Provider, credentials, and default model used for the orchestrator chat.",children:(0,O.jsx)(fD,{})}),(0,O.jsx)(fp,{id:"agents",label:"Agents",description:"Resident coding-agent process limits per workspace branch.",children:(0,O.jsx)(fO,{})}),(0,O.jsx)(fp,{id:"terminal",label:"Terminal",description:"Buffer size and typography for the executor terminal.",children:(0,O.jsx)(fB,{})}),!s&&(0,O.jsx)(fp,{id:"proxy",label:"Proxy",description:"Outbound network routing for AI providers and remote servers.",children:(0,O.jsx)(fA,{})})]})]})}let fH=(0,ew.default)("plug-zap",[["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m18 3-4 4h6l-4 4",key:"16psg9"}]]),fU=(0,ew.default)("key-round",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);var fq=e.i(710307);let fK=(0,ew.default)("refresh-cw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]),fV={name:""};function fY(){let[e,r]=(0,$.useState)([]),[s,n]=(0,$.useState)(!0),[i,a]=(0,$.useState)(""),[o,l]=(0,$.useState)(!1),[c,d]=(0,$.useState)(null),[u,h]=(0,$.useState)(fV),[f,p]=(0,$.useState)(""),[m,g]=(0,$.useState)(!1),[x,v]=(0,$.useState)(null),[_,y]=(0,$.useState)(!1),[b,w]=(0,$.useState)({}),[S,j]=(0,$.useState)({}),[C,k]=(0,$.useState)(null),[N,E]=(0,$.useState)(null),[D,R]=(0,$.useState)(null),[A,T]=(0,$.useState)(!1),[M,F]=(0,$.useState)(!1),[P,I]=(0,$.useState)(!1),[B,L]=(0,$.useState)(!1),z=(0,$.useRef)(null),H=(0,$.useCallback)(async()=>{try{let e=await rv.api.getRemoteServers();r(e),a("")}catch(e){a(e instanceof Error?e.message:"Failed to load servers")}finally{n(!1)}},[]);(0,$.useEffect)(()=>{H()},[H]),(0,$.useEffect)(()=>{let e=setInterval(H,15e3),r=()=>H();return window.addEventListener("focus",r),()=>{clearInterval(e),window.removeEventListener("focus",r)}},[H]);let U=async()=>{if(!u.name.trim())return void p("Name is required");g(!0),p("");try{c?u.name.trim()!==c.name&&await rv.api.updateRemoteServer(c.id,{name:u.name.trim()}):await rv.api.createRemoteServer({name:u.name.trim()}),l(!1),await H()}catch(e){p(e instanceof Error?e.message:"Failed to save server")}finally{g(!1)}},q=async()=>{if(x){y(!0);try{await rv.api.deleteRemoteServer(x.id),v(null),await H()}catch(e){p(e instanceof Error?e.message:"Failed to delete server")}finally{y(!1)}}},K=async e=>{w(r=>({...r,[e.id]:"testing"})),j(r=>{let s={...r};return delete s[e.id],s});try{let r=await rv.api.testRemoteServer(e.id);w(s=>({...s,[e.id]:r.success?"success":"error"})),r.success||j(r=>({...r,[e.id]:"Connection failed"}))}catch(r){w(r=>({...r,[e.id]:"error"})),j(s=>({...s,[e.id]:r instanceof Error?r.message:"Test failed"}))}},V=async e=>{z.current=e.id,k(e),E(null),R(null),F(!1),L(!1),I(!1),T(!0);try{let r=await rv.api.getRemoteServerConnectToken(e.id);if(z.current!==e.id)return;E(r.token),R(r.connectCommand)}catch(r){if(z.current!==e.id)return;z.current=null,p(r instanceof Error?r.message:"Failed to load token"),k(null)}finally{z.current===e.id&&T(!1)}},Y=async e=>{I(!0),F(!1);try{let r=await rv.api.rotateRemoteServerConnectToken(e.id);z.current===e.id&&(E(r.token),R(r.connectCommand),L(!1)),await H()}catch(e){a(e instanceof Error?e.message:"Failed to rotate token")}finally{z.current===e.id&&I(!1)}},G=async e=>{try{await rv.api.revokeRemoteServerConnectToken(e.id),await H()}catch(e){a(e instanceof Error?e.message:"Failed to revoke token")}},X=async(e,s)=>{try{let n=await rv.api.updateRemoteServer(e.id,{crossRemoteAccess:s});r(e=>e.map(e=>e.id===n.id?n:e))}catch(e){a(e instanceof Error?e.message:"Failed to update access")}},J="Update the vibedeckx package on the worker machine, then restart `vibedeckx connect`.";return s?(0,O.jsx)("div",{className:"flex items-center justify-center py-8",children:(0,O.jsx)(sj,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between",children:[(0,O.jsxs)("div",{children:[(0,O.jsx)("h3",{className:"text-sm font-medium",children:"Remote Servers"}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"Manage globally available remote servers"})]}),(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:()=>{d(null),h(fV),p(""),l(!0)},children:[(0,O.jsx)(eS,{className:"h-4 w-4 mr-1.5"}),"Add Server"]})]}),i&&(0,O.jsx)("p",{className:"text-sm text-red-500",children:i}),0===e.length?(0,O.jsxs)("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[(0,O.jsx)(ry,{className:"h-8 w-8 mx-auto mb-2 opacity-40"}),"No remote servers configured"]}):(0,O.jsxs)(uk,{children:[(0,O.jsx)(uN,{children:(0,O.jsxs)(uD,{children:[(0,O.jsx)(uR,{children:"Name"}),(0,O.jsx)(uR,{children:"Status"}),(0,O.jsx)(uR,{children:"Cross-remote access"}),(0,O.jsx)(uR,{className:"w-[180px] text-right",children:"Actions"})]})}),(0,O.jsx)(uE,{children:e.map(e=>{let r,s;return(0,O.jsxs)(uD,{children:[(0,O.jsx)(uA,{className:"font-medium",children:(0,O.jsxs)("div",{className:"flex items-center",children:[(r="online"===e.status,(0,O.jsx)("span",{className:`inline-block h-2.5 w-2.5 rounded-full mr-2 ${r?"bg-green-500":"bg-gray-400"}`,title:r?"Online":"Offline"})),e.name]})}),(0,O.jsxs)(uA,{className:"font-mono text-xs text-muted-foreground",children:[(0,O.jsx)("div",{children:"online"===e.status?"Connected":"Waiting for connection..."}),(e=>{if(!e.worker_version)return e.last_connected_at?(0,O.jsx)("div",{className:"mt-0.5 text-[11px] text-muted-foreground",title:J,children:"version unknown · upgrade recommended"}):null;let r="behind-min"===e.worker_update_status?(0,O.jsx)("span",{className:"text-red-500",title:J,children:"upgrade required"}):"behind-latest"===e.worker_update_status?(0,O.jsxs)("span",{className:"text-amber-500",title:J,children:["update available → v",e.latest_worker_version]}):null;return(0,O.jsxs)("div",{className:"mt-0.5 text-[11px]",children:[(0,O.jsxs)("span",{className:"text-muted-foreground",children:["v",e.worker_version]}),r&&(0,O.jsx)("span",{className:"ml-1.5",children:r})]})})(e)]}),(0,O.jsx)(uA,{children:(0,O.jsxs)(hw,{value:e.cross_remote_access,onValueChange:r=>X(e,r),children:[(0,O.jsx)(hj,{className:"w-[190px] text-[12.5px]",children:(0,O.jsx)(hS,{})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"off",className:"text-[12.5px]",children:"Off"}),(0,O.jsx)(hk,{value:"read",className:"text-[12.5px]",children:"Diagnostic read"}),(0,O.jsx)(hk,{value:"exec",className:"text-[12.5px]",children:"Command execution"})]})]})}),(0,O.jsxs)(uA,{className:"text-right",children:[(0,O.jsxs)("div",{className:"flex items-center justify-end gap-1",children:[(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:()=>V(e),title:"Connect token",className:"h-8 w-8",children:(0,O.jsx)(fU,{className:"h-4 w-4"})}),(s=b[e.id]||"idle",(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:()=>K(e),disabled:"testing"===s,title:"Test connection",className:"h-8 w-8",children:"testing"===s?(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"}):"success"===s?(0,O.jsx)(rf.Check,{className:"h-4 w-4 text-green-500"}):"error"===s?(0,O.jsx)(t7,{className:"h-4 w-4 text-red-500"}):(0,O.jsx)(fH,{className:"h-4 w-4"})})),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:()=>{d(e),h({name:e.name}),p(""),l(!0)},title:"Edit server",className:"h-8 w-8",children:(0,O.jsx)(rg,{className:"h-4 w-4"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:()=>v(e),title:"Delete server",className:"h-8 w-8 text-destructive hover:text-destructive",children:(0,O.jsx)(rc,{className:"h-4 w-4"})})]}),S[e.id]&&(0,O.jsx)("p",{className:"text-xs text-red-500 mt-1 text-right",children:S[e.id]})]})]},e.id)})})]}),(0,O.jsxs)("p",{className:"text-xs text-muted-foreground",children:["When enabled, agents running on your other machines can reach this one.",(0,O.jsx)("strong",{children:" Diagnostic read"})," exposes files, directories and the process list — including any secrets in logs and config files.",(0,O.jsx)("strong",{children:" Command execution"})," additionally allows arbitrary shell commands. Off by default."]}),(0,O.jsx)(t8,{open:o,onOpenChange:l,children:(0,O.jsxs)(rr,{className:"sm:max-w-md",children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:c?"Edit Server":"Add Remote Server"}),(0,O.jsx)(ra,{children:c?"Update the server name.":"Add a new remote server, then generate a connect token and run the connect command on the remote machine."})]}),(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Name"}),(0,O.jsx)(ro,{value:u.name,onChange:e=>{h(r=>({...r,name:e.target.value})),p("")},placeholder:"My Remote Server"})]}),f&&(0,O.jsx)("p",{className:"text-sm text-red-500",children:f})]}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),(0,O.jsxs)(W.Button,{onClick:U,disabled:m,children:[m&&(0,O.jsx)(sj,{className:"h-4 w-4 mr-1.5 animate-spin"}),c?"Save Changes":"Add Server"]})]})]})}),(0,O.jsx)(t8,{open:null!==C,onOpenChange:e=>{e||(z.current=null,k(null),E(null),R(null),L(!1))},children:(0,O.jsxs)(rr,{className:"sm:max-w-lg",children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:"Connect Token"}),(0,O.jsxs)(ra,{children:["Use this token to connect a remote node to"," ",(0,O.jsx)("span",{className:"font-semibold",children:C?.name}),". It stays the same every time you open this dialog — rotate it to issue a replacement."]})]}),A?(0,O.jsx)("div",{className:"flex items-center justify-center py-4",children:(0,O.jsx)(sj,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):N?(0,O.jsx)("div",{className:"space-y-4",children:(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Connect Command"}),(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsx)(ro,{readOnly:!0,value:D||"",className:"font-mono text-xs"}),(0,O.jsx)(W.Button,{variant:"outline",size:"icon",className:"shrink-0",onClick:()=>{var e;return e=D||"",void(navigator.clipboard.writeText(e),F(!0),setTimeout(()=>F(!1),2e3))},title:"Copy command",children:M?(0,O.jsx)(rf.Check,{className:"h-4 w-4 text-green-500"}):(0,O.jsx)(fq.Copy,{className:"h-4 w-4"})})]}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"Run this command on the remote machine to establish the reverse connection."}),B&&(0,O.jsx)("p",{className:"text-xs text-destructive",children:"Rotating invalidates the current token immediately. Any worker still using it will fail to reconnect until you re-run the new command."})]})}):null,(0,O.jsxs)(rn,{children:[N&&C&&(0,O.jsxs)("div",{className:"mr-auto flex items-center gap-2",children:[(0,O.jsxs)(W.Button,{variant:"outline",disabled:P,onClick:()=>{B?Y(C):L(!0)},children:[P?(0,O.jsx)(sj,{className:"mr-2 h-4 w-4 animate-spin"}):(0,O.jsx)(fK,{className:"mr-2 h-4 w-4"}),B?"Confirm rotate":"Rotate Token"]}),(0,O.jsx)(W.Button,{variant:"outline",className:"text-destructive hover:text-destructive",onClick:()=>{G(C),z.current=null,k(null),E(null)},children:"Revoke Token"})]}),(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>{z.current=null,k(null),E(null),R(null),L(!1)},children:"Close"})]})]})}),(0,O.jsx)(t8,{open:null!==x,onOpenChange:e=>{e||v(null)},children:(0,O.jsxs)(rr,{className:"sm:max-w-sm",children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:"Delete Server"}),(0,O.jsxs)(ra,{children:["Are you sure you want to delete"," ",(0,O.jsx)("span",{className:"font-semibold",children:x?.name}),"? This will also remove it from any projects that reference it."]})]}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>v(null),children:"Cancel"}),(0,O.jsxs)(W.Button,{variant:"destructive",onClick:q,disabled:_,children:[_&&(0,O.jsx)(sj,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Delete"]})]})]})})]})}function fG({projectId:e,project:r,open:s,onOpenChange:n,onWorktreeCreated:i}){let[a,o]=(0,$.useState)(""),[l,c]=(0,$.useState)(!1),[d,u]=(0,$.useState)(null),[h,f]=(0,$.useState)(null),[p,m]=(0,$.useState)(!0),[g,x]=(0,$.useState)(!0),[v,_]=(0,$.useState)([]),[y,b]=(0,$.useState)([]),[w,S]=(0,$.useState)("main"),[j,C]=(0,$.useState)("main"),[k,N]=(0,$.useState)(!1),E=!!(r.path&&r.remote_path);(0,$.useEffect)(()=>{s&&(N(!0),E?Promise.all([rv.api.getProjectBranches(e,"local"),rv.api.getProjectBranches(e,"remote")]).then(([e,r])=>{_(e),b(r),S(e.includes("main")?"main":e[0]||"main"),C(r.includes("main")?"main":r[0]||"main"),N(!1)}):rv.api.getProjectBranches(e).then(e=>{_(e),S(e.includes("main")?"main":e[0]||"main"),N(!1)}))},[s,e,E]);let D=async()=>{if(a.trim()){c(!0),u(null),f(null);try{let r;E&&(r=[],p&&r.push("local"),g&&r.push("remote"));let s=await rv.api.createWorktree(e,a.trim(),r,w,E?j:void 0);if(s.partialSuccess){let e,r=s.results?.remote?.success===!1?"remote":"local",n=s.results?.[r],i=n?.error||"Unknown error",a=n?.errorCode,o=n?.requestId;switch(a){case"timeout":e="Connection to remote server timed out. The remote server may be slow or unreachable.";break;case"network_error":e="Remote server is not connected. Run the connect command on the remote machine (Settings → Remote Servers → connect token).";break;case"auth_error":e="Authentication failed with remote server. Copy the current connect command (Settings → Remote Servers → connect token) and re-run it on the remote machine; rotate the token only if you need to replace it.";break;case"server_error":e=`Remote server returned an error: ${i}`;break;default:e=`Worktree created locally, but ${r} creation failed: ${i}`}o&&(e+=` (Request ID: ${o})`),f(e)}i(s.worktree.branch),s.partialSuccess||(n(!1),o(""))}catch(e){u(e instanceof Error?e.message:"Failed to create worktree")}finally{c(!1)}}},R=e=>{e||(o(""),u(null),f(null),m(!0),x(!0),_([]),b([]),S("main"),C("main")),n(e)},A=(e,r,s,n)=>(0,O.jsxs)(hw,{value:r,onValueChange:s,disabled:n||k,children:[(0,O.jsx)(hj,{size:"sm",children:(0,O.jsx)(hS,{placeholder:k?"Loading...":"Select branch"})}),(0,O.jsx)(hC,{children:e.map(e=>(0,O.jsx)(hk,{value:e,children:e},e))})]});return(0,O.jsx)(t8,{open:s,onOpenChange:R,children:(0,O.jsxs)(rr,{children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:"Create New Worktree"}),(0,O.jsx)(ra,{children:"Create a new branch based on an existing branch"})]}),(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{htmlFor:"branch-name",className:"text-sm font-medium",children:"Branch Name"}),(0,O.jsx)(ro,{id:"branch-name",placeholder:"feature/my-feature",value:a,onChange:e=>o(e.target.value),disabled:l,onKeyDown:e=>{"Enter"===e.key&&a.trim()&&(!E||p||g)&&D()}})]}),E?(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Create On"}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsxs)("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[(0,O.jsx)("input",{type:"checkbox",checked:p,onChange:e=>{(e.target.checked||g)&&m(e.target.checked)},disabled:l,className:"h-4 w-4 rounded border-input accent-primary"}),(0,O.jsx)("span",{children:"Local"}),(0,O.jsx)("span",{className:"text-muted-foreground truncate text-xs",children:r.path})]}),p&&v.length>0&&(0,O.jsxs)("div",{className:"ml-6",children:[(0,O.jsx)("label",{className:"text-xs text-muted-foreground",children:"Base Branch"}),A(v,w,S,l)]}),(0,O.jsxs)("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[(0,O.jsx)("input",{type:"checkbox",checked:g,onChange:e=>{(e.target.checked||p)&&x(e.target.checked)},disabled:l,className:"h-4 w-4 rounded border-input accent-primary"}),(0,O.jsx)("span",{children:"Remote"}),(0,O.jsx)("span",{className:"text-muted-foreground truncate text-xs",children:r.remote_path})]}),g&&y.length>0&&(0,O.jsxs)("div",{className:"ml-6",children:[(0,O.jsx)("label",{className:"text-xs text-muted-foreground",children:"Base Branch"}),A(y,j,C,l)]})]})]}):v.length>0&&(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Base Branch"}),A(v,w,S,l)]}),h&&(0,O.jsx)("div",{className:"text-sm text-yellow-600 dark:text-yellow-500 bg-yellow-500/10 px-3 py-2 rounded-md",children:h}),d&&(0,O.jsx)("div",{className:"text-sm text-destructive bg-destructive/10 px-3 py-2 rounded-md",children:d})]}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>R(!1),disabled:l,children:"Cancel"}),(0,O.jsx)(W.Button,{onClick:D,disabled:!a.trim()||l||E&&!p&&!g,children:l?"Creating...":"Create"})]})]})})}function fX({projectId:e,worktree:r,open:s,onOpenChange:n,onWorktreeDeleted:i}){let[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(null),[d,u]=(0,$.useState)(null),h=async()=>{if(r){o(!0),c(null),u(null);try{let s=await rv.api.deleteWorktree(e,r.branch);if(s.partialSuccess){let e=s.results?.remote?.error||"Unknown error";u(`Local worktree deleted, but remote deletion failed: ${e}`)}i(),s.partialSuccess||n(!1)}catch(e){c(e instanceof Error?e.message:"Failed to delete worktree")}finally{o(!1)}}},f=e=>{e||(c(null),u(null)),n(e)};return(0,O.jsx)(t8,{open:s,onOpenChange:f,children:(0,O.jsxs)(rr,{children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:"Delete Worktree"}),(0,O.jsx)(ra,{children:"Are you sure you want to delete this worktree?"})]}),r&&(0,O.jsx)("div",{className:"space-y-2",children:(0,O.jsxs)("div",{className:"text-sm",children:[(0,O.jsx)("span",{className:"font-medium",children:"Branch:"})," ",(0,O.jsx)("span",{className:"text-muted-foreground",children:r.branch})]})}),d&&(0,O.jsx)("div",{className:"text-sm text-yellow-600 dark:text-yellow-500 bg-yellow-500/10 px-3 py-2 rounded-md",children:d}),l&&(0,O.jsx)("div",{className:"text-sm text-destructive bg-destructive/10 px-3 py-2 rounded-md",children:l}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{variant:"outline",onClick:()=>f(!1),disabled:a,children:"Cancel"}),(0,O.jsx)(W.Button,{variant:"destructive",onClick:h,disabled:a,children:a?"Deleting...":"Delete"})]})]})})}e.i(247755);var fJ=e.i(642098);function fZ(){let{config:e}=(0,hL.useAppConfig)();return e?.authEnabled?(0,O.jsx)("div",{className:"flex items-center",children:(0,O.jsx)(fJ.UserButton,{appearance:{elements:{avatarBox:"h-7 w-7 ring-1 ring-border/60"}}})}):null}var fQ=e.i(183663),f0="Collapsible",[f1,f2]=q(f0),[f5,f3]=f1(f0),f4=$.forwardRef((e,r)=>{let{__scopeCollapsible:s,open:n,defaultOpen:i,disabled:a,onOpenChange:o,...l}=e,[c,d]=G({prop:n,defaultProp:i??!1,onChange:o,caller:f0});return(0,O.jsx)(f5,{scope:s,disabled:a,contentId:ek(),open:c,onOpenToggle:$.useCallback(()=>d(e=>!e),[d]),children:(0,O.jsx)(er.div,{"data-state":pt(c),"data-disabled":a?"":void 0,...l,ref:r})})});f4.displayName=f0;var f6="CollapsibleTrigger",f7=$.forwardRef((e,r)=>{let{__scopeCollapsible:s,...n}=e,i=f3(f6,s);return(0,O.jsx)(er.button,{type:"button","aria-controls":i.contentId,"aria-expanded":i.open||!1,"data-state":pt(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...n,ref:r,onClick:K(e.onClick,i.onOpenToggle)})});f7.displayName=f6;var f8="CollapsibleContent",f9=$.forwardRef((e,r)=>{let{forceMount:s,...n}=e,i=f3(f8,e.__scopeCollapsible);return(0,O.jsx)(Z,{present:s||i.open,children:({present:e})=>(0,O.jsx)(pe,{...n,ref:r,present:e})})});f9.displayName=f8;var pe=$.forwardRef((e,r)=>{let{__scopeCollapsible:s,present:n,children:i,...a}=e,o=f3(f8,s),[l,c]=$.useState(n),d=$.useRef(null),u=(0,U.useComposedRefs)(r,d),h=$.useRef(0),f=h.current,p=$.useRef(0),m=p.current,g=o.open||l,x=$.useRef(g),v=$.useRef(void 0);return $.useEffect(()=>{let e=requestAnimationFrame(()=>x.current=!1);return()=>cancelAnimationFrame(e)},[]),V(()=>{let e=d.current;if(e){v.current=v.current||{transitionDuration:e.style.transitionDuration,animationName:e.style.animationName},e.style.transitionDuration="0s",e.style.animationName="none";let r=e.getBoundingClientRect();h.current=r.height,p.current=r.width,x.current||(e.style.transitionDuration=v.current.transitionDuration,e.style.animationName=v.current.animationName),c(n)}},[o.open,n]),(0,O.jsx)(er.div,{"data-state":pt(o.open),"data-disabled":o.disabled?"":void 0,id:o.contentId,hidden:!g,...a,ref:u,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":m?`${m}px`:void 0,...e.style},children:g&&i})});function pt(e){return e?"open":"closed"}function pr({...e}){return(0,O.jsx)(f4,{"data-slot":"collapsible",...e})}function ps({...e}){return(0,O.jsx)(f7,{"data-slot":"collapsible-trigger",...e})}function pn({...e}){return(0,O.jsx)(f9,{"data-slot":"collapsible-content",...e})}let pi=(0,ew.default)("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]),pa=(0,ew.default)("ban",[["path",{d:"M4.929 4.929 19.07 19.071",key:"196cmz"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);var po=e.i(885101),pl=Object.defineProperty,pc=Object.getOwnPropertyDescriptor,pd=(e,r,s,n)=>{for(var i,a=n>1?void 0:n?pc(r,s):r,o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n?i(r,s,a):i(a))||a);return n&&a&&pl(r,s,a),a},pu=(e,r)=>(s,n)=>r(s,n,e),ph="Terminal input",pf="Too much output to announce, navigate to rows manually to read";function pp(e,r,s,n){var i;i=e=e.replace(/\r?\n/g,"\r"),e=s.decPrivateModes.bracketedPasteMode&&!0!==n.rawOptions.ignoreBracketedPasteMode?"\x1b[200~"+i+"\x1b[201~":i,s.triggerDataEvent(e,!0),r.value=""}function pm(e,r,s){let n=s.getBoundingClientRect(),i=e.clientX-n.left-10,a=e.clientY-n.top-10;r.style.width="20px",r.style.height="20px",r.style.left=`${i}px`,r.style.top=`${a}px`,r.style.zIndex="1000",r.focus()}function pg(e,r,s,n,i){pm(e,r,s),i&&n.rightClickSelect(e),r.value=n.selectionText,r.select()}function px(e){return e>65535?String.fromCharCode(((e-=65536)>>10)+55296)+String.fromCharCode(e%1024+56320):String.fromCharCode(e)}function pv(e,r=0,s=e.length){let n="";for(let i=r;i<s;++i){let r=e[i];r>65535?(r-=65536,n+=String.fromCharCode((r>>10)+55296)+String.fromCharCode(r%1024+56320)):n+=String.fromCharCode(r)}return n}var p_=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,r){let s=e.length;if(!s)return 0;let n=0,i=0;if(this._interim){let s=e.charCodeAt(i++);56320<=s&&s<=57343?r[n++]=(this._interim-55296)*1024+s-56320+65536:(r[n++]=this._interim,r[n++]=s),this._interim=0}for(let a=i;a<s;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=s)return this._interim=i,n;let o=e.charCodeAt(a);56320<=o&&o<=57343?r[n++]=(i-55296)*1024+o-56320+65536:(r[n++]=i,r[n++]=o);continue}65279!==i&&(r[n++]=i)}return n}},py=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,r){let s=e.length;if(!s)return 0;let n=0,i,a,o,l,c=0,d=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(224&a)==192?31:(240&a)==224?15:7;let o=0,l;for(;(l=63&this.interim[++o])&&o<4;)a<<=6,a|=l;let c=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,u=c-o;for(;d<u;){if(d>=s)return 0;if((192&(l=e[d++]))!=128){d--,i=!0;break}this.interim[o++]=l,a<<=6,a|=63&l}i||(2===c?a<128?d--:r[n++]=a:3===c?a<2048||a>=55296&&a<=57343||65279===a||(r[n++]=a):a<65536||a>1114111||(r[n++]=a)),this.interim.fill(0)}let u=s-4,h=d;for(;h<s;){for(;h<u&&!(128&(i=e[h]))&&!(128&(a=e[h+1]))&&!(128&(o=e[h+2]))&&!(128&(l=e[h+3]));)r[n++]=i,r[n++]=a,r[n++]=o,r[n++]=l,h+=4;if((i=e[h++])<128)r[n++]=i;else if((224&i)==192){if(h>=s)return this.interim[0]=i,n;if((192&(a=e[h++]))!=128||(c=(31&i)<<6|63&a)<128){h--;continue}r[n++]=c}else if((240&i)==224){if(h>=s)return this.interim[0]=i,n;if((192&(a=e[h++]))!=128){h--;continue}if(h>=s)return this.interim[0]=i,this.interim[1]=a,n;if((192&(o=e[h++]))!=128){h--;continue}if((c=(15&i)<<12|(63&a)<<6|63&o)<2048||c>=55296&&c<=57343||65279===c)continue;r[n++]=c}else if((248&i)==240){if(h>=s)return this.interim[0]=i,n;if((192&(a=e[h++]))!=128){h--;continue}if(h>=s)return this.interim[0]=i,this.interim[1]=a,n;if((192&(o=e[h++]))!=128){h--;continue}if(h>=s)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,n;if((192&(l=e[h++]))!=128){h--;continue}if((c=(7&i)<<18|(63&a)<<12|(63&o)<<6|63&l)<65536||c>1114111)continue;r[n++]=c}}return n}},pb=class e{constructor(){this.fg=0,this.bg=0,this.extended=new pw}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){let r=new e;return r.fg=this.fg,r.bg=this.bg,r.extended=this.extended.clone(),r}isInverse(){return 0x4000000&this.fg}isBold(){return 0x8000000&this.fg}isUnderline(){return this.hasExtendedAttrs()&&0!==this.extended.underlineStyle?1:0x10000000&this.fg}isBlink(){return 0x20000000&this.fg}isInvisible(){return 0x40000000&this.fg}isItalic(){return 0x4000000&this.bg}isDim(){return 0x8000000&this.bg}isStrikethrough(){return 0x80000000&this.fg}isProtected(){return 0x20000000&this.bg}isOverline(){return 0x40000000&this.bg}getFgColorMode(){return 0x3000000&this.fg}getBgColorMode(){return 0x3000000&this.bg}isFgRGB(){return(0x3000000&this.fg)==0x3000000}isBgRGB(){return(0x3000000&this.bg)==0x3000000}isFgPalette(){return(0x3000000&this.fg)==0x1000000||(0x3000000&this.fg)==0x2000000}isBgPalette(){return(0x3000000&this.bg)==0x1000000||(0x3000000&this.bg)==0x2000000}isFgDefault(){return(0x3000000&this.fg)==0}isBgDefault(){return(0x3000000&this.bg)==0}isAttributeDefault(){return 0===this.fg&&0===this.bg}getFgColor(){switch(0x3000000&this.fg){case 0x1000000:case 0x2000000:return 255&this.fg;case 0x3000000:return 0xffffff&this.fg;default:return -1}}getBgColor(){switch(0x3000000&this.bg){case 0x1000000:case 0x2000000:return 255&this.bg;case 0x3000000:return 0xffffff&this.bg;default:return -1}}hasExtendedAttrs(){return 0x10000000&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-0x10000001:this.bg|=0x10000000}getUnderlineColor(){if(0x10000000&this.bg&&~this.extended.underlineColor)switch(0x3000000&this.extended.underlineColor){case 0x1000000:case 0x2000000:return 255&this.extended.underlineColor;case 0x3000000:return 0xffffff&this.extended.underlineColor}return this.getFgColor()}getUnderlineColorMode(){return 0x10000000&this.bg&&~this.extended.underlineColor?0x3000000&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 0x10000000&this.bg&&~this.extended.underlineColor?(0x3000000&this.extended.underlineColor)==0x3000000:this.isFgRGB()}isUnderlineColorPalette(){return 0x10000000&this.bg&&~this.extended.underlineColor?(0x3000000&this.extended.underlineColor)==0x1000000||(0x3000000&this.extended.underlineColor)==0x2000000:this.isFgPalette()}isUnderlineColorDefault(){return 0x10000000&this.bg&&~this.extended.underlineColor?(0x3000000&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 0x10000000&this.fg?0x10000000&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},pw=class e{constructor(e=0,r=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=r}get ext(){return this._urlId?-0x1c000001&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(0x1c000000&this._ext)>>26}set underlineStyle(e){this._ext&=-0x1c000001,this._ext|=e<<26&0x1c000000}get underlineColor(){return 0x3ffffff&this._ext}set underlineColor(e){this._ext&=-0x4000000,this._ext|=0x3ffffff&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(0xe0000000&this._ext)>>29;return e<0?0xfffffff8^e:e}set underlineVariantOffset(e){this._ext&=0x1fffffff,this._ext|=e<<29&0xe0000000}clone(){return new e(this._ext,this._urlId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId}},pS=class e extends pb{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new pw,this.combinedData=""}static fromCharData(r){let s=new e;return s.setFromCharData(r),s}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?px(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[0],this.bg=0;let r=!1;if(e[1].length>2)r=!0;else if(2===e[1].length){let s=e[1].charCodeAt(0);if(55296<=s&&s<=56319){let n=e[1].charCodeAt(1);56320<=n&&n<=57343?this.content=(s-55296)*1024+n-56320+65536|e[2]<<22:r=!0}else r=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;r&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},pj="di$target",pC="di$dependencies",pk=new Map;function pN(e){if(pk.has(e))return pk.get(e);let r=function(e,s,n){var i,a,o;if(3!=arguments.length)throw Error("@IServiceName-decorator can only be used to decorate a parameter");i=r,a=e,o=n,a[pj]===a?a[pC].push({id:i,index:o}):(a[pC]=[{id:i,index:o}],a[pj]=a)};return r._id=e,pk.set(e,r),r}var pE=pN("BufferService"),pD=pN("CoreMouseService"),pR=pN("CoreService"),pA=pN("CharsetService"),pT=pN("InstantiationService"),pM=pN("LogService"),pF=pN("OptionsService"),pP=pN("OscLinkService"),pI=pN("UnicodeService"),pB=pN("DecorationService"),pL=class{constructor(e,r,s){this._bufferService=e,this._optionsService=r,this._oscLinkService=s}provideLinks(e,r){let s=this._bufferService.buffer.lines.get(e-1);if(!s)return void r(void 0);let n=[],i=this._optionsService.rawOptions.linkHandler,a=new pS,o=s.getTrimmedLength(),l=-1,c=-1,d=!1;for(let r=0;r<o;r++)if(!(-1===c&&!s.hasContent(r))){if(s.loadCell(r,a),a.hasExtendedAttrs()&&a.extended.urlId)if(-1===c){c=r,l=a.extended.urlId;continue}else d=a.extended.urlId!==l;else -1!==c&&(d=!0);if(d||-1!==c&&r===o-1){let s=this._oscLinkService.getLinkData(l)?.uri;if(s){let a={start:{x:c+1,y:e},end:{x:r+ +(!d&&r===o-1),y:e}},l=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(s);["http:","https:"].includes(e.protocol)||(l=!0)}catch{l=!0}l||n.push({text:s,range:a,activate:(e,r)=>i?i.activate(e,r,a):function(e,r){if(confirm(`Do you want to navigate to ${r}?
12
12
 
13
13
  WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=r}else console.warn("Opening link blocked as opener could not be cleared")}}(0,r),hover:(e,r)=>i?.hover?.(e,r,a),leave:(e,r)=>i?.leave?.(e,r,a)})}d=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=r,l=a.extended.urlId):(c=-1,l=-1)}}r(n)}};pL=pd([pu(0,pE),pu(1,pF),pu(2,pP)],pL);var pz=pN("CharSizeService"),pO=pN("CoreBrowserService"),p$=pN("MouseService"),pW=pN("RenderService"),pH=pN("SelectionService"),pU=pN("CharacterJoinerService"),pq=pN("ThemeService"),pK=pN("LinkProviderService"),pV=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?pJ.isErrorNoTelemetry(e)?new pJ(e.message+`
14
14
 
@@ -25,7 +25,7 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
25
25
  `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),x8&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:3===this._activeSelectionMode})}_isClickInSelection(e){let r=this._getMouseBufferCoords(e),s=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!!s&&!!n&&!!r&&this._areCoordsInSelection(r,s,n)}isCellInSelection(e,r){let s=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!!s&&!!n&&this._areCoordsInSelection([e,r],s,n)}_areCoordsInSelection(e,r,s){return e[1]>r[1]&&e[1]<s[1]||r[1]===s[1]&&e[1]===r[1]&&e[0]>=r[0]&&e[0]<s[0]||r[1]<s[1]&&e[1]===s[1]&&e[0]<s[0]||r[1]<s[1]&&e[1]===r[1]&&e[0]>=r[0]}_selectWordAtCursor(e,r){let s=this._linkifier.currentLink?.link?.range;if(s)return this._model.selectionStart=[s.start.x-1,s.start.y-1],this._model.selectionStartLength=vf(s,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let n=this._getMouseBufferCoords(e);return!!n&&(this._selectWordAt(n,r),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,r){this._model.clearSelection(),e=Math.max(e,0),r=Math.min(r,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,r],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let r=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(r)return r[0]--,r[1]--,r[1]+=this._bufferService.buffer.ydisp,r}_getMouseEventScrollAmount(e){let r=xq(this._coreBrowserService.window,e,this._screenElement)[1],s=this._renderService.dimensions.css.canvas.height;return r>=0&&r<=s?0:(r>s&&(r-=s),(r=Math.min(Math.max(r,-50),50)/50)/Math.abs(r)+Math.round(14*r))}shouldForceSelection(e){return x3?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(2===e.button&&this.hasSelection)&&0===e.button){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):1===e.detail?this._handleSingleClick(e):2===e.detail?this._handleDoubleClick(e):3===e.detail&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=3*!!this.shouldColumnSelect(e),this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let r=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);r&&r.length!==this._model.selectionStart[0]&&0===r.hasWidth(this._model.selectionStart[0])&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let r=this._getMouseBufferCoords(e);r&&(this._activeSelectionMode=2,this._selectLineAt(r[1]))}shouldColumnSelect(e){return e.altKey&&!(x3&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let r=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd)return void this.refresh(!0);2===this._activeSelectionMode?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:1===this._activeSelectionMode&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),3!==this._activeSelectionMode&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let s=this._bufferService.buffer;if(this._model.selectionEnd[1]<s.lines.length){let e=s.lines.get(this._model.selectionEnd[1]);e&&0===e.hasWidth(this._model.selectionEnd[0])&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}r&&r[0]===this._model.selectionEnd[0]&&r[1]===this._model.selectionEnd[1]||this.refresh(!0)}_dragScroll(){if(!(!this._model.selectionEnd||!this._model.selectionStart)&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let r=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&r<500&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let r=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(r&&void 0!==r[0]&&void 0!==r[1]){let e=function(e,r,s,n){var i,a,o,l,c,d,u,h,f,p,m,g,x,v,_,y,b,w;let S,j=s.buffer.x,C=s.buffer.y;if(!s.buffer.hasScrollback){let b,w,S;return i=j,o=0,(0===vo(a=C,r,l=s,c=n).length?"":vu(vc(i,a,i,a-vl(a,l),!1,l).length,vd("D",c)))+vo(C,r,s,n)+(d=j,u=C,h=e,b=vo(u,f=r,p=s,m=n).length>0?f-vl(f,p):u,S=(g=d,x=u,w=vo(v=h,_=f,y=p,m).length>0?_-vl(_,y):x,g<v&&w<=_||g>=v&&w<_?"C":"D"),vu(vc(d,b,h,f,"C"===S,p).length,vd(S,m)))}if(C===r)return S=j>e?"D":"C",vu(Math.abs(j-e),vd(S,n));S=C>r?"D":"C";let k=Math.abs(C-r);return vu((b=C>r?e:j,s.cols-b+(k-1)*s.cols+1+(w=0,(C>r?j:e)-1)),vd(S,n))}(r[0]-1,r[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,r=this._model.finalSelectionEnd,s=!!e&&!!r&&(e[0]!==r[0]||e[1]!==r[1]);if(!s){this._oldHasSelection&&this._fireOnSelectionChange(e,r,s);return}!e||!r||this._oldSelectionStart&&this._oldSelectionEnd&&e[0]===this._oldSelectionStart[0]&&e[1]===this._oldSelectionStart[1]&&r[0]===this._oldSelectionEnd[0]&&r[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(e,r,s)}_fireOnSelectionChange(e,r,s){this._oldSelectionStart=e,this._oldSelectionEnd=r,this._oldHasSelection=s,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,r){let s=r;for(let n=0;r>=n;n++){let i=e.loadCell(n,this._workCell).getChars().length;0===this._workCell.getWidth()?s--:i>1&&r!==n&&(s+=i-1)}return s}setSelection(e,r,s){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,r],this._model.selectionStartLength=s,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,r,s=!0,n=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),l=this._convertViewportColToCharacterIndex(a,e[0]),c=l,d=e[0]-l,u=0,h=0,f=0,p=0;if(" "===o.charAt(l)){for(;l>0&&" "===o.charAt(l-1);)l--;for(;c<o.length&&" "===o.charAt(c+1);)c++}else{let r=e[0],s=e[0];0===a.getWidth(r)&&(u++,r--),2===a.getWidth(s)&&(h++,s++);let n=a.getString(s).length;for(n>1&&(p+=n-1,c+=n-1);r>0&&l>0&&!this._isCharWordSeparator(a.loadCell(r-1,this._workCell));){a.loadCell(r-1,this._workCell);let e=this._workCell.getChars().length;0===this._workCell.getWidth()?(u++,r--):e>1&&(f+=e-1,l-=e-1),l--,r--}for(;s<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(s+1,this._workCell));){a.loadCell(s+1,this._workCell);let e=this._workCell.getChars().length;2===this._workCell.getWidth()?(h++,s++):e>1&&(p+=e-1,c+=e-1),c++,s++}}c++;let m=l+d-u+f,g=Math.min(this._bufferService.cols,c-l+u+h-f-p);if(!(!r&&""===o.slice(l,c).trim())){if(s&&0===m&&32!==a.getCodePoint(0)){let r=i.lines.get(e[1]-1);if(r&&a.isWrapped&&32!==r.getCodePoint(this._bufferService.cols-1)){let r=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(r){let e=this._bufferService.cols-r.start;m-=e,g+=e}}}if(n&&m+g===this._bufferService.cols&&32!==a.getCodePoint(this._bufferService.cols-1)){let r=i.lines.get(e[1]+1);if(r?.isWrapped&&32!==r.getCodePoint(0)){let r=this._getWordAt([0,e[1]+1],!1,!1,!0);r&&(g+=r.length)}}return{start:m,length:g}}}_selectWordAt(e,r){let s=this._getWordAt(e,r);if(s){for(;s.start<0;)s.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[s.start,e[1]],this._model.selectionStartLength=s.length}}_selectToWordAt(e){let r=this._getWordAt(e,!0);if(r){let s=e[1];for(;r.start<0;)r.start+=this._bufferService.cols,s--;if(!this._model.areSelectionValuesReversed())for(;r.start+r.length>this._bufferService.cols;)r.length-=this._bufferService.cols,s++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?r.start:r.start+r.length,s]}}_isCharWordSeparator(e){return 0!==e.getWidth()&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let r=this._bufferService.buffer.getWrappedRangeForLine(e),s={start:{x:0,y:r.first},end:{x:this._bufferService.cols-1,y:r.last}};this._model.selectionStart=[0,r.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=vf(s,this._bufferService.cols)}};vm=pd([pu(3,pE),pu(4,pR),pu(5,p$),pu(6,pF),pu(7,pW),pu(8,pO)],vm);var vg=class{constructor(){this._data={}}set(e,r,s){this._data[e]||(this._data[e]={}),this._data[e][r]=s}get(e,r){return this._data[e]?this._data[e][r]:void 0}clear(){this._data={}}},vx=class{constructor(){this._color=new vg,this._css=new vg}setCss(e,r,s){this._css.set(e,r,s)}getCss(e,r){return this._css.get(e,r)}setColor(e,r,s){this._color.set(e,r,s)}getColor(e,r){return this._color.get(e,r)}clear(){this._color.clear(),this._css.clear()}},vv=Object.freeze((()=>{let e=[v0.toColor("#2e3436"),v0.toColor("#cc0000"),v0.toColor("#4e9a06"),v0.toColor("#c4a000"),v0.toColor("#3465a4"),v0.toColor("#75507b"),v0.toColor("#06989a"),v0.toColor("#d3d7cf"),v0.toColor("#555753"),v0.toColor("#ef2929"),v0.toColor("#8ae234"),v0.toColor("#fce94f"),v0.toColor("#729fcf"),v0.toColor("#ad7fa8"),v0.toColor("#34e2e2"),v0.toColor("#eeeeec")],r=[0,95,135,175,215,255];for(let s=0;s<216;s++){let n=r[s/36%6|0],i=r[s/6%6|0],a=r[s%6];e.push({css:xl.toCss(n,i,a),rgba:xl.toRgba(n,i,a)})}for(let r=0;r<24;r++){let s=8+10*r;e.push({css:xl.toCss(s,s,s),rgba:xl.toRgba(s,s,s)})}return e})()),v_=v0.toColor("#ffffff"),vy=v0.toColor("#000000"),vb=v0.toColor("#ffffff"),vw={css:"rgba(255, 255, 255, 0.3)",rgba:0xffffff4d},vS=class extends p7{constructor(e){super(),this._optionsService=e,this._contrastCache=new vx,this._halfContrastCache=new vx,this._onChangeColors=this._register(new mC),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:v_,background:vy,cursor:vb,cursorAccent:vy,selectionForeground:void 0,selectionBackgroundTransparent:vw,selectionBackgroundOpaque:vQ.blend(vy,vw),selectionInactiveBackgroundTransparent:vw,selectionInactiveBackgroundOpaque:vQ.blend(vy,vw),scrollbarSliderBackground:vQ.opacity(v_,.2),scrollbarSliderHoverBackground:vQ.opacity(v_,.4),scrollbarSliderActiveBackground:vQ.opacity(v_,.5),overviewRulerBorder:v_,ansi:vv.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let r=this._colors;if(r.foreground=vj(e.foreground,v_),r.background=vj(e.background,vy),r.cursor=vQ.blend(r.background,vj(e.cursor,vb)),r.cursorAccent=vQ.blend(r.background,vj(e.cursorAccent,vy)),r.selectionBackgroundTransparent=vj(e.selectionBackground,vw),r.selectionBackgroundOpaque=vQ.blend(r.background,r.selectionBackgroundTransparent),r.selectionInactiveBackgroundTransparent=vj(e.selectionInactiveBackground,r.selectionBackgroundTransparent),r.selectionInactiveBackgroundOpaque=vQ.blend(r.background,r.selectionInactiveBackgroundTransparent),r.selectionForeground=e.selectionForeground?vj(e.selectionForeground,xf):void 0,r.selectionForeground===xf&&(r.selectionForeground=void 0),vQ.isOpaque(r.selectionBackgroundTransparent)&&(r.selectionBackgroundTransparent=vQ.opacity(r.selectionBackgroundTransparent,.3)),vQ.isOpaque(r.selectionInactiveBackgroundTransparent)&&(r.selectionInactiveBackgroundTransparent=vQ.opacity(r.selectionInactiveBackgroundTransparent,.3)),r.scrollbarSliderBackground=vj(e.scrollbarSliderBackground,vQ.opacity(r.foreground,.2)),r.scrollbarSliderHoverBackground=vj(e.scrollbarSliderHoverBackground,vQ.opacity(r.foreground,.4)),r.scrollbarSliderActiveBackground=vj(e.scrollbarSliderActiveBackground,vQ.opacity(r.foreground,.5)),r.overviewRulerBorder=vj(e.overviewRulerBorder,v_),r.ansi=vv.slice(),r.ansi[0]=vj(e.black,vv[0]),r.ansi[1]=vj(e.red,vv[1]),r.ansi[2]=vj(e.green,vv[2]),r.ansi[3]=vj(e.yellow,vv[3]),r.ansi[4]=vj(e.blue,vv[4]),r.ansi[5]=vj(e.magenta,vv[5]),r.ansi[6]=vj(e.cyan,vv[6]),r.ansi[7]=vj(e.white,vv[7]),r.ansi[8]=vj(e.brightBlack,vv[8]),r.ansi[9]=vj(e.brightRed,vv[9]),r.ansi[10]=vj(e.brightGreen,vv[10]),r.ansi[11]=vj(e.brightYellow,vv[11]),r.ansi[12]=vj(e.brightBlue,vv[12]),r.ansi[13]=vj(e.brightMagenta,vv[13]),r.ansi[14]=vj(e.brightCyan,vv[14]),r.ansi[15]=vj(e.brightWhite,vv[15]),e.extendedAnsi){let s=Math.min(r.ansi.length-16,e.extendedAnsi.length);for(let n=0;n<s;n++)r.ansi[n+16]=vj(e.extendedAnsi[n],vv[n+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(void 0===e){for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];return}switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function vj(e,r){if(void 0!==e)try{return v0.toColor(e)}catch{}return r}vS=pd([pu(0,pF)],vS);var vC=class{constructor(...e){for(let[r,s]of(this._entries=new Map,e))this.set(r,s)}set(e,r){let s=this._entries.get(e);return this._entries.set(e,r),s}forEach(e){for(let[r,s]of this._entries.entries())e(r,s)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},vk=class{constructor(){this._services=new vC,this._services.set(pT,this)}setService(e,r){this._services.set(e,r)}getService(e){return this._services.get(e)}createInstance(e,...r){let s=(e[pC]||[]).sort((e,r)=>e.index-r.index),n=[];for(let r of s){let s=this._services.get(r.id);if(!s)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${r.id._id}.`);n.push(s)}let i=s.length>0?s[0].index:r.length;if(r.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${r.length} static arguments`);return new e(...r,...n)}},vN={trace:0,debug:1,info:2,warn:3,error:4,off:5},vE=class extends p7{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=vN[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let r=0;r<e.length;r++)"function"==typeof e[r]&&(e[r]=e[r]())}_log(e,r,s){this._evalLazyOptionalParams(s),e.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+r,...s)}trace(e,...r){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,r)}debug(e,...r){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,r)}info(e,...r){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,r)}warn(e,...r){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,r)}error(e,...r){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,r)}};vE=pd([pu(0,pF)],vE);var vD=class extends p7{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new mC),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new mC),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new mC),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let r=Array(e);for(let s=0;s<Math.min(e,this.length);s++)r[s]=this._array[this._getCyclicIndex(s)];this._array=r,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let r=this._length;r<e;r++)this._array[r]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,r){this._array[this._getCyclicIndex(e)]=r}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,r,...s){if(r){for(let s=e;s<this._length-r;s++)this._array[this._getCyclicIndex(s)]=this._array[this._getCyclicIndex(s+r)];this._length-=r,this.onDeleteEmitter.fire({index:e,amount:r})}for(let r=this._length-1;r>=e;r--)this._array[this._getCyclicIndex(r+s.length)]=this._array[this._getCyclicIndex(r)];for(let r=0;r<s.length;r++)this._array[this._getCyclicIndex(e+r)]=s[r];if(s.length&&this.onInsertEmitter.fire({index:e,amount:s.length}),this._length+s.length>this._maxLength){let e=this._length+s.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=s.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,r,s){if(!(r<=0)){if(e<0||e>=this._length)throw Error("start argument out of range");if(e+s<0)throw Error("Cannot shift elements in list beyond index 0");if(s>0){for(let n=r-1;n>=0;n--)this.set(e+n+s,this.get(e+n));let n=e+r+s-this._length;if(n>0)for(this._length+=n;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let n=0;n<r;n++)this.set(e+n+s,this.get(e+n))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},vR=Object.freeze(new pb),vA=0,vT=class e{constructor(e,r,s=!1){this.isWrapped=s,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);let n=r||pS.fromCharData([0,"",1,0]);for(let r=0;r<e;++r)this.setCell(r,n);this.length=e}get(e){let r=this._data[3*e+0],s=2097151&r;return[this._data[3*e+1],2097152&r?this._combined[e]:s?px(s):"",r>>22,2097152&r?this._combined[e].charCodeAt(this._combined[e].length-1):s]}set(e,r){this._data[3*e+1]=r[0],r[1].length>1?(this._combined[e]=r[1],this._data[3*e+0]=2097152|e|r[2]<<22):this._data[3*e+0]=r[1].charCodeAt(0)|r[2]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 0xc00000&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){let r=this._data[3*e+0];return 2097152&r?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&r}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){let r=this._data[3*e+0];return 2097152&r?this._combined[e]:2097151&r?px(2097151&r):""}isProtected(e){return 0x20000000&this._data[3*e+2]}loadCell(e,r){return vA=3*e,r.content=this._data[vA+0],r.fg=this._data[vA+1],r.bg=this._data[vA+2],2097152&r.content&&(r.combinedData=this._combined[e]),0x10000000&r.bg&&(r.extended=this._extendedAttrs[e]),r}setCell(e,r){2097152&r.content&&(this._combined[e]=r.combinedData),0x10000000&r.bg&&(this._extendedAttrs[e]=r.extended),this._data[3*e+0]=r.content,this._data[3*e+1]=r.fg,this._data[3*e+2]=r.bg}setCellFromCodepoint(e,r,s,n){0x10000000&n.bg&&(this._extendedAttrs[e]=n.extended),this._data[3*e+0]=r|s<<22,this._data[3*e+1]=n.fg,this._data[3*e+2]=n.bg}addCodepointToCell(e,r,s){let n=this._data[3*e+0];2097152&n?this._combined[e]+=px(r):2097151&n?(this._combined[e]=px(2097151&n)+px(r),n&=-2097152,n|=2097152):n=4194304|r,s&&(n&=-0xc00001,n|=s<<22),this._data[3*e+0]=n}insertCells(e,r,s){if((e%=this.length)&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,s),r<this.length-e){let n=new pS;for(let s=this.length-e-r-1;s>=0;--s)this.setCell(e+r+s,this.loadCell(e+s,n));for(let n=0;n<r;++n)this.setCell(e+n,s)}else for(let r=e;r<this.length;++r)this.setCell(r,s);2===this.getWidth(this.length-1)&&this.setCellFromCodepoint(this.length-1,0,1,s)}deleteCells(e,r,s){if(e%=this.length,r<this.length-e){let n=new pS;for(let s=0;s<this.length-e-r;++s)this.setCell(e+s,this.loadCell(e+r+s,n));for(let e=this.length-r;e<this.length;++e)this.setCell(e,s)}else for(let r=e;r<this.length;++r)this.setCell(r,s);e&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,s),0!==this.getWidth(e)||this.hasContent(e)||this.setCellFromCodepoint(e,0,1,s)}replaceCells(e,r,s,n=!1){if(n){for(e&&2===this.getWidth(e-1)&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,s),r<this.length&&2===this.getWidth(r-1)&&!this.isProtected(r)&&this.setCellFromCodepoint(r,0,1,s);e<r&&e<this.length;)this.isProtected(e)||this.setCell(e,s),e++;return}for(e&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,s),r<this.length&&2===this.getWidth(r-1)&&this.setCellFromCodepoint(r,0,1,s);e<r&&e<this.length;)this.setCell(e++,s)}resize(e,r){if(e===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let s=3*e;if(e>this.length){if(this._data.buffer.byteLength>=4*s)this._data=new Uint32Array(this._data.buffer,0,s);else{let e=new Uint32Array(s);e.set(this._data),this._data=e}for(let s=this.length;s<e;++s)this.setCell(s,r)}else{this._data=this._data.subarray(0,s);let r=Object.keys(this._combined);for(let s=0;s<r.length;s++){let n=parseInt(r[s],10);n>=e&&delete this._combined[n]}let n=Object.keys(this._extendedAttrs);for(let r=0;r<n.length;r++){let s=parseInt(n[r],10);s>=e&&delete this._extendedAttrs[s]}}return this.length=e,4*s*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,r=!1){if(r){for(let r=0;r<this.length;++r)this.isProtected(r)||this.setCell(r,e);return}this._combined={},this._extendedAttrs={};for(let r=0;r<this.length;++r)this.setCell(r,e)}copyFrom(e){for(let r in this.length!==e.length?this._data=new Uint32Array(e._data):this._data.set(e._data),this.length=e.length,this._combined={},e._combined)this._combined[r]=e._combined[r];for(let r in this._extendedAttrs={},e._extendedAttrs)this._extendedAttrs[r]=e._extendedAttrs[r];this.isWrapped=e.isWrapped}clone(){let r=new e(0);for(let e in r._data=new Uint32Array(this._data),r.length=this.length,this._combined)r._combined[e]=this._combined[e];for(let e in this._extendedAttrs)r._extendedAttrs[e]=this._extendedAttrs[e];return r.isWrapped=this.isWrapped,r}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||0x3000000&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,r,s,n,i){let a=e._data;if(i)for(let i=n-1;i>=0;i--){for(let e=0;e<3;e++)this._data[(s+i)*3+e]=a[(r+i)*3+e];0x10000000&a[(r+i)*3+2]&&(this._extendedAttrs[s+i]=e._extendedAttrs[r+i])}else for(let i=0;i<n;i++){for(let e=0;e<3;e++)this._data[(s+i)*3+e]=a[(r+i)*3+e];0x10000000&a[(r+i)*3+2]&&(this._extendedAttrs[s+i]=e._extendedAttrs[r+i])}let o=Object.keys(e._combined);for(let n=0;n<o.length;n++){let i=parseInt(o[n],10);i>=r&&(this._combined[i-r+s]=e._combined[i])}}translateToString(e,r,s,n){r=r??0,s=s??this.length,e&&(s=Math.min(s,this.getTrimmedLength())),n&&(n.length=0);let i="";for(;r<s;){let e=this._data[3*r+0],s=2097151&e,a=2097152&e?this._combined[r]:s?px(s):" ";if(i+=a,n)for(let e=0;e<a.length;++e)n.push(r);r+=e>>22||1}return n&&n.push(r),i}};function vM(e,r,s){if(r===e.length-1)return e[r].getTrimmedLength();let n=!e[r].hasContent(s-1)&&1===e[r].getWidth(s-1),i=2===e[r+1].getWidth(0);return n&&i?s-1:s}var vF=class e{constructor(r){this.line=r,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new mC),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),p5(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};vF._nextId=1;var vP={},vI=vP.B;vP[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},vP.A={"#":"£"},vP.B=void 0,vP[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},vP.C=vP[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},vP.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},vP.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},vP.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},vP.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},vP.E=vP[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},vP.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},vP.H=vP[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},vP["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var vB=class{constructor(e,r,s){this._hasScrollback=e,this._optionsService=r,this._bufferService=s,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=vR.clone(),this.savedCharset=vI,this.markers=[],this._nullCell=pS.fromCharData([0,"",1,0]),this._whitespaceCell=pS.fromCharData([0," ",1,32]),this._isClearing=!1,this._memoryCleanupQueue=new vs,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new vD(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new pw),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new pw),this._whitespaceCell}getBlankLine(e,r){return new vT(this._bufferService.cols,this.getNullCell(e),r)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let r=e+this._optionsService.rawOptions.scrollback;return r>0xffffffff?0xffffffff:r}fillViewportRows(e){if(0===this.lines.length){void 0===e&&(e=vR);let r=this._rows;for(;r--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new vD(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,r){let s=this.getNullCell(vR),n=0,i=this._getCorrectBufferLength(r);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let r=0;r<this.lines.length;r++)n+=+this.lines.get(r).resize(e,s);let a=0;if(this._rows<r)for(let n=this._rows;n<r;n++)this.lines.length<r+this.ybase&&(this._optionsService.rawOptions.windowsMode||void 0!==this._optionsService.rawOptions.windowsPty.backend||void 0!==this._optionsService.rawOptions.windowsPty.buildNumber?this.lines.push(new vT(e,s)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new vT(e,s)));else for(let e=this._rows;e>r;e--)this.lines.length>r+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,r-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=r-1,this._isReflowEnabled&&(this._reflow(e,r),this._cols>e))for(let r=0;r<this.lines.length;r++)n+=+this.lines.get(r).resize(e,s);this._cols=e,this._rows=r,this._memoryCleanupQueue.clear(),n>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let r=0;for(;this._memoryCleanupPosition<this.lines.length;)if((r+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory())>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&"conpty"===e.backend&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,r){this._cols!==e&&(e>this._cols?this._reflowLarger(e,r):this._reflowSmaller(e,r))}_reflowLarger(e,r){let s=this._optionsService.rawOptions.reflowCursorLine,n=function(e,r,s,n,i,a){let o=[];for(let l=0;l<e.length-1;l++){let c=l,d=e.get(++c);if(!d.isWrapped)continue;let u=[e.get(l)];for(;c<e.length&&d.isWrapped;)u.push(d),d=e.get(++c);if(!a&&n>=l&&n<c){l+=u.length-1;continue}let h=0,f=vM(u,0,r),p=1,m=0;for(;p<u.length;){let e=vM(u,p,r),n=Math.min(e-m,s-f);u[h].copyCellsFrom(u[p],m,f,n,!1),(f+=n)===s&&(h++,f=0),(m+=n)===e&&(p++,m=0),0===f&&0!==h&&2===u[h-1].getWidth(s-1)&&(u[h].copyCellsFrom(u[h-1],s-1,f++,1,!1),u[h-1].setCell(s-1,i))}u[h].replaceCells(f,s,i);let g=0;for(let e=u.length-1;e>0&&(e>h||0===u[e].getTrimmedLength());e--)g++;g>0&&(o.push(l+u.length-g),o.push(g)),l+=u.length-1}return o}(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(vR),s);if(n.length>0){let s=function(e,r){let s=[],n=0,i=r[0],a=0;for(let o=0;o<e.length;o++)if(i===o){let s=r[++n];e.onDeleteEmitter.fire({index:o-a,amount:s}),o+=s-1,a+=s,i=r[++n]}else s.push(o);return{layout:s,countRemoved:a}}(this.lines,n);(function(e,r){let s=[];for(let n=0;n<r.length;n++)s.push(e.get(r[n]));for(let r=0;r<s.length;r++)e.set(r,s[r]);e.length=r.length})(this.lines,s.layout),this._reflowLargerAdjustViewport(e,r,s.countRemoved)}}_reflowLargerAdjustViewport(e,r,s){let n=this.getNullCell(vR),i=s;for(;i-- >0;)0===this.ybase?(this.y>0&&this.y--,this.lines.length<r&&this.lines.push(new vT(e,n))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-s,0)}_reflowSmaller(e,r){let s=this._optionsService.rawOptions.reflowCursorLine,n=this.getNullCell(vR),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let l=this.lines.get(o);if(!l||!l.isWrapped&&l.getTrimmedLength()<=e)continue;let c=[l];for(;l.isWrapped&&o>0;)l=this.lines.get(--o),c.unshift(l);if(!s){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let d=c[c.length-1].getTrimmedLength(),u=function(e,r,s){let n=[],i=e.map((s,n)=>vM(e,n,r)).reduce((e,r)=>e+r),a=0,o=0,l=0;for(;l<i;){if(i-l<s){n.push(i-l);break}a+=s;let c=vM(e,o,r);a>c&&(a-=c,o++);let d=2===e[o].getWidth(a-1);d&&a--;let u=d?s-1:s;n.push(u),l+=u}return n}(c,this._cols,e),h=u.length-c.length,f;f=0===this.ybase&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+h):Math.max(0,this.lines.length-this.lines.maxLength+h);let p=[];for(let e=0;e<h;e++){let e=this.getBlankLine(vR,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,g=u[m];0===g&&(g=u[--m]);let x=c.length-h-1,v=d;for(;x>=0;){let e=Math.min(v,g);if(void 0===c[m])break;c[m].copyCellsFrom(c[x],v-e,g-e,e,!0),0==(g-=e)&&(g=u[--m]),0==(v-=e)&&(v=vM(c,Math.max(--x,0),this._cols))}for(let r=0;r<c.length;r++)u[r]<e&&c[r].setCell(u[r],n);let _=h-f;for(;_-- >0;)0===this.ybase?this.y<r-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-r&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+h,this.ybase+r-1)}if(i.length>0){let e=[],r=[];for(let e=0;e<this.lines.length;e++)r.push(this.lines.get(e));let s=this.lines.length,n=s-1,o=0,l=i[0];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let d=Math.min(this.lines.maxLength-1,s+a-1);d>=0;d--)if(l&&l.start>n+c){for(let e=l.newLines.length-1;e>=0;e--)this.lines.set(d--,l.newLines[e]);d++,e.push({index:n+1,amount:l.newLines.length}),c+=l.newLines.length,l=i[++o]}else this.lines.set(d,r[n--]);let d=0;for(let r=e.length-1;r>=0;r--)e[r].index+=d,this.lines.onInsertEmitter.fire(e[r]),d+=e[r].amount;let u=Math.max(0,s+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,r,s=0,n){let i=this.lines.get(e);return i?i.translateToString(r,s,n):""}getWrappedRangeForLine(e){let r=e,s=e;for(;r>0&&this.lines.get(r).isWrapped;)r--;for(;s+1<this.lines.length&&this.lines.get(s+1).isWrapped;)s++;return{first:r,last:s}}setupTabStops(e){for(null!=e?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(null==e&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(null==e&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let r=0;r<this.markers.length;r++)this.markers[r].line===e&&(this.markers[r].dispose(),this.markers.splice(r--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let r=new vF(e);return this.markers.push(r),r.register(this.lines.onTrim(e=>{r.line-=e,r.line<0&&r.dispose()})),r.register(this.lines.onInsert(e=>{r.line>=e.index&&(r.line+=e.amount)})),r.register(this.lines.onDelete(e=>{r.line>=e.index&&r.line<e.index+e.amount&&r.dispose(),r.line>e.index&&(r.line-=e.amount)})),r.register(r.onDispose(()=>this._removeMarker(r))),r}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},vL=class extends p7{constructor(e,r){super(),this._optionsService=e,this._bufferService=r,this._onBufferActivate=this._register(new mC),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new vB(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new vB(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,r){this._normal.resize(e,r),this._alt.resize(e,r),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},vz=class extends p7{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new mC),this.onResize=this._onResize.event,this._onScroll=this._register(new mC),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,2),this.rows=Math.max(e.rawOptions.rows||0,1),this.buffers=this._register(new vL(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,r){let s=this.cols!==e,n=this.rows!==r;this.cols=e,this.rows=r,this.buffers.resize(e,r),this._onResize.fire({cols:e,rows:r,colsChanged:s,rowsChanged:n})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,r=!1){let s=this.buffer,n;(n=this._cachedBlankLine)&&n.length===this.cols&&n.getFg(0)===e.fg&&n.getBg(0)===e.bg||(n=s.getBlankLine(e,r),this._cachedBlankLine=n),n.isWrapped=r;let i=s.ybase+s.scrollTop,a=s.ybase+s.scrollBottom;if(0===s.scrollTop){let e=s.lines.isFull;a===s.lines.length-1?e?s.lines.recycle().copyFrom(n):s.lines.push(n.clone()):s.lines.splice(a+1,0,n.clone()),e?this.isUserScrolling&&(s.ydisp=Math.max(s.ydisp-1,0)):(s.ybase++,this.isUserScrolling||s.ydisp++)}else{let e=a-i+1;s.lines.shiftElements(i+1,e-1,-1),s.lines.set(a,n.clone())}this.isUserScrolling||(s.ydisp=s.ybase),this._onScroll.fire(s.ydisp)}scrollLines(e,r){let s=this.buffer;if(e<0){if(0===s.ydisp)return;this.isUserScrolling=!0}else e+s.ydisp>=s.ybase&&(this.isUserScrolling=!1);let n=s.ydisp;s.ydisp=Math.max(Math.min(s.ydisp+e,s.ybase),0),n!==s.ydisp&&(r||this._onScroll.fire(s.ydisp))}};vz=pd([pu(0,pF)],vz);var vO={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:x3,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},v$=["normal","bold","100","200","300","400","500","600","700","800","900"],vW=class extends p7{constructor(e){super(),this._onOptionChange=this._register(new mC),this.onOptionChange=this._onOptionChange.event;let r={...vO};for(let s in e)if(s in r)try{let n=e[s];r[s]=this._sanitizeAndValidateOption(s,n)}catch(e){console.error(e)}this.rawOptions=r,this.options={...r},this._setupOptions(),this._register(p3(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,r){return this.onOptionChange(s=>{s===e&&r(this.rawOptions[e])})}onMultipleOptionChange(e,r){return this.onOptionChange(s=>{-1!==e.indexOf(s)&&r()})}_setupOptions(){let e=e=>{if(!(e in vO))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},r=(e,r)=>{if(!(e in vO))throw Error(`No option with key "${e}"`);r=this._sanitizeAndValidateOption(e,r),this.rawOptions[e]!==r&&(this.rawOptions[e]=r,this._onOptionChange.fire(e))};for(let s in this.rawOptions){let n={get:e.bind(this,s),set:r.bind(this,s)};Object.defineProperty(this.options,s,n)}}_sanitizeAndValidateOption(e,r){switch(e){case"cursorStyle":var s;if(r||(r=vO[e]),"block"!==(s=r)&&"underline"!==s&&"bar"!==s)throw Error(`"${r}" is not a valid value for ${e}`);break;case"wordSeparator":r||(r=vO[e]);break;case"fontWeight":case"fontWeightBold":if("number"==typeof r&&1<=r&&r<=1e3)break;r=v$.includes(r)?r:vO[e];break;case"cursorWidth":r=Math.floor(r);case"lineHeight":case"tabStopWidth":if(r<1)throw Error(`${e} cannot be less than 1, value: ${r}`);break;case"minimumContrastRatio":r=Math.max(1,Math.min(21,Math.round(10*r)/10));break;case"scrollback":if((r=Math.min(r,0xffffffff))<0)throw Error(`${e} cannot be less than 0, value: ${r}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(r<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${r}`);break;case"rows":case"cols":if(!r&&0!==r)throw Error(`${e} must be numeric, value: ${r}`);break;case"windowsPty":r=r??{}}return r}};function vH(e,r=5){if("object"!=typeof e)return e;let s=Array.isArray(e)?[]:{};for(let n in e)s[n]=r<=1?e[n]:e[n]&&vH(e[n],r-1);return s}var vU=Object.freeze({insertMode:!1}),vq=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),vK=class extends p7{constructor(e,r,s){super(),this._bufferService=e,this._logService=r,this._optionsService=s,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new mC),this.onData=this._onData.event,this._onUserInput=this._register(new mC),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new mC),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new mC),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=vH(vU),this.decPrivateModes=vH(vq)}reset(){this.modes=vH(vU),this.decPrivateModes=vH(vq)}triggerDataEvent(e,r=!1){if(this._optionsService.rawOptions.disableStdin)return;let s=this._bufferService.buffer;r&&this._optionsService.rawOptions.scrollOnUserInput&&s.ybase!==s.ydisp&&this._onRequestScrollToBottom.fire(),r&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};vK=pd([pu(0,pE),pu(1,pM),pu(2,pF)],vK);var vV={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>4!==e.button&&1===e.action&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>32!==e.action},DRAG:{events:23,restrict:e=>32!==e.action||3!==e.button},ANY:{events:31,restrict:e=>!0}};function vY(e,r){let s=16*!!e.ctrl|4*!!e.shift|8*!!e.alt;return 4===e.button?(s|=64,s|=e.action):(s|=3&e.button,4&e.button&&(s|=64),8&e.button&&(s|=128),32===e.action?s|=32:0!==e.action||r||(s|=3)),s}var vG=String.fromCharCode,vX={DEFAULT:e=>{let r=[vY(e,!1)+32,e.col+32,e.row+32];return r[0]>255||r[1]>255||r[2]>255?"":`\x1b[M${vG(r[0])}${vG(r[1])}${vG(r[2])}`},SGR:e=>{let r=0===e.action&&4!==e.button?"m":"M";return`\x1b[<${vY(e,!0)};${e.col};${e.row}${r}`},SGR_PIXELS:e=>{let r=0===e.action&&4!==e.button?"m":"M";return`\x1b[<${vY(e,!0)};${e.x};${e.y}${r}`}},vJ=class extends p7{constructor(e,r,s){for(let n of(super(),this._bufferService=e,this._coreService=r,this._optionsService=s,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new mC),this.onProtocolChange=this._onProtocolChange.event,Object.keys(vV)))this.addProtocol(n,vV[n]);for(let e of Object.keys(vX))this.addEncoding(e,vX[e]);this.reset()}addProtocol(e,r){this._protocols[e]=r}addEncoding(e,r){this._encodings[e]=r}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return 0!==this._protocols[this._activeProtocol].events}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,r,s){if(0===e.deltaY||e.shiftKey||void 0===r||void 0===s)return 0;let n=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(n/=r/s+0,50>Math.abs(e.deltaY)&&(n*=.3),this._wheelPartialScroll+=n,n=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(n*=this._bufferService.rows),n}_applyScrollModifier(e,r){return r.altKey||r.ctrlKey||r.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||4===e.button&&32===e.action||3===e.button&&32!==e.action||4!==e.button&&(2===e.action||3===e.action)||(e.col++,e.row++,32===e.action&&this._lastEvent&&this._equalEvents(this._lastEvent,e,"SGR_PIXELS"===this._activeEncoding))||!this._protocols[this._activeProtocol].restrict(e))return!1;let r=this._encodings[this._activeEncoding](e);return r&&("DEFAULT"===this._activeEncoding?this._coreService.triggerBinaryEvent(r):this._coreService.triggerDataEvent(r,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,r,s){if(s){if(e.x!==r.x||e.y!==r.y)return!1}else if(e.col!==r.col||e.row!==r.row)return!1;return e.button===r.button&&e.action===r.action&&e.ctrl===r.ctrl&&e.alt===r.alt&&e.shift===r.shift}};vJ=pd([pu(0,pE),pu(1,pR),pu(2,pF)],vJ);var vZ,vQ,v0,v1,v2,v5,v3=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],v4=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],v6=class{constructor(){if(this.version="6",!v5){(v5=new Uint8Array(65536)).fill(1),v5[0]=0,v5.fill(0,1,32),v5.fill(0,127,160),v5.fill(2,4352,4448),v5[9001]=2,v5[9002]=2,v5.fill(2,11904,42192),v5[12351]=1,v5.fill(2,44032,55204),v5.fill(2,63744,64256),v5.fill(2,65040,65050),v5.fill(2,65072,65136),v5.fill(2,65280,65377),v5.fill(2,65504,65511);for(let e=0;e<v3.length;++e)v5.fill(0,v3[e][0],v3[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?v5[e]:!function(e,r){let s=0,n=r.length-1,i;if(e<r[0][0]||e>r[n][1])return!1;for(;n>=s;)if(e>r[i=s+n>>1][1])s=i+1;else{if(!(e<r[i][0]))return!0;n=i-1}return!1}(e,v4)?e>=131072&&e<=196605||e>=196608&&e<=262141?2:1:0}charProperties(e,r){let s=this.wcwidth(e),n=0===s&&0!==r;if(n){let e=v7.extractWidth(r);0===e?n=!1:e>s&&(s=e)}return v7.createPropertyValue(0,s,n)}},v7=class e{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new mC,this.onChange=this._onChange.event;let e=new v6;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return(1&e)!=0}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,r,s=!1){return(0xffffff&e)<<3|(3&r)<<1|!!s}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(r){let s=0,n=0,i=r.length;for(let a=0;a<i;++a){let o=r.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return s+this.wcwidth(o);let e=r.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:s+=this.wcwidth(e)}let l=this.charProperties(o,n),c=e.extractWidth(l);e.extractShouldJoin(l)&&(c-=e.extractWidth(n)),s+=c,n=l}return s}charProperties(e,r){return this._activeProvider.charProperties(e,r)}},v8=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,r){this._charsets[e]=r,this.glevel===e&&(this.charset=r)}};function v9(e){let r=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);s&&r&&(s.isWrapped=0!==r[3]&&32!==r[3])}var _e=class e{constructor(e=32,r=32){if(this.maxLength=e,this.maxSubParamsLength=r,r>256)throw Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(r),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(r){let s=new e;if(!r.length)return s;for(let e=+!!Array.isArray(r[0]);e<r.length;++e){let n=r[e];if(Array.isArray(n))for(let e=0;e<n.length;++e)s.addSubParam(n[e]);else s.addParam(n)}return s}clone(){let r=new e(this.maxLength,this.maxSubParamsLength);return r.params.set(this.params),r.length=this.length,r._subParams.set(this._subParams),r._subParamsLength=this._subParamsLength,r._subParamsIdx.set(this._subParamsIdx),r._rejectDigits=this._rejectDigits,r._rejectSubDigits=this._rejectSubDigits,r._digitIsSub=this._digitIsSub,r}toArray(){let e=[];for(let r=0;r<this.length;++r){e.push(this.params[r]);let s=this._subParamsIdx[r]>>8,n=255&this._subParamsIdx[r];n-s>0&&e.push(Array.prototype.slice.call(this._subParams,s,n))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(e<-1)throw Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>0x7fffffff?0x7fffffff:e}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=e>0x7fffffff?0x7fffffff:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let r=this._subParamsIdx[e]>>8,s=255&this._subParamsIdx[e];return s-r>0?this._subParams.subarray(r,s):null}getSubParamsAll(){let e={};for(let r=0;r<this.length;++r){let s=this._subParamsIdx[r]>>8,n=255&this._subParamsIdx[r];n-s>0&&(e[r]=this._subParams.slice(s,n))}return e}addDigit(e){let r;if(this._rejectDigits||!(r=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,n=s[r-1];s[r-1]=~n?Math.min(10*n+e,0x7fffffff):e}},_t=[],_r=class{constructor(){this._state=0,this._active=_t,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,r){void 0===this._handlers[e]&&(this._handlers[e]=[]);let s=this._handlers[e];return s.push(r),{dispose:()=>{let e=s.indexOf(r);-1!==e&&s.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=_t}reset(){if(2===this._state)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=_t,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||_t,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].start();else this._handlerFb(this._id,"START")}_put(e,r,s){if(this._active.length)for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,r,s);else this._handlerFb(this._id,"PUT",pv(e,r,s))}start(){this.reset(),this._state=1}put(e,r,s){if(3!==this._state){if(1===this._state)for(;r<s;){let s=e[r++];if(59===s){this._state=2,this._start();break}if(s<48||57<s){this._state=3;return}-1===this._id&&(this._id=0),this._id=10*this._id+s-48}2===this._state&&s-r>0&&this._put(e,r,s)}}end(e,r=!0){if(0!==this._state){if(3!==this._state)if(1===this._state&&this._start(),this._active.length){let s=!1,n=this._active.length-1,i=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,s=r,i=this._stack.fallThrough,this._stack.paused=!1),!i&&!1===s){for(;n>=0&&!0!==(s=this._active[n].end(e));n--)if(s instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,s;n--}for(;n>=0;n--)if((s=this._active[n].end(!1))instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,s}else this._handlerFb(this._id,"END",e);this._active=_t,this._id=-1,this._state=0}}},_s=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,r,s){this._hitLimit||(this._data+=pv(e,r,s),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let r=!1;if(this._hitLimit)r=!1;else if(e&&(r=this._handler(this._data))instanceof Promise)return r.then(e=>(this._data="",this._hitLimit=!1,e));return this._data="",this._hitLimit=!1,r}},_n=[],_i=class{constructor(){this._handlers=Object.create(null),this._active=_n,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=_n}registerHandler(e,r){void 0===this._handlers[e]&&(this._handlers[e]=[]);let s=this._handlers[e];return s.push(r),{dispose:()=>{let e=s.indexOf(r);-1!==e&&s.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=_n,this._ident=0}hook(e,r){if(this.reset(),this._ident=e,this._active=this._handlers[e]||_n,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(r);else this._handlerFb(this._ident,"HOOK",r)}put(e,r,s){if(this._active.length)for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,r,s);else this._handlerFb(this._ident,"PUT",pv(e,r,s))}unhook(e,r=!0){if(this._active.length){let s=!1,n=this._active.length-1,i=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,s=r,i=this._stack.fallThrough,this._stack.paused=!1),!i&&!1===s){for(;n>=0&&!0!==(s=this._active[n].unhook(e));n--)if(s instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,s;n--}for(;n>=0;n--)if((s=this._active[n].unhook(!1))instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,s}else this._handlerFb(this._ident,"UNHOOK",e);this._active=_n,this._ident=0}},_a=new _e;_a.addParam(0);var _o=class{constructor(e){this._handler=e,this._data="",this._params=_a,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():_a,this._data="",this._hitLimit=!1}put(e,r,s){this._hitLimit||(this._data+=pv(e,r,s),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let r=!1;if(this._hitLimit)r=!1;else if(e&&(r=this._handler(this._data,this._params))instanceof Promise)return r.then(e=>(this._params=_a,this._data="",this._hitLimit=!1,e));return this._params=_a,this._data="",this._hitLimit=!1,r}},_l=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,r){this.table.fill(e<<4|r)}add(e,r,s,n){this.table[r<<8|e]=s<<4|n}addMany(e,r,s,n){for(let i=0;i<e.length;i++)this.table[r<<8|e[i]]=s<<4|n}},_c=function(){let e=new _l(4095),r=Array.apply(null,Array(256)).map((e,r)=>r),s=(e,s)=>r.slice(e,s),n=s(32,127),i=s(0,24);i.push(25),i.push.apply(i,s(28,32));let a=s(0,14),o;for(o in e.setDefault(1,0),e.addMany(n,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(s(128,144),o,3,0),e.addMany(s(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(n,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(s(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(n,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(s(64,127),3,7,0),e.addMany(s(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(s(48,60),4,8,4),e.addMany(s(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(s(32,64),6,0,6),e.add(127,6,0,6),e.addMany(s(64,127),6,0,0),e.addMany(s(32,48),3,9,5),e.addMany(s(32,48),5,9,5),e.addMany(s(48,64),5,0,6),e.addMany(s(64,127),5,7,0),e.addMany(s(32,48),4,9,5),e.addMany(s(32,48),1,9,2),e.addMany(s(32,48),2,9,2),e.addMany(s(48,127),2,10,0),e.addMany(s(48,80),1,10,0),e.addMany(s(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(s(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(s(28,32),9,0,9),e.addMany(s(32,48),9,9,12),e.addMany(s(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(s(32,128),11,0,11),e.addMany(s(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(s(28,32),10,0,10),e.addMany(s(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(s(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(s(28,32),12,0,12),e.addMany(s(32,48),12,9,12),e.addMany(s(48,64),12,0,11),e.addMany(s(64,127),12,12,13),e.addMany(s(64,127),10,12,13),e.addMany(s(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(n,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(160,0,2,0),e.add(160,8,5,8),e.add(160,6,0,6),e.add(160,11,0,11),e.add(160,13,13,13),e}(),_d=class extends p7{constructor(e=_c){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new _e,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,r,s)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,r)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(p3(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new _r),this._dcsParser=this._register(new _i),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,r=[64,126]){let s=0;if(e.prefix){if(e.prefix.length>1)throw Error("only one byte as prefix supported");if((s=e.prefix.charCodeAt(0))&&60>s||s>63)throw Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw Error("only two bytes as intermediates are supported");for(let r=0;r<e.intermediates.length;++r){let n=e.intermediates.charCodeAt(r);if(32>n||n>47)throw Error("intermediate must be in range 0x20 .. 0x2f");s<<=8,s|=n}}if(1!==e.final.length)throw Error("final must be a single byte");let n=e.final.charCodeAt(0);if(r[0]>n||n>r[1])throw Error(`final must be in range ${r[0]} .. ${r[1]}`);return s<<=8,s|=n}identToString(e){let r=[];for(;e;)r.push(String.fromCharCode(255&e)),e>>=8;return r.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,r){let s=this._identifier(e,[48,126]);void 0===this._escHandlers[s]&&(this._escHandlers[s]=[]);let n=this._escHandlers[s];return n.push(r),{dispose:()=>{let e=n.indexOf(r);-1!==e&&n.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,r){this._executeHandlers[e.charCodeAt(0)]=r}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,r){let s=this._identifier(e);void 0===this._csiHandlers[s]&&(this._csiHandlers[s]=[]);let n=this._csiHandlers[s];return n.push(r),{dispose:()=>{let e=n.indexOf(r);-1!==e&&n.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,r){return this._dcsParser.registerHandler(this._identifier(e),r)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,r){return this._oscParser.registerHandler(e,r)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,0!==this._parseStack.state&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,r,s,n,i){this._parseStack.state=e,this._parseStack.handlers=r,this._parseStack.handlerPos=s,this._parseStack.transition=n,this._parseStack.chunkPos=i}parse(e,r,s){let n=0,i=0,a=0,o;if(this._parseStack.state)if(2===this._parseStack.state)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(void 0===s||1===this._parseStack.state)throw this._parseStack.state=1,Error("improper continuation due to previous async handler, giving up parsing");let r=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(!1===s&&i>-1){for(;i>=0&&!0!==(o=r[i](this._params));i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(!1===s&&i>-1){for(;i>=0&&!0!==(o=r[i]());i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(n=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(24!==n&&26!==n,s))return o;27===n&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(n=e[this._parseStack.chunkPos],o=this._oscParser.end(24!==n&&26!==n,s))return o;27===n&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let s=a;s<r;++s){switch(n=e[s],(i=this._transitions.table[this.currentState<<8|(n<160?n:160)])>>4){case 2:for(let i=s+1;;++i)if(i>=r||(n=e[i])<32||n>126&&n<160||++i>=r||(n=e[i])<32||n>126&&n<160||++i>=r||(n=e[i])<32||n>126&&n<160||++i>=r||(n=e[i])<32||n>126&&n<160){this._printHandler(e,s,i),s=i-1;break}break;case 3:this._executeHandlers[n]?this._executeHandlers[n]():this._executeHandlerFb(n),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:s,code:n,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|n],l=a?a.length-1:-1;for(;l>=0&&!0!==(o=a[l](this._params));l--)if(o instanceof Promise)return this._preserveStack(3,a,l,i,s),o;l<0&&this._csiHandlerFb(this._collect<<8|n,this._params),this.precedingJoinState=0;break;case 8:do switch(n){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(n-48)}while(++s<r&&(n=e[s])>47&&n<60)s--;break;case 9:this._collect<<=8,this._collect|=n;break;case 10:let c=this._escHandlers[this._collect<<8|n],d=c?c.length-1:-1;for(;d>=0&&!0!==(o=c[d]());d--)if(o instanceof Promise)return this._preserveStack(4,c,d,i,s),o;d<0&&this._escHandlerFb(this._collect<<8|n),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|n,this._params);break;case 13:for(let i=s+1;;++i)if(i>=r||24===(n=e[i])||26===n||27===n||n>127&&n<160){this._dcsParser.put(e,s,i),s=i-1;break}break;case 14:if(o=this._dcsParser.unhook(24!==n&&26!==n))return this._preserveStack(6,[],0,i,s),o;27===n&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=s+1;;i++)if(i>=r||(n=e[i])<32||n>127&&n<160){this._oscParser.put(e,s,i),s=i-1;break}break;case 6:if(o=this._oscParser.end(24!==n&&26!==n))return this._preserveStack(5,[],0,i,s),o;27===n&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&i}}},_u=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,_h=/^[\da-f]+$/;function _f(e){if(!e)return;let r=e.toLowerCase();if(0===r.indexOf("rgb:")){r=r.slice(4);let e=_u.exec(r);if(e){let r=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/r*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/r*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/r*255)]}}else if(0===r.indexOf("#")&&(r=r.slice(1),_h.exec(r)&&[3,6,9,12].includes(r.length))){let e=r.length/3,s=[0,0,0];for(let n=0;n<3;++n){let i=parseInt(r.slice(e*n,e*n+e),16);s[n]=1===e?i<<4:2===e?i:3===e?i>>4:i>>8}return s}}function _p(e,r){let s=e.toString(16),n=s.length<2?"0"+s:s;switch(r){case 4:return s[0];case 8:return n;case 12:return(n+n).slice(0,3);default:return n+n}}var _m={"(":0,")":1,"*":2,"+":3,"-":1,".":2};function _g(e,r){if(e>24)return r.setWinLines||!1;switch(e){case 1:return!!r.restoreWin;case 2:return!!r.minimizeWin;case 3:return!!r.setWinPosition;case 4:return!!r.setWinSizePixels;case 5:return!!r.raiseWin;case 6:return!!r.lowerWin;case 7:return!!r.refreshWin;case 8:return!!r.setWinSizeChars;case 9:return!!r.maximizeWin;case 10:return!!r.fullscreenWin;case 11:return!!r.getWinState;case 13:return!!r.getWinPosition;case 14:return!!r.getWinSizePixels;case 15:return!!r.getScreenSizePixels;case 16:return!!r.getCellSizePixels;case 18:return!!r.getWinSizeChars;case 19:return!!r.getScreenSizeChars;case 20:return!!r.getIconTitle;case 21:return!!r.getWinTitle;case 22:return!!r.pushTitle;case 23:return!!r.popTitle;case 24:return!!r.setWinLines}return!1}var _x=0,_v=class extends p7{constructor(e,r,s,n,i,a,o,l,c=new _d){for(let d in super(),this._bufferService=e,this._charsetService=r,this._coreService=s,this._logService=n,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=l,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new p_,this._utf8Decoder=new py,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=vR.clone(),this._eraseAttrDataInternal=vR.clone(),this._onRequestBell=this._register(new mC),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new mC),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new mC),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new mC),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new mC),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new mC),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new mC),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new mC),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new mC),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new mC),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new mC),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new mC),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new mC),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new __(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,r)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(e),params:r.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug("Unknown EXECUTE code: ",{code:e})}),this._parser.setOscHandlerFallback((e,r,s)=>{this._logService.debug("Unknown OSC code: ",{identifier:e,action:r,data:s})}),this._parser.setDcsHandlerFallback((e,r,s)=>{"HOOK"===r&&(s=s.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(e),action:r,payload:s})}),this._parser.setPrintHandler((e,r,s)=>this.print(e,r,s)),this._parser.registerCsiHandler({final:"@"},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:"A"},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:"B"},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:"C"},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:"D"},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:"E"},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:"F"},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:"G"},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:"H"},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:"I"},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:"J"},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:"K"},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:"L"},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:"M"},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:"P"},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:"S"},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:"T"},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:"X"},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:"Z"},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:"a"},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:"b"},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:"c"},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:">",final:"c"},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:"d"},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:"e"},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:"f"},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:"g"},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:"h"},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:"?",final:"h"},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:"l"},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:"?",final:"l"},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:"m"},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:"n"},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:"?",final:"n"},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:"r"},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:"s"},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:"t"},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:"u"},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler(xi.BEL,()=>this.bell()),this._parser.setExecuteHandler(xi.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(xi.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(xi.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(xi.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(xi.BS,()=>this.backspace()),this._parser.setExecuteHandler(xi.HT,()=>this.tab()),this._parser.setExecuteHandler(xi.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(xi.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(xa.IND,()=>this.index()),this._parser.setExecuteHandler(xa.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(xa.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new _s(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new _s(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new _s(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new _s(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new _s(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new _s(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new _s(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new _s(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new _s(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new _s(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new _s(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new _s(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset()),vP)this._parser.registerEscHandler({intermediates:"(",final:d},()=>this.selectCharset("("+d)),this._parser.registerEscHandler({intermediates:")",final:d},()=>this.selectCharset(")"+d)),this._parser.registerEscHandler({intermediates:"*",final:d},()=>this.selectCharset("*"+d)),this._parser.registerEscHandler({intermediates:"+",final:d},()=>this.selectCharset("+"+d)),this._parser.registerEscHandler({intermediates:"-",final:d},()=>this.selectCharset("-"+d)),this._parser.registerEscHandler({intermediates:".",final:d},()=>this.selectCharset("."+d)),this._parser.registerEscHandler({intermediates:"/",final:d},()=>this.selectCharset("/"+d));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error("Parsing error: ",e),e)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new _o((e,r)=>this.requestStatusString(e,r)))}getAttrData(){return this._curAttrData}_preserveStack(e,r,s,n){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=r,this._parseStack.decodedLength=s,this._parseStack.position=n}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,r)=>setTimeout(()=>r("#SLOW_TIMEOUT"),5e3))]).catch(e=>{if("#SLOW_TIMEOUT"!==e)throw e;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,r){let s,n=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(s=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,r))return this._logSlowResolvingAsync(s),s;n=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>131072&&(a=this._parseStack.position+131072)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${"string"==typeof e?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join("")}"`}`),0===this._logService.logLevel&&this._logService.trace("parsing data (codes)","string"==typeof e?e.split("").map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<131072&&(this._parseBuffer=new Uint32Array(Math.min(e.length,131072))),o||this._dirtyRowTracker.clearRange(),e.length>131072)for(let r=a;r<e.length;r+=131072){let a=r+131072<e.length?r+131072:e.length,o="string"==typeof e?this._stringDecoder.decode(e.substring(r,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(r,a),this._parseBuffer);if(s=this._parser.parse(this._parseBuffer,o))return this._preserveStack(n,i,o,r),this._logSlowResolvingAsync(s),s}else if(!o){let r="string"==typeof e?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(s=this._parser.parse(this._parseBuffer,r))return this._preserveStack(n,i,r,0),this._logSlowResolvingAsync(s),s}(this._activeBuffer.x!==n||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let l=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(l,this._bufferService.rows-1)})}print(e,r,s){let n,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,l=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,d=this._coreService.modes.insertMode,u=this._curAttrData,h=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&s-r>0&&2===h.getWidth(this._activeBuffer.x-1)&&h.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=r;p<s;++p){if((n=e[p])<127&&a){let e=a[String.fromCharCode(n)];e&&(n=e.charCodeAt(0))}let r=this._unicodeService.charProperties(n,f);i=v7.extractWidth(r);let s=v7.extractShouldJoin(r),m=s?v7.extractWidth(f):0;if(f=r,o&&this._onA11yChar.fire(px(n)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>l){if(c){let e=h,r=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),h=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&h instanceof vT&&h.copyCellsFrom(e,r,0,m,!1);r<l;)e.setCellFromCodepoint(r++,0,1,u)}else if(this._activeBuffer.x=l-1,2===i)continue}if(s&&this._activeBuffer.x){let e=h.getWidth(this._activeBuffer.x-1)?1:2;h.addCodepointToCell(this._activeBuffer.x-e,n,i);for(let e=i-m;--e>=0;)h.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(d&&(h.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),2===h.getWidth(l-1)&&h.setCellFromCodepoint(l-1,0,1,u)),h.setCellFromCodepoint(this._activeBuffer.x++,n,i,u),i>0)for(;--i;)h.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<l&&s-r>0&&0===h.getWidth(this._activeBuffer.x)&&!h.hasContent(this._activeBuffer.x)&&h.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,r){return"t"!==e.final||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,r):this._parser.registerCsiHandler(e,e=>!_g(e.params[0],this._optionsService.rawOptions.windowOptions)||r(e))}registerDcsHandler(e,r){return this._parser.registerDcsHandler(e,new _o(r))}registerEscHandler(e,r){return this._parser.registerEscHandler(e,r)}registerOscHandler(e,r){return this._parser.registerOscHandler(e,new _s(r))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(0===this._activeBuffer.x&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,r){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+r):(this._activeBuffer.x=e,this._activeBuffer.y=r),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,r){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+r)}cursorUp(e){let r=this._activeBuffer.y-this._activeBuffer.scrollTop;return r>=0?this._moveCursor(0,-Math.min(r,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let r=this._activeBuffer.scrollBottom-this._activeBuffer.y;return r>=0?this._moveCursor(0,Math.min(r,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let r=e.params[0];return 0===r?delete this._activeBuffer.tabs[this._activeBuffer.x]:3===r&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let r=e.params[0]||1;for(;r--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let r=e.params[0]||1;for(;r--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let r=e.params[0];return 1===r&&(this._curAttrData.bg|=0x20000000),(2===r||0===r)&&(this._curAttrData.bg&=-0x20000001),!0}_eraseInBufferLine(e,r,s,n=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(r,s,this._activeBuffer.getNullCell(this._eraseAttrData()),i),n&&(a.isWrapped=!1)}_resetBufferLine(e,r=!1){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s&&(s.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),r),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),s.isWrapped=!1)}eraseInDisplay(e,r=!1){let s;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(s=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s),this._eraseInBufferLine(s++,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,r);s<this._bufferService.rows;s++)this._resetBufferLine(s,r);this._dirtyRowTracker.markDirty(s);break;case 1:for(s=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s),this._eraseInBufferLine(s,0,this._activeBuffer.x+1,!0,r),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(s+1).isWrapped=!1);s--;)this._resetBufferLine(s,r);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(s=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,s-1);s--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+s)?.getTrimmedLength(););for(;s>=0;s--)this._bufferService.scroll(this._eraseAttrData())}else{for(s=this._bufferService.rows,this._dirtyRowTracker.markDirty(s-1);s--;)this._resetBufferLine(s,r);this._dirtyRowTracker.markDirty(0)}break;case 3:let n=this._activeBuffer.lines.length-this._bufferService.rows;n>0&&(this._activeBuffer.lines.trimStart(n),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-n,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-n,0),this._onScroll.fire(0))}return!0}eraseInLine(e,r=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,r);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,r);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,r)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let r=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let s=this._activeBuffer.ybase+this._activeBuffer.y,n=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-n+1;for(;r--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(s,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let r=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let s=this._activeBuffer.ybase+this._activeBuffer.y,n;for(n=this._bufferService.rows-1-this._activeBuffer.scrollBottom,n=this._bufferService.rows-1+this._activeBuffer.ybase-n;r--;)this._activeBuffer.lines.splice(s,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return r&&(r.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return r&&(r.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let r=e.params[0]||1;for(;r--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let r=e.params[0]||1;for(;r--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(vR));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let r=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s.deleteCells(0,r,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let r=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s.insertCells(0,r,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let r=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s.insertCells(this._activeBuffer.x,r,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let r=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s.deleteCells(this._activeBuffer.x,r,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return r&&(r.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let r=this._parser.precedingJoinState;if(!r)return!0;let s=e.params[0]||1,n=v7.extractWidth(r),i=this._activeBuffer.x-n,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*s),l=0;for(let e=0;e<a.length;){let r=a.codePointAt(e)||0;o[l++]=r,e+=r>65535?2:1}let c=l;for(let e=1;e<s;++e)o.copyWithin(c,0,l),c+=l;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(xi.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(xi.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(xi.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(xi.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(xi.ESC+"[>83;40003;0c")),!0}_is(e){return 0===(this._optionsService.rawOptions.termName+"").indexOf(e)}setMode(e){for(let r=0;r<e.length;r++)switch(e.params[r]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let r=0;r<e.length;r++)switch(e.params[r]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,vI),this._charsetService.setgCharset(1,vI),this._charsetService.setgCharset(2,vI),this._charsetService.setgCharset(3,vI);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let r=0;r<e.length;r++)switch(e.params[r]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let r=0;r<e.length;r++)switch(e.params[r]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),1049===e.params[r]&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,r){let s,n,i,a;(n=s||={})[n.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",n[n.SET=1]="SET",n[n.RESET=2]="RESET",n[n.PERMANENTLY_SET=3]="PERMANENTLY_SET",n[n.PERMANENTLY_RESET=4]="PERMANENTLY_RESET";let o=this._coreService.decPrivateModes,{activeProtocol:l,activeEncoding:c}=this._coreMouseService,d=this._coreService,{buffers:u,cols:h}=this._bufferService,{active:f,alt:p}=u,m=this._optionsService.rawOptions,g=e=>e?1:2,x=e.params[0];return i=x,a=r?2===x?4:4===x?g(d.modes.insertMode):12===x?3:20===x?g(m.convertEol):0:1===x?g(o.applicationCursorKeys):3===x?m.windowOptions.setWinLines?80===h?2:+(132===h):0:6===x?g(o.origin):7===x?g(o.wraparound):8===x?3:9===x?g("X10"===l):12===x?g(m.cursorBlink):25===x?g(!d.isCursorHidden):45===x?g(o.reverseWraparound):66===x?g(o.applicationKeypad):67===x?4:1e3===x?g("VT200"===l):1002===x?g("DRAG"===l):1003===x?g("ANY"===l):1004===x?g(o.sendFocus):1005===x?4:1006===x?g("SGR"===c):1015===x?4:1016===x?g("SGR_PIXELS"===c):1048===x?1:47===x||1047===x||1049===x?g(f===p):2004===x?g(o.bracketedPasteMode):2026===x?g(o.synchronizedOutput):0,d.triggerDataEvent(`${xi.ESC}[${r?"":"?"}${i};${a}$y`),!0}_updateAttrColor(e,r,s,n,i){return 2===r?(e|=0x3000000,e&=-0x1000000,e|=pb.fromColorRGB([s,n,i])):5===r&&(e&=-0x3000100,e|=0x2000000|255&s),e}_extractColor(e,r,s){let n=[0,0,-1,0,0,0],i=0,a=0;do{if(n[a+i]=e.params[r+a],e.hasSubParams(r+a)){let s=e.getSubParams(r+a),o=0;do 5===n[1]&&(i=1),n[a+o+1+i]=s[o];while(++o<s.length&&o+a+1+i<n.length)break}if(5===n[1]&&a+i>=2||2===n[1]&&a+i>=5)break;n[1]&&(i=1)}while(++a+r<e.length&&a+i<n.length)for(let e=2;e<n.length;++e)-1===n[e]&&(n[e]=0);switch(n[0]){case 38:s.fg=this._updateAttrColor(s.fg,n[1],n[3],n[4],n[5]);break;case 48:s.bg=this._updateAttrColor(s.bg,n[1],n[3],n[4],n[5]);break;case 58:s.extended=s.extended.clone(),s.extended.underlineColor=this._updateAttrColor(s.extended.underlineColor,n[1],n[3],n[4],n[5])}return a}_processUnderline(e,r){r.extended=r.extended.clone(),(!~e||e>5)&&(e=1),r.extended.underlineStyle=e,r.fg|=0x10000000,0===e&&(r.fg&=-0x10000001),r.updateExtended()}_processSGR0(e){e.fg=vR.fg,e.bg=vR.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-0x4000000,e.updateExtended()}charAttributes(e){if(1===e.length&&0===e.params[0])return this._processSGR0(this._curAttrData),!0;let r=e.length,s,n=this._curAttrData;for(let i=0;i<r;i++)(s=e.params[i])>=30&&s<=37?(n.fg&=-0x3000100,n.fg|=0x1000000|s-30):s>=40&&s<=47?(n.bg&=-0x3000100,n.bg|=0x1000000|s-40):s>=90&&s<=97?(n.fg&=-0x3000100,n.fg|=0x1000000|s-90|8):s>=100&&s<=107?(n.bg&=-0x3000100,n.bg|=0x1000000|s-100|8):0===s?this._processSGR0(n):1===s?n.fg|=0x8000000:3===s?n.bg|=0x4000000:4===s?(n.fg|=0x10000000,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,n)):5===s?n.fg|=0x20000000:7===s?n.fg|=0x4000000:8===s?n.fg|=0x40000000:9===s?n.fg|=0x80000000:2===s?n.bg|=0x8000000:21===s?this._processUnderline(2,n):22===s?(n.fg&=-0x8000001,n.bg&=-0x8000001):23===s?n.bg&=-0x4000001:24===s?(n.fg&=-0x10000001,this._processUnderline(0,n)):25===s?n.fg&=-0x20000001:27===s?n.fg&=-0x4000001:28===s?n.fg&=-0x40000001:29===s?n.fg&=0x7fffffff:39===s?(n.fg&=-0x4000000,n.fg|=0xffffff&vR.fg):49===s?(n.bg&=-0x4000000,n.bg|=0xffffff&vR.bg):38===s||48===s||58===s?i+=this._extractColor(e,i,n):53===s?n.bg|=0x40000000:55===s?n.bg&=-0x40000001:59===s?(n.extended=n.extended.clone(),n.extended.underlineColor=-1,n.updateExtended()):100===s?(n.fg&=-0x4000000,n.fg|=0xffffff&vR.fg,n.bg&=-0x4000000,n.bg|=0xffffff&vR.bg):this._logService.debug("Unknown SGR attribute: %d.",s);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${xi.ESC}[0n`);break;case 6:let r=this._activeBuffer.y+1,s=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${xi.ESC}[${r};${s}R`)}return!0}deviceStatusPrivate(e){if(6===e.params[0]){let e=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${xi.ESC}[?${e};${r}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=vR.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let r=0===e.length?1:e.params[0];if(0===r)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(r){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar"}this._coreService.decPrivateModes.cursorBlink=r%2==1}return!0}setScrollRegion(e){let r=e.params[0]||1,s;return(e.length<2||(s=e.params[1])>this._bufferService.rows||0===s)&&(s=this._bufferService.rows),s>r&&(this._activeBuffer.scrollTop=r-1,this._activeBuffer.scrollBottom=s-1,this._setCursor(0,0)),!0}windowOptions(e){if(!_g(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let r=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:2!==r&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${xi.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(0===r||2===r)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),(0===r||1===r)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:(0===r||2===r)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(0===r||1===r)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let r=[],s=e.split(";");for(;s.length>1;){let e=s.shift(),n=s.shift();if(/^\d+$/.exec(e)){let s=parseInt(e);if(_y(s))if("?"===n)r.push({type:0,index:s});else{let e=_f(n);e&&r.push({type:1,index:s,color:e})}}}return r.length&&this._onColor.fire(r),!0}setHyperlink(e){let r=e.indexOf(";");if(-1===r)return!0;let s=e.slice(0,r).trim(),n=e.slice(r+1);return n?this._createHyperlink(s,n):!s.trim()&&this._finishHyperlink()}_createHyperlink(e,r){this._getCurrentLinkId()&&this._finishHyperlink();let s=e.split(":"),n,i=s.findIndex(e=>e.startsWith("id="));return -1!==i&&(n=s[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:n,uri:r}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,r){let s=e.split(";");for(let e=0;e<s.length&&!(r>=this._specialColors.length);++e,++r)if("?"===s[e])this._onColor.fire([{type:0,index:this._specialColors[r]}]);else{let n=_f(s[e]);n&&this._onColor.fire([{type:1,index:this._specialColors[r],color:n}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let r=[],s=e.split(";");for(let e=0;e<s.length;++e)if(/^\d+$/.exec(s[e])){let n=parseInt(s[e]);_y(n)&&r.push({type:2,index:n})}return r.length&&this._onColor.fire(r),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,vI),!0}selectCharset(e){return 2!==e.length?this.selectDefaultCharset():"/"===e[0]||this._charsetService.setgCharset(_m[e[0]],vP[e[1]]||vI),!0}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=vR.clone(),this._eraseAttrDataInternal=vR.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-0x4000000,this._eraseAttrDataInternal.bg|=0x3ffffff&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new pS;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let r=0;r<this._bufferService.rows;++r){let s=this._activeBuffer.ybase+this._activeBuffer.y+r,n=this._activeBuffer.lines.get(s);n&&(n.fill(e),n.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,r){let s=e=>(this._coreService.triggerDataEvent(`${xi.ESC}${e}${xi.ESC}\\`),!0),n=this._bufferService.buffer,i=this._optionsService.rawOptions;return s('"q'===e?`P1$r${+!!this._curAttrData.isProtected()}"q`:'"p'===e?'P1$r61;1"p':"r"===e?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:"m"===e?"P1$r0m":" q"===e?`P1$r${({block:2,underline:4,bar:6})[i.cursorStyle]-!!i.cursorBlink} q`:"P0$r")}markRangeDirty(e,r){this._dirtyRowTracker.markRangeDirty(e,r)}},__=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,r){e>r&&(_x=e,e=r,r=_x),e<this.start&&(this.start=e),r>this.end&&(this.end=r)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function _y(e){return 0<=e&&e<256}__=pd([pu(0,pE)],__);var _b=class extends p7{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new mC),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,r){let s;if(void 0!==r&&this._syncCalls>r){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,!this._isSyncWriting){for(this._isSyncWriting=!0;s=this._writeBuffer.shift();){this._action(s);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=0x7fffffff,this._isSyncWriting=!1,this._syncCalls=0}}write(e,r){if(this._pendingData>5e7)throw Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(r),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(r)}_innerWrite(e=0,r=!0){let s=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],n=this._action(e,r);if(n){let e=e=>performance.now()-s>=12?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(s,e);n.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e);return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-s>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},_w=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let r=this._bufferService.buffer;if(void 0===e.id){let s=r.addMarker(r.ybase+r.y),n={data:e,id:this._nextId++,lines:[s]};return s.onDispose(()=>this._removeMarkerFromLink(n,s)),this._dataByLinkId.set(n.id,n),n.id}let s=this._getEntryIdKey(e),n=this._entriesWithId.get(s);if(n)return this.addLineToLink(n.id,r.ybase+r.y),n.id;let i=r.addMarker(r.ybase+r.y),a={id:this._nextId++,key:this._getEntryIdKey(e),data:e,lines:[i]};return i.onDispose(()=>this._removeMarkerFromLink(a,i)),this._entriesWithId.set(a.key,a),this._dataByLinkId.set(a.id,a),a.id}addLineToLink(e,r){let s=this._dataByLinkId.get(e);if(s&&s.lines.every(e=>e.line!==r)){let e=this._bufferService.buffer.addMarker(r);s.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(s,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,r){let s=e.lines.indexOf(r);-1!==s&&(e.lines.splice(s,1),0===e.lines.length&&(void 0!==e.data.id&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};_w=pd([pu(0,pE)],_w);var _S=!1,_j=class extends p7{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new p8),this._onBinary=this._register(new mC),this.onBinary=this._onBinary.event,this._onData=this._register(new mC),this.onData=this._onData.event,this._onLineFeed=this._register(new mC),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new mC),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new mC),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new mC),this._instantiationService=new vk,this.optionsService=this._register(new vW(e)),this._instantiationService.setService(pF,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(vz)),this._instantiationService.setService(pE,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(vE)),this._instantiationService.setService(pM,this._logService),this.coreService=this._register(this._instantiationService.createInstance(vK)),this._instantiationService.setService(pR,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(vJ)),this._instantiationService.setService(pD,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(v7)),this._instantiationService.setService(pI,this.unicodeService),this._charsetService=this._instantiationService.createInstance(v8),this._instantiationService.setService(pA,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(_w),this._instantiationService.setService(pP,this._oscLinkService),this._inputHandler=this._register(new _v(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(mv.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(mv.forward(this._bufferService.onResize,this._onResize)),this._register(mv.forward(this.coreService.onData,this._onData)),this._register(mv.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new _b((e,r)=>this._inputHandler.parse(e,r))),this._register(mv.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new mC),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let r in e)this.optionsService.options[r]=e[r]}write(e,r){this._writeBuffer.write(e,r)}writeSync(e,r){this._logService.logLevel<=3&&!_S&&(this._logService.warn("writeSync is unreliable and will be removed soon."),_S=!0),this._writeBuffer.writeSync(e,r)}input(e,r=!0){this.coreService.triggerDataEvent(e,r)}resize(e,r){isNaN(e)||isNaN(r)||(e=Math.max(e,2),r=Math.max(r,1),this._bufferService.resize(e,r))}scroll(e,r=!1){this._bufferService.scroll(e,r)}scrollLines(e,r){this._bufferService.scrollLines(e,r)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let r=e-this._bufferService.buffer.ydisp;0!==r&&this.scrollLines(r)}registerEscHandler(e,r){return this._inputHandler.registerEscHandler(e,r)}registerDcsHandler(e,r){return this._inputHandler.registerDcsHandler(e,r)}registerCsiHandler(e,r){return this._inputHandler.registerCsiHandler(e,r)}registerOscHandler(e,r){return this._inputHandler.registerOscHandler(e,r)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,r=this.optionsService.rawOptions.windowsPty;r&&void 0!==r.buildNumber&&void 0!==r.buildNumber?e="conpty"===r.backend&&r.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(v9.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(v9(this._bufferService),!1))),this._windowsWrappingHeuristics.value=p3(()=>{for(let r of e)r.dispose()})}}},_C={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']},_k=0,_N=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new vs,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new vs,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),0===this._insertedValues.length&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,r)=>this._getKey(e)-this._getKey(r)),r=0,s=0,n=Array(this._array.length+this._insertedValues.length);for(let i=0;i<n.length;i++)s>=this._array.length||this._getKey(e[r])<=this._getKey(this._array[s])?(n[i]=e[r],r++):n[i]=this._array[s++];this._array=n,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),0===this._array.length)return!1;let r=this._getKey(e);if(void 0===r||-1===(_k=this._search(r))||this._getKey(this._array[_k])!==r)return!1;do if(this._array[_k]===e)return 0===this._deletedIndices.length&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(_k),!0;while(++_k<this._array.length&&this._getKey(this._array[_k])===r)return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,r)=>e-r),r=0,s=Array(this._array.length-e.length),n=0;for(let i=0;i<this._array.length;i++)e[r]===i?r++:s[n++]=this._array[i];this._array=s,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),0!==this._array.length&&!((_k=this._search(e))<0||_k>=this._array.length)&&this._getKey(this._array[_k])===e)do yield this._array[_k];while(++_k<this._array.length&&this._getKey(this._array[_k])===e)}forEachByKey(e,r){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),0!==this._array.length&&!((_k=this._search(e))<0||_k>=this._array.length)&&this._getKey(this._array[_k])===e)do r(this._array[_k]);while(++_k<this._array.length&&this._getKey(this._array[_k])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let r=0,s=this._array.length-1;for(;s>=r;){let n=r+s>>1,i=this._getKey(this._array[n]);if(i>e)s=n-1;else if(i<e)r=n+1;else{for(;n>0&&this._getKey(this._array[n-1])===e;)n--;return n}}return r}},_E=0,_D=0,_R=class extends p7{constructor(){super(),this._decorations=new _N(e=>e?.marker.line),this._onDecorationRegistered=this._register(new mC),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new mC),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(p3(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let r=new _A(e);if(r){let e=r.marker.onDispose(()=>r.dispose()),s=r.onDispose(()=>{s.dispose(),r&&(this._decorations.delete(r)&&this._onDecorationRemoved.fire(r),e.dispose())});this._decorations.insert(r),this._onDecorationRegistered.fire(r)}return r}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,r,s){let n=0,i=0;for(let a of this._decorations.getKeyIterator(r))i=(n=a.options.x??0)+(a.options.width??1),e>=n&&e<i&&(!s||(a.options.layer??"bottom")===s)&&(yield a)}forEachDecorationAtCell(e,r,s,n){this._decorations.forEachByKey(r,r=>{_D=(_E=r.options.x??0)+(r.options.width??1),e>=_E&&e<_D&&(!s||(r.options.layer??"bottom")===s)&&n(r)})}},_A=class extends p6{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new mC),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new mC),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}get backgroundColorRGB(){return null===this._cachedBg&&(this.options.backgroundColor?this._cachedBg=v0.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return null===this._cachedFg&&(this.options.foregroundColor?this._cachedFg=v0.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},_T=class{constructor(e,r=1e3){this._renderCallback=e,this._debounceThresholdMS=r,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,r,s){this._rowCount=s,e=void 0!==e?e:0,r=void 0!==r?r:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,r):r;let n=performance.now();if(n-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=n,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=n-this._lastRefreshMs,r=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},r)}}_innerRefresh(){if(void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return;let e=Math.max(this._rowStart,0),r=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,r)}},_M=class extends p7{constructor(e,r,s,n){super(),this._terminal=e,this._coreBrowserService=s,this._renderService=n,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=i.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new _T(this._renderRows.bind(this))),!this._terminal.element)throw Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
26
26
  `))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(gD(i,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(p3(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let r=0;r<e;r++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
27
27
  `&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=pf)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,r){this._liveRegionDebouncer.refresh(e,r,this._terminal.rows)}_renderRows(e,r){let s=this._terminal.buffer,n=s.lines.length.toString();for(let i=e;i<=r;i++){let e=s.lines.get(s.ydisp+i),r=[],a=e?.translateToString(!0,void 0,void 0,r)||"",o=(s.ydisp+i+1).toString(),l=this._rowElements[i];l&&(0===a.length?(l.textContent=" ",this._rowColumns.set(l,[0,1])):(l.textContent=a,this._rowColumns.set(l,r)),l.setAttribute("aria-posinset",o),l.setAttribute("aria-setsize",n),this._alignRowWidth(l))}this._announceCharacters()}_announceCharacters(){0!==this._charsToAnnounce.length&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,r){let s,n,i=e.target,a=this._rowElements[0===r?1:this._rowElements.length-2];if(i.getAttribute("aria-posinset")!==(0===r?"1":`${this._terminal.buffer.lines.length}`)&&e.relatedTarget===a){if(0===r?(s=i,n=this._rowElements.pop(),this._rowContainer.removeChild(n)):(s=this._rowElements.shift(),n=i,this._rowContainer.removeChild(s)),s.removeEventListener("focus",this._topBoundaryFocusListener),n.removeEventListener("focus",this._bottomBoundaryFocusListener),0===r){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement("afterbegin",e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(0===r?-1:1),this._rowElements[0===r?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}}_handleSelectionChange(){if(0===this._rowElements.length)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode)return void console.error("anchorNode and/or focusNode are null");let r={node:e.anchorNode,offset:e.anchorOffset},s={node:e.focusNode,offset:e.focusOffset};if((r.node.compareDocumentPosition(s.node)&Node.DOCUMENT_POSITION_PRECEDING||r.node===s.node&&r.offset>s.offset)&&([r,s]=[s,r]),r.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(r={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(r.node))return;let n=this._rowElements.slice(-1)[0];if(s.node.compareDocumentPosition(n)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(s={node:n,offset:n.textContent?.length??0}),!this._rowContainer.contains(s.node))return;let i=({node:e,offset:r})=>{let s=e instanceof Text?e.parentNode:e,n=parseInt(s?.getAttribute("aria-posinset"),10)-1;if(isNaN(n))return console.warn("row is invalid. Race condition?"),null;let i=this._rowColumns.get(s);if(!i)return console.warn("columns is null. Race condition?"),null;let a=r<i.length?i[r]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++n,a=0),{row:n,column:a}},a=i(r),o=i(s);if(!(!a||!o)){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error("invalid range");this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform="";let r=e.getBoundingClientRect().width,s=this._rowColumns.get(e)?.slice(-1)?.[0];if(!s)return;let n=s*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${n/r})`}};_M=pd([pu(1,pT),pu(2,pO),pu(3,pW)],_M);var _F=class extends p7{constructor(e,r,s,n,i){super(),this._element=e,this._mouseService=r,this._renderService=s,this._bufferService=n,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new mC),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new mC),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(p3(()=>{p5(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(gD(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(gD(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(gD(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(gD(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let r=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!r)return;this._isMouseOut=!1;let s=e.composedPath();for(let e=0;e<s.length;e++){let r=s[e];if(r.classList.contains("xterm"))break;if(r.classList.contains("xterm-hover"))return}this._lastBufferCell&&r.x===this._lastBufferCell.x&&r.y===this._lastBufferCell.y||(this._handleHover(r),this._lastBufferCell=r)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized){this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1;return}this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,r){this._activeProviderReplies&&r||(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let s=!1;for(let[n,i]of this._linkProviderService.linkProviders.entries())r?this._activeProviderReplies?.get(n)&&(s=this._checkLinkProviderResult(n,e,s)):i.provideLinks(e.y,r=>{if(this._isMouseOut)return;let i=r?.map(e=>({link:e}));this._activeProviderReplies?.set(n,i),s=this._checkLinkProviderResult(n,e,s),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,r){let s=new Set;for(let n=0;n<r.size;n++){let i=r.get(n);if(i)for(let r=0;r<i.length;r++){let n=i[r],a=n.link.range.start.y<e?0:n.link.range.start.x,o=n.link.range.end.y>e?this._bufferService.cols:n.link.range.end.x;for(let e=a;e<=o;e++){if(s.has(e)){i.splice(r--,1);break}s.add(e)}}}}_checkLinkProviderResult(e,r,s){if(!this._activeProviderReplies)return s;let n=this._activeProviderReplies.get(e),i=!1;for(let r=0;r<e;r++)(!this._activeProviderReplies.has(r)||this._activeProviderReplies.get(r))&&(i=!0);if(!i&&n){let e=n.find(e=>this._linkAtPosition(e.link,r));e&&(s=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!s)for(let e=0;e<this._activeProviderReplies.size;e++){let n=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,r));if(n){s=!0,this._handleNewLink(n);break}}return s}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){var r,s;if(!this._currentLink)return;let n=this._positionFromMouseEvent(e,this._element,this._mouseService);n&&this._mouseDownLink&&(r=this._mouseDownLink.link,s=this._currentLink.link,r.text===s.text&&r.range.start.x===s.range.start.x&&r.range.start.y===s.range.start.y&&r.range.end.x===s.range.end.x&&r.range.end.y===s.range.end.y)&&this._linkAtPosition(this._currentLink.link,n)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,r){this._currentLink&&this._lastMouseEvent&&(!e||!r||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=r)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,p5(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let r=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);r&&this._linkAtPosition(e.link,r)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:void 0===e.link.decorations||e.link.decorations.underline,pointerCursor:void 0===e.link.decorations||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:r=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==r&&(this._currentLink.state.decorations.underline=r,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,r))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let r=0===e.start?0:e.start+1+this._bufferService.buffer.ydisp,s=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=r&&this._currentLink.link.range.end.y<=s&&(this._clearCurrentLink(r,s),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,r,s){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(r,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),r.hover&&r.hover(s,r.text)}_fireUnderlineEvent(e,r){let s=e.range,n=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(s.start.x-1,s.start.y-n-1,s.end.x,s.end.y-n-1,void 0);(r?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,r,s){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(r,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),r.leave&&r.leave(s,r.text)}_linkAtPosition(e,r){let s=e.range.start.y*this._bufferService.cols+e.range.start.x,n=e.range.end.y*this._bufferService.cols+e.range.end.x,i=r.y*this._bufferService.cols+r.x;return s<=i&&i<=n}_positionFromMouseEvent(e,r,s){let n=s.getCoords(e,r,this._bufferService.cols,this._bufferService.rows);if(n)return{x:n[0],y:n[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,r,s,n,i){return{x1:e,y1:r,x2:s,y2:n,cols:this._bufferService.cols,fg:i}}};_F=pd([pu(1,p$),pu(2,pW),pu(3,pE),pu(4,pK)],_F);var _P=class extends _j{constructor(e={}){super(e),this._linkifier=this._register(new p8),this.browser=xY,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new p8),this._onCursorMove=this._register(new mC),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new mC),this.onKey=this._onKey.event,this._onRender=this._register(new mC),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new mC),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new mC),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new mC),this.onBell=this._onBell.event,this._onFocus=this._register(new mC),this._onBlur=this._register(new mC),this._onA11yCharEmitter=this._register(new mC),this._onA11yTabEmitter=this._register(new mC),this._onWillOpen=this._register(new mC),this._setup(),this._decorationService=this._instantiationService.createInstance(_R),this._instantiationService.setService(pB,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(xU),this._instantiationService.setService(pK,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(pL)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(mv.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(mv.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(mv.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(mv.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(p3(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let r of e){let e,s="";switch(r.index){case 256:e="foreground",s="10";break;case 257:e="background",s="11";break;case 258:e="cursor",s="12";break;default:e="ansi",s="4;"+r.index}switch(r.type){case 0:let n=vQ.toColorRGB("ansi"===e?this._themeService.colors.ansi[r.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${xi.ESC}]${s};${function(e,r=16){let[s,n,i]=e;return`rgb:${_p(s,r)}/${_p(n,r)}/${_p(i,r)}`}(n)}${xo.ST}`);break;case 1:if("ansi"===e)this._themeService.modifyColors(e=>e.ansi[r.index]=xl.toColor(...r.color));else{let s=e;this._themeService.modifyColors(e=>e[s]=xl.toColor(...r.color))}break;case 2:this._themeService.restoreColor(r.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(_M,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(xi.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(xi.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,r=this.buffer.lines.get(e);if(!r)return;let s=Math.min(this.buffer.x,this.cols-1),n=this._renderService.dimensions.css.cell.height,i=r.getWidth(s),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,l=s*this._renderService.dimensions.css.cell.width;this.textarea.style.left=l+"px",this.textarea.style.top=o+"px",this.textarea.style.width=a+"px",this.textarea.style.height=n+"px",this.textarea.style.lineHeight=n+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(gD(this.element,"copy",e=>{var r;this.hasSelection()&&(r=this._selectionService,e.clipboardData&&e.clipboardData.setData("text/plain",r.selectionText),e.preventDefault())}));let e=e=>{var r,s,n;return r=this.textarea,s=this.coreService,n=this.optionsService,void(e.stopPropagation(),e.clipboardData&&pp(e.clipboardData.getData("text/plain"),r,s,n))};this._register(gD(this.textarea,"paste",e)),this._register(gD(this.element,"paste",e)),x0?this._register(gD(this.element,"mousedown",e=>{2===e.button&&pg(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(gD(this.element,"contextmenu",e=>{pg(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),x8&&this._register(gD(this.element,"auxclick",e=>{1===e.button&&pm(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(gD(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(gD(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(gD(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(gD(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(gD(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(gD(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(gD(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let r=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),r.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(gD(this.screenElement,"mousemove",e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),r.appendChild(this.screenElement);let s=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",ph),x9||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>s.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(xW,this.textarea,e.ownerDocument.defaultView??window,this._document??"u">typeof window?window.document:null)),this._instantiationService.setService(pO,this._coreBrowserService),this._register(gD(this.textarea,"focus",e=>this._handleTextAreaFocus(e))),this._register(gD(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(xL,this._document,this._helperContainer),this._instantiationService.setService(pz,this._charSizeService),this._themeService=this._instantiationService.createInstance(vS),this._instantiationService.setService(pq,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(xj),this._instantiationService.setService(pU,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(vi,this.rows,this.screenElement)),this._instantiationService.setService(pW,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(g9,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(xK),this._instantiationService.setService(p$,this._mouseService);let n=this._linkifier.value=this._register(this._instantiationService.createInstance(_F,this.screenElement));this.element.appendChild(r);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(g2,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(vm,this.element,this.screenElement,n)),this._instantiationService.setService(pH,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(mv.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(g5,this.screenElement)),this._register(gD(this.element,"mousedown",e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(_M,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(g8,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(g8,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(xB,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,r=this.element;function s(r){let s,n,i=e._mouseService.getMouseReportCoords(r,e.screenElement);if(!i)return!1;switch(r.overrideType||r.type){case"mousemove":n=32,void 0===r.buttons?(s=3,void 0!==r.button&&(s=r.button<3?r.button:3)):s=1&r.buttons?0:4&r.buttons?1:2&r.buttons?2:3;break;case"mouseup":n=0,s=r.button<3?r.button:3;break;case"mousedown":n=1,s=r.button<3?r.button:3;break;case"wheel":if(e._customWheelEventHandler&&!1===e._customWheelEventHandler(r))return!1;let a=r.deltaY;if(0===a||0===e.coreMouseService.consumeWheelEvent(r,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr))return!1;n=a<0?0:1,s=4;break;default:return!1}return void 0!==n&&void 0!==s&&!(s>4)&&e.coreMouseService.triggerMouseEvent({col:i.col,row:i.row,x:i.x,y:i.y,button:s,action:n,ctrl:r.ctrlKey,alt:r.altKey,shift:r.shiftKey})}let n={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i=e=>(s(e),e.buttons||(this._document.removeEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.removeEventListener("mousemove",n.mousedrag)),this.cancel(e)),a=e=>(s(e),this.cancel(e,!0)),o=e=>{e.buttons&&s(e)},l=e=>{e.buttons||s(e)};this._register(this.coreMouseService.onProtocolChange(e=>{e?("debug"===this.optionsService.rawOptions.logLevel&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(e)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&e?n.mousemove||(r.addEventListener("mousemove",l),n.mousemove=l):(r.removeEventListener("mousemove",n.mousemove),n.mousemove=null),16&e?n.wheel||(r.addEventListener("wheel",a,{passive:!1}),n.wheel=a):(r.removeEventListener("wheel",n.wheel),n.wheel=null),2&e?n.mouseup||(n.mouseup=i):(this._document.removeEventListener("mouseup",n.mouseup),n.mouseup=null),4&e?n.mousedrag||(n.mousedrag=o):(this._document.removeEventListener("mousemove",n.mousedrag),n.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(gD(r,"mousedown",e=>{if(e.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(e)))return s(e),n.mouseup&&this._document.addEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.addEventListener("mousemove",n.mousedrag),this.cancel(e)})),this._register(gD(r,"wheel",r=>{if(!n.wheel){if(this._customWheelEventHandler&&!1===this._customWheelEventHandler(r))return!1;if(!this.buffer.hasScrollback){if(0===r.deltaY)return!1;if(0===e.coreMouseService.consumeWheelEvent(r,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr))return this.cancel(r,!0);let s=xi.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(r.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(s,!0),this.cancel(r,!0)}}},{passive:!1}))}refresh(e,r){this._renderService?.refreshRows(e,r)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,r){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,r),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let r=e-this._bufferService.buffer.ydisp;0!==r&&this.scrollLines(r)}paste(e){pp(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error("Terminal must be opened first");let r=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),r}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(e,r,s){this._selectionService.setSelection(e,r,s)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,r){this._selectionService?.selectLines(e,r)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;let r=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!r&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;r||"Dead"!==e.key&&"AltGraph"!==e.key||(this._unprocessedDeadKey=!0);let s=function(e,r,s,n){let i={type:0,cancel:!1,key:void 0},a=!!e.shiftKey|2*!!e.altKey|4*!!e.ctrlKey|8*!!e.metaKey;switch(e.keyCode){case 0:"UIKeyInputUpArrow"===e.key?r?i.key=xi.ESC+"OA":i.key=xi.ESC+"[A":"UIKeyInputLeftArrow"===e.key?r?i.key=xi.ESC+"OD":i.key=xi.ESC+"[D":"UIKeyInputRightArrow"===e.key?r?i.key=xi.ESC+"OC":i.key=xi.ESC+"[C":"UIKeyInputDownArrow"===e.key&&(r?i.key=xi.ESC+"OB":i.key=xi.ESC+"[B");break;case 8:i.key=e.ctrlKey?"\b":xi.DEL,e.altKey&&(i.key=xi.ESC+i.key);break;case 9:if(e.shiftKey){i.key=xi.ESC+"[Z";break}i.key=xi.HT,i.cancel=!0;break;case 13:i.key=e.altKey?xi.ESC+xi.CR:xi.CR,i.cancel=!0;break;case 27:i.key=xi.ESC,e.altKey&&(i.key=xi.ESC+xi.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;a?i.key=xi.ESC+"[1;"+(a+1)+"D":r?i.key=xi.ESC+"OD":i.key=xi.ESC+"[D";break;case 39:if(e.metaKey)break;a?i.key=xi.ESC+"[1;"+(a+1)+"C":r?i.key=xi.ESC+"OC":i.key=xi.ESC+"[C";break;case 38:if(e.metaKey)break;a?i.key=xi.ESC+"[1;"+(a+1)+"A":r?i.key=xi.ESC+"OA":i.key=xi.ESC+"[A";break;case 40:if(e.metaKey)break;a?i.key=xi.ESC+"[1;"+(a+1)+"B":r?i.key=xi.ESC+"OB":i.key=xi.ESC+"[B";break;case 45:e.shiftKey||e.ctrlKey||(i.key=xi.ESC+"[2~");break;case 46:a?i.key=xi.ESC+"[3;"+(a+1)+"~":i.key=xi.ESC+"[3~";break;case 36:a?i.key=xi.ESC+"[1;"+(a+1)+"H":r?i.key=xi.ESC+"OH":i.key=xi.ESC+"[H";break;case 35:a?i.key=xi.ESC+"[1;"+(a+1)+"F":r?i.key=xi.ESC+"OF":i.key=xi.ESC+"[F";break;case 33:e.shiftKey?i.type=2:e.ctrlKey?i.key=xi.ESC+"[5;"+(a+1)+"~":i.key=xi.ESC+"[5~";break;case 34:e.shiftKey?i.type=3:e.ctrlKey?i.key=xi.ESC+"[6;"+(a+1)+"~":i.key=xi.ESC+"[6~";break;case 112:a?i.key=xi.ESC+"[1;"+(a+1)+"P":i.key=xi.ESC+"OP";break;case 113:a?i.key=xi.ESC+"[1;"+(a+1)+"Q":i.key=xi.ESC+"OQ";break;case 114:a?i.key=xi.ESC+"[1;"+(a+1)+"R":i.key=xi.ESC+"OR";break;case 115:a?i.key=xi.ESC+"[1;"+(a+1)+"S":i.key=xi.ESC+"OS";break;case 116:a?i.key=xi.ESC+"[15;"+(a+1)+"~":i.key=xi.ESC+"[15~";break;case 117:a?i.key=xi.ESC+"[17;"+(a+1)+"~":i.key=xi.ESC+"[17~";break;case 118:a?i.key=xi.ESC+"[18;"+(a+1)+"~":i.key=xi.ESC+"[18~";break;case 119:a?i.key=xi.ESC+"[19;"+(a+1)+"~":i.key=xi.ESC+"[19~";break;case 120:a?i.key=xi.ESC+"[20;"+(a+1)+"~":i.key=xi.ESC+"[20~";break;case 121:a?i.key=xi.ESC+"[21;"+(a+1)+"~":i.key=xi.ESC+"[21~";break;case 122:a?i.key=xi.ESC+"[23;"+(a+1)+"~":i.key=xi.ESC+"[23~";break;case 123:a?i.key=xi.ESC+"[24;"+(a+1)+"~":i.key=xi.ESC+"[24~";break;default:if(!e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)if((!s||n)&&e.altKey&&!e.metaKey){let r=_C[e.keyCode]?.[+!!e.shiftKey];if(r)i.key=xi.ESC+r;else if(e.keyCode>=65&&e.keyCode<=90){let r=String.fromCharCode(e.ctrlKey?e.keyCode-64:e.keyCode+32);e.shiftKey&&(r=r.toUpperCase()),i.key=xi.ESC+r}else if(32===e.keyCode)i.key=xi.ESC+(e.ctrlKey?xi.NUL:" ");else if("Dead"===e.key&&e.code.startsWith("Key")){let r=e.code.slice(3,4);e.shiftKey||(r=r.toLowerCase()),i.key=xi.ESC+r,i.cancel=!0}}else!s||e.altKey||e.ctrlKey||e.shiftKey||!e.metaKey?!e.key||e.ctrlKey||e.altKey||e.metaKey||!(e.keyCode>=48)||1!==e.key.length?e.key&&e.ctrlKey&&("_"===e.key&&(i.key=xi.US),"@"===e.key&&(i.key=xi.NUL)):i.key=e.key:65===e.keyCode&&(i.type=1);else e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):32===e.keyCode?i.key=xi.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):56===e.keyCode?i.key=xi.DEL:219===e.keyCode?i.key=xi.ESC:220===e.keyCode?i.key=xi.FS:221===e.keyCode&&(i.key=xi.GS)}return i}(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),3===s.type||2===s.type){let r=this.rows-1;return this.scrollLines(2===s.type?-r:r),this.cancel(e,!0)}return 1===s.type&&this.selectAll(),!!(this._isThirdLevelShift(this.browser,e)||(s.cancel&&this.cancel(e,!0),!s.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&1===e.key.length&&e.key.charCodeAt(0)>=65&&90>=e.key.charCodeAt(0))||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):((s.key===xi.ETX||s.key===xi.CR)&&(this.textarea.value=""),this._onKey.fire({key:s.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(s.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)?this.cancel(e,!0):void(this._keyDownHandled=!0))}_isThirdLevelShift(e,r){let s=e.isMac&&!this.options.macOptionIsMeta&&r.altKey&&!r.ctrlKey&&!r.metaKey||e.isWindows&&r.altKey&&r.ctrlKey&&!r.metaKey||e.isWindows&&r.getModifierState("AltGraph");return"keypress"===r.type?s:s&&(!r.keyCode||r.keyCode>47)}_keyUp(e){var r;this._keyDownSeen=!1,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e)||(16===(r=e).keyCode||17===r.keyCode||18===r.keyCode||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let r;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(this.cancel(e),e.charCode)r=e.charCode;else if(null===e.which||void 0===e.which)r=e.keyCode;else{if(0===e.which||0===e.charCode)return!1;r=e.which}return!!r&&(!e.altKey&&!e.ctrlKey&&!e.metaKey||!!this._isThirdLevelShift(this.browser,e))&&(r=String.fromCharCode(r),this._onKey.fire({key:r,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(r,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&"insertText"===e.inputType&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let r=e.data;return this.coreService.triggerDataEvent(r,!0),this.cancel(e),!0}return!1}resize(e,r){if(e===this.cols&&r===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,r)}_afterResize(e,r){this._charSizeService?.measure()}clear(){if(0!==this.buffer.ybase||0!==this.buffer.y){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(vR));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains("focus")?this.coreService.triggerDataEvent(xi.ESC+"[I"):this.coreService.triggerDataEvent(xi.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let r=this._renderService.dimensions.css.canvas.width.toFixed(0),s=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${xi.ESC}[4;${s};${r}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),i=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${xi.ESC}[6;${i};${n}t`)}}cancel(e,r){if(!(!this.options.cancelEvents&&!r))return e.preventDefault(),e.stopPropagation(),!1}},_I=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,r){let s={instance:r,dispose:r.dispose,isDisposed:!1};this._addons.push(s),r.dispose=()=>this._wrappedAddonDispose(s),r.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let r=-1;for(let s=0;s<this._addons.length;s++)if(this._addons[s]===e){r=s;break}if(-1===r)throw Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(r,1)}},_B=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,r){if(!(e<0||e>=this._line.length))return r?(this._line.loadCell(e,r),r):this._line.loadCell(e,new pS)}translateToString(e,r,s){return this._line.translateToString(e,r,s)}},_L=class{constructor(e,r){this._buffer=e,this.type=r}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let r=this._buffer.lines.get(e);if(r)return new _B(r)}getNullCell(){return new pS}},_z=class extends p7{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new mC),this.onBufferChange=this._onBufferChange.event,this._normal=new _L(this._core.buffers.normal,"normal"),this._alternate=new _L(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},_O=class{constructor(e){this._core=e}registerCsiHandler(e,r){return this._core.registerCsiHandler(e,e=>r(e.toArray()))}addCsiHandler(e,r){return this.registerCsiHandler(e,r)}registerDcsHandler(e,r){return this._core.registerDcsHandler(e,(e,s)=>r(e,s.toArray()))}addDcsHandler(e,r){return this.registerDcsHandler(e,r)}registerEscHandler(e,r){return this._core.registerEscHandler(e,r)}addEscHandler(e,r){return this.registerEscHandler(e,r)}registerOscHandler(e,r){return this._core.registerOscHandler(e,r)}addOscHandler(e,r){return this.registerOscHandler(e,r)}},_$=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},_W=["cols","rows"],_H=0,_U=class extends p7{constructor(e){super(),this._core=this._register(new _P(e)),this._addonManager=this._register(new _I),this._publicOptions={...this._core.options};let r=e=>this._core.options[e],s=(e,r)=>{this._checkReadonlyOptions(e),this._core.options[e]=r};for(let e in this._core.options){let n={get:r.bind(this,e),set:s.bind(this,e)};Object.defineProperty(this._publicOptions,e,n)}}_checkReadonlyOptions(e){if(_W.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new _O(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new _$(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new _z(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,r="none";switch(this._core.coreMouseService.activeProtocol){case"X10":r="x10";break;case"VT200":r="vt200";break;case"DRAG":r="drag";break;case"ANY":r="any"}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:r,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let r in e)this._publicOptions[r]=e[r]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,r=!0){this._core.input(e,r)}resize(e,r){this._verifyIntegers(e,r),this._core.resize(e,r)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,r,s){this._verifyIntegers(e,r,s),this._core.select(e,r,s)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,r){this._verifyIntegers(e,r),this._core.selectLines(e,r)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,r){this._core.write(e,r)}writeln(e,r){this._core.write(e),this._core.write(`\r
28
- `,r)}paste(e){this._core.paste(e)}refresh(e,r){this._verifyIntegers(e,r),this._core.refresh(e,r)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return ph},set promptLabel(t){ph=t},get tooMuchOutput(){return pf},set tooMuchOutput(t){pf=t}}}_verifyIntegers(...e){for(_H of e)if(_H===1/0||isNaN(_H)||_H%1!=0)throw Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(_H of e)if(_H&&(_H===1/0||isNaN(_H)||_H%1!=0||_H<0))throw Error("This API only accepts positive integers")}},_q=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let r=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(r._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(0===e.css.cell.width||0===e.css.cell.height)return;let r=0===this._terminal.options.scrollback?0:this._terminal.options.overviewRuler?.width||14,s=window.getComputedStyle(this._terminal.element.parentElement),n=parseInt(s.getPropertyValue("height")),i=Math.max(0,parseInt(s.getPropertyValue("width"))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue("padding-top")),bottom:parseInt(a.getPropertyValue("padding-bottom")),right:parseInt(a.getPropertyValue("padding-right")),left:parseInt(a.getPropertyValue("padding-left"))},l=o.top+o.bottom;return{cols:Math.max(2,Math.floor((i-(o.right+o.left)-r)/e.css.cell.width)),rows:Math.max(1,Math.floor((n-l)/e.css.cell.height))}}},_K=class{constructor(e,r,s,n={}){this._terminal=e,this._regex=r,this._handler=s,this._options=n}provideLinks(e,r){let s=_V.computeLink(e,this._regex,this._terminal,this._handler);r(this._addCallbacks(s))}_addCallbacks(e){return e.map(e=>(e.leave=this._options.leave,e.hover=(r,s)=>{if(this._options.hover){let{range:n}=e;this._options.hover(r,s,n)}},e))}},_V=class e{static computeLink(r,s,n,i){let a=RegExp(s.source,(s.flags||"")+"g"),[o,l]=e._getWindowedLineStrings(r-1,n),c=o.join(""),d,u=[];for(;d=a.exec(c);){let r=d[0];if(!function(e){try{let r=new URL(e),s=r.password&&r.username?`${r.protocol}//${r.username}:${r.password}@${r.host}`:r.username?`${r.protocol}//${r.username}@${r.host}`:`${r.protocol}//${r.host}`;return e.toLocaleLowerCase().startsWith(s.toLocaleLowerCase())}catch{return!1}}(r))continue;let[s,a]=e._mapStrIdx(n,l,0,d.index),[o,c]=e._mapStrIdx(n,s,a,r.length);if(-1===s||-1===a||-1===o||-1===c)continue;let h={start:{x:a+1,y:s+1},end:{x:c,y:o+1}};u.push({range:h,text:r,activate:i})}return u}static _getWindowedLineStrings(e,r){let s,n=e,i=e,a=0,o="",l=[];if(s=r.buffer.active.getLine(e)){let e=s.translateToString(!0);if(s.isWrapped&&" "!==e[0]){for(a=0;(s=r.buffer.active.getLine(--n))&&a<2048&&(a+=(o=s.translateToString(!0)).length,l.push(o),!(!s.isWrapped||-1!==o.indexOf(" "))););l.reverse()}for(l.push(e),a=0;(s=r.buffer.active.getLine(++i))&&s.isWrapped&&a<2048&&(a+=(o=s.translateToString(!0)).length,l.push(o),-1===o.indexOf(" ")););}return[l,n]}static _mapStrIdx(e,r,s,n){let i=e.buffer.active,a=i.getNullCell(),o=s;for(;n;){let e=i.getLine(r);if(!e)return[-1,-1];for(let s=o;s<e.length;++s){e.getCell(s,a);let o=a.getChars();if(a.getWidth()&&(n-=o.length||1,s===e.length-1&&""===o)){let e=i.getLine(r+1);e&&e.isWrapped&&(e.getCell(0,a),2===a.getWidth()&&(n+=1))}if(n<0)return[r,s]}r++,o=0}return[r,o]}},_Y=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function _G(e,r){let s=window.open();if(s){try{s.opener=null}catch{}s.location.href=r}else console.warn("Opening link blocked as opener could not be cleared")}var _X=class{constructor(e=_G,r={}){this._handler=e,this._options=r}activate(e){this._terminal=e;let r=this._options,s=r.urlRegex||_Y;this._linkProvider=this._terminal.registerLinkProvider(new _K(this._terminal,s,this._handler,r))}dispose(){this._linkProvider?.dispose()}};let _J=(0,ew.default)("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);var _Z=e.i(754219);let _Q=[{id:"agent",label:"Agent",code:"KeyA"},{id:"executors",label:"Executors",code:"KeyE"},{id:"diff",label:"Diff",code:"KeyD"},{id:"terminal",label:"Terminal",code:"KeyT"},{id:"preview",label:"Browser",code:"KeyB"},{id:"files",label:"Files",code:"KeyF"}],_0=Object.fromEntries(_Q.map(e=>[e.code,e.id])),_1=()=>"undefined"!=typeof navigator&&/Mac|iPhone|iPad/.test(navigator.platform);function _2(e){return(_1()?e.ctrlKey&&e.shiftKey&&!e.altKey&&!e.metaKey:e.ctrlKey&&e.altKey&&!e.shiftKey&&!e.metaKey)?_0[e.code]??null:null}let _5=(e,r)=>`${e?"⌃⇧":"Ctrl+Alt+"}${r.slice(3)}`,_3=/\x1B(?:\][^\x07]*(?:\x07|\x1B\\)|[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;function _4({logs:e,isPty:r,className:s,onInput:n,onResize:i,muteInput:a,processId:o,executorId:l,target:c,status:d,exitCode:u}){let h=(0,$.useRef)(null),f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=(0,$.useRef)(0),g=(0,$.useRef)(0),x=(0,$.useRef)(a);x.current!==a&&console.log(`[ExecutorOutput] muteInput changed: ${x.current} → ${a}`),x.current=a;let{settings:v}=(0,fT.useTerminalSettings)(),_=(0,$.useRef)(v),[y,b]=(0,$.useState)(!1),w=(0,$.useRef)(0),S=(0,$.useRef)(e);S.current=e;let j=async()=>{if(!y){w.current=S.current.length,b(!0);return}let e=S.current,r=Math.min(w.current,e.length),s=e.slice(r).map(e=>"stdout"===e.type||"stderr"===e.type||"pty"===e.type?e.data:"").join("");b(!1);let n=s.replace(_3,"");if(!n)return void _Z.toast.info("Capture stopped — no output to copy");try{await navigator.clipboard.writeText(n),_Z.toast.success("Copied captured output to clipboard")}catch{_Z.toast.error("Failed to copy to clipboard")}};(0,$.useEffect)(()=>{if(!h.current||f.current)return;let e=_.current,s=new _U({cursorBlink:r,cursorStyle:r?"block":"underline",disableStdin:!r,convertEol:!0,fontSize:e.fontSize,fontFamily:e.fontFamily,scrollback:e.scrollback,theme:{background:"#09090b",foreground:"#fafafa",cursor:r?"#fafafa":"#09090b",cursorAccent:"#09090b",selectionBackground:"#3f3f46",black:"#09090b",red:"#f87171",green:"#4ade80",yellow:"#facc15",blue:"#60a5fa",magenta:"#c084fc",cyan:"#22d3ee",white:"#fafafa",brightBlack:"#71717a",brightRed:"#fca5a5",brightGreen:"#86efac",brightYellow:"#fde047",brightBlue:"#93c5fd",brightMagenta:"#d8b4fe",brightCyan:"#67e8f9",brightWhite:"#ffffff"},allowProposedApi:!0}),a=new _q,o=new _X;return s.loadAddon(a),s.loadAddon(o),s.attachCustomKeyEventHandler(e=>null===_2(e)),s.open(h.current),setTimeout(()=>{try{let e=h.current;if(!e||0===e.clientWidth||0===e.clientHeight)return;a.fit(),r&&i?.(s.cols,s.rows)}catch{}},0),f.current=s,p.current=a,r&&n&&s.onData(e=>{x.current||0!==g.current||n(e)}),r&&i&&s.onResize(({cols:e,rows:r})=>{i(e,r)}),()=>{s.dispose(),f.current=null,p.current=null,m.current=0,g.current=0}},[r,n,i]),(0,$.useEffect)(()=>{if(!f.current)return;e.length<m.current&&(f.current.reset(),m.current=0);let r="",s="";for(let n=m.current;n<e.length;n++){let i=e[n];("pty"===i.type||"stdout"===i.type||"stderr"===i.type)&&(i.historical?r+=i.data:s+=i.data)}if(m.current=e.length,r){g.current++;try{f.current.write(r,()=>{g.current=Math.max(0,g.current-1)})}catch(e){g.current=Math.max(0,g.current-1),console.error("[ExecutorOutput] terminal write failed",e)}}if(s)try{f.current.write(s)}catch(e){console.error("[ExecutorOutput] terminal write failed",e)}},[e]),(0,$.useEffect)(()=>{let e=f.current;if(e){e.options.fontSize=v.fontSize,e.options.fontFamily=v.fontFamily,e.options.scrollback=v.scrollback;try{p.current?.fit()}catch{}}},[v.fontSize,v.fontFamily,v.scrollback]),(0,$.useEffect)(()=>{if(!h.current||!p.current)return;let e=new ResizeObserver(()=>{try{let e=h.current;if(!e||0===e.clientWidth||0===e.clientHeight)return;p.current?.fit()}catch{}});return e.observe(h.current),()=>{e.disconnect()}},[]);let C="closed"===d&&null!==u?`closed \xb7 exit ${u}`:d??null;return(0,O.jsxs)("div",{className:(0,ey.cn)("relative h-[300px] rounded-md border bg-zinc-950 overflow-hidden",s),children:[(0,O.jsx)("div",{ref:h,className:"h-full w-full"}),(0,O.jsxs)("div",{className:"absolute top-2 right-3 z-10 flex items-center gap-1.5",children:[(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)("button",{type:"button",title:"Process info","aria-label":"Show process info",className:(0,ey.cn)("flex h-6 w-6 items-center justify-center rounded","bg-zinc-900/70 backdrop-blur-sm border border-zinc-700/60","text-zinc-400 hover:text-zinc-100 hover:border-zinc-500 transition-colors"),children:(0,O.jsx)(_J,{className:"h-3 w-3"})})}),(0,O.jsxs)(a7,{align:"end",className:"w-72",children:[(0,O.jsx)(or,{className:"text-xs text-muted-foreground",children:"Process info"}),[{label:"Process",value:o??null},{label:"Executor",value:l??null},{label:"Target",value:c??null},{label:"Status",value:C}].map(e=>(0,O.jsxs)(a8,{disabled:!e.value,onSelect:r=>{var s,n;r.preventDefault(),s=e.label,(n=e.value)&&(navigator.clipboard.writeText(n),_Z.toast.success(`${s} copied`))},className:"flex items-center justify-between gap-3 font-mono text-xs",children:[(0,O.jsx)("span",{className:"shrink-0 text-muted-foreground",children:e.label}),(0,O.jsxs)("span",{className:"flex min-w-0 items-center gap-1.5",children:[(0,O.jsx)("span",{className:"truncate",children:e.value??"—"}),e.value&&(0,O.jsx)(fq.Copy,{className:"h-3 w-3 shrink-0 opacity-60"})]})]},e.label))]})]}),(0,O.jsx)("button",{type:"button",onClick:j,title:y?"Stop capture & copy to clipboard":"Start capturing output","aria-label":y?"Stop capture and copy":"Start capturing output",className:(0,ey.cn)("flex h-6 w-6 items-center justify-center rounded","bg-zinc-900/70 backdrop-blur-sm border border-zinc-700/60","text-zinc-400 hover:text-zinc-100 hover:border-zinc-500 transition-colors",y&&"text-red-400 border-red-500/70 hover:text-red-300"),children:y?(0,O.jsx)(lJ,{className:"h-3 w-3 fill-current"}):(0,O.jsx)(sZ,{className:"h-3 w-3"})})]})]})}let _6=[{name:"Dev Server",command:"pnpm dev",executor_type:"command",pty:!0,description:"Start the development server with hot reload"},{name:"Build",command:"pnpm build",executor_type:"command",pty:!0,description:"Build the project for production"},{name:"Lint",command:"pnpm lint",executor_type:"command",pty:!0,description:"Run the linter to check code quality"},{name:"Type Check",command:"npx tsc --noEmit",executor_type:"command",pty:!0,description:"Run TypeScript type checking without emitting files"},{name:"Test",command:"pnpm test",executor_type:"command",pty:!0,description:"Run the test suite"},{name:"Rebase on and merge into main",command:"Our goal is to sync the current local branch with the local branch/worktree `main`. The two branches may have diverged.\n\nPlease do the following in order. Only proceed to the next step if the previous step succeeds:\n\n1. Rebase the current local branch onto the local branch `main`, and resolve any conflicts if needed.\n2. If, after the rebase, `main` does not yet contain the current branch's commits, switch to the `main` branch/worktree and merge the current branch into `main` using `git merge`. Do not use `git branch -f`.\n3. If the current branch is already fully contained in `main`, and `main` has newer commits, update the current branch so it includes the latest commits from `main`.\n4. Push both the current local branch and the local branch `main` to the remote.",executor_type:"prompt",pty:!1,description:"Rebase current branch onto main, merge into main, and push both branches"},{name:"Reset to main",command:"git reset --hard main",executor_type:"command",pty:!0,description:"Hard reset the current branch to match main"},{name:"Push to remote",command:"git push --force-with-lease",executor_type:"command",pty:!0,description:"Force push to remote with lease safety check"},{name:"Git commit",command:"Inspect the modified and untracked and deleted files in the current repository, generate an appropriate commit message, and commit all relevant files.\n\nCommit message rules:\n- Use Conventional Commits format (feat:, fix:, chore:, refactor:, docs:, test:, ci:, build:, perf:, style:, etc.)\n- Choose the type that best matches the main purpose of the changes\n- Make the message specific to the actual changes\n- Keep it within 50 characters if possible\n- Use lowercase\n- Do not end with a period\n- Do not wrap the message in quotes, backticks, or markdown\n\nCommit requirements:\n- Include all relevant modified and untracked files\n- Do not include unrelated files\n- If there are no meaningful changes to commit, do not create a commit\n\nWhen finished, output only the final commit message.",executor_type:"prompt",pty:!1,description:"Inspect changes, generate a conventional commit message, and commit"},{name:"Tag and push",command:"Find the latest SemVer tag in the repository, increase the patch number by 1, create the new tag from the current commit, and push it to origin.",executor_type:"prompt",pty:!1,description:"Bump the patch version tag and push it to origin"}];function _7({open:e,onOpenChange:r,executor:s,onSubmit:n}){let[i,a]=(0,$.useState)(s?.name??""),[o,l]=(0,$.useState)(s?.executor_type??"command"),[c,d]=(0,$.useState)(s?.prompt_provider??"claude"),[u,h]=(0,$.useState)(s?.command??""),[f,p]=(0,$.useState)(s?.cwd??""),[m,g]=(0,$.useState)(s?.pty??!0),[x,v]=(0,$.useState)(!1),[_,y]=(0,$.useState)(!1),[b,w]=(0,$.useState)(null),[S,j]=(0,$.useState)(null),[C,k]=(0,$.useState)(""),N=!!s;(0,$.useEffect)(()=>{e&&(y(!1),w(null),j(null),k(""),s&&(a(s.name),l(s.executor_type??"command"),d(s.prompt_provider??"claude"),h(s.command),p(s.cwd??""),g(s.pty)))},[e]);let E=async e=>{if(e.preventDefault(),i.trim()&&u.trim()){v(!0);try{await n({name:i.trim(),command:u.trim(),executor_type:o,prompt_provider:"prompt"===o?c:null,cwd:f.trim()||void 0,pty:"prompt"===o||m}),r(!1),N||(a(""),l("command"),d("claude"),h(""),p(""),g(!0))}finally{v(!1)}}};return(0,O.jsx)(t8,{open:e,onOpenChange:r,children:(0,O.jsxs)(rr,{children:[(0,O.jsx)(rs,{children:(0,O.jsxs)("div",{className:"flex items-center justify-between pr-6",children:[(0,O.jsx)(ri,{children:_?"Select Preset":N?"Edit Executor":"Add Executor"}),!N&&!_&&(0,O.jsx)("button",{type:"button",className:"text-sm text-muted-foreground hover:text-foreground transition-colors",onClick:()=>y(!0),children:"Select from presets"})]})}),(0,O.jsxs)("div",{className:"h-[420px] flex flex-col",children:[!_&&(0,O.jsxs)("form",{onSubmit:E,className:"space-y-4 flex-1 flex flex-col",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Name"}),(0,O.jsx)(ro,{placeholder:"e.g., Dev Server",value:i,onChange:e=>a(e.target.value),required:!0})]}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Type"}),(0,O.jsxs)("div",{className:"flex rounded-md border border-input overflow-hidden",children:[(0,O.jsx)("button",{type:"button",className:(0,ey.cn)("flex-1 px-3 py-1.5 text-sm font-medium transition-colors","command"===o?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),onClick:()=>l("command"),children:"Command"}),(0,O.jsx)("button",{type:"button",className:(0,ey.cn)("flex-1 px-3 py-1.5 text-sm font-medium transition-colors border-l border-input","prompt"===o?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),onClick:()=>l("prompt"),children:"Prompt"})]})]}),"prompt"===o&&(0,O.jsxs)("div",{className:"flex gap-3",children:[(0,O.jsxs)("div",{className:"w-[140px] shrink-0 space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Provider"}),(0,O.jsxs)(hw,{value:c,onValueChange:e=>d(e),children:[(0,O.jsx)(hj,{className:"w-full",children:(0,O.jsx)(hS,{})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"claude",children:"Claude"}),(0,O.jsx)(hk,{value:"codex",children:"Codex"})]})]})]}),(0,O.jsxs)("div",{className:"flex-1 space-y-2",children:[(0,O.jsxs)("label",{className:"text-sm font-medium",children:["Working Directory"," ",(0,O.jsx)("span",{className:"text-muted-foreground",children:"(optional)"})]}),(0,O.jsx)(ro,{placeholder:"Relative to worktree root",value:f,onChange:e=>p(e.target.value)})]})]}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"prompt"===o?"Prompt":"Command"}),"prompt"===o?(0,O.jsx)("textarea",{className:"flex min-h-[90px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 resize-y",placeholder:"e.g., Review the code and suggest improvements",value:u,onChange:e=>h(e.target.value),required:!0}):(0,O.jsx)(ro,{placeholder:"e.g., npm run dev",value:u,onChange:e=>h(e.target.value),required:!0})]}),"command"===o&&(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsxs)("label",{className:"text-sm font-medium",children:["Working Directory"," ",(0,O.jsx)("span",{className:"text-muted-foreground",children:"(optional)"})]}),(0,O.jsx)(ro,{placeholder:"Relative to worktree root (leave empty for root)",value:f,onChange:e=>p(e.target.value)})]}),"command"===o&&(0,O.jsxs)("div",{className:"flex items-center justify-between",children:[(0,O.jsxs)("div",{className:"space-y-0.5",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Terminal Mode (PTY)"}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"Enable for interactive commands like top, vim, htop"})]}),(0,O.jsx)("button",{type:"button",role:"switch","aria-checked":m,onClick:()=>g(!m),className:(0,ey.cn)("relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",m?"bg-primary":"bg-input"),children:(0,O.jsx)("span",{className:(0,ey.cn)("pointer-events-none inline-block h-5 w-5 transform rounded-full bg-background shadow-lg ring-0 transition-transform",m?"translate-x-5":"translate-x-0")})})]}),(0,O.jsx)("div",{className:"flex-1"}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),(0,O.jsx)(W.Button,{type:"submit",disabled:x||!i.trim()||!u.trim(),children:x?"Saving...":N?"Save":"Add"})]})]}),_&&(0,O.jsxs)("div",{className:"space-y-4 flex-1 flex flex-col min-h-0",children:[(0,O.jsx)(ro,{placeholder:"Search presets...",value:C,onChange:e=>k(e.target.value),autoFocus:!0}),(0,O.jsx)("div",{className:"flex-1 overflow-y-auto min-h-0 space-y-1",children:_6.filter(e=>{if(!C.trim())return!0;let r=C.toLowerCase();return e.name.toLowerCase().includes(r)||e.command.toLowerCase().includes(r)||(e.description?.toLowerCase().includes(r)??!1)}).map(e=>{let r=b?.command===e.command,s=S===e.command;return(0,O.jsxs)("div",{className:"rounded-md overflow-hidden",children:[(0,O.jsxs)("button",{type:"button",className:(0,ey.cn)("w-full flex items-center gap-2 px-3 py-2 text-sm transition-colors",r?"bg-primary/10 text-primary":"hover:bg-muted"),onClick:()=>w(e),children:["command"===e.executor_type?(0,O.jsx)(ol,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):(0,O.jsx)(sD,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),(0,O.jsx)("span",{className:"font-medium flex-1 text-left",children:e.name}),(0,O.jsx)("button",{type:"button",className:"shrink-0 p-0.5 rounded hover:bg-muted-foreground/10 transition-colors",onClick:r=>{r.stopPropagation(),j(s?null:e.command)},children:s?(0,O.jsx)(ns,{className:"h-4 w-4 text-muted-foreground"}):(0,O.jsx)(a3,{className:"h-4 w-4 text-muted-foreground"})})]}),s&&(0,O.jsxs)("div",{className:(0,ey.cn)("px-3 pb-2 pt-1 text-xs text-muted-foreground space-y-1 border-t border-border/50",r?"bg-primary/5":"bg-muted/50"),children:[e.description&&(0,O.jsx)("p",{children:e.description}),(0,O.jsx)("pre",{className:"whitespace-pre-wrap break-all bg-muted/50 rounded px-2 py-1 font-mono",children:e.command}),(0,O.jsxs)("div",{className:"flex gap-3",children:[(0,O.jsxs)("span",{children:["Type: ",(0,O.jsx)("span",{className:"font-medium text-foreground/70",children:e.executor_type})]}),(0,O.jsxs)("span",{children:["PTY: ",(0,O.jsx)("span",{className:"font-medium text-foreground/70",children:e.pty?"on":"off"})]})]})]})]},e.command)})}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{type:"button",variant:"outline",onClick:()=>{y(!1),w(null),j(null)},children:"Cancel"}),(0,O.jsx)(W.Button,{type:"button",disabled:!b,onClick:()=>{b&&(a(b.name),h(b.command),l(b.executor_type),g(b.pty),y(!1),w(null),j(null))},children:"Select"})]})]})]})]})})}let _8={logs:[],status:"connecting",exitCode:null,isPty:!1,replayingHistory:!0},_9=(0,$.createContext)(null);function ye({projectId:e,children:r}){let s=(0,$.useRef)(new Map),n=(0,$.useRef)(new Map),i=(0,$.useRef)(new Set),a=(0,$.useRef)(null),o=(0,$.useRef)(0),l=(0,$.useRef)(null),c=(0,$.useCallback)(e=>{n.current.get(e)?.forEach(e=>e())},[]),d=(0,$.useCallback)((e,r)=>{let n=s.current.get(e)??_8;s.current.set(e,{...n,...r}),c(e)},[c]),u=(0,$.useCallback)(e=>{a.current?.readyState===WebSocket.OPEN&&a.current.send(JSON.stringify(e))},[]),h=(0,$.useCallback)(e=>{let{processId:r}=e;if("error"===e.type?e.message:"finished"===e.type?e.exitCode:"init"===e.type?e.isPty:"history_end"===e.type||e.data.length,"init"===e.type)d(r,{isPty:e.isPty,replayingHistory:!0,logs:[],status:"connected"});else if("history_end"===e.type)d(r,{replayingHistory:!1});else if("finished"===e.type)console.log(`[diag:remote-stop] ${new Date().toISOString()} mux received FINISHED processId=${r} exitCode=${e.exitCode} — will trigger markProcessFinished → button flips to Start`),d(r,{exitCode:e.exitCode,status:"closed"});else if("error"===e.type)console.log(`[diag:remote-stop] ${new Date().toISOString()} mux received ERROR processId=${r} — status=error, does NOT flip isRunning`),d(r,{status:"error"});else{let n=s.current.get(r)??_8,{processId:i,...a}=e;d(r,{logs:[...n.logs,{...a,historical:n.replayingHistory}]})}},[d]);(0,$.useEffect)(()=>{if(!e)return;let r=!1;o.current=0;let n=()=>{r||(0,rv.getFreshToken)().then(()=>{r||(()=>{if(r)return;let c=new WebSocket((0,rv.getWebSocketUrl)(`/api/executor-logs/stream?projectId=${encodeURIComponent(e)}`));a.current=c,c.onopen=()=>{if(!r)for(let e of(o.current=0,console.log("[diag:mux] WS open, resubscribing",[...i.current]),i.current))c.send(JSON.stringify({type:"subscribe",processId:e}))},c.onmessage=e=>{if(!r)try{h(JSON.parse(e.data))}catch(e){console.error("[ExecutorLogs] parse error:",e)}},c.onclose=()=>{if(a.current=null,console.log("[diag:mux] WS close, reconnectAttempt=",o.current,"cancelled=",r),r)return;let e=e=>{let r=s.current.get(e);return r?.status==="closed"||r?.status==="error"};if(o.current<8){let s=o.current++,a=Math.min(15e3,1e3*2**s),c=a+a*Math.random()*.25;for(let r of i.current)e(r)||d(r,{status:"connecting"});l.current=setTimeout(()=>{l.current=null,r||n()},c)}else for(let r of i.current)e(r)||d(r,{status:"error"})}})()})};return n(),()=>{r=!0,l.current&&clearTimeout(l.current),l.current=null,a.current?.close(),a.current=null}},[e,h,d]);let f=(0,$.useMemo)(()=>({subscribeProcess:e=>{i.current.has(e)||(i.current.add(e),s.current.set(e,{..._8}),c(e),console.log("[diag:mux] send subscribe",e,"(state reset to EMPTY)"),u({type:"subscribe",processId:e}))},unsubscribeProcess:e=>{i.current.has(e)&&(i.current.delete(e),console.log("[diag:mux] send unsubscribe",e),u({type:"unsubscribe",processId:e}))},sendInput:(e,r)=>u({type:"input",processId:e,data:r}),sendResize:(e,r,s)=>u({type:"resize",processId:e,cols:r,rows:s}),onProcessChange:(e,r)=>{let s=n.current.get(e);return s||(s=new Set,n.current.set(e,s)),s.add(r),()=>{s?.delete(r)}},getProcessState:e=>s.current.get(e)??_8}),[c,u]);return(0,O.jsx)(_9.Provider,{value:f,children:r})}let yt="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement;function yr(e){let r=Object.prototype.toString.call(e);return"[object Window]"===r||"[object global]"===r}function ys(e){return"nodeType"in e}function yn(e){var r,s;return e?yr(e)?e:ys(e)&&null!=(r=null==(s=e.ownerDocument)?void 0:s.defaultView)?r:window:window}function yi(e){let{Document:r}=yn(e);return e instanceof r}function ya(e){return!yr(e)&&e instanceof yn(e).HTMLElement}function yo(e){return e instanceof yn(e).SVGElement}function yl(e){return e?yr(e)?e.document:ys(e)?yi(e)?e:ya(e)||yo(e)?e.ownerDocument:document:document:document}let yc=yt?$.useLayoutEffect:$.useEffect;function yd(e){let r=(0,$.useRef)(e);return yc(()=>{r.current=e}),(0,$.useCallback)(function(){for(var e=arguments.length,s=Array(e),n=0;n<e;n++)s[n]=arguments[n];return null==r.current?void 0:r.current(...s)},[])}function yu(e,r){void 0===r&&(r=[e]);let s=(0,$.useRef)(e);return yc(()=>{s.current!==e&&(s.current=e)},r),s}function yh(e,r){let s=(0,$.useRef)();return(0,$.useMemo)(()=>{let r=e(s.current);return s.current=r,r},[...r])}function yf(e){let r=yd(e),s=(0,$.useRef)(null),n=(0,$.useCallback)(e=>{e!==s.current&&(null==r||r(e,s.current)),s.current=e},[]);return[s,n]}function yp(e){let r=(0,$.useRef)();return(0,$.useEffect)(()=>{r.current=e},[e]),r.current}let ym={};function yg(e,r){return(0,$.useMemo)(()=>{if(r)return r;let s=null==ym[e]?0:ym[e]+1;return ym[e]=s,e+"-"+s},[e,r])}function yx(e){return function(r){for(var s=arguments.length,n=Array(s>1?s-1:0),i=1;i<s;i++)n[i-1]=arguments[i];return n.reduce((r,s)=>{for(let[n,i]of Object.entries(s)){let s=r[n];null!=s&&(r[n]=s+e*i)}return r},{...r})}}let yv=yx(1),y_=yx(-1);function yy(e){if(!e)return!1;let{KeyboardEvent:r}=yn(e.target);return r&&e instanceof r}function yb(e){if(function(e){if(!e)return!1;let{TouchEvent:r}=yn(e.target);return r&&e instanceof r}(e)){if(e.touches&&e.touches.length){let{clientX:r,clientY:s}=e.touches[0];return{x:r,y:s}}else if(e.changedTouches&&e.changedTouches.length){let{clientX:r,clientY:s}=e.changedTouches[0];return{x:r,y:s}}}return"clientX"in e&&"clientY"in e?{x:e.clientX,y:e.clientY}:null}let yw=Object.freeze({Translate:{toString(e){if(!e)return;let{x:r,y:s}=e;return"translate3d("+(r?Math.round(r):0)+"px, "+(s?Math.round(s):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;let{scaleX:r,scaleY:s}=e;return"scaleX("+r+") scaleY("+s+")"}},Transform:{toString(e){if(e)return[yw.Translate.toString(e),yw.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:r,duration:s,easing:n}=e;return r+" "+s+"ms "+n}}}),yS="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]",yj={display:"none"};function yC(e){let{id:r,value:s}=e;return $.default.createElement("div",{id:r,style:yj},s)}function yk(e){let{id:r,announcement:s,ariaLiveType:n="assertive"}=e;return $.default.createElement("div",{id:r,style:{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"},role:"status","aria-live":n,"aria-atomic":!0},s)}let yN=(0,$.createContext)(null),yE={draggable:"\n To pick up a draggable item, press the space bar.\n While dragging, use the arrow keys to move the item.\n Press space again to drop the item in its new position, or press escape to cancel.\n "},yD={onDragStart(e){let{active:r}=e;return"Picked up draggable item "+r.id+"."},onDragOver(e){let{active:r,over:s}=e;return s?"Draggable item "+r.id+" was moved over droppable area "+s.id+".":"Draggable item "+r.id+" is no longer over a droppable area."},onDragEnd(e){let{active:r,over:s}=e;return s?"Draggable item "+r.id+" was dropped over droppable area "+s.id:"Draggable item "+r.id+" was dropped."},onDragCancel(e){let{active:r}=e;return"Dragging was cancelled. Draggable item "+r.id+" was dropped."}};function yR(e){var r;let s,{announcements:n=yD,container:i,hiddenTextDescribedById:a,screenReaderInstructions:o=yE}=e,{announce:l,announcement:c}=function(){let[e,r]=(0,$.useState)("");return{announce:(0,$.useCallback)(e=>{null!=e&&r(e)},[]),announcement:e}}(),d=yg("DndLiveRegion"),[u,h]=(0,$.useState)(!1);if((0,$.useEffect)(()=>{h(!0)},[]),r=(0,$.useMemo)(()=>({onDragStart(e){let{active:r}=e;l(n.onDragStart({active:r}))},onDragMove(e){let{active:r,over:s}=e;n.onDragMove&&l(n.onDragMove({active:r,over:s}))},onDragOver(e){let{active:r,over:s}=e;l(n.onDragOver({active:r,over:s}))},onDragEnd(e){let{active:r,over:s}=e;l(n.onDragEnd({active:r,over:s}))},onDragCancel(e){let{active:r,over:s}=e;l(n.onDragCancel({active:r,over:s}))}}),[l,n]),s=(0,$.useContext)(yN),(0,$.useEffect)(()=>{if(!s)throw Error("useDndMonitor must be used within a children of <DndContext>");return s(r)},[r,s]),!u)return null;let f=$.default.createElement($.default.Fragment,null,$.default.createElement(yC,{id:a,value:o.draggable}),$.default.createElement(yk,{id:d,announcement:c}));return i?(0,ee.createPortal)(f,i):f}function yA(){}function yT(e,r){return(0,$.useMemo)(()=>({sensor:e,options:null!=r?r:{}}),[e,r])}(_=E||(E={})).DragStart="dragStart",_.DragMove="dragMove",_.DragEnd="dragEnd",_.DragCancel="dragCancel",_.DragOver="dragOver",_.RegisterDroppable="registerDroppable",_.SetDroppableDisabled="setDroppableDisabled",_.UnregisterDroppable="unregisterDroppable";let yM=Object.freeze({x:0,y:0});function yF(e,r){return Math.sqrt(Math.pow(e.x-r.x,2)+Math.pow(e.y-r.y,2))}function yP(e,r){let{data:{value:s}}=e,{data:{value:n}}=r;return s-n}function yI(e,r){let{data:{value:s}}=e,{data:{value:n}}=r;return n-s}function yB(e){let{left:r,top:s,height:n,width:i}=e;return[{x:r,y:s},{x:r+i,y:s},{x:r,y:s+n},{x:r+i,y:s+n}]}function yL(e,r){if(!e||0===e.length)return null;let[s]=e;return r?s[r]:s}function yz(e,r,s){return void 0===r&&(r=e.left),void 0===s&&(s=e.top),{x:r+.5*e.width,y:s+.5*e.height}}let yO=e=>{let{collisionRect:r,droppableRects:s,droppableContainers:n}=e,i=[];for(let e of n){let{id:n}=e,a=s.get(n);if(a){let s=function(e,r){let s=Math.max(r.top,e.top),n=Math.max(r.left,e.left),i=Math.min(r.left+r.width,e.left+e.width),a=Math.min(r.top+r.height,e.top+e.height);if(n<i&&s<a){let o=r.width*r.height,l=e.width*e.height,c=(i-n)*(a-s);return Number((c/(o+l-c)).toFixed(4))}return 0}(a,r);s>0&&i.push({id:n,data:{droppableContainer:e,value:s}})}}return i.sort(yI)};function y$(e,r){return e&&r?{x:e.left-r.left,y:e.top-r.top}:yM}let yW=function(e){for(var r=arguments.length,s=Array(r>1?r-1:0),n=1;n<r;n++)s[n-1]=arguments[n];return s.reduce((e,r)=>({...e,top:e.top+ +r.y,bottom:e.bottom+ +r.y,left:e.left+ +r.x,right:e.right+ +r.x}),{...e})},yH={ignoreTransform:!1};function yU(e,r){void 0===r&&(r=yH);let s=e.getBoundingClientRect();if(r.ignoreTransform){let{transform:r,transformOrigin:n}=yn(e).getComputedStyle(e);r&&(s=function(e,r,s){let n=function(e){if(e.startsWith("matrix3d(")){let r=e.slice(9,-1).split(/, /);return{x:+r[12],y:+r[13],scaleX:+r[0],scaleY:+r[5]}}if(e.startsWith("matrix(")){let r=e.slice(7,-1).split(/, /);return{x:+r[4],y:+r[5],scaleX:+r[0],scaleY:+r[3]}}return null}(r);if(!n)return e;let{scaleX:i,scaleY:a,x:o,y:l}=n,c=e.left-o-(1-i)*parseFloat(s),d=e.top-l-(1-a)*parseFloat(s.slice(s.indexOf(" ")+1)),u=i?e.width/i:e.width,h=a?e.height/a:e.height;return{width:u,height:h,top:d,right:c+u,bottom:d+h,left:c}}(s,r,n))}let{top:n,left:i,width:a,height:o,bottom:l,right:c}=s;return{top:n,left:i,width:a,height:o,bottom:l,right:c}}function yq(e){return yU(e,{ignoreTransform:!0})}function yK(e,r){let s=[];return e?function n(i){var a,o;let l;if(null!=r&&s.length>=r||!i)return s;if(yi(i)&&null!=i.scrollingElement&&!s.includes(i.scrollingElement))return s.push(i.scrollingElement),s;if(!ya(i)||yo(i)||s.includes(i))return s;let c=yn(e).getComputedStyle(i);return(i!==e&&(void 0===(a=c)&&(a=yn(i).getComputedStyle(i)),l=/(auto|scroll|overlay)/,["overflow","overflowX","overflowY"].some(e=>{let r=a[e];return"string"==typeof r&&l.test(r)}))&&s.push(i),void 0===(o=c)&&(o=yn(i).getComputedStyle(i)),"fixed"===o.position)?s:n(i.parentNode)}(e):s}function yV(e){let[r]=yK(e,1);return null!=r?r:null}function yY(e){return yt&&e?yr(e)?e:ys(e)?yi(e)||e===yl(e).scrollingElement?window:ya(e)?e:null:null:null}function yG(e){return yr(e)?e.scrollX:e.scrollLeft}function yX(e){return yr(e)?e.scrollY:e.scrollTop}function yJ(e){return{x:yG(e),y:yX(e)}}function yZ(e){return!!yt&&!!e&&e===document.scrollingElement}function yQ(e){let r={x:0,y:0},s=yZ(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},n={x:e.scrollWidth-s.width,y:e.scrollHeight-s.height},i=e.scrollTop<=r.y,a=e.scrollLeft<=r.x;return{isTop:i,isLeft:a,isBottom:e.scrollTop>=n.y,isRight:e.scrollLeft>=n.x,maxScroll:n,minScroll:r}}(y=D||(D={}))[y.Forward=1]="Forward",y[y.Backward=-1]="Backward";let y0={x:.2,y:.2};function y1(e){return e.reduce((e,r)=>yv(e,yJ(r)),yM)}let y2=[["x",["left","right"],function(e){return e.reduce((e,r)=>e+yG(r),0)}],["y",["top","bottom"],function(e){return e.reduce((e,r)=>e+yX(r),0)}]];class y5{constructor(e,r){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const s=yK(r),n=y1(s);for(const[r,i,a]of(this.rect={...e},this.width=e.width,this.height=e.height,y2))for(const e of i)Object.defineProperty(this,e,{get:()=>{let i=a(s),o=n[r]-i;return this.rect[e]+o},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class y3{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(e=>{var r;return null==(r=this.target)?void 0:r.removeEventListener(...e)})},this.target=e}add(e,r,s){var n;null==(n=this.target)||n.addEventListener(e,r,s),this.listeners.push([e,r,s])}}function y4(e,r){let s=Math.abs(e.x),n=Math.abs(e.y);return"number"==typeof r?Math.sqrt(s**2+n**2)>r:"x"in r&&"y"in r?s>r.x&&n>r.y:"x"in r?s>r.x:"y"in r&&n>r.y}function y6(e){e.preventDefault()}function y7(e){e.stopPropagation()}(b=R||(R={})).Click="click",b.DragStart="dragstart",b.Keydown="keydown",b.ContextMenu="contextmenu",b.Resize="resize",b.SelectionChange="selectionchange",b.VisibilityChange="visibilitychange",(w=A||(A={})).Space="Space",w.Down="ArrowDown",w.Right="ArrowRight",w.Left="ArrowLeft",w.Up="ArrowUp",w.Esc="Escape",w.Enter="Enter",w.Tab="Tab";let y8={start:[A.Space,A.Enter],cancel:[A.Esc],end:[A.Space,A.Enter,A.Tab]},y9=(e,r)=>{let{currentCoordinates:s}=r;switch(e.code){case A.Right:return{...s,x:s.x+25};case A.Left:return{...s,x:s.x-25};case A.Down:return{...s,y:s.y+25};case A.Up:return{...s,y:s.y-25}}};class be{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:r}}=e;this.props=e,this.listeners=new y3(yl(r)),this.windowListeners=new y3(yn(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(R.Resize,this.handleCancel),this.windowListeners.add(R.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(R.Keydown,this.handleKeyDown))}handleStart(){let{activeNode:e,onStart:r}=this.props,s=e.node.current;s&&function(e,r){if(void 0===r&&(r=yU),!e)return;let{top:s,left:n,bottom:i,right:a}=r(e);yV(e)&&(i<=0||a<=0||s>=window.innerHeight||n>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}(s),r(yM)}handleKeyDown(e){if(yy(e)){let{active:r,context:s,options:n}=this.props,{keyboardCodes:i=y8,coordinateGetter:a=y9,scrollBehavior:o="smooth"}=n,{code:l}=e;if(i.end.includes(l))return void this.handleEnd(e);if(i.cancel.includes(l))return void this.handleCancel(e);let{collisionRect:c}=s.current,d=c?{x:c.left,y:c.top}:yM;this.referenceCoordinates||(this.referenceCoordinates=d);let u=a(e,{active:r,context:s.current,currentCoordinates:d});if(u){let r=y_(u,d),n={x:0,y:0},{scrollableAncestors:i}=s.current;for(let s of i){let i=e.code,{isTop:a,isRight:l,isLeft:c,isBottom:d,maxScroll:h,minScroll:f}=yQ(s),p=function(e){if(e===document.scrollingElement){let{innerWidth:e,innerHeight:r}=window;return{top:0,left:0,right:e,bottom:r,width:e,height:r}}let{top:r,left:s,right:n,bottom:i}=e.getBoundingClientRect();return{top:r,left:s,right:n,bottom:i,width:e.clientWidth,height:e.clientHeight}}(s),m={x:Math.min(i===A.Right?p.right-p.width/2:p.right,Math.max(i===A.Right?p.left:p.left+p.width/2,u.x)),y:Math.min(i===A.Down?p.bottom-p.height/2:p.bottom,Math.max(i===A.Down?p.top:p.top+p.height/2,u.y))},g=i===A.Right&&!l||i===A.Left&&!c,x=i===A.Down&&!d||i===A.Up&&!a;if(g&&m.x!==u.x){let e=s.scrollLeft+r.x,a=i===A.Right&&e<=h.x||i===A.Left&&e>=f.x;if(a&&!r.y)return void s.scrollTo({left:e,behavior:o});a?n.x=s.scrollLeft-e:n.x=i===A.Right?s.scrollLeft-h.x:s.scrollLeft-f.x,n.x&&s.scrollBy({left:-n.x,behavior:o});break}if(x&&m.y!==u.y){let e=s.scrollTop+r.y,a=i===A.Down&&e<=h.y||i===A.Up&&e>=f.y;if(a&&!r.x)return void s.scrollTo({top:e,behavior:o});a?n.y=s.scrollTop-e:n.y=i===A.Down?s.scrollTop-h.y:s.scrollTop-f.y,n.y&&s.scrollBy({top:-n.y,behavior:o});break}}this.handleMove(e,yv(y_(u,this.referenceCoordinates),n))}}}handleMove(e,r){let{onMove:s}=this.props;e.preventDefault(),s(r)}handleEnd(e){let{onEnd:r}=this.props;e.preventDefault(),this.detach(),r()}handleCancel(e){let{onCancel:r}=this.props;e.preventDefault(),this.detach(),r()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}function bt(e){return!!(e&&"distance"in e)}function br(e){return!!(e&&"delay"in e)}be.activators=[{eventName:"onKeyDown",handler:(e,r,s)=>{let{keyboardCodes:n=y8,onActivation:i}=r,{active:a}=s,{code:o}=e.nativeEvent;if(n.start.includes(o)){let r=a.activatorNode.current;return(!r||e.target===r)&&(e.preventDefault(),null==i||i({event:e.nativeEvent}),!0)}return!1}}];class bs{constructor(e,r,s){var n;void 0===s&&(s=function(e){let{EventTarget:r}=yn(e);return e instanceof r?e:yl(e)}(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=r;const{event:i}=e,{target:a}=i;this.props=e,this.events=r,this.document=yl(a),this.documentListeners=new y3(this.document),this.listeners=new y3(s),this.windowListeners=new y3(yn(a)),this.initialCoordinates=null!=(n=yb(i))?n:yM,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){let{events:e,props:{options:{activationConstraint:r,bypassActivationConstraint:s}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(R.Resize,this.handleCancel),this.windowListeners.add(R.DragStart,y6),this.windowListeners.add(R.VisibilityChange,this.handleCancel),this.windowListeners.add(R.ContextMenu,y6),this.documentListeners.add(R.Keydown,this.handleKeydown),r){if(null!=s&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(br(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(bt(r))return void this.handlePending(r)}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,r){let{active:s,onPending:n}=this.props;n(s,e,this.initialCoordinates,r)}handleStart(){let{initialCoordinates:e}=this,{onStart:r}=this.props;e&&(this.activated=!0,this.documentListeners.add(R.Click,y7,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(R.SelectionChange,this.removeTextSelection),r(e))}handleMove(e){var r;let{activated:s,initialCoordinates:n,props:i}=this,{onMove:a,options:{activationConstraint:o}}=i;if(!n)return;let l=null!=(r=yb(e))?r:yM,c=y_(n,l);if(!s&&o){if(bt(o)){if(null!=o.tolerance&&y4(c,o.tolerance))return this.handleCancel();if(y4(c,o.distance))return this.handleStart()}return br(o)&&y4(c,o.tolerance)?this.handleCancel():void this.handlePending(o,c)}e.cancelable&&e.preventDefault(),a(l)}handleEnd(){let{onAbort:e,onEnd:r}=this.props;this.detach(),this.activated||e(this.props.active),r()}handleCancel(){let{onAbort:e,onCancel:r}=this.props;this.detach(),this.activated||e(this.props.active),r()}handleKeydown(e){e.code===A.Esc&&this.handleCancel()}removeTextSelection(){var e;null==(e=this.document.getSelection())||e.removeAllRanges()}}let bn={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class bi extends bs{constructor(e){const{event:r}=e;super(e,bn,yl(r.target))}}bi.activators=[{eventName:"onPointerDown",handler:(e,r)=>{let{nativeEvent:s}=e,{onActivation:n}=r;return!!s.isPrimary&&0===s.button&&(null==n||n({event:s}),!0)}}];(S=T||(T={}))[S.RightClick=2]="RightClick";(j=M||(M={}))[j.Pointer=0]="Pointer",j[j.DraggableRect=1]="DraggableRect",(C=F||(F={}))[C.TreeOrder=0]="TreeOrder",C[C.ReversedTreeOrder=1]="ReversedTreeOrder";let ba={x:{[D.Backward]:!1,[D.Forward]:!1},y:{[D.Backward]:!1,[D.Forward]:!1}};(k=P||(P={}))[k.Always=0]="Always",k[k.BeforeDragging=1]="BeforeDragging",k[k.WhileDragging=2]="WhileDragging",(I||(I={})).Optimized="optimized";let bo=new Map;function bl(e,r){return yh(s=>e?s||("function"==typeof r?r(e):e):null,[r,e])}function bc(e){let{callback:r,disabled:s}=e,n=yd(r),i=(0,$.useMemo)(()=>{if(s||"undefined"==typeof window||void 0===window.ResizeObserver)return;let{ResizeObserver:e}=window;return new e(n)},[s]);return(0,$.useEffect)(()=>()=>null==i?void 0:i.disconnect(),[i]),i}function bd(e){return new y5(yU(e),e)}function bu(e,r,s){void 0===r&&(r=bd);let[n,i]=(0,$.useState)(null);function a(){i(n=>{if(!e)return null;if(!1===e.isConnected){var i;return null!=(i=null!=n?n:s)?i:null}let a=r(e);return JSON.stringify(n)===JSON.stringify(a)?n:a})}let o=function(e){let{callback:r,disabled:s}=e,n=yd(r),i=(0,$.useMemo)(()=>{if(s||"undefined"==typeof window||void 0===window.MutationObserver)return;let{MutationObserver:e}=window;return new e(n)},[n,s]);return(0,$.useEffect)(()=>()=>null==i?void 0:i.disconnect(),[i]),i}({callback(r){if(e)for(let s of r){let{type:r,target:n}=s;if("childList"===r&&n instanceof HTMLElement&&n.contains(e)){a();break}}}}),l=bc({callback:a});return yc(()=>{a(),e?(null==l||l.observe(e),null==o||o.observe(document.body,{childList:!0,subtree:!0})):(null==l||l.disconnect(),null==o||o.disconnect())},[e]),n}let bh=[];function bf(e,r){void 0===r&&(r=[]);let s=(0,$.useRef)(null);return(0,$.useEffect)(()=>{s.current=null},r),(0,$.useEffect)(()=>{let r=e!==yM;r&&!s.current&&(s.current=e),!r&&s.current&&(s.current=null)},[e]),s.current?y_(e,s.current):yM}function bp(e){return(0,$.useMemo)(()=>{let r,s;return e?(r=e.innerWidth,{top:0,left:0,right:r,bottom:s=e.innerHeight,width:r,height:s}):null},[e])}let bm=[],bg=[{sensor:bi,options:{}},{sensor:be,options:{}}],bx={current:{}},bv={draggable:{measure:yq},droppable:{measure:yq,strategy:P.WhileDragging,frequency:I.Optimized},dragOverlay:{measure:yU}};class b_ extends Map{get(e){var r;return null!=e&&null!=(r=super.get(e))?r:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:r}=e;return!r})}getNodeFor(e){var r,s;return null!=(r=null==(s=this.get(e))?void 0:s.node.current)?r:void 0}}let by={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new b_,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:yA},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:bv,measureDroppableContainers:yA,windowRect:null,measuringScheduled:!1},bb={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:yA,draggableNodes:new Map,over:null,measureDroppableContainers:yA},bw=(0,$.createContext)(bb),bS=(0,$.createContext)(by);function bj(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new b_}}}function bC(e,r){switch(r.type){case E.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:r.initialCoordinates,active:r.active}};case E.DragMove:if(null==e.draggable.active)return e;return{...e,draggable:{...e.draggable,translate:{x:r.coordinates.x-e.draggable.initialCoordinates.x,y:r.coordinates.y-e.draggable.initialCoordinates.y}}};case E.DragEnd:case E.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case E.RegisterDroppable:{let{element:s}=r,{id:n}=s,i=new b_(e.droppable.containers);return i.set(n,s),{...e,droppable:{...e.droppable,containers:i}}}case E.SetDroppableDisabled:{let{id:s,key:n,disabled:i}=r,a=e.droppable.containers.get(s);if(!a||n!==a.key)return e;let o=new b_(e.droppable.containers);return o.set(s,{...a,disabled:i}),{...e,droppable:{...e.droppable,containers:o}}}case E.UnregisterDroppable:{let{id:s,key:n}=r,i=e.droppable.containers.get(s);if(!i||n!==i.key)return e;let a=new b_(e.droppable.containers);return a.delete(s),{...e,droppable:{...e.droppable,containers:a}}}default:return e}}function bk(e){let{disabled:r}=e,{active:s,activatorEvent:n,draggableNodes:i}=(0,$.useContext)(bw),a=yp(n),o=yp(null==s?void 0:s.id);return(0,$.useEffect)(()=>{if(!r&&!n&&a&&null!=o){if(!yy(a)||document.activeElement===a.target)return;let e=i.get(o);if(!e)return;let{activatorNode:r,node:s}=e;(r.current||s.current)&&requestAnimationFrame(()=>{for(let e of[r.current,s.current]){if(!e)continue;let r=e.matches(yS)?e:e.querySelector(yS);if(r){r.focus();break}}})}},[n,r,i,o,a]),null}let bN=(0,$.createContext)({...yM,scaleX:1,scaleY:1});(N=B||(B={}))[N.Uninitialized=0]="Uninitialized",N[N.Initializing=1]="Initializing",N[N.Initialized=2]="Initialized";let bE=(0,$.memo)(function(e){var r,s,n,i,a,o,l,c;let d,u,h,f,p,m,g,x,{id:v,accessibility:_,autoScroll:y=!0,children:b,sensors:w=bg,collisionDetection:S=yO,measuring:j,modifiers:C,...k}=e,[N,R]=(0,$.useReducer)(bC,void 0,bj),[A,T]=function(){let[e]=(0,$.useState)(()=>new Set),r=(0,$.useCallback)(r=>(e.add(r),()=>e.delete(r)),[e]);return[(0,$.useCallback)(r=>{let{type:s,event:n}=r;e.forEach(e=>{var r;return null==(r=e[s])?void 0:r.call(e,n)})},[e]),r]}(),[I,L]=(0,$.useState)(B.Uninitialized),z=I===B.Initialized,{draggable:{active:O,nodes:W,translate:H},droppable:{containers:U}}=N,q=null!=O?W.get(O):null,K=(0,$.useRef)({initial:null,translated:null}),V=(0,$.useMemo)(()=>{var e;return null!=O?{id:O,data:null!=(e=null==q?void 0:q.data)?e:bx,rect:K}:null},[O,q]),Y=(0,$.useRef)(null),[G,X]=(0,$.useState)(null),[J,Z]=(0,$.useState)(null),Q=yu(k,Object.values(k)),et=yg("DndDescribedBy",v),er=(0,$.useMemo)(()=>U.getEnabled(),[U]),es=(0,$.useMemo)(()=>({draggable:{...bv.draggable,...null==j?void 0:j.draggable},droppable:{...bv.droppable,...null==j?void 0:j.droppable},dragOverlay:{...bv.dragOverlay,...null==j?void 0:j.dragOverlay}}),[null==j?void 0:j.draggable,null==j?void 0:j.droppable,null==j?void 0:j.dragOverlay]),{droppableRects:en,measureDroppableContainers:ei,measuringScheduled:ea}=function(e,r){let{dragging:s,dependencies:n,config:i}=r,[a,o]=(0,$.useState)(null),{frequency:l,measure:c,strategy:d}=i,u=(0,$.useRef)(e),h=function(){switch(d){case P.Always:return!1;case P.BeforeDragging:return s;default:return!s}}(),f=yu(h),p=(0,$.useCallback)(function(e){void 0===e&&(e=[]),f.current||o(r=>null===r?e:r.concat(e.filter(e=>!r.includes(e))))},[f]),m=(0,$.useRef)(null),g=yh(r=>{if(h&&!s)return bo;if(!r||r===bo||u.current!==e||null!=a){let r=new Map;for(let s of e){if(!s)continue;if(a&&a.length>0&&!a.includes(s.id)&&s.rect.current){r.set(s.id,s.rect.current);continue}let e=s.node.current,n=e?new y5(c(e),e):null;s.rect.current=n,n&&r.set(s.id,n)}return r}return r},[e,a,s,h,c]);return(0,$.useEffect)(()=>{u.current=e},[e]),(0,$.useEffect)(()=>{h||p()},[s,h]),(0,$.useEffect)(()=>{a&&a.length>0&&o(null)},[JSON.stringify(a)]),(0,$.useEffect)(()=>{h||"number"!=typeof l||null!==m.current||(m.current=setTimeout(()=>{p(),m.current=null},l))},[l,h,p,...n]),{droppableRects:g,measureDroppableContainers:p,measuringScheduled:null!=a}}(er,{dragging:z,dependencies:[H.x,H.y],config:es.droppable}),eo=yh(e=>{var r;return null==O?null:null!=(r=null!=p?p:e)?r:null},[p=(f=null!=O?W.get(O):void 0)?f.node.current:null,O]),el=(0,$.useMemo)(()=>J?yb(J):null,[J]),ec=(d=(null==G?void 0:G.autoScrollEnabled)===!1,u="object"==typeof y?!1===y.enabled:!1===y,h=z&&!d&&!u,"object"==typeof y?{...y,enabled:h}:{enabled:h}),ed=bl(eo,es.draggable.measure);!function(e){let{activeNode:r,measure:s,initialRect:n,config:i=!0}=e,a=(0,$.useRef)(!1),{x:o,y:l}="boolean"==typeof i?{x:i,y:i}:i;yc(()=>{if(!o&&!l||!r){a.current=!1;return}if(a.current||!n)return;let e=null==r?void 0:r.node.current;if(!e||!1===e.isConnected)return;let i=y$(s(e),n);if(o||(i.x=0),l||(i.y=0),a.current=!0,Math.abs(i.x)>0||Math.abs(i.y)>0){let r=yV(e);r&&r.scrollBy({top:i.y,left:i.x})}},[r,o,l,n,s])}({activeNode:null!=O?W.get(O):null,config:ec.layoutShiftCompensation,initialRect:ed,measure:es.draggable.measure});let eu=bu(eo,es.draggable.measure,ed),eh=bu(eo?eo.parentElement:null),ef=(0,$.useRef)({activatorEvent:null,active:null,activeNode:eo,collisionRect:null,collisions:null,droppableRects:en,draggableNodes:W,draggingNode:null,draggingNodeRect:null,droppableContainers:U,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ep=U.getNodeFor(null==(r=ef.current.over)?void 0:r.id),em=function(e){let{measure:r}=e,[s,n]=(0,$.useState)(null),i=bc({callback:(0,$.useCallback)(e=>{for(let{target:s}of e)if(ya(s)){n(e=>{let n=r(s);return e?{...e,width:n.width,height:n.height}:n});break}},[r])}),[a,o]=yf((0,$.useCallback)(e=>{let s=function(e){if(!e)return null;if(e.children.length>1)return e;let r=e.children[0];return ya(r)?r:e}(e);null==i||i.disconnect(),s&&(null==i||i.observe(s)),n(s?r(s):null)},[r,i]));return(0,$.useMemo)(()=>({nodeRef:a,rect:s,setRef:o}),[s,a,o])}({measure:es.dragOverlay.measure}),eg=null!=(s=em.nodeRef.current)?s:eo,ex=z?null!=(n=em.rect)?n:eu:null,ev=!!(em.nodeRef.current&&em.rect),e_=(m=bl(a=ev?null:eu),y$(a,m)),ey=bp(eg?yn(eg):null),eb=(o=z?null!=ep?ep:eo:null,g=(0,$.useRef)(o),x=yh(e=>o?e&&e!==bh&&o&&g.current&&o.parentNode===g.current.parentNode?e:yK(o):bh,[o]),(0,$.useEffect)(()=>{g.current=o},[o]),x),ew=function(e,r){void 0===r&&(r=yU);let[s]=e,n=bp(s?yn(s):null),[i,a]=(0,$.useState)(bm);function o(){a(()=>e.length?e.map(e=>yZ(e)?n:new y5(r(e),e)):bm)}let l=bc({callback:o});return yc(()=>{null==l||l.disconnect(),o(),e.forEach(e=>null==l?void 0:l.observe(e))},[e]),i}(eb),eS=function(e,r){let{transform:s,...n}=r;return null!=e&&e.length?e.reduce((e,r)=>r({transform:e,...n}),s):s}(C,{transform:{x:H.x-e_.x,y:H.y-e_.y,scaleX:1,scaleY:1},activatorEvent:J,active:V,activeNodeRect:eu,containerNodeRect:eh,draggingNodeRect:ex,over:ef.current.over,overlayNodeRect:em.rect,scrollableAncestors:eb,scrollableAncestorRects:ew,windowRect:ey}),ej=el?yv(el,H):null,eC=function(e){let[r,s]=(0,$.useState)(null),n=(0,$.useRef)(e),i=(0,$.useCallback)(e=>{let r=yY(e.target);r&&s(e=>e?(e.set(r,yJ(r)),new Map(e)):null)},[]);return(0,$.useEffect)(()=>{let r=n.current;if(e!==r){a(r);let o=e.map(e=>{let r=yY(e);return r?(r.addEventListener("scroll",i,{passive:!0}),[r,yJ(r)]):null}).filter(e=>null!=e);s(o.length?new Map(o):null),n.current=e}return()=>{a(e),a(r)};function a(e){e.forEach(e=>{let r=yY(e);null==r||r.removeEventListener("scroll",i)})}},[i,e]),(0,$.useMemo)(()=>e.length?r?Array.from(r.values()).reduce((e,r)=>yv(e,r),yM):y1(e):yM,[e,r])}(eb),ek=bf(eC),eN=bf(eC,[eu]),eE=yv(eS,ek),eD=ex?yW(ex,eS):null,eR=V&&eD?S({active:V,collisionRect:eD,droppableRects:en,droppableContainers:er,pointerCoordinates:ej}):null,eA=yL(eR,"id"),[eT,eM]=(0,$.useState)(null),eF=(l=ev?eS:yv(eS,eN),c=null!=(i=null==eT?void 0:eT.rect)?i:null,{...l,scaleX:c&&eu?c.width/eu.width:1,scaleY:c&&eu?c.height/eu.height:1}),eP=(0,$.useRef)(null),eI=(0,$.useCallback)((e,r)=>{let{sensor:s,options:n}=r;if(null==Y.current)return;let i=W.get(Y.current);if(!i)return;let a=e.nativeEvent,o=new s({active:Y.current,activeNode:i,event:a,options:n,context:ef,onAbort(e){if(!W.get(e))return;let{onDragAbort:r}=Q.current,s={id:e};null==r||r(s),A({type:"onDragAbort",event:s})},onPending(e,r,s,n){if(!W.get(e))return;let{onDragPending:i}=Q.current,a={id:e,constraint:r,initialCoordinates:s,offset:n};null==i||i(a),A({type:"onDragPending",event:a})},onStart(e){let r=Y.current;if(null==r)return;let s=W.get(r);if(!s)return;let{onDragStart:n}=Q.current,i={activatorEvent:a,active:{id:r,data:s.data,rect:K}};(0,ee.unstable_batchedUpdates)(()=>{null==n||n(i),L(B.Initializing),R({type:E.DragStart,initialCoordinates:e,active:r}),A({type:"onDragStart",event:i}),X(eP.current),Z(a)})},onMove(e){R({type:E.DragMove,coordinates:e})},onEnd:l(E.DragEnd),onCancel:l(E.DragCancel)});function l(e){return async function(){let{active:r,collisions:s,over:n,scrollAdjustedTranslate:i}=ef.current,o=null;if(r&&i){let{cancelDrop:l}=Q.current;o={activatorEvent:a,active:r,collisions:s,delta:i,over:n},e===E.DragEnd&&"function"==typeof l&&await Promise.resolve(l(o))&&(e=E.DragCancel)}Y.current=null,(0,ee.unstable_batchedUpdates)(()=>{R({type:e}),L(B.Uninitialized),eM(null),X(null),Z(null),eP.current=null;let r=e===E.DragEnd?"onDragEnd":"onDragCancel";if(o){let e=Q.current[r];null==e||e(o),A({type:r,event:o})}})}}eP.current=o},[W]),eB=(0,$.useCallback)((e,r)=>(s,n)=>{let i=s.nativeEvent,a=W.get(n);null!==Y.current||!a||i.dndKit||i.defaultPrevented||!0===e(s,r.options,{active:a})&&(i.dndKit={capturedBy:r.sensor},Y.current=n,eI(s,r))},[W,eI]),eL=(0,$.useMemo)(()=>w.reduce((e,r)=>{let{sensor:s}=r;return[...e,...s.activators.map(e=>({eventName:e.eventName,handler:eB(e.handler,r)}))]},[]),[w,eB]);(0,$.useEffect)(()=>{if(!yt)return;let e=w.map(e=>{let{sensor:r}=e;return null==r.setup?void 0:r.setup()});return()=>{for(let r of e)null==r||r()}},w.map(e=>{let{sensor:r}=e;return r})),yc(()=>{eu&&I===B.Initializing&&L(B.Initialized)},[eu,I]),(0,$.useEffect)(()=>{let{onDragMove:e}=Q.current,{active:r,activatorEvent:s,collisions:n,over:i}=ef.current;if(!r||!s)return;let a={active:r,activatorEvent:s,collisions:n,delta:{x:eE.x,y:eE.y},over:i};(0,ee.unstable_batchedUpdates)(()=>{null==e||e(a),A({type:"onDragMove",event:a})})},[eE.x,eE.y]),(0,$.useEffect)(()=>{let{active:e,activatorEvent:r,collisions:s,droppableContainers:n,scrollAdjustedTranslate:i}=ef.current;if(!e||null==Y.current||!r||!i)return;let{onDragOver:a}=Q.current,o=n.get(eA),l=o&&o.rect.current?{id:o.id,rect:o.rect.current,data:o.data,disabled:o.disabled}:null,c={active:e,activatorEvent:r,collisions:s,delta:{x:i.x,y:i.y},over:l};(0,ee.unstable_batchedUpdates)(()=>{eM(l),null==a||a(c),A({type:"onDragOver",event:c})})},[eA]),yc(()=>{ef.current={activatorEvent:J,active:V,activeNode:eo,collisionRect:eD,collisions:eR,droppableRects:en,draggableNodes:W,draggingNode:eg,draggingNodeRect:ex,droppableContainers:U,over:eT,scrollableAncestors:eb,scrollAdjustedTranslate:eE},K.current={initial:ex,translated:eD}},[V,eo,eR,eD,W,eg,ex,en,U,eT,eb,eE]),function(e){let r,{acceleration:s,activator:n=M.Pointer,canScroll:i,draggingRect:a,enabled:o,interval:l=5,order:c=F.TreeOrder,pointerCoordinates:d,scrollableAncestors:u,scrollableAncestorRects:h,delta:f,threshold:p}=e,m=function(e){let{delta:r,disabled:s}=e,n=yp(r);return yh(e=>{if(s||!n||!e)return ba;let i={x:Math.sign(r.x-n.x),y:Math.sign(r.y-n.y)};return{x:{[D.Backward]:e.x[D.Backward]||-1===i.x,[D.Forward]:e.x[D.Forward]||1===i.x},y:{[D.Backward]:e.y[D.Backward]||-1===i.y,[D.Forward]:e.y[D.Forward]||1===i.y}}},[s,r,n])}({delta:f,disabled:!o}),[g,x]=(r=(0,$.useRef)(null),[(0,$.useCallback)((e,s)=>{r.current=setInterval(e,s)},[]),(0,$.useCallback)(()=>{null!==r.current&&(clearInterval(r.current),r.current=null)},[])]),v=(0,$.useRef)({x:0,y:0}),_=(0,$.useRef)({x:0,y:0}),y=(0,$.useMemo)(()=>{switch(n){case M.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case M.DraggableRect:return a}},[n,a,d]),b=(0,$.useRef)(null),w=(0,$.useCallback)(()=>{let e=b.current;if(!e)return;let r=v.current.x*_.current.x,s=v.current.y*_.current.y;e.scrollBy(r,s)},[]),S=(0,$.useMemo)(()=>c===F.TreeOrder?[...u].reverse():u,[c,u]);(0,$.useEffect)(()=>{if(!o||!u.length||!y)return void x();for(let e of S){if((null==i?void 0:i(e))===!1)continue;let r=h[u.indexOf(e)];if(!r)continue;let{direction:n,speed:a}=function(e,r,s,n,i){let{top:a,left:o,right:l,bottom:c}=s;void 0===n&&(n=10),void 0===i&&(i=y0);let{isTop:d,isBottom:u,isLeft:h,isRight:f}=yQ(e),p={x:0,y:0},m={x:0,y:0},g={height:r.height*i.y,width:r.width*i.x};return!d&&a<=r.top+g.height?(p.y=D.Backward,m.y=n*Math.abs((r.top+g.height-a)/g.height)):!u&&c>=r.bottom-g.height&&(p.y=D.Forward,m.y=n*Math.abs((r.bottom-g.height-c)/g.height)),!f&&l>=r.right-g.width?(p.x=D.Forward,m.x=n*Math.abs((r.right-g.width-l)/g.width)):!h&&o<=r.left+g.width&&(p.x=D.Backward,m.x=n*Math.abs((r.left+g.width-o)/g.width)),{direction:p,speed:m}}(e,r,y,s,p);for(let e of["x","y"])m[e][n[e]]||(a[e]=0,n[e]=0);if(a.x>0||a.y>0){x(),b.current=e,g(w,l),v.current=a,_.current=n;return}}v.current={x:0,y:0},_.current={x:0,y:0},x()},[s,w,i,x,o,l,JSON.stringify(y),JSON.stringify(m),g,u,S,h,JSON.stringify(p)])}({...ec,delta:H,draggingRect:eD,pointerCoordinates:ej,scrollableAncestors:eb,scrollableAncestorRects:ew});let ez=(0,$.useMemo)(()=>({active:V,activeNode:eo,activeNodeRect:eu,activatorEvent:J,collisions:eR,containerNodeRect:eh,dragOverlay:em,draggableNodes:W,droppableContainers:U,droppableRects:en,over:eT,measureDroppableContainers:ei,scrollableAncestors:eb,scrollableAncestorRects:ew,measuringConfiguration:es,measuringScheduled:ea,windowRect:ey}),[V,eo,eu,J,eR,eh,em,W,U,en,eT,ei,eb,ew,es,ea,ey]),eO=(0,$.useMemo)(()=>({activatorEvent:J,activators:eL,active:V,activeNodeRect:eu,ariaDescribedById:{draggable:et},dispatch:R,draggableNodes:W,over:eT,measureDroppableContainers:ei}),[J,eL,V,eu,R,et,W,eT,ei]);return $.default.createElement(yN.Provider,{value:T},$.default.createElement(bw.Provider,{value:eO},$.default.createElement(bS.Provider,{value:ez},$.default.createElement(bN.Provider,{value:eF},b)),$.default.createElement(bk,{disabled:(null==_?void 0:_.restoreFocus)===!1})),$.default.createElement(yR,{..._,hiddenTextDescribedById:et}))}),bD=(0,$.createContext)(null),bR="button",bA={timeout:25},bT={position:"fixed",touchAction:"none"},bM=e=>yy(e)?"transform 250ms ease":void 0;function bF(e,r,s){let n=e.slice();return n.splice(s<0?n.length+s:s,0,n.splice(r,1)[0]),n}function bP(e){return null!==e&&e>=0}(e,r)=>{let{as:s,activatorEvent:n,adjustScale:i,children:a,className:o,rect:l,style:c,transform:d,transition:u=bM}=e;if(!l)return null;let h=i?d:{...d,scaleX:1,scaleY:1},f={...bT,width:l.width,height:l.height,top:l.top,left:l.left,transform:yw.Transform.toString(h),transformOrigin:i&&n?function(e,r){let s=yb(e);if(!s)return"0 0";let n={x:(s.x-r.left)/r.width*100,y:(s.y-r.top)/r.height*100};return n.x+"% "+n.y+"%"}(n,l):void 0,transition:"function"==typeof u?u(n):u,...c};return $.default.createElement(s,{className:o,style:f,ref:r},a)},x={styles:{active:{opacity:"0"}}};let bI=e=>{let{rects:r,activeIndex:s,overIndex:n,index:i}=e,a=bF(r,n,s),o=r[i],l=a[i];return l&&o?{x:l.left-o.left,y:l.top-o.top,scaleX:l.width/o.width,scaleY:l.height/o.height}:null},bB={scaleX:1,scaleY:1},bL=e=>{var r,s,n,i;let a,o,l,{activeIndex:c,activeNodeRect:d,index:u,rects:h,overIndex:f}=e,p=null!=(r=h[c])?r:d;if(!p)return null;if(u===c){let e=h[f];return e?{x:0,y:c<f?e.top+e.height-(p.top+p.height):e.top-p.top,...bB}:null}let m=(s=h,n=u,i=c,a=s[n],o=s[n-1],l=s[n+1],a?i<n?o?a.top-(o.top+o.height):l?l.top-(a.top+a.height):0:l?l.top-(a.top+a.height):o?a.top-(o.top+o.height):0:0);return u>c&&u<=f?{x:0,y:-p.height-m,...bB}:u<c&&u>=f?{x:0,y:p.height+m,...bB}:{x:0,y:0,...bB}},bz="Sortable",bO=$.default.createContext({activeIndex:-1,containerId:bz,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:bI,disabled:{draggable:!1,droppable:!1}});function b$(e){let{children:r,id:s,items:n,strategy:i=bI,disabled:a=!1}=e,{active:o,dragOverlay:l,droppableRects:c,over:d,measureDroppableContainers:u}=(0,$.useContext)(bS),h=yg(bz,s),f=null!==l.rect,p=(0,$.useMemo)(()=>n.map(e=>"object"==typeof e&&"id"in e?e.id:e),[n]),m=null!=o,g=o?p.indexOf(o.id):-1,x=d?p.indexOf(d.id):-1,v=(0,$.useRef)(p),_=!function(e,r){if(e===r)return!0;if(e.length!==r.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==r[s])return!1;return!0}(p,v.current),y=-1!==x&&-1===g||_,b="boolean"==typeof a?{draggable:a,droppable:a}:a;yc(()=>{_&&m&&u(p)},[_,p,m,u]),(0,$.useEffect)(()=>{v.current=p},[p]);let w=(0,$.useMemo)(()=>({activeIndex:g,containerId:h,disabled:b,disableTransforms:y,items:p,overIndex:x,useDragOverlay:f,sortedRects:p.reduce((e,r,s)=>{let n=c.get(r);return n&&(e[s]=n),e},Array(p.length)),strategy:i}),[g,h,b.draggable,b.droppable,y,p,x,c,f,i]);return $.default.createElement(bO.Provider,{value:w},r)}let bW=e=>{let{id:r,items:s,activeIndex:n,overIndex:i}=e;return bF(s,n,i).indexOf(r)},bH=e=>{let{containerId:r,isSorting:s,wasDragging:n,index:i,items:a,newIndex:o,previousItems:l,previousContainerId:c,transition:d}=e;return!!d&&!!n&&(l===a||i!==o)&&(!!s||o!==i&&r===c)},bU={duration:200,easing:"ease"},bq="transform",bK=yw.Transition.toString({property:bq,duration:0,easing:"linear"}),bV={roleDescription:"sortable"};function bY(e){if(!e)return!1;let r=e.data.current;return!!r&&"sortable"in r&&"object"==typeof r.sortable&&"containerId"in r.sortable&&"items"in r.sortable&&"index"in r.sortable}let bG=[A.Down,A.Right,A.Up,A.Left],bX=(e,r)=>{let{context:{active:s,collisionRect:n,droppableRects:i,droppableContainers:a,over:o,scrollableAncestors:l}}=r;if(bG.includes(e.code)){if(e.preventDefault(),!s||!n)return;let r=[];a.getEnabled().forEach(s=>{if(!s||null!=s&&s.disabled)return;let a=i.get(s.id);if(a)switch(e.code){case A.Down:n.top<a.top&&r.push(s);break;case A.Up:n.top>a.top&&r.push(s);break;case A.Left:n.left>a.left&&r.push(s);break;case A.Right:n.left<a.left&&r.push(s)}});let u=(e=>{let{collisionRect:r,droppableRects:s,droppableContainers:n}=e,i=yB(r),a=[];for(let e of n){let{id:r}=e,n=s.get(r);if(n){let s=yB(n),o=Number((i.reduce((e,r,n)=>e+yF(s[n],r),0)/4).toFixed(4));a.push({id:r,data:{droppableContainer:e,value:o}})}}return a.sort(yP)})({active:s,collisionRect:n,droppableRects:i,droppableContainers:r,pointerCoordinates:null}),h=yL(u,"id");if(h===(null==o?void 0:o.id)&&u.length>1&&(h=u[1].id),null!=h){let e=a.get(s.id),r=a.get(h),o=r?i.get(r.id):null,u=null==r?void 0:r.node.current;if(u&&o&&e&&r){var c,d;let s=yK(u).some((e,r)=>l[r]!==e),i=bJ(e,r),a=(c=e,d=r,!!bY(c)&&!!bY(d)&&!!bJ(c,d)&&c.data.current.sortable.index<d.data.current.sortable.index),h=s||!i?{x:0,y:0}:{x:a?n.width-o.width:0,y:a?n.height-o.height:0},f={x:o.left,y:o.top};return h.x&&h.y?f:y_(f,h)}}}};function bJ(e,r){return!!bY(e)&&!!bY(r)&&e.data.current.sortable.containerId===r.data.current.sortable.containerId}function bZ({executor:e,executorMode:r,isOpen:s,onOpenChange:n,onStart:i,onStop:a,onUpdate:o,onDelete:l,onProcessFinished:c}){let d,u,h,f,p,m,g,[x,v]=(0,$.useState)(!1),[_,y]=(0,$.useState)(e.currentProcessId??e.lastProcessId),b=(0,$.useRef)(!1),w=(0,$.useRef)(e.currentProcessId),{attributes:S,listeners:j,setNodeRef:C,transform:k,transition:N,isDragging:D}=function(e){var r,s,n,i;let{animateLayoutChanges:a=bH,attributes:o,disabled:l,data:c,getNewIndex:d=bW,id:u,strategy:h,resizeObserverConfig:f,transition:p=bU}=e,{items:m,containerId:g,activeIndex:x,disabled:v,disableTransforms:_,sortedRects:y,overIndex:b,useDragOverlay:w,strategy:S}=(0,$.useContext)(bO),j=(r=l,s=v,"boolean"==typeof r?{draggable:r,droppable:!1}:{draggable:null!=(n=null==r?void 0:r.draggable)?n:s.draggable,droppable:null!=(i=null==r?void 0:r.droppable)?i:s.droppable}),C=m.indexOf(u),k=(0,$.useMemo)(()=>({sortable:{containerId:g,index:C,items:m},...c}),[g,c,C,m]),N=(0,$.useMemo)(()=>m.slice(m.indexOf(u)),[m,u]),{rect:D,node:R,isOver:A,setNodeRef:T}=function(e){let{data:r,disabled:s=!1,id:n,resizeObserverConfig:i}=e,a=yg("Droppable"),{active:o,dispatch:l,over:c,measureDroppableContainers:d}=(0,$.useContext)(bw),u=(0,$.useRef)({disabled:s}),h=(0,$.useRef)(!1),f=(0,$.useRef)(null),p=(0,$.useRef)(null),{disabled:m,updateMeasurementsFor:g,timeout:x}={...bA,...i},v=yu(null!=g?g:n),_=bc({callback:(0,$.useCallback)(()=>{if(!h.current){h.current=!0;return}null!=p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{d(Array.isArray(v.current)?v.current:[v.current]),p.current=null},x)},[x]),disabled:m||!o}),[y,b]=yf((0,$.useCallback)((e,r)=>{_&&(r&&(_.unobserve(r),h.current=!1),e&&_.observe(e))},[_])),w=yu(r);return(0,$.useEffect)(()=>{_&&y.current&&(_.disconnect(),h.current=!1,_.observe(y.current))},[y,_]),(0,$.useEffect)(()=>(l({type:E.RegisterDroppable,element:{id:n,key:a,disabled:s,node:y,rect:f,data:w}}),()=>l({type:E.UnregisterDroppable,key:a,id:n})),[n]),(0,$.useEffect)(()=>{s!==u.current.disabled&&(l({type:E.SetDroppableDisabled,id:n,key:a,disabled:s}),u.current.disabled=s)},[n,a,s,l]),{active:o,rect:f,isOver:(null==c?void 0:c.id)===n,node:y,over:c,setNodeRef:b}}({id:u,data:k,disabled:j.droppable,resizeObserverConfig:{updateMeasurementsFor:N,...f}}),{active:M,activatorEvent:F,activeNodeRect:P,attributes:I,setNodeRef:B,listeners:L,isDragging:z,over:O,setActivatorNodeRef:W,transform:H}=function(e){let{id:r,data:s,disabled:n=!1,attributes:i}=e,a=yg("Draggable"),{activators:o,activatorEvent:l,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:f}=(0,$.useContext)(bw),{role:p=bR,roleDescription:m="draggable",tabIndex:g=0}=null!=i?i:{},x=(null==c?void 0:c.id)===r,v=(0,$.useContext)(x?bN:bD),[_,y]=yf(),[b,w]=yf(),S=(0,$.useMemo)(()=>o.reduce((e,s)=>{let{eventName:n,handler:i}=s;return e[n]=e=>{i(e,r)},e},{}),[o,r]),j=yu(s);return yc(()=>(h.set(r,{id:r,key:a,node:_,activatorNode:b,data:j}),()=>{let e=h.get(r);e&&e.key===a&&h.delete(r)}),[h,r]),{active:c,activatorEvent:l,activeNodeRect:d,attributes:(0,$.useMemo)(()=>({role:p,tabIndex:g,"aria-disabled":n,"aria-pressed":!!x&&p===bR||void 0,"aria-roledescription":m,"aria-describedby":u.draggable}),[n,p,g,x,m,u.draggable]),isDragging:x,listeners:n?void 0:S,node:_,over:f,setNodeRef:y,setActivatorNodeRef:w,transform:v}}({id:u,data:k,attributes:{...bV,...o},disabled:j.draggable}),U=function(){for(var e=arguments.length,r=Array(e),s=0;s<e;s++)r[s]=arguments[s];return(0,$.useMemo)(()=>e=>{r.forEach(r=>r(e))},r)}(T,B),q=!!M,K=q&&!_&&bP(x)&&bP(b),V=!w&&z,Y=V&&K?H:null,G=K?null!=Y?Y:(null!=h?h:S)({rects:y,activeNodeRect:P,activeIndex:x,overIndex:b,index:C}):null,X=bP(x)&&bP(b)?d({id:u,items:m,activeIndex:x,overIndex:b}):C,J=null==M?void 0:M.id,Z=(0,$.useRef)({activeId:J,items:m,newIndex:X,containerId:g}),Q=m!==Z.current.items,ee=a({active:M,containerId:g,isDragging:z,isSorting:q,id:u,index:C,items:m,newIndex:Z.current.newIndex,previousItems:Z.current.items,previousContainerId:Z.current.containerId,transition:p,wasDragging:null!=Z.current.activeId}),et=function(e){let{disabled:r,index:s,node:n,rect:i}=e,[a,o]=(0,$.useState)(null),l=(0,$.useRef)(s);return yc(()=>{if(!r&&s!==l.current&&n.current){let e=i.current;if(e){let r=yU(n.current,{ignoreTransform:!0}),s={x:e.left-r.left,y:e.top-r.top,scaleX:e.width/r.width,scaleY:e.height/r.height};(s.x||s.y)&&o(s)}}s!==l.current&&(l.current=s)},[r,s,n,i]),(0,$.useEffect)(()=>{a&&o(null)},[a]),a}({disabled:!ee,index:C,node:R,rect:D});return(0,$.useEffect)(()=>{q&&Z.current.newIndex!==X&&(Z.current.newIndex=X),g!==Z.current.containerId&&(Z.current.containerId=g),m!==Z.current.items&&(Z.current.items=m)},[q,X,g,m]),(0,$.useEffect)(()=>{if(J===Z.current.activeId)return;if(null!=J&&null==Z.current.activeId){Z.current.activeId=J;return}let e=setTimeout(()=>{Z.current.activeId=J},50);return()=>clearTimeout(e)},[J]),{active:M,activeIndex:x,attributes:I,data:k,rect:D,index:C,newIndex:X,items:m,isOver:A,isSorting:q,isDragging:z,listeners:L,node:R,overIndex:b,over:O,setNodeRef:U,setActivatorNodeRef:W,setDroppableNodeRef:T,setDraggableNodeRef:B,transform:null!=et?et:G,transition:et||Q&&Z.current.newIndex===C?bK:(!V||yy(F))&&p&&(q||ee)?yw.Transition.toString({...p,property:bq}):void 0}}({id:e.id}),R={transform:yw.Translate.toString(k),transition:N,zIndex:D?50:void 0,position:D?"relative":void 0,opacity:D?1:void 0},{logs:A,status:T,exitCode:M,isPty:F,replayingHistory:P,sendInput:I,sendResize:B}=(d=function(){let e=(0,$.useContext)(_9);if(!e)throw Error("useExecutorLogsStore must be used within ExecutorLogsProvider");return e}(),u=(0,$.useCallback)(e=>{if(!_)return()=>{};d.subscribeProcess(_);let r=d.onProcessChange(_,e);return()=>{r(),d.unsubscribeProcess(_)}},[_,r,d]),h=(0,$.useCallback)(()=>_?d.getProcessState(_):null,[_,d]),f=(0,$.useSyncExternalStore)(u,h,h),p=(0,$.useCallback)(()=>{},[]),m=(0,$.useCallback)(e=>{_&&d.sendInput(_,e)},[_,d]),g=(0,$.useCallback)((e,r)=>{_&&d.sendResize(_,e,r)},[_,d]),{logs:f?.logs??[],status:f?.status??"closed",exitCode:f?.exitCode??null,isPty:f?.isPty??!1,replayingHistory:f?.replayingHistory??!0,clearLogs:p,sendInput:m,sendResize:g});(0,$.useEffect)(()=>(console.log("[diag:mux] ExecutorItem MOUNT",e.id,"localProcessId=",_),()=>console.log("[diag:mux] ExecutorItem UNMOUNT",e.id)),[]),(0,$.useEffect)(()=>{console.log("[diag:mux] localProcessId →",_,"executor=",e.id)},[_,e.id]),(0,$.useEffect)(()=>{let r=w.current;w.current=e.currentProcessId,e.currentProcessId&&e.currentProcessId!==r&&(y(e.currentProcessId),b.current=!1,n(!0))},[e.currentProcessId,n]),(0,$.useEffect)(()=>{e.currentProcessId||e.lastProcessId&&y(r=>r??e.lastProcessId)},[e.currentProcessId,e.lastProcessId]),(0,$.useEffect)(()=>{"closed"!==T||null===M||b.current||(b.current=!0,console.log(`[diag:remote-stop] ${new Date().toISOString()} executor-item marking finished executorId=${e.id} processId=${_} exitCode=${M} — removing from runningProcesses (button → Start)`),c(_))},[T,M,_,c]);let L=async()=>{console.log(`[ExecutorItem] Starting executor ${e.id}`),b.current=!1;let r=await i();console.log(`[ExecutorItem] Got processId: ${r}`),r&&(y(r),n(!0))},z=async()=>{await a(_||void 0)},H=e.isRunning,U=e.isDisabled,q=e.lastStartedAt?new Date(e.lastStartedAt).toLocaleString(void 0,{dateStyle:"short",timeStyle:"short"}):null;return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(pr,{open:s,onOpenChange:n,children:(0,O.jsxs)("div",{ref:C,style:R,className:(0,ey.cn)("border rounded-lg",D&&"shadow-lg bg-background"),children:[(0,O.jsx)(ps,{asChild:!0,children:(0,O.jsxs)("div",{className:"group flex items-center justify-between p-3 cursor-pointer hover:bg-muted/50",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)("button",{type:"button",className:"cursor-grab touch-none text-muted-foreground hover:text-foreground",...S,...j,onClick:e=>e.stopPropagation(),children:(0,O.jsx)(dm,{className:"h-4 w-4"})}),s?(0,O.jsx)(ns,{className:"h-4 w-4"}):(0,O.jsx)(a3,{className:"h-4 w-4"}),(0,O.jsx)("span",{className:(0,ey.cn)("font-medium",U&&"text-muted-foreground line-through"),children:e.name}),U?(0,O.jsxs)(sa,{variant:"outline",className:"text-muted-foreground border-muted-foreground/40 gap-1",children:[(0,O.jsx)(pa,{className:"h-3 w-3"}),"Disabled"]}):(0,O.jsx)(sa,{variant:H?"default":"secondary",className:(0,ey.cn)(H&&"bg-green-600 hover:bg-green-600"),children:H?"Running":null!==M?0===M?"Completed":"Failed":"Stopped"})]}),(0,O.jsxs)("div",{className:"flex items-center gap-2",onClick:e=>e.stopPropagation(),children:[q&&(0,O.jsxs)("span",{className:"text-xs text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity",title:new Date(e.lastStartedAt).toLocaleString(),children:["Last run: ",q]}),H?(0,O.jsxs)(W.Button,{size:"sm",variant:"destructive",onClick:z,className:"w-20 border border-destructive",children:[(0,O.jsx)(lJ,{className:"h-3 w-3 mr-1"}),"Stop"]}):(0,O.jsxs)(W.Button,{size:"sm",onClick:L,disabled:U,title:U?"Executor is disabled":void 0,className:"w-20",children:[(0,O.jsx)(rh,{className:"h-3 w-3 mr-1"}),"Start"]}),(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)(W.Button,{size:"icon",variant:"ghost",className:"h-8 w-8",children:(0,O.jsx)(pi,{className:"h-4 w-4"})})}),(0,O.jsxs)(a7,{align:"end",children:[(0,O.jsxs)(a8,{onClick:()=>v(!0),children:[(0,O.jsx)(rg,{className:"h-4 w-4 mr-2"}),"Edit"]}),(0,O.jsx)(a8,{onClick:()=>o({target:r??"local",disabled:!U}),children:U?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(sJ,{className:"h-4 w-4 mr-2"}),"Enable"]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(pa,{className:"h-4 w-4 mr-2"}),"Disable"]})}),(0,O.jsxs)(a8,{onClick:l,className:"text-destructive",children:[(0,O.jsx)(rc,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})]})}),(0,O.jsx)(pn,{children:(0,O.jsxs)("div",{className:"px-3 pb-3",children:[(0,O.jsx)("div",{className:"text-xs text-muted-foreground mb-2 font-mono",children:"prompt"===e.executor_type?`${e.prompt_provider??"claude"} → ${e.command}`:`$ ${e.command}`}),(0,O.jsx)(_4,{logs:A,isPty:F,onInput:I,onResize:B,muteInput:P,processId:_,executorId:e.id,target:r??"local",status:T,exitCode:M})]})})]})}),(0,O.jsx)(_7,{open:x,onOpenChange:v,executor:e,onSubmit:async e=>{await o(e)}})]})}let bQ=(0,$.createContext)(null);function b0({projectId:e,children:r}){let s=sg(e,{withStatus:!0});return(0,O.jsx)(bQ.Provider,{value:s,children:r})}function b1(){let e=(0,$.useContext)(bQ);if(!e)throw Error("useProjectRemotesContext must be used within a ProjectRemotesProvider");return e}let b2=e=>{let{droppableContainers:r,pointerCoordinates:s}=e;if(!s)return(e=>{let{collisionRect:r,droppableRects:s,droppableContainers:n}=e,i=yz(r,r.left,r.top),a=[];for(let e of n){let{id:r}=e,n=s.get(r);if(n){let s=yF(yz(n),i);a.push({id:r,data:{droppableContainer:e,value:s}})}}return a.sort(yP)})(e);let n=[];for(let e of r){let r=e.rect.current;if(!r)continue;let i=r.top,a=r.top+52;s.x>=r.left&&s.x<=r.right&&s.y>=i&&s.y<=a&&n.push({id:e.id,data:{droppableContainer:e}})}if(n.length>0)return n;let i=null;for(let e of r){let r=e.rect.current;if(!r)continue;let n=r.top+26,a=r.left+r.width/2,o=Math.sqrt(Math.pow(s.x-a,2)+Math.pow(s.y-n,2));(!i||o<i.distance)&&(i={id:e.id,distance:o,data:{droppableContainer:e}})}return i?[{id:i.id,data:i.data}]:[]};function b5({projectId:e,selectedBranch:r,project:s,onExecutorModeChange:n}){let[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(new Set),{remotes:c}=b1(),d=[];for(let e of(s?.path&&d.push({id:"local",label:"Local",icon:oc}),c))d.push({id:e.remote_server_id,label:e.server_name,icon:sx(e)});let{activeGroup:u,loading:h,createGroup:f}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(null),[o,l]=(0,$.useState)(!0),c=r??"",d=(0,$.useCallback)(async()=>{if(!e){n([]),a(null),l(!1);return}try{let[r,s]=await Promise.all([rv.api.getExecutorGroups(e),rv.api.getExecutorGroupByBranch(e,c)]);n(r),a(s)}catch(e){console.error("Failed to fetch executor groups:",e)}finally{l(!1)}},[e,c]);(0,$.useEffect)(()=>{l(!0),d()},[d]);let u=(0,$.useCallback)(async r=>{if(!e)return null;try{let s=await rv.api.createExecutorGroup(e,{name:r,branch:c});return n(e=>[...e,s]),a(s),s}catch(e){return console.error("Failed to create executor group:",e),null}},[e,c]);return{groups:s,activeGroup:i,loading:o,createGroup:u,updateGroup:(0,$.useCallback)(async(e,r)=>{try{let s=await rv.api.updateExecutorGroup(e,r);return n(r=>r.map(r=>r.id===e?s:r)),a(r=>r?.id===e?s:r),s}catch(e){return console.error("Failed to update executor group:",e),null}},[]),deleteGroup:(0,$.useCallback)(async e=>{try{await rv.api.deleteExecutorGroup(e),n(r=>r.filter(r=>r.id!==e)),a(r=>r?.id===e?null:r)}catch(e){console.error("Failed to delete executor group:",e)}},[]),refetch:d}}(e,r),{executors:p,loading:m,createExecutor:g,updateExecutor:x,deleteExecutor:v,startExecutor:_,stopExecutor:y,markProcessFinished:b,reorderExecutors:w}=function(e,r,s){let[n,i]=(0,$.useState)([]),[a,o]=(0,$.useState)(new Map),[l,c]=(0,$.useState)(new Map),[d,u]=(0,$.useState)(!0),h=(0,$.useCallback)(async()=>{if(!e||!r){i([]),u(!1);return}try{let s=await rv.api.getExecutors(e,r);i(s)}catch(e){console.error("Failed to fetch executors:",e)}finally{u(!1)}},[e,r]),f=(0,$.useCallback)(async()=>{try{let e=await rv.api.getRunningProcesses();console.log(`[useExecutors] fetchRunningProcesses: ${e.length} running`,e.map(e=>`${e.executor_id}/${e.id}/${e.target??"local"}`));let{runningProcesses:r,lastStartedProcess:s}=function(e){let r=new Map,s=new Map;for(let n of e){let e={processId:n.id,target:n.target??"local"},i=r.get(n.executor_id);i?i.push(e):r.set(n.executor_id,[e]),s.set(n.executor_id,e)}return{runningProcesses:r,lastStartedProcess:s}}(e);o(r),c(e=>{let n=function(e,r){let s=new Map;for(let[n,i]of e)r.get(n)?.some(e=>e.processId===i.processId&&e.target===i.target)&&s.set(n,i);return s}(e,r);for(let[e,r]of s)n.set(e,r);return n})}catch(e){console.error("Failed to fetch running processes:",e)}},[]);(0,$.useEffect)(()=>{h()},[h]),(0,$.useEffect)(()=>{f()},[f]),(0,$.useEffect)(()=>{e&&f()},[e,f]),(0,$.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&f()};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[f]);let p=(0,$.useRef)(new Set);(0,$.useEffect)(()=>{p.current=new Set(n.map(e=>e.id))},[n]),(0,sC.useGlobalEventStream)(r=>{if(("executor:started"===r.type||"executor:stopped"===r.type)&&console.log(`[useExecutors] SSE received: ${r.type} executor=${r.executorId} process=${r.processId} target=${r.target??"local"} project=${r.projectId}`),!e||r.projectId!==e){("executor:started"===r.type||"executor:stopped"===r.type)&&console.log(`[useExecutors] SSE filtered: projectId mismatch (event=${r.projectId}, hook=${e})`);return}if(!p.current.has(r.executorId)){("executor:started"===r.type||"executor:stopped"===r.type)&&console.log(`[useExecutors] SSE filtered: executorId ${r.executorId} not in current group (known: ${Array.from(p.current).join(",")})`);return}"executor:started"===r.type?(console.log("[useExecutors] Processing executor:started, adding to runningProcesses"),o(e=>{let s=e.get(r.executorId)??[];if(s.some(e=>e.processId===r.processId))return e;let n=new Map(e);return n.set(r.executorId,[...s,{processId:r.processId,target:r.target??"local"}]),n}),c(e=>{let s=new Map(e);return s.set(r.executorId,{processId:r.processId,target:r.target??"local"}),s}),i(e=>e.map(e=>{if(e.id!==r.executorId)return e;let s=r.target??"local";return{...e,last_runs:{...e.last_runs??{},[s]:{started_at:new Date().toISOString(),process_id:r.processId}}}}))):"executor:stopped"===r.type&&(console.log("[useExecutors] Processing executor:stopped, removing from runningProcesses"),console.log(`[diag:remote-stop] ${new Date().toISOString()} SSE executor:stopped executor=${r.executorId} process=${r.processId} target=${r.target??"local"} — flips button via SSE (NOT the mux finished path)`),o(e=>{let s=e.get(r.executorId);if(!s)return e;let n=s.filter(e=>e.processId!==r.processId),i=new Map(e);return 0===n.length?i.delete(r.executorId):i.set(r.executorId,n),i}),c(e=>{let s=e.get(r.executorId);if(!s||s.processId!==r.processId)return e;let n=new Map(e);return n.delete(r.executorId),n}))});let m=(0,$.useCallback)(async s=>{if(!e||!r)return null;try{let n=await rv.api.createExecutor(e,{...s,group_id:r});return i(e=>[...e,n]),n}catch(e){return console.error("Failed to create executor:",e),null}},[e,r]),g=(0,$.useCallback)(async(e,r)=>{try{let s=await rv.api.updateExecutor(e,r);return i(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update executor:",e),_Z.toast.error("Failed to update executor",{description:e instanceof Error?e.message:void 0}),null}},[]),x=(0,$.useCallback)(async e=>{try{await rv.api.deleteExecutor(e),i(r=>r.filter(r=>r.id!==e))}catch(e){console.error("Failed to delete executor:",e)}},[]),v=(0,$.useCallback)(async(e,r)=>{try{let n=await rv.api.startExecutor(e,r,s),a=s??"local";return o(r=>{let s=r.get(e)??[],i=new Map(r);return i.set(e,[...s,{processId:n,target:a}]),i}),c(r=>{let s=new Map(r);return s.set(e,{processId:n,target:a}),s}),i(r=>r.map(r=>r.id!==e?r:{...r,last_runs:{...r.last_runs??{},[a]:{started_at:new Date().toISOString(),process_id:n}}})),n}catch(e){return console.error("Failed to start executor:",e),null}},[s]),_=(0,$.useCallback)(async(e,r)=>{let n=a.get(e),i=n?.find(e=>e.target===(s??"local")),l=r||i?.processId;if(l){try{await rv.api.stopProcess(l)}catch(e){console.error("Failed to stop executor:",e)}o(r=>{let s=r.get(e);if(!s)return r;let n=s.filter(e=>e.processId!==l),i=new Map(r);return 0===n.length?i.delete(e):i.set(e,n),i}),c(r=>{let s=r.get(e);if(!s||s.processId!==l)return r;let n=new Map(r);return n.delete(e),n})}},[a,s]),y=(0,$.useCallback)((e,r)=>{o(s=>{let n=s.get(e);if(!n)return s;if(r){let i=n.filter(e=>e.processId!==r);if(i.length===n.length)return s;let a=new Map(s);return 0===i.length?a.delete(e):a.set(e,i),a}let i=new Map(s);return i.delete(e),i}),c(s=>{if(!r){if(!s.has(e))return s;let r=new Map(s);return r.delete(e),r}let n=s.get(e);if(!n||n.processId!==r)return s;let i=new Map(s);return i.delete(e),i})},[]),b=(0,$.useCallback)(async s=>{if(e&&r){i(s.map(e=>n.find(r=>r.id===e)).filter(e=>void 0!==e));try{await rv.api.reorderExecutors(e,s,r)}catch(e){console.error("Failed to reorder executors:",e),i(n)}}},[e,r,n]);return{executors:n.map(e=>{let r=a.get(e.id),n=s??"local",i=r?.find(e=>e.target===n),o=l.get(e.id),c=o?.target===n?o:void 0,d=e.last_runs?.[n];return{...e,currentProcessId:i?.processId??c?.processId??null,isRunning:!!i,lastProcessId:d?.process_id??null,lastStartedAt:d?.started_at??null,isDisabled:e.disabled_targets.includes(n)}}),loading:d,createExecutor:m,updateExecutor:g,deleteExecutor:x,startExecutor:v,stopExecutor:_,markProcessFinished:y,reorderExecutors:b,refetch:h}}(e,u?.id,s?.executor_mode),S=function(){for(var e=arguments.length,r=Array(e),s=0;s<e;s++)r[s]=arguments[s];return(0,$.useMemo)(()=>[...r].filter(e=>null!=e),[...r])}(yT(bi,{activationConstraint:{distance:8}}),yT(be,{coordinateGetter:bX}));return e?(0,O.jsx)(ye,{projectId:e,children:(0,O.jsxs)("div",{className:"h-full flex flex-col",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border/60 h-10",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsxs)("h2",{className:"text-xs font-semibold flex items-center gap-2 text-foreground",children:[(0,O.jsx)(ol,{className:"h-3.5 w-3.5"}),u?u.name:"Executors"]}),d.length>1&&n&&(0,O.jsx)(oo,{targets:d,activeTarget:s?.executor_mode??"local",onTargetChange:n})]}),u&&(0,O.jsxs)(W.Button,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>a(!0),children:[(0,O.jsx)(eS,{className:"h-3 w-3 mr-1"}),"Add"]})]}),(0,O.jsx)("div",{className:"flex-1 overflow-y-auto",children:(0,O.jsx)("div",{className:"p-4 space-y-3",children:h||m?(0,O.jsx)("div",{className:"text-center text-muted-foreground py-8",children:"Loading executors..."}):u?0===p.length?(0,O.jsxs)("div",{className:"text-center text-muted-foreground py-8",children:[(0,O.jsx)("p",{children:"No executors configured"}),(0,O.jsx)("p",{className:"text-sm mt-1",children:'Add an executor to run commands like "npm run dev"'})]}):(0,O.jsx)(bE,{sensors:S,collisionDetection:b2,onDragEnd:e=>{let{active:r,over:s}=e;if(s&&r.id!==s.id){let e=p.findIndex(e=>e.id===r.id),n=p.findIndex(e=>e.id===s.id),i=[...p],[a]=i.splice(e,1);i.splice(n,0,a),w(i.map(e=>e.id))}},children:(0,O.jsx)(b$,{items:p.map(e=>e.id),strategy:bL,children:p.map(e=>(0,O.jsx)(bZ,{executor:e,executorMode:s?.executor_mode??"local",isOpen:o.has(e.id),onOpenChange:r=>l(s=>{let n=new Set(s);return r?n.add(e.id):n.delete(e.id),n}),onStart:()=>_(e.id,r),onStop:r=>y(e.id,r||e.currentProcessId||void 0),onUpdate:r=>x(e.id,r),onDelete:()=>v(e.id),onProcessFinished:r=>b(e.id,r)},`${e.id}-${s?.executor_mode??"local"}`))})}):(0,O.jsxs)("div",{className:"text-center text-muted-foreground py-8",children:[(0,O.jsx)("p",{children:"No executor group for this branch"}),(0,O.jsx)("p",{className:"text-sm mt-1 mb-4",children:"Create a group to start adding executors"}),(0,O.jsxs)(W.Button,{size:"sm",onClick:()=>f(r?`Executors (${r})`:"Default"),children:[(0,O.jsx)(oG,{className:"h-4 w-4 mr-1"}),"Create Group"]})]})})}),(0,O.jsx)(_7,{open:i,onOpenChange:a,onSubmit:async e=>{await g(e)}})]})},`${e??"none"}-${s?.executor_mode??"local"}`):(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(ol,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to manage executors"})]})})}let b3=(0,ew.default)("chevrons-up-down",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);function b4({line:e}){let r="add"===e.type?"+":"delete"===e.type?"-":" ",s="add"===e.type,n="delete"===e.type,i=s?"bg-emerald-500/[0.07]":n?"bg-rose-500/[0.07]":"",a=s?"bg-emerald-500/[0.10]":n?"bg-rose-500/[0.10]":"bg-secondary",o=s?"text-emerald-600":n?"text-rose-600":"text-muted-foreground/70";return(0,O.jsxs)("div",{className:"flex font-mono text-[11.5px] leading-[1.55]",children:[(0,O.jsx)("span",{className:(0,ey.cn)("w-9 flex-shrink-0 text-right pr-2 select-none border-r border-border/60",a,o),children:e.oldLineNo??""}),(0,O.jsx)("span",{className:(0,ey.cn)("w-9 flex-shrink-0 text-right pr-2 select-none border-r border-border/60",a,o),children:e.newLineNo??""}),(0,O.jsx)("span",{className:(0,ey.cn)("w-5 flex-shrink-0 text-center select-none",i,o),children:r}),(0,O.jsx)("span",{className:(0,ey.cn)("whitespace-pre-wrap break-all pr-4 flex-1 min-w-0 pl-2",i,(s||n)&&"text-foreground"),children:e.content})]})}let b6={modified:"bg-yellow-500/20 text-yellow-500",added:"bg-green-500/20 text-green-500",deleted:"bg-red-500/20 text-red-500",renamed:"bg-blue-500/20 text-blue-500"},b7={modified:"Modified",added:"Added",deleted:"Deleted",renamed:"Renamed"};function b8({file:e,defaultOpen:r=!0}){let[s,n]=(0,$.useState)(r);return(0,O.jsxs)(pr,{open:s,onOpenChange:n,className:"border border-border rounded-lg overflow-hidden",children:[(0,O.jsxs)(ps,{className:"flex items-center gap-2 px-4 py-2 bg-secondary border-b border-border w-full cursor-pointer hover:bg-muted transition-colors",children:[s?(0,O.jsx)(ns,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,O.jsx)(a3,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,O.jsx)("span",{className:"font-mono text-[11.5px] flex-1 min-w-0 truncate text-left text-foreground font-medium",children:e.oldPath&&"renamed"===e.status?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("span",{className:"text-muted-foreground font-normal",children:e.oldPath}),(0,O.jsx)("span",{className:"mx-2 text-muted-foreground",children:"→"}),e.path]}):e.path}),(0,O.jsx)(sa,{variant:"secondary",className:b6[e.status],children:b7[e.status]})]}),(0,O.jsx)(pn,{children:(0,O.jsx)("div",{children:e.hunks.map((e,r)=>(0,O.jsxs)("div",{children:[(0,O.jsxs)("div",{className:"px-4 py-0.5 bg-accent text-accent-foreground text-[11px] font-mono font-medium sticky top-0",children:["@@ -",e.oldStart,",",e.oldLines," +",e.newStart,",",e.newLines," @@"]}),e.lines.map((e,r)=>(0,O.jsx)(b4,{line:e},r))]},r))})})]})}let b9=(0,ew.default)("git-commit-horizontal",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]]),we="__head__",wt="__compare__";function wr({commits:e,selectedCommit:r,onSelectCommit:s,compareTarget:n,compareSelected:i,onSelectCompare:a,loading:o,disabled:l}){return(0,O.jsxs)(hw,{value:i?wt:r??we,onValueChange:e=>{e===wt?a?.():s(e===we?null:e)},disabled:l||o,children:[(0,O.jsxs)(hj,{size:"sm",className:"w-[200px]",children:[(0,O.jsx)(b9,{className:"h-3.5 w-3.5 shrink-0"}),(0,O.jsx)(hS,{placeholder:"Select commit..."})]}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:we,children:"HEAD (uncommitted)"}),n&&(0,O.jsxs)(hk,{value:wt,children:["vs ",(0,O.jsx)("span",{className:"font-mono text-xs",children:n})]}),e.map(e=>(0,O.jsxs)(hk,{value:e.hash,children:[(0,O.jsx)("span",{className:"font-mono text-xs",children:e.shortHash})," ",(0,O.jsx)("span",{className:"truncate",children:e.message.length>40?e.message.slice(0,40)+"...":e.message})]},e.hash))]})]})}function ws({projectId:e,selectedBranch:r,onMergeRequest:s,project:n,mergeTarget:i,compareRequestNonce:a}){let[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(a),[f,p]=(0,$.useState)(r),m=void 0!==a&&a!==u;m&&(h(a),d(!0),l(null)),r!==f&&(p(r),l(null),m||d(!1));let{remotes:g}=b1(),x=[];for(let e of(n?.path&&x.push({id:"local",label:"Local",icon:oc}),g))x.push({id:e.remote_server_id,label:e.server_name,icon:sp});let v=n?.path?"local":g.length>0?g[0].remote_server_id:"local",[_,y]=(0,$.useState)(v),[b,w]=(0,$.useState)(!0),[S,j]=(0,$.useState)(0),C="local"===_?n?.path?"local":void 0:"remote",{diff:k,loading:N,error:E,refresh:D}=function(e,r,s,n,i){let[a,o]=(0,$.useState)(null),[l,c]=(0,$.useState)(!1),[d,u]=(0,$.useState)(null),h=(0,$.useCallback)(async()=>{if(!e)return void o(null);c(!0),u(null);try{let a=await rv.api.getDiff(e,r,s,n,i);o(a)}catch(e){u(e instanceof Error?e.message:"Failed to load diff"),o(null)}finally{c(!1)}},[e,r,s,n,i]);return{diff:a,loading:l,error:d,refresh:h}}(e,r,o,C,c&&i?i:null),{commits:R,loading:A,refetch:T}=function(e,r,s,n){let[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)(!1);return{commits:i,loading:o,refetch:(0,$.useCallback)(async()=>{if(!e)return void a([]);l(!0);try{let i=await rv.api.getCommits(e,r,s,n);a(i)}catch{a([])}finally{l(!1)}},[e,r,s,n])}}(e,r,void 0,C);if((0,$.useEffect)(()=>{D()},[D]),(0,$.useEffect)(()=>{T()},[T]),(0,$.useEffect)(()=>{y(v)},[e,v]),!e)return(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(sU,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to view changes"})]})});let M=k?.files.length??0;return(0,O.jsxs)("div",{className:"h-full flex flex-col",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border/60 h-10",children:[(0,O.jsx)("div",{className:"flex items-center gap-4",children:M>0&&(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("span",{className:"text-xs text-muted-foreground",children:[M," file",1!==M?"s":""," changed"]}),(0,O.jsxs)(W.Button,{size:"sm",variant:"ghost",onClick:()=>{w(e=>!e),j(e=>e+1)},title:b?"Collapse all":"Expand all",children:[(0,O.jsx)(b3,{className:"h-4 w-4 mr-1"}),b?"Collapse all":"Expand all"]})]})}),(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[x.length>1&&(0,O.jsx)(oo,{targets:x,activeTarget:_,onTargetChange:y,disabled:N}),(0,O.jsx)("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Commit:"}),(0,O.jsx)(wr,{commits:R,selectedCommit:o,onSelectCommit:e=>{d(!1),l(e)},compareTarget:i,compareSelected:c,onSelectCompare:()=>{d(!0),l(null)},loading:A,disabled:N}),(0,O.jsxs)(W.Button,{size:"sm",variant:"outline",onClick:s,disabled:N||0===M,children:[(0,O.jsx)(dr,{className:"h-4 w-4 mr-1"}),"Merge"]}),(0,O.jsxs)(W.Button,{size:"sm",variant:"outline",onClick:D,disabled:N,children:[(0,O.jsx)(fK,{className:`h-4 w-4 mr-1 ${N?"animate-spin":""}`}),"Refresh"]})]})]}),(0,O.jsx)(oK,{className:"flex-1 overflow-hidden",children:(0,O.jsx)("div",{className:"p-4 space-y-4",children:N&&!k?(0,O.jsx)("div",{className:"text-center text-muted-foreground py-8",children:"Loading changes..."}):E?(0,O.jsx)("div",{className:"text-center text-red-400 py-8",children:E}):0===M?(0,O.jsx)("div",{className:"text-center text-muted-foreground py-8",children:(0,O.jsx)("p",{children:c&&i?`No changes vs ${i}`:o?"No changes in this commit":"No uncommitted changes"})}):k?.files.map((e,r)=>(0,O.jsx)(b8,{file:e,defaultOpen:b},`${r}-${S}`))})})]})}function wn({terminalId:e,onExit:r}){let{logs:s,sendInput:n,sendResize:i,exitCode:a,replayingHistory:o}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)("closed"),[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(!0),f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=(0,$.useRef)(0),g=(0,$.useRef)(null),x=(0,$.useRef)(!1),v=(0,$.useCallback)(()=>{n([]),l(null),d(!1)},[]),_=(0,$.useCallback)(e=>{f.current?.readyState===WebSocket.OPEN&&f.current.send(JSON.stringify({type:"input",data:e}))},[]),y=(0,$.useCallback)((e,r)=>{f.current?.readyState===WebSocket.OPEN?f.current.send(JSON.stringify({type:"resize",cols:e,rows:r})):p.current={cols:e,rows:r}},[]);return(0,$.useEffect)(()=>{if(!e)return;n([]),l(null),d(!1),x.current=!1,m.current=0;let r=!1;return function s(){r||x.current||(0,rv.getFreshToken)().then(()=>{r||x.current||function(){if(r||x.current)return;a("connecting");let i=(0,rv.getWebSocketUrl)(`/api/executor-processes/${e}/logs`);console.log(`[useExecutorLogs] Connecting to WebSocket: ${i}`);let o=new WebSocket(i);f.current=o;let c=!1,u=!1;o.onopen=()=>{if(!r&&(console.log("[useExecutorLogs] WebSocket connected"),a("connected"),n([]),p.current)){let{cols:e,rows:r}=p.current;o.send(JSON.stringify({type:"resize",cols:e,rows:r})),p.current=null}},o.onmessage=e=>{if(!r)try{let r=JSON.parse(e.data);if("init"===r.type)d(r.isPty),h(!0),console.log("[useExecutorLogs] init received, setReplayingHistory(true)");else if("history_end"===r.type)u=!0,h(!1),console.log("[useExecutorLogs] history_end received, setReplayingHistory(false)");else if("finished"===r.type)x.current=!0,l(r.exitCode),a("closed");else if("error"===r.type)x.current=!0,a("error");else{u&&(c=!0,m.current=0);let e="stdout"===r.type||"stderr"===r.type||"pty"===r.type?{...r,historical:!u}:r;n(r=>[...r,e])}}catch(e){console.error("Failed to parse WebSocket message:",e)}},o.onerror=e=>{r||console.error("[useExecutorLogs] WebSocket error:",e)},o.onclose=e=>{if(console.log("[useExecutorLogs] WebSocket closed:",e.code,e.reason),f.current=null,x.current||r)return void a("closed");if(u&&!c){console.log(`[useExecutorLogs] Server closed after history with no live data — treating as terminal`),x.current=!0,a("closed");return}if(m.current<8){let e=m.current,n=Math.min(15e3,1e3*Math.pow(2,e)),i=n*Math.random()*.25,o=n+i;console.log(`[useExecutorLogs] Scheduling reconnect in ${Math.round(o)}ms (attempt ${e+1}/8)`),a("connecting"),m.current=e+1,g.current=setTimeout(()=>{g.current=null,r||s()},o)}else console.log("[useExecutorLogs] Max reconnect attempts reached"),a("error")}}()})}(),()=>{r=!0,g.current&&(clearTimeout(g.current),g.current=null),f.current&&(f.current.close(),f.current=null)}},[e,void 0]),{logs:s,status:i,exitCode:o,isPty:c,replayingHistory:u,clearLogs:v,sendInput:_,sendResize:y}}(e);return(0,$.useEffect)(()=>{null!==a&&r(e)},[a,r,e]),(0,O.jsx)(_4,{logs:s,isPty:!0,className:"h-full rounded-none border-0",onInput:n,onResize:i,muteInput:o})}function wi({projectId:e,selectedBranch:r,project:s}){let{terminals:n,activeTerminalId:i,createTerminal:a,closeTerminal:o,setActiveTerminal:l,removeTerminal:c}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(null);(0,$.useEffect)(()=>{if(!e){n([]),a(null);return}rv.api.getTerminals(e,r).then(e=>{n(e),a(e.length>0?e[0].id:null)})},[e,r]);let o=(0,$.useCallback)(async(s,i)=>{if(e)try{let o=await rv.api.createTerminal(e,r,s,i);n(e=>[...e,o]),a(o.id)}catch(e){console.error("[useTerminals] Failed to create terminal:",e)}},[e,r]),l=(0,$.useCallback)(async e=>{await rv.api.closeTerminal(e),n(r=>{let s=r.filter(r=>r.id!==e);return a(r=>r===e?s.length>0?s[s.length-1].id:null:r),s})},[]);return{terminals:s,activeTerminalId:i,createTerminal:o,closeTerminal:l,setActiveTerminal:(0,$.useCallback)(e=>{a(e)},[]),removeTerminal:(0,$.useCallback)(e=>{n(r=>{let s=r.filter(r=>r.id!==e);return a(r=>r===e?s.length>0?s[s.length-1].id:null:r),s})},[])}}(e,r),{remotes:d}=b1(),[u,h]=(0,$.useState)(!1),f=(0,$.useRef)(null),p=!!s?.path,m=d.length>0,g=p&&m||d.length>1,x=!p&&m||g&&s?.executor_mode!=="local"?"remote":"local",v=(0,$.useCallback)(()=>{a(x)},[a,x]),_=(0,$.useCallback)((e,r)=>{h(!1),a(e,r)},[a]);(0,$.useEffect)(()=>{if(u)return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e);function e(e){f.current&&!f.current.contains(e.target)&&h(!1)}},[u]);let y=(0,$.useCallback)(e=>{c(e)},[c]);return e?(0,O.jsxs)("div",{className:"h-full flex flex-col",children:[(0,O.jsxs)("div",{className:"flex items-center h-10 border-b border-border/60 px-2 gap-1 shrink-0 bg-muted/20",children:[(0,O.jsx)("div",{className:"flex-1 min-w-0 flex items-center gap-1 overflow-hidden",children:n.map(e=>{let r="remote"===e.location||e.id.startsWith("remote-"),s=g?r?sp:oc:ol,n=i===e.id;return(0,O.jsxs)("button",{onClick:()=>l(e.id),title:e.name,className:(0,ey.cn)("group flex items-center gap-1.5 px-2 py-1 rounded-md text-xs transition-all duration-150 border flex-1 min-w-0 basis-0 max-w-[180px]",n?"bg-background text-foreground border-border shadow-sm":"text-muted-foreground hover:text-foreground bg-muted/40 hover:bg-background/60 border-border/30 hover:border-border/60"),children:[(0,O.jsx)(s,{className:"h-3 w-3 shrink-0"}),(0,O.jsx)("span",{className:"truncate flex-1 text-left",children:e.name}),(0,O.jsx)("span",{role:"button",onClick:r=>{r.stopPropagation(),o(e.id)},className:(0,ey.cn)("shrink-0 rounded-sm p-0.5 hover:bg-destructive/10 hover:text-destructive",n?"opacity-80 hover:opacity-100":"opacity-0 group-hover:opacity-80 hover:!opacity-100"),children:(0,O.jsx)(t7,{className:"h-3 w-3"})})]},e.id)})}),(0,O.jsxs)("div",{className:"relative shrink-0",ref:f,children:[(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:g?()=>h(e=>!e):v,children:(0,O.jsx)(eS,{className:"h-3.5 w-3.5"})}),g&&u&&(0,O.jsxs)("div",{className:"absolute right-0 top-full mt-1 z-50 min-w-[160px] rounded-md border bg-popover p-1 shadow-md",children:[p&&(0,O.jsxs)("button",{className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground transition-colors",onClick:()=>_("local"),children:[(0,O.jsx)(oc,{className:"h-3.5 w-3.5"}),"Local Terminal"]}),d.map(e=>(0,O.jsxs)("button",{className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground transition-colors",onClick:()=>_("remote",e.remote_server_id),children:[(0,O.jsx)(sp,{className:"h-3.5 w-3.5"}),e.server_name," Terminal"]},e.remote_server_id))]})]})]}),(0,O.jsx)("div",{className:"flex-1 overflow-hidden bg-zinc-950",children:i?(0,O.jsx)(wn,{terminalId:i,onExit:y},i):(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,O.jsx)(ol,{className:"h-10 w-10 text-muted-foreground/70"})})})]}):(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(ol,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to use the terminal"})]})})}let wa=(0,$.createContext)(null),wo=({className:e,children:r,defaultUrl:s="",onUrlChange:n,...i})=>{let[a,o]=(0,$.useState)(s),[l,c]=(0,$.useState)(!1);return(0,O.jsx)(wa.Provider,{value:{url:a,setUrl:e=>{o(e),n?.(e)},consoleOpen:l,setConsoleOpen:c},children:(0,O.jsx)("div",{className:(0,ey.cn)("flex size-full flex-col bg-card",e),...i,children:r})})},wl=({className:e,children:r,...s})=>(0,O.jsx)("div",{className:(0,ey.cn)("flex items-center gap-1 border-b p-2 h-14",e),...s,children:r}),wc=({onClick:e,disabled:r,tooltip:s,children:n,...i})=>(0,O.jsx)(cb,{children:(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsx)(W.Button,{className:"h-8 w-8 p-0 hover:text-foreground",disabled:r,onClick:e,size:"sm",variant:"ghost",...i,children:n})}),(0,O.jsx)(cj,{children:(0,O.jsx)("p",{children:s})})]})}),wd=({value:e,onChange:r,onKeyDown:s,...n})=>{let{url:i,setUrl:a}=(()=>{let e=(0,$.useContext)(wa);if(!e)throw Error("WebPreview components must be used within a WebPreview");return e})(),[o,l]=(0,$.useState)(i);return(0,$.useEffect)(()=>{l(i)},[i]),(0,O.jsx)(ro,{className:"h-8 flex-1 text-sm",onChange:r??(e=>{l(e.target.value),r?.(e)}),onKeyDown:e=>{"Enter"===e.key&&a(e.target.value),s?.(e)},placeholder:"Enter URL...",value:e??o,...n})};var wu=e.i(254824);function wh({projectId:e}){let r=(0,$.useRef)(null),s=(0,$.useRef)(null),{addFrame:n,updateFrameUrl:i,refreshFrame:a,hasFrame:o,claimFrame:l,getFrameUrl:c}=(0,wu.useBrowserFrames)(),d=e?c(e):void 0;(0,$.useEffect)(()=>{if(e&&d&&r.current){let n=setTimeout(()=>{r.current&&(s.current?.(),s.current=l(e,r.current))},50);return()=>{clearTimeout(n),s.current?.(),s.current=null}}return()=>{s.current?.(),s.current=null}},[e,d,l]);let u=(0,$.useCallback)(()=>{e&&a(e)},[e,a]),h=(0,$.useCallback)(()=>{d&&window.open(d,"_blank")},[d]),f=(0,$.useCallback)(r=>{e&&(o(e)?i(e,r):n(e,r))},[e,o,i,n]);return(0,O.jsx)("div",{className:"h-full flex flex-col",children:(0,O.jsxs)(wo,{defaultUrl:d??"",onUrlChange:f,className:"h-full",children:[(0,O.jsxs)(wl,{className:"h-10 p-1.5 gap-0.5",children:[(0,O.jsx)(wc,{tooltip:"Refresh",onClick:u,disabled:!d,children:(0,O.jsx)(fK,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(wc,{tooltip:"Open in browser",onClick:h,disabled:!d,children:(0,O.jsx)(s7,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(wd,{className:"h-7 text-xs"})]}),d?(0,O.jsx)("div",{ref:r,className:"flex-1 bg-white"}):(0,O.jsx)("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:(0,O.jsxs)("div",{className:"flex flex-col items-center gap-2",children:[(0,O.jsx)(ry,{className:"h-8 w-8 opacity-40"}),(0,O.jsx)("p",{className:"text-sm",children:"Enter a URL above to preview"})]})})]})})}let wf=(0,ew.default)("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),wp=(0,ew.default)("eye-off",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),wm=(0,ew.default)("panel-left-close",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]),wg=(0,ew.default)("panel-left-open",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]),wx=(0,ew.default)("arrow-right",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);function wv({className:e,...r}){return(0,O.jsx)("div",{"data-slot":"input-group",role:"group",className:(0,ey.cn)("group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-xs transition-[color,box-shadow] outline-none","h-9 min-w-0 has-[textarea]:h-auto","has-[>[data-align=inline-start]]:[&>input]:pl-2","has-[>[data-align=inline-end]]:[&>input]:pr-2","has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3","has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3","has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:ring-[3px]","has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",e),...r})}let w_=(0,sn.cva)("text-muted-foreground flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium select-none [&>svg:not([class*='size-'])]:size-4 [&>kbd]:rounded-[calc(var(--radius)-5px)] group-data-[disabled=true]/input-group:opacity-50",{variants:{align:{"inline-start":"order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]","inline-end":"order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]","block-start":"order-first w-full justify-start px-3 pt-3 [.border-b]:pb-3 group-has-[>input]/input-group:pt-2.5","block-end":"order-last w-full justify-start px-3 pb-3 [.border-t]:pt-3 group-has-[>input]/input-group:pb-2.5"}},defaultVariants:{align:"inline-start"}});function wy({className:e,align:r="inline-start",...s}){return(0,O.jsx)("div",{role:"group","data-slot":"input-group-addon","data-align":r,className:(0,ey.cn)(w_({align:r}),e),onClick:e=>{e.target.closest("button")||e.currentTarget.parentElement?.querySelector("input")?.focus()},...s})}let wb=(0,sn.cva)("text-sm shadow-none flex gap-2 items-center",{variants:{size:{xs:"h-6 gap-1 px-2 rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-3.5 has-[>svg]:px-2",sm:"h-8 px-2.5 gap-1.5 rounded-md has-[>svg]:px-2.5","icon-xs":"size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0","icon-sm":"size-8 p-0 has-[>svg]:p-0"}},defaultVariants:{size:"xs"}});function ww({className:e,type:r="button",variant:s="ghost",size:n="xs",...i}){return(0,O.jsx)(W.Button,{type:r,"data-size":n,variant:s,className:(0,ey.cn)(wb({size:n}),e),...i})}function wS({className:e,...r}){return(0,O.jsx)(ro,{"data-slot":"input-group-control",className:(0,ey.cn)("flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",e),...r})}function wj({className:e,...r}){return(0,O.jsx)(rl,{"data-slot":"input-group-control",className:(0,ey.cn)("flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",e),...r})}var wC=/[\\\/_+.#"@\[\(\{&]/,wk=/[\\\/_+.#"@\[\(\{&]/g,wN=/[\s-]/,wE=/[\s-]/g;function wD(e){return e.toLowerCase().replace(wE," ")}var wR=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,r)=>{let s=se(`Primitive.${r}`),n=$.forwardRef((e,n)=>{let{asChild:i,...a}=e;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),(0,O.jsx)(i?s:r,{...a,ref:n})});return n.displayName=`Primitive.${r}`,{...e,[r]:n}},{}),wA='[cmdk-group=""]',wT='[cmdk-group-items=""]',wM='[cmdk-item=""]',wF=`${wM}:not([aria-disabled="true"])`,wP="cmdk-item-select",wI="data-value",wB=(e,r,s)=>{var n;return n=e,function e(r,s,n,i,a,o,l){if(o===s.length)return a===r.length?1:.99;var c=`${a},${o}`;if(void 0!==l[c])return l[c];for(var d,u,h,f,p=i.charAt(o),m=n.indexOf(p,a),g=0;m>=0;)(d=e(r,s,n,i,m+1,o+1,l))>g&&(m===a?d*=1:wC.test(r.charAt(m-1))?(d*=.8,(h=r.slice(a,m-1).match(wk))&&a>0&&(d*=Math.pow(.999,h.length))):wN.test(r.charAt(m-1))?(d*=.9,(f=r.slice(a,m-1).match(wE))&&a>0&&(d*=Math.pow(.999,f.length))):(d*=.17,a>0&&(d*=Math.pow(.999,m-a))),r.charAt(m)!==s.charAt(o)&&(d*=.9999)),(d<.1&&n.charAt(m-1)===i.charAt(o+1)||i.charAt(o+1)===i.charAt(o)&&n.charAt(m-1)!==i.charAt(o))&&.1*(u=e(r,s,n,i,m+1,o+2,l))>d&&(d=.1*u),d>g&&(g=d),m=n.indexOf(p,m+1);return l[c]=g,g}(n=s&&s.length>0?`${n+" "+s.join(" ")}`:n,r,wD(n),wD(r),0,0,{})},wL=$.createContext(void 0),wz=$.createContext(void 0),wO=$.createContext(void 0),w$=$.forwardRef((e,r)=>{let s=wJ(()=>{var r,s;return{search:"",value:null!=(s=null!=(r=e.value)?r:e.defaultValue)?s:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=wJ(()=>new Set),i=wJ(()=>new Map),a=wJ(()=>new Map),o=wJ(()=>new Set),l=wG(e),{label:c,children:d,value:u,onValueChange:h,filter:f,shouldFilter:p,loop:m,disablePointerSelection:g=!1,vimBindings:x=!0,...v}=e,_=ek(),y=ek(),b=ek(),w=$.useRef(null),S=w0();wX(()=>{if(void 0!==u){let e=u.trim();s.current.value=e,j.emit()}},[u]),wX(()=>{S(6,R)},[]);let j=$.useMemo(()=>({subscribe:e=>(o.current.add(e),()=>o.current.delete(e)),snapshot:()=>s.current,setState:(e,r,n)=>{var i,a,o,c;if(!Object.is(s.current[e],r)){if(s.current[e]=r,"search"===e)D(),N(),S(1,E);else if("value"===e){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let e=document.getElementById(b);e?e.focus():null==(i=document.getElementById(_))||i.focus()}if(S(7,()=>{var e;s.current.selectedItemId=null==(e=A())?void 0:e.id,j.emit()}),n||S(5,R),(null==(a=l.current)?void 0:a.value)!==void 0){null==(c=(o=l.current).onValueChange)||c.call(o,null!=r?r:"");return}}j.emit()}},emit:()=>{o.current.forEach(e=>e())}}),[]),C=$.useMemo(()=>({value:(e,r,n)=>{var i;r!==(null==(i=a.current.get(e))?void 0:i.value)&&(a.current.set(e,{value:r,keywords:n}),s.current.filtered.items.set(e,k(r,n)),S(2,()=>{N(),j.emit()}))},item:(e,r)=>(n.current.add(e),r&&(i.current.has(r)?i.current.get(r).add(e):i.current.set(r,new Set([e]))),S(3,()=>{D(),N(),s.current.value||E(),j.emit()}),()=>{a.current.delete(e),n.current.delete(e),s.current.filtered.items.delete(e);let r=A();S(4,()=>{D(),(null==r?void 0:r.getAttribute("id"))===e&&E(),j.emit()})}),group:e=>(i.current.has(e)||i.current.set(e,new Set),()=>{a.current.delete(e),i.current.delete(e)}),filter:()=>l.current.shouldFilter,label:c||e["aria-label"],getDisablePointerSelection:()=>l.current.disablePointerSelection,listId:_,inputId:b,labelId:y,listInnerRef:w}),[]);function k(e,r){var n,i;let a=null!=(i=null==(n=l.current)?void 0:n.filter)?i:wB;return e?a(e,s.current.search,r):0}function N(){if(!s.current.search||!1===l.current.shouldFilter)return;let e=s.current.filtered.items,r=[];s.current.filtered.groups.forEach(s=>{let n=i.current.get(s),a=0;n.forEach(r=>{a=Math.max(e.get(r),a)}),r.push([s,a])});let n=w.current;T().sort((r,s)=>{var n,i;let a=r.getAttribute("id"),o=s.getAttribute("id");return(null!=(n=e.get(o))?n:0)-(null!=(i=e.get(a))?i:0)}).forEach(e=>{let r=e.closest(wT);r?r.appendChild(e.parentElement===r?e:e.closest(`${wT} > *`)):n.appendChild(e.parentElement===n?e:e.closest(`${wT} > *`))}),r.sort((e,r)=>r[1]-e[1]).forEach(e=>{var r;let s=null==(r=w.current)?void 0:r.querySelector(`${wA}[${wI}="${encodeURIComponent(e[0])}"]`);null==s||s.parentElement.appendChild(s)})}function E(){let e=T().find(e=>"true"!==e.getAttribute("aria-disabled")),r=null==e?void 0:e.getAttribute(wI);j.setState("value",r||void 0)}function D(){var e,r,o,c;if(!s.current.search||!1===l.current.shouldFilter){s.current.filtered.count=n.current.size;return}s.current.filtered.groups=new Set;let d=0;for(let i of n.current){let n=k(null!=(r=null==(e=a.current.get(i))?void 0:e.value)?r:"",null!=(c=null==(o=a.current.get(i))?void 0:o.keywords)?c:[]);s.current.filtered.items.set(i,n),n>0&&d++}for(let[e,r]of i.current)for(let n of r)if(s.current.filtered.items.get(n)>0){s.current.filtered.groups.add(e);break}s.current.filtered.count=d}function R(){var e,r,s;let n=A();n&&((null==(e=n.parentElement)?void 0:e.firstChild)===n&&(null==(s=null==(r=n.closest(wA))?void 0:r.querySelector('[cmdk-group-heading=""]'))||s.scrollIntoView({block:"nearest"})),n.scrollIntoView({block:"nearest"}))}function A(){var e;return null==(e=w.current)?void 0:e.querySelector(`${wM}[aria-selected="true"]`)}function T(){var e;return Array.from((null==(e=w.current)?void 0:e.querySelectorAll(wF))||[])}function M(e){let r=T()[e];r&&j.setState("value",r.getAttribute(wI))}function F(e){var r;let s=A(),n=T(),i=n.findIndex(e=>e===s),a=n[i+e];null!=(r=l.current)&&r.loop&&(a=i+e<0?n[n.length-1]:i+e===n.length?n[0]:n[i+e]),a&&j.setState("value",a.getAttribute(wI))}function P(e){let r=A(),s=null==r?void 0:r.closest(wA),n;for(;s&&!n;)n=null==(s=e>0?function(e,r){let s=e.nextElementSibling;for(;s;){if(s.matches(r))return s;s=s.nextElementSibling}}(s,wA):function(e,r){let s=e.previousElementSibling;for(;s;){if(s.matches(r))return s;s=s.previousElementSibling}}(s,wA))?void 0:s.querySelector(wF);n?j.setState("value",n.getAttribute(wI)):F(e)}let I=()=>M(T().length-1),B=e=>{e.preventDefault(),e.metaKey?I():e.altKey?P(1):F(1)},L=e=>{e.preventDefault(),e.metaKey?M(0):e.altKey?P(-1):F(-1)};return $.createElement(wR.div,{ref:r,tabIndex:-1,...v,"cmdk-root":"",onKeyDown:e=>{var r;null==(r=v.onKeyDown)||r.call(v,e);let s=e.nativeEvent.isComposing||229===e.keyCode;if(!(e.defaultPrevented||s))switch(e.key){case"n":case"j":x&&e.ctrlKey&&B(e);break;case"ArrowDown":B(e);break;case"p":case"k":x&&e.ctrlKey&&L(e);break;case"ArrowUp":L(e);break;case"Home":e.preventDefault(),M(0);break;case"End":e.preventDefault(),I();break;case"Enter":{e.preventDefault();let r=A();if(r){let e=new Event(wP);r.dispatchEvent(e)}}}}},$.createElement("label",{"cmdk-label":"",htmlFor:C.inputId,id:C.labelId,style:w2},c),w1(e,e=>$.createElement(wz.Provider,{value:j},$.createElement(wL.Provider,{value:C},e))))}),wW=$.forwardRef((e,r)=>{var s,n;let i=ek(),a=$.useRef(null),o=$.useContext(wO),l=$.useContext(wL),c=wG(e),d=null!=(n=null==(s=c.current)?void 0:s.forceMount)?n:null==o?void 0:o.forceMount;wX(()=>{if(!d)return l.item(i,null==o?void 0:o.id)},[d]);let u=wQ(i,a,[e.value,e.children,a],e.keywords),h=$.useContext(wz),f=wZ(e=>e.value&&e.value===u.current),p=wZ(e=>!!d||!1===l.filter()||!e.search||e.filtered.items.get(i)>0);function m(){var e,r;g(),null==(r=(e=c.current).onSelect)||r.call(e,u.current)}function g(){h.setState("value",u.current,!0)}if($.useEffect(()=>{let r=a.current;if(!(!r||e.disabled))return r.addEventListener(wP,m),()=>r.removeEventListener(wP,m)},[p,e.onSelect,e.disabled]),!p)return null;let{disabled:x,value:v,onSelect:_,forceMount:y,keywords:b,...w}=e;return $.createElement(wR.div,{ref:(0,U.composeRefs)(a,r),...w,id:i,"cmdk-item":"",role:"option","aria-disabled":!!x,"aria-selected":!!f,"data-disabled":!!x,"data-selected":!!f,onPointerMove:x||l.getDisablePointerSelection()?void 0:g,onClick:x?void 0:m},e.children)}),wH=$.forwardRef((e,r)=>{let{heading:s,children:n,forceMount:i,...a}=e,o=ek(),l=$.useRef(null),c=$.useRef(null),d=ek(),u=$.useContext(wL),h=wZ(e=>!!i||!1===u.filter()||!e.search||e.filtered.groups.has(o));wX(()=>u.group(o),[]),wQ(o,l,[e.value,e.heading,c]);let f=$.useMemo(()=>({id:o,forceMount:i}),[i]);return $.createElement(wR.div,{ref:(0,U.composeRefs)(l,r),...a,"cmdk-group":"",role:"presentation",hidden:!h||void 0},s&&$.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},s),w1(e,e=>$.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":s?d:void 0},$.createElement(wO.Provider,{value:f},e))))}),wU=$.forwardRef((e,r)=>{let{alwaysRender:s,...n}=e,i=$.useRef(null),a=wZ(e=>!e.search);return s||a?$.createElement(wR.div,{ref:(0,U.composeRefs)(i,r),...n,"cmdk-separator":"",role:"separator"}):null}),wq=$.forwardRef((e,r)=>{let{onValueChange:s,...n}=e,i=null!=e.value,a=$.useContext(wz),o=wZ(e=>e.search),l=wZ(e=>e.selectedItemId),c=$.useContext(wL);return $.useEffect(()=>{null!=e.value&&a.setState("search",e.value)},[e.value]),$.createElement(wR.input,{ref:r,...n,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":l,id:c.inputId,type:"text",value:i?e.value:o,onChange:e=>{i||a.setState("search",e.target.value),null==s||s(e.target.value)}})}),wK=$.forwardRef((e,r)=>{let{children:s,label:n="Suggestions",...i}=e,a=$.useRef(null),o=$.useRef(null),l=wZ(e=>e.selectedItemId),c=$.useContext(wL);return $.useEffect(()=>{if(o.current&&a.current){let e=o.current,r=a.current,s,n=new ResizeObserver(()=>{s=requestAnimationFrame(()=>{let s=e.offsetHeight;r.style.setProperty("--cmdk-list-height",s.toFixed(1)+"px")})});return n.observe(e),()=>{cancelAnimationFrame(s),n.unobserve(e)}}},[]),$.createElement(wR.div,{ref:(0,U.composeRefs)(a,r),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":l,"aria-label":n,id:c.listId},w1(e,e=>$.createElement("div",{ref:(0,U.composeRefs)(o,c.listInnerRef),"cmdk-list-sizer":""},e)))}),wV=$.forwardRef((e,r)=>{let{open:s,onOpenChange:n,overlayClassName:i,contentClassName:a,container:o,...l}=e;return $.createElement(tM,{open:s,onOpenChange:n},$.createElement(tz,{container:o},$.createElement(t$,{"cmdk-overlay":"",className:i}),$.createElement(tq,{"aria-label":e.label,"cmdk-dialog":"",className:a},$.createElement(w$,{ref:r,...l}))))}),wY=Object.assign(w$,{List:wK,Item:wW,Input:wq,Group:wH,Separator:wU,Dialog:wV,Empty:$.forwardRef((e,r)=>wZ(e=>0===e.filtered.count)?$.createElement(wR.div,{ref:r,...e,"cmdk-empty":"",role:"presentation"}):null),Loading:$.forwardRef((e,r)=>{let{progress:s,children:n,label:i="Loading...",...a}=e;return $.createElement(wR.div,{ref:r,...a,"cmdk-loading":"",role:"progressbar","aria-valuenow":s,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},w1(e,e=>$.createElement("div",{"aria-hidden":!0},e)))})});function wG(e){let r=$.useRef(e);return wX(()=>{r.current=e}),r}var wX="undefined"==typeof window?$.useEffect:$.useLayoutEffect;function wJ(e){let r=$.useRef();return void 0===r.current&&(r.current=e()),r}function wZ(e){let r=$.useContext(wz),s=()=>e(r.snapshot());return $.useSyncExternalStore(r.subscribe,s,s)}function wQ(e,r,s,n=[]){let i=$.useRef(),a=$.useContext(wL);return wX(()=>{var o;let l=(()=>{var e;for(let r of s){if("string"==typeof r)return r.trim();if("object"==typeof r&&"current"in r)return r.current?null==(e=r.current.textContent)?void 0:e.trim():i.current}})(),c=n.map(e=>e.trim());a.value(e,l,c),null==(o=r.current)||o.setAttribute(wI,l),i.current=l}),i}var w0=()=>{let[e,r]=$.useState(),s=wJ(()=>new Map);return wX(()=>{s.current.forEach(e=>e()),s.current=new Map},[e]),(e,n)=>{s.current.set(e,n),r({})}};function w1({asChild:e,children:r},s){let n;return e&&$.isValidElement(r)?$.cloneElement("function"==typeof(n=r.type)?n(r.props):"render"in n?n.render(r.props):r,{ref:r.ref},s(r.props.children)):s(r)}var w2={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function w5({className:e,...r}){return(0,O.jsx)(wY,{"data-slot":"command",className:(0,ey.cn)("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",e),...r})}function w3({title:e="Command Palette",description:r="Search for a command to run...",children:s,className:n,showCloseButton:i=!0,shouldFilter:a,...o}){return(0,O.jsxs)(t8,{...o,children:[(0,O.jsxs)(rs,{className:"sr-only",children:[(0,O.jsx)(ri,{children:e}),(0,O.jsx)(ra,{children:r})]}),(0,O.jsx)(rr,{className:(0,ey.cn)("overflow-hidden p-0",n),showCloseButton:i,children:(0,O.jsx)(w5,{shouldFilter:a,className:"[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:s})})]})}function w4({className:e,...r}){return(0,O.jsxs)("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[(0,O.jsx)(sA,{className:"size-4 shrink-0 opacity-50"}),(0,O.jsx)(wY.Input,{"data-slot":"command-input",className:(0,ey.cn)("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",e),...r})]})}function w6({className:e,...r}){return(0,O.jsx)(wY.List,{"data-slot":"command-list",className:(0,ey.cn)("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...r})}function w7({...e}){return(0,O.jsx)(wY.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...e})}function w8({className:e,...r}){return(0,O.jsx)(wY.Group,{"data-slot":"command-group",className:(0,ey.cn)("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",e),...r})}function w9({className:e,...r}){return(0,O.jsx)(wY.Item,{"data-slot":"command-item",className:(0,ey.cn)("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r})}let Se=(0,ew.default)("file",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]]),St=(0,ew.default)("file-code",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]]),Sr=(0,ew.default)("file-text",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]),Ss=new Set(["ts","tsx","js","jsx","py","rb","go","rs","java","c","cpp","h","css","scss","html","vue","svelte","php","swift","kt","sh","bash","yaml","yml","toml","json","xml","sql","graphql","proto"]),Sn=new Set(["md","txt","log","csv","env","gitignore","dockerignore","editorconfig"]);function Si(e){return Array.from(e.dataTransfer.types).includes("Files")}function Sa(e){let r=e.dataTransfer.items;if(r&&r.length>0&&"function"==typeof r[0].webkitGetAsEntry){let e=[];for(let s of Array.from(r)){if("file"!==s.kind)continue;let r=s.webkitGetAsEntry();if(r?.isDirectory)continue;let n=s.getAsFile();n&&e.push(n)}return e}return Array.from(e.dataTransfer.files)}function So({path:e}){let[r,s]=(0,$.useState)(!1),n=(0,$.useCallback)(r=>{r.stopPropagation(),navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)},[e]);return(0,O.jsx)("button",{onClick:n,className:"p-0.5 rounded hover:bg-muted-foreground/20 transition-colors",title:`Copy path: ${e}`,children:r?(0,O.jsx)(rf.Check,{className:"h-3 w-3 text-green-500"}):(0,O.jsx)(fq.Copy,{className:"h-3 w-3 text-muted-foreground"})})}function Sl({entryPath:e,type:r,deleting:s,onRequestDelete:n}){return s?(0,O.jsx)(sj,{className:"h-3 w-3 animate-spin text-muted-foreground"}):(0,O.jsx)("button",{onClick:s=>{s.stopPropagation(),n(e,r)},className:"p-0.5 rounded hover:bg-destructive/20 transition-colors",title:`Delete ${e}`,"aria-label":`Delete ${e}`,children:(0,O.jsx)(rc,{className:"h-3 w-3 text-muted-foreground hover:text-destructive"})})}function Sc({entry:e,path:r,depth:s,expandedDirs:n,directoryContents:i,loadingDirs:a,selectedFile:o,uploadingDirs:l,dragOverPath:c,deletingPaths:d,onToggleDirectory:u,onSelectFile:h,onUploadFiles:f,onSetDragOverPath:p,onRequestDelete:m}){var g,x,v;let _,y,b,w,S,j=n.has(r),C=a.has(r),k=i.get(r),N=e.name.startsWith(".");if("directory"===e.type){let g=j?ns:a3,x=c===r,v=l.has(r),_=d.has(r);return(0,O.jsxs)("div",{children:[(0,O.jsxs)("div",{className:(0,ey.cn)("group flex items-center w-full px-2 py-2 rounded-sm transition-colors cursor-pointer",x?"bg-primary/15 outline-2 -outline-offset-2 outline-dashed outline-primary/60":"hover:bg-accent"),style:{paddingLeft:`${16*s+8}px`},onClick:()=>u(r),onDragOver:e=>{Si(e)&&(e.preventDefault(),e.stopPropagation(),p(r))},onDrop:e=>{if(!Si(e))return;e.preventDefault(),e.stopPropagation(),p(null);let s=Sa(e);s.length&&f(r,s)},children:[(0,O.jsxs)("div",{className:"flex items-center gap-1 min-w-0 flex-1",children:[v||C?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):(0,O.jsx)(g,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,O.jsx)(j?r_:oY,{className:(0,ey.cn)("h-4 w-4 shrink-0 text-blue-500",N&&"opacity-60")}),(0,O.jsx)("span",{className:(0,ey.cn)("truncate",N&&"text-muted-foreground"),children:e.name})]}),(0,O.jsxs)("div",{className:(0,ey.cn)("shrink-0 ml-1 items-center gap-1",_?"flex":"hidden group-hover:flex"),children:[(0,O.jsx)(So,{path:r}),(0,O.jsx)(Sl,{entryPath:r,type:"directory",deleting:_,onRequestDelete:m})]})]}),j&&k&&(0,O.jsx)("div",{children:k.map(e=>{let g=r?`${r}/${e.name}`:e.name;return(0,O.jsx)(Sc,{entry:e,path:g,depth:s+1,expandedDirs:n,directoryContents:i,loadingDirs:a,selectedFile:o,uploadingDirs:l,dragOverPath:c,deletingPaths:d,onToggleDirectory:u,onSelectFile:h,onUploadFiles:f,onSetDragOverPath:p,onRequestDelete:m},g)})})]})}let E=(g=e.name,_=g.split(".").pop()?.toLowerCase()??"",Ss.has(_)?St:Sn.has(_)?Sr:Se),D=o===r,R=r.includes("/")?r.slice(0,r.lastIndexOf("/")):"",A=d.has(r);return(0,O.jsxs)("div",{className:(0,ey.cn)("group flex items-center w-full px-2 py-2 rounded-sm transition-colors cursor-pointer",D?"bg-accent text-accent-foreground":"hover:bg-accent/50"),style:{paddingLeft:`${16*s+8+18}px`},onClick:()=>h(r),onDragOver:e=>{Si(e)&&(e.preventDefault(),e.stopPropagation(),p(R))},onDrop:e=>{if(!Si(e))return;e.preventDefault(),e.stopPropagation(),p(null);let r=Sa(e);r.length&&f(R,r)},children:[(0,O.jsxs)("div",{className:"flex items-center gap-1 min-w-0 flex-1",children:[(0,O.jsx)(E,{className:(0,ey.cn)("h-4 w-4 shrink-0 text-muted-foreground",N&&"opacity-60")}),(0,O.jsx)("span",{className:(0,ey.cn)("truncate",N&&"text-muted-foreground"),children:e.name})]}),(0,O.jsxs)("div",{className:"shrink-0 flex items-center gap-2 ml-1",children:[(0,O.jsx)("span",{className:"text-[11px] text-muted-foreground/70 group-hover:hidden whitespace-nowrap w-[52px] text-right tabular-nums",children:e.mtime&&(x=e.mtime,y=Date.now(),S=Math.floor((w=Math.floor((b=Math.floor(Math.floor((y-new Date(x).getTime())/1e3)/60))/60))/24),b<1?"just now":b<60?`${b}m ago`:w<24?`${w}h ago`:S<30?`${S}d ago`:new Date(x).toLocaleDateString(void 0,{month:"short",day:"numeric"}))}),(0,O.jsx)("span",{className:"text-[11px] text-muted-foreground/70 group-hover:hidden whitespace-nowrap w-[52px] text-right tabular-nums",children:null!=e.size&&((v=e.size)<1024?`${v} B`:v<1048576?`${(v/1024).toFixed(1)} KB`:`${(v/1048576).toFixed(1)} MB`)}),(0,O.jsxs)("div",{className:(0,ey.cn)("items-center gap-1",A?"flex":"hidden group-hover:flex"),children:[(0,O.jsx)(So,{path:r}),(0,O.jsx)(Sl,{entryPath:r,type:"file",deleting:A,onRequestDelete:m})]})]})]})}function Sd({entries:e,expandedDirs:r,directoryContents:s,loadingDirs:n,selectedFile:i,uploadingDirs:a,rootLoading:o,deletingPaths:l,onToggleDirectory:c,onSelectFile:d,onUploadFiles:u,onDeleteEntry:h}){let[f,p]=(0,$.useState)(null),[m,g]=(0,$.useState)(null),x=""===f,v=a.has(""),_=(0,$.useCallback)((e,r)=>{g({path:e,type:r})},[]),y=m?m.path.includes("/")?m.path.slice(m.path.lastIndexOf("/")+1):m.path:"";return(0,O.jsxs)("div",{className:(0,ey.cn)("h-full transition-colors",x&&"bg-accent/30 outline-2 -outline-offset-2 outline-dashed outline-primary/50"),style:{fontSize:"var(--files-tree-font-size, 14px)"},onDragOver:e=>{Si(e)&&(e.preventDefault(),p(""))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||p(null)},onDrop:e=>{if(!Si(e))return;e.preventDefault(),p(null);let r=Sa(e);r.length&&u("",r)},children:[(0,O.jsx)(oK,{className:"h-full",children:(0,O.jsxs)("div",{className:"py-1",children:[v&&(0,O.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1 text-xs text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-3.5 w-3.5 animate-spin"}),"Uploading…"]}),o&&0===e.length?(0,O.jsx)("div",{className:"flex items-center justify-center py-12 text-muted-foreground text-sm",children:"Loading files..."}):0===e.length?(0,O.jsx)("div",{className:"flex items-center justify-center py-8 text-muted-foreground text-sm",children:x?"Drop files to upload":"No files found. Drop files here to upload."}):e.map(e=>{let o=e.name;return(0,O.jsx)(Sc,{entry:e,path:o,depth:0,expandedDirs:r,directoryContents:s,loadingDirs:n,selectedFile:i,uploadingDirs:a,dragOverPath:f,deletingPaths:l,onToggleDirectory:c,onSelectFile:d,onUploadFiles:u,onSetDragOverPath:p,onRequestDelete:_},o)})]})}),(0,O.jsx)(lL,{open:null!==m,onOpenChange:e=>{e||g(null)},children:(0,O.jsxs)(l$,{children:[(0,O.jsxs)(lW,{children:[(0,O.jsxs)(lU,{children:["Delete ",m?.type==="directory"?"folder":"file","?"]}),(0,O.jsx)(lq,{children:m?.type==="directory"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("span",{className:"font-medium text-foreground",children:y})," and all its contents will be permanently deleted. This can't be undone."]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("span",{className:"font-medium text-foreground",children:y})," will be permanently deleted. This can't be undone."]})})]}),(0,O.jsxs)(lH,{children:[(0,O.jsx)(lV,{children:"Cancel"}),(0,O.jsx)(lK,{className:(0,ey.cn)((0,W.buttonVariants)({variant:"destructive"}),"border-transparent"),onClick:()=>{m&&h(m.path,m.type)},children:"Delete"})]})]})})]})}let Su=(0,ew.default)("download",[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]]),Sh=(0,ew.default)("file-exclamation-point",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),Sf=(0,ew.default)("code",[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]]),Sp=(0,ew.default)("list-collapse",[["path",{d:"M10 5h11",key:"1hkqpe"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 19h11",key:"14g2nv"}],["path",{d:"m3 10 3-3-3-3",key:"i7pm08"}],["path",{d:"m3 20 3-3-3-3",key:"20gx1n"}]]),Sm=(0,ew.default)("list-tree",[["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"M3 10a2 2 0 0 0 2 2h3",key:"1npucw"}],["path",{d:"M3 5v12a2 2 0 0 0 2 2h3",key:"x1gjn2"}]]),Sg=/[\0-\x1F!-,\.\/:-@\[-\^`\{-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0378\u0379\u037E\u0380-\u0385\u0387\u038B\u038D\u03A2\u03F6\u0482\u0530\u0557\u0558\u055A-\u055F\u0589-\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05EB-\u05EE\u05F3-\u060F\u061B-\u061F\u066A-\u066D\u06D4\u06DD\u06DE\u06E9\u06FD\u06FE\u0700-\u070F\u074B\u074C\u07B2-\u07BF\u07F6-\u07F9\u07FB\u07FC\u07FE\u07FF\u082E-\u083F\u085C-\u085F\u086B-\u089F\u08B5\u08C8-\u08D2\u08E2\u0964\u0965\u0970\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA\u09BB\u09C5\u09C6\u09C9\u09CA\u09CF-\u09D6\u09D8-\u09DB\u09DE\u09E4\u09E5\u09F2-\u09FB\u09FD\u09FF\u0A00\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A\u0A3B\u0A3D\u0A43-\u0A46\u0A49\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA\u0ABB\u0AC6\u0ACA\u0ACE\u0ACF\u0AD1-\u0ADF\u0AE4\u0AE5\u0AF0-\u0AF8\u0B00\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A\u0B3B\u0B45\u0B46\u0B49\u0B4A\u0B4E-\u0B54\u0B58-\u0B5B\u0B5E\u0B64\u0B65\u0B70\u0B72-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BF0-\u0BFF\u0C0D\u0C11\u0C29\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5B-\u0C5F\u0C64\u0C65\u0C70-\u0C7F\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4\u0CE5\u0CF0\u0CF3-\u0CFF\u0D0D\u0D11\u0D45\u0D49\u0D4F-\u0D53\u0D58-\u0D5E\u0D64\u0D65\u0D70-\u0D79\u0D80\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DE5\u0DF0\u0DF1\u0DF4-\u0E00\u0E3B-\u0E3F\u0E4F\u0E5A-\u0E80\u0E83\u0E85\u0E8B\u0EA4\u0EA6\u0EBE\u0EBF\u0EC5\u0EC7\u0ECE\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F01-\u0F17\u0F1A-\u0F1F\u0F2A-\u0F34\u0F36\u0F38\u0F3A-\u0F3D\u0F48\u0F6D-\u0F70\u0F85\u0F98\u0FBD-\u0FC5\u0FC7-\u0FFF\u104A-\u104F\u109E\u109F\u10C6\u10C8-\u10CC\u10CE\u10CF\u10FB\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B\u135C\u1360-\u137F\u1390-\u139F\u13F6\u13F7\u13FE-\u1400\u166D\u166E\u1680\u169B-\u169F\u16EB-\u16ED\u16F9-\u16FF\u170D\u1715-\u171F\u1735-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17D4-\u17D6\u17D8-\u17DB\u17DE\u17DF\u17EA-\u180A\u180E\u180F\u181A-\u181F\u1879-\u187F\u18AB-\u18AF\u18F6-\u18FF\u191F\u192C-\u192F\u193C-\u1945\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DA-\u19FF\u1A1C-\u1A1F\u1A5F\u1A7D\u1A7E\u1A8A-\u1A8F\u1A9A-\u1AA6\u1AA8-\u1AAF\u1AC1-\u1AFF\u1B4C-\u1B4F\u1B5A-\u1B6A\u1B74-\u1B7F\u1BF4-\u1BFF\u1C38-\u1C3F\u1C4A-\u1C4C\u1C7E\u1C7F\u1C89-\u1C8F\u1CBB\u1CBC\u1CC0-\u1CCF\u1CD3\u1CFB-\u1CFF\u1DFA\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FBD\u1FBF-\u1FC1\u1FC5\u1FCD-\u1FCF\u1FD4\u1FD5\u1FDC-\u1FDF\u1FED-\u1FF1\u1FF5\u1FFD-\u203E\u2041-\u2053\u2055-\u2070\u2072-\u207E\u2080-\u208F\u209D-\u20CF\u20F1-\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F-\u215F\u2189-\u24B5\u24EA-\u2BFF\u2C2F\u2C5F\u2CE5-\u2CEA\u2CF4-\u2CFF\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D70-\u2D7E\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E00-\u2E2E\u2E30-\u3004\u3008-\u3020\u3030\u3036\u3037\u303D-\u3040\u3097\u3098\u309B\u309C\u30A0\u30FB\u3100-\u3104\u3130\u318F-\u319F\u31C0-\u31EF\u3200-\u33FF\u4DC0-\u4DFF\u9FFD-\u9FFF\uA48D-\uA4CF\uA4FE\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA673\uA67E\uA6F2-\uA716\uA720\uA721\uA789\uA78A\uA7C0\uA7C1\uA7CB-\uA7F4\uA828-\uA82B\uA82D-\uA83F\uA874-\uA87F\uA8C6-\uA8CF\uA8DA-\uA8DF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA954-\uA95F\uA97D-\uA97F\uA9C1-\uA9CE\uA9DA-\uA9DF\uA9FF\uAA37-\uAA3F\uAA4E\uAA4F\uAA5A-\uAA5F\uAA77-\uAA79\uAAC3-\uAADA\uAADE\uAADF\uAAF0\uAAF1\uAAF7-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F\uAB5B\uAB6A-\uAB6F\uABEB\uABEE\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uE000-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB29\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFC-\uFDFF\uFE10-\uFE1F\uFE30-\uFE32\uFE35-\uFE4C\uFE50-\uFE6F\uFE75\uFEFD-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF3E\uFF40\uFF5B-\uFF65\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFFF]|\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDD3F\uDD75-\uDDFC\uDDFE-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEDF\uDEE1-\uDEFF\uDF20-\uDF2C\uDF4B-\uDF4F\uDF7B-\uDF7F\uDF9E\uDF9F\uDFC4-\uDFC7\uDFD0\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56-\uDC5F\uDC77-\uDC7F\uDC9F-\uDCDF\uDCF3\uDCF6-\uDCFF\uDD16-\uDD1F\uDD3A-\uDD7F\uDDB8-\uDDBD\uDDC0-\uDDFF\uDE04\uDE07-\uDE0B\uDE14\uDE18\uDE36\uDE37\uDE3B-\uDE3E\uDE40-\uDE5F\uDE7D-\uDE7F\uDE9D-\uDEBF\uDEC8\uDEE7-\uDEFF\uDF36-\uDF3F\uDF56-\uDF5F\uDF73-\uDF7F\uDF92-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCFF\uDD28-\uDD2F\uDD3A-\uDE7F\uDEAA\uDEAD-\uDEAF\uDEB2-\uDEFF\uDF1D-\uDF26\uDF28-\uDF2F\uDF51-\uDFAF\uDFC5-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC47-\uDC65\uDC70-\uDC7E\uDCBB-\uDCCF\uDCE9-\uDCEF\uDCFA-\uDCFF\uDD35\uDD40-\uDD43\uDD48-\uDD4F\uDD74\uDD75\uDD77-\uDD7F\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDFF\uDE12\uDE38-\uDE3D\uDE3F-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEA9-\uDEAF\uDEEB-\uDEEF\uDEFA-\uDEFF\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A\uDF45\uDF46\uDF49\uDF4A\uDF4E\uDF4F\uDF51-\uDF56\uDF58-\uDF5C\uDF64\uDF65\uDF6D-\uDF6F\uDF75-\uDFFF]|\uD805[\uDC4B-\uDC4F\uDC5A-\uDC5D\uDC62-\uDC7F\uDCC6\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDB6\uDDB7\uDDC1-\uDDD7\uDDDE-\uDDFF\uDE41-\uDE43\uDE45-\uDE4F\uDE5A-\uDE7F\uDEB9-\uDEBF\uDECA-\uDEFF\uDF1B\uDF1C\uDF2C-\uDF2F\uDF3A-\uDFFF]|\uD806[\uDC3B-\uDC9F\uDCEA-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD36\uDD39\uDD3A\uDD44-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD8\uDDD9\uDDE2\uDDE5-\uDDFF\uDE3F-\uDE46\uDE48-\uDE4F\uDE9A-\uDE9C\uDE9E-\uDEBF\uDEF9-\uDFFF]|\uD807[\uDC09\uDC37\uDC41-\uDC4F\uDC5A-\uDC71\uDC90\uDC91\uDCA8\uDCB7-\uDCFF\uDD07\uDD0A\uDD37-\uDD39\uDD3B\uDD3E\uDD48-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8F\uDD92\uDD99-\uDD9F\uDDAA-\uDEDF\uDEF7-\uDFAF\uDFB1-\uDFFF]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD80B\uD80E-\uD810\uD812-\uD819\uD824-\uD82B\uD82D\uD82E\uD830-\uD833\uD837\uD839\uD83D\uD83F\uD87B-\uD87D\uD87F\uD885-\uDB3F\uDB41-\uDBFF][\uDC00-\uDFFF]|\uD80D[\uDC2F-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDECF\uDEEE\uDEEF\uDEF5-\uDEFF\uDF37-\uDF3F\uDF44-\uDF4F\uDF5A-\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDE3F\uDE80-\uDEFF\uDF4B-\uDF4E\uDF88-\uDF8E\uDFA0-\uDFDF\uDFE2\uDFE5-\uDFEF\uDFF2-\uDFFF]|\uD821[\uDFF8-\uDFFF]|\uD823[\uDCD6-\uDCFF\uDD09-\uDFFF]|\uD82C[\uDD1F-\uDD4F\uDD53-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A-\uDC9C\uDC9F-\uDFFF]|\uD834[\uDC00-\uDD64\uDD6A-\uDD6C\uDD73-\uDD7A\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDE41\uDE45-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3\uDFCC\uDFCD]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85-\uDE9A\uDEA0\uDEB0-\uDFFF]|\uD838[\uDC07\uDC19\uDC1A\uDC22\uDC25\uDC2B-\uDCFF\uDD2D-\uDD2F\uDD3E\uDD3F\uDD4A-\uDD4D\uDD4F-\uDEBF\uDEFA-\uDFFF]|\uD83A[\uDCC5-\uDCCF\uDCD7-\uDCFF\uDD4C-\uDD4F\uDD5A-\uDFFF]|\uD83B[\uDC00-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDFFF]|\uD83C[\uDC00-\uDD2F\uDD4A-\uDD4F\uDD6A-\uDD6F\uDD8A-\uDFFF]|\uD83E[\uDC00-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEDE-\uDEFF]|\uD86D[\uDF35-\uDF3F]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEA2-\uDEAF]|\uD87A[\uDFE1-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDFFF]|\uDB40[\uDC00-\uDCFF\uDDF0-\uDFFF]/g,Sx=Object.hasOwnProperty;var Sv=e.i(216920);let S_={},Sy=new class{constructor(){this.occurrences,this.reset()}slug(e,r){var s,n;let i=(s=e,n=!0===r,"string"!=typeof s?"":(n||(s=s.toLowerCase()),s.replace(Sg,"").replace(/ /g,"-"))),a=i;for(;Sx.call(this.occurrences,i);)this.occurrences[a]++,i=a+"-"+this.occurrences[a];return this.occurrences[i]=0,i}reset(){this.occurrences=Object.create(null)}};function Sb(e){let r=(e||S_).prefix||"";return function(e){Sy.reset(),(0,Sv.visit)(e,"element",function(e){let s,n;((n=2===(s="element"===e.type?e.tagName.toLowerCase():"").length&&104===s.charCodeAt(0)?s.charCodeAt(1):0)>48&&n<55?n-48:void 0)&&!e.properties.id&&(e.properties.id=r+Sy.slug("children"in e?function e(r){let s=-1,n=[];for(;++s<r.children.length;){var i;n[s]="text"===(i=r.children[s]).type?i.value:"children"in i?e(i):""}return n.join("")}(e):"value"in e?e.value:""))})}}var Sw=cC,H=H,SS=e.i(829692),SS=SS,Sj=e.i(615742);let SC=(0,$.createContext)({code:""}),Sk={name:"line-data",line(e,r){e.properties["data-line"]=String(r)}},SN={name:"line-numbers",line(e,r){e.children.unshift({type:"element",tagName:"span",properties:{className:["inline-block","min-w-10","mr-2","text-right","select-none","text-muted-foreground"]},children:[{type:"text",value:String(r)}]})}};async function SE(e,r,s=!1,n){let i=[Sk];return n&&n.size>0&&i.push({name:"fold-gutter",line(e,r){e.children.unshift({type:"element",tagName:"span",properties:n.has(r)?{className:["code-fold-toggle"],"data-fold-start":String(r)}:{className:["code-fold-spacer"]},children:[]})}}),s&&i.push(SN),await Promise.all([(0,Sj.codeToHtml)(e,{lang:r,theme:"one-light",transformers:i}),(0,Sj.codeToHtml)(e,{lang:r,theme:"one-dark-pro",transformers:i})])}let SD=(0,$.forwardRef)(function({code:e,language:r,showLineNumbers:s=!1,scrollToLine:n,scrollKey:i,foldable:a=!1,className:o,children:l,...c},d){let[u,h]=(0,$.useState)(""),[f,p]=(0,$.useState)(""),m=(0,$.useRef)(!1),g=(0,$.useRef)(null),x=(0,$.useMemo)(()=>a?function(e,r={}){return function(...e){let r=new Map;for(let s of e.flat())!(s.endLine<=s.startLine)&&(r.has(s.startLine)||r.set(s.startLine,s));let s=[...r.values()].sort((e,r)=>e.startLine-r.startLine||r.endLine-e.endLine),n=[],i=[];for(let e of s){for(;i.length&&i[i.length-1].endLine<e.startLine;)i.pop();let r=i[i.length-1];r&&e.endLine>r.endLine||(n.push(e),i.push(e))}return n}((r.tokenIndex,[]),function(e){let r=e.split("\n"),s=[],n=[],i=0,a=e=>{i>e.line&&s.push({startLine:e.line+1,endLine:i+1})};for(let e=0;e<r.length;e++){let s=function(e){let r=e.match(/^[ \t]*/),s=r?r[0].length:0;return s===e.length?null:s}(r[e]);if(null!==s){for(;n.length&&n[n.length-1].indent>=s;)a(n.pop());n.push({indent:s,line:e}),i=e}}for(;n.length;)a(n.pop());return s}(e))}(e):[],[a,e]),v=(0,$.useMemo)(()=>new Set(x.map(e=>e.startLine)),[x]),[_,y]=(0,$.useState)(new Set),[b,w]=(0,$.useState)(e),[S,j]=(0,$.useState)({line:n,key:i});if((0,$.useImperativeHandle)(d,()=>({foldAll:()=>y(new Set(x.map(e=>e.startLine))),expandAll:()=>y(new Set)}),[x]),(0,$.useEffect)(()=>(SE(e,r,s,v).then(([e,r])=>{m.current||(h(e),p(r),m.current=!0)}),()=>{m.current=!1}),[e,r,s,v]),(0,$.useEffect)(()=>{let e=g.current;if(!e)return;let r=new Map(x.map(e=>[e.startLine,e])),s=new Set;for(let e of _){let n=r.get(e);if(n)for(let e=n.startLine+1;e<=n.endLine;e++)s.add(e)}for(let r of e.querySelectorAll("[data-line]")){let e=Number(r.getAttribute("data-line"));r.style.display=s.has(e)?"none":"",r.classList.toggle("code-line-collapsed",_.has(e))}},[_,x,u,f]),(0,$.useEffect)(()=>{if(!a)return;let e=g.current;if(!e)return;let r=e=>{let r=e.target?.closest?.("[data-fold-start]");if(!r)return;e.stopPropagation(),e.preventDefault();let s=Number(r.getAttribute("data-fold-start"));y(e=>{let r=new Set(e);return r.has(s)?r.delete(s):r.add(s),r})};return e.addEventListener("click",r),()=>e.removeEventListener("click",r)},[a]),(0,$.useEffect)(()=>{if(null==n)return;let e=g.current;if(!e||!u&&!f)return;let r=Array.from(e.querySelectorAll(`[data-line="${n}"]`));if(0===r.length)return;let s=r.find(e=>null!==e.offsetParent)??r[0],i=requestAnimationFrame(()=>{s.scrollIntoView({block:"center",behavior:"auto"}),r.forEach(e=>e.classList.add("code-line-highlight"))}),a=window.setTimeout(()=>r.forEach(e=>e.classList.remove("code-line-highlight")),1600);return()=>{cancelAnimationFrame(i),window.clearTimeout(a),r.forEach(e=>e.classList.remove("code-line-highlight"))}},[n,i,u,f]),e!==b&&(w(e),y(new Set)),(S.line!==n||S.key!==i)&&(j({line:n,key:i}),null!=n&&_.size>0)){let e=!1,r=new Set(_);for(let s of x)r.has(s.startLine)&&n>s.startLine&&n<=s.endLine&&(r.delete(s.startLine),e=!0);e&&y(r)}return(0,O.jsx)(SC.Provider,{value:{code:e},children:(0,O.jsx)("div",{ref:g,className:(0,ey.cn)("group relative w-full overflow-hidden rounded-md border bg-background text-foreground",o),...c,children:(0,O.jsxs)("div",{className:"relative",children:[(0,O.jsx)("div",{className:"overflow-auto dark:hidden [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:grid [&_code]:font-mono [&_code]:text-sm",dangerouslySetInnerHTML:{__html:u}}),(0,O.jsx)("div",{className:"hidden overflow-auto dark:block [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:grid [&_code]:font-mono [&_code]:text-sm",dangerouslySetInnerHTML:{__html:f}}),l&&(0,O.jsx)("div",{className:"absolute top-2 right-2 flex items-center gap-2",children:l})]})})})}),SR=({onCopy:e,onError:r,timeout:s=2e3,children:n,className:i,...a})=>{let[o,l]=(0,$.useState)(!1),{code:c}=(0,$.useContext)(SC),d=async()=>{if(!navigator?.clipboard?.writeText)return void r?.(Error("Clipboard API not available"));try{await navigator.clipboard.writeText(c),l(!0),e?.(),setTimeout(()=>l(!1),s)}catch(e){r?.(e)}},u=o?H.default:SS.default;return(0,O.jsx)(W.Button,{className:(0,ey.cn)("shrink-0",i),onClick:d,size:"icon",variant:"ghost",...a,children:n??(0,O.jsx)(u,{size:14})})};function SA({className:e,...r}){return(0,O.jsx)("div",{"data-slot":"skeleton",className:(0,ey.cn)("bg-accent animate-pulse rounded-md",e),...r})}function ST({projectId:e,symbol:r,branch:s,target:n,currentFile:i,anchor:a,onJump:o,onClose:l}){let[c,d]=(0,$.useState)(!0),[u,h]=(0,$.useState)([]),[f,p]=(0,$.useState)(!1),m=(0,$.useRef)(null);(0,$.useEffect)(()=>{let i=!0;return d(!0),rv.api.searchSymbol(e,r,s,n).then(e=>{i&&(h(e.hits),p(e.truncated))}).catch(()=>{i&&h([])}).finally(()=>{i&&d(!1)}),()=>{i=!1}},[e,r,s,n]),(0,$.useEffect)(()=>{let e=e=>{e.detail>=2||m.current&&!m.current.contains(e.target)&&l()},s=e=>{if("Escape"===e.key)return void l();if((e.metaKey||e.ctrlKey)&&("c"===e.key||"C"===e.key)){let s=window.getSelection();if(s&&s.rangeCount>0&&!s.isCollapsed)return;e.preventDefault(),navigator.clipboard?.writeText(r)}};return document.addEventListener("mousedown",e),document.addEventListener("keydown",s),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",s)}},[l,r]);let g=(e,r)=>Number(r.file===i)-Number(e.file===i),x=u.filter(e=>"definition"===e.kind).sort(g),v=u.filter(e=>"reference"===e.kind).sort(g),_=Math.max(8,Math.min(a.x,window.innerWidth-440-8)),y=window.innerHeight-8-(a.y+18),b=a.y-18-8,w=y>=340||y>=b,S=Math.max(120,Math.min(340,w?y:b)),j=w?{top:a.y+18}:{bottom:window.innerHeight-(a.y-18)},C=({hit:e})=>(0,O.jsxs)("button",{type:"button",onClick:()=>{o(e.file,e.line),l()},className:"flex w-full flex-col items-start gap-0.5 rounded px-2 py-1.5 text-left hover:bg-accent",children:[(0,O.jsxs)("span",{className:"flex w-full items-baseline justify-between gap-2",children:[(0,O.jsxs)("span",{className:"truncate font-mono text-xs",children:[e.file.split("/").pop(),(0,O.jsxs)("span",{className:"text-muted-foreground",children:[":",e.line]})]}),e.file===i&&(0,O.jsx)("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:"this file"})]}),(0,O.jsx)("code",{className:"w-full truncate text-xs text-muted-foreground",children:e.text.trim()})]}),k=({title:e,children:r})=>(0,O.jsxs)("div",{className:"mb-1",children:[(0,O.jsx)("div",{className:"px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:e}),r]});return(0,ee.createPortal)((0,O.jsxs)("div",{ref:m,style:{left:_,...j,width:440,maxHeight:S},className:"fixed z-50 flex flex-col overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-lg select-none",children:[(0,O.jsx)("div",{className:"border-b px-3 py-1.5 text-xs font-medium",children:(0,O.jsx)("span",{className:"font-mono",children:r})}),(0,O.jsx)("div",{className:"flex-1 overflow-auto p-1",children:c?(0,O.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"})," Searching…"]}):0===u.length?(0,O.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No results."}):(0,O.jsxs)(O.Fragment,{children:[x.length>0&&(0,O.jsx)(k,{title:`Definitions (${x.length})`,children:x.map((e,r)=>(0,O.jsx)(C,{hit:e},`d-${r}`))}),v.length>0&&(0,O.jsx)(k,{title:`References (${v.length})`,children:v.map((e,r)=>(0,O.jsx)(C,{hit:e},`r-${r}`))}),f&&(0,O.jsx)("div",{className:"px-2 py-1.5 text-[11px] text-muted-foreground",children:"Showing first matches — results truncated."})]})})]}),document.body)}let SM=(0,ew.default)("image-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]);function SF({projectId:e,filePath:r,branch:s,target:n,onDownload:i}){let[a,o]=(0,$.useState)(null),[l,c]=(0,$.useState)(!1);return((0,$.useEffect)(()=>{let i=null,a=!1;return rv.api.getFileBlob(e,r,s,n).then(e=>{a||o(i=URL.createObjectURL(e))}).catch(()=>{a||c(!0)}),()=>{a=!0,i&&URL.revokeObjectURL(i)}},[e,r,s,n]),l)?(0,O.jsxs)("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[(0,O.jsx)(SM,{className:"h-10 w-10"}),(0,O.jsx)("p",{className:"text-sm",children:"Couldn't load image"}),(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:i,children:[(0,O.jsx)(Su,{className:"h-4 w-4 mr-2"}),"Download"]})]}):a?(0,O.jsx)("div",{className:"flex items-center justify-center h-full p-4 bg-muted/30",children:(0,O.jsx)("img",{src:a,alt:r.split("/").pop()??"image",className:"max-w-full max-h-full object-contain",onError:()=>c(!0)})}):(0,O.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,O.jsx)(sj,{className:"h-6 w-6 animate-spin"})})}async function SP(e,r){let s=await (0,Sj.codeToTokensBase)(e,{lang:r,theme:"one-light",includeExplanation:"scopeName"}),n=new Map;return s.forEach((e,r)=>{let s=0,i=[];for(let r of e){let e=(r.explanation??[]).flatMap(e=>e.scopes.map(e=>e.scopeName)),n=s+r.content.length;i.push({start:s,end:n,kind:e.some(e=>e.startsWith("comment"))?"comment":e.some(e=>e.startsWith("string")||e.startsWith("constant.character"))?"string":e.some(e=>e.startsWith("keyword")||e.startsWith("storage")||e.startsWith("constant.language")||e.startsWith("variable.language"))?"keyword":"code"}),s=n}n.set(r+1,i)}),n}let SI=new Set(["png","jpg","jpeg","gif","webp","bmp","ico","avif","svg"]);function SB(e){let r=e.split("/").pop()?.split(".").pop()?.toLowerCase()??"";return SI.has(r)}let SL=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Sz="symbol-nav";function SO(e,r,s){let n=document.createRange();return n.selectNodeContents(e),n.setEnd(r,s),n.toString().length}function S$(e,r){let s,n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),i=0;for(;s=n.nextNode();){let e=(s.textContent??"").length;if(r<=i+e)return{node:s,offset:r-i};i+=e}return null}function SW(e){let r=Array.from(document.querySelectorAll(`[data-line="${CSS.escape(e.line)}"]`)),s=r.find(e=>null!==e.offsetParent)??r[0];if(!s)return null;let n=S$(s,e.start),i=S$(s,e.end);if(!n||!i)return null;let a=document.createRange();return a.setStart(n.node,n.offset),a.setEnd(i.node,i.offset),a}let SH=/[A-Za-z0-9_$]/;function SU(e,r,s){let n=document,i=null,a=0;if(n.caretRangeFromPoint){let s=n.caretRangeFromPoint(e,r);s&&(i=s.startContainer,a=s.startOffset)}else if(n.caretPositionFromPoint){let s=n.caretPositionFromPoint(e,r);s&&(i=s.offsetNode,a=s.offset)}if(!i||i.nodeType!==Node.TEXT_NODE)return null;let o=i.textContent??"",l=a,c=a;for(;l>0&&SH.test(o[l-1]);)l--;for(;c<o.length&&SH.test(o[c]);)c++;if(l>=c)return null;let d=o.slice(l,c);if(!SL.test(d))return null;let u=document.createRange();u.setStart(i,l),u.setEnd(i,c);let h=function(e){let r=e.startContainer.nodeType===Node.ELEMENT_NODE?e.startContainer:e.startContainer.parentElement,s=r?.closest("[data-line]");if(!s||!s.contains(e.endContainer))return null;let n=s.getAttribute("data-line");if(null===n)return null;let i=SO(s,e.startContainer,e.startOffset),a=SO(s,e.endContainer,e.endOffset);return i>=a?null:{line:n,start:i,end:a}}(u);if(!h)return null;if(s){let e=h.start-h.line.length,r=function(e,r,s){let n=e.get(r);if(!n)return null;for(let e of n)if(s>=e.start&&s<e.end)return e.kind;return null}(s,Number(h.line),e);if(r&&"code"!==r)return null}return{word:d,anchor:h}}function Sq(){return"undefined"!=typeof CSS&&"highlights"in CSS&&"undefined"!=typeof Highlight}let SK=!1;function SV(){Sq()&&CSS.highlights.delete(Sz)}let SY={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",css:"css",scss:"scss",html:"html",vue:"vue",svelte:"svelte",php:"php",swift:"swift",kt:"kotlin",sh:"bash",bash:"bash",zsh:"bash",yaml:"yaml",yml:"yaml",toml:"toml",json:"json",xml:"xml",sql:"sql",graphql:"graphql",md:"markdown",mdx:"mdx",dockerfile:"dockerfile",makefile:"makefile",lua:"lua",r:"r",scala:"scala",zig:"zig"};function SG(e){let r=e.split("/").pop()?.toLowerCase()??"";return"dockerfile"===r?"dockerfile":"makefile"===r?"makefile":SY[r.split(".").pop()?.toLowerCase()??""]??"text"}function SX(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function SJ({filePath:e,fileContent:r,loading:s,downloadUrl:n,projectId:i,branch:a,target:o,scrollToLine:l,scrollKey:c,onJump:d,restoreScrollTop:u,restoreScrollKey:h,onScroll:f}){let p,[m,g]=(0,$.useState)("rendered"),[x,v]=(0,$.useState)(e),[_,y]=(0,$.useState)(null),b=(0,$.useRef)(null),w=(0,$.useRef)(null),S=(0,$.useRef)(!1);(0,$.useEffect)(()=>{S.current=null!==_},[_]);let j=(0,$.useCallback)(e=>{if(e.detail>=2){let r=window.getSelection();if(S.current){r?.removeAllRanges(),y(e=>e?{...e,selectWord:!0}:e);return}let s=SU(e.clientX,e.clientY),n=s?SW(s.anchor):null;n&&(r?.removeAllRanges(),r?.addRange(n));return}let r=window.getSelection();if(r&&!r.isCollapsed)return;let s=SU(e.clientX,e.clientY,b.current);s&&(r?.removeAllRanges(),y({symbol:s.word,x:e.clientX,y:e.clientY,anchor:s.anchor,selectWord:!1}))},[]),C=(0,$.useCallback)(e=>{e.detail>=2&&e.preventDefault()},[]);(0,$.useEffect)(()=>{if(!_?.anchor)return void SV();let e=SW(_.anchor);if(!e)return void SV();if(_.selectWord){SV();let r=window.getSelection();r?.removeAllRanges(),r?.addRange(e);return}return Sq()?(!function(){if(SK||"undefined"==typeof document)return;SK=!0;let e=document.createElement("style");e.textContent=`::highlight(${Sz}){background-color:rgba(255, 196, 0, 0.32);}`,document.head.appendChild(e)}(),CSS.highlights.set(Sz,new Highlight(e)),SV):void SV()},[_]),(0,$.useEffect)(()=>{b.current=null;let s=r?.content;if(!e||null==s||r?.binary||r?.tooLarge)return;let n=!1;return SP(s,SG(e)).then(e=>{n||(b.current=e)}).catch(()=>{}),()=>{n=!0}},[e,r]);let k=(0,$.useRef)(null),N=(0,$.useRef)(null),E=(0,$.useCallback)(e=>{let r=k.current;if(!r)return;let s=r.querySelector(`[id="${CSS.escape(e)}"]`);if(!s)return;N.current?.();let n=()=>s.scrollIntoView({block:"start",behavior:"auto"});n();let i=new ResizeObserver(n);i.observe(r);let a=()=>{i.disconnect(),window.clearTimeout(o),window.removeEventListener("wheel",a),window.removeEventListener("touchmove",a),window.removeEventListener("keydown",a),N.current=null},o=window.setTimeout(a,1e3);window.addEventListener("wheel",a,{passive:!0}),window.addEventListener("touchmove",a,{passive:!0}),window.addEventListener("keydown",a),N.current=a},[]);(0,$.useEffect)(()=>()=>N.current?.(),[]);let D=(0,$.useRef)(null),R=(0,$.useRef)(!1),A=(0,$.useRef)(f);A.current=f;let T=(0,$.useRef)(null),M=(0,$.useRef)(null),F=(0,$.useCallback)(e=>{if(R.current)return;let r=e.currentTarget.scrollTop;T.current&&clearTimeout(T.current),T.current=setTimeout(()=>A.current?.(r),200)},[]);(0,$.useEffect)(()=>{void 0!==h&&(M.current=u??0)},[h,u]),(0,$.useEffect)(()=>{let e=D.current;e&&(e.scrollTop=0)},[e]),(0,$.useEffect)(()=>{let e=M.current;if(null==e)return;let r=D.current;if(!r||(M.current=null,!e))return;R.current=!0;let s=()=>{r.scrollTop=e};s();let n=new ResizeObserver(s);n.observe(r.firstElementChild??r);let i=()=>{R.current=!1,n.disconnect(),window.clearTimeout(a),r.removeEventListener("wheel",i),r.removeEventListener("touchmove",i),r.removeEventListener("keydown",i)},a=window.setTimeout(i,1500);return r.addEventListener("wheel",i,{passive:!0}),r.addEventListener("touchmove",i,{passive:!0}),r.addEventListener("keydown",i),i},[r]);let P=(0,$.useMemo)(()=>[...Object.values(Sw.e),Sb],[]),I=(0,$.useMemo)(()=>({a:({href:e,children:r,className:s,node:n,...i})=>{let a="string"==typeof e&&e.startsWith("#");return(0,O.jsx)("a",{href:e,className:(0,ey.cn)("wrap-anywhere font-medium text-primary underline",s),"data-streamdown":"link",...a?{onClick:r=>{r.preventDefault(),E(decodeURIComponent(e.slice(1)))}}:{target:"_blank",rel:"noreferrer"},...i,children:r})}}),[E]);if(e!==x&&(v(e),g("rendered"),y(null)),!e)return(0,O.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Select a file to preview."});if(s)return(0,O.jsxs)("div",{className:"flex flex-col h-full",children:[(0,O.jsx)("div",{className:"flex items-center justify-between px-4 py-2 border-b flex-shrink-0",children:(0,O.jsx)(SA,{className:"h-4 w-48"})}),(0,O.jsxs)("div",{className:"flex-1 p-4",children:[(0,O.jsx)(SA,{className:"h-4 w-full mb-2"}),(0,O.jsx)(SA,{className:"h-4 w-3/4 mb-2"}),(0,O.jsx)(SA,{className:"h-4 w-5/6 mb-2"}),(0,O.jsx)(SA,{className:"h-4 w-2/3"})]})]});if(!r)return(0,O.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Failed to load file."});let B=()=>{e&&rv.api.downloadFile(i,e,a,o).catch(e=>{console.error("Failed to download file",e)})},L=("markdown"===(p=SG(e))||"mdx"===p)&&!r.tooLarge&&!r.binary&&!!r.content,z=L&&"rendered"===m,H=!r.tooLarge&&!r.binary&&!z&&null!==r.content;return(0,O.jsxs)("div",{className:"flex flex-col h-full",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b flex-shrink-0 gap-2",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,O.jsx)("span",{className:"text-sm font-mono truncate",children:e}),(0,O.jsx)("span",{className:"text-xs text-muted-foreground shrink-0",children:SX(r.size)})]}),(0,O.jsxs)("div",{className:"flex items-center gap-1 shrink-0",children:[L&&(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(e=>"rendered"===e?"source":"rendered"),title:z?"View source":"View rendered",children:z?(0,O.jsx)(Sf,{className:"h-3.5 w-3.5"}):(0,O.jsx)(wf,{className:"h-3.5 w-3.5"})}),H&&(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>w.current?.foldAll(),title:"Fold all",children:(0,O.jsx)(Sp,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>w.current?.expandAll(),title:"Expand all",children:(0,O.jsx)(Sm,{className:"h-3.5 w-3.5"})})]}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{navigator.clipboard.writeText(e)},title:"Copy path",children:(0,O.jsx)(fq.Copy,{className:"h-3.5 w-3.5"})}),n&&(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:B,title:"Download",children:(0,O.jsx)(Su,{className:"h-3.5 w-3.5"})})]})]}),(0,O.jsx)("div",{className:"flex-1 overflow-auto",ref:D,onScroll:F,children:r.tooLarge?(0,O.jsxs)("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[(0,O.jsx)(Sh,{className:"h-10 w-10"}),(0,O.jsxs)("p",{className:"text-sm",children:["File too large to preview (",SX(r.size),")"]}),n&&(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:B,children:[(0,O.jsx)(Su,{className:"h-4 w-4 mr-2"}),"Download"]})]}):r.binary&&SB(e)&&r.size<=0xa00000?(0,O.jsx)(SF,{projectId:i,filePath:e,branch:a,target:o,onDownload:B},e):r.binary?(0,O.jsxs)("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[(0,O.jsx)(Sh,{className:"h-10 w-10"}),(0,O.jsx)("p",{className:"text-sm",children:SB(e)?`Image too large to preview (${SX(r.size)})`:`Binary file (${SX(r.size)})`}),n&&(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:B,children:[(0,O.jsx)(Su,{className:"h-4 w-4 mr-2"}),"Download"]})]}):z?(0,O.jsx)("div",{className:"p-4",style:{fontSize:"var(--files-content-font-size, 14px)"},ref:k,children:(0,O.jsx)(cD,{components:I,rehypePlugins:P,children:r.content??""})}):null!==r.content?(0,O.jsx)("div",{className:"h-full [&_pre]:text-[length:var(--files-content-font-size,14px)]! [&_code]:text-[length:var(--files-content-font-size,14px)]!",onMouseDown:C,onClick:j,children:(0,O.jsx)(SD,{ref:w,code:r.content,language:SG(e),showLineNumbers:!0,foldable:!0,scrollToLine:l,scrollKey:c,className:"border-0 rounded-none",children:(0,O.jsx)(SR,{})})}):(0,O.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Empty file."})}),_&&(0,O.jsx)(ST,{projectId:i,symbol:_.symbol,branch:a,target:o,currentFile:e,anchor:{x:_.x,y:_.y},onJump:d,onClose:()=>y(null)})]})}class SZ{capacity;map;constructor(e){if(this.capacity=e,this.map=new Map,e<1)throw Error("LRUCache capacity must be at least 1")}get(e){if(!this.map.has(e))return;let r=this.map.get(e);return this.map.delete(e),this.map.set(e,r),r}has(e){return this.map.has(e)}set(e,r){for(this.map.has(e)&&this.map.delete(e),this.map.set(e,r);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(void 0===e)break;this.map.delete(e)}}delete(e){return this.map.delete(e)}deleteWhere(e){for(let r of[...this.map.keys()])e(r)&&this.map.delete(r)}clear(){this.map.clear()}get size(){return this.map.size}}let SQ="vibedeckx:files:views";function S0(){return{v:1,views:{}}}function S1(){try{let e=localStorage.getItem(SQ);if(!e)return S0();let r=JSON.parse(e);if(!r||1!==r.v||!r.views||"object"!=typeof r.views)return S0();return r}catch{return S0()}}function S2(e){try{localStorage.setItem(SQ,JSON.stringify(e))}catch{}}function S5(e){return e.slice(e.lastIndexOf("\0")+1)}let S3=new Set(["/","-","_","."," "]);function S4({projectId:e,project:r,selectedBranch:s,navRequest:n}){let i=r&&!r.path?"remote":void 0,[a,o]=(0,$.useState)(!1),{settings:l}=(0,hG.useConversationSettings)(),c=(0,$.useRef)(null),[d,u]=(0,$.useState)(!1),h=(0,$.useCallback)(()=>{let e=c.current;e&&(e.isCollapsed()?e.expand():e.collapse())},[]),{rootEntries:f,directoryContents:p,expandedDirs:m,selectedFile:g,fileContent:x,fileLoading:v,rootLoading:_,loadingDirs:y,uploadingDirs:b,deletingPaths:w,jumpTarget:S,canGoBack:j,canGoForward:C,fetchRoot:k,refresh:N,reportScroll:E,restoreScroll:D,toggleDirectory:R,navigate:A,jumpTo:T,goBack:M,goForward:F,uploadFiles:P,deleteEntry:I}=function({projectId:e,branch:r,target:s,showHidden:n=!1}){let[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)(new Map),[c,d]=(0,$.useState)(new Set),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(null),[m,g]=(0,$.useState)(null),x=(0,$.useRef)(0),[v,_]=(0,$.useState)({entries:[],index:-1}),y=(0,$.useRef)(v);y.current=v;let[b,w]=(0,$.useState)(!1),[S,j]=(0,$.useState)(!1),[C,k]=(0,$.useState)(new Set),[N,E]=(0,$.useState)(new Set),[D,R]=(0,$.useState)(new Set),A=(0,$.useRef)(0),T=(0,$.useRef)(0),M=(0,$.useRef)(new SZ(50)),F=e?[e,r??"",s??""].join("|"):null,P=(0,$.useRef)(F);P.current=F;let I=(0,$.useRef)(u);I.current=u;let B=(0,$.useRef)(0),L=(0,$.useRef)(null),z=(0,$.useRef)(0),[O,W]=(0,$.useState)(null),H=(0,$.useRef)(null),U=(0,$.useCallback)(n=>[e,r??"",s??"",n].join("\0"),[e,r,s]),q=(0,$.useCallback)(()=>{let e,r,s=P.current;if(!s||L.current!==s)return;let n={selectedFile:I.current,history:y.current,scrollTop:B.current};(e=S1()).views[s]={...n,updatedAt:Date.now()},(r=Object.keys(e.views)).length>30&&r.sort((r,s)=>e.views[r].updatedAt-e.views[s].updatedAt).slice(0,r.length-30).forEach(r=>delete e.views[r]),S2(e)},[]),K=(0,$.useCallback)(()=>{H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{H.current=null,q()},300)},[q]),V=(0,$.useCallback)(e=>{B.current=e,K()},[K]);(0,$.useEffect)(()=>{K()},[u,v,K]);let Y=(0,$.useCallback)(async i=>{if(e&&(d(e=>{let r=new Set(e);return r.has(i)?r.delete(i):r.add(i),r}),!o.has(i))){k(e=>new Set(e).add(i));try{let a=await rv.api.browseProjectDirectory(e,i,r,s,n);l(e=>{let r=new Map(e);return r.set(i,a.items),r})}catch(e){console.error("Failed to browse directory:",e),_Z.toast.error(`Failed to open ${i}`,{description:e instanceof Error?e.message:String(e)})}finally{k(e=>{let r=new Set(e);return r.delete(i),r})}}},[e,r,s,n,o]),G=(0,$.useCallback)(async n=>{if(!e)return"failed";let i=U(n),a=M.current.get(i);if(a)return p(a),w(!1),"loaded";let o=++T.current;w(!0),p(null);try{let a=await rv.api.getFileContent(e,n,r,s);if(o!==T.current)return"stale";return M.current.set(i,a),p(a),"loaded"}catch(e){if(o!==T.current)return"stale";return console.error("Failed to get file content:",e),p(null),"failed"}finally{o===T.current&&w(!1)}},[e,r,s,U]),X=(0,$.useCallback)(async r=>{e&&(h(r),await G(r))},[e,G]),J=(0,$.useCallback)(async()=>{if(!e)return!1;j(!0);let i=++A.current;try{let o=await rv.api.browseProjectDirectory(e,void 0,r,s,n);if(i!==A.current)return!1;return a(o.items),l(new Map),d(new Set),!0}catch(e){if(console.error("Failed to browse root directory:",e),i!==A.current)return!1;return a([]),_Z.toast.error("Failed to browse files",{description:e instanceof Error?e.message:String(e)}),!1}finally{i===A.current&&j(!1)}},[e,r,s,n]),Z=(0,$.useCallback)(async()=>{let r;if(!e||!await J())return;let s=P.current,n=s?(r=S1().views[s])&&"object"==typeof r&&(null===r.selectedFile||"string"==typeof r.selectedFile)&&r.history&&"object"==typeof r.history&&Array.isArray(r.history.entries)&&"number"==typeof r.history.index?{selectedFile:r.selectedFile,history:r.history,scrollTop:"number"==typeof r.scrollTop&&Number.isFinite(r.scrollTop)?r.scrollTop:0}:null:null;if(s&&n&&n.selectedFile){if(_(n.history.entries.length?n.history:{entries:[{path:n.selectedFile,line:null}],index:0}),B.current=n.scrollTop,W({top:n.scrollTop,nonce:++z.current}),h(n.selectedFile),L.current=s,"failed"===await G(n.selectedFile)){let e;h(null),_({entries:[],index:-1}),B.current=0,(e=S1()).views[s]&&(delete e.views[s],S2(e))}}else h(null),p(null),_({entries:[],index:-1}),B.current=0,L.current=s},[e,J,G]),Q=(0,$.useCallback)(async()=>{if(!e||(M.current.clear(),!await J()))return;let r=I.current;r&&await G(r)},[e,J,G]),ee=(0,$.useCallback)(async(e,r=null)=>{_(({entries:s,index:n})=>{let i=s[n];if(i&&i.path===e){let i=s.slice();return i[n]={path:e,line:r},{entries:i,index:n}}let a=s.slice(0,n+1);return{entries:[...a,{path:e,line:r}],index:a.length}}),await X(e),null!=r&&g({line:r,nonce:++x.current})},[X]),et=(0,$.useCallback)((e,r)=>ee(e,r),[ee]),er=(0,$.useCallback)(()=>{let{entries:e,index:r}=y.current;if(r<=0)return;let s=e[r-1];_(e=>({...e,index:e.index-1})),X(s.path),null!=s.line&&g({line:s.line,nonce:++x.current})},[X]),es=(0,$.useCallback)(()=>{let{entries:e,index:r}=y.current;if(r>=e.length-1)return;let s=e[r+1];_(e=>({...e,index:e.index+1})),X(s.path),null!=s.line&&g({line:s.line,nonce:++x.current})},[X]),en=(0,$.useCallback)(async i=>{if(e)if(""===i)a((await rv.api.browseProjectDirectory(e,void 0,r,s,n)).items);else{let a=await rv.api.browseProjectDirectory(e,i,r,s,n);l(e=>{let r=new Map(e);return r.set(i,a.items),r})}},[e,r,s,n]),ei=(0,$.useCallback)(async(n,i)=>{if(e&&0!==i.length){E(e=>new Set(e).add(n));try{let{uploaded:a}=await rv.api.uploadFiles(e,i,n,r,s),o=new Set(a.map(e=>n?`${n}/${e}`:e));M.current.deleteWhere(e=>o.has(S5(e))),""!==n&&d(e=>new Set(e).add(n)),await en(n),_Z.toast.success(`Uploaded ${a.length} file${1===a.length?"":"s"}`)}catch(e){console.error("Failed to upload files:",e),_Z.toast.error("Upload failed",{description:e instanceof Error?e.message:String(e)})}finally{E(e=>{let r=new Set(e);return r.delete(n),r})}}},[e,r,s,en]),ea=(0,$.useCallback)(async n=>{if(e&&n){R(e=>new Set(e).add(n));try{await rv.api.deleteFile(e,n,r,s),M.current.deleteWhere(e=>{let r=S5(e);return r===n||r.startsWith(`${n}/`)}),h(e=>e===n||e&&e.startsWith(`${n}/`)?(p(null),null):e);let i=n.includes("/")?n.slice(0,n.lastIndexOf("/")):"";await en(i),_Z.toast.success("Deleted")}catch(e){console.error("Failed to delete:",e),_Z.toast.error("Delete failed",{description:e instanceof Error?e.message:String(e)})}finally{R(e=>{let r=new Set(e);return r.delete(n),r})}}},[e,r,s,en]);return{rootEntries:i,directoryContents:o,expandedDirs:c,selectedFile:u,fileContent:f,fileLoading:b,rootLoading:S,loadingDirs:C,uploadingDirs:N,deletingPaths:D,jumpTarget:m,canGoBack:v.index>0,canGoForward:v.index<v.entries.length-1,fetchRoot:Z,refresh:Q,reportScroll:V,restoreScroll:O,toggleDirectory:Y,selectFile:X,navigate:ee,jumpTo:et,goBack:er,goForward:es,uploadFiles:ei,refreshDirectory:en,deleteEntry:ea}}({projectId:e,branch:s,target:i,showHidden:a}),B=function({projectId:e,branch:r,target:s}){let[n,i]=(0,$.useState)([]),[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(!1),[d,u]=(0,$.useState)(!1),[h,f]=(0,$.useState)(""),p=(0,$.useRef)(0);(0,$.useEffect)(()=>{i([]),o(!1),u(!1),c(!1),f(""),p.current++},[e,r,s]);let m=(0,$.useCallback)(async()=>{if(!e)return;c(!0);let n=++p.current;try{let a=await rv.api.listProjectFiles(e,r,s);if(n!==p.current)return;i(a.files),o(a.truncated),u(!0)}catch(e){if(n!==p.current)return;i([]),u(!1),_Z.toast.error("Failed to load file list",{description:e instanceof Error?e.message:String(e)})}finally{n===p.current&&c(!1)}},[e,r,s]),g=(0,$.useCallback)(()=>{d||l||m()},[d,l,m]),x=(0,$.useCallback)(()=>{u(!1),p.current++,h&&m()},[h,m]),v=(0,$.useDeferredValue)(h);return{query:h,setQuery:f,results:(0,$.useMemo)(()=>(function(e,r,s){if(!r.trim())return[];let n=[];for(let s of e){let e=function(e,r){let s=e.toLowerCase().replace(/\s+/g,"");if(!s)return null;let n=r.toLowerCase(),i=r.lastIndexOf("/")+1,a=0,o=0,l=-2;for(let e=0;e<s.length;e++){let c=s[e],d=-1;for(;o<n.length;o++)if(n[o]===c){d=o;break}if(-1===d)return null;let u=1;d===l+1&&(u+=5),d>=i&&(u+=3);let h=d>0?r[d-1]:"/";(0===d||d===i||S3.has(h))&&(u+=4),a+=u,l=d,o=d+1}return a+.1*Math.max(0,40-r.length)}(r,s);null!==e&&n.push({path:s,score:e})}return n.sort((e,r)=>r.score-e.score||e.path.length-r.path.length),n.slice(0,50)})(n,v,0),[n,v]),truncated:a,loading:l,loaded:d,ensureLoaded:g,refresh:x}}({projectId:e,branch:s,target:i});(0,$.useEffect)(()=>{k()},[k]),(0,$.useEffect)(()=>{n&&(null!=n.line?T(n.path,n.line):A(n.path))},[n?.nonce]);let L=(0,$.useCallback)(()=>{N(),B.refresh()},[N,B]),z=(0,$.useCallback)(e=>{A(e),B.setQuery("")},[A,B]);if(!e)return(0,O.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(fK,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to browse files."})]})});let H=g&&e?rv.api.getFileDownloadUrl(e,g,s,i):null;return(0,O.jsxs)("div",{className:"flex flex-col h-full",style:{"--files-tree-font-size":`${l.filesTreeFontSize}px`,"--files-content-font-size":`${l.filesContentFontSize}px`},children:[(0,O.jsx)(dh,{title:"Files",actions:(0,O.jsxs)("div",{className:"flex items-center gap-1",children:[(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:h,title:d?"Show file tree":"Hide file tree","aria-pressed":!d,children:d?(0,O.jsx)(wg,{className:"h-3.5 w-3.5"}):(0,O.jsx)(wm,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:`h-7 w-7 hover:text-foreground ${a?"text-foreground":"text-muted-foreground"}`,onClick:()=>o(e=>!e),title:a?"Hide hidden files":"Show hidden files","aria-pressed":a,children:a?(0,O.jsx)(wf,{className:"h-3.5 w-3.5"}):(0,O.jsx)(wp,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:M,disabled:!j,title:"Back",children:(0,O.jsx)(o9.ArrowLeft,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:F,disabled:!C,title:"Forward",children:(0,O.jsx)(wx,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:L,title:"Refresh",children:(0,O.jsx)(fK,{className:`h-3.5 w-3.5 ${_?"animate-spin":""}`})})]})}),(0,O.jsxs)(uj,{direction:"horizontal",autoSaveId:"files-panels",className:"flex-1",children:[(0,O.jsx)(dN,{ref:c,collapsible:!0,collapsedSize:0,defaultSize:33,minSize:20,onCollapse:()=>u(!0),onExpand:()=>u(!1),children:(0,O.jsxs)(w5,{shouldFilter:!1,className:"flex h-full flex-col bg-transparent",children:[(0,O.jsx)("div",{className:"border-b p-2",children:(0,O.jsxs)(wv,{children:[(0,O.jsx)(wy,{children:(0,O.jsx)(sA,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(wS,{type:"search",name:"files-search",autoComplete:"off","data-1p-ignore":!0,"data-lpignore":"true","data-form-type":"other",readOnly:!0,onFocus:e=>{e.currentTarget.removeAttribute("readonly"),B.ensureLoaded()},placeholder:"Search files...",value:B.query,onChange:e=>B.setQuery(e.target.value)}),B.query&&(0,O.jsx)(wy,{align:"inline-end",children:(0,O.jsx)(ww,{size:"icon-xs","aria-label":"Clear search",onClick:()=>B.setQuery(""),children:(0,O.jsx)(t7,{className:"h-3.5 w-3.5"})})})]})}),B.query?(0,O.jsx)(w6,{className:"max-h-none flex-1",children:B.loading&&0===B.results.length?(0,O.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"}),"Loading files…"]}):0===B.results.length?(0,O.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No matching files."}):(0,O.jsxs)(O.Fragment,{children:[B.results.map(e=>{let r=e.path.lastIndexOf("/"),s=r>=0?e.path.slice(0,r+1):"",n=r>=0?e.path.slice(r+1):e.path;return(0,O.jsxs)(w9,{value:e.path,onSelect:()=>z(e.path),className:"flex-col items-start gap-0 text-[length:var(--files-tree-font-size,14px)]!",children:[(0,O.jsx)("span",{className:"font-medium",children:n}),s&&(0,O.jsx)("span",{className:"w-full truncate text-xs text-muted-foreground",children:s})]},e.path)}),B.truncated&&(0,O.jsx)("div",{className:"px-2 py-2 text-xs text-muted-foreground",children:"Showing first 50,000 files — refine your search to narrow results."})]})}):(0,O.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,O.jsx)(Sd,{entries:f,expandedDirs:m,directoryContents:p,loadingDirs:y,selectedFile:g,uploadingDirs:b,rootLoading:_,deletingPaths:w,onToggleDirectory:R,onSelectFile:A,onUploadFiles:P,onDeleteEntry:I})})]})}),(0,O.jsx)(uC,{withHandle:!0}),(0,O.jsx)(dN,{defaultSize:67,minSize:25,children:(0,O.jsx)("div",{className:"h-full overflow-hidden",children:(0,O.jsx)(SJ,{filePath:g,fileContent:x,loading:v,downloadUrl:H,projectId:e,branch:s,target:i,scrollToLine:S?.line??null,scrollKey:S?.nonce,onJump:T,restoreScrollTop:D?.top??null,restoreScrollKey:D?.nonce,onScroll:E})})})]})]})}let S6=(0,$.createContext)(null),S7={openFile:()=>{},index:null};function S8(){return(0,$.useContext)(S6)??S7}let S9=S6.Provider,je=0;function jt(e){let r=e.lastIndexOf("/");return r>=0?e.slice(r+1):e}let jr=[500,1e3,2e3,4e3,8e3];async function js(e,r={}){let s=r.delaysMs??jr,n=r.sleep??(e=>new Promise(r=>setTimeout(r,e))),i=r.cancelled??(()=>!1);for(let r=0;;r++){if(i())return null;let a=null;try{a=await e()}catch{a=null}if(i())return null;if(a&&a.files.length>0||r>=s.length)return a;await n(s[r])}}let jn={agent:sb,executors:ol,diff:sU,terminal:hq,preview:ry,files:r_},ji=_Q.map(e=>({...e,icon:jn[e.id]})),ja=()=>()=>{},jo=$.useLayoutEffect;function jl({projectId:e,selectedBranch:r,onMergeRequest:s,project:n,onExecutorModeChange:i,agentSlot:a,activateAgentTabNonce:o,diffCompareNonce:l,mergeTarget:c,forceAgentTab:d=!1,active:u=!0}){let[h,f]=function(e,r){let s=`vibedeckx:activeTab:${e??"none"}:${r??"main"}`,[n,i]=(0,$.useState)(()=>localStorage.getItem(s)??"agent");return jo(()=>{i(localStorage.getItem(s)??"agent")},[s]),[n,(0,$.useCallback)(e=>{i(e),localStorage.setItem(s,e)},[s])]}(e,r),p=d?"agent":h,m=(0,$.useRef)(o);jo(()=>{void 0===o||m.current!==o&&(m.current=o,f("agent"))},[o,f]);let g=(0,$.useRef)(l);jo(()=>{void 0===l||g.current!==l&&(g.current=l,f("diff"))},[l,f]),(0,$.useEffect)(()=>{if(!u)return;let e=e=>{let r=_2(e);r&&(e.preventDefault(),f(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[u,f]);let x=(0,$.useSyncExternalStore)(ja,_1,()=>!1),v=function({projectId:e,branch:r,target:s,enabled:n=!0}){let[i,a]=(0,$.useState)(null),o=(0,$.useRef)(0);return(0,$.useEffect)(()=>{if(a(null),!n||!e)return;let i=++o.current;js(()=>rv.api.listProjectFiles(e,r,s),{cancelled:()=>i!==o.current}).then(e=>{i===o.current&&e&&a(function(e){let r=`idx-${++je}`,s=new Set(e),n=new Map;for(let r of e){let e=jt(r),s=n.get(e);s?s.push(r):n.set(e,[r])}return{version:r,resolve(e){if(!e)return[];let r=e.replace(/^\/+/,"");if(!r)return[];if(r.includes("/")){if(s.has(r))return[r];let e=jt(r);return(n.get(e)??[]).filter(e=>e===r||e.endsWith("/"+r)||r.endsWith("/"+e))}return n.get(r)??[]}}}(e.files))})},[e,r,s,n]),i}({projectId:e,branch:r,target:n&&!n.path?"remote":void 0,enabled:u}),_=(0,$.useRef)(0),[y,b]=(0,$.useState)(null),w=(0,$.useCallback)((e,r=null)=>{f("files"),b({path:e,line:r,nonce:++_.current})},[f]),S=(0,$.useMemo)(()=>({openFile:w,index:v}),[w,v]);return(0,O.jsx)(S9,{value:S,children:(0,O.jsxs)("div",{className:"h-full flex flex-col",children:[(0,O.jsx)("div",{className:"flex items-center px-3 gap-4 border-b border-border",children:ji.map(({id:e,icon:r,label:s,code:n})=>(0,O.jsxs)($.Fragment,{children:[(0,O.jsxs)("button",{onClick:()=>f(e),title:`${s} (${_5(x,n)})`,className:(0,ey.cn)("flex items-center gap-0.5 py-2.5 text-xs font-medium border-b-2 transition-colors",p===e?"text-foreground border-primary":"text-muted-foreground border-transparent hover:text-foreground/70"),children:[(0,O.jsx)(r,{className:"h-3.5 w-3.5"}),s]}),"agent"===e&&(0,O.jsx)("span",{className:"h-4 w-px bg-border/60 mx-1.5","aria-hidden":!0})]},e))}),(0,O.jsxs)("div",{className:"relative flex-1 overflow-hidden",children:[(0,O.jsx)("div",{className:(0,ey.cn)("absolute inset-0 overflow-hidden","agent"!==p&&"invisible pointer-events-none"),children:a}),(0,O.jsx)("div",{className:(0,ey.cn)("absolute inset-0 overflow-hidden","executors"!==p&&"hidden"),children:(0,O.jsx)(b5,{projectId:e,selectedBranch:r,project:n,onExecutorModeChange:i})}),(0,O.jsx)("div",{className:(0,ey.cn)("absolute inset-0 overflow-hidden","diff"!==p&&"hidden"),children:(0,O.jsx)(ws,{projectId:e,selectedBranch:r,onMergeRequest:s,project:n,mergeTarget:c,compareRequestNonce:l})}),(0,O.jsx)("div",{className:(0,ey.cn)("absolute inset-0 overflow-hidden","terminal"!==p&&"hidden"),children:(0,O.jsx)(wi,{projectId:e,selectedBranch:r,project:n})}),(0,O.jsx)("div",{className:(0,ey.cn)("absolute inset-0 overflow-hidden","preview"!==p&&"hidden"),children:(0,O.jsx)(wh,{projectId:e,selectedBranch:r,project:n})}),(0,O.jsx)("div",{className:(0,ey.cn)("absolute inset-0 overflow-hidden","files"!==p&&"hidden"),children:(0,O.jsx)(S4,{projectId:e,project:n,selectedBranch:r,navRequest:y})})]})]})})}var jc=Symbol.for("immer-nothing"),jd=Symbol.for("immer-draftable"),ju=Symbol.for("immer-state");function jh(e){throw Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var jf=Object.getPrototypeOf;function jp(e){return!!e&&!!e[ju]}function jm(e){return!!e&&(jv(e)||Array.isArray(e)||!!e[jd]||!!e.constructor?.[jd]||jS(e)||jj(e))}var jg=Object.prototype.constructor.toString(),jx=new WeakMap;function jv(e){if(!e||"object"!=typeof e)return!1;let r=Object.getPrototypeOf(e);if(null===r||r===Object.prototype)return!0;let s=Object.hasOwnProperty.call(r,"constructor")&&r.constructor;if(s===Object)return!0;if("function"!=typeof s)return!1;let n=jx.get(s);return void 0===n&&(n=Function.toString.call(s),jx.set(s,n)),n===jg}function j_(e,r,s=!0){0===jy(e)?(s?Reflect.ownKeys(e):Object.keys(e)).forEach(s=>{r(s,e[s],e)}):e.forEach((s,n)=>r(n,s,e))}function jy(e){let r=e[ju];return r?r.type_:Array.isArray(e)?1:jS(e)?2:3*!!jj(e)}function jb(e,r){return 2===jy(e)?e.has(r):Object.prototype.hasOwnProperty.call(e,r)}function jw(e,r,s){let n=jy(e);2===n?e.set(r,s):3===n?e.add(s):e[r]=s}function jS(e){return e instanceof Map}function jj(e){return e instanceof Set}function jC(e){return e.copy_||e.base_}function jk(e,r){if(jS(e))return new Map(e);if(jj(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let s=jv(e);if(!0!==r&&("class_only"!==r||s)){let r=jf(e);return null!==r&&s?{...e}:Object.assign(Object.create(r),e)}{let r=Object.getOwnPropertyDescriptors(e);delete r[ju];let s=Reflect.ownKeys(r);for(let n=0;n<s.length;n++){let i=s[n],a=r[i];!1===a.writable&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[i]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[i]})}return Object.create(jf(e),r)}}function jN(e,r=!1){return jD(e)||jp(e)||!jm(e)||(jy(e)>1&&Object.defineProperties(e,{set:jE,add:jE,clear:jE,delete:jE}),Object.freeze(e),r&&Object.values(e).forEach(e=>jN(e,!0))),e}var jE={value:function(){jh(2)}};function jD(e){return null===e||"object"!=typeof e||Object.isFrozen(e)}var jR={};function jA(e){let r=jR[e];return r||jh(0,e),r}function jT(e,r){r&&(jA("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=r)}function jM(e){jF(e),e.drafts_.forEach(jI),e.drafts_=null}function jF(e){e===L&&(L=e.parent_)}function jP(e){return L={drafts_:[],parent_:L,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function jI(e){let r=e[ju];0===r.type_||1===r.type_?r.revoke_():r.revoked_=!0}function jB(e,r){r.unfinalizedDrafts_=r.drafts_.length;let s=r.drafts_[0];return void 0!==e&&e!==s?(s[ju].modified_&&(jM(r),jh(4)),jm(e)&&(e=jL(r,e),r.parent_||jO(r,e)),r.patches_&&jA("Patches").generateReplacementPatches_(s[ju].base_,e,r.patches_,r.inversePatches_)):e=jL(r,s,[]),jM(r),r.patches_&&r.patchListener_(r.patches_,r.inversePatches_),e!==jc?e:void 0}function jL(e,r,s){if(jD(r))return r;let n=e.immer_.shouldUseStrictIteration(),i=r[ju];if(!i)return j_(r,(n,a)=>jz(e,i,r,n,a,s),n),r;if(i.scope_!==e)return r;if(!i.modified_)return jO(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;let r=i.copy_,a=r,o=!1;3===i.type_&&(a=new Set(r),r.clear(),o=!0),j_(a,(n,a)=>jz(e,i,r,n,a,s,o),n),jO(e,r,!1),s&&e.patches_&&jA("Patches").generatePatches_(i,s,e.patches_,e.inversePatches_)}return i.copy_}function jz(e,r,s,n,i,a,o){if(null==i||"object"!=typeof i&&!o)return;let l=jD(i);if(!l||o){if(jp(i)){let o=jL(e,i,a&&r&&3!==r.type_&&!jb(r.assigned_,n)?a.concat(n):void 0);if(jw(s,n,o),!jp(o))return;e.canAutoFreeze_=!1}else o&&s.add(i);if(jm(i)&&!l){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||r&&r.base_&&r.base_[n]===i&&l)return;jL(e,i),(!r||!r.scope_.parent_)&&"symbol"!=typeof n&&(jS(s)?s.has(n):Object.prototype.propertyIsEnumerable.call(s,n))&&jO(e,i)}}}function jO(e,r,s=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&jN(r,s)}var j$={get(e,r){if(r===ju)return e;let s=jC(e);if(!jb(s,r)){var n;let i;return n=e,(i=jU(s,r))?"value"in i?i.value:i.get?.call(n.draft_):void 0}let i=s[r];return e.finalized_||!jm(i)?i:i===jH(e.base_,r)?(jK(e),e.copy_[r]=jV(i,e)):i},has:(e,r)=>r in jC(e),ownKeys:e=>Reflect.ownKeys(jC(e)),set(e,r,s){let n=jU(jC(e),r);if(n?.set)return n.set.call(e.draft_,s),!0;if(!e.modified_){let n=jH(jC(e),r),i=n?.[ju];if(i&&i.base_===s)return e.copy_[r]=s,e.assigned_[r]=!1,!0;if((s===n?0!==s||1/s==1/n:s!=s&&n!=n)&&(void 0!==s||jb(e.base_,r)))return!0;jK(e),jq(e)}return!!(e.copy_[r]===s&&(void 0!==s||r in e.copy_)||Number.isNaN(s)&&Number.isNaN(e.copy_[r]))||(e.copy_[r]=s,e.assigned_[r]=!0,!0)},deleteProperty:(e,r)=>(void 0!==jH(e.base_,r)||r in e.base_?(e.assigned_[r]=!1,jK(e),jq(e)):delete e.assigned_[r],e.copy_&&delete e.copy_[r],!0),getOwnPropertyDescriptor(e,r){let s=jC(e),n=Reflect.getOwnPropertyDescriptor(s,r);return n?{writable:!0,configurable:1!==e.type_||"length"!==r,enumerable:n.enumerable,value:s[r]}:n},defineProperty(){jh(11)},getPrototypeOf:e=>jf(e.base_),setPrototypeOf(){jh(12)}},jW={};function jH(e,r){let s=e[ju];return(s?jC(s):e)[r]}function jU(e,r){if(!(r in e))return;let s=jf(e);for(;s;){let e=Object.getOwnPropertyDescriptor(s,r);if(e)return e;s=jf(s)}}function jq(e){!e.modified_&&(e.modified_=!0,e.parent_&&jq(e.parent_))}function jK(e){e.copy_||(e.copy_=jk(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function jV(e,r){let s=jS(e)?jA("MapSet").proxyMap_(e,r):jj(e)?jA("MapSet").proxySet_(e,r):function(e,r){let s=Array.isArray(e),n={type_:+!!s,scope_:r?r.scope_:L,modified_:!1,finalized_:!1,assigned_:{},parent_:r,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},i=n,a=j$;s&&(i=[n],a=jW);let{revoke:o,proxy:l}=Proxy.revocable(i,a);return n.draft_=l,n.revoke_=o,l}(e,r);return(r?r.scope_:L).drafts_.push(s),s}j_(j$,(e,r)=>{jW[e]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)}}),jW.deleteProperty=function(e,r){return jW.set.call(this,e,r,void 0)},jW.set=function(e,r,s){return j$.set.call(this,e[0],r,s,e[0])};var jY=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(e,r,s)=>{let n;if("function"==typeof e&&"function"!=typeof r){let s=r;r=e;let n=this;return function(e=s,...i){return n.produce(e,e=>r.call(this,e,...i))}}if("function"!=typeof r&&jh(6),void 0!==s&&"function"!=typeof s&&jh(7),jm(e)){let i=jP(this),a=jV(e,void 0),o=!0;try{n=r(a),o=!1}finally{o?jM(i):jF(i)}return jT(i,s),jB(n,i)}if(e&&"object"==typeof e)jh(1,e);else{if(void 0===(n=r(e))&&(n=e),n===jc&&(n=void 0),this.autoFreeze_&&jN(n,!0),s){let r=[],i=[];jA("Patches").generateReplacementPatches_(e,n,r,i),s(r,i)}return n}},this.produceWithPatches=(e,r)=>{let s,n;return"function"==typeof e?(r,...s)=>this.produceWithPatches(r,r=>e(r,...s)):[this.produce(e,r,(e,r)=>{s=e,n=r}),s,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),"boolean"==typeof e?.useStrictIteration&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){var r;jm(e)||jh(8),jp(e)&&(jp(r=e)||jh(10,r),e=function e(r){let s;if(!jm(r)||jD(r))return r;let n=r[ju],i=!0;if(n){if(!n.modified_)return n.base_;n.finalized_=!0,s=jk(r,n.scope_.immer_.useStrictShallowCopy_),i=n.scope_.immer_.shouldUseStrictIteration()}else s=jk(r,!0);return j_(s,(r,n)=>{jw(s,r,e(n))},i),n&&(n.finalized_=!1),s}(r));let s=jP(this),n=jV(e,void 0);return n[ju].isManual_=!0,jF(s),n}finishDraft(e,r){let s=e&&e[ju];s&&s.isManual_||jh(9);let{scope_:n}=s;return jT(n,r),jB(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,r){let s;for(s=r.length-1;s>=0;s--){let n=r[s];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}s>-1&&(r=r.slice(s+1));let n=jA("Patches").applyPatches_;return jp(e)?n(e,r):this.produce(e,e=>n(e,r))}}().produce;let jG="vibedeckx:placeholder-workspaces";function jX(e){try{window.localStorage.setItem(jG,JSON.stringify([...e]))}catch{}}let jJ=function(){try{let e=window.localStorage.getItem(jG);if(!e)return new Map;let r=JSON.parse(e);if(!Array.isArray(r))return new Map;let s=new Map;for(let e of r)Array.isArray(e)&&"string"==typeof e[0]&&"number"==typeof e[1]?s.set(e[0],e[1]):"string"==typeof e&&s.set(e,Date.now());return s}catch{return new Map}}(),jZ=new Set,jQ=new Map;function j0(){for(let e of jZ)e()}function j1(e){return jZ.add(e),()=>{jZ.delete(e)}}function j2(){return jJ}function j5(){return jQ}function j3(e,r,s){return`${e}:${r??""}:${s??""}`}function j4(e){if(!jJ.has(e))return!1;let r=new Map(jJ);return r.delete(e),jX(jJ=r),j0(),!0}function j6(){return"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}async function j7(e,r,s,n){let i=await (0,rv.authFetch)(`${j6()}/api/projects/${e}/agent-sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:r,permissionMode:s,agentType:n})});if(!i.ok)throw Error("Failed to load session");return i.json()}async function j8(e,r){let s=await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r})});if(!s.ok){let r="";try{let e=await s.json();if(e.errorCode){let s=[`${e.errorCode}`];e.attempts&&s.push(`${e.attempts} attempts`),e.totalDurationMs&&s.push(`${(e.totalDurationMs/1e3).toFixed(1)}s`),r=` (${s.join(", ")})`}else e.error&&(r=` — ${e.error}`)}catch{}throw console.error(`[AgentSession] /message failed: status=${s.status}, sessionId=${e}, detail=${r}`),Error(`Failed to send message [${s.status}]${r}`)}}async function j9(e,r){let s=await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/paste`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r})});if(!s.ok){let r="";try{let e=await s.json();if(e.errorCode){let s=[`${e.errorCode}`];e.attempts&&s.push(`${e.attempts} attempts`),e.totalDurationMs&&s.push(`${(e.totalDurationMs/1e3).toFixed(1)}s`),r=` (${s.join(", ")})`}else e.error&&(r=` — ${e.error}`)}catch{}throw console.error(`[AgentSession] /paste failed: status=${s.status}, sessionId=${e}, detail=${r}`),Error(`Failed to upload paste [${s.status}]${r}`)}return s.json()}async function Ce(e,r){if(!(await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/restart`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentType:r})})).ok)throw Error("Failed to restart session")}async function Ct(e,r){let s=await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/agent-type`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentType:r})});if(!s.ok){let e="";try{let r=await s.json();r.error&&(e=r.error)}catch{}throw Error(e||`Failed to switch agent [${s.status}]`)}}async function Cr(e,r){let s=await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/model`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r})});if(!s.ok){let e="";try{let r=await s.json();r.error&&(e=r.error)}catch{}throw Error(e||`Failed to set model [${s.status}]`)}return(await s.json().catch(()=>({}))).model??null}async function Cs(e){if(!(await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/stop`,{method:"POST"})).ok)throw Error("Failed to stop session")}async function Cn(e,r){if(!(await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/switch-mode`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:r})})).ok)throw Error("Failed to switch mode")}async function Ci(e,r){if(!(await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/accept-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planContent:r})})).ok)throw Error("Failed to accept plan")}let Ca=new Map;function Co(e,r,s){return`${e}:${r??""}:${s??"latest"}`}async function Cl(e){let r=await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}`);if(!r.ok)throw Error(`Session ${e} not found`);return r.json()}let Cc=(0,ew.default)("user",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]),Cd=(0,ew.default)("wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]]),Cu=(0,ew.default)("brain",[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]]),Ch=(0,ew.default)("circle-question-mark",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),Cf=(0,ew.default)("file-check",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m9 15 2 2 4-4",key:"1grp1n"}]]),Cp=(0,ew.default)("folder-search",[["path",{d:"M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]]),Cm=(0,ew.default)("workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]),Cg=(0,ew.default)("file-pen-line",[["path",{d:"m18.226 5.226-2.52-2.52A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-.351",key:"1k2beg"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}],["path",{d:"M8 18h1",key:"13wk12"}]]),Cx=(0,ew.default)("file-plus-corner",[["path",{d:"M11.35 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v5.35",key:"17jvcc"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M14 19h6",key:"bvotb8"}],["path",{d:"M17 16v6",key:"18yu1i"}]]),Cv=(0,ew.default)("earth",[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),C_=(0,ew.default)("shield-alert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);var ck=cC,Sw=cC;let Cy=RegExp("(?<![\\w./-])([\\w-]+(?:[./][\\w-]+)+)(?::(\\d+)(?::\\d+)?|#L(\\d+)(?:-L?\\d+)?)?","g"),Cb=/\[([^\]\n]*)\]\(\s*([^)\s]+?)\s*\)/g;function Cw(e){return e.includes("/")||/\.[A-Za-z0-9]+$/.test(e)}function CS(e){let r=e.trim();if(!r)return null;let s=/^(.*?)(?::(\d+)(?::\d+)?|#L(\d+)(?:-L?\d+)?)?$/.exec(r);if(!s||!s[1])return null;let n=s[1];return/^[a-z][a-z0-9+.-]*:/i.test(n)||n.startsWith("//")||n.startsWith("#")?null:{rawPath:n,line:s[2]?Number(s[2]):s[3]?Number(s[3]):null}}function Cj(e){let r=r=>e.index?e.index.resolve(r):[];function s(e,r,s){return{type:"element",tagName:"a",properties:{className:["file-ref"],href:"#file-ref",dataFilePaths:JSON.stringify(e),...null!=r?{dataFileLine:String(r)}:{}},children:s}}return e=>{!function e(n,i=!1){if(!n.children)return;let a=i||"pre"===n.tagName,o=[];for(let i of n.children)"text"===i.type?a?o.push(i):o.push(...function(e){let n=function(e){let r,s=[],n=[];for(Cb.lastIndex=0;null!==(r=Cb.exec(e));){let e=CS(r[2]);if(!e||!Cw(e.rawPath))continue;let i=r.index,a=r.index+r[0].length;s.push({start:i,end:a,rawPath:e.rawPath,line:e.line,display:r[1]||void 0}),n.push([i,a])}for(Cy.lastIndex=0;null!==(r=Cy.exec(e));){let e=r.index;if(n.some(([r,s])=>e>=r&&e<s))continue;let i=r[1];if(!Cw(i))continue;let a=r[2]?Number(r[2]):r[3]?Number(r[3]):null;s.push({start:e,end:e+r[0].length,rawPath:i,line:a})}return s.sort((e,r)=>e.start-r.start),s}(e);if(0===n.length)return[{type:"text",value:e}];let i=[],a=0,o=!1;for(let l of n){let n=r(l.rawPath);if(0===n.length)continue;l.start>a&&i.push({type:"text",value:e.slice(a,l.start)});let c=l.display??e.slice(l.start,l.end);i.push(s(n,l.line,[{type:"text",value:c}])),a=l.end,o=!0}return o?(a<e.length&&i.push({type:"text",value:e.slice(a)}),i):[{type:"text",value:e}]}(i.value??"")):"element"===i.type&&"pre"===i.tagName?(e(i,!0),o.push(i)):"element"!==i.type||"a"!==i.tagName||a?(e(i,a),o.push(i)):o.push(...function(e){let n=CS(String(e.properties?.href??""));if(!n)return[e];let i=r(n.rawPath);return 0===i.length?e.children??[]:[s(i,n.line,e.children??[])]}(i));n.children=o}(e)}}let CC="text-primary underline decoration-dotted underline-offset-2 cursor-pointer hover:decoration-solid";function Ck({node:e,children:r,href:s,...n}){let{openFile:i}=S8(),a=e?.properties?.dataFilePaths;if(!a)return"string"==typeof s&&s.startsWith("#")?(0,O.jsx)("a",{href:s,...n,children:r}):(0,O.jsx)("a",{href:s,target:"_blank",rel:"noreferrer noopener",...n,children:r});let o=[];try{o=JSON.parse(a)}catch{o=[]}let l=e?.properties?.dataFileLine,c=null!=l?Number(l):null;return o.length<=1?(0,O.jsx)("a",{href:"#",className:CC,onClick:e=>{e.preventDefault(),o[0]&&i(o[0],c)},children:r}):(0,O.jsx)(CN,{paths:o,line:c,children:r})}function CN({paths:e,line:r,children:s}){let{openFile:n}=S8();return(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)("a",{href:"#",className:CC,onClick:e=>e.preventDefault(),children:s})}),(0,O.jsxs)(a7,{align:"start",className:"max-w-md",children:[(0,O.jsxs)(or,{children:[e.length," matching files"]}),e.map(e=>(0,O.jsx)(a8,{className:"font-mono text-xs",onSelect:()=>n(e,r),children:e},e))]})]})}let CE=(0,$.memo)(function({children:e}){let{index:r}=S8(),{harden:s,...n}=Sw.e,i=[...Object.values(n),[Cj,{index:r}],...s?[s]:[]];return(0,O.jsx)(ck.i,{className:"size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",rehypePlugins:i,components:{a:Ck},children:e},r?.version??"no-file-ref-index")});function CD({input:e,messageIndex:r}){let{sendMessage:s,messages:n}=N7(),i=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&Array.isArray(r.questions)&&r.questions.length>0&&r.questions.every(e=>"string"==typeof e.question&&"string"==typeof e.header&&Array.isArray(e.options)))return r}catch{}return null}(e),a=n[r+1],o=a?.type==="user",l=o?a.content:"",c="string"==typeof l?l:l.filter(e=>"text"===e.type).map(e=>e.text).join("\n");if(!i){let r="string"==typeof e?e:JSON.stringify(e,null,2);return(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>500?r.substring(0,500)+"...":r})}return o?(0,O.jsx)(CR,{questions:i.questions,answeredText:c}):(0,O.jsx)(CA,{questions:i.questions,sendMessage:s})}function CR({questions:e,answeredText:r}){return(0,O.jsx)("div",{className:"space-y-3 mt-2",children:e.map((e,s)=>(0,O.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3",children:[(0,O.jsx)("div",{className:"flex items-center gap-2 mb-1.5",children:(0,O.jsx)(sa,{variant:"secondary",className:"text-[10px]",children:e.header})}),(0,O.jsx)("p",{className:"text-sm text-muted-foreground mb-2",children:e.question}),(0,O.jsxs)("div",{className:"flex items-center gap-2 text-sm text-green-600 dark:text-green-400",children:[(0,O.jsx)(sJ,{className:"h-4 w-4"}),(0,O.jsx)("span",{className:"font-medium",children:r})]})]},s))})}function CA({questions:e,sendMessage:r}){let[s,n]=(0,$.useState)(new Map),[i,a]=(0,$.useState)(new Map),[o,l]=(0,$.useState)(new Set),[c,d]=(0,$.useState)(!1);async function u(){let n=[];for(let r=0;r<e.length;r++)if(o.has(r)){let e=i.get(r)?.trim();e&&n.push(e)}else{let e=s.get(r);e&&e.size>0&&n.push(Array.from(e).join(", "))}if(n.length>0){d(!0);try{await r(n.join("\n"))}finally{d(!1)}}}let h=e.some((e,r)=>{if(o.has(r))return!!i.get(r)?.trim();let n=s.get(r);return n&&n.size>0});return(0,O.jsxs)("div",{className:"space-y-4 mt-2",children:[e.map((e,r)=>{let c=s.get(r)||new Set,d=i.get(r)||"",u=o.has(r);return(0,O.jsxs)("div",{className:"rounded-lg border bg-card p-3",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 mb-1.5",children:[(0,O.jsx)(Ch,{className:"h-3.5 w-3.5 text-violet-500"}),(0,O.jsx)(sa,{variant:"secondary",className:"text-[10px]",children:e.header})]}),(0,O.jsx)("p",{className:"text-sm font-medium mb-3",children:e.question}),(0,O.jsxs)("div",{className:"grid gap-2",children:[e.options.map(s=>{let i=c.has(s.label)&&!u;return(0,O.jsx)(W.Button,{variant:i?"default":"outline",className:(0,ey.cn)("h-auto py-2 px-3 justify-start text-left whitespace-normal",i&&"ring-2 ring-primary/50"),onClick:()=>{var i,a;return i=s.label,a=e.multiSelect,void(n(e=>{let s=new Map(e),n=new Set(s.get(r)||[]);return a?n.has(i)?n.delete(i):n.add(i):n.has(i)?n.clear():(n.clear(),n.add(i)),s.set(r,n),s}),l(e=>{let s=new Set(e);return s.delete(r),s}))},children:(0,O.jsxs)("div",{children:[(0,O.jsx)("span",{className:"font-medium text-sm",children:s.label}),s.description&&(0,O.jsx)("span",{className:"block text-xs text-muted-foreground mt-0.5",children:s.description})]})},s.label)}),(0,O.jsx)("div",{className:"flex items-center gap-2 mt-1",children:(0,O.jsx)(ro,{placeholder:"Other...",value:d,onChange:e=>{var s;return s=e.target.value,void(a(e=>new Map(e).set(r,s)),s&&(n(e=>{let s=new Map(e);return s.set(r,new Set),s}),l(e=>new Set(e).add(r))))},className:"text-sm"})})]})]},r)}),(0,O.jsxs)(W.Button,{onClick:u,disabled:!h||c,size:"sm",className:"active:scale-95 transition-transform",children:[c&&(0,O.jsx)(sj,{className:"h-3.5 w-3.5 animate-spin"}),c?"Submitting...":"Submit"]})]})}function CT(e){try{return JSON.parse(e)}catch{return null}}function CM({input:e,messageIndex:r}){let{messages:s,acceptPlan:n,permissionMode:i,agentType:a}=N7(),[o,l]=(0,$.useState)(!0),[c,d]=(0,$.useState)(!1),u=function(e,r,s){let n="string"==typeof e?CT(e):e;if(n&&"object"==typeof n&&"plan"in n){let e=n.plan;if(e)return e}if("claude-code"===s)for(let e=r.length-1;e>=0;e--){let s=r[e];if("tool_use"===s.type&&"Write"===s.tool){let e="string"==typeof s.input?CT(s.input):s.input;if(e&&"object"==typeof e&&e.file_path?.includes(".claude/plans/")&&e.content)return e.content}}return"Plan written to file"}(e,s,a),h=(0,$.useCallback)(async()=>{d(!0);try{await n(u)}catch{d(!1)}},[n,u]),f="edit"===i,p=!1,m="";for(let e=r+1;e<s.length;e++){let r=s[e];if(r?.type==="user"){p=!0;let e=r.content??"";m="string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n");break}}return(f&&!p&&(p=!0),f||p)?(0,O.jsxs)("div",{className:"space-y-2 mt-2",children:[f?(0,O.jsxs)(sa,{variant:"default",className:"bg-green-600 hover:bg-green-700 text-white",children:[(0,O.jsx)(sJ,{className:"h-3 w-3 mr-1"}),"Plan Accepted"]}):(0,O.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,O.jsx)(sD,{className:"h-3.5 w-3.5"}),(0,O.jsxs)("span",{children:["Feedback sent: ",m.length>100?m.substring(0,100)+"...":m]})]}),(0,O.jsxs)("details",{open:!f,children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"View Plan"}),(0,O.jsx)("div",{className:"mt-2 rounded-lg border p-3 bg-muted/30",children:(0,O.jsx)("div",{className:"prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,O.jsx)(cD,{children:u})})})]})]}):(0,O.jsxs)("div",{className:"space-y-3 mt-2",children:[(0,O.jsxs)("div",{className:"rounded-lg border p-3 bg-card",children:[(0,O.jsxs)("button",{onClick:()=>l(!o),className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground mb-2 block",children:[o?"Collapse":"Expand"," Plan"]}),o&&(0,O.jsx)("div",{className:"prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words max-h-96 overflow-y-auto",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,O.jsx)(cD,{children:u})})]}),(0,O.jsxs)(W.Button,{onClick:h,disabled:c,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:[c?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):(0,O.jsx)(rh,{className:"h-3.5 w-3.5 mr-1.5"}),c?"Accepting Plan...":"Accept Plan & Start Editing"]})]})}function CF({requestId:e,command:r,cwd:s,messageIndex:n}){let{messages:i,sessionId:a}=N7(),[o,l]=(0,$.useState)(!1),[c,d]=(0,$.useState)(null),u=!1;for(let e=n+1;e<i.length;e++)if(i[e]?.type==="user"){u=!0;break}c&&(u=!0);let h=(0,$.useCallback)(async r=>{if(a){l(!0),d(r);try{await (0,rv.sendApprovalResponse)(a,e,r)}catch{d(null),l(!1)}}},[a,e]);return u?(0,O.jsxs)("div",{className:"space-y-2 mt-2",children:[(0,O.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,O.jsx)(ol,{className:"h-3.5 w-3.5 text-muted-foreground"}),(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:"Command"})]}),(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r||"(empty)"}),s&&(0,O.jsxs)("p",{className:"text-xs text-muted-foreground mt-1",children:["cwd: ",s]})]}),(0,O.jsxs)(sa,{variant:"default",className:"decline"===c?"bg-red-600 hover:bg-red-700 text-white":"bg-green-600 hover:bg-green-700 text-white",children:[(0,O.jsx)(sJ,{className:"h-3 w-3 mr-1"}),"decline"===c?"Denied":"Allowed"]})]}):(0,O.jsxs)("div",{className:"space-y-2 mt-2",children:[(0,O.jsxs)("div",{className:"rounded-lg border bg-card p-3",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,O.jsx)(ol,{className:"h-3.5 w-3.5 text-muted-foreground"}),(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:"Command"})]}),(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r||"(empty)"}),s&&(0,O.jsxs)("p",{className:"text-xs text-muted-foreground mt-1",children:["cwd: ",s]})]}),(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsxs)(W.Button,{onClick:()=>h("accept"),disabled:o,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:[o&&"accept"===c?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,O.jsx)(sJ,{className:"h-3.5 w-3.5 mr-1"}),"Allow"]}),(0,O.jsxs)(W.Button,{onClick:()=>h("decline"),disabled:o,variant:"destructive",size:"sm",children:[o&&"decline"===c?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5 mr-1"}),"Deny"]})]})]})}function CP({requestId:e,changes:r,messageIndex:s}){let{messages:n,sessionId:i}=N7(),[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(null),d=!1;for(let e=s+1;e<n.length;e++)if(n[e]?.type==="user"){d=!0;break}l&&(d=!0);let u=(0,$.useCallback)(async r=>{if(i){o(!0),c(r);try{await (0,rv.sendApprovalResponse)(i,e,r)}catch{c(null),o(!1)}}},[i,e]),h=r??[],f=()=>(0,O.jsx)("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:0===h.length?(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"No file changes"}):h.map((e,r)=>(0,O.jsxs)("div",{children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)(Sr,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),(0,O.jsx)("code",{className:"text-xs break-all",children:e.path}),(0,O.jsx)(sa,{variant:"secondary",className:`text-[10px] ${function(e){switch(e){case"added":case"add":return"bg-green-500/10 text-green-600";case"deleted":case"delete":return"bg-red-500/10 text-red-600";default:return"bg-blue-500/10 text-blue-600"}}(e.kind)}`,children:function(e){switch(e){case"added":case"add":return"added";case"deleted":case"delete":return"deleted";default:return"modified"}}(e.kind)})]}),e.diff&&(0,O.jsxs)("details",{className:"mt-1",children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"View diff"}),(0,O.jsx)("pre",{className:"mt-1 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.diff.split("\n").map((e,r)=>{let s="";return e.startsWith("+")?s="bg-green-500/10 text-green-700 dark:text-green-400":e.startsWith("-")&&(s="bg-red-500/10 text-red-700 dark:text-red-400"),(0,O.jsx)("div",{className:s,children:e},r)})})]})]},r))});return d?(0,O.jsxs)("div",{className:"space-y-2 mt-2",children:[f(),(0,O.jsxs)(sa,{variant:"default",className:"decline"===l?"bg-red-600 hover:bg-red-700 text-white":"bg-green-600 hover:bg-green-700 text-white",children:[(0,O.jsx)(sJ,{className:"h-3 w-3 mr-1"}),"decline"===l?"Denied":"Allowed"]})]}):(0,O.jsxs)("div",{className:"space-y-2 mt-2",children:[f(),(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsxs)(W.Button,{onClick:()=>u("accept"),disabled:a,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:[a&&"accept"===l?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,O.jsx)(sJ,{className:"h-3.5 w-3.5 mr-1"}),"Allow"]}),(0,O.jsxs)(W.Button,{onClick:()=>u("decline"),disabled:a,variant:"destructive",size:"sm",children:[a&&"decline"===l?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5 mr-1"}),"Deny"]})]})]})}let CI=(0,ew.default)("circle-plus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]),CB=(0,ew.default)("badge",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}]]);function CL({status:e,className:r}){switch(e){case"completed":return(0,O.jsx)(sJ,{className:(0,ey.cn)("h-4 w-4 text-green-500",r)});case"in_progress":return(0,O.jsx)(sj,{className:(0,ey.cn)("h-4 w-4 text-cyan-500 animate-spin",r)});case"pending":default:return(0,O.jsx)(sZ,{className:(0,ey.cn)("h-4 w-4 text-muted-foreground",r)});case"deleted":return(0,O.jsx)(s0,{className:(0,ey.cn)("h-4 w-4 text-red-400",r)})}}function Cz(e,r){try{let s="string"==typeof e?JSON.parse(e):e;if(s&&"object"==typeof s&&r(s))return s}catch{}return null}function CO({input:e}){let r="string"==typeof e?e:JSON.stringify(e,null,2);return(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>500?r.substring(0,500)+"...":r})}function C$({input:e}){let r=Cz(e,e=>Array.isArray(e.todos)&&e.todos.length>0);return r?(0,O.jsx)("div",{className:"mt-2 space-y-1",children:r.todos.map((e,r)=>(0,O.jsxs)("div",{className:"flex items-start gap-2 py-0.5",children:[(0,O.jsx)(CL,{status:e.status,className:"mt-0.5 flex-shrink-0"}),(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("span",{className:(0,ey.cn)("text-sm break-words","completed"===e.status&&"line-through text-muted-foreground"),children:e.subject??e.content??"Untitled task"}),"in_progress"===e.status&&e.activeForm&&(0,O.jsx)("span",{className:"block text-xs italic text-cyan-500",children:e.activeForm})]})]},e.id??r))}):(0,O.jsx)(CO,{input:e})}function CW({input:e}){let r=Cz(e,e=>"string"==typeof e.subject);return r?(0,O.jsxs)("div",{className:"mt-2 flex items-start gap-2",children:[(0,O.jsx)(CI,{className:"h-4 w-4 text-cyan-500 mt-0.5 flex-shrink-0"}),(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("span",{className:"text-sm font-medium break-words",children:r.subject}),r.description&&(0,O.jsx)("span",{className:"block text-xs text-muted-foreground mt-0.5 break-words",children:r.description.length>200?r.description.substring(0,200)+"...":r.description})]})]}):(0,O.jsx)(CO,{input:e})}function CH({input:e}){let r=Cz(e,e=>"string"==typeof e.taskId);return r?(0,O.jsxs)("div",{className:"mt-2 flex items-start gap-2 flex-wrap",children:[r.status?(0,O.jsx)(CL,{status:r.status,className:"mt-0.5 flex-shrink-0"}):(0,O.jsx)(wx,{className:"h-4 w-4 text-cyan-500 mt-0.5 flex-shrink-0"}),(0,O.jsxs)("span",{className:"text-sm break-words",children:["Task #",r.taskId,r.status&&(0,O.jsxs)(O.Fragment,{children:[" ",(0,O.jsx)(wx,{className:"inline h-3 w-3 text-muted-foreground mx-0.5"})," ",r.status]}),r.subject&&(0,O.jsxs)("span",{className:"text-muted-foreground",children:[" — ",r.subject]})]}),r.addBlockedBy&&r.addBlockedBy.length>0&&(0,O.jsx)("div",{className:"flex gap-1 mt-1 w-full pl-6",children:r.addBlockedBy.map(e=>(0,O.jsxs)(sa,{variant:"outline",className:"text-[10px]",children:[(0,O.jsx)(CB,{className:"h-2.5 w-2.5 mr-0.5"}),"blocked by #",e]},e))}),r.addBlocks&&r.addBlocks.length>0&&(0,O.jsx)("div",{className:"flex gap-1 mt-1 w-full pl-6",children:r.addBlocks.map(e=>(0,O.jsxs)(sa,{variant:"outline",className:"text-[10px]",children:[(0,O.jsx)(CB,{className:"h-2.5 w-2.5 mr-0.5"}),"blocks #",e]},e))})]}):(0,O.jsx)(CO,{input:e})}function CU(){return(0,O.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-sm text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin text-cyan-500"}),(0,O.jsx)("span",{children:"Listing tasks..."})]})}function Cq({input:e}){let r=Cz(e,e=>"string"==typeof e.taskId);return r?(0,O.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-sm text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin text-cyan-500"}),(0,O.jsxs)("span",{children:["Fetching task #",r.taskId,"..."]})]}):(0,O.jsx)(CO,{input:e})}function CK({output:e}){let r=function(e){try{let r=JSON.parse(e);if(Array.isArray(r))return r.filter(e=>e.id&&e.subject).map(e=>({id:String(e.id),subject:String(e.subject),status:e.status||"pending",owner:e.owner?String(e.owner):void 0,blockedBy:Array.isArray(e.blockedBy)?e.blockedBy.map(String):void 0}));let s=r.tasks??r.items??r.data;if(Array.isArray(s))return s.filter(e=>e.id&&e.subject).map(e=>({id:String(e.id),subject:String(e.subject),status:e.status||"pending",owner:e.owner?String(e.owner):void 0,blockedBy:Array.isArray(e.blockedBy)?e.blockedBy.map(String):void 0}))}catch{let r=e.trim().split("\n").filter(Boolean),s=[];for(let e of r){let r=e.match(/^#?(\d+)[\s.:\-]+\[?(completed|in_progress|pending|deleted)\]?\s+(.+)/i);r&&s.push({id:r[1],status:r[2].toLowerCase(),subject:r[3].trim()})}if(s.length>0)return s}return null}(e);return r?(0,O.jsx)("div",{className:"mt-1 space-y-1",children:r.map(e=>(0,O.jsxs)("div",{className:"flex items-start gap-2 py-0.5",children:[(0,O.jsx)(CL,{status:e.status,className:"mt-0.5 flex-shrink-0"}),(0,O.jsxs)("div",{className:"min-w-0 flex items-center gap-1.5 flex-wrap",children:[(0,O.jsxs)("span",{className:"text-xs text-muted-foreground",children:["#",e.id]}),(0,O.jsx)("span",{className:(0,ey.cn)("text-sm break-words","completed"===e.status&&"line-through text-muted-foreground"),children:e.subject}),e.blockedBy&&e.blockedBy.length>0&&(0,O.jsx)(sa,{variant:"outline",className:"text-[10px]",children:"blocked"})]})]},e.id))}):null}function CV({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.file_path)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{file_path:s,offset:n,limit:i}=r,a=s.split("/"),o=a.pop()||s,l=a.join("/"),c=null!=n||null!=i,d="";if(c){let e=n??1;d=null!=i?`Lines ${e}\u2013${e+i-1}`:`From line ${e}`}return(0,O.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("span",{className:"text-sm font-medium break-all",children:o}),l&&(0,O.jsx)("p",{className:"text-xs text-muted-foreground truncate",title:s,children:l})]}),c&&(0,O.jsx)(sa,{variant:"outline",className:"text-xs shrink-0",children:d})]})}function CY({output:e}){let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["File contents (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function CG({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.file_path)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{file_path:s,content:n}=r,i=s.split("/"),a=i.pop()||s,o=i.join("/"),l=n.split("\n").length;return(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("span",{className:"text-sm font-medium break-all",children:a}),o&&(0,O.jsx)("p",{className:"text-xs text-muted-foreground truncate",title:s,children:o})]}),(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Content (",l," ",1===l?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:n.length>1e3?n.substring(0,1e3)+"...":n})]})]})}function CX({output:e}){return e&&""!==e.trim()?(0,O.jsxs)("details",{children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Result"}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]}):(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"File written"})}function CJ({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.command)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{command:s,description:n,timeout:i}=r;return(0,O.jsxs)("div",{className:"space-y-1",children:[n&&(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:n}),(0,O.jsxs)("div",{className:"flex items-start gap-2",children:[(0,O.jsxs)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,O.jsx)("span",{className:"text-muted-foreground select-none",children:"$ "}),s]}),null!=i&&(0,O.jsx)(sa,{variant:"outline",className:"text-xs shrink-0 mt-1",children:function(e){if(e>=6e4){let r=e/6e4;return`${r%1==0?r:r.toFixed(1)}m`}return`${e/1e3}s`}(i)})]})]})}function CZ({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Output (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function CQ({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.pattern)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let s=[];return r.path&&s.push({label:r.path}),r.glob&&s.push({label:r.glob}),r.type&&s.push({label:`.${r.type}`}),r.output_mode&&"files_with_matches"!==r.output_mode&&s.push({label:r.output_mode}),null!=r.context&&s.push({label:`context: ${r.context}`}),null!=r["-C"]&&s.push({label:`context: ${r["-C"]}`}),null!=r["-B"]&&s.push({label:`before: ${r["-B"]}`}),null!=r["-A"]&&s.push({label:`after: ${r["-A"]}`}),r["-i"]&&s.push({label:"case-insensitive"}),r.multiline&&s.push({label:"multiline"}),null!=r.head_limit&&s.push({label:`limit: ${r.head_limit}`}),null!=r.offset&&s.push({label:`offset: ${r.offset}`}),(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsx)("div",{className:"flex items-start gap-2",children:(0,O.jsxs)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,O.jsx)("span",{className:"text-muted-foreground select-none",children:"/ "}),r.pattern]})}),s.length>0&&(0,O.jsx)("div",{className:"flex items-center gap-1.5 flex-wrap",children:s.map((e,r)=>(0,O.jsx)(sa,{variant:"outline",className:"text-xs",children:e.label},r))})]})}function C0({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No matches"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Results (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function C1({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.pattern)return r;return null}catch{return null}}(e);return r?(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsx)("div",{className:"flex items-start gap-2",children:(0,O.jsx)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.pattern})}),r.path&&(0,O.jsx)("div",{className:"flex items-center gap-1.5 flex-wrap",children:(0,O.jsx)(sa,{variant:"outline",className:"text-xs",children:r.path})})]}):(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)})}function C2({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No matches"});let r=e.trim().split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:[r," ",1===r?"file":"files"," found"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}let C5={Explore:"Explore",Bash:"Bash",Plan:"Plan","general-purpose":"General","code-simplifier":"Simplify","superpowers:code-reviewer":"Review","memory-leak-detector":"Memory","directory-structure-validator":"Structure","tech-docs-finder":"Docs","claude-code-guide":"Guide","statusline-setup":"Status"};function C3({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.description&&"string"==typeof r.subagent_type)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{description:s,subagent_type:n,prompt:i,model:a,max_turns:o,resume:l,run_in_background:c}=r,d=[];return d.push({label:C5[n]||n}),a&&d.push({label:a}),null!=o&&d.push({label:`${o} turns`}),c&&d.push({label:"background"}),l&&d.push({label:"resume"}),(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,O.jsx)("span",{className:"text-sm",children:s}),d.map((e,r)=>(0,O.jsx)(sa,{variant:"outline",className:"text-xs shrink-0",children:e.label},r))]}),i&&(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Prompt (",i.length>1e3?`${Math.round(i.length/1e3)}k chars`:`${i.length} chars`,")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:i.length>1e3?i.substring(0,1e3)+"...":i})]})]})}function C4({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Agent result (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function C6(e,r){return e.length>r?e.substring(0,r)+"...":e}function C7({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.file_path&&"string"==typeof r.old_string&&"string"==typeof r.new_string)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{file_path:s,old_string:n,new_string:i,replace_all:a}=r,o=s.split("/"),l=o.pop()||s,c=o.join("/"),d=n.split("\n").length,u=i.split("\n").length;return(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("span",{className:"text-sm font-medium break-all",children:l}),c&&(0,O.jsx)("p",{className:"text-xs text-muted-foreground truncate",title:s,children:c})]}),(0,O.jsx)(sa,{variant:"outline",className:"text-xs shrink-0",children:d===u?`${d} ${1===d?"line":"lines"}`:`${d}\u2192${u} lines`}),a&&(0,O.jsx)(sa,{variant:"outline",className:"text-xs shrink-0",children:"replace all"})]}),(0,O.jsxs)("details",{children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Diff"}),(0,O.jsxs)("div",{className:"mt-1 text-xs rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full",children:[(0,O.jsxs)("pre",{className:"bg-red-500/10 p-1.5 rounded-t whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,O.jsx)("span",{className:"text-red-500 select-none",children:"- "}),C6(n,500)]}),(0,O.jsxs)("pre",{className:"bg-green-500/10 p-1.5 rounded-b whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,O.jsx)("span",{className:"text-green-500 select-none",children:"+ "}),C6(i,500)]})]})]})]})}function C8({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});if(e.length<=200)return(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:e});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Result (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function C9({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.url&&"string"==typeof r.prompt)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{display:s,href:n}=function(e){try{let r=new URL(e),s="/"===r.pathname?"":r.pathname,n=r.hostname+s;return{display:n.length>80?n.substring(0,77)+"...":n,href:e}}catch{return{display:e.length>80?e.substring(0,77)+"...":e,href:e}}}(r.url),i=r.prompt.length>150?r.prompt.substring(0,147)+"...":r.prompt;return(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsx)("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"block text-xs font-mono text-blue-500 hover:underline truncate",children:s}),(0,O.jsxs)("p",{className:"text-xs text-muted-foreground",children:['"',i,'"']})]})}function ke({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No content fetched"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Response (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function kt({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.query)return r;return null}catch{return null}}(e);return r?(0,O.jsxs)("div",{className:"space-y-1.5",children:[(0,O.jsx)("p",{className:"text-xs font-mono bg-muted/50 px-2 py-1 rounded break-words",children:r.query}),r.allowed_domains&&r.allowed_domains.length>0&&(0,O.jsxs)("div",{className:"flex items-center gap-1 flex-wrap",children:[(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:"only:"}),r.allowed_domains.map(e=>(0,O.jsx)(sa,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:e},e))]}),r.blocked_domains&&r.blocked_domains.length>0&&(0,O.jsxs)("div",{className:"flex items-center gap-1 flex-wrap",children:[(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:"exclude:"}),r.blocked_domains.map(e=>(0,O.jsx)(sa,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:e},e))]})]}):(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)})}function kr({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No search results"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Results (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function ks({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.skill)return r;return null}catch{return null}}(e);return r?(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsx)("p",{className:"text-xs font-mono text-pink-500",children:r.skill}),r.args&&(0,O.jsxs)("p",{className:"text-xs text-muted-foreground truncate",children:["args: ",r.args]})]}):(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)})}function kn({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Loaded (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function ki({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.task_id)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{task_id:s,block:n,timeout:i}=r,a=[];return a.push({label:!1===n?"non-blocking":"blocking"}),null!=i&&a.push({label:`${Math.round(i/1e3)}s`}),(0,O.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,O.jsx)("code",{className:"text-sm bg-muted/50 px-1.5 py-0.5 rounded",children:s}),a.map((e,r)=>(0,O.jsx)(sa,{variant:"outline",className:"text-xs shrink-0",children:e.label},r))]})}function ka({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Task output (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function ko({input:e}){let r="string"==typeof e?function(e){try{return JSON.parse(e)}catch{return null}}(e):e,s=r?.changes??[];return 0===s.length?(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"No file changes"}):(0,O.jsx)("div",{className:"space-y-2 mt-1",children:s.map((e,r)=>(0,O.jsxs)("div",{children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)(Sr,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),(0,O.jsx)("code",{className:"text-xs break-all",children:e.path}),(0,O.jsx)(sa,{variant:"secondary",className:`text-[10px] ${function(e){switch(e){case"added":case"add":return"bg-green-500/10 text-green-600";case"deleted":case"delete":return"bg-red-500/10 text-red-600";default:return"bg-blue-500/10 text-blue-600"}}(e.kind)}`,children:function(e){switch(e){case"added":case"add":return"added";case"deleted":case"delete":return"deleted";default:return"modified"}}(e.kind)})]}),e.diff&&(0,O.jsxs)("details",{className:"mt-1",children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"View diff"}),(0,O.jsx)("pre",{className:"mt-1 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.diff.split("\n").map((e,r)=>{let s="";return e.startsWith("+")?s="bg-green-500/10 text-green-700 dark:text-green-400":e.startsWith("-")&&(s="bg-red-500/10 text-red-700 dark:text-red-400"),(0,O.jsx)("div",{className:s,children:e},r)})})]})]},r))})}function kl({output:e}){let r=e.toLowerCase(),s="text-muted-foreground";return r.includes("completed")||r.includes("success")?s="text-green-600 dark:text-green-400":r.includes("failed")||r.includes("error")?s="text-red-600 dark:text-red-400":(r.includes("declined")||r.includes("denied"))&&(s="text-amber-600 dark:text-amber-400"),(0,O.jsx)("p",{className:`text-xs ${s}`,children:e})}function kc({path:e,size:r}){let s;return(0,O.jsxs)("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-border bg-muted/60 px-1.5 py-0.5 text-xs font-mono align-baseline",title:e,children:[(0,O.jsx)(Sr,{className:"w-3 h-3 text-muted-foreground shrink-0"}),(0,O.jsx)("span",{className:"truncate max-w-[18ch]",children:(s=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")))>=0?e.slice(s+1):e}),(0,O.jsx)("span",{className:"text-muted-foreground",children:function(e){if(e<1024)return`${e} B`;let r=e/1024;return r<10?`${r.toFixed(1)} KB`:r<1024?`${Math.round(r)} KB`:`${(r/1024).toFixed(1)} MB`}(r)})]})}let kd=/<vpaste path="([^"]+)" size="(\d+)" \/>/g;function ku({message:e,messageIndex:r}){let s=function(e,r){switch(e.type){case"user":return(0,O.jsx)(kf,{content:e.content,origin:e.origin});case"assistant":return(0,O.jsx)(kp,{content:e.content,agentType:e.agentType});case"tool_use":return(0,O.jsx)(km,{tool:e.tool,input:e.input,messageIndex:r});case"tool_result":return(0,O.jsx)(kg,{tool:e.tool,output:e.output});case"thinking":return(0,O.jsx)(kx,{content:e.content});case"error":return(0,O.jsx)(kv,{message:e.message});case"system":return(0,O.jsx)(k_,{content:e.content});case"approval_request":return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-amber-500/10 flex items-center justify-center",children:(0,O.jsx)(C_,{className:"w-4 h-4 text-amber-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-amber-500 mb-1",children:"command"===e.requestType?"Command Approval":"File Change Approval"}),"command"===e.requestType?(0,O.jsx)(CF,{requestId:e.requestId,command:e.command,cwd:e.cwd,messageIndex:r}):(0,O.jsx)(CP,{requestId:e.requestId,changes:e.changes,messageIndex:r})]})]});default:return null}}(e,r);return s?(0,O.jsxs)("div",{className:"group relative",children:[s,(0,O.jsx)("span",{className:"pointer-events-none absolute right-0 top-3 text-xs tabular-nums text-muted-foreground opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:function(e){let r=new Date(e),s=new Date,n=r.getFullYear()===s.getFullYear()&&r.getMonth()===s.getMonth()&&r.getDate()===s.getDate(),i=r.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});if(n)return i;let a=r.toLocaleDateString(void 0,{year:"numeric",month:"2-digit",day:"2-digit"});return`${a} ${i}`}(e.timestamp)})]}):null}function kh(e){let r=function(e){let r,s=[],n=0,i=RegExp(kd.source,"g");for(;null!==(r=i.exec(e));)r.index>n&&s.push({kind:"text",text:e.slice(n,r.index)}),s.push({kind:"chip",path:r[1],size:Number(r[2])}),n=r.index+r[0].length;return n<e.length&&s.push({kind:"text",text:e.slice(n)}),s}(e);return 1===r.length&&"text"===r[0].kind?(0,O.jsx)("span",{className:"whitespace-pre-wrap break-words",children:e??""}):(0,O.jsx)("div",{className:"text-foreground max-w-none break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:r.map((e,r)=>"text"===e.kind?(0,O.jsx)("span",{className:"whitespace-pre-wrap break-words",children:e.text},r):(0,O.jsx)(kc,{path:e.path,size:e.size},r))})}function kf({content:e,origin:r}){return"workflow"===r&&"string"==typeof e?(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,O.jsx)(Cm,{className:"w-3.5 h-3.5 text-sky-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Workflow"}),(0,O.jsx)("div",{className:"text-foreground prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,O.jsx)(CE,{children:e})})]})]}):(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-primary/10 flex items-center justify-center",children:(0,O.jsx)(Cc,{className:"w-3.5 h-3.5 text-primary"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-foreground mb-1",children:"You"}),(0,O.jsx)("div",{className:"text-foreground max-w-none break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:"string"==typeof e?kh(e):e.map((e,r)=>"text"===e.type?(0,O.jsx)($.Fragment,{children:kh(e.text)},r):(0,O.jsx)("img",{src:`data:${e.mediaType};base64,${e.data}`,alt:"Attached image",className:"max-w-sm rounded-lg mt-2"},r))})]})]})}function kp({content:e,agentType:r}){let s=function(){try{return N7().agentType}catch{return"claude-code"}}(),n="codex"===(r??s),[i,a]=(0,$.useState)(!1);return(0,O.jsxs)("div",{className:"group flex gap-3 py-3",children:[(0,O.jsx)("div",{className:`flex-shrink-0 w-7 h-7 rounded-lg ${n?"bg-green-500/10":"bg-violet-500/10"} flex items-center justify-center`,children:(0,O.jsx)(sb,{className:`w-3.5 h-3.5 ${n?"text-green-500":"text-violet-500"}`})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,O.jsx)("p",{className:`text-sm font-medium ${n?"text-green-500":"text-violet-500"}`,children:n?"Codex":"Claude"}),(0,O.jsx)("button",{type:"button",onClick:()=>a(e=>!e),title:i?"View rendered":"View source","aria-label":i?"View rendered":"View source","aria-pressed":i,className:"opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity text-muted-foreground hover:text-foreground",children:i?(0,O.jsx)(wf,{className:"w-3.5 h-3.5"}):(0,O.jsx)(Sf,{className:"w-3.5 h-3.5"})})]}),i?(0,O.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-words bg-muted/50 rounded-md p-3 overflow-x-auto text-foreground select-text",children:e??""}):(0,O.jsx)("div",{className:"text-foreground prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,O.jsx)(CE,{children:e??""})})]})]})}function km({tool:e,input:r,messageIndex:s}){if("ImageView"===e){let e="object"==typeof r&&null!==r&&"path"in r&&"string"==typeof r.path?r.path:"";return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,O.jsx)(wf,{className:"w-4 h-4 text-sky-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"View Image"}),(0,O.jsx)("p",{className:"font-mono text-muted-foreground break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e})]})]})}if("AskUserQuestion"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-violet-500/10 flex items-center justify-center",children:(0,O.jsx)(Ch,{className:"w-4 h-4 text-violet-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-violet-500 mb-1",children:"Question"}),(0,O.jsx)(CD,{input:r,messageIndex:s})]})]});if("ExitPlanMode"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-green-500/10 flex items-center justify-center",children:(0,O.jsx)(Cf,{className:"w-4 h-4 text-green-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-green-500 mb-1",children:"Plan Ready"}),(0,O.jsx)(CM,{input:r,messageIndex:s})]})]});let n={TodoWrite:{label:"Tasks",ui:(0,O.jsx)(C$,{input:r})},TaskCreate:{label:"Create Task",ui:(0,O.jsx)(CW,{input:r})},TaskUpdate:{label:"Update Task",ui:(0,O.jsx)(CH,{input:r})},TaskList:{label:"Task List",ui:(0,O.jsx)(CU,{})},TaskGet:{label:"Get Task",ui:(0,O.jsx)(Cq,{input:r})}}[e];if(n)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-cyan-500/10 flex items-center justify-center",children:(0,O.jsx)(sQ,{className:"w-4 h-4 text-cyan-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-cyan-500 mb-1",children:n.label}),n.ui]})]});if("Read"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,O.jsx)(Sr,{className:"w-4 h-4 text-sky-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Read File"}),(0,O.jsx)(CV,{input:r})]})]});if("Edit"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,O.jsx)(Cg,{className:"w-4 h-4 text-sky-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Edit File"}),(0,O.jsx)(C7,{input:r})]})]});if("Write"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,O.jsx)(Cx,{className:"w-4 h-4 text-sky-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Write File"}),(0,O.jsx)(CG,{input:r})]})]});if("Bash"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-emerald-500/10 flex items-center justify-center",children:(0,O.jsx)(ol,{className:"w-4 h-4 text-emerald-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-emerald-500 mb-1",children:"Run Command"}),(0,O.jsx)(CJ,{input:r})]})]});if("Grep"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-orange-500/10 flex items-center justify-center",children:(0,O.jsx)(sA,{className:"w-4 h-4 text-orange-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-orange-500 mb-1",children:"Search"}),(0,O.jsx)(CQ,{input:r})]})]});if("Glob"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-teal-500/10 flex items-center justify-center",children:(0,O.jsx)(Cp,{className:"w-4 h-4 text-teal-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-teal-500 mb-1",children:"Glob"}),(0,O.jsx)(C1,{input:r})]})]});if("Task"===e||"Agent"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-purple-500/10 flex items-center justify-center",children:(0,O.jsx)(Cm,{className:"w-4 h-4 text-purple-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-purple-500 mb-1",children:"Agent"}),(0,O.jsx)(C3,{input:r})]})]});if("TaskOutput"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-purple-500/10 flex items-center justify-center",children:(0,O.jsx)(Cm,{className:"w-4 h-4 text-purple-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-purple-500 mb-1",children:"Task Output"}),(0,O.jsx)(ki,{input:r})]})]});if("WebFetch"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-blue-500/10 flex items-center justify-center",children:(0,O.jsx)(ry,{className:"w-4 h-4 text-blue-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-blue-500 mb-1",children:"Fetch Web Page"}),(0,O.jsx)(C9,{input:r})]})]});if("WebSearch"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-indigo-500/10 flex items-center justify-center",children:(0,O.jsx)(Cv,{className:"w-4 h-4 text-indigo-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-indigo-500 mb-1",children:"Web Search"}),(0,O.jsx)(kt,{input:r})]})]});if("Skill"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-pink-500/10 flex items-center justify-center",children:(0,O.jsx)(hU,{className:"w-4 h-4 text-pink-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-pink-500 mb-1",children:"Skill"}),(0,O.jsx)(ks,{input:r})]})]});if("FileChange"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,O.jsx)(Cg,{className:"w-4 h-4 text-sky-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"File Changes"}),(0,O.jsx)(ko,{input:r})]})]});let i="string"==typeof r?r:JSON.stringify(r,null,2);return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-amber-500/10 flex items-center justify-center",children:(0,O.jsx)(Cd,{className:"w-4 h-4 text-amber-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsxs)("p",{className:"text-sm font-medium text-amber-500 mb-1 break-words",children:["Tool: ",e]}),(0,O.jsxs)("details",{open:!0,children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Input"}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:i.length>500?i.substring(0,500)+"...":i})]})]})]})}function kg({tool:e,output:r}){if(["TodoWrite","TaskCreate","TaskUpdate","TaskList","TaskGet"].includes(e)){let s="TaskList"===e?(0,O.jsx)(CK,{output:r}):null;return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsxs)("p",{className:"text-xs text-muted-foreground mb-1",children:["Result (",e,")"]}),s||(0,O.jsxs)("details",{children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Output"}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>1e3?r.substring(0,1e3)+"...":r})]})]})})}if("Read"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(CY,{output:r})})});if("Edit"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(C8,{output:r})})});if("Write"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(CX,{output:r})})});if("Bash"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(CZ,{output:r})})});if("Grep"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(C0,{output:r})})});if("Glob"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(C2,{output:r})})});if("Task"===e||"Agent"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(C4,{output:r})})});if("TaskOutput"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(ka,{output:r})})});if("WebFetch"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(ke,{output:r})})});if("WebSearch"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(kr,{output:r})})});if("Skill"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(kn,{output:r})})});if("FileChange"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(kl,{output:r})})});let s=r.length>200;return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsxs)("p",{className:"text-xs text-muted-foreground mb-1",children:["Result",e?` (${e})`:""]}),(0,O.jsxs)("details",{className:(0,ey.cn)(!s&&"open"),children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Output"}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>1e3?r.substring(0,1e3)+"...":r})]})]})})}function kx({content:e}){let r=e??"",s=r.trim().length>0,n=s?r.length>500?r.substring(0,500)+"...":r:"Reasoning unavailable — this model does not expose its thinking content.";return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-blue-500/10 flex items-center justify-center",children:(0,O.jsx)(Cu,{className:"w-3.5 h-3.5 text-blue-500"})}),(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsxs)("details",{children:[(0,O.jsx)("summary",{className:"text-xs font-medium text-blue-500 cursor-pointer hover:underline",children:"Thinking..."}),(0,O.jsx)("div",{className:`mt-2 whitespace-pre-wrap break-words bg-blue-500/5 p-2 rounded-md overflow-hidden ${s?"text-muted-foreground":"text-muted-foreground/70 italic"}`,style:{fontSize:"var(--conv-font-size, 12px)"},children:n})]})})]})}function kv({message:e}){return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-red-500/10 flex items-center justify-center",children:(0,O.jsx)(sy,{className:"w-3.5 h-3.5 text-red-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-red-500 mb-1",children:"Error"}),(0,O.jsx)("p",{className:"text-red-500/80 break-words whitespace-pre-wrap",style:{fontSize:"var(--conv-font-size, 14px)"},children:e})]})]})}function k_({content:e}){return(0,O.jsxs)("div",{className:"flex gap-3 py-2",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-gray-500/10 flex items-center justify-center",children:(0,O.jsx)(_J,{className:"w-3.5 h-3.5 text-gray-500"})}),(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)("p",{className:"text-muted-foreground break-words",style:{fontSize:"var(--conv-font-size, 12px)"},children:e??""})})]})}var ky="HoverCard",[kb,kw]=q(ky,[iw]),kS=iw(),[kj,kC]=kb(ky),kk=e=>{let{__scopeHoverCard:r,children:s,open:n,defaultOpen:i,onOpenChange:a,openDelay:o=700,closeDelay:l=300}=e,c=kS(r),d=$.useRef(0),u=$.useRef(0),h=$.useRef(!1),f=$.useRef(!1),[p,m]=G({prop:n,defaultProp:i??!1,onChange:a,caller:ky}),g=$.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>m(!0),o)},[o,m]),x=$.useCallback(()=>{clearTimeout(d.current),h.current||f.current||(u.current=window.setTimeout(()=>m(!1),l))},[l,m]),v=$.useCallback(()=>m(!1),[m]);return $.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),(0,O.jsx)(kj,{scope:r,open:p,onOpenChange:m,onOpen:g,onClose:x,onDismiss:v,hasSelectionRef:h,isPointerDownOnContentRef:f,children:(0,O.jsx)(iC,{...c,children:s})})};kk.displayName=ky;var kN="HoverCardTrigger",kE=$.forwardRef((e,r)=>{let{__scopeHoverCard:s,...n}=e,i=kC(kN,s),a=kS(s);return(0,O.jsx)(iN,{asChild:!0,...a,children:(0,O.jsx)(er.a,{"data-state":i.open?"open":"closed",...n,ref:r,onPointerEnter:K(e.onPointerEnter,kI(i.onOpen)),onPointerLeave:K(e.onPointerLeave,kI(i.onClose)),onFocus:K(e.onFocus,i.onOpen),onBlur:K(e.onBlur,i.onClose),onTouchStart:K(e.onTouchStart,e=>e.preventDefault())})})});kE.displayName=kN;var kD="HoverCardPortal",[kR,kA]=kb(kD,{forceMount:void 0}),kT=e=>{let{__scopeHoverCard:r,forceMount:s,children:n,container:i}=e,a=kC(kD,r);return(0,O.jsx)(kR,{scope:r,forceMount:s,children:(0,O.jsx)(Z,{present:s||a.open,children:(0,O.jsx)(eW,{asChild:!0,container:i,children:n})})})};kT.displayName=kD;var kM="HoverCardContent",kF=$.forwardRef((e,r)=>{let s=kA(kM,e.__scopeHoverCard),{forceMount:n=s.forceMount,...i}=e,a=kC(kM,e.__scopeHoverCard);return(0,O.jsx)(Z,{present:n||a.open,children:(0,O.jsx)(kP,{"data-state":a.open?"open":"closed",...i,onPointerEnter:K(e.onPointerEnter,kI(a.onOpen)),onPointerLeave:K(e.onPointerLeave,kI(a.onClose)),ref:r})})});kF.displayName=kM;var kP=$.forwardRef((e,r)=>{let{__scopeHoverCard:s,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:a,onInteractOutside:o,...l}=e,c=kC(kM,s),d=kS(s),u=$.useRef(null),h=(0,U.useComposedRefs)(r,u),[f,p]=$.useState(!1);return $.useEffect(()=>{if(f){let e=document.body;return z=e.style.userSelect||e.style.webkitUserSelect,e.style.userSelect="none",e.style.webkitUserSelect="none",()=>{e.style.userSelect=z,e.style.webkitUserSelect=z}}},[f]),$.useEffect(()=>{if(u.current){let e=()=>{p(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{document.getSelection()?.toString()!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",e),()=>{document.removeEventListener("pointerup",e),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),$.useEffect(()=>{u.current&&(function(e){let r=[],s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();)r.push(s.currentNode);return r})(u.current).forEach(e=>e.setAttribute("tabindex","-1"))}),(0,O.jsx)(eR,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:o,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:K(a,e=>{e.preventDefault()}),onDismiss:c.onDismiss,children:(0,O.jsx)(iA,{...d,...l,onPointerDown:K(l.onPointerDown,e=>{e.currentTarget.contains(e.target)&&p(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:h,style:{...l.style,userSelect:f?"text":void 0,WebkitUserSelect:f?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})});function kI(e){return r=>"touch"===r.pointerType?void 0:e()}function kB({...e}){return(0,O.jsx)(kk,{"data-slot":"hover-card",...e})}function kL({...e}){return(0,O.jsx)(kE,{"data-slot":"hover-card-trigger",...e})}function kz({className:e,align:r="center",sideOffset:s=4,...n}){return(0,O.jsx)(kT,{"data-slot":"hover-card-portal",children:(0,O.jsx)(kF,{"data-slot":"hover-card-content",align:r,sideOffset:s,className:(0,ey.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...n})})}$.forwardRef((e,r)=>{let{__scopeHoverCard:s,...n}=e,i=kS(s);return(0,O.jsx)(iF,{...i,...n,ref:r})}).displayName="HoverCardArrow";let kO=(0,ew.default)("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),k$=(0,ew.default)("image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);(0,ew.default)("mic",[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]]);let kW=(0,ew.default)("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]),kH=(e=21)=>{let r="",s=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)r+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&s[e]];return r},kU=(0,$.createContext)(null),kq=(0,$.createContext)(null),kK=()=>(0,$.useContext)(kU),kV=(0,$.createContext)(null),kY=()=>{let e=(0,$.useContext)(kq),r=(0,$.useContext)(kV),s=e??r;if(!s)throw Error("usePromptInputAttachments must be used within a PromptInput or PromptInputProvider");return s};function kG({data:e,className:r,...s}){let n=kY(),i=e.filename||"",a="image"==(e.mediaType?.startsWith("image/")&&e.url?"image":"file"),o=i||(a?"Image":"Attachment");return(0,O.jsxs)(k7,{children:[(0,O.jsx)(kL,{asChild:!0,children:(0,O.jsxs)("div",{className:(0,ey.cn)("group relative flex h-8 cursor-pointer select-none items-center gap-1.5 rounded-md border border-border px-1.5 font-medium text-sm transition-all hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",r),...s,children:[(0,O.jsxs)("div",{className:"relative size-5 shrink-0",children:[(0,O.jsx)("div",{className:"absolute inset-0 flex size-5 items-center justify-center overflow-hidden rounded bg-background transition-opacity group-hover:opacity-0",children:a?(0,O.jsx)("img",{alt:i||"attachment",className:"size-5 object-cover",height:20,src:e.url,width:20}):(0,O.jsx)("div",{className:"flex size-5 items-center justify-center text-muted-foreground",children:(0,O.jsx)(kW,{className:"size-3"})})}),(0,O.jsxs)(W.Button,{"aria-label":"Remove attachment",className:"absolute inset-0 size-5 cursor-pointer rounded p-0 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 [&>svg]:size-2.5",onClick:r=>{r.stopPropagation(),n.remove(e.id)},type:"button",variant:"ghost",children:[(0,O.jsx)(t7,{}),(0,O.jsx)("span",{className:"sr-only",children:"Remove"})]})]}),(0,O.jsx)("span",{className:"flex-1 truncate",children:o})]},e.id)}),(0,O.jsx)(k8,{className:"w-auto p-2",children:(0,O.jsxs)("div",{className:"w-auto space-y-3",children:[a&&(0,O.jsx)("div",{className:"flex max-h-96 w-96 items-center justify-center overflow-hidden rounded-md border",children:(0,O.jsx)("img",{alt:i||"attachment preview",className:"max-h-full max-w-full object-contain",height:384,src:e.url,width:448})}),(0,O.jsx)("div",{className:"flex items-center gap-2.5",children:(0,O.jsxs)("div",{className:"min-w-0 flex-1 space-y-1 px-0.5",children:[(0,O.jsx)("h4",{className:"truncate font-semibold text-sm leading-none",children:i||(a?"Image":"Attachment")}),e.mediaType&&(0,O.jsx)("p",{className:"truncate font-mono text-muted-foreground text-xs",children:e.mediaType})]})})]})})]})}function kX({children:e,className:r,...s}){let n=kY();return n.files.length?(0,O.jsx)("div",{className:(0,ey.cn)("flex flex-wrap items-center gap-2 p-3 w-full",r),...s,children:n.files.map(r=>(0,O.jsx)($.Fragment,{children:e(r)},r.id))}):null}let kJ=({label:e="Add photos or files",...r})=>{let s=kY();return(0,O.jsxs)(a8,{...r,onSelect:e=>{e.preventDefault(),s.openFileDialog()},children:[(0,O.jsx)(k$,{className:"mr-2 size-4"})," ",e]})},kZ=({className:e,accept:r,multiple:s,globalDrop:n,syncHiddenInput:i,maxFiles:a,maxFileSize:o,onError:l,onSubmit:c,children:d,...u})=>{let h=kK(),f=!!h,p=(0,$.useRef)(null),m=(0,$.useRef)(null),[g,x]=(0,$.useState)([]),v=f?h.attachments.files:g,_=(0,$.useRef)(v);_.current=v;let y=(0,$.useCallback)(()=>{p.current?.click()},[]),b=(0,$.useCallback)(e=>!r||""===r.trim()||r.split(",").map(e=>e.trim()).filter(Boolean).some(r=>{if(r.endsWith("/*")){let s=r.slice(0,-1);return e.type.startsWith(s)}return e.type===r}),[r]),w=(0,$.useCallback)(e=>{let r=Array.from(e),s=r.filter(e=>b(e));if(r.length&&0===s.length)return void l?.({code:"accept",message:"No files match the accepted types."});let n=s.filter(e=>!o||e.size<=o);s.length>0&&0===n.length?l?.({code:"max_file_size",message:"All files exceed the maximum size."}):x(e=>{let r="number"==typeof a?Math.max(0,a-e.length):void 0,s="number"==typeof r?n.slice(0,r):n;"number"==typeof r&&n.length>r&&l?.({code:"max_files",message:"Too many files. Some were not added."});let i=[];for(let e of s)i.push({id:kH(),type:"file",url:URL.createObjectURL(e),mediaType:e.type,filename:e.name});return e.concat(i)})},[b,a,o,l]),S=(0,$.useCallback)(e=>x(r=>{let s=r.find(r=>r.id===e);return s?.url&&URL.revokeObjectURL(s.url),r.filter(r=>r.id!==e)}),[]),j=(0,$.useCallback)(()=>x(e=>{for(let r of e)r.url&&URL.revokeObjectURL(r.url);return[]}),[]),C=f?h.attachments.add:w,k=f?h.attachments.remove:S,N=f?h.attachments.clear:j,E=f?h.attachments.openFileDialog:y;(0,$.useEffect)(()=>{f&&h.__registerFileInput(p,()=>p.current?.click())},[f,h]),(0,$.useEffect)(()=>{i&&p.current&&0===v.length&&(p.current.value="")},[v,i]),(0,$.useEffect)(()=>{let e=m.current;if(!e||n)return;let r=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault()},s=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault(),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&C(e.dataTransfer.files)};return e.addEventListener("dragover",r),e.addEventListener("drop",s),()=>{e.removeEventListener("dragover",r),e.removeEventListener("drop",s)}},[C,n]),(0,$.useEffect)(()=>{if(!n)return;let e=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault()},r=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault(),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&C(e.dataTransfer.files)};return document.addEventListener("dragover",e),document.addEventListener("drop",r),()=>{document.removeEventListener("dragover",e),document.removeEventListener("drop",r)}},[C,n]),(0,$.useEffect)(()=>()=>{if(!f)for(let e of _.current)e.url&&URL.revokeObjectURL(e.url)},[f]);let D=async e=>{try{let r=await fetch(e),s=await r.blob();return new Promise(e=>{let r=new FileReader;r.onloadend=()=>e(r.result),r.onerror=()=>e(null),r.readAsDataURL(s)})}catch{return null}},R=(0,$.useMemo)(()=>({files:v.map(e=>({...e,id:e.id})),add:C,remove:k,clear:N,openFileDialog:E,fileInputRef:p}),[v,C,k,N,E]),A=(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("input",{accept:r,"aria-label":"Upload files",className:"hidden",multiple:s,onChange:e=>{e.currentTarget.files&&C(e.currentTarget.files),e.currentTarget.value=""},ref:p,title:"Upload files",type:"file"}),(0,O.jsx)("form",{className:(0,ey.cn)("w-full",e),onSubmit:e=>{e.preventDefault();let r=e.currentTarget,s=f?h.textInput.value:new FormData(r).get("message")||"";f||r.reset(),Promise.all(v.map(async({id:e,...r})=>{if(r.url&&r.url.startsWith("blob:")){let e=await D(r.url);return{...r,url:e??r.url}}return r})).then(r=>{try{let n=c({text:s,files:r},e);n instanceof Promise?n.then(()=>{N(),f&&h.textInput.clear()}).catch(()=>{}):(N(),f&&h.textInput.clear())}catch{}}).catch(()=>{})},ref:m,...u,children:(0,O.jsx)(wv,{className:"overflow-hidden border-[#dedede] bg-card shadow-none dark:border-input dark:bg-card focus-within:border-foreground has-[[data-slot=input-group-control]:focus-visible]:border-foreground has-[[data-slot=input-group-control]:focus-visible]:ring-0",children:d})})]});return f?A:(0,O.jsx)(kV.Provider,{value:R,children:A})},kQ=({onChange:e,onKeyDown:r,onPasteText:s,className:n,placeholder:i="What would you like to know?",...a})=>{let o=kK(),l=kY(),[c,d]=(0,$.useState)(!1),u=o?{value:o.textInput.value,onChange:r=>{o.textInput.setInput(r.currentTarget.value),e?.(r)}}:{onChange:e};return(0,O.jsx)(wj,{className:(0,ey.cn)("field-sizing-content max-h-48 min-h-9",n),name:"message",onCompositionEnd:()=>d(!1),onCompositionStart:()=>d(!0),onKeyDown:e=>{if(r?.(e),!e.defaultPrevented){if("Enter"===e.key){if(c||e.nativeEvent.isComposing||e.shiftKey)return;e.preventDefault();let r=e.currentTarget.form,s=r?.querySelector('button[type="submit"]');if(s?.disabled)return;r?.requestSubmit()}if("Backspace"===e.key&&""===e.currentTarget.value&&l.files.length>0){e.preventDefault();let r=l.files.at(-1);r&&l.remove(r.id)}}},onPaste:e=>{let r=e.clipboardData?.items;if(!r)return;let n=[];for(let e of r)if("file"===e.kind){let r=e.getAsFile();r&&n.push(r)}if(n.length>0){e.preventDefault(),l.add(n);return}if(s){let r=e.clipboardData.getData("text");r.length>0&&s(e,r)}},placeholder:i,...a,...u})},k0=({className:e,...r})=>(0,O.jsx)(wy,{align:"block-end",className:(0,ey.cn)("order-first flex-wrap gap-1",e),...r}),k1=({variant:e="ghost",className:r,size:s,...n})=>{let i=s??($.Children.count(n.children)>1?"sm":"icon-sm");return(0,O.jsx)(ww,{className:(0,ey.cn)(r),size:i,type:"button",variant:e,...n})},k2=e=>(0,O.jsx)(a4,{...e}),k5=({className:e,children:r,...s})=>(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)(k1,{className:e,...s,children:r??(0,O.jsx)(eS,{className:"size-4"})})}),k3=({className:e,...r})=>(0,O.jsx)(a7,{align:"start",className:(0,ey.cn)(e),...r}),k4=({className:e,...r})=>(0,O.jsx)(a8,{className:(0,ey.cn)(e),...r}),k6=({className:e,variant:r="default",size:s="icon-sm",status:n,children:i,...a})=>{let o=(0,O.jsx)(kO,{className:"size-4"});return"submitted"===n?o=(0,O.jsx)(sj,{className:"size-4 animate-spin"}):"streaming"===n?o=(0,O.jsx)(lJ,{className:"size-4"}):"error"===n&&(o=(0,O.jsx)(t7,{className:"size-4"})),(0,O.jsx)(ww,{"aria-label":"Submit",className:(0,ey.cn)("rounded-full",e),size:s,type:"submit",variant:r,...a,children:i??o})},k7=({openDelay:e=0,closeDelay:r=0,...s})=>(0,O.jsx)(kB,{closeDelay:r,openDelay:e,...s}),k8=({align:e="start",...r})=>(0,O.jsx)(kz,{align:e,...r}),k9=({size:e=16})=>(0,O.jsxs)("svg",{height:e,strokeLinejoin:"round",style:{color:"currentcolor"},viewBox:"0 0 16 16",width:e,children:[(0,O.jsx)("title",{children:"Loader"}),(0,O.jsxs)("g",{clipPath:"url(#clip0_2393_1490)",children:[(0,O.jsx)("path",{d:"M8 0V4",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M8 16V12",opacity:"0.5",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M3.29773 1.52783L5.64887 4.7639",opacity:"0.9",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M12.7023 1.52783L10.3511 4.7639",opacity:"0.1",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M12.7023 14.472L10.3511 11.236",opacity:"0.4",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M3.29773 14.472L5.64887 11.236",opacity:"0.6",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M15.6085 5.52783L11.8043 6.7639",opacity:"0.2",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M0.391602 10.472L4.19583 9.23598",opacity:"0.7",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M15.6085 10.4722L11.8043 9.2361",opacity:"0.3",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M0.391602 5.52783L4.19583 6.7639",opacity:"0.8",stroke:"currentColor",strokeWidth:"1.5"})]}),(0,O.jsx)("defs",{children:(0,O.jsx)("clipPath",{id:"clip0_2393_1490",children:(0,O.jsx)("rect",{fill:"white",height:"16",width:"16"})})})]}),Ne=({className:e,size:r=16,...s})=>(0,O.jsx)("div",{className:(0,ey.cn)("inline-flex animate-spin items-center justify-center",e),...s,children:(0,O.jsx)(k9,{size:r})}),Nt=(0,ew.default)("wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]),Nr=(0,ew.default)("wifi-off",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),Ns=(0,ew.default)("square-pen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]),Nn=(0,ew.default)("languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]),Ni=(0,ew.default)("split",[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M8 3H3v5",key:"15dfkv"}],["path",{d:"M12 22v-8.3a4 4 0 0 0-1.172-2.872L3 3",key:"1qrqzj"}],["path",{d:"m15 9 6-6",key:"ko1vev"}]]),Na=e=>(0,ey.cn)("flex h-5 w-5 shrink-0 items-center justify-center rounded-full","codex"===e?"bg-emerald-500/10 text-emerald-600":"bg-violet-500/10 text-violet-600");function No({agentType:e,currentAgentName:r,alternateProviders:s,onBranch:n,disabled:i,emphasis:a="normal"}){return(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:(0,ey.cn)("h-7 w-7 rounded-md transition-colors hover:bg-muted hover:text-foreground","subtle"===a?"text-muted-foreground/50 group-hover:text-muted-foreground group-focus-within:text-muted-foreground":"text-muted-foreground"),disabled:i,"aria-label":"Branch conversation",children:i?(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"}):(0,O.jsx)(Ni,{className:"h-4 w-4"})})}),(0,O.jsxs)(a7,{align:"start",className:"w-44 p-1.5",children:[(0,O.jsx)(or,{className:"px-2 py-1.5",children:(0,O.jsx)("div",{className:"text-xs font-medium",children:"Branch conversation"})}),(0,O.jsxs)(a8,{className:"h-8 cursor-pointer items-center gap-2 rounded-md px-2 text-xs",onSelect:()=>n(),children:[(0,O.jsx)("div",{className:Na(e),children:(0,O.jsx)(sb,{className:"h-3 w-3"})}),(0,O.jsx)("span",{className:"min-w-0 flex-1 truncate",children:r}),(0,O.jsx)("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:"current"})]}),s.length>0&&(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(os,{className:"my-1"}),s.map(e=>(0,O.jsxs)(a8,{className:"h-8 cursor-pointer items-center gap-2 rounded-md px-2 text-xs",onSelect:()=>n(e.type),children:[(0,O.jsx)("div",{className:Na(e.type),children:(0,O.jsx)(sb,{className:"h-3 w-3"})}),(0,O.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.displayName})]},e.type))]})]})]})}function Nl({durationMs:e,outcome:r,emphasis:s,agentType:n,currentAgentName:i,alternateProviders:a,onBranch:o,disabled:l,showFinalize:c,finalizeBusy:d,onFinalize:u}){let h=void 0!==e?function(e){let r=Math.round(e/1e3);if(r<60)return`${r}s`;let s=Math.floor(r/60),n=r%60;if(s<60)return n?`${s}m ${n}s`:`${s}m`;let i=Math.floor(s/60),a=s%60;return a?`${i}h ${a}m`:`${i}h`}(e):"server_restart"===r?"interrupted":null;return(0,O.jsxs)("div",{className:"group flex items-center gap-2 py-0.5","data-turn-end":!0,children:[(0,O.jsx)("div",{className:"h-px flex-1 bg-border/60"}),null!==h&&(0,O.jsx)("span",{className:(0,ey.cn)("shrink-0 text-[11px] tabular-nums transition-colors","subtle"===s?"text-muted-foreground/50 group-hover:text-muted-foreground group-focus-within:text-muted-foreground":"text-muted-foreground"),children:h}),c&&(0,O.jsx)(cb,{children:(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:(0,ey.cn)("h-7 w-7 shrink-0 rounded-md transition-colors hover:bg-muted hover:text-foreground","subtle"===s?"text-muted-foreground/50 group-hover:text-muted-foreground group-focus-within:text-muted-foreground":"text-muted-foreground"),"aria-label":"生成 review 终稿",onClick:u,disabled:l||d,children:d?(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"}):(0,O.jsx)(Cf,{className:"h-4 w-4"})})}),(0,O.jsx)(cj,{children:"生成 review 终稿"})]})}),(0,O.jsx)(No,{agentType:n,currentAgentName:i,alternateProviders:a,onBranch:o,disabled:l,emphasis:s}),(0,O.jsx)("div",{className:"h-px flex-1 bg-border/60"})]})}var Nc="Popover",[Nd,Nu]=q(Nc,[iw]),Nh=iw(),[Nf,Np]=Nd(Nc),Nm=e=>{let{__scopePopover:r,children:s,open:n,defaultOpen:i,onOpenChange:a,modal:o=!1}=e,l=Nh(r),c=$.useRef(null),[d,u]=$.useState(!1),[h,f]=G({prop:n,defaultProp:i??!1,onChange:a,caller:Nc});return(0,O.jsx)(iC,{...l,children:(0,O.jsx)(Nf,{scope:r,contentId:ek(),triggerRef:c,open:h,onOpenChange:f,onOpenToggle:$.useCallback(()=>f(e=>!e),[f]),hasCustomAnchor:d,onCustomAnchorAdd:$.useCallback(()=>u(!0),[]),onCustomAnchorRemove:$.useCallback(()=>u(!1),[]),modal:o,children:s})})};Nm.displayName=Nc;var Ng="PopoverAnchor",Nx=$.forwardRef((e,r)=>{let{__scopePopover:s,...n}=e,i=Np(Ng,s),a=Nh(s),{onCustomAnchorAdd:o,onCustomAnchorRemove:l}=i;return $.useEffect(()=>(o(),()=>l()),[o,l]),(0,O.jsx)(iN,{...a,...n,ref:r})});Nx.displayName=Ng;var Nv="PopoverTrigger",N_=$.forwardRef((e,r)=>{let{__scopePopover:s,...n}=e,i=Np(Nv,s),a=Nh(s),o=(0,U.useComposedRefs)(r,i.triggerRef),l=(0,O.jsx)(er.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":NM(i.open),...n,ref:o,onClick:K(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?l:(0,O.jsx)(iN,{asChild:!0,...a,children:l})});N_.displayName=Nv;var Ny="PopoverPortal",[Nb,Nw]=Nd(Ny,{forceMount:void 0}),NS=e=>{let{__scopePopover:r,forceMount:s,children:n,container:i}=e,a=Np(Ny,r);return(0,O.jsx)(Nb,{scope:r,forceMount:s,children:(0,O.jsx)(Z,{present:s||a.open,children:(0,O.jsx)(eW,{asChild:!0,container:i,children:n})})})};NS.displayName=Ny;var Nj="PopoverContent",NC=$.forwardRef((e,r)=>{let s=Nw(Nj,e.__scopePopover),{forceMount:n=s.forceMount,...i}=e,a=Np(Nj,e.__scopePopover);return(0,O.jsx)(Z,{present:n||a.open,children:a.modal?(0,O.jsx)(NN,{...i,ref:r}):(0,O.jsx)(NE,{...i,ref:r})})});NC.displayName=Nj;var Nk=(0,et.createSlot)("PopoverContent.RemoveScroll"),NN=$.forwardRef((e,r)=>{let s=Np(Nj,e.__scopePopover),n=$.useRef(null),i=(0,U.useComposedRefs)(r,n),a=$.useRef(!1);return $.useEffect(()=>{let e=n.current;if(e)return tN(e)},[]),(0,O.jsx)(ty,{as:Nk,allowPinchZoom:!0,children:(0,O.jsx)(ND,{...e,ref:i,trapFocus:s.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:K(e.onCloseAutoFocus,e=>{e.preventDefault(),a.current||s.triggerRef.current?.focus()}),onPointerDownOutside:K(e.onPointerDownOutside,e=>{let r=e.detail.originalEvent,s=0===r.button&&!0===r.ctrlKey;a.current=2===r.button||s},{checkForDefaultPrevented:!1}),onFocusOutside:K(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1})})})}),NE=$.forwardRef((e,r)=>{let s=Np(Nj,e.__scopePopover),n=$.useRef(!1),i=$.useRef(!1);return(0,O.jsx)(ND,{...e,ref:r,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:r=>{e.onCloseAutoFocus?.(r),r.defaultPrevented||(n.current||s.triggerRef.current?.focus(),r.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:r=>{e.onInteractOutside?.(r),r.defaultPrevented||(n.current=!0,"pointerdown"===r.detail.originalEvent.type&&(i.current=!0));let a=r.target;s.triggerRef.current?.contains(a)&&r.preventDefault(),"focusin"===r.detail.originalEvent.type&&i.current&&r.preventDefault()}})}),ND=$.forwardRef((e,r)=>{let{__scopePopover:s,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:o,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:u,...h}=e,f=Np(Nj,s),p=Nh(s);return eU(),(0,O.jsx)(eI,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:a,children:(0,O.jsx)(eR,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:u,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>f.onOpenChange(!1),children:(0,O.jsx)(iA,{"data-state":NM(f.open),role:"dialog",id:f.contentId,...p,...h,ref:r,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)"}})})})}),NR="PopoverClose",NA=$.forwardRef((e,r)=>{let{__scopePopover:s,...n}=e,i=Np(NR,s);return(0,O.jsx)(er.button,{type:"button",...n,ref:r,onClick:K(e.onClick,()=>i.onOpenChange(!1))})});NA.displayName=NR;var NT=$.forwardRef((e,r)=>{let{__scopePopover:s,...n}=e,i=Nh(s);return(0,O.jsx)(iF,{...i,...n,ref:r})});function NM(e){return e?"open":"closed"}NT.displayName="PopoverArrow",e.s(["Anchor",()=>Nx,"Arrow",()=>NT,"Close",()=>NA,"Content",()=>NC,"Popover",()=>Nm,"PopoverAnchor",()=>Nx,"PopoverArrow",()=>NT,"PopoverClose",()=>NA,"PopoverContent",()=>NC,"PopoverPortal",()=>NS,"PopoverTrigger",()=>N_,"Portal",()=>NS,"Root",()=>Nm,"Trigger",()=>N_,"createPopoverScope",()=>Nu],154484);var NF=e.i(154484),NF=NF;function NP({...e}){return(0,O.jsx)(NF.Root,{"data-slot":"popover",...e})}function NI({...e}){return(0,O.jsx)(NF.Trigger,{"data-slot":"popover-trigger",...e})}function NB({className:e,align:r="start",sideOffset:s=4,...n}){return(0,O.jsx)(NF.Portal,{children:(0,O.jsx)(NF.Content,{"data-slot":"popover-content",align:r,sideOffset:s,className:(0,ey.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-0 shadow-md outline-hidden",e),...n})})}function NL({candidates:e,className:r,children:s}){let n=Array.from(new Set(e));return(0,O.jsxs)("span",{className:(0,ey.cn)("grid overflow-hidden text-left",r),children:[n.map(e=>(0,O.jsx)("span",{"aria-hidden":!0,className:"col-start-1 row-start-1 invisible whitespace-nowrap",children:e},e)),(0,O.jsx)("span",{className:"col-start-1 row-start-1 min-w-0 truncate",children:s})]})}let Nz="Default",NO="Runs whatever model the CLI is currently set to, which may not be its built-in default.",N$="inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-0.5 text-xs font-medium";function NW({models:e,widthCandidates:r,value:s,onChange:n,locked:i}){let a,[o,l]=(0,$.useState)(!1),[c,d]=(0,$.useState)(""),[u,h]=(0,$.useState)(!1),f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=(0,$.useRef)(0);(0,$.useLayoutEffect)(()=>{let e=f.current,r=p.current;if(e&&r){var s;u||(m.current=e.clientWidth),h((s={textWidth:r.offsetWidth,narrowFieldWidth:m.current,wide:u}).narrowFieldWidth<=0?s.wide:s.textWidth>s.narrowFieldWidth)}},[o,c,u]);let g=s??Nz,x=[Nz,...r??e];if(i)return(0,O.jsxs)("span",{className:(0,ey.cn)(N$,"text-muted-foreground cursor-default"),title:`${g} — fixed while the agent is running, changeable once the turn ends`,children:[(0,O.jsx)(NL,{candidates:x,className:"max-w-40",children:g}),(0,O.jsx)(ns,{className:"h-3 w-3"})]});let v=c.trim(),_=(a=c.trim()).length>0&&!e.includes(a),y=e=>{n(e),d(""),l(!1)};return(0,O.jsxs)(NP,{open:o,onOpenChange:l,children:[(0,O.jsx)(NI,{asChild:!0,children:(0,O.jsxs)("button",{className:(0,ey.cn)(N$,"transition-colors hover:bg-muted"),title:g,children:[(0,O.jsx)(NL,{candidates:x,className:"max-w-40",children:g}),(0,O.jsx)(ns,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,O.jsxs)(NB,{className:u?"w-56":"w-[var(--radix-popover-trigger-width)]",children:[(0,O.jsx)("span",{ref:p,"aria-hidden":!0,className:"pointer-events-none invisible absolute whitespace-pre text-sm",children:c}),(0,O.jsxs)(w5,{shouldFilter:!0,children:[(0,O.jsx)(w4,{ref:f,className:"min-w-0",value:c,onValueChange:d}),(0,O.jsxs)(w6,{children:[(0,O.jsx)(w7,{children:"No match."}),(0,O.jsxs)(w8,{children:[(0,O.jsxs)(w9,{value:Nz,onSelect:()=>y(null),className:"text-xs",children:[Nz,(0,O.jsx)(cb,{delayDuration:200,children:(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsx)("span",{onClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),className:"ml-auto flex cursor-help items-center text-muted-foreground",children:(0,O.jsx)(_J,{"aria-hidden":!0,className:"size-3"})})}),(0,O.jsx)(cj,{side:"right",className:"max-w-56",children:NO})]})}),(0,O.jsx)("span",{className:"sr-only",children:NO})]}),e.map(e=>(0,O.jsx)(w9,{value:e,onSelect:()=>y(e),className:"text-xs",children:e},e))]}),_&&(0,O.jsx)(w8,{heading:"Custom",children:(0,O.jsx)(w9,{value:v,onSelect:()=>y(v),className:"text-xs [&>span]:truncate",title:v,children:(0,O.jsxs)("span",{children:['Use "',v,'"']})})})]})]})]})]})}let NH=(0,ew.default)("clipboard-list",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);function NU({mode:e,onModeChange:r,disabled:s}){return(0,O.jsxs)("div",{className:"inline-flex items-center rounded-md border bg-muted/50 px-0.5 text-xs",children:[(0,O.jsxs)("button",{onClick:()=>r("plan"),disabled:s,className:(0,ey.cn)("inline-flex items-center gap-1 rounded-sm px-2 py-0.5 transition-colors","plan"===e?"bg-primary text-primary-foreground font-medium shadow-sm":"text-muted-foreground hover:text-foreground",s&&"opacity-50 cursor-not-allowed"),children:[(0,O.jsx)(NH,{className:"h-3 w-3"}),"Plan"]}),(0,O.jsxs)("button",{onClick:()=>r("edit"),disabled:s,className:(0,ey.cn)("inline-flex items-center gap-1 rounded-sm px-2 py-0.5 transition-colors","edit"===e?"bg-primary text-primary-foreground font-medium shadow-sm":"text-muted-foreground hover:text-foreground",s&&"opacity-50 cursor-not-allowed"),children:[(0,O.jsx)(rg,{className:"h-3 w-3"}),"Edit"]})]})}function Nq({type:e,className:r}){return(0,O.jsx)(sb,{className:(0,ey.cn)("h-3 w-3 shrink-0","codex"===e?"text-green-500":"text-violet-500",r)})}function NK(e){if(!e)return[];try{let r=window.localStorage.getItem(e);if(!r)return[];let s=JSON.parse(r);if(!Array.isArray(s))return[];return s.filter(e=>"string"==typeof e)}catch{return[]}}let NV=new Set(["waiting_reviewer","waiting_feedback","discussing","sending_feedback"]);function NY(e){if(!e)return"";try{return window.localStorage.getItem(e)??""}catch{return""}}function NG(e){let r=e.parentElement;for(;r;){let{overflowY:e}=getComputedStyle(r);if("auto"===e||"scroll"===e)return r;r=r.parentElement}return null}function NX({messages:e,contentRef:r}){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(null),c=(0,$.useRef)(null),d=(0,$.useCallback)(()=>{let s=r.current;if(!s)return;c.current||(c.current=NG(s));let i=c.current;if(!i)return;let o=i.scrollHeight>i.clientHeight;if(a(o),!o)return void n([]);let l=s.querySelectorAll("[data-user-msg-idx]"),d=i.getBoundingClientRect(),u=[];l.forEach(r=>{let s=parseInt(r.dataset.userMsgIdx,10),n=e[s];if(!n)return;let a=(r.getBoundingClientRect().top-d.top+i.scrollTop)/i.scrollHeight;u.push({index:s,position:Math.max(0,Math.min(1,a)),preview:function(e){if("user"!==e.type)return"";let r=e.content,s="string"==typeof r?r:r.filter(e=>"text"===e.type).map(e=>e.text).join(" "),n="string"!=typeof r&&r.some(e=>"image"===e.type),i=s.split("\n")[0]??"";return(i.length>80?i.slice(0,77)+"...":i)||(n?"(Image)":"")}(n)})}),n(u)},[e,r]);(0,$.useEffect)(()=>{let e=r.current;if(!e){c.current=null,n([]),a(!1);return}let s=NG(e);if(!s)return;c.current=s,d();let i=new ResizeObserver(d);return i.observe(s),i.observe(e),()=>{i.disconnect()}},[e,d,r]);let u=(0,$.useCallback)(e=>{let s=r.current;if(!s)return;let n=s.querySelector(`[data-user-msg-idx="${e}"]`);n&&n.scrollIntoView({block:"start",behavior:"smooth"})},[r]);return i&&0!==s.length?(0,O.jsx)("div",{className:"absolute right-0 top-0 bottom-0 w-6 z-20 pointer-events-none",children:s.map(e=>(0,O.jsxs)("div",{className:"absolute right-0.5 -translate-y-1/2 pointer-events-auto",style:{top:`${100*e.position}%`},children:[(0,O.jsx)("div",{className:"w-3 h-[3px] rounded-sm bg-primary/50 hover:bg-primary cursor-pointer transition-colors",onClick:()=>u(e.index),onMouseEnter:()=>l(e.index),onMouseLeave:()=>l(null)}),o===e.index&&e.preview&&(0,O.jsxs)("div",{className:"absolute right-full mr-2 top-1/2 -translate-y-1/2 max-w-64 px-2.5 py-1.5 bg-popover border border-border rounded-md shadow-md text-xs text-popover-foreground whitespace-nowrap overflow-hidden text-ellipsis pointer-events-none",children:[e.preview,(0,O.jsx)("div",{className:"absolute top-1/2 -translate-y-1/2 -right-1 w-2 h-2 bg-popover border-r border-t border-border rotate-45"})]})]},e.index))}):null}let NJ=(0,ew.default)("star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);function NZ({projectId:e,branch:r,currentSessionId:s,refreshKey:n,pendingTitleSessionId:i,aiTitleOverride:a,onSwitch:o,onDelete:l}){let[c,d]=(0,$.useState)([]),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(""),[m,g]=(0,$.useState)(!1),[x,v]=(0,$.useState)(null),[_,y]=(0,$.useState)(null),[b,w]=(0,$.useState)(0),S=(0,$.useCallback)(()=>w(e=>e+1),[]);(0,$.useEffect)(()=>{let s=!1;return(0,rv.listBranchSessions)(e,r).then(e=>{s||d(e.sessions)}).catch(e=>{s||console.error("[SessionHistoryDropdown] refresh failed:",e)}),()=>{s=!0}},[e,r,n,b]);let j=(0,$.useRef)(null);(0,$.useEffect)(()=>{if(!s)return;if(c.some(e=>e.id===s)){j.current=null;return}if(j.current===s)return;j.current=s;let n=!1;return(0,rv.listBranchSessions)(e,r).then(e=>{if(n)return;d(e.sessions);let r=e.sessions.find(e=>e.id===s),i=!!r&&(a?.sessionId===r.id||!!(r.title&&r.title.trim().length>0));r&&!i&&y(s)}).catch(e=>{n||console.error("[SessionHistoryDropdown] missing-session refresh failed:",e)}),()=>{n=!0}},[s,c,e,r,a]),(0,$.useEffect)(()=>{if(!_)return;let e=setTimeout(()=>{y(e=>e===_?null:e)},3e4);return()=>clearTimeout(e)},[_]),(0,$.useEffect)(()=>{if(!_)return;let e=setTimeout(()=>{y(e=>e===_?null:e)},3e4);return()=>clearTimeout(e)},[_]);let C=async(e,r)=>{let s=r.trim().length>0?r.trim():null;try{await (0,rv.renameSession)(e,s),d(r=>r.map(r=>r.id===e?{...r,title:s}:r)),h(null),_Z.toast.success("Renamed")}catch(e){_Z.toast.error("Rename failed"),console.error(e)}},k=async(e,r)=>{let s=null==r,n=s?Date.now():null;d(r=>r.map(r=>r.id===e?{...r,favorited_at:n}:r));try{await (0,rv.setSessionFavorited)(e,s)}catch(n){d(s=>s.map(s=>s.id===e?{...s,favorited_at:r}:s)),_Z.toast.error(s?"Favorite failed":"Unfavorite failed"),console.error(n)}},N=async e=>{try{await (0,rv.deleteSession)(e);let r=c.filter(r=>r.id!==e);d(r),l?.(e,r),_Z.toast.success("Deleted")}catch(e){_Z.toast.error("Delete failed"),console.error(e)}},E=e=>a&&a.sessionId===e.id?a.title:e.title&&e.title.trim().length>0?e.title:e.updated_at?new Date(e.updated_at).toLocaleString():new Date(e.created_at).toLocaleString(),D=e=>{let r;return a?.sessionId!==e.id&&(!e.title||!(e.title.trim().length>0))&&(r=e.id,null!==i&&i===r||_===e.id)},R=c.find(e=>e.id===s),A=null!==s&&(!R||D(R)),T=R?E(R):null===s?"New Session":"History",M=A?"Generating title…":T;return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)(a4,{open:m,onOpenChange:e=>{g(e),e&&S()},children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsxs)(W.Button,{variant:"ghost",size:"sm",className:"h-7 text-xs gap-1 w-[200px] justify-start",title:M,children:[A?(0,O.jsx)("span",{className:"block h-3 flex-1 rounded-sm bg-accent animate-pulse",role:"status","aria-label":"Generating title"}):(0,O.jsx)("span",{className:"truncate flex-1 text-left",children:T}),(0,O.jsx)(ns,{className:"h-3 w-3 flex-shrink-0"})]})}),(0,O.jsxs)(a7,{align:"start",className:"w-80 max-h-96 overflow-y-auto",children:[0===c.length&&(0,O.jsx)("div",{className:"px-2 py-3 text-xs text-muted-foreground",children:"No history yet."}),c.map(e=>{let r=e.id===s,n=u===e.id;return(0,O.jsxs)(a8,{onSelect:s=>{n?s.preventDefault():r||o(e.id)},onPointerMove:null!==u?e=>e.preventDefault():void 0,className:`flex items-center gap-2 group ${r?"bg-accent text-accent-foreground":""}`,children:[(0,O.jsx)("div",{className:"flex-1 min-w-0",children:n?(0,O.jsxs)("div",{className:"flex items-center gap-1",children:[(0,O.jsx)(ro,{value:f,onChange:e=>p(e.target.value),onKeyDown:r=>{r.stopPropagation(),"Enter"===r.key&&C(e.id,f),"Escape"===r.key&&h(null)},autoFocus:!0,className:"h-6 text-xs"}),(0,O.jsx)("button",{type:"button","aria-label":"Save rename",onClick:r=>{r.stopPropagation(),C(e.id,f)},children:(0,O.jsx)(rf.Check,{className:"h-3 w-3"})}),(0,O.jsx)("button",{type:"button","aria-label":"Cancel rename",onClick:e=>{e.stopPropagation(),h(null)},children:(0,O.jsx)(t7,{className:"h-3 w-3"})})]}):D(e)?(0,O.jsx)("div",{className:"py-0.5",title:"Generating title…",children:(0,O.jsx)("span",{className:"block h-3 w-40 rounded-sm bg-accent animate-pulse",role:"status","aria-label":"Generating title"})}):(0,O.jsx)("div",{className:"truncate text-xs",title:`${e.updated_at?new Date(e.updated_at).toLocaleString():new Date(e.created_at).toLocaleString()} • ${e.entry_count??0} messages • status: ${e.status} • model: ${e.model??"Default"}`,children:E(e)})}),!n&&(0,O.jsxs)("div",{className:"flex items-center gap-1",children:[(0,O.jsxs)("div",{className:"opacity-0 group-hover:opacity-100 flex items-center gap-1",children:[(0,O.jsx)("button",{type:"button","aria-label":"Rename conversation",onClick:r=>{r.stopPropagation(),h(e.id),p(e.title??"")},className:"p-1 hover:bg-muted rounded",children:(0,O.jsx)(rg,{className:"h-3 w-3"})}),(0,O.jsx)("button",{type:"button","aria-label":"Delete conversation",onClick:r=>{r.stopPropagation(),g(!1),v(e)},className:"p-1 hover:bg-muted rounded text-destructive",children:(0,O.jsx)(rc,{className:"h-3 w-3"})})]}),(0,O.jsx)("button",{type:"button","aria-label":null!=e.favorited_at?"Unfavorite conversation":"Favorite conversation",title:null!=e.favorited_at?"Unfavorite":"Favorite",onClick:r=>{r.stopPropagation(),k(e.id,e.favorited_at??null)},className:`p-1 hover:bg-muted rounded ${null!=e.favorited_at?"opacity-100 text-yellow-500":"opacity-0 group-hover:opacity-100 text-muted-foreground"}`,children:(0,O.jsx)(NJ,{className:`h-3 w-3 ${null!=e.favorited_at?"fill-current":""}`})})]})]},e.id)}),c.length>0&&(0,O.jsx)(os,{}),(0,O.jsx)(a8,{onSelect:()=>S(),className:"text-xs text-muted-foreground",children:"Refresh"})]})]}),(0,O.jsx)(lL,{open:null!==x,onOpenChange:e=>{e||v(null)},children:(0,O.jsxs)(l$,{children:[(0,O.jsxs)(lW,{children:[(0,O.jsx)(lU,{children:"Delete conversation?"}),(0,O.jsx)(lq,{children:x?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("span",{className:"font-medium text-foreground",children:E(x)})," ","and its message history will be permanently deleted. This cannot be undone."]}):null})]}),(0,O.jsxs)(lH,{children:[(0,O.jsx)(lV,{children:"Cancel"}),(0,O.jsx)(lK,{className:(0,ey.cn)((0,W.buttonVariants)({variant:"destructive"}),"border-transparent"),onClick:()=>{x&&N(x.id),v(null)},children:"Delete"})]})]})})]})}let NQ=(0,ew.default)("quote",[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"rib7q0"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"1ymkrd"}]]);function N0(e,r){let s=e;for(;s&&s!==r;){if(s.nodeType===Node.ELEMENT_NODE){let e=s.getAttribute("data-message-idx");if(null!==e)return e}s=s.parentNode}return null}function N1({containerRef:e,onQuote:r}){let[s,n]=(0,$.useState)(null);if((0,$.useEffect)(()=>{function r(){let r=e.current;if(!r)return void n(null);let s=window.getSelection();if(!s||s.isCollapsed||0===s.rangeCount)return void n(null);let i=s.toString();if(!i.trim())return void n(null);let{anchorNode:a,focusNode:o}=s;if(!a||!o||!r.contains(a)||!r.contains(o))return void n(null);let l=N0(a,r),c=N0(o,r);if(null===l||null===c||l!==c)return void n(null);let d=s.getRangeAt(0).getBoundingClientRect();0===d.width&&0===d.height?n(null):n({text:i,rect:{top:d.top,bottom:d.bottom,left:d.left,width:d.width}})}function s(){let e=window.getSelection();e&&!e.isCollapsed&&e.toString().trim()||n(null)}return document.addEventListener("mouseup",r),document.addEventListener("keyup",r),document.addEventListener("touchend",r),document.addEventListener("selectionchange",s),window.addEventListener("scroll",r,!0),window.addEventListener("resize",r),()=>{document.removeEventListener("mouseup",r),document.removeEventListener("keyup",r),document.removeEventListener("touchend",r),document.removeEventListener("selectionchange",s),window.removeEventListener("scroll",r,!0),window.removeEventListener("resize",r)}},[e]),!s||"undefined"==typeof document)return null;let i=s.rect.top-8-30<8?s.rect.bottom+8:s.rect.top-8-30,a=s.rect.left+s.rect.width/2,o=Math.max(8,Math.min(window.innerWidth-8,a));return(0,ee.createPortal)((0,O.jsxs)("button",{type:"button",onMouseDown:e=>{e.preventDefault(),r(s.text),window.getSelection()?.removeAllRanges(),n(null)},style:{position:"fixed",top:i,left:o,transform:"translateX(-50%)",zIndex:50},className:"inline-flex items-center gap-1.5 rounded-md border border-border bg-popover px-3 py-1.5 text-xs font-medium text-popover-foreground shadow-2xl hover:bg-accent",children:[(0,O.jsx)(NQ,{className:"h-3 w-3"}),"Quote"]}),document.body)}let N2=(0,ew.default)("search-check",[["path",{d:"m8 11 2 2 4-4",key:"1sed1v"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]),N5=[{type:"claude-code",displayName:"Claude Code",available:!0},{type:"codex",displayName:"Codex",available:!0}];function N3({projectId:e,branch:r,sessionId:s,currentAgentType:n,providers:i}){let[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(""),[d,u]=(0,$.useState)("claude-code"),[h,f]=(0,$.useState)("this_turn"),[p,m]=(0,$.useState)("new"),[g,x]=(0,$.useState)(null),[v,_]=(0,$.useState)(!1),[y,b]=(0,$.useState)(null),[w,S]=(0,$.useState)(!1),[j,C]=(0,$.useState)(null),k=(0,$.useRef)(null),N=i?.length?i:N5;if((0,$.useEffect)(()=>{if(a){var e;let r;u((e=n??null,r=N.filter(e=>e.available),r.find(r=>r.type!==e)?.type??r[0]?.type??"claude-code")),f("this_turn")}},[a]),(0,$.useEffect)(()=>{if(!a||!s)return;let r=!1;return m("new"),x(null),b(null),_(!0),rv.api.getReviewerCandidate(e,s).then(e=>{!r&&(x(e),e?.available&&e.sessionId?m("reuse"):e&&b("上次 reviewer 已不可用,将创建新 session"))}).catch(()=>{r||b("无法加载上次 reviewer,将创建新 session")}).finally(()=>{r||_(!1)}),()=>{r=!0}},[a,e,s]),(0,$.useEffect)(()=>{if(!a){k.current=null;return}if(!s)return;let r=k.current;r&&r.projectId===e&&r.sessionId===s||(k.current={projectId:e,sessionId:s,result:rv.api.generateReviewIntentBrief(e,s).then(e=>({reached:!0,brief:e})).catch(()=>({reached:!1,brief:null}))})},[a,e,s]),!s)return null;let E=async()=>{S(!0),C(null);try{let n="reuse"===p&&g?.sessionId?{reviewerSessionId:g.sessionId}:{reviewerAgentType:d},i=k.current,a="reviewerAgentType"in n&&i?.projectId===e&&i?.sessionId===s?i:null,u=a?await a.result:null,f=u?.reached?{intentBrief:u.brief??""}:{};await rv.api.createWorkflowRun({projectId:e,branch:r,sourceSessionId:s,reviewFocus:l.trim()||void 0,reviewSpan:h,...n,...f}),o(!1),c("")}catch(r){C(r instanceof Error?r.message:String(r)),rv.api.getReviewerCandidate(e,s).then(e=>{x(e),e?.available&&e.sessionId||(m("new"),b("上次 reviewer 已不可用,将创建新 session"))}).catch(()=>void 0)}finally{S(!1)}};return(0,O.jsxs)(t8,{open:a,onOpenChange:o,children:[(0,O.jsx)(t9,{asChild:!0,children:(0,O.jsx)(W.Button,{variant:"ghost",size:"sm",title:"让另一个 agent review 这个 session 的最新成果",children:(0,O.jsx)(N2,{className:"h-4 w-4"})})}),(0,O.jsxs)(rr,{className:"sm:max-w-md",children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:"发起 Review"}),(0,O.jsx)(ra,{children:"默认继续上次 reviewer 的上下文,也可以创建新 reviewer session。反馈会先经你确认,再发回本 session。"})]}),(0,O.jsxs)("div",{className:"grid gap-2",children:[g?.available&&g.sessionId&&(0,O.jsxs)(W.Button,{type:"button",variant:"reuse"===p?"secondary":"outline",className:"h-auto justify-start whitespace-normal py-2 text-left","aria-pressed":"reuse"===p,onClick:()=>m("reuse"),children:["继续上次 Reviewer — ",g.title??"Review session"]}),(0,O.jsx)(W.Button,{type:"button",variant:"new"===p?"secondary":"outline",className:"justify-start","aria-pressed":"new"===p,onClick:()=>m("new"),children:"创建新 Reviewer Session"})]}),y&&(0,O.jsx)("p",{className:"text-sm text-amber-600 dark:text-amber-400",children:y}),"new"===p&&(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)("span",{className:"text-sm text-muted-foreground shrink-0",children:"Reviewer agent"}),(0,O.jsxs)(hw,{value:d,onValueChange:e=>u(e),children:[(0,O.jsx)(hj,{className:"h-8 text-sm flex-1",children:(0,O.jsx)(hS,{})}),(0,O.jsx)(hC,{children:N.map(e=>(0,O.jsxs)(hk,{value:e.type,disabled:!e.available,children:[e.displayName,e.type===n?"(当前 agent)":""]},e.type))})]})]}),"new"===p&&(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)("span",{className:"text-sm text-muted-foreground shrink-0",children:"审查范围"}),(0,O.jsxs)(hw,{value:h,onValueChange:e=>f(e),children:[(0,O.jsx)(hj,{className:"h-8 text-sm flex-1",children:(0,O.jsx)(hS,{})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"this_turn",children:"仅本次 turn(默认)"}),(0,O.jsx)(hk,{value:"session_start",children:"整个 session(自起点)"})]})]})]}),(0,O.jsx)("input",{className:"w-full rounded-md border bg-transparent px-3 py-2 text-sm",placeholder:"Review focus(可选):本次审查重点…",value:l,onChange:e=>c(e.target.value)}),j&&(0,O.jsx)("p",{className:"text-sm text-destructive",children:j}),(0,O.jsx)(rn,{children:(0,O.jsx)(W.Button,{onClick:E,disabled:w||v,children:w?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}),"正在准备 review 上下文…"]}):"开始 Review"})})]})]})}function N4(){return 0===kY().files.length?null:(0,O.jsx)(k0,{className:"pt-3 pb-0",children:(0,O.jsx)(kX,{className:"p-0",children:e=>(0,O.jsx)(kG,{data:e})})})}let N6=(0,$.createContext)(null);function N7(){let e=(0,$.useContext)(N6);if(!e)throw Error("useAgentConversation must be used within AgentConversationContext");return e}let N8=/\[📎 paste #(\d+) \([^)]+\)\]/g;function N9(e,r){return`[📎 paste #${e} (${function(e){if(e<1024)return`${e}B`;let r=e/1024;return r<10?`${r.toFixed(1)}KB`:`${Math.round(r)}KB`}(r)})]`}let Ee=(0,$.forwardRef)(function({projectId:e,branch:r,sessionId:s,setSessionUrlParam:n,project:i,onAgentModeChange:a,onTaskCompleted:o,onSessionStarted:l,onSessionTitleUpdated:c,onSessionSelected:d,onStatusChange:u,onNewConversation:h,onActiveSessionChange:f},p){var m;let g,x,v,_,[y,b]=function(e,r){let s=e&&r?`vibedeckx:agent-draft:${e}:${r}`:null,[n,i]=(0,$.useState)(()=>NY(s)),[a,o]=(0,$.useState)(s);return a!==s&&(o(s),i(NY(s))),[n,(0,$.useCallback)(e=>{i(e);if(s)try{e?window.localStorage.setItem(s,e):window.localStorage.removeItem(s)}catch{}},[s])]}(e,r),[w,S]=(0,$.useState)([]),[j,C]=(0,$.useState)(1),[k,N]=(0,$.useState)("edit"),[E,D]=(0,$.useState)(!1),[R,A]=(0,$.useState)(!1),[T,M]=(0,$.useState)(!1),[F,P]=(0,$.useState)("claude-code"),[I,B]=(0,$.useState)([]),[L,z]=(0,$.useState)(null),[H,U]=(0,$.useState)(0),[q,K]=(0,$.useState)(null),[V,Y]=(0,$.useState)(null),G=(0,$.useRef)(null),X=(0,$.useCallback)(e=>{if("ArrowUp"!==e.key&&"ArrowDown"!==e.key||!e.shiftKey||e.ctrlKey||e.metaKey||e.altKey)return;let r=G.current;if(!r)return;let s=NG(r);if(!s)return;let n=s.getBoundingClientRect(),i=s.scrollTop,a="ArrowUp"===e.key,o=null,l=a?-1/0:1/0;r.querySelectorAll("[data-user-msg-idx]").forEach(e=>{let r=e.getBoundingClientRect().top-n.top+s.scrollTop;a?r<i-12&&r>l&&(l=r,o=e):r>i+12&&r<l&&(l=r,o=e)}),o&&(e.preventDefault(),o.scrollIntoView({block:"start",behavior:"smooth"}))},[G]),J=(0,$.useRef)(null),Z=function(e,r,s){let n=r&&s?`vibedeckx:agent-input-history:${r}:${s}`:null,i=(0,$.useRef)(NK(n)),a=(0,$.useRef)(-1),o=(0,$.useRef)(""),[l,c]=(0,$.useState)(n);return l!==n&&(c(n),i.current=NK(n),a.current=-1,o.current=""),{push:(0,$.useCallback)(e=>{let r=e.trim();if(!r)return;let s=i.current;if(s.length>0&&s[s.length-1]===r){a.current=-1;return}s.push(r),s.length>50&&s.shift(),a.current=-1;if(n)try{0===s.length?window.localStorage.removeItem(n):window.localStorage.setItem(n,JSON.stringify(s))}catch{}},[n]),handleKeyDown:(0,$.useCallback)(r=>{let s=r.currentTarget,n=i.current;if(0!==n.length)if("ArrowUp"===r.key){if(0!==s.selectionStart||0!==s.selectionEnd)return;if(r.preventDefault(),-1===a.current)o.current=s.value,a.current=n.length-1;else{if(!(a.current>0))return;a.current--}e(n[a.current])}else if("ArrowDown"===r.key){if(-1===a.current)return;let i=s.value.length;if(s.selectionStart!==i||s.selectionEnd!==i)return;r.preventDefault(),a.current<n.length-1?(a.current++,e(n[a.current])):(a.current=-1,e(o.current))}else -1!==a.current&&(a.current=-1)},[e])}}(b,e,r),{remotes:Q}=b1(),ee=[];for(let e of(i?.path&&ee.push({id:"local",label:"Local",icon:oc}),Q))ee.push({id:e.remote_server_id,label:e.server_name,icon:sx(e)});let{session:et,messages:er,status:es,isConnected:en,isInitialized:ei,isLoading:ea,error:eo,remoteStatus:el,workflowRunUpdate:ec,sendMessage:ed,uploadPaste:eu,stopSession:eh,switchAgentType:ef,setModel:ep,startNewConversation:em,ensureSession:eg,switchMode:ex,acceptPlan:ev,residentLimitPrompt:e_}=function(e,r,s,n,i){let a=i?.sessionId??null,[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)([]),[u,h]=(0,$.useState)("stopped"),[f,p]=(0,$.useState)(!1),[m,g]=(0,$.useState)(!1),[x,v]=(0,$.useState)(!1),[_,y]=(0,$.useState)(null),[b,w]=(0,$.useState)(null),[S,j]=(0,$.useState)(null),C=(0,$.useRef)(null),k=(0,$.useRef)(null),N=(0,$.useRef)(()=>{}),E=(0,$.useRef)(null),D=(0,$.useRef)(0),R=(0,$.useRef)({entries:[],status:"stopped"}),A=(0,$.useRef)(!1),T=(0,$.useRef)(!0),M=(0,$.useRef)(null),F=(0,$.useRef)(null),P=(0,$.useRef)(0),I=(0,$.useRef)(!1),B=(0,$.useRef)(null),L=(0,$.useRef)(0),z=(0,$.useRef)(!1),O=(0,$.useRef)(!1),W=(0,$.useRef)(Promise.resolve()),H=(0,$.useRef)(i?.onTaskCompleted),U=(0,$.useRef)(i?.onSessionStarted),q=(0,$.useRef)(i?.onTitleUpdated),K=(0,$.useRef)(e),V=(0,$.useRef)(r),Y=(0,$.useRef)(a);(0,$.useEffect)(()=>{H.current=i?.onTaskCompleted,U.current=i?.onSessionStarted,q.current=i?.onTitleUpdated,K.current=e,V.current=r,Y.current=a});let G=(0,$.useCallback)(()=>{B.current&&(clearTimeout(B.current),B.current=null)},[]),X=(0,$.useCallback)(e=>{B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{if(B.current=null,e.readyState===WebSocket.OPEN){console.warn(`[AgentSession] No frames for 95000ms — assuming dead socket, forcing reconnect`);try{e.close(4e3,"silence watchdog")}catch{}}},95e3)},[]),J=(0,$.useCallback)((e,r=!1)=>{Promise.race([(0,rv.getFreshToken)(r?{skipCache:!0}:void 0),new Promise(e=>setTimeout(e,5e3))]).catch(()=>void 0).then(()=>N.current(e))},[]),Z=(0,$.useCallback)(e=>{let r=()=>{let e=K.current;if(!e)return;let r=V.current;Ca.delete(Co(e,r,Y.current));let s=k.current;s&&Ca.delete(Co(e,r,s)),Ca.delete(Co(e,r,null))};if(C.current&&k.current!==e&&(console.log(`[AgentSession] Closing stale WS for ${k.current}, switching to ${e}`),C.current.close(1e3,"session-switch"),C.current=null,k.current=null),C.current?.readyState===WebSocket.OPEN||C.current?.readyState===WebSocket.CONNECTING)return;0===R.current.entries.filter(Boolean).length&&(R.current={entries:[],status:"running"}),A.current=!1,I.current=!0;let s=(0,rv.getWebSocketUrl)(`/api/agent-sessions/${e}/stream`);console.log("[AgentSession] Connecting to WebSocket:",s);let n=new WebSocket(s);C.current=n,k.current=e,n.onopen=()=>{console.log("[AgentSession] WebSocket connected"),p(!0),y(null),w(null),M.current=Date.now(),X(n),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>{console.log("[AgentSession] Connection stable, resetting backoff counter"),D.current=0,P.current=0},5e3)},n.onmessage=e=>{X(n);try{let i=JSON.parse(e.data);if("keepalive"in i)return;if("JsonPatch"in i){var s;let e=i.JsonPatch;s=R.current,R.current=jY(s,r=>{for(let s of e){let{op:e,path:n,value:i}=s;if("/entries"===n&&"replace"===e&&i?.type==="ENTRY"&&i.content?.type==="system"&&i.content?.content==="__CLEAR_ALL__"){console.log("[JsonPatch] Received clearAll signal - clearing all entries"),r.entries=[];continue}if(n.startsWith("/entries/")){let s=parseInt(n.replace("/entries/",""),10);if(isNaN(s)){console.warn(`[JsonPatch] Invalid index in path: ${n}`);continue}if(i?.type!=="ENTRY"){console.warn("[JsonPatch] Expected ENTRY type for entries path");continue}switch(e){case"add":for(;r.entries.length<=s;)r.entries.push(null);r.entries[s]=i.content;break;case"replace":s<r.entries.length?r.entries[s]=i.content:console.warn(`[JsonPatch] Replace index out of bounds: ${s}`);break;case"remove":s<r.entries.length&&r.entries.splice(s,1)}}else"/status"===n&&i?.type==="STATUS"&&(console.log("[AgentSession] /status patch →",i.content),r.status=i.content)}}),I.current?console.log("[AgentSession] /status patch applied during replay (no setStatus), container.status =",R.current.status):(d([...R.current.entries.filter(Boolean)]),console.log("[AgentSession] setStatus(live) →",R.current.status),h(R.current.status),("stopped"===R.current.status||"error"===R.current.status)&&r());return}if("Ready"in i){console.log("[AgentSession] Received Ready signal - history complete, status=",R.current.status),I.current=!1,d([...R.current.entries.filter(Boolean)]),h(R.current.status),g(!0);return}if("finished"in i){console.log("[AgentSession] Received finished signal, invalidating cache"),A.current=!0,r(),n.close(1e3,"finished");return}if("taskCompleted"in i){let{duration_ms:e,cost_usd:r,input_tokens:s,output_tokens:n}=i.taskCompleted,a=[];if(null!=e){let r=(e/1e3).toFixed(1);a.push(`${r}s`)}if(null!=r)a.push(`$${r.toFixed(4)}`);else if(null!=s||null!=n){let e=(s??0)+(n??0),r=e>1e3?`${(e/1e3).toFixed(1)}K`:String(e);a.push(`${r} tokens`)}_Z.toast.success("Task completed",{description:a.length>0?a.join(" · "):void 0}),H.current?.();return}if("remoteStatus"in i)return void w(i.remoteStatus);if("titleUpdated"in i)return void q.current?.(i.titleUpdated.title,k.current);if("workflowRunUpdated"in i&&j(i.workflowRunUpdated),"error"in i){console.error("[AgentSession] Server error:",i.error),y(i.error),"Session not found"===i.error&&(console.log("[AgentSession] Session invalid, invalidating cache, will create new session"),r(),A.current=!0,l(null),h("stopped"),g(!1),T.current=!0);return}}catch(e){console.error("[AgentSession] Failed to parse message:",e)}},n.onclose=e=>{let s,n;console.log("[AgentSession] WebSocket disconnected",e.code,e.reason),p(!1),G(),F.current&&(clearTimeout(F.current),F.current=null);let i=M.current?Date.now()-M.current:0;if(M.current=null,i>0&&i<5e3){if(P.current++,console.log(`[AgentSession] Short-lived connection (${i}ms), count: ${P.current}, backoff attempt: ${D.current}`),P.current>=3){if(console.log("[AgentSession] Multiple short-lived connections detected, session likely invalid - will recreate"),z.current){console.log("[AgentSession] Skipping auto-restart: last session creation failed"),y("Unable to connect to remote server. Please check the server configuration.");return}r(),l(null),y(null),D.current=0,P.current=0,T.current=!0;return}}else i>=5e3&&(P.current=0);if(A.current||1e3===e.code)return;if(D.current>=10){console.log("[AgentSession] Max reconnect attempts reached"),y("Unable to connect to server. Please check if the backend is running.");return}let a=(n=(s=Math.min(3e4,1e3*Math.pow(2,D.current)))*Math.random()*.25,s+n);console.log(`[AgentSession] Reconnecting in ${Math.round(a)}ms (attempt ${D.current+1})`),D.current++,E.current=setTimeout(()=>{let e=k.current;e&&!A.current&&J(e,!0)},a)},n.onerror=e=>{console.error("[AgentSession] WebSocket error:",e)}},[J,X,G]);(0,$.useEffect)(()=>{N.current=Z},[Z]);let Q=(0,$.useCallback)(async s=>{if(!e)return null;if(O.current)return console.log("[AgentSession] startSession already in progress, skipping"),null;O.current=!0;let i=L.current;y(null),w(null),g(!1),z.current=!1;let o=Co(e,r,a),c=Ca.get(o);if(c)return console.log(`[AgentSession] Cache hit for ${o}, reconnecting WebSocket directly`),l(c),h(c.status),J(c.id),U.current?.(c),O.current=!1,c;v(!0);try{console.log(`[AgentSession] Starting REST call: projectId=${e}, branch=${r}, sessionId=${a??"latest"}, agentType=${n}, generation=${i}`);let{session:c,messages:u}=a?await Cl(a):await j7(e,r,s,n);if(L.current!==i)return console.log("[AgentSession] Discarding stale session response (generation mismatch)"),null;if(!c)return console.log(`[AgentSession] No existing session for ${e}/${r??"<null>"} — placeholder`),l(null),h("stopped"),d([]),R.current={entries:[],status:"stopped"},g(!0),null;return console.log(`[AgentSession] REST response: sessionId=${c.id}, msgCount=${u?.length??0}, status=${c.status}, explicitSessionIdRequested=${a??"<null>"}`),Ca.set(o,c),a&&Ca.set(Co(e,r,c.id),c),l(c),h(c.status),u&&u.length>0&&(d(u),R.current={entries:[...u],status:c.status}),J(c.id),U.current?.(c),c}catch(e){if(console.error("[AgentSession] startSession error:",e),L.current!==i)return console.log("[AgentSession] Discarding error (generation mismatch)"),null;return y(e instanceof Error?e.message:"Failed to start session"),z.current=!0,null}finally{O.current=!1,L.current===i&&v(!1)}},[e,r,n,a,J]),ee=(0,$.useCallback)(async(s,n)=>{let i=n||o?.id;if(!i)return void console.warn("[AgentSession] sendMessage: no session ID available (sessionId param:",n,", session?.id:",o?.id,")");if(("string"!=typeof s||s.trim())&&(!Array.isArray(s)||0!==s.length)){console.log(`[AgentSession] sendMessage: targetSessionId=${i}, source=${n?"explicit":"state"}`);try{let e="string"==typeof s?s.trim():s;await j8(i,e)}catch(n){let s=n instanceof Error?n.message:"Failed to send message";console.error("[AgentSession] Failed to send message:",s),s.includes("[404]")&&(e&&(Ca.delete(Co(e,r,a)),o?.id&&Ca.delete(Co(e,r,o.id))),l(null),h("stopped"),g(!1),T.current=!0),y(s),_Z.toast.error("Failed to send message",{description:s})}}},[o?.id,e,r,a]),et=(0,$.useCallback)(async(e,r)=>{let s=r||o?.id;if(!s)throw Error("No session id available for paste upload");return j9(s,e)},[o?.id]),er=(0,$.useCallback)(async()=>{if(o?.id)try{await Cs(o.id)}catch(e){e instanceof Error&&e.message,console.error("[AgentSession] Failed to stop session:",e),_Z.toast.error("Failed to stop session")}},[o?.id]),es=(0,$.useCallback)(async s=>{if(o?.id){e&&(Ca.delete(Co(e,r,a)),Ca.delete(Co(e,r,o.id))),v(!0),y(null);try{await Ce(o.id,s),s&&l(e=>e?{...e,agentType:s}:null)}catch(e){y(e instanceof Error?e.message:"Failed to restart session"),console.error("[AgentSession] Failed to restart session:",e)}finally{v(!1)}}},[o?.id,e,r,a]),en=(0,$.useCallback)(async s=>{if(!o?.id)return"No active session";y(null);try{return await Ct(o.id,s),l(n=>{if(!n)return n;let i={...n,agentType:s,model:null};return e&&(Ca.set(Co(e,r,a),i),Ca.set(Co(e,r,i.id),i)),i}),null}catch(r){let e=r instanceof Error?r.message:"Failed to switch agent";return console.error("[AgentSession] Failed to switch agent:",r),e}},[o?.id,e,r,a]),ei=(0,$.useCallback)(async s=>{let n=o?.id;if(!n)return"No active session";y(null);let i=W.current.then(()=>Cr(n,s));W.current=i.then(()=>void 0,()=>void 0);try{let s=await i;return l(i=>{if(!i||i.id!==n)return i;let o={...i,model:s};return e&&(Ca.set(Co(e,r,a),o),Ca.set(Co(e,r,o.id),o)),o}),null}catch(r){let e=r instanceof Error?r.message:"Failed to set model";return console.error("[AgentSession] Failed to set model:",r),e}},[o?.id,e,r,a]),ea=(0,$.useCallback)(async s=>{if(o?.id){y(null);try{await Cn(o.id,s),l(n=>{if(!n)return n;let i={...n,permissionMode:s};return e&&(Ca.set(Co(e,r,a),i),Ca.set(Co(e,r,i.id),i)),i})}catch(e){y(e instanceof Error?e.message:"Failed to switch mode"),console.error("[AgentSession] Failed to switch mode:",e)}}},[o?.id,e,r,a]),eo=(0,$.useCallback)(async s=>{if(o?.id){y(null);try{await Ci(o.id,s),l(s=>{if(!s)return s;let n={...s,permissionMode:"edit"};return e&&(Ca.set(Co(e,r,a),n),Ca.set(Co(e,r,n.id),n)),n})}catch(e){y(e instanceof Error?e.message:"Failed to accept plan"),console.error("[AgentSession] Failed to accept plan:",e)}}},[o?.id,e,r,a]),el=(0,$.useCallback)(async()=>{var n;let i;return e?(o?.id&&Ca.delete(Co(e,r,o.id)),Ca.delete(Co(e,r,a)),C.current&&(C.current.close(1e3,"new-conversation"),C.current=null,k.current=null),E.current&&(clearTimeout(E.current),E.current=null),F.current&&(clearTimeout(F.current),F.current=null),A.current=!1,I.current=!1,p(!1),l(null),h("stopped"),g(!0),y(null),w(null),d([]),R.current={entries:[],status:"stopped"},n=j3(e,r,s),(i=new Map(jJ)).set(n,Date.now()),jX(jJ=i),j0(),null):null},[e,r,s,o?.id,a]),[ec,ed]=(0,$.useState)(null),eu=(0,$.useRef)(null),eh=(0,$.useCallback)(()=>{eu.current?.resolve(!1),eu.current=null,ed(null)},[]),ef=(0,$.useRef)(new Map),ep=(0,$.useCallback)((i,c)=>{if(!e)return Promise.resolve(null);if(o)return Promise.resolve(o);let d=L.current,u=`${d}:${c??null}`,f=ef.current.get(u);if(f)return f;let p=(async()=>{v(!0),y(null);try{let o;try{o=await (0,rv.createNewAgentSession)(e,r,i,n,void 0,c)}catch(h){let s;if(!(h instanceof rv.ResidentLimitError))throw h;let a=new Promise(e=>{s=e}),l={maxResidentAgentProcesses:h.maxResidentAgentProcesses,runningSessions:h.runningSessions,resolve:s};eu.current=l,ed(l);let u=await a;if(eu.current===l&&(eu.current=null),ed(e=>e===l?null:e),L.current!==d)return null;if(!u)throw h;o=await (0,rv.createNewAgentSession)(e,r,i,n,!0,c)}if(L.current!==d)return console.log("[AgentSession] Discarding stale ensureSession result (generation mismatch)"),null;let u={id:o.session.id,projectId:o.session.projectId,branch:o.session.branch,status:o.session.status,permissionMode:o.session.permissionMode??"edit",agentType:o.session.agentType??"claude-code",model:o.session.model??null,processAlive:o.session.processAlive??!0};return Ca.set(Co(e,r,a),u),Ca.set(Co(e,r,u.id),u),l(u),h(u.status),g(!0),j4(j3(e,r,s)),J(u.id),U.current?.(u),u}catch(e){if(console.error("[AgentSession] ensureSession:",e),L.current!==d)return null;return y(e instanceof Error?e.message:"Failed to create session"),null}finally{ef.current.get(u)===p&&ef.current.delete(u),L.current===d&&v(!1)}})();return ef.current.set(u,p),p},[e,r,s,n,o,a,J]);return(0,$.useEffect)(()=>()=>{C.current&&(A.current=!0,C.current.close(),k.current=null),E.current&&clearTimeout(E.current),F.current&&clearTimeout(F.current),G(),L.current+=1,eh()},[eh,G]),(0,$.useEffect)(()=>{C.current&&(C.current.close(1e3,"branch-switch"),C.current=null,k.current=null),E.current&&(clearTimeout(E.current),E.current=null),F.current&&(clearTimeout(F.current),F.current=null),G(),L.current+=1,eh();let n=e?j3(e,r,s):null;n&&a&&j4(n);let i=!a&&null!==n&&jJ.has(n);l(null),h("stopped"),p(!1),g(i),y(null),v(!1),w(null),d([]),R.current={entries:[],status:"stopped"},A.current=!1,D.current=0,M.current=null,P.current=0,z.current=!1,O.current=!1,T.current=!i,e&&Ca.delete(Co(e,r,a))},[e,r,s,a,eh,G]),(0,$.useEffect)(()=>{var n;let i=null!==e&&(n=j3(e,r,s),jJ.has(n));!T.current||!e||o||x||z.current||i||(T.current=!1,console.log(`[AgentSession] Auto-start: projectId=${e}, branch=${r}, agentMode=${s}`),Q())},[e,r,s,o,x,Q]),(0,$.useEffect)(()=>{let e=()=>{if("visible"===document.visibilityState&&o?.id&&!A.current){let e=C.current;e&&e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING||(console.log("[AgentSession] Tab visible, WebSocket disconnected - reconnecting"),D.current=0,P.current=0,E.current&&(clearTimeout(E.current),E.current=null),J(o.id))}};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[o?.id,J]),(0,$.useEffect)(()=>{o?.id&&!A.current&&J(o.id)},[o?.id,J]),{session:o,messages:c,status:u,isConnected:f,isInitialized:m,isLoading:x,error:_,remoteStatus:b,workflowRunUpdate:S,startSession:Q,sendMessage:ee,uploadPaste:et,stopSession:er,restartSession:es,switchAgentType:en,setModel:ei,startNewConversation:el,ensureSession:ep,switchMode:ea,acceptPlan:eo,residentLimitPrompt:ec}}(e,r,i?.agent_mode,F,{sessionId:s,onTaskCompleted:o,onSessionStarted:l,onTitleUpdated:(e,r)=>{let s=r??et?.id;s&&e&&(Y({sessionId:s,title:e}),c?.(s,e)),U(e=>e+1),K(null)}});m=et?.id??null,(0,sC.useGlobalEventStream)(s=>{"session:status"!==s.type||"running"!==s.status||!e||s.projectId!==e||(s.branch??null)!==(r??null)||s.sessionId&&s.sessionId!==m&&(e=>n?.(e))(s.sessionId)});let eb=et?.id??null;(0,$.useEffect)(()=>{f?.(eb)},[eb,f]);let ew=(0,$.useRef)(f);ew.current=f,(0,$.useEffect)(()=>()=>ew.current?.(null),[]),(0,$.useEffect)(()=>{(0,rv.getAgentProviders)().then(B).catch(()=>{})},[]),(0,$.useEffect)(()=>{et?.permissionMode&&N(et.permissionMode)},[et?.permissionMode]),(0,$.useEffect)(()=>{et?.agentType&&P(et.agentType)},[et?.agentType]),(0,$.useEffect)(()=>{S([]),C(1),z(null)},[e,r]);let eS=(0,$.useRef)({sessionId:null,count:0});(0,$.useEffect)(()=>{let e=et?.id??null,r=eS.current;e&&r.sessionId===e&&0===r.count&&er.length>0&&K(e),eS.current={sessionId:e,count:er.length}},[et?.id,er.length]),(0,$.useEffect)(()=>{q&&et?.id!==q&&K(null)},[et?.id,q]),(0,$.useEffect)(()=>{V&&et?.id!==V.sessionId&&Y(null)},[et?.id,V]),(0,$.useEffect)(()=>{if(!V)return;let e=setTimeout(()=>{Y(e=>e===V?null:e)},5e3);return()=>clearTimeout(e)},[V]),(0,$.useEffect)(()=>{if(!q)return;let e=setTimeout(()=>{K(e=>e===q?null:e)},3e4);return()=>clearTimeout(e)},[q]);let[ej,eC]=(0,$.useState)(!1);(0,$.useEffect)(()=>{eC(!1)},[et?.id]),(0,$.useEffect)(()=>{en&&eC(!0)},[en]);let ek=async e=>{N(e),et&&await ex(e)},eN=async e=>{let r=await ep(e);r&&_Z.toast.error("Failed to change model",{description:r})},eE=async e=>{await ev(e),N("edit"),u?.()},[eD,eR]=(0,$.useState)(!1),eA=async(e,r)=>{if(et&&!eD){eR(!0);try{let s=await (0,rv.branchAgentSession)(et.id,e,r);U(e=>e+1),n?.(s.session.id)}catch(r){let e=r instanceof Error?r.message:"Failed to branch conversation";_Z.toast.error("Branch failed",{description:e})}finally{eR(!1)}}},eT=I.find(e=>e.type===F)?.displayName??("codex"===F?"Codex":"Claude Code"),eM=I.filter(e=>e.available).filter(e=>e.type!==F),eF=(0,$.useMemo)(()=>{for(let e=er.length-1;e>=0;e--)if(er[e]?.type==="turn_end")return e;return -1},[er]),eP=function(e,r,s,n){let[i,a]=(0,$.useState)(null),o=(0,$.useRef)(0),[l,c]=(0,$.useState)({runUpdate:null,sessionId:null});(l.runUpdate!==n||l.sessionId!==s)&&(c({runUpdate:n,sessionId:s}),n&&n.reviewer_session_id===s&&a(NV.has(n.status)?n:null)),(0,$.useLayoutEffect)(()=>{n&&n.reviewer_session_id===s&&o.current++},[n,s]);let[d,u]=(0,$.useState)({projectId:null,sessionId:null});return(d.projectId!==e||d.sessionId!==s)&&(u({projectId:e,sessionId:s}),a(null)),(0,$.useEffect)(()=>{if(!e||!s)return;let n=!1,i=o.current;return rv.api.getActiveWorkflowRuns(e,r).then(e=>{n||o.current!==i||a(e.find(e=>e.reviewer_session_id===s)??null)}).catch(()=>{}),()=>{n=!0}},[e,r,s]),i}(e,r,eb,ec),[eI,eB]=(0,$.useState)(!1),eL=(0,$.useCallback)(async()=>{if(eP){eB(!0);try{await rv.api.workflowRunGate(eP.id,"finalize")}catch(e){_Z.toast.error(e instanceof Error?e.message:"生成终稿失败")}finally{eB(!1)}}},[eP]),ez=(0,$.useCallback)(e=>{var r,s;let n;b((r=y,s=e,n=0===r.length||r.endsWith("\n\n")?"":r.endsWith("\n")?"\n":"\n\n",r+n+(s.replace(/\r?\n/g,"\n").split("\n").map(e=>`> ${e}`).join("\n")+"\n\n"))),requestAnimationFrame(()=>{let e=J.current?.querySelector("textarea");if(!e)return;e.focus();let r=e.value.length;try{e.setSelectionRange(r,r)}catch{}})},[b,y]),eO=(0,$.useCallback)(async()=>{!ea&&et&&(await em(),z(null),h?.(),n?.(null),J.current?.querySelector("textarea")?.focus())},[ea,et,em,h,n]);(0,$.useImperativeHandle)(p,()=>({startNewConversation:eO,submitMessage:async e=>{if(u?.(),et)ed(e);else{let r=await eg(k,L);r&&(K(r.id),ed(e,r.id))}}}),[eO,et,eg,ed,k,L,u]);let e$=(0,$.useCallback)((e,r)=>{if(r.length<=2e3)return;e.preventDefault();let s=e.currentTarget,n=s.selectionStart??y.length,i=s.selectionEnd??y.length,a=new TextEncoder().encode(r).length,o=N9(j,a);b(y.slice(0,n)+o+y.slice(i)),S(e=>[...e,{id:j,content:r,size:a}]),C(j+1);let l=n+o.length;requestAnimationFrame(()=>{try{s.setSelectionRange(l,l)}catch{}})},[y,j,b]);async function eW(e,r,s,n){let i=new Set;for(let r of e.matchAll(N8))i.add(Number(r[1]));let a=r.filter(e=>i.has(e.id));if(0===a.length)return e;let o=e;for(let e of a){let r=await s(e.content,n),i=N9(e.id,e.size),a=`<vpaste path="${r.path}" size="${r.size}" />`;o=o.split(i).join(a)}return o}let eH=async e=>{let r=e.text,s=e.files.length>0,n=w.length>0,i=r.trim();if(i||s){M(!0);try{let a;b(""),Z.push(i),u?.();let o=et?.id,l=null;if(!et){if(!(l=await eg(k,L)))return void b(r);o=l.id,K(l.id)}let c=i;if(n)try{c=(await eW(r,w,eu,o)).trim()}catch(s){let e=s instanceof Error?s.message:"Failed to upload paste";_Z.toast.error("Paste upload failed",{description:e}),b(r);return}if(c.length>2e3)try{let e=await eu(c,o);c=`<vpaste path="${e.path}" size="${e.size}" />`}catch(s){let e=s instanceof Error?s.message:"Failed to upload paste";_Z.toast.error("Paste upload failed",{description:e}),b(r);return}if(S([]),C(1),s){let r=[];for(let s of(c&&r.push({type:"text",text:c}),e.files))if(s.mediaType&&s.url){let e=s.url.match(/^data:[^;]+;base64,(.+)$/);e&&r.push({type:"image",mediaType:s.mediaType,data:e[1]})}a=r}else a=c;if(E){let e="string"==typeof a?a:a.filter(e=>"text"===e.type).map(e=>e.text).join("\n");if(e.trim()){A(!0);try{let s=await (0,rv.translateText)(e);if(s.error){b(r),S(w),C(j),_Z.toast.error("Translation failed",{description:"Disable translation to send the original text."});return}a="string"==typeof a?s.translatedText:a.map(e=>"text"===e.type?{...e,text:s.translatedText}:e)}catch{b(r),S(w),C(j),_Z.toast.error("Translation failed",{description:"Disable translation to send the original text."});return}finally{A(!1)}}}l?(console.log(`[AgentConversation] handleSubmit: using freshly started session ${l.id}`),await ed(a,l.id)):(console.log(`[AgentConversation] handleSubmit: existing session ${et.id}, status=${es}`),await ed(a))}finally{M(!1)}}},{settings:eU}=(0,hG.useConversationSettings)();return e?(0,O.jsxs)("div",{className:"h-full flex flex-col min-h-0",style:{"--conv-font-size":`${eU.agentFontSize}px`},children:[(0,O.jsxs)("div",{className:"flex-shrink-0 flex items-center justify-between px-4 h-10 border-b border-border/60 bg-muted/20",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[I.length>1?(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsxs)("button",{disabled:ea||"running"===es&&er.length>0,className:(0,ey.cn)("inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-0.5 text-xs font-medium transition-colors hover:bg-muted",(ea||"running"===es&&er.length>0)&&"opacity-50 cursor-not-allowed"),children:[(0,O.jsx)(Nq,{type:F}),(0,O.jsx)(NL,{candidates:I.map(e=>e.displayName),children:eT}),(0,O.jsx)(ns,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,O.jsx)(a7,{align:"start",className:"min-w-[var(--radix-dropdown-menu-trigger-width)]",children:(0,O.jsx)(oe,{value:F,onValueChange:async e=>{if(!et){e!==F&&z(null),P(e);return}let r=await ef(e);r?_Z.toast.error("Failed to switch agent",{description:r}):P(e)},children:I.map(e=>(0,O.jsxs)(ot,{value:e.type,disabled:!e.available,className:"text-xs pl-2 [&>span:first-child]:hidden data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground",children:[(0,O.jsx)(Nq,{type:e.type}),e.displayName]},e.type))})})]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Nq,{type:F,className:"h-4 w-4"}),(0,O.jsx)("span",{className:"text-sm font-medium",children:eT})]}),(0,O.jsx)(NW,{models:I.find(e=>e.type===F)?.models??[],widthCandidates:I.flatMap(e=>e.models??[]),value:et?et.model??null:L,onChange:et?eN:z,locked:null!=et&&"running"===es&&er.length>0}),(0,O.jsx)(NU,{mode:k,onModeChange:ek}),ee.length>=1&&a&&(0,O.jsx)(oo,{targets:ee,activeTarget:i?.agent_mode??"local",onTargetChange:a}),et&&(g=et.id.startsWith("remote-"),x="text-muted-foreground",v=(0,O.jsx)(Nr,{className:"h-3 w-3"}),_="Disconnected",en?g&&"connected"!==el&&null!==el?"reconnecting"===el?(x="text-amber-500",v=(0,O.jsx)(Nt,{className:"h-3 w-3 animate-pulse"}),_="Reconnecting..."):"disconnected"===el&&(x="text-red-500",v=(0,O.jsx)(Nr,{className:"h-3 w-3"}),_="Remote disconnected"):(x="text-green-500",v=(0,O.jsx)(Nt,{className:"h-3 w-3"}),_="Connected"):ej||(x="text-amber-500",v=(0,O.jsx)(Nt,{className:"h-3 w-3 animate-pulse"}),_="Connecting..."),(0,O.jsx)("span",{className:`flex items-center ${x}`,title:_,children:v}))]}),(0,O.jsxs)("div",{className:"flex items-center gap-1",children:[e&&(0,O.jsx)(N3,{projectId:e,branch:r,sessionId:et?.id??null,currentAgentType:F,providers:I}),e&&(0,O.jsx)(NZ,{projectId:e,branch:r,currentSessionId:et?.id??null,refreshKey:H,pendingTitleSessionId:q,aiTitleOverride:V,onSwitch:e=>{d?.(e),n?.(e)},onDelete:(e,r)=>{if(e===et?.id){let e=r[0];n?.(e?e.id:null)}}}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:eO,disabled:ea||!et,className:"h-7 w-7",title:"New Conversation (⌘⇧O / Ctrl+Shift+O)",children:(0,O.jsx)(Ns,{className:"h-3.5 w-3.5"})}),(0,O.jsxs)(W.Button,{variant:"ghost",size:"sm",onClick:()=>eh(),disabled:"running"!==es,className:"h-7 text-xs",children:[(0,O.jsx)(lJ,{className:"h-3 w-3 mr-1"}),"Stop"]})]})]}),(0,O.jsxs)("div",{className:"flex-1 min-h-0 relative",children:[(0,O.jsxs)(c$,{className:"h-full",initial:"instant",children:[(0,O.jsxs)(cW,{className:"gap-1 p-4",scrollClassName:"edge-scrollbar",children:[et||0!==er.length?(0,O.jsx)(N6.Provider,{value:{sendMessage:ed,messages:er,acceptPlan:eE,permissionMode:et?.permissionMode??k,agentType:et?.agentType??F,sessionId:et?.id??null},children:(0,O.jsxs)("div",{className:"space-y-1 outline-none",ref:G,tabIndex:-1,onKeyDown:X,children:[er.map((e,r)=>e?.type==="turn_end"?(0,O.jsx)(Nl,{durationMs:e.durationMs,outcome:e.outcome,emphasis:r===eF?"normal":"subtle",agentType:F,currentAgentName:eT,alternateProviders:eM,onBranch:e=>eA(e,r),disabled:eD,showFinalize:r===eF&&eP?.status==="discussing",finalizeBusy:eI,onFinalize:eL},r):(0,O.jsx)("div",{"data-message-idx":r,..."user"===e.type?{"data-user-msg-idx":r}:{},className:"scroll-mt-2",children:(0,O.jsx)(ku,{message:e,messageIndex:r})},r)),ea&&(0,O.jsxs)("div",{className:"flex items-center gap-2 py-4 text-muted-foreground",children:[(0,O.jsx)(Ne,{className:"h-4 w-4"}),(0,O.jsx)("span",{className:"text-sm",children:"Connecting to agent..."})]})]})}):(0,O.jsx)("div",{className:"text-center py-16",children:ea||e&&!ei?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Ne,{className:"h-6 w-6 mx-auto mb-4"}),(0,O.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Connecting to agent..."}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Setting up the session for this worktree"})]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-4",children:(0,O.jsx)(sb,{className:"h-6 w-6 text-primary/60"})}),(0,O.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Start a conversation"}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Ask the agent to help you with coding tasks in this worktree"})]})}),eo&&(0,O.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-red-500/10 rounded-lg text-red-500 text-sm mt-4",children:[(0,O.jsx)(sy,{className:"h-4 w-4"}),eo]})]}),(0,O.jsx)(cH,{})]}),(0,O.jsx)(NX,{messages:er,contentRef:G}),(0,O.jsx)(N1,{containerRef:G,onQuote:ez})]}),(0,O.jsx)("div",{className:"flex-shrink-0 p-3",children:(0,O.jsxs)(kZ,{onSubmit:eH,accept:"image/*",className:"w-full",children:[(0,O.jsx)(N4,{}),(0,O.jsxs)("div",{className:"relative flex w-full flex-col",children:[E&&(0,O.jsx)("div",{className:"flex items-center pl-12 pr-2 pt-1.5 pb-0.5",children:(0,O.jsxs)("button",{type:"button",onClick:()=>D(!1),className:"inline-flex shrink-0 items-center gap-1.5 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 px-2.5 py-0.5 text-xs font-medium hover:bg-blue-500/20 transition-colors",children:[R?(0,O.jsx)(sj,{className:"size-3 animate-spin"}):(0,O.jsx)(Nn,{className:"size-3"}),"Translate",(0,O.jsx)(t7,{className:"size-3"})]})}),(0,O.jsxs)("div",{className:"flex w-full items-center",children:[(0,O.jsxs)(k2,{children:[(0,O.jsx)(k5,{className:"ml-1"}),(0,O.jsxs)(k3,{children:[(0,O.jsx)(kJ,{label:"Add images"}),(0,O.jsxs)(k4,{onSelect:()=>{D(!E)},children:[(0,O.jsx)(Nn,{className:"mr-2 size-4"}),E?"Disable translation":"Translate"]})]})]}),(0,O.jsx)("div",{ref:J,className:"contents",children:(0,O.jsx)(kQ,{value:y,onChange:e=>b(e.target.value),onPasteText:e$,onKeyDown:Z.handleKeyDown,placeholder:et?"Ask the agent to help with your code...":"Type your first message to start...",className:"pr-12",style:{fontSize:"var(--conv-font-size, 14px)"}})}),(0,O.jsx)("div",{className:"pointer-events-none absolute bottom-0 right-2 flex items-center text-base md:text-sm",style:{fontSize:"var(--conv-font-size, 14px)",height:"calc(1lh + 1.5rem)"},children:(0,O.jsx)(k6,{className:"pointer-events-auto",disabled:!y.trim()&&!ea||R||T,status:T||R?"submitted":ea?"streaming":"ready"})})]})]})]})}),(0,O.jsx)(lL,{open:null!==e_,onOpenChange:e=>{e||e_?.resolve(!1)},children:(0,O.jsxs)(l$,{children:[(0,O.jsxs)(lW,{children:[(0,O.jsx)(lU,{children:"Agent process limit reached"}),(0,O.jsxs)(lq,{children:["All ",e_?.maxResidentAgentProcesses," resident agent processes for this workspace branch are running. Starting a new conversation will stop the least recently active running session in this branch."]})]}),(0,O.jsxs)(lH,{children:[(0,O.jsx)(lV,{children:"Cancel"}),(0,O.jsx)(lK,{onClick:()=>e_?.resolve(!0),children:"Stop & start new"})]})]})})]}):(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(sb,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to start coding"})]})})});function Et(){return"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}async function Er(e,r){let s=await (0,rv.authFetch)(`${Et()}/api/projects/${e}/chat-sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:r})});if(!s.ok)throw Error("Failed to create chat session");return s.json()}async function Es(e,r){if(!(await (0,rv.authFetch)(`${Et()}/api/chat-sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r})})).ok)throw Error("Failed to send message")}async function En(e){if(!(await (0,rv.authFetch)(`${Et()}/api/chat-sessions/${e}/stop`,{method:"POST"})).ok)throw Error("Failed to stop generation")}let Ei=new Map;function Ea(e,r){return`chat:${e}:${r??""}`}function Eo({sessionId:e,approvalId:r,tool:s,input:n,resolved:i}){let[a,o]=(0,$.useState)(null),l=function(e){if(null!==e&&"object"==typeof e){if("string"==typeof e.message)return e.message;if("string"==typeof e.prompt)return e.prompt}return JSON.stringify(e)}(n),c=async s=>{if(!a&&!i){o(s?"approve":"deny");try{await rv.api.chatToolApproval(e,r,s)}finally{o(null)}}};return(0,O.jsx)("div",{className:"mx-4 my-1",children:(0,O.jsxs)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 space-y-2",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)(sb,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),(0,O.jsxs)("span",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:["Approval needed · ","spawnAgentSession"===s?"Start a new coding agent":"Send to the coding agent"]})]}),(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all text-foreground/80",style:{fontSize:"var(--conv-font-size, 12px)"},children:l}),i?(0,O.jsxs)(sa,{variant:"default",className:"approved"===i?"bg-green-600 hover:bg-green-700 text-white":"bg-red-600 hover:bg-red-700 text-white",children:["approved"===i?(0,O.jsx)(sJ,{className:"h-3 w-3 mr-1"}):(0,O.jsx)(s0,{className:"h-3 w-3 mr-1"}),"approved"===i?"Approved — sent.":"Denied — not sent."]}):(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsxs)(W.Button,{onClick:()=>c(!0),disabled:null!==a,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:["approve"===a?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,O.jsx)(sJ,{className:"h-3.5 w-3.5 mr-1"}),"Approve"]}),(0,O.jsxs)(W.Button,{onClick:()=>c(!1),disabled:null!==a,variant:"destructive",size:"sm",children:["deny"===a?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5 mr-1"}),"Deny"]})]})]})})}let El=new Set(["waiting_reviewer","waiting_feedback","discussing","sending_feedback"]);function Ec({projectId:e,branch:r,runUpdate:s,onRunsChange:n}){let[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)({}),[c,d]=(0,$.useState)({}),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(null),m=(0,$.useCallback)(async()=>{if(e)try{let s=await rv.api.getActiveWorkflowRuns(e,r);a(s),n?.(s)}catch{}},[e,r,n]);(0,$.useEffect)(()=>{m()},[m]),(0,$.useEffect)(()=>{s&&m()},[s,m]),(0,$.useEffect)(()=>{if(0===i.length)return;let e=setInterval(()=>void m(),5e3);return()=>clearInterval(e)},[i.length,m]);let g=async(e,r)=>{h(r),p(null);try{await e()}catch(e){p(e instanceof Error?e.message:String(e))}finally{h(null),await m()}},x=i.filter(e=>El.has(e.status));return 0===x.length?null:(0,O.jsx)("div",{className:"shrink-0 border-b bg-muted/30 px-4 py-2 space-y-2 max-h-[50vh] overflow-y-auto",children:x.map(e=>(0,O.jsxs)("div",{className:"text-sm space-y-2",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between",children:[(0,O.jsxs)("span",{className:"font-medium",children:["Review",e.review_focus?` — ${e.review_focus}`:"",(0,O.jsxs)("span",{className:"ml-2 text-muted-foreground",children:["waiting_reviewer"===e.status&&"reviewer 审查中…","waiting_feedback"===e.status&&"等你确认反馈","discussing"===e.status&&"讨论中","sending_feedback"===e.status&&"发送中…"]})]}),(0,O.jsxs)(W.Button,{variant:"ghost",size:"sm",disabled:u===e.id,onClick:()=>g(()=>rv.api.cancelWorkflowRun(e.id),e.id),children:[(0,O.jsx)(t7,{className:"h-3 w-3 mr-1"}),"结束"]})]}),e.error&&(0,O.jsx)("div",{className:"text-xs text-amber-600",children:e.error}),"waiting_reviewer"===e.status&&(0,O.jsxs)("div",{className:"flex items-center text-muted-foreground text-xs",children:[(0,O.jsx)(sj,{className:"h-3 w-3 mr-1 animate-spin"})," reviewer session 正在工作"]}),"discussing"===e.status&&(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:"与 reviewer 讨论后,生成终稿再发送"}),(0,O.jsx)(W.Button,{size:"icon-sm",variant:"outline","aria-label":"生成 review 终稿",disabled:u===e.id,onClick:()=>g(()=>rv.api.workflowRunGate(e.id,"finalize"),e.id),children:(0,O.jsx)(Cf,{className:"h-3 w-3"})})]}),"waiting_feedback"===e.status&&(0,O.jsxs)(O.Fragment,{children:[c[e.id]?(0,O.jsx)(rl,{className:"text-xs font-mono min-h-28 max-h-72",value:o[e.id]??e.feedback_snapshot??"",onChange:r=>l(s=>({...s,[e.id]:r.target.value}))}):(0,O.jsx)("div",{className:"text-xs border rounded-md bg-background px-3 py-2 max-h-72 overflow-y-auto",children:(0,O.jsx)(cD,{children:o[e.id]??e.feedback_snapshot??""})}),(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsx)(W.Button,{size:"sm",disabled:u===e.id,onClick:()=>g(()=>rv.api.workflowRunGate(e.id,"approve",o[e.id]??void 0),e.id),children:"发送反馈给原 session"}),(0,O.jsx)(W.Button,{variant:"outline",size:"sm",disabled:u===e.id,onClick:()=>d(r=>({...r,[e.id]:!r[e.id]})),children:c[e.id]?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(wf,{className:"h-3 w-3 mr-1"}),"预览"]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(rg,{className:"h-3 w-3 mr-1"}),"编辑"]})})]})]}),f&&(0,O.jsx)("div",{className:"text-xs text-destructive",children:f})]},e.id))})}let Ed=(0,ew.default)("radio",[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);function Eu({messages:e}){let{scrollToBottom:r}=cO(),s=(0,$.useRef)(e.length);return(0,$.useEffect)(()=>{let n=s.current;if(s.current=e.length,!(e.length<=n))for(let s=n;s<e.length;s++){let n=e[s];if("user"===n.type&&n.content.startsWith("[Executor Event:"))return void r({animation:"instant"})}},[e,r]),null}let Eh=(0,$.forwardRef)(function({projectId:e,branch:r},s){let{session:n,messages:i,status:a,isInitialized:o,isLoading:l,error:c,sendMessage:d,stopGeneration:u,restartSession:h,workflowRunUpdate:f}=function(e,r){let[s,n]=(0,$.useState)(null),[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)("stopped"),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(!1),[f,p]=(0,$.useState)(!1),[m,g]=(0,$.useState)(null),[x,v]=(0,$.useState)(null),_=(0,$.useRef)(null),y=(0,$.useRef)(()=>{}),b=(0,$.useRef)(null),w=(0,$.useRef)(0),S=(0,$.useRef)({entries:[],status:"stopped"}),j=(0,$.useRef)(!1),C=(0,$.useRef)(!0),k=(0,$.useRef)(!1),N=(0,$.useRef)(0),E=(0,$.useRef)(null),D=(0,$.useRef)(null),R=(0,$.useRef)(0),A=(0,$.useRef)(!1),T=(0,$.useCallback)((e,r=!1)=>{_.current?.readyState!==WebSocket.OPEN&&_.current?.readyState!==WebSocket.CONNECTING&&(0,rv.getFreshToken)(r?{skipCache:!0}:void 0).then(()=>y.current(e))},[]),M=(0,$.useCallback)(i=>{if(_.current?.readyState===WebSocket.OPEN||_.current?.readyState===WebSocket.CONNECTING)return;S.current={entries:[],status:"stopped"},j.current=!1,k.current=!0;let o=new WebSocket((0,rv.getWebSocketUrl)(`/api/chat-sessions/${i}/stream`));_.current=o;let c=N.current;o.onopen=()=>{d(!0),g(null),E.current=Date.now(),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{w.current=0,R.current=0},5e3)},o.onmessage=s=>{if(c===N.current)try{let c=JSON.parse(s.data);if("JsonPatch"in c){var n,i;let e=S.current.entries.filter(Boolean).length;n=S.current,i=c.JsonPatch,S.current=jY(n,e=>{for(let r of i){let{op:s,path:n,value:i}=r;if("/entries"===n&&"replace"===s&&i?.type==="ENTRY"&&i.content?.type==="system"&&i.content?.content==="__CLEAR_ALL__"){e.entries=[];continue}if(n.startsWith("/entries/")){let r=parseInt(n.replace("/entries/",""),10);if(isNaN(r)||i?.type!=="ENTRY")continue;switch(s){case"add":for(;e.entries.length<=r;)e.entries.push(null);e.entries[r]=i.content;break;case"replace":r<e.entries.length&&(e.entries[r]=i.content);break;case"remove":r<e.entries.length&&e.entries.splice(r,1)}}else"/status"===n&&i?.type==="STATUS"&&(e.status=i.content)}});let r=S.current.entries.filter(Boolean).length;k.current?r!==e&&console.log(`[ChatSession] WS patch added message (${e} → ${r}) but isReplaying=true, state NOT updated`):(r!==e&&console.log(`[ChatSession] New message via WS patch (${e} → ${r}), calling setMessages`),a([...S.current.entries.filter(Boolean)]),l(S.current.status));return}if("Ready"in c){k.current=!1;let e=S.current.entries.filter(Boolean).length;console.log(`[ChatSession] Ready received, isReplaying → false, ${e} messages`),a([...S.current.entries.filter(Boolean)]),l(S.current.status),h(!0);return}if("finished"in c){j.current=!0,o.close(1e3,"finished");return}if("openPreviewFrame"in c)return void(0,wu.openPreviewFrame)(c.openPreviewFrame.projectId,c.openPreviewFrame.url);if("WorkflowRunUpdated"in c)return void v(c.WorkflowRunUpdated);if("browserCommand"in c){let r=c.browserCommand;e&&(0,wu.sendCommandToIframe)(e,{type:"vibedeckx-command",...r}).then(e=>{e&&o.readyState===WebSocket.OPEN&&o.send(JSON.stringify({type:"browser_result",result:{id:r.id,success:e.success??!1,error:e.error,content:e.content,found:e.found,tag:e.tag,text:e.text}}))});return}if("error"in c){g(c.error),"Session not found"===c.error&&(e&&Ei.delete(Ea(e,r)),j.current=!0);return}}catch(e){console.error("[ChatSession] Failed to parse message:",e)}},o.onclose=i=>{let a,o;if(c!==N.current)return;d(!1),_.current=null,D.current&&(clearTimeout(D.current),D.current=null);let l=4e3===i.code,u=E.current?Date.now()-E.current:0;if(E.current=null,!l&&u>0&&u<5e3){if(R.current++,R.current>=3)return A.current?void g("Unable to connect to remote server. Please check the server configuration."):(e&&Ei.delete(Ea(e,r)),n(null),g(null),w.current=0,R.current=0,void(C.current=!0))}else u>=5e3&&(R.current=0);if(j.current||1e3===i.code)return;if(w.current>=10)return void g("Unable to connect to server.");let h=(o=(a=Math.min(3e4,1e3*Math.pow(2,w.current)))*Math.random()*.25,a+o);w.current++,b.current=setTimeout(()=>{s?.id&&!j.current&&T(s.id,!0)},h)},o.onerror=()=>{}},[s?.id,T]);(0,$.useEffect)(()=>{y.current=M},[M]);let F=(0,$.useCallback)(async()=>{if(!e)return null;let s=N.current;g(null),h(!1),A.current=!1;let i=Ea(e,r),o=Ei.get(i);if(o)return n(o),l(o.status),T(o.id),o;p(!0);try{let{session:o,messages:c}=await Er(e,r);if(N.current!==s)return null;return Ei.set(i,o),n(o),l(o.status),c&&c.length>0&&a(c),T(o.id),o}catch(e){if(N.current!==s)return null;return g(e instanceof Error?e.message:"Failed to start session"),A.current=!0,null}finally{N.current===s&&p(!1)}},[e,r,T]),P=(0,$.useCallback)(async e=>{let r=s?.id;if(r&&e.trim())try{await Es(r,e.trim())}catch(r){let e=r instanceof Error?r.message:"Failed to send message";g(e),_Z.toast.error("Failed to send message",{description:e})}},[s?.id]),I=(0,$.useCallback)(async()=>{if(s?.id)try{await En(s.id)}catch(e){console.error("[ChatSession] Failed to stop generation:",e)}},[s?.id]),B=(0,$.useCallback)(async()=>{if(s?.id)try{await rv.api.resetChatSession(s.id),a([]),l("stopped"),S.current={entries:[],status:"stopped"}}catch(e){console.error("[ChatSession] Failed to reset session:",e),_Z.toast.error("Failed to start new conversation")}},[s?.id]);return(0,$.useEffect)(()=>()=>{_.current&&(j.current=!0,_.current.close()),b.current&&clearTimeout(b.current),D.current&&clearTimeout(D.current)},[]),(0,$.useEffect)(()=>{_.current&&(_.current.close(1e3,"branch-switch"),_.current=null),b.current&&(clearTimeout(b.current),b.current=null),D.current&&(clearTimeout(D.current),D.current=null),N.current+=1,n(null),l("stopped"),d(!1),h(!1),g(null),p(!1),S.current={entries:[],status:"stopped"},j.current=!1,w.current=0,E.current=null,R.current=0,A.current=!1,C.current=!0},[e,r]),(0,$.useEffect)(()=>{!C.current||!e||s||f||A.current||(C.current=!1,F())},[e,s,f,F]),(0,$.useEffect)(()=>{!s?.id||c||j.current||T(s.id)},[s?.id,c,T]),(0,$.useEffect)(()=>{let e=()=>{if("visible"!==document.visibilityState||!s?.id||j.current)return;let e=_.current,r=S.current.entries.filter(Boolean).length;console.log(`[ChatSession] Tab visible: ws.readyState=${e?.readyState??"null"}, isReplaying=${k.current}, messages=${r}`),e&&e.readyState===WebSocket.OPEN&&e.close(4e3,"visibility-recovery")};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[s?.id]),{session:s,messages:i,status:o,isConnected:c,isInitialized:u,isLoading:f,error:m,workflowRunUpdate:x,sendMessage:P,stopGeneration:I,restartSession:B}}(e,r),{settings:p}=(0,hG.useConversationSettings)(),[m,g]=(0,$.useState)([]);(0,$.useImperativeHandle)(s,()=>({sendMessage:async e=>{let r=e.trim();r&&await d(r)}}),[d]);let[x,v]=(0,$.useState)(""),[_,y]=(0,$.useState)(!1);(0,$.useEffect)(()=>{n?.eventListeningEnabled!=null&&y(n.eventListeningEnabled)},[n?.eventListeningEnabled]);let b="running"===a,w=(0,$.useCallback)(async e=>{let r=e.text.trim();r&&(v(""),await d(r))},[d]);return e?(0,O.jsxs)("div",{className:"h-full flex flex-col min-h-0",style:{"--conv-font-size":`${p.chatFontSize}px`},children:[(0,O.jsxs)("div",{className:"flex-shrink-0 flex items-center justify-between px-4 h-10 border-b border-border/60 bg-muted/20",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)(sD,{className:"h-3.5 w-3.5 text-primary"}),(0,O.jsx)("span",{className:"text-xs font-medium text-foreground",children:"Main Chat"}),b&&(0,O.jsx)(sj,{className:"h-3 w-3 animate-spin text-primary/60"})]}),n&&(0,O.jsxs)("div",{className:"flex items-center gap-1",children:[(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:async()=>{let e=!_;try{await rv.api.setChatEventListening(n.id,e),y(e)}catch{_Z.toast.error("Failed to toggle event listening")}},className:`h-7 w-7 ${_?"text-amber-500":""}`,title:_?"Listening to executor events (click to disable)":"Listen to executor events (click to enable)",children:(0,O.jsx)(Ed,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:()=>h(),disabled:b,className:"h-7 w-7",title:"New Conversation",children:(0,O.jsx)(Ns,{className:"h-3.5 w-3.5"})})]})]}),(0,O.jsx)(Ec,{projectId:e,branch:r,runUpdate:f,onRunsChange:g}),(0,O.jsxs)(c$,{className:"flex-1 min-h-0",initial:"instant",children:[(0,O.jsx)(Eu,{messages:i}),(0,O.jsxs)(cW,{className:"gap-4 p-4",children:[l&&0===i.length&&(0,O.jsx)("div",{className:"flex items-center justify-center py-8",children:(0,O.jsx)(sj,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),!l&&o&&0===i.length&&(0,O.jsxs)("div",{className:"text-center py-16",children:[(0,O.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-4",children:(0,O.jsx)(sD,{className:"h-6 w-6 text-primary/60"})}),(0,O.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Start a conversation"}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Chat with the AI assistant about your project"})]}),i.map((s,i)=>{if("turn_end"===s.type)return(0,O.jsxs)("div",{className:"mx-4 my-3 flex items-center gap-2","aria-hidden":!0,children:[(0,O.jsx)("div",{className:"h-px flex-1 bg-border"}),(0,O.jsx)("div",{className:"h-1 w-1 shrink-0 rounded-full bg-border"}),(0,O.jsx)("div",{className:"h-px flex-1 bg-border"})]},i);if("user"===s.type&&s.content.startsWith("[System Invariant Violation]")){let e=s.content.replace(/^\[System Invariant Violation\]\n?/,"");return(0,O.jsxs)("div",{className:"mx-4 my-2 flex gap-2 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2",children:[(0,O.jsx)(s6,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("div",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:"System invariant correction"}),(0,O.jsx)("div",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:e})]})]},i)}if("user"===s.type){let n=s.event,a=n?.kind==="agent_task_completed"&&m.some(e=>e.source_session_id===n.sessionId||e.reviewer_session_id===n.sessionId);return(0,O.jsxs)("div",{children:[(0,O.jsx)(cN,{from:"user",children:(0,O.jsx)(cE,{style:{fontSize:"var(--conv-font-size, 14px)"},children:s.content})}),n?.kind==="agent_task_completed"&&(0,O.jsx)("div",{className:"mt-1 flex justify-end",children:(0,O.jsx)(W.Button,{variant:"outline",size:"sm",disabled:a,title:a?"该 session 已在一个进行中的 review 里":void 0,onClick:async()=>{if(e)try{await rv.api.createWorkflowRun({projectId:e,branch:r,sourceSessionId:n.sessionId,sourceTurnEndIndex:n.turnEndEntryIndex})}catch(e){alert(e instanceof Error?e.message:String(e))}},children:"Review"})})]},i)}return"assistant"===s.type?(0,O.jsx)(cN,{from:"assistant",children:(0,O.jsx)(cE,{style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,O.jsx)(cD,{children:s.content})})},i):"tool_use"===s.type?(0,O.jsxs)("div",{className:"flex items-center gap-2 px-4 py-2 text-xs text-muted-foreground",children:[(0,O.jsx)(sA,{className:"w-3.5 h-3.5 animate-pulse"}),(0,O.jsx)("span",{children:function(e){switch(e){case"getExecutorStatus":return"Checking executor status...";case"getAgentConversation":return"Checking agent conversation...";case"listTerminals":return"Listing terminals...";case"runInTerminal":return"Sending command to terminal...";case"spawnAgentSession":return"Starting a coding agent...";case"sendToAgentSession":return"Sending a message to the agent...";default:return`Running ${e}...`}}(s.tool)})]},i):"tool_result"===s.type?(0,O.jsx)("div",{className:"px-4 py-2",children:(0,O.jsxs)("details",{className:"text-xs text-muted-foreground",children:[(0,O.jsx)("summary",{className:"cursor-pointer hover:text-foreground",children:"Tool result"}),(0,O.jsx)("pre",{className:"mt-1 p-2 bg-muted/50 rounded overflow-x-auto whitespace-pre-wrap",style:{fontSize:"var(--conv-font-size, 12px)"},children:s.output})]})},i):"tool_approval_request"===s.type?n?(0,O.jsx)(Eo,{sessionId:n.id,approvalId:s.approvalId,tool:s.tool,input:s.input,resolved:s.resolved},i):null:"error"===s.type?(0,O.jsx)("div",{className:"mx-auto max-w-[90%] rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-destructive",style:{fontSize:"var(--conv-font-size, 14px)"},children:s.message},i):null}),c&&(0,O.jsx)("div",{className:"mx-auto max-w-[90%] rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:c})]}),(0,O.jsx)(cH,{})]}),(0,O.jsxs)("div",{className:"flex-shrink-0 p-3",children:[b&&(0,O.jsx)("div",{className:"flex justify-center mb-2",children:(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:u,className:"gap-1.5",children:[(0,O.jsx)(lJ,{className:"h-3 w-3"}),"Stop generating"]})}),(0,O.jsxs)(kZ,{onSubmit:w,className:"w-full",children:[(0,O.jsx)(kQ,{disabled:!o||b,placeholder:o?b?"Waiting for response...":"Type a message...":"Connecting...",className:"pr-12",style:{fontSize:"var(--conv-font-size, 14px)"},value:x,onChange:e=>v(e.currentTarget.value)}),(0,O.jsx)("div",{className:"pointer-events-none absolute bottom-0 right-2 flex items-center text-base md:text-sm",style:{fontSize:"var(--conv-font-size, 14px)",height:"calc(1lh + 1.5rem)"},children:(0,O.jsx)(k6,{className:"pointer-events-auto",disabled:!o||b||!x.trim()})})]})]})]}):(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(sD,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to start chatting"})]})})}),Ef=(0,ew.default)("archive-restore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);function Ep({task:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,onClick:o,worktrees:l,assignedBranches:c,onAssign:d}){let[u,h]=(0,$.useState)(!1),[f,p]=(0,$.useState)(e.title),m=(0,$.useRef)(null);(0,$.useEffect)(()=>{u&&(m.current?.focus(),m.current?.select())},[u]),(0,$.useEffect)(()=>{p(e.title)},[e.title]);let g=()=>{h(!1);let s=f.trim();s&&s!==e.title?r(e.id,{title:s}):p(e.title)},x="done"===e.status||"cancelled"===e.status;return(0,O.jsxs)(uD,{className:"group cursor-pointer",onClick:()=>o?.(e),children:[(0,O.jsx)(uA,{className:"w-10",onClick:e=>e.stopPropagation(),children:(0,O.jsx)(eb,{checked:"done"===e.status,onCheckedChange:s=>{r(e.id,{status:s?"done":"todo"})}})}),(0,O.jsx)(uA,{className:"font-medium",children:u?(0,O.jsx)("input",{ref:m,className:"w-full bg-transparent border-b border-primary outline-none text-sm py-0.5",value:f,onChange:e=>p(e.target.value),onBlur:g,onClick:e=>e.stopPropagation(),onKeyDown:r=>{"Enter"===r.key&&g(),"Escape"===r.key&&(p(e.title),h(!1))}}):(0,O.jsxs)("div",{children:[(0,O.jsx)("span",{className:`cursor-pointer hover:underline text-sm ${x?"line-through text-muted-foreground":""}`,onClick:e=>{e.stopPropagation(),h(!0)},children:e.title}),e.description&&(0,O.jsx)("p",{className:"text-xs text-muted-foreground truncate max-w-[400px] mt-0.5",children:e.description.length>80?e.description.slice(0,80)+"...":e.description})]})}),(0,O.jsx)(uA,{onClick:e=>e.stopPropagation(),children:(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)("button",{className:"focus:outline-none",children:(0,O.jsx)(sa,{variant:"outline",className:`cursor-pointer text-xs ${so[e.status].color}`,children:so[e.status].label})})}),(0,O.jsx)(a7,{align:"start",children:sc.map(s=>(0,O.jsxs)(a8,{onClick:()=>r(e.id,{status:s}),children:[(0,O.jsx)("span",{className:`inline-block w-2 h-2 rounded-full mr-2 ${so[s].color}`}),so[s].label]},s))})]})}),(0,O.jsx)(uA,{onClick:e=>e.stopPropagation(),children:(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)("button",{className:"focus:outline-none",children:(0,O.jsx)(sa,{variant:"outline",className:`cursor-pointer text-xs ${sl[e.priority].color}`,children:sl[e.priority].label})})}),(0,O.jsx)(a7,{align:"start",children:sd.map(s=>(0,O.jsxs)(a8,{onClick:()=>r(e.id,{priority:s}),children:[(0,O.jsx)("span",{className:`inline-block w-2 h-2 rounded-full mr-2 ${sl[s].color}`}),sl[s].label]},s))})]})}),(0,O.jsx)(uA,{onClick:e=>e.stopPropagation(),children:(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)("button",{className:"focus:outline-none",children:(0,O.jsxs)(sa,{variant:"outline",className:`cursor-pointer text-xs font-mono ${null!==e.assigned_branch?"bg-accent text-accent-foreground border-transparent":"text-muted-foreground"}`,children:[(0,O.jsx)(sU,{className:"h-3 w-3 mr-1"}),null!==e.assigned_branch?""===e.assigned_branch?"main":e.assigned_branch:"Unassigned"]})})}),(0,O.jsxs)(a7,{align:"start",children:[null!==e.assigned_branch&&(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(a8,{onClick:()=>d(e.id,null),children:"Unassign"}),(0,O.jsx)(os,{})]}),l.filter(r=>{let s=null===r.branch?"":r.branch;return!(e.assigned_branch===s||c.has(s))}).map(r=>{let s=null===r.branch?"":r.branch,n=r.branch??"main";return(0,O.jsxs)(a8,{onClick:()=>d(e.id,s),children:[(0,O.jsx)(sU,{className:"h-3 w-3 mr-2"}),n]},s)})]})]})}),(0,O.jsx)(uA,{className:"text-muted-foreground text-[10.5px] font-mono",children:new Date(e.created_at).toLocaleDateString()}),(0,O.jsx)(uA,{className:"w-10",onClick:e=>e.stopPropagation(),children:(0,O.jsxs)("div",{className:"flex items-center gap-0.5",children:[a?(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",title:"Unarchive",onClick:()=>i(e.id),children:(0,O.jsx)(Ef,{className:"h-3.5 w-3.5 text-muted-foreground"})}):(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",onClick:()=>n(e.id),children:(0,O.jsx)(sN,{className:"h-3.5 w-3.5 text-muted-foreground"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",title:"Delete",onClick:()=>s(e.id),children:(0,O.jsx)(rc,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})})]})}let Em={todo:0,in_progress:1,done:2,cancelled:3},Eg={urgent:0,high:1,medium:2,low:3};function Ex({tasks:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,worktrees:o,onAssign:l}){let[c,d]=(0,$.useState)(null),[u,h]=(0,$.useState)("asc"),[f,p]=(0,$.useState)(null),[m,g]=(0,$.useState)(!1),x=e=>{c===e?h(e=>"asc"===e?"desc":"asc"):(d(e),h("asc"))},v=(0,$.useMemo)(()=>{if(!c)return e;let r="asc"===u?1:-1;return[...e].sort((e,s)=>{switch(c){case"title":return r*e.title.localeCompare(s.title);case"status":return r*(Em[e.status]-Em[s.status]);case"priority":return r*(Eg[e.priority]-Eg[s.priority]);case"created_at":return r*(new Date(e.created_at).getTime()-new Date(s.created_at).getTime());default:return 0}})},[e,c,u]),_=e=>c!==e?null:"asc"===u?" ↑":" ↓",y=(0,$.useMemo)(()=>new Set(e.filter(e=>null!==e.assigned_branch).map(e=>e.assigned_branch)),[e]);return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)(uk,{children:[(0,O.jsx)(uN,{children:(0,O.jsxs)(uD,{children:[(0,O.jsx)(uR,{className:"w-10"}),(0,O.jsxs)(uR,{className:"cursor-pointer select-none",onClick:()=>x("title"),children:["Title",_("title")]}),(0,O.jsxs)(uR,{className:"cursor-pointer select-none w-32",onClick:()=>x("status"),children:["Status",_("status")]}),(0,O.jsxs)(uR,{className:"cursor-pointer select-none w-28",onClick:()=>x("priority"),children:["Priority",_("priority")]}),(0,O.jsx)(uR,{className:"w-32",children:"Assign"}),(0,O.jsxs)(uR,{className:"cursor-pointer select-none w-28",onClick:()=>x("created_at"),children:["Created",_("created_at")]}),(0,O.jsx)(uR,{className:"w-10"})]})}),(0,O.jsxs)(uE,{children:[v.map(e=>(0,O.jsx)(Ep,{task:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,onClick:e=>{p(e),g(!0)},worktrees:o,assignedBranches:y,onAssign:l},e.id)),0===e.length&&(0,O.jsx)(uD,{children:(0,O.jsx)("td",{colSpan:7,className:"text-center text-muted-foreground py-12 text-sm",children:(0,O.jsxs)("div",{className:"flex flex-col items-center gap-1",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-foreground/60",children:"No tasks yet"}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"Create one to get started."})]})})})]})]}),(0,O.jsx)(su,{task:f,open:m,onOpenChange:g})]})}function Ev({open:e,onOpenChange:r,onSubmit:s}){let[n,i]=(0,$.useState)(""),[a,o]=(0,$.useState)("todo"),[l,c]=(0,$.useState)("medium");return(0,O.jsx)(t8,{open:e,onOpenChange:r,children:(0,O.jsxs)(rr,{className:"sm:max-w-md max-h-[85vh] flex flex-col",children:[(0,O.jsx)(rs,{children:(0,O.jsx)(ri,{children:"Create Task"})}),(0,O.jsxs)("form",{onSubmit:e=>{e.preventDefault(),n.trim()&&(s({description:n.trim(),status:a,priority:l}),i(""),o("todo"),c("medium"),r(!1))},className:"space-y-4 overflow-y-auto min-h-0 px-0.5",children:[(0,O.jsx)("div",{className:"space-y-2",children:(0,O.jsx)(rl,{placeholder:"Describe the task...",value:n,onChange:e=>i(e.target.value),className:"max-h-[40vh] focus-visible:border-input focus-visible:ring-0",rows:3,autoFocus:!0})}),(0,O.jsxs)("div",{className:"flex gap-3",children:[(0,O.jsxs)("div",{className:"flex-1 space-y-1",children:[(0,O.jsx)("label",{className:"text-xs text-muted-foreground",children:"Status"}),(0,O.jsxs)(hw,{value:a,onValueChange:e=>o(e),children:[(0,O.jsx)(hj,{children:(0,O.jsx)(hS,{})}),(0,O.jsx)(hC,{children:sc.map(e=>(0,O.jsx)(hk,{value:e,children:so[e].label},e))})]})]}),(0,O.jsxs)("div",{className:"flex-1 space-y-1",children:[(0,O.jsx)("label",{className:"text-xs text-muted-foreground",children:"Priority"}),(0,O.jsxs)(hw,{value:l,onValueChange:e=>c(e),children:[(0,O.jsx)(hj,{children:(0,O.jsx)(hS,{})}),(0,O.jsx)(hC,{children:sd.map(e=>(0,O.jsx)(hk,{value:e,children:sl[e].label},e))})]})]})]}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),(0,O.jsx)(W.Button,{type:"submit",disabled:!n.trim(),children:"Create"})]})]})]})})}let E_=[{value:"all",label:"All"},{value:"todo",label:"Todo"},{value:"in_progress",label:"Doing"},{value:"done",label:"Done"},{value:"cancelled",label:"Cancelled"},{value:"archived",label:"Archived"}];function Ey({projectId:e,tasks:r,loading:s,worktrees:n,onCreateTask:i,onUpdateTask:a,onDeleteTask:o,onArchiveTask:l,onUnarchiveTask:c}){let[d,u]=(0,$.useState)(!1),[h,f]=(0,$.useState)("all"),p=(0,$.useMemo)(()=>r.filter(e=>null===e.archived_at),[r]),m=(0,$.useMemo)(()=>r.filter(e=>null!==e.archived_at),[r]),g=(0,$.useMemo)(()=>{let e={all:p.length,todo:0,in_progress:0,done:0,cancelled:0,archived:m.length};for(let r of p)e[r.status]++;return e},[p,m]),x=(0,$.useMemo)(()=>"archived"===h?m:"all"===h?p:p.filter(e=>e.status===h),[p,m,h]),v="archived"===h;return e?(0,O.jsxs)("div",{className:"flex flex-col h-full",children:[(0,O.jsx)(dh,{title:"Tasks",count:p.length,actions:(0,O.jsxs)(W.Button,{size:"sm",onClick:()=>u(!0),className:"shadow-sm",children:[(0,O.jsx)(eS,{className:"h-3.5 w-3.5 mr-1.5"}),"New Task"]})}),(0,O.jsx)(df,{children:E_.map(e=>(0,O.jsx)(dp,{active:h===e.value,count:g[e.value],onClick:()=>f(e.value),children:e.label},e.value))}),(0,O.jsx)("div",{className:"flex-1 overflow-auto px-5 edge-scrollbar",children:s?(0,O.jsx)("div",{className:"flex items-center justify-center py-12 text-muted-foreground text-sm",children:"Loading tasks..."}):(0,O.jsx)(Ex,{tasks:x,onUpdate:a,onDelete:o,onArchive:l,onUnarchive:c,archivedView:v,worktrees:n,onAssign:(e,r)=>{a(e,{assigned_branch:r})}})}),(0,O.jsx)(Ev,{open:d,onOpenChange:u,onSubmit:i})]}):(0,O.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(eS,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to view tasks."})]})})}var Eb=e.i(115796);function Ew({open:e,onOpenChange:r,onNavigateProject:s,onNavigateWorkspace:n,onNavigateSession:i}){let[a,o]=(0,$.useState)(""),[l,c]=(0,$.useState)(null),[d,u]=(0,$.useState)(!1),h=(0,$.useRef)(null),f=(0,$.useRef)(null),p=(0,$.useRef)("");(0,$.useLayoutEffect)(()=>{p.current=a},[a]),(0,sC.useGlobalEventStream)(e=>{if("session:title"!==e.type||"string"!=typeof e.sessionId)return;let r="string"==typeof e.title?e.title.trim():"";(0,Eb.updateCachedSessionTitle)(e.sessionId,r||null)});let[m,g]=(0,$.useState)(e);e!==m&&(g(e),e&&(o(""),c((0,Eb.getCachedEmptyResults)()),u(!1)));let x=(0,$.useCallback)(async e=>{h.current?.abort();let r=new AbortController;h.current=r;let s=""===e?(0,Eb.beginEmptyQuerySearch)():null;try{let n=await (0,rv.searchAll)(e,{signal:r.signal});r.signal.aborted||(null!==s&&(0,Eb.commitEmptyQueryResults)(s,n),c(n),u(!1))}catch{r.signal.aborted||u(!0)}},[]),v=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let r=e&&!v.current;if(v.current=e,e)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>void x(a),150*!r),()=>{f.current&&clearTimeout(f.current)}},[a,e,x]),(0,$.useEffect)(()=>{if(!e)return;let r=!1;return(0,rv.refreshSearchCache)().then(()=>{r||x(p.current)}).catch(()=>{}),()=>{r=!0,h.current?.abort()}},[e,x]);let _=l?a.trim()?{sessions:l.sessions,favorites:l.favorites}:(0,Eb.overlayRecents)(l):null,y=null===l,b=!!_&&0===l.projects.length&&0===l.workspaces.length&&0===_.sessions.length&&0===_.favorites.length,w=l?.cacheState==="cold",S=e=>(0,O.jsxs)(w9,{value:`session-${e.sessionId}`,onSelect:()=>i(e),children:[(0,O.jsx)(sD,{}),(0,O.jsx)("span",{className:"truncate",children:e.title??"Untitled session"}),e.favoritedAt&&(0,O.jsx)(NJ,{className:"h-3.5 w-3.5 shrink-0 fill-current text-amber-500"}),(0,O.jsxs)("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:[e.projectName," · ",e.branch??"main"," · ",function(e){if(!e)return"";let r=Date.now()-e;return r<6e4?"just now":r<36e5?`${Math.floor(r/6e4)}m ago`:r<864e5?`${Math.floor(r/36e5)}h ago`:`${Math.floor(r/864e5)}d ago`}(e.lastActiveAt)]})]},e.sessionId);return(0,O.jsxs)(w3,{open:e,onOpenChange:r,title:"Quick Switcher",description:"Search projects, workspaces, and sessions",shouldFilter:!1,className:"top-[max(1rem,calc(50%_-_175px))] translate-y-0",children:[(0,O.jsx)(w4,{placeholder:"Search projects, workspaces, sessions…",value:a,onValueChange:o}),(0,O.jsxs)(w6,{children:[d&&(0,O.jsxs)("div",{className:"flex items-center justify-between gap-2 px-4 py-3 text-sm text-destructive",children:[(0,O.jsx)("span",{children:"Search failed."}),(0,O.jsx)(W.Button,{variant:"link",size:"sm",className:"h-auto p-0 text-destructive",onClick:()=>void x(p.current),children:"Retry"})]}),!d&&y&&(0,O.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"}),"Searching…"]}),!d&&!y&&b&&w&&(0,O.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"}),"Syncing history…"]}),!d&&!y&&b&&!w&&(0,O.jsx)(w7,{children:"No results found."}),l&&l.projects.length>0&&(0,O.jsx)(w8,{heading:"Projects",children:l.projects.map(e=>(0,O.jsxs)(w9,{value:`project-${e.id}`,onSelect:()=>s(e.id),children:[(0,O.jsx)(c9,{name:e.name,size:"md"}),(0,O.jsx)("span",{children:e.name}),e.path&&(0,O.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:e.path})]},e.id))}),l&&l.workspaces.length>0&&(0,O.jsx)(w8,{heading:"Workspaces",children:l.workspaces.map(e=>(0,O.jsxs)(w9,{value:`ws-${e.projectId}-${e.targetId}-${e.branch??""}`,onSelect:()=>n(e),children:[(0,O.jsx)(sU,{}),(0,O.jsx)("span",{children:e.branch??"main"}),(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:e.projectName})]},`${e.projectId}-${e.targetId}-${e.branch??""}`))}),_&&_.sessions.length>0&&(0,O.jsx)(w8,{heading:a.trim()?"Sessions":"Recent",children:_.sessions.map(S)}),_&&_.favorites.length>0&&(0,O.jsx)(w8,{heading:"Favorites",children:_.favorites.map(S)})]})]})}let ES={session_result_ready:"/sounds/sound1.mp3",review_ready:"/sounds/sound2.mp3",session_failed:"/sounds/failure.mp3",workflow_failed:"/sounds/failure.mp3"};function Ej(e,r){let s=[...e.filter(e=>e.id!==r.id),r];return s.sort((e,r)=>r.created_at-e.created_at||(e.id<r.id?1:-1)),s}let EC=new Set(["session_result_ready","session_failed"]);function Ek(e){return EC.has(e.kind)&&e.session_id?`${e.kind}:${e.session_id}`:e.id}function EN(e){let r=new Map;for(let s of e){let e=null===s.read_at,n=r.get(Ek(s));n?(n.ids.push(s.id),n.count+=1,e&&(n.unreadCount+=1,n.unread=!0)):r.set(Ek(s),{latest:s,ids:[s.id],count:1,unreadCount:+!!e,unread:e})}return[...r.values()]}let EE=new Map,ED=new Set,ER=(0,ew.default)("bell",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]]),EA={session_result_ready:{label:"Session result is ready",dot:"bg-lime-400"},review_ready:{label:"Review feedback is ready",dot:"bg-emerald-500"},session_failed:{label:"Session failed",dot:"bg-destructive"},workflow_failed:{label:"Workflow needs attention",dot:"bg-destructive"}};function ET({notifications:e,unreadCount:r,projects:s,onNavigate:n,markRead:i,markAllRead:a,remove:o,clear:l}){let[c,d]=(0,$.useState)(!1);return(0,$.useEffect)(()=>{let e=e=>{"j"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),d(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,O.jsxs)(a4,{open:c,onOpenChange:d,children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsxs)(W.Button,{variant:"ghost",size:"icon-sm",className:"relative",title:"Notifications (⌘J)","aria-label":r>0?`${r} unread notifications`:"Notifications",children:[(0,O.jsx)(ER,{className:"h-4 w-4"}),r>0&&(0,O.jsx)("span",{className:"absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[9px] font-semibold leading-none text-primary-foreground",children:r>9?"9+":r})]})}),(0,O.jsxs)(a7,{align:"end",className:"w-80 p-0",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between px-3 py-2",children:[(0,O.jsx)("span",{className:"text-[12.5px] font-semibold text-foreground",children:"Notifications"}),e.length>0&&(0,O.jsxs)("div",{className:"flex items-center gap-1",children:[(0,O.jsxs)("button",{onClick:a,disabled:0===r,className:"flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40",title:"Mark all read",children:[(0,O.jsx)(de,{className:"h-3 w-3"}),"Mark all read"]}),(0,O.jsx)("button",{onClick:l,className:"rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",title:"Dismiss all (marks them read)",children:"Clear"})]})]}),(0,O.jsx)("div",{className:"max-h-[60vh] overflow-y-auto border-t border-border",children:0===e.length?(0,O.jsx)("div",{className:"px-3 py-8 text-center text-[12px] text-muted-foreground/70",children:"Nothing needs your attention."}):EN(e).map(e=>{let r,a=e.latest,l=EA[a.kind],c=e.unread;return(0,O.jsxs)(a8,{onSelect:()=>{for(let r of e.ids)i(r);n(a.project_id,a.branch,a.session_id)},className:(0,ey.cn)("group flex flex-col items-start gap-0.5 rounded-none px-3 py-2",c&&"bg-primary/[0.08]"),children:[(0,O.jsxs)("div",{className:"flex w-full items-center gap-2",children:[(0,O.jsx)("span",{className:(0,ey.cn)("h-[7px] w-[7px] shrink-0 rounded-full",l?.dot)}),(0,O.jsx)("span",{className:(0,ey.cn)("min-w-0 flex-1 truncate text-[12.5px]",c?"font-medium text-foreground":"text-foreground/70"),children:a.body??(r=a.project_id,s.find(e=>e.id===r)?.name??"Unknown project")}),e.unreadCount>1&&(0,O.jsxs)("span",{className:"shrink-0 rounded-full bg-muted px-1.5 text-[10px] font-medium leading-4 text-muted-foreground",title:`${e.unreadCount} new notifications, showing the latest`,children:["×",e.unreadCount]}),(0,O.jsx)("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:function(e){let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return"just now";let s=Math.round(r/60);if(s<60)return`${s}m ago`;let n=Math.round(s/60);if(n<24)return`${n}h ago`;let i=Math.round(n/24);return`${i}d ago`}(a.created_at)}),(0,O.jsx)("button",{onClick:r=>{for(let s of(r.stopPropagation(),e.ids))o(s)},className:"shrink-0 rounded p-0.5 text-muted-foreground/60 opacity-0 transition-all hover:bg-muted hover:text-foreground group-hover:opacity-100",title:"Dismiss (marks it read)",children:(0,O.jsx)(t7,{className:"h-3 w-3"})})]}),(0,O.jsxs)("div",{className:"flex w-full items-center gap-1.5 pl-[15px] text-[11px] text-muted-foreground",children:[(0,O.jsx)("span",{className:"font-mono truncate",children:a.branch??"main"}),(0,O.jsx)("span",{className:"text-muted-foreground/50",children:"·"}),(0,O.jsx)("span",{className:"shrink-0",children:l?.label??a.title})]})]},a.id)})})]})]})}let EM=(0,ew.default)("keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]),EF=(e,r)=>e?`⌘${r}`:`Ctrl+${r}`,EP=()=>()=>{};function EI(){let[e,r]=(0,$.useState)(!1),s=(0,$.useSyncExternalStore)(EP,_1,()=>!1);return(0,$.useEffect)(()=>{let e=e=>{let s,n="/"===e.key&&(e.metaKey||e.ctrlKey)&&!e.shiftKey&&!e.altKey,i="?"===e.key&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!((s=e.target)instanceof HTMLElement&&("INPUT"===s.tagName||"TEXTAREA"===s.tagName||"SELECT"===s.tagName||s.isContentEditable));(n||i)&&(e.preventDefault(),r(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(W.Button,{variant:"ghost",size:"icon-sm","aria-label":"Keyboard shortcuts",title:"Keyboard shortcuts (?)",onClick:()=>r(!0),children:(0,O.jsx)(EM,{className:"h-4 w-4"})}),(0,O.jsx)(t8,{open:e,onOpenChange:r,children:(0,O.jsxs)(rr,{className:"sm:max-w-xl",children:[(0,O.jsx)(rs,{children:(0,O.jsx)(ri,{children:"Keyboard shortcuts"})}),(0,O.jsx)("div",{className:"grid gap-x-8 gap-y-5 sm:grid-cols-2",children:[{title:"Global",entries:[{hints:[EF(s,"K")],description:"Quick switcher"},{hints:[EF(s,"J")],description:"Notifications"},{hints:[EF(s,"B")],description:"Toggle sidebar"},{hints:[s?`⌘⇧O`:"Ctrl+Shift+O"],description:"New agent conversation"},{hints:["?",EF(s,"/")],description:"This dialog"}]},{title:"Workspace tabs",entries:_Q.map(e=>({hints:[_5(s,e.code)],description:`Open ${e.label}`}))}].map(e=>(0,O.jsxs)("section",{children:[(0,O.jsx)("h3",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:e.title}),(0,O.jsx)("ul",{className:"space-y-1.5",children:e.entries.map(e=>(0,O.jsxs)("li",{className:"flex items-center justify-between gap-3 text-[13px]",children:[(0,O.jsx)("span",{className:"text-foreground/90",children:e.description}),(0,O.jsx)("span",{className:"flex shrink-0 items-center gap-1",children:e.hints.map(e=>(0,O.jsx)("kbd",{className:"rounded-md border border-border bg-muted px-1.5 py-0.5 font-mono text-[11px] leading-none text-foreground/80",children:e},e))})]},e.description))})]},e.title))})]})})]})}function EB(e){if(null===e)return"尚未连接";let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return`${r} 秒前`;let s=Math.floor(r/60);return s<60?`${s} 分钟前`:`${Math.floor(s/60)} 小时前`}function EL(){let{state:e,lastEventAt:r,reconnect:s}=(0,sC.useConnectionStatus)(),[,n]=(0,$.useState)(0);if((0,$.useEffect)(()=>{let e=setInterval(()=>n(e=>e+1),5e3);return()=>clearInterval(e)},[]),"stale"===e)return(0,O.jsxs)("button",{type:"button",onClick:s,title:`实时更新已断开 \xb7 上次更新 ${EB(r)} \xb7 点击重新连接`,className:"flex items-center gap-1.5 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-600 transition-colors hover:bg-amber-500/20",children:[(0,O.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500"}),"实时更新已断开"]});let i="live"===e;return(0,O.jsx)("span",{title:i?`实时更新正常 \xb7 上次更新 ${EB(r)}`:"正在连接实时更新…",className:"flex items-center px-1","aria-label":i?"实时更新正常":"正在连接实时更新",children:(0,O.jsx)("span",{className:i?"h-1.5 w-1.5 rounded-full bg-emerald-500":"h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground/40"})})}let Ez=new Set(["workspace","tasks","schedules","remote-servers","settings","project-info","project-chat"]),EO="tasks";function E$(e){return e.length>0&&e.trim()===e&&!/[\u0000-\u001f\u007f/\\]/.test(e)}function EW(){let e=window.location.pathname,r=new URLSearchParams(window.location.search),s=r.get("project");if(s){let e=r.get("tab");return{projectId:s,tab:e&&Ez.has(e)?e:EO,branch:r.get("branch"),threadId:null}}let n=e.split("/").filter(Boolean);if(1===n.length&&Ez.has(n[0])){let e=n[0];if("remote-servers"===e||"settings"===e)return{projectId:null,tab:e,branch:null,threadId:null}}let i=null,a=EO,o=null;if("p"===n[0]&&n[1]){i=n[1];let e=n[2];if("chat"===e&&4===n.length&&n[3])try{let e=decodeURIComponent(n[3]);E$(e)?(o=e,a="project-chat"):a="project-info"}catch{a="project-info",o=null}else"chat"===e?a="project-info":e&&Ez.has(e)&&"project-chat"!==e&&(a=e)}return{projectId:i,tab:a,branch:r.get("branch"),threadId:o}}function EH(e){let{projectId:r,tab:s,branch:n,threadId:i}=e;if("remote-servers"===s||"settings"===s)return`/${s}`;if(!r)return"/";if("project-chat"===s)return i&&E$(i)?`/p/${r}/chat/${encodeURIComponent(i)}`:`/p/${r}/project-info`;let a=`/p/${r}/${s??EO}`;return n&&(a+=`?branch=${encodeURIComponent(n)}`),a}function EU(e){return null===e?"":e}function Eq(e,r,s,n){return!!e&&e.projectId===r&&e.branch===s&&e.sessionId===n}function EK(){var e,r,s,n,i,a,o;let l,c,d,u,h,f,p,m,g,x,v,_,y,b,w,S,j,{projectId:C,tab:k,branch:N,threadId:E}=function(){let[e,r]=(0,$.useState)(EW);return(0,$.useEffect)(()=>{let e=()=>r(EW());return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]),e}(),{config:D}=(0,hL.useAppConfig)(),[R,A]=(0,$.useState)(()=>new URLSearchParams(window.location.search).get("session")),[T,M]=(0,$.useState)(null),F=(0,$.useCallback)(e=>{A(e);let r=new URL(window.location.href);e?r.searchParams.set("session",e):r.searchParams.delete("session"),window.history.replaceState(null,"",r.toString())},[]);(0,$.useEffect)(()=>{let e=()=>{A(new URLSearchParams(window.location.search).get("session"))};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]),(0,$.useEffect)(()=>{if(new URLSearchParams(window.location.search).has("project")){let e=EH({projectId:C,tab:k,branch:N,threadId:E});window.history.replaceState(null,"",e)}},[]);let[P,I]=(0,$.useState)(!1),[B,L]=(0,$.useState)(!1),[z,H]=(0,$.useState)(!1),[U,q]=(0,$.useState)(null),[K,V]=(0,$.useState)(N),[Y,G]=(0,$.useState)(k),[X,J]=(0,$.useState)(E),[Z,Q]=(0,$.useState)(0),[ee,et]=(0,$.useState)(0),[er,es]=(0,$.useState)(!1),en=(0,$.useRef)(null),[ei,ea]=(0,$.useState)(void 0),[eo,el]=(0,$.useTransition)(),{projects:ec,currentProject:ed,loading:eu,addProject:eh,createProject:ef,updateProject:ep,deleteProject:em,selectProject:eg,routeProjectPending:ex,routeProjectNotFound:ev}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(null),[a,o]=(0,$.useState)(!0),[l,c]=(0,$.useState)(e),d=(0,$.useRef)(n),u=(0,$.useRef)(e);d.current=n,u.current=e;let h=l!==e,f=a||h,p=!f&&!!e&&!r.some(r=>r.id===e),m=(0,$.useCallback)(async()=>{o(!0);try{let e=await rv.api.getProjects();if(s(e),e.length>0&&!d.current){let r=u.current?e.find(e=>e.id===u.current):e[0];i(r??null)}}finally{o(!1)}},[]);(0,$.useEffect)(()=>{m()},[m]),(0,$.useEffect)(()=>{h&&!a&&(c(e),i(e?r.find(r=>r.id===e)??null:r[0]??null))},[e,a,r,h]);let g=async(e,r)=>{let a=await rv.api.updateProject(e,r);return s(r=>r.map(r=>r.id===e?a:r)),n?.id===e&&i(a),a},x=async e=>{await rv.api.deleteProject(e),s(r=>r.filter(r=>r.id!==e)),n?.id===e&&i(r.find(r=>r.id!==e)??null)};return{projects:r,currentProject:h?null:n,routeProjectPending:f,routeProjectNotFound:p,loading:a,addProject:e=>{s(r=>[e,...r]),i(e)},createProject:async e=>{let r=await rv.api.createProject(e);return s(e=>[r,...e]),i(r),r},updateProject:g,deleteProject:x,selectProject:e=>{i(e)},refresh:m}}(C);ed?.id!==ei&&(void 0!==ei&&V(null),ea(ed?.id));let{worktrees:e_,loading:ey,refetch:eb}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),[o,l]=(0,$.useState)(null),c=(0,$.useRef)(0),d=(0,$.useRef)(null),u=(0,$.useRef)(null),h=(0,$.useRef)(r);h.current=r;let f=(0,$.useCallback)(async(r=!1)=>{if(r&&d.current)return;d.current?.abort();let s=new AbortController;d.current=s;let i=c.current;if(!e){d.current=null,n([]),l(null),a(!1);return}r||a(!0);try{let a=await rv.api.getProjectWorktrees(e,void 0,s.signal);if(i!==c.current)return;n(e=>{let s=r?function(e,r,s){if(void 0===s||r.some(e=>e.branch===s))return r;let n=e.findIndex(e=>e.branch===s);if(n<0)return r;let i=[...r];return i.splice(Math.min(n,i.length),0,e[n]),i}(e,a,h.current):a;return e.length===s.length&&e.every((e,r)=>e.branch===s[r].branch&&e.currentBranch===s[r].currentBranch)?e:s})}catch(e){if(i!==c.current||e instanceof Error&&"AbortError"===e.name)return;console.error("Failed to fetch worktrees:",e),r||n([{branch:null}])}finally{if(i!==c.current||d.current!==s)return;l(e),r||a(!1),d.current=null}},[e]);return(0,$.useEffect)(()=>(f(),()=>{d.current?.abort(),d.current=null,c.current+=1}),[f]),(0,$.useEffect)(()=>{let s=u.current;u.current={projectId:e,branch:r},s&&s.projectId===e&&s.branch!==r&&f(!0)},[e,r,f]),(0,sC.useGlobalEventStream)(r=>{if(!e||r.projectId!==e)return;let s="session:status"===r.type&&("stopped"===r.status||"error"===r.status);("session:taskCompleted"===r.type||"executor:stopped"===r.type||s)&&f(!0)}),(0,$.useEffect)(()=>{let e=null,r=()=>{null!==e&&(window.clearInterval(e),e=null)},s=()=>{r(),e=window.setInterval(()=>void f(!0),3e5)},n=()=>void f(!0),i=()=>{"visible"===document.visibilityState?(f(!0),s()):r()};return window.addEventListener("focus",n),document.addEventListener("visibilitychange",i),"visible"===document.visibilityState&&s(),()=>{r(),window.removeEventListener("focus",n),document.removeEventListener("visibilitychange",i)}},[f]),{worktrees:s,loading:i||o!==e,refetch:(0,$.useCallback)(()=>f(!1),[f])}}(ed?.id??null,K),{statuses:ew,defaultTarget:ej,repositoryLabel:eC,setTarget:ek,refetch:eN}=function(e,r){let[s,n]=(0,$.useState)(new Map),[i,a]=(0,$.useState)(null),[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(0),[u,h]=(0,$.useState)(e);e!==u&&(h(e),n(new Map),a(null),l(null));let f=(0,$.useCallback)(()=>d(e=>e+1),[]);return(0,$.useEffect)(()=>{let s=r.map(e=>e.branch).filter(e=>null!==e),i=!1;return(async()=>{if(!e||0===s.length){i||(n(new Map),a(null),l(null));return}if(c1(e).length>0&&(await function(e){let r=c2.get(e);if(r)return r;let s=(async()=>{let r=new Map;for(;;){let s=c1(e).filter(({key:e,target:s})=>r.get(e)!==s);if(0===s.length)break;for(let{key:n,branch:i,target:a}of s){r.set(n,a);let s=!1;try{s=await rv.api.setMergeTarget(e,i,a,{ifAbsent:!0})}catch{}if(s)try{localStorage.getItem(n)===a&&localStorage.removeItem(n)}catch{}}}})();return c2.set(e,s),s.finally(()=>{c2.get(e)===s&&c2.delete(e)}),s}(e),i))return;let r=s.map(e=>({branch:e})),o=await rv.api.getMergeStatus(e,r);i||o.ok&&(n(function(e){let r=new Map;for(let s of e){if("target-not-found"===s.error&&s.requestedTarget){r.set(s.branch,{branch:s.branch,error:s.error,requestedTarget:s.requestedTarget,targetSource:s.targetSource});continue}!s.error&&s.target&&s.status&&r.set(s.branch,{branch:s.branch,status:s.status,unmergedCount:s.unmergedCount??0,dirty:s.dirty??!1,target:s.target})}return r}(o.entries)),a(function(e){for(let r of e)if("default"===r.targetSource&&r.target)return r.target;return null}(o.entries)),l(o.repository.label))})(),()=>{i=!0}},[e,r,c,f]),{statuses:s,defaultTarget:i,repositoryLabel:o,setTarget:(0,$.useCallback)((r,s)=>{e&&rv.api.setMergeTarget(e,r,s).then(e=>{e&&f()})},[e,f]),refetch:f}}(ed?.id??null,e_),eE=function(e,r,s){let n=(0,$.useMemo)(()=>r?.map(e=>e.branch)??[],[r]),[i,a]=(0,$.useState)([]),o=(0,$.useCallback)(async()=>{if(!e||0===n.length)return void a([]);let r=await Promise.all(n.map(async r=>(await (0,rv.listBranchSessions)(e,r)).sessions.filter(e=>e.processAlive).map(s=>({id:s.id,projectId:e,branch:r,title:s.title?.trim()||"New Session",status:s.status,processAlive:!0,updated_at:s.updated_at}))));a(e=>{var s;let n;return s=r.flat(),n=new Map(e.map(e=>[e.id,e])),s.map(e=>{let r=n.get(e.id);return r&&"New Session"===e.title&&"New Session"!==r.title?{...e,title:r.title}:e})})},[n,e]);(0,$.useEffect)(()=>{let e=!1;return o().catch(r=>{e||console.warn("[ResidentSessions] refresh failed:",r)}),()=>{e=!0}},[o]);let{state:l}=(0,sC.useConnectionStatus)(),c=(0,$.useRef)(null),d=(0,$.useRef)(!1);return(0,$.useEffect)(()=>{var e;let r=c.current;c.current=l;let s=(e=d.current,"live"===l&&e&&"live"!==r);"live"===l&&(d.current=!0),s&&o().catch(e=>console.warn("[ResidentSessions] reconnect refresh failed:",e))},[l,o]),(0,$.useEffect)(()=>{s&&s.processAlive&&e&&s.projectId===e&&a(e=>(function(e,r){let s=e.findIndex(e=>e.id===r.id);if(-1===s)return[r,...e];let n=e[s],i="New Session"===r.title&&"New Session"!==n.title?n.title:r.title,a=[...e];return a[s]={...r,title:i,status:n.status},a})(e,s))},[e,s]),(0,sC.useGlobalEventStream)(r=>{if(e&&r.projectId===e){if("session:process"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null,s="boolean"==typeof r.alive?r.alive:null,n="string"==typeof r.branch?r.branch:null;if(!e||null===s)return;if(!s)return void a(r=>r.filter(r=>r.id!==e));o().catch(e=>console.warn("[ResidentSessions] process refresh failed:",e)),null!==n&&a(r=>r.map(r=>r.id===e?{...r,branch:n}:r))}if("session:status"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null,s="string"==typeof r.status?r.status:null;if(!e||!s)return;a(r=>r.map(r=>r.id===e?{...r,status:s}:r))}if("session:title"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null;if(!e)return;a(s=>{var n,i;return i=("string"==typeof(n=r.title)?n.trim():"")||"New Session",s.map(r=>r.id===e?{...r,title:i}:r)})}}}),(0,$.useMemo)(()=>{let e=new Map;for(let r of i){let s=r.branch??"",n=e.get(s)??[];n.push(r),e.set(s,n)}for(let r of e.values())r.sort((e,r)=>(r.updated_at??"").localeCompare(e.updated_at??""));return e},[i])}(ed?.id??null,e_,T),{tasks:eD,loading:eR,createTask:eA,updateTask:eT,deleteTask:eM,archive:eF,unarchive:eP,refetch:eI}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(!0),a=(0,$.useCallback)(async()=>{if(!e){s([]),i(!1);return}try{let r=await rv.api.getTasks(e,{includeArchived:!0});s(r)}catch(e){console.error("Failed to fetch tasks:",e)}finally{i(!1)}},[e]);(0,$.useEffect)(()=>{a()},[a]);let o=(0,$.useCallback)(async r=>{if(!e)return null;try{let n=await rv.api.createTask(e,r);return s(e=>[...e,n]),n}catch(e){return console.error("Failed to create task:",e),null}},[e]),l=(0,$.useCallback)(async(e,n)=>{s(r=>r.map(r=>r.id===e?{...r,...n,updated_at:new Date().toISOString()}:r));try{let r=await rv.api.updateTask(e,n);return s(s=>s.map(s=>s.id===e?r:s)),r}catch(e){return console.error("Failed to update task:",e),s(r),null}},[r]),c=(0,$.useCallback)(async e=>{s(r=>r.filter(r=>r.id!==e));try{await rv.api.deleteTask(e)}catch(e){console.error("Failed to delete task:",e),s(r)}},[r]),d=(0,$.useCallback)(async e=>{s(r=>r.map(r=>r.id===e?{...r,archived_at:Date.now()}:r));try{let r=await rv.api.archiveTask(e);s(s=>s.map(s=>s.id===e?r:s))}catch(e){console.error("Failed to archive task:",e),s(r)}},[r]),u=(0,$.useCallback)(async e=>{s(r=>r.map(r=>r.id===e?{...r,archived_at:null}:r));try{let r=await rv.api.unarchiveTask(e);s(s=>s.map(s=>s.id===e?r:s))}catch(e){console.error("Failed to unarchive task:",e),s(r)}},[r]),h=(0,$.useCallback)(async n=>{if(e){s(n.map(e=>r.find(r=>r.id===e)).filter(e=>void 0!==e));try{await rv.api.reorderTasks(e,n)}catch(e){console.error("Failed to reorder tasks:",e),s(r)}}},[e,r]);return{tasks:r,loading:n,createTask:o,updateTask:l,deleteTask:c,archive:d,unarchive:u,reorderTasks:h,refetch:a}}(ed?.id??null),{schedules:eB,loading:eL,createSchedule:ez,updateSchedule:eO,deleteSchedule:e$,runNow:eW}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(!1),a=(0,$.useRef)(e),o=(0,$.useRef)(0),l=(0,$.useCallback)(async(e,r,n)=>{if(!e){o.current===r&&(s([]),i(!1));return}n&&i(!0);try{let n=await rv.api.getSchedules(e);o.current===r&&s(n)}catch(e){console.error("Failed to fetch schedules:",e)}finally{n&&o.current===r&&i(!1)}},[]);(0,$.useEffect)(()=>{a.current=e,o.current+=1,l(e,o.current,!0)},[e,l]);let c=(0,$.useCallback)(async()=>{let e=a.current;e&&await l(e,o.current,!1)},[l]),d=(0,$.useRef)(c);(0,$.useEffect)(()=>{d.current=c},[c]),(0,sC.useGlobalEventStream)(e=>{!e.type?.startsWith("schedule:")||a.current&&e.projectId===a.current&&d.current()});let u=(0,$.useCallback)(async r=>{if(!e)throw Error("No project selected");let s=await rv.api.createSchedule(e,r);return await c(),s},[e,c]),h=(0,$.useCallback)(async(e,r)=>{let s=await rv.api.updateSchedule(e,r);return await c(),s},[c]),f=(0,$.useCallback)(async e=>{await rv.api.deleteSchedule(e),await c()},[c]),p=(0,$.useCallback)(async(e,r)=>{let s=r;if(!s){let e=crypto.randomUUID();s={requestId:e,runId:e}}let n=await rv.api.runScheduleNow(e,s);return await c(),n},[c]);return{schedules:r,loading:n,refetch:c,createSchedule:u,updateSchedule:h,deleteSchedule:f,runNow:p}}(ed?.id??null),[eH,eU]=(0,$.useState)(null),[eq,eK]=(0,$.useState)(null),[eV,eY]=(0,$.useState)(!1),[eG,eX]=(0,$.useState)(null),{activity:eJ,since:eZ,refetch:eQ,setOptimisticActivity:e0}=function(e){let[r,s]=(0,$.useState)(new Map),[n,i]=(0,$.useState)(new Map),a=(0,$.useRef)(new Map),o=(0,$.useRef)(new Map),l=(0,$.useRef)(null),c=(0,$.useCallback)(async()=>{if(!e){s(new Map),i(new Map),o.current=new Map,l.current=null,a.current=new Map;return}try{let r=await (0,rv.authFetch)(`${"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}/api/projects/${e}/branches/activity`);if(!r.ok)return;let n=await r.json(),c=l.current!==e,{nextActivity:d,nextSince:u}=function(e,r,s,n){let i=new Map,a=new Map,o=[];for(let l of e){let e=l.branch??"",c=s.get(e)??0;if(!n&&l.since<c){let s=r.get(e);if(void 0!==s){i.set(e,s),a.set(e,c);continue}}i.set(e,l.activity),a.set(e,l.since),n||r.get(e)===l.activity||o.push(l.branch)}return{nextActivity:i,nextSince:a,transitions:o}}(n.branches,o.current,a.current,c);s(d),i(u),o.current=d,l.current=e,a.current=u}catch{}},[e]);return(0,$.useEffect)(()=>{c()},[c]),(0,sC.useGlobalEventStream)(r=>{var n,l,c;let d,u;if("branch:activity"!==r.type||!e||r.projectId!==e)return;let h=(n=r,l=o.current,c=a.current,d=n.branch??"",u=c.get(d)??0,n.since<u?{kind:"stale"}:l.get(d)===n.activity?{kind:"redundant",key:d}:{kind:"transition",key:d});"stale"===h.kind||(a.current.set(h.key,r.since),i(new Map(a.current)),"redundant"!==h.kind&&s(e=>{let s=new Map(e);return s.set(h.key,r.activity),o.current=s,s}))}),{activity:r,since:n,refetch:c,setOptimisticActivity:(0,$.useCallback)((e,r)=>{s(s=>{let n=function(e,r,s){let n=r??"";if(e.get(n)===s)return e;let i=new Map(e);return i.set(n,s),i}(s,e,r);return o.current=n,n})},[])}}(ed?.id??null),{rules:e1,createRule:e2,updateRule:e5,deleteRule:e3}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),o=(0,$.useCallback)(async()=>{if(!e){n([]),a(!1);return}try{let s=await rv.api.getRules(e,r);n(s)}catch(e){console.error("Failed to fetch rules:",e)}finally{a(!1)}},[e,r]);(0,$.useEffect)(()=>{o()},[o]);let l=(0,$.useCallback)(async s=>{if(!e)return null;try{let i=await rv.api.createRule(e,{...s,branch:r});return n(e=>[...e,i]),i}catch(e){return console.error("Failed to create rule:",e),null}},[e,r]),c=(0,$.useCallback)(async(e,r)=>{n(s=>s.map(s=>s.id===e?{...s,...r,enabled:void 0!==r.enabled?+!!r.enabled:s.enabled,updated_at:new Date().toISOString()}:s));try{let s=await rv.api.updateRule(e,r);return n(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update rule:",e),n(s),null}},[s]),d=(0,$.useCallback)(async e=>{n(r=>r.filter(r=>r.id!==e));try{await rv.api.deleteRule(e)}catch(e){console.error("Failed to delete rule:",e),n(s)}},[s]);return{rules:s,loading:i,createRule:l,updateRule:c,deleteRule:d,refetch:o}}(ed?.id??null,K),{commands:e4,createCommand:e6,updateCommand:e7,deleteCommand:e8}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),o=(0,$.useCallback)(async()=>{if(!e){n([]),a(!1);return}try{let s=await rv.api.getCommands(e,r);n(s)}catch(e){console.error("Failed to fetch commands:",e)}finally{a(!1)}},[e,r]);(0,$.useEffect)(()=>{o()},[o]);let l=(0,$.useCallback)(async s=>{if(!e)return null;try{let i=await rv.api.createCommand(e,{...s,branch:r});return n(e=>[...e,i]),i}catch(e){return console.error("Failed to create command:",e),null}},[e,r]),c=(0,$.useCallback)(async(e,r)=>{n(s=>s.map(s=>s.id===e?{...s,...r,updated_at:new Date().toISOString()}:s));try{let s=await rv.api.updateCommand(e,r);return n(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update command:",e),n(s),null}},[s]),d=(0,$.useCallback)(async e=>{n(r=>r.filter(r=>r.id!==e));try{await rv.api.deleteCommand(e)}catch(e){console.error("Failed to delete command:",e),n(s)}},[s]);return{commands:s,loading:i,createCommand:l,updateCommand:c,deleteCommand:d,refetch:o}}(ed?.id??null,K),e9=(0,$.useRef)(null),te=(0,$.useSyncExternalStore)(j1,j2,j5),tt=ed?.id??null,tr=ed?.agent_mode??null,ts=(0,$.useCallback)(e=>!!tt&&te.has(j3(tt,e,tr)),[te,tt,tr]),tn=(0,$.useCallback)(e=>{if(tt)return te.get(j3(tt,e,tr))},[te,tt,tr]),ti=(0,$.useCallback)(e=>eZ.get(EU(e)),[eZ]),ta=(0,$.useMemo)(()=>(function(e,r,s,n){let i=new Map;if(!e)return i;for(let a of e){let e=EU(a.branch),o=r.get(e);if(!s?.(a.branch)){i.set(e,o??"idle");continue}if("main-running"===o)i.set(e,"main-running");else if("main-completed"===o){let r=n?.backendSince?.(a.branch)??0,s=n?.placeholderSince?.(a.branch)??0;i.set(e,s>r?"idle":"main-completed")}else i.set(e,"idle")}return i})(e_,eJ,ts,{backendSince:ti,placeholderSince:tn}),[e_,eJ,ts,ti,tn]);i=eN,a=ta,o=ed?.id??null,l=(0,$.useRef)(new Set),d=(c=function(e){let r=new Set;if(!e)return r;for(let[s,n]of e)c5.has(n)&&r.add(s);return r}(a)).size>0,u=JSON.stringify(Array.from(c).sort()),(0,$.useEffect)(()=>{let e=new Set(JSON.parse(u)),r=l.current;l.current=e,function(e,r){for(let s of e)if(!r.has(s))return!0;return!1}(r,e)&&i()},[u,i]),(0,$.useEffect)(()=>{let e=()=>i();return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[i]),(0,sC.useGlobalEventStream)(e=>{"executor:stopped"===e.type&&e.projectId===o&&i(),"merge-target:updated"===e.type&&null!==o&&e.projectId===o&&i()}),(0,$.useEffect)(()=>{let e=null,r=()=>{null!==e&&(clearInterval(e),e=null)},s=()=>{r(),e=setInterval(i,d?3e4:6e4)},n=()=>{"visible"===document.visibilityState?s():r()};return"visible"===document.visibilityState&&s(),document.addEventListener("visibilitychange",n),()=>{r(),document.removeEventListener("visibilitychange",n)}},[i,d]);let[to,tl]=(0,$.useState)(null),{notifications:tc,unreadCount:td,markRead:tu,markAllRead:th,remove:tf,clear:tp}=function(e){let[r,s]=(0,$.useState)([]),n=(0,$.useRef)(new Set),i=(0,$.useRef)(new Set);(0,$.useEffect)(()=>{for(let e of new Set(Object.values(ES)))EE.has(e)||ED.has(e)||(ED.add(e),(async()=>{try{let r=await fetch(e),s=await r.blob(),n=new Audio(URL.createObjectURL(s));n.preload="auto",n.load(),EE.set(e,n)}catch{}finally{ED.delete(e)}})())},[]);let a=(0,$.useRef)(e);(0,$.useEffect)(()=>{a.current=e},[e]);let o=(0,$.useCallback)(e=>{if(i.current.has(e))return;i.current.add(e);let r=Date.now();s(s=>s.map(s=>s.id===e&&null===s.read_at?{...s,read_at:r}:s)),(0,rv.markNotificationRead)(e).catch(()=>{s(s=>s.map(s=>s.id===e&&s.read_at===r?{...s,read_at:null}:s))}).finally(()=>{i.current.delete(e)})},[]);(0,$.useEffect)(()=>{let e=!1;return(0,rv.getNotifications)({limit:100}).then(r=>{if(!e){for(let e of r)n.current.add(e.id);s(e=>{let s=[];for(let e of r)s=Ej(s,e);for(let n of e)r.some(e=>e.id===n.id)||(s=Ej(s,n));return s});try{window.localStorage.removeItem("vibedeckx:completion-notifications")}catch{}}}).catch(e=>{console.warn("[notifications] hydration failed:",e)}),()=>{e=!0}},[]),(0,sC.useGlobalEventStream)(e=>{var r;let i;if("notification:created"!==e.type)return;let o=e.notification;if(!o?.id)return;let l=!n.current.has(o.id);n.current.add(o.id);let c=a.current,d=null!==o.session_id&&o.session_id===c;l&&(r=ES[o.kind],(i=EE.get(r))||((i=new Audio(r)).preload="auto",EE.set(r,i)),i.currentTime=0,i.play().catch(()=>{})),s(e=>Ej(e,d?{...o,read_at:o.read_at??Date.now()}:o)),d&&null===o.read_at&&(0,rv.markNotificationRead)(o.id).catch(()=>{})}),(0,$.useEffect)(()=>{if(e)for(let n of r){if(n.session_id!==e||null!==n.read_at||i.current.has(n.id))continue;let{id:r}=n;i.current.add(r),(0,rv.markNotificationRead)(r).then(()=>{s(e=>e.map(e=>e.id===r&&null===e.read_at?{...e,read_at:Date.now()}:e))}).catch(()=>{}).finally(()=>{i.current.delete(r)})}},[e,r]);let l=(0,$.useCallback)(e=>o(e),[o]),c=(0,$.useCallback)(()=>{let e=Date.now();s(r=>r.some(e=>null===e.read_at)?r.map(r=>null===r.read_at?{...r,read_at:e}:r):r),(0,rv.markAllNotificationsRead)().catch(()=>s(r))},[r]),d=(0,$.useCallback)(e=>{o(e),s(r=>r.filter(r=>r.id!==e))},[o]),u=(0,$.useCallback)(()=>{(0,rv.markAllNotificationsRead)().catch(e=>console.warn("[notifications] read-all failed:",e)),s(e=>e.length?[]:e)},[]),h=EN(r).reduce((e,r)=>e+ +!!r.unread,0);return{notifications:r,unreadCount:h,markRead:l,markAllRead:c,remove:d,clear:u}}("workspace"===Y?to:null),tm=(0,$.useMemo)(()=>tc.filter(e=>e.project_id===ed?.id&&null===e.read_at).length,[tc,ed?.id]),tg=(0,$.useCallback)(()=>{e0(K,"working")},[K,e0]),tx=(0,$.useRef)(null),tv=(0,$.useCallback)(()=>{eI()},[eI]),t_=(0,$.useCallback)((e,r,s)=>{tx.current={projectId:s??ed?.id,branch:e,sessionId:r},V(e),F(r),Q(e=>e+1),es(!1),(0,Eb.touchRecentSessionOpen)(r)},[ed?.id,F]),ty=(0,$.useCallback)(e=>{t_(e.branch,e.id),G("workspace")},[t_]),tb=(0,$.useCallback)(e=>{eQ();let r=ec.find(r=>r.id===e.projectId);(0,Eb.touchSessionStarted)({sessionId:e.id,projectId:e.projectId,projectName:r?.name??"",targetId:r?.agent_mode??"local",branch:e.branch}),!1!==e.processAlive&&M({id:e.id,projectId:e.projectId,branch:e.branch,title:"New Session",status:e.status,processAlive:!0,updated_at:new Date().toISOString()})},[eQ,ec]),tw=(0,$.useCallback)((e,r)=>{r.trim()&&(0,Eb.updateCachedSessionTitle)(e,r.trim()),ed?.id&&r.trim()&&M(s=>({id:e,projectId:ed.id,branch:s?.id===e?s.branch:K,title:r,status:s?.id===e?s.status:"running",processAlive:!0,updated_at:s?.id===e?s.updated_at:new Date().toISOString()}))},[ed?.id,K]),tS=(0,$.useCallback)(()=>{e0(K,"idle")},[K,e0]),tj=(0,$.useCallback)(()=>{eI()},[eI]);e=ed?.id??null,r={onTaskChanged:tj},h=(0,$.useRef)(r.onTaskChanged),(0,$.useEffect)(()=>{h.current=r.onTaskChanged}),(0,sC.useGlobalEventStream)(r=>{e&&r.projectId===e&&("task:created"===r.type||"task:updated"===r.type||"task:deleted"===r.type)&&h.current?.()});let tC=(0,$.useMemo)(()=>{let e=EU(K);return eD.find(r=>r.assigned_branch===e)??null},[eD,K]);(0,$.useCallback)(e=>{el(async()=>{await en.current?.submitMessage(e.description??e.title)})},[]),(0,$.useCallback)(e=>{eT(e,{assigned_branch:null})},[eT]);let tk=(0,$.useRef)(void 0);(0,$.useEffect)(()=>{if(ey||0===e_.length)return;let e=tk.current;if(void 0!==e){if(e_.some(r=>r.branch===e.branch)){tk.current=void 0,e.sessionId?t_(e.branch,e.sessionId):V(e.branch);return}tk.current=void 0,es(!1)}e_.some(e=>e.branch===K)||V(e_[0].branch)},[e_,ey,K,t_]),(0,$.useEffect)(()=>{er&&(null===K&&(ey||0!==e_.length)||es(!1))},[er,K,ey,e_]);let tN=(0,$.useCallback)((e,r,s=null)=>{if(G("workspace"),e===ed?.id)return void(s?t_(r,s):V(r));let n=ec.find(r=>r.id===e);n&&(s&&es(!0),tk.current={branch:r,sessionId:s},eg(n))},[ed?.id,ec,eg,t_]),[tE,tD]=(0,$.useState)(!1);(0,$.useEffect)(()=>{let e=e=>{if("k"===e.key&&(e.metaKey||e.ctrlKey)){e.preventDefault(),tD(e=>!e);return}"o"===e.key.toLowerCase()&&e.shiftKey&&(e.metaKey||e.ctrlKey)&&"workspace"===Y&&(e.preventDefault(),Q(e=>e+1),en.current?.startNewConversation())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[Y]);let tR=(0,$.useRef)(!1),tA=(0,$.useCallback)(async(e,r)=>{let s=ec.find(r=>r.id===e);if(!s)return null;let n="local"===r?"local":r;return(s.agent_mode??"local")!==n?ep(s.id,{agentMode:n}):s},[ec,ep]),tT=(s={projectId:ed?.id??null,resolveProjectForTarget:tA,getScheduleRun:rv.api.getScheduleRun,getSchedules:rv.api.getSchedules,runScheduleNow:eW,selectAgentSession:(e,r,s)=>{G("workspace"),t_(e,r,s)},openScheduleRun:(e,r)=>{eU(e),eK(r),G("schedules")},onRerunResult:e=>{e.replay&&e.status&&"starting"!==e.status&&"running"!==e.status?"completed"===e.status?_Z.toast.success("Schedule run already completed"):_Z.toast.error(`Schedule run already ${e.status}`):_Z.toast.success("Schedule run started")},onError:(e,r)=>{console.error(`Project activity ${e} failed:`,r),"session-navigation"===e?_Z.toast.error("Failed to open agent session"):"schedule-navigation"===e?_Z.toast.error("Failed to open schedule run"):_Z.toast.error(r instanceof Error?r.message:"Failed to start schedule run")}},(f=(0,$.useRef)(s)).current=s,(p=(0,$.useRef)({projectId:s.projectId,generation:0})).current.projectId!==s.projectId&&(p.current={projectId:s.projectId,generation:p.current.generation+1}),m=(0,$.useRef)(new Map),g=(0,$.useRef)(new Map),x=(0,$.useCallback)(e=>p.current.projectId===e.projectId&&p.current.generation===e.generation,[]),v=(0,$.useCallback)(async(e,r)=>{if(!e.projectId)return null;let s=f.current,n=await s.getScheduleRun(r);if(!x(e))return null;if(n.project_id!==e.projectId)throw Error("Schedule run does not belong to the active project");let i=await s.getSchedules(e.projectId);if(!x(e))return null;let a=i.find(e=>e.id===n.schedule_id);if(!a||a.project_id!==e.projectId)throw Error("Schedule does not belong to the active project");return{run:n,schedule:a}},[x]),_=(0,$.useCallback)(async(e,r,s)=>{let n={...p.current};if(n.projectId)try{let i=await f.current.resolveProjectForTarget(n.projectId,r);if(!x(n)||!i||i.id!==n.projectId)return;f.current.selectAgentSession(s,e,i.id)}catch(e){x(n)&&f.current.onError("session-navigation",e)}},[x]),y=(0,$.useCallback)(async(e,r)=>{let s={...p.current};try{let n=await v(s,e);if(!n||!x(s))return;if(r&&r!==n.schedule.id)throw Error("Schedule run target changed while opening");f.current.openScheduleRun(n.schedule.id,e)}catch(e){x(s)&&f.current.onError("schedule-navigation",e)}},[x,v]),b=(0,$.useCallback)(e=>{let r={...p.current};if(!r.projectId)return Promise.resolve();let s=`${r.projectId}:${e}`,n=g.current.get(s);if(n)return n;let i=(async()=>{try{let n,i=c3(r.projectId,e),a=m.current.get(i)??function(e,r,s){try{let n=window.sessionStorage.getItem(e);if(!n)return;let i=JSON.parse(n);return"string"==typeof i.requestId&&"string"==typeof i.runId&&i.projectId===r&&"string"==typeof i.scheduleId&&i.scheduleId.length>0&&i.sourceRunId===s?i:void 0}catch{return}}(i,r.projectId,e);if(a){let e=await f.current.getSchedules(r.projectId);if(!x(r))return;let s=a.scheduleId,o=e.find(e=>e.id===s);if(!o||o.project_id!==r.projectId)throw Error("Schedule does not belong to the active project");n=o,m.current.set(i,a)}else{let o=await v(r,e);if(!o||!x(r))return;n=o.schedule;let l=crypto.randomUUID();a={projectId:r.projectId,scheduleId:n.id,requestId:l,runId:l,sourceRunId:e},m.current.set(i,a);var s=a;try{window.sessionStorage.setItem(i,JSON.stringify(s))}catch{}}let o={requestId:a.requestId,runId:a.runId,sourceRunId:a.sourceRunId},l=await f.current.runScheduleNow(n.id,o);if(m.current.delete(i),c4(i),!x(r))return;f.current.onRerunResult(l)}catch(s){if(r.projectId&&("object"==typeof s&&null!==s&&"status"in s&&409===s.status||"object"==typeof s&&null!==s&&"durable"in s&&!0===s.durable)){let s=c3(r.projectId,e);m.current.delete(s),c4(s)}throw x(r)&&f.current.onError("schedule-rerun",s),s}})().finally(()=>{g.current.get(s)===i&&g.current.delete(s)});return g.current.set(s,i),i},[x,v]),{openAgentSession:_,openScheduleRun:y,runScheduleAgain:b}),tM=(n={projectId:ed?.id??null,schedules:eB,getTask:rv.api.getTask,resolveProjectForTarget:tA,openTask:eX,selectAgentSession:(e,r,s)=>{G("workspace"),t_(e,r,s)},selectWorkspace:e=>{F(null),V(e),G("workspace")},selectSchedule:e=>{eU(e),G("schedules")},openScheduleRun:tT.openScheduleRun,onError:e=>{_Z.toast.error(e instanceof Error?e.message:"Unable to open Context item")}},(w=(0,$.useRef)(n)).current=n,(S=(0,$.useRef)({projectId:n.projectId,generation:0})).current.projectId!==n.projectId&&(S.current={projectId:n.projectId,generation:S.current.generation+1}),j=(0,$.useCallback)(e=>e.projectId===S.current.projectId&&e.generation===S.current.generation,[]),{open:(0,$.useCallback)(async e=>{let r={...S.current},s=e.navigation;if(!r.projectId||e.deleted||!s){j(r)&&w.current.onError(Error("This Context item is no longer available"));return}try{if("task"===s.kind){let e=await w.current.getTask(r.projectId,s.taskId);if(!j(r))return;if(e.id!==s.taskId||e.project_id!==r.projectId)throw Error("Task is no longer available in this project");w.current.openTask(e);return}if("agent_session"===s.kind||"workspace"===s.kind){let e=await w.current.resolveProjectForTarget(r.projectId,s.target);if(!j(r))return;if(!e||e.id!==r.projectId)throw Error("Workspace target is no longer available");"agent_session"===s.kind?w.current.selectAgentSession(s.branch,s.sessionId,e.id):w.current.selectWorkspace(s.branch,e.id);return}if("schedule"===s.kind){let e=w.current.schedules.find(e=>e.id===s.scheduleId&&e.project_id===r.projectId);if(!e)throw Error("Schedule is no longer available in this project");w.current.selectSchedule(e.id);return}await w.current.openScheduleRun(s.runId,s.scheduleId)}catch(e){j(r)&&w.current.onError(e)}},[j])}),tF=(0,$.useCallback)(e=>{J(e),V(null),F(null),G("project-chat")},[F]),tP=(0,$.useCallback)(()=>{J(null),G("project-info")},[]);(0,$.useEffect)(()=>{G(k),J("project-chat"===k?E:null),"project-chat"===k&&(V(null),F(null))},[k,E,F]);let tI=(0,$.useCallback)(e=>{eK(r=>r===e?null:r)},[]),tB=(0,$.useCallback)(e=>{if(tR.current)return;let r=ec.find(r=>r.id===e);r&&(tD(!1),eg(r),G("project-info"))},[ec,eg]),tL=(0,$.useCallback)(async e=>{if(!tR.current){tR.current=!0,tD(!1);try{let r=await tA(e.projectId,e.targetId);if(!r)return;G("workspace"),r.id===ed?.id?(V(e.branch),F(null)):(tk.current={branch:e.branch,sessionId:null},eg(r))}catch(e){console.error("Quick switcher navigation failed:",e),_Z.toast.error("Failed to open workspace")}finally{tR.current=!1}}},[ed?.id,tA,eg,F]),tz=(0,$.useCallback)(async e=>{if(!tR.current){tR.current=!0,tD(!1);try{let r=await tA(e.projectId,e.targetId);if(!r)return;(0,Eb.touchRecentSessionOpen)(e.sessionId,e),G("workspace"),r.id===ed?.id?t_(e.branch,e.sessionId,e.projectId):(es(!0),tk.current={branch:e.branch,sessionId:e.sessionId},eg(r))}catch(e){console.error("Quick switcher navigation failed:",e),_Z.toast.error("Failed to open session")}finally{tR.current=!1}}},[ed?.id,tA,eg,t_]),tO=(0,$.useRef)(K),t$=(0,$.useRef)(ed?.id),tW=(0,$.useRef)(!1);(0,$.useEffect)(()=>{if(eu||ex||ev)return;let e=!tW.current,r=!e&&tO.current!==K,s=!e&&t$.current!==ed?.id;tO.current=K,t$.current=ed?.id,tW.current=!0;let n=tx.current;if(Eq(n,ed?.id,K,R)&&(tx.current=null),function({branchChanged:e,projectChanged:r,urlSessionId:s,pendingSessionSelection:n,currentProjectId:i,selectedBranch:a}){return(!!e||!!r)&&!!s&&!Eq(n,i,a,s)}({branchChanged:r,projectChanged:s,urlSessionId:R,pendingSessionSelection:n,currentProjectId:ed?.id,selectedBranch:K})){tx.current=null,F(null);return}let i=EH({projectId:ed?.id,tab:Y,branch:K,threadId:X});if(R){let e=new URL(i,window.location.origin);e.searchParams.set("session",R),window.history.replaceState(null,"",e.pathname+e.search)}else window.history.replaceState(null,"",i)},[ed?.id,Y,K,X,eu,ex,ev,R,F]);let tH=(0,$.useCallback)(e=>{eb(),V(e)},[eb]);(0,$.useCallback)((e,r)=>{ed&&r!==ed.agent_mode?ep(ed.id,{agentMode:r}).then(()=>{en.current?.submitMessage(e)}):en.current?.submitMessage(e)},[ed,ep]);let tU=(0,$.useRef)({content:"",at:0}),tq=(0,$.useCallback)(e=>{let r=Date.now(),s=tU.current;s.content===e&&r-s.at<600||(tU.current={content:e,at:r},e9.current?.sendMessage(e))},[]),tK=(0,$.useCallback)(()=>{let e=`Please perform the following git operations for this worktree:
28
+ `,r)}paste(e){this._core.paste(e)}refresh(e,r){this._verifyIntegers(e,r),this._core.refresh(e,r)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return ph},set promptLabel(t){ph=t},get tooMuchOutput(){return pf},set tooMuchOutput(t){pf=t}}}_verifyIntegers(...e){for(_H of e)if(_H===1/0||isNaN(_H)||_H%1!=0)throw Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(_H of e)if(_H&&(_H===1/0||isNaN(_H)||_H%1!=0||_H<0))throw Error("This API only accepts positive integers")}},_q=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let r=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(r._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(0===e.css.cell.width||0===e.css.cell.height)return;let r=0===this._terminal.options.scrollback?0:this._terminal.options.overviewRuler?.width||14,s=window.getComputedStyle(this._terminal.element.parentElement),n=parseInt(s.getPropertyValue("height")),i=Math.max(0,parseInt(s.getPropertyValue("width"))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue("padding-top")),bottom:parseInt(a.getPropertyValue("padding-bottom")),right:parseInt(a.getPropertyValue("padding-right")),left:parseInt(a.getPropertyValue("padding-left"))},l=o.top+o.bottom;return{cols:Math.max(2,Math.floor((i-(o.right+o.left)-r)/e.css.cell.width)),rows:Math.max(1,Math.floor((n-l)/e.css.cell.height))}}},_K=class{constructor(e,r,s,n={}){this._terminal=e,this._regex=r,this._handler=s,this._options=n}provideLinks(e,r){let s=_V.computeLink(e,this._regex,this._terminal,this._handler);r(this._addCallbacks(s))}_addCallbacks(e){return e.map(e=>(e.leave=this._options.leave,e.hover=(r,s)=>{if(this._options.hover){let{range:n}=e;this._options.hover(r,s,n)}},e))}},_V=class e{static computeLink(r,s,n,i){let a=RegExp(s.source,(s.flags||"")+"g"),[o,l]=e._getWindowedLineStrings(r-1,n),c=o.join(""),d,u=[];for(;d=a.exec(c);){let r=d[0];if(!function(e){try{let r=new URL(e),s=r.password&&r.username?`${r.protocol}//${r.username}:${r.password}@${r.host}`:r.username?`${r.protocol}//${r.username}@${r.host}`:`${r.protocol}//${r.host}`;return e.toLocaleLowerCase().startsWith(s.toLocaleLowerCase())}catch{return!1}}(r))continue;let[s,a]=e._mapStrIdx(n,l,0,d.index),[o,c]=e._mapStrIdx(n,s,a,r.length);if(-1===s||-1===a||-1===o||-1===c)continue;let h={start:{x:a+1,y:s+1},end:{x:c,y:o+1}};u.push({range:h,text:r,activate:i})}return u}static _getWindowedLineStrings(e,r){let s,n=e,i=e,a=0,o="",l=[];if(s=r.buffer.active.getLine(e)){let e=s.translateToString(!0);if(s.isWrapped&&" "!==e[0]){for(a=0;(s=r.buffer.active.getLine(--n))&&a<2048&&(a+=(o=s.translateToString(!0)).length,l.push(o),!(!s.isWrapped||-1!==o.indexOf(" "))););l.reverse()}for(l.push(e),a=0;(s=r.buffer.active.getLine(++i))&&s.isWrapped&&a<2048&&(a+=(o=s.translateToString(!0)).length,l.push(o),-1===o.indexOf(" ")););}return[l,n]}static _mapStrIdx(e,r,s,n){let i=e.buffer.active,a=i.getNullCell(),o=s;for(;n;){let e=i.getLine(r);if(!e)return[-1,-1];for(let s=o;s<e.length;++s){e.getCell(s,a);let o=a.getChars();if(a.getWidth()&&(n-=o.length||1,s===e.length-1&&""===o)){let e=i.getLine(r+1);e&&e.isWrapped&&(e.getCell(0,a),2===a.getWidth()&&(n+=1))}if(n<0)return[r,s]}r++,o=0}return[r,o]}},_Y=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function _G(e,r){let s=window.open();if(s){try{s.opener=null}catch{}s.location.href=r}else console.warn("Opening link blocked as opener could not be cleared")}var _X=class{constructor(e=_G,r={}){this._handler=e,this._options=r}activate(e){this._terminal=e;let r=this._options,s=r.urlRegex||_Y;this._linkProvider=this._terminal.registerLinkProvider(new _K(this._terminal,s,this._handler,r))}dispose(){this._linkProvider?.dispose()}};let _J=(0,ew.default)("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);var _Z=e.i(754219);let _Q=[{id:"agent",label:"Agent",code:"KeyA"},{id:"executors",label:"Executors",code:"KeyE"},{id:"diff",label:"Diff",code:"KeyD"},{id:"terminal",label:"Terminal",code:"KeyT"},{id:"preview",label:"Browser",code:"KeyB"},{id:"files",label:"Files",code:"KeyF"}],_0=Object.fromEntries(_Q.map(e=>[e.code,e.id])),_1=()=>"undefined"!=typeof navigator&&/Mac|iPhone|iPad/.test(navigator.platform);function _2(e){return(_1()?e.ctrlKey&&e.shiftKey&&!e.altKey&&!e.metaKey:e.ctrlKey&&e.altKey&&!e.shiftKey&&!e.metaKey)?_0[e.code]??null:null}let _5=(e,r)=>`${e?"⌃⇧":"Ctrl+Alt+"}${r.slice(3)}`,_3=/\x1B(?:\][^\x07]*(?:\x07|\x1B\\)|[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;function _4({logs:e,isPty:r,className:s,onInput:n,onResize:i,muteInput:a,processId:o,executorId:l,target:c,status:d,exitCode:u}){let h=(0,$.useRef)(null),f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=(0,$.useRef)(0),g=(0,$.useRef)(0),x=(0,$.useRef)(a);x.current!==a&&console.log(`[ExecutorOutput] muteInput changed: ${x.current} → ${a}`),x.current=a;let{settings:v}=(0,fT.useTerminalSettings)(),_=(0,$.useRef)(v),[y,b]=(0,$.useState)(!1),w=(0,$.useRef)(0),S=(0,$.useRef)(e);S.current=e;let j=async()=>{if(!y){w.current=S.current.length,b(!0);return}let e=S.current,r=Math.min(w.current,e.length),s=e.slice(r).map(e=>"stdout"===e.type||"stderr"===e.type||"pty"===e.type?e.data:"").join("");b(!1);let n=s.replace(_3,"");if(!n)return void _Z.toast.info("Capture stopped — no output to copy");try{await navigator.clipboard.writeText(n),_Z.toast.success("Copied captured output to clipboard")}catch{_Z.toast.error("Failed to copy to clipboard")}};(0,$.useEffect)(()=>{if(!h.current||f.current)return;let e=_.current,s=new _U({cursorBlink:r,cursorStyle:r?"block":"underline",disableStdin:!r,convertEol:!0,fontSize:e.fontSize,fontFamily:e.fontFamily,scrollback:e.scrollback,theme:{background:"#09090b",foreground:"#fafafa",cursor:r?"#fafafa":"#09090b",cursorAccent:"#09090b",selectionBackground:"#3f3f46",black:"#09090b",red:"#f87171",green:"#4ade80",yellow:"#facc15",blue:"#60a5fa",magenta:"#c084fc",cyan:"#22d3ee",white:"#fafafa",brightBlack:"#71717a",brightRed:"#fca5a5",brightGreen:"#86efac",brightYellow:"#fde047",brightBlue:"#93c5fd",brightMagenta:"#d8b4fe",brightCyan:"#67e8f9",brightWhite:"#ffffff"},allowProposedApi:!0}),a=new _q,o=new _X;return s.loadAddon(a),s.loadAddon(o),s.attachCustomKeyEventHandler(e=>null===_2(e)),s.open(h.current),setTimeout(()=>{try{let e=h.current;if(!e||0===e.clientWidth||0===e.clientHeight)return;a.fit(),r&&i?.(s.cols,s.rows)}catch{}},0),f.current=s,p.current=a,r&&n&&s.onData(e=>{x.current||0!==g.current||n(e)}),r&&i&&s.onResize(({cols:e,rows:r})=>{i(e,r)}),()=>{s.dispose(),f.current=null,p.current=null,m.current=0,g.current=0}},[r,n,i]),(0,$.useEffect)(()=>{if(!f.current)return;e.length<m.current&&(f.current.reset(),m.current=0);let r="",s="";for(let n=m.current;n<e.length;n++){let i=e[n];("pty"===i.type||"stdout"===i.type||"stderr"===i.type)&&(i.historical?r+=i.data:s+=i.data)}if(m.current=e.length,r){g.current++;try{f.current.write(r,()=>{g.current=Math.max(0,g.current-1)})}catch(e){g.current=Math.max(0,g.current-1),console.error("[ExecutorOutput] terminal write failed",e)}}if(s)try{f.current.write(s)}catch(e){console.error("[ExecutorOutput] terminal write failed",e)}},[e]),(0,$.useEffect)(()=>{let e=f.current;if(e){e.options.fontSize=v.fontSize,e.options.fontFamily=v.fontFamily,e.options.scrollback=v.scrollback;try{p.current?.fit()}catch{}}},[v.fontSize,v.fontFamily,v.scrollback]),(0,$.useEffect)(()=>{if(!h.current||!p.current)return;let e=new ResizeObserver(()=>{try{let e=h.current;if(!e||0===e.clientWidth||0===e.clientHeight)return;p.current?.fit()}catch{}});return e.observe(h.current),()=>{e.disconnect()}},[]);let C="closed"===d&&null!==u?`closed \xb7 exit ${u}`:d??null;return(0,O.jsxs)("div",{className:(0,ey.cn)("relative h-[300px] rounded-md border bg-zinc-950 overflow-hidden",s),children:[(0,O.jsx)("div",{ref:h,className:"h-full w-full"}),(0,O.jsxs)("div",{className:"absolute top-2 right-3 z-10 flex items-center gap-1.5",children:[(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)("button",{type:"button",title:"Process info","aria-label":"Show process info",className:(0,ey.cn)("flex h-6 w-6 items-center justify-center rounded","bg-zinc-900/70 backdrop-blur-sm border border-zinc-700/60","text-zinc-400 hover:text-zinc-100 hover:border-zinc-500 transition-colors"),children:(0,O.jsx)(_J,{className:"h-3 w-3"})})}),(0,O.jsxs)(a7,{align:"end",className:"w-72",children:[(0,O.jsx)(or,{className:"text-xs text-muted-foreground",children:"Process info"}),[{label:"Process",value:o??null},{label:"Executor",value:l??null},{label:"Target",value:c??null},{label:"Status",value:C}].map(e=>(0,O.jsxs)(a8,{disabled:!e.value,onSelect:r=>{var s,n;r.preventDefault(),s=e.label,(n=e.value)&&(navigator.clipboard.writeText(n),_Z.toast.success(`${s} copied`))},className:"flex items-center justify-between gap-3 font-mono text-xs",children:[(0,O.jsx)("span",{className:"shrink-0 text-muted-foreground",children:e.label}),(0,O.jsxs)("span",{className:"flex min-w-0 items-center gap-1.5",children:[(0,O.jsx)("span",{className:"truncate",children:e.value??"—"}),e.value&&(0,O.jsx)(fq.Copy,{className:"h-3 w-3 shrink-0 opacity-60"})]})]},e.label))]})]}),(0,O.jsx)("button",{type:"button",onClick:j,title:y?"Stop capture & copy to clipboard":"Start capturing output","aria-label":y?"Stop capture and copy":"Start capturing output",className:(0,ey.cn)("flex h-6 w-6 items-center justify-center rounded","bg-zinc-900/70 backdrop-blur-sm border border-zinc-700/60","text-zinc-400 hover:text-zinc-100 hover:border-zinc-500 transition-colors",y&&"text-red-400 border-red-500/70 hover:text-red-300"),children:y?(0,O.jsx)(lJ,{className:"h-3 w-3 fill-current"}):(0,O.jsx)(sZ,{className:"h-3 w-3"})})]})]})}let _6=[{name:"Dev Server",command:"pnpm dev",executor_type:"command",pty:!0,description:"Start the development server with hot reload"},{name:"Build",command:"pnpm build",executor_type:"command",pty:!0,description:"Build the project for production"},{name:"Lint",command:"pnpm lint",executor_type:"command",pty:!0,description:"Run the linter to check code quality"},{name:"Type Check",command:"npx tsc --noEmit",executor_type:"command",pty:!0,description:"Run TypeScript type checking without emitting files"},{name:"Test",command:"pnpm test",executor_type:"command",pty:!0,description:"Run the test suite"},{name:"Rebase on and merge into main",command:"Our goal is to sync the current local branch with the local branch/worktree `main`. The two branches may have diverged.\n\nPlease do the following in order. Only proceed to the next step if the previous step succeeds:\n\n1. Rebase the current local branch onto the local branch `main`, and resolve any conflicts if needed.\n2. If, after the rebase, `main` does not yet contain the current branch's commits, switch to the `main` branch/worktree and merge the current branch into `main` using `git merge`. Do not use `git branch -f`.\n3. If the current branch is already fully contained in `main`, and `main` has newer commits, update the current branch so it includes the latest commits from `main`.\n4. Push both the current local branch and the local branch `main` to the remote.",executor_type:"prompt",pty:!1,description:"Rebase current branch onto main, merge into main, and push both branches"},{name:"Reset to main",command:"git reset --hard main",executor_type:"command",pty:!0,description:"Hard reset the current branch to match main"},{name:"Push to remote",command:"git push --force-with-lease",executor_type:"command",pty:!0,description:"Force push to remote with lease safety check"},{name:"Git commit",command:"Inspect the modified and untracked and deleted files in the current repository, generate an appropriate commit message, and commit all relevant files.\n\nCommit message rules:\n- Use Conventional Commits format (feat:, fix:, chore:, refactor:, docs:, test:, ci:, build:, perf:, style:, etc.)\n- Choose the type that best matches the main purpose of the changes\n- Make the message specific to the actual changes\n- Keep it within 50 characters if possible\n- Use lowercase\n- Do not end with a period\n- Do not wrap the message in quotes, backticks, or markdown\n\nCommit requirements:\n- Include all relevant modified and untracked files\n- Do not include unrelated files\n- If there are no meaningful changes to commit, do not create a commit\n\nWhen finished, output only the final commit message.",executor_type:"prompt",pty:!1,description:"Inspect changes, generate a conventional commit message, and commit"},{name:"Tag and push",command:"Find the latest SemVer tag in the repository, increase the patch number by 1, create the new tag from the current commit, and push it to origin.",executor_type:"prompt",pty:!1,description:"Bump the patch version tag and push it to origin"}];function _7({open:e,onOpenChange:r,executor:s,onSubmit:n}){let[i,a]=(0,$.useState)(s?.name??""),[o,l]=(0,$.useState)(s?.executor_type??"command"),[c,d]=(0,$.useState)(s?.prompt_provider??"claude"),[u,h]=(0,$.useState)(s?.command??""),[f,p]=(0,$.useState)(s?.cwd??""),[m,g]=(0,$.useState)(s?.pty??!0),[x,v]=(0,$.useState)(!1),[_,y]=(0,$.useState)(!1),[b,w]=(0,$.useState)(null),[S,j]=(0,$.useState)(null),[C,k]=(0,$.useState)(""),N=!!s;(0,$.useEffect)(()=>{e&&(y(!1),w(null),j(null),k(""),s&&(a(s.name),l(s.executor_type??"command"),d(s.prompt_provider??"claude"),h(s.command),p(s.cwd??""),g(s.pty)))},[e]);let E=async e=>{if(e.preventDefault(),i.trim()&&u.trim()){v(!0);try{await n({name:i.trim(),command:u.trim(),executor_type:o,prompt_provider:"prompt"===o?c:null,cwd:f.trim()||void 0,pty:"prompt"===o||m}),r(!1),N||(a(""),l("command"),d("claude"),h(""),p(""),g(!0))}finally{v(!1)}}};return(0,O.jsx)(t8,{open:e,onOpenChange:r,children:(0,O.jsxs)(rr,{children:[(0,O.jsx)(rs,{children:(0,O.jsxs)("div",{className:"flex items-center justify-between pr-6",children:[(0,O.jsx)(ri,{children:_?"Select Preset":N?"Edit Executor":"Add Executor"}),!N&&!_&&(0,O.jsx)("button",{type:"button",className:"text-sm text-muted-foreground hover:text-foreground transition-colors",onClick:()=>y(!0),children:"Select from presets"})]})}),(0,O.jsxs)("div",{className:"h-[420px] flex flex-col",children:[!_&&(0,O.jsxs)("form",{onSubmit:E,className:"space-y-4 flex-1 flex flex-col",children:[(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Name"}),(0,O.jsx)(ro,{placeholder:"e.g., Dev Server",value:i,onChange:e=>a(e.target.value),required:!0})]}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Type"}),(0,O.jsxs)("div",{className:"flex rounded-md border border-input overflow-hidden",children:[(0,O.jsx)("button",{type:"button",className:(0,ey.cn)("flex-1 px-3 py-1.5 text-sm font-medium transition-colors","command"===o?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),onClick:()=>l("command"),children:"Command"}),(0,O.jsx)("button",{type:"button",className:(0,ey.cn)("flex-1 px-3 py-1.5 text-sm font-medium transition-colors border-l border-input","prompt"===o?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),onClick:()=>l("prompt"),children:"Prompt"})]})]}),"prompt"===o&&(0,O.jsxs)("div",{className:"flex gap-3",children:[(0,O.jsxs)("div",{className:"w-[140px] shrink-0 space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Provider"}),(0,O.jsxs)(hw,{value:c,onValueChange:e=>d(e),children:[(0,O.jsx)(hj,{className:"w-full",children:(0,O.jsx)(hS,{})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"claude",children:"Claude"}),(0,O.jsx)(hk,{value:"codex",children:"Codex"})]})]})]}),(0,O.jsxs)("div",{className:"flex-1 space-y-2",children:[(0,O.jsxs)("label",{className:"text-sm font-medium",children:["Working Directory"," ",(0,O.jsx)("span",{className:"text-muted-foreground",children:"(optional)"})]}),(0,O.jsx)(ro,{placeholder:"Relative to worktree root",value:f,onChange:e=>p(e.target.value)})]})]}),(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"prompt"===o?"Prompt":"Command"}),"prompt"===o?(0,O.jsx)("textarea",{className:"flex min-h-[90px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 resize-y",placeholder:"e.g., Review the code and suggest improvements",value:u,onChange:e=>h(e.target.value),required:!0}):(0,O.jsx)(ro,{placeholder:"e.g., npm run dev",value:u,onChange:e=>h(e.target.value),required:!0})]}),"command"===o&&(0,O.jsxs)("div",{className:"space-y-2",children:[(0,O.jsxs)("label",{className:"text-sm font-medium",children:["Working Directory"," ",(0,O.jsx)("span",{className:"text-muted-foreground",children:"(optional)"})]}),(0,O.jsx)(ro,{placeholder:"Relative to worktree root (leave empty for root)",value:f,onChange:e=>p(e.target.value)})]}),"command"===o&&(0,O.jsxs)("div",{className:"flex items-center justify-between",children:[(0,O.jsxs)("div",{className:"space-y-0.5",children:[(0,O.jsx)("label",{className:"text-sm font-medium",children:"Terminal Mode (PTY)"}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"Enable for interactive commands like top, vim, htop"})]}),(0,O.jsx)("button",{type:"button",role:"switch","aria-checked":m,onClick:()=>g(!m),className:(0,ey.cn)("relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",m?"bg-primary":"bg-input"),children:(0,O.jsx)("span",{className:(0,ey.cn)("pointer-events-none inline-block h-5 w-5 transform rounded-full bg-background shadow-lg ring-0 transition-transform",m?"translate-x-5":"translate-x-0")})})]}),(0,O.jsx)("div",{className:"flex-1"}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),(0,O.jsx)(W.Button,{type:"submit",disabled:x||!i.trim()||!u.trim(),children:x?"Saving...":N?"Save":"Add"})]})]}),_&&(0,O.jsxs)("div",{className:"space-y-4 flex-1 flex flex-col min-h-0",children:[(0,O.jsx)(ro,{placeholder:"Search presets...",value:C,onChange:e=>k(e.target.value),autoFocus:!0}),(0,O.jsx)("div",{className:"flex-1 overflow-y-auto min-h-0 space-y-1",children:_6.filter(e=>{if(!C.trim())return!0;let r=C.toLowerCase();return e.name.toLowerCase().includes(r)||e.command.toLowerCase().includes(r)||(e.description?.toLowerCase().includes(r)??!1)}).map(e=>{let r=b?.command===e.command,s=S===e.command;return(0,O.jsxs)("div",{className:"rounded-md overflow-hidden",children:[(0,O.jsxs)("button",{type:"button",className:(0,ey.cn)("w-full flex items-center gap-2 px-3 py-2 text-sm transition-colors",r?"bg-primary/10 text-primary":"hover:bg-muted"),onClick:()=>w(e),children:["command"===e.executor_type?(0,O.jsx)(ol,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):(0,O.jsx)(sD,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),(0,O.jsx)("span",{className:"font-medium flex-1 text-left",children:e.name}),(0,O.jsx)("button",{type:"button",className:"shrink-0 p-0.5 rounded hover:bg-muted-foreground/10 transition-colors",onClick:r=>{r.stopPropagation(),j(s?null:e.command)},children:s?(0,O.jsx)(ns,{className:"h-4 w-4 text-muted-foreground"}):(0,O.jsx)(a3,{className:"h-4 w-4 text-muted-foreground"})})]}),s&&(0,O.jsxs)("div",{className:(0,ey.cn)("px-3 pb-2 pt-1 text-xs text-muted-foreground space-y-1 border-t border-border/50",r?"bg-primary/5":"bg-muted/50"),children:[e.description&&(0,O.jsx)("p",{children:e.description}),(0,O.jsx)("pre",{className:"whitespace-pre-wrap break-all bg-muted/50 rounded px-2 py-1 font-mono",children:e.command}),(0,O.jsxs)("div",{className:"flex gap-3",children:[(0,O.jsxs)("span",{children:["Type: ",(0,O.jsx)("span",{className:"font-medium text-foreground/70",children:e.executor_type})]}),(0,O.jsxs)("span",{children:["PTY: ",(0,O.jsx)("span",{className:"font-medium text-foreground/70",children:e.pty?"on":"off"})]})]})]})]},e.command)})}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{type:"button",variant:"outline",onClick:()=>{y(!1),w(null),j(null)},children:"Cancel"}),(0,O.jsx)(W.Button,{type:"button",disabled:!b,onClick:()=>{b&&(a(b.name),h(b.command),l(b.executor_type),g(b.pty),y(!1),w(null),j(null))},children:"Select"})]})]})]})]})})}let _8={logs:[],status:"connecting",exitCode:null,isPty:!1,replayingHistory:!0},_9=(0,$.createContext)(null);function ye({projectId:e,children:r}){let s=(0,$.useRef)(new Map),n=(0,$.useRef)(new Map),i=(0,$.useRef)(new Set),a=(0,$.useRef)(null),o=(0,$.useRef)(0),l=(0,$.useRef)(null),c=(0,$.useCallback)(e=>{n.current.get(e)?.forEach(e=>e())},[]),d=(0,$.useCallback)((e,r)=>{let n=s.current.get(e)??_8;s.current.set(e,{...n,...r}),c(e)},[c]),u=(0,$.useCallback)(e=>{a.current?.readyState===WebSocket.OPEN&&a.current.send(JSON.stringify(e))},[]),h=(0,$.useCallback)(e=>{let{processId:r}=e;if("error"===e.type?e.message:"finished"===e.type?e.exitCode:"init"===e.type?e.isPty:"history_end"===e.type||e.data.length,"init"===e.type)d(r,{isPty:e.isPty,replayingHistory:!0,logs:[],status:"connected"});else if("history_end"===e.type)d(r,{replayingHistory:!1});else if("finished"===e.type)console.log(`[diag:remote-stop] ${new Date().toISOString()} mux received FINISHED processId=${r} exitCode=${e.exitCode} — will trigger markProcessFinished → button flips to Start`),d(r,{exitCode:e.exitCode,status:"closed"});else if("error"===e.type)console.log(`[diag:remote-stop] ${new Date().toISOString()} mux received ERROR processId=${r} — status=error, does NOT flip isRunning`),d(r,{status:"error"});else{let n=s.current.get(r)??_8,{processId:i,...a}=e;d(r,{logs:[...n.logs,{...a,historical:n.replayingHistory}]})}},[d]);(0,$.useEffect)(()=>{if(!e)return;let r=!1;o.current=0;let n=()=>{r||(0,rv.getFreshToken)().then(()=>{r||(()=>{if(r)return;let c=new WebSocket((0,rv.getWebSocketUrl)(`/api/executor-logs/stream?projectId=${encodeURIComponent(e)}`));a.current=c,c.onopen=()=>{if(!r)for(let e of(o.current=0,console.log("[diag:mux] WS open, resubscribing",[...i.current]),i.current))c.send(JSON.stringify({type:"subscribe",processId:e}))},c.onmessage=e=>{if(!r)try{h(JSON.parse(e.data))}catch(e){console.error("[ExecutorLogs] parse error:",e)}},c.onclose=()=>{if(a.current=null,console.log("[diag:mux] WS close, reconnectAttempt=",o.current,"cancelled=",r),r)return;let e=e=>{let r=s.current.get(e);return r?.status==="closed"||r?.status==="error"};if(o.current<8){let s=o.current++,a=Math.min(15e3,1e3*2**s),c=a+a*Math.random()*.25;for(let r of i.current)e(r)||d(r,{status:"connecting"});l.current=setTimeout(()=>{l.current=null,r||n()},c)}else for(let r of i.current)e(r)||d(r,{status:"error"})}})()})};return n(),()=>{r=!0,l.current&&clearTimeout(l.current),l.current=null,a.current?.close(),a.current=null}},[e,h,d]);let f=(0,$.useMemo)(()=>({subscribeProcess:e=>{i.current.has(e)||(i.current.add(e),s.current.set(e,{..._8}),c(e),console.log("[diag:mux] send subscribe",e,"(state reset to EMPTY)"),u({type:"subscribe",processId:e}))},unsubscribeProcess:e=>{i.current.has(e)&&(i.current.delete(e),console.log("[diag:mux] send unsubscribe",e),u({type:"unsubscribe",processId:e}))},sendInput:(e,r)=>u({type:"input",processId:e,data:r}),sendResize:(e,r,s)=>u({type:"resize",processId:e,cols:r,rows:s}),onProcessChange:(e,r)=>{let s=n.current.get(e);return s||(s=new Set,n.current.set(e,s)),s.add(r),()=>{s?.delete(r)}},getProcessState:e=>s.current.get(e)??_8}),[c,u]);return(0,O.jsx)(_9.Provider,{value:f,children:r})}let yt="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement;function yr(e){let r=Object.prototype.toString.call(e);return"[object Window]"===r||"[object global]"===r}function ys(e){return"nodeType"in e}function yn(e){var r,s;return e?yr(e)?e:ys(e)&&null!=(r=null==(s=e.ownerDocument)?void 0:s.defaultView)?r:window:window}function yi(e){let{Document:r}=yn(e);return e instanceof r}function ya(e){return!yr(e)&&e instanceof yn(e).HTMLElement}function yo(e){return e instanceof yn(e).SVGElement}function yl(e){return e?yr(e)?e.document:ys(e)?yi(e)?e:ya(e)||yo(e)?e.ownerDocument:document:document:document}let yc=yt?$.useLayoutEffect:$.useEffect;function yd(e){let r=(0,$.useRef)(e);return yc(()=>{r.current=e}),(0,$.useCallback)(function(){for(var e=arguments.length,s=Array(e),n=0;n<e;n++)s[n]=arguments[n];return null==r.current?void 0:r.current(...s)},[])}function yu(e,r){void 0===r&&(r=[e]);let s=(0,$.useRef)(e);return yc(()=>{s.current!==e&&(s.current=e)},r),s}function yh(e,r){let s=(0,$.useRef)();return(0,$.useMemo)(()=>{let r=e(s.current);return s.current=r,r},[...r])}function yf(e){let r=yd(e),s=(0,$.useRef)(null),n=(0,$.useCallback)(e=>{e!==s.current&&(null==r||r(e,s.current)),s.current=e},[]);return[s,n]}function yp(e){let r=(0,$.useRef)();return(0,$.useEffect)(()=>{r.current=e},[e]),r.current}let ym={};function yg(e,r){return(0,$.useMemo)(()=>{if(r)return r;let s=null==ym[e]?0:ym[e]+1;return ym[e]=s,e+"-"+s},[e,r])}function yx(e){return function(r){for(var s=arguments.length,n=Array(s>1?s-1:0),i=1;i<s;i++)n[i-1]=arguments[i];return n.reduce((r,s)=>{for(let[n,i]of Object.entries(s)){let s=r[n];null!=s&&(r[n]=s+e*i)}return r},{...r})}}let yv=yx(1),y_=yx(-1);function yy(e){if(!e)return!1;let{KeyboardEvent:r}=yn(e.target);return r&&e instanceof r}function yb(e){if(function(e){if(!e)return!1;let{TouchEvent:r}=yn(e.target);return r&&e instanceof r}(e)){if(e.touches&&e.touches.length){let{clientX:r,clientY:s}=e.touches[0];return{x:r,y:s}}else if(e.changedTouches&&e.changedTouches.length){let{clientX:r,clientY:s}=e.changedTouches[0];return{x:r,y:s}}}return"clientX"in e&&"clientY"in e?{x:e.clientX,y:e.clientY}:null}let yw=Object.freeze({Translate:{toString(e){if(!e)return;let{x:r,y:s}=e;return"translate3d("+(r?Math.round(r):0)+"px, "+(s?Math.round(s):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;let{scaleX:r,scaleY:s}=e;return"scaleX("+r+") scaleY("+s+")"}},Transform:{toString(e){if(e)return[yw.Translate.toString(e),yw.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:r,duration:s,easing:n}=e;return r+" "+s+"ms "+n}}}),yS="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]",yj={display:"none"};function yC(e){let{id:r,value:s}=e;return $.default.createElement("div",{id:r,style:yj},s)}function yk(e){let{id:r,announcement:s,ariaLiveType:n="assertive"}=e;return $.default.createElement("div",{id:r,style:{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"},role:"status","aria-live":n,"aria-atomic":!0},s)}let yN=(0,$.createContext)(null),yE={draggable:"\n To pick up a draggable item, press the space bar.\n While dragging, use the arrow keys to move the item.\n Press space again to drop the item in its new position, or press escape to cancel.\n "},yD={onDragStart(e){let{active:r}=e;return"Picked up draggable item "+r.id+"."},onDragOver(e){let{active:r,over:s}=e;return s?"Draggable item "+r.id+" was moved over droppable area "+s.id+".":"Draggable item "+r.id+" is no longer over a droppable area."},onDragEnd(e){let{active:r,over:s}=e;return s?"Draggable item "+r.id+" was dropped over droppable area "+s.id:"Draggable item "+r.id+" was dropped."},onDragCancel(e){let{active:r}=e;return"Dragging was cancelled. Draggable item "+r.id+" was dropped."}};function yR(e){var r;let s,{announcements:n=yD,container:i,hiddenTextDescribedById:a,screenReaderInstructions:o=yE}=e,{announce:l,announcement:c}=function(){let[e,r]=(0,$.useState)("");return{announce:(0,$.useCallback)(e=>{null!=e&&r(e)},[]),announcement:e}}(),d=yg("DndLiveRegion"),[u,h]=(0,$.useState)(!1);if((0,$.useEffect)(()=>{h(!0)},[]),r=(0,$.useMemo)(()=>({onDragStart(e){let{active:r}=e;l(n.onDragStart({active:r}))},onDragMove(e){let{active:r,over:s}=e;n.onDragMove&&l(n.onDragMove({active:r,over:s}))},onDragOver(e){let{active:r,over:s}=e;l(n.onDragOver({active:r,over:s}))},onDragEnd(e){let{active:r,over:s}=e;l(n.onDragEnd({active:r,over:s}))},onDragCancel(e){let{active:r,over:s}=e;l(n.onDragCancel({active:r,over:s}))}}),[l,n]),s=(0,$.useContext)(yN),(0,$.useEffect)(()=>{if(!s)throw Error("useDndMonitor must be used within a children of <DndContext>");return s(r)},[r,s]),!u)return null;let f=$.default.createElement($.default.Fragment,null,$.default.createElement(yC,{id:a,value:o.draggable}),$.default.createElement(yk,{id:d,announcement:c}));return i?(0,ee.createPortal)(f,i):f}function yA(){}function yT(e,r){return(0,$.useMemo)(()=>({sensor:e,options:null!=r?r:{}}),[e,r])}(_=E||(E={})).DragStart="dragStart",_.DragMove="dragMove",_.DragEnd="dragEnd",_.DragCancel="dragCancel",_.DragOver="dragOver",_.RegisterDroppable="registerDroppable",_.SetDroppableDisabled="setDroppableDisabled",_.UnregisterDroppable="unregisterDroppable";let yM=Object.freeze({x:0,y:0});function yF(e,r){return Math.sqrt(Math.pow(e.x-r.x,2)+Math.pow(e.y-r.y,2))}function yP(e,r){let{data:{value:s}}=e,{data:{value:n}}=r;return s-n}function yI(e,r){let{data:{value:s}}=e,{data:{value:n}}=r;return n-s}function yB(e){let{left:r,top:s,height:n,width:i}=e;return[{x:r,y:s},{x:r+i,y:s},{x:r,y:s+n},{x:r+i,y:s+n}]}function yL(e,r){if(!e||0===e.length)return null;let[s]=e;return r?s[r]:s}function yz(e,r,s){return void 0===r&&(r=e.left),void 0===s&&(s=e.top),{x:r+.5*e.width,y:s+.5*e.height}}let yO=e=>{let{collisionRect:r,droppableRects:s,droppableContainers:n}=e,i=[];for(let e of n){let{id:n}=e,a=s.get(n);if(a){let s=function(e,r){let s=Math.max(r.top,e.top),n=Math.max(r.left,e.left),i=Math.min(r.left+r.width,e.left+e.width),a=Math.min(r.top+r.height,e.top+e.height);if(n<i&&s<a){let o=r.width*r.height,l=e.width*e.height,c=(i-n)*(a-s);return Number((c/(o+l-c)).toFixed(4))}return 0}(a,r);s>0&&i.push({id:n,data:{droppableContainer:e,value:s}})}}return i.sort(yI)};function y$(e,r){return e&&r?{x:e.left-r.left,y:e.top-r.top}:yM}let yW=function(e){for(var r=arguments.length,s=Array(r>1?r-1:0),n=1;n<r;n++)s[n-1]=arguments[n];return s.reduce((e,r)=>({...e,top:e.top+ +r.y,bottom:e.bottom+ +r.y,left:e.left+ +r.x,right:e.right+ +r.x}),{...e})},yH={ignoreTransform:!1};function yU(e,r){void 0===r&&(r=yH);let s=e.getBoundingClientRect();if(r.ignoreTransform){let{transform:r,transformOrigin:n}=yn(e).getComputedStyle(e);r&&(s=function(e,r,s){let n=function(e){if(e.startsWith("matrix3d(")){let r=e.slice(9,-1).split(/, /);return{x:+r[12],y:+r[13],scaleX:+r[0],scaleY:+r[5]}}if(e.startsWith("matrix(")){let r=e.slice(7,-1).split(/, /);return{x:+r[4],y:+r[5],scaleX:+r[0],scaleY:+r[3]}}return null}(r);if(!n)return e;let{scaleX:i,scaleY:a,x:o,y:l}=n,c=e.left-o-(1-i)*parseFloat(s),d=e.top-l-(1-a)*parseFloat(s.slice(s.indexOf(" ")+1)),u=i?e.width/i:e.width,h=a?e.height/a:e.height;return{width:u,height:h,top:d,right:c+u,bottom:d+h,left:c}}(s,r,n))}let{top:n,left:i,width:a,height:o,bottom:l,right:c}=s;return{top:n,left:i,width:a,height:o,bottom:l,right:c}}function yq(e){return yU(e,{ignoreTransform:!0})}function yK(e,r){let s=[];return e?function n(i){var a,o;let l;if(null!=r&&s.length>=r||!i)return s;if(yi(i)&&null!=i.scrollingElement&&!s.includes(i.scrollingElement))return s.push(i.scrollingElement),s;if(!ya(i)||yo(i)||s.includes(i))return s;let c=yn(e).getComputedStyle(i);return(i!==e&&(void 0===(a=c)&&(a=yn(i).getComputedStyle(i)),l=/(auto|scroll|overlay)/,["overflow","overflowX","overflowY"].some(e=>{let r=a[e];return"string"==typeof r&&l.test(r)}))&&s.push(i),void 0===(o=c)&&(o=yn(i).getComputedStyle(i)),"fixed"===o.position)?s:n(i.parentNode)}(e):s}function yV(e){let[r]=yK(e,1);return null!=r?r:null}function yY(e){return yt&&e?yr(e)?e:ys(e)?yi(e)||e===yl(e).scrollingElement?window:ya(e)?e:null:null:null}function yG(e){return yr(e)?e.scrollX:e.scrollLeft}function yX(e){return yr(e)?e.scrollY:e.scrollTop}function yJ(e){return{x:yG(e),y:yX(e)}}function yZ(e){return!!yt&&!!e&&e===document.scrollingElement}function yQ(e){let r={x:0,y:0},s=yZ(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},n={x:e.scrollWidth-s.width,y:e.scrollHeight-s.height},i=e.scrollTop<=r.y,a=e.scrollLeft<=r.x;return{isTop:i,isLeft:a,isBottom:e.scrollTop>=n.y,isRight:e.scrollLeft>=n.x,maxScroll:n,minScroll:r}}(y=D||(D={}))[y.Forward=1]="Forward",y[y.Backward=-1]="Backward";let y0={x:.2,y:.2};function y1(e){return e.reduce((e,r)=>yv(e,yJ(r)),yM)}let y2=[["x",["left","right"],function(e){return e.reduce((e,r)=>e+yG(r),0)}],["y",["top","bottom"],function(e){return e.reduce((e,r)=>e+yX(r),0)}]];class y5{constructor(e,r){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const s=yK(r),n=y1(s);for(const[r,i,a]of(this.rect={...e},this.width=e.width,this.height=e.height,y2))for(const e of i)Object.defineProperty(this,e,{get:()=>{let i=a(s),o=n[r]-i;return this.rect[e]+o},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class y3{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(e=>{var r;return null==(r=this.target)?void 0:r.removeEventListener(...e)})},this.target=e}add(e,r,s){var n;null==(n=this.target)||n.addEventListener(e,r,s),this.listeners.push([e,r,s])}}function y4(e,r){let s=Math.abs(e.x),n=Math.abs(e.y);return"number"==typeof r?Math.sqrt(s**2+n**2)>r:"x"in r&&"y"in r?s>r.x&&n>r.y:"x"in r?s>r.x:"y"in r&&n>r.y}function y6(e){e.preventDefault()}function y7(e){e.stopPropagation()}(b=R||(R={})).Click="click",b.DragStart="dragstart",b.Keydown="keydown",b.ContextMenu="contextmenu",b.Resize="resize",b.SelectionChange="selectionchange",b.VisibilityChange="visibilitychange",(w=A||(A={})).Space="Space",w.Down="ArrowDown",w.Right="ArrowRight",w.Left="ArrowLeft",w.Up="ArrowUp",w.Esc="Escape",w.Enter="Enter",w.Tab="Tab";let y8={start:[A.Space,A.Enter],cancel:[A.Esc],end:[A.Space,A.Enter,A.Tab]},y9=(e,r)=>{let{currentCoordinates:s}=r;switch(e.code){case A.Right:return{...s,x:s.x+25};case A.Left:return{...s,x:s.x-25};case A.Down:return{...s,y:s.y+25};case A.Up:return{...s,y:s.y-25}}};class be{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:r}}=e;this.props=e,this.listeners=new y3(yl(r)),this.windowListeners=new y3(yn(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(R.Resize,this.handleCancel),this.windowListeners.add(R.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(R.Keydown,this.handleKeyDown))}handleStart(){let{activeNode:e,onStart:r}=this.props,s=e.node.current;s&&function(e,r){if(void 0===r&&(r=yU),!e)return;let{top:s,left:n,bottom:i,right:a}=r(e);yV(e)&&(i<=0||a<=0||s>=window.innerHeight||n>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}(s),r(yM)}handleKeyDown(e){if(yy(e)){let{active:r,context:s,options:n}=this.props,{keyboardCodes:i=y8,coordinateGetter:a=y9,scrollBehavior:o="smooth"}=n,{code:l}=e;if(i.end.includes(l))return void this.handleEnd(e);if(i.cancel.includes(l))return void this.handleCancel(e);let{collisionRect:c}=s.current,d=c?{x:c.left,y:c.top}:yM;this.referenceCoordinates||(this.referenceCoordinates=d);let u=a(e,{active:r,context:s.current,currentCoordinates:d});if(u){let r=y_(u,d),n={x:0,y:0},{scrollableAncestors:i}=s.current;for(let s of i){let i=e.code,{isTop:a,isRight:l,isLeft:c,isBottom:d,maxScroll:h,minScroll:f}=yQ(s),p=function(e){if(e===document.scrollingElement){let{innerWidth:e,innerHeight:r}=window;return{top:0,left:0,right:e,bottom:r,width:e,height:r}}let{top:r,left:s,right:n,bottom:i}=e.getBoundingClientRect();return{top:r,left:s,right:n,bottom:i,width:e.clientWidth,height:e.clientHeight}}(s),m={x:Math.min(i===A.Right?p.right-p.width/2:p.right,Math.max(i===A.Right?p.left:p.left+p.width/2,u.x)),y:Math.min(i===A.Down?p.bottom-p.height/2:p.bottom,Math.max(i===A.Down?p.top:p.top+p.height/2,u.y))},g=i===A.Right&&!l||i===A.Left&&!c,x=i===A.Down&&!d||i===A.Up&&!a;if(g&&m.x!==u.x){let e=s.scrollLeft+r.x,a=i===A.Right&&e<=h.x||i===A.Left&&e>=f.x;if(a&&!r.y)return void s.scrollTo({left:e,behavior:o});a?n.x=s.scrollLeft-e:n.x=i===A.Right?s.scrollLeft-h.x:s.scrollLeft-f.x,n.x&&s.scrollBy({left:-n.x,behavior:o});break}if(x&&m.y!==u.y){let e=s.scrollTop+r.y,a=i===A.Down&&e<=h.y||i===A.Up&&e>=f.y;if(a&&!r.x)return void s.scrollTo({top:e,behavior:o});a?n.y=s.scrollTop-e:n.y=i===A.Down?s.scrollTop-h.y:s.scrollTop-f.y,n.y&&s.scrollBy({top:-n.y,behavior:o});break}}this.handleMove(e,yv(y_(u,this.referenceCoordinates),n))}}}handleMove(e,r){let{onMove:s}=this.props;e.preventDefault(),s(r)}handleEnd(e){let{onEnd:r}=this.props;e.preventDefault(),this.detach(),r()}handleCancel(e){let{onCancel:r}=this.props;e.preventDefault(),this.detach(),r()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}function bt(e){return!!(e&&"distance"in e)}function br(e){return!!(e&&"delay"in e)}be.activators=[{eventName:"onKeyDown",handler:(e,r,s)=>{let{keyboardCodes:n=y8,onActivation:i}=r,{active:a}=s,{code:o}=e.nativeEvent;if(n.start.includes(o)){let r=a.activatorNode.current;return(!r||e.target===r)&&(e.preventDefault(),null==i||i({event:e.nativeEvent}),!0)}return!1}}];class bs{constructor(e,r,s){var n;void 0===s&&(s=function(e){let{EventTarget:r}=yn(e);return e instanceof r?e:yl(e)}(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=r;const{event:i}=e,{target:a}=i;this.props=e,this.events=r,this.document=yl(a),this.documentListeners=new y3(this.document),this.listeners=new y3(s),this.windowListeners=new y3(yn(a)),this.initialCoordinates=null!=(n=yb(i))?n:yM,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){let{events:e,props:{options:{activationConstraint:r,bypassActivationConstraint:s}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(R.Resize,this.handleCancel),this.windowListeners.add(R.DragStart,y6),this.windowListeners.add(R.VisibilityChange,this.handleCancel),this.windowListeners.add(R.ContextMenu,y6),this.documentListeners.add(R.Keydown,this.handleKeydown),r){if(null!=s&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(br(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(bt(r))return void this.handlePending(r)}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,r){let{active:s,onPending:n}=this.props;n(s,e,this.initialCoordinates,r)}handleStart(){let{initialCoordinates:e}=this,{onStart:r}=this.props;e&&(this.activated=!0,this.documentListeners.add(R.Click,y7,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(R.SelectionChange,this.removeTextSelection),r(e))}handleMove(e){var r;let{activated:s,initialCoordinates:n,props:i}=this,{onMove:a,options:{activationConstraint:o}}=i;if(!n)return;let l=null!=(r=yb(e))?r:yM,c=y_(n,l);if(!s&&o){if(bt(o)){if(null!=o.tolerance&&y4(c,o.tolerance))return this.handleCancel();if(y4(c,o.distance))return this.handleStart()}return br(o)&&y4(c,o.tolerance)?this.handleCancel():void this.handlePending(o,c)}e.cancelable&&e.preventDefault(),a(l)}handleEnd(){let{onAbort:e,onEnd:r}=this.props;this.detach(),this.activated||e(this.props.active),r()}handleCancel(){let{onAbort:e,onCancel:r}=this.props;this.detach(),this.activated||e(this.props.active),r()}handleKeydown(e){e.code===A.Esc&&this.handleCancel()}removeTextSelection(){var e;null==(e=this.document.getSelection())||e.removeAllRanges()}}let bn={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class bi extends bs{constructor(e){const{event:r}=e;super(e,bn,yl(r.target))}}bi.activators=[{eventName:"onPointerDown",handler:(e,r)=>{let{nativeEvent:s}=e,{onActivation:n}=r;return!!s.isPrimary&&0===s.button&&(null==n||n({event:s}),!0)}}];(S=T||(T={}))[S.RightClick=2]="RightClick";(j=M||(M={}))[j.Pointer=0]="Pointer",j[j.DraggableRect=1]="DraggableRect",(C=F||(F={}))[C.TreeOrder=0]="TreeOrder",C[C.ReversedTreeOrder=1]="ReversedTreeOrder";let ba={x:{[D.Backward]:!1,[D.Forward]:!1},y:{[D.Backward]:!1,[D.Forward]:!1}};(k=P||(P={}))[k.Always=0]="Always",k[k.BeforeDragging=1]="BeforeDragging",k[k.WhileDragging=2]="WhileDragging",(I||(I={})).Optimized="optimized";let bo=new Map;function bl(e,r){return yh(s=>e?s||("function"==typeof r?r(e):e):null,[r,e])}function bc(e){let{callback:r,disabled:s}=e,n=yd(r),i=(0,$.useMemo)(()=>{if(s||"undefined"==typeof window||void 0===window.ResizeObserver)return;let{ResizeObserver:e}=window;return new e(n)},[s]);return(0,$.useEffect)(()=>()=>null==i?void 0:i.disconnect(),[i]),i}function bd(e){return new y5(yU(e),e)}function bu(e,r,s){void 0===r&&(r=bd);let[n,i]=(0,$.useState)(null);function a(){i(n=>{if(!e)return null;if(!1===e.isConnected){var i;return null!=(i=null!=n?n:s)?i:null}let a=r(e);return JSON.stringify(n)===JSON.stringify(a)?n:a})}let o=function(e){let{callback:r,disabled:s}=e,n=yd(r),i=(0,$.useMemo)(()=>{if(s||"undefined"==typeof window||void 0===window.MutationObserver)return;let{MutationObserver:e}=window;return new e(n)},[n,s]);return(0,$.useEffect)(()=>()=>null==i?void 0:i.disconnect(),[i]),i}({callback(r){if(e)for(let s of r){let{type:r,target:n}=s;if("childList"===r&&n instanceof HTMLElement&&n.contains(e)){a();break}}}}),l=bc({callback:a});return yc(()=>{a(),e?(null==l||l.observe(e),null==o||o.observe(document.body,{childList:!0,subtree:!0})):(null==l||l.disconnect(),null==o||o.disconnect())},[e]),n}let bh=[];function bf(e,r){void 0===r&&(r=[]);let s=(0,$.useRef)(null);return(0,$.useEffect)(()=>{s.current=null},r),(0,$.useEffect)(()=>{let r=e!==yM;r&&!s.current&&(s.current=e),!r&&s.current&&(s.current=null)},[e]),s.current?y_(e,s.current):yM}function bp(e){return(0,$.useMemo)(()=>{let r,s;return e?(r=e.innerWidth,{top:0,left:0,right:r,bottom:s=e.innerHeight,width:r,height:s}):null},[e])}let bm=[],bg=[{sensor:bi,options:{}},{sensor:be,options:{}}],bx={current:{}},bv={draggable:{measure:yq},droppable:{measure:yq,strategy:P.WhileDragging,frequency:I.Optimized},dragOverlay:{measure:yU}};class b_ extends Map{get(e){var r;return null!=e&&null!=(r=super.get(e))?r:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:r}=e;return!r})}getNodeFor(e){var r,s;return null!=(r=null==(s=this.get(e))?void 0:s.node.current)?r:void 0}}let by={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new b_,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:yA},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:bv,measureDroppableContainers:yA,windowRect:null,measuringScheduled:!1},bb={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:yA,draggableNodes:new Map,over:null,measureDroppableContainers:yA},bw=(0,$.createContext)(bb),bS=(0,$.createContext)(by);function bj(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new b_}}}function bC(e,r){switch(r.type){case E.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:r.initialCoordinates,active:r.active}};case E.DragMove:if(null==e.draggable.active)return e;return{...e,draggable:{...e.draggable,translate:{x:r.coordinates.x-e.draggable.initialCoordinates.x,y:r.coordinates.y-e.draggable.initialCoordinates.y}}};case E.DragEnd:case E.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case E.RegisterDroppable:{let{element:s}=r,{id:n}=s,i=new b_(e.droppable.containers);return i.set(n,s),{...e,droppable:{...e.droppable,containers:i}}}case E.SetDroppableDisabled:{let{id:s,key:n,disabled:i}=r,a=e.droppable.containers.get(s);if(!a||n!==a.key)return e;let o=new b_(e.droppable.containers);return o.set(s,{...a,disabled:i}),{...e,droppable:{...e.droppable,containers:o}}}case E.UnregisterDroppable:{let{id:s,key:n}=r,i=e.droppable.containers.get(s);if(!i||n!==i.key)return e;let a=new b_(e.droppable.containers);return a.delete(s),{...e,droppable:{...e.droppable,containers:a}}}default:return e}}function bk(e){let{disabled:r}=e,{active:s,activatorEvent:n,draggableNodes:i}=(0,$.useContext)(bw),a=yp(n),o=yp(null==s?void 0:s.id);return(0,$.useEffect)(()=>{if(!r&&!n&&a&&null!=o){if(!yy(a)||document.activeElement===a.target)return;let e=i.get(o);if(!e)return;let{activatorNode:r,node:s}=e;(r.current||s.current)&&requestAnimationFrame(()=>{for(let e of[r.current,s.current]){if(!e)continue;let r=e.matches(yS)?e:e.querySelector(yS);if(r){r.focus();break}}})}},[n,r,i,o,a]),null}let bN=(0,$.createContext)({...yM,scaleX:1,scaleY:1});(N=B||(B={}))[N.Uninitialized=0]="Uninitialized",N[N.Initializing=1]="Initializing",N[N.Initialized=2]="Initialized";let bE=(0,$.memo)(function(e){var r,s,n,i,a,o,l,c;let d,u,h,f,p,m,g,x,{id:v,accessibility:_,autoScroll:y=!0,children:b,sensors:w=bg,collisionDetection:S=yO,measuring:j,modifiers:C,...k}=e,[N,R]=(0,$.useReducer)(bC,void 0,bj),[A,T]=function(){let[e]=(0,$.useState)(()=>new Set),r=(0,$.useCallback)(r=>(e.add(r),()=>e.delete(r)),[e]);return[(0,$.useCallback)(r=>{let{type:s,event:n}=r;e.forEach(e=>{var r;return null==(r=e[s])?void 0:r.call(e,n)})},[e]),r]}(),[I,L]=(0,$.useState)(B.Uninitialized),z=I===B.Initialized,{draggable:{active:O,nodes:W,translate:H},droppable:{containers:U}}=N,q=null!=O?W.get(O):null,K=(0,$.useRef)({initial:null,translated:null}),V=(0,$.useMemo)(()=>{var e;return null!=O?{id:O,data:null!=(e=null==q?void 0:q.data)?e:bx,rect:K}:null},[O,q]),Y=(0,$.useRef)(null),[G,X]=(0,$.useState)(null),[J,Z]=(0,$.useState)(null),Q=yu(k,Object.values(k)),et=yg("DndDescribedBy",v),er=(0,$.useMemo)(()=>U.getEnabled(),[U]),es=(0,$.useMemo)(()=>({draggable:{...bv.draggable,...null==j?void 0:j.draggable},droppable:{...bv.droppable,...null==j?void 0:j.droppable},dragOverlay:{...bv.dragOverlay,...null==j?void 0:j.dragOverlay}}),[null==j?void 0:j.draggable,null==j?void 0:j.droppable,null==j?void 0:j.dragOverlay]),{droppableRects:en,measureDroppableContainers:ei,measuringScheduled:ea}=function(e,r){let{dragging:s,dependencies:n,config:i}=r,[a,o]=(0,$.useState)(null),{frequency:l,measure:c,strategy:d}=i,u=(0,$.useRef)(e),h=function(){switch(d){case P.Always:return!1;case P.BeforeDragging:return s;default:return!s}}(),f=yu(h),p=(0,$.useCallback)(function(e){void 0===e&&(e=[]),f.current||o(r=>null===r?e:r.concat(e.filter(e=>!r.includes(e))))},[f]),m=(0,$.useRef)(null),g=yh(r=>{if(h&&!s)return bo;if(!r||r===bo||u.current!==e||null!=a){let r=new Map;for(let s of e){if(!s)continue;if(a&&a.length>0&&!a.includes(s.id)&&s.rect.current){r.set(s.id,s.rect.current);continue}let e=s.node.current,n=e?new y5(c(e),e):null;s.rect.current=n,n&&r.set(s.id,n)}return r}return r},[e,a,s,h,c]);return(0,$.useEffect)(()=>{u.current=e},[e]),(0,$.useEffect)(()=>{h||p()},[s,h]),(0,$.useEffect)(()=>{a&&a.length>0&&o(null)},[JSON.stringify(a)]),(0,$.useEffect)(()=>{h||"number"!=typeof l||null!==m.current||(m.current=setTimeout(()=>{p(),m.current=null},l))},[l,h,p,...n]),{droppableRects:g,measureDroppableContainers:p,measuringScheduled:null!=a}}(er,{dragging:z,dependencies:[H.x,H.y],config:es.droppable}),eo=yh(e=>{var r;return null==O?null:null!=(r=null!=p?p:e)?r:null},[p=(f=null!=O?W.get(O):void 0)?f.node.current:null,O]),el=(0,$.useMemo)(()=>J?yb(J):null,[J]),ec=(d=(null==G?void 0:G.autoScrollEnabled)===!1,u="object"==typeof y?!1===y.enabled:!1===y,h=z&&!d&&!u,"object"==typeof y?{...y,enabled:h}:{enabled:h}),ed=bl(eo,es.draggable.measure);!function(e){let{activeNode:r,measure:s,initialRect:n,config:i=!0}=e,a=(0,$.useRef)(!1),{x:o,y:l}="boolean"==typeof i?{x:i,y:i}:i;yc(()=>{if(!o&&!l||!r){a.current=!1;return}if(a.current||!n)return;let e=null==r?void 0:r.node.current;if(!e||!1===e.isConnected)return;let i=y$(s(e),n);if(o||(i.x=0),l||(i.y=0),a.current=!0,Math.abs(i.x)>0||Math.abs(i.y)>0){let r=yV(e);r&&r.scrollBy({top:i.y,left:i.x})}},[r,o,l,n,s])}({activeNode:null!=O?W.get(O):null,config:ec.layoutShiftCompensation,initialRect:ed,measure:es.draggable.measure});let eu=bu(eo,es.draggable.measure,ed),eh=bu(eo?eo.parentElement:null),ef=(0,$.useRef)({activatorEvent:null,active:null,activeNode:eo,collisionRect:null,collisions:null,droppableRects:en,draggableNodes:W,draggingNode:null,draggingNodeRect:null,droppableContainers:U,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ep=U.getNodeFor(null==(r=ef.current.over)?void 0:r.id),em=function(e){let{measure:r}=e,[s,n]=(0,$.useState)(null),i=bc({callback:(0,$.useCallback)(e=>{for(let{target:s}of e)if(ya(s)){n(e=>{let n=r(s);return e?{...e,width:n.width,height:n.height}:n});break}},[r])}),[a,o]=yf((0,$.useCallback)(e=>{let s=function(e){if(!e)return null;if(e.children.length>1)return e;let r=e.children[0];return ya(r)?r:e}(e);null==i||i.disconnect(),s&&(null==i||i.observe(s)),n(s?r(s):null)},[r,i]));return(0,$.useMemo)(()=>({nodeRef:a,rect:s,setRef:o}),[s,a,o])}({measure:es.dragOverlay.measure}),eg=null!=(s=em.nodeRef.current)?s:eo,ex=z?null!=(n=em.rect)?n:eu:null,ev=!!(em.nodeRef.current&&em.rect),e_=(m=bl(a=ev?null:eu),y$(a,m)),ey=bp(eg?yn(eg):null),eb=(o=z?null!=ep?ep:eo:null,g=(0,$.useRef)(o),x=yh(e=>o?e&&e!==bh&&o&&g.current&&o.parentNode===g.current.parentNode?e:yK(o):bh,[o]),(0,$.useEffect)(()=>{g.current=o},[o]),x),ew=function(e,r){void 0===r&&(r=yU);let[s]=e,n=bp(s?yn(s):null),[i,a]=(0,$.useState)(bm);function o(){a(()=>e.length?e.map(e=>yZ(e)?n:new y5(r(e),e)):bm)}let l=bc({callback:o});return yc(()=>{null==l||l.disconnect(),o(),e.forEach(e=>null==l?void 0:l.observe(e))},[e]),i}(eb),eS=function(e,r){let{transform:s,...n}=r;return null!=e&&e.length?e.reduce((e,r)=>r({transform:e,...n}),s):s}(C,{transform:{x:H.x-e_.x,y:H.y-e_.y,scaleX:1,scaleY:1},activatorEvent:J,active:V,activeNodeRect:eu,containerNodeRect:eh,draggingNodeRect:ex,over:ef.current.over,overlayNodeRect:em.rect,scrollableAncestors:eb,scrollableAncestorRects:ew,windowRect:ey}),ej=el?yv(el,H):null,eC=function(e){let[r,s]=(0,$.useState)(null),n=(0,$.useRef)(e),i=(0,$.useCallback)(e=>{let r=yY(e.target);r&&s(e=>e?(e.set(r,yJ(r)),new Map(e)):null)},[]);return(0,$.useEffect)(()=>{let r=n.current;if(e!==r){a(r);let o=e.map(e=>{let r=yY(e);return r?(r.addEventListener("scroll",i,{passive:!0}),[r,yJ(r)]):null}).filter(e=>null!=e);s(o.length?new Map(o):null),n.current=e}return()=>{a(e),a(r)};function a(e){e.forEach(e=>{let r=yY(e);null==r||r.removeEventListener("scroll",i)})}},[i,e]),(0,$.useMemo)(()=>e.length?r?Array.from(r.values()).reduce((e,r)=>yv(e,r),yM):y1(e):yM,[e,r])}(eb),ek=bf(eC),eN=bf(eC,[eu]),eE=yv(eS,ek),eD=ex?yW(ex,eS):null,eR=V&&eD?S({active:V,collisionRect:eD,droppableRects:en,droppableContainers:er,pointerCoordinates:ej}):null,eA=yL(eR,"id"),[eT,eM]=(0,$.useState)(null),eF=(l=ev?eS:yv(eS,eN),c=null!=(i=null==eT?void 0:eT.rect)?i:null,{...l,scaleX:c&&eu?c.width/eu.width:1,scaleY:c&&eu?c.height/eu.height:1}),eP=(0,$.useRef)(null),eI=(0,$.useCallback)((e,r)=>{let{sensor:s,options:n}=r;if(null==Y.current)return;let i=W.get(Y.current);if(!i)return;let a=e.nativeEvent,o=new s({active:Y.current,activeNode:i,event:a,options:n,context:ef,onAbort(e){if(!W.get(e))return;let{onDragAbort:r}=Q.current,s={id:e};null==r||r(s),A({type:"onDragAbort",event:s})},onPending(e,r,s,n){if(!W.get(e))return;let{onDragPending:i}=Q.current,a={id:e,constraint:r,initialCoordinates:s,offset:n};null==i||i(a),A({type:"onDragPending",event:a})},onStart(e){let r=Y.current;if(null==r)return;let s=W.get(r);if(!s)return;let{onDragStart:n}=Q.current,i={activatorEvent:a,active:{id:r,data:s.data,rect:K}};(0,ee.unstable_batchedUpdates)(()=>{null==n||n(i),L(B.Initializing),R({type:E.DragStart,initialCoordinates:e,active:r}),A({type:"onDragStart",event:i}),X(eP.current),Z(a)})},onMove(e){R({type:E.DragMove,coordinates:e})},onEnd:l(E.DragEnd),onCancel:l(E.DragCancel)});function l(e){return async function(){let{active:r,collisions:s,over:n,scrollAdjustedTranslate:i}=ef.current,o=null;if(r&&i){let{cancelDrop:l}=Q.current;o={activatorEvent:a,active:r,collisions:s,delta:i,over:n},e===E.DragEnd&&"function"==typeof l&&await Promise.resolve(l(o))&&(e=E.DragCancel)}Y.current=null,(0,ee.unstable_batchedUpdates)(()=>{R({type:e}),L(B.Uninitialized),eM(null),X(null),Z(null),eP.current=null;let r=e===E.DragEnd?"onDragEnd":"onDragCancel";if(o){let e=Q.current[r];null==e||e(o),A({type:r,event:o})}})}}eP.current=o},[W]),eB=(0,$.useCallback)((e,r)=>(s,n)=>{let i=s.nativeEvent,a=W.get(n);null!==Y.current||!a||i.dndKit||i.defaultPrevented||!0===e(s,r.options,{active:a})&&(i.dndKit={capturedBy:r.sensor},Y.current=n,eI(s,r))},[W,eI]),eL=(0,$.useMemo)(()=>w.reduce((e,r)=>{let{sensor:s}=r;return[...e,...s.activators.map(e=>({eventName:e.eventName,handler:eB(e.handler,r)}))]},[]),[w,eB]);(0,$.useEffect)(()=>{if(!yt)return;let e=w.map(e=>{let{sensor:r}=e;return null==r.setup?void 0:r.setup()});return()=>{for(let r of e)null==r||r()}},w.map(e=>{let{sensor:r}=e;return r})),yc(()=>{eu&&I===B.Initializing&&L(B.Initialized)},[eu,I]),(0,$.useEffect)(()=>{let{onDragMove:e}=Q.current,{active:r,activatorEvent:s,collisions:n,over:i}=ef.current;if(!r||!s)return;let a={active:r,activatorEvent:s,collisions:n,delta:{x:eE.x,y:eE.y},over:i};(0,ee.unstable_batchedUpdates)(()=>{null==e||e(a),A({type:"onDragMove",event:a})})},[eE.x,eE.y]),(0,$.useEffect)(()=>{let{active:e,activatorEvent:r,collisions:s,droppableContainers:n,scrollAdjustedTranslate:i}=ef.current;if(!e||null==Y.current||!r||!i)return;let{onDragOver:a}=Q.current,o=n.get(eA),l=o&&o.rect.current?{id:o.id,rect:o.rect.current,data:o.data,disabled:o.disabled}:null,c={active:e,activatorEvent:r,collisions:s,delta:{x:i.x,y:i.y},over:l};(0,ee.unstable_batchedUpdates)(()=>{eM(l),null==a||a(c),A({type:"onDragOver",event:c})})},[eA]),yc(()=>{ef.current={activatorEvent:J,active:V,activeNode:eo,collisionRect:eD,collisions:eR,droppableRects:en,draggableNodes:W,draggingNode:eg,draggingNodeRect:ex,droppableContainers:U,over:eT,scrollableAncestors:eb,scrollAdjustedTranslate:eE},K.current={initial:ex,translated:eD}},[V,eo,eR,eD,W,eg,ex,en,U,eT,eb,eE]),function(e){let r,{acceleration:s,activator:n=M.Pointer,canScroll:i,draggingRect:a,enabled:o,interval:l=5,order:c=F.TreeOrder,pointerCoordinates:d,scrollableAncestors:u,scrollableAncestorRects:h,delta:f,threshold:p}=e,m=function(e){let{delta:r,disabled:s}=e,n=yp(r);return yh(e=>{if(s||!n||!e)return ba;let i={x:Math.sign(r.x-n.x),y:Math.sign(r.y-n.y)};return{x:{[D.Backward]:e.x[D.Backward]||-1===i.x,[D.Forward]:e.x[D.Forward]||1===i.x},y:{[D.Backward]:e.y[D.Backward]||-1===i.y,[D.Forward]:e.y[D.Forward]||1===i.y}}},[s,r,n])}({delta:f,disabled:!o}),[g,x]=(r=(0,$.useRef)(null),[(0,$.useCallback)((e,s)=>{r.current=setInterval(e,s)},[]),(0,$.useCallback)(()=>{null!==r.current&&(clearInterval(r.current),r.current=null)},[])]),v=(0,$.useRef)({x:0,y:0}),_=(0,$.useRef)({x:0,y:0}),y=(0,$.useMemo)(()=>{switch(n){case M.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case M.DraggableRect:return a}},[n,a,d]),b=(0,$.useRef)(null),w=(0,$.useCallback)(()=>{let e=b.current;if(!e)return;let r=v.current.x*_.current.x,s=v.current.y*_.current.y;e.scrollBy(r,s)},[]),S=(0,$.useMemo)(()=>c===F.TreeOrder?[...u].reverse():u,[c,u]);(0,$.useEffect)(()=>{if(!o||!u.length||!y)return void x();for(let e of S){if((null==i?void 0:i(e))===!1)continue;let r=h[u.indexOf(e)];if(!r)continue;let{direction:n,speed:a}=function(e,r,s,n,i){let{top:a,left:o,right:l,bottom:c}=s;void 0===n&&(n=10),void 0===i&&(i=y0);let{isTop:d,isBottom:u,isLeft:h,isRight:f}=yQ(e),p={x:0,y:0},m={x:0,y:0},g={height:r.height*i.y,width:r.width*i.x};return!d&&a<=r.top+g.height?(p.y=D.Backward,m.y=n*Math.abs((r.top+g.height-a)/g.height)):!u&&c>=r.bottom-g.height&&(p.y=D.Forward,m.y=n*Math.abs((r.bottom-g.height-c)/g.height)),!f&&l>=r.right-g.width?(p.x=D.Forward,m.x=n*Math.abs((r.right-g.width-l)/g.width)):!h&&o<=r.left+g.width&&(p.x=D.Backward,m.x=n*Math.abs((r.left+g.width-o)/g.width)),{direction:p,speed:m}}(e,r,y,s,p);for(let e of["x","y"])m[e][n[e]]||(a[e]=0,n[e]=0);if(a.x>0||a.y>0){x(),b.current=e,g(w,l),v.current=a,_.current=n;return}}v.current={x:0,y:0},_.current={x:0,y:0},x()},[s,w,i,x,o,l,JSON.stringify(y),JSON.stringify(m),g,u,S,h,JSON.stringify(p)])}({...ec,delta:H,draggingRect:eD,pointerCoordinates:ej,scrollableAncestors:eb,scrollableAncestorRects:ew});let ez=(0,$.useMemo)(()=>({active:V,activeNode:eo,activeNodeRect:eu,activatorEvent:J,collisions:eR,containerNodeRect:eh,dragOverlay:em,draggableNodes:W,droppableContainers:U,droppableRects:en,over:eT,measureDroppableContainers:ei,scrollableAncestors:eb,scrollableAncestorRects:ew,measuringConfiguration:es,measuringScheduled:ea,windowRect:ey}),[V,eo,eu,J,eR,eh,em,W,U,en,eT,ei,eb,ew,es,ea,ey]),eO=(0,$.useMemo)(()=>({activatorEvent:J,activators:eL,active:V,activeNodeRect:eu,ariaDescribedById:{draggable:et},dispatch:R,draggableNodes:W,over:eT,measureDroppableContainers:ei}),[J,eL,V,eu,R,et,W,eT,ei]);return $.default.createElement(yN.Provider,{value:T},$.default.createElement(bw.Provider,{value:eO},$.default.createElement(bS.Provider,{value:ez},$.default.createElement(bN.Provider,{value:eF},b)),$.default.createElement(bk,{disabled:(null==_?void 0:_.restoreFocus)===!1})),$.default.createElement(yR,{..._,hiddenTextDescribedById:et}))}),bD=(0,$.createContext)(null),bR="button",bA={timeout:25},bT={position:"fixed",touchAction:"none"},bM=e=>yy(e)?"transform 250ms ease":void 0;function bF(e,r,s){let n=e.slice();return n.splice(s<0?n.length+s:s,0,n.splice(r,1)[0]),n}function bP(e){return null!==e&&e>=0}(e,r)=>{let{as:s,activatorEvent:n,adjustScale:i,children:a,className:o,rect:l,style:c,transform:d,transition:u=bM}=e;if(!l)return null;let h=i?d:{...d,scaleX:1,scaleY:1},f={...bT,width:l.width,height:l.height,top:l.top,left:l.left,transform:yw.Transform.toString(h),transformOrigin:i&&n?function(e,r){let s=yb(e);if(!s)return"0 0";let n={x:(s.x-r.left)/r.width*100,y:(s.y-r.top)/r.height*100};return n.x+"% "+n.y+"%"}(n,l):void 0,transition:"function"==typeof u?u(n):u,...c};return $.default.createElement(s,{className:o,style:f,ref:r},a)},x={styles:{active:{opacity:"0"}}};let bI=e=>{let{rects:r,activeIndex:s,overIndex:n,index:i}=e,a=bF(r,n,s),o=r[i],l=a[i];return l&&o?{x:l.left-o.left,y:l.top-o.top,scaleX:l.width/o.width,scaleY:l.height/o.height}:null},bB={scaleX:1,scaleY:1},bL=e=>{var r,s,n,i;let a,o,l,{activeIndex:c,activeNodeRect:d,index:u,rects:h,overIndex:f}=e,p=null!=(r=h[c])?r:d;if(!p)return null;if(u===c){let e=h[f];return e?{x:0,y:c<f?e.top+e.height-(p.top+p.height):e.top-p.top,...bB}:null}let m=(s=h,n=u,i=c,a=s[n],o=s[n-1],l=s[n+1],a?i<n?o?a.top-(o.top+o.height):l?l.top-(a.top+a.height):0:l?l.top-(a.top+a.height):o?a.top-(o.top+o.height):0:0);return u>c&&u<=f?{x:0,y:-p.height-m,...bB}:u<c&&u>=f?{x:0,y:p.height+m,...bB}:{x:0,y:0,...bB}},bz="Sortable",bO=$.default.createContext({activeIndex:-1,containerId:bz,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:bI,disabled:{draggable:!1,droppable:!1}});function b$(e){let{children:r,id:s,items:n,strategy:i=bI,disabled:a=!1}=e,{active:o,dragOverlay:l,droppableRects:c,over:d,measureDroppableContainers:u}=(0,$.useContext)(bS),h=yg(bz,s),f=null!==l.rect,p=(0,$.useMemo)(()=>n.map(e=>"object"==typeof e&&"id"in e?e.id:e),[n]),m=null!=o,g=o?p.indexOf(o.id):-1,x=d?p.indexOf(d.id):-1,v=(0,$.useRef)(p),_=!function(e,r){if(e===r)return!0;if(e.length!==r.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==r[s])return!1;return!0}(p,v.current),y=-1!==x&&-1===g||_,b="boolean"==typeof a?{draggable:a,droppable:a}:a;yc(()=>{_&&m&&u(p)},[_,p,m,u]),(0,$.useEffect)(()=>{v.current=p},[p]);let w=(0,$.useMemo)(()=>({activeIndex:g,containerId:h,disabled:b,disableTransforms:y,items:p,overIndex:x,useDragOverlay:f,sortedRects:p.reduce((e,r,s)=>{let n=c.get(r);return n&&(e[s]=n),e},Array(p.length)),strategy:i}),[g,h,b.draggable,b.droppable,y,p,x,c,f,i]);return $.default.createElement(bO.Provider,{value:w},r)}let bW=e=>{let{id:r,items:s,activeIndex:n,overIndex:i}=e;return bF(s,n,i).indexOf(r)},bH=e=>{let{containerId:r,isSorting:s,wasDragging:n,index:i,items:a,newIndex:o,previousItems:l,previousContainerId:c,transition:d}=e;return!!d&&!!n&&(l===a||i!==o)&&(!!s||o!==i&&r===c)},bU={duration:200,easing:"ease"},bq="transform",bK=yw.Transition.toString({property:bq,duration:0,easing:"linear"}),bV={roleDescription:"sortable"};function bY(e){if(!e)return!1;let r=e.data.current;return!!r&&"sortable"in r&&"object"==typeof r.sortable&&"containerId"in r.sortable&&"items"in r.sortable&&"index"in r.sortable}let bG=[A.Down,A.Right,A.Up,A.Left],bX=(e,r)=>{let{context:{active:s,collisionRect:n,droppableRects:i,droppableContainers:a,over:o,scrollableAncestors:l}}=r;if(bG.includes(e.code)){if(e.preventDefault(),!s||!n)return;let r=[];a.getEnabled().forEach(s=>{if(!s||null!=s&&s.disabled)return;let a=i.get(s.id);if(a)switch(e.code){case A.Down:n.top<a.top&&r.push(s);break;case A.Up:n.top>a.top&&r.push(s);break;case A.Left:n.left>a.left&&r.push(s);break;case A.Right:n.left<a.left&&r.push(s)}});let u=(e=>{let{collisionRect:r,droppableRects:s,droppableContainers:n}=e,i=yB(r),a=[];for(let e of n){let{id:r}=e,n=s.get(r);if(n){let s=yB(n),o=Number((i.reduce((e,r,n)=>e+yF(s[n],r),0)/4).toFixed(4));a.push({id:r,data:{droppableContainer:e,value:o}})}}return a.sort(yP)})({active:s,collisionRect:n,droppableRects:i,droppableContainers:r,pointerCoordinates:null}),h=yL(u,"id");if(h===(null==o?void 0:o.id)&&u.length>1&&(h=u[1].id),null!=h){let e=a.get(s.id),r=a.get(h),o=r?i.get(r.id):null,u=null==r?void 0:r.node.current;if(u&&o&&e&&r){var c,d;let s=yK(u).some((e,r)=>l[r]!==e),i=bJ(e,r),a=(c=e,d=r,!!bY(c)&&!!bY(d)&&!!bJ(c,d)&&c.data.current.sortable.index<d.data.current.sortable.index),h=s||!i?{x:0,y:0}:{x:a?n.width-o.width:0,y:a?n.height-o.height:0},f={x:o.left,y:o.top};return h.x&&h.y?f:y_(f,h)}}}};function bJ(e,r){return!!bY(e)&&!!bY(r)&&e.data.current.sortable.containerId===r.data.current.sortable.containerId}function bZ({executor:e,executorMode:r,isOpen:s,onOpenChange:n,onStart:i,onStop:a,onUpdate:o,onDelete:l,onProcessFinished:c}){let d,u,h,f,p,m,g,[x,v]=(0,$.useState)(!1),[_,y]=(0,$.useState)(e.currentProcessId??e.lastProcessId),b=(0,$.useRef)(!1),w=(0,$.useRef)(e.currentProcessId),{attributes:S,listeners:j,setNodeRef:C,transform:k,transition:N,isDragging:D}=function(e){var r,s,n,i;let{animateLayoutChanges:a=bH,attributes:o,disabled:l,data:c,getNewIndex:d=bW,id:u,strategy:h,resizeObserverConfig:f,transition:p=bU}=e,{items:m,containerId:g,activeIndex:x,disabled:v,disableTransforms:_,sortedRects:y,overIndex:b,useDragOverlay:w,strategy:S}=(0,$.useContext)(bO),j=(r=l,s=v,"boolean"==typeof r?{draggable:r,droppable:!1}:{draggable:null!=(n=null==r?void 0:r.draggable)?n:s.draggable,droppable:null!=(i=null==r?void 0:r.droppable)?i:s.droppable}),C=m.indexOf(u),k=(0,$.useMemo)(()=>({sortable:{containerId:g,index:C,items:m},...c}),[g,c,C,m]),N=(0,$.useMemo)(()=>m.slice(m.indexOf(u)),[m,u]),{rect:D,node:R,isOver:A,setNodeRef:T}=function(e){let{data:r,disabled:s=!1,id:n,resizeObserverConfig:i}=e,a=yg("Droppable"),{active:o,dispatch:l,over:c,measureDroppableContainers:d}=(0,$.useContext)(bw),u=(0,$.useRef)({disabled:s}),h=(0,$.useRef)(!1),f=(0,$.useRef)(null),p=(0,$.useRef)(null),{disabled:m,updateMeasurementsFor:g,timeout:x}={...bA,...i},v=yu(null!=g?g:n),_=bc({callback:(0,$.useCallback)(()=>{if(!h.current){h.current=!0;return}null!=p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{d(Array.isArray(v.current)?v.current:[v.current]),p.current=null},x)},[x]),disabled:m||!o}),[y,b]=yf((0,$.useCallback)((e,r)=>{_&&(r&&(_.unobserve(r),h.current=!1),e&&_.observe(e))},[_])),w=yu(r);return(0,$.useEffect)(()=>{_&&y.current&&(_.disconnect(),h.current=!1,_.observe(y.current))},[y,_]),(0,$.useEffect)(()=>(l({type:E.RegisterDroppable,element:{id:n,key:a,disabled:s,node:y,rect:f,data:w}}),()=>l({type:E.UnregisterDroppable,key:a,id:n})),[n]),(0,$.useEffect)(()=>{s!==u.current.disabled&&(l({type:E.SetDroppableDisabled,id:n,key:a,disabled:s}),u.current.disabled=s)},[n,a,s,l]),{active:o,rect:f,isOver:(null==c?void 0:c.id)===n,node:y,over:c,setNodeRef:b}}({id:u,data:k,disabled:j.droppable,resizeObserverConfig:{updateMeasurementsFor:N,...f}}),{active:M,activatorEvent:F,activeNodeRect:P,attributes:I,setNodeRef:B,listeners:L,isDragging:z,over:O,setActivatorNodeRef:W,transform:H}=function(e){let{id:r,data:s,disabled:n=!1,attributes:i}=e,a=yg("Draggable"),{activators:o,activatorEvent:l,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:f}=(0,$.useContext)(bw),{role:p=bR,roleDescription:m="draggable",tabIndex:g=0}=null!=i?i:{},x=(null==c?void 0:c.id)===r,v=(0,$.useContext)(x?bN:bD),[_,y]=yf(),[b,w]=yf(),S=(0,$.useMemo)(()=>o.reduce((e,s)=>{let{eventName:n,handler:i}=s;return e[n]=e=>{i(e,r)},e},{}),[o,r]),j=yu(s);return yc(()=>(h.set(r,{id:r,key:a,node:_,activatorNode:b,data:j}),()=>{let e=h.get(r);e&&e.key===a&&h.delete(r)}),[h,r]),{active:c,activatorEvent:l,activeNodeRect:d,attributes:(0,$.useMemo)(()=>({role:p,tabIndex:g,"aria-disabled":n,"aria-pressed":!!x&&p===bR||void 0,"aria-roledescription":m,"aria-describedby":u.draggable}),[n,p,g,x,m,u.draggable]),isDragging:x,listeners:n?void 0:S,node:_,over:f,setNodeRef:y,setActivatorNodeRef:w,transform:v}}({id:u,data:k,attributes:{...bV,...o},disabled:j.draggable}),U=function(){for(var e=arguments.length,r=Array(e),s=0;s<e;s++)r[s]=arguments[s];return(0,$.useMemo)(()=>e=>{r.forEach(r=>r(e))},r)}(T,B),q=!!M,K=q&&!_&&bP(x)&&bP(b),V=!w&&z,Y=V&&K?H:null,G=K?null!=Y?Y:(null!=h?h:S)({rects:y,activeNodeRect:P,activeIndex:x,overIndex:b,index:C}):null,X=bP(x)&&bP(b)?d({id:u,items:m,activeIndex:x,overIndex:b}):C,J=null==M?void 0:M.id,Z=(0,$.useRef)({activeId:J,items:m,newIndex:X,containerId:g}),Q=m!==Z.current.items,ee=a({active:M,containerId:g,isDragging:z,isSorting:q,id:u,index:C,items:m,newIndex:Z.current.newIndex,previousItems:Z.current.items,previousContainerId:Z.current.containerId,transition:p,wasDragging:null!=Z.current.activeId}),et=function(e){let{disabled:r,index:s,node:n,rect:i}=e,[a,o]=(0,$.useState)(null),l=(0,$.useRef)(s);return yc(()=>{if(!r&&s!==l.current&&n.current){let e=i.current;if(e){let r=yU(n.current,{ignoreTransform:!0}),s={x:e.left-r.left,y:e.top-r.top,scaleX:e.width/r.width,scaleY:e.height/r.height};(s.x||s.y)&&o(s)}}s!==l.current&&(l.current=s)},[r,s,n,i]),(0,$.useEffect)(()=>{a&&o(null)},[a]),a}({disabled:!ee,index:C,node:R,rect:D});return(0,$.useEffect)(()=>{q&&Z.current.newIndex!==X&&(Z.current.newIndex=X),g!==Z.current.containerId&&(Z.current.containerId=g),m!==Z.current.items&&(Z.current.items=m)},[q,X,g,m]),(0,$.useEffect)(()=>{if(J===Z.current.activeId)return;if(null!=J&&null==Z.current.activeId){Z.current.activeId=J;return}let e=setTimeout(()=>{Z.current.activeId=J},50);return()=>clearTimeout(e)},[J]),{active:M,activeIndex:x,attributes:I,data:k,rect:D,index:C,newIndex:X,items:m,isOver:A,isSorting:q,isDragging:z,listeners:L,node:R,overIndex:b,over:O,setNodeRef:U,setActivatorNodeRef:W,setDroppableNodeRef:T,setDraggableNodeRef:B,transform:null!=et?et:G,transition:et||Q&&Z.current.newIndex===C?bK:(!V||yy(F))&&p&&(q||ee)?yw.Transition.toString({...p,property:bq}):void 0}}({id:e.id}),R={transform:yw.Translate.toString(k),transition:N,zIndex:D?50:void 0,position:D?"relative":void 0,opacity:D?1:void 0},{logs:A,status:T,exitCode:M,isPty:F,replayingHistory:P,sendInput:I,sendResize:B}=(d=function(){let e=(0,$.useContext)(_9);if(!e)throw Error("useExecutorLogsStore must be used within ExecutorLogsProvider");return e}(),u=(0,$.useCallback)(e=>{if(!_)return()=>{};d.subscribeProcess(_);let r=d.onProcessChange(_,e);return()=>{r(),d.unsubscribeProcess(_)}},[_,r,d]),h=(0,$.useCallback)(()=>_?d.getProcessState(_):null,[_,d]),f=(0,$.useSyncExternalStore)(u,h,h),p=(0,$.useCallback)(()=>{},[]),m=(0,$.useCallback)(e=>{_&&d.sendInput(_,e)},[_,d]),g=(0,$.useCallback)((e,r)=>{_&&d.sendResize(_,e,r)},[_,d]),{logs:f?.logs??[],status:f?.status??"closed",exitCode:f?.exitCode??null,isPty:f?.isPty??!1,replayingHistory:f?.replayingHistory??!0,clearLogs:p,sendInput:m,sendResize:g});(0,$.useEffect)(()=>(console.log("[diag:mux] ExecutorItem MOUNT",e.id,"localProcessId=",_),()=>console.log("[diag:mux] ExecutorItem UNMOUNT",e.id)),[]),(0,$.useEffect)(()=>{console.log("[diag:mux] localProcessId →",_,"executor=",e.id)},[_,e.id]),(0,$.useEffect)(()=>{let r=w.current;w.current=e.currentProcessId,e.currentProcessId&&e.currentProcessId!==r&&(y(e.currentProcessId),b.current=!1,n(!0))},[e.currentProcessId,n]),(0,$.useEffect)(()=>{e.currentProcessId||e.lastProcessId&&y(r=>r??e.lastProcessId)},[e.currentProcessId,e.lastProcessId]),(0,$.useEffect)(()=>{"closed"!==T||null===M||b.current||(b.current=!0,console.log(`[diag:remote-stop] ${new Date().toISOString()} executor-item marking finished executorId=${e.id} processId=${_} exitCode=${M} — removing from runningProcesses (button → Start)`),c(_))},[T,M,_,c]);let L=async()=>{console.log(`[ExecutorItem] Starting executor ${e.id}`),b.current=!1;let r=await i();console.log(`[ExecutorItem] Got processId: ${r}`),r&&(y(r),n(!0))},z=async()=>{await a(_||void 0)},H=e.isRunning,U=e.isDisabled,q=e.lastStartedAt?new Date(e.lastStartedAt).toLocaleString(void 0,{dateStyle:"short",timeStyle:"short"}):null;return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(pr,{open:s,onOpenChange:n,children:(0,O.jsxs)("div",{ref:C,style:R,className:(0,ey.cn)("border rounded-lg",D&&"shadow-lg bg-background"),children:[(0,O.jsx)(ps,{asChild:!0,children:(0,O.jsxs)("div",{className:"group flex items-center justify-between p-3 cursor-pointer hover:bg-muted/50",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)("button",{type:"button",className:"cursor-grab touch-none text-muted-foreground hover:text-foreground",...S,...j,onClick:e=>e.stopPropagation(),children:(0,O.jsx)(dm,{className:"h-4 w-4"})}),s?(0,O.jsx)(ns,{className:"h-4 w-4"}):(0,O.jsx)(a3,{className:"h-4 w-4"}),(0,O.jsx)("span",{className:(0,ey.cn)("font-medium",U&&"text-muted-foreground line-through"),children:e.name}),U?(0,O.jsxs)(sa,{variant:"outline",className:"text-muted-foreground border-muted-foreground/40 gap-1",children:[(0,O.jsx)(pa,{className:"h-3 w-3"}),"Disabled"]}):(0,O.jsx)(sa,{variant:H?"default":"secondary",className:(0,ey.cn)(H&&"bg-green-600 hover:bg-green-600"),children:H?"Running":null!==M?0===M?"Completed":"Failed":"Stopped"})]}),(0,O.jsxs)("div",{className:"flex items-center gap-2",onClick:e=>e.stopPropagation(),children:[q&&(0,O.jsxs)("span",{className:"text-xs text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity",title:new Date(e.lastStartedAt).toLocaleString(),children:["Last run: ",q]}),H?(0,O.jsxs)(W.Button,{size:"sm",variant:"destructive",onClick:z,className:"w-20 border border-destructive",children:[(0,O.jsx)(lJ,{className:"h-3 w-3 mr-1"}),"Stop"]}):(0,O.jsxs)(W.Button,{size:"sm",onClick:L,disabled:U,title:U?"Executor is disabled":void 0,className:"w-20",children:[(0,O.jsx)(rh,{className:"h-3 w-3 mr-1"}),"Start"]}),(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)(W.Button,{size:"icon",variant:"ghost",className:"h-8 w-8",children:(0,O.jsx)(pi,{className:"h-4 w-4"})})}),(0,O.jsxs)(a7,{align:"end",children:[(0,O.jsxs)(a8,{onClick:()=>v(!0),children:[(0,O.jsx)(rg,{className:"h-4 w-4 mr-2"}),"Edit"]}),(0,O.jsx)(a8,{onClick:()=>o({target:r??"local",disabled:!U}),children:U?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(sJ,{className:"h-4 w-4 mr-2"}),"Enable"]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(pa,{className:"h-4 w-4 mr-2"}),"Disable"]})}),(0,O.jsxs)(a8,{onClick:l,className:"text-destructive",children:[(0,O.jsx)(rc,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})]})}),(0,O.jsx)(pn,{children:(0,O.jsxs)("div",{className:"px-3 pb-3",children:[(0,O.jsx)("div",{className:"text-xs text-muted-foreground mb-2 font-mono",children:"prompt"===e.executor_type?`${e.prompt_provider??"claude"} → ${e.command}`:`$ ${e.command}`}),(0,O.jsx)(_4,{logs:A,isPty:F,onInput:I,onResize:B,muteInput:P,processId:_,executorId:e.id,target:r??"local",status:T,exitCode:M})]})})]})}),(0,O.jsx)(_7,{open:x,onOpenChange:v,executor:e,onSubmit:async e=>{await o(e)}})]})}let bQ=(0,$.createContext)(null);function b0({projectId:e,children:r}){let s=sg(e,{withStatus:!0});return(0,O.jsx)(bQ.Provider,{value:s,children:r})}function b1(){let e=(0,$.useContext)(bQ);if(!e)throw Error("useProjectRemotesContext must be used within a ProjectRemotesProvider");return e}let b2=e=>{let{droppableContainers:r,pointerCoordinates:s}=e;if(!s)return(e=>{let{collisionRect:r,droppableRects:s,droppableContainers:n}=e,i=yz(r,r.left,r.top),a=[];for(let e of n){let{id:r}=e,n=s.get(r);if(n){let s=yF(yz(n),i);a.push({id:r,data:{droppableContainer:e,value:s}})}}return a.sort(yP)})(e);let n=[];for(let e of r){let r=e.rect.current;if(!r)continue;let i=r.top,a=r.top+52;s.x>=r.left&&s.x<=r.right&&s.y>=i&&s.y<=a&&n.push({id:e.id,data:{droppableContainer:e}})}if(n.length>0)return n;let i=null;for(let e of r){let r=e.rect.current;if(!r)continue;let n=r.top+26,a=r.left+r.width/2,o=Math.sqrt(Math.pow(s.x-a,2)+Math.pow(s.y-n,2));(!i||o<i.distance)&&(i={id:e.id,distance:o,data:{droppableContainer:e}})}return i?[{id:i.id,data:i.data}]:[]};function b5({projectId:e,selectedBranch:r,project:s,onExecutorModeChange:n}){let[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(new Set),{remotes:c}=b1(),d=[];for(let e of(s?.path&&d.push({id:"local",label:"Local",icon:oc}),c))d.push({id:e.remote_server_id,label:e.server_name,icon:sx(e)});let{executors:u,loading:h,createExecutor:f,updateExecutor:p,deleteExecutor:m,startExecutor:g,stopExecutor:x,markProcessFinished:v,reorderExecutors:_}=function(e,r,s){let n=r??"",[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)(new Map),[c,d]=(0,$.useState)(new Map),[u,h]=(0,$.useState)(!0),f=(0,$.useCallback)(async()=>{if(!e){a([]),h(!1);return}try{let r=await rv.api.getExecutors(e,n);a(r)}catch(e){console.error("Failed to fetch executors:",e)}finally{h(!1)}},[e,n]),p=(0,$.useCallback)(async()=>{try{let e=await rv.api.getRunningProcesses();console.log(`[useExecutors] fetchRunningProcesses: ${e.length} running`,e.map(e=>`${e.executor_id}/${e.id}/${e.target??"local"}`));let{runningProcesses:r,lastStartedProcess:s}=function(e){let r=new Map,s=new Map;for(let n of e){let e={processId:n.id,target:n.target??"local"},i=r.get(n.executor_id);i?i.push(e):r.set(n.executor_id,[e]),s.set(n.executor_id,e)}return{runningProcesses:r,lastStartedProcess:s}}(e);l(r),d(e=>{let n=function(e,r){let s=new Map;for(let[n,i]of e)r.get(n)?.some(e=>e.processId===i.processId&&e.target===i.target)&&s.set(n,i);return s}(e,r);for(let[e,r]of s)n.set(e,r);return n})}catch(e){console.error("Failed to fetch running processes:",e)}},[]);(0,$.useEffect)(()=>{f()},[f]),(0,$.useEffect)(()=>{p()},[p]),(0,$.useEffect)(()=>{e&&p()},[e,p]),(0,$.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&p()};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[p]);let m=(0,$.useRef)(new Set);(0,$.useEffect)(()=>{m.current=new Set(i.map(e=>e.id))},[i]),(0,sC.useGlobalEventStream)(r=>{if(("executor:started"===r.type||"executor:stopped"===r.type)&&console.log(`[useExecutors] SSE received: ${r.type} executor=${r.executorId} process=${r.processId} target=${r.target??"local"} project=${r.projectId}`),!e||r.projectId!==e){("executor:started"===r.type||"executor:stopped"===r.type)&&console.log(`[useExecutors] SSE filtered: projectId mismatch (event=${r.projectId}, hook=${e})`);return}if(!m.current.has(r.executorId)){("executor:started"===r.type||"executor:stopped"===r.type)&&console.log(`[useExecutors] SSE filtered: executorId ${r.executorId} not in current group (known: ${Array.from(m.current).join(",")})`);return}"executor:started"===r.type?(console.log("[useExecutors] Processing executor:started, adding to runningProcesses"),l(e=>{let s=e.get(r.executorId)??[];if(s.some(e=>e.processId===r.processId))return e;let n=new Map(e);return n.set(r.executorId,[...s,{processId:r.processId,target:r.target??"local"}]),n}),d(e=>{let s=new Map(e);return s.set(r.executorId,{processId:r.processId,target:r.target??"local"}),s}),a(e=>e.map(e=>{if(e.id!==r.executorId)return e;let s=r.target??"local";return{...e,last_runs:{...e.last_runs??{},[s]:{started_at:new Date().toISOString(),process_id:r.processId}}}}))):"executor:stopped"===r.type&&(console.log("[useExecutors] Processing executor:stopped, removing from runningProcesses"),console.log(`[diag:remote-stop] ${new Date().toISOString()} SSE executor:stopped executor=${r.executorId} process=${r.processId} target=${r.target??"local"} — flips button via SSE (NOT the mux finished path)`),l(e=>{let s=e.get(r.executorId);if(!s)return e;let n=s.filter(e=>e.processId!==r.processId),i=new Map(e);return 0===n.length?i.delete(r.executorId):i.set(r.executorId,n),i}),d(e=>{let s=e.get(r.executorId);if(!s||s.processId!==r.processId)return e;let n=new Map(e);return n.delete(r.executorId),n}))});let g=(0,$.useCallback)(async r=>{if(!e)return null;try{let s=await rv.api.createExecutor(e,{...r,branch:n});return a(e=>[...e,s]),s}catch(e){return console.error("Failed to create executor:",e),null}},[e,n]),x=(0,$.useCallback)(async(e,r)=>{try{let s=await rv.api.updateExecutor(e,r);return a(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update executor:",e),_Z.toast.error("Failed to update executor",{description:e instanceof Error?e.message:void 0}),null}},[]),v=(0,$.useCallback)(async e=>{try{await rv.api.deleteExecutor(e),a(r=>r.filter(r=>r.id!==e))}catch(e){console.error("Failed to delete executor:",e)}},[]),_=(0,$.useCallback)(async e=>{try{let r=await rv.api.startExecutor(e,s),n=s??"local";return l(s=>{let i=s.get(e)??[],a=new Map(s);return a.set(e,[...i,{processId:r,target:n}]),a}),d(s=>{let i=new Map(s);return i.set(e,{processId:r,target:n}),i}),a(s=>s.map(s=>s.id!==e?s:{...s,last_runs:{...s.last_runs??{},[n]:{started_at:new Date().toISOString(),process_id:r}}})),r}catch(e){return console.error("Failed to start executor:",e),null}},[s]),y=(0,$.useCallback)(async(e,r)=>{let n=o.get(e),i=n?.find(e=>e.target===(s??"local")),a=r||i?.processId;if(a){try{await rv.api.stopProcess(a)}catch(e){console.error("Failed to stop executor:",e)}l(r=>{let s=r.get(e);if(!s)return r;let n=s.filter(e=>e.processId!==a),i=new Map(r);return 0===n.length?i.delete(e):i.set(e,n),i}),d(r=>{let s=r.get(e);if(!s||s.processId!==a)return r;let n=new Map(r);return n.delete(e),n})}},[o,s]),b=(0,$.useCallback)((e,r)=>{l(s=>{let n=s.get(e);if(!n)return s;if(r){let i=n.filter(e=>e.processId!==r);if(i.length===n.length)return s;let a=new Map(s);return 0===i.length?a.delete(e):a.set(e,i),a}let i=new Map(s);return i.delete(e),i}),d(s=>{if(!r){if(!s.has(e))return s;let r=new Map(s);return r.delete(e),r}let n=s.get(e);if(!n||n.processId!==r)return s;let i=new Map(s);return i.delete(e),i})},[]),w=(0,$.useCallback)(async r=>{if(e){a(r.map(e=>i.find(r=>r.id===e)).filter(e=>void 0!==e));try{await rv.api.reorderExecutors(e,r,n)}catch(e){console.error("Failed to reorder executors:",e),a(i)}}},[e,n,i]);return{executors:i.map(e=>{let r=o.get(e.id),n=s??"local",i=r?.find(e=>e.target===n),a=c.get(e.id),l=a?.target===n?a:void 0,d=e.last_runs?.[n];return{...e,currentProcessId:i?.processId??l?.processId??null,isRunning:!!i,lastProcessId:d?.process_id??null,lastStartedAt:d?.started_at??null,isDisabled:e.disabled_targets.includes(n)}}),loading:u,createExecutor:g,updateExecutor:x,deleteExecutor:v,startExecutor:_,stopExecutor:y,markProcessFinished:b,reorderExecutors:w,refetch:f}}(e,r,s?.executor_mode),y=function(){for(var e=arguments.length,r=Array(e),s=0;s<e;s++)r[s]=arguments[s];return(0,$.useMemo)(()=>[...r].filter(e=>null!=e),[...r])}(yT(bi,{activationConstraint:{distance:8}}),yT(be,{coordinateGetter:bX}));return e?(0,O.jsx)(ye,{projectId:e,children:(0,O.jsxs)("div",{className:"h-full flex flex-col",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border/60 h-10",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsxs)("h2",{className:"text-xs font-semibold flex items-center gap-2 text-foreground",children:[(0,O.jsx)(ol,{className:"h-3.5 w-3.5"}),"Executors"]}),d.length>1&&n&&(0,O.jsx)(oo,{targets:d,activeTarget:s?.executor_mode??"local",onTargetChange:n})]}),(0,O.jsxs)(W.Button,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>a(!0),children:[(0,O.jsx)(eS,{className:"h-3 w-3 mr-1"}),"Add"]})]}),(0,O.jsx)("div",{className:"flex-1 overflow-y-auto",children:(0,O.jsx)("div",{className:"p-4 space-y-3",children:h?(0,O.jsx)("div",{className:"text-center text-muted-foreground py-8",children:"Loading executors..."}):0===u.length?(0,O.jsxs)("div",{className:"text-center text-muted-foreground py-8",children:[(0,O.jsx)("p",{children:"No executors configured"}),(0,O.jsx)("p",{className:"text-sm mt-1",children:'Add an executor to run commands like "npm run dev"'})]}):(0,O.jsx)(bE,{sensors:y,collisionDetection:b2,onDragEnd:e=>{let{active:r,over:s}=e;if(s&&r.id!==s.id){let e=u.findIndex(e=>e.id===r.id),n=u.findIndex(e=>e.id===s.id),i=[...u],[a]=i.splice(e,1);i.splice(n,0,a),_(i.map(e=>e.id))}},children:(0,O.jsx)(b$,{items:u.map(e=>e.id),strategy:bL,children:u.map(e=>(0,O.jsx)(bZ,{executor:e,executorMode:s?.executor_mode??"local",isOpen:o.has(e.id),onOpenChange:r=>l(s=>{let n=new Set(s);return r?n.add(e.id):n.delete(e.id),n}),onStart:()=>g(e.id),onStop:r=>x(e.id,r||e.currentProcessId||void 0),onUpdate:r=>p(e.id,r),onDelete:()=>m(e.id),onProcessFinished:r=>v(e.id,r)},`${e.id}-${s?.executor_mode??"local"}`))})})})}),(0,O.jsx)(_7,{open:i,onOpenChange:a,onSubmit:async e=>{await f(e)}})]})},`${e??"none"}-${s?.executor_mode??"local"}`):(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(ol,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to manage executors"})]})})}let b3=(0,ew.default)("chevrons-up-down",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);function b4({line:e}){let r="add"===e.type?"+":"delete"===e.type?"-":" ",s="add"===e.type,n="delete"===e.type,i=s?"bg-emerald-500/[0.07]":n?"bg-rose-500/[0.07]":"",a=s?"bg-emerald-500/[0.10]":n?"bg-rose-500/[0.10]":"bg-secondary",o=s?"text-emerald-600":n?"text-rose-600":"text-muted-foreground/70";return(0,O.jsxs)("div",{className:"flex font-mono text-[11.5px] leading-[1.55]",children:[(0,O.jsx)("span",{className:(0,ey.cn)("w-9 flex-shrink-0 text-right pr-2 select-none border-r border-border/60",a,o),children:e.oldLineNo??""}),(0,O.jsx)("span",{className:(0,ey.cn)("w-9 flex-shrink-0 text-right pr-2 select-none border-r border-border/60",a,o),children:e.newLineNo??""}),(0,O.jsx)("span",{className:(0,ey.cn)("w-5 flex-shrink-0 text-center select-none",i,o),children:r}),(0,O.jsx)("span",{className:(0,ey.cn)("whitespace-pre-wrap break-all pr-4 flex-1 min-w-0 pl-2",i,(s||n)&&"text-foreground"),children:e.content})]})}let b6={modified:"bg-yellow-500/20 text-yellow-500",added:"bg-green-500/20 text-green-500",deleted:"bg-red-500/20 text-red-500",renamed:"bg-blue-500/20 text-blue-500"},b7={modified:"Modified",added:"Added",deleted:"Deleted",renamed:"Renamed"};function b8({file:e,defaultOpen:r=!0}){let[s,n]=(0,$.useState)(r);return(0,O.jsxs)(pr,{open:s,onOpenChange:n,className:"border border-border rounded-lg overflow-hidden",children:[(0,O.jsxs)(ps,{className:"flex items-center gap-2 px-4 py-2 bg-secondary border-b border-border w-full cursor-pointer hover:bg-muted transition-colors",children:[s?(0,O.jsx)(ns,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,O.jsx)(a3,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,O.jsx)("span",{className:"font-mono text-[11.5px] flex-1 min-w-0 truncate text-left text-foreground font-medium",children:e.oldPath&&"renamed"===e.status?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("span",{className:"text-muted-foreground font-normal",children:e.oldPath}),(0,O.jsx)("span",{className:"mx-2 text-muted-foreground",children:"→"}),e.path]}):e.path}),(0,O.jsx)(sa,{variant:"secondary",className:b6[e.status],children:b7[e.status]})]}),(0,O.jsx)(pn,{children:(0,O.jsx)("div",{children:e.hunks.map((e,r)=>(0,O.jsxs)("div",{children:[(0,O.jsxs)("div",{className:"px-4 py-0.5 bg-accent text-accent-foreground text-[11px] font-mono font-medium sticky top-0",children:["@@ -",e.oldStart,",",e.oldLines," +",e.newStart,",",e.newLines," @@"]}),e.lines.map((e,r)=>(0,O.jsx)(b4,{line:e},r))]},r))})})]})}let b9=(0,ew.default)("git-commit-horizontal",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]]),we="__head__",wt="__compare__";function wr({commits:e,selectedCommit:r,onSelectCommit:s,compareTarget:n,compareSelected:i,onSelectCompare:a,loading:o,disabled:l}){return(0,O.jsxs)(hw,{value:i?wt:r??we,onValueChange:e=>{e===wt?a?.():s(e===we?null:e)},disabled:l||o,children:[(0,O.jsxs)(hj,{size:"sm",className:"w-[200px]",children:[(0,O.jsx)(b9,{className:"h-3.5 w-3.5 shrink-0"}),(0,O.jsx)(hS,{placeholder:"Select commit..."})]}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:we,children:"HEAD (uncommitted)"}),n&&(0,O.jsxs)(hk,{value:wt,children:["vs ",(0,O.jsx)("span",{className:"font-mono text-xs",children:n})]}),e.map(e=>(0,O.jsxs)(hk,{value:e.hash,children:[(0,O.jsx)("span",{className:"font-mono text-xs",children:e.shortHash})," ",(0,O.jsx)("span",{className:"truncate",children:e.message.length>40?e.message.slice(0,40)+"...":e.message})]},e.hash))]})]})}function ws({projectId:e,selectedBranch:r,onMergeRequest:s,project:n,mergeTarget:i,compareRequestNonce:a}){let[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(a),[f,p]=(0,$.useState)(r),m=void 0!==a&&a!==u;m&&(h(a),d(!0),l(null)),r!==f&&(p(r),l(null),m||d(!1));let{remotes:g}=b1(),x=[];for(let e of(n?.path&&x.push({id:"local",label:"Local",icon:oc}),g))x.push({id:e.remote_server_id,label:e.server_name,icon:sp});let v=n?.path?"local":g.length>0?g[0].remote_server_id:"local",[_,y]=(0,$.useState)(v),[b,w]=(0,$.useState)(!0),[S,j]=(0,$.useState)(0),C="local"===_?n?.path?"local":void 0:"remote",{diff:k,loading:N,error:E,refresh:D}=function(e,r,s,n,i){let[a,o]=(0,$.useState)(null),[l,c]=(0,$.useState)(!1),[d,u]=(0,$.useState)(null),h=(0,$.useCallback)(async()=>{if(!e)return void o(null);c(!0),u(null);try{let a=await rv.api.getDiff(e,r,s,n,i);o(a)}catch(e){u(e instanceof Error?e.message:"Failed to load diff"),o(null)}finally{c(!1)}},[e,r,s,n,i]);return{diff:a,loading:l,error:d,refresh:h}}(e,r,o,C,c&&i?i:null),{commits:R,loading:A,refetch:T}=function(e,r,s,n){let[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)(!1);return{commits:i,loading:o,refetch:(0,$.useCallback)(async()=>{if(!e)return void a([]);l(!0);try{let i=await rv.api.getCommits(e,r,s,n);a(i)}catch{a([])}finally{l(!1)}},[e,r,s,n])}}(e,r,void 0,C);if((0,$.useEffect)(()=>{D()},[D]),(0,$.useEffect)(()=>{T()},[T]),(0,$.useEffect)(()=>{y(v)},[e,v]),!e)return(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(sU,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to view changes"})]})});let M=k?.files.length??0;return(0,O.jsxs)("div",{className:"h-full flex flex-col",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border/60 h-10",children:[(0,O.jsx)("div",{className:"flex items-center gap-4",children:M>0&&(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("span",{className:"text-xs text-muted-foreground",children:[M," file",1!==M?"s":""," changed"]}),(0,O.jsxs)(W.Button,{size:"sm",variant:"ghost",onClick:()=>{w(e=>!e),j(e=>e+1)},title:b?"Collapse all":"Expand all",children:[(0,O.jsx)(b3,{className:"h-4 w-4 mr-1"}),b?"Collapse all":"Expand all"]})]})}),(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[x.length>1&&(0,O.jsx)(oo,{targets:x,activeTarget:_,onTargetChange:y,disabled:N}),(0,O.jsx)("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Commit:"}),(0,O.jsx)(wr,{commits:R,selectedCommit:o,onSelectCommit:e=>{d(!1),l(e)},compareTarget:i,compareSelected:c,onSelectCompare:()=>{d(!0),l(null)},loading:A,disabled:N}),(0,O.jsxs)(W.Button,{size:"sm",variant:"outline",onClick:s,disabled:N||0===M,children:[(0,O.jsx)(dr,{className:"h-4 w-4 mr-1"}),"Merge"]}),(0,O.jsxs)(W.Button,{size:"sm",variant:"outline",onClick:D,disabled:N,children:[(0,O.jsx)(fK,{className:`h-4 w-4 mr-1 ${N?"animate-spin":""}`}),"Refresh"]})]})]}),(0,O.jsx)(oK,{className:"flex-1 overflow-hidden",children:(0,O.jsx)("div",{className:"p-4 space-y-4",children:N&&!k?(0,O.jsx)("div",{className:"text-center text-muted-foreground py-8",children:"Loading changes..."}):E?(0,O.jsx)("div",{className:"text-center text-red-400 py-8",children:E}):0===M?(0,O.jsx)("div",{className:"text-center text-muted-foreground py-8",children:(0,O.jsx)("p",{children:c&&i?`No changes vs ${i}`:o?"No changes in this commit":"No uncommitted changes"})}):k?.files.map((e,r)=>(0,O.jsx)(b8,{file:e,defaultOpen:b},`${r}-${S}`))})})]})}function wn({terminalId:e,onExit:r}){let{logs:s,sendInput:n,sendResize:i,exitCode:a,replayingHistory:o}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)("closed"),[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(!0),f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=(0,$.useRef)(0),g=(0,$.useRef)(null),x=(0,$.useRef)(!1),v=(0,$.useCallback)(()=>{n([]),l(null),d(!1)},[]),_=(0,$.useCallback)(e=>{f.current?.readyState===WebSocket.OPEN&&f.current.send(JSON.stringify({type:"input",data:e}))},[]),y=(0,$.useCallback)((e,r)=>{f.current?.readyState===WebSocket.OPEN?f.current.send(JSON.stringify({type:"resize",cols:e,rows:r})):p.current={cols:e,rows:r}},[]);return(0,$.useEffect)(()=>{if(!e)return;n([]),l(null),d(!1),x.current=!1,m.current=0;let r=!1;return function s(){r||x.current||(0,rv.getFreshToken)().then(()=>{r||x.current||function(){if(r||x.current)return;a("connecting");let i=(0,rv.getWebSocketUrl)(`/api/executor-processes/${e}/logs`);console.log(`[useExecutorLogs] Connecting to WebSocket: ${i}`);let o=new WebSocket(i);f.current=o;let c=!1,u=!1;o.onopen=()=>{if(!r&&(console.log("[useExecutorLogs] WebSocket connected"),a("connected"),n([]),p.current)){let{cols:e,rows:r}=p.current;o.send(JSON.stringify({type:"resize",cols:e,rows:r})),p.current=null}},o.onmessage=e=>{if(!r)try{let r=JSON.parse(e.data);if("init"===r.type)d(r.isPty),h(!0),console.log("[useExecutorLogs] init received, setReplayingHistory(true)");else if("history_end"===r.type)u=!0,h(!1),console.log("[useExecutorLogs] history_end received, setReplayingHistory(false)");else if("finished"===r.type)x.current=!0,l(r.exitCode),a("closed");else if("error"===r.type)x.current=!0,a("error");else{u&&(c=!0,m.current=0);let e="stdout"===r.type||"stderr"===r.type||"pty"===r.type?{...r,historical:!u}:r;n(r=>[...r,e])}}catch(e){console.error("Failed to parse WebSocket message:",e)}},o.onerror=e=>{r||console.error("[useExecutorLogs] WebSocket error:",e)},o.onclose=e=>{if(console.log("[useExecutorLogs] WebSocket closed:",e.code,e.reason),f.current=null,x.current||r)return void a("closed");if(u&&!c){console.log(`[useExecutorLogs] Server closed after history with no live data — treating as terminal`),x.current=!0,a("closed");return}if(m.current<8){let e=m.current,n=Math.min(15e3,1e3*Math.pow(2,e)),i=n*Math.random()*.25,o=n+i;console.log(`[useExecutorLogs] Scheduling reconnect in ${Math.round(o)}ms (attempt ${e+1}/8)`),a("connecting"),m.current=e+1,g.current=setTimeout(()=>{g.current=null,r||s()},o)}else console.log("[useExecutorLogs] Max reconnect attempts reached"),a("error")}}()})}(),()=>{r=!0,g.current&&(clearTimeout(g.current),g.current=null),f.current&&(f.current.close(),f.current=null)}},[e,void 0]),{logs:s,status:i,exitCode:o,isPty:c,replayingHistory:u,clearLogs:v,sendInput:_,sendResize:y}}(e);return(0,$.useEffect)(()=>{null!==a&&r(e)},[a,r,e]),(0,O.jsx)(_4,{logs:s,isPty:!0,className:"h-full rounded-none border-0",onInput:n,onResize:i,muteInput:o})}function wi({projectId:e,selectedBranch:r,project:s}){let{terminals:n,activeTerminalId:i,createTerminal:a,closeTerminal:o,setActiveTerminal:l,removeTerminal:c}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(null);(0,$.useEffect)(()=>{if(!e){n([]),a(null);return}rv.api.getTerminals(e,r).then(e=>{n(e),a(e.length>0?e[0].id:null)})},[e,r]);let o=(0,$.useCallback)(async(s,i)=>{if(e)try{let o=await rv.api.createTerminal(e,r,s,i);n(e=>[...e,o]),a(o.id)}catch(e){console.error("[useTerminals] Failed to create terminal:",e)}},[e,r]),l=(0,$.useCallback)(async e=>{await rv.api.closeTerminal(e),n(r=>{let s=r.filter(r=>r.id!==e);return a(r=>r===e?s.length>0?s[s.length-1].id:null:r),s})},[]);return{terminals:s,activeTerminalId:i,createTerminal:o,closeTerminal:l,setActiveTerminal:(0,$.useCallback)(e=>{a(e)},[]),removeTerminal:(0,$.useCallback)(e=>{n(r=>{let s=r.filter(r=>r.id!==e);return a(r=>r===e?s.length>0?s[s.length-1].id:null:r),s})},[])}}(e,r),{remotes:d}=b1(),[u,h]=(0,$.useState)(!1),f=(0,$.useRef)(null),p=!!s?.path,m=d.length>0,g=p&&m||d.length>1,x=!p&&m||g&&s?.executor_mode!=="local"?"remote":"local",v=(0,$.useCallback)(()=>{a(x)},[a,x]),_=(0,$.useCallback)((e,r)=>{h(!1),a(e,r)},[a]);(0,$.useEffect)(()=>{if(u)return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e);function e(e){f.current&&!f.current.contains(e.target)&&h(!1)}},[u]);let y=(0,$.useCallback)(e=>{c(e)},[c]);return e?(0,O.jsxs)("div",{className:"h-full flex flex-col",children:[(0,O.jsxs)("div",{className:"flex items-center h-10 border-b border-border/60 px-2 gap-1 shrink-0 bg-muted/20",children:[(0,O.jsx)("div",{className:"flex-1 min-w-0 flex items-center gap-1 overflow-hidden",children:n.map(e=>{let r="remote"===e.location||e.id.startsWith("remote-"),s=g?r?sp:oc:ol,n=i===e.id;return(0,O.jsxs)("button",{onClick:()=>l(e.id),title:e.name,className:(0,ey.cn)("group flex items-center gap-1.5 px-2 py-1 rounded-md text-xs transition-all duration-150 border flex-1 min-w-0 basis-0 max-w-[180px]",n?"bg-background text-foreground border-border shadow-sm":"text-muted-foreground hover:text-foreground bg-muted/40 hover:bg-background/60 border-border/30 hover:border-border/60"),children:[(0,O.jsx)(s,{className:"h-3 w-3 shrink-0"}),(0,O.jsx)("span",{className:"truncate flex-1 text-left",children:e.name}),(0,O.jsx)("span",{role:"button",onClick:r=>{r.stopPropagation(),o(e.id)},className:(0,ey.cn)("shrink-0 rounded-sm p-0.5 hover:bg-destructive/10 hover:text-destructive",n?"opacity-80 hover:opacity-100":"opacity-0 group-hover:opacity-80 hover:!opacity-100"),children:(0,O.jsx)(t7,{className:"h-3 w-3"})})]},e.id)})}),(0,O.jsxs)("div",{className:"relative shrink-0",ref:f,children:[(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:g?()=>h(e=>!e):v,children:(0,O.jsx)(eS,{className:"h-3.5 w-3.5"})}),g&&u&&(0,O.jsxs)("div",{className:"absolute right-0 top-full mt-1 z-50 min-w-[160px] rounded-md border bg-popover p-1 shadow-md",children:[p&&(0,O.jsxs)("button",{className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground transition-colors",onClick:()=>_("local"),children:[(0,O.jsx)(oc,{className:"h-3.5 w-3.5"}),"Local Terminal"]}),d.map(e=>(0,O.jsxs)("button",{className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground transition-colors",onClick:()=>_("remote",e.remote_server_id),children:[(0,O.jsx)(sp,{className:"h-3.5 w-3.5"}),e.server_name," Terminal"]},e.remote_server_id))]})]})]}),(0,O.jsx)("div",{className:"flex-1 overflow-hidden bg-zinc-950",children:i?(0,O.jsx)(wn,{terminalId:i,onExit:y},i):(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,O.jsx)(ol,{className:"h-10 w-10 text-muted-foreground/70"})})})]}):(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(ol,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to use the terminal"})]})})}let wa=(0,$.createContext)(null),wo=({className:e,children:r,defaultUrl:s="",onUrlChange:n,...i})=>{let[a,o]=(0,$.useState)(s),[l,c]=(0,$.useState)(!1);return(0,O.jsx)(wa.Provider,{value:{url:a,setUrl:e=>{o(e),n?.(e)},consoleOpen:l,setConsoleOpen:c},children:(0,O.jsx)("div",{className:(0,ey.cn)("flex size-full flex-col bg-card",e),...i,children:r})})},wl=({className:e,children:r,...s})=>(0,O.jsx)("div",{className:(0,ey.cn)("flex items-center gap-1 border-b p-2 h-14",e),...s,children:r}),wc=({onClick:e,disabled:r,tooltip:s,children:n,...i})=>(0,O.jsx)(cb,{children:(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsx)(W.Button,{className:"h-8 w-8 p-0 hover:text-foreground",disabled:r,onClick:e,size:"sm",variant:"ghost",...i,children:n})}),(0,O.jsx)(cj,{children:(0,O.jsx)("p",{children:s})})]})}),wd=({value:e,onChange:r,onKeyDown:s,...n})=>{let{url:i,setUrl:a}=(()=>{let e=(0,$.useContext)(wa);if(!e)throw Error("WebPreview components must be used within a WebPreview");return e})(),[o,l]=(0,$.useState)(i);return(0,$.useEffect)(()=>{l(i)},[i]),(0,O.jsx)(ro,{className:"h-8 flex-1 text-sm",onChange:r??(e=>{l(e.target.value),r?.(e)}),onKeyDown:e=>{"Enter"===e.key&&a(e.target.value),s?.(e)},placeholder:"Enter URL...",value:e??o,...n})};var wu=e.i(254824);function wh({projectId:e}){let r=(0,$.useRef)(null),s=(0,$.useRef)(null),{addFrame:n,updateFrameUrl:i,refreshFrame:a,hasFrame:o,claimFrame:l,getFrameUrl:c}=(0,wu.useBrowserFrames)(),d=e?c(e):void 0;(0,$.useEffect)(()=>{if(e&&d&&r.current){let n=setTimeout(()=>{r.current&&(s.current?.(),s.current=l(e,r.current))},50);return()=>{clearTimeout(n),s.current?.(),s.current=null}}return()=>{s.current?.(),s.current=null}},[e,d,l]);let u=(0,$.useCallback)(()=>{e&&a(e)},[e,a]),h=(0,$.useCallback)(()=>{d&&window.open(d,"_blank")},[d]),f=(0,$.useCallback)(r=>{e&&(o(e)?i(e,r):n(e,r))},[e,o,i,n]);return(0,O.jsx)("div",{className:"h-full flex flex-col",children:(0,O.jsxs)(wo,{defaultUrl:d??"",onUrlChange:f,className:"h-full",children:[(0,O.jsxs)(wl,{className:"h-10 p-1.5 gap-0.5",children:[(0,O.jsx)(wc,{tooltip:"Refresh",onClick:u,disabled:!d,children:(0,O.jsx)(fK,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(wc,{tooltip:"Open in browser",onClick:h,disabled:!d,children:(0,O.jsx)(s7,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(wd,{className:"h-7 text-xs"})]}),d?(0,O.jsx)("div",{ref:r,className:"flex-1 bg-white"}):(0,O.jsx)("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:(0,O.jsxs)("div",{className:"flex flex-col items-center gap-2",children:[(0,O.jsx)(ry,{className:"h-8 w-8 opacity-40"}),(0,O.jsx)("p",{className:"text-sm",children:"Enter a URL above to preview"})]})})]})})}let wf=(0,ew.default)("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),wp=(0,ew.default)("eye-off",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),wm=(0,ew.default)("panel-left-close",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]),wg=(0,ew.default)("panel-left-open",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]),wx=(0,ew.default)("arrow-right",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);function wv({className:e,...r}){return(0,O.jsx)("div",{"data-slot":"input-group",role:"group",className:(0,ey.cn)("group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-xs transition-[color,box-shadow] outline-none","h-9 min-w-0 has-[textarea]:h-auto","has-[>[data-align=inline-start]]:[&>input]:pl-2","has-[>[data-align=inline-end]]:[&>input]:pr-2","has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3","has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3","has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:ring-[3px]","has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",e),...r})}let w_=(0,sn.cva)("text-muted-foreground flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium select-none [&>svg:not([class*='size-'])]:size-4 [&>kbd]:rounded-[calc(var(--radius)-5px)] group-data-[disabled=true]/input-group:opacity-50",{variants:{align:{"inline-start":"order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]","inline-end":"order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]","block-start":"order-first w-full justify-start px-3 pt-3 [.border-b]:pb-3 group-has-[>input]/input-group:pt-2.5","block-end":"order-last w-full justify-start px-3 pb-3 [.border-t]:pt-3 group-has-[>input]/input-group:pb-2.5"}},defaultVariants:{align:"inline-start"}});function wy({className:e,align:r="inline-start",...s}){return(0,O.jsx)("div",{role:"group","data-slot":"input-group-addon","data-align":r,className:(0,ey.cn)(w_({align:r}),e),onClick:e=>{e.target.closest("button")||e.currentTarget.parentElement?.querySelector("input")?.focus()},...s})}let wb=(0,sn.cva)("text-sm shadow-none flex gap-2 items-center",{variants:{size:{xs:"h-6 gap-1 px-2 rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-3.5 has-[>svg]:px-2",sm:"h-8 px-2.5 gap-1.5 rounded-md has-[>svg]:px-2.5","icon-xs":"size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0","icon-sm":"size-8 p-0 has-[>svg]:p-0"}},defaultVariants:{size:"xs"}});function ww({className:e,type:r="button",variant:s="ghost",size:n="xs",...i}){return(0,O.jsx)(W.Button,{type:r,"data-size":n,variant:s,className:(0,ey.cn)(wb({size:n}),e),...i})}function wS({className:e,...r}){return(0,O.jsx)(ro,{"data-slot":"input-group-control",className:(0,ey.cn)("flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",e),...r})}function wj({className:e,...r}){return(0,O.jsx)(rl,{"data-slot":"input-group-control",className:(0,ey.cn)("flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",e),...r})}var wC=/[\\\/_+.#"@\[\(\{&]/,wk=/[\\\/_+.#"@\[\(\{&]/g,wN=/[\s-]/,wE=/[\s-]/g;function wD(e){return e.toLowerCase().replace(wE," ")}var wR=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,r)=>{let s=se(`Primitive.${r}`),n=$.forwardRef((e,n)=>{let{asChild:i,...a}=e;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),(0,O.jsx)(i?s:r,{...a,ref:n})});return n.displayName=`Primitive.${r}`,{...e,[r]:n}},{}),wA='[cmdk-group=""]',wT='[cmdk-group-items=""]',wM='[cmdk-item=""]',wF=`${wM}:not([aria-disabled="true"])`,wP="cmdk-item-select",wI="data-value",wB=(e,r,s)=>{var n;return n=e,function e(r,s,n,i,a,o,l){if(o===s.length)return a===r.length?1:.99;var c=`${a},${o}`;if(void 0!==l[c])return l[c];for(var d,u,h,f,p=i.charAt(o),m=n.indexOf(p,a),g=0;m>=0;)(d=e(r,s,n,i,m+1,o+1,l))>g&&(m===a?d*=1:wC.test(r.charAt(m-1))?(d*=.8,(h=r.slice(a,m-1).match(wk))&&a>0&&(d*=Math.pow(.999,h.length))):wN.test(r.charAt(m-1))?(d*=.9,(f=r.slice(a,m-1).match(wE))&&a>0&&(d*=Math.pow(.999,f.length))):(d*=.17,a>0&&(d*=Math.pow(.999,m-a))),r.charAt(m)!==s.charAt(o)&&(d*=.9999)),(d<.1&&n.charAt(m-1)===i.charAt(o+1)||i.charAt(o+1)===i.charAt(o)&&n.charAt(m-1)!==i.charAt(o))&&.1*(u=e(r,s,n,i,m+1,o+2,l))>d&&(d=.1*u),d>g&&(g=d),m=n.indexOf(p,m+1);return l[c]=g,g}(n=s&&s.length>0?`${n+" "+s.join(" ")}`:n,r,wD(n),wD(r),0,0,{})},wL=$.createContext(void 0),wz=$.createContext(void 0),wO=$.createContext(void 0),w$=$.forwardRef((e,r)=>{let s=wJ(()=>{var r,s;return{search:"",value:null!=(s=null!=(r=e.value)?r:e.defaultValue)?s:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=wJ(()=>new Set),i=wJ(()=>new Map),a=wJ(()=>new Map),o=wJ(()=>new Set),l=wG(e),{label:c,children:d,value:u,onValueChange:h,filter:f,shouldFilter:p,loop:m,disablePointerSelection:g=!1,vimBindings:x=!0,...v}=e,_=ek(),y=ek(),b=ek(),w=$.useRef(null),S=w0();wX(()=>{if(void 0!==u){let e=u.trim();s.current.value=e,j.emit()}},[u]),wX(()=>{S(6,R)},[]);let j=$.useMemo(()=>({subscribe:e=>(o.current.add(e),()=>o.current.delete(e)),snapshot:()=>s.current,setState:(e,r,n)=>{var i,a,o,c;if(!Object.is(s.current[e],r)){if(s.current[e]=r,"search"===e)D(),N(),S(1,E);else if("value"===e){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let e=document.getElementById(b);e?e.focus():null==(i=document.getElementById(_))||i.focus()}if(S(7,()=>{var e;s.current.selectedItemId=null==(e=A())?void 0:e.id,j.emit()}),n||S(5,R),(null==(a=l.current)?void 0:a.value)!==void 0){null==(c=(o=l.current).onValueChange)||c.call(o,null!=r?r:"");return}}j.emit()}},emit:()=>{o.current.forEach(e=>e())}}),[]),C=$.useMemo(()=>({value:(e,r,n)=>{var i;r!==(null==(i=a.current.get(e))?void 0:i.value)&&(a.current.set(e,{value:r,keywords:n}),s.current.filtered.items.set(e,k(r,n)),S(2,()=>{N(),j.emit()}))},item:(e,r)=>(n.current.add(e),r&&(i.current.has(r)?i.current.get(r).add(e):i.current.set(r,new Set([e]))),S(3,()=>{D(),N(),s.current.value||E(),j.emit()}),()=>{a.current.delete(e),n.current.delete(e),s.current.filtered.items.delete(e);let r=A();S(4,()=>{D(),(null==r?void 0:r.getAttribute("id"))===e&&E(),j.emit()})}),group:e=>(i.current.has(e)||i.current.set(e,new Set),()=>{a.current.delete(e),i.current.delete(e)}),filter:()=>l.current.shouldFilter,label:c||e["aria-label"],getDisablePointerSelection:()=>l.current.disablePointerSelection,listId:_,inputId:b,labelId:y,listInnerRef:w}),[]);function k(e,r){var n,i;let a=null!=(i=null==(n=l.current)?void 0:n.filter)?i:wB;return e?a(e,s.current.search,r):0}function N(){if(!s.current.search||!1===l.current.shouldFilter)return;let e=s.current.filtered.items,r=[];s.current.filtered.groups.forEach(s=>{let n=i.current.get(s),a=0;n.forEach(r=>{a=Math.max(e.get(r),a)}),r.push([s,a])});let n=w.current;T().sort((r,s)=>{var n,i;let a=r.getAttribute("id"),o=s.getAttribute("id");return(null!=(n=e.get(o))?n:0)-(null!=(i=e.get(a))?i:0)}).forEach(e=>{let r=e.closest(wT);r?r.appendChild(e.parentElement===r?e:e.closest(`${wT} > *`)):n.appendChild(e.parentElement===n?e:e.closest(`${wT} > *`))}),r.sort((e,r)=>r[1]-e[1]).forEach(e=>{var r;let s=null==(r=w.current)?void 0:r.querySelector(`${wA}[${wI}="${encodeURIComponent(e[0])}"]`);null==s||s.parentElement.appendChild(s)})}function E(){let e=T().find(e=>"true"!==e.getAttribute("aria-disabled")),r=null==e?void 0:e.getAttribute(wI);j.setState("value",r||void 0)}function D(){var e,r,o,c;if(!s.current.search||!1===l.current.shouldFilter){s.current.filtered.count=n.current.size;return}s.current.filtered.groups=new Set;let d=0;for(let i of n.current){let n=k(null!=(r=null==(e=a.current.get(i))?void 0:e.value)?r:"",null!=(c=null==(o=a.current.get(i))?void 0:o.keywords)?c:[]);s.current.filtered.items.set(i,n),n>0&&d++}for(let[e,r]of i.current)for(let n of r)if(s.current.filtered.items.get(n)>0){s.current.filtered.groups.add(e);break}s.current.filtered.count=d}function R(){var e,r,s;let n=A();n&&((null==(e=n.parentElement)?void 0:e.firstChild)===n&&(null==(s=null==(r=n.closest(wA))?void 0:r.querySelector('[cmdk-group-heading=""]'))||s.scrollIntoView({block:"nearest"})),n.scrollIntoView({block:"nearest"}))}function A(){var e;return null==(e=w.current)?void 0:e.querySelector(`${wM}[aria-selected="true"]`)}function T(){var e;return Array.from((null==(e=w.current)?void 0:e.querySelectorAll(wF))||[])}function M(e){let r=T()[e];r&&j.setState("value",r.getAttribute(wI))}function F(e){var r;let s=A(),n=T(),i=n.findIndex(e=>e===s),a=n[i+e];null!=(r=l.current)&&r.loop&&(a=i+e<0?n[n.length-1]:i+e===n.length?n[0]:n[i+e]),a&&j.setState("value",a.getAttribute(wI))}function P(e){let r=A(),s=null==r?void 0:r.closest(wA),n;for(;s&&!n;)n=null==(s=e>0?function(e,r){let s=e.nextElementSibling;for(;s;){if(s.matches(r))return s;s=s.nextElementSibling}}(s,wA):function(e,r){let s=e.previousElementSibling;for(;s;){if(s.matches(r))return s;s=s.previousElementSibling}}(s,wA))?void 0:s.querySelector(wF);n?j.setState("value",n.getAttribute(wI)):F(e)}let I=()=>M(T().length-1),B=e=>{e.preventDefault(),e.metaKey?I():e.altKey?P(1):F(1)},L=e=>{e.preventDefault(),e.metaKey?M(0):e.altKey?P(-1):F(-1)};return $.createElement(wR.div,{ref:r,tabIndex:-1,...v,"cmdk-root":"",onKeyDown:e=>{var r;null==(r=v.onKeyDown)||r.call(v,e);let s=e.nativeEvent.isComposing||229===e.keyCode;if(!(e.defaultPrevented||s))switch(e.key){case"n":case"j":x&&e.ctrlKey&&B(e);break;case"ArrowDown":B(e);break;case"p":case"k":x&&e.ctrlKey&&L(e);break;case"ArrowUp":L(e);break;case"Home":e.preventDefault(),M(0);break;case"End":e.preventDefault(),I();break;case"Enter":{e.preventDefault();let r=A();if(r){let e=new Event(wP);r.dispatchEvent(e)}}}}},$.createElement("label",{"cmdk-label":"",htmlFor:C.inputId,id:C.labelId,style:w2},c),w1(e,e=>$.createElement(wz.Provider,{value:j},$.createElement(wL.Provider,{value:C},e))))}),wW=$.forwardRef((e,r)=>{var s,n;let i=ek(),a=$.useRef(null),o=$.useContext(wO),l=$.useContext(wL),c=wG(e),d=null!=(n=null==(s=c.current)?void 0:s.forceMount)?n:null==o?void 0:o.forceMount;wX(()=>{if(!d)return l.item(i,null==o?void 0:o.id)},[d]);let u=wQ(i,a,[e.value,e.children,a],e.keywords),h=$.useContext(wz),f=wZ(e=>e.value&&e.value===u.current),p=wZ(e=>!!d||!1===l.filter()||!e.search||e.filtered.items.get(i)>0);function m(){var e,r;g(),null==(r=(e=c.current).onSelect)||r.call(e,u.current)}function g(){h.setState("value",u.current,!0)}if($.useEffect(()=>{let r=a.current;if(!(!r||e.disabled))return r.addEventListener(wP,m),()=>r.removeEventListener(wP,m)},[p,e.onSelect,e.disabled]),!p)return null;let{disabled:x,value:v,onSelect:_,forceMount:y,keywords:b,...w}=e;return $.createElement(wR.div,{ref:(0,U.composeRefs)(a,r),...w,id:i,"cmdk-item":"",role:"option","aria-disabled":!!x,"aria-selected":!!f,"data-disabled":!!x,"data-selected":!!f,onPointerMove:x||l.getDisablePointerSelection()?void 0:g,onClick:x?void 0:m},e.children)}),wH=$.forwardRef((e,r)=>{let{heading:s,children:n,forceMount:i,...a}=e,o=ek(),l=$.useRef(null),c=$.useRef(null),d=ek(),u=$.useContext(wL),h=wZ(e=>!!i||!1===u.filter()||!e.search||e.filtered.groups.has(o));wX(()=>u.group(o),[]),wQ(o,l,[e.value,e.heading,c]);let f=$.useMemo(()=>({id:o,forceMount:i}),[i]);return $.createElement(wR.div,{ref:(0,U.composeRefs)(l,r),...a,"cmdk-group":"",role:"presentation",hidden:!h||void 0},s&&$.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},s),w1(e,e=>$.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":s?d:void 0},$.createElement(wO.Provider,{value:f},e))))}),wU=$.forwardRef((e,r)=>{let{alwaysRender:s,...n}=e,i=$.useRef(null),a=wZ(e=>!e.search);return s||a?$.createElement(wR.div,{ref:(0,U.composeRefs)(i,r),...n,"cmdk-separator":"",role:"separator"}):null}),wq=$.forwardRef((e,r)=>{let{onValueChange:s,...n}=e,i=null!=e.value,a=$.useContext(wz),o=wZ(e=>e.search),l=wZ(e=>e.selectedItemId),c=$.useContext(wL);return $.useEffect(()=>{null!=e.value&&a.setState("search",e.value)},[e.value]),$.createElement(wR.input,{ref:r,...n,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":l,id:c.inputId,type:"text",value:i?e.value:o,onChange:e=>{i||a.setState("search",e.target.value),null==s||s(e.target.value)}})}),wK=$.forwardRef((e,r)=>{let{children:s,label:n="Suggestions",...i}=e,a=$.useRef(null),o=$.useRef(null),l=wZ(e=>e.selectedItemId),c=$.useContext(wL);return $.useEffect(()=>{if(o.current&&a.current){let e=o.current,r=a.current,s,n=new ResizeObserver(()=>{s=requestAnimationFrame(()=>{let s=e.offsetHeight;r.style.setProperty("--cmdk-list-height",s.toFixed(1)+"px")})});return n.observe(e),()=>{cancelAnimationFrame(s),n.unobserve(e)}}},[]),$.createElement(wR.div,{ref:(0,U.composeRefs)(a,r),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":l,"aria-label":n,id:c.listId},w1(e,e=>$.createElement("div",{ref:(0,U.composeRefs)(o,c.listInnerRef),"cmdk-list-sizer":""},e)))}),wV=$.forwardRef((e,r)=>{let{open:s,onOpenChange:n,overlayClassName:i,contentClassName:a,container:o,...l}=e;return $.createElement(tM,{open:s,onOpenChange:n},$.createElement(tz,{container:o},$.createElement(t$,{"cmdk-overlay":"",className:i}),$.createElement(tq,{"aria-label":e.label,"cmdk-dialog":"",className:a},$.createElement(w$,{ref:r,...l}))))}),wY=Object.assign(w$,{List:wK,Item:wW,Input:wq,Group:wH,Separator:wU,Dialog:wV,Empty:$.forwardRef((e,r)=>wZ(e=>0===e.filtered.count)?$.createElement(wR.div,{ref:r,...e,"cmdk-empty":"",role:"presentation"}):null),Loading:$.forwardRef((e,r)=>{let{progress:s,children:n,label:i="Loading...",...a}=e;return $.createElement(wR.div,{ref:r,...a,"cmdk-loading":"",role:"progressbar","aria-valuenow":s,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},w1(e,e=>$.createElement("div",{"aria-hidden":!0},e)))})});function wG(e){let r=$.useRef(e);return wX(()=>{r.current=e}),r}var wX="undefined"==typeof window?$.useEffect:$.useLayoutEffect;function wJ(e){let r=$.useRef();return void 0===r.current&&(r.current=e()),r}function wZ(e){let r=$.useContext(wz),s=()=>e(r.snapshot());return $.useSyncExternalStore(r.subscribe,s,s)}function wQ(e,r,s,n=[]){let i=$.useRef(),a=$.useContext(wL);return wX(()=>{var o;let l=(()=>{var e;for(let r of s){if("string"==typeof r)return r.trim();if("object"==typeof r&&"current"in r)return r.current?null==(e=r.current.textContent)?void 0:e.trim():i.current}})(),c=n.map(e=>e.trim());a.value(e,l,c),null==(o=r.current)||o.setAttribute(wI,l),i.current=l}),i}var w0=()=>{let[e,r]=$.useState(),s=wJ(()=>new Map);return wX(()=>{s.current.forEach(e=>e()),s.current=new Map},[e]),(e,n)=>{s.current.set(e,n),r({})}};function w1({asChild:e,children:r},s){let n;return e&&$.isValidElement(r)?$.cloneElement("function"==typeof(n=r.type)?n(r.props):"render"in n?n.render(r.props):r,{ref:r.ref},s(r.props.children)):s(r)}var w2={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function w5({className:e,...r}){return(0,O.jsx)(wY,{"data-slot":"command",className:(0,ey.cn)("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",e),...r})}function w3({title:e="Command Palette",description:r="Search for a command to run...",children:s,className:n,showCloseButton:i=!0,shouldFilter:a,...o}){return(0,O.jsxs)(t8,{...o,children:[(0,O.jsxs)(rs,{className:"sr-only",children:[(0,O.jsx)(ri,{children:e}),(0,O.jsx)(ra,{children:r})]}),(0,O.jsx)(rr,{className:(0,ey.cn)("overflow-hidden p-0",n),showCloseButton:i,children:(0,O.jsx)(w5,{shouldFilter:a,className:"[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:s})})]})}function w4({className:e,...r}){return(0,O.jsxs)("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[(0,O.jsx)(sA,{className:"size-4 shrink-0 opacity-50"}),(0,O.jsx)(wY.Input,{"data-slot":"command-input",className:(0,ey.cn)("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",e),...r})]})}function w6({className:e,...r}){return(0,O.jsx)(wY.List,{"data-slot":"command-list",className:(0,ey.cn)("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...r})}function w7({...e}){return(0,O.jsx)(wY.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...e})}function w8({className:e,...r}){return(0,O.jsx)(wY.Group,{"data-slot":"command-group",className:(0,ey.cn)("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",e),...r})}function w9({className:e,...r}){return(0,O.jsx)(wY.Item,{"data-slot":"command-item",className:(0,ey.cn)("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r})}let Se=(0,ew.default)("file",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]]),St=(0,ew.default)("file-code",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]]),Sr=(0,ew.default)("file-text",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]),Ss=new Set(["ts","tsx","js","jsx","py","rb","go","rs","java","c","cpp","h","css","scss","html","vue","svelte","php","swift","kt","sh","bash","yaml","yml","toml","json","xml","sql","graphql","proto"]),Sn=new Set(["md","txt","log","csv","env","gitignore","dockerignore","editorconfig"]);function Si(e){return Array.from(e.dataTransfer.types).includes("Files")}function Sa(e){let r=e.dataTransfer.items;if(r&&r.length>0&&"function"==typeof r[0].webkitGetAsEntry){let e=[];for(let s of Array.from(r)){if("file"!==s.kind)continue;let r=s.webkitGetAsEntry();if(r?.isDirectory)continue;let n=s.getAsFile();n&&e.push(n)}return e}return Array.from(e.dataTransfer.files)}function So({path:e}){let[r,s]=(0,$.useState)(!1),n=(0,$.useCallback)(r=>{r.stopPropagation(),navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)},[e]);return(0,O.jsx)("button",{onClick:n,className:"p-0.5 rounded hover:bg-muted-foreground/20 transition-colors",title:`Copy path: ${e}`,children:r?(0,O.jsx)(rf.Check,{className:"h-3 w-3 text-green-500"}):(0,O.jsx)(fq.Copy,{className:"h-3 w-3 text-muted-foreground"})})}function Sl({entryPath:e,type:r,deleting:s,onRequestDelete:n}){return s?(0,O.jsx)(sj,{className:"h-3 w-3 animate-spin text-muted-foreground"}):(0,O.jsx)("button",{onClick:s=>{s.stopPropagation(),n(e,r)},className:"p-0.5 rounded hover:bg-destructive/20 transition-colors",title:`Delete ${e}`,"aria-label":`Delete ${e}`,children:(0,O.jsx)(rc,{className:"h-3 w-3 text-muted-foreground hover:text-destructive"})})}function Sc({entry:e,path:r,depth:s,expandedDirs:n,directoryContents:i,loadingDirs:a,selectedFile:o,uploadingDirs:l,dragOverPath:c,deletingPaths:d,onToggleDirectory:u,onSelectFile:h,onUploadFiles:f,onSetDragOverPath:p,onRequestDelete:m}){var g,x,v;let _,y,b,w,S,j=n.has(r),C=a.has(r),k=i.get(r),N=e.name.startsWith(".");if("directory"===e.type){let g=j?ns:a3,x=c===r,v=l.has(r),_=d.has(r);return(0,O.jsxs)("div",{children:[(0,O.jsxs)("div",{className:(0,ey.cn)("group flex items-center w-full px-2 py-2 rounded-sm transition-colors cursor-pointer",x?"bg-primary/15 outline-2 -outline-offset-2 outline-dashed outline-primary/60":"hover:bg-accent"),style:{paddingLeft:`${16*s+8}px`},onClick:()=>u(r),onDragOver:e=>{Si(e)&&(e.preventDefault(),e.stopPropagation(),p(r))},onDrop:e=>{if(!Si(e))return;e.preventDefault(),e.stopPropagation(),p(null);let s=Sa(e);s.length&&f(r,s)},children:[(0,O.jsxs)("div",{className:"flex items-center gap-1 min-w-0 flex-1",children:[v||C?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):(0,O.jsx)(g,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,O.jsx)(j?r_:oY,{className:(0,ey.cn)("h-4 w-4 shrink-0 text-blue-500",N&&"opacity-60")}),(0,O.jsx)("span",{className:(0,ey.cn)("truncate",N&&"text-muted-foreground"),children:e.name})]}),(0,O.jsxs)("div",{className:(0,ey.cn)("shrink-0 ml-1 items-center gap-1",_?"flex":"hidden group-hover:flex"),children:[(0,O.jsx)(So,{path:r}),(0,O.jsx)(Sl,{entryPath:r,type:"directory",deleting:_,onRequestDelete:m})]})]}),j&&k&&(0,O.jsx)("div",{children:k.map(e=>{let g=r?`${r}/${e.name}`:e.name;return(0,O.jsx)(Sc,{entry:e,path:g,depth:s+1,expandedDirs:n,directoryContents:i,loadingDirs:a,selectedFile:o,uploadingDirs:l,dragOverPath:c,deletingPaths:d,onToggleDirectory:u,onSelectFile:h,onUploadFiles:f,onSetDragOverPath:p,onRequestDelete:m},g)})})]})}let E=(g=e.name,_=g.split(".").pop()?.toLowerCase()??"",Ss.has(_)?St:Sn.has(_)?Sr:Se),D=o===r,R=r.includes("/")?r.slice(0,r.lastIndexOf("/")):"",A=d.has(r);return(0,O.jsxs)("div",{className:(0,ey.cn)("group flex items-center w-full px-2 py-2 rounded-sm transition-colors cursor-pointer",D?"bg-accent text-accent-foreground":"hover:bg-accent/50"),style:{paddingLeft:`${16*s+8+18}px`},onClick:()=>h(r),onDragOver:e=>{Si(e)&&(e.preventDefault(),e.stopPropagation(),p(R))},onDrop:e=>{if(!Si(e))return;e.preventDefault(),e.stopPropagation(),p(null);let r=Sa(e);r.length&&f(R,r)},children:[(0,O.jsxs)("div",{className:"flex items-center gap-1 min-w-0 flex-1",children:[(0,O.jsx)(E,{className:(0,ey.cn)("h-4 w-4 shrink-0 text-muted-foreground",N&&"opacity-60")}),(0,O.jsx)("span",{className:(0,ey.cn)("truncate",N&&"text-muted-foreground"),children:e.name})]}),(0,O.jsxs)("div",{className:"shrink-0 flex items-center gap-2 ml-1",children:[(0,O.jsx)("span",{className:"text-[11px] text-muted-foreground/70 group-hover:hidden whitespace-nowrap w-[52px] text-right tabular-nums",children:e.mtime&&(x=e.mtime,y=Date.now(),S=Math.floor((w=Math.floor((b=Math.floor(Math.floor((y-new Date(x).getTime())/1e3)/60))/60))/24),b<1?"just now":b<60?`${b}m ago`:w<24?`${w}h ago`:S<30?`${S}d ago`:new Date(x).toLocaleDateString(void 0,{month:"short",day:"numeric"}))}),(0,O.jsx)("span",{className:"text-[11px] text-muted-foreground/70 group-hover:hidden whitespace-nowrap w-[52px] text-right tabular-nums",children:null!=e.size&&((v=e.size)<1024?`${v} B`:v<1048576?`${(v/1024).toFixed(1)} KB`:`${(v/1048576).toFixed(1)} MB`)}),(0,O.jsxs)("div",{className:(0,ey.cn)("items-center gap-1",A?"flex":"hidden group-hover:flex"),children:[(0,O.jsx)(So,{path:r}),(0,O.jsx)(Sl,{entryPath:r,type:"file",deleting:A,onRequestDelete:m})]})]})]})}function Sd({entries:e,expandedDirs:r,directoryContents:s,loadingDirs:n,selectedFile:i,uploadingDirs:a,rootLoading:o,deletingPaths:l,onToggleDirectory:c,onSelectFile:d,onUploadFiles:u,onDeleteEntry:h}){let[f,p]=(0,$.useState)(null),[m,g]=(0,$.useState)(null),x=""===f,v=a.has(""),_=(0,$.useCallback)((e,r)=>{g({path:e,type:r})},[]),y=m?m.path.includes("/")?m.path.slice(m.path.lastIndexOf("/")+1):m.path:"";return(0,O.jsxs)("div",{className:(0,ey.cn)("h-full transition-colors",x&&"bg-accent/30 outline-2 -outline-offset-2 outline-dashed outline-primary/50"),style:{fontSize:"var(--files-tree-font-size, 14px)"},onDragOver:e=>{Si(e)&&(e.preventDefault(),p(""))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||p(null)},onDrop:e=>{if(!Si(e))return;e.preventDefault(),p(null);let r=Sa(e);r.length&&u("",r)},children:[(0,O.jsx)(oK,{className:"h-full",children:(0,O.jsxs)("div",{className:"py-1",children:[v&&(0,O.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1 text-xs text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-3.5 w-3.5 animate-spin"}),"Uploading…"]}),o&&0===e.length?(0,O.jsx)("div",{className:"flex items-center justify-center py-12 text-muted-foreground text-sm",children:"Loading files..."}):0===e.length?(0,O.jsx)("div",{className:"flex items-center justify-center py-8 text-muted-foreground text-sm",children:x?"Drop files to upload":"No files found. Drop files here to upload."}):e.map(e=>{let o=e.name;return(0,O.jsx)(Sc,{entry:e,path:o,depth:0,expandedDirs:r,directoryContents:s,loadingDirs:n,selectedFile:i,uploadingDirs:a,dragOverPath:f,deletingPaths:l,onToggleDirectory:c,onSelectFile:d,onUploadFiles:u,onSetDragOverPath:p,onRequestDelete:_},o)})]})}),(0,O.jsx)(lL,{open:null!==m,onOpenChange:e=>{e||g(null)},children:(0,O.jsxs)(l$,{children:[(0,O.jsxs)(lW,{children:[(0,O.jsxs)(lU,{children:["Delete ",m?.type==="directory"?"folder":"file","?"]}),(0,O.jsx)(lq,{children:m?.type==="directory"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("span",{className:"font-medium text-foreground",children:y})," and all its contents will be permanently deleted. This can't be undone."]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("span",{className:"font-medium text-foreground",children:y})," will be permanently deleted. This can't be undone."]})})]}),(0,O.jsxs)(lH,{children:[(0,O.jsx)(lV,{children:"Cancel"}),(0,O.jsx)(lK,{className:(0,ey.cn)((0,W.buttonVariants)({variant:"destructive"}),"border-transparent"),onClick:()=>{m&&h(m.path,m.type)},children:"Delete"})]})]})})]})}let Su=(0,ew.default)("download",[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]]),Sh=(0,ew.default)("file-exclamation-point",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),Sf=(0,ew.default)("code",[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]]),Sp=(0,ew.default)("list-collapse",[["path",{d:"M10 5h11",key:"1hkqpe"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 19h11",key:"14g2nv"}],["path",{d:"m3 10 3-3-3-3",key:"i7pm08"}],["path",{d:"m3 20 3-3-3-3",key:"20gx1n"}]]),Sm=(0,ew.default)("list-tree",[["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"M3 10a2 2 0 0 0 2 2h3",key:"1npucw"}],["path",{d:"M3 5v12a2 2 0 0 0 2 2h3",key:"x1gjn2"}]]),Sg=/[\0-\x1F!-,\.\/:-@\[-\^`\{-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0378\u0379\u037E\u0380-\u0385\u0387\u038B\u038D\u03A2\u03F6\u0482\u0530\u0557\u0558\u055A-\u055F\u0589-\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05EB-\u05EE\u05F3-\u060F\u061B-\u061F\u066A-\u066D\u06D4\u06DD\u06DE\u06E9\u06FD\u06FE\u0700-\u070F\u074B\u074C\u07B2-\u07BF\u07F6-\u07F9\u07FB\u07FC\u07FE\u07FF\u082E-\u083F\u085C-\u085F\u086B-\u089F\u08B5\u08C8-\u08D2\u08E2\u0964\u0965\u0970\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA\u09BB\u09C5\u09C6\u09C9\u09CA\u09CF-\u09D6\u09D8-\u09DB\u09DE\u09E4\u09E5\u09F2-\u09FB\u09FD\u09FF\u0A00\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A\u0A3B\u0A3D\u0A43-\u0A46\u0A49\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA\u0ABB\u0AC6\u0ACA\u0ACE\u0ACF\u0AD1-\u0ADF\u0AE4\u0AE5\u0AF0-\u0AF8\u0B00\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A\u0B3B\u0B45\u0B46\u0B49\u0B4A\u0B4E-\u0B54\u0B58-\u0B5B\u0B5E\u0B64\u0B65\u0B70\u0B72-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BF0-\u0BFF\u0C0D\u0C11\u0C29\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5B-\u0C5F\u0C64\u0C65\u0C70-\u0C7F\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4\u0CE5\u0CF0\u0CF3-\u0CFF\u0D0D\u0D11\u0D45\u0D49\u0D4F-\u0D53\u0D58-\u0D5E\u0D64\u0D65\u0D70-\u0D79\u0D80\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DE5\u0DF0\u0DF1\u0DF4-\u0E00\u0E3B-\u0E3F\u0E4F\u0E5A-\u0E80\u0E83\u0E85\u0E8B\u0EA4\u0EA6\u0EBE\u0EBF\u0EC5\u0EC7\u0ECE\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F01-\u0F17\u0F1A-\u0F1F\u0F2A-\u0F34\u0F36\u0F38\u0F3A-\u0F3D\u0F48\u0F6D-\u0F70\u0F85\u0F98\u0FBD-\u0FC5\u0FC7-\u0FFF\u104A-\u104F\u109E\u109F\u10C6\u10C8-\u10CC\u10CE\u10CF\u10FB\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B\u135C\u1360-\u137F\u1390-\u139F\u13F6\u13F7\u13FE-\u1400\u166D\u166E\u1680\u169B-\u169F\u16EB-\u16ED\u16F9-\u16FF\u170D\u1715-\u171F\u1735-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17D4-\u17D6\u17D8-\u17DB\u17DE\u17DF\u17EA-\u180A\u180E\u180F\u181A-\u181F\u1879-\u187F\u18AB-\u18AF\u18F6-\u18FF\u191F\u192C-\u192F\u193C-\u1945\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DA-\u19FF\u1A1C-\u1A1F\u1A5F\u1A7D\u1A7E\u1A8A-\u1A8F\u1A9A-\u1AA6\u1AA8-\u1AAF\u1AC1-\u1AFF\u1B4C-\u1B4F\u1B5A-\u1B6A\u1B74-\u1B7F\u1BF4-\u1BFF\u1C38-\u1C3F\u1C4A-\u1C4C\u1C7E\u1C7F\u1C89-\u1C8F\u1CBB\u1CBC\u1CC0-\u1CCF\u1CD3\u1CFB-\u1CFF\u1DFA\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FBD\u1FBF-\u1FC1\u1FC5\u1FCD-\u1FCF\u1FD4\u1FD5\u1FDC-\u1FDF\u1FED-\u1FF1\u1FF5\u1FFD-\u203E\u2041-\u2053\u2055-\u2070\u2072-\u207E\u2080-\u208F\u209D-\u20CF\u20F1-\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F-\u215F\u2189-\u24B5\u24EA-\u2BFF\u2C2F\u2C5F\u2CE5-\u2CEA\u2CF4-\u2CFF\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D70-\u2D7E\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E00-\u2E2E\u2E30-\u3004\u3008-\u3020\u3030\u3036\u3037\u303D-\u3040\u3097\u3098\u309B\u309C\u30A0\u30FB\u3100-\u3104\u3130\u318F-\u319F\u31C0-\u31EF\u3200-\u33FF\u4DC0-\u4DFF\u9FFD-\u9FFF\uA48D-\uA4CF\uA4FE\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA673\uA67E\uA6F2-\uA716\uA720\uA721\uA789\uA78A\uA7C0\uA7C1\uA7CB-\uA7F4\uA828-\uA82B\uA82D-\uA83F\uA874-\uA87F\uA8C6-\uA8CF\uA8DA-\uA8DF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA954-\uA95F\uA97D-\uA97F\uA9C1-\uA9CE\uA9DA-\uA9DF\uA9FF\uAA37-\uAA3F\uAA4E\uAA4F\uAA5A-\uAA5F\uAA77-\uAA79\uAAC3-\uAADA\uAADE\uAADF\uAAF0\uAAF1\uAAF7-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F\uAB5B\uAB6A-\uAB6F\uABEB\uABEE\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uE000-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB29\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFC-\uFDFF\uFE10-\uFE1F\uFE30-\uFE32\uFE35-\uFE4C\uFE50-\uFE6F\uFE75\uFEFD-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF3E\uFF40\uFF5B-\uFF65\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFFF]|\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDD3F\uDD75-\uDDFC\uDDFE-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEDF\uDEE1-\uDEFF\uDF20-\uDF2C\uDF4B-\uDF4F\uDF7B-\uDF7F\uDF9E\uDF9F\uDFC4-\uDFC7\uDFD0\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56-\uDC5F\uDC77-\uDC7F\uDC9F-\uDCDF\uDCF3\uDCF6-\uDCFF\uDD16-\uDD1F\uDD3A-\uDD7F\uDDB8-\uDDBD\uDDC0-\uDDFF\uDE04\uDE07-\uDE0B\uDE14\uDE18\uDE36\uDE37\uDE3B-\uDE3E\uDE40-\uDE5F\uDE7D-\uDE7F\uDE9D-\uDEBF\uDEC8\uDEE7-\uDEFF\uDF36-\uDF3F\uDF56-\uDF5F\uDF73-\uDF7F\uDF92-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCFF\uDD28-\uDD2F\uDD3A-\uDE7F\uDEAA\uDEAD-\uDEAF\uDEB2-\uDEFF\uDF1D-\uDF26\uDF28-\uDF2F\uDF51-\uDFAF\uDFC5-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC47-\uDC65\uDC70-\uDC7E\uDCBB-\uDCCF\uDCE9-\uDCEF\uDCFA-\uDCFF\uDD35\uDD40-\uDD43\uDD48-\uDD4F\uDD74\uDD75\uDD77-\uDD7F\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDFF\uDE12\uDE38-\uDE3D\uDE3F-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEA9-\uDEAF\uDEEB-\uDEEF\uDEFA-\uDEFF\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A\uDF45\uDF46\uDF49\uDF4A\uDF4E\uDF4F\uDF51-\uDF56\uDF58-\uDF5C\uDF64\uDF65\uDF6D-\uDF6F\uDF75-\uDFFF]|\uD805[\uDC4B-\uDC4F\uDC5A-\uDC5D\uDC62-\uDC7F\uDCC6\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDB6\uDDB7\uDDC1-\uDDD7\uDDDE-\uDDFF\uDE41-\uDE43\uDE45-\uDE4F\uDE5A-\uDE7F\uDEB9-\uDEBF\uDECA-\uDEFF\uDF1B\uDF1C\uDF2C-\uDF2F\uDF3A-\uDFFF]|\uD806[\uDC3B-\uDC9F\uDCEA-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD36\uDD39\uDD3A\uDD44-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD8\uDDD9\uDDE2\uDDE5-\uDDFF\uDE3F-\uDE46\uDE48-\uDE4F\uDE9A-\uDE9C\uDE9E-\uDEBF\uDEF9-\uDFFF]|\uD807[\uDC09\uDC37\uDC41-\uDC4F\uDC5A-\uDC71\uDC90\uDC91\uDCA8\uDCB7-\uDCFF\uDD07\uDD0A\uDD37-\uDD39\uDD3B\uDD3E\uDD48-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8F\uDD92\uDD99-\uDD9F\uDDAA-\uDEDF\uDEF7-\uDFAF\uDFB1-\uDFFF]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD80B\uD80E-\uD810\uD812-\uD819\uD824-\uD82B\uD82D\uD82E\uD830-\uD833\uD837\uD839\uD83D\uD83F\uD87B-\uD87D\uD87F\uD885-\uDB3F\uDB41-\uDBFF][\uDC00-\uDFFF]|\uD80D[\uDC2F-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDECF\uDEEE\uDEEF\uDEF5-\uDEFF\uDF37-\uDF3F\uDF44-\uDF4F\uDF5A-\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDE3F\uDE80-\uDEFF\uDF4B-\uDF4E\uDF88-\uDF8E\uDFA0-\uDFDF\uDFE2\uDFE5-\uDFEF\uDFF2-\uDFFF]|\uD821[\uDFF8-\uDFFF]|\uD823[\uDCD6-\uDCFF\uDD09-\uDFFF]|\uD82C[\uDD1F-\uDD4F\uDD53-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A-\uDC9C\uDC9F-\uDFFF]|\uD834[\uDC00-\uDD64\uDD6A-\uDD6C\uDD73-\uDD7A\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDE41\uDE45-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3\uDFCC\uDFCD]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85-\uDE9A\uDEA0\uDEB0-\uDFFF]|\uD838[\uDC07\uDC19\uDC1A\uDC22\uDC25\uDC2B-\uDCFF\uDD2D-\uDD2F\uDD3E\uDD3F\uDD4A-\uDD4D\uDD4F-\uDEBF\uDEFA-\uDFFF]|\uD83A[\uDCC5-\uDCCF\uDCD7-\uDCFF\uDD4C-\uDD4F\uDD5A-\uDFFF]|\uD83B[\uDC00-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDFFF]|\uD83C[\uDC00-\uDD2F\uDD4A-\uDD4F\uDD6A-\uDD6F\uDD8A-\uDFFF]|\uD83E[\uDC00-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEDE-\uDEFF]|\uD86D[\uDF35-\uDF3F]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEA2-\uDEAF]|\uD87A[\uDFE1-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDFFF]|\uDB40[\uDC00-\uDCFF\uDDF0-\uDFFF]/g,Sx=Object.hasOwnProperty;var Sv=e.i(216920);let S_={},Sy=new class{constructor(){this.occurrences,this.reset()}slug(e,r){var s,n;let i=(s=e,n=!0===r,"string"!=typeof s?"":(n||(s=s.toLowerCase()),s.replace(Sg,"").replace(/ /g,"-"))),a=i;for(;Sx.call(this.occurrences,i);)this.occurrences[a]++,i=a+"-"+this.occurrences[a];return this.occurrences[i]=0,i}reset(){this.occurrences=Object.create(null)}};function Sb(e){let r=(e||S_).prefix||"";return function(e){Sy.reset(),(0,Sv.visit)(e,"element",function(e){let s,n;((n=2===(s="element"===e.type?e.tagName.toLowerCase():"").length&&104===s.charCodeAt(0)?s.charCodeAt(1):0)>48&&n<55?n-48:void 0)&&!e.properties.id&&(e.properties.id=r+Sy.slug("children"in e?function e(r){let s=-1,n=[];for(;++s<r.children.length;){var i;n[s]="text"===(i=r.children[s]).type?i.value:"children"in i?e(i):""}return n.join("")}(e):"value"in e?e.value:""))})}}var Sw=cC,H=H,SS=e.i(829692),SS=SS,Sj=e.i(615742);let SC=(0,$.createContext)({code:""}),Sk={name:"line-data",line(e,r){e.properties["data-line"]=String(r)}},SN={name:"line-numbers",line(e,r){e.children.unshift({type:"element",tagName:"span",properties:{className:["inline-block","min-w-10","mr-2","text-right","select-none","text-muted-foreground"]},children:[{type:"text",value:String(r)}]})}};async function SE(e,r,s=!1,n){let i=[Sk];return n&&n.size>0&&i.push({name:"fold-gutter",line(e,r){e.children.unshift({type:"element",tagName:"span",properties:n.has(r)?{className:["code-fold-toggle"],"data-fold-start":String(r)}:{className:["code-fold-spacer"]},children:[]})}}),s&&i.push(SN),await Promise.all([(0,Sj.codeToHtml)(e,{lang:r,theme:"one-light",transformers:i}),(0,Sj.codeToHtml)(e,{lang:r,theme:"one-dark-pro",transformers:i})])}let SD=(0,$.forwardRef)(function({code:e,language:r,showLineNumbers:s=!1,scrollToLine:n,scrollKey:i,foldable:a=!1,className:o,children:l,...c},d){let[u,h]=(0,$.useState)(""),[f,p]=(0,$.useState)(""),m=(0,$.useRef)(!1),g=(0,$.useRef)(null),x=(0,$.useMemo)(()=>a?function(e,r={}){return function(...e){let r=new Map;for(let s of e.flat())!(s.endLine<=s.startLine)&&(r.has(s.startLine)||r.set(s.startLine,s));let s=[...r.values()].sort((e,r)=>e.startLine-r.startLine||r.endLine-e.endLine),n=[],i=[];for(let e of s){for(;i.length&&i[i.length-1].endLine<e.startLine;)i.pop();let r=i[i.length-1];r&&e.endLine>r.endLine||(n.push(e),i.push(e))}return n}((r.tokenIndex,[]),function(e){let r=e.split("\n"),s=[],n=[],i=0,a=e=>{i>e.line&&s.push({startLine:e.line+1,endLine:i+1})};for(let e=0;e<r.length;e++){let s=function(e){let r=e.match(/^[ \t]*/),s=r?r[0].length:0;return s===e.length?null:s}(r[e]);if(null!==s){for(;n.length&&n[n.length-1].indent>=s;)a(n.pop());n.push({indent:s,line:e}),i=e}}for(;n.length;)a(n.pop());return s}(e))}(e):[],[a,e]),v=(0,$.useMemo)(()=>new Set(x.map(e=>e.startLine)),[x]),[_,y]=(0,$.useState)(new Set),[b,w]=(0,$.useState)(e),[S,j]=(0,$.useState)({line:n,key:i});if((0,$.useImperativeHandle)(d,()=>({foldAll:()=>y(new Set(x.map(e=>e.startLine))),expandAll:()=>y(new Set)}),[x]),(0,$.useEffect)(()=>(SE(e,r,s,v).then(([e,r])=>{m.current||(h(e),p(r),m.current=!0)}),()=>{m.current=!1}),[e,r,s,v]),(0,$.useEffect)(()=>{let e=g.current;if(!e)return;let r=new Map(x.map(e=>[e.startLine,e])),s=new Set;for(let e of _){let n=r.get(e);if(n)for(let e=n.startLine+1;e<=n.endLine;e++)s.add(e)}for(let r of e.querySelectorAll("[data-line]")){let e=Number(r.getAttribute("data-line"));r.style.display=s.has(e)?"none":"",r.classList.toggle("code-line-collapsed",_.has(e))}},[_,x,u,f]),(0,$.useEffect)(()=>{if(!a)return;let e=g.current;if(!e)return;let r=e=>{let r=e.target?.closest?.("[data-fold-start]");if(!r)return;e.stopPropagation(),e.preventDefault();let s=Number(r.getAttribute("data-fold-start"));y(e=>{let r=new Set(e);return r.has(s)?r.delete(s):r.add(s),r})};return e.addEventListener("click",r),()=>e.removeEventListener("click",r)},[a]),(0,$.useEffect)(()=>{if(null==n)return;let e=g.current;if(!e||!u&&!f)return;let r=Array.from(e.querySelectorAll(`[data-line="${n}"]`));if(0===r.length)return;let s=r.find(e=>null!==e.offsetParent)??r[0],i=requestAnimationFrame(()=>{s.scrollIntoView({block:"center",behavior:"auto"}),r.forEach(e=>e.classList.add("code-line-highlight"))}),a=window.setTimeout(()=>r.forEach(e=>e.classList.remove("code-line-highlight")),1600);return()=>{cancelAnimationFrame(i),window.clearTimeout(a),r.forEach(e=>e.classList.remove("code-line-highlight"))}},[n,i,u,f]),e!==b&&(w(e),y(new Set)),(S.line!==n||S.key!==i)&&(j({line:n,key:i}),null!=n&&_.size>0)){let e=!1,r=new Set(_);for(let s of x)r.has(s.startLine)&&n>s.startLine&&n<=s.endLine&&(r.delete(s.startLine),e=!0);e&&y(r)}return(0,O.jsx)(SC.Provider,{value:{code:e},children:(0,O.jsx)("div",{ref:g,className:(0,ey.cn)("group relative w-full overflow-hidden rounded-md border bg-background text-foreground",o),...c,children:(0,O.jsxs)("div",{className:"relative",children:[(0,O.jsx)("div",{className:"overflow-auto dark:hidden [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:grid [&_code]:font-mono [&_code]:text-sm",dangerouslySetInnerHTML:{__html:u}}),(0,O.jsx)("div",{className:"hidden overflow-auto dark:block [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:grid [&_code]:font-mono [&_code]:text-sm",dangerouslySetInnerHTML:{__html:f}}),l&&(0,O.jsx)("div",{className:"absolute top-2 right-2 flex items-center gap-2",children:l})]})})})}),SR=({onCopy:e,onError:r,timeout:s=2e3,children:n,className:i,...a})=>{let[o,l]=(0,$.useState)(!1),{code:c}=(0,$.useContext)(SC),d=async()=>{if(!navigator?.clipboard?.writeText)return void r?.(Error("Clipboard API not available"));try{await navigator.clipboard.writeText(c),l(!0),e?.(),setTimeout(()=>l(!1),s)}catch(e){r?.(e)}},u=o?H.default:SS.default;return(0,O.jsx)(W.Button,{className:(0,ey.cn)("shrink-0",i),onClick:d,size:"icon",variant:"ghost",...a,children:n??(0,O.jsx)(u,{size:14})})};function SA({className:e,...r}){return(0,O.jsx)("div",{"data-slot":"skeleton",className:(0,ey.cn)("bg-accent animate-pulse rounded-md",e),...r})}function ST({projectId:e,symbol:r,branch:s,target:n,currentFile:i,anchor:a,onJump:o,onClose:l}){let[c,d]=(0,$.useState)(!0),[u,h]=(0,$.useState)([]),[f,p]=(0,$.useState)(!1),m=(0,$.useRef)(null);(0,$.useEffect)(()=>{let i=!0;return d(!0),rv.api.searchSymbol(e,r,s,n).then(e=>{i&&(h(e.hits),p(e.truncated))}).catch(()=>{i&&h([])}).finally(()=>{i&&d(!1)}),()=>{i=!1}},[e,r,s,n]),(0,$.useEffect)(()=>{let e=e=>{e.detail>=2||m.current&&!m.current.contains(e.target)&&l()},s=e=>{if("Escape"===e.key)return void l();if((e.metaKey||e.ctrlKey)&&("c"===e.key||"C"===e.key)){let s=window.getSelection();if(s&&s.rangeCount>0&&!s.isCollapsed)return;e.preventDefault(),navigator.clipboard?.writeText(r)}};return document.addEventListener("mousedown",e),document.addEventListener("keydown",s),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",s)}},[l,r]);let g=(e,r)=>Number(r.file===i)-Number(e.file===i),x=u.filter(e=>"definition"===e.kind).sort(g),v=u.filter(e=>"reference"===e.kind).sort(g),_=Math.max(8,Math.min(a.x,window.innerWidth-440-8)),y=window.innerHeight-8-(a.y+18),b=a.y-18-8,w=y>=340||y>=b,S=Math.max(120,Math.min(340,w?y:b)),j=w?{top:a.y+18}:{bottom:window.innerHeight-(a.y-18)},C=({hit:e})=>(0,O.jsxs)("button",{type:"button",onClick:()=>{o(e.file,e.line),l()},className:"flex w-full flex-col items-start gap-0.5 rounded px-2 py-1.5 text-left hover:bg-accent",children:[(0,O.jsxs)("span",{className:"flex w-full items-baseline justify-between gap-2",children:[(0,O.jsxs)("span",{className:"truncate font-mono text-xs",children:[e.file.split("/").pop(),(0,O.jsxs)("span",{className:"text-muted-foreground",children:[":",e.line]})]}),e.file===i&&(0,O.jsx)("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:"this file"})]}),(0,O.jsx)("code",{className:"w-full truncate text-xs text-muted-foreground",children:e.text.trim()})]}),k=({title:e,children:r})=>(0,O.jsxs)("div",{className:"mb-1",children:[(0,O.jsx)("div",{className:"px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:e}),r]});return(0,ee.createPortal)((0,O.jsxs)("div",{ref:m,style:{left:_,...j,width:440,maxHeight:S},className:"fixed z-50 flex flex-col overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-lg select-none",children:[(0,O.jsx)("div",{className:"border-b px-3 py-1.5 text-xs font-medium",children:(0,O.jsx)("span",{className:"font-mono",children:r})}),(0,O.jsx)("div",{className:"flex-1 overflow-auto p-1",children:c?(0,O.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"})," Searching…"]}):0===u.length?(0,O.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No results."}):(0,O.jsxs)(O.Fragment,{children:[x.length>0&&(0,O.jsx)(k,{title:`Definitions (${x.length})`,children:x.map((e,r)=>(0,O.jsx)(C,{hit:e},`d-${r}`))}),v.length>0&&(0,O.jsx)(k,{title:`References (${v.length})`,children:v.map((e,r)=>(0,O.jsx)(C,{hit:e},`r-${r}`))}),f&&(0,O.jsx)("div",{className:"px-2 py-1.5 text-[11px] text-muted-foreground",children:"Showing first matches — results truncated."})]})})]}),document.body)}let SM=(0,ew.default)("image-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]);function SF({projectId:e,filePath:r,branch:s,target:n,onDownload:i}){let[a,o]=(0,$.useState)(null),[l,c]=(0,$.useState)(!1);return((0,$.useEffect)(()=>{let i=null,a=!1;return rv.api.getFileBlob(e,r,s,n).then(e=>{a||o(i=URL.createObjectURL(e))}).catch(()=>{a||c(!0)}),()=>{a=!0,i&&URL.revokeObjectURL(i)}},[e,r,s,n]),l)?(0,O.jsxs)("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[(0,O.jsx)(SM,{className:"h-10 w-10"}),(0,O.jsx)("p",{className:"text-sm",children:"Couldn't load image"}),(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:i,children:[(0,O.jsx)(Su,{className:"h-4 w-4 mr-2"}),"Download"]})]}):a?(0,O.jsx)("div",{className:"flex items-center justify-center h-full p-4 bg-muted/30",children:(0,O.jsx)("img",{src:a,alt:r.split("/").pop()??"image",className:"max-w-full max-h-full object-contain",onError:()=>c(!0)})}):(0,O.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,O.jsx)(sj,{className:"h-6 w-6 animate-spin"})})}async function SP(e,r){let s=await (0,Sj.codeToTokensBase)(e,{lang:r,theme:"one-light",includeExplanation:"scopeName"}),n=new Map;return s.forEach((e,r)=>{let s=0,i=[];for(let r of e){let e=(r.explanation??[]).flatMap(e=>e.scopes.map(e=>e.scopeName)),n=s+r.content.length;i.push({start:s,end:n,kind:e.some(e=>e.startsWith("comment"))?"comment":e.some(e=>e.startsWith("string")||e.startsWith("constant.character"))?"string":e.some(e=>e.startsWith("keyword")||e.startsWith("storage")||e.startsWith("constant.language")||e.startsWith("variable.language"))?"keyword":"code"}),s=n}n.set(r+1,i)}),n}let SI=new Set(["png","jpg","jpeg","gif","webp","bmp","ico","avif","svg"]);function SB(e){let r=e.split("/").pop()?.split(".").pop()?.toLowerCase()??"";return SI.has(r)}let SL=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Sz="symbol-nav";function SO(e,r,s){let n=document.createRange();return n.selectNodeContents(e),n.setEnd(r,s),n.toString().length}function S$(e,r){let s,n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),i=0;for(;s=n.nextNode();){let e=(s.textContent??"").length;if(r<=i+e)return{node:s,offset:r-i};i+=e}return null}function SW(e){let r=Array.from(document.querySelectorAll(`[data-line="${CSS.escape(e.line)}"]`)),s=r.find(e=>null!==e.offsetParent)??r[0];if(!s)return null;let n=S$(s,e.start),i=S$(s,e.end);if(!n||!i)return null;let a=document.createRange();return a.setStart(n.node,n.offset),a.setEnd(i.node,i.offset),a}let SH=/[A-Za-z0-9_$]/;function SU(e,r,s){let n=document,i=null,a=0;if(n.caretRangeFromPoint){let s=n.caretRangeFromPoint(e,r);s&&(i=s.startContainer,a=s.startOffset)}else if(n.caretPositionFromPoint){let s=n.caretPositionFromPoint(e,r);s&&(i=s.offsetNode,a=s.offset)}if(!i||i.nodeType!==Node.TEXT_NODE)return null;let o=i.textContent??"",l=a,c=a;for(;l>0&&SH.test(o[l-1]);)l--;for(;c<o.length&&SH.test(o[c]);)c++;if(l>=c)return null;let d=o.slice(l,c);if(!SL.test(d))return null;let u=document.createRange();u.setStart(i,l),u.setEnd(i,c);let h=function(e){let r=e.startContainer.nodeType===Node.ELEMENT_NODE?e.startContainer:e.startContainer.parentElement,s=r?.closest("[data-line]");if(!s||!s.contains(e.endContainer))return null;let n=s.getAttribute("data-line");if(null===n)return null;let i=SO(s,e.startContainer,e.startOffset),a=SO(s,e.endContainer,e.endOffset);return i>=a?null:{line:n,start:i,end:a}}(u);if(!h)return null;if(s){let e=h.start-h.line.length,r=function(e,r,s){let n=e.get(r);if(!n)return null;for(let e of n)if(s>=e.start&&s<e.end)return e.kind;return null}(s,Number(h.line),e);if(r&&"code"!==r)return null}return{word:d,anchor:h}}function Sq(){return"undefined"!=typeof CSS&&"highlights"in CSS&&"undefined"!=typeof Highlight}let SK=!1;function SV(){Sq()&&CSS.highlights.delete(Sz)}let SY={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",css:"css",scss:"scss",html:"html",vue:"vue",svelte:"svelte",php:"php",swift:"swift",kt:"kotlin",sh:"bash",bash:"bash",zsh:"bash",yaml:"yaml",yml:"yaml",toml:"toml",json:"json",xml:"xml",sql:"sql",graphql:"graphql",md:"markdown",mdx:"mdx",dockerfile:"dockerfile",makefile:"makefile",lua:"lua",r:"r",scala:"scala",zig:"zig"};function SG(e){let r=e.split("/").pop()?.toLowerCase()??"";return"dockerfile"===r?"dockerfile":"makefile"===r?"makefile":SY[r.split(".").pop()?.toLowerCase()??""]??"text"}function SX(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function SJ({filePath:e,fileContent:r,loading:s,downloadUrl:n,projectId:i,branch:a,target:o,scrollToLine:l,scrollKey:c,onJump:d,restoreScrollTop:u,restoreScrollKey:h,onScroll:f}){let p,[m,g]=(0,$.useState)("rendered"),[x,v]=(0,$.useState)(e),[_,y]=(0,$.useState)(null),b=(0,$.useRef)(null),w=(0,$.useRef)(null),S=(0,$.useRef)(!1);(0,$.useEffect)(()=>{S.current=null!==_},[_]);let j=(0,$.useCallback)(e=>{if(e.detail>=2){let r=window.getSelection();if(S.current){r?.removeAllRanges(),y(e=>e?{...e,selectWord:!0}:e);return}let s=SU(e.clientX,e.clientY),n=s?SW(s.anchor):null;n&&(r?.removeAllRanges(),r?.addRange(n));return}let r=window.getSelection();if(r&&!r.isCollapsed)return;let s=SU(e.clientX,e.clientY,b.current);s&&(r?.removeAllRanges(),y({symbol:s.word,x:e.clientX,y:e.clientY,anchor:s.anchor,selectWord:!1}))},[]),C=(0,$.useCallback)(e=>{e.detail>=2&&e.preventDefault()},[]);(0,$.useEffect)(()=>{if(!_?.anchor)return void SV();let e=SW(_.anchor);if(!e)return void SV();if(_.selectWord){SV();let r=window.getSelection();r?.removeAllRanges(),r?.addRange(e);return}return Sq()?(!function(){if(SK||"undefined"==typeof document)return;SK=!0;let e=document.createElement("style");e.textContent=`::highlight(${Sz}){background-color:rgba(255, 196, 0, 0.32);}`,document.head.appendChild(e)}(),CSS.highlights.set(Sz,new Highlight(e)),SV):void SV()},[_]),(0,$.useEffect)(()=>{b.current=null;let s=r?.content;if(!e||null==s||r?.binary||r?.tooLarge)return;let n=!1;return SP(s,SG(e)).then(e=>{n||(b.current=e)}).catch(()=>{}),()=>{n=!0}},[e,r]);let k=(0,$.useRef)(null),N=(0,$.useRef)(null),E=(0,$.useCallback)(e=>{let r=k.current;if(!r)return;let s=r.querySelector(`[id="${CSS.escape(e)}"]`);if(!s)return;N.current?.();let n=()=>s.scrollIntoView({block:"start",behavior:"auto"});n();let i=new ResizeObserver(n);i.observe(r);let a=()=>{i.disconnect(),window.clearTimeout(o),window.removeEventListener("wheel",a),window.removeEventListener("touchmove",a),window.removeEventListener("keydown",a),N.current=null},o=window.setTimeout(a,1e3);window.addEventListener("wheel",a,{passive:!0}),window.addEventListener("touchmove",a,{passive:!0}),window.addEventListener("keydown",a),N.current=a},[]);(0,$.useEffect)(()=>()=>N.current?.(),[]);let D=(0,$.useRef)(null),R=(0,$.useRef)(!1),A=(0,$.useRef)(f);A.current=f;let T=(0,$.useRef)(null),M=(0,$.useRef)(null),F=(0,$.useCallback)(e=>{if(R.current)return;let r=e.currentTarget.scrollTop;T.current&&clearTimeout(T.current),T.current=setTimeout(()=>A.current?.(r),200)},[]);(0,$.useEffect)(()=>{void 0!==h&&(M.current=u??0)},[h,u]),(0,$.useEffect)(()=>{let e=D.current;e&&(e.scrollTop=0)},[e]),(0,$.useEffect)(()=>{let e=M.current;if(null==e)return;let r=D.current;if(!r||(M.current=null,!e))return;R.current=!0;let s=()=>{r.scrollTop=e};s();let n=new ResizeObserver(s);n.observe(r.firstElementChild??r);let i=()=>{R.current=!1,n.disconnect(),window.clearTimeout(a),r.removeEventListener("wheel",i),r.removeEventListener("touchmove",i),r.removeEventListener("keydown",i)},a=window.setTimeout(i,1500);return r.addEventListener("wheel",i,{passive:!0}),r.addEventListener("touchmove",i,{passive:!0}),r.addEventListener("keydown",i),i},[r]);let P=(0,$.useMemo)(()=>[...Object.values(Sw.e),Sb],[]),I=(0,$.useMemo)(()=>({a:({href:e,children:r,className:s,node:n,...i})=>{let a="string"==typeof e&&e.startsWith("#");return(0,O.jsx)("a",{href:e,className:(0,ey.cn)("wrap-anywhere font-medium text-primary underline",s),"data-streamdown":"link",...a?{onClick:r=>{r.preventDefault(),E(decodeURIComponent(e.slice(1)))}}:{target:"_blank",rel:"noreferrer"},...i,children:r})}}),[E]);if(e!==x&&(v(e),g("rendered"),y(null)),!e)return(0,O.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Select a file to preview."});if(s)return(0,O.jsxs)("div",{className:"flex flex-col h-full",children:[(0,O.jsx)("div",{className:"flex items-center justify-between px-4 py-2 border-b flex-shrink-0",children:(0,O.jsx)(SA,{className:"h-4 w-48"})}),(0,O.jsxs)("div",{className:"flex-1 p-4",children:[(0,O.jsx)(SA,{className:"h-4 w-full mb-2"}),(0,O.jsx)(SA,{className:"h-4 w-3/4 mb-2"}),(0,O.jsx)(SA,{className:"h-4 w-5/6 mb-2"}),(0,O.jsx)(SA,{className:"h-4 w-2/3"})]})]});if(!r)return(0,O.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Failed to load file."});let B=()=>{e&&rv.api.downloadFile(i,e,a,o).catch(e=>{console.error("Failed to download file",e)})},L=("markdown"===(p=SG(e))||"mdx"===p)&&!r.tooLarge&&!r.binary&&!!r.content,z=L&&"rendered"===m,H=!r.tooLarge&&!r.binary&&!z&&null!==r.content;return(0,O.jsxs)("div",{className:"flex flex-col h-full",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b flex-shrink-0 gap-2",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,O.jsx)("span",{className:"text-sm font-mono truncate",children:e}),(0,O.jsx)("span",{className:"text-xs text-muted-foreground shrink-0",children:SX(r.size)})]}),(0,O.jsxs)("div",{className:"flex items-center gap-1 shrink-0",children:[L&&(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(e=>"rendered"===e?"source":"rendered"),title:z?"View source":"View rendered",children:z?(0,O.jsx)(Sf,{className:"h-3.5 w-3.5"}):(0,O.jsx)(wf,{className:"h-3.5 w-3.5"})}),H&&(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>w.current?.foldAll(),title:"Fold all",children:(0,O.jsx)(Sp,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>w.current?.expandAll(),title:"Expand all",children:(0,O.jsx)(Sm,{className:"h-3.5 w-3.5"})})]}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{navigator.clipboard.writeText(e)},title:"Copy path",children:(0,O.jsx)(fq.Copy,{className:"h-3.5 w-3.5"})}),n&&(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:B,title:"Download",children:(0,O.jsx)(Su,{className:"h-3.5 w-3.5"})})]})]}),(0,O.jsx)("div",{className:"flex-1 overflow-auto",ref:D,onScroll:F,children:r.tooLarge?(0,O.jsxs)("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[(0,O.jsx)(Sh,{className:"h-10 w-10"}),(0,O.jsxs)("p",{className:"text-sm",children:["File too large to preview (",SX(r.size),")"]}),n&&(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:B,children:[(0,O.jsx)(Su,{className:"h-4 w-4 mr-2"}),"Download"]})]}):r.binary&&SB(e)&&r.size<=0xa00000?(0,O.jsx)(SF,{projectId:i,filePath:e,branch:a,target:o,onDownload:B},e):r.binary?(0,O.jsxs)("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[(0,O.jsx)(Sh,{className:"h-10 w-10"}),(0,O.jsx)("p",{className:"text-sm",children:SB(e)?`Image too large to preview (${SX(r.size)})`:`Binary file (${SX(r.size)})`}),n&&(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:B,children:[(0,O.jsx)(Su,{className:"h-4 w-4 mr-2"}),"Download"]})]}):z?(0,O.jsx)("div",{className:"p-4",style:{fontSize:"var(--files-content-font-size, 14px)"},ref:k,children:(0,O.jsx)(cD,{components:I,rehypePlugins:P,children:r.content??""})}):null!==r.content?(0,O.jsx)("div",{className:"h-full [&_pre]:text-[length:var(--files-content-font-size,14px)]! [&_code]:text-[length:var(--files-content-font-size,14px)]!",onMouseDown:C,onClick:j,children:(0,O.jsx)(SD,{ref:w,code:r.content,language:SG(e),showLineNumbers:!0,foldable:!0,scrollToLine:l,scrollKey:c,className:"border-0 rounded-none",children:(0,O.jsx)(SR,{})})}):(0,O.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:"Empty file."})}),_&&(0,O.jsx)(ST,{projectId:i,symbol:_.symbol,branch:a,target:o,currentFile:e,anchor:{x:_.x,y:_.y},onJump:d,onClose:()=>y(null)})]})}class SZ{capacity;map;constructor(e){if(this.capacity=e,this.map=new Map,e<1)throw Error("LRUCache capacity must be at least 1")}get(e){if(!this.map.has(e))return;let r=this.map.get(e);return this.map.delete(e),this.map.set(e,r),r}has(e){return this.map.has(e)}set(e,r){for(this.map.has(e)&&this.map.delete(e),this.map.set(e,r);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(void 0===e)break;this.map.delete(e)}}delete(e){return this.map.delete(e)}deleteWhere(e){for(let r of[...this.map.keys()])e(r)&&this.map.delete(r)}clear(){this.map.clear()}get size(){return this.map.size}}let SQ="vibedeckx:files:views";function S0(){return{v:1,views:{}}}function S1(){try{let e=localStorage.getItem(SQ);if(!e)return S0();let r=JSON.parse(e);if(!r||1!==r.v||!r.views||"object"!=typeof r.views)return S0();return r}catch{return S0()}}function S2(e){try{localStorage.setItem(SQ,JSON.stringify(e))}catch{}}function S5(e){return e.slice(e.lastIndexOf("\0")+1)}let S3=new Set(["/","-","_","."," "]);function S4({projectId:e,project:r,selectedBranch:s,navRequest:n}){let i=r&&!r.path?"remote":void 0,[a,o]=(0,$.useState)(!1),{settings:l}=(0,hG.useConversationSettings)(),c=(0,$.useRef)(null),[d,u]=(0,$.useState)(!1),h=(0,$.useCallback)(()=>{let e=c.current;e&&(e.isCollapsed()?e.expand():e.collapse())},[]),{rootEntries:f,directoryContents:p,expandedDirs:m,selectedFile:g,fileContent:x,fileLoading:v,rootLoading:_,loadingDirs:y,uploadingDirs:b,deletingPaths:w,jumpTarget:S,canGoBack:j,canGoForward:C,fetchRoot:k,refresh:N,reportScroll:E,restoreScroll:D,toggleDirectory:R,navigate:A,jumpTo:T,goBack:M,goForward:F,uploadFiles:P,deleteEntry:I}=function({projectId:e,branch:r,target:s,showHidden:n=!1}){let[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)(new Map),[c,d]=(0,$.useState)(new Set),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(null),[m,g]=(0,$.useState)(null),x=(0,$.useRef)(0),[v,_]=(0,$.useState)({entries:[],index:-1}),y=(0,$.useRef)(v);y.current=v;let[b,w]=(0,$.useState)(!1),[S,j]=(0,$.useState)(!1),[C,k]=(0,$.useState)(new Set),[N,E]=(0,$.useState)(new Set),[D,R]=(0,$.useState)(new Set),A=(0,$.useRef)(0),T=(0,$.useRef)(0),M=(0,$.useRef)(new SZ(50)),F=e?[e,r??"",s??""].join("|"):null,P=(0,$.useRef)(F);P.current=F;let I=(0,$.useRef)(u);I.current=u;let B=(0,$.useRef)(0),L=(0,$.useRef)(null),z=(0,$.useRef)(0),[O,W]=(0,$.useState)(null),H=(0,$.useRef)(null),U=(0,$.useCallback)(n=>[e,r??"",s??"",n].join("\0"),[e,r,s]),q=(0,$.useCallback)(()=>{let e,r,s=P.current;if(!s||L.current!==s)return;let n={selectedFile:I.current,history:y.current,scrollTop:B.current};(e=S1()).views[s]={...n,updatedAt:Date.now()},(r=Object.keys(e.views)).length>30&&r.sort((r,s)=>e.views[r].updatedAt-e.views[s].updatedAt).slice(0,r.length-30).forEach(r=>delete e.views[r]),S2(e)},[]),K=(0,$.useCallback)(()=>{H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{H.current=null,q()},300)},[q]),V=(0,$.useCallback)(e=>{B.current=e,K()},[K]);(0,$.useEffect)(()=>{K()},[u,v,K]);let Y=(0,$.useCallback)(async i=>{if(e&&(d(e=>{let r=new Set(e);return r.has(i)?r.delete(i):r.add(i),r}),!o.has(i))){k(e=>new Set(e).add(i));try{let a=await rv.api.browseProjectDirectory(e,i,r,s,n);l(e=>{let r=new Map(e);return r.set(i,a.items),r})}catch(e){console.error("Failed to browse directory:",e),_Z.toast.error(`Failed to open ${i}`,{description:e instanceof Error?e.message:String(e)})}finally{k(e=>{let r=new Set(e);return r.delete(i),r})}}},[e,r,s,n,o]),G=(0,$.useCallback)(async n=>{if(!e)return"failed";let i=U(n),a=M.current.get(i);if(a)return p(a),w(!1),"loaded";let o=++T.current;w(!0),p(null);try{let a=await rv.api.getFileContent(e,n,r,s);if(o!==T.current)return"stale";return M.current.set(i,a),p(a),"loaded"}catch(e){if(o!==T.current)return"stale";return console.error("Failed to get file content:",e),p(null),"failed"}finally{o===T.current&&w(!1)}},[e,r,s,U]),X=(0,$.useCallback)(async r=>{e&&(h(r),await G(r))},[e,G]),J=(0,$.useCallback)(async()=>{if(!e)return!1;j(!0);let i=++A.current;try{let o=await rv.api.browseProjectDirectory(e,void 0,r,s,n);if(i!==A.current)return!1;return a(o.items),l(new Map),d(new Set),!0}catch(e){if(console.error("Failed to browse root directory:",e),i!==A.current)return!1;return a([]),_Z.toast.error("Failed to browse files",{description:e instanceof Error?e.message:String(e)}),!1}finally{i===A.current&&j(!1)}},[e,r,s,n]),Z=(0,$.useCallback)(async()=>{let r;if(!e||!await J())return;let s=P.current,n=s?(r=S1().views[s])&&"object"==typeof r&&(null===r.selectedFile||"string"==typeof r.selectedFile)&&r.history&&"object"==typeof r.history&&Array.isArray(r.history.entries)&&"number"==typeof r.history.index?{selectedFile:r.selectedFile,history:r.history,scrollTop:"number"==typeof r.scrollTop&&Number.isFinite(r.scrollTop)?r.scrollTop:0}:null:null;if(s&&n&&n.selectedFile){if(_(n.history.entries.length?n.history:{entries:[{path:n.selectedFile,line:null}],index:0}),B.current=n.scrollTop,W({top:n.scrollTop,nonce:++z.current}),h(n.selectedFile),L.current=s,"failed"===await G(n.selectedFile)){let e;h(null),_({entries:[],index:-1}),B.current=0,(e=S1()).views[s]&&(delete e.views[s],S2(e))}}else h(null),p(null),_({entries:[],index:-1}),B.current=0,L.current=s},[e,J,G]),Q=(0,$.useCallback)(async()=>{if(!e||(M.current.clear(),!await J()))return;let r=I.current;r&&await G(r)},[e,J,G]),ee=(0,$.useCallback)(async(e,r=null)=>{_(({entries:s,index:n})=>{let i=s[n];if(i&&i.path===e){let i=s.slice();return i[n]={path:e,line:r},{entries:i,index:n}}let a=s.slice(0,n+1);return{entries:[...a,{path:e,line:r}],index:a.length}}),await X(e),null!=r&&g({line:r,nonce:++x.current})},[X]),et=(0,$.useCallback)((e,r)=>ee(e,r),[ee]),er=(0,$.useCallback)(()=>{let{entries:e,index:r}=y.current;if(r<=0)return;let s=e[r-1];_(e=>({...e,index:e.index-1})),X(s.path),null!=s.line&&g({line:s.line,nonce:++x.current})},[X]),es=(0,$.useCallback)(()=>{let{entries:e,index:r}=y.current;if(r>=e.length-1)return;let s=e[r+1];_(e=>({...e,index:e.index+1})),X(s.path),null!=s.line&&g({line:s.line,nonce:++x.current})},[X]),en=(0,$.useCallback)(async i=>{if(e)if(""===i)a((await rv.api.browseProjectDirectory(e,void 0,r,s,n)).items);else{let a=await rv.api.browseProjectDirectory(e,i,r,s,n);l(e=>{let r=new Map(e);return r.set(i,a.items),r})}},[e,r,s,n]),ei=(0,$.useCallback)(async(n,i)=>{if(e&&0!==i.length){E(e=>new Set(e).add(n));try{let{uploaded:a}=await rv.api.uploadFiles(e,i,n,r,s),o=new Set(a.map(e=>n?`${n}/${e}`:e));M.current.deleteWhere(e=>o.has(S5(e))),""!==n&&d(e=>new Set(e).add(n)),await en(n),_Z.toast.success(`Uploaded ${a.length} file${1===a.length?"":"s"}`)}catch(e){console.error("Failed to upload files:",e),_Z.toast.error("Upload failed",{description:e instanceof Error?e.message:String(e)})}finally{E(e=>{let r=new Set(e);return r.delete(n),r})}}},[e,r,s,en]),ea=(0,$.useCallback)(async n=>{if(e&&n){R(e=>new Set(e).add(n));try{await rv.api.deleteFile(e,n,r,s),M.current.deleteWhere(e=>{let r=S5(e);return r===n||r.startsWith(`${n}/`)}),h(e=>e===n||e&&e.startsWith(`${n}/`)?(p(null),null):e);let i=n.includes("/")?n.slice(0,n.lastIndexOf("/")):"";await en(i),_Z.toast.success("Deleted")}catch(e){console.error("Failed to delete:",e),_Z.toast.error("Delete failed",{description:e instanceof Error?e.message:String(e)})}finally{R(e=>{let r=new Set(e);return r.delete(n),r})}}},[e,r,s,en]);return{rootEntries:i,directoryContents:o,expandedDirs:c,selectedFile:u,fileContent:f,fileLoading:b,rootLoading:S,loadingDirs:C,uploadingDirs:N,deletingPaths:D,jumpTarget:m,canGoBack:v.index>0,canGoForward:v.index<v.entries.length-1,fetchRoot:Z,refresh:Q,reportScroll:V,restoreScroll:O,toggleDirectory:Y,selectFile:X,navigate:ee,jumpTo:et,goBack:er,goForward:es,uploadFiles:ei,refreshDirectory:en,deleteEntry:ea}}({projectId:e,branch:s,target:i,showHidden:a}),B=function({projectId:e,branch:r,target:s}){let[n,i]=(0,$.useState)([]),[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(!1),[d,u]=(0,$.useState)(!1),[h,f]=(0,$.useState)(""),p=(0,$.useRef)(0);(0,$.useEffect)(()=>{i([]),o(!1),u(!1),c(!1),f(""),p.current++},[e,r,s]);let m=(0,$.useCallback)(async()=>{if(!e)return;c(!0);let n=++p.current;try{let a=await rv.api.listProjectFiles(e,r,s);if(n!==p.current)return;i(a.files),o(a.truncated),u(!0)}catch(e){if(n!==p.current)return;i([]),u(!1),_Z.toast.error("Failed to load file list",{description:e instanceof Error?e.message:String(e)})}finally{n===p.current&&c(!1)}},[e,r,s]),g=(0,$.useCallback)(()=>{d||l||m()},[d,l,m]),x=(0,$.useCallback)(()=>{u(!1),p.current++,h&&m()},[h,m]),v=(0,$.useDeferredValue)(h);return{query:h,setQuery:f,results:(0,$.useMemo)(()=>(function(e,r,s){if(!r.trim())return[];let n=[];for(let s of e){let e=function(e,r){let s=e.toLowerCase().replace(/\s+/g,"");if(!s)return null;let n=r.toLowerCase(),i=r.lastIndexOf("/")+1,a=0,o=0,l=-2;for(let e=0;e<s.length;e++){let c=s[e],d=-1;for(;o<n.length;o++)if(n[o]===c){d=o;break}if(-1===d)return null;let u=1;d===l+1&&(u+=5),d>=i&&(u+=3);let h=d>0?r[d-1]:"/";(0===d||d===i||S3.has(h))&&(u+=4),a+=u,l=d,o=d+1}return a+.1*Math.max(0,40-r.length)}(r,s);null!==e&&n.push({path:s,score:e})}return n.sort((e,r)=>r.score-e.score||e.path.length-r.path.length),n.slice(0,50)})(n,v,0),[n,v]),truncated:a,loading:l,loaded:d,ensureLoaded:g,refresh:x}}({projectId:e,branch:s,target:i});(0,$.useEffect)(()=>{k()},[k]),(0,$.useEffect)(()=>{n&&(null!=n.line?T(n.path,n.line):A(n.path))},[n?.nonce]);let L=(0,$.useCallback)(()=>{N(),B.refresh()},[N,B]),z=(0,$.useCallback)(e=>{A(e),B.setQuery("")},[A,B]);if(!e)return(0,O.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(fK,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to browse files."})]})});let H=g&&e?rv.api.getFileDownloadUrl(e,g,s,i):null;return(0,O.jsxs)("div",{className:"flex flex-col h-full",style:{"--files-tree-font-size":`${l.filesTreeFontSize}px`,"--files-content-font-size":`${l.filesContentFontSize}px`},children:[(0,O.jsx)(dh,{title:"Files",actions:(0,O.jsxs)("div",{className:"flex items-center gap-1",children:[(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:h,title:d?"Show file tree":"Hide file tree","aria-pressed":!d,children:d?(0,O.jsx)(wg,{className:"h-3.5 w-3.5"}):(0,O.jsx)(wm,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:`h-7 w-7 hover:text-foreground ${a?"text-foreground":"text-muted-foreground"}`,onClick:()=>o(e=>!e),title:a?"Hide hidden files":"Show hidden files","aria-pressed":a,children:a?(0,O.jsx)(wf,{className:"h-3.5 w-3.5"}):(0,O.jsx)(wp,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:M,disabled:!j,title:"Back",children:(0,O.jsx)(o9.ArrowLeft,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:F,disabled:!C,title:"Forward",children:(0,O.jsx)(wx,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:L,title:"Refresh",children:(0,O.jsx)(fK,{className:`h-3.5 w-3.5 ${_?"animate-spin":""}`})})]})}),(0,O.jsxs)(uj,{direction:"horizontal",autoSaveId:"files-panels",className:"flex-1",children:[(0,O.jsx)(dN,{ref:c,collapsible:!0,collapsedSize:0,defaultSize:33,minSize:20,onCollapse:()=>u(!0),onExpand:()=>u(!1),children:(0,O.jsxs)(w5,{shouldFilter:!1,className:"flex h-full flex-col bg-transparent",children:[(0,O.jsx)("div",{className:"border-b p-2",children:(0,O.jsxs)(wv,{children:[(0,O.jsx)(wy,{children:(0,O.jsx)(sA,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(wS,{type:"search",name:"files-search",autoComplete:"off","data-1p-ignore":!0,"data-lpignore":"true","data-form-type":"other",readOnly:!0,onFocus:e=>{e.currentTarget.removeAttribute("readonly"),B.ensureLoaded()},placeholder:"Search files...",value:B.query,onChange:e=>B.setQuery(e.target.value)}),B.query&&(0,O.jsx)(wy,{align:"inline-end",children:(0,O.jsx)(ww,{size:"icon-xs","aria-label":"Clear search",onClick:()=>B.setQuery(""),children:(0,O.jsx)(t7,{className:"h-3.5 w-3.5"})})})]})}),B.query?(0,O.jsx)(w6,{className:"max-h-none flex-1",children:B.loading&&0===B.results.length?(0,O.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"}),"Loading files…"]}):0===B.results.length?(0,O.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No matching files."}):(0,O.jsxs)(O.Fragment,{children:[B.results.map(e=>{let r=e.path.lastIndexOf("/"),s=r>=0?e.path.slice(0,r+1):"",n=r>=0?e.path.slice(r+1):e.path;return(0,O.jsxs)(w9,{value:e.path,onSelect:()=>z(e.path),className:"flex-col items-start gap-0 text-[length:var(--files-tree-font-size,14px)]!",children:[(0,O.jsx)("span",{className:"font-medium",children:n}),s&&(0,O.jsx)("span",{className:"w-full truncate text-xs text-muted-foreground",children:s})]},e.path)}),B.truncated&&(0,O.jsx)("div",{className:"px-2 py-2 text-xs text-muted-foreground",children:"Showing first 50,000 files — refine your search to narrow results."})]})}):(0,O.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,O.jsx)(Sd,{entries:f,expandedDirs:m,directoryContents:p,loadingDirs:y,selectedFile:g,uploadingDirs:b,rootLoading:_,deletingPaths:w,onToggleDirectory:R,onSelectFile:A,onUploadFiles:P,onDeleteEntry:I})})]})}),(0,O.jsx)(uC,{withHandle:!0}),(0,O.jsx)(dN,{defaultSize:67,minSize:25,children:(0,O.jsx)("div",{className:"h-full overflow-hidden",children:(0,O.jsx)(SJ,{filePath:g,fileContent:x,loading:v,downloadUrl:H,projectId:e,branch:s,target:i,scrollToLine:S?.line??null,scrollKey:S?.nonce,onJump:T,restoreScrollTop:D?.top??null,restoreScrollKey:D?.nonce,onScroll:E})})})]})]})}let S6=(0,$.createContext)(null),S7={openFile:()=>{},index:null};function S8(){return(0,$.useContext)(S6)??S7}let S9=S6.Provider,je=0;function jt(e){let r=e.lastIndexOf("/");return r>=0?e.slice(r+1):e}let jr=[500,1e3,2e3,4e3,8e3];async function js(e,r={}){let s=r.delaysMs??jr,n=r.sleep??(e=>new Promise(r=>setTimeout(r,e))),i=r.cancelled??(()=>!1);for(let r=0;;r++){if(i())return null;let a=null;try{a=await e()}catch{a=null}if(i())return null;if(a&&a.files.length>0||r>=s.length)return a;await n(s[r])}}let jn={agent:sb,executors:ol,diff:sU,terminal:hq,preview:ry,files:r_},ji=_Q.map(e=>({...e,icon:jn[e.id]})),ja=()=>()=>{},jo=$.useLayoutEffect;function jl({projectId:e,selectedBranch:r,onMergeRequest:s,project:n,onExecutorModeChange:i,agentSlot:a,activateAgentTabNonce:o,diffCompareNonce:l,mergeTarget:c,forceAgentTab:d=!1,active:u=!0}){let[h,f]=function(e,r){let s=`vibedeckx:activeTab:${e??"none"}:${r??"main"}`,[n,i]=(0,$.useState)(()=>localStorage.getItem(s)??"agent");return jo(()=>{i(localStorage.getItem(s)??"agent")},[s]),[n,(0,$.useCallback)(e=>{i(e),localStorage.setItem(s,e)},[s])]}(e,r),p=d?"agent":h,m=(0,$.useRef)(o);jo(()=>{void 0===o||m.current!==o&&(m.current=o,f("agent"))},[o,f]);let g=(0,$.useRef)(l);jo(()=>{void 0===l||g.current!==l&&(g.current=l,f("diff"))},[l,f]),(0,$.useEffect)(()=>{if(!u)return;let e=e=>{let r=_2(e);r&&(e.preventDefault(),f(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[u,f]);let x=(0,$.useSyncExternalStore)(ja,_1,()=>!1),v=function({projectId:e,branch:r,target:s,enabled:n=!0}){let[i,a]=(0,$.useState)(null),o=(0,$.useRef)(0);return(0,$.useEffect)(()=>{if(a(null),!n||!e)return;let i=++o.current;js(()=>rv.api.listProjectFiles(e,r,s),{cancelled:()=>i!==o.current}).then(e=>{i===o.current&&e&&a(function(e){let r=`idx-${++je}`,s=new Set(e),n=new Map;for(let r of e){let e=jt(r),s=n.get(e);s?s.push(r):n.set(e,[r])}return{version:r,resolve(e){if(!e)return[];let r=e.replace(/^\/+/,"");if(!r)return[];if(r.includes("/")){if(s.has(r))return[r];let e=jt(r);return(n.get(e)??[]).filter(e=>e===r||e.endsWith("/"+r)||r.endsWith("/"+e))}return n.get(r)??[]}}}(e.files))})},[e,r,s,n]),i}({projectId:e,branch:r,target:n&&!n.path?"remote":void 0,enabled:u}),_=(0,$.useRef)(0),[y,b]=(0,$.useState)(null),w=(0,$.useCallback)((e,r=null)=>{f("files"),b({path:e,line:r,nonce:++_.current})},[f]),S=(0,$.useMemo)(()=>({openFile:w,index:v}),[w,v]);return(0,O.jsx)(S9,{value:S,children:(0,O.jsxs)("div",{className:"h-full flex flex-col",children:[(0,O.jsx)("div",{className:"flex items-center px-3 gap-4 border-b border-border",children:ji.map(({id:e,icon:r,label:s,code:n})=>(0,O.jsxs)($.Fragment,{children:[(0,O.jsxs)("button",{onClick:()=>f(e),title:`${s} (${_5(x,n)})`,className:(0,ey.cn)("flex items-center gap-0.5 py-2.5 text-xs font-medium border-b-2 transition-colors",p===e?"text-foreground border-primary":"text-muted-foreground border-transparent hover:text-foreground/70"),children:[(0,O.jsx)(r,{className:"h-3.5 w-3.5"}),s]}),"agent"===e&&(0,O.jsx)("span",{className:"h-4 w-px bg-border/60 mx-1.5","aria-hidden":!0})]},e))}),(0,O.jsxs)("div",{className:"relative flex-1 overflow-hidden",children:[(0,O.jsx)("div",{className:(0,ey.cn)("absolute inset-0 overflow-hidden","agent"!==p&&"invisible pointer-events-none"),children:a}),(0,O.jsx)("div",{className:(0,ey.cn)("absolute inset-0 overflow-hidden","executors"!==p&&"hidden"),children:(0,O.jsx)(b5,{projectId:e,selectedBranch:r,project:n,onExecutorModeChange:i})}),(0,O.jsx)("div",{className:(0,ey.cn)("absolute inset-0 overflow-hidden","diff"!==p&&"hidden"),children:(0,O.jsx)(ws,{projectId:e,selectedBranch:r,onMergeRequest:s,project:n,mergeTarget:c,compareRequestNonce:l})}),(0,O.jsx)("div",{className:(0,ey.cn)("absolute inset-0 overflow-hidden","terminal"!==p&&"hidden"),children:(0,O.jsx)(wi,{projectId:e,selectedBranch:r,project:n})}),(0,O.jsx)("div",{className:(0,ey.cn)("absolute inset-0 overflow-hidden","preview"!==p&&"hidden"),children:(0,O.jsx)(wh,{projectId:e,selectedBranch:r,project:n})}),(0,O.jsx)("div",{className:(0,ey.cn)("absolute inset-0 overflow-hidden","files"!==p&&"hidden"),children:(0,O.jsx)(S4,{projectId:e,project:n,selectedBranch:r,navRequest:y})})]})]})})}var jc=Symbol.for("immer-nothing"),jd=Symbol.for("immer-draftable"),ju=Symbol.for("immer-state");function jh(e){throw Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var jf=Object.getPrototypeOf;function jp(e){return!!e&&!!e[ju]}function jm(e){return!!e&&(jv(e)||Array.isArray(e)||!!e[jd]||!!e.constructor?.[jd]||jS(e)||jj(e))}var jg=Object.prototype.constructor.toString(),jx=new WeakMap;function jv(e){if(!e||"object"!=typeof e)return!1;let r=Object.getPrototypeOf(e);if(null===r||r===Object.prototype)return!0;let s=Object.hasOwnProperty.call(r,"constructor")&&r.constructor;if(s===Object)return!0;if("function"!=typeof s)return!1;let n=jx.get(s);return void 0===n&&(n=Function.toString.call(s),jx.set(s,n)),n===jg}function j_(e,r,s=!0){0===jy(e)?(s?Reflect.ownKeys(e):Object.keys(e)).forEach(s=>{r(s,e[s],e)}):e.forEach((s,n)=>r(n,s,e))}function jy(e){let r=e[ju];return r?r.type_:Array.isArray(e)?1:jS(e)?2:3*!!jj(e)}function jb(e,r){return 2===jy(e)?e.has(r):Object.prototype.hasOwnProperty.call(e,r)}function jw(e,r,s){let n=jy(e);2===n?e.set(r,s):3===n?e.add(s):e[r]=s}function jS(e){return e instanceof Map}function jj(e){return e instanceof Set}function jC(e){return e.copy_||e.base_}function jk(e,r){if(jS(e))return new Map(e);if(jj(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let s=jv(e);if(!0!==r&&("class_only"!==r||s)){let r=jf(e);return null!==r&&s?{...e}:Object.assign(Object.create(r),e)}{let r=Object.getOwnPropertyDescriptors(e);delete r[ju];let s=Reflect.ownKeys(r);for(let n=0;n<s.length;n++){let i=s[n],a=r[i];!1===a.writable&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[i]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[i]})}return Object.create(jf(e),r)}}function jN(e,r=!1){return jD(e)||jp(e)||!jm(e)||(jy(e)>1&&Object.defineProperties(e,{set:jE,add:jE,clear:jE,delete:jE}),Object.freeze(e),r&&Object.values(e).forEach(e=>jN(e,!0))),e}var jE={value:function(){jh(2)}};function jD(e){return null===e||"object"!=typeof e||Object.isFrozen(e)}var jR={};function jA(e){let r=jR[e];return r||jh(0,e),r}function jT(e,r){r&&(jA("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=r)}function jM(e){jF(e),e.drafts_.forEach(jI),e.drafts_=null}function jF(e){e===L&&(L=e.parent_)}function jP(e){return L={drafts_:[],parent_:L,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function jI(e){let r=e[ju];0===r.type_||1===r.type_?r.revoke_():r.revoked_=!0}function jB(e,r){r.unfinalizedDrafts_=r.drafts_.length;let s=r.drafts_[0];return void 0!==e&&e!==s?(s[ju].modified_&&(jM(r),jh(4)),jm(e)&&(e=jL(r,e),r.parent_||jO(r,e)),r.patches_&&jA("Patches").generateReplacementPatches_(s[ju].base_,e,r.patches_,r.inversePatches_)):e=jL(r,s,[]),jM(r),r.patches_&&r.patchListener_(r.patches_,r.inversePatches_),e!==jc?e:void 0}function jL(e,r,s){if(jD(r))return r;let n=e.immer_.shouldUseStrictIteration(),i=r[ju];if(!i)return j_(r,(n,a)=>jz(e,i,r,n,a,s),n),r;if(i.scope_!==e)return r;if(!i.modified_)return jO(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;let r=i.copy_,a=r,o=!1;3===i.type_&&(a=new Set(r),r.clear(),o=!0),j_(a,(n,a)=>jz(e,i,r,n,a,s,o),n),jO(e,r,!1),s&&e.patches_&&jA("Patches").generatePatches_(i,s,e.patches_,e.inversePatches_)}return i.copy_}function jz(e,r,s,n,i,a,o){if(null==i||"object"!=typeof i&&!o)return;let l=jD(i);if(!l||o){if(jp(i)){let o=jL(e,i,a&&r&&3!==r.type_&&!jb(r.assigned_,n)?a.concat(n):void 0);if(jw(s,n,o),!jp(o))return;e.canAutoFreeze_=!1}else o&&s.add(i);if(jm(i)&&!l){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||r&&r.base_&&r.base_[n]===i&&l)return;jL(e,i),(!r||!r.scope_.parent_)&&"symbol"!=typeof n&&(jS(s)?s.has(n):Object.prototype.propertyIsEnumerable.call(s,n))&&jO(e,i)}}}function jO(e,r,s=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&jN(r,s)}var j$={get(e,r){if(r===ju)return e;let s=jC(e);if(!jb(s,r)){var n;let i;return n=e,(i=jU(s,r))?"value"in i?i.value:i.get?.call(n.draft_):void 0}let i=s[r];return e.finalized_||!jm(i)?i:i===jH(e.base_,r)?(jK(e),e.copy_[r]=jV(i,e)):i},has:(e,r)=>r in jC(e),ownKeys:e=>Reflect.ownKeys(jC(e)),set(e,r,s){let n=jU(jC(e),r);if(n?.set)return n.set.call(e.draft_,s),!0;if(!e.modified_){let n=jH(jC(e),r),i=n?.[ju];if(i&&i.base_===s)return e.copy_[r]=s,e.assigned_[r]=!1,!0;if((s===n?0!==s||1/s==1/n:s!=s&&n!=n)&&(void 0!==s||jb(e.base_,r)))return!0;jK(e),jq(e)}return!!(e.copy_[r]===s&&(void 0!==s||r in e.copy_)||Number.isNaN(s)&&Number.isNaN(e.copy_[r]))||(e.copy_[r]=s,e.assigned_[r]=!0,!0)},deleteProperty:(e,r)=>(void 0!==jH(e.base_,r)||r in e.base_?(e.assigned_[r]=!1,jK(e),jq(e)):delete e.assigned_[r],e.copy_&&delete e.copy_[r],!0),getOwnPropertyDescriptor(e,r){let s=jC(e),n=Reflect.getOwnPropertyDescriptor(s,r);return n?{writable:!0,configurable:1!==e.type_||"length"!==r,enumerable:n.enumerable,value:s[r]}:n},defineProperty(){jh(11)},getPrototypeOf:e=>jf(e.base_),setPrototypeOf(){jh(12)}},jW={};function jH(e,r){let s=e[ju];return(s?jC(s):e)[r]}function jU(e,r){if(!(r in e))return;let s=jf(e);for(;s;){let e=Object.getOwnPropertyDescriptor(s,r);if(e)return e;s=jf(s)}}function jq(e){!e.modified_&&(e.modified_=!0,e.parent_&&jq(e.parent_))}function jK(e){e.copy_||(e.copy_=jk(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function jV(e,r){let s=jS(e)?jA("MapSet").proxyMap_(e,r):jj(e)?jA("MapSet").proxySet_(e,r):function(e,r){let s=Array.isArray(e),n={type_:+!!s,scope_:r?r.scope_:L,modified_:!1,finalized_:!1,assigned_:{},parent_:r,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},i=n,a=j$;s&&(i=[n],a=jW);let{revoke:o,proxy:l}=Proxy.revocable(i,a);return n.draft_=l,n.revoke_=o,l}(e,r);return(r?r.scope_:L).drafts_.push(s),s}j_(j$,(e,r)=>{jW[e]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)}}),jW.deleteProperty=function(e,r){return jW.set.call(this,e,r,void 0)},jW.set=function(e,r,s){return j$.set.call(this,e[0],r,s,e[0])};var jY=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(e,r,s)=>{let n;if("function"==typeof e&&"function"!=typeof r){let s=r;r=e;let n=this;return function(e=s,...i){return n.produce(e,e=>r.call(this,e,...i))}}if("function"!=typeof r&&jh(6),void 0!==s&&"function"!=typeof s&&jh(7),jm(e)){let i=jP(this),a=jV(e,void 0),o=!0;try{n=r(a),o=!1}finally{o?jM(i):jF(i)}return jT(i,s),jB(n,i)}if(e&&"object"==typeof e)jh(1,e);else{if(void 0===(n=r(e))&&(n=e),n===jc&&(n=void 0),this.autoFreeze_&&jN(n,!0),s){let r=[],i=[];jA("Patches").generateReplacementPatches_(e,n,r,i),s(r,i)}return n}},this.produceWithPatches=(e,r)=>{let s,n;return"function"==typeof e?(r,...s)=>this.produceWithPatches(r,r=>e(r,...s)):[this.produce(e,r,(e,r)=>{s=e,n=r}),s,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),"boolean"==typeof e?.useStrictIteration&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){var r;jm(e)||jh(8),jp(e)&&(jp(r=e)||jh(10,r),e=function e(r){let s;if(!jm(r)||jD(r))return r;let n=r[ju],i=!0;if(n){if(!n.modified_)return n.base_;n.finalized_=!0,s=jk(r,n.scope_.immer_.useStrictShallowCopy_),i=n.scope_.immer_.shouldUseStrictIteration()}else s=jk(r,!0);return j_(s,(r,n)=>{jw(s,r,e(n))},i),n&&(n.finalized_=!1),s}(r));let s=jP(this),n=jV(e,void 0);return n[ju].isManual_=!0,jF(s),n}finishDraft(e,r){let s=e&&e[ju];s&&s.isManual_||jh(9);let{scope_:n}=s;return jT(n,r),jB(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,r){let s;for(s=r.length-1;s>=0;s--){let n=r[s];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}s>-1&&(r=r.slice(s+1));let n=jA("Patches").applyPatches_;return jp(e)?n(e,r):this.produce(e,e=>n(e,r))}}().produce;let jG="vibedeckx:placeholder-workspaces";function jX(e){try{window.localStorage.setItem(jG,JSON.stringify([...e]))}catch{}}let jJ=function(){try{let e=window.localStorage.getItem(jG);if(!e)return new Map;let r=JSON.parse(e);if(!Array.isArray(r))return new Map;let s=new Map;for(let e of r)Array.isArray(e)&&"string"==typeof e[0]&&"number"==typeof e[1]?s.set(e[0],e[1]):"string"==typeof e&&s.set(e,Date.now());return s}catch{return new Map}}(),jZ=new Set,jQ=new Map;function j0(){for(let e of jZ)e()}function j1(e){return jZ.add(e),()=>{jZ.delete(e)}}function j2(){return jJ}function j5(){return jQ}function j3(e,r,s){return`${e}:${r??""}:${s??""}`}function j4(e){if(!jJ.has(e))return!1;let r=new Map(jJ);return r.delete(e),jX(jJ=r),j0(),!0}function j6(){return"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}async function j7(e,r,s,n){let i=await (0,rv.authFetch)(`${j6()}/api/projects/${e}/agent-sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:r,permissionMode:s,agentType:n})});if(!i.ok)throw Error("Failed to load session");return i.json()}async function j8(e,r){let s=await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r})});if(!s.ok){let r="";try{let e=await s.json();if(e.errorCode){let s=[`${e.errorCode}`];e.attempts&&s.push(`${e.attempts} attempts`),e.totalDurationMs&&s.push(`${(e.totalDurationMs/1e3).toFixed(1)}s`),r=` (${s.join(", ")})`}else e.error&&(r=` — ${e.error}`)}catch{}throw console.error(`[AgentSession] /message failed: status=${s.status}, sessionId=${e}, detail=${r}`),Error(`Failed to send message [${s.status}]${r}`)}}async function j9(e,r){let s=await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/paste`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r})});if(!s.ok){let r="";try{let e=await s.json();if(e.errorCode){let s=[`${e.errorCode}`];e.attempts&&s.push(`${e.attempts} attempts`),e.totalDurationMs&&s.push(`${(e.totalDurationMs/1e3).toFixed(1)}s`),r=` (${s.join(", ")})`}else e.error&&(r=` — ${e.error}`)}catch{}throw console.error(`[AgentSession] /paste failed: status=${s.status}, sessionId=${e}, detail=${r}`),Error(`Failed to upload paste [${s.status}]${r}`)}return s.json()}async function Ce(e,r){if(!(await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/restart`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentType:r})})).ok)throw Error("Failed to restart session")}async function Ct(e,r){let s=await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/agent-type`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentType:r})});if(!s.ok){let e="";try{let r=await s.json();r.error&&(e=r.error)}catch{}throw Error(e||`Failed to switch agent [${s.status}]`)}}async function Cr(e,r){let s=await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/model`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r})});if(!s.ok){let e="";try{let r=await s.json();r.error&&(e=r.error)}catch{}throw Error(e||`Failed to set model [${s.status}]`)}return(await s.json().catch(()=>({}))).model??null}async function Cs(e){if(!(await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/stop`,{method:"POST"})).ok)throw Error("Failed to stop session")}async function Cn(e,r){if(!(await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/switch-mode`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:r})})).ok)throw Error("Failed to switch mode")}async function Ci(e,r){if(!(await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}/accept-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planContent:r})})).ok)throw Error("Failed to accept plan")}let Ca=new Map;function Co(e,r,s){return`${e}:${r??""}:${s??"latest"}`}async function Cl(e){let r=await (0,rv.authFetch)(`${j6()}/api/agent-sessions/${e}`);if(!r.ok)throw Error(`Session ${e} not found`);return r.json()}let Cc=(0,ew.default)("user",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]),Cd=(0,ew.default)("wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]]),Cu=(0,ew.default)("brain",[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]]),Ch=(0,ew.default)("circle-question-mark",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),Cf=(0,ew.default)("file-check",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m9 15 2 2 4-4",key:"1grp1n"}]]),Cp=(0,ew.default)("folder-search",[["path",{d:"M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]]),Cm=(0,ew.default)("workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]),Cg=(0,ew.default)("file-pen-line",[["path",{d:"m18.226 5.226-2.52-2.52A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-.351",key:"1k2beg"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}],["path",{d:"M8 18h1",key:"13wk12"}]]),Cx=(0,ew.default)("file-plus-corner",[["path",{d:"M11.35 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v5.35",key:"17jvcc"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M14 19h6",key:"bvotb8"}],["path",{d:"M17 16v6",key:"18yu1i"}]]),Cv=(0,ew.default)("earth",[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),C_=(0,ew.default)("shield-alert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);var ck=cC,Sw=cC;let Cy=RegExp("(?<![\\w./-])([\\w-]+(?:[./][\\w-]+)+)(?::(\\d+)(?::\\d+)?|#L(\\d+)(?:-L?\\d+)?)?","g"),Cb=/\[([^\]\n]*)\]\(\s*([^)\s]+?)\s*\)/g;function Cw(e){return e.includes("/")||/\.[A-Za-z0-9]+$/.test(e)}function CS(e){let r=e.trim();if(!r)return null;let s=/^(.*?)(?::(\d+)(?::\d+)?|#L(\d+)(?:-L?\d+)?)?$/.exec(r);if(!s||!s[1])return null;let n=s[1];return/^[a-z][a-z0-9+.-]*:/i.test(n)||n.startsWith("//")||n.startsWith("#")?null:{rawPath:n,line:s[2]?Number(s[2]):s[3]?Number(s[3]):null}}function Cj(e){let r=r=>e.index?e.index.resolve(r):[];function s(e,r,s){return{type:"element",tagName:"a",properties:{className:["file-ref"],href:"#file-ref",dataFilePaths:JSON.stringify(e),...null!=r?{dataFileLine:String(r)}:{}},children:s}}return e=>{!function e(n,i=!1){if(!n.children)return;let a=i||"pre"===n.tagName,o=[];for(let i of n.children)"text"===i.type?a?o.push(i):o.push(...function(e){let n=function(e){let r,s=[],n=[];for(Cb.lastIndex=0;null!==(r=Cb.exec(e));){let e=CS(r[2]);if(!e||!Cw(e.rawPath))continue;let i=r.index,a=r.index+r[0].length;s.push({start:i,end:a,rawPath:e.rawPath,line:e.line,display:r[1]||void 0}),n.push([i,a])}for(Cy.lastIndex=0;null!==(r=Cy.exec(e));){let e=r.index;if(n.some(([r,s])=>e>=r&&e<s))continue;let i=r[1];if(!Cw(i))continue;let a=r[2]?Number(r[2]):r[3]?Number(r[3]):null;s.push({start:e,end:e+r[0].length,rawPath:i,line:a})}return s.sort((e,r)=>e.start-r.start),s}(e);if(0===n.length)return[{type:"text",value:e}];let i=[],a=0,o=!1;for(let l of n){let n=r(l.rawPath);if(0===n.length)continue;l.start>a&&i.push({type:"text",value:e.slice(a,l.start)});let c=l.display??e.slice(l.start,l.end);i.push(s(n,l.line,[{type:"text",value:c}])),a=l.end,o=!0}return o?(a<e.length&&i.push({type:"text",value:e.slice(a)}),i):[{type:"text",value:e}]}(i.value??"")):"element"===i.type&&"pre"===i.tagName?(e(i,!0),o.push(i)):"element"!==i.type||"a"!==i.tagName||a?(e(i,a),o.push(i)):o.push(...function(e){let n=CS(String(e.properties?.href??""));if(!n)return[e];let i=r(n.rawPath);return 0===i.length?e.children??[]:[s(i,n.line,e.children??[])]}(i));n.children=o}(e)}}let CC="text-primary underline decoration-dotted underline-offset-2 cursor-pointer hover:decoration-solid";function Ck({node:e,children:r,href:s,...n}){let{openFile:i}=S8(),a=e?.properties?.dataFilePaths;if(!a)return"string"==typeof s&&s.startsWith("#")?(0,O.jsx)("a",{href:s,...n,children:r}):(0,O.jsx)("a",{href:s,target:"_blank",rel:"noreferrer noopener",...n,children:r});let o=[];try{o=JSON.parse(a)}catch{o=[]}let l=e?.properties?.dataFileLine,c=null!=l?Number(l):null;return o.length<=1?(0,O.jsx)("a",{href:"#",className:CC,onClick:e=>{e.preventDefault(),o[0]&&i(o[0],c)},children:r}):(0,O.jsx)(CN,{paths:o,line:c,children:r})}function CN({paths:e,line:r,children:s}){let{openFile:n}=S8();return(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)("a",{href:"#",className:CC,onClick:e=>e.preventDefault(),children:s})}),(0,O.jsxs)(a7,{align:"start",className:"max-w-md",children:[(0,O.jsxs)(or,{children:[e.length," matching files"]}),e.map(e=>(0,O.jsx)(a8,{className:"font-mono text-xs",onSelect:()=>n(e,r),children:e},e))]})]})}let CE=(0,$.memo)(function({children:e}){let{index:r}=S8(),{harden:s,...n}=Sw.e,i=[...Object.values(n),[Cj,{index:r}],...s?[s]:[]];return(0,O.jsx)(ck.i,{className:"size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",rehypePlugins:i,components:{a:Ck},children:e},r?.version??"no-file-ref-index")});function CD({input:e,messageIndex:r}){let{sendMessage:s,messages:n}=N7(),i=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&Array.isArray(r.questions)&&r.questions.length>0&&r.questions.every(e=>"string"==typeof e.question&&"string"==typeof e.header&&Array.isArray(e.options)))return r}catch{}return null}(e),a=n[r+1],o=a?.type==="user",l=o?a.content:"",c="string"==typeof l?l:l.filter(e=>"text"===e.type).map(e=>e.text).join("\n");if(!i){let r="string"==typeof e?e:JSON.stringify(e,null,2);return(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>500?r.substring(0,500)+"...":r})}return o?(0,O.jsx)(CR,{questions:i.questions,answeredText:c}):(0,O.jsx)(CA,{questions:i.questions,sendMessage:s})}function CR({questions:e,answeredText:r}){return(0,O.jsx)("div",{className:"space-y-3 mt-2",children:e.map((e,s)=>(0,O.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3",children:[(0,O.jsx)("div",{className:"flex items-center gap-2 mb-1.5",children:(0,O.jsx)(sa,{variant:"secondary",className:"text-[10px]",children:e.header})}),(0,O.jsx)("p",{className:"text-sm text-muted-foreground mb-2",children:e.question}),(0,O.jsxs)("div",{className:"flex items-center gap-2 text-sm text-green-600 dark:text-green-400",children:[(0,O.jsx)(sJ,{className:"h-4 w-4"}),(0,O.jsx)("span",{className:"font-medium",children:r})]})]},s))})}function CA({questions:e,sendMessage:r}){let[s,n]=(0,$.useState)(new Map),[i,a]=(0,$.useState)(new Map),[o,l]=(0,$.useState)(new Set),[c,d]=(0,$.useState)(!1);async function u(){let n=[];for(let r=0;r<e.length;r++)if(o.has(r)){let e=i.get(r)?.trim();e&&n.push(e)}else{let e=s.get(r);e&&e.size>0&&n.push(Array.from(e).join(", "))}if(n.length>0){d(!0);try{await r(n.join("\n"))}finally{d(!1)}}}let h=e.some((e,r)=>{if(o.has(r))return!!i.get(r)?.trim();let n=s.get(r);return n&&n.size>0});return(0,O.jsxs)("div",{className:"space-y-4 mt-2",children:[e.map((e,r)=>{let c=s.get(r)||new Set,d=i.get(r)||"",u=o.has(r);return(0,O.jsxs)("div",{className:"rounded-lg border bg-card p-3",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 mb-1.5",children:[(0,O.jsx)(Ch,{className:"h-3.5 w-3.5 text-violet-500"}),(0,O.jsx)(sa,{variant:"secondary",className:"text-[10px]",children:e.header})]}),(0,O.jsx)("p",{className:"text-sm font-medium mb-3",children:e.question}),(0,O.jsxs)("div",{className:"grid gap-2",children:[e.options.map(s=>{let i=c.has(s.label)&&!u;return(0,O.jsx)(W.Button,{variant:i?"default":"outline",className:(0,ey.cn)("h-auto py-2 px-3 justify-start text-left whitespace-normal",i&&"ring-2 ring-primary/50"),onClick:()=>{var i,a;return i=s.label,a=e.multiSelect,void(n(e=>{let s=new Map(e),n=new Set(s.get(r)||[]);return a?n.has(i)?n.delete(i):n.add(i):n.has(i)?n.clear():(n.clear(),n.add(i)),s.set(r,n),s}),l(e=>{let s=new Set(e);return s.delete(r),s}))},children:(0,O.jsxs)("div",{children:[(0,O.jsx)("span",{className:"font-medium text-sm",children:s.label}),s.description&&(0,O.jsx)("span",{className:"block text-xs text-muted-foreground mt-0.5",children:s.description})]})},s.label)}),(0,O.jsx)("div",{className:"flex items-center gap-2 mt-1",children:(0,O.jsx)(ro,{placeholder:"Other...",value:d,onChange:e=>{var s;return s=e.target.value,void(a(e=>new Map(e).set(r,s)),s&&(n(e=>{let s=new Map(e);return s.set(r,new Set),s}),l(e=>new Set(e).add(r))))},className:"text-sm"})})]})]},r)}),(0,O.jsxs)(W.Button,{onClick:u,disabled:!h||c,size:"sm",className:"active:scale-95 transition-transform",children:[c&&(0,O.jsx)(sj,{className:"h-3.5 w-3.5 animate-spin"}),c?"Submitting...":"Submit"]})]})}function CT(e){try{return JSON.parse(e)}catch{return null}}function CM({input:e,messageIndex:r}){let{messages:s,acceptPlan:n,permissionMode:i,agentType:a}=N7(),[o,l]=(0,$.useState)(!0),[c,d]=(0,$.useState)(!1),u=function(e,r,s){let n="string"==typeof e?CT(e):e;if(n&&"object"==typeof n&&"plan"in n){let e=n.plan;if(e)return e}if("claude-code"===s)for(let e=r.length-1;e>=0;e--){let s=r[e];if("tool_use"===s.type&&"Write"===s.tool){let e="string"==typeof s.input?CT(s.input):s.input;if(e&&"object"==typeof e&&e.file_path?.includes(".claude/plans/")&&e.content)return e.content}}return"Plan written to file"}(e,s,a),h=(0,$.useCallback)(async()=>{d(!0);try{await n(u)}catch{d(!1)}},[n,u]),f="edit"===i,p=!1,m="";for(let e=r+1;e<s.length;e++){let r=s[e];if(r?.type==="user"){p=!0;let e=r.content??"";m="string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n");break}}return(f&&!p&&(p=!0),f||p)?(0,O.jsxs)("div",{className:"space-y-2 mt-2",children:[f?(0,O.jsxs)(sa,{variant:"default",className:"bg-green-600 hover:bg-green-700 text-white",children:[(0,O.jsx)(sJ,{className:"h-3 w-3 mr-1"}),"Plan Accepted"]}):(0,O.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,O.jsx)(sD,{className:"h-3.5 w-3.5"}),(0,O.jsxs)("span",{children:["Feedback sent: ",m.length>100?m.substring(0,100)+"...":m]})]}),(0,O.jsxs)("details",{open:!f,children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"View Plan"}),(0,O.jsx)("div",{className:"mt-2 rounded-lg border p-3 bg-muted/30",children:(0,O.jsx)("div",{className:"prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,O.jsx)(cD,{children:u})})})]})]}):(0,O.jsxs)("div",{className:"space-y-3 mt-2",children:[(0,O.jsxs)("div",{className:"rounded-lg border p-3 bg-card",children:[(0,O.jsxs)("button",{onClick:()=>l(!o),className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground mb-2 block",children:[o?"Collapse":"Expand"," Plan"]}),o&&(0,O.jsx)("div",{className:"prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words max-h-96 overflow-y-auto",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,O.jsx)(cD,{children:u})})]}),(0,O.jsxs)(W.Button,{onClick:h,disabled:c,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:[c?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):(0,O.jsx)(rh,{className:"h-3.5 w-3.5 mr-1.5"}),c?"Accepting Plan...":"Accept Plan & Start Editing"]})]})}function CF({requestId:e,command:r,cwd:s,messageIndex:n}){let{messages:i,sessionId:a}=N7(),[o,l]=(0,$.useState)(!1),[c,d]=(0,$.useState)(null),u=!1;for(let e=n+1;e<i.length;e++)if(i[e]?.type==="user"){u=!0;break}c&&(u=!0);let h=(0,$.useCallback)(async r=>{if(a){l(!0),d(r);try{await (0,rv.sendApprovalResponse)(a,e,r)}catch{d(null),l(!1)}}},[a,e]);return u?(0,O.jsxs)("div",{className:"space-y-2 mt-2",children:[(0,O.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,O.jsx)(ol,{className:"h-3.5 w-3.5 text-muted-foreground"}),(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:"Command"})]}),(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r||"(empty)"}),s&&(0,O.jsxs)("p",{className:"text-xs text-muted-foreground mt-1",children:["cwd: ",s]})]}),(0,O.jsxs)(sa,{variant:"default",className:"decline"===c?"bg-red-600 hover:bg-red-700 text-white":"bg-green-600 hover:bg-green-700 text-white",children:[(0,O.jsx)(sJ,{className:"h-3 w-3 mr-1"}),"decline"===c?"Denied":"Allowed"]})]}):(0,O.jsxs)("div",{className:"space-y-2 mt-2",children:[(0,O.jsxs)("div",{className:"rounded-lg border bg-card p-3",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,O.jsx)(ol,{className:"h-3.5 w-3.5 text-muted-foreground"}),(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:"Command"})]}),(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r||"(empty)"}),s&&(0,O.jsxs)("p",{className:"text-xs text-muted-foreground mt-1",children:["cwd: ",s]})]}),(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsxs)(W.Button,{onClick:()=>h("accept"),disabled:o,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:[o&&"accept"===c?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,O.jsx)(sJ,{className:"h-3.5 w-3.5 mr-1"}),"Allow"]}),(0,O.jsxs)(W.Button,{onClick:()=>h("decline"),disabled:o,variant:"destructive",size:"sm",children:[o&&"decline"===c?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5 mr-1"}),"Deny"]})]})]})}function CP({requestId:e,changes:r,messageIndex:s}){let{messages:n,sessionId:i}=N7(),[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(null),d=!1;for(let e=s+1;e<n.length;e++)if(n[e]?.type==="user"){d=!0;break}l&&(d=!0);let u=(0,$.useCallback)(async r=>{if(i){o(!0),c(r);try{await (0,rv.sendApprovalResponse)(i,e,r)}catch{c(null),o(!1)}}},[i,e]),h=r??[],f=()=>(0,O.jsx)("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:0===h.length?(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"No file changes"}):h.map((e,r)=>(0,O.jsxs)("div",{children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)(Sr,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),(0,O.jsx)("code",{className:"text-xs break-all",children:e.path}),(0,O.jsx)(sa,{variant:"secondary",className:`text-[10px] ${function(e){switch(e){case"added":case"add":return"bg-green-500/10 text-green-600";case"deleted":case"delete":return"bg-red-500/10 text-red-600";default:return"bg-blue-500/10 text-blue-600"}}(e.kind)}`,children:function(e){switch(e){case"added":case"add":return"added";case"deleted":case"delete":return"deleted";default:return"modified"}}(e.kind)})]}),e.diff&&(0,O.jsxs)("details",{className:"mt-1",children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"View diff"}),(0,O.jsx)("pre",{className:"mt-1 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.diff.split("\n").map((e,r)=>{let s="";return e.startsWith("+")?s="bg-green-500/10 text-green-700 dark:text-green-400":e.startsWith("-")&&(s="bg-red-500/10 text-red-700 dark:text-red-400"),(0,O.jsx)("div",{className:s,children:e},r)})})]})]},r))});return d?(0,O.jsxs)("div",{className:"space-y-2 mt-2",children:[f(),(0,O.jsxs)(sa,{variant:"default",className:"decline"===l?"bg-red-600 hover:bg-red-700 text-white":"bg-green-600 hover:bg-green-700 text-white",children:[(0,O.jsx)(sJ,{className:"h-3 w-3 mr-1"}),"decline"===l?"Denied":"Allowed"]})]}):(0,O.jsxs)("div",{className:"space-y-2 mt-2",children:[f(),(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsxs)(W.Button,{onClick:()=>u("accept"),disabled:a,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:[a&&"accept"===l?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,O.jsx)(sJ,{className:"h-3.5 w-3.5 mr-1"}),"Allow"]}),(0,O.jsxs)(W.Button,{onClick:()=>u("decline"),disabled:a,variant:"destructive",size:"sm",children:[a&&"decline"===l?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5 mr-1"}),"Deny"]})]})]})}let CI=(0,ew.default)("circle-plus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]),CB=(0,ew.default)("badge",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}]]);function CL({status:e,className:r}){switch(e){case"completed":return(0,O.jsx)(sJ,{className:(0,ey.cn)("h-4 w-4 text-green-500",r)});case"in_progress":return(0,O.jsx)(sj,{className:(0,ey.cn)("h-4 w-4 text-cyan-500 animate-spin",r)});case"pending":default:return(0,O.jsx)(sZ,{className:(0,ey.cn)("h-4 w-4 text-muted-foreground",r)});case"deleted":return(0,O.jsx)(s0,{className:(0,ey.cn)("h-4 w-4 text-red-400",r)})}}function Cz(e,r){try{let s="string"==typeof e?JSON.parse(e):e;if(s&&"object"==typeof s&&r(s))return s}catch{}return null}function CO({input:e}){let r="string"==typeof e?e:JSON.stringify(e,null,2);return(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>500?r.substring(0,500)+"...":r})}function C$({input:e}){let r=Cz(e,e=>Array.isArray(e.todos)&&e.todos.length>0);return r?(0,O.jsx)("div",{className:"mt-2 space-y-1",children:r.todos.map((e,r)=>(0,O.jsxs)("div",{className:"flex items-start gap-2 py-0.5",children:[(0,O.jsx)(CL,{status:e.status,className:"mt-0.5 flex-shrink-0"}),(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("span",{className:(0,ey.cn)("text-sm break-words","completed"===e.status&&"line-through text-muted-foreground"),children:e.subject??e.content??"Untitled task"}),"in_progress"===e.status&&e.activeForm&&(0,O.jsx)("span",{className:"block text-xs italic text-cyan-500",children:e.activeForm})]})]},e.id??r))}):(0,O.jsx)(CO,{input:e})}function CW({input:e}){let r=Cz(e,e=>"string"==typeof e.subject);return r?(0,O.jsxs)("div",{className:"mt-2 flex items-start gap-2",children:[(0,O.jsx)(CI,{className:"h-4 w-4 text-cyan-500 mt-0.5 flex-shrink-0"}),(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("span",{className:"text-sm font-medium break-words",children:r.subject}),r.description&&(0,O.jsx)("span",{className:"block text-xs text-muted-foreground mt-0.5 break-words",children:r.description.length>200?r.description.substring(0,200)+"...":r.description})]})]}):(0,O.jsx)(CO,{input:e})}function CH({input:e}){let r=Cz(e,e=>"string"==typeof e.taskId);return r?(0,O.jsxs)("div",{className:"mt-2 flex items-start gap-2 flex-wrap",children:[r.status?(0,O.jsx)(CL,{status:r.status,className:"mt-0.5 flex-shrink-0"}):(0,O.jsx)(wx,{className:"h-4 w-4 text-cyan-500 mt-0.5 flex-shrink-0"}),(0,O.jsxs)("span",{className:"text-sm break-words",children:["Task #",r.taskId,r.status&&(0,O.jsxs)(O.Fragment,{children:[" ",(0,O.jsx)(wx,{className:"inline h-3 w-3 text-muted-foreground mx-0.5"})," ",r.status]}),r.subject&&(0,O.jsxs)("span",{className:"text-muted-foreground",children:[" — ",r.subject]})]}),r.addBlockedBy&&r.addBlockedBy.length>0&&(0,O.jsx)("div",{className:"flex gap-1 mt-1 w-full pl-6",children:r.addBlockedBy.map(e=>(0,O.jsxs)(sa,{variant:"outline",className:"text-[10px]",children:[(0,O.jsx)(CB,{className:"h-2.5 w-2.5 mr-0.5"}),"blocked by #",e]},e))}),r.addBlocks&&r.addBlocks.length>0&&(0,O.jsx)("div",{className:"flex gap-1 mt-1 w-full pl-6",children:r.addBlocks.map(e=>(0,O.jsxs)(sa,{variant:"outline",className:"text-[10px]",children:[(0,O.jsx)(CB,{className:"h-2.5 w-2.5 mr-0.5"}),"blocks #",e]},e))})]}):(0,O.jsx)(CO,{input:e})}function CU(){return(0,O.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-sm text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin text-cyan-500"}),(0,O.jsx)("span",{children:"Listing tasks..."})]})}function Cq({input:e}){let r=Cz(e,e=>"string"==typeof e.taskId);return r?(0,O.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-sm text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin text-cyan-500"}),(0,O.jsxs)("span",{children:["Fetching task #",r.taskId,"..."]})]}):(0,O.jsx)(CO,{input:e})}function CK({output:e}){let r=function(e){try{let r=JSON.parse(e);if(Array.isArray(r))return r.filter(e=>e.id&&e.subject).map(e=>({id:String(e.id),subject:String(e.subject),status:e.status||"pending",owner:e.owner?String(e.owner):void 0,blockedBy:Array.isArray(e.blockedBy)?e.blockedBy.map(String):void 0}));let s=r.tasks??r.items??r.data;if(Array.isArray(s))return s.filter(e=>e.id&&e.subject).map(e=>({id:String(e.id),subject:String(e.subject),status:e.status||"pending",owner:e.owner?String(e.owner):void 0,blockedBy:Array.isArray(e.blockedBy)?e.blockedBy.map(String):void 0}))}catch{let r=e.trim().split("\n").filter(Boolean),s=[];for(let e of r){let r=e.match(/^#?(\d+)[\s.:\-]+\[?(completed|in_progress|pending|deleted)\]?\s+(.+)/i);r&&s.push({id:r[1],status:r[2].toLowerCase(),subject:r[3].trim()})}if(s.length>0)return s}return null}(e);return r?(0,O.jsx)("div",{className:"mt-1 space-y-1",children:r.map(e=>(0,O.jsxs)("div",{className:"flex items-start gap-2 py-0.5",children:[(0,O.jsx)(CL,{status:e.status,className:"mt-0.5 flex-shrink-0"}),(0,O.jsxs)("div",{className:"min-w-0 flex items-center gap-1.5 flex-wrap",children:[(0,O.jsxs)("span",{className:"text-xs text-muted-foreground",children:["#",e.id]}),(0,O.jsx)("span",{className:(0,ey.cn)("text-sm break-words","completed"===e.status&&"line-through text-muted-foreground"),children:e.subject}),e.blockedBy&&e.blockedBy.length>0&&(0,O.jsx)(sa,{variant:"outline",className:"text-[10px]",children:"blocked"})]})]},e.id))}):null}function CV({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.file_path)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{file_path:s,offset:n,limit:i}=r,a=s.split("/"),o=a.pop()||s,l=a.join("/"),c=null!=n||null!=i,d="";if(c){let e=n??1;d=null!=i?`Lines ${e}\u2013${e+i-1}`:`From line ${e}`}return(0,O.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("span",{className:"text-sm font-medium break-all",children:o}),l&&(0,O.jsx)("p",{className:"text-xs text-muted-foreground truncate",title:s,children:l})]}),c&&(0,O.jsx)(sa,{variant:"outline",className:"text-xs shrink-0",children:d})]})}function CY({output:e}){let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["File contents (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function CG({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.file_path)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{file_path:s,content:n}=r,i=s.split("/"),a=i.pop()||s,o=i.join("/"),l=n.split("\n").length;return(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("span",{className:"text-sm font-medium break-all",children:a}),o&&(0,O.jsx)("p",{className:"text-xs text-muted-foreground truncate",title:s,children:o})]}),(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Content (",l," ",1===l?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:n.length>1e3?n.substring(0,1e3)+"...":n})]})]})}function CX({output:e}){return e&&""!==e.trim()?(0,O.jsxs)("details",{children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Result"}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]}):(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"File written"})}function CJ({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.command)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{command:s,description:n,timeout:i}=r;return(0,O.jsxs)("div",{className:"space-y-1",children:[n&&(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:n}),(0,O.jsxs)("div",{className:"flex items-start gap-2",children:[(0,O.jsxs)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,O.jsx)("span",{className:"text-muted-foreground select-none",children:"$ "}),s]}),null!=i&&(0,O.jsx)(sa,{variant:"outline",className:"text-xs shrink-0 mt-1",children:function(e){if(e>=6e4){let r=e/6e4;return`${r%1==0?r:r.toFixed(1)}m`}return`${e/1e3}s`}(i)})]})]})}function CZ({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Output (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function CQ({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.pattern)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let s=[];return r.path&&s.push({label:r.path}),r.glob&&s.push({label:r.glob}),r.type&&s.push({label:`.${r.type}`}),r.output_mode&&"files_with_matches"!==r.output_mode&&s.push({label:r.output_mode}),null!=r.context&&s.push({label:`context: ${r.context}`}),null!=r["-C"]&&s.push({label:`context: ${r["-C"]}`}),null!=r["-B"]&&s.push({label:`before: ${r["-B"]}`}),null!=r["-A"]&&s.push({label:`after: ${r["-A"]}`}),r["-i"]&&s.push({label:"case-insensitive"}),r.multiline&&s.push({label:"multiline"}),null!=r.head_limit&&s.push({label:`limit: ${r.head_limit}`}),null!=r.offset&&s.push({label:`offset: ${r.offset}`}),(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsx)("div",{className:"flex items-start gap-2",children:(0,O.jsxs)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,O.jsx)("span",{className:"text-muted-foreground select-none",children:"/ "}),r.pattern]})}),s.length>0&&(0,O.jsx)("div",{className:"flex items-center gap-1.5 flex-wrap",children:s.map((e,r)=>(0,O.jsx)(sa,{variant:"outline",className:"text-xs",children:e.label},r))})]})}function C0({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No matches"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Results (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function C1({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.pattern)return r;return null}catch{return null}}(e);return r?(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsx)("div",{className:"flex items-start gap-2",children:(0,O.jsx)("pre",{className:"flex-1 min-w-0 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.pattern})}),r.path&&(0,O.jsx)("div",{className:"flex items-center gap-1.5 flex-wrap",children:(0,O.jsx)(sa,{variant:"outline",className:"text-xs",children:r.path})})]}):(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)})}function C2({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No matches"});let r=e.trim().split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:[r," ",1===r?"file":"files"," found"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}let C5={Explore:"Explore",Bash:"Bash",Plan:"Plan","general-purpose":"General","code-simplifier":"Simplify","superpowers:code-reviewer":"Review","memory-leak-detector":"Memory","directory-structure-validator":"Structure","tech-docs-finder":"Docs","claude-code-guide":"Guide","statusline-setup":"Status"};function C3({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.description&&"string"==typeof r.subagent_type)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{description:s,subagent_type:n,prompt:i,model:a,max_turns:o,resume:l,run_in_background:c}=r,d=[];return d.push({label:C5[n]||n}),a&&d.push({label:a}),null!=o&&d.push({label:`${o} turns`}),c&&d.push({label:"background"}),l&&d.push({label:"resume"}),(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,O.jsx)("span",{className:"text-sm",children:s}),d.map((e,r)=>(0,O.jsx)(sa,{variant:"outline",className:"text-xs shrink-0",children:e.label},r))]}),i&&(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Prompt (",i.length>1e3?`${Math.round(i.length/1e3)}k chars`:`${i.length} chars`,")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:i.length>1e3?i.substring(0,1e3)+"...":i})]})]})}function C4({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Agent result (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function C6(e,r){return e.length>r?e.substring(0,r)+"...":e}function C7({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.file_path&&"string"==typeof r.old_string&&"string"==typeof r.new_string)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{file_path:s,old_string:n,new_string:i,replace_all:a}=r,o=s.split("/"),l=o.pop()||s,c=o.join("/"),d=n.split("\n").length,u=i.split("\n").length;return(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("span",{className:"text-sm font-medium break-all",children:l}),c&&(0,O.jsx)("p",{className:"text-xs text-muted-foreground truncate",title:s,children:c})]}),(0,O.jsx)(sa,{variant:"outline",className:"text-xs shrink-0",children:d===u?`${d} ${1===d?"line":"lines"}`:`${d}\u2192${u} lines`}),a&&(0,O.jsx)(sa,{variant:"outline",className:"text-xs shrink-0",children:"replace all"})]}),(0,O.jsxs)("details",{children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Diff"}),(0,O.jsxs)("div",{className:"mt-1 text-xs rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full",children:[(0,O.jsxs)("pre",{className:"bg-red-500/10 p-1.5 rounded-t whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,O.jsx)("span",{className:"text-red-500 select-none",children:"- "}),C6(n,500)]}),(0,O.jsxs)("pre",{className:"bg-green-500/10 p-1.5 rounded-b whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,O.jsx)("span",{className:"text-green-500 select-none",children:"+ "}),C6(i,500)]})]})]})]})}function C8({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});if(e.length<=200)return(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:e});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Result (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function C9({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.url&&"string"==typeof r.prompt)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{display:s,href:n}=function(e){try{let r=new URL(e),s="/"===r.pathname?"":r.pathname,n=r.hostname+s;return{display:n.length>80?n.substring(0,77)+"...":n,href:e}}catch{return{display:e.length>80?e.substring(0,77)+"...":e,href:e}}}(r.url),i=r.prompt.length>150?r.prompt.substring(0,147)+"...":r.prompt;return(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsx)("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"block text-xs font-mono text-blue-500 hover:underline truncate",children:s}),(0,O.jsxs)("p",{className:"text-xs text-muted-foreground",children:['"',i,'"']})]})}function ke({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No content fetched"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Response (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function kt({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.query)return r;return null}catch{return null}}(e);return r?(0,O.jsxs)("div",{className:"space-y-1.5",children:[(0,O.jsx)("p",{className:"text-xs font-mono bg-muted/50 px-2 py-1 rounded break-words",children:r.query}),r.allowed_domains&&r.allowed_domains.length>0&&(0,O.jsxs)("div",{className:"flex items-center gap-1 flex-wrap",children:[(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:"only:"}),r.allowed_domains.map(e=>(0,O.jsx)(sa,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:e},e))]}),r.blocked_domains&&r.blocked_domains.length>0&&(0,O.jsxs)("div",{className:"flex items-center gap-1 flex-wrap",children:[(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:"exclude:"}),r.blocked_domains.map(e=>(0,O.jsx)(sa,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:e},e))]})]}):(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)})}function kr({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No search results"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Results (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function ks({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.skill)return r;return null}catch{return null}}(e);return r?(0,O.jsxs)("div",{className:"space-y-1",children:[(0,O.jsx)("p",{className:"text-xs font-mono text-pink-500",children:r.skill}),r.args&&(0,O.jsxs)("p",{className:"text-xs text-muted-foreground truncate",children:["args: ",r.args]})]}):(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)})}function kn({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Loaded (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function ki({input:e}){let r=function(e){try{let r="string"==typeof e?JSON.parse(e):e;if(r&&"object"==typeof r&&"string"==typeof r.task_id)return r;return null}catch{return null}}(e);if(!r)return(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:"string"==typeof e?e:JSON.stringify(e,null,2)});let{task_id:s,block:n,timeout:i}=r,a=[];return a.push({label:!1===n?"non-blocking":"blocking"}),null!=i&&a.push({label:`${Math.round(i/1e3)}s`}),(0,O.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,O.jsx)("code",{className:"text-sm bg-muted/50 px-1.5 py-0.5 rounded",children:s}),a.map((e,r)=>(0,O.jsx)(sa,{variant:"outline",className:"text-xs shrink-0",children:e.label},r))]})}function ka({output:e}){if(!e||""===e.trim())return(0,O.jsx)("p",{className:"text-xs text-muted-foreground italic",children:"No output"});let r=e.split("\n").length;return(0,O.jsxs)("details",{children:[(0,O.jsxs)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:["Task output (",r," ",1===r?"line":"lines",")"]}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.length>1e3?e.substring(0,1e3)+"...":e})]})}function ko({input:e}){let r="string"==typeof e?function(e){try{return JSON.parse(e)}catch{return null}}(e):e,s=r?.changes??[];return 0===s.length?(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"No file changes"}):(0,O.jsx)("div",{className:"space-y-2 mt-1",children:s.map((e,r)=>(0,O.jsxs)("div",{children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)(Sr,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),(0,O.jsx)("code",{className:"text-xs break-all",children:e.path}),(0,O.jsx)(sa,{variant:"secondary",className:`text-[10px] ${function(e){switch(e){case"added":case"add":return"bg-green-500/10 text-green-600";case"deleted":case"delete":return"bg-red-500/10 text-red-600";default:return"bg-blue-500/10 text-blue-600"}}(e.kind)}`,children:function(e){switch(e){case"added":case"add":return"added";case"deleted":case"delete":return"deleted";default:return"modified"}}(e.kind)})]}),e.diff&&(0,O.jsxs)("details",{className:"mt-1",children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"View diff"}),(0,O.jsx)("pre",{className:"mt-1 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.diff.split("\n").map((e,r)=>{let s="";return e.startsWith("+")?s="bg-green-500/10 text-green-700 dark:text-green-400":e.startsWith("-")&&(s="bg-red-500/10 text-red-700 dark:text-red-400"),(0,O.jsx)("div",{className:s,children:e},r)})})]})]},r))})}function kl({output:e}){let r=e.toLowerCase(),s="text-muted-foreground";return r.includes("completed")||r.includes("success")?s="text-green-600 dark:text-green-400":r.includes("failed")||r.includes("error")?s="text-red-600 dark:text-red-400":(r.includes("declined")||r.includes("denied"))&&(s="text-amber-600 dark:text-amber-400"),(0,O.jsx)("p",{className:`text-xs ${s}`,children:e})}function kc({path:e,size:r}){let s;return(0,O.jsxs)("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-border bg-muted/60 px-1.5 py-0.5 text-xs font-mono align-baseline",title:e,children:[(0,O.jsx)(Sr,{className:"w-3 h-3 text-muted-foreground shrink-0"}),(0,O.jsx)("span",{className:"truncate max-w-[18ch]",children:(s=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")))>=0?e.slice(s+1):e}),(0,O.jsx)("span",{className:"text-muted-foreground",children:function(e){if(e<1024)return`${e} B`;let r=e/1024;return r<10?`${r.toFixed(1)} KB`:r<1024?`${Math.round(r)} KB`:`${(r/1024).toFixed(1)} MB`}(r)})]})}let kd=/<vpaste path="([^"]+)" size="(\d+)" \/>/g;function ku({message:e,messageIndex:r}){let s=function(e,r){switch(e.type){case"user":return(0,O.jsx)(kf,{content:e.content,origin:e.origin});case"assistant":return(0,O.jsx)(kp,{content:e.content,agentType:e.agentType});case"tool_use":return(0,O.jsx)(km,{tool:e.tool,input:e.input,messageIndex:r});case"tool_result":return(0,O.jsx)(kg,{tool:e.tool,output:e.output});case"thinking":return(0,O.jsx)(kx,{content:e.content});case"error":return(0,O.jsx)(kv,{message:e.message});case"system":return(0,O.jsx)(k_,{content:e.content});case"approval_request":return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-amber-500/10 flex items-center justify-center",children:(0,O.jsx)(C_,{className:"w-4 h-4 text-amber-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-amber-500 mb-1",children:"command"===e.requestType?"Command Approval":"File Change Approval"}),"command"===e.requestType?(0,O.jsx)(CF,{requestId:e.requestId,command:e.command,cwd:e.cwd,messageIndex:r}):(0,O.jsx)(CP,{requestId:e.requestId,changes:e.changes,messageIndex:r})]})]});default:return null}}(e,r);return s?(0,O.jsxs)("div",{className:"group relative",children:[s,(0,O.jsx)("span",{className:"pointer-events-none absolute right-0 top-3 text-xs tabular-nums text-muted-foreground opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:function(e){let r=new Date(e),s=new Date,n=r.getFullYear()===s.getFullYear()&&r.getMonth()===s.getMonth()&&r.getDate()===s.getDate(),i=r.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});if(n)return i;let a=r.toLocaleDateString(void 0,{year:"numeric",month:"2-digit",day:"2-digit"});return`${a} ${i}`}(e.timestamp)})]}):null}function kh(e){let r=function(e){let r,s=[],n=0,i=RegExp(kd.source,"g");for(;null!==(r=i.exec(e));)r.index>n&&s.push({kind:"text",text:e.slice(n,r.index)}),s.push({kind:"chip",path:r[1],size:Number(r[2])}),n=r.index+r[0].length;return n<e.length&&s.push({kind:"text",text:e.slice(n)}),s}(e);return 1===r.length&&"text"===r[0].kind?(0,O.jsx)("span",{className:"whitespace-pre-wrap break-words",children:e??""}):(0,O.jsx)("div",{className:"text-foreground max-w-none break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:r.map((e,r)=>"text"===e.kind?(0,O.jsx)("span",{className:"whitespace-pre-wrap break-words",children:e.text},r):(0,O.jsx)(kc,{path:e.path,size:e.size},r))})}function kf({content:e,origin:r}){return"workflow"===r&&"string"==typeof e?(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,O.jsx)(Cm,{className:"w-3.5 h-3.5 text-sky-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Workflow"}),(0,O.jsx)("div",{className:"text-foreground prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,O.jsx)(CE,{children:e})})]})]}):(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-primary/10 flex items-center justify-center",children:(0,O.jsx)(Cc,{className:"w-3.5 h-3.5 text-primary"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-foreground mb-1",children:"You"}),(0,O.jsx)("div",{className:"text-foreground max-w-none break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:"string"==typeof e?kh(e):e.map((e,r)=>"text"===e.type?(0,O.jsx)($.Fragment,{children:kh(e.text)},r):(0,O.jsx)("img",{src:`data:${e.mediaType};base64,${e.data}`,alt:"Attached image",className:"max-w-sm rounded-lg mt-2"},r))})]})]})}function kp({content:e,agentType:r}){let s=function(){try{return N7().agentType}catch{return"claude-code"}}(),n="codex"===(r??s),[i,a]=(0,$.useState)(!1);return(0,O.jsxs)("div",{className:"group flex gap-3 py-3",children:[(0,O.jsx)("div",{className:`flex-shrink-0 w-7 h-7 rounded-lg ${n?"bg-green-500/10":"bg-violet-500/10"} flex items-center justify-center`,children:(0,O.jsx)(sb,{className:`w-3.5 h-3.5 ${n?"text-green-500":"text-violet-500"}`})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,O.jsx)("p",{className:`text-sm font-medium ${n?"text-green-500":"text-violet-500"}`,children:n?"Codex":"Claude"}),(0,O.jsx)("button",{type:"button",onClick:()=>a(e=>!e),title:i?"View rendered":"View source","aria-label":i?"View rendered":"View source","aria-pressed":i,className:"opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity text-muted-foreground hover:text-foreground",children:i?(0,O.jsx)(wf,{className:"w-3.5 h-3.5"}):(0,O.jsx)(Sf,{className:"w-3.5 h-3.5"})})]}),i?(0,O.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-words bg-muted/50 rounded-md p-3 overflow-x-auto text-foreground select-text",children:e??""}):(0,O.jsx)("div",{className:"text-foreground prose prose-sm dark:prose-invert max-w-none break-words [&_pre]:overflow-x-auto [&_pre]:max-w-full [&_code]:break-all [&_p]:break-words",style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,O.jsx)(CE,{children:e??""})})]})]})}function km({tool:e,input:r,messageIndex:s}){if("ImageView"===e){let e="object"==typeof r&&null!==r&&"path"in r&&"string"==typeof r.path?r.path:"";return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,O.jsx)(wf,{className:"w-4 h-4 text-sky-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"View Image"}),(0,O.jsx)("p",{className:"font-mono text-muted-foreground break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:e})]})]})}if("AskUserQuestion"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-violet-500/10 flex items-center justify-center",children:(0,O.jsx)(Ch,{className:"w-4 h-4 text-violet-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-violet-500 mb-1",children:"Question"}),(0,O.jsx)(CD,{input:r,messageIndex:s})]})]});if("ExitPlanMode"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-green-500/10 flex items-center justify-center",children:(0,O.jsx)(Cf,{className:"w-4 h-4 text-green-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-green-500 mb-1",children:"Plan Ready"}),(0,O.jsx)(CM,{input:r,messageIndex:s})]})]});let n={TodoWrite:{label:"Tasks",ui:(0,O.jsx)(C$,{input:r})},TaskCreate:{label:"Create Task",ui:(0,O.jsx)(CW,{input:r})},TaskUpdate:{label:"Update Task",ui:(0,O.jsx)(CH,{input:r})},TaskList:{label:"Task List",ui:(0,O.jsx)(CU,{})},TaskGet:{label:"Get Task",ui:(0,O.jsx)(Cq,{input:r})}}[e];if(n)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-cyan-500/10 flex items-center justify-center",children:(0,O.jsx)(sQ,{className:"w-4 h-4 text-cyan-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-cyan-500 mb-1",children:n.label}),n.ui]})]});if("Read"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,O.jsx)(Sr,{className:"w-4 h-4 text-sky-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Read File"}),(0,O.jsx)(CV,{input:r})]})]});if("Edit"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,O.jsx)(Cg,{className:"w-4 h-4 text-sky-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Edit File"}),(0,O.jsx)(C7,{input:r})]})]});if("Write"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,O.jsx)(Cx,{className:"w-4 h-4 text-sky-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"Write File"}),(0,O.jsx)(CG,{input:r})]})]});if("Bash"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-emerald-500/10 flex items-center justify-center",children:(0,O.jsx)(ol,{className:"w-4 h-4 text-emerald-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-emerald-500 mb-1",children:"Run Command"}),(0,O.jsx)(CJ,{input:r})]})]});if("Grep"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-orange-500/10 flex items-center justify-center",children:(0,O.jsx)(sA,{className:"w-4 h-4 text-orange-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-orange-500 mb-1",children:"Search"}),(0,O.jsx)(CQ,{input:r})]})]});if("Glob"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-teal-500/10 flex items-center justify-center",children:(0,O.jsx)(Cp,{className:"w-4 h-4 text-teal-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-teal-500 mb-1",children:"Glob"}),(0,O.jsx)(C1,{input:r})]})]});if("Task"===e||"Agent"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-purple-500/10 flex items-center justify-center",children:(0,O.jsx)(Cm,{className:"w-4 h-4 text-purple-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-purple-500 mb-1",children:"Agent"}),(0,O.jsx)(C3,{input:r})]})]});if("TaskOutput"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-purple-500/10 flex items-center justify-center",children:(0,O.jsx)(Cm,{className:"w-4 h-4 text-purple-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-purple-500 mb-1",children:"Task Output"}),(0,O.jsx)(ki,{input:r})]})]});if("WebFetch"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-blue-500/10 flex items-center justify-center",children:(0,O.jsx)(ry,{className:"w-4 h-4 text-blue-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-blue-500 mb-1",children:"Fetch Web Page"}),(0,O.jsx)(C9,{input:r})]})]});if("WebSearch"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-indigo-500/10 flex items-center justify-center",children:(0,O.jsx)(Cv,{className:"w-4 h-4 text-indigo-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-indigo-500 mb-1",children:"Web Search"}),(0,O.jsx)(kt,{input:r})]})]});if("Skill"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-pink-500/10 flex items-center justify-center",children:(0,O.jsx)(hU,{className:"w-4 h-4 text-pink-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-pink-500 mb-1",children:"Skill"}),(0,O.jsx)(ks,{input:r})]})]});if("FileChange"===e)return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-sky-500/10 flex items-center justify-center",children:(0,O.jsx)(Cg,{className:"w-4 h-4 text-sky-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-sky-500 mb-1",children:"File Changes"}),(0,O.jsx)(ko,{input:r})]})]});let i="string"==typeof r?r:JSON.stringify(r,null,2);return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-amber-500/10 flex items-center justify-center",children:(0,O.jsx)(Cd,{className:"w-4 h-4 text-amber-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsxs)("p",{className:"text-sm font-medium text-amber-500 mb-1 break-words",children:["Tool: ",e]}),(0,O.jsxs)("details",{open:!0,children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Input"}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:i.length>500?i.substring(0,500)+"...":i})]})]})]})}function kg({tool:e,output:r}){if(["TodoWrite","TaskCreate","TaskUpdate","TaskList","TaskGet"].includes(e)){let s="TaskList"===e?(0,O.jsx)(CK,{output:r}):null;return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsxs)("p",{className:"text-xs text-muted-foreground mb-1",children:["Result (",e,")"]}),s||(0,O.jsxs)("details",{children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Output"}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>1e3?r.substring(0,1e3)+"...":r})]})]})})}if("Read"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(CY,{output:r})})});if("Edit"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(C8,{output:r})})});if("Write"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(CX,{output:r})})});if("Bash"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(CZ,{output:r})})});if("Grep"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(C0,{output:r})})});if("Glob"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(C2,{output:r})})});if("Task"===e||"Agent"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(C4,{output:r})})});if("TaskOutput"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(ka,{output:r})})});if("WebFetch"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(ke,{output:r})})});if("WebSearch"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(kr,{output:r})})});if("Skill"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(kn,{output:r})})});if("FileChange"===e)return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)(kl,{output:r})})});let s=r.length>200;return(0,O.jsx)("div",{className:"flex gap-3 py-3 pl-11",children:(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsxs)("p",{className:"text-xs text-muted-foreground mb-1",children:["Result",e?` (${e})`:""]}),(0,O.jsxs)("details",{className:(0,ey.cn)(!s&&"open"),children:[(0,O.jsx)("summary",{className:"text-xs text-muted-foreground cursor-pointer hover:text-foreground",children:"Output"}),(0,O.jsx)("pre",{className:"mt-1 bg-muted/50 p-2 rounded overflow-x-auto max-h-48 overflow-y-auto max-w-full whitespace-pre-wrap break-all",style:{fontSize:"var(--conv-font-size, 12px)"},children:r.length>1e3?r.substring(0,1e3)+"...":r})]})]})})}function kx({content:e}){let r=e??"",s=r.trim().length>0,n=s?r.length>500?r.substring(0,500)+"...":r:"Reasoning unavailable — this model does not expose its thinking content.";return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-blue-500/10 flex items-center justify-center",children:(0,O.jsx)(Cu,{className:"w-3.5 h-3.5 text-blue-500"})}),(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsxs)("details",{children:[(0,O.jsx)("summary",{className:"text-xs font-medium text-blue-500 cursor-pointer hover:underline",children:"Thinking..."}),(0,O.jsx)("div",{className:`mt-2 whitespace-pre-wrap break-words bg-blue-500/5 p-2 rounded-md overflow-hidden ${s?"text-muted-foreground":"text-muted-foreground/70 italic"}`,style:{fontSize:"var(--conv-font-size, 12px)"},children:n})]})})]})}function kv({message:e}){return(0,O.jsxs)("div",{className:"flex gap-3 py-3",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-red-500/10 flex items-center justify-center",children:(0,O.jsx)(sy,{className:"w-3.5 h-3.5 text-red-500"})}),(0,O.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-red-500 mb-1",children:"Error"}),(0,O.jsx)("p",{className:"text-red-500/80 break-words whitespace-pre-wrap",style:{fontSize:"var(--conv-font-size, 14px)"},children:e})]})]})}function k_({content:e}){return(0,O.jsxs)("div",{className:"flex gap-3 py-2",children:[(0,O.jsx)("div",{className:"flex-shrink-0 w-7 h-7 rounded-lg bg-gray-500/10 flex items-center justify-center",children:(0,O.jsx)(_J,{className:"w-3.5 h-3.5 text-gray-500"})}),(0,O.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,O.jsx)("p",{className:"text-muted-foreground break-words",style:{fontSize:"var(--conv-font-size, 12px)"},children:e??""})})]})}var ky="HoverCard",[kb,kw]=q(ky,[iw]),kS=iw(),[kj,kC]=kb(ky),kk=e=>{let{__scopeHoverCard:r,children:s,open:n,defaultOpen:i,onOpenChange:a,openDelay:o=700,closeDelay:l=300}=e,c=kS(r),d=$.useRef(0),u=$.useRef(0),h=$.useRef(!1),f=$.useRef(!1),[p,m]=G({prop:n,defaultProp:i??!1,onChange:a,caller:ky}),g=$.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>m(!0),o)},[o,m]),x=$.useCallback(()=>{clearTimeout(d.current),h.current||f.current||(u.current=window.setTimeout(()=>m(!1),l))},[l,m]),v=$.useCallback(()=>m(!1),[m]);return $.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),(0,O.jsx)(kj,{scope:r,open:p,onOpenChange:m,onOpen:g,onClose:x,onDismiss:v,hasSelectionRef:h,isPointerDownOnContentRef:f,children:(0,O.jsx)(iC,{...c,children:s})})};kk.displayName=ky;var kN="HoverCardTrigger",kE=$.forwardRef((e,r)=>{let{__scopeHoverCard:s,...n}=e,i=kC(kN,s),a=kS(s);return(0,O.jsx)(iN,{asChild:!0,...a,children:(0,O.jsx)(er.a,{"data-state":i.open?"open":"closed",...n,ref:r,onPointerEnter:K(e.onPointerEnter,kI(i.onOpen)),onPointerLeave:K(e.onPointerLeave,kI(i.onClose)),onFocus:K(e.onFocus,i.onOpen),onBlur:K(e.onBlur,i.onClose),onTouchStart:K(e.onTouchStart,e=>e.preventDefault())})})});kE.displayName=kN;var kD="HoverCardPortal",[kR,kA]=kb(kD,{forceMount:void 0}),kT=e=>{let{__scopeHoverCard:r,forceMount:s,children:n,container:i}=e,a=kC(kD,r);return(0,O.jsx)(kR,{scope:r,forceMount:s,children:(0,O.jsx)(Z,{present:s||a.open,children:(0,O.jsx)(eW,{asChild:!0,container:i,children:n})})})};kT.displayName=kD;var kM="HoverCardContent",kF=$.forwardRef((e,r)=>{let s=kA(kM,e.__scopeHoverCard),{forceMount:n=s.forceMount,...i}=e,a=kC(kM,e.__scopeHoverCard);return(0,O.jsx)(Z,{present:n||a.open,children:(0,O.jsx)(kP,{"data-state":a.open?"open":"closed",...i,onPointerEnter:K(e.onPointerEnter,kI(a.onOpen)),onPointerLeave:K(e.onPointerLeave,kI(a.onClose)),ref:r})})});kF.displayName=kM;var kP=$.forwardRef((e,r)=>{let{__scopeHoverCard:s,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:a,onInteractOutside:o,...l}=e,c=kC(kM,s),d=kS(s),u=$.useRef(null),h=(0,U.useComposedRefs)(r,u),[f,p]=$.useState(!1);return $.useEffect(()=>{if(f){let e=document.body;return z=e.style.userSelect||e.style.webkitUserSelect,e.style.userSelect="none",e.style.webkitUserSelect="none",()=>{e.style.userSelect=z,e.style.webkitUserSelect=z}}},[f]),$.useEffect(()=>{if(u.current){let e=()=>{p(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{document.getSelection()?.toString()!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",e),()=>{document.removeEventListener("pointerup",e),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),$.useEffect(()=>{u.current&&(function(e){let r=[],s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();)r.push(s.currentNode);return r})(u.current).forEach(e=>e.setAttribute("tabindex","-1"))}),(0,O.jsx)(eR,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:o,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:K(a,e=>{e.preventDefault()}),onDismiss:c.onDismiss,children:(0,O.jsx)(iA,{...d,...l,onPointerDown:K(l.onPointerDown,e=>{e.currentTarget.contains(e.target)&&p(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:h,style:{...l.style,userSelect:f?"text":void 0,WebkitUserSelect:f?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})});function kI(e){return r=>"touch"===r.pointerType?void 0:e()}function kB({...e}){return(0,O.jsx)(kk,{"data-slot":"hover-card",...e})}function kL({...e}){return(0,O.jsx)(kE,{"data-slot":"hover-card-trigger",...e})}function kz({className:e,align:r="center",sideOffset:s=4,...n}){return(0,O.jsx)(kT,{"data-slot":"hover-card-portal",children:(0,O.jsx)(kF,{"data-slot":"hover-card-content",align:r,sideOffset:s,className:(0,ey.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...n})})}$.forwardRef((e,r)=>{let{__scopeHoverCard:s,...n}=e,i=kS(s);return(0,O.jsx)(iF,{...i,...n,ref:r})}).displayName="HoverCardArrow";let kO=(0,ew.default)("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),k$=(0,ew.default)("image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);(0,ew.default)("mic",[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]]);let kW=(0,ew.default)("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]),kH=(e=21)=>{let r="",s=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)r+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&s[e]];return r},kU=(0,$.createContext)(null),kq=(0,$.createContext)(null),kK=()=>(0,$.useContext)(kU),kV=(0,$.createContext)(null),kY=()=>{let e=(0,$.useContext)(kq),r=(0,$.useContext)(kV),s=e??r;if(!s)throw Error("usePromptInputAttachments must be used within a PromptInput or PromptInputProvider");return s};function kG({data:e,className:r,...s}){let n=kY(),i=e.filename||"",a="image"==(e.mediaType?.startsWith("image/")&&e.url?"image":"file"),o=i||(a?"Image":"Attachment");return(0,O.jsxs)(k7,{children:[(0,O.jsx)(kL,{asChild:!0,children:(0,O.jsxs)("div",{className:(0,ey.cn)("group relative flex h-8 cursor-pointer select-none items-center gap-1.5 rounded-md border border-border px-1.5 font-medium text-sm transition-all hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",r),...s,children:[(0,O.jsxs)("div",{className:"relative size-5 shrink-0",children:[(0,O.jsx)("div",{className:"absolute inset-0 flex size-5 items-center justify-center overflow-hidden rounded bg-background transition-opacity group-hover:opacity-0",children:a?(0,O.jsx)("img",{alt:i||"attachment",className:"size-5 object-cover",height:20,src:e.url,width:20}):(0,O.jsx)("div",{className:"flex size-5 items-center justify-center text-muted-foreground",children:(0,O.jsx)(kW,{className:"size-3"})})}),(0,O.jsxs)(W.Button,{"aria-label":"Remove attachment",className:"absolute inset-0 size-5 cursor-pointer rounded p-0 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 [&>svg]:size-2.5",onClick:r=>{r.stopPropagation(),n.remove(e.id)},type:"button",variant:"ghost",children:[(0,O.jsx)(t7,{}),(0,O.jsx)("span",{className:"sr-only",children:"Remove"})]})]}),(0,O.jsx)("span",{className:"flex-1 truncate",children:o})]},e.id)}),(0,O.jsx)(k8,{className:"w-auto p-2",children:(0,O.jsxs)("div",{className:"w-auto space-y-3",children:[a&&(0,O.jsx)("div",{className:"flex max-h-96 w-96 items-center justify-center overflow-hidden rounded-md border",children:(0,O.jsx)("img",{alt:i||"attachment preview",className:"max-h-full max-w-full object-contain",height:384,src:e.url,width:448})}),(0,O.jsx)("div",{className:"flex items-center gap-2.5",children:(0,O.jsxs)("div",{className:"min-w-0 flex-1 space-y-1 px-0.5",children:[(0,O.jsx)("h4",{className:"truncate font-semibold text-sm leading-none",children:i||(a?"Image":"Attachment")}),e.mediaType&&(0,O.jsx)("p",{className:"truncate font-mono text-muted-foreground text-xs",children:e.mediaType})]})})]})})]})}function kX({children:e,className:r,...s}){let n=kY();return n.files.length?(0,O.jsx)("div",{className:(0,ey.cn)("flex flex-wrap items-center gap-2 p-3 w-full",r),...s,children:n.files.map(r=>(0,O.jsx)($.Fragment,{children:e(r)},r.id))}):null}let kJ=({label:e="Add photos or files",...r})=>{let s=kY();return(0,O.jsxs)(a8,{...r,onSelect:e=>{e.preventDefault(),s.openFileDialog()},children:[(0,O.jsx)(k$,{className:"mr-2 size-4"})," ",e]})},kZ=({className:e,accept:r,multiple:s,globalDrop:n,syncHiddenInput:i,maxFiles:a,maxFileSize:o,onError:l,onSubmit:c,children:d,...u})=>{let h=kK(),f=!!h,p=(0,$.useRef)(null),m=(0,$.useRef)(null),[g,x]=(0,$.useState)([]),v=f?h.attachments.files:g,_=(0,$.useRef)(v);_.current=v;let y=(0,$.useCallback)(()=>{p.current?.click()},[]),b=(0,$.useCallback)(e=>!r||""===r.trim()||r.split(",").map(e=>e.trim()).filter(Boolean).some(r=>{if(r.endsWith("/*")){let s=r.slice(0,-1);return e.type.startsWith(s)}return e.type===r}),[r]),w=(0,$.useCallback)(e=>{let r=Array.from(e),s=r.filter(e=>b(e));if(r.length&&0===s.length)return void l?.({code:"accept",message:"No files match the accepted types."});let n=s.filter(e=>!o||e.size<=o);s.length>0&&0===n.length?l?.({code:"max_file_size",message:"All files exceed the maximum size."}):x(e=>{let r="number"==typeof a?Math.max(0,a-e.length):void 0,s="number"==typeof r?n.slice(0,r):n;"number"==typeof r&&n.length>r&&l?.({code:"max_files",message:"Too many files. Some were not added."});let i=[];for(let e of s)i.push({id:kH(),type:"file",url:URL.createObjectURL(e),mediaType:e.type,filename:e.name});return e.concat(i)})},[b,a,o,l]),S=(0,$.useCallback)(e=>x(r=>{let s=r.find(r=>r.id===e);return s?.url&&URL.revokeObjectURL(s.url),r.filter(r=>r.id!==e)}),[]),j=(0,$.useCallback)(()=>x(e=>{for(let r of e)r.url&&URL.revokeObjectURL(r.url);return[]}),[]),C=f?h.attachments.add:w,k=f?h.attachments.remove:S,N=f?h.attachments.clear:j,E=f?h.attachments.openFileDialog:y;(0,$.useEffect)(()=>{f&&h.__registerFileInput(p,()=>p.current?.click())},[f,h]),(0,$.useEffect)(()=>{i&&p.current&&0===v.length&&(p.current.value="")},[v,i]),(0,$.useEffect)(()=>{let e=m.current;if(!e||n)return;let r=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault()},s=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault(),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&C(e.dataTransfer.files)};return e.addEventListener("dragover",r),e.addEventListener("drop",s),()=>{e.removeEventListener("dragover",r),e.removeEventListener("drop",s)}},[C,n]),(0,$.useEffect)(()=>{if(!n)return;let e=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault()},r=e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault(),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&C(e.dataTransfer.files)};return document.addEventListener("dragover",e),document.addEventListener("drop",r),()=>{document.removeEventListener("dragover",e),document.removeEventListener("drop",r)}},[C,n]),(0,$.useEffect)(()=>()=>{if(!f)for(let e of _.current)e.url&&URL.revokeObjectURL(e.url)},[f]);let D=async e=>{try{let r=await fetch(e),s=await r.blob();return new Promise(e=>{let r=new FileReader;r.onloadend=()=>e(r.result),r.onerror=()=>e(null),r.readAsDataURL(s)})}catch{return null}},R=(0,$.useMemo)(()=>({files:v.map(e=>({...e,id:e.id})),add:C,remove:k,clear:N,openFileDialog:E,fileInputRef:p}),[v,C,k,N,E]),A=(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("input",{accept:r,"aria-label":"Upload files",className:"hidden",multiple:s,onChange:e=>{e.currentTarget.files&&C(e.currentTarget.files),e.currentTarget.value=""},ref:p,title:"Upload files",type:"file"}),(0,O.jsx)("form",{className:(0,ey.cn)("w-full",e),onSubmit:e=>{e.preventDefault();let r=e.currentTarget,s=f?h.textInput.value:new FormData(r).get("message")||"";f||r.reset(),Promise.all(v.map(async({id:e,...r})=>{if(r.url&&r.url.startsWith("blob:")){let e=await D(r.url);return{...r,url:e??r.url}}return r})).then(r=>{try{let n=c({text:s,files:r},e);n instanceof Promise?n.then(()=>{N(),f&&h.textInput.clear()}).catch(()=>{}):(N(),f&&h.textInput.clear())}catch{}}).catch(()=>{})},ref:m,...u,children:(0,O.jsx)(wv,{className:"overflow-hidden border-[#dedede] bg-card shadow-none dark:border-input dark:bg-card focus-within:border-foreground has-[[data-slot=input-group-control]:focus-visible]:border-foreground has-[[data-slot=input-group-control]:focus-visible]:ring-0",children:d})})]});return f?A:(0,O.jsx)(kV.Provider,{value:R,children:A})},kQ=({onChange:e,onKeyDown:r,onPasteText:s,className:n,placeholder:i="What would you like to know?",...a})=>{let o=kK(),l=kY(),[c,d]=(0,$.useState)(!1),u=o?{value:o.textInput.value,onChange:r=>{o.textInput.setInput(r.currentTarget.value),e?.(r)}}:{onChange:e};return(0,O.jsx)(wj,{className:(0,ey.cn)("field-sizing-content max-h-48 min-h-9",n),name:"message",onCompositionEnd:()=>d(!1),onCompositionStart:()=>d(!0),onKeyDown:e=>{if(r?.(e),!e.defaultPrevented){if("Enter"===e.key){if(c||e.nativeEvent.isComposing||e.shiftKey)return;e.preventDefault();let r=e.currentTarget.form,s=r?.querySelector('button[type="submit"]');if(s?.disabled)return;r?.requestSubmit()}if("Backspace"===e.key&&""===e.currentTarget.value&&l.files.length>0){e.preventDefault();let r=l.files.at(-1);r&&l.remove(r.id)}}},onPaste:e=>{let r=e.clipboardData?.items;if(!r)return;let n=[];for(let e of r)if("file"===e.kind){let r=e.getAsFile();r&&n.push(r)}if(n.length>0){e.preventDefault(),l.add(n);return}if(s){let r=e.clipboardData.getData("text");r.length>0&&s(e,r)}},placeholder:i,...a,...u})},k0=({className:e,...r})=>(0,O.jsx)(wy,{align:"block-end",className:(0,ey.cn)("order-first flex-wrap gap-1",e),...r}),k1=({variant:e="ghost",className:r,size:s,...n})=>{let i=s??($.Children.count(n.children)>1?"sm":"icon-sm");return(0,O.jsx)(ww,{className:(0,ey.cn)(r),size:i,type:"button",variant:e,...n})},k2=e=>(0,O.jsx)(a4,{...e}),k5=({className:e,children:r,...s})=>(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)(k1,{className:e,...s,children:r??(0,O.jsx)(eS,{className:"size-4"})})}),k3=({className:e,...r})=>(0,O.jsx)(a7,{align:"start",className:(0,ey.cn)(e),...r}),k4=({className:e,...r})=>(0,O.jsx)(a8,{className:(0,ey.cn)(e),...r}),k6=({className:e,variant:r="default",size:s="icon-sm",status:n,children:i,...a})=>{let o=(0,O.jsx)(kO,{className:"size-4"});return"submitted"===n?o=(0,O.jsx)(sj,{className:"size-4 animate-spin"}):"streaming"===n?o=(0,O.jsx)(lJ,{className:"size-4"}):"error"===n&&(o=(0,O.jsx)(t7,{className:"size-4"})),(0,O.jsx)(ww,{"aria-label":"Submit",className:(0,ey.cn)("rounded-full",e),size:s,type:"submit",variant:r,...a,children:i??o})},k7=({openDelay:e=0,closeDelay:r=0,...s})=>(0,O.jsx)(kB,{closeDelay:r,openDelay:e,...s}),k8=({align:e="start",...r})=>(0,O.jsx)(kz,{align:e,...r}),k9=({size:e=16})=>(0,O.jsxs)("svg",{height:e,strokeLinejoin:"round",style:{color:"currentcolor"},viewBox:"0 0 16 16",width:e,children:[(0,O.jsx)("title",{children:"Loader"}),(0,O.jsxs)("g",{clipPath:"url(#clip0_2393_1490)",children:[(0,O.jsx)("path",{d:"M8 0V4",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M8 16V12",opacity:"0.5",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M3.29773 1.52783L5.64887 4.7639",opacity:"0.9",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M12.7023 1.52783L10.3511 4.7639",opacity:"0.1",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M12.7023 14.472L10.3511 11.236",opacity:"0.4",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M3.29773 14.472L5.64887 11.236",opacity:"0.6",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M15.6085 5.52783L11.8043 6.7639",opacity:"0.2",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M0.391602 10.472L4.19583 9.23598",opacity:"0.7",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M15.6085 10.4722L11.8043 9.2361",opacity:"0.3",stroke:"currentColor",strokeWidth:"1.5"}),(0,O.jsx)("path",{d:"M0.391602 5.52783L4.19583 6.7639",opacity:"0.8",stroke:"currentColor",strokeWidth:"1.5"})]}),(0,O.jsx)("defs",{children:(0,O.jsx)("clipPath",{id:"clip0_2393_1490",children:(0,O.jsx)("rect",{fill:"white",height:"16",width:"16"})})})]}),Ne=({className:e,size:r=16,...s})=>(0,O.jsx)("div",{className:(0,ey.cn)("inline-flex animate-spin items-center justify-center",e),...s,children:(0,O.jsx)(k9,{size:r})}),Nt=(0,ew.default)("wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]),Nr=(0,ew.default)("wifi-off",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),Ns=(0,ew.default)("square-pen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]),Nn=(0,ew.default)("languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]),Ni=(0,ew.default)("split",[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M8 3H3v5",key:"15dfkv"}],["path",{d:"M12 22v-8.3a4 4 0 0 0-1.172-2.872L3 3",key:"1qrqzj"}],["path",{d:"m15 9 6-6",key:"ko1vev"}]]),Na=e=>(0,ey.cn)("flex h-5 w-5 shrink-0 items-center justify-center rounded-full","codex"===e?"bg-emerald-500/10 text-emerald-600":"bg-violet-500/10 text-violet-600");function No({agentType:e,currentAgentName:r,alternateProviders:s,onBranch:n,disabled:i,emphasis:a="normal"}){return(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:(0,ey.cn)("h-7 w-7 rounded-md transition-colors hover:bg-muted hover:text-foreground","subtle"===a?"text-muted-foreground/50 group-hover:text-muted-foreground group-focus-within:text-muted-foreground":"text-muted-foreground"),disabled:i,"aria-label":"Branch conversation",children:i?(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"}):(0,O.jsx)(Ni,{className:"h-4 w-4"})})}),(0,O.jsxs)(a7,{align:"start",className:"w-44 p-1.5",children:[(0,O.jsx)(or,{className:"px-2 py-1.5",children:(0,O.jsx)("div",{className:"text-xs font-medium",children:"Branch conversation"})}),(0,O.jsxs)(a8,{className:"h-8 cursor-pointer items-center gap-2 rounded-md px-2 text-xs",onSelect:()=>n(),children:[(0,O.jsx)("div",{className:Na(e),children:(0,O.jsx)(sb,{className:"h-3 w-3"})}),(0,O.jsx)("span",{className:"min-w-0 flex-1 truncate",children:r}),(0,O.jsx)("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:"current"})]}),s.length>0&&(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(os,{className:"my-1"}),s.map(e=>(0,O.jsxs)(a8,{className:"h-8 cursor-pointer items-center gap-2 rounded-md px-2 text-xs",onSelect:()=>n(e.type),children:[(0,O.jsx)("div",{className:Na(e.type),children:(0,O.jsx)(sb,{className:"h-3 w-3"})}),(0,O.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.displayName})]},e.type))]})]})]})}function Nl({durationMs:e,outcome:r,emphasis:s,agentType:n,currentAgentName:i,alternateProviders:a,onBranch:o,disabled:l,showFinalize:c,finalizeBusy:d,onFinalize:u}){let h=void 0!==e?function(e){let r=Math.round(e/1e3);if(r<60)return`${r}s`;let s=Math.floor(r/60),n=r%60;if(s<60)return n?`${s}m ${n}s`:`${s}m`;let i=Math.floor(s/60),a=s%60;return a?`${i}h ${a}m`:`${i}h`}(e):"server_restart"===r?"interrupted":null;return(0,O.jsxs)("div",{className:"group flex items-center gap-2 py-0.5","data-turn-end":!0,children:[(0,O.jsx)("div",{className:"h-px flex-1 bg-border/60"}),null!==h&&(0,O.jsx)("span",{className:(0,ey.cn)("shrink-0 text-[11px] tabular-nums transition-colors","subtle"===s?"text-muted-foreground/50 group-hover:text-muted-foreground group-focus-within:text-muted-foreground":"text-muted-foreground"),children:h}),c&&(0,O.jsx)(cb,{children:(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:(0,ey.cn)("h-7 w-7 shrink-0 rounded-md transition-colors hover:bg-muted hover:text-foreground","subtle"===s?"text-muted-foreground/50 group-hover:text-muted-foreground group-focus-within:text-muted-foreground":"text-muted-foreground"),"aria-label":"生成 review 终稿",onClick:u,disabled:l||d,children:d?(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"}):(0,O.jsx)(Cf,{className:"h-4 w-4"})})}),(0,O.jsx)(cj,{children:"生成 review 终稿"})]})}),(0,O.jsx)(No,{agentType:n,currentAgentName:i,alternateProviders:a,onBranch:o,disabled:l,emphasis:s}),(0,O.jsx)("div",{className:"h-px flex-1 bg-border/60"})]})}var Nc="Popover",[Nd,Nu]=q(Nc,[iw]),Nh=iw(),[Nf,Np]=Nd(Nc),Nm=e=>{let{__scopePopover:r,children:s,open:n,defaultOpen:i,onOpenChange:a,modal:o=!1}=e,l=Nh(r),c=$.useRef(null),[d,u]=$.useState(!1),[h,f]=G({prop:n,defaultProp:i??!1,onChange:a,caller:Nc});return(0,O.jsx)(iC,{...l,children:(0,O.jsx)(Nf,{scope:r,contentId:ek(),triggerRef:c,open:h,onOpenChange:f,onOpenToggle:$.useCallback(()=>f(e=>!e),[f]),hasCustomAnchor:d,onCustomAnchorAdd:$.useCallback(()=>u(!0),[]),onCustomAnchorRemove:$.useCallback(()=>u(!1),[]),modal:o,children:s})})};Nm.displayName=Nc;var Ng="PopoverAnchor",Nx=$.forwardRef((e,r)=>{let{__scopePopover:s,...n}=e,i=Np(Ng,s),a=Nh(s),{onCustomAnchorAdd:o,onCustomAnchorRemove:l}=i;return $.useEffect(()=>(o(),()=>l()),[o,l]),(0,O.jsx)(iN,{...a,...n,ref:r})});Nx.displayName=Ng;var Nv="PopoverTrigger",N_=$.forwardRef((e,r)=>{let{__scopePopover:s,...n}=e,i=Np(Nv,s),a=Nh(s),o=(0,U.useComposedRefs)(r,i.triggerRef),l=(0,O.jsx)(er.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":NM(i.open),...n,ref:o,onClick:K(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?l:(0,O.jsx)(iN,{asChild:!0,...a,children:l})});N_.displayName=Nv;var Ny="PopoverPortal",[Nb,Nw]=Nd(Ny,{forceMount:void 0}),NS=e=>{let{__scopePopover:r,forceMount:s,children:n,container:i}=e,a=Np(Ny,r);return(0,O.jsx)(Nb,{scope:r,forceMount:s,children:(0,O.jsx)(Z,{present:s||a.open,children:(0,O.jsx)(eW,{asChild:!0,container:i,children:n})})})};NS.displayName=Ny;var Nj="PopoverContent",NC=$.forwardRef((e,r)=>{let s=Nw(Nj,e.__scopePopover),{forceMount:n=s.forceMount,...i}=e,a=Np(Nj,e.__scopePopover);return(0,O.jsx)(Z,{present:n||a.open,children:a.modal?(0,O.jsx)(NN,{...i,ref:r}):(0,O.jsx)(NE,{...i,ref:r})})});NC.displayName=Nj;var Nk=(0,et.createSlot)("PopoverContent.RemoveScroll"),NN=$.forwardRef((e,r)=>{let s=Np(Nj,e.__scopePopover),n=$.useRef(null),i=(0,U.useComposedRefs)(r,n),a=$.useRef(!1);return $.useEffect(()=>{let e=n.current;if(e)return tN(e)},[]),(0,O.jsx)(ty,{as:Nk,allowPinchZoom:!0,children:(0,O.jsx)(ND,{...e,ref:i,trapFocus:s.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:K(e.onCloseAutoFocus,e=>{e.preventDefault(),a.current||s.triggerRef.current?.focus()}),onPointerDownOutside:K(e.onPointerDownOutside,e=>{let r=e.detail.originalEvent,s=0===r.button&&!0===r.ctrlKey;a.current=2===r.button||s},{checkForDefaultPrevented:!1}),onFocusOutside:K(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1})})})}),NE=$.forwardRef((e,r)=>{let s=Np(Nj,e.__scopePopover),n=$.useRef(!1),i=$.useRef(!1);return(0,O.jsx)(ND,{...e,ref:r,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:r=>{e.onCloseAutoFocus?.(r),r.defaultPrevented||(n.current||s.triggerRef.current?.focus(),r.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:r=>{e.onInteractOutside?.(r),r.defaultPrevented||(n.current=!0,"pointerdown"===r.detail.originalEvent.type&&(i.current=!0));let a=r.target;s.triggerRef.current?.contains(a)&&r.preventDefault(),"focusin"===r.detail.originalEvent.type&&i.current&&r.preventDefault()}})}),ND=$.forwardRef((e,r)=>{let{__scopePopover:s,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:o,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:u,...h}=e,f=Np(Nj,s),p=Nh(s);return eU(),(0,O.jsx)(eI,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:a,children:(0,O.jsx)(eR,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:u,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>f.onOpenChange(!1),children:(0,O.jsx)(iA,{"data-state":NM(f.open),role:"dialog",id:f.contentId,...p,...h,ref:r,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)"}})})})}),NR="PopoverClose",NA=$.forwardRef((e,r)=>{let{__scopePopover:s,...n}=e,i=Np(NR,s);return(0,O.jsx)(er.button,{type:"button",...n,ref:r,onClick:K(e.onClick,()=>i.onOpenChange(!1))})});NA.displayName=NR;var NT=$.forwardRef((e,r)=>{let{__scopePopover:s,...n}=e,i=Nh(s);return(0,O.jsx)(iF,{...i,...n,ref:r})});function NM(e){return e?"open":"closed"}NT.displayName="PopoverArrow",e.s(["Anchor",()=>Nx,"Arrow",()=>NT,"Close",()=>NA,"Content",()=>NC,"Popover",()=>Nm,"PopoverAnchor",()=>Nx,"PopoverArrow",()=>NT,"PopoverClose",()=>NA,"PopoverContent",()=>NC,"PopoverPortal",()=>NS,"PopoverTrigger",()=>N_,"Portal",()=>NS,"Root",()=>Nm,"Trigger",()=>N_,"createPopoverScope",()=>Nu],154484);var NF=e.i(154484),NF=NF;function NP({...e}){return(0,O.jsx)(NF.Root,{"data-slot":"popover",...e})}function NI({...e}){return(0,O.jsx)(NF.Trigger,{"data-slot":"popover-trigger",...e})}function NB({className:e,align:r="start",sideOffset:s=4,...n}){return(0,O.jsx)(NF.Portal,{children:(0,O.jsx)(NF.Content,{"data-slot":"popover-content",align:r,sideOffset:s,className:(0,ey.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-0 shadow-md outline-hidden",e),...n})})}function NL({candidates:e,className:r,children:s}){let n=Array.from(new Set(e));return(0,O.jsxs)("span",{className:(0,ey.cn)("grid overflow-hidden text-left",r),children:[n.map(e=>(0,O.jsx)("span",{"aria-hidden":!0,className:"col-start-1 row-start-1 invisible whitespace-nowrap",children:e},e)),(0,O.jsx)("span",{className:"col-start-1 row-start-1 min-w-0 truncate",children:s})]})}let Nz="Default",NO="Runs whatever model the CLI is currently set to, which may not be its built-in default.",N$="inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-0.5 text-xs font-medium";function NW({models:e,widthCandidates:r,value:s,onChange:n,locked:i}){let a,[o,l]=(0,$.useState)(!1),[c,d]=(0,$.useState)(""),[u,h]=(0,$.useState)(!1),f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=(0,$.useRef)(0);(0,$.useLayoutEffect)(()=>{let e=f.current,r=p.current;if(e&&r){var s;u||(m.current=e.clientWidth),h((s={textWidth:r.offsetWidth,narrowFieldWidth:m.current,wide:u}).narrowFieldWidth<=0?s.wide:s.textWidth>s.narrowFieldWidth)}},[o,c,u]);let g=s??Nz,x=[Nz,...r??e];if(i)return(0,O.jsxs)("span",{className:(0,ey.cn)(N$,"text-muted-foreground cursor-default"),title:`${g} — fixed while the agent is running, changeable once the turn ends`,children:[(0,O.jsx)(NL,{candidates:x,className:"max-w-40",children:g}),(0,O.jsx)(ns,{className:"h-3 w-3"})]});let v=c.trim(),_=(a=c.trim()).length>0&&!e.includes(a),y=e=>{n(e),d(""),l(!1)};return(0,O.jsxs)(NP,{open:o,onOpenChange:l,children:[(0,O.jsx)(NI,{asChild:!0,children:(0,O.jsxs)("button",{className:(0,ey.cn)(N$,"transition-colors hover:bg-muted"),title:g,children:[(0,O.jsx)(NL,{candidates:x,className:"max-w-40",children:g}),(0,O.jsx)(ns,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,O.jsxs)(NB,{className:u?"w-56":"w-[var(--radix-popover-trigger-width)]",children:[(0,O.jsx)("span",{ref:p,"aria-hidden":!0,className:"pointer-events-none invisible absolute whitespace-pre text-sm",children:c}),(0,O.jsxs)(w5,{shouldFilter:!0,children:[(0,O.jsx)(w4,{ref:f,className:"min-w-0",value:c,onValueChange:d}),(0,O.jsxs)(w6,{children:[(0,O.jsx)(w7,{children:"No match."}),(0,O.jsxs)(w8,{children:[(0,O.jsxs)(w9,{value:Nz,onSelect:()=>y(null),className:"text-xs",children:[Nz,(0,O.jsx)(cb,{delayDuration:200,children:(0,O.jsxs)(cw,{children:[(0,O.jsx)(cS,{asChild:!0,children:(0,O.jsx)("span",{onClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),className:"ml-auto flex cursor-help items-center text-muted-foreground",children:(0,O.jsx)(_J,{"aria-hidden":!0,className:"size-3"})})}),(0,O.jsx)(cj,{side:"right",className:"max-w-56",children:NO})]})}),(0,O.jsx)("span",{className:"sr-only",children:NO})]}),e.map(e=>(0,O.jsx)(w9,{value:e,onSelect:()=>y(e),className:"text-xs",children:e},e))]}),_&&(0,O.jsx)(w8,{heading:"Custom",children:(0,O.jsx)(w9,{value:v,onSelect:()=>y(v),className:"text-xs [&>span]:truncate",title:v,children:(0,O.jsxs)("span",{children:['Use "',v,'"']})})})]})]})]})]})}let NH=(0,ew.default)("clipboard-list",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);function NU({mode:e,onModeChange:r,disabled:s}){return(0,O.jsxs)("div",{className:"inline-flex items-center rounded-md border bg-muted/50 px-0.5 text-xs",children:[(0,O.jsxs)("button",{onClick:()=>r("plan"),disabled:s,className:(0,ey.cn)("inline-flex items-center gap-1 rounded-sm px-2 py-0.5 transition-colors","plan"===e?"bg-primary text-primary-foreground font-medium shadow-sm":"text-muted-foreground hover:text-foreground",s&&"opacity-50 cursor-not-allowed"),children:[(0,O.jsx)(NH,{className:"h-3 w-3"}),"Plan"]}),(0,O.jsxs)("button",{onClick:()=>r("edit"),disabled:s,className:(0,ey.cn)("inline-flex items-center gap-1 rounded-sm px-2 py-0.5 transition-colors","edit"===e?"bg-primary text-primary-foreground font-medium shadow-sm":"text-muted-foreground hover:text-foreground",s&&"opacity-50 cursor-not-allowed"),children:[(0,O.jsx)(rg,{className:"h-3 w-3"}),"Edit"]})]})}function Nq({type:e,className:r}){return(0,O.jsx)(sb,{className:(0,ey.cn)("h-3 w-3 shrink-0","codex"===e?"text-green-500":"text-violet-500",r)})}function NK(e){if(!e)return[];try{let r=window.localStorage.getItem(e);if(!r)return[];let s=JSON.parse(r);if(!Array.isArray(s))return[];return s.filter(e=>"string"==typeof e)}catch{return[]}}let NV=new Set(["waiting_reviewer","waiting_feedback","discussing","sending_feedback"]);function NY(e){if(!e)return"";try{return window.localStorage.getItem(e)??""}catch{return""}}function NG(e){let r=e.parentElement;for(;r;){let{overflowY:e}=getComputedStyle(r);if("auto"===e||"scroll"===e)return r;r=r.parentElement}return null}function NX({messages:e,contentRef:r}){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(null),c=(0,$.useRef)(null),d=(0,$.useCallback)(()=>{let s=r.current;if(!s)return;c.current||(c.current=NG(s));let i=c.current;if(!i)return;let o=i.scrollHeight>i.clientHeight;if(a(o),!o)return void n([]);let l=s.querySelectorAll("[data-user-msg-idx]"),d=i.getBoundingClientRect(),u=[];l.forEach(r=>{let s=parseInt(r.dataset.userMsgIdx,10),n=e[s];if(!n)return;let a=(r.getBoundingClientRect().top-d.top+i.scrollTop)/i.scrollHeight;u.push({index:s,position:Math.max(0,Math.min(1,a)),preview:function(e){if("user"!==e.type)return"";let r=e.content,s="string"==typeof r?r:r.filter(e=>"text"===e.type).map(e=>e.text).join(" "),n="string"!=typeof r&&r.some(e=>"image"===e.type),i=s.split("\n")[0]??"";return(i.length>80?i.slice(0,77)+"...":i)||(n?"(Image)":"")}(n)})}),n(u)},[e,r]);(0,$.useEffect)(()=>{let e=r.current;if(!e){c.current=null,n([]),a(!1);return}let s=NG(e);if(!s)return;c.current=s,d();let i=new ResizeObserver(d);return i.observe(s),i.observe(e),()=>{i.disconnect()}},[e,d,r]);let u=(0,$.useCallback)(e=>{let s=r.current;if(!s)return;let n=s.querySelector(`[data-user-msg-idx="${e}"]`);n&&n.scrollIntoView({block:"start",behavior:"smooth"})},[r]);return i&&0!==s.length?(0,O.jsx)("div",{className:"absolute right-0 top-0 bottom-0 w-6 z-20 pointer-events-none",children:s.map(e=>(0,O.jsxs)("div",{className:"absolute right-0.5 -translate-y-1/2 pointer-events-auto",style:{top:`${100*e.position}%`},children:[(0,O.jsx)("div",{className:"w-3 h-[3px] rounded-sm bg-primary/50 hover:bg-primary cursor-pointer transition-colors",onClick:()=>u(e.index),onMouseEnter:()=>l(e.index),onMouseLeave:()=>l(null)}),o===e.index&&e.preview&&(0,O.jsxs)("div",{className:"absolute right-full mr-2 top-1/2 -translate-y-1/2 max-w-64 px-2.5 py-1.5 bg-popover border border-border rounded-md shadow-md text-xs text-popover-foreground whitespace-nowrap overflow-hidden text-ellipsis pointer-events-none",children:[e.preview,(0,O.jsx)("div",{className:"absolute top-1/2 -translate-y-1/2 -right-1 w-2 h-2 bg-popover border-r border-t border-border rotate-45"})]})]},e.index))}):null}let NJ=(0,ew.default)("star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);function NZ({projectId:e,branch:r,currentSessionId:s,refreshKey:n,pendingTitleSessionId:i,aiTitleOverride:a,onSwitch:o,onDelete:l}){let[c,d]=(0,$.useState)([]),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(""),[m,g]=(0,$.useState)(!1),[x,v]=(0,$.useState)(null),[_,y]=(0,$.useState)(null),[b,w]=(0,$.useState)(0),S=(0,$.useCallback)(()=>w(e=>e+1),[]);(0,$.useEffect)(()=>{let s=!1;return(0,rv.listBranchSessions)(e,r).then(e=>{s||d(e.sessions)}).catch(e=>{s||console.error("[SessionHistoryDropdown] refresh failed:",e)}),()=>{s=!0}},[e,r,n,b]);let j=(0,$.useRef)(null);(0,$.useEffect)(()=>{if(!s)return;if(c.some(e=>e.id===s)){j.current=null;return}if(j.current===s)return;j.current=s;let n=!1;return(0,rv.listBranchSessions)(e,r).then(e=>{if(n)return;d(e.sessions);let r=e.sessions.find(e=>e.id===s),i=!!r&&(a?.sessionId===r.id||!!(r.title&&r.title.trim().length>0));r&&!i&&y(s)}).catch(e=>{n||console.error("[SessionHistoryDropdown] missing-session refresh failed:",e)}),()=>{n=!0}},[s,c,e,r,a]),(0,$.useEffect)(()=>{if(!_)return;let e=setTimeout(()=>{y(e=>e===_?null:e)},3e4);return()=>clearTimeout(e)},[_]),(0,$.useEffect)(()=>{if(!_)return;let e=setTimeout(()=>{y(e=>e===_?null:e)},3e4);return()=>clearTimeout(e)},[_]);let C=async(e,r)=>{let s=r.trim().length>0?r.trim():null;try{await (0,rv.renameSession)(e,s),d(r=>r.map(r=>r.id===e?{...r,title:s}:r)),h(null),_Z.toast.success("Renamed")}catch(e){_Z.toast.error("Rename failed"),console.error(e)}},k=async(e,r)=>{let s=null==r,n=s?Date.now():null;d(r=>r.map(r=>r.id===e?{...r,favorited_at:n}:r));try{await (0,rv.setSessionFavorited)(e,s)}catch(n){d(s=>s.map(s=>s.id===e?{...s,favorited_at:r}:s)),_Z.toast.error(s?"Favorite failed":"Unfavorite failed"),console.error(n)}},N=async e=>{try{await (0,rv.deleteSession)(e);let r=c.filter(r=>r.id!==e);d(r),l?.(e,r),_Z.toast.success("Deleted")}catch(e){_Z.toast.error("Delete failed"),console.error(e)}},E=e=>a&&a.sessionId===e.id?a.title:e.title&&e.title.trim().length>0?e.title:e.updated_at?new Date(e.updated_at).toLocaleString():new Date(e.created_at).toLocaleString(),D=e=>{let r;return a?.sessionId!==e.id&&(!e.title||!(e.title.trim().length>0))&&(r=e.id,null!==i&&i===r||_===e.id)},R=c.find(e=>e.id===s),A=null!==s&&(!R||D(R)),T=R?E(R):null===s?"New Session":"History",M=A?"Generating title…":T;return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)(a4,{open:m,onOpenChange:e=>{g(e),e&&S()},children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsxs)(W.Button,{variant:"ghost",size:"sm",className:"h-7 text-xs gap-1 w-[200px] justify-start",title:M,children:[A?(0,O.jsx)("span",{className:"block h-3 flex-1 rounded-sm bg-accent animate-pulse",role:"status","aria-label":"Generating title"}):(0,O.jsx)("span",{className:"truncate flex-1 text-left",children:T}),(0,O.jsx)(ns,{className:"h-3 w-3 flex-shrink-0"})]})}),(0,O.jsxs)(a7,{align:"start",className:"w-80 max-h-96 overflow-y-auto",children:[0===c.length&&(0,O.jsx)("div",{className:"px-2 py-3 text-xs text-muted-foreground",children:"No history yet."}),c.map(e=>{let r=e.id===s,n=u===e.id;return(0,O.jsxs)(a8,{onSelect:s=>{n?s.preventDefault():r||o(e.id)},onPointerMove:null!==u?e=>e.preventDefault():void 0,className:`flex items-center gap-2 group ${r?"bg-accent text-accent-foreground":""}`,children:[(0,O.jsx)("div",{className:"flex-1 min-w-0",children:n?(0,O.jsxs)("div",{className:"flex items-center gap-1",children:[(0,O.jsx)(ro,{value:f,onChange:e=>p(e.target.value),onKeyDown:r=>{r.stopPropagation(),"Enter"===r.key&&C(e.id,f),"Escape"===r.key&&h(null)},autoFocus:!0,className:"h-6 text-xs"}),(0,O.jsx)("button",{type:"button","aria-label":"Save rename",onClick:r=>{r.stopPropagation(),C(e.id,f)},children:(0,O.jsx)(rf.Check,{className:"h-3 w-3"})}),(0,O.jsx)("button",{type:"button","aria-label":"Cancel rename",onClick:e=>{e.stopPropagation(),h(null)},children:(0,O.jsx)(t7,{className:"h-3 w-3"})})]}):D(e)?(0,O.jsx)("div",{className:"py-0.5",title:"Generating title…",children:(0,O.jsx)("span",{className:"block h-3 w-40 rounded-sm bg-accent animate-pulse",role:"status","aria-label":"Generating title"})}):(0,O.jsx)("div",{className:"truncate text-xs",title:`${e.updated_at?new Date(e.updated_at).toLocaleString():new Date(e.created_at).toLocaleString()} • ${e.entry_count??0} messages • status: ${e.status} • model: ${e.model??"Default"}`,children:E(e)})}),!n&&(0,O.jsxs)("div",{className:"flex items-center gap-1",children:[(0,O.jsxs)("div",{className:"opacity-0 group-hover:opacity-100 flex items-center gap-1",children:[(0,O.jsx)("button",{type:"button","aria-label":"Rename conversation",onClick:r=>{r.stopPropagation(),h(e.id),p(e.title??"")},className:"p-1 hover:bg-muted rounded",children:(0,O.jsx)(rg,{className:"h-3 w-3"})}),(0,O.jsx)("button",{type:"button","aria-label":"Delete conversation",onClick:r=>{r.stopPropagation(),g(!1),v(e)},className:"p-1 hover:bg-muted rounded text-destructive",children:(0,O.jsx)(rc,{className:"h-3 w-3"})})]}),(0,O.jsx)("button",{type:"button","aria-label":null!=e.favorited_at?"Unfavorite conversation":"Favorite conversation",title:null!=e.favorited_at?"Unfavorite":"Favorite",onClick:r=>{r.stopPropagation(),k(e.id,e.favorited_at??null)},className:`p-1 hover:bg-muted rounded ${null!=e.favorited_at?"opacity-100 text-yellow-500":"opacity-0 group-hover:opacity-100 text-muted-foreground"}`,children:(0,O.jsx)(NJ,{className:`h-3 w-3 ${null!=e.favorited_at?"fill-current":""}`})})]})]},e.id)}),c.length>0&&(0,O.jsx)(os,{}),(0,O.jsx)(a8,{onSelect:()=>S(),className:"text-xs text-muted-foreground",children:"Refresh"})]})]}),(0,O.jsx)(lL,{open:null!==x,onOpenChange:e=>{e||v(null)},children:(0,O.jsxs)(l$,{children:[(0,O.jsxs)(lW,{children:[(0,O.jsx)(lU,{children:"Delete conversation?"}),(0,O.jsx)(lq,{children:x?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("span",{className:"font-medium text-foreground",children:E(x)})," ","and its message history will be permanently deleted. This cannot be undone."]}):null})]}),(0,O.jsxs)(lH,{children:[(0,O.jsx)(lV,{children:"Cancel"}),(0,O.jsx)(lK,{className:(0,ey.cn)((0,W.buttonVariants)({variant:"destructive"}),"border-transparent"),onClick:()=>{x&&N(x.id),v(null)},children:"Delete"})]})]})})]})}let NQ=(0,ew.default)("quote",[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"rib7q0"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"1ymkrd"}]]);function N0(e,r){let s=e;for(;s&&s!==r;){if(s.nodeType===Node.ELEMENT_NODE){let e=s.getAttribute("data-message-idx");if(null!==e)return e}s=s.parentNode}return null}function N1({containerRef:e,onQuote:r}){let[s,n]=(0,$.useState)(null);if((0,$.useEffect)(()=>{function r(){let r=e.current;if(!r)return void n(null);let s=window.getSelection();if(!s||s.isCollapsed||0===s.rangeCount)return void n(null);let i=s.toString();if(!i.trim())return void n(null);let{anchorNode:a,focusNode:o}=s;if(!a||!o||!r.contains(a)||!r.contains(o))return void n(null);let l=N0(a,r),c=N0(o,r);if(null===l||null===c||l!==c)return void n(null);let d=s.getRangeAt(0).getBoundingClientRect();0===d.width&&0===d.height?n(null):n({text:i,rect:{top:d.top,bottom:d.bottom,left:d.left,width:d.width}})}function s(){let e=window.getSelection();e&&!e.isCollapsed&&e.toString().trim()||n(null)}return document.addEventListener("mouseup",r),document.addEventListener("keyup",r),document.addEventListener("touchend",r),document.addEventListener("selectionchange",s),window.addEventListener("scroll",r,!0),window.addEventListener("resize",r),()=>{document.removeEventListener("mouseup",r),document.removeEventListener("keyup",r),document.removeEventListener("touchend",r),document.removeEventListener("selectionchange",s),window.removeEventListener("scroll",r,!0),window.removeEventListener("resize",r)}},[e]),!s||"undefined"==typeof document)return null;let i=s.rect.top-8-30<8?s.rect.bottom+8:s.rect.top-8-30,a=s.rect.left+s.rect.width/2,o=Math.max(8,Math.min(window.innerWidth-8,a));return(0,ee.createPortal)((0,O.jsxs)("button",{type:"button",onMouseDown:e=>{e.preventDefault(),r(s.text),window.getSelection()?.removeAllRanges(),n(null)},style:{position:"fixed",top:i,left:o,transform:"translateX(-50%)",zIndex:50},className:"inline-flex items-center gap-1.5 rounded-md border border-border bg-popover px-3 py-1.5 text-xs font-medium text-popover-foreground shadow-2xl hover:bg-accent",children:[(0,O.jsx)(NQ,{className:"h-3 w-3"}),"Quote"]}),document.body)}let N2=(0,ew.default)("search-check",[["path",{d:"m8 11 2 2 4-4",key:"1sed1v"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]),N5=[{type:"claude-code",displayName:"Claude Code",available:!0},{type:"codex",displayName:"Codex",available:!0}];function N3({projectId:e,branch:r,sessionId:s,currentAgentType:n,providers:i}){let[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(""),[d,u]=(0,$.useState)("claude-code"),[h,f]=(0,$.useState)("this_turn"),[p,m]=(0,$.useState)("new"),[g,x]=(0,$.useState)(null),[v,_]=(0,$.useState)(!1),[y,b]=(0,$.useState)(null),[w,S]=(0,$.useState)(!1),[j,C]=(0,$.useState)(null),k=(0,$.useRef)(null),N=i?.length?i:N5;if((0,$.useEffect)(()=>{if(a){var e;let r;u((e=n??null,r=N.filter(e=>e.available),r.find(r=>r.type!==e)?.type??r[0]?.type??"claude-code")),f("this_turn")}},[a]),(0,$.useEffect)(()=>{if(!a||!s)return;let r=!1;return m("new"),x(null),b(null),_(!0),rv.api.getReviewerCandidate(e,s).then(e=>{!r&&(x(e),e?.available&&e.sessionId?m("reuse"):e&&b("上次 reviewer 已不可用,将创建新 session"))}).catch(()=>{r||b("无法加载上次 reviewer,将创建新 session")}).finally(()=>{r||_(!1)}),()=>{r=!0}},[a,e,s]),(0,$.useEffect)(()=>{if(!a){k.current=null;return}if(!s)return;let r=k.current;r&&r.projectId===e&&r.sessionId===s||(k.current={projectId:e,sessionId:s,result:rv.api.generateReviewIntentBrief(e,s).then(e=>({reached:!0,brief:e})).catch(()=>({reached:!1,brief:null}))})},[a,e,s]),!s)return null;let E=async()=>{S(!0),C(null);try{let n="reuse"===p&&g?.sessionId?{reviewerSessionId:g.sessionId}:{reviewerAgentType:d},i=k.current,a="reviewerAgentType"in n&&i?.projectId===e&&i?.sessionId===s?i:null,u=a?await a.result:null,f=u?.reached?{intentBrief:u.brief??""}:{};await rv.api.createWorkflowRun({projectId:e,branch:r,sourceSessionId:s,reviewFocus:l.trim()||void 0,reviewSpan:h,...n,...f}),o(!1),c("")}catch(r){C(r instanceof Error?r.message:String(r)),rv.api.getReviewerCandidate(e,s).then(e=>{x(e),e?.available&&e.sessionId||(m("new"),b("上次 reviewer 已不可用,将创建新 session"))}).catch(()=>void 0)}finally{S(!1)}};return(0,O.jsxs)(t8,{open:a,onOpenChange:o,children:[(0,O.jsx)(t9,{asChild:!0,children:(0,O.jsx)(W.Button,{variant:"ghost",size:"sm",title:"让另一个 agent review 这个 session 的最新成果",children:(0,O.jsx)(N2,{className:"h-4 w-4"})})}),(0,O.jsxs)(rr,{className:"sm:max-w-md",children:[(0,O.jsxs)(rs,{children:[(0,O.jsx)(ri,{children:"发起 Review"}),(0,O.jsx)(ra,{children:"默认继续上次 reviewer 的上下文,也可以创建新 reviewer session。反馈会先经你确认,再发回本 session。"})]}),(0,O.jsxs)("div",{className:"grid gap-2",children:[g?.available&&g.sessionId&&(0,O.jsxs)(W.Button,{type:"button",variant:"reuse"===p?"secondary":"outline",className:"h-auto justify-start whitespace-normal py-2 text-left","aria-pressed":"reuse"===p,onClick:()=>m("reuse"),children:["继续上次 Reviewer — ",g.title??"Review session"]}),(0,O.jsx)(W.Button,{type:"button",variant:"new"===p?"secondary":"outline",className:"justify-start","aria-pressed":"new"===p,onClick:()=>m("new"),children:"创建新 Reviewer Session"})]}),y&&(0,O.jsx)("p",{className:"text-sm text-amber-600 dark:text-amber-400",children:y}),"new"===p&&(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)("span",{className:"text-sm text-muted-foreground shrink-0",children:"Reviewer agent"}),(0,O.jsxs)(hw,{value:d,onValueChange:e=>u(e),children:[(0,O.jsx)(hj,{className:"h-8 text-sm flex-1",children:(0,O.jsx)(hS,{})}),(0,O.jsx)(hC,{children:N.map(e=>(0,O.jsxs)(hk,{value:e.type,disabled:!e.available,children:[e.displayName,e.type===n?"(当前 agent)":""]},e.type))})]})]}),"new"===p&&(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)("span",{className:"text-sm text-muted-foreground shrink-0",children:"审查范围"}),(0,O.jsxs)(hw,{value:h,onValueChange:e=>f(e),children:[(0,O.jsx)(hj,{className:"h-8 text-sm flex-1",children:(0,O.jsx)(hS,{})}),(0,O.jsxs)(hC,{children:[(0,O.jsx)(hk,{value:"this_turn",children:"仅本次 turn(默认)"}),(0,O.jsx)(hk,{value:"session_start",children:"整个 session(自起点)"})]})]})]}),(0,O.jsx)("input",{className:"w-full rounded-md border bg-transparent px-3 py-2 text-sm",placeholder:"Review focus(可选):本次审查重点…",value:l,onChange:e=>c(e.target.value)}),j&&(0,O.jsx)("p",{className:"text-sm text-destructive",children:j}),(0,O.jsx)(rn,{children:(0,O.jsx)(W.Button,{onClick:E,disabled:w||v,children:w?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}),"正在准备 review 上下文…"]}):"开始 Review"})})]})]})}function N4(){return 0===kY().files.length?null:(0,O.jsx)(k0,{className:"pt-3 pb-0",children:(0,O.jsx)(kX,{className:"p-0",children:e=>(0,O.jsx)(kG,{data:e})})})}let N6=(0,$.createContext)(null);function N7(){let e=(0,$.useContext)(N6);if(!e)throw Error("useAgentConversation must be used within AgentConversationContext");return e}let N8=/\[📎 paste #(\d+) \([^)]+\)\]/g;function N9(e,r){return`[📎 paste #${e} (${function(e){if(e<1024)return`${e}B`;let r=e/1024;return r<10?`${r.toFixed(1)}KB`:`${Math.round(r)}KB`}(r)})]`}let Ee=(0,$.forwardRef)(function({projectId:e,branch:r,sessionId:s,setSessionUrlParam:n,project:i,onAgentModeChange:a,onTaskCompleted:o,onSessionStarted:l,onSessionTitleUpdated:c,onSessionSelected:d,onStatusChange:u,onNewConversation:h,onActiveSessionChange:f},p){var m;let g,x,v,_,[y,b]=function(e,r){let s=e&&r?`vibedeckx:agent-draft:${e}:${r}`:null,[n,i]=(0,$.useState)(()=>NY(s)),[a,o]=(0,$.useState)(s);return a!==s&&(o(s),i(NY(s))),[n,(0,$.useCallback)(e=>{i(e);if(s)try{e?window.localStorage.setItem(s,e):window.localStorage.removeItem(s)}catch{}},[s])]}(e,r),[w,S]=(0,$.useState)([]),[j,C]=(0,$.useState)(1),[k,N]=(0,$.useState)("edit"),[E,D]=(0,$.useState)(!1),[R,A]=(0,$.useState)(!1),[T,M]=(0,$.useState)(!1),[F,P]=(0,$.useState)("claude-code"),[I,B]=(0,$.useState)([]),[L,z]=(0,$.useState)(null),[H,U]=(0,$.useState)(0),[q,K]=(0,$.useState)(null),[V,Y]=(0,$.useState)(null),G=(0,$.useRef)(null),X=(0,$.useCallback)(e=>{if("ArrowUp"!==e.key&&"ArrowDown"!==e.key||!e.shiftKey||e.ctrlKey||e.metaKey||e.altKey)return;let r=G.current;if(!r)return;let s=NG(r);if(!s)return;let n=s.getBoundingClientRect(),i=s.scrollTop,a="ArrowUp"===e.key,o=null,l=a?-1/0:1/0;r.querySelectorAll("[data-user-msg-idx]").forEach(e=>{let r=e.getBoundingClientRect().top-n.top+s.scrollTop;a?r<i-12&&r>l&&(l=r,o=e):r>i+12&&r<l&&(l=r,o=e)}),o&&(e.preventDefault(),o.scrollIntoView({block:"start",behavior:"smooth"}))},[G]),J=(0,$.useRef)(null),Z=function(e,r,s){let n=r&&s?`vibedeckx:agent-input-history:${r}:${s}`:null,i=(0,$.useRef)(NK(n)),a=(0,$.useRef)(-1),o=(0,$.useRef)(""),[l,c]=(0,$.useState)(n);return l!==n&&(c(n),i.current=NK(n),a.current=-1,o.current=""),{push:(0,$.useCallback)(e=>{let r=e.trim();if(!r)return;let s=i.current;if(s.length>0&&s[s.length-1]===r){a.current=-1;return}s.push(r),s.length>50&&s.shift(),a.current=-1;if(n)try{0===s.length?window.localStorage.removeItem(n):window.localStorage.setItem(n,JSON.stringify(s))}catch{}},[n]),handleKeyDown:(0,$.useCallback)(r=>{let s=r.currentTarget,n=i.current;if(0!==n.length)if("ArrowUp"===r.key){if(0!==s.selectionStart||0!==s.selectionEnd)return;if(r.preventDefault(),-1===a.current)o.current=s.value,a.current=n.length-1;else{if(!(a.current>0))return;a.current--}e(n[a.current])}else if("ArrowDown"===r.key){if(-1===a.current)return;let i=s.value.length;if(s.selectionStart!==i||s.selectionEnd!==i)return;r.preventDefault(),a.current<n.length-1?(a.current++,e(n[a.current])):(a.current=-1,e(o.current))}else -1!==a.current&&(a.current=-1)},[e])}}(b,e,r),{remotes:Q}=b1(),ee=[];for(let e of(i?.path&&ee.push({id:"local",label:"Local",icon:oc}),Q))ee.push({id:e.remote_server_id,label:e.server_name,icon:sx(e)});let{session:et,messages:er,status:es,isConnected:en,isInitialized:ei,isLoading:ea,error:eo,remoteStatus:el,workflowRunUpdate:ec,sendMessage:ed,uploadPaste:eu,stopSession:eh,switchAgentType:ef,setModel:ep,startNewConversation:em,ensureSession:eg,switchMode:ex,acceptPlan:ev,residentLimitPrompt:e_}=function(e,r,s,n,i){let a=i?.sessionId??null,[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)([]),[u,h]=(0,$.useState)("stopped"),[f,p]=(0,$.useState)(!1),[m,g]=(0,$.useState)(!1),[x,v]=(0,$.useState)(!1),[_,y]=(0,$.useState)(null),[b,w]=(0,$.useState)(null),[S,j]=(0,$.useState)(null),C=(0,$.useRef)(null),k=(0,$.useRef)(null),N=(0,$.useRef)(()=>{}),E=(0,$.useRef)(null),D=(0,$.useRef)(0),R=(0,$.useRef)({entries:[],status:"stopped"}),A=(0,$.useRef)(!1),T=(0,$.useRef)(!0),M=(0,$.useRef)(null),F=(0,$.useRef)(null),P=(0,$.useRef)(0),I=(0,$.useRef)(!1),B=(0,$.useRef)(null),L=(0,$.useRef)(0),z=(0,$.useRef)(!1),O=(0,$.useRef)(!1),W=(0,$.useRef)(Promise.resolve()),H=(0,$.useRef)(i?.onTaskCompleted),U=(0,$.useRef)(i?.onSessionStarted),q=(0,$.useRef)(i?.onTitleUpdated),K=(0,$.useRef)(e),V=(0,$.useRef)(r),Y=(0,$.useRef)(a);(0,$.useEffect)(()=>{H.current=i?.onTaskCompleted,U.current=i?.onSessionStarted,q.current=i?.onTitleUpdated,K.current=e,V.current=r,Y.current=a});let G=(0,$.useCallback)(()=>{B.current&&(clearTimeout(B.current),B.current=null)},[]),X=(0,$.useCallback)(e=>{B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{if(B.current=null,e.readyState===WebSocket.OPEN){console.warn(`[AgentSession] No frames for 95000ms — assuming dead socket, forcing reconnect`);try{e.close(4e3,"silence watchdog")}catch{}}},95e3)},[]),J=(0,$.useCallback)((e,r=!1)=>{Promise.race([(0,rv.getFreshToken)(r?{skipCache:!0}:void 0),new Promise(e=>setTimeout(e,5e3))]).catch(()=>void 0).then(()=>N.current(e))},[]),Z=(0,$.useCallback)(e=>{let r=()=>{let e=K.current;if(!e)return;let r=V.current;Ca.delete(Co(e,r,Y.current));let s=k.current;s&&Ca.delete(Co(e,r,s)),Ca.delete(Co(e,r,null))};if(C.current&&k.current!==e&&(console.log(`[AgentSession] Closing stale WS for ${k.current}, switching to ${e}`),C.current.close(1e3,"session-switch"),C.current=null,k.current=null),C.current?.readyState===WebSocket.OPEN||C.current?.readyState===WebSocket.CONNECTING)return;0===R.current.entries.filter(Boolean).length&&(R.current={entries:[],status:"running"}),A.current=!1,I.current=!0;let s=(0,rv.getWebSocketUrl)(`/api/agent-sessions/${e}/stream`);console.log("[AgentSession] Connecting to WebSocket:",s);let n=new WebSocket(s);C.current=n,k.current=e,n.onopen=()=>{console.log("[AgentSession] WebSocket connected"),p(!0),y(null),w(null),M.current=Date.now(),X(n),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>{console.log("[AgentSession] Connection stable, resetting backoff counter"),D.current=0,P.current=0},5e3)},n.onmessage=e=>{X(n);try{let i=JSON.parse(e.data);if("keepalive"in i)return;if("JsonPatch"in i){var s;let e=i.JsonPatch;s=R.current,R.current=jY(s,r=>{for(let s of e){let{op:e,path:n,value:i}=s;if("/entries"===n&&"replace"===e&&i?.type==="ENTRY"&&i.content?.type==="system"&&i.content?.content==="__CLEAR_ALL__"){console.log("[JsonPatch] Received clearAll signal - clearing all entries"),r.entries=[];continue}if(n.startsWith("/entries/")){let s=parseInt(n.replace("/entries/",""),10);if(isNaN(s)){console.warn(`[JsonPatch] Invalid index in path: ${n}`);continue}if(i?.type!=="ENTRY"){console.warn("[JsonPatch] Expected ENTRY type for entries path");continue}switch(e){case"add":for(;r.entries.length<=s;)r.entries.push(null);r.entries[s]=i.content;break;case"replace":s<r.entries.length?r.entries[s]=i.content:console.warn(`[JsonPatch] Replace index out of bounds: ${s}`);break;case"remove":s<r.entries.length&&r.entries.splice(s,1)}}else"/status"===n&&i?.type==="STATUS"&&(console.log("[AgentSession] /status patch →",i.content),r.status=i.content)}}),I.current?console.log("[AgentSession] /status patch applied during replay (no setStatus), container.status =",R.current.status):(d([...R.current.entries.filter(Boolean)]),console.log("[AgentSession] setStatus(live) →",R.current.status),h(R.current.status),("stopped"===R.current.status||"error"===R.current.status)&&r());return}if("Ready"in i){console.log("[AgentSession] Received Ready signal - history complete, status=",R.current.status),I.current=!1,d([...R.current.entries.filter(Boolean)]),h(R.current.status),g(!0);return}if("finished"in i){console.log("[AgentSession] Received finished signal, invalidating cache"),A.current=!0,r(),n.close(1e3,"finished");return}if("taskCompleted"in i){let{duration_ms:e,cost_usd:r,input_tokens:s,output_tokens:n}=i.taskCompleted,a=[];if(null!=e){let r=(e/1e3).toFixed(1);a.push(`${r}s`)}if(null!=r)a.push(`$${r.toFixed(4)}`);else if(null!=s||null!=n){let e=(s??0)+(n??0),r=e>1e3?`${(e/1e3).toFixed(1)}K`:String(e);a.push(`${r} tokens`)}_Z.toast.success("Task completed",{description:a.length>0?a.join(" · "):void 0}),H.current?.();return}if("remoteStatus"in i)return void w(i.remoteStatus);if("titleUpdated"in i)return void q.current?.(i.titleUpdated.title,k.current);if("workflowRunUpdated"in i&&j(i.workflowRunUpdated),"error"in i){console.error("[AgentSession] Server error:",i.error),y(i.error),"Session not found"===i.error&&(console.log("[AgentSession] Session invalid, invalidating cache, will create new session"),r(),A.current=!0,l(null),h("stopped"),g(!1),T.current=!0);return}}catch(e){console.error("[AgentSession] Failed to parse message:",e)}},n.onclose=e=>{let s,n;console.log("[AgentSession] WebSocket disconnected",e.code,e.reason),p(!1),G(),F.current&&(clearTimeout(F.current),F.current=null);let i=M.current?Date.now()-M.current:0;if(M.current=null,i>0&&i<5e3){if(P.current++,console.log(`[AgentSession] Short-lived connection (${i}ms), count: ${P.current}, backoff attempt: ${D.current}`),P.current>=3){if(console.log("[AgentSession] Multiple short-lived connections detected, session likely invalid - will recreate"),z.current){console.log("[AgentSession] Skipping auto-restart: last session creation failed"),y("Unable to connect to remote server. Please check the server configuration.");return}r(),l(null),y(null),D.current=0,P.current=0,T.current=!0;return}}else i>=5e3&&(P.current=0);if(A.current||1e3===e.code)return;if(D.current>=10){console.log("[AgentSession] Max reconnect attempts reached"),y("Unable to connect to server. Please check if the backend is running.");return}let a=(n=(s=Math.min(3e4,1e3*Math.pow(2,D.current)))*Math.random()*.25,s+n);console.log(`[AgentSession] Reconnecting in ${Math.round(a)}ms (attempt ${D.current+1})`),D.current++,E.current=setTimeout(()=>{let e=k.current;e&&!A.current&&J(e,!0)},a)},n.onerror=e=>{console.error("[AgentSession] WebSocket error:",e)}},[J,X,G]);(0,$.useEffect)(()=>{N.current=Z},[Z]);let Q=(0,$.useCallback)(async s=>{if(!e)return null;if(O.current)return console.log("[AgentSession] startSession already in progress, skipping"),null;O.current=!0;let i=L.current;y(null),w(null),g(!1),z.current=!1;let o=Co(e,r,a),c=Ca.get(o);if(c)return console.log(`[AgentSession] Cache hit for ${o}, reconnecting WebSocket directly`),l(c),h(c.status),J(c.id),U.current?.(c),O.current=!1,c;v(!0);try{console.log(`[AgentSession] Starting REST call: projectId=${e}, branch=${r}, sessionId=${a??"latest"}, agentType=${n}, generation=${i}`);let{session:c,messages:u}=a?await Cl(a):await j7(e,r,s,n);if(L.current!==i)return console.log("[AgentSession] Discarding stale session response (generation mismatch)"),null;if(!c)return console.log(`[AgentSession] No existing session for ${e}/${r??"<null>"} — placeholder`),l(null),h("stopped"),d([]),R.current={entries:[],status:"stopped"},g(!0),null;return console.log(`[AgentSession] REST response: sessionId=${c.id}, msgCount=${u?.length??0}, status=${c.status}, explicitSessionIdRequested=${a??"<null>"}`),Ca.set(o,c),a&&Ca.set(Co(e,r,c.id),c),l(c),h(c.status),u&&u.length>0&&(d(u),R.current={entries:[...u],status:c.status}),J(c.id),U.current?.(c),c}catch(e){if(console.error("[AgentSession] startSession error:",e),L.current!==i)return console.log("[AgentSession] Discarding error (generation mismatch)"),null;return y(e instanceof Error?e.message:"Failed to start session"),z.current=!0,null}finally{O.current=!1,L.current===i&&v(!1)}},[e,r,n,a,J]),ee=(0,$.useCallback)(async(s,n)=>{let i=n||o?.id;if(!i)return void console.warn("[AgentSession] sendMessage: no session ID available (sessionId param:",n,", session?.id:",o?.id,")");if(("string"!=typeof s||s.trim())&&(!Array.isArray(s)||0!==s.length)){console.log(`[AgentSession] sendMessage: targetSessionId=${i}, source=${n?"explicit":"state"}`);try{let e="string"==typeof s?s.trim():s;await j8(i,e)}catch(n){let s=n instanceof Error?n.message:"Failed to send message";console.error("[AgentSession] Failed to send message:",s),s.includes("[404]")&&(e&&(Ca.delete(Co(e,r,a)),o?.id&&Ca.delete(Co(e,r,o.id))),l(null),h("stopped"),g(!1),T.current=!0),y(s),_Z.toast.error("Failed to send message",{description:s})}}},[o?.id,e,r,a]),et=(0,$.useCallback)(async(e,r)=>{let s=r||o?.id;if(!s)throw Error("No session id available for paste upload");return j9(s,e)},[o?.id]),er=(0,$.useCallback)(async()=>{if(o?.id)try{await Cs(o.id)}catch(e){e instanceof Error&&e.message,console.error("[AgentSession] Failed to stop session:",e),_Z.toast.error("Failed to stop session")}},[o?.id]),es=(0,$.useCallback)(async s=>{if(o?.id){e&&(Ca.delete(Co(e,r,a)),Ca.delete(Co(e,r,o.id))),v(!0),y(null);try{await Ce(o.id,s),s&&l(e=>e?{...e,agentType:s}:null)}catch(e){y(e instanceof Error?e.message:"Failed to restart session"),console.error("[AgentSession] Failed to restart session:",e)}finally{v(!1)}}},[o?.id,e,r,a]),en=(0,$.useCallback)(async s=>{if(!o?.id)return"No active session";y(null);try{return await Ct(o.id,s),l(n=>{if(!n)return n;let i={...n,agentType:s,model:null};return e&&(Ca.set(Co(e,r,a),i),Ca.set(Co(e,r,i.id),i)),i}),null}catch(r){let e=r instanceof Error?r.message:"Failed to switch agent";return console.error("[AgentSession] Failed to switch agent:",r),e}},[o?.id,e,r,a]),ei=(0,$.useCallback)(async s=>{let n=o?.id;if(!n)return"No active session";y(null);let i=W.current.then(()=>Cr(n,s));W.current=i.then(()=>void 0,()=>void 0);try{let s=await i;return l(i=>{if(!i||i.id!==n)return i;let o={...i,model:s};return e&&(Ca.set(Co(e,r,a),o),Ca.set(Co(e,r,o.id),o)),o}),null}catch(r){let e=r instanceof Error?r.message:"Failed to set model";return console.error("[AgentSession] Failed to set model:",r),e}},[o?.id,e,r,a]),ea=(0,$.useCallback)(async s=>{if(o?.id){y(null);try{await Cn(o.id,s),l(n=>{if(!n)return n;let i={...n,permissionMode:s};return e&&(Ca.set(Co(e,r,a),i),Ca.set(Co(e,r,i.id),i)),i})}catch(e){y(e instanceof Error?e.message:"Failed to switch mode"),console.error("[AgentSession] Failed to switch mode:",e)}}},[o?.id,e,r,a]),eo=(0,$.useCallback)(async s=>{if(o?.id){y(null);try{await Ci(o.id,s),l(s=>{if(!s)return s;let n={...s,permissionMode:"edit"};return e&&(Ca.set(Co(e,r,a),n),Ca.set(Co(e,r,n.id),n)),n})}catch(e){y(e instanceof Error?e.message:"Failed to accept plan"),console.error("[AgentSession] Failed to accept plan:",e)}}},[o?.id,e,r,a]),el=(0,$.useCallback)(async()=>{var n;let i;return e?(o?.id&&Ca.delete(Co(e,r,o.id)),Ca.delete(Co(e,r,a)),C.current&&(C.current.close(1e3,"new-conversation"),C.current=null,k.current=null),E.current&&(clearTimeout(E.current),E.current=null),F.current&&(clearTimeout(F.current),F.current=null),A.current=!1,I.current=!1,p(!1),l(null),h("stopped"),g(!0),y(null),w(null),d([]),R.current={entries:[],status:"stopped"},n=j3(e,r,s),(i=new Map(jJ)).set(n,Date.now()),jX(jJ=i),j0(),null):null},[e,r,s,o?.id,a]),[ec,ed]=(0,$.useState)(null),eu=(0,$.useRef)(null),eh=(0,$.useCallback)(()=>{eu.current?.resolve(!1),eu.current=null,ed(null)},[]),ef=(0,$.useRef)(new Map),ep=(0,$.useCallback)((i,c)=>{if(!e)return Promise.resolve(null);if(o)return Promise.resolve(o);let d=L.current,u=`${d}:${c??null}`,f=ef.current.get(u);if(f)return f;let p=(async()=>{v(!0),y(null);try{let o;try{o=await (0,rv.createNewAgentSession)(e,r,i,n,void 0,c)}catch(h){let s;if(!(h instanceof rv.ResidentLimitError))throw h;let a=new Promise(e=>{s=e}),l={maxResidentAgentProcesses:h.maxResidentAgentProcesses,runningSessions:h.runningSessions,resolve:s};eu.current=l,ed(l);let u=await a;if(eu.current===l&&(eu.current=null),ed(e=>e===l?null:e),L.current!==d)return null;if(!u)throw h;o=await (0,rv.createNewAgentSession)(e,r,i,n,!0,c)}if(L.current!==d)return console.log("[AgentSession] Discarding stale ensureSession result (generation mismatch)"),null;let u={id:o.session.id,projectId:o.session.projectId,branch:o.session.branch,status:o.session.status,permissionMode:o.session.permissionMode??"edit",agentType:o.session.agentType??"claude-code",model:o.session.model??null,processAlive:o.session.processAlive??!0};return Ca.set(Co(e,r,a),u),Ca.set(Co(e,r,u.id),u),l(u),h(u.status),g(!0),j4(j3(e,r,s)),J(u.id),U.current?.(u),u}catch(e){if(console.error("[AgentSession] ensureSession:",e),L.current!==d)return null;return y(e instanceof Error?e.message:"Failed to create session"),null}finally{ef.current.get(u)===p&&ef.current.delete(u),L.current===d&&v(!1)}})();return ef.current.set(u,p),p},[e,r,s,n,o,a,J]);return(0,$.useEffect)(()=>()=>{C.current&&(A.current=!0,C.current.close(),k.current=null),E.current&&clearTimeout(E.current),F.current&&clearTimeout(F.current),G(),L.current+=1,eh()},[eh,G]),(0,$.useEffect)(()=>{C.current&&(C.current.close(1e3,"branch-switch"),C.current=null,k.current=null),E.current&&(clearTimeout(E.current),E.current=null),F.current&&(clearTimeout(F.current),F.current=null),G(),L.current+=1,eh();let n=e?j3(e,r,s):null;n&&a&&j4(n);let i=!a&&null!==n&&jJ.has(n);l(null),h("stopped"),p(!1),g(i),y(null),v(!1),w(null),d([]),R.current={entries:[],status:"stopped"},A.current=!1,D.current=0,M.current=null,P.current=0,z.current=!1,O.current=!1,T.current=!i,e&&Ca.delete(Co(e,r,a))},[e,r,s,a,eh,G]),(0,$.useEffect)(()=>{var n;let i=null!==e&&(n=j3(e,r,s),jJ.has(n));!T.current||!e||o||x||z.current||i||(T.current=!1,console.log(`[AgentSession] Auto-start: projectId=${e}, branch=${r}, agentMode=${s}`),Q())},[e,r,s,o,x,Q]),(0,$.useEffect)(()=>{let e=()=>{if("visible"===document.visibilityState&&o?.id&&!A.current){let e=C.current;e&&e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING||(console.log("[AgentSession] Tab visible, WebSocket disconnected - reconnecting"),D.current=0,P.current=0,E.current&&(clearTimeout(E.current),E.current=null),J(o.id))}};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[o?.id,J]),(0,$.useEffect)(()=>{o?.id&&!A.current&&J(o.id)},[o?.id,J]),{session:o,messages:c,status:u,isConnected:f,isInitialized:m,isLoading:x,error:_,remoteStatus:b,workflowRunUpdate:S,startSession:Q,sendMessage:ee,uploadPaste:et,stopSession:er,restartSession:es,switchAgentType:en,setModel:ei,startNewConversation:el,ensureSession:ep,switchMode:ea,acceptPlan:eo,residentLimitPrompt:ec}}(e,r,i?.agent_mode,F,{sessionId:s,onTaskCompleted:o,onSessionStarted:l,onTitleUpdated:(e,r)=>{let s=r??et?.id;s&&e&&(Y({sessionId:s,title:e}),c?.(s,e)),U(e=>e+1),K(null)}});m=et?.id??null,(0,sC.useGlobalEventStream)(s=>{"session:status"!==s.type||"running"!==s.status||!e||s.projectId!==e||(s.branch??null)!==(r??null)||s.sessionId&&s.sessionId!==m&&(e=>n?.(e))(s.sessionId)});let eb=et?.id??null;(0,$.useEffect)(()=>{f?.(eb)},[eb,f]);let ew=(0,$.useRef)(f);ew.current=f,(0,$.useEffect)(()=>()=>ew.current?.(null),[]),(0,$.useEffect)(()=>{(0,rv.getAgentProviders)().then(B).catch(()=>{})},[]),(0,$.useEffect)(()=>{et?.permissionMode&&N(et.permissionMode)},[et?.permissionMode]),(0,$.useEffect)(()=>{et?.agentType&&P(et.agentType)},[et?.agentType]),(0,$.useEffect)(()=>{S([]),C(1),z(null)},[e,r]);let eS=(0,$.useRef)({sessionId:null,count:0});(0,$.useEffect)(()=>{let e=et?.id??null,r=eS.current;e&&r.sessionId===e&&0===r.count&&er.length>0&&K(e),eS.current={sessionId:e,count:er.length}},[et?.id,er.length]),(0,$.useEffect)(()=>{q&&et?.id!==q&&K(null)},[et?.id,q]),(0,$.useEffect)(()=>{V&&et?.id!==V.sessionId&&Y(null)},[et?.id,V]),(0,$.useEffect)(()=>{if(!V)return;let e=setTimeout(()=>{Y(e=>e===V?null:e)},5e3);return()=>clearTimeout(e)},[V]),(0,$.useEffect)(()=>{if(!q)return;let e=setTimeout(()=>{K(e=>e===q?null:e)},3e4);return()=>clearTimeout(e)},[q]);let[ej,eC]=(0,$.useState)(!1);(0,$.useEffect)(()=>{eC(!1)},[et?.id]),(0,$.useEffect)(()=>{en&&eC(!0)},[en]);let ek=async e=>{N(e),et&&await ex(e)},eN=async e=>{let r=await ep(e);r&&_Z.toast.error("Failed to change model",{description:r})},eE=async e=>{await ev(e),N("edit"),u?.()},[eD,eR]=(0,$.useState)(!1),eA=async(e,r)=>{if(et&&!eD){eR(!0);try{let s=await (0,rv.branchAgentSession)(et.id,e,r);U(e=>e+1),n?.(s.session.id)}catch(r){let e=r instanceof Error?r.message:"Failed to branch conversation";_Z.toast.error("Branch failed",{description:e})}finally{eR(!1)}}},eT=I.find(e=>e.type===F)?.displayName??("codex"===F?"Codex":"Claude Code"),eM=I.filter(e=>e.available).filter(e=>e.type!==F),eF=(0,$.useMemo)(()=>{for(let e=er.length-1;e>=0;e--)if(er[e]?.type==="turn_end")return e;return -1},[er]),eP=function(e,r,s,n){let[i,a]=(0,$.useState)(null),o=(0,$.useRef)(0),[l,c]=(0,$.useState)({runUpdate:null,sessionId:null});(l.runUpdate!==n||l.sessionId!==s)&&(c({runUpdate:n,sessionId:s}),n&&n.reviewer_session_id===s&&a(NV.has(n.status)?n:null)),(0,$.useLayoutEffect)(()=>{n&&n.reviewer_session_id===s&&o.current++},[n,s]);let[d,u]=(0,$.useState)({projectId:null,sessionId:null});return(d.projectId!==e||d.sessionId!==s)&&(u({projectId:e,sessionId:s}),a(null)),(0,$.useEffect)(()=>{if(!e||!s)return;let n=!1,i=o.current;return rv.api.getActiveWorkflowRuns(e,r).then(e=>{n||o.current!==i||a(e.find(e=>e.reviewer_session_id===s)??null)}).catch(()=>{}),()=>{n=!0}},[e,r,s]),i}(e,r,eb,ec),[eI,eB]=(0,$.useState)(!1),eL=(0,$.useCallback)(async()=>{if(eP){eB(!0);try{await rv.api.workflowRunGate(eP.id,"finalize")}catch(e){_Z.toast.error(e instanceof Error?e.message:"生成终稿失败")}finally{eB(!1)}}},[eP]),ez=(0,$.useCallback)(e=>{var r,s;let n;b((r=y,s=e,n=0===r.length||r.endsWith("\n\n")?"":r.endsWith("\n")?"\n":"\n\n",r+n+(s.replace(/\r?\n/g,"\n").split("\n").map(e=>`> ${e}`).join("\n")+"\n\n"))),requestAnimationFrame(()=>{let e=J.current?.querySelector("textarea");if(!e)return;e.focus();let r=e.value.length;try{e.setSelectionRange(r,r)}catch{}})},[b,y]),eO=(0,$.useCallback)(async()=>{!ea&&et&&(await em(),z(null),h?.(),n?.(null),J.current?.querySelector("textarea")?.focus())},[ea,et,em,h,n]);(0,$.useImperativeHandle)(p,()=>({startNewConversation:eO,submitMessage:async e=>{if(u?.(),et)ed(e);else{let r=await eg(k,L);r&&(K(r.id),ed(e,r.id))}}}),[eO,et,eg,ed,k,L,u]);let e$=(0,$.useCallback)((e,r)=>{if(r.length<=2e3)return;e.preventDefault();let s=e.currentTarget,n=s.selectionStart??y.length,i=s.selectionEnd??y.length,a=new TextEncoder().encode(r).length,o=N9(j,a);b(y.slice(0,n)+o+y.slice(i)),S(e=>[...e,{id:j,content:r,size:a}]),C(j+1);let l=n+o.length;requestAnimationFrame(()=>{try{s.setSelectionRange(l,l)}catch{}})},[y,j,b]);async function eW(e,r,s,n){let i=new Set;for(let r of e.matchAll(N8))i.add(Number(r[1]));let a=r.filter(e=>i.has(e.id));if(0===a.length)return e;let o=e;for(let e of a){let r=await s(e.content,n),i=N9(e.id,e.size),a=`<vpaste path="${r.path}" size="${r.size}" />`;o=o.split(i).join(a)}return o}let eH=async e=>{let r=e.text,s=e.files.length>0,n=w.length>0,i=r.trim();if(i||s){M(!0);try{let a;b(""),Z.push(i),u?.();let o=et?.id,l=null;if(!et){if(!(l=await eg(k,L)))return void b(r);o=l.id,K(l.id)}let c=i;if(n)try{c=(await eW(r,w,eu,o)).trim()}catch(s){let e=s instanceof Error?s.message:"Failed to upload paste";_Z.toast.error("Paste upload failed",{description:e}),b(r);return}if(c.length>2e3)try{let e=await eu(c,o);c=`<vpaste path="${e.path}" size="${e.size}" />`}catch(s){let e=s instanceof Error?s.message:"Failed to upload paste";_Z.toast.error("Paste upload failed",{description:e}),b(r);return}if(S([]),C(1),s){let r=[];for(let s of(c&&r.push({type:"text",text:c}),e.files))if(s.mediaType&&s.url){let e=s.url.match(/^data:[^;]+;base64,(.+)$/);e&&r.push({type:"image",mediaType:s.mediaType,data:e[1]})}a=r}else a=c;if(E){let e="string"==typeof a?a:a.filter(e=>"text"===e.type).map(e=>e.text).join("\n");if(e.trim()){A(!0);try{let s=await (0,rv.translateText)(e);if(s.error){b(r),S(w),C(j),_Z.toast.error("Translation failed",{description:"Disable translation to send the original text."});return}a="string"==typeof a?s.translatedText:a.map(e=>"text"===e.type?{...e,text:s.translatedText}:e)}catch{b(r),S(w),C(j),_Z.toast.error("Translation failed",{description:"Disable translation to send the original text."});return}finally{A(!1)}}}l?(console.log(`[AgentConversation] handleSubmit: using freshly started session ${l.id}`),await ed(a,l.id)):(console.log(`[AgentConversation] handleSubmit: existing session ${et.id}, status=${es}`),await ed(a))}finally{M(!1)}}},{settings:eU}=(0,hG.useConversationSettings)();return e?(0,O.jsxs)("div",{className:"h-full flex flex-col min-h-0",style:{"--conv-font-size":`${eU.agentFontSize}px`},children:[(0,O.jsxs)("div",{className:"flex-shrink-0 flex items-center justify-between px-4 h-10 border-b border-border/60 bg-muted/20",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[I.length>1?(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsxs)("button",{disabled:ea||"running"===es&&er.length>0,className:(0,ey.cn)("inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-0.5 text-xs font-medium transition-colors hover:bg-muted",(ea||"running"===es&&er.length>0)&&"opacity-50 cursor-not-allowed"),children:[(0,O.jsx)(Nq,{type:F}),(0,O.jsx)(NL,{candidates:I.map(e=>e.displayName),children:eT}),(0,O.jsx)(ns,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,O.jsx)(a7,{align:"start",className:"min-w-[var(--radix-dropdown-menu-trigger-width)]",children:(0,O.jsx)(oe,{value:F,onValueChange:async e=>{if(!et){e!==F&&z(null),P(e);return}let r=await ef(e);r?_Z.toast.error("Failed to switch agent",{description:r}):P(e)},children:I.map(e=>(0,O.jsxs)(ot,{value:e.type,disabled:!e.available,className:"text-xs pl-2 [&>span:first-child]:hidden data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground",children:[(0,O.jsx)(Nq,{type:e.type}),e.displayName]},e.type))})})]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Nq,{type:F,className:"h-4 w-4"}),(0,O.jsx)("span",{className:"text-sm font-medium",children:eT})]}),(0,O.jsx)(NW,{models:I.find(e=>e.type===F)?.models??[],widthCandidates:I.flatMap(e=>e.models??[]),value:et?et.model??null:L,onChange:et?eN:z,locked:null!=et&&"running"===es&&er.length>0}),(0,O.jsx)(NU,{mode:k,onModeChange:ek}),ee.length>=1&&a&&(0,O.jsx)(oo,{targets:ee,activeTarget:i?.agent_mode??"local",onTargetChange:a}),et&&(g=et.id.startsWith("remote-"),x="text-muted-foreground",v=(0,O.jsx)(Nr,{className:"h-3 w-3"}),_="Disconnected",en?g&&"connected"!==el&&null!==el?"reconnecting"===el?(x="text-amber-500",v=(0,O.jsx)(Nt,{className:"h-3 w-3 animate-pulse"}),_="Reconnecting..."):"disconnected"===el&&(x="text-red-500",v=(0,O.jsx)(Nr,{className:"h-3 w-3"}),_="Remote disconnected"):(x="text-green-500",v=(0,O.jsx)(Nt,{className:"h-3 w-3"}),_="Connected"):ej||(x="text-amber-500",v=(0,O.jsx)(Nt,{className:"h-3 w-3 animate-pulse"}),_="Connecting..."),(0,O.jsx)("span",{className:`flex items-center ${x}`,title:_,children:v}))]}),(0,O.jsxs)("div",{className:"flex items-center gap-1",children:[e&&(0,O.jsx)(N3,{projectId:e,branch:r,sessionId:et?.id??null,currentAgentType:F,providers:I}),e&&(0,O.jsx)(NZ,{projectId:e,branch:r,currentSessionId:et?.id??null,refreshKey:H,pendingTitleSessionId:q,aiTitleOverride:V,onSwitch:e=>{d?.(e),n?.(e)},onDelete:(e,r)=>{if(e===et?.id){let e=r[0];n?.(e?e.id:null)}}}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:eO,disabled:ea||!et,className:"h-7 w-7",title:"New Conversation (⌘⇧O / Ctrl+Shift+O)",children:(0,O.jsx)(Ns,{className:"h-3.5 w-3.5"})}),(0,O.jsxs)(W.Button,{variant:"ghost",size:"sm",onClick:()=>eh(),disabled:"running"!==es,className:"h-7 text-xs",children:[(0,O.jsx)(lJ,{className:"h-3 w-3 mr-1"}),"Stop"]})]})]}),(0,O.jsxs)("div",{className:"flex-1 min-h-0 relative",children:[(0,O.jsxs)(c$,{className:"h-full",initial:"instant",children:[(0,O.jsxs)(cW,{className:"gap-1 p-4",scrollClassName:"edge-scrollbar",children:[et||0!==er.length?(0,O.jsx)(N6.Provider,{value:{sendMessage:ed,messages:er,acceptPlan:eE,permissionMode:et?.permissionMode??k,agentType:et?.agentType??F,sessionId:et?.id??null},children:(0,O.jsxs)("div",{className:"space-y-1 outline-none",ref:G,tabIndex:-1,onKeyDown:X,children:[er.map((e,r)=>e?.type==="turn_end"?(0,O.jsx)(Nl,{durationMs:e.durationMs,outcome:e.outcome,emphasis:r===eF?"normal":"subtle",agentType:F,currentAgentName:eT,alternateProviders:eM,onBranch:e=>eA(e,r),disabled:eD,showFinalize:r===eF&&eP?.status==="discussing",finalizeBusy:eI,onFinalize:eL},r):(0,O.jsx)("div",{"data-message-idx":r,..."user"===e.type?{"data-user-msg-idx":r}:{},className:"scroll-mt-2",children:(0,O.jsx)(ku,{message:e,messageIndex:r})},r)),ea&&(0,O.jsxs)("div",{className:"flex items-center gap-2 py-4 text-muted-foreground",children:[(0,O.jsx)(Ne,{className:"h-4 w-4"}),(0,O.jsx)("span",{className:"text-sm",children:"Connecting to agent..."})]})]})}):(0,O.jsx)("div",{className:"text-center py-16",children:ea||e&&!ei?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Ne,{className:"h-6 w-6 mx-auto mb-4"}),(0,O.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Connecting to agent..."}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Setting up the session for this worktree"})]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-4",children:(0,O.jsx)(sb,{className:"h-6 w-6 text-primary/60"})}),(0,O.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Start a conversation"}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Ask the agent to help you with coding tasks in this worktree"})]})}),eo&&(0,O.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-red-500/10 rounded-lg text-red-500 text-sm mt-4",children:[(0,O.jsx)(sy,{className:"h-4 w-4"}),eo]})]}),(0,O.jsx)(cH,{})]}),(0,O.jsx)(NX,{messages:er,contentRef:G}),(0,O.jsx)(N1,{containerRef:G,onQuote:ez})]}),(0,O.jsx)("div",{className:"flex-shrink-0 p-3",children:(0,O.jsxs)(kZ,{onSubmit:eH,accept:"image/*",className:"w-full",children:[(0,O.jsx)(N4,{}),(0,O.jsxs)("div",{className:"relative flex w-full flex-col",children:[E&&(0,O.jsx)("div",{className:"flex items-center pl-12 pr-2 pt-1.5 pb-0.5",children:(0,O.jsxs)("button",{type:"button",onClick:()=>D(!1),className:"inline-flex shrink-0 items-center gap-1.5 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 px-2.5 py-0.5 text-xs font-medium hover:bg-blue-500/20 transition-colors",children:[R?(0,O.jsx)(sj,{className:"size-3 animate-spin"}):(0,O.jsx)(Nn,{className:"size-3"}),"Translate",(0,O.jsx)(t7,{className:"size-3"})]})}),(0,O.jsxs)("div",{className:"flex w-full items-center",children:[(0,O.jsxs)(k2,{children:[(0,O.jsx)(k5,{className:"ml-1"}),(0,O.jsxs)(k3,{children:[(0,O.jsx)(kJ,{label:"Add images"}),(0,O.jsxs)(k4,{onSelect:()=>{D(!E)},children:[(0,O.jsx)(Nn,{className:"mr-2 size-4"}),E?"Disable translation":"Translate"]})]})]}),(0,O.jsx)("div",{ref:J,className:"contents",children:(0,O.jsx)(kQ,{value:y,onChange:e=>b(e.target.value),onPasteText:e$,onKeyDown:Z.handleKeyDown,placeholder:et?"Ask the agent to help with your code...":"Type your first message to start...",className:"pr-12",style:{fontSize:"var(--conv-font-size, 14px)"}})}),(0,O.jsx)("div",{className:"pointer-events-none absolute bottom-0 right-2 flex items-center text-base md:text-sm",style:{fontSize:"var(--conv-font-size, 14px)",height:"calc(1lh + 1.5rem)"},children:(0,O.jsx)(k6,{className:"pointer-events-auto",disabled:!y.trim()&&!ea||R||T,status:T||R?"submitted":ea?"streaming":"ready"})})]})]})]})}),(0,O.jsx)(lL,{open:null!==e_,onOpenChange:e=>{e||e_?.resolve(!1)},children:(0,O.jsxs)(l$,{children:[(0,O.jsxs)(lW,{children:[(0,O.jsx)(lU,{children:"Agent process limit reached"}),(0,O.jsxs)(lq,{children:["All ",e_?.maxResidentAgentProcesses," resident agent processes for this workspace branch are running. Starting a new conversation will stop the least recently active running session in this branch."]})]}),(0,O.jsxs)(lH,{children:[(0,O.jsx)(lV,{children:"Cancel"}),(0,O.jsx)(lK,{onClick:()=>e_?.resolve(!0),children:"Stop & start new"})]})]})})]}):(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(sb,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to start coding"})]})})});function Et(){return"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}async function Er(e,r){let s=await (0,rv.authFetch)(`${Et()}/api/projects/${e}/chat-sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:r})});if(!s.ok)throw Error("Failed to create chat session");return s.json()}async function Es(e,r){if(!(await (0,rv.authFetch)(`${Et()}/api/chat-sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r})})).ok)throw Error("Failed to send message")}async function En(e){if(!(await (0,rv.authFetch)(`${Et()}/api/chat-sessions/${e}/stop`,{method:"POST"})).ok)throw Error("Failed to stop generation")}let Ei=new Map;function Ea(e,r){return`chat:${e}:${r??""}`}function Eo({sessionId:e,approvalId:r,tool:s,input:n,resolved:i}){let[a,o]=(0,$.useState)(null),l=function(e){if(null!==e&&"object"==typeof e){if("string"==typeof e.message)return e.message;if("string"==typeof e.prompt)return e.prompt}return JSON.stringify(e)}(n),c=async s=>{if(!a&&!i){o(s?"approve":"deny");try{await rv.api.chatToolApproval(e,r,s)}finally{o(null)}}};return(0,O.jsx)("div",{className:"mx-4 my-1",children:(0,O.jsxs)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 space-y-2",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)(sb,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),(0,O.jsxs)("span",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:["Approval needed · ","spawnAgentSession"===s?"Start a new coding agent":"Send to the coding agent"]})]}),(0,O.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all text-foreground/80",style:{fontSize:"var(--conv-font-size, 12px)"},children:l}),i?(0,O.jsxs)(sa,{variant:"default",className:"approved"===i?"bg-green-600 hover:bg-green-700 text-white":"bg-red-600 hover:bg-red-700 text-white",children:["approved"===i?(0,O.jsx)(sJ,{className:"h-3 w-3 mr-1"}):(0,O.jsx)(s0,{className:"h-3 w-3 mr-1"}),"approved"===i?"Approved — sent.":"Denied — not sent."]}):(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsxs)(W.Button,{onClick:()=>c(!0),disabled:null!==a,className:"bg-green-600 hover:bg-green-700 text-white",size:"sm",children:["approve"===a?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,O.jsx)(sJ,{className:"h-3.5 w-3.5 mr-1"}),"Approve"]}),(0,O.jsxs)(W.Button,{onClick:()=>c(!1),disabled:null!==a,variant:"destructive",size:"sm",children:["deny"===a?(0,O.jsx)(sj,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,O.jsx)(s0,{className:"h-3.5 w-3.5 mr-1"}),"Deny"]})]})]})})}let El=new Set(["waiting_reviewer","waiting_feedback","discussing","sending_feedback"]);function Ec({projectId:e,branch:r,runUpdate:s,onRunsChange:n}){let[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)({}),[c,d]=(0,$.useState)({}),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(null),m=(0,$.useCallback)(async()=>{if(e)try{let s=await rv.api.getActiveWorkflowRuns(e,r);a(s),n?.(s)}catch{}},[e,r,n]);(0,$.useEffect)(()=>{m()},[m]),(0,$.useEffect)(()=>{s&&m()},[s,m]),(0,$.useEffect)(()=>{if(0===i.length)return;let e=setInterval(()=>void m(),5e3);return()=>clearInterval(e)},[i.length,m]);let g=async(e,r)=>{h(r),p(null);try{await e()}catch(e){p(e instanceof Error?e.message:String(e))}finally{h(null),await m()}},x=i.filter(e=>El.has(e.status));return 0===x.length?null:(0,O.jsx)("div",{className:"shrink-0 border-b bg-muted/30 px-4 py-2 space-y-2 max-h-[50vh] overflow-y-auto",children:x.map(e=>(0,O.jsxs)("div",{className:"text-sm space-y-2",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between",children:[(0,O.jsxs)("span",{className:"font-medium",children:["Review",e.review_focus?` — ${e.review_focus}`:"",(0,O.jsxs)("span",{className:"ml-2 text-muted-foreground",children:["waiting_reviewer"===e.status&&"reviewer 审查中…","waiting_feedback"===e.status&&"等你确认反馈","discussing"===e.status&&"讨论中","sending_feedback"===e.status&&"发送中…"]})]}),(0,O.jsxs)(W.Button,{variant:"ghost",size:"sm",disabled:u===e.id,onClick:()=>g(()=>rv.api.cancelWorkflowRun(e.id),e.id),children:[(0,O.jsx)(t7,{className:"h-3 w-3 mr-1"}),"结束"]})]}),e.error&&(0,O.jsx)("div",{className:"text-xs text-amber-600",children:e.error}),"waiting_reviewer"===e.status&&(0,O.jsxs)("div",{className:"flex items-center text-muted-foreground text-xs",children:[(0,O.jsx)(sj,{className:"h-3 w-3 mr-1 animate-spin"})," reviewer session 正在工作"]}),"discussing"===e.status&&(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:"与 reviewer 讨论后,生成终稿再发送"}),(0,O.jsx)(W.Button,{size:"icon-sm",variant:"outline","aria-label":"生成 review 终稿",disabled:u===e.id,onClick:()=>g(()=>rv.api.workflowRunGate(e.id,"finalize"),e.id),children:(0,O.jsx)(Cf,{className:"h-3 w-3"})})]}),"waiting_feedback"===e.status&&(0,O.jsxs)(O.Fragment,{children:[c[e.id]?(0,O.jsx)(rl,{className:"text-xs font-mono min-h-28 max-h-72",value:o[e.id]??e.feedback_snapshot??"",onChange:r=>l(s=>({...s,[e.id]:r.target.value}))}):(0,O.jsx)("div",{className:"text-xs border rounded-md bg-background px-3 py-2 max-h-72 overflow-y-auto",children:(0,O.jsx)(cD,{children:o[e.id]??e.feedback_snapshot??""})}),(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsx)(W.Button,{size:"sm",disabled:u===e.id,onClick:()=>g(()=>rv.api.workflowRunGate(e.id,"approve",o[e.id]??void 0),e.id),children:"发送反馈给原 session"}),(0,O.jsx)(W.Button,{variant:"outline",size:"sm",disabled:u===e.id,onClick:()=>d(r=>({...r,[e.id]:!r[e.id]})),children:c[e.id]?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(wf,{className:"h-3 w-3 mr-1"}),"预览"]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(rg,{className:"h-3 w-3 mr-1"}),"编辑"]})})]})]}),f&&(0,O.jsx)("div",{className:"text-xs text-destructive",children:f})]},e.id))})}let Ed=(0,ew.default)("radio",[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);function Eu({messages:e}){let{scrollToBottom:r}=cO(),s=(0,$.useRef)(e.length);return(0,$.useEffect)(()=>{let n=s.current;if(s.current=e.length,!(e.length<=n))for(let s=n;s<e.length;s++){let n=e[s];if("user"===n.type&&n.content.startsWith("[Executor Event:"))return void r({animation:"instant"})}},[e,r]),null}let Eh=(0,$.forwardRef)(function({projectId:e,branch:r},s){let{session:n,messages:i,status:a,isInitialized:o,isLoading:l,error:c,sendMessage:d,stopGeneration:u,restartSession:h,workflowRunUpdate:f}=function(e,r){let[s,n]=(0,$.useState)(null),[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)("stopped"),[c,d]=(0,$.useState)(!1),[u,h]=(0,$.useState)(!1),[f,p]=(0,$.useState)(!1),[m,g]=(0,$.useState)(null),[x,v]=(0,$.useState)(null),_=(0,$.useRef)(null),y=(0,$.useRef)(()=>{}),b=(0,$.useRef)(null),w=(0,$.useRef)(0),S=(0,$.useRef)({entries:[],status:"stopped"}),j=(0,$.useRef)(!1),C=(0,$.useRef)(!0),k=(0,$.useRef)(!1),N=(0,$.useRef)(0),E=(0,$.useRef)(null),D=(0,$.useRef)(null),R=(0,$.useRef)(0),A=(0,$.useRef)(!1),T=(0,$.useCallback)((e,r=!1)=>{_.current?.readyState!==WebSocket.OPEN&&_.current?.readyState!==WebSocket.CONNECTING&&(0,rv.getFreshToken)(r?{skipCache:!0}:void 0).then(()=>y.current(e))},[]),M=(0,$.useCallback)(i=>{if(_.current?.readyState===WebSocket.OPEN||_.current?.readyState===WebSocket.CONNECTING)return;S.current={entries:[],status:"stopped"},j.current=!1,k.current=!0;let o=new WebSocket((0,rv.getWebSocketUrl)(`/api/chat-sessions/${i}/stream`));_.current=o;let c=N.current;o.onopen=()=>{d(!0),g(null),E.current=Date.now(),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{w.current=0,R.current=0},5e3)},o.onmessage=s=>{if(c===N.current)try{let c=JSON.parse(s.data);if("JsonPatch"in c){var n,i;let e=S.current.entries.filter(Boolean).length;n=S.current,i=c.JsonPatch,S.current=jY(n,e=>{for(let r of i){let{op:s,path:n,value:i}=r;if("/entries"===n&&"replace"===s&&i?.type==="ENTRY"&&i.content?.type==="system"&&i.content?.content==="__CLEAR_ALL__"){e.entries=[];continue}if(n.startsWith("/entries/")){let r=parseInt(n.replace("/entries/",""),10);if(isNaN(r)||i?.type!=="ENTRY")continue;switch(s){case"add":for(;e.entries.length<=r;)e.entries.push(null);e.entries[r]=i.content;break;case"replace":r<e.entries.length&&(e.entries[r]=i.content);break;case"remove":r<e.entries.length&&e.entries.splice(r,1)}}else"/status"===n&&i?.type==="STATUS"&&(e.status=i.content)}});let r=S.current.entries.filter(Boolean).length;k.current?r!==e&&console.log(`[ChatSession] WS patch added message (${e} → ${r}) but isReplaying=true, state NOT updated`):(r!==e&&console.log(`[ChatSession] New message via WS patch (${e} → ${r}), calling setMessages`),a([...S.current.entries.filter(Boolean)]),l(S.current.status));return}if("Ready"in c){k.current=!1;let e=S.current.entries.filter(Boolean).length;console.log(`[ChatSession] Ready received, isReplaying → false, ${e} messages`),a([...S.current.entries.filter(Boolean)]),l(S.current.status),h(!0);return}if("finished"in c){j.current=!0,o.close(1e3,"finished");return}if("openPreviewFrame"in c)return void(0,wu.openPreviewFrame)(c.openPreviewFrame.projectId,c.openPreviewFrame.url);if("WorkflowRunUpdated"in c)return void v(c.WorkflowRunUpdated);if("browserCommand"in c){let r=c.browserCommand;e&&(0,wu.sendCommandToIframe)(e,{type:"vibedeckx-command",...r}).then(e=>{e&&o.readyState===WebSocket.OPEN&&o.send(JSON.stringify({type:"browser_result",result:{id:r.id,success:e.success??!1,error:e.error,content:e.content,found:e.found,tag:e.tag,text:e.text}}))});return}if("error"in c){g(c.error),"Session not found"===c.error&&(e&&Ei.delete(Ea(e,r)),j.current=!0);return}}catch(e){console.error("[ChatSession] Failed to parse message:",e)}},o.onclose=i=>{let a,o;if(c!==N.current)return;d(!1),_.current=null,D.current&&(clearTimeout(D.current),D.current=null);let l=4e3===i.code,u=E.current?Date.now()-E.current:0;if(E.current=null,!l&&u>0&&u<5e3){if(R.current++,R.current>=3)return A.current?void g("Unable to connect to remote server. Please check the server configuration."):(e&&Ei.delete(Ea(e,r)),n(null),g(null),w.current=0,R.current=0,void(C.current=!0))}else u>=5e3&&(R.current=0);if(j.current||1e3===i.code)return;if(w.current>=10)return void g("Unable to connect to server.");let h=(o=(a=Math.min(3e4,1e3*Math.pow(2,w.current)))*Math.random()*.25,a+o);w.current++,b.current=setTimeout(()=>{s?.id&&!j.current&&T(s.id,!0)},h)},o.onerror=()=>{}},[s?.id,T]);(0,$.useEffect)(()=>{y.current=M},[M]);let F=(0,$.useCallback)(async()=>{if(!e)return null;let s=N.current;g(null),h(!1),A.current=!1;let i=Ea(e,r),o=Ei.get(i);if(o)return n(o),l(o.status),T(o.id),o;p(!0);try{let{session:o,messages:c}=await Er(e,r);if(N.current!==s)return null;return Ei.set(i,o),n(o),l(o.status),c&&c.length>0&&a(c),T(o.id),o}catch(e){if(N.current!==s)return null;return g(e instanceof Error?e.message:"Failed to start session"),A.current=!0,null}finally{N.current===s&&p(!1)}},[e,r,T]),P=(0,$.useCallback)(async e=>{let r=s?.id;if(r&&e.trim())try{await Es(r,e.trim())}catch(r){let e=r instanceof Error?r.message:"Failed to send message";g(e),_Z.toast.error("Failed to send message",{description:e})}},[s?.id]),I=(0,$.useCallback)(async()=>{if(s?.id)try{await En(s.id)}catch(e){console.error("[ChatSession] Failed to stop generation:",e)}},[s?.id]),B=(0,$.useCallback)(async()=>{if(s?.id)try{await rv.api.resetChatSession(s.id),a([]),l("stopped"),S.current={entries:[],status:"stopped"}}catch(e){console.error("[ChatSession] Failed to reset session:",e),_Z.toast.error("Failed to start new conversation")}},[s?.id]);return(0,$.useEffect)(()=>()=>{_.current&&(j.current=!0,_.current.close()),b.current&&clearTimeout(b.current),D.current&&clearTimeout(D.current)},[]),(0,$.useEffect)(()=>{_.current&&(_.current.close(1e3,"branch-switch"),_.current=null),b.current&&(clearTimeout(b.current),b.current=null),D.current&&(clearTimeout(D.current),D.current=null),N.current+=1,n(null),l("stopped"),d(!1),h(!1),g(null),p(!1),S.current={entries:[],status:"stopped"},j.current=!1,w.current=0,E.current=null,R.current=0,A.current=!1,C.current=!0},[e,r]),(0,$.useEffect)(()=>{!C.current||!e||s||f||A.current||(C.current=!1,F())},[e,s,f,F]),(0,$.useEffect)(()=>{!s?.id||c||j.current||T(s.id)},[s?.id,c,T]),(0,$.useEffect)(()=>{let e=()=>{if("visible"!==document.visibilityState||!s?.id||j.current)return;let e=_.current,r=S.current.entries.filter(Boolean).length;console.log(`[ChatSession] Tab visible: ws.readyState=${e?.readyState??"null"}, isReplaying=${k.current}, messages=${r}`),e&&e.readyState===WebSocket.OPEN&&e.close(4e3,"visibility-recovery")};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[s?.id]),{session:s,messages:i,status:o,isConnected:c,isInitialized:u,isLoading:f,error:m,workflowRunUpdate:x,sendMessage:P,stopGeneration:I,restartSession:B}}(e,r),{settings:p}=(0,hG.useConversationSettings)(),[m,g]=(0,$.useState)([]);(0,$.useImperativeHandle)(s,()=>({sendMessage:async e=>{let r=e.trim();r&&await d(r)}}),[d]);let[x,v]=(0,$.useState)(""),[_,y]=(0,$.useState)(!1);(0,$.useEffect)(()=>{n?.eventListeningEnabled!=null&&y(n.eventListeningEnabled)},[n?.eventListeningEnabled]);let b="running"===a,w=(0,$.useCallback)(async e=>{let r=e.text.trim();r&&(v(""),await d(r))},[d]);return e?(0,O.jsxs)("div",{className:"h-full flex flex-col min-h-0",style:{"--conv-font-size":`${p.chatFontSize}px`},children:[(0,O.jsxs)("div",{className:"flex-shrink-0 flex items-center justify-between px-4 h-10 border-b border-border/60 bg-muted/20",children:[(0,O.jsxs)("div",{className:"flex items-center gap-2",children:[(0,O.jsx)(sD,{className:"h-3.5 w-3.5 text-primary"}),(0,O.jsx)("span",{className:"text-xs font-medium text-foreground",children:"Main Chat"}),b&&(0,O.jsx)(sj,{className:"h-3 w-3 animate-spin text-primary/60"})]}),n&&(0,O.jsxs)("div",{className:"flex items-center gap-1",children:[(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:async()=>{let e=!_;try{await rv.api.setChatEventListening(n.id,e),y(e)}catch{_Z.toast.error("Failed to toggle event listening")}},className:`h-7 w-7 ${_?"text-amber-500":""}`,title:_?"Listening to executor events (click to disable)":"Listen to executor events (click to enable)",children:(0,O.jsx)(Ed,{className:"h-3.5 w-3.5"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",onClick:()=>h(),disabled:b,className:"h-7 w-7",title:"New Conversation",children:(0,O.jsx)(Ns,{className:"h-3.5 w-3.5"})})]})]}),(0,O.jsx)(Ec,{projectId:e,branch:r,runUpdate:f,onRunsChange:g}),(0,O.jsxs)(c$,{className:"flex-1 min-h-0",initial:"instant",children:[(0,O.jsx)(Eu,{messages:i}),(0,O.jsxs)(cW,{className:"gap-4 p-4",children:[l&&0===i.length&&(0,O.jsx)("div",{className:"flex items-center justify-center py-8",children:(0,O.jsx)(sj,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),!l&&o&&0===i.length&&(0,O.jsxs)("div",{className:"text-center py-16",children:[(0,O.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-4",children:(0,O.jsx)(sD,{className:"h-6 w-6 text-primary/60"})}),(0,O.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Start a conversation"}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Chat with the AI assistant about your project"})]}),i.map((s,i)=>{if("turn_end"===s.type)return(0,O.jsxs)("div",{className:"mx-4 my-3 flex items-center gap-2","aria-hidden":!0,children:[(0,O.jsx)("div",{className:"h-px flex-1 bg-border"}),(0,O.jsx)("div",{className:"h-1 w-1 shrink-0 rounded-full bg-border"}),(0,O.jsx)("div",{className:"h-px flex-1 bg-border"})]},i);if("user"===s.type&&s.content.startsWith("[System Invariant Violation]")){let e=s.content.replace(/^\[System Invariant Violation\]\n?/,"");return(0,O.jsxs)("div",{className:"mx-4 my-2 flex gap-2 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2",children:[(0,O.jsx)(s6,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),(0,O.jsxs)("div",{className:"min-w-0",children:[(0,O.jsx)("div",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:"System invariant correction"}),(0,O.jsx)("div",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:e})]})]},i)}if("user"===s.type){let n=s.event,a=n?.kind==="agent_task_completed"&&m.some(e=>e.source_session_id===n.sessionId||e.reviewer_session_id===n.sessionId);return(0,O.jsxs)("div",{children:[(0,O.jsx)(cN,{from:"user",children:(0,O.jsx)(cE,{style:{fontSize:"var(--conv-font-size, 14px)"},children:s.content})}),n?.kind==="agent_task_completed"&&(0,O.jsx)("div",{className:"mt-1 flex justify-end",children:(0,O.jsx)(W.Button,{variant:"outline",size:"sm",disabled:a,title:a?"该 session 已在一个进行中的 review 里":void 0,onClick:async()=>{if(e)try{await rv.api.createWorkflowRun({projectId:e,branch:r,sourceSessionId:n.sessionId,sourceTurnEndIndex:n.turnEndEntryIndex})}catch(e){alert(e instanceof Error?e.message:String(e))}},children:"Review"})})]},i)}return"assistant"===s.type?(0,O.jsx)(cN,{from:"assistant",children:(0,O.jsx)(cE,{style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,O.jsx)(cD,{children:s.content})})},i):"tool_use"===s.type?(0,O.jsxs)("div",{className:"flex items-center gap-2 px-4 py-2 text-xs text-muted-foreground",children:[(0,O.jsx)(sA,{className:"w-3.5 h-3.5 animate-pulse"}),(0,O.jsx)("span",{children:function(e){switch(e){case"getExecutorStatus":return"Checking executor status...";case"getAgentConversation":return"Checking agent conversation...";case"listTerminals":return"Listing terminals...";case"runInTerminal":return"Sending command to terminal...";case"spawnAgentSession":return"Starting a coding agent...";case"sendToAgentSession":return"Sending a message to the agent...";default:return`Running ${e}...`}}(s.tool)})]},i):"tool_result"===s.type?(0,O.jsx)("div",{className:"px-4 py-2",children:(0,O.jsxs)("details",{className:"text-xs text-muted-foreground",children:[(0,O.jsx)("summary",{className:"cursor-pointer hover:text-foreground",children:"Tool result"}),(0,O.jsx)("pre",{className:"mt-1 p-2 bg-muted/50 rounded overflow-x-auto whitespace-pre-wrap",style:{fontSize:"var(--conv-font-size, 12px)"},children:s.output})]})},i):"tool_approval_request"===s.type?n?(0,O.jsx)(Eo,{sessionId:n.id,approvalId:s.approvalId,tool:s.tool,input:s.input,resolved:s.resolved},i):null:"error"===s.type?(0,O.jsx)("div",{className:"mx-auto max-w-[90%] rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-destructive",style:{fontSize:"var(--conv-font-size, 14px)"},children:s.message},i):null}),c&&(0,O.jsx)("div",{className:"mx-auto max-w-[90%] rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:c})]}),(0,O.jsx)(cH,{})]}),(0,O.jsxs)("div",{className:"flex-shrink-0 p-3",children:[b&&(0,O.jsx)("div",{className:"flex justify-center mb-2",children:(0,O.jsxs)(W.Button,{variant:"outline",size:"sm",onClick:u,className:"gap-1.5",children:[(0,O.jsx)(lJ,{className:"h-3 w-3"}),"Stop generating"]})}),(0,O.jsxs)(kZ,{onSubmit:w,className:"w-full",children:[(0,O.jsx)(kQ,{disabled:!o||b,placeholder:o?b?"Waiting for response...":"Type a message...":"Connecting...",className:"pr-12",style:{fontSize:"var(--conv-font-size, 14px)"},value:x,onChange:e=>v(e.currentTarget.value)}),(0,O.jsx)("div",{className:"pointer-events-none absolute bottom-0 right-2 flex items-center text-base md:text-sm",style:{fontSize:"var(--conv-font-size, 14px)",height:"calc(1lh + 1.5rem)"},children:(0,O.jsx)(k6,{className:"pointer-events-auto",disabled:!o||b||!x.trim()})})]})]})]}):(0,O.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(sD,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to start chatting"})]})})}),Ef=(0,ew.default)("archive-restore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);function Ep({task:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,onClick:o,worktrees:l,assignedBranches:c,onAssign:d}){let[u,h]=(0,$.useState)(!1),[f,p]=(0,$.useState)(e.title),m=(0,$.useRef)(null);(0,$.useEffect)(()=>{u&&(m.current?.focus(),m.current?.select())},[u]),(0,$.useEffect)(()=>{p(e.title)},[e.title]);let g=()=>{h(!1);let s=f.trim();s&&s!==e.title?r(e.id,{title:s}):p(e.title)},x="done"===e.status||"cancelled"===e.status;return(0,O.jsxs)(uD,{className:"group cursor-pointer",onClick:()=>o?.(e),children:[(0,O.jsx)(uA,{className:"w-10",onClick:e=>e.stopPropagation(),children:(0,O.jsx)(eb,{checked:"done"===e.status,onCheckedChange:s=>{r(e.id,{status:s?"done":"todo"})}})}),(0,O.jsx)(uA,{className:"font-medium",children:u?(0,O.jsx)("input",{ref:m,className:"w-full bg-transparent border-b border-primary outline-none text-sm py-0.5",value:f,onChange:e=>p(e.target.value),onBlur:g,onClick:e=>e.stopPropagation(),onKeyDown:r=>{"Enter"===r.key&&g(),"Escape"===r.key&&(p(e.title),h(!1))}}):(0,O.jsxs)("div",{children:[(0,O.jsx)("span",{className:`cursor-pointer hover:underline text-sm ${x?"line-through text-muted-foreground":""}`,onClick:e=>{e.stopPropagation(),h(!0)},children:e.title}),e.description&&(0,O.jsx)("p",{className:"text-xs text-muted-foreground truncate max-w-[400px] mt-0.5",children:e.description.length>80?e.description.slice(0,80)+"...":e.description})]})}),(0,O.jsx)(uA,{onClick:e=>e.stopPropagation(),children:(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)("button",{className:"focus:outline-none",children:(0,O.jsx)(sa,{variant:"outline",className:`cursor-pointer text-xs ${so[e.status].color}`,children:so[e.status].label})})}),(0,O.jsx)(a7,{align:"start",children:sc.map(s=>(0,O.jsxs)(a8,{onClick:()=>r(e.id,{status:s}),children:[(0,O.jsx)("span",{className:`inline-block w-2 h-2 rounded-full mr-2 ${so[s].color}`}),so[s].label]},s))})]})}),(0,O.jsx)(uA,{onClick:e=>e.stopPropagation(),children:(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)("button",{className:"focus:outline-none",children:(0,O.jsx)(sa,{variant:"outline",className:`cursor-pointer text-xs ${sl[e.priority].color}`,children:sl[e.priority].label})})}),(0,O.jsx)(a7,{align:"start",children:sd.map(s=>(0,O.jsxs)(a8,{onClick:()=>r(e.id,{priority:s}),children:[(0,O.jsx)("span",{className:`inline-block w-2 h-2 rounded-full mr-2 ${sl[s].color}`}),sl[s].label]},s))})]})}),(0,O.jsx)(uA,{onClick:e=>e.stopPropagation(),children:(0,O.jsxs)(a4,{children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsx)("button",{className:"focus:outline-none",children:(0,O.jsxs)(sa,{variant:"outline",className:`cursor-pointer text-xs font-mono ${null!==e.assigned_branch?"bg-accent text-accent-foreground border-transparent":"text-muted-foreground"}`,children:[(0,O.jsx)(sU,{className:"h-3 w-3 mr-1"}),null!==e.assigned_branch?""===e.assigned_branch?"main":e.assigned_branch:"Unassigned"]})})}),(0,O.jsxs)(a7,{align:"start",children:[null!==e.assigned_branch&&(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(a8,{onClick:()=>d(e.id,null),children:"Unassign"}),(0,O.jsx)(os,{})]}),l.filter(r=>{let s=null===r.branch?"":r.branch;return!(e.assigned_branch===s||c.has(s))}).map(r=>{let s=null===r.branch?"":r.branch,n=r.branch??"main";return(0,O.jsxs)(a8,{onClick:()=>d(e.id,s),children:[(0,O.jsx)(sU,{className:"h-3 w-3 mr-2"}),n]},s)})]})]})}),(0,O.jsx)(uA,{className:"text-muted-foreground text-[10.5px] font-mono",children:new Date(e.created_at).toLocaleDateString()}),(0,O.jsx)(uA,{className:"w-10",onClick:e=>e.stopPropagation(),children:(0,O.jsxs)("div",{className:"flex items-center gap-0.5",children:[a?(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",title:"Unarchive",onClick:()=>i(e.id),children:(0,O.jsx)(Ef,{className:"h-3.5 w-3.5 text-muted-foreground"})}):(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",onClick:()=>n(e.id),children:(0,O.jsx)(sN,{className:"h-3.5 w-3.5 text-muted-foreground"})}),(0,O.jsx)(W.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",title:"Delete",onClick:()=>s(e.id),children:(0,O.jsx)(rc,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})})]})}let Em={todo:0,in_progress:1,done:2,cancelled:3},Eg={urgent:0,high:1,medium:2,low:3};function Ex({tasks:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,worktrees:o,onAssign:l}){let[c,d]=(0,$.useState)(null),[u,h]=(0,$.useState)("asc"),[f,p]=(0,$.useState)(null),[m,g]=(0,$.useState)(!1),x=e=>{c===e?h(e=>"asc"===e?"desc":"asc"):(d(e),h("asc"))},v=(0,$.useMemo)(()=>{if(!c)return e;let r="asc"===u?1:-1;return[...e].sort((e,s)=>{switch(c){case"title":return r*e.title.localeCompare(s.title);case"status":return r*(Em[e.status]-Em[s.status]);case"priority":return r*(Eg[e.priority]-Eg[s.priority]);case"created_at":return r*(new Date(e.created_at).getTime()-new Date(s.created_at).getTime());default:return 0}})},[e,c,u]),_=e=>c!==e?null:"asc"===u?" ↑":" ↓",y=(0,$.useMemo)(()=>new Set(e.filter(e=>null!==e.assigned_branch).map(e=>e.assigned_branch)),[e]);return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)(uk,{children:[(0,O.jsx)(uN,{children:(0,O.jsxs)(uD,{children:[(0,O.jsx)(uR,{className:"w-10"}),(0,O.jsxs)(uR,{className:"cursor-pointer select-none",onClick:()=>x("title"),children:["Title",_("title")]}),(0,O.jsxs)(uR,{className:"cursor-pointer select-none w-32",onClick:()=>x("status"),children:["Status",_("status")]}),(0,O.jsxs)(uR,{className:"cursor-pointer select-none w-28",onClick:()=>x("priority"),children:["Priority",_("priority")]}),(0,O.jsx)(uR,{className:"w-32",children:"Assign"}),(0,O.jsxs)(uR,{className:"cursor-pointer select-none w-28",onClick:()=>x("created_at"),children:["Created",_("created_at")]}),(0,O.jsx)(uR,{className:"w-10"})]})}),(0,O.jsxs)(uE,{children:[v.map(e=>(0,O.jsx)(Ep,{task:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,onClick:e=>{p(e),g(!0)},worktrees:o,assignedBranches:y,onAssign:l},e.id)),0===e.length&&(0,O.jsx)(uD,{children:(0,O.jsx)("td",{colSpan:7,className:"text-center text-muted-foreground py-12 text-sm",children:(0,O.jsxs)("div",{className:"flex flex-col items-center gap-1",children:[(0,O.jsx)("p",{className:"text-sm font-medium text-foreground/60",children:"No tasks yet"}),(0,O.jsx)("p",{className:"text-xs text-muted-foreground",children:"Create one to get started."})]})})})]})]}),(0,O.jsx)(su,{task:f,open:m,onOpenChange:g})]})}function Ev({open:e,onOpenChange:r,onSubmit:s}){let[n,i]=(0,$.useState)(""),[a,o]=(0,$.useState)("todo"),[l,c]=(0,$.useState)("medium");return(0,O.jsx)(t8,{open:e,onOpenChange:r,children:(0,O.jsxs)(rr,{className:"sm:max-w-md max-h-[85vh] flex flex-col",children:[(0,O.jsx)(rs,{children:(0,O.jsx)(ri,{children:"Create Task"})}),(0,O.jsxs)("form",{onSubmit:e=>{e.preventDefault(),n.trim()&&(s({description:n.trim(),status:a,priority:l}),i(""),o("todo"),c("medium"),r(!1))},className:"space-y-4 overflow-y-auto min-h-0 px-0.5",children:[(0,O.jsx)("div",{className:"space-y-2",children:(0,O.jsx)(rl,{placeholder:"Describe the task...",value:n,onChange:e=>i(e.target.value),className:"max-h-[40vh] focus-visible:border-input focus-visible:ring-0",rows:3,autoFocus:!0})}),(0,O.jsxs)("div",{className:"flex gap-3",children:[(0,O.jsxs)("div",{className:"flex-1 space-y-1",children:[(0,O.jsx)("label",{className:"text-xs text-muted-foreground",children:"Status"}),(0,O.jsxs)(hw,{value:a,onValueChange:e=>o(e),children:[(0,O.jsx)(hj,{children:(0,O.jsx)(hS,{})}),(0,O.jsx)(hC,{children:sc.map(e=>(0,O.jsx)(hk,{value:e,children:so[e].label},e))})]})]}),(0,O.jsxs)("div",{className:"flex-1 space-y-1",children:[(0,O.jsx)("label",{className:"text-xs text-muted-foreground",children:"Priority"}),(0,O.jsxs)(hw,{value:l,onValueChange:e=>c(e),children:[(0,O.jsx)(hj,{children:(0,O.jsx)(hS,{})}),(0,O.jsx)(hC,{children:sd.map(e=>(0,O.jsx)(hk,{value:e,children:sl[e].label},e))})]})]})]}),(0,O.jsxs)(rn,{children:[(0,O.jsx)(W.Button,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),(0,O.jsx)(W.Button,{type:"submit",disabled:!n.trim(),children:"Create"})]})]})]})})}let E_=[{value:"all",label:"All"},{value:"todo",label:"Todo"},{value:"in_progress",label:"Doing"},{value:"done",label:"Done"},{value:"cancelled",label:"Cancelled"},{value:"archived",label:"Archived"}];function Ey({projectId:e,tasks:r,loading:s,worktrees:n,onCreateTask:i,onUpdateTask:a,onDeleteTask:o,onArchiveTask:l,onUnarchiveTask:c}){let[d,u]=(0,$.useState)(!1),[h,f]=(0,$.useState)("all"),p=(0,$.useMemo)(()=>r.filter(e=>null===e.archived_at),[r]),m=(0,$.useMemo)(()=>r.filter(e=>null!==e.archived_at),[r]),g=(0,$.useMemo)(()=>{let e={all:p.length,todo:0,in_progress:0,done:0,cancelled:0,archived:m.length};for(let r of p)e[r.status]++;return e},[p,m]),x=(0,$.useMemo)(()=>"archived"===h?m:"all"===h?p:p.filter(e=>e.status===h),[p,m,h]),v="archived"===h;return e?(0,O.jsxs)("div",{className:"flex flex-col h-full",children:[(0,O.jsx)(dh,{title:"Tasks",count:p.length,actions:(0,O.jsxs)(W.Button,{size:"sm",onClick:()=>u(!0),className:"shadow-sm",children:[(0,O.jsx)(eS,{className:"h-3.5 w-3.5 mr-1.5"}),"New Task"]})}),(0,O.jsx)(df,{children:E_.map(e=>(0,O.jsx)(dp,{active:h===e.value,count:g[e.value],onClick:()=>f(e.value),children:e.label},e.value))}),(0,O.jsx)("div",{className:"flex-1 overflow-auto px-5 edge-scrollbar",children:s?(0,O.jsx)("div",{className:"flex items-center justify-center py-12 text-muted-foreground text-sm",children:"Loading tasks..."}):(0,O.jsx)(Ex,{tasks:x,onUpdate:a,onDelete:o,onArchive:l,onUnarchive:c,archivedView:v,worktrees:n,onAssign:(e,r)=>{a(e,{assigned_branch:r})}})}),(0,O.jsx)(Ev,{open:d,onOpenChange:u,onSubmit:i})]}):(0,O.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,O.jsxs)("div",{className:"text-center",children:[(0,O.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,O.jsx)(eS,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,O.jsx)("p",{className:"text-sm",children:"Select a project to view tasks."})]})})}var Eb=e.i(115796);function Ew({open:e,onOpenChange:r,onNavigateProject:s,onNavigateWorkspace:n,onNavigateSession:i}){let[a,o]=(0,$.useState)(""),[l,c]=(0,$.useState)(null),[d,u]=(0,$.useState)(!1),h=(0,$.useRef)(null),f=(0,$.useRef)(null),p=(0,$.useRef)("");(0,$.useLayoutEffect)(()=>{p.current=a},[a]),(0,sC.useGlobalEventStream)(e=>{if("session:title"!==e.type||"string"!=typeof e.sessionId)return;let r="string"==typeof e.title?e.title.trim():"";(0,Eb.updateCachedSessionTitle)(e.sessionId,r||null)});let[m,g]=(0,$.useState)(e);e!==m&&(g(e),e&&(o(""),c((0,Eb.getCachedEmptyResults)()),u(!1)));let x=(0,$.useCallback)(async e=>{h.current?.abort();let r=new AbortController;h.current=r;let s=""===e?(0,Eb.beginEmptyQuerySearch)():null;try{let n=await (0,rv.searchAll)(e,{signal:r.signal});r.signal.aborted||(null!==s&&(0,Eb.commitEmptyQueryResults)(s,n),c(n),u(!1))}catch{r.signal.aborted||u(!0)}},[]),v=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let r=e&&!v.current;if(v.current=e,e)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>void x(a),150*!r),()=>{f.current&&clearTimeout(f.current)}},[a,e,x]),(0,$.useEffect)(()=>{if(!e)return;let r=!1;return(0,rv.refreshSearchCache)().then(()=>{r||x(p.current)}).catch(()=>{}),()=>{r=!0,h.current?.abort()}},[e,x]);let _=l?a.trim()?{sessions:l.sessions,favorites:l.favorites}:(0,Eb.overlayRecents)(l):null,y=null===l,b=!!_&&0===l.projects.length&&0===l.workspaces.length&&0===_.sessions.length&&0===_.favorites.length,w=l?.cacheState==="cold",S=e=>(0,O.jsxs)(w9,{value:`session-${e.sessionId}`,onSelect:()=>i(e),children:[(0,O.jsx)(sD,{}),(0,O.jsx)("span",{className:"truncate",children:e.title??"Untitled session"}),e.favoritedAt&&(0,O.jsx)(NJ,{className:"h-3.5 w-3.5 shrink-0 fill-current text-amber-500"}),(0,O.jsxs)("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:[e.projectName," · ",e.branch??"main"," · ",function(e){if(!e)return"";let r=Date.now()-e;return r<6e4?"just now":r<36e5?`${Math.floor(r/6e4)}m ago`:r<864e5?`${Math.floor(r/36e5)}h ago`:`${Math.floor(r/864e5)}d ago`}(e.lastActiveAt)]})]},e.sessionId);return(0,O.jsxs)(w3,{open:e,onOpenChange:r,title:"Quick Switcher",description:"Search projects, workspaces, and sessions",shouldFilter:!1,className:"top-[max(1rem,calc(50%_-_175px))] translate-y-0",children:[(0,O.jsx)(w4,{placeholder:"Search projects, workspaces, sessions…",value:a,onValueChange:o}),(0,O.jsxs)(w6,{children:[d&&(0,O.jsxs)("div",{className:"flex items-center justify-between gap-2 px-4 py-3 text-sm text-destructive",children:[(0,O.jsx)("span",{children:"Search failed."}),(0,O.jsx)(W.Button,{variant:"link",size:"sm",className:"h-auto p-0 text-destructive",onClick:()=>void x(p.current),children:"Retry"})]}),!d&&y&&(0,O.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"}),"Searching…"]}),!d&&!y&&b&&w&&(0,O.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,O.jsx)(sj,{className:"h-4 w-4 animate-spin"}),"Syncing history…"]}),!d&&!y&&b&&!w&&(0,O.jsx)(w7,{children:"No results found."}),l&&l.projects.length>0&&(0,O.jsx)(w8,{heading:"Projects",children:l.projects.map(e=>(0,O.jsxs)(w9,{value:`project-${e.id}`,onSelect:()=>s(e.id),children:[(0,O.jsx)(c9,{name:e.name,size:"md"}),(0,O.jsx)("span",{children:e.name}),e.path&&(0,O.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:e.path})]},e.id))}),l&&l.workspaces.length>0&&(0,O.jsx)(w8,{heading:"Workspaces",children:l.workspaces.map(e=>(0,O.jsxs)(w9,{value:`ws-${e.projectId}-${e.targetId}-${e.branch??""}`,onSelect:()=>n(e),children:[(0,O.jsx)(sU,{}),(0,O.jsx)("span",{children:e.branch??"main"}),(0,O.jsx)("span",{className:"text-xs text-muted-foreground",children:e.projectName})]},`${e.projectId}-${e.targetId}-${e.branch??""}`))}),_&&_.sessions.length>0&&(0,O.jsx)(w8,{heading:a.trim()?"Sessions":"Recent",children:_.sessions.map(S)}),_&&_.favorites.length>0&&(0,O.jsx)(w8,{heading:"Favorites",children:_.favorites.map(S)})]})]})}let ES={session_result_ready:"/sounds/sound1.mp3",review_ready:"/sounds/sound2.mp3",session_failed:"/sounds/failure.mp3",workflow_failed:"/sounds/failure.mp3"};function Ej(e,r){let s=[...e.filter(e=>e.id!==r.id),r];return s.sort((e,r)=>r.created_at-e.created_at||(e.id<r.id?1:-1)),s}let EC=new Set(["session_result_ready","session_failed"]);function Ek(e){return EC.has(e.kind)&&e.session_id?`${e.kind}:${e.session_id}`:e.id}function EN(e){let r=new Map;for(let s of e){let e=null===s.read_at,n=r.get(Ek(s));n?(n.ids.push(s.id),n.count+=1,e&&(n.unreadCount+=1,n.unread=!0)):r.set(Ek(s),{latest:s,ids:[s.id],count:1,unreadCount:+!!e,unread:e})}return[...r.values()]}let EE=new Map,ED=new Set,ER=(0,ew.default)("bell",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]]),EA={session_result_ready:{label:"Session result is ready",dot:"bg-lime-400"},review_ready:{label:"Review feedback is ready",dot:"bg-emerald-500"},session_failed:{label:"Session failed",dot:"bg-destructive"},workflow_failed:{label:"Workflow needs attention",dot:"bg-destructive"}};function ET({notifications:e,unreadCount:r,projects:s,onNavigate:n,markRead:i,markAllRead:a,remove:o,clear:l}){let[c,d]=(0,$.useState)(!1);return(0,$.useEffect)(()=>{let e=e=>{"j"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),d(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,O.jsxs)(a4,{open:c,onOpenChange:d,children:[(0,O.jsx)(a6,{asChild:!0,children:(0,O.jsxs)(W.Button,{variant:"ghost",size:"icon-sm",className:"relative",title:"Notifications (⌘J)","aria-label":r>0?`${r} unread notifications`:"Notifications",children:[(0,O.jsx)(ER,{className:"h-4 w-4"}),r>0&&(0,O.jsx)("span",{className:"absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[9px] font-semibold leading-none text-primary-foreground",children:r>9?"9+":r})]})}),(0,O.jsxs)(a7,{align:"end",className:"w-80 p-0",children:[(0,O.jsxs)("div",{className:"flex items-center justify-between px-3 py-2",children:[(0,O.jsx)("span",{className:"text-[12.5px] font-semibold text-foreground",children:"Notifications"}),e.length>0&&(0,O.jsxs)("div",{className:"flex items-center gap-1",children:[(0,O.jsxs)("button",{onClick:a,disabled:0===r,className:"flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40",title:"Mark all read",children:[(0,O.jsx)(de,{className:"h-3 w-3"}),"Mark all read"]}),(0,O.jsx)("button",{onClick:l,className:"rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",title:"Dismiss all (marks them read)",children:"Clear"})]})]}),(0,O.jsx)("div",{className:"max-h-[60vh] overflow-y-auto border-t border-border",children:0===e.length?(0,O.jsx)("div",{className:"px-3 py-8 text-center text-[12px] text-muted-foreground/70",children:"Nothing needs your attention."}):EN(e).map(e=>{let r,a=e.latest,l=EA[a.kind],c=e.unread;return(0,O.jsxs)(a8,{onSelect:()=>{for(let r of e.ids)i(r);n(a.project_id,a.branch,a.session_id)},className:(0,ey.cn)("group flex flex-col items-start gap-0.5 rounded-none px-3 py-2",c&&"bg-primary/[0.08]"),children:[(0,O.jsxs)("div",{className:"flex w-full items-center gap-2",children:[(0,O.jsx)("span",{className:(0,ey.cn)("h-[7px] w-[7px] shrink-0 rounded-full",l?.dot)}),(0,O.jsx)("span",{className:(0,ey.cn)("min-w-0 flex-1 truncate text-[12.5px]",c?"font-medium text-foreground":"text-foreground/70"),children:a.body??(r=a.project_id,s.find(e=>e.id===r)?.name??"Unknown project")}),e.unreadCount>1&&(0,O.jsxs)("span",{className:"shrink-0 rounded-full bg-muted px-1.5 text-[10px] font-medium leading-4 text-muted-foreground",title:`${e.unreadCount} new notifications, showing the latest`,children:["×",e.unreadCount]}),(0,O.jsx)("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:function(e){let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return"just now";let s=Math.round(r/60);if(s<60)return`${s}m ago`;let n=Math.round(s/60);if(n<24)return`${n}h ago`;let i=Math.round(n/24);return`${i}d ago`}(a.created_at)}),(0,O.jsx)("button",{onClick:r=>{for(let s of(r.stopPropagation(),e.ids))o(s)},className:"shrink-0 rounded p-0.5 text-muted-foreground/60 opacity-0 transition-all hover:bg-muted hover:text-foreground group-hover:opacity-100",title:"Dismiss (marks it read)",children:(0,O.jsx)(t7,{className:"h-3 w-3"})})]}),(0,O.jsxs)("div",{className:"flex w-full items-center gap-1.5 pl-[15px] text-[11px] text-muted-foreground",children:[(0,O.jsx)("span",{className:"font-mono truncate",children:a.branch??"main"}),(0,O.jsx)("span",{className:"text-muted-foreground/50",children:"·"}),(0,O.jsx)("span",{className:"shrink-0",children:l?.label??a.title})]})]},a.id)})})]})]})}let EM=(0,ew.default)("keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]),EF=(e,r)=>e?`⌘${r}`:`Ctrl+${r}`,EP=()=>()=>{};function EI(){let[e,r]=(0,$.useState)(!1),s=(0,$.useSyncExternalStore)(EP,_1,()=>!1);return(0,$.useEffect)(()=>{let e=e=>{let s,n="/"===e.key&&(e.metaKey||e.ctrlKey)&&!e.shiftKey&&!e.altKey,i="?"===e.key&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!((s=e.target)instanceof HTMLElement&&("INPUT"===s.tagName||"TEXTAREA"===s.tagName||"SELECT"===s.tagName||s.isContentEditable));(n||i)&&(e.preventDefault(),r(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(W.Button,{variant:"ghost",size:"icon-sm","aria-label":"Keyboard shortcuts",title:"Keyboard shortcuts (?)",onClick:()=>r(!0),children:(0,O.jsx)(EM,{className:"h-4 w-4"})}),(0,O.jsx)(t8,{open:e,onOpenChange:r,children:(0,O.jsxs)(rr,{className:"sm:max-w-xl",children:[(0,O.jsx)(rs,{children:(0,O.jsx)(ri,{children:"Keyboard shortcuts"})}),(0,O.jsx)("div",{className:"grid gap-x-8 gap-y-5 sm:grid-cols-2",children:[{title:"Global",entries:[{hints:[EF(s,"K")],description:"Quick switcher"},{hints:[EF(s,"J")],description:"Notifications"},{hints:[EF(s,"B")],description:"Toggle sidebar"},{hints:[s?`⌘⇧O`:"Ctrl+Shift+O"],description:"New agent conversation"},{hints:["?",EF(s,"/")],description:"This dialog"}]},{title:"Workspace tabs",entries:_Q.map(e=>({hints:[_5(s,e.code)],description:`Open ${e.label}`}))}].map(e=>(0,O.jsxs)("section",{children:[(0,O.jsx)("h3",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:e.title}),(0,O.jsx)("ul",{className:"space-y-1.5",children:e.entries.map(e=>(0,O.jsxs)("li",{className:"flex items-center justify-between gap-3 text-[13px]",children:[(0,O.jsx)("span",{className:"text-foreground/90",children:e.description}),(0,O.jsx)("span",{className:"flex shrink-0 items-center gap-1",children:e.hints.map(e=>(0,O.jsx)("kbd",{className:"rounded-md border border-border bg-muted px-1.5 py-0.5 font-mono text-[11px] leading-none text-foreground/80",children:e},e))})]},e.description))})]},e.title))})]})})]})}function EB(e){if(null===e)return"尚未连接";let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return`${r} 秒前`;let s=Math.floor(r/60);return s<60?`${s} 分钟前`:`${Math.floor(s/60)} 小时前`}function EL(){let{state:e,lastEventAt:r,reconnect:s}=(0,sC.useConnectionStatus)(),[,n]=(0,$.useState)(0);if((0,$.useEffect)(()=>{let e=setInterval(()=>n(e=>e+1),5e3);return()=>clearInterval(e)},[]),"stale"===e)return(0,O.jsxs)("button",{type:"button",onClick:s,title:`实时更新已断开 \xb7 上次更新 ${EB(r)} \xb7 点击重新连接`,className:"flex items-center gap-1.5 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-600 transition-colors hover:bg-amber-500/20",children:[(0,O.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500"}),"实时更新已断开"]});let i="live"===e;return(0,O.jsx)("span",{title:i?`实时更新正常 \xb7 上次更新 ${EB(r)}`:"正在连接实时更新…",className:"flex items-center px-1","aria-label":i?"实时更新正常":"正在连接实时更新",children:(0,O.jsx)("span",{className:i?"h-1.5 w-1.5 rounded-full bg-emerald-500":"h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground/40"})})}let Ez=new Set(["workspace","tasks","schedules","remote-servers","settings","project-info","project-chat"]),EO="tasks";function E$(e){return e.length>0&&e.trim()===e&&!/[\u0000-\u001f\u007f/\\]/.test(e)}function EW(){let e=window.location.pathname,r=new URLSearchParams(window.location.search),s=r.get("project");if(s){let e=r.get("tab");return{projectId:s,tab:e&&Ez.has(e)?e:EO,branch:r.get("branch"),threadId:null}}let n=e.split("/").filter(Boolean);if(1===n.length&&Ez.has(n[0])){let e=n[0];if("remote-servers"===e||"settings"===e)return{projectId:null,tab:e,branch:null,threadId:null}}let i=null,a=EO,o=null;if("p"===n[0]&&n[1]){i=n[1];let e=n[2];if("chat"===e&&4===n.length&&n[3])try{let e=decodeURIComponent(n[3]);E$(e)?(o=e,a="project-chat"):a="project-info"}catch{a="project-info",o=null}else"chat"===e?a="project-info":e&&Ez.has(e)&&"project-chat"!==e&&(a=e)}return{projectId:i,tab:a,branch:r.get("branch"),threadId:o}}function EH(e){let{projectId:r,tab:s,branch:n,threadId:i}=e;if("remote-servers"===s||"settings"===s)return`/${s}`;if(!r)return"/";if("project-chat"===s)return i&&E$(i)?`/p/${r}/chat/${encodeURIComponent(i)}`:`/p/${r}/project-info`;let a=`/p/${r}/${s??EO}`;return n&&(a+=`?branch=${encodeURIComponent(n)}`),a}function EU(e){return null===e?"":e}function Eq(e,r,s,n){return!!e&&e.projectId===r&&e.branch===s&&e.sessionId===n}function EK(){var e,r,s,n,i,a,o;let l,c,d,u,h,f,p,m,g,x,v,_,y,b,w,S,j,{projectId:C,tab:k,branch:N,threadId:E}=function(){let[e,r]=(0,$.useState)(EW);return(0,$.useEffect)(()=>{let e=()=>r(EW());return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]),e}(),{config:D}=(0,hL.useAppConfig)(),[R,A]=(0,$.useState)(()=>new URLSearchParams(window.location.search).get("session")),[T,M]=(0,$.useState)(null),F=(0,$.useCallback)(e=>{A(e);let r=new URL(window.location.href);e?r.searchParams.set("session",e):r.searchParams.delete("session"),window.history.replaceState(null,"",r.toString())},[]);(0,$.useEffect)(()=>{let e=()=>{A(new URLSearchParams(window.location.search).get("session"))};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]),(0,$.useEffect)(()=>{if(new URLSearchParams(window.location.search).has("project")){let e=EH({projectId:C,tab:k,branch:N,threadId:E});window.history.replaceState(null,"",e)}},[]);let[P,I]=(0,$.useState)(!1),[B,L]=(0,$.useState)(!1),[z,H]=(0,$.useState)(!1),[U,q]=(0,$.useState)(null),[K,V]=(0,$.useState)(N),[Y,G]=(0,$.useState)(k),[X,J]=(0,$.useState)(E),[Z,Q]=(0,$.useState)(0),[ee,et]=(0,$.useState)(0),[er,es]=(0,$.useState)(!1),en=(0,$.useRef)(null),[ei,ea]=(0,$.useState)(void 0),[eo,el]=(0,$.useTransition)(),{projects:ec,currentProject:ed,loading:eu,addProject:eh,createProject:ef,updateProject:ep,deleteProject:em,selectProject:eg,routeProjectPending:ex,routeProjectNotFound:ev}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(null),[a,o]=(0,$.useState)(!0),[l,c]=(0,$.useState)(e),d=(0,$.useRef)(n),u=(0,$.useRef)(e);d.current=n,u.current=e;let h=l!==e,f=a||h,p=!f&&!!e&&!r.some(r=>r.id===e),m=(0,$.useCallback)(async()=>{o(!0);try{let e=await rv.api.getProjects();if(s(e),e.length>0&&!d.current){let r=u.current?e.find(e=>e.id===u.current):e[0];i(r??null)}}finally{o(!1)}},[]);(0,$.useEffect)(()=>{m()},[m]),(0,$.useEffect)(()=>{h&&!a&&(c(e),i(e?r.find(r=>r.id===e)??null:r[0]??null))},[e,a,r,h]);let g=async(e,r)=>{let a=await rv.api.updateProject(e,r);return s(r=>r.map(r=>r.id===e?a:r)),n?.id===e&&i(a),a},x=async e=>{await rv.api.deleteProject(e),s(r=>r.filter(r=>r.id!==e)),n?.id===e&&i(r.find(r=>r.id!==e)??null)};return{projects:r,currentProject:h?null:n,routeProjectPending:f,routeProjectNotFound:p,loading:a,addProject:e=>{s(r=>[e,...r]),i(e)},createProject:async e=>{let r=await rv.api.createProject(e);return s(e=>[r,...e]),i(r),r},updateProject:g,deleteProject:x,selectProject:e=>{i(e)},refresh:m}}(C);ed?.id!==ei&&(void 0!==ei&&V(null),ea(ed?.id));let{worktrees:e_,loading:ey,refetch:eb}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),[o,l]=(0,$.useState)(null),c=(0,$.useRef)(0),d=(0,$.useRef)(null),u=(0,$.useRef)(null),h=(0,$.useRef)(r);h.current=r;let f=(0,$.useCallback)(async(r=!1)=>{if(r&&d.current)return;d.current?.abort();let s=new AbortController;d.current=s;let i=c.current;if(!e){d.current=null,n([]),l(null),a(!1);return}r||a(!0);try{let a=await rv.api.getProjectWorktrees(e,void 0,s.signal);if(i!==c.current)return;n(e=>{let s=r?function(e,r,s){if(void 0===s||r.some(e=>e.branch===s))return r;let n=e.findIndex(e=>e.branch===s);if(n<0)return r;let i=[...r];return i.splice(Math.min(n,i.length),0,e[n]),i}(e,a,h.current):a;return e.length===s.length&&e.every((e,r)=>e.branch===s[r].branch&&e.currentBranch===s[r].currentBranch&&e.expectedBranch===s[r].expectedBranch)?e:s})}catch(e){if(i!==c.current||e instanceof Error&&"AbortError"===e.name)return;console.error("Failed to fetch worktrees:",e),r||n([{branch:null}])}finally{if(i!==c.current||d.current!==s)return;l(e),r||a(!1),d.current=null}},[e]);return(0,$.useEffect)(()=>(f(),()=>{d.current?.abort(),d.current=null,c.current+=1}),[f]),(0,$.useEffect)(()=>{let s=u.current;u.current={projectId:e,branch:r},s&&s.projectId===e&&s.branch!==r&&f(!0)},[e,r,f]),(0,sC.useGlobalEventStream)(r=>{if(!e||r.projectId!==e)return;let s="session:status"===r.type&&("stopped"===r.status||"error"===r.status);("session:taskCompleted"===r.type||"executor:stopped"===r.type||s)&&f(!0)}),(0,$.useEffect)(()=>{let e=null,r=()=>{null!==e&&(window.clearInterval(e),e=null)},s=()=>{r(),e=window.setInterval(()=>void f(!0),3e5)},n=()=>void f(!0),i=()=>{"visible"===document.visibilityState?(f(!0),s()):r()};return window.addEventListener("focus",n),document.addEventListener("visibilitychange",i),"visible"===document.visibilityState&&s(),()=>{r(),window.removeEventListener("focus",n),document.removeEventListener("visibilitychange",i)}},[f]),{worktrees:s,loading:i||o!==e,refetch:(0,$.useCallback)(()=>f(!1),[f])}}(ed?.id??null,K),{statuses:ew,defaultTarget:ej,repositoryLabel:eC,setTarget:ek,refetch:eN}=function(e,r){let[s,n]=(0,$.useState)(new Map),[i,a]=(0,$.useState)(null),[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(0),[u,h]=(0,$.useState)(e);e!==u&&(h(e),n(new Map),a(null),l(null));let f=(0,$.useCallback)(()=>d(e=>e+1),[]);return(0,$.useEffect)(()=>{let s=r.map(e=>e.branch).filter(e=>null!==e),i=!1;return(async()=>{if(!e||0===s.length){i||(n(new Map),a(null),l(null));return}if(c1(e).length>0&&(await function(e){let r=c2.get(e);if(r)return r;let s=(async()=>{let r=new Map;for(;;){let s=c1(e).filter(({key:e,target:s})=>r.get(e)!==s);if(0===s.length)break;for(let{key:n,branch:i,target:a}of s){r.set(n,a);let s=!1;try{s=await rv.api.setMergeTarget(e,i,a,{ifAbsent:!0})}catch{}if(s)try{localStorage.getItem(n)===a&&localStorage.removeItem(n)}catch{}}}})();return c2.set(e,s),s.finally(()=>{c2.get(e)===s&&c2.delete(e)}),s}(e),i))return;let r=s.map(e=>({branch:e})),o=await rv.api.getMergeStatus(e,r);i||o.ok&&(n(function(e){let r=new Map;for(let s of e){if("target-not-found"===s.error&&s.requestedTarget){r.set(s.branch,{branch:s.branch,error:s.error,requestedTarget:s.requestedTarget,targetSource:s.targetSource});continue}!s.error&&s.target&&s.status&&r.set(s.branch,{branch:s.branch,status:s.status,unmergedCount:s.unmergedCount??0,dirty:s.dirty??!1,target:s.target})}return r}(o.entries)),a(function(e){for(let r of e)if("default"===r.targetSource&&r.target)return r.target;return null}(o.entries)),l(o.repository.label))})(),()=>{i=!0}},[e,r,c,f]),{statuses:s,defaultTarget:i,repositoryLabel:o,setTarget:(0,$.useCallback)((r,s)=>{e&&rv.api.setMergeTarget(e,r,s).then(e=>{e&&f()})},[e,f]),refetch:f}}(ed?.id??null,e_),eE=function(e,r,s){let n=(0,$.useMemo)(()=>r?.map(e=>e.branch)??[],[r]),[i,a]=(0,$.useState)([]),o=(0,$.useCallback)(async()=>{if(!e||0===n.length)return void a([]);let r=await Promise.all(n.map(async r=>(await (0,rv.listBranchSessions)(e,r)).sessions.filter(e=>e.processAlive).map(s=>({id:s.id,projectId:e,branch:r,title:s.title?.trim()||"New Session",status:s.status,processAlive:!0,updated_at:s.updated_at}))));a(e=>{var s;let n;return s=r.flat(),n=new Map(e.map(e=>[e.id,e])),s.map(e=>{let r=n.get(e.id);return r&&"New Session"===e.title&&"New Session"!==r.title?{...e,title:r.title}:e})})},[n,e]);(0,$.useEffect)(()=>{let e=!1;return o().catch(r=>{e||console.warn("[ResidentSessions] refresh failed:",r)}),()=>{e=!0}},[o]);let{state:l}=(0,sC.useConnectionStatus)(),c=(0,$.useRef)(null),d=(0,$.useRef)(!1);return(0,$.useEffect)(()=>{var e;let r=c.current;c.current=l;let s=(e=d.current,"live"===l&&e&&"live"!==r);"live"===l&&(d.current=!0),s&&o().catch(e=>console.warn("[ResidentSessions] reconnect refresh failed:",e))},[l,o]),(0,$.useEffect)(()=>{s&&s.processAlive&&e&&s.projectId===e&&a(e=>(function(e,r){let s=e.findIndex(e=>e.id===r.id);if(-1===s)return[r,...e];let n=e[s],i="New Session"===r.title&&"New Session"!==n.title?n.title:r.title,a=[...e];return a[s]={...r,title:i,status:n.status},a})(e,s))},[e,s]),(0,sC.useGlobalEventStream)(r=>{if(e&&r.projectId===e){if("session:process"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null,s="boolean"==typeof r.alive?r.alive:null,n="string"==typeof r.branch?r.branch:null;if(!e||null===s)return;if(!s)return void a(r=>r.filter(r=>r.id!==e));o().catch(e=>console.warn("[ResidentSessions] process refresh failed:",e)),null!==n&&a(r=>r.map(r=>r.id===e?{...r,branch:n}:r))}if("session:status"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null,s="string"==typeof r.status?r.status:null;if(!e||!s)return;a(r=>r.map(r=>r.id===e?{...r,status:s}:r))}if("session:title"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null;if(!e)return;a(s=>{var n,i;return i=("string"==typeof(n=r.title)?n.trim():"")||"New Session",s.map(r=>r.id===e?{...r,title:i}:r)})}}}),(0,$.useMemo)(()=>{let e=new Map;for(let r of i){let s=r.branch??"",n=e.get(s)??[];n.push(r),e.set(s,n)}for(let r of e.values())r.sort((e,r)=>(r.updated_at??"").localeCompare(e.updated_at??""));return e},[i])}(ed?.id??null,e_,T),{tasks:eD,loading:eR,createTask:eA,updateTask:eT,deleteTask:eM,archive:eF,unarchive:eP,refetch:eI}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(!0),a=(0,$.useCallback)(async()=>{if(!e){s([]),i(!1);return}try{let r=await rv.api.getTasks(e,{includeArchived:!0});s(r)}catch(e){console.error("Failed to fetch tasks:",e)}finally{i(!1)}},[e]);(0,$.useEffect)(()=>{a()},[a]);let o=(0,$.useCallback)(async r=>{if(!e)return null;try{let n=await rv.api.createTask(e,r);return s(e=>[...e,n]),n}catch(e){return console.error("Failed to create task:",e),null}},[e]),l=(0,$.useCallback)(async(e,n)=>{s(r=>r.map(r=>r.id===e?{...r,...n,updated_at:new Date().toISOString()}:r));try{let r=await rv.api.updateTask(e,n);return s(s=>s.map(s=>s.id===e?r:s)),r}catch(e){return console.error("Failed to update task:",e),s(r),null}},[r]),c=(0,$.useCallback)(async e=>{s(r=>r.filter(r=>r.id!==e));try{await rv.api.deleteTask(e)}catch(e){console.error("Failed to delete task:",e),s(r)}},[r]),d=(0,$.useCallback)(async e=>{s(r=>r.map(r=>r.id===e?{...r,archived_at:Date.now()}:r));try{let r=await rv.api.archiveTask(e);s(s=>s.map(s=>s.id===e?r:s))}catch(e){console.error("Failed to archive task:",e),s(r)}},[r]),u=(0,$.useCallback)(async e=>{s(r=>r.map(r=>r.id===e?{...r,archived_at:null}:r));try{let r=await rv.api.unarchiveTask(e);s(s=>s.map(s=>s.id===e?r:s))}catch(e){console.error("Failed to unarchive task:",e),s(r)}},[r]),h=(0,$.useCallback)(async n=>{if(e){s(n.map(e=>r.find(r=>r.id===e)).filter(e=>void 0!==e));try{await rv.api.reorderTasks(e,n)}catch(e){console.error("Failed to reorder tasks:",e),s(r)}}},[e,r]);return{tasks:r,loading:n,createTask:o,updateTask:l,deleteTask:c,archive:d,unarchive:u,reorderTasks:h,refetch:a}}(ed?.id??null),{schedules:eB,loading:eL,createSchedule:ez,updateSchedule:eO,deleteSchedule:e$,runNow:eW}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(!1),a=(0,$.useRef)(e),o=(0,$.useRef)(0),l=(0,$.useCallback)(async(e,r,n)=>{if(!e){o.current===r&&(s([]),i(!1));return}n&&i(!0);try{let n=await rv.api.getSchedules(e);o.current===r&&s(n)}catch(e){console.error("Failed to fetch schedules:",e)}finally{n&&o.current===r&&i(!1)}},[]);(0,$.useEffect)(()=>{a.current=e,o.current+=1,l(e,o.current,!0)},[e,l]);let c=(0,$.useCallback)(async()=>{let e=a.current;e&&await l(e,o.current,!1)},[l]),d=(0,$.useRef)(c);(0,$.useEffect)(()=>{d.current=c},[c]),(0,sC.useGlobalEventStream)(e=>{!e.type?.startsWith("schedule:")||a.current&&e.projectId===a.current&&d.current()});let u=(0,$.useCallback)(async r=>{if(!e)throw Error("No project selected");let s=await rv.api.createSchedule(e,r);return await c(),s},[e,c]),h=(0,$.useCallback)(async(e,r)=>{let s=await rv.api.updateSchedule(e,r);return await c(),s},[c]),f=(0,$.useCallback)(async e=>{await rv.api.deleteSchedule(e),await c()},[c]),p=(0,$.useCallback)(async(e,r)=>{let s=r;if(!s){let e=crypto.randomUUID();s={requestId:e,runId:e}}let n=await rv.api.runScheduleNow(e,s);return await c(),n},[c]);return{schedules:r,loading:n,refetch:c,createSchedule:u,updateSchedule:h,deleteSchedule:f,runNow:p}}(ed?.id??null),[eH,eU]=(0,$.useState)(null),[eq,eK]=(0,$.useState)(null),[eV,eY]=(0,$.useState)(!1),[eG,eX]=(0,$.useState)(null),{activity:eJ,since:eZ,refetch:eQ,setOptimisticActivity:e0}=function(e){let[r,s]=(0,$.useState)(new Map),[n,i]=(0,$.useState)(new Map),a=(0,$.useRef)(new Map),o=(0,$.useRef)(new Map),l=(0,$.useRef)(null),c=(0,$.useCallback)(async()=>{if(!e){s(new Map),i(new Map),o.current=new Map,l.current=null,a.current=new Map;return}try{let r=await (0,rv.authFetch)(`${"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}/api/projects/${e}/branches/activity`);if(!r.ok)return;let n=await r.json(),c=l.current!==e,{nextActivity:d,nextSince:u}=function(e,r,s,n){let i=new Map,a=new Map,o=[];for(let l of e){let e=l.branch??"",c=s.get(e)??0;if(!n&&l.since<c){let s=r.get(e);if(void 0!==s){i.set(e,s),a.set(e,c);continue}}i.set(e,l.activity),a.set(e,l.since),n||r.get(e)===l.activity||o.push(l.branch)}return{nextActivity:i,nextSince:a,transitions:o}}(n.branches,o.current,a.current,c);s(d),i(u),o.current=d,l.current=e,a.current=u}catch{}},[e]);return(0,$.useEffect)(()=>{c()},[c]),(0,sC.useGlobalEventStream)(r=>{var n,l,c;let d,u;if("branch:activity"!==r.type||!e||r.projectId!==e)return;let h=(n=r,l=o.current,c=a.current,d=n.branch??"",u=c.get(d)??0,n.since<u?{kind:"stale"}:l.get(d)===n.activity?{kind:"redundant",key:d}:{kind:"transition",key:d});"stale"===h.kind||(a.current.set(h.key,r.since),i(new Map(a.current)),"redundant"!==h.kind&&s(e=>{let s=new Map(e);return s.set(h.key,r.activity),o.current=s,s}))}),{activity:r,since:n,refetch:c,setOptimisticActivity:(0,$.useCallback)((e,r)=>{s(s=>{let n=function(e,r,s){let n=r??"";if(e.get(n)===s)return e;let i=new Map(e);return i.set(n,s),i}(s,e,r);return o.current=n,n})},[])}}(ed?.id??null),{rules:e1,createRule:e2,updateRule:e5,deleteRule:e3}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),o=(0,$.useCallback)(async()=>{if(!e){n([]),a(!1);return}try{let s=await rv.api.getRules(e,r);n(s)}catch(e){console.error("Failed to fetch rules:",e)}finally{a(!1)}},[e,r]);(0,$.useEffect)(()=>{o()},[o]);let l=(0,$.useCallback)(async s=>{if(!e)return null;try{let i=await rv.api.createRule(e,{...s,branch:r});return n(e=>[...e,i]),i}catch(e){return console.error("Failed to create rule:",e),null}},[e,r]),c=(0,$.useCallback)(async(e,r)=>{n(s=>s.map(s=>s.id===e?{...s,...r,enabled:void 0!==r.enabled?+!!r.enabled:s.enabled,updated_at:new Date().toISOString()}:s));try{let s=await rv.api.updateRule(e,r);return n(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update rule:",e),n(s),null}},[s]),d=(0,$.useCallback)(async e=>{n(r=>r.filter(r=>r.id!==e));try{await rv.api.deleteRule(e)}catch(e){console.error("Failed to delete rule:",e),n(s)}},[s]);return{rules:s,loading:i,createRule:l,updateRule:c,deleteRule:d,refetch:o}}(ed?.id??null,K),{commands:e4,createCommand:e6,updateCommand:e7,deleteCommand:e8}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),o=(0,$.useCallback)(async()=>{if(!e){n([]),a(!1);return}try{let s=await rv.api.getCommands(e,r);n(s)}catch(e){console.error("Failed to fetch commands:",e)}finally{a(!1)}},[e,r]);(0,$.useEffect)(()=>{o()},[o]);let l=(0,$.useCallback)(async s=>{if(!e)return null;try{let i=await rv.api.createCommand(e,{...s,branch:r});return n(e=>[...e,i]),i}catch(e){return console.error("Failed to create command:",e),null}},[e,r]),c=(0,$.useCallback)(async(e,r)=>{n(s=>s.map(s=>s.id===e?{...s,...r,updated_at:new Date().toISOString()}:s));try{let s=await rv.api.updateCommand(e,r);return n(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update command:",e),n(s),null}},[s]),d=(0,$.useCallback)(async e=>{n(r=>r.filter(r=>r.id!==e));try{await rv.api.deleteCommand(e)}catch(e){console.error("Failed to delete command:",e),n(s)}},[s]);return{commands:s,loading:i,createCommand:l,updateCommand:c,deleteCommand:d,refetch:o}}(ed?.id??null,K),e9=(0,$.useRef)(null),te=(0,$.useSyncExternalStore)(j1,j2,j5),tt=ed?.id??null,tr=ed?.agent_mode??null,ts=(0,$.useCallback)(e=>!!tt&&te.has(j3(tt,e,tr)),[te,tt,tr]),tn=(0,$.useCallback)(e=>{if(tt)return te.get(j3(tt,e,tr))},[te,tt,tr]),ti=(0,$.useCallback)(e=>eZ.get(EU(e)),[eZ]),ta=(0,$.useMemo)(()=>(function(e,r,s,n){let i=new Map;if(!e)return i;for(let a of e){let e=EU(a.branch),o=r.get(e);if(!s?.(a.branch)){i.set(e,o??"idle");continue}if("main-running"===o)i.set(e,"main-running");else if("main-completed"===o){let r=n?.backendSince?.(a.branch)??0,s=n?.placeholderSince?.(a.branch)??0;i.set(e,s>r?"idle":"main-completed")}else i.set(e,"idle")}return i})(e_,eJ,ts,{backendSince:ti,placeholderSince:tn}),[e_,eJ,ts,ti,tn]);i=eN,a=ta,o=ed?.id??null,l=(0,$.useRef)(new Set),d=(c=function(e){let r=new Set;if(!e)return r;for(let[s,n]of e)c5.has(n)&&r.add(s);return r}(a)).size>0,u=JSON.stringify(Array.from(c).sort()),(0,$.useEffect)(()=>{let e=new Set(JSON.parse(u)),r=l.current;l.current=e,function(e,r){for(let s of e)if(!r.has(s))return!0;return!1}(r,e)&&i()},[u,i]),(0,$.useEffect)(()=>{let e=()=>i();return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[i]),(0,sC.useGlobalEventStream)(e=>{"executor:stopped"===e.type&&e.projectId===o&&i(),"merge-target:updated"===e.type&&null!==o&&e.projectId===o&&i()}),(0,$.useEffect)(()=>{let e=null,r=()=>{null!==e&&(clearInterval(e),e=null)},s=()=>{r(),e=setInterval(i,d?3e4:6e4)},n=()=>{"visible"===document.visibilityState?s():r()};return"visible"===document.visibilityState&&s(),document.addEventListener("visibilitychange",n),()=>{r(),document.removeEventListener("visibilitychange",n)}},[i,d]);let[to,tl]=(0,$.useState)(null),{notifications:tc,unreadCount:td,markRead:tu,markAllRead:th,remove:tf,clear:tp}=function(e){let[r,s]=(0,$.useState)([]),n=(0,$.useRef)(new Set),i=(0,$.useRef)(new Set);(0,$.useEffect)(()=>{for(let e of new Set(Object.values(ES)))EE.has(e)||ED.has(e)||(ED.add(e),(async()=>{try{let r=await fetch(e),s=await r.blob(),n=new Audio(URL.createObjectURL(s));n.preload="auto",n.load(),EE.set(e,n)}catch{}finally{ED.delete(e)}})())},[]);let a=(0,$.useRef)(e);(0,$.useEffect)(()=>{a.current=e},[e]);let o=(0,$.useCallback)(e=>{if(i.current.has(e))return;i.current.add(e);let r=Date.now();s(s=>s.map(s=>s.id===e&&null===s.read_at?{...s,read_at:r}:s)),(0,rv.markNotificationRead)(e).catch(()=>{s(s=>s.map(s=>s.id===e&&s.read_at===r?{...s,read_at:null}:s))}).finally(()=>{i.current.delete(e)})},[]);(0,$.useEffect)(()=>{let e=!1;return(0,rv.getNotifications)({limit:100}).then(r=>{if(!e){for(let e of r)n.current.add(e.id);s(e=>{let s=[];for(let e of r)s=Ej(s,e);for(let n of e)r.some(e=>e.id===n.id)||(s=Ej(s,n));return s});try{window.localStorage.removeItem("vibedeckx:completion-notifications")}catch{}}}).catch(e=>{console.warn("[notifications] hydration failed:",e)}),()=>{e=!0}},[]),(0,sC.useGlobalEventStream)(e=>{var r;let i;if("notification:created"!==e.type)return;let o=e.notification;if(!o?.id)return;let l=!n.current.has(o.id);n.current.add(o.id);let c=a.current,d=null!==o.session_id&&o.session_id===c;l&&(r=ES[o.kind],(i=EE.get(r))||((i=new Audio(r)).preload="auto",EE.set(r,i)),i.currentTime=0,i.play().catch(()=>{})),s(e=>Ej(e,d?{...o,read_at:o.read_at??Date.now()}:o)),d&&null===o.read_at&&(0,rv.markNotificationRead)(o.id).catch(()=>{})}),(0,$.useEffect)(()=>{if(e)for(let n of r){if(n.session_id!==e||null!==n.read_at||i.current.has(n.id))continue;let{id:r}=n;i.current.add(r),(0,rv.markNotificationRead)(r).then(()=>{s(e=>e.map(e=>e.id===r&&null===e.read_at?{...e,read_at:Date.now()}:e))}).catch(()=>{}).finally(()=>{i.current.delete(r)})}},[e,r]);let l=(0,$.useCallback)(e=>o(e),[o]),c=(0,$.useCallback)(()=>{let e=Date.now();s(r=>r.some(e=>null===e.read_at)?r.map(r=>null===r.read_at?{...r,read_at:e}:r):r),(0,rv.markAllNotificationsRead)().catch(()=>s(r))},[r]),d=(0,$.useCallback)(e=>{o(e),s(r=>r.filter(r=>r.id!==e))},[o]),u=(0,$.useCallback)(()=>{(0,rv.markAllNotificationsRead)().catch(e=>console.warn("[notifications] read-all failed:",e)),s(e=>e.length?[]:e)},[]),h=EN(r).reduce((e,r)=>e+ +!!r.unread,0);return{notifications:r,unreadCount:h,markRead:l,markAllRead:c,remove:d,clear:u}}("workspace"===Y?to:null),tm=(0,$.useMemo)(()=>tc.filter(e=>e.project_id===ed?.id&&null===e.read_at).length,[tc,ed?.id]),tg=(0,$.useCallback)(()=>{e0(K,"working")},[K,e0]),tx=(0,$.useRef)(null),tv=(0,$.useCallback)(()=>{eI()},[eI]),t_=(0,$.useCallback)((e,r,s)=>{tx.current={projectId:s??ed?.id,branch:e,sessionId:r},V(e),F(r),Q(e=>e+1),es(!1),(0,Eb.touchRecentSessionOpen)(r)},[ed?.id,F]),ty=(0,$.useCallback)(e=>{t_(e.branch,e.id),G("workspace")},[t_]),tb=(0,$.useCallback)(e=>{eQ();let r=ec.find(r=>r.id===e.projectId);(0,Eb.touchSessionStarted)({sessionId:e.id,projectId:e.projectId,projectName:r?.name??"",targetId:r?.agent_mode??"local",branch:e.branch}),!1!==e.processAlive&&M({id:e.id,projectId:e.projectId,branch:e.branch,title:"New Session",status:e.status,processAlive:!0,updated_at:new Date().toISOString()})},[eQ,ec]),tw=(0,$.useCallback)((e,r)=>{r.trim()&&(0,Eb.updateCachedSessionTitle)(e,r.trim()),ed?.id&&r.trim()&&M(s=>({id:e,projectId:ed.id,branch:s?.id===e?s.branch:K,title:r,status:s?.id===e?s.status:"running",processAlive:!0,updated_at:s?.id===e?s.updated_at:new Date().toISOString()}))},[ed?.id,K]),tS=(0,$.useCallback)(()=>{e0(K,"idle")},[K,e0]),tj=(0,$.useCallback)(()=>{eI()},[eI]);e=ed?.id??null,r={onTaskChanged:tj},h=(0,$.useRef)(r.onTaskChanged),(0,$.useEffect)(()=>{h.current=r.onTaskChanged}),(0,sC.useGlobalEventStream)(r=>{e&&r.projectId===e&&("task:created"===r.type||"task:updated"===r.type||"task:deleted"===r.type)&&h.current?.()});let tC=(0,$.useMemo)(()=>{let e=EU(K);return eD.find(r=>r.assigned_branch===e)??null},[eD,K]);(0,$.useCallback)(e=>{el(async()=>{await en.current?.submitMessage(e.description??e.title)})},[]),(0,$.useCallback)(e=>{eT(e,{assigned_branch:null})},[eT]);let tk=(0,$.useRef)(void 0);(0,$.useEffect)(()=>{if(ey||0===e_.length)return;let e=tk.current;if(void 0!==e){if(e_.some(r=>r.branch===e.branch)){tk.current=void 0,e.sessionId?t_(e.branch,e.sessionId):V(e.branch);return}tk.current=void 0,es(!1)}e_.some(e=>e.branch===K)||V(e_[0].branch)},[e_,ey,K,t_]),(0,$.useEffect)(()=>{er&&(null===K&&(ey||0!==e_.length)||es(!1))},[er,K,ey,e_]);let tN=(0,$.useCallback)((e,r,s=null)=>{if(G("workspace"),e===ed?.id)return void(s?t_(r,s):V(r));let n=ec.find(r=>r.id===e);n&&(s&&es(!0),tk.current={branch:r,sessionId:s},eg(n))},[ed?.id,ec,eg,t_]),[tE,tD]=(0,$.useState)(!1);(0,$.useEffect)(()=>{let e=e=>{if("k"===e.key&&(e.metaKey||e.ctrlKey)){e.preventDefault(),tD(e=>!e);return}"o"===e.key.toLowerCase()&&e.shiftKey&&(e.metaKey||e.ctrlKey)&&"workspace"===Y&&(e.preventDefault(),Q(e=>e+1),en.current?.startNewConversation())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[Y]);let tR=(0,$.useRef)(!1),tA=(0,$.useCallback)(async(e,r)=>{let s=ec.find(r=>r.id===e);if(!s)return null;let n="local"===r?"local":r;return(s.agent_mode??"local")!==n?ep(s.id,{agentMode:n}):s},[ec,ep]),tT=(s={projectId:ed?.id??null,resolveProjectForTarget:tA,getScheduleRun:rv.api.getScheduleRun,getSchedules:rv.api.getSchedules,runScheduleNow:eW,selectAgentSession:(e,r,s)=>{G("workspace"),t_(e,r,s)},openScheduleRun:(e,r)=>{eU(e),eK(r),G("schedules")},onRerunResult:e=>{e.replay&&e.status&&"starting"!==e.status&&"running"!==e.status?"completed"===e.status?_Z.toast.success("Schedule run already completed"):_Z.toast.error(`Schedule run already ${e.status}`):_Z.toast.success("Schedule run started")},onError:(e,r)=>{console.error(`Project activity ${e} failed:`,r),"session-navigation"===e?_Z.toast.error("Failed to open agent session"):"schedule-navigation"===e?_Z.toast.error("Failed to open schedule run"):_Z.toast.error(r instanceof Error?r.message:"Failed to start schedule run")}},(f=(0,$.useRef)(s)).current=s,(p=(0,$.useRef)({projectId:s.projectId,generation:0})).current.projectId!==s.projectId&&(p.current={projectId:s.projectId,generation:p.current.generation+1}),m=(0,$.useRef)(new Map),g=(0,$.useRef)(new Map),x=(0,$.useCallback)(e=>p.current.projectId===e.projectId&&p.current.generation===e.generation,[]),v=(0,$.useCallback)(async(e,r)=>{if(!e.projectId)return null;let s=f.current,n=await s.getScheduleRun(r);if(!x(e))return null;if(n.project_id!==e.projectId)throw Error("Schedule run does not belong to the active project");let i=await s.getSchedules(e.projectId);if(!x(e))return null;let a=i.find(e=>e.id===n.schedule_id);if(!a||a.project_id!==e.projectId)throw Error("Schedule does not belong to the active project");return{run:n,schedule:a}},[x]),_=(0,$.useCallback)(async(e,r,s)=>{let n={...p.current};if(n.projectId)try{let i=await f.current.resolveProjectForTarget(n.projectId,r);if(!x(n)||!i||i.id!==n.projectId)return;f.current.selectAgentSession(s,e,i.id)}catch(e){x(n)&&f.current.onError("session-navigation",e)}},[x]),y=(0,$.useCallback)(async(e,r)=>{let s={...p.current};try{let n=await v(s,e);if(!n||!x(s))return;if(r&&r!==n.schedule.id)throw Error("Schedule run target changed while opening");f.current.openScheduleRun(n.schedule.id,e)}catch(e){x(s)&&f.current.onError("schedule-navigation",e)}},[x,v]),b=(0,$.useCallback)(e=>{let r={...p.current};if(!r.projectId)return Promise.resolve();let s=`${r.projectId}:${e}`,n=g.current.get(s);if(n)return n;let i=(async()=>{try{let n,i=c3(r.projectId,e),a=m.current.get(i)??function(e,r,s){try{let n=window.sessionStorage.getItem(e);if(!n)return;let i=JSON.parse(n);return"string"==typeof i.requestId&&"string"==typeof i.runId&&i.projectId===r&&"string"==typeof i.scheduleId&&i.scheduleId.length>0&&i.sourceRunId===s?i:void 0}catch{return}}(i,r.projectId,e);if(a){let e=await f.current.getSchedules(r.projectId);if(!x(r))return;let s=a.scheduleId,o=e.find(e=>e.id===s);if(!o||o.project_id!==r.projectId)throw Error("Schedule does not belong to the active project");n=o,m.current.set(i,a)}else{let o=await v(r,e);if(!o||!x(r))return;n=o.schedule;let l=crypto.randomUUID();a={projectId:r.projectId,scheduleId:n.id,requestId:l,runId:l,sourceRunId:e},m.current.set(i,a);var s=a;try{window.sessionStorage.setItem(i,JSON.stringify(s))}catch{}}let o={requestId:a.requestId,runId:a.runId,sourceRunId:a.sourceRunId},l=await f.current.runScheduleNow(n.id,o);if(m.current.delete(i),c4(i),!x(r))return;f.current.onRerunResult(l)}catch(s){if(r.projectId&&("object"==typeof s&&null!==s&&"status"in s&&409===s.status||"object"==typeof s&&null!==s&&"durable"in s&&!0===s.durable)){let s=c3(r.projectId,e);m.current.delete(s),c4(s)}throw x(r)&&f.current.onError("schedule-rerun",s),s}})().finally(()=>{g.current.get(s)===i&&g.current.delete(s)});return g.current.set(s,i),i},[x,v]),{openAgentSession:_,openScheduleRun:y,runScheduleAgain:b}),tM=(n={projectId:ed?.id??null,schedules:eB,getTask:rv.api.getTask,resolveProjectForTarget:tA,openTask:eX,selectAgentSession:(e,r,s)=>{G("workspace"),t_(e,r,s)},selectWorkspace:e=>{F(null),V(e),G("workspace")},selectSchedule:e=>{eU(e),G("schedules")},openScheduleRun:tT.openScheduleRun,onError:e=>{_Z.toast.error(e instanceof Error?e.message:"Unable to open Context item")}},(w=(0,$.useRef)(n)).current=n,(S=(0,$.useRef)({projectId:n.projectId,generation:0})).current.projectId!==n.projectId&&(S.current={projectId:n.projectId,generation:S.current.generation+1}),j=(0,$.useCallback)(e=>e.projectId===S.current.projectId&&e.generation===S.current.generation,[]),{open:(0,$.useCallback)(async e=>{let r={...S.current},s=e.navigation;if(!r.projectId||e.deleted||!s){j(r)&&w.current.onError(Error("This Context item is no longer available"));return}try{if("task"===s.kind){let e=await w.current.getTask(r.projectId,s.taskId);if(!j(r))return;if(e.id!==s.taskId||e.project_id!==r.projectId)throw Error("Task is no longer available in this project");w.current.openTask(e);return}if("agent_session"===s.kind||"workspace"===s.kind){let e=await w.current.resolveProjectForTarget(r.projectId,s.target);if(!j(r))return;if(!e||e.id!==r.projectId)throw Error("Workspace target is no longer available");"agent_session"===s.kind?w.current.selectAgentSession(s.branch,s.sessionId,e.id):w.current.selectWorkspace(s.branch,e.id);return}if("schedule"===s.kind){let e=w.current.schedules.find(e=>e.id===s.scheduleId&&e.project_id===r.projectId);if(!e)throw Error("Schedule is no longer available in this project");w.current.selectSchedule(e.id);return}await w.current.openScheduleRun(s.runId,s.scheduleId)}catch(e){j(r)&&w.current.onError(e)}},[j])}),tF=(0,$.useCallback)(e=>{J(e),V(null),F(null),G("project-chat")},[F]),tP=(0,$.useCallback)(()=>{J(null),G("project-info")},[]);(0,$.useEffect)(()=>{G(k),J("project-chat"===k?E:null),"project-chat"===k&&(V(null),F(null))},[k,E,F]);let tI=(0,$.useCallback)(e=>{eK(r=>r===e?null:r)},[]),tB=(0,$.useCallback)(e=>{if(tR.current)return;let r=ec.find(r=>r.id===e);r&&(tD(!1),eg(r),G("project-info"))},[ec,eg]),tL=(0,$.useCallback)(async e=>{if(!tR.current){tR.current=!0,tD(!1);try{let r=await tA(e.projectId,e.targetId);if(!r)return;G("workspace"),r.id===ed?.id?(V(e.branch),F(null)):(tk.current={branch:e.branch,sessionId:null},eg(r))}catch(e){console.error("Quick switcher navigation failed:",e),_Z.toast.error("Failed to open workspace")}finally{tR.current=!1}}},[ed?.id,tA,eg,F]),tz=(0,$.useCallback)(async e=>{if(!tR.current){tR.current=!0,tD(!1);try{let r=await tA(e.projectId,e.targetId);if(!r)return;(0,Eb.touchRecentSessionOpen)(e.sessionId,e),G("workspace"),r.id===ed?.id?t_(e.branch,e.sessionId,e.projectId):(es(!0),tk.current={branch:e.branch,sessionId:e.sessionId},eg(r))}catch(e){console.error("Quick switcher navigation failed:",e),_Z.toast.error("Failed to open session")}finally{tR.current=!1}}},[ed?.id,tA,eg,t_]),tO=(0,$.useRef)(K),t$=(0,$.useRef)(ed?.id),tW=(0,$.useRef)(!1);(0,$.useEffect)(()=>{if(eu||ex||ev)return;let e=!tW.current,r=!e&&tO.current!==K,s=!e&&t$.current!==ed?.id;tO.current=K,t$.current=ed?.id,tW.current=!0;let n=tx.current;if(Eq(n,ed?.id,K,R)&&(tx.current=null),function({branchChanged:e,projectChanged:r,urlSessionId:s,pendingSessionSelection:n,currentProjectId:i,selectedBranch:a}){return(!!e||!!r)&&!!s&&!Eq(n,i,a,s)}({branchChanged:r,projectChanged:s,urlSessionId:R,pendingSessionSelection:n,currentProjectId:ed?.id,selectedBranch:K})){tx.current=null,F(null);return}let i=EH({projectId:ed?.id,tab:Y,branch:K,threadId:X});if(R){let e=new URL(i,window.location.origin);e.searchParams.set("session",R),window.history.replaceState(null,"",e.pathname+e.search)}else window.history.replaceState(null,"",i)},[ed?.id,Y,K,X,eu,ex,ev,R,F]);let tH=(0,$.useCallback)(e=>{eb(),V(e)},[eb]);(0,$.useCallback)((e,r)=>{ed&&r!==ed.agent_mode?ep(ed.id,{agentMode:r}).then(()=>{en.current?.submitMessage(e)}):en.current?.submitMessage(e)},[ed,ep]);let tU=(0,$.useRef)({content:"",at:0}),tq=(0,$.useCallback)(e=>{let r=Date.now(),s=tU.current;s.content===e&&r-s.at<600||(tU.current={content:e,at:r},e9.current?.sendMessage(e))},[]),tK=(0,$.useCallback)(()=>{let e=`Please perform the following git operations for this worktree:
29
29
 
30
30
  1. Commit all current uncommitted changes with an appropriate commit message
31
31
  2. Fetch the latest changes from the remote main branch