nterminal 1.2.20 → 1.2.21

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.
@@ -11,7 +11,7 @@ Error generating stack: `+l.message+`
11
11
  While dragging, use the arrow keys to move the item.
12
12
  Press space again to drop the item in its new position, or press escape to cancel.
13
13
  `},ux={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function hx(e){let{announcements:t=ux,container:n,hiddenTextDescribedById:a,screenReaderInstructions:o=cx}=e;const{announce:c,announcement:d}=ax(),p=ku("DndLiveRegion"),[m,f]=g.useState(!1);if(g.useEffect(()=>{f(!0)},[]),lx(g.useMemo(()=>({onDragStart(y){let{active:b}=y;c(t.onDragStart({active:b}))},onDragMove(y){let{active:b,over:x}=y;t.onDragMove&&c(t.onDragMove({active:b,over:x}))},onDragOver(y){let{active:b,over:x}=y;c(t.onDragOver({active:b,over:x}))},onDragEnd(y){let{active:b,over:x}=y;c(t.onDragEnd({active:b,over:x}))},onDragCancel(y){let{active:b,over:x}=y;c(t.onDragCancel({active:b,over:x}))}}),[c,t])),!m)return null;const S=xi.createElement(xi.Fragment,null,xi.createElement(nx,{id:a,value:o.draggable}),xi.createElement(rx,{id:p,announcement:d}));return n?Il.createPortal(S,n):S}var ni;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(ni||(ni={}));function cu(){}function ky(e,t){return g.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function dx(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return g.useMemo(()=>[...t].filter(a=>a!=null),[...t])}const Ns=Object.freeze({x:0,y:0});function fx(e,t){let{data:{value:n}}=e,{data:{value:a}}=t;return a-n}function px(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function mx(e,t){const n=Math.max(t.top,e.top),a=Math.max(t.left,e.left),o=Math.min(t.left+t.width,e.left+e.width),c=Math.min(t.top+t.height,e.top+e.height),d=o-a,p=c-n;if(a<o&&n<c){const m=t.width*t.height,f=e.width*e.height,S=d*p,y=S/(m+f-S);return Number(y.toFixed(4))}return 0}const _x=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:a}=e;const o=[];for(const c of a){const{id:d}=c,p=n.get(d);if(p){const m=mx(p,t);m>0&&o.push({id:d,data:{droppableContainer:c,value:m}})}}return o.sort(fx)};function vx(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function Db(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Ns}function gx(e){return function(n){for(var a=arguments.length,o=new Array(a>1?a-1:0),c=1;c<a;c++)o[c-1]=arguments[c];return o.reduce((d,p)=>({...d,top:d.top+e*p.y,bottom:d.bottom+e*p.y,left:d.left+e*p.x,right:d.right+e*p.x}),{...n})}}const yx=gx(1);function Sx(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function bx(e,t,n){const a=Sx(t);if(!a)return e;const{scaleX:o,scaleY:c,x:d,y:p}=a,m=e.left-d-(1-o)*parseFloat(n),f=e.top-p-(1-c)*parseFloat(n.slice(n.indexOf(" ")+1)),S=o?e.width/o:e.width,y=c?e.height/c:e.height;return{width:S,height:y,top:f,right:m+S,bottom:f+y,left:m}}const wx={ignoreTransform:!1};function bo(e,t){t===void 0&&(t=wx);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:f,transformOrigin:S}=$i(e).getComputedStyle(e);f&&(n=bx(n,f,S))}const{top:a,left:o,width:c,height:d,bottom:p,right:m}=n;return{top:a,left:o,width:c,height:d,bottom:p,right:m}}function Dy(e){return bo(e,{ignoreTransform:!0})}function Cx(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function xx(e,t){return t===void 0&&(t=$i(e).getComputedStyle(e)),t.position==="fixed"}function Ex(e,t){t===void 0&&(t=$i(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(o=>{const c=t[o];return typeof c=="string"?n.test(c):!1})}function Zp(e,t){const n=[];function a(o){if(t!=null&&n.length>=t||!o)return n;if(Xp(o)&&o.scrollingElement!=null&&!n.includes(o.scrollingElement))return n.push(o.scrollingElement),n;if(!yo(o)||xb(o)||n.includes(o))return n;const c=$i(e).getComputedStyle(o);return o!==e&&Ex(o,c)&&n.push(o),xx(o,c)?n:a(o.parentNode)}return e?a(e):n}function Rb(e){const[t]=Zp(e,1);return t??null}function Gd(e){return!Tu||!e?null:za(e)?e:Vp(e)?Xp(e)||e===ja(e).scrollingElement?window:yo(e)?e:null:null}function Mb(e){return za(e)?e.scrollX:e.scrollLeft}function Ab(e){return za(e)?e.scrollY:e.scrollTop}function kf(e){return{x:Mb(e),y:Ab(e)}}var ui;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(ui||(ui={}));function Nb(e){return!Tu||!e?!1:e===document.scrollingElement}function Bb(e){const t={x:0,y:0},n=Nb(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},a={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},o=e.scrollTop<=t.y,c=e.scrollLeft<=t.x,d=e.scrollTop>=a.y,p=e.scrollLeft>=a.x;return{isTop:o,isLeft:c,isBottom:d,isRight:p,maxScroll:a,minScroll:t}}const Tx={x:.2,y:.2};function kx(e,t,n,a,o){let{top:c,left:d,right:p,bottom:m}=n;a===void 0&&(a=10),o===void 0&&(o=Tx);const{isTop:f,isBottom:S,isLeft:y,isRight:b}=Bb(e),x={x:0,y:0},C={x:0,y:0},k={height:t.height*o.y,width:t.width*o.x};return!f&&c<=t.top+k.height?(x.y=ui.Backward,C.y=a*Math.abs((t.top+k.height-c)/k.height)):!S&&m>=t.bottom-k.height&&(x.y=ui.Forward,C.y=a*Math.abs((t.bottom-k.height-m)/k.height)),!b&&p>=t.right-k.width?(x.x=ui.Forward,C.x=a*Math.abs((t.right-k.width-p)/k.width)):!y&&d<=t.left+k.width&&(x.x=ui.Backward,C.x=a*Math.abs((t.left+k.width-d)/k.width)),{direction:x,speed:C}}function Dx(e){if(e===document.scrollingElement){const{innerWidth:c,innerHeight:d}=window;return{top:0,left:0,right:c,bottom:d,width:c,height:d}}const{top:t,left:n,right:a,bottom:o}=e.getBoundingClientRect();return{top:t,left:n,right:a,bottom:o,width:e.clientWidth,height:e.clientHeight}}function Lb(e){return e.reduce((t,n)=>Aa(t,kf(n)),Ns)}function Rx(e){return e.reduce((t,n)=>t+Mb(n),0)}function Mx(e){return e.reduce((t,n)=>t+Ab(n),0)}function Ax(e,t){if(t===void 0&&(t=bo),!e)return;const{top:n,left:a,bottom:o,right:c}=t(e);Rb(e)&&(o<=0||c<=0||n>=window.innerHeight||a>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const Nx=[["x",["left","right"],Rx],["y",["top","bottom"],Mx]];class Qp{constructor(t,n){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 a=Zp(n),o=Lb(a);this.rect={...t},this.width=t.width,this.height=t.height;for(const[c,d,p]of Nx)for(const m of d)Object.defineProperty(this,m,{get:()=>{const f=p(a),S=o[c]-f;return this.rect[m]+S},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Gl{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var a;return(a=this.target)==null?void 0:a.removeEventListener(...n)})},this.target=t}add(t,n,a){var o;(o=this.target)==null||o.addEventListener(t,n,a),this.listeners.push([t,n,a])}}function Bx(e){const{EventTarget:t}=$i(e);return e instanceof t?e:ja(e)}function Zd(e,t){const n=Math.abs(e.x),a=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+a**2)>t:"x"in t&&"y"in t?n>t.x&&a>t.y:"x"in t?n>t.x:"y"in t?a>t.y:!1}var bs;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(bs||(bs={}));function Ry(e){e.preventDefault()}function Lx(e){e.stopPropagation()}var vt;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(vt||(vt={}));const Ob={start:[vt.Space,vt.Enter],cancel:[vt.Esc],end:[vt.Space,vt.Enter,vt.Tab]},Ox=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case vt.Right:return{...n,x:n.x+25};case vt.Left:return{...n,x:n.x-25};case vt.Down:return{...n,y:n.y+25};case vt.Up:return{...n,y:n.y-25}}};class zb{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new Gl(ja(n)),this.windowListeners=new Gl($i(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(bs.Resize,this.handleCancel),this.windowListeners.add(bs.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(bs.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,a=t.node.current;a&&Ax(a),n(Ns)}handleKeyDown(t){if(Tb(t)){const{active:n,context:a,options:o}=this.props,{keyboardCodes:c=Ob,coordinateGetter:d=Ox,scrollBehavior:p="smooth"}=o,{code:m}=t;if(c.end.includes(m)){this.handleEnd(t);return}if(c.cancel.includes(m)){this.handleCancel(t);return}const{collisionRect:f}=a.current,S=f?{x:f.left,y:f.top}:Ns;this.referenceCoordinates||(this.referenceCoordinates=S);const y=d(t,{active:n,context:a.current,currentCoordinates:S});if(y){const b=ou(y,S),x={x:0,y:0},{scrollableAncestors:C}=a.current;for(const k of C){const B=t.code,{isTop:R,isRight:re,isLeft:F,isBottom:J,maxScroll:ce,minScroll:q}=Bb(k),I=Dx(k),ie={x:Math.min(B===vt.Right?I.right-I.width/2:I.right,Math.max(B===vt.Right?I.left:I.left+I.width/2,y.x)),y:Math.min(B===vt.Down?I.bottom-I.height/2:I.bottom,Math.max(B===vt.Down?I.top:I.top+I.height/2,y.y))},de=B===vt.Right&&!re||B===vt.Left&&!F,j=B===vt.Down&&!J||B===vt.Up&&!R;if(de&&ie.x!==y.x){const $=k.scrollLeft+b.x,H=B===vt.Right&&$<=ce.x||B===vt.Left&&$>=q.x;if(H&&!b.y){k.scrollTo({left:$,behavior:p});return}H?x.x=k.scrollLeft-$:x.x=B===vt.Right?k.scrollLeft-ce.x:k.scrollLeft-q.x,x.x&&k.scrollBy({left:-x.x,behavior:p});break}else if(j&&ie.y!==y.y){const $=k.scrollTop+b.y,H=B===vt.Down&&$<=ce.y||B===vt.Up&&$>=q.y;if(H&&!b.x){k.scrollTo({top:$,behavior:p});return}H?x.y=k.scrollTop-$:x.y=B===vt.Down?k.scrollTop-ce.y:k.scrollTop-q.y,x.y&&k.scrollBy({top:-x.y,behavior:p});break}}this.handleMove(t,Aa(ou(y,this.referenceCoordinates),x))}}}handleMove(t,n){const{onMove:a}=this.props;t.preventDefault(),a(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}zb.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:a=Ob,onActivation:o}=t,{active:c}=n;const{code:d}=e.nativeEvent;if(a.start.includes(d)){const p=c.activatorNode.current;return p&&e.target!==p?!1:(e.preventDefault(),o?.({event:e.nativeEvent}),!0)}return!1}}];function My(e){return!!(e&&"distance"in e)}function Ay(e){return!!(e&&"delay"in e)}class Jp{constructor(t,n,a){var o;a===void 0&&(a=Bx(t.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=t,this.events=n;const{event:c}=t,{target:d}=c;this.props=t,this.events=n,this.document=ja(d),this.documentListeners=new Gl(this.document),this.listeners=new Gl(a),this.windowListeners=new Gl($i(d)),this.initialCoordinates=(o=Ef(c))!=null?o:Ns,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(){const{events:t,props:{options:{activationConstraint:n,bypassActivationConstraint:a}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(bs.Resize,this.handleCancel),this.windowListeners.add(bs.DragStart,Ry),this.windowListeners.add(bs.VisibilityChange,this.handleCancel),this.windowListeners.add(bs.ContextMenu,Ry),this.documentListeners.add(bs.Keydown,this.handleKeydown),n){if(a!=null&&a({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Ay(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(My(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:a,onPending:o}=this.props;o(a,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(bs.Click,Lx,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(bs.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:a,initialCoordinates:o,props:c}=this,{onMove:d,options:{activationConstraint:p}}=c;if(!o)return;const m=(n=Ef(t))!=null?n:Ns,f=ou(o,m);if(!a&&p){if(My(p)){if(p.tolerance!=null&&Zd(f,p.tolerance))return this.handleCancel();if(Zd(f,p.distance))return this.handleStart()}if(Ay(p)&&Zd(f,p.tolerance))return this.handleCancel();this.handlePending(p,f);return}t.cancelable&&t.preventDefault(),d(m)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===vt.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const zx={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class jb extends Jp{constructor(t){const{event:n}=t,a=ja(n.target);super(t,zx,a)}}jb.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:a}=t;return!n.isPrimary||n.button!==0?!1:(a?.({event:n}),!0)}}];const jx={move:{name:"mousemove"},end:{name:"mouseup"}};var Df;(function(e){e[e.RightClick=2]="RightClick"})(Df||(Df={}));class Hb extends Jp{constructor(t){super(t,jx,ja(t.event.target))}}Hb.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:a}=t;return n.button===Df.RightClick?!1:(a?.({event:n}),!0)}}];const Qd={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class Ub extends Jp{constructor(t){super(t,Qd)}static setup(){return window.addEventListener(Qd.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(Qd.move.name,t)};function t(){}}}Ub.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:a}=t;const{touches:o}=n;return o.length>1?!1:(a?.({event:n}),!0)}}];var Zl;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Zl||(Zl={}));var uu;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(uu||(uu={}));function Hx(e){let{acceleration:t,activator:n=Zl.Pointer,canScroll:a,draggingRect:o,enabled:c,interval:d=5,order:p=uu.TreeOrder,pointerCoordinates:m,scrollableAncestors:f,scrollableAncestorRects:S,delta:y,threshold:b}=e;const x=Px({delta:y,disabled:!c}),[C,k]=JC(),B=g.useRef({x:0,y:0}),R=g.useRef({x:0,y:0}),re=g.useMemo(()=>{switch(n){case Zl.Pointer:return m?{top:m.y,bottom:m.y,left:m.x,right:m.x}:null;case Zl.DraggableRect:return o}},[n,o,m]),F=g.useRef(null),J=g.useCallback(()=>{const q=F.current;if(!q)return;const I=B.current.x*R.current.x,ie=B.current.y*R.current.y;q.scrollBy(I,ie)},[]),ce=g.useMemo(()=>p===uu.TreeOrder?[...f].reverse():f,[p,f]);g.useEffect(()=>{if(!c||!f.length||!re){k();return}for(const q of ce){if(a?.(q)===!1)continue;const I=f.indexOf(q),ie=S[I];if(!ie)continue;const{direction:de,speed:j}=kx(q,ie,re,t,b);for(const $ of["x","y"])x[$][de[$]]||(j[$]=0,de[$]=0);if(j.x>0||j.y>0){k(),F.current=q,C(J,d),B.current=j,R.current=de;return}}B.current={x:0,y:0},R.current={x:0,y:0},k()},[t,J,a,k,c,d,JSON.stringify(re),JSON.stringify(x),C,f,ce,S,JSON.stringify(b)])}const Ux={x:{[ui.Backward]:!1,[ui.Forward]:!1},y:{[ui.Backward]:!1,[ui.Forward]:!1}};function Px(e){let{delta:t,disabled:n}=e;const a=xf(t);return So(o=>{if(n||!a||!o)return Ux;const c={x:Math.sign(t.x-a.x),y:Math.sign(t.y-a.y)};return{x:{[ui.Backward]:o.x[ui.Backward]||c.x===-1,[ui.Forward]:o.x[ui.Forward]||c.x===1},y:{[ui.Backward]:o.y[ui.Backward]||c.y===-1,[ui.Forward]:o.y[ui.Forward]||c.y===1}}},[n,t,a])}function Kx(e,t){const n=t!=null?e.get(t):void 0,a=n?n.node.current:null;return So(o=>{var c;return t==null?null:(c=a??o)!=null?c:null},[a,t])}function Ix(e,t){return g.useMemo(()=>e.reduce((n,a)=>{const{sensor:o}=a,c=o.activators.map(d=>({eventName:d.eventName,handler:t(d.handler,a)}));return[...n,...c]},[]),[e,t])}var no;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(no||(no={}));var Rf;(function(e){e.Optimized="optimized"})(Rf||(Rf={}));const Ny=new Map;function Fx(e,t){let{dragging:n,dependencies:a,config:o}=t;const[c,d]=g.useState(null),{frequency:p,measure:m,strategy:f}=o,S=g.useRef(e),y=B(),b=so(y),x=g.useCallback(function(R){R===void 0&&(R=[]),!b.current&&d(re=>re===null?R:re.concat(R.filter(F=>!re.includes(F))))},[b]),C=g.useRef(null),k=So(R=>{if(y&&!n)return Ny;if(!R||R===Ny||S.current!==e||c!=null){const re=new Map;for(let F of e){if(!F)continue;if(c&&c.length>0&&!c.includes(F.id)&&F.rect.current){re.set(F.id,F.rect.current);continue}const J=F.node.current,ce=J?new Qp(m(J),J):null;F.rect.current=ce,ce&&re.set(F.id,ce)}return re}return R},[e,c,n,y,m]);return g.useEffect(()=>{S.current=e},[e]),g.useEffect(()=>{y||x()},[n,y]),g.useEffect(()=>{c&&c.length>0&&d(null)},[JSON.stringify(c)]),g.useEffect(()=>{y||typeof p!="number"||C.current!==null||(C.current=setTimeout(()=>{x(),C.current=null},p))},[p,y,x,...a]),{droppableRects:k,measureDroppableContainers:x,measuringScheduled:c!=null};function B(){switch(f){case no.Always:return!1;case no.BeforeDragging:return n;default:return!n}}}function Pb(e,t){return So(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function qx(e,t){return Pb(e,t)}function Wx(e){let{callback:t,disabled:n}=e;const a=Gp(t),o=g.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:c}=window;return new c(a)},[a,n]);return g.useEffect(()=>()=>o?.disconnect(),[o]),o}function Du(e){let{callback:t,disabled:n}=e;const a=Gp(t),o=g.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:c}=window;return new c(a)},[n]);return g.useEffect(()=>()=>o?.disconnect(),[o]),o}function Yx(e){return new Qp(bo(e),e)}function By(e,t,n){t===void 0&&(t=Yx);const[a,o]=g.useState(null);function c(){o(m=>{if(!e)return null;if(e.isConnected===!1){var f;return(f=m??n)!=null?f:null}const S=t(e);return JSON.stringify(m)===JSON.stringify(S)?m:S})}const d=Wx({callback(m){if(e)for(const f of m){const{type:S,target:y}=f;if(S==="childList"&&y instanceof HTMLElement&&y.contains(e)){c();break}}}}),p=Du({callback:c});return ar(()=>{c(),e?(p?.observe(e),d?.observe(document.body,{childList:!0,subtree:!0})):(p?.disconnect(),d?.disconnect())},[e]),a}function $x(e){const t=Pb(e);return Db(e,t)}const Ly=[];function Vx(e){const t=g.useRef(e),n=So(a=>e?a&&a!==Ly&&e&&t.current&&e.parentNode===t.current.parentNode?a:Zp(e):Ly,[e]);return g.useEffect(()=>{t.current=e},[e]),n}function Xx(e){const[t,n]=g.useState(null),a=g.useRef(e),o=g.useCallback(c=>{const d=Gd(c.target);d&&n(p=>p?(p.set(d,kf(d)),new Map(p)):null)},[]);return g.useEffect(()=>{const c=a.current;if(e!==c){d(c);const p=e.map(m=>{const f=Gd(m);return f?(f.addEventListener("scroll",o,{passive:!0}),[f,kf(f)]):null}).filter(m=>m!=null);n(p.length?new Map(p):null),a.current=e}return()=>{d(e),d(c)};function d(p){p.forEach(m=>{const f=Gd(m);f?.removeEventListener("scroll",o)})}},[o,e]),g.useMemo(()=>e.length?t?Array.from(t.values()).reduce((c,d)=>Aa(c,d),Ns):Lb(e):Ns,[e,t])}function Oy(e,t){t===void 0&&(t=[]);const n=g.useRef(null);return g.useEffect(()=>{n.current=null},t),g.useEffect(()=>{const a=e!==Ns;a&&!n.current&&(n.current=e),!a&&n.current&&(n.current=null)},[e]),n.current?ou(e,n.current):Ns}function Gx(e){g.useEffect(()=>{if(!Tu)return;const t=e.map(n=>{let{sensor:a}=n;return a.setup==null?void 0:a.setup()});return()=>{for(const n of t)n?.()}},e.map(t=>{let{sensor:n}=t;return n}))}function Zx(e,t){return g.useMemo(()=>e.reduce((n,a)=>{let{eventName:o,handler:c}=a;return n[o]=d=>{c(d,t)},n},{}),[e,t])}function Kb(e){return g.useMemo(()=>e?Cx(e):null,[e])}const zy=[];function Qx(e,t){t===void 0&&(t=bo);const[n]=e,a=Kb(n?$i(n):null),[o,c]=g.useState(zy);function d(){c(()=>e.length?e.map(m=>Nb(m)?a:new Qp(t(m),m)):zy)}const p=Du({callback:d});return ar(()=>{p?.disconnect(),d(),e.forEach(m=>p?.observe(m))},[e]),o}function Jx(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return yo(t)?t:e}function eE(e){let{measure:t}=e;const[n,a]=g.useState(null),o=g.useCallback(f=>{for(const{target:S}of f)if(yo(S)){a(y=>{const b=t(S);return y?{...y,width:b.width,height:b.height}:b});break}},[t]),c=Du({callback:o}),d=g.useCallback(f=>{const S=Jx(f);c?.disconnect(),S&&c?.observe(S),a(S?t(S):null)},[t,c]),[p,m]=lu(d);return g.useMemo(()=>({nodeRef:p,rect:n,setRef:m}),[n,p,m])}const tE=[{sensor:jb,options:{}},{sensor:zb,options:{}}],iE={current:{}},Gc={draggable:{measure:Dy},droppable:{measure:Dy,strategy:no.WhileDragging,frequency:Rf.Optimized},dragOverlay:{measure:bo}};class Ql extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,a;return(n=(a=this.get(t))==null?void 0:a.node.current)!=null?n:void 0}}const sE={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ql,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:cu},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Gc,measureDroppableContainers:cu,windowRect:null,measuringScheduled:!1},nE={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:cu,draggableNodes:new Map,over:null,measureDroppableContainers:cu},Ru=g.createContext(nE),rE=g.createContext(sE);function aE(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ql}}}function lE(e,t){switch(t.type){case ni.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case ni.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case ni.DragEnd:case ni.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ni.RegisterDroppable:{const{element:n}=t,{id:a}=n,o=new Ql(e.droppable.containers);return o.set(a,n),{...e,droppable:{...e.droppable,containers:o}}}case ni.SetDroppableDisabled:{const{id:n,key:a,disabled:o}=t,c=e.droppable.containers.get(n);if(!c||a!==c.key)return e;const d=new Ql(e.droppable.containers);return d.set(n,{...c,disabled:o}),{...e,droppable:{...e.droppable,containers:d}}}case ni.UnregisterDroppable:{const{id:n,key:a}=t,o=e.droppable.containers.get(n);if(!o||a!==o.key)return e;const c=new Ql(e.droppable.containers);return c.delete(n),{...e,droppable:{...e.droppable,containers:c}}}default:return e}}function oE(e){let{disabled:t}=e;const{active:n,activatorEvent:a,draggableNodes:o}=g.useContext(Ru),c=xf(a),d=xf(n?.id);return g.useEffect(()=>{if(!t&&!a&&c&&d!=null){if(!Tb(c)||document.activeElement===c.target)return;const p=o.get(d);if(!p)return;const{activatorNode:m,node:f}=p;if(!m.current&&!f.current)return;requestAnimationFrame(()=>{for(const S of[m.current,f.current]){if(!S)continue;const y=ix(S);if(y){y.focus();break}}})}},[a,t,o,d,c]),null}function cE(e,t){let{transform:n,...a}=t;return e!=null&&e.length?e.reduce((o,c)=>c({transform:o,...a}),n):n}function uE(e){return g.useMemo(()=>({draggable:{...Gc.draggable,...e?.draggable},droppable:{...Gc.droppable,...e?.droppable},dragOverlay:{...Gc.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function hE(e){let{activeNode:t,measure:n,initialRect:a,config:o=!0}=e;const c=g.useRef(!1),{x:d,y:p}=typeof o=="boolean"?{x:o,y:o}:o;ar(()=>{if(!d&&!p||!t){c.current=!1;return}if(c.current||!a)return;const f=t?.node.current;if(!f||f.isConnected===!1)return;const S=n(f),y=Db(S,a);if(d||(y.x=0),p||(y.y=0),c.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const b=Rb(f);b&&b.scrollBy({top:y.y,left:y.x})}},[t,d,p,a,n])}const Ib=g.createContext({...Ns,scaleX:1,scaleY:1});var er;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(er||(er={}));const dE=g.memo(function(t){var n,a,o,c;let{id:d,accessibility:p,autoScroll:m=!0,children:f,sensors:S=tE,collisionDetection:y=_x,measuring:b,modifiers:x,...C}=t;const k=g.useReducer(lE,void 0,aE),[B,R]=k,[re,F]=ox(),[J,ce]=g.useState(er.Uninitialized),q=J===er.Initialized,{draggable:{active:I,nodes:ie,translate:de},droppable:{containers:j}}=B,$=I!=null?ie.get(I):null,H=g.useRef({initial:null,translated:null}),L=g.useMemo(()=>{var ot;return I!=null?{id:I,data:(ot=$?.data)!=null?ot:iE,rect:H}:null},[I,$]),X=g.useRef(null),[G,M]=g.useState(null),[V,Q]=g.useState(null),ve=so(C,Object.values(C)),Se=ku("DndDescribedBy",d),E=g.useMemo(()=>j.getEnabled(),[j]),W=uE(b),{droppableRects:ee,measureDroppableContainers:he,measuringScheduled:ge}=Fx(E,{dragging:q,dependencies:[de.x,de.y],config:W.droppable}),me=Kx(ie,I),Ce=g.useMemo(()=>V?Ef(V):null,[V]),ze=ks(),Ne=qx(me,W.draggable.measure);hE({activeNode:I!=null?ie.get(I):null,config:ze.layoutShiftCompensation,initialRect:Ne,measure:W.draggable.measure});const Re=By(me,W.draggable.measure,Ne),Pe=By(me?me.parentElement:null),Ye=g.useRef({activatorEvent:null,active:null,activeNode:me,collisionRect:null,collisions:null,droppableRects:ee,draggableNodes:ie,draggingNode:null,draggingNodeRect:null,droppableContainers:j,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Be=j.getNodeFor((n=Ye.current.over)==null?void 0:n.id),ae=eE({measure:W.dragOverlay.measure}),Ee=(a=ae.nodeRef.current)!=null?a:me,xe=q?(o=ae.rect)!=null?o:Re:null,Ke=!!(ae.nodeRef.current&&ae.rect),Xe=$x(Ke?null:Re),gt=Kb(Ee?$i(Ee):null),yt=Vx(q?Be??me:null),mi=Qx(yt),te=cE(x,{transform:{x:de.x-Xe.x,y:de.y-Xe.y,scaleX:1,scaleY:1},activatorEvent:V,active:L,activeNodeRect:Re,containerNodeRect:Pe,draggingNodeRect:xe,over:Ye.current.over,overlayNodeRect:ae.rect,scrollableAncestors:yt,scrollableAncestorRects:mi,windowRect:gt}),je=Ce?Aa(Ce,de):null,He=Xx(yt),_i=Oy(He),Vi=Oy(He,[Re]),ai=Aa(te,_i),kt=xe?yx(xe,te):null,ji=L&&kt?y({active:L,collisionRect:kt,droppableRects:ee,droppableContainers:E,pointerCoordinates:je}):null,Ti=px(ji,"id"),[Nt,$s]=g.useState(null),Hi=Ke?te:Aa(te,Vi),qt=vx(Hi,(c=Nt?.rect)!=null?c:null,Re),Jt=g.useRef(null),Dt=g.useCallback((ot,St)=>{let{sensor:Rt,options:li}=St;if(X.current==null)return;const ei=ie.get(X.current);if(!ei)return;const Bt=ot.nativeEvent,nt=new Rt({active:X.current,activeNode:ei,event:Bt,options:li,context:Ye,onAbort(bt){if(!ie.get(bt))return;const{onDragAbort:ct}=ve.current,vi={id:bt};ct?.(vi),re({type:"onDragAbort",event:vi})},onPending(bt,Ge,ct,vi){if(!ie.get(bt))return;const{onDragPending:Ni}=ve.current,ki={id:bt,constraint:Ge,initialCoordinates:ct,offset:vi};Ni?.(ki),re({type:"onDragPending",event:ki})},onStart(bt){const Ge=X.current;if(Ge==null)return;const ct=ie.get(Ge);if(!ct)return;const{onDragStart:vi}=ve.current,Ai={activatorEvent:Bt,active:{id:Ge,data:ct.data,rect:H}};Il.unstable_batchedUpdates(()=>{vi?.(Ai),ce(er.Initializing),R({type:ni.DragStart,initialCoordinates:bt,active:Ge}),re({type:"onDragStart",event:Ai}),M(Jt.current),Q(Bt)})},onMove(bt){R({type:ni.DragMove,coordinates:bt})},onEnd:Wt(ni.DragEnd),onCancel:Wt(ni.DragCancel)});Jt.current=nt;function Wt(bt){return async function(){const{active:ct,collisions:vi,over:Ai,scrollAdjustedTranslate:Ni}=Ye.current;let ki=null;if(ct&&Ni){const{cancelDrop:cs}=ve.current;ki={activatorEvent:Bt,active:ct,collisions:vi,delta:Ni,over:Ai},bt===ni.DragEnd&&typeof cs=="function"&&await Promise.resolve(cs(ki))&&(bt=ni.DragCancel)}X.current=null,Il.unstable_batchedUpdates(()=>{R({type:bt}),ce(er.Uninitialized),$s(null),M(null),Q(null),Jt.current=null;const cs=bt===ni.DragEnd?"onDragEnd":"onDragCancel";if(ki){const gi=ve.current[cs];gi?.(ki),re({type:cs,event:ki})}})}}},[ie]),Cn=g.useCallback((ot,St)=>(Rt,li)=>{const ei=Rt.nativeEvent,Bt=ie.get(li);if(X.current!==null||!Bt||ei.dndKit||ei.defaultPrevented)return;const nt={active:Bt};ot(Rt,St.options,nt)===!0&&(ei.dndKit={capturedBy:St.sensor},X.current=li,Dt(Rt,St))},[ie,Dt]),Bs=Ix(S,Cn);Gx(S),ar(()=>{Re&&J===er.Initializing&&ce(er.Initialized)},[Re,J]),g.useEffect(()=>{const{onDragMove:ot}=ve.current,{active:St,activatorEvent:Rt,collisions:li,over:ei}=Ye.current;if(!St||!Rt)return;const Bt={active:St,activatorEvent:Rt,collisions:li,delta:{x:ai.x,y:ai.y},over:ei};Il.unstable_batchedUpdates(()=>{ot?.(Bt),re({type:"onDragMove",event:Bt})})},[ai.x,ai.y]),g.useEffect(()=>{const{active:ot,activatorEvent:St,collisions:Rt,droppableContainers:li,scrollAdjustedTranslate:ei}=Ye.current;if(!ot||X.current==null||!St||!ei)return;const{onDragOver:Bt}=ve.current,nt=li.get(Ti),Wt=nt&&nt.rect.current?{id:nt.id,rect:nt.rect.current,data:nt.data,disabled:nt.disabled}:null,bt={active:ot,activatorEvent:St,collisions:Rt,delta:{x:ei.x,y:ei.y},over:Wt};Il.unstable_batchedUpdates(()=>{$s(Wt),Bt?.(bt),re({type:"onDragOver",event:bt})})},[Ti]),ar(()=>{Ye.current={activatorEvent:V,active:L,activeNode:me,collisionRect:kt,collisions:ji,droppableRects:ee,draggableNodes:ie,draggingNode:Ee,draggingNodeRect:xe,droppableContainers:j,over:Nt,scrollableAncestors:yt,scrollAdjustedTranslate:ai},H.current={initial:xe,translated:kt}},[L,me,ji,kt,ie,Ee,xe,ee,j,Nt,yt,ai]),Hx({...ze,delta:de,draggingRect:kt,pointerCoordinates:je,scrollableAncestors:yt,scrollableAncestorRects:mi});const Vs=g.useMemo(()=>({active:L,activeNode:me,activeNodeRect:Re,activatorEvent:V,collisions:ji,containerNodeRect:Pe,dragOverlay:ae,draggableNodes:ie,droppableContainers:j,droppableRects:ee,over:Nt,measureDroppableContainers:he,scrollableAncestors:yt,scrollableAncestorRects:mi,measuringConfiguration:W,measuringScheduled:ge,windowRect:gt}),[L,me,Re,V,ji,Pe,ae,ie,j,ee,Nt,he,yt,mi,W,ge,gt]),Ts=g.useMemo(()=>({activatorEvent:V,activators:Bs,active:L,activeNodeRect:Re,ariaDescribedById:{draggable:Se},dispatch:R,draggableNodes:ie,over:Nt,measureDroppableContainers:he}),[V,Bs,L,Re,R,Se,ie,Nt,he]);return xi.createElement(kb.Provider,{value:F},xi.createElement(Ru.Provider,{value:Ts},xi.createElement(rE.Provider,{value:Vs},xi.createElement(Ib.Provider,{value:qt},f)),xi.createElement(oE,{disabled:p?.restoreFocus===!1})),xi.createElement(hx,{...p,hiddenTextDescribedById:Se}));function ks(){const ot=G?.autoScrollEnabled===!1,St=typeof m=="object"?m.enabled===!1:m===!1,Rt=q&&!ot&&!St;return typeof m=="object"?{...m,enabled:Rt}:{enabled:Rt}}}),fE=g.createContext(null),jy="button",pE="Draggable";function Fb(e){let{id:t,data:n,disabled:a=!1,attributes:o}=e;const c=ku(pE),{activators:d,activatorEvent:p,active:m,activeNodeRect:f,ariaDescribedById:S,draggableNodes:y,over:b}=g.useContext(Ru),{role:x=jy,roleDescription:C="draggable",tabIndex:k=0}=o??{},B=m?.id===t,R=g.useContext(B?Ib:fE),[re,F]=lu(),[J,ce]=lu(),q=Zx(d,t),I=so(n);ar(()=>(y.set(t,{id:t,key:c,node:re,activatorNode:J,data:I}),()=>{const de=y.get(t);de&&de.key===c&&y.delete(t)}),[y,t]);const ie=g.useMemo(()=>({role:x,tabIndex:k,"aria-disabled":a,"aria-pressed":B&&x===jy?!0:void 0,"aria-roledescription":C,"aria-describedby":S.draggable}),[a,x,k,B,C,S.draggable]);return{active:m,activatorEvent:p,activeNodeRect:f,attributes:ie,isDragging:B,listeners:a?void 0:q,node:re,over:b,setNodeRef:F,setActivatorNodeRef:ce,transform:R}}const mE="Droppable",_E={timeout:25};function qb(e){let{data:t,disabled:n=!1,id:a,resizeObserverConfig:o}=e;const c=ku(mE),{active:d,dispatch:p,over:m,measureDroppableContainers:f}=g.useContext(Ru),S=g.useRef({disabled:n}),y=g.useRef(!1),b=g.useRef(null),x=g.useRef(null),{disabled:C,updateMeasurementsFor:k,timeout:B}={..._E,...o},R=so(k??a),re=g.useCallback(()=>{if(!y.current){y.current=!0;return}x.current!=null&&clearTimeout(x.current),x.current=setTimeout(()=>{f(Array.isArray(R.current)?R.current:[R.current]),x.current=null},B)},[B]),F=Du({callback:re,disabled:C||!d}),J=g.useCallback((ie,de)=>{F&&(de&&(F.unobserve(de),y.current=!1),ie&&F.observe(ie))},[F]),[ce,q]=lu(J),I=so(t);return g.useEffect(()=>{!F||!ce.current||(F.disconnect(),y.current=!1,F.observe(ce.current))},[ce,F]),g.useEffect(()=>(p({type:ni.RegisterDroppable,element:{id:a,key:c,disabled:n,node:ce,rect:b,data:I}}),()=>p({type:ni.UnregisterDroppable,key:c,id:a})),[a]),g.useEffect(()=>{n!==S.current.disabled&&(p({type:ni.SetDroppableDisabled,id:a,key:c,disabled:n}),S.current.disabled=n)},[a,c,n,p]),{active:d,rect:b,isOver:m?.id===a,node:ce,over:m,setNodeRef:q}}const vE=128,gE=512,yE=64,SE=4096;function Wb(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.activeWorkspaceId!="string"&&t.activeWorkspaceId!==null||!Array.isArray(t.workspaces)||t.workspaces.length>vE)return null;const n=t.workspaces.map(bE);return n.some(a=>a===null)?null:{activeWorkspaceId:t.activeWorkspaceId,workspaces:n}}function bE(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.id!="string"||typeof t.title!="string"||typeof t.activeTabId!="string"&&t.activeTabId!==null||!Array.isArray(t.tabs)||t.tabs.length>gE)return null;const n=t.tabs.map(wE);return n.some(a=>a===null)?null:{id:t.id,title:t.title,activeTabId:t.activeTabId,tabs:n}}function wE(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.id!="string"||typeof t.title!="string"||typeof t.activeTerminalId!="string")return null;const n=CE(t.root);return n?{id:t.id,title:t.title,activeTerminalId:t.activeTerminalId,root:n}:null}function CE(e){if(!e||typeof e!="object")return null;let t=0;return Mf(e,1,()=>(t+=1,t<=SE))}function Mf(e,t,n){if(!e||typeof e!="object"||t>yE||!n())return null;const a=e;if(a.type==="pane")return typeof a.terminalId=="string"?{type:"pane",terminalId:a.terminalId}:null;if(a.type!=="split"||a.direction!=="horizontal"&&a.direction!=="vertical")return null;const o=Mf(a.first,t+1,n),c=Mf(a.second,t+1,n);return!o||!c?null:{type:"split",direction:a.direction,ratio:xE(a.ratio),first:o,second:c}}function xE(e){return typeof e=="number"&&Number.isFinite(e)?Math.min(.9,Math.max(.1,e)):.5}const Yb=[{id:"builtin-character-2260",filename:"character-2260.mp4",contentType:"video/mp4",size:123288,createdAt:"2026-05-26T00:00:00.000Z",url:"/assets/notifications/character-2260.mp4"},{id:"builtin-character-2272",filename:"character-2272.mp4",contentType:"video/mp4",size:55873,createdAt:"2026-05-26T00:00:00.000Z",url:"/assets/notifications/character-2272.mp4"},{id:"builtin-character-2258",filename:"character-2258.mp4",contentType:"video/mp4",size:112612,createdAt:"2026-05-26T00:00:00.000Z",url:"/assets/notifications/character-2258.mp4"}];function Hy(e){return e===void 0?"unknown":e==="error"?"offline":"ok"}function Uy(e){const t=e.trim();return t?t.charAt(0).toUpperCase():"?"}const Py="Local",EE=3e4;function Jd(e){return e===void 0?"":e==="error"?"offline":[`CPU ${Cs(e.cpuPercent)} ${em(e)}`,`MEM ${Cs(e.memoryPercent)} ${Sn(e.memoryUsedBytes,e.memoryTotalBytes)}`,`DISK ${Cs(e.diskPercent)} ${Sn(e.diskUsedBytes,e.diskTotalBytes)}`,`SWAP ${Cs(e.swapPercent)} ${Sn(e.swapUsedBytes,e.swapTotalBytes)}`].join(" · ")}function TE(e){if(!(e===void 0||e==="error"))return[`CPU ${Cs(e.cpuPercent)} (${em(e)})`,`RAM ${Cs(e.memoryPercent)} (${Sn(e.memoryUsedBytes,e.memoryTotalBytes)})`,`Disk ${Cs(e.diskPercent)} (${Sn(e.diskUsedBytes,e.diskTotalBytes)})`,`Swap ${Cs(e.swapPercent)} (${Sn(e.swapUsedBytes,e.swapTotalBytes)})`].join(" · ")}function Cs(e){return typeof e=="number"&&Number.isFinite(e)?`${Math.round(e)}%`:"–"}function em(e){const t=Number.isFinite(e.cores)&&e.cores>0?e.cores:null;return e.cpuPercent===null||e.cpuPercent===void 0||!Number.isFinite(e.cpuPercent)||t===null?`–/${t??"–"} cores`:`${Af(e.cpuPercent/100*t)}/${t} cores`}function Sn(e,t){return!Ky(e)||!Ky(t)?"–/–":kE(e,t)}function kE(e,t){const n=t>=1073741824?"GB":t>=1048576?"MB":"KB",a=n==="GB"?1024**3:n==="MB"?1024**2:1024;return`${Af(e/a)}/${Af(t/a)} ${n}`}function Af(e){return e>=10||Number.isInteger(e)?e.toFixed(0):e.toFixed(1)}function Ky(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function DE(e){return[{label:"CPU",percent:Cs(e.cpuPercent),detail:em(e)},{label:"MEM",percent:Cs(e.memoryPercent),detail:Sn(e.memoryUsedBytes,e.memoryTotalBytes)},{label:"DISK",percent:Cs(e.diskPercent),detail:Sn(e.diskUsedBytes,e.diskTotalBytes)},{label:"SWAP",percent:Cs(e.swapPercent),detail:Sn(e.swapUsedBytes,e.swapTotalBytes)}]}function Iy({entry:e}){return e==="error"?_.jsx("span",{className:"server-list-stats server-list-stats--offline",children:"offline"}):e===void 0?_.jsx("span",{className:"server-list-stats server-list-stats-grid","aria-hidden":"true",children:["CPU","MEM","DISK","SWAP"].map(t=>_.jsxs("span",{className:"server-list-stat-cell",children:[_.jsx("span",{className:"server-list-stat-label",children:t}),_.jsx("span",{className:"server-list-stat-value",children:"–"}),_.jsx("span",{className:"server-list-stat-detail",children:"–"})]},t))}):_.jsx("span",{className:"server-list-stats server-list-stats-grid",title:TE(e),children:DE(e).map(t=>_.jsxs("span",{className:"server-list-stat-cell",children:[_.jsx("span",{className:"server-list-stat-label",children:t.label}),_.jsx("span",{className:"server-list-stat-value",children:t.percent}),_.jsx("span",{className:"server-list-stat-detail",children:t.detail})]},t.label))})}function ef({api:e,activeAgentId:t,onSelectServer:n,onSessionInvalid:a,refreshToken:o=0,compact:c=!1}){const[d,p]=g.useState([]),[m,f]=g.useState(null),[S,y]=g.useState(null),[b,x]=g.useState(""),C=g.useRef(null),[k,B]=g.useState({});g.useEffect(()=>{let q=!1;return e.listAgents().then(I=>{q||p(I.agents)}).catch(()=>{}),e.getMainInfo().then(I=>{q||f(I.name)}).catch(()=>{}),()=>{q=!0}},[e,o]),g.useEffect(()=>{S&&(C.current?.focus(),C.current?.select())},[S]),g.useEffect(()=>{let q=!1;async function I(){let de=!1;const j=[{key:"__main__",load:()=>e.getMainStats()},...d.map(H=>({key:H.id,load:()=>e.getAgentStats(H.id)}))],$=await Promise.all(j.map(async H=>{try{return[H.key,await H.load()]}catch(L){return L instanceof yn&&L.status===401?(de=!0,[H.key,"error"]):[H.key,"error"]}}));if(!q){if(de){a?.();return}B(H=>{const L={};for(const[G,M]of $)L[G]=M;const X=new Set(["__main__",...d.map(G=>G.id)]);for(const G of Object.keys(H))!X.has(G)||G in L||(L[G]=H[G]);return L})}}I();const ie=window.setInterval(()=>{I()},EE);return()=>{q=!0,window.clearInterval(ie)}},[e,d,a]);function R(q){q==="main"?(x(m??""),y({kind:"main"})):(x(q.name),y({kind:"agent",id:q.id}))}async function re(){if(!S)return;const q=b.trim(),I=S;if(y(null),I.kind==="main"){const ie=q||"";try{const de=await e.renameMain(ie);f(de.name)}catch{}}else{if(!q)return;const ie=d.find(de=>de.id===I.id)?.name;p(de=>de.map(j=>j.id===I.id?{...j,name:q}:j));try{await e.renameAgent(I.id,q)}catch{ie!==void 0&&p(de=>de.map(j=>j.id===I.id?{...j,name:ie}:j))}}}function F(){y(null)}const J=m?.trim()||Py,ce=S?.kind==="main";return c?_.jsxs("div",{className:"server-list server-list--compact",children:[_.jsxs("button",{type:"button",className:`server-list-chip${t===null?" server-list-chip--active":""}`,onClick:()=>n(null),"aria-label":J,title:`${J}${Jd(k.__main__)?` — ${Jd(k.__main__)}`:""}`,children:[_.jsx("span",{className:"server-list-chip-initial",children:Uy(J)}),_.jsx("span",{className:"server-list-chip-pip","data-status":Hy(k.__main__)})]}),d.map(q=>{const I=k[q.id],ie=Jd(I);return _.jsxs("button",{type:"button",className:`server-list-chip${t===q.id?" server-list-chip--active":""}`,onClick:()=>n(q.id),"aria-label":q.name,title:`${q.name}${ie?` — ${ie}`:""}`,children:[_.jsx("span",{className:"server-list-chip-initial",children:Uy(q.name)}),_.jsx("span",{className:"server-list-chip-pip","data-status":Hy(I)})]},q.id)})]}):_.jsxs("div",{className:"server-list",children:[_.jsx("div",{className:"server-list-row",children:ce?_.jsx("form",{className:"server-list-editor",onSubmit:q=>{q.preventDefault(),re()},children:_.jsx("input",{ref:C,"aria-label":"Rename main server",value:b,onChange:q=>x(q.target.value),onBlur:()=>{re()},onKeyDown:q=>{q.key==="Escape"&&(q.preventDefault(),F())},placeholder:Py})}):_.jsxs("button",{type:"button",className:`server-list-item${t===null?" server-list-item--active":""}`,onClick:()=>n(null),onDoubleClick:q=>{q.preventDefault(),R("main")},title:"Double-click to rename",children:[_.jsxs("span",{className:"server-list-item-header",children:[_.jsx("span",{className:"server-list-dot"}),_.jsx("span",{className:"server-list-name",children:J})]}),_.jsx(Iy,{entry:k.__main__})]})}),d.map(q=>{const I=S?.kind==="agent"&&S.id===q.id;return _.jsx("div",{className:"server-list-row",children:I?_.jsx("form",{className:"server-list-editor",onSubmit:ie=>{ie.preventDefault(),re()},children:_.jsx("input",{ref:C,"aria-label":`Rename ${q.name}`,value:b,onChange:ie=>x(ie.target.value),onBlur:()=>{re()},onKeyDown:ie=>{ie.key==="Escape"&&(ie.preventDefault(),F())}})}):_.jsxs("button",{type:"button",className:`server-list-item${t===q.id?" server-list-item--active":""}`,onClick:()=>n(q.id),onDoubleClick:ie=>{ie.preventDefault(),R({id:q.id,name:q.name})},title:"Double-click to rename",children:[_.jsxs("span",{className:"server-list-item-header",children:[_.jsx("span",{className:"server-list-dot"}),_.jsx("span",{className:"server-list-name",title:q.url,children:q.name})]}),_.jsx(Iy,{entry:k[q.id]})]})},q.id)})]})}function RE({api:e}){const[t,n]=g.useState([]),[a,o]=g.useState([]),[c,d]=g.useState(!1),[p,m]=g.useState(null),[f,S]=g.useState(""),[y,b]=g.useState("");async function x(){try{const[R,re,F]=await Promise.all([e.listDevices(),e.listNetworks(),e.getSession()]);n(R.devices),o(re.networks),d(F.totpEnabled),m(null)}catch(R){m(R instanceof Error?R.message:"Failed to load")}}g.useEffect(()=>{x()},[]);async function C(R){await e.revokeDevice(R),await x()}async function k(R){await e.removeNetwork(R),await x()}async function B(R){R.preventDefault(),m(null);try{await e.addNetwork({value:f.trim(),label:y.trim()}),S(""),b(""),await x()}catch(re){m(re instanceof Error?re.message:"Failed to add network")}}return _.jsxs(_.Fragment,{children:[p?_.jsx("p",{className:"form-error",children:p}):null,_.jsxs("section",{className:"security-section",children:[_.jsx("h3",{children:"Trusted devices"}),_.jsx("p",{className:"muted",children:"Devices that can re-authenticate with a 2FA code only (no password) for 30 days."}),t.length===0?_.jsx("p",{className:"muted",children:"No trusted devices."}):_.jsx("ul",{className:"security-list",children:t.map(R=>_.jsxs("li",{children:[_.jsxs("div",{children:[_.jsxs("span",{className:"security-item-label",children:[R.label,R.current?_.jsx("span",{className:"security-badge",children:"this device"}):null]}),_.jsxs("span",{className:"security-item-meta",children:["last seen ",new Date(R.lastSeenAt).toLocaleString()]})]}),_.jsx("button",{type:"button",className:"security-remove",onClick:()=>{C(R.id)},children:"revoke"})]},R.id))})]}),_.jsxs("section",{className:"security-section",children:[_.jsx("h3",{children:"Trusted networks"}),_.jsx("p",{className:"muted",children:"Sessions from these IPs/ranges skip the 2FA re-auth prompt."}),a.length===0?_.jsx("p",{className:"muted",children:"No trusted networks."}):_.jsx("ul",{className:"security-list",children:a.map(R=>_.jsxs("li",{children:[_.jsxs("div",{children:[_.jsx("span",{className:"security-item-label",children:R.value}),R.label!==R.value?_.jsx("span",{className:"security-item-meta",children:R.label}):null]}),_.jsx("button",{type:"button",className:"security-remove",onClick:()=>{k(R.id)},children:"remove"})]},R.id))}),_.jsxs("form",{className:"security-add-form",onSubmit:B,children:[_.jsx("input",{type:"text",placeholder:"IP or CIDR (e.g. 203.0.113.4 or 192.168.0.0/24)",value:f,onChange:R=>S(R.currentTarget.value),required:!0}),_.jsx("input",{type:"text",placeholder:"Label (optional)",value:y,onChange:R=>b(R.currentTarget.value)}),_.jsx("button",{type:"submit",disabled:!f.trim(),children:"Add"})]})]}),c?_.jsxs("section",{className:"security-section",children:[_.jsx("h3",{children:"Two-factor authentication"}),_.jsx("p",{className:"muted",children:"2FA is enabled. Disabling it removes the requirement; you will be asked to set it up again on next login."}),_.jsx("button",{type:"button",className:"security-remove",onClick:async()=>{await e.disableTotp(),await x()},children:"Disable 2FA"})]}):null]})}const $b="nterminal.notifications.completionEnabled",tm="nterminal.notifications.completionToastEnabled",im="nterminal.notifications.completionToastDurationSeconds",sm="nterminal.notifications.completionToastPersistent",Nf="nterminal:completion-toast-display",Jl=6.5,Bf=2,Lf=60;function Mu(){return typeof window<"u"&&"Notification"in window}function Vb(){try{return window.localStorage.getItem($b)==="true"}catch{return!1}}function Fy(e){try{window.localStorage.setItem($b,e?"true":"false")}catch{}}function zr(){return{enabled:BE(),durationSeconds:NE(),persistUntilDismissed:LE()}}function ME(e){if(typeof window<"u"){try{window.localStorage.setItem(tm,e?"true":"false")}catch{}rm()}return zr()}function qy(e){const t=Gb(e);if(typeof window<"u"){try{window.localStorage.setItem(im,String(t))}catch{}rm()}return zr()}function AE(e){if(typeof window<"u"){try{window.localStorage.setItem(sm,e?"true":"false")}catch{}rm()}return zr()}function Xb(e){if(typeof window>"u")return()=>{};const t=n=>{(n.key===tm||n.key===im||n.key===sm)&&e()};return window.addEventListener(Nf,e),window.addEventListener("storage",t),()=>{window.removeEventListener(Nf,e),window.removeEventListener("storage",t)}}function nm(){return Mu()?window.Notification.permission:"unsupported"}function NE(){if(typeof window>"u")return Jl;try{const e=window.localStorage.getItem(im);return e===null?Jl:Gb(Number(e))}catch{return Jl}}function BE(){if(typeof window>"u")return!0;try{return window.localStorage.getItem(tm)!=="false"}catch{return!0}}function LE(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(sm)==="true"}catch{return!1}}function Gb(e){if(!Number.isFinite(e))return Jl;const t=Math.round(e*2)/2;return Math.max(Bf,Math.min(Lf,t))}function rm(){typeof window<"u"&&window.dispatchEvent(new CustomEvent(Nf))}async function OE(){if(!Mu())return"unsupported";try{return await window.Notification.requestPermission()}catch{return nm()}}function zE(e){if(!Mu()||nm()!=="granted"||!Vb()||typeof document<"u"&&document.visibilityState==="visible")return;const t=e.commandName?`${e.commandName} finished`:"Command finished";try{new Notification(`NTerminal · ${e.tabTitle}`,{body:t,tag:e.terminalId,icon:"/icons/app-icon-384.png",silent:!0})}catch{}}const jE=1500,am="nterminal.terminal.fontSize",lm="nterminal.terminal.fontFamily",Of="nterminal:terminal-font-size",zf="nterminal:terminal-font-family",jf=11,Hf=20,Lr=14,hu=[{id:"meslo",label:"MesloLGS NF",cssFamily:['"MesloLGS NF"','"MesloLGS Nerd Font Mono"','"MesloLGSNerdFontMono"','"JetBrainsMono Nerd Font"','"Hack Nerd Font"','"FiraCode Nerd Font"','"SF Mono"',"Menlo","Monaco","Consolas",'"Liberation Mono"','"Symbols Nerd Font Mono"','"Apple Symbols"','"Apple Color Emoji"',"monospace"].join(", "),webFontFamilies:['"MesloLGS NF"']},{id:"jetbrains",label:"JetBrains Mono",cssFamily:['"JetBrainsMono Nerd Font"','"JetBrains Mono"','"Hack Nerd Font"','"FiraCode Nerd Font"','"SF Mono"',"Menlo","Monaco","Consolas",'"Liberation Mono"','"Symbols Nerd Font Mono"','"Apple Symbols"','"Apple Color Emoji"',"monospace"].join(", "),webFontFamilies:[]},{id:"system",label:"System mono",cssFamily:['"SF Mono"',"Menlo","Monaco","Consolas",'"Liberation Mono"','"Symbols Nerd Font Mono"','"Apple Symbols"','"Apple Color Emoji"',"monospace"].join(", "),webFontFamilies:[]}],Na="meslo";Uf(Na);async function tf(e=Lr,t=Na){if(typeof document>"u"||!document.fonts)return;const n=Jb(t).webFontFamilies;if(n.length===0)return;const a=Promise.all(n.map(o=>document.fonts.load(`${e}px ${o}`))).then(()=>{}).catch(()=>{});await Promise.race([a,new Promise(o=>{globalThis.setTimeout(o,jE)})])}function Zb(e){const t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return Lr;const n=Math.round(t);return Math.max(jf,Math.min(Hf,n))}function Qb(e){return hu.some(t=>t.id===e)?e:Na}function Uf(e){return Jb(e).cssFamily}function Jb(e){return hu.find(t=>t.id===e)??hu[0]}function Pf(){if(typeof window>"u")return Lr;try{const e=window.localStorage.getItem(am);return e?Zb(e):Lr}catch{return Lr}}function Kf(){if(typeof window>"u")return Na;try{return Qb(window.localStorage.getItem(lm))}catch{return Na}}function Hc(e){const t=Zb(e);if(typeof window>"u")return t;try{window.localStorage.setItem(am,String(t))}catch{}return window.dispatchEvent(new CustomEvent(Of,{detail:t})),t}function HE(e){const t=Qb(e);if(typeof window>"u")return t;try{window.localStorage.setItem(lm,t)}catch{}return window.dispatchEvent(new CustomEvent(zf,{detail:t})),t}function e0(e){if(typeof window>"u")return()=>{};const t=n=>{n.key===am&&e()};return window.addEventListener(Of,e),window.addEventListener("storage",t),()=>{window.removeEventListener(Of,e),window.removeEventListener("storage",t)}}function t0(e){if(typeof window>"u")return()=>{};const t=n=>{n.key===lm&&e()};return window.addEventListener(zf,e),window.addEventListener("storage",t),()=>{window.removeEventListener(zf,e),window.removeEventListener("storage",t)}}const om="nterminal.terminal.showScrollProgress",If="nterminal:terminal-scroll-progress";function Ff(){if(typeof window>"u")return!0;try{return window.localStorage.getItem(om)!=="false"}catch{return!0}}function UE(e){if(typeof window<"u"){try{window.localStorage.setItem(om,e?"true":"false")}catch{}window.dispatchEvent(new CustomEvent(If,{detail:e}))}return e}function i0(e){if(typeof window>"u")return()=>{};const t=n=>{n.key===om&&e()};return window.addEventListener(If,e),window.addEventListener("storage",t),()=>{window.removeEventListener(If,e),window.removeEventListener("storage",t)}}const cm="nterminal.shortcuts.workspace.v1",qf="nterminal:workspace-shortcuts",ro=[{id:"server.previous",label:"Previous server",group:"Servers"},{id:"server.next",label:"Next server",group:"Servers"},{id:"tab.previous",label:"Previous tab",group:"Tabs"},{id:"tab.next",label:"Next tab",group:"Tabs"},{id:"tab.index",label:"Select tab 1-9",group:"Tabs",indexed:!0},{id:"pane.index",label:"Select pane 1-9",group:"Panes",indexed:!0},{id:"split.right",label:"Split right",group:"Panes"},{id:"split.down",label:"Split down",group:"Panes"}],um={"server.previous":Mi("ArrowUp",{ctrlKey:!0}),"server.next":Mi("ArrowDown",{ctrlKey:!0}),"tab.previous":Mi("ArrowLeft",{ctrlKey:!0}),"tab.next":Mi("ArrowRight",{ctrlKey:!0}),"tab.index":Mi("Digit",{ctrlKey:!0,altKey:!0}),"pane.index":Mi("Digit",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"split.right":Mi("ArrowRight",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"split.down":Mi("ArrowDown",{ctrlKey:!0,altKey:!0,shiftKey:!0})},PE={"server.previous":Mi("BracketLeft",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"server.next":Mi("BracketRight",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"tab.previous":Mi("BracketLeft",{ctrlKey:!0,altKey:!0}),"tab.next":Mi("BracketRight",{ctrlKey:!0,altKey:!0}),"tab.index":Mi("Digit",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"pane.index":Mi("Digit",{ctrlKey:!0,altKey:!0}),"split.right":Mi("ArrowRight",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"split.down":Mi("ArrowDown",{ctrlKey:!0,altKey:!0,shiftKey:!0})};function jr(){const e=a0(um);if(typeof window>"u")return e;try{const t=window.localStorage.getItem(cm);if(!t)return e;const n=JSON.parse(t);for(const a of ro){const o=n[a.id];if(XE(o)){const c=l0(o,a);VE(c,PE[a.id])||(e[a.id]=c)}}}catch{return e}return e}function Wy(){return JSON.stringify(jr())}function KE(e,t){const n=jr(),a=ro.find(o=>o.id===e);return a&&(n[e]=l0(t,a),hm(n)),n}function IE(e){const t=jr();return t[e]={...um[e]},hm(t),t}function FE(){const e=a0(um);return hm(e),e}function s0(e){if(typeof window>"u")return()=>{};const t=n=>{n.key===cm&&e()};return window.addEventListener(qf,e),window.addEventListener("storage",t),()=>{window.removeEventListener(qf,e),window.removeEventListener("storage",t)}}function qE(e,t){const n=c0(e);return!n||ZE(n)||t.indexed&&o0(e)===null?null:{ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey,metaKey:e.metaKey,code:t.indexed?"Digit":n}}function WE(e){const t=jr();for(const n of ro){const a=t[n.id];if(!(!a||!GE(e,a))){if(n.indexed){if(a.code!=="Digit")continue;const o=o0(e);if(o!==null)return{id:n.id,index:o};continue}if(c0(e)===a.code)return{id:n.id,index:null}}}return null}function n0(e){return r0(jr()[e])}function r0(e){const t=[];return e.ctrlKey&&t.push("Ctrl"),e.altKey&&t.push("Alt"),e.shiftKey&&t.push("Shift"),e.metaKey&&t.push("Meta"),t.push(QE(e.code)),t.join("+")}const YE=()=>n0("split.right"),$E=()=>n0("split.down");function Mi(e,t){return{ctrlKey:t.ctrlKey??!1,altKey:t.altKey??!1,shiftKey:t.shiftKey??!1,metaKey:t.metaKey??!1,code:e}}function a0(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n}]))}function VE(e,t){return e.ctrlKey===t.ctrlKey&&e.altKey===t.altKey&&e.shiftKey===t.shiftKey&&e.metaKey===t.metaKey&&e.code===t.code}function hm(e){if(!(typeof window>"u")){try{window.localStorage.setItem(cm,JSON.stringify(e))}catch{}window.dispatchEvent(new CustomEvent(qf))}}function l0(e,t){return{ctrlKey:!!e.ctrlKey,altKey:!!e.altKey,shiftKey:!!e.shiftKey,metaKey:!!e.metaKey,code:t.indexed?"Digit":e.code}}function XE(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.ctrlKey=="boolean"&&typeof t.altKey=="boolean"&&typeof t.shiftKey=="boolean"&&typeof t.metaKey=="boolean"&&typeof t.code=="string"&&t.code.length>0}function GE(e,t){return e.ctrlKey===t.ctrlKey&&e.altKey===t.altKey&&e.shiftKey===t.shiftKey&&e.metaKey===t.metaKey}function o0(e){const t=/^Digit([1-9])$/.exec(e.code);return t?.[1]?Number(t[1]):/^[1-9]$/.test(e.key)?Number(e.key):null}function c0(e){if(e.code)return e.code;if(/^[a-z]$/i.test(e.key))return`Key${e.key.toUpperCase()}`;if(/^[0-9]$/.test(e.key))return`Digit${e.key}`;switch(e.key){case"[":case"{":return"BracketLeft";case"]":case"}":return"BracketRight";case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":case"Tab":case"Enter":case"Escape":case"Space":return e.key==="Space"?"Space":e.key;default:return null}}function ZE(e){return e==="ControlLeft"||e==="ControlRight"||e==="AltLeft"||e==="AltRight"||e==="ShiftLeft"||e==="ShiftRight"||e==="MetaLeft"||e==="MetaRight"}function QE(e){if(e==="Digit")return"1-9";const t=/^Digit([0-9])$/.exec(e);if(t?.[1])return t[1];const n=/^Key([A-Z])$/.exec(e);if(n?.[1])return n[1];switch(e){case"BracketLeft":return"[";case"BracketRight":return"]";case"ArrowLeft":return"Left";case"ArrowRight":return"Right";case"ArrowUp":return"Up";case"ArrowDown":return"Down";case"Space":return"Space";default:return e.replace(/^(Numpad|Digit|Key)/,"")}}const dm="nterminal.theme.accent",Wf="nterminal:theme-accent",ao=[{id:"aqua",label:"Aqua Teal",accent:"#5EEAD4",soft:"rgba(94, 234, 212, 0.10)",glow:"rgba(94, 234, 212, 0.55)",xtermSelection:"#1f3f45"},{id:"signal-red",label:"Signal Red",accent:"#FF2A3D",soft:"rgba(255, 42, 61, 0.12)",glow:"rgba(255, 42, 61, 0.52)",xtermSelection:"#4a1b22"}],du="aqua";function wo(e){return ao.some(t=>t.id===e)?e:du}function fm(e){return ao.find(t=>t.id===e)??ao[0]}function lr(){if(typeof window>"u")return du;try{return wo(window.localStorage.getItem(dm))}catch{return du}}function JE(e){const t=wo(e);if(typeof window<"u"){try{window.localStorage.setItem(dm,t)}catch{}pm(t),window.dispatchEvent(new CustomEvent(Wf,{detail:t}))}return t}function pm(e=lr()){if(typeof document>"u")return;const t=fm(wo(e)),n=document.documentElement;n.style.setProperty("--nt-accent",t.accent),n.style.setProperty("--nt-accent-soft",t.soft),n.style.setProperty("--nt-accent-glow",t.glow)}function e2(e=lr()){return fm(wo(e)).accent}function t2(e=lr()){return fm(wo(e)).xtermSelection}function u0(e){if(typeof window>"u")return()=>{};const t=n=>{n.key===dm&&(pm(lr()),e())};return window.addEventListener(Wf,e),window.addEventListener("storage",t),()=>{window.removeEventListener(Wf,e),window.removeEventListener("storage",t)}}const i2="Automatic update needs write access to the global npm install. Run the manual update command as the NTerminal runtime user; only the npm install step should use sudo.";function s2(e="nterminal",t=new Date){return{reason:"permission",message:i2,command:`sudo npm i -g ${e}@latest --prefer-online && nterminal restart`,detectedAt:t.toISOString()}}function n2(e){return/\b(?:EACCES|EPERM)\b|permission denied|missing write access|access denied|operation was rejected by your operating system|operation not permitted|root-owned files/i.test(e)}const h0=3600*1e3,r2="local",Yf=new Set,nr=new Map;let or={checking:!1,hasUpdates:!1,lastCheckedAt:null},mm=null,eo=null,fu=0,Jn=null;function a2(e){return Yf.add(e),()=>{Yf.delete(e)}}function Yy(){return or}function l2(e){const t=d2();mm=e,_m(),$f(e,t);const n=()=>{if(document.visibilityState!=="visible"||!cr(e,t))return;const a=or.lastCheckedAt;(a===null||Date.now()-a>=h0)&&$f(e,t)};return document.addEventListener("visibilitychange",n),()=>{document.removeEventListener("visibilitychange",n),cr(e,t)&&h2()}}function o2(e,t){nr.set(e,d0(t)),Ba({...or,hasUpdates:vm(),lastCheckedAt:Date.now()})}function sf(e){e===void 0?nr.clear():nr.set(e,!1),Ba({...or,hasUpdates:vm()})}async function $f(e,t){if(!cr(e,t))return;if(Jn&&Jn.api===e&&Jn.runId===t)return Jn.promise;Ba({...or,checking:!0});const n=c2(e,t).finally(()=>{Jn?.promise===n&&(Jn=null),cr(e,t)&&(Ba({...or,checking:!1,lastCheckedAt:Date.now()}),u2(e,t))});return Jn={api:e,runId:t,promise:n},n}async function c2(e,t){try{const n=await e.listAgents();if(!cr(e,t))return;const a=[{key:r2,check:()=>e.checkUpdate()},...n.agents.map(c=>({key:c.id,check:()=>e.checkAgentUpdate(c.id)}))],o=new Map;if(await Promise.all(a.map(async c=>{try{const d=await c.check();o.set(c.key,d0(d))}catch{o.set(c.key,nr.get(c.key)??!1)}})),!cr(e,t))return;nr.clear();for(const[c,d]of o)nr.set(c,d);Ba({...or,hasUpdates:vm()})}catch{}}function u2(e,t){cr(e,t)&&(_m(),eo=window.setTimeout(()=>{eo=null,cr(e,t)&&$f(e,t)},h0))}function h2(){fu+=1,_m(),mm=null,Jn=null,nr.clear(),Ba({checking:!1,hasUpdates:!1,lastCheckedAt:null})}function _m(){eo!==null&&(window.clearTimeout(eo),eo=null)}function d2(){return fu+=1,fu}function cr(e,t){return mm===e&&fu===t}function d0(e){return e.updateAvailable===!0}function vm(){return Array.from(nr.values()).some(Boolean)}function Ba(e){or=e;for(const t of Array.from(Yf))t()}const f2=e=>new Promise(t=>setTimeout(t,e));function p2({api:e,onAgentRemoved:t}){const[n,a]=g.useState([{key:"local",id:null,name:"Local (main)"}]),[o,c]=g.useState({}),[d,p]=g.useState(!1),[m,f]=g.useState(null),[S,y]=g.useState(!1);function b(j,$){c(H=>({...H,[j]:{...H[j],...$}}))}const x=j=>j.id===null?e.getVersion():e.getAgentVersion(j.id),C=j=>j.id===null?e.checkUpdate():e.checkAgentUpdate(j.id),k=j=>j.id===null?e.runUpdate():e.runAgentUpdate(j.id);g.useEffect(()=>{let j=!1;return e.listAgents().then($=>{if(j)return;const H=[{key:"local",id:null,name:"Local (main)"},...$.agents.map(L=>({key:L.id,id:L.id,name:L.name}))];a(H);for(const L of H)x(L).then(X=>b(L.key,{version:X,manualUpdate:X.manualUpdate??null})).catch(X=>b(L.key,{error:X instanceof Error?X.message:"unreachable"}))}).catch(()=>{}),()=>{j=!0}},[]);async function B(j){b(j.key,{busy:!0,status:"checking…",error:void 0});try{const $=await C(j);o2(j.key,$),b(j.key,{latestVersion:$.latestVersion,updateAvailable:$.updateAvailable,status:I($),...$.updateAvailable===!1?{manualUpdate:null}:{},busy:!1})}catch($){b(j.key,{busy:!1,error:$ instanceof Error?$.message:"check failed"})}}async function R(){p(!0),await Promise.all(n.map(j=>B(j))),p(!1)}async function re(j,$){const H=Date.now()+18e4;for(;Date.now()<H;){await f2(3e3);try{const L=await x(j);if($&&L.runningVersion!==$.runningVersion)return L}catch{}}return null}async function F(j,$={}){let H=o[j.key]?.version;if(!H)try{H=await x(j),b(j.key,{version:H,manualUpdate:H.manualUpdate??null})}catch(M){return b(j.key,{busy:!1,error:M instanceof Error?M.message:"version check failed"}),"failed"}const L=o[j.key]?.manualUpdate??H.manualUpdate??null;if(L&&$.skipManual)return b(j.key,{busy:!1,status:"manual update required",error:void 0,manualUpdate:L}),"manual";b(j.key,{busy:!0,status:"updating…",error:void 0});let X;try{X=await k(j)}catch(M){return b(j.key,{busy:!1,error:M instanceof Error?M.message:"update failed"}),"failed"}if(!X.ok){const M=X.manualUpdate??(n2(X.message)?s2():null);return M?(b(j.key,{busy:!1,status:"manual update required",error:void 0,manualUpdate:M}),"manual"):(b(j.key,{busy:!1,status:void 0,error:X.message}),"failed")}if(!X.changed)return b(j.key,{busy:!1,status:"already up to date",updateAvailable:!1,manualUpdate:null}),sf(j.key),"unchanged";b(j.key,{status:"restarting…"});const G=await re(j,H);return G?(b(j.key,{busy:!1,version:G,updateAvailable:!1,status:"updated",manualUpdate:G.manualUpdate??null}),sf(j.key),j.id===null&&(y(!0),f("Main server updated. Reload the page to use the new client.")),"updated"):(b(j.key,{busy:!1,status:void 0,error:"timed out — check the server log"}),"failed")}async function J(j){if(!(j.id===null||!window.confirm([`Delete secondary server "${j.name}"?`,"","If the secondary is reachable, NTerminal will schedule a clean uninstall on that host, stop its runtime, remove its local state, and remove it from this main server.","If it is already gone or unreachable, only the stale registration on this main server will be removed.","","This can close live terminals on that secondary. Continue?"].join(`
14
- `)))){b(j.key,{busy:!0,status:"deleting…",error:void 0}),f(null);try{const H=await e.uninstallAgent(j.id);a(L=>L.filter(X=>X.key!==j.key)),c(L=>{const X={...L};return delete X[j.key],X}),sf(j.key),t?.(j.id),f(H.message)}catch(H){b(j.key,{busy:!1,status:void 0,error:H instanceof Error?H.message:"delete failed"})}}}async function ce(){p(!0),f(null);const j=n.filter(G=>G.id!==null),$=n.find(G=>G.id===null),H=await Promise.all(j.map(G=>F(G,{skipManual:!0}))),L=H.filter(G=>G==="failed").length;let X=H.filter(G=>G==="manual").length;if(L>0){p(!1);return}if($){const G=await F($,{skipManual:!0});if(G==="manual"&&(X+=1),G==="updated"){p(!1);return}}X>0&&f("Some servers need manual update. Copy and run the command shown on each marked server."),p(!1)}function q(j){return j?j.error?j.error:j.status?j.status:j.manualUpdate?"manual update required":j.version?`v${j.version.version}`:"…":"…"}function I(j){return j.error?j.error:typeof j.updateAvailable=="boolean"?j.updateAvailable?`latest v${j.latestVersion??"available"}`:"up to date":"unknown"}function ie(j){const $=j?.version;return $?`npm package v${$.runningVersion}`:""}async function de(j,$){try{await m2($),b(j,{copiedCommand:!0}),window.setTimeout(()=>b(j,{copiedCommand:!1}),1800)}catch(H){b(j,{error:H instanceof Error?H.message:"copy failed"})}}return _.jsxs("section",{className:"security-section",children:[_.jsx("h3",{children:"Servers"}),_.jsxs("div",{className:"update-actions",children:[_.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{R()},disabled:d,children:"Check for updates"}),_.jsx("button",{type:"button",onClick:()=>{ce()},disabled:d,children:"Update all"})]}),m?_.jsx("p",{className:"settings-status",children:m}):null,S?_.jsxs("div",{className:"server-reload-required",role:"status",children:[_.jsx("span",{children:"Main server update is ready."}),_.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:"Reload page"})]}):null,_.jsx("ul",{className:"security-list",children:n.map(j=>{const $=o[j.key],H=ie($),L=$?.manualUpdate??null,X=$?.version!==void 0&&$?.updateAvailable!==!1&&!L&&!$?.busy&&!d,G=j.id!==null&&!$?.busy&&!d;return _.jsxs("li",{children:[_.jsxs("div",{className:"server-row-main",children:[_.jsxs("div",{children:[_.jsx("span",{className:"security-item-label",children:j.name}),_.jsxs("span",{className:"security-item-meta",children:[H?`${H} — `:"",q($)]})]}),L?_.jsxs("div",{className:"server-manual-update",children:[_.jsx("span",{children:L.message}),_.jsxs("div",{className:"server-manual-command",children:[_.jsx("code",{children:L.command}),_.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{de(j.key,L.command)},children:$?.copiedCommand?"Copied":"Copy"})]})]}):null]}),_.jsxs("div",{className:"server-row-actions",children:[_.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{F(j)},disabled:!X,children:$?.busy?"…":"Update"}),j.id!==null?_.jsx("button",{type:"button",className:"server-delete-button",onClick:()=>{J(j)},disabled:!G,children:"Delete"}):null]})]},j.key)})})]})}async function m2(e){if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(e);return}const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{if(!document.execCommand("copy"))throw new Error("copy failed")}finally{t.remove()}}const Uc=[{id:"terminal",label:"Terminal"},{id:"shortcuts",label:"Shortcuts"},{id:"notifications",label:"Notifications"},{id:"security",label:"Security"},{id:"servers",label:"Servers"}];function _2({onClose:e,api:t,updateAvailable:n=!1,onNotificationAssetsChanged:a,onAgentRemoved:o}){const c=g.useMemo(()=>t??Eu(),[t]),[d,p]=g.useState(()=>Pf()),[m,f]=g.useState(()=>Kf()),[S,y]=g.useState(()=>Ff()),[b,x]=g.useState(()=>lr()),[C,k]=g.useState(()=>jr()),[B,R]=g.useState(null),[re,F]=g.useState(null),[J,ce]=g.useState("terminal"),[q,I]=g.useState(()=>Vb()),[ie,de]=g.useState(()=>zr()),[j,$]=g.useState(()=>nm()),[H,L]=g.useState([]),[X,G]=g.useState([]),[M,V]=g.useState([]),[Q,ve]=g.useState(5*1024*1024),[Se,E]=g.useState(!1),[W,ee]=g.useState(null),he=g.useRef(null),ge=g.useRef(null),me=g.useRef({terminal:null,shortcuts:null,notifications:null,security:null,servers:null}),Ce=g.useMemo(()=>new Set(X),[X]),ze=!v2(X,M);g.useEffect(()=>e0(()=>p(Pf())),[]),g.useEffect(()=>t0(()=>f(Kf())),[]),g.useEffect(()=>i0(()=>y(Ff())),[]),g.useEffect(()=>u0(()=>x(lr())),[]),g.useEffect(()=>s0(()=>k(jr())),[]),g.useEffect(()=>Xb(()=>de(zr())),[]),g.useEffect(()=>{if(!B)return;const te=ro.find(He=>He.id===B);if(!te)return;const je=He=>{if(He.preventDefault(),He.stopPropagation(),He.key==="Escape"){R(null),F(null);return}const _i=qE(He,te);if(!_i){F(te.indexed?"Press a shortcut ending in a number from 1 to 9.":"Press a complete shortcut.");return}k(KE(B,_i)),R(null),F(null)};return window.addEventListener("keydown",je,!0),()=>window.removeEventListener("keydown",je,!0)},[B]),g.useEffect(()=>{let te=!1;return c.listNotificationAssets().then(je=>{te||Ee(je)}).catch(je=>{te||ee(Pc(je))}),()=>{te=!0}},[c]);function Ne(te){p(Hc(Number(te)))}function Re(te){de(qy(Number(te)))}function Pe(te){ce(te),me.current[te]?.scrollIntoView?.({block:"start",behavior:"smooth"})}function Ye(){const te=ge.current;if(!te)return;if(te.scrollTop+te.clientHeight>=te.scrollHeight-2){ce(Uc[Uc.length-1].id);return}const je=te.getBoundingClientRect();let He="terminal",_i=0;for(const Vi of Uc){const ai=me.current[Vi.id];if(!ai)continue;const kt=ai.getBoundingClientRect(),ji=Math.max(kt.top,je.top),Ti=Math.min(kt.bottom,je.bottom),Nt=Math.max(0,Ti-ji);Nt>_i&&(He=Vi.id,_i=Nt)}ce(He)}function Be(te){k(IE(te)),R(null),F(null)}function ae(){k(FE()),R(null),F(null)}function Ee(te){const je=te.assets.filter(He=>He.enabled).map(He=>He.id);L(te.assets),G(je),V(je),ve(te.maxFileBytes),ee(null)}async function xe(){if(q){Fy(!1),I(!1);return}let te=j;te==="default"&&(te=await OE(),$(te)),te==="granted"&&(Fy(!0),I(!0))}async function Ke(te){const je=te?.[0];if(je){if(je.size>Q){ee(`File must be ${nf(Q)} or smaller.`),gt();return}if(je.type!=="video/mp4"&&je.type!=="video/webm"){ee("Upload an MP4 or WebM video."),gt();return}E(!0),ee(null);try{await c.uploadNotificationAsset(je),Ee(await c.listNotificationAssets()),a?.()}catch(He){ee(Pc(He))}finally{E(!1),gt()}}}async function Xe(te){E(!0),ee(null);try{await c.deleteNotificationAsset(te),Ee(await c.listNotificationAssets()),a?.()}catch(je){ee(Pc(je))}finally{E(!1)}}function gt(){he.current&&(he.current.value="")}function yt(te,je){const He=new Set(X);if(je?He.add(te):He.delete(te),He.size===0){ee("Keep at least one toast video selected.");return}ee(null),G(Array.from(He))}async function mi(){if(X.length===0){ee("Keep at least one toast video selected.");return}E(!0),ee(null);try{const te=await c.updateNotificationAssetSelection({enabledAssetIds:X});Ee(te),a?.()}catch(te){ee(Pc(te))}finally{E(!1)}}return _.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-label":"Settings",onClick:e,children:_.jsxs("div",{className:"security-panel settings-panel",onClick:te=>te.stopPropagation(),children:[_.jsxs("header",{className:"security-panel-header",children:[_.jsx("h2",{children:"Settings"}),_.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:e,children:"×"})]}),_.jsxs("div",{className:"settings-layout",children:[_.jsx("nav",{className:"settings-nav","aria-label":"Settings categories",children:Uc.map(te=>_.jsxs("button",{type:"button","data-active":J===te.id?"true":"false","aria-current":J===te.id?"true":void 0,onClick:()=>Pe(te.id),children:[te.label,te.id==="servers"&&n?_.jsx("span",{className:"update-pulse-dot settings-update-dot","aria-hidden":"true"}):null]},te.id))}),_.jsxs("div",{ref:ge,className:"settings-content",onScroll:Ye,children:[_.jsxs("section",{id:"settings-terminal",ref:te=>{me.current.terminal=te},className:"security-section settings-section",children:[_.jsx("h3",{children:"Terminal"}),_.jsxs("label",{className:"settings-control",children:[_.jsx("span",{children:"Font size"}),_.jsxs("span",{className:"settings-control-value",children:[d,"px"]}),_.jsx("input",{type:"range",min:jf,max:Hf,step:1,value:d,"aria-label":"Terminal font size",onChange:te=>Ne(te.currentTarget.value)})]}),_.jsxs("div",{className:"settings-stepper-row",children:[_.jsx("button",{type:"button",className:"secondary-button settings-stepper-button",onClick:()=>p(Hc(d-1)),children:"-"}),_.jsx("input",{type:"number",min:jf,max:Hf,step:1,value:d,"aria-label":"Terminal font size value",onChange:te=>Ne(te.currentTarget.value)}),_.jsx("button",{type:"button",className:"secondary-button settings-stepper-button",onClick:()=>p(Hc(d+1)),children:"+"}),_.jsx("button",{type:"button",className:"secondary-button settings-reset-button",onClick:()=>p(Hc(Lr)),children:"Reset"})]}),_.jsxs("label",{className:"settings-control",children:[_.jsx("span",{children:"Font family"}),_.jsx("select",{value:m,"aria-label":"Terminal font family",onChange:te=>f(HE(te.currentTarget.value)),children:hu.map(te=>_.jsx("option",{value:te.id,children:te.label},te.id))})]}),_.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[_.jsx("input",{type:"checkbox",checked:S,onChange:te=>y(UE(te.currentTarget.checked))}),"Show scroll progress"]}),_.jsxs("label",{className:"settings-control",children:[_.jsx("span",{children:"Accent theme"}),_.jsx("select",{value:b,"aria-label":"Theme accent",onChange:te=>x(JE(te.currentTarget.value)),children:ao.map(te=>_.jsx("option",{value:te.id,children:te.label},te.id))})]}),_.jsx("div",{className:"settings-theme-swatches","aria-hidden":"true",children:ao.map(te=>_.jsx("span",{className:"settings-theme-swatch","data-active":b===te.id?"true":"false",style:{"--settings-theme-accent":te.accent}},te.id))})]}),_.jsxs("section",{id:"settings-shortcuts",ref:te=>{me.current.shortcuts=te},className:"security-section settings-section",children:[_.jsxs("div",{className:"settings-section-heading",children:[_.jsx("h3",{children:"Shortcuts"}),_.jsx("button",{type:"button",className:"secondary-button settings-reset-button",onClick:ae,children:"Reset all"})]}),_.jsx("p",{className:"muted",children:"Defaults avoid Chrome's browser-tab shortcuts. Click a shortcut, then press the new key combo."}),re?_.jsx("p",{className:"settings-error",children:re}):null,_.jsx("ul",{className:"settings-shortcut-list","aria-label":"Workspace shortcuts",children:ro.map(te=>{const je=B===te.id;return _.jsxs("li",{children:[_.jsxs("div",{children:[_.jsx("span",{className:"settings-shortcut-label",children:te.label}),_.jsx("span",{className:"settings-shortcut-group",children:te.group})]}),_.jsxs("div",{className:"settings-shortcut-actions",children:[_.jsx("button",{type:"button",className:"settings-shortcut-recorder","data-recording":je?"true":"false",onClick:()=>{R(te.id),F(null)},children:je?"Press keys…":r0(C[te.id])}),_.jsx("button",{type:"button",className:"secondary-button settings-shortcut-reset",onClick:()=>Be(te.id),children:"Reset"})]})]},te.id)})})]}),_.jsxs("section",{id:"settings-notifications",ref:te=>{me.current.notifications=te},className:"security-section settings-section",children:[_.jsx("h3",{children:"Notifications"}),Mu()?_.jsxs(_.Fragment,{children:[_.jsxs("label",{className:"auth-checkbox",children:[_.jsx("input",{type:"checkbox",checked:q&&j==="granted",onChange:()=>{xe()},disabled:j==="denied"}),"System notification when page is hidden"]}),j==="denied"?_.jsx("p",{className:"muted",children:"Notification permission is blocked for this site. Re-enable it in the browser's site settings, then come back here to turn the toggle on."}):_.jsx("p",{className:"muted",children:"Uses browser notifications only when this page isn't visible. Animated toast is controlled separately below."})]}):_.jsx("p",{className:"muted",children:"This browser doesn't expose the Notification API; animated toast and in-app badges can still work."}),_.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[_.jsx("input",{type:"checkbox",checked:ie.enabled,onChange:te=>de(ME(te.currentTarget.checked))}),"Show animated completion toast"]}),_.jsxs("label",{className:"settings-control",children:[_.jsx("span",{children:"Toast duration"}),_.jsx("span",{className:"settings-control-value",children:ie.persistUntilDismissed?"Until closed":`${ie.durationSeconds}s`}),_.jsx("input",{type:"range",min:Bf,max:Lf,step:.5,value:ie.durationSeconds,disabled:!ie.enabled||ie.persistUntilDismissed,"aria-label":"Completion toast duration",onChange:te=>Re(te.currentTarget.value)})]}),_.jsxs("div",{className:"settings-stepper-row settings-duration-row",children:[_.jsx("input",{type:"number",min:Bf,max:Lf,step:.5,value:ie.durationSeconds,disabled:!ie.enabled||ie.persistUntilDismissed,"aria-label":"Completion toast duration value",onChange:te=>Re(te.currentTarget.value)}),_.jsx("button",{type:"button",className:"secondary-button settings-reset-button",disabled:!ie.enabled||ie.persistUntilDismissed,onClick:()=>de(qy(Jl)),children:"Reset"})]}),_.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[_.jsx("input",{type:"checkbox",checked:ie.persistUntilDismissed,disabled:!ie.enabled,onChange:te=>de(AE(te.currentTarget.checked))}),"Keep toast until dismissed"]}),_.jsxs("div",{className:"settings-assets-header",children:[_.jsx("span",{children:"Toast videos"}),_.jsxs("span",{children:[nf(Q)," max"]})]}),_.jsx("input",{ref:he,type:"file",accept:"video/mp4,video/webm",className:"settings-asset-input","aria-label":"Upload toast video",onChange:te=>{Ke(te.currentTarget.files)}}),_.jsx("button",{type:"button",className:"secondary-button settings-upload-button",disabled:Se,onClick:()=>he.current?.click(),children:"Upload video"}),W?_.jsx("p",{className:"settings-error",children:W}):null,H.length>0?_.jsx("ul",{className:"settings-asset-list","aria-label":"Toast videos",children:H.map(te=>_.jsxs("li",{"data-enabled":Ce.has(te.id)?"true":"false",children:[_.jsxs("label",{className:"settings-asset-choice",children:[_.jsx("input",{type:"checkbox",checked:Ce.has(te.id),disabled:Se,"aria-label":`Use ${te.filename}`,onChange:je=>yt(te.id,je.currentTarget.checked)}),_.jsx("video",{src:te.url,muted:!0,autoPlay:!0,loop:!0,playsInline:!0,"aria-hidden":"true"}),_.jsxs("span",{className:"settings-asset-copy",children:[_.jsx("span",{children:te.filename}),_.jsx("small",{children:te.source==="built-in"?"Built-in":nf(te.size)})]})]}),te.source==="uploaded"?_.jsx("button",{type:"button",className:"secondary-button settings-asset-delete",disabled:Se,"aria-label":`Delete ${te.filename}`,onClick:()=>{Xe(te.id)},children:"x"}):null]},te.id))}):_.jsx("p",{className:"muted",children:"Built-in videos will be used."}),_.jsx("button",{type:"button",className:"secondary-button settings-save-assets-button",disabled:Se||H.length===0||!ze,onClick:()=>{mi()},children:"Save selected videos"})]}),_.jsx("div",{id:"settings-security",ref:te=>{me.current.security=te},className:"settings-section-group",children:_.jsx(RE,{api:c})}),_.jsx("div",{id:"settings-servers",ref:te=>{me.current.servers=te},className:"settings-section-group",children:_.jsx(p2,{api:c,...o?{onAgentRemoved:o}:{}})})]})]})]})})}function nf(e){return e>=1024*1024?`${Math.round(e/1024/1024*10)/10} MB`:e>=1024?`${Math.round(e/1024*10)/10} KB`:`${e} B`}function Pc(e){return e instanceof Error?e.message:"Request failed."}function v2(e,t){if(e.length!==t.length)return!1;const n=new Set(t);return e.every(a=>n.has(a))}class Dr extends Error{constructor(t,n){super(n),this.status=t,this.name="UploadClientError"}status}function g2(e){const t=e.createXhr?.()??new XMLHttpRequest,n=new FormData,a=e.files.map((o,c)=>({fieldName:`file${c}`,relativePath:o.relativePath,size:o.file.size}));n.append("manifest",JSON.stringify({terminalId:e.terminalId,entries:a}));for(const[o,c]of e.files.entries())n.append(`file${o}`,c.file);return new Promise((o,c)=>{let d=!1;const p=()=>{e.signal?.removeEventListener("abort",S)},m=y=>{d||(d=!0,p(),o(y))},f=y=>{d||(d=!0,p(),c(y))},S=()=>{t.abort(),f(new Dr(0,"Upload aborted."))};if(e.signal?.aborted){f(new Dr(0,"Upload aborted."));return}e.signal?.addEventListener("abort",S,{once:!0}),t.open("POST","/api/uploads"),t.withCredentials=!0,t.upload.onprogress=y=>{if(e.onProgress){if(y.lengthComputable&&y.total>0){e.onProgress({loaded:y.loaded,total:y.total,percent:Math.round(y.loaded/y.total*100)});return}e.onProgress({loaded:y.loaded,total:null,percent:null})}},t.onload=()=>{if(t.status>=200&&t.status<300){try{m(JSON.parse(t.responseText))}catch{f(new Dr(t.status,"Invalid upload response."))}return}f(new Dr(t.status,y2(t.responseText,t.statusText||`HTTP ${t.status}`)))},t.onerror=()=>f(new Dr(0,"Upload failed.")),t.onabort=()=>f(new Dr(0,"Upload aborted.")),t.ontimeout=()=>f(new Dr(0,"Upload timed out.")),t.send(n)})}function y2(e,t){try{const n=JSON.parse(e),a=typeof n.error=="string"?n.error:n.message;if(typeof a=="string"&&a.trim())return a}catch{}return t}const S2="modulepreload",b2=function(e){return"/"+e},$y={},f0=function(t,n,a){let o=Promise.resolve();if(n&&n.length>0){let m=function(f){return Promise.all(f.map(S=>Promise.resolve(S).then(y=>({status:"fulfilled",value:y}),y=>({status:"rejected",reason:y}))))};document.getElementsByTagName("link");const d=document.querySelector("meta[property=csp-nonce]"),p=d?.nonce||d?.getAttribute("nonce");o=m(n.map(f=>{if(f=b2(f),f in $y)return;$y[f]=!0;const S=f.endsWith(".css"),y=S?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${y}`))return;const b=document.createElement("link");if(b.rel=S?"stylesheet":S2,S||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),S)return new Promise((x,C)=>{b.addEventListener("load",x),b.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${f}`)))})}))}function c(d){const p=new Event("vite:preloadError",{cancelable:!0});if(p.payload=d,window.dispatchEvent(p),!p.defaultPrevented)throw d}return o.then(d=>{for(const p of d||[])p.status==="rejected"&&c(p.reason);return t().catch(c)})},w2=g.lazy(()=>f0(()=>import("./MarkdownPreview-Bmnfh7i1.js"),[]));function C2({api:e,activeTerminalId:t,activeTerminalCwd:n,onOpenFile:a}){const[o,c]=g.useState(null),[d,p]=g.useState(""),[m,f]=g.useState({}),[S,y]=g.useState(()=>new Set),[b,x]=g.useState(null),[C,k]=g.useState({type:"empty"}),[B,R]=g.useState("idle"),[re,F]=g.useState(null),J=g.useRef(null),ce=g.useRef(null),q=g.useRef(!1),I=g.useRef(0),ie=g.useRef(null);ie.current===null&&t&&(ie.current=t);const de=ie.current,j=t?af(t,n):null,$=o?[o.rootPath,d].filter(Boolean).join("/"):"",H=b?.path??null;g.useEffect(()=>(q.current=!0,()=>{q.current=!1,I.current+=1,ze()}),[]),g.useEffect(()=>{ie.current=t,ce.current=null;const ae=t?af(t,n):null;L(t,ae)},[e]),g.useEffect(()=>{if(!de||t!==de)return;const ae=af(de,n);ae!==ce.current&&L(de,ae)},[de,t,n]);async function L(ae,Ee=j){const xe=Ne();if(ce.current=Ee,ze(),c(null),p(""),f({}),y(new Set),x(null),k({type:"empty"}),F(null),!ae){R("idle");return}R("loading");try{const Ke=await e.createFileRoot({terminalId:ae});if(!Re(xe))return;c({rootToken:Ke.rootToken,rootPath:Ke.rootPath});const Xe=await e.listFiles({rootToken:Ke.rootToken,path:""});if(!Re(xe))return;M(Xe),R("idle")}catch(Ke){if(await Pe(Ke,xe))return;Re(xe)&&(F(Xn(Ke)),R("idle"))}}async function X(ae=d,Ee=o){if(!Ee)return;const xe=Ne();R("loading"),F(null);try{const Ke=await e.listFiles({rootToken:Ee.rootToken,path:ae});if(!Re(xe))return;M(Ke),R("idle")}catch(Ke){if(await Pe(Ke,xe))return;Re(xe)&&(F(Xn(Ke)),R("idle"))}}async function G(){ie.current=t,await L(t,j)}function M(ae){f(Ee=>({...Ee,[ae.path]:E2(ae.entries)}))}async function V(ae){if(!(!rf(ae)||!o)){if(x(ae),F(null),ae.kind==="directory"){p(ae.path),Ce(),await ve(ae);return}if(p(Rr(ae.path)),ae.editable){await E(ae);return}ae.previewKind!=="none"&&await ee(ae,ae.previewKind)}}async function Q(ae){if(!(!rf(ae)||!o)){if(x(ae),F(null),ae.kind==="directory"){p(ae.path),Ce(),await ve(ae);return}if(p(Rr(ae.path)),ae.editable){await W(ae);return}ae.previewKind!=="none"&&await ee(ae,ae.previewKind)}}async function ve(ae){if(S.has(ae.path)){y(Ee=>{const xe=new Set(Ee);return xe.delete(ae.path),xe});return}y(Ee=>new Set(Ee).add(ae.path)),await X(ae.path)}function Se(ae,Ee){ae.key==="Enter"&&(ae.preventDefault(),Q(Ee))}async function E(ae){if(!o)return;const Ee=Ne();R("loading"),ze();try{const xe=await e.readFile({rootToken:o.rootToken,path:ae.path});if(!Re(Ee))return;k({type:"text-preview",file:ae,read:xe}),R("idle")}catch(xe){if(await Pe(xe,Ee))return;Re(Ee)&&(F(Xn(xe)),R("idle"))}}async function W(ae){if(!o)return;const Ee=Ne();R("loading");try{await a({rootToken:o.rootToken,path:ae.path}),Re(Ee)&&R("idle")}catch(xe){if(await Pe(xe,Ee))return;Re(Ee)&&(F(Xn(xe)),R("idle"))}}async function ee(ae,Ee){if(!o)return;const xe=Ne();R("loading"),ze();try{const Ke=await e.previewFile({rootToken:o.rootToken,path:ae.path});if(!Re(xe))return;const Xe=URL.createObjectURL(Ke);if(!Re(xe)){URL.revokeObjectURL(Xe);return}J.current=Xe,k({type:"preview",file:ae,previewKind:Ee,url:Xe}),R("idle")}catch(Ke){if(await Pe(Ke,xe))return;Re(xe)&&(F(Xn(Ke)),R("idle"))}}async function he(ae){if(!o)return;const Ee=ae==="file"?"New file":"New folder",xe=window.prompt(Ee,""),Ke=b?b.kind==="directory"?b.path:Rr(b.path):d,Xe=Vy(xe,Ke);if(Xe){F(null);try{const gt=await e.createFileEntry({rootToken:o.rootToken,path:Xe,kind:ae});x(gt.entry),await X(Ke)}catch(gt){if(await Pe(gt))return;F(Xn(gt))}}}async function ge(){if(!o||!b)return;const ae=window.prompt("Move selected entry",b.path),Ee=Vy(ae,"");if(!Ee||Ee===b.path)return;const xe=Rr(b.path),Ke=Rr(Ee);F(null);try{const Xe=await e.moveFileEntry({rootToken:o.rootToken,sourcePath:b.path,destinationPath:Ee});x(Xe.entry),p(Xe.entry.kind==="directory"?Xe.entry.path:Rr(Xe.entry.path)),Ce(),await X(xe),Ke!==xe&&await X(Ke)}catch(Xe){if(await Pe(Xe))return;F(Xn(Xe))}}async function me(){if(!o||!b)return;const ae=b.path,Ee=Rr(ae);F(null);try{const xe=await e.previewDeleteFileEntry({rootToken:o.rootToken,path:b.path}),Ke=xe.descendantCount>0?` and ${xe.descendantCount} nested item${xe.descendantCount===1?"":"s"}`:"";if(!window.confirm(`Delete ${xe.path}${Ke}?`))return;await e.deleteFileEntry({rootToken:o.rootToken,path:b.path,previewToken:xe.previewToken}),x(null),p(Ee),y(Xe=>{const gt=new Set(Xe);for(const yt of Xe)(yt===ae||yt.startsWith(`${ae}/`))&&gt.delete(yt);return gt}),Ce(),await X(Ee)}catch(xe){if(await Pe(xe))return;F(Xn(xe))}}function Ce(){I.current+=1,ze(),k({type:"empty"})}function ze(){J.current&&(URL.revokeObjectURL(J.current),J.current=null)}function Ne(){return I.current+=1,I.current}function Re(ae){return q.current&&ae===I.current}async function Pe(ae,Ee){return T2(ae)?(Ee!==void 0&&!Re(Ee)||await L(t,j),!0):!1}function Ye(ae,Ee){const xe=rf(ae),Ke=ae.kind==="directory"&&S.has(ae.path),Xe=m[ae.path]??[],gt={"--file-tree-depth":Ee};return _.jsxs(xi.Fragment,{children:[_.jsxs("button",{type:"button",className:"file-entry-button","data-kind":ae.kind,"data-expanded":Ke,"data-active":H===ae.path,disabled:!xe,style:gt,"aria-expanded":ae.kind==="directory"?Ke:void 0,"aria-label":`${ae.kind==="directory"?"Open folder":"Open file"} ${ae.name}`,title:ae.kind==="directory"?"Expand or collapse folder":"Click to preview. Double-click or press Enter to open.",onClick:()=>{V(ae)},onDoubleClick:()=>{Q(ae)},onKeyDown:yt=>Se(yt,ae),children:[_.jsx("span",{className:"file-entry-disclosure","aria-hidden":"true",children:ae.kind==="directory"?Ke?"▾":"▸":""}),_.jsx("span",{className:"file-entry-name",children:ae.name}),_.jsx("small",{children:x2(ae)})]}),Ke?_.jsx("div",{className:"file-tree-children",role:"group",children:Xe.map(yt=>Ye(yt,Ee+1))}):null]},ae.path)}const Be=m[""]??[];return _.jsxs("section",{className:"file-explorer","aria-label":"Files","aria-busy":B==="loading",children:[_.jsxs("header",{className:"file-explorer-header",children:[_.jsx("div",{className:"file-explorer-path",title:$,children:$||"No active pane"}),_.jsxs("div",{className:"file-explorer-toolbar","aria-label":"File actions",children:[_.jsx("button",{type:"button","aria-label":"Refresh files",title:"Refresh",disabled:!t,onClick:()=>{G()},children:"↻"}),_.jsx("button",{type:"button","aria-label":"New file",title:"New file",disabled:!o,onClick:()=>{he("file")},children:"+"}),_.jsx("button",{type:"button","aria-label":"New folder",title:"New folder",disabled:!o,onClick:()=>{he("directory")},children:"▣"})]})]}),re?_.jsx("div",{className:"file-explorer-alert",role:"alert",children:re}):null,_.jsxs("div",{className:"file-explorer-layout",children:[_.jsx("div",{className:"file-tree","aria-label":$?`Files in ${$}`:"Files",children:Be.map(ae=>Ye(ae,0))}),_.jsxs("section",{className:"file-detail","aria-label":"File detail",children:[_.jsxs("div",{className:"file-detail-header",children:[_.jsx("strong",{children:b?.name??"detail"}),_.jsxs("div",{className:"file-detail-actions",children:[_.jsx("button",{type:"button","aria-label":"Move selected entry",disabled:!b,onClick:()=>{ge()},children:"Move"}),_.jsx("button",{type:"button","aria-label":"Delete selected entry",disabled:!b,onClick:()=>{me()},children:"Delete"})]})]}),B==="loading"?_.jsx("div",{className:"file-detail-empty",children:"loading"}):null,C.type==="empty"&&B!=="loading"?_.jsx("div",{className:"file-detail-empty",children:"No file selected"}):null,C.type==="preview"?_.jsxs("div",{className:"file-preview-frame",children:[C.previewKind==="image"?_.jsx("img",{src:C.url,alt:C.file.name}):null,C.previewKind==="pdf"?_.jsx("iframe",{src:C.url,title:C.file.name}):null]}):null,C.type==="text-preview"&&C.read.language==="markdown"?_.jsx("div",{className:"file-markdown-preview","aria-label":`Preview for ${C.file.name}`,children:_.jsx(g.Suspense,{fallback:_.jsx("div",{className:"file-markdown-preview-loading",children:"loading preview"}),children:_.jsx(w2,{content:C.read.content})})}):null,C.type==="text-preview"&&C.read.language==="text"?_.jsx("pre",{className:"file-text-preview","aria-label":`Preview for ${C.file.name}`,children:C.read.content}):null]})]})]})}function rf(e){return e.kind==="directory"||e.editable||e.previewKind!=="none"}function x2(e){return e.kind==="directory"?"dir":e.editable?"edit":e.previewKind!=="none"?e.previewKind:"unsupported"}function af(e,t){return`${e}\0${t??""}`}function E2(e){return[...e].sort((t,n)=>t.kind==="directory"&&n.kind!=="directory"?-1:t.kind!=="directory"&&n.kind==="directory"?1:t.name.localeCompare(n.name))}function Rr(e){const t=e.split("/").filter(Boolean);return t.pop(),t.join("/")}function Vy(e,t){if(e===null)return null;const n=e.trim().replace(/^\/+/,"").replace(/\/{2,}/g,"/").replace(/\/$/,"");return n?!t||n.includes("/")?n:`${t}/${n}`:null}function Xn(e){return e instanceof Error?e.message:"Request failed"}function T2(e){return e instanceof yn&&e.status===409&&e.message==="terminal_cwd_changed"}const k2=g.lazy(()=>f0(()=>import("./MarkdownPreview-Bmnfh7i1.js"),[]));function Xy({api:e,editor:t,canClose:n,onClose:a}){const[o,c]=g.useState(t.read),[d,p]=g.useState(t.read.content),[m,f]=g.useState("idle"),[S,y]=g.useState(null),[b,x]=g.useState(!1),[C,k]=g.useState("edit"),B=g.useRef(t),R=g.useRef(t.read),re=g.useRef(t.read.content),F=g.useRef(!1),J=g.useRef(!1),ce=g.useRef(0),q=d!==o.content&&m!=="saving"&&!b;g.useEffect(()=>(J.current=!0,()=>{J.current=!1,ce.current+=1}),[]),g.useEffect(()=>{ce.current+=1,F.current=!1,B.current=t,R.current=t.read,re.current=t.read.content,c(t.read),p(t.read.content),f("idle"),y(null),x(!1),k("edit")},[t.id,t.read]),g.useEffect(()=>{B.current=t},[t]),g.useEffect(()=>{R.current=o},[o]),g.useEffect(()=>{re.current=d},[d]),g.useEffect(()=>{if(d===o.content||b)return;const $=window.setInterval(()=>{!F.current&&re.current!==R.current.content&&I()},1e3);return()=>window.clearInterval($)},[d===o.content,b,t.id]);async function I(){if(F.current)return;const $=re.current,H=R.current;if($===H.content)return;const L=B.current,X=ce.current;F.current=!0,f("saving"),y(null),x(!1);try{const G=await e.writeFile({rootToken:L.rootToken,path:L.path,content:$,expectedVersion:H.version});if(!J.current||X!==ce.current)return;const M={...H,content:$,version:G.version};R.current=M,c(M),f(re.current===$?"saved":"idle")}catch(G){if(!J.current||X!==ce.current)return;if(G instanceof yn&&G.status===409){x(!0),f("idle");return}y(D2(G)),f("idle")}finally{X===ce.current&&(F.current=!1)}}const ie=m==="saving"?"saving":m==="saved"?"saved":o.language,de=o.language==="markdown",j=de&&C==="preview";return _.jsxs("section",{className:"editor-pane","aria-label":`Editor pane ${t.title}`,children:[_.jsxs("header",{className:"editor-pane-header",children:[_.jsx("span",{className:"terminal-pane-dot","aria-hidden":"true"}),_.jsx("strong",{children:t.title}),_.jsx("span",{className:"terminal-pane-spacer"}),_.jsx("span",{className:"terminal-pane-state",children:ie}),_.jsx("button",{type:"button","aria-label":`Save ${t.title}`,disabled:!q,onClick:()=>{I()},children:"Save"}),de?_.jsx("button",{type:"button","aria-label":`${j?"Edit":"Preview"} ${t.title}`,onClick:()=>k($=>$==="preview"?"edit":"preview"),children:j?"Edit":"Preview"}):null,n?_.jsx("button",{type:"button",className:"terminal-pane-close","aria-label":`Close editor ${t.title}`,onClick:a,children:"x"}):null]}),S?_.jsx("div",{className:"editor-pane-alert",role:"alert",children:S}):null,b?_.jsx("div",{className:"editor-pane-alert",role:"alert",children:"File changed on disk."}):null,j?_.jsx("div",{className:"editor-markdown-preview","aria-label":`Markdown preview for ${t.title}`,children:_.jsx(g.Suspense,{fallback:_.jsx("div",{className:"editor-markdown-preview-loading",children:"loading preview"}),children:_.jsx(k2,{content:d})})}):_.jsx("textarea",{className:"editor-pane-textarea","aria-label":`Editor for ${t.title}`,spellCheck:!1,value:d,onChange:$=>{const H=$.target.value;re.current=H,p(H),f("idle"),y(null),x(!1)}})]})}function D2(e){return e instanceof Error?e.message:"Request failed"}var R2=2,M2=1,A2=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._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(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),a=parseInt(n.getPropertyValue("height")),o=Math.max(0,parseInt(n.getPropertyValue("width"))),c=window.getComputedStyle(this._terminal.element),d={top:parseInt(c.getPropertyValue("padding-top")),bottom:parseInt(c.getPropertyValue("padding-bottom")),right:parseInt(c.getPropertyValue("padding-right")),left:parseInt(c.getPropertyValue("padding-left"))},p=d.top+d.bottom,m=d.right+d.left,f=a-p,S=o-m-t;return{cols:Math.max(R2,Math.floor(S/e.css.cell.width)),rows:Math.max(M2,Math.floor(f/e.css.cell.height))}}};var p0=Object.defineProperty,N2=Object.getOwnPropertyDescriptor,B2=(e,t)=>{for(var n in t)p0(e,n,{get:t[n],enumerable:!0})},Ht=(e,t,n,a)=>{for(var o=a>1?void 0:a?N2(t,n):t,c=e.length-1,d;c>=0;c--)(d=e[c])&&(o=(a?d(t,n,o):d(o))||o);return a&&o&&p0(t,n,o),o},ye=(e,t)=>(n,a)=>t(n,a,e),Gy="Terminal input",Vf={get:()=>Gy,set:e=>Gy=e},Zy="Too much output to announce, navigate to rows manually to read",Xf={get:()=>Zy,set:e=>Zy=e};function L2(e){return e.replace(/\r?\n/g,"\r")}function O2(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function z2(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function j2(e,t,n,a){if(e.stopPropagation(),e.clipboardData){let o=e.clipboardData.getData("text/plain");m0(o,t,n,a)}}function m0(e,t,n,a){e=L2(e),e=O2(e,n.decPrivateModes.bracketedPasteMode&&a.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=""}function _0(e,t,n){let a=n.getBoundingClientRect(),o=e.clientX-a.left-10,c=e.clientY-a.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${o}px`,t.style.top=`${c}px`,t.style.zIndex="1000",t.focus()}function Qy(e,t,n,a,o){_0(e,t,n),o&&a.rightClickSelect(e),t.value=a.selectionText,t.select()}function tr(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Au(e,t=0,n=e.length){let a="";for(let o=t;o<n;++o){let c=e[o];c>65535?(c-=65536,a+=String.fromCharCode((c>>10)+55296)+String.fromCharCode(c%1024+56320)):a+=String.fromCharCode(c)}return a}var H2=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let a=0,o=0;if(this._interim){let c=e.charCodeAt(o++);56320<=c&&c<=57343?t[a++]=(this._interim-55296)*1024+c-56320+65536:(t[a++]=this._interim,t[a++]=c),this._interim=0}for(let c=o;c<n;++c){let d=e.charCodeAt(c);if(55296<=d&&d<=56319){if(++c>=n)return this._interim=d,a;let p=e.charCodeAt(c);56320<=p&&p<=57343?t[a++]=(d-55296)*1024+p-56320+65536:(t[a++]=d,t[a++]=p);continue}d!==65279&&(t[a++]=d)}return a}},U2=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let a=0,o,c,d,p,m=0,f=0;if(this.interim[0]){let b=!1,x=this.interim[0];x&=(x&224)===192?31:(x&240)===224?15:7;let C=0,k;for(;(k=this.interim[++C]&63)&&C<4;)x<<=6,x|=k;let B=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,R=B-C;for(;f<R;){if(f>=n)return 0;if(k=e[f++],(k&192)!==128){f--,b=!0;break}else this.interim[C++]=k,x<<=6,x|=k&63}b||(B===2?x<128?f--:t[a++]=x:B===3?x<2048||x>=55296&&x<=57343||x===65279||(t[a++]=x):x<65536||x>1114111||(t[a++]=x)),this.interim.fill(0)}let S=n-4,y=f;for(;y<n;){for(;y<S&&!((o=e[y])&128)&&!((c=e[y+1])&128)&&!((d=e[y+2])&128)&&!((p=e[y+3])&128);)t[a++]=o,t[a++]=c,t[a++]=d,t[a++]=p,y+=4;if(o=e[y++],o<128)t[a++]=o;else if((o&224)===192){if(y>=n)return this.interim[0]=o,a;if(c=e[y++],(c&192)!==128){y--;continue}if(m=(o&31)<<6|c&63,m<128){y--;continue}t[a++]=m}else if((o&240)===224){if(y>=n)return this.interim[0]=o,a;if(c=e[y++],(c&192)!==128){y--;continue}if(y>=n)return this.interim[0]=o,this.interim[1]=c,a;if(d=e[y++],(d&192)!==128){y--;continue}if(m=(o&15)<<12|(c&63)<<6|d&63,m<2048||m>=55296&&m<=57343||m===65279)continue;t[a++]=m}else if((o&248)===240){if(y>=n)return this.interim[0]=o,a;if(c=e[y++],(c&192)!==128){y--;continue}if(y>=n)return this.interim[0]=o,this.interim[1]=c,a;if(d=e[y++],(d&192)!==128){y--;continue}if(y>=n)return this.interim[0]=o,this.interim[1]=c,this.interim[2]=d,a;if(p=e[y++],(p&192)!==128){y--;continue}if(m=(o&7)<<18|(c&63)<<12|(d&63)<<6|p&63,m<65536||m>1114111)continue;t[a++]=m}}return a}},v0="",sr=" ",Co=class g0{constructor(){this.fg=0,this.bg=0,this.extended=new pu}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new g0;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},pu=class y0{constructor(t=0,n=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=n}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new y0(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},xs=class S0 extends Co{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new pu,this.combinedData=""}static fromCharData(t){let n=new S0;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?tr(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let n=!1;if(t[1].length>2)n=!0;else if(t[1].length===2){let a=t[1].charCodeAt(0);if(55296<=a&&a<=56319){let o=t[1].charCodeAt(1);56320<=o&&o<=57343?this.content=(a-55296)*1024+o-56320+65536|t[2]<<22:n=!0}else n=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;n&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Jy="di$target",Gf="di$dependencies",lf=new Map;function P2(e){return e[Gf]||[]}function pi(e){if(lf.has(e))return lf.get(e);let t=function(n,a,o){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");K2(t,n,o)};return t._id=e,lf.set(e,t),t}function K2(e,t,n){t[Jy]===t?t[Gf].push({id:e,index:n}):(t[Gf]=[{id:e,index:n}],t[Jy]=t)}var Oi=pi("BufferService"),b0=pi("CoreMouseService"),Pr=pi("CoreService"),I2=pi("CharsetService"),gm=pi("InstantiationService"),w0=pi("LogService"),zi=pi("OptionsService"),C0=pi("OscLinkService"),F2=pi("UnicodeService"),xo=pi("DecorationService"),Zf=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let a=[],o=this._optionsService.rawOptions.linkHandler,c=new xs,d=n.getTrimmedLength(),p=-1,m=-1,f=!1;for(let S=0;S<d;S++)if(!(m===-1&&!n.hasContent(S))){if(n.loadCell(S,c),c.hasExtendedAttrs()&&c.extended.urlId)if(m===-1){m=S,p=c.extended.urlId;continue}else f=c.extended.urlId!==p;else m!==-1&&(f=!0);if(f||m!==-1&&S===d-1){let y=this._oscLinkService.getLinkData(p)?.uri;if(y){let b={start:{x:m+1,y:e},end:{x:S+(!f&&S===d-1?1:0),y:e}},x=!1;if(!o?.allowNonHttpProtocols)try{let C=new URL(y);["http:","https:"].includes(C.protocol)||(x=!0)}catch{x=!0}x||a.push({text:y,range:b,activate:(C,k)=>o?o.activate(C,k,b):q2(C,k),hover:(C,k)=>o?.hover?.(C,k,b),leave:(C,k)=>o?.leave?.(C,k,b)})}f=!1,c.hasExtendedAttrs()&&c.extended.urlId?(m=S,p=c.extended.urlId):(m=-1,p=-1)}}t(a)}};Zf=Ht([ye(0,Oi),ye(1,zi),ye(2,C0)],Zf);function q2(e,t){if(confirm(`Do you want to navigate to ${t}?
14
+ `)))){b(j.key,{busy:!0,status:"deleting…",error:void 0}),f(null);try{const H=await e.uninstallAgent(j.id);a(L=>L.filter(X=>X.key!==j.key)),c(L=>{const X={...L};return delete X[j.key],X}),sf(j.key),t?.(j.id),f(H.message)}catch(H){b(j.key,{busy:!1,status:void 0,error:H instanceof Error?H.message:"delete failed"})}}}async function ce(){p(!0),f(null);const j=n.filter(G=>G.id!==null),$=n.find(G=>G.id===null),H=await Promise.all(j.map(G=>F(G,{skipManual:!0}))),L=H.filter(G=>G==="failed").length;let X=H.filter(G=>G==="manual").length;if(L>0){p(!1);return}if($){const G=await F($,{skipManual:!0});if(G==="manual"&&(X+=1),G==="updated"){p(!1);return}}X>0&&f("Some servers need manual update. Copy and run the command shown on each marked server."),p(!1)}function q(j){return j?j.error?j.error:j.status?j.status:j.manualUpdate?"manual update required":j.version?`v${j.version.version}`:"…":"…"}function I(j){return j.error?j.error:typeof j.updateAvailable=="boolean"?j.updateAvailable?`latest v${j.latestVersion??"available"}`:"up to date":"unknown"}function ie(j){const $=j?.version;return $?`npm package v${$.runningVersion}`:""}async function de(j,$){try{await m2($),b(j,{copiedCommand:!0}),window.setTimeout(()=>b(j,{copiedCommand:!1}),1800)}catch(H){b(j,{error:H instanceof Error?H.message:"copy failed"})}}return _.jsxs("section",{className:"security-section",children:[_.jsx("h3",{children:"Servers"}),_.jsxs("div",{className:"update-actions",children:[_.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{R()},disabled:d,children:"Check for updates"}),_.jsx("button",{type:"button",onClick:()=>{ce()},disabled:d,children:"Update all"})]}),m?_.jsx("p",{className:"settings-status",children:m}):null,S?_.jsxs("div",{className:"server-reload-required",role:"status",children:[_.jsx("span",{children:"Main server update is ready."}),_.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:"Reload page"})]}):null,_.jsx("ul",{className:"security-list",children:n.map(j=>{const $=o[j.key],H=ie($),L=$?.manualUpdate??null,X=$?.version!==void 0&&$?.updateAvailable!==!1&&!L&&!$?.busy&&!d,G=j.id!==null&&!$?.busy&&!d;return _.jsxs("li",{children:[_.jsxs("div",{className:"server-row-main",children:[_.jsxs("div",{children:[_.jsx("span",{className:"security-item-label",children:j.name}),_.jsxs("span",{className:"security-item-meta",children:[H?`${H} — `:"",q($)]})]}),L?_.jsxs("div",{className:"server-manual-update",children:[_.jsx("span",{children:L.message}),_.jsxs("div",{className:"server-manual-command",children:[_.jsx("code",{children:L.command}),_.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{de(j.key,L.command)},children:$?.copiedCommand?"Copied":"Copy"})]})]}):null]}),_.jsxs("div",{className:"server-row-actions",children:[_.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{F(j)},disabled:!X,children:$?.busy?"…":"Update"}),j.id!==null?_.jsx("button",{type:"button",className:"server-delete-button",onClick:()=>{J(j)},disabled:!G,children:"Delete"}):null]})]},j.key)})})]})}async function m2(e){if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(e);return}const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{if(!document.execCommand("copy"))throw new Error("copy failed")}finally{t.remove()}}const Uc=[{id:"terminal",label:"Terminal"},{id:"shortcuts",label:"Shortcuts"},{id:"notifications",label:"Notifications"},{id:"security",label:"Security"},{id:"servers",label:"Servers"}];function _2({onClose:e,api:t,updateAvailable:n=!1,onNotificationAssetsChanged:a,onAgentRemoved:o}){const c=g.useMemo(()=>t??Eu(),[t]),[d,p]=g.useState(()=>Pf()),[m,f]=g.useState(()=>Kf()),[S,y]=g.useState(()=>Ff()),[b,x]=g.useState(()=>lr()),[C,k]=g.useState(()=>jr()),[B,R]=g.useState(null),[re,F]=g.useState(null),[J,ce]=g.useState("terminal"),[q,I]=g.useState(()=>Vb()),[ie,de]=g.useState(()=>zr()),[j,$]=g.useState(()=>nm()),[H,L]=g.useState([]),[X,G]=g.useState([]),[M,V]=g.useState([]),[Q,ve]=g.useState(5*1024*1024),[Se,E]=g.useState(!1),[W,ee]=g.useState(null),he=g.useRef(null),ge=g.useRef(null),me=g.useRef({terminal:null,shortcuts:null,notifications:null,security:null,servers:null}),Ce=g.useMemo(()=>new Set(X),[X]),ze=!v2(X,M);g.useEffect(()=>e0(()=>p(Pf())),[]),g.useEffect(()=>t0(()=>f(Kf())),[]),g.useEffect(()=>i0(()=>y(Ff())),[]),g.useEffect(()=>u0(()=>x(lr())),[]),g.useEffect(()=>s0(()=>k(jr())),[]),g.useEffect(()=>Xb(()=>de(zr())),[]),g.useEffect(()=>{if(!B)return;const te=ro.find(He=>He.id===B);if(!te)return;const je=He=>{if(He.preventDefault(),He.stopPropagation(),He.key==="Escape"){R(null),F(null);return}const _i=qE(He,te);if(!_i){F(te.indexed?"Press a shortcut ending in a number from 1 to 9.":"Press a complete shortcut.");return}k(KE(B,_i)),R(null),F(null)};return window.addEventListener("keydown",je,!0),()=>window.removeEventListener("keydown",je,!0)},[B]),g.useEffect(()=>{let te=!1;return c.listNotificationAssets().then(je=>{te||Ee(je)}).catch(je=>{te||ee(Pc(je))}),()=>{te=!0}},[c]);function Ne(te){p(Hc(Number(te)))}function Re(te){de(qy(Number(te)))}function Pe(te){ce(te),me.current[te]?.scrollIntoView?.({block:"start",behavior:"smooth"})}function Ye(){const te=ge.current;if(!te)return;if(te.scrollTop+te.clientHeight>=te.scrollHeight-2){ce(Uc[Uc.length-1].id);return}const je=te.getBoundingClientRect();let He="terminal",_i=0;for(const Vi of Uc){const ai=me.current[Vi.id];if(!ai)continue;const kt=ai.getBoundingClientRect(),ji=Math.max(kt.top,je.top),Ti=Math.min(kt.bottom,je.bottom),Nt=Math.max(0,Ti-ji);Nt>_i&&(He=Vi.id,_i=Nt)}ce(He)}function Be(te){k(IE(te)),R(null),F(null)}function ae(){k(FE()),R(null),F(null)}function Ee(te){const je=te.assets.filter(He=>He.enabled).map(He=>He.id);L(te.assets),G(je),V(je),ve(te.maxFileBytes),ee(null)}async function xe(){if(q){Fy(!1),I(!1);return}let te=j;te==="default"&&(te=await OE(),$(te)),te==="granted"&&(Fy(!0),I(!0))}async function Ke(te){const je=te?.[0];if(je){if(je.size>Q){ee(`File must be ${nf(Q)} or smaller.`),gt();return}if(je.type!=="video/mp4"&&je.type!=="video/webm"){ee("Upload an MP4 or WebM video."),gt();return}E(!0),ee(null);try{await c.uploadNotificationAsset(je),Ee(await c.listNotificationAssets()),a?.()}catch(He){ee(Pc(He))}finally{E(!1),gt()}}}async function Xe(te){E(!0),ee(null);try{await c.deleteNotificationAsset(te),Ee(await c.listNotificationAssets()),a?.()}catch(je){ee(Pc(je))}finally{E(!1)}}function gt(){he.current&&(he.current.value="")}function yt(te,je){const He=new Set(X);if(je?He.add(te):He.delete(te),He.size===0){ee("Keep at least one toast video selected.");return}ee(null),G(Array.from(He))}async function mi(){if(X.length===0){ee("Keep at least one toast video selected.");return}E(!0),ee(null);try{const te=await c.updateNotificationAssetSelection({enabledAssetIds:X});Ee(te),a?.()}catch(te){ee(Pc(te))}finally{E(!1)}}return _.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-label":"Settings",onClick:e,children:_.jsxs("div",{className:"security-panel settings-panel",onClick:te=>te.stopPropagation(),children:[_.jsxs("header",{className:"security-panel-header",children:[_.jsx("h2",{children:"Settings"}),_.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:e,children:"×"})]}),_.jsxs("div",{className:"settings-layout",children:[_.jsx("nav",{className:"settings-nav","aria-label":"Settings categories",children:Uc.map(te=>_.jsxs("button",{type:"button","data-active":J===te.id?"true":"false","aria-current":J===te.id?"true":void 0,onClick:()=>Pe(te.id),children:[te.label,te.id==="servers"&&n?_.jsx("span",{className:"update-pulse-dot settings-update-dot","aria-hidden":"true"}):null]},te.id))}),_.jsxs("div",{ref:ge,className:"settings-content",onScroll:Ye,children:[_.jsxs("section",{id:"settings-terminal",ref:te=>{me.current.terminal=te},className:"security-section settings-section",children:[_.jsx("h3",{children:"Terminal"}),_.jsxs("label",{className:"settings-control",children:[_.jsx("span",{children:"Font size"}),_.jsxs("span",{className:"settings-control-value",children:[d,"px"]}),_.jsx("input",{type:"range",min:jf,max:Hf,step:1,value:d,"aria-label":"Terminal font size",onChange:te=>Ne(te.currentTarget.value)})]}),_.jsxs("div",{className:"settings-stepper-row",children:[_.jsx("button",{type:"button",className:"secondary-button settings-stepper-button",onClick:()=>p(Hc(d-1)),children:"-"}),_.jsx("input",{type:"number",min:jf,max:Hf,step:1,value:d,"aria-label":"Terminal font size value",onChange:te=>Ne(te.currentTarget.value)}),_.jsx("button",{type:"button",className:"secondary-button settings-stepper-button",onClick:()=>p(Hc(d+1)),children:"+"}),_.jsx("button",{type:"button",className:"secondary-button settings-reset-button",onClick:()=>p(Hc(Lr)),children:"Reset"})]}),_.jsxs("label",{className:"settings-control",children:[_.jsx("span",{children:"Font family"}),_.jsx("select",{value:m,"aria-label":"Terminal font family",onChange:te=>f(HE(te.currentTarget.value)),children:hu.map(te=>_.jsx("option",{value:te.id,children:te.label},te.id))})]}),_.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[_.jsx("input",{type:"checkbox",checked:S,onChange:te=>y(UE(te.currentTarget.checked))}),"Show scroll progress"]}),_.jsxs("label",{className:"settings-control",children:[_.jsx("span",{children:"Accent theme"}),_.jsx("select",{value:b,"aria-label":"Theme accent",onChange:te=>x(JE(te.currentTarget.value)),children:ao.map(te=>_.jsx("option",{value:te.id,children:te.label},te.id))})]}),_.jsx("div",{className:"settings-theme-swatches","aria-hidden":"true",children:ao.map(te=>_.jsx("span",{className:"settings-theme-swatch","data-active":b===te.id?"true":"false",style:{"--settings-theme-accent":te.accent}},te.id))})]}),_.jsxs("section",{id:"settings-shortcuts",ref:te=>{me.current.shortcuts=te},className:"security-section settings-section",children:[_.jsxs("div",{className:"settings-section-heading",children:[_.jsx("h3",{children:"Shortcuts"}),_.jsx("button",{type:"button",className:"secondary-button settings-reset-button",onClick:ae,children:"Reset all"})]}),_.jsx("p",{className:"muted",children:"Defaults avoid Chrome's browser-tab shortcuts. Click a shortcut, then press the new key combo."}),re?_.jsx("p",{className:"settings-error",children:re}):null,_.jsx("ul",{className:"settings-shortcut-list","aria-label":"Workspace shortcuts",children:ro.map(te=>{const je=B===te.id;return _.jsxs("li",{children:[_.jsxs("div",{children:[_.jsx("span",{className:"settings-shortcut-label",children:te.label}),_.jsx("span",{className:"settings-shortcut-group",children:te.group})]}),_.jsxs("div",{className:"settings-shortcut-actions",children:[_.jsx("button",{type:"button",className:"settings-shortcut-recorder","data-recording":je?"true":"false",onClick:()=>{R(te.id),F(null)},children:je?"Press keys…":r0(C[te.id])}),_.jsx("button",{type:"button",className:"secondary-button settings-shortcut-reset",onClick:()=>Be(te.id),children:"Reset"})]})]},te.id)})})]}),_.jsxs("section",{id:"settings-notifications",ref:te=>{me.current.notifications=te},className:"security-section settings-section",children:[_.jsx("h3",{children:"Notifications"}),Mu()?_.jsxs(_.Fragment,{children:[_.jsxs("label",{className:"auth-checkbox",children:[_.jsx("input",{type:"checkbox",checked:q&&j==="granted",onChange:()=>{xe()},disabled:j==="denied"}),"System notification when page is hidden"]}),j==="denied"?_.jsx("p",{className:"muted",children:"Notification permission is blocked for this site. Re-enable it in the browser's site settings, then come back here to turn the toggle on."}):_.jsx("p",{className:"muted",children:"Uses browser notifications only when this page isn't visible. Animated toast is controlled separately below."})]}):_.jsx("p",{className:"muted",children:"This browser doesn't expose the Notification API; animated toast and in-app badges can still work."}),_.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[_.jsx("input",{type:"checkbox",checked:ie.enabled,onChange:te=>de(ME(te.currentTarget.checked))}),"Show animated completion toast"]}),_.jsxs("label",{className:"settings-control",children:[_.jsx("span",{children:"Toast duration"}),_.jsx("span",{className:"settings-control-value",children:ie.persistUntilDismissed?"Until closed":`${ie.durationSeconds}s`}),_.jsx("input",{type:"range",min:Bf,max:Lf,step:.5,value:ie.durationSeconds,disabled:!ie.enabled||ie.persistUntilDismissed,"aria-label":"Completion toast duration",onChange:te=>Re(te.currentTarget.value)})]}),_.jsxs("div",{className:"settings-stepper-row settings-duration-row",children:[_.jsx("input",{type:"number",min:Bf,max:Lf,step:.5,value:ie.durationSeconds,disabled:!ie.enabled||ie.persistUntilDismissed,"aria-label":"Completion toast duration value",onChange:te=>Re(te.currentTarget.value)}),_.jsx("button",{type:"button",className:"secondary-button settings-reset-button",disabled:!ie.enabled||ie.persistUntilDismissed,onClick:()=>de(qy(Jl)),children:"Reset"})]}),_.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[_.jsx("input",{type:"checkbox",checked:ie.persistUntilDismissed,disabled:!ie.enabled,onChange:te=>de(AE(te.currentTarget.checked))}),"Keep toast until dismissed"]}),_.jsxs("div",{className:"settings-assets-header",children:[_.jsx("span",{children:"Toast videos"}),_.jsxs("span",{children:[nf(Q)," max"]})]}),_.jsx("input",{ref:he,type:"file",accept:"video/mp4,video/webm",className:"settings-asset-input","aria-label":"Upload toast video",onChange:te=>{Ke(te.currentTarget.files)}}),_.jsx("button",{type:"button",className:"secondary-button settings-upload-button",disabled:Se,onClick:()=>he.current?.click(),children:"Upload video"}),W?_.jsx("p",{className:"settings-error",children:W}):null,H.length>0?_.jsx("ul",{className:"settings-asset-list","aria-label":"Toast videos",children:H.map(te=>_.jsxs("li",{"data-enabled":Ce.has(te.id)?"true":"false",children:[_.jsxs("label",{className:"settings-asset-choice",children:[_.jsx("input",{type:"checkbox",checked:Ce.has(te.id),disabled:Se,"aria-label":`Use ${te.filename}`,onChange:je=>yt(te.id,je.currentTarget.checked)}),_.jsx("video",{src:te.url,muted:!0,autoPlay:!0,loop:!0,playsInline:!0,"aria-hidden":"true"}),_.jsxs("span",{className:"settings-asset-copy",children:[_.jsx("span",{children:te.filename}),_.jsx("small",{children:te.source==="built-in"?"Built-in":nf(te.size)})]})]}),te.source==="uploaded"?_.jsx("button",{type:"button",className:"secondary-button settings-asset-delete",disabled:Se,"aria-label":`Delete ${te.filename}`,onClick:()=>{Xe(te.id)},children:"x"}):null]},te.id))}):_.jsx("p",{className:"muted",children:"Built-in videos will be used."}),_.jsx("button",{type:"button",className:"secondary-button settings-save-assets-button",disabled:Se||H.length===0||!ze,onClick:()=>{mi()},children:"Save selected videos"})]}),_.jsx("div",{id:"settings-security",ref:te=>{me.current.security=te},className:"settings-section-group",children:_.jsx(RE,{api:c})}),_.jsx("div",{id:"settings-servers",ref:te=>{me.current.servers=te},className:"settings-section-group",children:_.jsx(p2,{api:c,...o?{onAgentRemoved:o}:{}})})]})]})]})})}function nf(e){return e>=1024*1024?`${Math.round(e/1024/1024*10)/10} MB`:e>=1024?`${Math.round(e/1024*10)/10} KB`:`${e} B`}function Pc(e){return e instanceof Error?e.message:"Request failed."}function v2(e,t){if(e.length!==t.length)return!1;const n=new Set(t);return e.every(a=>n.has(a))}class Dr extends Error{constructor(t,n){super(n),this.status=t,this.name="UploadClientError"}status}function g2(e){const t=e.createXhr?.()??new XMLHttpRequest,n=new FormData,a=e.files.map((o,c)=>({fieldName:`file${c}`,relativePath:o.relativePath,size:o.file.size}));n.append("manifest",JSON.stringify({terminalId:e.terminalId,entries:a}));for(const[o,c]of e.files.entries())n.append(`file${o}`,c.file);return new Promise((o,c)=>{let d=!1;const p=()=>{e.signal?.removeEventListener("abort",S)},m=y=>{d||(d=!0,p(),o(y))},f=y=>{d||(d=!0,p(),c(y))},S=()=>{t.abort(),f(new Dr(0,"Upload aborted."))};if(e.signal?.aborted){f(new Dr(0,"Upload aborted."));return}e.signal?.addEventListener("abort",S,{once:!0}),t.open("POST","/api/uploads"),t.withCredentials=!0,t.upload.onprogress=y=>{if(e.onProgress){if(y.lengthComputable&&y.total>0){e.onProgress({loaded:y.loaded,total:y.total,percent:Math.round(y.loaded/y.total*100)});return}e.onProgress({loaded:y.loaded,total:null,percent:null})}},t.onload=()=>{if(t.status>=200&&t.status<300){try{m(JSON.parse(t.responseText))}catch{f(new Dr(t.status,"Invalid upload response."))}return}f(new Dr(t.status,y2(t.responseText,t.statusText||`HTTP ${t.status}`)))},t.onerror=()=>f(new Dr(0,"Upload failed.")),t.onabort=()=>f(new Dr(0,"Upload aborted.")),t.ontimeout=()=>f(new Dr(0,"Upload timed out.")),t.send(n)})}function y2(e,t){try{const n=JSON.parse(e),a=typeof n.error=="string"?n.error:n.message;if(typeof a=="string"&&a.trim())return a}catch{}return t}const S2="modulepreload",b2=function(e){return"/"+e},$y={},f0=function(t,n,a){let o=Promise.resolve();if(n&&n.length>0){let m=function(f){return Promise.all(f.map(S=>Promise.resolve(S).then(y=>({status:"fulfilled",value:y}),y=>({status:"rejected",reason:y}))))};document.getElementsByTagName("link");const d=document.querySelector("meta[property=csp-nonce]"),p=d?.nonce||d?.getAttribute("nonce");o=m(n.map(f=>{if(f=b2(f),f in $y)return;$y[f]=!0;const S=f.endsWith(".css"),y=S?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${y}`))return;const b=document.createElement("link");if(b.rel=S?"stylesheet":S2,S||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),S)return new Promise((x,C)=>{b.addEventListener("load",x),b.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${f}`)))})}))}function c(d){const p=new Event("vite:preloadError",{cancelable:!0});if(p.payload=d,window.dispatchEvent(p),!p.defaultPrevented)throw d}return o.then(d=>{for(const p of d||[])p.status==="rejected"&&c(p.reason);return t().catch(c)})},w2=g.lazy(()=>f0(()=>import("./MarkdownPreview-DkMcZHuI.js"),[]));function C2({api:e,activeTerminalId:t,activeTerminalCwd:n,onOpenFile:a}){const[o,c]=g.useState(null),[d,p]=g.useState(""),[m,f]=g.useState({}),[S,y]=g.useState(()=>new Set),[b,x]=g.useState(null),[C,k]=g.useState({type:"empty"}),[B,R]=g.useState("idle"),[re,F]=g.useState(null),J=g.useRef(null),ce=g.useRef(null),q=g.useRef(!1),I=g.useRef(0),ie=g.useRef(null);ie.current===null&&t&&(ie.current=t);const de=ie.current,j=t?af(t,n):null,$=o?[o.rootPath,d].filter(Boolean).join("/"):"",H=b?.path??null;g.useEffect(()=>(q.current=!0,()=>{q.current=!1,I.current+=1,ze()}),[]),g.useEffect(()=>{ie.current=t,ce.current=null;const ae=t?af(t,n):null;L(t,ae)},[e]),g.useEffect(()=>{if(!de||t!==de)return;const ae=af(de,n);ae!==ce.current&&L(de,ae)},[de,t,n]);async function L(ae,Ee=j){const xe=Ne();if(ce.current=Ee,ze(),c(null),p(""),f({}),y(new Set),x(null),k({type:"empty"}),F(null),!ae){R("idle");return}R("loading");try{const Ke=await e.createFileRoot({terminalId:ae});if(!Re(xe))return;c({rootToken:Ke.rootToken,rootPath:Ke.rootPath});const Xe=await e.listFiles({rootToken:Ke.rootToken,path:""});if(!Re(xe))return;M(Xe),R("idle")}catch(Ke){if(await Pe(Ke,xe))return;Re(xe)&&(F(Xn(Ke)),R("idle"))}}async function X(ae=d,Ee=o){if(!Ee)return;const xe=Ne();R("loading"),F(null);try{const Ke=await e.listFiles({rootToken:Ee.rootToken,path:ae});if(!Re(xe))return;M(Ke),R("idle")}catch(Ke){if(await Pe(Ke,xe))return;Re(xe)&&(F(Xn(Ke)),R("idle"))}}async function G(){ie.current=t,await L(t,j)}function M(ae){f(Ee=>({...Ee,[ae.path]:E2(ae.entries)}))}async function V(ae){if(!(!rf(ae)||!o)){if(x(ae),F(null),ae.kind==="directory"){p(ae.path),Ce(),await ve(ae);return}if(p(Rr(ae.path)),ae.editable){await E(ae);return}ae.previewKind!=="none"&&await ee(ae,ae.previewKind)}}async function Q(ae){if(!(!rf(ae)||!o)){if(x(ae),F(null),ae.kind==="directory"){p(ae.path),Ce(),await ve(ae);return}if(p(Rr(ae.path)),ae.editable){await W(ae);return}ae.previewKind!=="none"&&await ee(ae,ae.previewKind)}}async function ve(ae){if(S.has(ae.path)){y(Ee=>{const xe=new Set(Ee);return xe.delete(ae.path),xe});return}y(Ee=>new Set(Ee).add(ae.path)),await X(ae.path)}function Se(ae,Ee){ae.key==="Enter"&&(ae.preventDefault(),Q(Ee))}async function E(ae){if(!o)return;const Ee=Ne();R("loading"),ze();try{const xe=await e.readFile({rootToken:o.rootToken,path:ae.path});if(!Re(Ee))return;k({type:"text-preview",file:ae,read:xe}),R("idle")}catch(xe){if(await Pe(xe,Ee))return;Re(Ee)&&(F(Xn(xe)),R("idle"))}}async function W(ae){if(!o)return;const Ee=Ne();R("loading");try{await a({rootToken:o.rootToken,path:ae.path}),Re(Ee)&&R("idle")}catch(xe){if(await Pe(xe,Ee))return;Re(Ee)&&(F(Xn(xe)),R("idle"))}}async function ee(ae,Ee){if(!o)return;const xe=Ne();R("loading"),ze();try{const Ke=await e.previewFile({rootToken:o.rootToken,path:ae.path});if(!Re(xe))return;const Xe=URL.createObjectURL(Ke);if(!Re(xe)){URL.revokeObjectURL(Xe);return}J.current=Xe,k({type:"preview",file:ae,previewKind:Ee,url:Xe}),R("idle")}catch(Ke){if(await Pe(Ke,xe))return;Re(xe)&&(F(Xn(Ke)),R("idle"))}}async function he(ae){if(!o)return;const Ee=ae==="file"?"New file":"New folder",xe=window.prompt(Ee,""),Ke=b?b.kind==="directory"?b.path:Rr(b.path):d,Xe=Vy(xe,Ke);if(Xe){F(null);try{const gt=await e.createFileEntry({rootToken:o.rootToken,path:Xe,kind:ae});x(gt.entry),await X(Ke)}catch(gt){if(await Pe(gt))return;F(Xn(gt))}}}async function ge(){if(!o||!b)return;const ae=window.prompt("Move selected entry",b.path),Ee=Vy(ae,"");if(!Ee||Ee===b.path)return;const xe=Rr(b.path),Ke=Rr(Ee);F(null);try{const Xe=await e.moveFileEntry({rootToken:o.rootToken,sourcePath:b.path,destinationPath:Ee});x(Xe.entry),p(Xe.entry.kind==="directory"?Xe.entry.path:Rr(Xe.entry.path)),Ce(),await X(xe),Ke!==xe&&await X(Ke)}catch(Xe){if(await Pe(Xe))return;F(Xn(Xe))}}async function me(){if(!o||!b)return;const ae=b.path,Ee=Rr(ae);F(null);try{const xe=await e.previewDeleteFileEntry({rootToken:o.rootToken,path:b.path}),Ke=xe.descendantCount>0?` and ${xe.descendantCount} nested item${xe.descendantCount===1?"":"s"}`:"";if(!window.confirm(`Delete ${xe.path}${Ke}?`))return;await e.deleteFileEntry({rootToken:o.rootToken,path:b.path,previewToken:xe.previewToken}),x(null),p(Ee),y(Xe=>{const gt=new Set(Xe);for(const yt of Xe)(yt===ae||yt.startsWith(`${ae}/`))&&gt.delete(yt);return gt}),Ce(),await X(Ee)}catch(xe){if(await Pe(xe))return;F(Xn(xe))}}function Ce(){I.current+=1,ze(),k({type:"empty"})}function ze(){J.current&&(URL.revokeObjectURL(J.current),J.current=null)}function Ne(){return I.current+=1,I.current}function Re(ae){return q.current&&ae===I.current}async function Pe(ae,Ee){return T2(ae)?(Ee!==void 0&&!Re(Ee)||await L(t,j),!0):!1}function Ye(ae,Ee){const xe=rf(ae),Ke=ae.kind==="directory"&&S.has(ae.path),Xe=m[ae.path]??[],gt={"--file-tree-depth":Ee};return _.jsxs(xi.Fragment,{children:[_.jsxs("button",{type:"button",className:"file-entry-button","data-kind":ae.kind,"data-expanded":Ke,"data-active":H===ae.path,disabled:!xe,style:gt,"aria-expanded":ae.kind==="directory"?Ke:void 0,"aria-label":`${ae.kind==="directory"?"Open folder":"Open file"} ${ae.name}`,title:ae.kind==="directory"?"Expand or collapse folder":"Click to preview. Double-click or press Enter to open.",onClick:()=>{V(ae)},onDoubleClick:()=>{Q(ae)},onKeyDown:yt=>Se(yt,ae),children:[_.jsx("span",{className:"file-entry-disclosure","aria-hidden":"true",children:ae.kind==="directory"?Ke?"▾":"▸":""}),_.jsx("span",{className:"file-entry-name",children:ae.name}),_.jsx("small",{children:x2(ae)})]}),Ke?_.jsx("div",{className:"file-tree-children",role:"group",children:Xe.map(yt=>Ye(yt,Ee+1))}):null]},ae.path)}const Be=m[""]??[];return _.jsxs("section",{className:"file-explorer","aria-label":"Files","aria-busy":B==="loading",children:[_.jsxs("header",{className:"file-explorer-header",children:[_.jsx("div",{className:"file-explorer-path",title:$,children:$||"No active pane"}),_.jsxs("div",{className:"file-explorer-toolbar","aria-label":"File actions",children:[_.jsx("button",{type:"button","aria-label":"Refresh files",title:"Refresh",disabled:!t,onClick:()=>{G()},children:"↻"}),_.jsx("button",{type:"button","aria-label":"New file",title:"New file",disabled:!o,onClick:()=>{he("file")},children:"+"}),_.jsx("button",{type:"button","aria-label":"New folder",title:"New folder",disabled:!o,onClick:()=>{he("directory")},children:"▣"})]})]}),re?_.jsx("div",{className:"file-explorer-alert",role:"alert",children:re}):null,_.jsxs("div",{className:"file-explorer-layout",children:[_.jsx("div",{className:"file-tree","aria-label":$?`Files in ${$}`:"Files",children:Be.map(ae=>Ye(ae,0))}),_.jsxs("section",{className:"file-detail","aria-label":"File detail",children:[_.jsxs("div",{className:"file-detail-header",children:[_.jsx("strong",{children:b?.name??"detail"}),_.jsxs("div",{className:"file-detail-actions",children:[_.jsx("button",{type:"button","aria-label":"Move selected entry",disabled:!b,onClick:()=>{ge()},children:"Move"}),_.jsx("button",{type:"button","aria-label":"Delete selected entry",disabled:!b,onClick:()=>{me()},children:"Delete"})]})]}),B==="loading"?_.jsx("div",{className:"file-detail-empty",children:"loading"}):null,C.type==="empty"&&B!=="loading"?_.jsx("div",{className:"file-detail-empty",children:"No file selected"}):null,C.type==="preview"?_.jsxs("div",{className:"file-preview-frame",children:[C.previewKind==="image"?_.jsx("img",{src:C.url,alt:C.file.name}):null,C.previewKind==="pdf"?_.jsx("iframe",{src:C.url,title:C.file.name}):null]}):null,C.type==="text-preview"&&C.read.language==="markdown"?_.jsx("div",{className:"file-markdown-preview","aria-label":`Preview for ${C.file.name}`,children:_.jsx(g.Suspense,{fallback:_.jsx("div",{className:"file-markdown-preview-loading",children:"loading preview"}),children:_.jsx(w2,{content:C.read.content})})}):null,C.type==="text-preview"&&C.read.language==="text"?_.jsx("pre",{className:"file-text-preview","aria-label":`Preview for ${C.file.name}`,children:C.read.content}):null]})]})]})}function rf(e){return e.kind==="directory"||e.editable||e.previewKind!=="none"}function x2(e){return e.kind==="directory"?"dir":e.editable?"edit":e.previewKind!=="none"?e.previewKind:"unsupported"}function af(e,t){return`${e}\0${t??""}`}function E2(e){return[...e].sort((t,n)=>t.kind==="directory"&&n.kind!=="directory"?-1:t.kind!=="directory"&&n.kind==="directory"?1:t.name.localeCompare(n.name))}function Rr(e){const t=e.split("/").filter(Boolean);return t.pop(),t.join("/")}function Vy(e,t){if(e===null)return null;const n=e.trim().replace(/^\/+/,"").replace(/\/{2,}/g,"/").replace(/\/$/,"");return n?!t||n.includes("/")?n:`${t}/${n}`:null}function Xn(e){return e instanceof Error?e.message:"Request failed"}function T2(e){return e instanceof yn&&e.status===409&&e.message==="terminal_cwd_changed"}const k2=g.lazy(()=>f0(()=>import("./MarkdownPreview-DkMcZHuI.js"),[]));function Xy({api:e,editor:t,canClose:n,onClose:a}){const[o,c]=g.useState(t.read),[d,p]=g.useState(t.read.content),[m,f]=g.useState("idle"),[S,y]=g.useState(null),[b,x]=g.useState(!1),[C,k]=g.useState("edit"),B=g.useRef(t),R=g.useRef(t.read),re=g.useRef(t.read.content),F=g.useRef(!1),J=g.useRef(!1),ce=g.useRef(0),q=d!==o.content&&m!=="saving"&&!b;g.useEffect(()=>(J.current=!0,()=>{J.current=!1,ce.current+=1}),[]),g.useEffect(()=>{ce.current+=1,F.current=!1,B.current=t,R.current=t.read,re.current=t.read.content,c(t.read),p(t.read.content),f("idle"),y(null),x(!1),k("edit")},[t.id,t.read]),g.useEffect(()=>{B.current=t},[t]),g.useEffect(()=>{R.current=o},[o]),g.useEffect(()=>{re.current=d},[d]),g.useEffect(()=>{if(d===o.content||b)return;const $=window.setInterval(()=>{!F.current&&re.current!==R.current.content&&I()},1e3);return()=>window.clearInterval($)},[d===o.content,b,t.id]);async function I(){if(F.current)return;const $=re.current,H=R.current;if($===H.content)return;const L=B.current,X=ce.current;F.current=!0,f("saving"),y(null),x(!1);try{const G=await e.writeFile({rootToken:L.rootToken,path:L.path,content:$,expectedVersion:H.version});if(!J.current||X!==ce.current)return;const M={...H,content:$,version:G.version};R.current=M,c(M),f(re.current===$?"saved":"idle")}catch(G){if(!J.current||X!==ce.current)return;if(G instanceof yn&&G.status===409){x(!0),f("idle");return}y(D2(G)),f("idle")}finally{X===ce.current&&(F.current=!1)}}const ie=m==="saving"?"saving":m==="saved"?"saved":o.language,de=o.language==="markdown",j=de&&C==="preview";return _.jsxs("section",{className:"editor-pane","aria-label":`Editor pane ${t.title}`,children:[_.jsxs("header",{className:"editor-pane-header",children:[_.jsx("span",{className:"terminal-pane-dot","aria-hidden":"true"}),_.jsx("strong",{children:t.title}),_.jsx("span",{className:"terminal-pane-spacer"}),_.jsx("span",{className:"terminal-pane-state",children:ie}),_.jsx("button",{type:"button","aria-label":`Save ${t.title}`,disabled:!q,onClick:()=>{I()},children:"Save"}),de?_.jsx("button",{type:"button","aria-label":`${j?"Edit":"Preview"} ${t.title}`,onClick:()=>k($=>$==="preview"?"edit":"preview"),children:j?"Edit":"Preview"}):null,n?_.jsx("button",{type:"button",className:"terminal-pane-close","aria-label":`Close editor ${t.title}`,onClick:a,children:"x"}):null]}),S?_.jsx("div",{className:"editor-pane-alert",role:"alert",children:S}):null,b?_.jsx("div",{className:"editor-pane-alert",role:"alert",children:"File changed on disk."}):null,j?_.jsx("div",{className:"editor-markdown-preview","aria-label":`Markdown preview for ${t.title}`,children:_.jsx(g.Suspense,{fallback:_.jsx("div",{className:"editor-markdown-preview-loading",children:"loading preview"}),children:_.jsx(k2,{content:d})})}):_.jsx("textarea",{className:"editor-pane-textarea","aria-label":`Editor for ${t.title}`,spellCheck:!1,value:d,onChange:$=>{const H=$.target.value;re.current=H,p(H),f("idle"),y(null),x(!1)}})]})}function D2(e){return e instanceof Error?e.message:"Request failed"}var R2=2,M2=1,A2=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._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(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),a=parseInt(n.getPropertyValue("height")),o=Math.max(0,parseInt(n.getPropertyValue("width"))),c=window.getComputedStyle(this._terminal.element),d={top:parseInt(c.getPropertyValue("padding-top")),bottom:parseInt(c.getPropertyValue("padding-bottom")),right:parseInt(c.getPropertyValue("padding-right")),left:parseInt(c.getPropertyValue("padding-left"))},p=d.top+d.bottom,m=d.right+d.left,f=a-p,S=o-m-t;return{cols:Math.max(R2,Math.floor(S/e.css.cell.width)),rows:Math.max(M2,Math.floor(f/e.css.cell.height))}}};var p0=Object.defineProperty,N2=Object.getOwnPropertyDescriptor,B2=(e,t)=>{for(var n in t)p0(e,n,{get:t[n],enumerable:!0})},Ht=(e,t,n,a)=>{for(var o=a>1?void 0:a?N2(t,n):t,c=e.length-1,d;c>=0;c--)(d=e[c])&&(o=(a?d(t,n,o):d(o))||o);return a&&o&&p0(t,n,o),o},ye=(e,t)=>(n,a)=>t(n,a,e),Gy="Terminal input",Vf={get:()=>Gy,set:e=>Gy=e},Zy="Too much output to announce, navigate to rows manually to read",Xf={get:()=>Zy,set:e=>Zy=e};function L2(e){return e.replace(/\r?\n/g,"\r")}function O2(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function z2(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function j2(e,t,n,a){if(e.stopPropagation(),e.clipboardData){let o=e.clipboardData.getData("text/plain");m0(o,t,n,a)}}function m0(e,t,n,a){e=L2(e),e=O2(e,n.decPrivateModes.bracketedPasteMode&&a.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=""}function _0(e,t,n){let a=n.getBoundingClientRect(),o=e.clientX-a.left-10,c=e.clientY-a.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${o}px`,t.style.top=`${c}px`,t.style.zIndex="1000",t.focus()}function Qy(e,t,n,a,o){_0(e,t,n),o&&a.rightClickSelect(e),t.value=a.selectionText,t.select()}function tr(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Au(e,t=0,n=e.length){let a="";for(let o=t;o<n;++o){let c=e[o];c>65535?(c-=65536,a+=String.fromCharCode((c>>10)+55296)+String.fromCharCode(c%1024+56320)):a+=String.fromCharCode(c)}return a}var H2=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let a=0,o=0;if(this._interim){let c=e.charCodeAt(o++);56320<=c&&c<=57343?t[a++]=(this._interim-55296)*1024+c-56320+65536:(t[a++]=this._interim,t[a++]=c),this._interim=0}for(let c=o;c<n;++c){let d=e.charCodeAt(c);if(55296<=d&&d<=56319){if(++c>=n)return this._interim=d,a;let p=e.charCodeAt(c);56320<=p&&p<=57343?t[a++]=(d-55296)*1024+p-56320+65536:(t[a++]=d,t[a++]=p);continue}d!==65279&&(t[a++]=d)}return a}},U2=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let a=0,o,c,d,p,m=0,f=0;if(this.interim[0]){let b=!1,x=this.interim[0];x&=(x&224)===192?31:(x&240)===224?15:7;let C=0,k;for(;(k=this.interim[++C]&63)&&C<4;)x<<=6,x|=k;let B=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,R=B-C;for(;f<R;){if(f>=n)return 0;if(k=e[f++],(k&192)!==128){f--,b=!0;break}else this.interim[C++]=k,x<<=6,x|=k&63}b||(B===2?x<128?f--:t[a++]=x:B===3?x<2048||x>=55296&&x<=57343||x===65279||(t[a++]=x):x<65536||x>1114111||(t[a++]=x)),this.interim.fill(0)}let S=n-4,y=f;for(;y<n;){for(;y<S&&!((o=e[y])&128)&&!((c=e[y+1])&128)&&!((d=e[y+2])&128)&&!((p=e[y+3])&128);)t[a++]=o,t[a++]=c,t[a++]=d,t[a++]=p,y+=4;if(o=e[y++],o<128)t[a++]=o;else if((o&224)===192){if(y>=n)return this.interim[0]=o,a;if(c=e[y++],(c&192)!==128){y--;continue}if(m=(o&31)<<6|c&63,m<128){y--;continue}t[a++]=m}else if((o&240)===224){if(y>=n)return this.interim[0]=o,a;if(c=e[y++],(c&192)!==128){y--;continue}if(y>=n)return this.interim[0]=o,this.interim[1]=c,a;if(d=e[y++],(d&192)!==128){y--;continue}if(m=(o&15)<<12|(c&63)<<6|d&63,m<2048||m>=55296&&m<=57343||m===65279)continue;t[a++]=m}else if((o&248)===240){if(y>=n)return this.interim[0]=o,a;if(c=e[y++],(c&192)!==128){y--;continue}if(y>=n)return this.interim[0]=o,this.interim[1]=c,a;if(d=e[y++],(d&192)!==128){y--;continue}if(y>=n)return this.interim[0]=o,this.interim[1]=c,this.interim[2]=d,a;if(p=e[y++],(p&192)!==128){y--;continue}if(m=(o&7)<<18|(c&63)<<12|(d&63)<<6|p&63,m<65536||m>1114111)continue;t[a++]=m}}return a}},v0="",sr=" ",Co=class g0{constructor(){this.fg=0,this.bg=0,this.extended=new pu}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new g0;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},pu=class y0{constructor(t=0,n=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=n}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new y0(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},xs=class S0 extends Co{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new pu,this.combinedData=""}static fromCharData(t){let n=new S0;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?tr(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let n=!1;if(t[1].length>2)n=!0;else if(t[1].length===2){let a=t[1].charCodeAt(0);if(55296<=a&&a<=56319){let o=t[1].charCodeAt(1);56320<=o&&o<=57343?this.content=(a-55296)*1024+o-56320+65536|t[2]<<22:n=!0}else n=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;n&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Jy="di$target",Gf="di$dependencies",lf=new Map;function P2(e){return e[Gf]||[]}function pi(e){if(lf.has(e))return lf.get(e);let t=function(n,a,o){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");K2(t,n,o)};return t._id=e,lf.set(e,t),t}function K2(e,t,n){t[Jy]===t?t[Gf].push({id:e,index:n}):(t[Gf]=[{id:e,index:n}],t[Jy]=t)}var Oi=pi("BufferService"),b0=pi("CoreMouseService"),Pr=pi("CoreService"),I2=pi("CharsetService"),gm=pi("InstantiationService"),w0=pi("LogService"),zi=pi("OptionsService"),C0=pi("OscLinkService"),F2=pi("UnicodeService"),xo=pi("DecorationService"),Zf=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let a=[],o=this._optionsService.rawOptions.linkHandler,c=new xs,d=n.getTrimmedLength(),p=-1,m=-1,f=!1;for(let S=0;S<d;S++)if(!(m===-1&&!n.hasContent(S))){if(n.loadCell(S,c),c.hasExtendedAttrs()&&c.extended.urlId)if(m===-1){m=S,p=c.extended.urlId;continue}else f=c.extended.urlId!==p;else m!==-1&&(f=!0);if(f||m!==-1&&S===d-1){let y=this._oscLinkService.getLinkData(p)?.uri;if(y){let b={start:{x:m+1,y:e},end:{x:S+(!f&&S===d-1?1:0),y:e}},x=!1;if(!o?.allowNonHttpProtocols)try{let C=new URL(y);["http:","https:"].includes(C.protocol)||(x=!0)}catch{x=!0}x||a.push({text:y,range:b,activate:(C,k)=>o?o.activate(C,k,b):q2(C,k),hover:(C,k)=>o?.hover?.(C,k,b),leave:(C,k)=>o?.leave?.(C,k,b)})}f=!1,c.hasExtendedAttrs()&&c.extended.urlId?(m=S,p=c.extended.urlId):(m=-1,p=-1)}}t(a)}};Zf=Ht([ye(0,Oi),ye(1,zi),ye(2,C0)],Zf);function q2(e,t){if(confirm(`Do you want to navigate to ${t}?
15
15
 
16
16
  WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){try{n.opener=null}catch{}n.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Nu=pi("CharSizeService"),bn=pi("CoreBrowserService"),ym=pi("MouseService"),wn=pi("RenderService"),W2=pi("SelectionService"),x0=pi("CharacterJoinerService"),Ha=pi("ThemeService"),E0=pi("LinkProviderService"),Y2=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?eS.isErrorNoTelemetry(e)?new eS(e.message+`
17
17
 
@@ -27,18 +27,18 @@ WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){t
27
27
  `))),this._register(this._terminal.onA11yTab(c=>this._handleTab(c))),this._register(this._terminal.onKey(c=>this._handleKey(c.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Le(o,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(Tt(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<IS+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
28
28
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===IS+1&&(this._liveRegion.textContent+=Xf.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,a=n.lines.length.toString();for(let o=e;o<=t;o++){let c=n.lines.get(n.ydisp+o),d=[],p=c?.translateToString(!0,void 0,void 0,d)||"",m=(n.ydisp+o+1).toString(),f=this._rowElements[o];f&&(p.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=p,this._rowColumns.set(f,d)),f.setAttribute("aria-posinset",m),f.setAttribute("aria-setsize",a),this._alignRowWidth(f))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let n=e.target,a=this._rowElements[t===0?1:this._rowElements.length-2],o=n.getAttribute("aria-posinset"),c=t===0?"1":`${this._terminal.buffer.lines.length}`;if(o===c||e.relatedTarget!==a)return;let d,p;if(t===0?(d=n,p=this._rowElements.pop(),this._rowContainer.removeChild(p)):(d=this._rowElements.shift(),p=n,this._rowContainer.removeChild(d)),d.removeEventListener("focus",this._topBoundaryFocusListener),p.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let m=this._createAccessibilityTreeNode();this._rowElements.unshift(m),this._rowContainer.insertAdjacentElement("afterbegin",m)}else{let m=this._createAccessibilityTreeNode();this._rowElements.push(m),this._rowContainer.appendChild(m)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)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){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let a=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(a)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:a,offset:a.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let o=({node:p,offset:m})=>{let f=p instanceof Text?p.parentNode:p,S=parseInt(f?.getAttribute("aria-posinset"),10)-1;if(isNaN(S))return console.warn("row is invalid. Race condition?"),null;let y=this._rowColumns.get(f);if(!y)return console.warn("columns is null. Race condition?"),null;let b=m<y.length?y[m]:y.slice(-1)[0]+1;return b>=this._terminal.cols&&(++S,b=0),{row:S,column:b}},c=o(t),d=o(n);if(!(!c||!d)){if(c.row>d.row||c.row===d.row&&c.column>=d.column)throw new Error("invalid range");this._terminal.select(c.column,c.row,(d.row-c.row)*this._terminal.cols-c.column+d.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);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 t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let a=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${a/t})`}};yu=Ht([ye(1,gm),ye(2,bn),ye(3,wn)],yu);var Mp=class extends We{constructor(e,t,n,a,o){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=a,this._linkProviderService=o,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new _e),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new _e),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(Tt(()=>{Hr(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(Le(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Le(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Le(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Le(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let a=0;a<n.length;a++){let o=n[a];if(o.classList.contains("xterm"))break;if(o.classList.contains("xterm-hover"))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_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,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(a=>{a?.forEach(o=>{o.link.dispose&&o.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[a,o]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(a)&&(n=this._checkLinkProviderResult(a,e,n)):o.provideLinks(e.y,c=>{if(this._isMouseOut)return;let d=c?.map(p=>({link:p}));this._activeProviderReplies?.set(a,d),n=this._checkLinkProviderResult(a,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let a=0;a<t.size;a++){let o=t.get(a);if(o)for(let c=0;c<o.length;c++){let d=o[c],p=d.link.range.start.y<e?0:d.link.range.start.x,m=d.link.range.end.y>e?this._bufferService.cols:d.link.range.end.x;for(let f=p;f<=m;f++){if(n.has(f)){o.splice(c--,1);break}n.add(f)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let a=this._activeProviderReplies.get(e),o=!1;for(let c=0;c<e;c++)(!this._activeProviderReplies.has(c)||this._activeProviderReplies.get(c))&&(o=!0);if(!o&&a){let c=a.find(d=>this._linkAtPosition(d.link,t));c&&(n=!0,this._handleNewLink(c))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let c=0;c<this._activeProviderReplies.size;c++){let d=this._activeProviderReplies.get(c)?.find(p=>this._linkAtPosition(p.link,t));if(d){n=!0,this._handleNewLink(d);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&AD(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Hr(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0: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:n=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==n&&(this._currentLink.state.decorations.pointerCursor=n,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",n))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:n=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==n&&(this._currentLink.state.decorations.underline=n,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,n))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(n=>{if(!this._currentLink)return;let a=n.start===0?0:n.start+1+this._bufferService.buffer.ydisp,o=this._bufferService.buffer.ydisp+1+n.end;if(this._currentLink.link.range.start.y>=a&&this._currentLink.link.range.end.y<=o&&(this._clearCurrentLink(a,o),this._lastMouseEvent)){let c=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);c&&this._askForLink(c,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,a=this._bufferService.buffer.ydisp,o=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-a-1,n.end.x,n.end.y-a-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(o)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,a=e.range.end.y*this._bufferService.cols+e.range.end.x,o=t.y*this._bufferService.cols+t.x;return n<=o&&o<=a}_positionFromMouseEvent(e,t,n){let a=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(a)return{x:a[0],y:a[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,a,o){return{x1:e,y1:t,x2:n,y2:a,cols:this._bufferService.cols,fg:o}}};Mp=Ht([ye(1,ym),ye(2,wn),ye(3,Oi),ye(4,E0)],Mp);function AD(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var ND=class extends CD{constructor(e={}){super(e),this._linkifier=this._register(new La),this.browser=q0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new La),this._onCursorMove=this._register(new _e),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new _e),this.onKey=this._onKey.event,this._onRender=this._register(new _e),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new _e),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new _e),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new _e),this.onBell=this._onBell.event,this._onFocus=this._register(new _e),this._onBlur=this._register(new _e),this._onA11yCharEmitter=this._register(new _e),this._onA11yTabEmitter=this._register(new _e),this._onWillOpen=this._register(new _e),this._setup(),this._decorationService=this._instantiationService.createInstance(kD),this._instantiationService.setService(xo,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(bk),this._instantiationService.setService(E0,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Zf)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(Ei.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Ei.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Ei.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Ei.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(Tt(()=>{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 t of e){let n,a="";switch(t.index){case 256:n="foreground",a="10";break;case 257:n="background",a="11";break;case 258:n="cursor",a="12";break;default:n="ansi",a="4;"+t.index}switch(t.type){case 0:let o=xt.toColorRGB(n==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[n]);this.coreService.triggerDataEvent(`${oe.ESC}]${a};${vD(o)}${I0.ST}`);break;case 1:if(n==="ansi")this._themeService.modifyColors(c=>c.ansi[t.index]=Qt.toColor(...t.color));else{let c=n;this._themeService.modifyColors(d=>d[c]=Qt.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_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(yu,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(oe.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(oe.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,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),a=this._renderService.dimensions.css.cell.height,o=t.getWidth(n),c=this._renderService.dimensions.css.cell.width*o,d=this.buffer.y*this._renderService.dimensions.css.cell.height,p=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=p+"px",this.textarea.style.top=d+"px",this.textarea.style.width=c+"px",this.textarea.style.height=a+"px",this.textarea.style.lineHeight=a+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Le(this.element,"copy",t=>{this.hasSelection()&&z2(t,this._selectionService)}));let e=t=>j2(t,this.textarea,this.coreService,this.optionsService);this._register(Le(this.textarea,"paste",e)),this._register(Le(this.element,"paste",e)),W0?this._register(Le(this.element,"mousedown",t=>{t.button===2&&Qy(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Le(this.element,"contextmenu",t=>{Qy(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),km&&this._register(Le(this.element,"auxclick",t=>{t.button===1&&_0(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Le(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Le(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Le(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Le(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Le(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Le(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Le(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new 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 t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(Le(this.screenElement,"mousemove",o=>this.updateCursorStyle(o))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Vf.get()),V0||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",()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(yk,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(bn,this._coreBrowserService),this._register(Le(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Le(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(gp,this._document,this._helperContainer),this._instantiationService.setService(Nu,this._charSizeService),this._themeService=this._instantiationService.createInstance(wp),this._instantiationService.setService(Ha,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(_u),this._instantiationService.setService(x0,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Sp,this.rows,this.screenElement)),this._instantiationService.setService(wn,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(mp,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(yp),this._instantiationService.setService(ym,this._mouseService);let a=this._linkifier.value=this._register(this._instantiationService.createInstance(Mp,this.screenElement));this.element.appendChild(t);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(fp,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(bp,this.element,this.screenElement,a)),this._instantiationService.setService(W2,this._selectionService),this._register(this._selectionService.onRequestScrollLines(o=>this.scrollLines(o.amount,o.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(o=>this._renderService.handleSelectionChanged(o.start,o.end,o.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(o=>{this.textarea.value=o,this.textarea.focus(),this.textarea.select()})),this._register(Ei.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(pp,this.screenElement)),this._register(Le(this.element,"mousedown",o=>this._selectionService.handleMouseDown(o))),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(yu,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(mu,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(mu,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(vp,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(c){let d=e._mouseService.getMouseReportCoords(c,e.screenElement);if(!d)return!1;let p,m;switch(c.overrideType||c.type){case"mousemove":m=32,c.buttons===void 0?(p=3,c.button!==void 0&&(p=c.button<3?c.button:3)):p=c.buttons&1?0:c.buttons&4?1:c.buttons&2?2:3;break;case"mouseup":m=0,p=c.button<3?c.button:3;break;case"mousedown":m=1,p=c.button<3?c.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(c)===!1)return!1;let f=c.deltaY;if(f===0||e.coreMouseService.consumeWheelEvent(c,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;m=f<0?0:1,p=4;break;default:return!1}return m===void 0||p===void 0||p>4?!1:e.coreMouseService.triggerMouseEvent({col:d.col,row:d.row,x:d.x,y:d.y,button:p,action:m,ctrl:c.ctrlKey,alt:c.altKey,shift:c.shiftKey})}let a={mouseup:null,wheel:null,mousedrag:null,mousemove:null},o={mouseup:c=>(n(c),c.buttons||(this._document.removeEventListener("mouseup",a.mouseup),a.mousedrag&&this._document.removeEventListener("mousemove",a.mousedrag)),this.cancel(c)),wheel:c=>(n(c),this.cancel(c,!0)),mousedrag:c=>{c.buttons&&n(c)},mousemove:c=>{c.buttons||n(c)}};this._register(this.coreMouseService.onProtocolChange(c=>{c?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(c)),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()),c&8?a.mousemove||(t.addEventListener("mousemove",o.mousemove),a.mousemove=o.mousemove):(t.removeEventListener("mousemove",a.mousemove),a.mousemove=null),c&16?a.wheel||(t.addEventListener("wheel",o.wheel,{passive:!1}),a.wheel=o.wheel):(t.removeEventListener("wheel",a.wheel),a.wheel=null),c&2?a.mouseup||(a.mouseup=o.mouseup):(this._document.removeEventListener("mouseup",a.mouseup),a.mouseup=null),c&4?a.mousedrag||(a.mousedrag=o.mousedrag):(this._document.removeEventListener("mousemove",a.mousedrag),a.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Le(t,"mousedown",c=>{if(c.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(c)))return n(c),a.mouseup&&this._document.addEventListener("mouseup",a.mouseup),a.mousedrag&&this._document.addEventListener("mousemove",a.mousedrag),this.cancel(c)})),this._register(Le(t,"wheel",c=>{if(!a.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(c)===!1)return!1;if(!this.buffer.hasScrollback){if(c.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(c,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(c,!0);let d=oe.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(c.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(d,!0),this.cancel(c,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}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,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),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 t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){m0(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 new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new 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:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}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,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let n=ED(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let a=this.rows-1;return this.scrollLines(n.type===2?-a:a),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===oe.ETX||n.key===oe.CR)&&(this.textarea.value=""),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(BD(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){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(Zt));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(oe.ESC+"[I"):this.coreService.triggerDataEvent(oe.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let t=this._renderService.dimensions.css.canvas.width.toFixed(0),n=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${oe.ESC}[4;${n};${t}t`);break;case 1:let a=this._renderService.dimensions.css.cell.width.toFixed(0),o=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${oe.ESC}[6;${o};${a}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function BD(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var LD=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw new Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},OD=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new xs)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},FS=class{constructor(e,t){this._buffer=e,this.type=t}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 t=this._buffer.lines.get(e);if(t)return new OD(t)}getNullCell(){return new xs}},zD=class extends We{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new _e),this.onBufferChange=this._onBufferChange.event,this._normal=new FS(this._core.buffers.normal,"normal"),this._alternate=new FS(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 new 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)}},jD=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,n=>t(n.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(n,a)=>t(n,a.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},HD=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}},UD=["cols","rows"],Is=0,PD=class extends We{constructor(e){super(),this._core=this._register(new ND(e)),this._addonManager=this._register(new LD),this._publicOptions={...this._core.options};let t=a=>this._core.options[a],n=(a,o)=>{this._checkReadonlyOptions(a),this._core.options[a]=o};for(let a in this._core.options){let o={get:t.bind(this,a),set:n.bind(this,a)};Object.defineProperty(this._publicOptions,a,o)}}_checkReadonlyOptions(e){if(UD.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new 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 jD(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new HD(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 zD(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,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 t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}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,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}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,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
29
29
  `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Vf.get()},set promptLabel(e){Vf.set(e)},get tooMuchOutput(){return Xf.get()},set tooMuchOutput(e){Xf.set(e)}}}_verifyIntegers(...e){for(Is of e)if(Is===1/0||isNaN(Is)||Is%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Is of e)if(Is&&(Is===1/0||isNaN(Is)||Is%1!==0||Is<0))throw new Error("This API only accepts positive integers")}};class KD{pending=null;accept(t){let n="";for(const a of t)n+=this.acceptChar(a);return n}acceptChar(t){return t===""?this.acceptBackspace():lw.has(t)?this.acceptConsonant(t):ow.has(t)?this.acceptVowel(t):WD(t)&&this.canReplacePendingWith(t)?(this.pending=WS(t),""):this.flushPending()+t}acceptConsonant(t){if(!this.pending)return this.pending={initial:t},"";if(!this.pending.vowel){const o=this.flushPending();return this.pending={initial:t},o}if(!this.pending.final){if(cw.has(t))return this.pending.final=t,"";const o=this.flushPending();return this.pending={initial:t},o}const n=qD.get(`${this.pending.final}${t}`);if(n)return this.pending.final=n,"";const a=this.flushPending();return this.pending={initial:t},a}acceptVowel(t){if(!this.pending)return t;if(!this.pending.vowel)return this.pending.vowel=t,"";if(!this.pending.final){const c=FD.get(`${this.pending.vowel}${t}`);return c?(this.pending.vowel=c,""):this.flushPending()+t}const n=qS.get(this.pending.final);if(n){this.pending.final=n[0];const c=this.flushPending();return this.pending={initial:n[1],vowel:t},c}const a=this.pending.final,o=YS({initial:this.pending.initial,vowel:this.pending.vowel});return this.pending={initial:a,vowel:t},o}acceptBackspace(){if(!this.pending)return"";if(this.pending.final){const t=qS.get(this.pending.final);return t?this.pending.final=t[0]:delete this.pending.final,""}return this.pending.vowel?(delete this.pending.vowel,""):(this.pending=null,"")}canReplacePendingWith(t){if(!this.pending?.initial)return!1;const n=WS(t);return n.initial===this.pending.initial&&(!this.pending.vowel||n.vowel===this.pending.vowel)&&(!this.pending.final||n.final===this.pending.final)}flushPending(){if(!this.pending)return"";const t=YS(this.pending);return this.pending=null,t}}const Su=44032,bu=21,Ra=28,ID=19*bu*Ra,nw=["ㄱ","ㄲ","ㄴ","ㄷ","ㄸ","ㄹ","ㅁ","ㅂ","ㅃ","ㅅ","ㅆ","ㅇ","ㅈ","ㅉ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"],rw=["ㅏ","ㅐ","ㅑ","ㅒ","ㅓ","ㅔ","ㅕ","ㅖ","ㅗ","ㅘ","ㅙ","ㅚ","ㅛ","ㅜ","ㅝ","ㅞ","ㅟ","ㅠ","ㅡ","ㅢ","ㅣ"],aw=["","ㄱ","ㄲ","ㄳ","ㄴ","ㄵ","ㄶ","ㄷ","ㄹ","ㄺ","ㄻ","ㄼ","ㄽ","ㄾ","ㄿ","ㅀ","ㅁ","ㅂ","ㅄ","ㅅ","ㅆ","ㅇ","ㅈ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"],lw=Dm(nw),ow=Dm(rw),cw=Dm(aw),FD=new Map([["ㅗㅏ","ㅘ"],["ㅗㅐ","ㅙ"],["ㅗㅣ","ㅚ"],["ㅜㅓ","ㅝ"],["ㅜㅔ","ㅞ"],["ㅜㅣ","ㅟ"],["ㅡㅣ","ㅢ"]]),uw=[["ㄱㅅ","ㄳ"],["ㄴㅈ","ㄵ"],["ㄴㅎ","ㄶ"],["ㄹㄱ","ㄺ"],["ㄹㅁ","ㄻ"],["ㄹㅂ","ㄼ"],["ㄹㅅ","ㄽ"],["ㄹㅌ","ㄾ"],["ㄹㅍ","ㄿ"],["ㄹㅎ","ㅀ"],["ㅂㅅ","ㅄ"]],qD=new Map(uw),qS=new Map(uw.map(([e,t])=>[t,[e[0],e[1]]]));function Dm(e){return new Map(e.map((t,n)=>[t,n]))}function WD(e){const t=e.codePointAt(0);return t!==void 0&&t>=Su&&t<Su+ID}function WS(e){const t=e.codePointAt(0)-Su,n=Math.floor(t/(bu*Ra)),a=Math.floor(t%(bu*Ra)/Ra),o=t%Ra,c={initial:nw[n],vowel:rw[a]};return o===0?c:{...c,final:aw[o]}}function YS(e){if(!e.vowel)return e.initial;const t=lw.get(e.initial),n=ow.get(e.vowel),a=e.final?cw.get(e.final):0;return t===void 0||n===void 0||a===void 0?`${e.initial}${e.vowel}${e.final??""}`:String.fromCodePoint(Su+(t*bu+n)*Ra+a)}const YD=[{key:"escape",label:"Esc",ariaLabel:"Send Escape"},{key:"tab",label:"Tab",ariaLabel:"Send Tab"},{key:"arrowLeft",label:"←",ariaLabel:"Send Arrow Left"},{key:"arrowDown",label:"↓",ariaLabel:"Send Arrow Down"},{key:"arrowUp",label:"↑",ariaLabel:"Send Arrow Up"},{key:"arrowRight",label:"→",ariaLabel:"Send Arrow Right"}];function $D({ctrlActive:e,onCtrl:t,onStandaloneKey:n,onPreserveFocus:a,onHide:o}){function c(d){d.stopPropagation(),a()}return _.jsxs("div",{className:"mobile-terminal-key-bar",role:"toolbar","aria-label":"Mobile terminal keys",onMouseDown:c,onPointerDown:c,children:[_.jsx("button",{type:"button",className:"mobile-terminal-key mobile-terminal-key-ctrl","aria-label":"Arm Control modifier","aria-pressed":e,"data-active":e,onClick:t,children:"Ctrl"}),YD.map(d=>_.jsx("button",{type:"button",className:"mobile-terminal-key","aria-label":d.ariaLabel,onClick:()=>n(d.key),children:d.label},d.key)),_.jsx("button",{type:"button",className:"mobile-terminal-key mobile-terminal-key-hide","aria-label":"Hide terminal control keys",title:"Hide",onClick:o,children:"×"})]})}const VD={escape:"\x1B",tab:" ",arrowUp:"\x1B[A",arrowDown:"\x1B[B",arrowRight:"\x1B[C",arrowLeft:"\x1B[D"};function XD(e){return VD[e]}function GD(e){return/^[a-z]$/i.test(e)?String.fromCharCode(e.toUpperCase().charCodeAt(0)-64):null}const ko=new Map,uo=new Map,ZD=Object.freeze({open:!1,text:""});function QD(e){let t=uo.get(e);return t||(t=new Set,uo.set(e,t)),t}function hw(e){const t=uo.get(e);if(t)for(const n of Array.from(t))n()}function Rm(e){return ko.get(e)??ZD}function JD(e,t){const n=QD(e);return n.add(t),()=>{n.delete(t)}}function eR(e,t){const n=Rm(e);n.open!==t&&(ko.set(e,{...n,open:t}),hw(e))}function tR(e,t){const n=Rm(e);n.text!==t&&(ko.set(e,{...n,text:t}),hw(e))}function $S(e){ko.delete(e),uo.delete(e)}function iR(){ko.clear(),uo.clear()}const sR=20;function nR({terminalId:e,onSubmit:t,disabled:n=!1}){const a=g.useMemo(()=>b=>JD(e,b),[e]),o=g.useMemo(()=>()=>Rm(e),[e]),c=g.useSyncExternalStore(a,o,o),{open:d,text:p}=c,m=g.useRef(null);g.useEffect(()=>{d&&m.current?.focus()},[d]);function f(b){eR(e,b)}function S(b){tR(e,b)}function y(){if(n||!p)return;const b=p.replace(/\r\n/g,`
30
- `).replace(/\n/g,"\r");b&&t(b),window.setTimeout(()=>t("\r"),sR),S(""),m.current?.focus()}return d?_.jsxs("div",{className:"compose-drawer compose-drawer--open",children:[_.jsxs("button",{type:"button",className:"compose-drawer-header","aria-label":"Collapse compose drawer",title:"Click to collapse — Esc also closes when focus is in the textarea",onClick:()=>f(!1),children:[_.jsx("span",{"aria-hidden":"true",children:"▾"}),_.jsx("span",{className:"compose-drawer-title",children:"compose"}),_.jsx("span",{className:"compose-drawer-hint","aria-hidden":"true",children:"Cmd/Ctrl+Enter to send · Enter for newline · Esc to close"}),_.jsx("span",{className:"compose-drawer-close","aria-hidden":"true",children:"×"})]}),_.jsx("textarea",{ref:m,className:"compose-drawer-input","aria-label":"Compose input",spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",value:p,onChange:b=>S(b.target.value),onKeyDown:b=>{if(b.key==="Enter"&&(b.metaKey||b.ctrlKey)){b.preventDefault(),y();return}b.key==="Escape"&&(b.preventDefault(),f(!1))},placeholder:"Type a longer command here, then Cmd/Ctrl+Enter to send."}),_.jsxs("div",{className:"compose-drawer-actions",children:[_.jsx("button",{type:"button",className:"compose-drawer-clear",onClick:()=>{S(""),m.current?.focus()},disabled:!p,children:"Clear"}),_.jsx("button",{type:"button",className:"compose-drawer-send",onClick:y,disabled:n||!p,children:"Send"})]})]}):_.jsx("div",{className:"compose-drawer compose-drawer--closed",children:_.jsxs("button",{type:"button",className:"compose-drawer-handle","aria-label":"Open compose drawer",title:"Compose long input — type without per-keystroke latency, send with Cmd/Ctrl+Enter",onClick:()=>f(!0),children:[_.jsx("span",{"aria-hidden":"true",children:"▴"}),_.jsx("span",{children:"compose"}),p?_.jsx("span",{className:"compose-drawer-handle-dot","aria-label":"draft saved"}):null]})})}function rR(e){e.attachCustomKeyEventHandler(o=>{if(aR(o)){const c=VS(e);return c?(o.preventDefault(),o.stopPropagation(),XS(c),!1):!0}return lR(o)?(o.preventDefault(),o.stopPropagation(),oR(e),!1):!0});const t=e.element;if(!t)return{dispose(){e.attachCustomKeyEventHandler(()=>!0)}};const n=o=>{const c=VS(e);if(c){if(o.clipboardData){o.clipboardData.setData("text/plain",c),o.preventDefault();return}o.preventDefault(),XS(c)}},a=o=>{const c=o.clipboardData?.getData("text/plain");if(c===void 0)return;const d=dw(c);d!==c&&(o.preventDefault(),o.stopImmediatePropagation(),e.paste(d))};return t.addEventListener("copy",n,!0),t.addEventListener("paste",a,!0),{dispose(){t.removeEventListener("copy",n,!0),t.removeEventListener("paste",a,!0),e.attachCustomKeyEventHandler(()=>!0)}}}function aR(e){return e.type!=="keydown"||e.altKey||e.key.toLowerCase()!=="c"?!1:e.metaKey&&!e.ctrlKey&&!e.shiftKey||e.ctrlKey&&e.shiftKey&&!e.metaKey?!0:e.ctrlKey&&!e.shiftKey&&!e.metaKey}function lR(e){return e.type!=="keydown"||e.altKey||e.key.toLowerCase()!=="v"?!1:e.metaKey&&!e.ctrlKey&&!e.shiftKey||e.ctrlKey&&e.shiftKey&&!e.metaKey?!0:e.ctrlKey&&!e.shiftKey&&!e.metaKey}async function oR(e){if(navigator.clipboard?.readText)try{const t=await navigator.clipboard.readText();if(!t)return;e.paste(dw(t))}catch{}}function VS(e){return e.hasSelection()?e.getSelection():""}function dw(e){return e.replace(/(?:\r\n|\r|\n)+$/,"")}async function XS(e){if(navigator.clipboard?.writeText)try{await navigator.clipboard.writeText(e);return}catch{}cR(e)}function cR(e){const t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=document.createElement("textarea");n.value=e,n.setAttribute("readonly","true"),n.style.position="fixed",n.style.left="-9999px",n.style.top="0",n.style.opacity="0",document.body.appendChild(n),n.focus({preventScroll:!0}),n.select();try{typeof document.execCommand=="function"&&document.execCommand("copy")}finally{n.remove(),t?.focus({preventScroll:!0})}}const uR=[4,10,11,12];function hR(e,t){const n=[e.parser.registerCsiHandler({final:"c"},a=>GS(a)),e.parser.registerCsiHandler({prefix:">",final:"c"},a=>GS(a)),e.parser.registerCsiHandler({final:"n"},a=>dR(a)),e.parser.registerCsiHandler({prefix:"?",final:"n"},a=>fR(a)),e.parser.registerCsiHandler({final:"t"},a=>pR(a)),e.parser.registerDcsHandler({intermediates:"$",final:"q"},()=>!0),...uR.map(a=>e.parser.registerOscHandler(a,o=>mR(o)))];return{dispose(){for(const a of n)a.dispose()}}}function GS(e){return Ou(e)===0}function dR(e){const t=Ou(e);return t===5||t===6}function fR(e){return Ou(e)===6}function pR(e){const t=Ou(e);return t===14||t===16||t===18}function mR(e){return e.split(";").some(t=>t==="?")}function Ou(e){const t=e[0];return typeof t=="number"?t:0}const ho=new Map,_R=2*1024*1024,vR=1500,gR=25e3;function yR(e,t){let n=ho.get(e);n||(n=SR(e),ho.set(e,n),fw(n)),n.listeners.add(t);const a=c=>CR(n,c),o=()=>{n.listeners.delete(t)};return{status:n.status,snapshot:n.snapshot,output:n.output.slice(),history:n.history,send:a,detach:o}}function Ap(e){const t=ho.get(e);t&&(xR(t),ho.delete(e))}function ZS(){for(const e of Array.from(ho.keys()))Ap(e)}function SR(e){return{url:e,socket:null,status:"connecting",snapshot:null,output:[],history:null,outputBytes:0,pendingOut:[],listeners:new Set,reconnectTimer:null,reconnectEnabled:!0,heartbeat:null,isAlive:!1,exited:!1}}function fw(e){if(!e.reconnectEnabled)return;Hl(e,e.socket===null&&e.status!=="reconnecting"?"connecting":"reconnecting");const t=new WebSocket(e.url);e.socket=t,e.isAlive=!1,t.addEventListener("open",()=>{if(e.socket===t){Hl(e,"connected");for(const n of e.pendingOut)t.send(JSON.stringify(n));e.pendingOut.length=0,e.isAlive=!0,bR(e)}}),t.addEventListener("message",n=>{if(e.socket!==t)return;const a=typeof n.data=="string"?n.data:"";if(!a)return;let o=null;try{o=JSON.parse(a)}catch{return}if(!(!o||typeof o.type!="string")){if(o.type==="pong"){e.isAlive=!0;return}wR(e,o),pw(e,{type:"message",message:o})}}),t.addEventListener("close",n=>{if(e.socket===t){if(e.socket=null,Mm(e),n.code===1008){e.reconnectEnabled=!1,Hl(e,"unauthorized");return}if(e.exited||!e.reconnectEnabled){Hl(e,"closed");return}Hl(e,"reconnecting"),e.reconnectTimer=window.setTimeout(()=>{e.reconnectTimer=null,fw(e)},vR)}}),t.addEventListener("error",()=>{})}function bR(e){Mm(e),e.heartbeat=window.setInterval(()=>{const t=e.socket;if(!(!t||t.readyState!==WebSocket.OPEN)){if(!e.isAlive){t.close();return}e.isAlive=!1,t.send(JSON.stringify({type:"ping",nonce:Date.now().toString(36)}))}},gR)}function Mm(e){e.heartbeat!==null&&(window.clearInterval(e.heartbeat),e.heartbeat=null)}function wR(e,t){if(t.type==="snapshot"){e.snapshot=t.terminal,e.output=t.output.slice(),e.history=t.history??null,e.outputBytes=e.output.reduce((n,a)=>n+a.length,0),e.exited=t.terminal.status==="exited",QS(e);return}if(t.type==="output"){e.output.push(t.data),e.outputBytes+=t.data.length,QS(e);return}if(t.type==="terminal_updated"){e.snapshot=t.terminal,t.terminal.status==="exited"&&(e.exited=!0);return}if(t.type==="exit"){e.exited=!0,e.snapshot&&e.snapshot.id===t.terminalId&&(e.snapshot={...e.snapshot,status:"exited",exitCode:t.exitCode});return}}function QS(e){for(;e.outputBytes>_R&&e.output.length>1;){const t=e.output.shift();e.outputBytes-=t.length}}function Hl(e,t){e.status!==t&&(e.status=t,pw(e,{type:"status",status:t}))}function pw(e,t){for(const n of Array.from(e.listeners))n(t)}function CR(e,t){const n=e.socket;return n&&n.readyState===WebSocket.OPEN?(n.send(JSON.stringify(t)),!0):(t.type==="input"&&e.pendingOut.push(t),!1)}function xR(e){e.reconnectEnabled=!1,e.reconnectTimer!==null&&(window.clearTimeout(e.reconnectTimer),e.reconnectTimer=null),Mm(e);const t=e.socket;e.socket=null,t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),e.listeners.clear()}const ER=[0,50,150,350],TR=[300,1200,2500],kR=1e3,DR=1e5,Np="\x1B[?1049l\x1B[?1047l\x1B[?47l",RR=new Set(["47","1047","1049"]),MR=80,AR=6,JS=[500,1500,3e3,5e3,8e3];function eb({terminal:e,serverApi:t,active:n,visible:a=!0,canClose:o,refreshCwdOnEnter:c=!1,tabId:d,onSelect:p,onClose:m,onExit:f,onSnapshot:S,onAuthClose:y}){const b=g.useSyncExternalStore(e0,Pf,()=>Lr),x=g.useSyncExternalStore(t0,Kf,()=>Na),C=g.useSyncExternalStore(i0,Ff,()=>!0),k=g.useSyncExternalStore(u0,lr,()=>du),B=g.useRef(null),R=g.useRef(null),re=g.useRef(null),F=g.useRef(null),J=g.useRef({onExit:f,onSnapshot:S}),ce=g.useRef(t.createWebSocketUrl),q=g.useRef(y),I=g.useRef(null),ie=g.useRef(new Map),de=g.useRef([]),j=g.useRef([]),$=g.useRef([]),H=g.useRef(0),L=g.useRef(!1),X=g.useRef(null),G=g.useRef(0),M=g.useRef(null),V=g.useRef(null),Q=g.useRef(!1),ve=g.useRef(!1),Se=g.useRef(!1),E=g.useRef(null),W=g.useRef(null),ee=g.useRef(!1),he=g.useRef(!1),ge=g.useRef(!1),me=g.useRef(!1),Ce=g.useRef(!1),ze=g.useRef(!1),Ne=g.useRef(!1),Re=g.useRef(n),Pe=g.useRef(a),Ye=g.useRef(c),Be=g.useRef(b),ae=g.useRef(x),[,Ee]=g.useState("connecting"),[xe,Ke]=g.useState(!1),[Xe,gt]=g.useState(null),[yt,mi]=g.useState(!1),[te,je]=g.useState(null),[He,_i]=g.useState(!1),[Vi,ai]=g.useState(!1),[kt,ji]=g.useState(!1),[Ti,Nt]=g.useState(null),[$s,Hi]=g.useState(!1),[qt,Jt]=g.useState(!1);g.useLayoutEffect(()=>{Re.current=n},[n]),g.useLayoutEffect(()=>{Pe.current=a},[a]),g.useLayoutEffect(()=>{Ye.current=c},[c]),g.useLayoutEffect(()=>{Be.current=b},[b]),g.useLayoutEffect(()=>{ae.current=x},[x]),g.useEffect(()=>{a&&n&&e.status==="running"&&(nt(),Qi())},[n,a,e.status]),g.useEffect(()=>{J.current={onExit:f,onSnapshot:S}},[f,S]),g.useEffect(()=>{ce.current=t.createWebSocketUrl,q.current=y},[t,y]),g.useEffect(()=>{let O=!1,fe=null,Oe=0;const T=jR(e.currentCommand);function A(){fe!==null&&(window.clearTimeout(fe),fe=null)}function K(){if(!T||Oe>=JS.length||O)return;const pe=JS[Oe++];fe=window.setTimeout(()=>{fe=null,ue()},pe)}async function ue(){try{const pe=await t.getTerminalTranscriptSource(e.id);if(O)return;Nt(pe.source),pe.source||K()}catch(pe){if(O)return;Nt(null),Sf(pe)&&K()}}return Nt(null),e.status!=="running"?()=>{O=!0,A()}:(ue(),()=>{O=!0,A()})},[t,e.currentCommand,e.id,e.status]),g.useEffect(()=>{Hi(!1)},[e.id,Ti?.provider,Ti?.sessionId]),g.useEffect(()=>{const O=R.current;O&&(O.options.disableStdin=e.status==="exited"),e.status==="exited"&&Ee("closed")},[e.status]),g.useEffect(()=>{const O=R.current;O&&(O.options.fontSize=b,tf(b,ae.current).then(()=>{Be.current===b&&nt()}))},[b]),g.useEffect(()=>{const O=R.current;O&&(O.options.fontFamily=Uf(x),tf(Be.current,x).then(()=>{ae.current===x&&nt()}))},[x]),g.useEffect(()=>{const O=R.current;O&&(O.options.theme=tb(k))},[k]),g.useEffect(()=>{const O=B.current;if(!O)return;let fe=!1,Oe=null,T=null,A=null,K=null,ue=null,pe=null,ke=null;I.current=null,Ce.current=!1,ze.current=!1,Wt(),Cn();const De=Be.current,rt=ae.current,ut=new PD({cursorBlink:!0,convertEol:!1,disableStdin:e.status==="exited",fontFamily:Uf(rt),fontSize:De,fontWeight:400,fontWeightBold:700,macOptionClickForcesSelection:!0,scrollback:DR,theme:{...tb(lr())}}),yi=new A2;return ut.loadAddon(yi),K=hR(ut),R.current=ut,re.current=yi,tf(De,rt).then(()=>{if(fe)return;ut.open(O),Ce.current=!0,Oe=rR(ut),Pe.current&&Re.current&&e.status==="running"&&Qi(),nt(),ue=XR(O,ut,()=>Be.current*1.2,Ge,Ut=>{ot(Ut)},Yt,us),pe=YR(O,ut,Ge,Ut=>{ot(Ut)},Yt,us);const Fr=new KD;T=ut.onData(Ut=>{if(Ne.current){const Ia=GD(Ut);if(Ia){Ui(!1),Zi(Ia);return}}const qr=Fr.accept(Ut);qr&&Zi(qr)}),A=ut.onScroll(Ut=>{if(he.current||me.current||ge.current){ct();return}Ni(),ir(ut)&&mt({scrollToBottom:!0}),Ge(),Ut<=3&&ot()}),ke=new ResizeObserver(()=>{ei()}),ke.observe(O),ze.current&&(Ts(),ze.current=!1,nt()),Bt()}),()=>{fe=!0,Ce.current=!1,ze.current=!1,Wt(),bt(),Ai(),ge.current=!1,ue?.(),pe?.(),ke?.disconnect(),Oe?.dispose(),T?.dispose(),A?.dispose(),K?.dispose(),ut.dispose(),R.current=null,re.current=null}},[e.id]),g.useEffect(()=>{const O=ce.current(e.id),fe=yR(O,Dt);return F.current=fe.send,Ee(fe.status),fe.status==="connected"&&nt(),fe.snapshot&&(J.current.onSnapshot(fe.snapshot,{notifyCompletion:!1}),R.current&&(nt(),Bs(fe.output,fe.history),nt())),()=>{fe.detach(),F.current=null}},[e.id]);function Dt(O){if(O.type==="status"){Ee(O.status),O.status==="unauthorized"&&q.current?.(),O.status==="connected"&&nt();return}li(O.message)}function Cn(O=[],fe=null){j.current=[],$.current=ib(O),H.current=0,L.current=!1,X.current=null,ge.current=!1,G.current+=1,M.current=fe,V.current=null,Q.current=!1,ve.current=!1,Se.current=!1,ze.current=!1,E.current=null,ee.current=!1,Ke(!1),gt(null),mi(!1),je(null),_i(!1),ai(!1)}function Bs(O=[],fe=null){Cn(O,fe),Vs()}function Vs(){if(!R.current||!Ce.current){ze.current=!0;return}ze.current=!1,Ts()}async function Ts(){const O=R.current;if(!O)return;const fe=$c(O,ee.current),Oe=fe?$.current.length:H.current;await ks(O,{liveOutputLimit:Oe,scrollToBottom:fe}),R.current===O&&ct()}function ks(O,fe={}){return new Promise(Oe=>{ge.current=!0,L.current=!1;const T=G.current+1;G.current=T;const A=Math.max(0,Math.min(fe.liveOutputLimit??$.current.length,$.current.length)),K=()=>{if(R.current!==O||G.current!==T){Oe();return}try{H.current=A,fe.scrollToBottom&&Xs(O)}finally{ge.current=!1;const pe=gi();pe&&mt(pe),Oe()}},ue=()=>{if(R.current!==O||G.current!==T){Oe();return}O.clear();const pe=ib([...j.current,...$.current.slice(0,A)]);if(pe.length===0){K();return}for(let ke=0;ke<pe.length;ke+=1){const De=pe[ke];ke===pe.length-1?O.write(De,K):O.write(De)}};if(O.buffer.active.type==="alternate"){O.write(Np,ue);return}ue()})}async function ot(O=0){const fe=R.current;if(Se.current||!fe)return;const Oe=M.current;Se.current=!0,Ke(!0);const T=fe.buffer.active.viewportY;try{let A=!!(Oe&&!Oe.hasMore);if(!A)try{const K=await t.getTerminalHistory(e.id,{beforeLine:Oe?.startLine??0,limit:kR});if(M.current={startLine:K.startLine,endLine:K.endLine,hasMore:K.hasMore},K.output.length>0){await Rt(fe,K.output,T,O);return}A=!K.hasMore}catch(K){A=Sf(K)}A&&await St(fe,T,O)}catch{}finally{Se.current=!1,Ke(!1)}}async function St(O,fe,Oe){if(!(Q.current||ve.current))try{const T=V.current,A=await t.getTerminalTranscriptHistory(e.id,{...T?{cursor:T}:{},limit:80});if(Nt(A.source),V.current=A.cursor,ve.current=!A.hasMore||!A.cursor,A.output.length===0)return;await Rt(O,A.output,fe,Oe)}catch(T){Sf(T)&&(Q.current=!0)}}async function Rt(O,fe,Oe,T){j.current=[...fe,...j.current];const A=qR(fe);await ks(O,{liveOutputLimit:H.current,scrollToBottom:!1}),R.current===O&&(xn(O,Math.max(0,Oe+A+Math.min(0,T))),ee.current=!ir(O),Ge())}g.useEffect(()=>{const O=window.visualViewport;function fe(){document.visibilityState==="visible"&&nt()}function Oe(){nt()}function T(){Bt()}return document.addEventListener("visibilitychange",fe),window.addEventListener("pageshow",Oe),window.addEventListener("resize",T),O?.addEventListener("resize",T),O?.addEventListener("scroll",T),()=>{document.removeEventListener("visibilitychange",fe),window.removeEventListener("pageshow",Oe),window.removeEventListener("resize",T),O?.removeEventListener("resize",T),O?.removeEventListener("scroll",T)}},[e.id]);function li(O){if(O.type==="snapshot"&&O.terminal.id===e.id){if(J.current.onSnapshot(O.terminal,{notifyCompletion:!1}),!R.current)return;nt(),Bs(O.output,O.history??null),nt();return}if(O.type==="terminal_updated"&&O.terminal.id===e.id){J.current.onSnapshot(O.terminal,{notifyCompletion:!0});return}if(O.type==="output"&&O.terminalId===e.id){const Oe=_w(O.data);if(!Oe)return;$.current.push(Oe),R.current&&Ce.current?mt({scrollToBottom:!0}):ze.current=!0;return}const fe=R.current;if(fe){if(O.type==="exit"&&O.terminalId===e.id){J.current.onExit(O.exitCode),Ee("closed");return}O.type==="error"&&fe.writeln(`\r
31
- [nterminal] ${O.message}`)}}function ei(O=25){if(document.visibilityState==="hidden"||!Pe.current||ie.current.has(O))return;const fe=window.setTimeout(()=>{ie.current.delete(O),Os()},O);ie.current.set(O,fe)}function Bt(){for(const O of ER)ei(O)}function nt(){I.current=null,Bt()}function Wt(){for(const O of ie.current.values())window.clearTimeout(O);ie.current.clear()}function bt(){for(const O of de.current)window.clearTimeout(O);de.current=[]}function Ge(){if(ct(),!E.current){mi(!1);return}mi(!0),Ai(),W.current=window.setTimeout(()=>{W.current=null,mi(!1)},1200)}function ct(){const O=R.current,fe=O?WR(O):null;if(E.current=fe,gt(fe),ai(!!(O&&fe)),_i(!!(O&&fe&&!ir(O))),fe||!O||!vi()){je(null);return}je({alternate:O.buffer.active.type==="alternate"})}function vi(){const O=M.current;return j.current.length>0||!!O?.hasMore}function Ai(){W.current!==null&&(window.clearTimeout(W.current),W.current=null)}function Ni(){const O=R.current;O&&(ee.current=!ir(O),ct())}function ki(O){X.current=bf(X.current,O)}function cs(O){const fe=X.current;return X.current=null,bf(fe,O)}function gi(){const O=X.current;return X.current=null,O}function mt(O={}){const fe=R.current;if(!fe||!Ce.current){ze.current=!0;return}if(ge.current){ki(O);return}if(L.current){ki(O);return}const Oe=cs(O);if(!Oe.force&&!$c(fe,ee.current)){ct();return}L.current=!0;const T=G.current,A=()=>{if(R.current!==fe||G.current!==T){L.current=!1;return}if(!Oe.force&&!$c(fe,ee.current)){L.current=!1,ct();return}const K=H.current,ue=$.current[K];if(ue===void 0){L.current=!1,Oe.scrollToBottom&&Xs(fe),ct();const pe=gi();pe&&mt(bf(Oe,pe));return}H.current=K+1,fe.write(ue,A)};A()}function Yt(){me.current=!0}function us(){Ni(),me.current=!1;const O=R.current;O&&ir(O)&&mt({scrollToBottom:!0})}function Xs(O){hr(()=>sb(O))&&(ee.current=!1)}function xn(O,fe){hr(()=>(O.scrollToLine(fe),!0))}function hr(O){he.current=!0;try{return O()}finally{he.current=!1}}function Xi(){const O=R.current;if(!O)return;const fe=()=>{sb(O),ee.current=!1,ct(),mt({force:!0,scrollToBottom:!0}),Qi()};if(O.buffer.active.type==="alternate"){O.write(Np,fe);return}fe()}function Gi(O){const fe=R.current,Oe=B.current;if(!fe||!Oe)return;const T=Oe.getBoundingClientRect();if(T.height<=0)return;const A=Math.max(0,Math.min(1,(O-T.top)/T.height)),K=Math.round(fe.buffer.active.baseY*A);Yt();try{fe.scrollToLine(K)}finally{us()}ee.current=!ir(fe),ct(),Ge(),K<=3&&ot()}function En(O){O.preventDefault(),O.stopPropagation(),O.currentTarget.setPointerCapture?.(O.pointerId),Gi(O.clientY)}function Ls(O){(O.buttons&1)!==0&&(O.preventDefault(),O.stopPropagation(),Gi(O.clientY))}function Os(){const O=R.current,fe=re.current;if(!(!O||!fe)&&!(document.visibilityState==="hidden"||!Pe.current||B.current?.isConnected===!1))try{const Oe=$c(O,ee.current);fe.fit(),Oe&&Xs(O),O.refresh(0,Math.max(0,O.rows-1)),ct();const T={cols:O.cols,rows:O.rows},A=I.current;if(A&&A.cols===T.cols&&A.rows===T.rows)return;Ds({type:"resize",terminalId:e.id,cols:T.cols,rows:T.rows})&&(I.current=T)}catch{}}function Ds(O){const fe=F.current;return fe?fe(O):!1}function Zi(O){mt({force:!0,scrollToBottom:!0}),Ds({type:"input",terminalId:e.id,data:O})&&zR(O)&&Lt()}function Lt(){!Ye.current||!Re.current||(bt(),de.current=TR.map(O=>{const fe=window.setTimeout(()=>{de.current=de.current.filter(Oe=>Oe!==fe),Ye.current&&Re.current&&Ds({type:"refresh_cwd",terminalId:e.id})},O);return fe}))}function Qi(){R.current?.focus()}function Ir(){ji(O=>{const fe=!O;return Ne.current=fe,fe}),Qi()}function Ui(O){Ne.current=O,ji(O)}function zs(O){Ne.current&&Ui(!1),Zi(XD(O)),Qi()}return _.jsxs("section",{className:"terminal-pane","data-active":n,onMouseDown:()=>{n||p()},children:[_.jsx(NR,{terminal:e,canClose:o,tabId:d,transcriptSource:Ti,onOpenTranscript:()=>Hi(!0),onClose:m}),_.jsx("div",{className:"xterm-container",ref:B}),xe?_.jsx("div",{className:"terminal-history-loader",role:"status","aria-label":"Loading older terminal output",children:_.jsx("span",{"aria-hidden":"true"})}):null,C&&Xe?_.jsxs("div",{className:"terminal-scroll-progress","data-active":yt,"aria-hidden":"true",children:[Xe.current,"/",Xe.total]}):C&&te?_.jsxs("div",{className:"terminal-scroll-progress","data-active":!1,"data-pending":"true","data-buffer":te.alternate?"alternate":"normal","aria-hidden":"true",children:[te.alternate?"alt ":"","0/?"]}):null,He?_.jsx("button",{type:"button",className:"terminal-scroll-bottom-button","aria-label":"Scroll terminal to bottom",title:"Scroll to bottom",onPointerDown:O=>O.stopPropagation(),onMouseDown:O=>O.stopPropagation(),onClick:O=>{O.stopPropagation(),Xi()},children:"↓"}):null,Vi?_.jsx("button",{type:"button",className:"terminal-scroll-handle","aria-label":"Drag terminal scroll handle",title:"Drag to scroll",onPointerDown:En,onPointerMove:Ls,children:_.jsx("span",{"aria-hidden":"true"})}):null,n&&e.status==="running"?qt?_.jsx($D,{ctrlActive:kt,onCtrl:Ir,onStandaloneKey:zs,onPreserveFocus:Qi,onHide:()=>Jt(!1)}):_.jsx("button",{type:"button",className:"mobile-terminal-key-toggle","aria-label":"Show terminal control keys",title:"Show Ctrl / Esc / Tab / arrows",onMouseDown:O=>{O.stopPropagation(),Qi()},onPointerDown:O=>{O.stopPropagation(),Qi()},onClick:()=>Jt(!0),children:"⌨"}):null,_.jsx(nR,{terminalId:e.id,onSubmit:Zi,disabled:e.status!=="running"}),$s&&Ti?_.jsx(BR,{terminal:e,serverApi:t,source:Ti,onClose:()=>Hi(!1)}):null]})}function tb(e){return{background:"#0a0d10",foreground:"#e2e8ee",cursor:e2(e),selectionBackground:t2(e)}}function NR({terminal:e,canClose:t,tabId:n,transcriptSource:a,onOpenTranscript:o,onClose:c}){const d=Fb({id:`pane-${e.id}`,disabled:!n,...n?{data:{kind:"pane",sourceTabId:n,terminalId:e.id}}:{}}),p={cursor:n?"grab":"default",opacity:d.isDragging?.5:void 0};return _.jsxs("header",{ref:d.setNodeRef,className:"terminal-pane-header",style:p,"data-dragging":d.isDragging,...d.attributes,...d.listeners,children:[_.jsx("span",{className:"terminal-pane-dot","aria-hidden":"true"}),_.jsx("span",{className:"terminal-pane-cwd",title:e.cwd,children:e.cwd}),_.jsx("span",{className:"terminal-pane-spacer"}),a?_.jsx("button",{type:"button",className:"terminal-pane-transcript","data-provider":a.provider,title:`View ${Oa(a.provider)} transcript history`,"aria-label":`View ${Oa(a.provider)} transcript history`,onPointerDown:m=>m.stopPropagation(),onMouseDown:m=>m.stopPropagation(),onClick:m=>{m.stopPropagation(),o()},children:"View history"}):null,_.jsx("span",{className:`terminal-pane-state terminal-pane-state-${e.status}`,children:e.status}),t?_.jsx("button",{type:"button",className:"terminal-pane-close","aria-label":`Close pane ${e.title}`,title:"Close pane",onPointerDown:m=>m.stopPropagation(),onMouseDown:m=>m.stopPropagation(),onClick:m=>{m.stopPropagation(),c()},children:"x"}):null]})}function BR({terminal:e,serverApi:t,source:n,onClose:a}){const o=g.useRef(null),c=g.useRef(0),d=g.useRef(!1),p=g.useRef(!1),m=g.useRef(null),[f,S]=g.useState([]),[y,b]=g.useState(null),[x,C]=g.useState(!1),[k,B]=g.useState(!0),[R,re]=g.useState(!1),[F,J]=g.useState(null),[ce,q]=g.useState(""),[I,ie]=g.useState("all"),[de,j]=g.useState(()=>new Set);g.useEffect(()=>{c.current+=1;const E=c.current;return d.current=!1,p.current=!0,m.current=null,S([]),b(null),C(!1),J(null),$(null,"initial",E),()=>{c.current===E&&(c.current+=1)}},[t,n.provider,n.sessionId,e.id]),g.useLayoutEffect(()=>{const E=o.current;if(!E)return;if(p.current){p.current=!1,E.scrollTop=E.scrollHeight;return}const W=m.current;W!==null&&(m.current=null,E.scrollTop+=E.scrollHeight-W)},[f]);async function $(E,W,ee=c.current){if(!d.current){d.current=!0,W==="initial"?B(!0):(re(!0),m.current=o.current?.scrollHeight??null),J(null);try{await H(E,W,ee)}catch(he){if(c.current!==ee)return;J(he instanceof Error?he.message:"Failed to load transcript history.")}finally{c.current===ee&&(d.current=!1,B(!1),re(!1))}}}async function H(E,W,ee){let he=E,ge=0;for(;c.current===ee;){const me=await t.getTerminalTranscriptHistory(e.id,{...he?{cursor:he}:{},limit:MR});if(c.current!==ee)return;const Ce=HR(me.output,n.provider);if(b(me.cursor),C(!!(me.hasMore&&me.cursor)),Ce){S(ze=>W==="older"?[Ce,...ze]:[Ce]);return}if(!me.hasMore||!me.cursor||ge>=AR)return;he=me.cursor,ge+=1}}function L(){const E=o.current;!E||E.scrollTop>72||!x||!y||d.current||$(y,"older")}const X=Oa(n.provider),G=f.join(""),M=g.useMemo(()=>UR(G,n.provider),[n.provider,G]),V=ce.trim().toLowerCase(),Q=g.useMemo(()=>M.filter(E=>I!=="all"&&E.kind!==I?!1:V?E.searchText.includes(V):!0),[I,V,M]),ve=M.length===0?"0 entries":`${Q.length}/${M.length} entries`;function Se(E){j(W=>{const ee=new Set(W);return ee.has(E)?ee.delete(E):ee.add(E),ee})}return _.jsx("div",{className:"security-overlay transcript-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"transcript-dialog-title",onClick:a,children:_.jsxs("div",{className:"security-panel transcript-dialog",onClick:E=>E.stopPropagation(),children:[_.jsxs("header",{className:"security-panel-header",children:[_.jsxs("div",{className:"transcript-dialog-title",children:[_.jsxs("h2",{id:"transcript-dialog-title",children:[X," JSONL"]}),_.jsx("span",{title:n.sessionId,children:n.sessionId})]}),_.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:a,children:"×"})]}),_.jsxs("div",{className:"transcript-dialog-controls",children:[_.jsxs("label",{className:"transcript-search",children:[_.jsx("span",{children:"Search"}),_.jsx("input",{type:"search",value:ce,"aria-label":"Search JSONL transcript",placeholder:"Find text",onChange:E=>q(E.currentTarget.value)})]}),_.jsx("div",{className:"transcript-filter-group",role:"group","aria-label":"Transcript type filter",children:LR.map(E=>_.jsx("button",{type:"button","data-active":I===E.value,onClick:()=>ie(E.value),children:E.label},E.value))}),_.jsx("span",{className:"transcript-result-count",children:ve})]}),_.jsxs("div",{ref:o,className:"transcript-dialog-scroll","aria-label":"JSONL transcript output",onScroll:L,children:[R?_.jsx("div",{className:"transcript-dialog-status",children:"Loading older entries..."}):null,!k&&x?_.jsx("div",{className:"transcript-dialog-hint",children:"Scroll up for older entries"}):null,G?_.jsx("div",{className:"transcript-block-list",children:Q.map(E=>_.jsx(OR,{block:E,expanded:de.has(E.id),onToggle:()=>Se(E.id)},E.id))}):null,k?_.jsx("div",{className:"transcript-dialog-status",children:"Loading transcript..."}):null,!k&&!G&&!F?_.jsx("div",{className:"transcript-dialog-status",children:"No transcript entries found."}):null,!k&&G&&Q.length===0?_.jsx("div",{className:"transcript-dialog-status",children:"No matching transcript entries."}):null,F?_.jsx("div",{className:"transcript-dialog-error",children:F}):null]})]})})}const LR=[{value:"all",label:"All"},{value:"user",label:"User"},{value:"assistant",label:"Assistant"},{value:"tool",label:"Tool"},{value:"system",label:"System"}];function OR({block:e,expanded:t,onToggle:n}){const a=e.kind==="tool"&&(e.body.length>1800||IR(e.body)>42),c=a&&!t?`${e.body.slice(0,1800).trimEnd()}
30
+ `).replace(/\n/g,"\r");b&&t(b),window.setTimeout(()=>t("\r"),sR),S(""),m.current?.focus()}return d?_.jsxs("div",{className:"compose-drawer compose-drawer--open",children:[_.jsxs("button",{type:"button",className:"compose-drawer-header","aria-label":"Collapse compose drawer",title:"Click to collapse — Esc also closes when focus is in the textarea",onClick:()=>f(!1),children:[_.jsx("span",{"aria-hidden":"true",children:"▾"}),_.jsx("span",{className:"compose-drawer-title",children:"compose"}),_.jsx("span",{className:"compose-drawer-hint","aria-hidden":"true",children:"Cmd/Ctrl+Enter to send · Enter for newline · Esc to close"}),_.jsx("span",{className:"compose-drawer-close","aria-hidden":"true",children:"×"})]}),_.jsx("textarea",{ref:m,className:"compose-drawer-input","aria-label":"Compose input",spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",value:p,onChange:b=>S(b.target.value),onKeyDown:b=>{if(b.key==="Enter"&&(b.metaKey||b.ctrlKey)){b.preventDefault(),y();return}b.key==="Escape"&&(b.preventDefault(),f(!1))},placeholder:"Type a longer command here, then Cmd/Ctrl+Enter to send."}),_.jsxs("div",{className:"compose-drawer-actions",children:[_.jsx("button",{type:"button",className:"compose-drawer-clear",onClick:()=>{S(""),m.current?.focus()},disabled:!p,children:"Clear"}),_.jsx("button",{type:"button",className:"compose-drawer-send",onClick:y,disabled:n||!p,children:"Send"})]})]}):_.jsx("div",{className:"compose-drawer compose-drawer--closed",children:_.jsxs("button",{type:"button",className:"compose-drawer-handle","aria-label":"Open compose drawer",title:"Compose long input — type without per-keystroke latency, send with Cmd/Ctrl+Enter",onClick:()=>f(!0),children:[_.jsx("span",{"aria-hidden":"true",children:"▴"}),_.jsx("span",{children:"compose"}),p?_.jsx("span",{className:"compose-drawer-handle-dot","aria-label":"draft saved"}):null]})})}function rR(e){e.attachCustomKeyEventHandler(o=>{if(aR(o)){const c=VS(e);return c?(o.preventDefault(),o.stopPropagation(),XS(c),!1):!0}return lR(o)?(o.preventDefault(),o.stopPropagation(),oR(e),!1):!0});const t=e.element;if(!t)return{dispose(){e.attachCustomKeyEventHandler(()=>!0)}};const n=o=>{const c=VS(e);if(c){if(o.clipboardData){o.clipboardData.setData("text/plain",c),o.preventDefault();return}o.preventDefault(),XS(c)}},a=o=>{const c=o.clipboardData?.getData("text/plain");if(c===void 0)return;const d=dw(c);d!==c&&(o.preventDefault(),o.stopImmediatePropagation(),e.paste(d))};return t.addEventListener("copy",n,!0),t.addEventListener("paste",a,!0),{dispose(){t.removeEventListener("copy",n,!0),t.removeEventListener("paste",a,!0),e.attachCustomKeyEventHandler(()=>!0)}}}function aR(e){return e.type!=="keydown"||e.altKey||e.key.toLowerCase()!=="c"?!1:e.metaKey&&!e.ctrlKey&&!e.shiftKey||e.ctrlKey&&e.shiftKey&&!e.metaKey?!0:e.ctrlKey&&!e.shiftKey&&!e.metaKey}function lR(e){return e.type!=="keydown"||e.altKey||e.key.toLowerCase()!=="v"?!1:e.metaKey&&!e.ctrlKey&&!e.shiftKey||e.ctrlKey&&e.shiftKey&&!e.metaKey?!0:e.ctrlKey&&!e.shiftKey&&!e.metaKey}async function oR(e){if(navigator.clipboard?.readText)try{const t=await navigator.clipboard.readText();if(!t)return;e.paste(dw(t))}catch{}}function VS(e){return e.hasSelection()?e.getSelection():""}function dw(e){return e.replace(/(?:\r\n|\r|\n)+$/,"")}async function XS(e){if(navigator.clipboard?.writeText)try{await navigator.clipboard.writeText(e);return}catch{}cR(e)}function cR(e){const t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=document.createElement("textarea");n.value=e,n.setAttribute("readonly","true"),n.style.position="fixed",n.style.left="-9999px",n.style.top="0",n.style.opacity="0",document.body.appendChild(n),n.focus({preventScroll:!0}),n.select();try{typeof document.execCommand=="function"&&document.execCommand("copy")}finally{n.remove(),t?.focus({preventScroll:!0})}}const uR=[4,10,11,12];function hR(e,t){const n=[e.parser.registerCsiHandler({final:"c"},a=>GS(a)),e.parser.registerCsiHandler({prefix:">",final:"c"},a=>GS(a)),e.parser.registerCsiHandler({final:"n"},a=>dR(a)),e.parser.registerCsiHandler({prefix:"?",final:"n"},a=>fR(a)),e.parser.registerCsiHandler({final:"t"},a=>pR(a)),e.parser.registerDcsHandler({intermediates:"$",final:"q"},()=>!0),...uR.map(a=>e.parser.registerOscHandler(a,o=>mR(o)))];return{dispose(){for(const a of n)a.dispose()}}}function GS(e){return Ou(e)===0}function dR(e){const t=Ou(e);return t===5||t===6}function fR(e){return Ou(e)===6}function pR(e){const t=Ou(e);return t===14||t===16||t===18}function mR(e){return e.split(";").some(t=>t==="?")}function Ou(e){const t=e[0];return typeof t=="number"?t:0}const ho=new Map,_R=2*1024*1024,vR=1500,gR=25e3;function yR(e,t){let n=ho.get(e);n||(n=SR(e),ho.set(e,n),fw(n)),n.listeners.add(t);const a=c=>CR(n,c),o=()=>{n.listeners.delete(t)};return{status:n.status,snapshot:n.snapshot,output:n.output.slice(),history:n.history,send:a,detach:o}}function Ap(e){const t=ho.get(e);t&&(xR(t),ho.delete(e))}function ZS(){for(const e of Array.from(ho.keys()))Ap(e)}function SR(e){return{url:e,socket:null,status:"connecting",snapshot:null,output:[],history:null,outputBytes:0,pendingOut:[],listeners:new Set,reconnectTimer:null,reconnectEnabled:!0,heartbeat:null,isAlive:!1,exited:!1}}function fw(e){if(!e.reconnectEnabled)return;Hl(e,e.socket===null&&e.status!=="reconnecting"?"connecting":"reconnecting");const t=new WebSocket(e.url);e.socket=t,e.isAlive=!1,t.addEventListener("open",()=>{if(e.socket===t){Hl(e,"connected");for(const n of e.pendingOut)t.send(JSON.stringify(n));e.pendingOut.length=0,e.isAlive=!0,bR(e)}}),t.addEventListener("message",n=>{if(e.socket!==t)return;const a=typeof n.data=="string"?n.data:"";if(!a)return;let o=null;try{o=JSON.parse(a)}catch{return}if(!(!o||typeof o.type!="string")){if(o.type==="pong"){e.isAlive=!0;return}wR(e,o),pw(e,{type:"message",message:o})}}),t.addEventListener("close",n=>{if(e.socket===t){if(e.socket=null,Mm(e),n.code===1008){e.reconnectEnabled=!1,Hl(e,"unauthorized");return}if(e.exited||!e.reconnectEnabled){Hl(e,"closed");return}Hl(e,"reconnecting"),e.reconnectTimer=window.setTimeout(()=>{e.reconnectTimer=null,fw(e)},vR)}}),t.addEventListener("error",()=>{})}function bR(e){Mm(e),e.heartbeat=window.setInterval(()=>{const t=e.socket;if(!(!t||t.readyState!==WebSocket.OPEN)){if(!e.isAlive){t.close();return}e.isAlive=!1,t.send(JSON.stringify({type:"ping",nonce:Date.now().toString(36)}))}},gR)}function Mm(e){e.heartbeat!==null&&(window.clearInterval(e.heartbeat),e.heartbeat=null)}function wR(e,t){if(t.type==="snapshot"){e.snapshot=t.terminal,e.output=t.output.slice(),e.history=t.history??null,e.outputBytes=e.output.reduce((n,a)=>n+a.length,0),e.exited=t.terminal.status==="exited",QS(e);return}if(t.type==="output"){e.output.push(t.data),e.outputBytes+=t.data.length,QS(e);return}if(t.type==="terminal_updated"){e.snapshot=t.terminal,t.terminal.status==="exited"&&(e.exited=!0);return}if(t.type==="exit"){e.exited=!0,e.snapshot&&e.snapshot.id===t.terminalId&&(e.snapshot={...e.snapshot,status:"exited",exitCode:t.exitCode});return}}function QS(e){for(;e.outputBytes>_R&&e.output.length>1;){const t=e.output.shift();e.outputBytes-=t.length}}function Hl(e,t){e.status!==t&&(e.status=t,pw(e,{type:"status",status:t}))}function pw(e,t){for(const n of Array.from(e.listeners))n(t)}function CR(e,t){const n=e.socket;return n&&n.readyState===WebSocket.OPEN?(n.send(JSON.stringify(t)),!0):(t.type==="input"&&e.pendingOut.push(t),!1)}function xR(e){e.reconnectEnabled=!1,e.reconnectTimer!==null&&(window.clearTimeout(e.reconnectTimer),e.reconnectTimer=null),Mm(e);const t=e.socket;e.socket=null,t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),e.listeners.clear()}const ER=[0,50,150,350],TR=[300,1200,2500],kR=1e3,DR=1e5,Np="\x1B[?1049l\x1B[?1047l\x1B[?47l",RR=new Set(["47","1047","1049"]),MR=80,AR=6,JS=[500,1500,3e3,5e3,8e3];function eb({terminal:e,serverApi:t,active:n,visible:a=!0,canClose:o,refreshCwdOnEnter:c=!1,tabId:d,onSelect:p,onClose:m,onExit:f,onSnapshot:S,onAuthClose:y}){const b=g.useSyncExternalStore(e0,Pf,()=>Lr),x=g.useSyncExternalStore(t0,Kf,()=>Na),C=g.useSyncExternalStore(i0,Ff,()=>!0),k=g.useSyncExternalStore(u0,lr,()=>du),B=g.useRef(null),R=g.useRef(null),re=g.useRef(null),F=g.useRef(null),J=g.useRef({onExit:f,onSnapshot:S}),ce=g.useRef(t.createWebSocketUrl),q=g.useRef(y),I=g.useRef(null),ie=g.useRef(new Map),de=g.useRef([]),j=g.useRef([]),$=g.useRef([]),H=g.useRef(0),L=g.useRef(!1),X=g.useRef(null),G=g.useRef(0),M=g.useRef(null),V=g.useRef(null),Q=g.useRef(!1),ve=g.useRef(!1),Se=g.useRef(!1),E=g.useRef(null),W=g.useRef(null),ee=g.useRef(!1),he=g.useRef(!1),ge=g.useRef(!1),me=g.useRef(!1),Ce=g.useRef(!1),ze=g.useRef(!1),Ne=g.useRef(!1),Re=g.useRef(n),Pe=g.useRef(a),Ye=g.useRef(c),Be=g.useRef(b),ae=g.useRef(x),[,Ee]=g.useState("connecting"),[xe,Ke]=g.useState(!1),[Xe,gt]=g.useState(null),[yt,mi]=g.useState(!1),[te,je]=g.useState(null),[He,_i]=g.useState(!1),[Vi,ai]=g.useState(!1),[kt,ji]=g.useState(!1),[Ti,Nt]=g.useState(null),[$s,Hi]=g.useState(!1),[qt,Jt]=g.useState(!1);g.useLayoutEffect(()=>{Re.current=n},[n]),g.useLayoutEffect(()=>{Pe.current=a},[a]),g.useLayoutEffect(()=>{Ye.current=c},[c]),g.useLayoutEffect(()=>{Be.current=b},[b]),g.useLayoutEffect(()=>{ae.current=x},[x]),g.useEffect(()=>{a&&n&&e.status==="running"&&(nt(),Qi())},[n,a,e.status]),g.useEffect(()=>{J.current={onExit:f,onSnapshot:S}},[f,S]),g.useEffect(()=>{ce.current=t.createWebSocketUrl,q.current=y},[t,y]),g.useEffect(()=>{let O=!1,fe=null,Oe=0;const T=HR(e.currentCommand);function A(){fe!==null&&(window.clearTimeout(fe),fe=null)}function K(){if(!T||Oe>=JS.length||O)return;const pe=JS[Oe++];fe=window.setTimeout(()=>{fe=null,ue()},pe)}async function ue(){try{const pe=await t.getTerminalTranscriptSource(e.id);if(O)return;Nt(pe.source),pe.source||K()}catch(pe){if(O)return;Nt(null),Sf(pe)&&K()}}return Nt(null),e.status!=="running"?()=>{O=!0,A()}:(ue(),()=>{O=!0,A()})},[t,e.currentCommand,e.id,e.status]),g.useEffect(()=>{Hi(!1)},[e.id,Ti?.provider,Ti?.sessionId]),g.useEffect(()=>{const O=R.current;O&&(O.options.disableStdin=e.status==="exited"),e.status==="exited"&&Ee("closed")},[e.status]),g.useEffect(()=>{const O=R.current;O&&(O.options.fontSize=b,tf(b,ae.current).then(()=>{Be.current===b&&nt()}))},[b]),g.useEffect(()=>{const O=R.current;O&&(O.options.fontFamily=Uf(x),tf(Be.current,x).then(()=>{ae.current===x&&nt()}))},[x]),g.useEffect(()=>{const O=R.current;O&&(O.options.theme=tb(k))},[k]),g.useEffect(()=>{const O=B.current;if(!O)return;let fe=!1,Oe=null,T=null,A=null,K=null,ue=null,pe=null,ke=null;I.current=null,Ce.current=!1,ze.current=!1,Wt(),Cn();const De=Be.current,rt=ae.current,ut=new PD({cursorBlink:!0,convertEol:!1,disableStdin:e.status==="exited",fontFamily:Uf(rt),fontSize:De,fontWeight:400,fontWeightBold:700,macOptionClickForcesSelection:!0,scrollback:DR,theme:{...tb(lr())}}),yi=new A2;return ut.loadAddon(yi),K=hR(ut),R.current=ut,re.current=yi,tf(De,rt).then(()=>{if(fe)return;ut.open(O),Ce.current=!0,Oe=rR(ut),Pe.current&&Re.current&&e.status==="running"&&Qi(),nt(),ue=GR(O,ut,()=>Be.current*1.2,Ge,Ut=>{ot(Ut)},Yt,us),pe=$R(O,ut,Ge,Ut=>{ot(Ut)},Yt,us);const Fr=new KD;T=ut.onData(Ut=>{if(Ne.current){const Ia=GD(Ut);if(Ia){Ui(!1),Zi(Ia);return}}const qr=Fr.accept(Ut);qr&&Zi(qr)}),A=ut.onScroll(Ut=>{if(he.current||me.current||ge.current){ct();return}Ni(),ir(ut)&&mt({scrollToBottom:!0}),Ge(),Ut<=3&&ot()}),ke=new ResizeObserver(()=>{ei()}),ke.observe(O),ze.current&&(Ts(),ze.current=!1,nt()),Bt()}),()=>{fe=!0,Ce.current=!1,ze.current=!1,Wt(),bt(),Ai(),ge.current=!1,ue?.(),pe?.(),ke?.disconnect(),Oe?.dispose(),T?.dispose(),A?.dispose(),K?.dispose(),ut.dispose(),R.current=null,re.current=null}},[e.id]),g.useEffect(()=>{const O=ce.current(e.id),fe=yR(O,Dt);return F.current=fe.send,Ee(fe.status),fe.status==="connected"&&nt(),fe.snapshot&&(J.current.onSnapshot(fe.snapshot,{notifyCompletion:!1}),R.current&&(nt(),Bs(fe.output,fe.history),nt())),()=>{fe.detach(),F.current=null}},[e.id]);function Dt(O){if(O.type==="status"){Ee(O.status),O.status==="unauthorized"&&q.current?.(),O.status==="connected"&&nt();return}li(O.message)}function Cn(O=[],fe=null){j.current=[],$.current=ib(O),H.current=0,L.current=!1,X.current=null,ge.current=!1,G.current+=1,M.current=fe,V.current=null,Q.current=!1,ve.current=!1,Se.current=!1,ze.current=!1,E.current=null,ee.current=!1,Ke(!1),gt(null),mi(!1),je(null),_i(!1),ai(!1)}function Bs(O=[],fe=null){Cn(O,fe),Vs()}function Vs(){if(!R.current||!Ce.current){ze.current=!0;return}ze.current=!1,Ts()}async function Ts(){const O=R.current;if(!O)return;const fe=$c(O,ee.current),Oe=fe?$.current.length:H.current;await ks(O,{liveOutputLimit:Oe,scrollToBottom:fe}),R.current===O&&ct()}function ks(O,fe={}){return new Promise(Oe=>{ge.current=!0,L.current=!1;const T=G.current+1;G.current=T;const A=Math.max(0,Math.min(fe.liveOutputLimit??$.current.length,$.current.length)),K=()=>{if(R.current!==O||G.current!==T){Oe();return}try{H.current=A,fe.scrollToBottom&&Xs(O)}finally{ge.current=!1;const pe=gi();pe&&mt(pe),Oe()}},ue=()=>{if(R.current!==O||G.current!==T){Oe();return}O.clear();const pe=ib([...j.current,...$.current.slice(0,A)]);if(pe.length===0){K();return}for(let ke=0;ke<pe.length;ke+=1){const De=pe[ke];ke===pe.length-1?O.write(De,K):O.write(De)}};if(O.buffer.active.type==="alternate"){O.write(Np,ue);return}ue()})}async function ot(O=0){const fe=R.current;if(Se.current||!fe)return;const Oe=M.current;Se.current=!0,Ke(!0);const T=fe.buffer.active.viewportY;try{let A=!!(Oe&&!Oe.hasMore);if(!A)try{const K=await t.getTerminalHistory(e.id,{beforeLine:Oe?.startLine??0,limit:kR});if(M.current={startLine:K.startLine,endLine:K.endLine,hasMore:K.hasMore},K.output.length>0){await Rt(fe,K.output,T,O);return}A=!K.hasMore}catch(K){A=Sf(K)}A&&await St(fe,T,O)}catch{}finally{Se.current=!1,Ke(!1)}}async function St(O,fe,Oe){if(!(Q.current||ve.current))try{const T=V.current,A=await t.getTerminalTranscriptHistory(e.id,{...T?{cursor:T}:{},limit:80});if(Nt(A.source),V.current=A.cursor,ve.current=!A.hasMore||!A.cursor,A.output.length===0)return;await Rt(O,A.output,fe,Oe)}catch(T){Sf(T)&&(Q.current=!0)}}async function Rt(O,fe,Oe,T){j.current=[...fe,...j.current];const A=WR(fe);await ks(O,{liveOutputLimit:H.current,scrollToBottom:!1}),R.current===O&&(xn(O,Math.max(0,Oe+A+Math.min(0,T))),ee.current=!ir(O),Ge())}g.useEffect(()=>{const O=window.visualViewport;function fe(){document.visibilityState==="visible"&&nt()}function Oe(){nt()}function T(){Bt()}return document.addEventListener("visibilitychange",fe),window.addEventListener("pageshow",Oe),window.addEventListener("resize",T),O?.addEventListener("resize",T),O?.addEventListener("scroll",T),()=>{document.removeEventListener("visibilitychange",fe),window.removeEventListener("pageshow",Oe),window.removeEventListener("resize",T),O?.removeEventListener("resize",T),O?.removeEventListener("scroll",T)}},[e.id]);function li(O){if(O.type==="snapshot"&&O.terminal.id===e.id){if(J.current.onSnapshot(O.terminal,{notifyCompletion:!1}),!R.current)return;nt(),Bs(O.output,O.history??null),nt();return}if(O.type==="terminal_updated"&&O.terminal.id===e.id){J.current.onSnapshot(O.terminal,{notifyCompletion:!0});return}if(O.type==="output"&&O.terminalId===e.id){const Oe=_w(O.data);if(!Oe)return;$.current.push(Oe),R.current&&Ce.current?mt({scrollToBottom:!0}):ze.current=!0;return}const fe=R.current;if(fe){if(O.type==="exit"&&O.terminalId===e.id){J.current.onExit(O.exitCode),Ee("closed");return}O.type==="error"&&fe.writeln(`\r
31
+ [nterminal] ${O.message}`)}}function ei(O=25){if(document.visibilityState==="hidden"||!Pe.current||ie.current.has(O))return;const fe=window.setTimeout(()=>{ie.current.delete(O),Os()},O);ie.current.set(O,fe)}function Bt(){for(const O of ER)ei(O)}function nt(){I.current=null,Bt()}function Wt(){for(const O of ie.current.values())window.clearTimeout(O);ie.current.clear()}function bt(){for(const O of de.current)window.clearTimeout(O);de.current=[]}function Ge(){if(ct(),!E.current){mi(!1);return}mi(!0),Ai(),W.current=window.setTimeout(()=>{W.current=null,mi(!1)},1200)}function ct(){const O=R.current,fe=O?YR(O):null;if(E.current=fe,gt(fe),ai(!!(O&&fe)),_i(!!(O&&fe&&!ir(O))),fe||!O||!vi()){je(null);return}je({alternate:O.buffer.active.type==="alternate"})}function vi(){const O=M.current;return j.current.length>0||!!O?.hasMore}function Ai(){W.current!==null&&(window.clearTimeout(W.current),W.current=null)}function Ni(){const O=R.current;O&&(ee.current=!ir(O),ct())}function ki(O){X.current=bf(X.current,O)}function cs(O){const fe=X.current;return X.current=null,bf(fe,O)}function gi(){const O=X.current;return X.current=null,O}function mt(O={}){const fe=R.current;if(!fe||!Ce.current){ze.current=!0;return}if(ge.current){ki(O);return}if(L.current){ki(O);return}const Oe=cs(O);if(!Oe.force&&!$c(fe,ee.current)){ct();return}L.current=!0;const T=G.current,A=()=>{if(R.current!==fe||G.current!==T){L.current=!1;return}if(!Oe.force&&!$c(fe,ee.current)){L.current=!1,ct();return}const K=H.current,ue=$.current[K];if(ue===void 0){L.current=!1,Oe.scrollToBottom&&Xs(fe),ct();const pe=gi();pe&&mt(bf(Oe,pe));return}H.current=K+1,fe.write(ue,A)};A()}function Yt(){me.current=!0}function us(){Ni(),me.current=!1;const O=R.current;O&&ir(O)&&mt({scrollToBottom:!0})}function Xs(O){hr(()=>sb(O))&&(ee.current=!1)}function xn(O,fe){hr(()=>(O.scrollToLine(fe),!0))}function hr(O){he.current=!0;try{return O()}finally{he.current=!1}}function Xi(){const O=R.current;if(!O)return;const fe=()=>{sb(O),ee.current=!1,ct(),mt({force:!0,scrollToBottom:!0}),Qi()};if(O.buffer.active.type==="alternate"){O.write(Np,fe);return}fe()}function Gi(O){const fe=R.current,Oe=B.current;if(!fe||!Oe)return;const T=Oe.getBoundingClientRect();if(T.height<=0)return;const A=Math.max(0,Math.min(1,(O-T.top)/T.height)),K=Math.round(fe.buffer.active.baseY*A);Yt();try{fe.scrollToLine(K)}finally{us()}ee.current=!ir(fe),ct(),Ge(),K<=3&&ot()}function En(O){O.preventDefault(),O.stopPropagation(),O.currentTarget.setPointerCapture?.(O.pointerId),Gi(O.clientY)}function Ls(O){(O.buttons&1)!==0&&(O.preventDefault(),O.stopPropagation(),Gi(O.clientY))}function Os(){const O=R.current,fe=re.current;if(!(!O||!fe)&&!(document.visibilityState==="hidden"||!Pe.current||B.current?.isConnected===!1))try{const Oe=$c(O,ee.current);fe.fit(),Oe&&Xs(O),O.refresh(0,Math.max(0,O.rows-1)),ct();const T={cols:O.cols,rows:O.rows},A=I.current;if(A&&A.cols===T.cols&&A.rows===T.rows)return;Ds({type:"resize",terminalId:e.id,cols:T.cols,rows:T.rows})&&(I.current=T)}catch{}}function Ds(O){const fe=F.current;return fe?fe(O):!1}function Zi(O){mt({force:!0,scrollToBottom:!0}),Ds({type:"input",terminalId:e.id,data:O})&&zR(O)&&Lt()}function Lt(){!Ye.current||!Re.current||(bt(),de.current=TR.map(O=>{const fe=window.setTimeout(()=>{de.current=de.current.filter(Oe=>Oe!==fe),Ye.current&&Re.current&&Ds({type:"refresh_cwd",terminalId:e.id})},O);return fe}))}function Qi(){R.current?.focus()}function Ir(){ji(O=>{const fe=!O;return Ne.current=fe,fe}),Qi()}function Ui(O){Ne.current=O,ji(O)}function zs(O){Ne.current&&Ui(!1),Zi(XD(O)),Qi()}return _.jsxs("section",{className:"terminal-pane","data-active":n,onMouseDown:()=>{n||p()},children:[_.jsx(NR,{terminal:e,canClose:o,tabId:d,transcriptSource:Ti,onOpenTranscript:()=>Hi(!0),onClose:m}),_.jsx("div",{className:"xterm-container",ref:B}),xe?_.jsx("div",{className:"terminal-history-loader",role:"status","aria-label":"Loading older terminal output",children:_.jsx("span",{"aria-hidden":"true"})}):null,C&&Xe?_.jsxs("div",{className:"terminal-scroll-progress","data-active":yt,"aria-hidden":"true",children:[Xe.current,"/",Xe.total]}):C&&te?_.jsxs("div",{className:"terminal-scroll-progress","data-active":!1,"data-pending":"true","data-buffer":te.alternate?"alternate":"normal","aria-hidden":"true",children:[te.alternate?"alt ":"","0/?"]}):null,He?_.jsx("button",{type:"button",className:"terminal-scroll-bottom-button","aria-label":"Scroll terminal to bottom",title:"Scroll to bottom",onPointerDown:O=>O.stopPropagation(),onMouseDown:O=>O.stopPropagation(),onClick:O=>{O.stopPropagation(),Xi()},children:"↓"}):null,Vi?_.jsx("button",{type:"button",className:"terminal-scroll-handle","aria-label":"Drag terminal scroll handle",title:"Drag to scroll",onPointerDown:En,onPointerMove:Ls,children:_.jsx("span",{"aria-hidden":"true"})}):null,n&&e.status==="running"?qt?_.jsx($D,{ctrlActive:kt,onCtrl:Ir,onStandaloneKey:zs,onPreserveFocus:Qi,onHide:()=>Jt(!1)}):_.jsx("button",{type:"button",className:"mobile-terminal-key-toggle","aria-label":"Show terminal control keys",title:"Show Ctrl / Esc / Tab / arrows",onMouseDown:O=>{O.stopPropagation(),Qi()},onPointerDown:O=>{O.stopPropagation(),Qi()},onClick:()=>Jt(!0),children:"⌨"}):null,_.jsx(nR,{terminalId:e.id,onSubmit:Zi,disabled:e.status!=="running"}),$s&&Ti?_.jsx(BR,{terminal:e,serverApi:t,source:Ti,onClose:()=>Hi(!1)}):null]})}function tb(e){return{background:"#0a0d10",foreground:"#e2e8ee",cursor:e2(e),selectionBackground:t2(e)}}function NR({terminal:e,canClose:t,tabId:n,transcriptSource:a,onOpenTranscript:o,onClose:c}){const d=Fb({id:`pane-${e.id}`,disabled:!n,...n?{data:{kind:"pane",sourceTabId:n,terminalId:e.id}}:{}}),p={cursor:n?"grab":"default",opacity:d.isDragging?.5:void 0};return _.jsxs("header",{ref:d.setNodeRef,className:"terminal-pane-header",style:p,"data-dragging":d.isDragging,...d.attributes,...d.listeners,children:[_.jsx("span",{className:"terminal-pane-dot","aria-hidden":"true"}),_.jsx("span",{className:"terminal-pane-cwd",title:e.cwd,children:e.cwd}),_.jsx("span",{className:"terminal-pane-spacer"}),a?_.jsx("button",{type:"button",className:"terminal-pane-transcript","data-provider":a.provider,title:`View ${Oa(a.provider)} transcript history`,"aria-label":`View ${Oa(a.provider)} transcript history`,onPointerDown:m=>m.stopPropagation(),onMouseDown:m=>m.stopPropagation(),onClick:m=>{m.stopPropagation(),o()},children:"View history"}):null,_.jsx("span",{className:`terminal-pane-state terminal-pane-state-${e.status}`,children:e.status}),t?_.jsx("button",{type:"button",className:"terminal-pane-close","aria-label":`Close pane ${e.title}`,title:"Close pane",onPointerDown:m=>m.stopPropagation(),onMouseDown:m=>m.stopPropagation(),onClick:m=>{m.stopPropagation(),c()},children:"x"}):null]})}function BR({terminal:e,serverApi:t,source:n,onClose:a}){const o=g.useRef(null),c=g.useRef(0),d=g.useRef(!1),p=g.useRef(!1),m=g.useRef(null),[f,S]=g.useState([]),[y,b]=g.useState(null),[x,C]=g.useState(!1),[k,B]=g.useState(!0),[R,re]=g.useState(!1),[F,J]=g.useState(null),[ce,q]=g.useState(""),[I,ie]=g.useState("all"),[de,j]=g.useState(()=>new Set);g.useEffect(()=>{c.current+=1;const E=c.current;return d.current=!1,p.current=!0,m.current=null,S([]),b(null),C(!1),J(null),$(null,"initial",E),()=>{c.current===E&&(c.current+=1)}},[t,n.provider,n.sessionId,e.id]),g.useLayoutEffect(()=>{const E=o.current;if(!E)return;if(p.current){p.current=!1,E.scrollTop=E.scrollHeight;return}const W=m.current;W!==null&&(m.current=null,E.scrollTop+=E.scrollHeight-W)},[f]);async function $(E,W,ee=c.current){if(!d.current){d.current=!0,W==="initial"?B(!0):(re(!0),m.current=o.current?.scrollHeight??null),J(null);try{await H(E,W,ee)}catch(he){if(c.current!==ee)return;J(he instanceof Error?he.message:"Failed to load transcript history.")}finally{c.current===ee&&(d.current=!1,B(!1),re(!1))}}}async function H(E,W,ee){let he=E,ge=0;for(;c.current===ee;){const me=await t.getTerminalTranscriptHistory(e.id,{...he?{cursor:he}:{},limit:MR});if(c.current!==ee)return;const Ce=UR(me.output,n.provider);if(b(me.cursor),C(!!(me.hasMore&&me.cursor)),Ce){S(ze=>W==="older"?[Ce,...ze]:[Ce]);return}if(!me.hasMore||!me.cursor||ge>=AR)return;he=me.cursor,ge+=1}}function L(){const E=o.current;!E||E.scrollTop>72||!x||!y||d.current||$(y,"older")}const X=Oa(n.provider),G=f.join(""),M=g.useMemo(()=>PR(G,n.provider),[n.provider,G]),V=ce.trim().toLowerCase(),Q=g.useMemo(()=>M.filter(E=>I!=="all"&&E.kind!==I?!1:V?E.searchText.includes(V):!0),[I,V,M]),ve=M.length===0?"0 entries":`${Q.length}/${M.length} entries`;function Se(E){j(W=>{const ee=new Set(W);return ee.has(E)?ee.delete(E):ee.add(E),ee})}return _.jsx("div",{className:"security-overlay transcript-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"transcript-dialog-title",onClick:a,children:_.jsxs("div",{className:"security-panel transcript-dialog",onClick:E=>E.stopPropagation(),children:[_.jsxs("header",{className:"security-panel-header",children:[_.jsxs("div",{className:"transcript-dialog-title",children:[_.jsxs("h2",{id:"transcript-dialog-title",children:[X," JSONL"]}),_.jsx("span",{title:n.sessionId,children:n.sessionId})]}),_.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:a,children:"×"})]}),_.jsxs("div",{className:"transcript-dialog-controls",children:[_.jsxs("label",{className:"transcript-search",children:[_.jsx("span",{children:"Search"}),_.jsx("input",{type:"search",value:ce,"aria-label":"Search JSONL transcript",placeholder:"Find text",onChange:E=>q(E.currentTarget.value)})]}),_.jsx("div",{className:"transcript-filter-group",role:"group","aria-label":"Transcript type filter",children:LR.map(E=>_.jsx("button",{type:"button","data-active":I===E.value,onClick:()=>ie(E.value),children:E.label},E.value))}),_.jsx("span",{className:"transcript-result-count",children:ve})]}),_.jsxs("div",{ref:o,className:"transcript-dialog-scroll","aria-label":"JSONL transcript output",onScroll:L,children:[R?_.jsx("div",{className:"transcript-dialog-status",children:"Loading older entries..."}):null,!k&&x?_.jsx("div",{className:"transcript-dialog-hint",children:"Scroll up for older entries"}):null,G?_.jsx("div",{className:"transcript-block-list",children:Q.map(E=>_.jsx(OR,{block:E,expanded:de.has(E.id),onToggle:()=>Se(E.id)},E.id))}):null,k?_.jsx("div",{className:"transcript-dialog-status",children:"Loading transcript..."}):null,!k&&!G&&!F?_.jsx("div",{className:"transcript-dialog-status",children:"No transcript entries found."}):null,!k&&G&&Q.length===0?_.jsx("div",{className:"transcript-dialog-status",children:"No matching transcript entries."}):null,F?_.jsx("div",{className:"transcript-dialog-error",children:F}):null]})]})})}const LR=[{value:"all",label:"All"},{value:"user",label:"User"},{value:"assistant",label:"Assistant"},{value:"tool",label:"Tool"},{value:"system",label:"System"}];function OR({block:e,expanded:t,onToggle:n}){const a=e.kind==="tool"&&(e.body.length>1800||FR(e.body)>42),c=a&&!t?`${e.body.slice(0,1800).trimEnd()}
32
32
  ...`:e.body;return _.jsxs("article",{className:"transcript-block","data-kind":e.kind,children:[_.jsxs("header",{children:[_.jsx("span",{children:e.header}),a?_.jsx("button",{type:"button",onClick:n,children:t?"Collapse":"Expand"}):null]}),_.jsx("pre",{children:c})]})}function zR(e){return e.includes("\r")||e.includes(`
33
- `)}function Sf(e){return e instanceof yn&&e.status===404}function jR(e){if(!e)return!1;const t=e.replace(/^.*[\\/]/,"").toLowerCase();return t==="codex"||t==="codex.js"||t.startsWith("codex-")||t==="claude"||t==="claude.js"||t.startsWith("claude-")}function Oa(e){return e==="codex"?"Codex":"Claude"}function HR(e,t){const n=`[nterminal] ${Oa(t)} transcript archive ends here. Live terminal screen continues below.`,a=e.join("").replace(/\r\n/g,`
33
+ `)}function Sf(e){return e instanceof yn&&e.status===404}function jR(e){if(!e)return!1;const t=e.replace(/^.*[\\/]/,"").toLowerCase();return t==="codex"||t==="codex.js"||t.startsWith("codex-")||t==="claude"||t==="claude.js"||t.startsWith("claude-")}function HR(e){if(jR(e))return!0;if(!e)return!1;const t=e.replace(/^.*[\\/]/,"").toLowerCase();return t==="node"||t==="nodejs"}function Oa(e){return e==="codex"?"Codex":"Claude"}function UR(e,t){const n=`[nterminal] ${Oa(t)} transcript archive ends here. Live terminal screen continues below.`,a=e.join("").replace(/\r\n/g,`
34
34
  `).replace(/\r/g,`
35
35
  `).replace(n,"").replace(/\n{3,}/g,`
36
36
 
37
37
  `).trimEnd();return a?`${a}
38
- `:""}function UR(e,t){const n=e.trim();if(!n)return[];const a=n.split(`
39
- `),o=[];let c=null;for(let d=0;d<a.length;d+=1){const p=a[d];if((d===0||a[d-1]?.trim()==="")&&PR(p,t)){c&&o.push(c),c={header:p,bodyLines:[]};continue}c||(c={header:"Transcript",bodyLines:[]}),c.bodyLines.push(p)}return c&&o.push(c),o.map((d,p)=>{const m=d.bodyLines.join(`
38
+ `:""}function PR(e,t){const n=e.trim();if(!n)return[];const a=n.split(`
39
+ `),o=[];let c=null;for(let d=0;d<a.length;d+=1){const p=a[d];if((d===0||a[d-1]?.trim()==="")&&KR(p,t)){c&&o.push(c),c={header:p,bodyLines:[]};continue}c||(c={header:"Transcript",bodyLines:[]}),c.bodyLines.push(p)}return c&&o.push(c),o.map((d,p)=>{const m=d.bodyLines.join(`
40
40
  `).trimEnd(),f=m?`${d.header}
41
- ${m}`:d.header;return{id:`${p}:${FR(f)}`,kind:KR(d.header,m,t),header:d.header,body:m,text:f,searchText:f.toLowerCase()}})}function PR(e,t){const n=mw(e);return n?n==="User"||n===Oa(t)||n==="System"||n==="Tool output"||n.startsWith("Tool call:"):!1}function mw(e){return(e.match(/^\[[^\]\n]+\]\s+(.+)$/)?.[1]??e).trim()||null}function KR(e,t,n){const a=mw(e);return a==="User"?"user":a===Oa(n)?t.startsWith("[tool call:")||t.startsWith("[tool output]")?"tool":"assistant":a==="System"?"system":a==="Tool output"||a?.startsWith("Tool call:")?"tool":"other"}function IR(e){return e.split(`
42
- `).length}function FR(e){let t=5381;for(let n=0;n<e.length;n+=1)t=t*33^e.charCodeAt(n);return(t>>>0).toString(36)}function qR(e){let t=0;for(const n of e){if(!n)continue;const a=n.match(/\r\n|\r|\n/g);t+=a?.length??1}return Math.max(1,t)}function ib(e){const t=[];for(const n of e){const a=_w(n);a&&t.push(a)}return t}function _w(e){return e.replace(/\x1b\[\?([0-9;:]*)([hl])/g,(t,n,a)=>{const o=n.split(";").filter(Boolean).filter(c=>!RR.has(c.split(":")[0]??""));return o.length>0?`\x1B[?${o.join(";")}${a}`:""})}function bf(e,t={}){const n={};return(e?.force||t.force)&&(n.force=!0),(e?.scrollToBottom||t.scrollToBottom)&&(n.scrollToBottom=!0),n}function WR(e){const t=e.buffer.active,n=t.baseY+e.rows;return n<=e.rows?null:{current:Math.max(1,Math.min(n,t.viewportY+1)),total:n}}function ir(e){return e.buffer.active.viewportY>=Math.max(0,e.buffer.active.baseY-1)}function $c(e,t){return!t||ir(e)}function sb(e){return ir(e)?!1:(e.scrollToLine(Math.max(0,e.buffer.active.baseY)),!0)}function YR(e,t,n,a,o,c){const d=p=>{const m=VR(p);m!==0&&(p.cancelable&&p.preventDefault(),p.stopPropagation(),$R(t,m,n,a,o,c))};return e.addEventListener("wheel",d,{capture:!0,passive:!1}),()=>{e.removeEventListener("wheel",d,{capture:!0})}}function $R(e,t,n,a,o,c){const d=()=>{o();try{e.scrollLines(t)}finally{c()}n(),t<0&&e.buffer.active.viewportY<=3&&a(t)};if(e.buffer.active.type==="alternate"){e.write(Np,d);return}d()}function VR(e){const n=e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?e.deltaY/24:e.deltaMode===WheelEvent.DOM_DELTA_PAGE?e.deltaY*24:e.deltaY;if(n===0)return 0;const a=n<0?Math.floor(n):Math.ceil(n);return Math.max(-30,Math.min(30,a))}function XR(e,t,n,a,o,c,d){let p=null,m=0;const f={passive:!1};function S(x){p=wf(x),m=0}function y(x){const C=wf(x);if(C===null){p=null,m=0;return}if(p===null){p=C;return}const k=C.clientY-p.clientY;if(p=C,x.cancelable&&x.preventDefault(),k===0)return;if(GR(t)&&ZR(t,C,-k)){m=0;return}m-=k/n();const B=m<0?Math.ceil(m):Math.floor(m);if(B!==0){m-=B,c();try{t.scrollLines(B)}finally{d()}a(),B<0&&t.buffer.active.viewportY<=3&&o(B)}}function b(x){if(x.touches.length>0){p=wf(x);return}p=null,m=0}return e.addEventListener("touchstart",S,f),e.addEventListener("touchmove",y,f),e.addEventListener("touchend",b),e.addEventListener("touchcancel",b),()=>{e.removeEventListener("touchstart",S,f),e.removeEventListener("touchmove",y,f),e.removeEventListener("touchend",b),e.removeEventListener("touchcancel",b)}}function wf(e){if(e.touches.length!==1)return null;const t=e.touches[0];return t?{clientX:t.clientX,clientY:t.clientY}:null}function GR(e){return e.buffer.active.type==="alternate"||e.modes.mouseTrackingMode!=="none"}function ZR(e,t,n){const a=e.element;return a?(a.dispatchEvent(QR(t,n)),!0):!1}function QR(e,t){const n=typeof WheelEvent=="function"?WheelEvent.DOM_DELTA_PIXEL:0,a={bubbles:!0,cancelable:!0,clientX:e.clientX,clientY:e.clientY,deltaX:0,deltaY:t,deltaMode:n};if(typeof WheelEvent=="function")return new WheelEvent("wheel",a);const o=new Event("wheel",a);return Object.defineProperties(o,{clientX:{value:e.clientX},clientY:{value:e.clientY},deltaX:{value:0},deltaY:{value:t},deltaMode:{value:0}}),o}function Bp({node:e,terminals:t,editors:n,api:a,activeTerminalId:o,visible:c=!0,refreshCwdOnEnter:d=!1,tabId:p,dropZoneActive:m=!1,draggingTerminalId:f=null,mobileFocusLeafKey:S=null,path:y=[],totalPanes:b,onSelect:x,onClose:C,onResize:k,onExit:B,onSnapshot:R,onCloseEditor:re,onAuthClose:F}){const J=b??Lp(e);if(y.length===0&&S){const ie=Op(e),de=ie.some(j=>j.key===S)?S:ie[0]?.key;if(ie.length>1&&de)return _.jsx("div",{className:"mobile-focused-split",children:ie.map(j=>{const $=j.key===de;if(j.type==="editor"){const L=n[j.editorId];return _.jsx("div",{className:"mobile-focused-pane","data-active":$,"aria-hidden":!$,children:L?_.jsx(Xy,{api:a,editor:L,canClose:J>1,onClose:()=>re(j.editorId)}):_.jsx("div",{className:"missing-pane",children:"Editor unavailable"})},j.key)}const H=t[j.terminalId];return H?_.jsx("div",{className:"mobile-focused-pane","data-active":$,"aria-hidden":!$,children:_.jsx(eb,{terminal:H,serverApi:a,active:$,visible:c&&$,canClose:J>1,refreshCwdOnEnter:d&&$,tabId:p,onSelect:()=>x(j.terminalId),onClose:()=>C(j.terminalId),onExit:L=>B(j.terminalId,L),onSnapshot:R,...F?{onAuthClose:F}:{}})},j.key):_.jsx("div",{className:"mobile-focused-pane","data-active":$,"aria-hidden":!$,children:_.jsx("div",{className:"missing-pane",children:"Terminal unavailable"})},j.key)})})}if(e.type==="pane"){const ie=t[e.terminalId];if(!ie)return _.jsx("div",{className:"missing-pane",children:"Terminal unavailable"});const de=_.jsx(eb,{terminal:ie,serverApi:a,active:e.terminalId===o,visible:c,canClose:J>1,refreshCwdOnEnter:d&&e.terminalId===o,tabId:p,onSelect:()=>x(e.terminalId),onClose:()=>C(e.terminalId),onExit:$=>B(e.terminalId,$),onSnapshot:R,...F?{onAuthClose:F}:{}});return m&&f!==e.terminalId?_.jsxs("div",{className:"pane-drop-host",children:[de,_.jsx(Vc,{terminalId:e.terminalId,side:"top"}),_.jsx(Vc,{terminalId:e.terminalId,side:"right"}),_.jsx(Vc,{terminalId:e.terminalId,side:"bottom"}),_.jsx(Vc,{terminalId:e.terminalId,side:"left"})]}):de}if(e.type==="editor"){const ie=n[e.editorId];return ie?_.jsx(Xy,{api:a,editor:ie,canClose:J>1,onClose:()=>re(e.editorId)}):_.jsx("div",{className:"missing-pane",children:"Editor unavailable"})}const ce=`${e.ratio*100}%`,q=`${(1-e.ratio)*100}%`,I=e.direction==="vertical"?{gridTemplateColumns:`${ce} 1px ${q}`}:{gridTemplateRows:`${ce} 1px ${q}`};return _.jsxs("div",{className:"split-pane","data-direction":e.direction,style:I,children:[_.jsx("div",{className:"split-cell",children:_.jsx(Bp,{node:e.first,terminals:t,editors:n,api:a,activeTerminalId:o,visible:c,refreshCwdOnEnter:d,tabId:p,dropZoneActive:m,draggingTerminalId:f,mobileFocusLeafKey:S,path:[...y,0],totalPanes:J,onSelect:x,onClose:C,onResize:k,onExit:B,onSnapshot:R,onCloseEditor:re,...F?{onAuthClose:F}:{}})}),_.jsx(JR,{direction:e.direction,path:y,onResize:k}),_.jsx("div",{className:"split-cell",children:_.jsx(Bp,{node:e.second,terminals:t,editors:n,api:a,activeTerminalId:o,visible:c,refreshCwdOnEnter:d,tabId:p,dropZoneActive:m,draggingTerminalId:f,mobileFocusLeafKey:S,path:[...y,1],totalPanes:J,onSelect:x,onClose:C,onResize:k,onExit:B,onSnapshot:R,onCloseEditor:re,...F?{onAuthClose:F}:{}})})]})}function Vc({terminalId:e,side:t}){const{setNodeRef:n,isOver:a}=qb({id:`pane-${e}-${t}`,data:{kind:"pane-zone",terminalId:e,side:t}});return _.jsx("div",{ref:n,className:`pane-drop-zone pane-drop-zone--${t}`,"data-over":a,"aria-hidden":"true"})}function JR({direction:e,path:t,onResize:n}){function a(o){o.preventDefault(),o.stopPropagation();const c=o.currentTarget;c.setPointerCapture?.(o.pointerId),c.classList.add("is-dragging"),document.body.style.cursor=e==="vertical"?"col-resize":"row-resize";const d=c.parentElement;if(!d)return;const p=d.getBoundingClientRect();function m(S){const y=e==="vertical"?(S.clientX-p.left)/p.width:(S.clientY-p.top)/p.height;n(t,Math.min(.9,Math.max(.1,y)))}function f(){window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",f),c.classList.remove("is-dragging"),document.body.style.cursor=""}window.addEventListener("pointermove",m),window.addEventListener("pointerup",f)}return _.jsx("div",{"aria-label":"Resize panes","aria-orientation":e==="vertical"?"vertical":"horizontal",className:"split-divider","data-direction":e,onPointerDown:a,role:"separator",children:_.jsx("span",{className:"split-divider-handle","aria-hidden":"true"})})}function Lp(e){return e.type==="pane"||e.type==="editor"?1:Lp(e.first)+Lp(e.second)}function Op(e){return e.type==="pane"?[{key:eM(e.terminalId),type:"terminal",terminalId:e.terminalId}]:e.type==="editor"?[{key:tM(e.editorId),type:"editor",editorId:e.editorId}]:[...Op(e.first),...Op(e.second)]}function eM(e){return`terminal:${e}`}function tM(e){return`editor:${e}`}const Am="workspace-default",iM="NTerminal";function sM(){return{workspaces:[],activeWorkspaceId:null,terminals:{}}}function nM(e,t){switch(t.type){case"workspace.hydrated":return zp(t.terminals,t.savedTabs,t.savedWorkspaces,t.savedActiveWorkspaceId);case"workspace.created":return rM(e,{id:t.workspaceId,title:t.title});case"workspace.closed":return lM(e,t.workspaceId);case"workspace.selected":return vw(e,t.workspaceId);case"workspace.renamed":return aM(e,t.workspaceId,t.title);case"terminal.created":return gw(e,t.terminal);case"terminal.split":return oM(e,t.terminal,t.direction);case"terminal.updated":return SM(e,t.terminal);case"terminal.exited":return bM(e,t.terminalId,t.exitCode);case"terminal.closed":return Sw(e,t.terminalId);case"terminal.detached":return wM(e,t.terminalId);case"editor.split":return cM(e,t.editorId,t.title,t.direction);case"editor.closed":return CM(e,t.editorId);case"pane.selected":return _M(e,t.terminalId);case"pane.resized":return vM(e,t.path,t.ratio);case"tab.selected":return hM(e,t.tabId);case"tab.renamed":return mM(e,t.tabId,t.title);case"tab.reordered":return yw(e,t.sourceTabId,t.targetIndex);case"tab.dropped_into_pane":return dM(e,t.sourceTabId,t.sourceTerminalId,t.targetTerminalId,t.side);case"terminal.extracted_to_tab":return fM(e,t.sourceTabId,t.sourceTerminalId,t.targetIndex);case"activePane.closed":return uM(e);default:return e}}function rM(e,t){if(e.workspaces.some(a=>a.id===t.id))return vw(e,t.id);const n={id:t.id,title:t.title,tabs:[],activeTabId:null};return{...e,workspaces:[...e.workspaces,n],activeWorkspaceId:n.id}}function vw(e,t){return e.workspaces.some(n=>n.id===t)?{...e,activeWorkspaceId:t}:e}function aM(e,t,n){const a=n.trim();if(!a)return e;let o=!1;const c=e.workspaces.map(d=>d.id!==t||d.title===a?d:(o=!0,{...d,title:a}));return o?{...e,workspaces:c}:e}function lM(e,t){if(e.workspaces.length<=1||!e.workspaces.some(p=>p.id===t))return e;const n=e.workspaces.find(p=>p.id===t),a=new Set(n?yM(n):[]),o={...e.terminals};for(const p of a)delete o[p];const c=e.workspaces.filter(p=>p.id!==t),d=e.activeWorkspaceId===t?c[0]?.id??null:e.activeWorkspaceId;return{workspaces:c,activeWorkspaceId:d,terminals:o}}function gw(e,t){const n=ww(e),a=Kr(n)??ju(),o=Cw(t);return{...n,activeWorkspaceId:a.id,terminals:{...n.terminals,[t.id]:t},workspaces:n.workspaces.map(c=>c.id===a.id?{...c,tabs:[...c.tabs,o],activeTabId:o.id}:c)}}function oM(e,t,n){const a=Kr(e),o=a?zu(a):void 0;if(!a||!o)return gw(e,t);const c=o.activeTerminalId,d=fo(o.root,c,{type:"split",direction:n,ratio:.5,first:{type:"pane",terminalId:c},second:{type:"pane",terminalId:t.id}});return{...e,terminals:{...e.terminals,[t.id]:t},workspaces:e.workspaces.map(p=>p.id===a.id?{...p,tabs:p.tabs.map(m=>m.id===o.id?{...m,root:d,activeTerminalId:t.id}:m)}:p)}}function cM(e,t,n,a){const o=Kr(e),c=o?zu(o):void 0;if(!o||!c)return e;const d=c.activeTerminalId,p=fo(c.root,d,{type:"split",direction:a,ratio:.5,first:{type:"pane",terminalId:d},second:{type:"editor",editorId:t,title:n}});return{...e,workspaces:e.workspaces.map(m=>m.id===o.id?{...m,tabs:m.tabs.map(f=>f.id===c.id?{...f,root:p,activeTerminalId:d}:f)}:m)}}function uM(e){const t=Kr(e),n=t?zu(t):void 0;return n?Sw(e,n.activeTerminalId):e}function hM(e,t){const n=Kr(e);return!n||!n.tabs.some(a=>a.id===t)?e:{...e,workspaces:e.workspaces.map(a=>a.id===n.id?{...a,activeTabId:t}:a)}}function yw(e,t,n){const a=e.workspaces.map(o=>{const c=o.tabs.findIndex(S=>S.id===t);if(c<0)return o;const d=o.tabs.slice(),[p]=d.splice(c,1);if(!p)return o;const m=Math.max(0,Math.min(d.length,n)),f=d.slice();return f.splice(m,0,p),pM(o.tabs,f)?o:{...o,tabs:f}});return a.every((o,c)=>o===e.workspaces[c])?e:{...e,workspaces:a}}function dM(e,t,n,a,o){if(n===a||!e.terminals[n]||!e.terminals[a])return e;let c=e.workspaces.map(m=>{const f=m.tabs.findIndex(C=>C.id===t);if(f<0)return m;const S=m.tabs[f];if(!S)return m;const y=po(S.root,n);if(!y){const C=m.tabs.filter((k,B)=>B!==f);return{...m,tabs:C}}const b={...S,root:y,activeTerminalId:Es(y)[0]??S.activeTerminalId},x=m.tabs.slice();return x[f]=b,{...m,tabs:x}});const d=o==="left"||o==="right"?"vertical":"horizontal",p=o==="left"||o==="top";return c=c.map(m=>{const f=m.tabs.findIndex(k=>Es(k.root).includes(a));if(f<0)return m;const S=m.tabs[f];if(!S)return m;const y={type:"pane",terminalId:n},b={type:"split",direction:d,ratio:.5,first:p?y:{type:"pane",terminalId:a},second:p?{type:"pane",terminalId:a}:y},x=fo(S.root,a,b),C=m.tabs.slice();return C[f]={...S,root:x,activeTerminalId:n},{...m,tabs:C,activeTabId:S.id}}),ww({...e,workspaces:c})}function fM(e,t,n,a){let o=-1,c=-1;for(let B=0;B<e.workspaces.length;B+=1){const R=e.workspaces[B].tabs.findIndex(re=>re.id===t);if(R>=0){o=B,c=R;break}}if(o<0)return e;const d=e.workspaces[o],p=d.tabs[c],m=Es(p.root);if(!m.includes(n))return e;if(m.length===1)return yw(e,t,a);const f=po(p.root,n);if(!f)return e;const S={...p,root:f,activeTerminalId:Es(f)[0]??p.activeTerminalId},y=e.terminals[n],b={id:`tab-${Date.now().toString(36)}-${n.slice(0,8)}`,title:y?.title??"",activeTerminalId:n,root:{type:"pane",terminalId:n}},x=d.tabs.slice();x[c]=S;const C=Math.max(0,Math.min(x.length,a));x.splice(C,0,b);const k=e.workspaces.slice();return k[o]={...d,tabs:x,activeTabId:b.id},{...e,workspaces:k}}function pM(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.id!==t[n]?.id)return!1;return!0}function mM(e,t,n){const a=n.trim();if(!a)return e;let o=!1;const c=e.workspaces.map(d=>{let p=!1;const m=d.tabs.map(f=>f.id!==t||f.title===a?f:(o=!0,p=!0,{...f,title:a}));return p?{...d,tabs:m}:d});return o?{...e,workspaces:c}:e}function _M(e,t){const n=e.workspaces.find(o=>o.tabs.some(c=>mo(c.root,t))),a=n?.tabs.find(o=>mo(o.root,t));return!n||!a?e:{...e,activeWorkspaceId:n.id,workspaces:e.workspaces.map(o=>o.id===n.id?{...o,activeTabId:a.id,tabs:o.tabs.map(c=>c.id===a.id?{...c,activeTerminalId:t}:c)}:o)}}function vM(e,t,n){const a=Kr(e),o=a?zu(a):void 0;if(!a||!o)return e;const c=Kp(o.root,t,xw(n));return c===o.root?e:{...e,workspaces:e.workspaces.map(d=>d.id===a.id?{...d,tabs:d.tabs.map(p=>p.id===o.id?{...p,root:c}:p)}:d)}}function zp(e,t,n,a){const o=Object.fromEntries(e.map(S=>[S.id,S])),c=new Set(e.map(S=>S.id)),d=new Set;let p=xM(t,n,c,d);p.length===0&&(p=[ju()]);const m=typeof a=="string"&&p.some(S=>S.id===a)?a:p[0]?.id??null,f=m??p[0]?.id??Am;for(const S of e){if(d.has(S.id))continue;const y=Cw(S);p=EM(p,f,y),d.add(S.id)}return{workspaces:p.map(Do),activeWorkspaceId:m,terminals:o}}function Nm(e){return Es(e.root)}function gM(e){return Ip(e.root)}function yM(e){return e.tabs.flatMap(t=>Es(t.root))}function Cf(e){const t=e.workspaces.map(n=>{const a=n.tabs.flatMap(o=>{const c=Up(o.root);return c?[{...o,root:c}]:[]});return Do({...n,tabs:a})});return{activeWorkspaceId:t.some(n=>n.id===e.activeWorkspaceId)?e.activeWorkspaceId:t[0]?.id??null,workspaces:t}}function SM(e,t){return{...e,terminals:{...e.terminals,[t.id]:t},workspaces:e.workspaces.map(n=>({...n,tabs:n.tabs.map(a=>mo(a.root,t.id)?{...a,title:a.title||t.title}:a)}))}}function bM(e,t,n){const a=e.terminals[t];return a?{...e,terminals:{...e.terminals,[t]:{...a,status:"exited",exitCode:n}}}:e}function Sw(e,t){const n={...e.terminals};return delete n[t],bw(e,t,n)}function wM(e,t){return e.terminals[t]?bw(e,t,{...e.terminals}):e}function bw(e,t,n){const a=e.workspaces.map(c=>{const d=[];for(const p of c.tabs){const m=po(p.root,t);if(!m)continue;const f=Es(m),S=f.includes(p.activeTerminalId)?p.activeTerminalId:f[0];S&&d.push({...p,root:m,activeTerminalId:S})}return Do({...c,tabs:d})}),o=a.some(c=>c.id===e.activeWorkspaceId);return{workspaces:a,activeWorkspaceId:o?e.activeWorkspaceId:a[0]?.id??null,terminals:n}}function CM(e,t){const n=e.workspaces.map(o=>{const c=[];for(const d of o.tabs){const p=jp(d.root,t);if(!p)continue;const m=Es(p),f=m.includes(d.activeTerminalId)?d.activeTerminalId:m[0];f&&c.push({...d,root:p,activeTerminalId:f})}return Do({...o,tabs:c})}),a=n.some(o=>o.id===e.activeWorkspaceId);return{...e,workspaces:n,activeWorkspaceId:a?e.activeWorkspaceId:n[0]?.id??null}}function xM(e,t,n,a){if(t&&t.length>0){const o=[];for(const c of t)TM(c)&&o.push(nb(c,n,a));if(o.length>0)return o}return[nb({...ju(),tabs:e??[]},n,a)]}function nb(e,t,n){const a=[];for(const o of e.tabs){if(!kM(o))continue;const c=Hp(o.root,t);if(!c)continue;const d=Es(c);for(const m of d)n.add(m);const p=d.includes(o.activeTerminalId)?o.activeTerminalId:d[0];p&&a.push({...o,root:c,activeTerminalId:p})}return Do({...e,tabs:a})}function ww(e){return Kr(e)?e:{...e,workspaces:[ju()],activeWorkspaceId:Am}}function Kr(e){return e.workspaces.find(t=>t.id===e.activeWorkspaceId)??e.workspaces[0]}function zu(e){return e.tabs.find(t=>t.id===e.activeTabId)??e.tabs[0]}function ju(){return{id:Am,title:iM,tabs:[],activeTabId:null}}function Do(e){const t=e.tabs.some(n=>n.id===e.activeTabId);return{...e,activeTabId:t?e.activeTabId:e.tabs[0]?.id??null}}function EM(e,t,n){return e.map(a=>a.id===t?{...a,tabs:[...a.tabs,n],activeTabId:a.activeTabId??n.id}:a)}function Cw(e){return{id:`tab-${e.id}`,title:e.title||e.id,root:{type:"pane",terminalId:e.id},activeTerminalId:e.id}}function fo(e,t,n){return e.type==="pane"?e.terminalId===t?n:e:e.type==="editor"?e:{...e,first:fo(e.first,t,n),second:fo(e.second,t,n)}}function po(e,t){if(e.type==="pane")return e.terminalId===t?null:e;if(e.type==="editor")return e;const n=po(e.first,t),a=po(e.second,t);return n&&a?{...e,first:n,second:a}:n??a}function jp(e,t){if(e.type==="editor")return e.editorId===t?null:e;if(e.type==="pane")return e;const n=jp(e.first,t),a=jp(e.second,t);return n&&a?{...e,first:n,second:a}:n??a}function Hp(e,t){if(e.type==="pane")return t.has(e.terminalId)?e:null;if(e.type==="editor")return null;const n=Hp(e.first,t),a=Hp(e.second,t);return n&&a?{...e,ratio:xw(e.ratio),first:n,second:a}:n??a}function Up(e){if(e.type==="editor")return null;if(e.type==="pane")return e;const t=Up(e.first),n=Up(e.second);return t&&n?{...e,first:t,second:n}:t??n}function TM(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&typeof t.title=="string"&&(typeof t.activeTabId=="string"||t.activeTabId===null)&&Array.isArray(t.tabs)}function kM(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&typeof t.title=="string"&&typeof t.activeTerminalId=="string"&&Pp(t.root)}function Pp(e){if(!e||typeof e!="object")return!1;const t=e;return t.type==="pane"?typeof t.terminalId=="string":t.type==="editor"?typeof t.editorId=="string"&&typeof t.title=="string":t.type==="split"?(t.direction==="horizontal"||t.direction==="vertical")&&Pp(t.first)&&Pp(t.second):!1}function Kp(e,t,n){if(e.type==="pane"||e.type==="editor")return e;if(t.length===0)return e.ratio===n?e:{...e,ratio:n};const[a,...o]=t;if(a===0){const c=Kp(e.first,o,n);return c===e.first?e:{...e,first:c}}if(a===1){const c=Kp(e.second,o,n);return c===e.second?e:{...e,second:c}}return e}function xw(e){return Number.isFinite(e)?Math.min(.9,Math.max(.1,e)):.5}function mo(e,t){return e.type==="pane"?e.terminalId===t:e.type==="editor"?!1:mo(e.first,t)||mo(e.second,t)}function Es(e){return e.type==="pane"?[e.terminalId]:e.type==="editor"?[]:[...Es(e.first),...Es(e.second)]}function Ip(e){return e.type==="pane"||e.type==="editor"?1:Ip(e.first)+Ip(e.second)}const ur=new Map,_o=new Map,vo=new Map;function Pa(e){return e??"__local__"}function DM(e){return{agentId:e,state:sM(),editors:{},loaded:!1,error:null,layoutRevision:null,lastPersistedLayoutJson:null,unreadCompletions:new Set,mutable:{editorIdCounter:0,saveCoord:{pendingLayoutSave:null,saveTimer:null,persistChain:Promise.resolve(),nextPersistQueued:!1,nextPersistLayout:null,queuedBaseRevision:void 0}}}}function Ft(e){const t=Pa(e);let n=ur.get(t);return n||(n=DM(e),ur.set(t,n)),n}function Ew(e,t){const n=Pa(e);let a=_o.get(n);return a||(a=new Set,_o.set(n,a)),a.add(t),()=>{a.delete(t)}}function RM(e){const t=Pa(e),n=_o.get(t);if(n)for(const a of Array.from(n))a()}function Ka(e,t){ur.set(Pa(e),t),RM(e)}const Fp=new Set;function MM(e){return Fp.add(e),()=>{Fp.delete(e)}}function Ul(e,t){const n=Ft(e),a=Pa(e);t.type==="workspace.hydrated"&&vo.delete(a);const o=nM(n.state,t);let c=n.unreadCompletions,d=null;if(t.type==="terminal.updated"){const f=n.state.terminals[t.terminal.id],S=f?.activity==="busy",y=t.terminal.activity==="busy",b=t.terminal.activity==="idle",x=jM(a);if(t.notifyCompletion===!0&&y&&x.add(t.terminal.id),t.notifyCompletion===!0&&S&&b&&x.has(t.terminal.id)){const C=AM(o,t.terminal.id);C&&(d={terminalId:t.terminal.id,tabId:C.tab.id,commandName:f?.currentCommand??null},C.workspace.activeTabId!==C.tab.id&&(c.has(C.tab.id)||(c=new Set(c),c.add(C.tab.id))))}(b||t.terminal.status==="exited")&&x.delete(t.terminal.id)}t.type==="tab.selected"&&c.has(t.tabId)&&(c=new Set(c),c.delete(t.tabId));const p=o!==n.state,m=c!==n.unreadCompletions;if((p||m)&&Ka(e,{...n,state:o,unreadCompletions:c}),m&&Bm(),d)for(const f of Array.from(Fp))f({agentId:e,...d})}function AM(e,t){for(const n of e.workspaces)for(const a of n.tabs)if(Es(a.root).includes(t))return{workspace:n,tab:a};return null}const qp=new Set;function NM(e){return qp.add(e),()=>{qp.delete(e)}}function BM(){let e=0;for(const t of ur.values())e+=t.unreadCompletions.size;return e}function Bm(){for(const e of Array.from(qp))e()}function LM(e,t){const n=Ft(e);if(!n.unreadCompletions.has(t))return;const a=new Set(n.unreadCompletions);a.delete(t),Ka(e,{...n,unreadCompletions:a}),Bm()}function rb(e,t){const n=Ft(e);t!==n.state&&Ka(e,{...n,state:t})}function ab(e,t){const n=Ft(e),a=t(n.editors);a!==n.editors&&Ka(e,{...n,editors:a})}function Ta(e,t,n){const a=Ft(e);a.loaded===t&&a.error===n||Ka(e,{...a,loaded:t,error:n})}function Xc(e,t,n){const a=Ft(e);a.layoutRevision===t&&a.lastPersistedLayoutJson===n||Ka(e,{...a,layoutRevision:t,lastPersistedLayoutJson:n})}function OM(e){const t=Ft(e);return t.mutable.editorIdCounter+=1,t.mutable.editorIdCounter}function zM(e){const t=Pa(e),n=ur.get(t);n&&n.mutable.saveCoord.saveTimer!==null&&window.clearTimeout(n.mutable.saveCoord.saveTimer);const a=n?n.unreadCompletions.size>0:!1;ur.delete(t),_o.delete(t),vo.delete(t),a&&Bm()}function lb(){for(const e of ur.values()){const t=e.mutable.saveCoord.saveTimer;t!==null&&window.clearTimeout(t),e.unreadCompletions.size>0}ur.clear(),_o.clear(),vo.clear()}function jM(e){let t=vo.get(e);return t||(t=new Set,vo.set(e,t)),t}function HM(e,t){let n=!1,a=!1,o=null,c=!1;for(const d of Nm(e)){const p=t[d];if(p){if(p.status==="exited"){c=!0,n=!0;continue}p.activity==="busy"?(a=!0,n=!0,!o&&p.currentCommand&&(o=p.currentCommand)):p.activity==="idle"&&(n=!0)}}return n?c?{state:"exited",commandName:null}:a?{state:"busy",commandName:o}:{state:"idle",commandName:null}:null}function UM(e){return e?e.state==="busy"?e.commandName?`running: ${e.commandName}`:"running":e.state==="exited"?"exited":"idle":""}function PM({tabs:e,activeTabId:t,terminals:n,unreadCompletionTabIds:a,detachedTerminals:o,onSelectTab:c,onCreateTab:d,onToggleWorkspaces:p,onCloseTerminals:m,onReattachTerminal:f,onDeleteTerminal:S,onSplitVertical:y,onSplitHorizontal:b,onRenameTab:x,activePaneAvailable:C}){const[k,B]=g.useState(null),[R,re]=g.useState(null),F=g.useRef(null);g.useEffect(()=>{F.current?.focus(),F.current?.select()},[k?.tabId]);function J(I,ie){B({tabId:I,title:ie})}function ce(){if(!k)return;const I=k.title.trim();I&&x(k.tabId,I),B(null)}function q(){return _.jsxs("div",{className:"terminal-pane-actions","aria-label":"Pane actions",children:[_.jsx("button",{type:"button",className:"pane-action-button","aria-label":"Split right",title:`Split right - ${YE()}`,onClick:y,disabled:!C,children:_.jsx("span",{className:"split-icon split-icon-right","aria-hidden":"true"})}),_.jsx("button",{type:"button",className:"pane-action-button","aria-label":"Split down",title:`Split down - ${$E()}`,onClick:b,disabled:!C,children:_.jsx("span",{className:"split-icon split-icon-down","aria-hidden":"true"})})]})}return _.jsxs(_.Fragment,{children:[_.jsxs("nav",{className:"terminal-tabs","aria-label":"Terminal tabs",children:[_.jsx("button",{type:"button",className:"mobile-menu-button","aria-label":"Toggle workspaces",title:"Workspaces",onClick:p,children:_.jsxs("span",{className:"hamburger-lines","aria-hidden":"true",children:[_.jsx("span",{}),_.jsx("span",{}),_.jsx("span",{})]})}),_.jsxs("div",{className:"terminal-tab-list",children:[e.map((I,ie)=>{const de=Nm(I),j=gM(I),$=n[I.activeTerminalId],H=I.title||$?.title||I.activeTerminalId,L=I.id===t,X=k?.tabId===I.id,G=HM(I,n),M=a?.has(I.id)??!1;return _.jsxs(xi.Fragment,{children:[_.jsx(ob,{index:ie}),_.jsx(KM,{tab:I,active:L,editing:X,title:H,paneCount:j,terminalIds:de,canClose:e.length>1,editValue:X?k.title:null,editInputRef:X?F:null,activity:G,unread:M,onSelect:()=>c(I.id),onBeginRename:()=>J(I.id,H),onCloseAll:()=>m(de),onCommitRename:ce,onCancelRename:()=>B(null),onRenameChange:V=>B({tabId:I.id,title:V})})]},I.id)}),_.jsx(ob,{index:e.length}),_.jsx("button",{type:"button",className:"tab-add-button","aria-label":"New tab",title:"New tab",onClick:d,children:"+"}),(o?.length??0)>0?_.jsx("div",{className:"terminal-detached-pills","aria-label":"Detached terminals",children:(o??[]).map(I=>_.jsx(IM,{terminal:I,onReattach:()=>f?.(I.id),onDelete:()=>re(I)},I.id))}):null]}),C?q():null]}),R?_.jsx(FM,{terminal:R,onCancel:()=>re(null),onConfirm:()=>{S?.(R.id),re(null)}}):null]})}function KM({tab:e,active:t,editing:n,title:a,paneCount:o,canClose:c,editValue:d,editInputRef:p,activity:m,unread:f,onSelect:S,onBeginRename:y,onCloseAll:b,onCommitRename:x,onCancelRename:C,onRenameChange:k}){const{attributes:B,listeners:R,setNodeRef:re,transform:F,isDragging:J}=Fb({id:`tab-${e.id}`,data:{kind:"tab",tabId:e.id,terminalId:e.activeTerminalId},disabled:n}),ce={transform:Tf.Translate.toString(F),opacity:J?.4:void 0,zIndex:J?2:void 0};return _.jsxs("div",{ref:re,className:"terminal-tab","data-active":t,"data-dragging":J,"data-unread":f?"true":void 0,style:ce,...B,...R,children:[m?_.jsx("span",{className:"terminal-tab-status-dot","data-activity":m.state,"aria-hidden":"true",title:UM(m)}):null,n&&p&&d!==null?_.jsxs("form",{className:"terminal-tab-editor",onSubmit:q=>{q.preventDefault(),x()},children:[_.jsx("input",{ref:p,"aria-label":`Rename ${a}`,value:d,onBlur:x,onChange:q=>k(q.target.value),onKeyDown:q=>{if(q.key==="Enter"){q.preventDefault(),x();return}q.key==="Escape"&&(q.preventDefault(),C())}}),_.jsx("small",{children:o})]}):_.jsxs("button",{type:"button",className:"terminal-tab-select","aria-label":`Select ${a}`,title:a,onClick:S,onDoubleClick:q=>{q.preventDefault(),y()},children:[_.jsx("span",{children:a}),_.jsxs("small",{children:[o," pane",o===1?"":"s"]})]}),c&&!n?_.jsx("button",{type:"button",className:"icon-button","aria-label":`Close ${a}`,title:`Close ${a}`,onPointerDown:q=>q.stopPropagation(),onClick:q=>{q.stopPropagation(),b()},children:"x"}):null]})}function ob({index:e}){const{setNodeRef:t,isOver:n}=qb({id:`tab-position-${e}`,data:{kind:"tab-position",index:e}});return _.jsx("div",{ref:t,className:"terminal-tab-drop-slot","data-over":n,"aria-hidden":"true"})}function IM({terminal:e,onReattach:t,onDelete:n}){const a=e.title||e.cwd||e.id.slice(0,8),o=`${e.title||"Terminal"}
41
+ ${m}`:d.header;return{id:`${p}:${qR(f)}`,kind:IR(d.header,m,t),header:d.header,body:m,text:f,searchText:f.toLowerCase()}})}function KR(e,t){const n=mw(e);return n?n==="User"||n===Oa(t)||n==="System"||n==="Tool output"||n.startsWith("Tool call:"):!1}function mw(e){return(e.match(/^\[[^\]\n]+\]\s+(.+)$/)?.[1]??e).trim()||null}function IR(e,t,n){const a=mw(e);return a==="User"?"user":a===Oa(n)?t.startsWith("[tool call:")||t.startsWith("[tool output]")?"tool":"assistant":a==="System"?"system":a==="Tool output"||a?.startsWith("Tool call:")?"tool":"other"}function FR(e){return e.split(`
42
+ `).length}function qR(e){let t=5381;for(let n=0;n<e.length;n+=1)t=t*33^e.charCodeAt(n);return(t>>>0).toString(36)}function WR(e){let t=0;for(const n of e){if(!n)continue;const a=n.match(/\r\n|\r|\n/g);t+=a?.length??1}return Math.max(1,t)}function ib(e){const t=[];for(const n of e){const a=_w(n);a&&t.push(a)}return t}function _w(e){return e.replace(/\x1b\[\?([0-9;:]*)([hl])/g,(t,n,a)=>{const o=n.split(";").filter(Boolean).filter(c=>!RR.has(c.split(":")[0]??""));return o.length>0?`\x1B[?${o.join(";")}${a}`:""})}function bf(e,t={}){const n={};return(e?.force||t.force)&&(n.force=!0),(e?.scrollToBottom||t.scrollToBottom)&&(n.scrollToBottom=!0),n}function YR(e){const t=e.buffer.active,n=t.baseY+e.rows;return n<=e.rows?null:{current:Math.max(1,Math.min(n,t.viewportY+1)),total:n}}function ir(e){return e.buffer.active.viewportY>=Math.max(0,e.buffer.active.baseY-1)}function $c(e,t){return!t||ir(e)}function sb(e){return ir(e)?!1:(e.scrollToLine(Math.max(0,e.buffer.active.baseY)),!0)}function $R(e,t,n,a,o,c){const d=p=>{const m=XR(p);m!==0&&(p.cancelable&&p.preventDefault(),p.stopPropagation(),VR(t,m,n,a,o,c))};return e.addEventListener("wheel",d,{capture:!0,passive:!1}),()=>{e.removeEventListener("wheel",d,{capture:!0})}}function VR(e,t,n,a,o,c){const d=()=>{o();try{e.scrollLines(t)}finally{c()}n(),t<0&&e.buffer.active.viewportY<=3&&a(t)};if(e.buffer.active.type==="alternate"){e.write(Np,d);return}d()}function XR(e){const n=e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?e.deltaY/24:e.deltaMode===WheelEvent.DOM_DELTA_PAGE?e.deltaY*24:e.deltaY;if(n===0)return 0;const a=n<0?Math.floor(n):Math.ceil(n);return Math.max(-30,Math.min(30,a))}function GR(e,t,n,a,o,c,d){let p=null,m=0;const f={passive:!1};function S(x){p=wf(x),m=0}function y(x){const C=wf(x);if(C===null){p=null,m=0;return}if(p===null){p=C;return}const k=C.clientY-p.clientY;if(p=C,x.cancelable&&x.preventDefault(),k===0)return;if(ZR(t)&&QR(t,C,-k)){m=0;return}m-=k/n();const B=m<0?Math.ceil(m):Math.floor(m);if(B!==0){m-=B,c();try{t.scrollLines(B)}finally{d()}a(),B<0&&t.buffer.active.viewportY<=3&&o(B)}}function b(x){if(x.touches.length>0){p=wf(x);return}p=null,m=0}return e.addEventListener("touchstart",S,f),e.addEventListener("touchmove",y,f),e.addEventListener("touchend",b),e.addEventListener("touchcancel",b),()=>{e.removeEventListener("touchstart",S,f),e.removeEventListener("touchmove",y,f),e.removeEventListener("touchend",b),e.removeEventListener("touchcancel",b)}}function wf(e){if(e.touches.length!==1)return null;const t=e.touches[0];return t?{clientX:t.clientX,clientY:t.clientY}:null}function ZR(e){return e.buffer.active.type==="alternate"||e.modes.mouseTrackingMode!=="none"}function QR(e,t,n){const a=e.element;return a?(a.dispatchEvent(JR(t,n)),!0):!1}function JR(e,t){const n=typeof WheelEvent=="function"?WheelEvent.DOM_DELTA_PIXEL:0,a={bubbles:!0,cancelable:!0,clientX:e.clientX,clientY:e.clientY,deltaX:0,deltaY:t,deltaMode:n};if(typeof WheelEvent=="function")return new WheelEvent("wheel",a);const o=new Event("wheel",a);return Object.defineProperties(o,{clientX:{value:e.clientX},clientY:{value:e.clientY},deltaX:{value:0},deltaY:{value:t},deltaMode:{value:0}}),o}function Bp({node:e,terminals:t,editors:n,api:a,activeTerminalId:o,visible:c=!0,refreshCwdOnEnter:d=!1,tabId:p,dropZoneActive:m=!1,draggingTerminalId:f=null,mobileFocusLeafKey:S=null,path:y=[],totalPanes:b,onSelect:x,onClose:C,onResize:k,onExit:B,onSnapshot:R,onCloseEditor:re,onAuthClose:F}){const J=b??Lp(e);if(y.length===0&&S){const ie=Op(e),de=ie.some(j=>j.key===S)?S:ie[0]?.key;if(ie.length>1&&de)return _.jsx("div",{className:"mobile-focused-split",children:ie.map(j=>{const $=j.key===de;if(j.type==="editor"){const L=n[j.editorId];return _.jsx("div",{className:"mobile-focused-pane","data-active":$,"aria-hidden":!$,children:L?_.jsx(Xy,{api:a,editor:L,canClose:J>1,onClose:()=>re(j.editorId)}):_.jsx("div",{className:"missing-pane",children:"Editor unavailable"})},j.key)}const H=t[j.terminalId];return H?_.jsx("div",{className:"mobile-focused-pane","data-active":$,"aria-hidden":!$,children:_.jsx(eb,{terminal:H,serverApi:a,active:$,visible:c&&$,canClose:J>1,refreshCwdOnEnter:d&&$,tabId:p,onSelect:()=>x(j.terminalId),onClose:()=>C(j.terminalId),onExit:L=>B(j.terminalId,L),onSnapshot:R,...F?{onAuthClose:F}:{}})},j.key):_.jsx("div",{className:"mobile-focused-pane","data-active":$,"aria-hidden":!$,children:_.jsx("div",{className:"missing-pane",children:"Terminal unavailable"})},j.key)})})}if(e.type==="pane"){const ie=t[e.terminalId];if(!ie)return _.jsx("div",{className:"missing-pane",children:"Terminal unavailable"});const de=_.jsx(eb,{terminal:ie,serverApi:a,active:e.terminalId===o,visible:c,canClose:J>1,refreshCwdOnEnter:d&&e.terminalId===o,tabId:p,onSelect:()=>x(e.terminalId),onClose:()=>C(e.terminalId),onExit:$=>B(e.terminalId,$),onSnapshot:R,...F?{onAuthClose:F}:{}});return m&&f!==e.terminalId?_.jsxs("div",{className:"pane-drop-host",children:[de,_.jsx(Vc,{terminalId:e.terminalId,side:"top"}),_.jsx(Vc,{terminalId:e.terminalId,side:"right"}),_.jsx(Vc,{terminalId:e.terminalId,side:"bottom"}),_.jsx(Vc,{terminalId:e.terminalId,side:"left"})]}):de}if(e.type==="editor"){const ie=n[e.editorId];return ie?_.jsx(Xy,{api:a,editor:ie,canClose:J>1,onClose:()=>re(e.editorId)}):_.jsx("div",{className:"missing-pane",children:"Editor unavailable"})}const ce=`${e.ratio*100}%`,q=`${(1-e.ratio)*100}%`,I=e.direction==="vertical"?{gridTemplateColumns:`${ce} 1px ${q}`}:{gridTemplateRows:`${ce} 1px ${q}`};return _.jsxs("div",{className:"split-pane","data-direction":e.direction,style:I,children:[_.jsx("div",{className:"split-cell",children:_.jsx(Bp,{node:e.first,terminals:t,editors:n,api:a,activeTerminalId:o,visible:c,refreshCwdOnEnter:d,tabId:p,dropZoneActive:m,draggingTerminalId:f,mobileFocusLeafKey:S,path:[...y,0],totalPanes:J,onSelect:x,onClose:C,onResize:k,onExit:B,onSnapshot:R,onCloseEditor:re,...F?{onAuthClose:F}:{}})}),_.jsx(eM,{direction:e.direction,path:y,onResize:k}),_.jsx("div",{className:"split-cell",children:_.jsx(Bp,{node:e.second,terminals:t,editors:n,api:a,activeTerminalId:o,visible:c,refreshCwdOnEnter:d,tabId:p,dropZoneActive:m,draggingTerminalId:f,mobileFocusLeafKey:S,path:[...y,1],totalPanes:J,onSelect:x,onClose:C,onResize:k,onExit:B,onSnapshot:R,onCloseEditor:re,...F?{onAuthClose:F}:{}})})]})}function Vc({terminalId:e,side:t}){const{setNodeRef:n,isOver:a}=qb({id:`pane-${e}-${t}`,data:{kind:"pane-zone",terminalId:e,side:t}});return _.jsx("div",{ref:n,className:`pane-drop-zone pane-drop-zone--${t}`,"data-over":a,"aria-hidden":"true"})}function eM({direction:e,path:t,onResize:n}){function a(o){o.preventDefault(),o.stopPropagation();const c=o.currentTarget;c.setPointerCapture?.(o.pointerId),c.classList.add("is-dragging"),document.body.style.cursor=e==="vertical"?"col-resize":"row-resize";const d=c.parentElement;if(!d)return;const p=d.getBoundingClientRect();function m(S){const y=e==="vertical"?(S.clientX-p.left)/p.width:(S.clientY-p.top)/p.height;n(t,Math.min(.9,Math.max(.1,y)))}function f(){window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",f),c.classList.remove("is-dragging"),document.body.style.cursor=""}window.addEventListener("pointermove",m),window.addEventListener("pointerup",f)}return _.jsx("div",{"aria-label":"Resize panes","aria-orientation":e==="vertical"?"vertical":"horizontal",className:"split-divider","data-direction":e,onPointerDown:a,role:"separator",children:_.jsx("span",{className:"split-divider-handle","aria-hidden":"true"})})}function Lp(e){return e.type==="pane"||e.type==="editor"?1:Lp(e.first)+Lp(e.second)}function Op(e){return e.type==="pane"?[{key:tM(e.terminalId),type:"terminal",terminalId:e.terminalId}]:e.type==="editor"?[{key:iM(e.editorId),type:"editor",editorId:e.editorId}]:[...Op(e.first),...Op(e.second)]}function tM(e){return`terminal:${e}`}function iM(e){return`editor:${e}`}const Am="workspace-default",sM="NTerminal";function nM(){return{workspaces:[],activeWorkspaceId:null,terminals:{}}}function rM(e,t){switch(t.type){case"workspace.hydrated":return zp(t.terminals,t.savedTabs,t.savedWorkspaces,t.savedActiveWorkspaceId);case"workspace.created":return aM(e,{id:t.workspaceId,title:t.title});case"workspace.closed":return oM(e,t.workspaceId);case"workspace.selected":return vw(e,t.workspaceId);case"workspace.renamed":return lM(e,t.workspaceId,t.title);case"terminal.created":return gw(e,t.terminal);case"terminal.split":return cM(e,t.terminal,t.direction);case"terminal.updated":return bM(e,t.terminal);case"terminal.exited":return wM(e,t.terminalId,t.exitCode);case"terminal.closed":return Sw(e,t.terminalId);case"terminal.detached":return CM(e,t.terminalId);case"editor.split":return uM(e,t.editorId,t.title,t.direction);case"editor.closed":return xM(e,t.editorId);case"pane.selected":return vM(e,t.terminalId);case"pane.resized":return gM(e,t.path,t.ratio);case"tab.selected":return dM(e,t.tabId);case"tab.renamed":return _M(e,t.tabId,t.title);case"tab.reordered":return yw(e,t.sourceTabId,t.targetIndex);case"tab.dropped_into_pane":return fM(e,t.sourceTabId,t.sourceTerminalId,t.targetTerminalId,t.side);case"terminal.extracted_to_tab":return pM(e,t.sourceTabId,t.sourceTerminalId,t.targetIndex);case"activePane.closed":return hM(e);default:return e}}function aM(e,t){if(e.workspaces.some(a=>a.id===t.id))return vw(e,t.id);const n={id:t.id,title:t.title,tabs:[],activeTabId:null};return{...e,workspaces:[...e.workspaces,n],activeWorkspaceId:n.id}}function vw(e,t){return e.workspaces.some(n=>n.id===t)?{...e,activeWorkspaceId:t}:e}function lM(e,t,n){const a=n.trim();if(!a)return e;let o=!1;const c=e.workspaces.map(d=>d.id!==t||d.title===a?d:(o=!0,{...d,title:a}));return o?{...e,workspaces:c}:e}function oM(e,t){if(e.workspaces.length<=1||!e.workspaces.some(p=>p.id===t))return e;const n=e.workspaces.find(p=>p.id===t),a=new Set(n?SM(n):[]),o={...e.terminals};for(const p of a)delete o[p];const c=e.workspaces.filter(p=>p.id!==t),d=e.activeWorkspaceId===t?c[0]?.id??null:e.activeWorkspaceId;return{workspaces:c,activeWorkspaceId:d,terminals:o}}function gw(e,t){const n=ww(e),a=Kr(n)??ju(),o=Cw(t);return{...n,activeWorkspaceId:a.id,terminals:{...n.terminals,[t.id]:t},workspaces:n.workspaces.map(c=>c.id===a.id?{...c,tabs:[...c.tabs,o],activeTabId:o.id}:c)}}function cM(e,t,n){const a=Kr(e),o=a?zu(a):void 0;if(!a||!o)return gw(e,t);const c=o.activeTerminalId,d=fo(o.root,c,{type:"split",direction:n,ratio:.5,first:{type:"pane",terminalId:c},second:{type:"pane",terminalId:t.id}});return{...e,terminals:{...e.terminals,[t.id]:t},workspaces:e.workspaces.map(p=>p.id===a.id?{...p,tabs:p.tabs.map(m=>m.id===o.id?{...m,root:d,activeTerminalId:t.id}:m)}:p)}}function uM(e,t,n,a){const o=Kr(e),c=o?zu(o):void 0;if(!o||!c)return e;const d=c.activeTerminalId,p=fo(c.root,d,{type:"split",direction:a,ratio:.5,first:{type:"pane",terminalId:d},second:{type:"editor",editorId:t,title:n}});return{...e,workspaces:e.workspaces.map(m=>m.id===o.id?{...m,tabs:m.tabs.map(f=>f.id===c.id?{...f,root:p,activeTerminalId:d}:f)}:m)}}function hM(e){const t=Kr(e),n=t?zu(t):void 0;return n?Sw(e,n.activeTerminalId):e}function dM(e,t){const n=Kr(e);return!n||!n.tabs.some(a=>a.id===t)?e:{...e,workspaces:e.workspaces.map(a=>a.id===n.id?{...a,activeTabId:t}:a)}}function yw(e,t,n){const a=e.workspaces.map(o=>{const c=o.tabs.findIndex(S=>S.id===t);if(c<0)return o;const d=o.tabs.slice(),[p]=d.splice(c,1);if(!p)return o;const m=Math.max(0,Math.min(d.length,n)),f=d.slice();return f.splice(m,0,p),mM(o.tabs,f)?o:{...o,tabs:f}});return a.every((o,c)=>o===e.workspaces[c])?e:{...e,workspaces:a}}function fM(e,t,n,a,o){if(n===a||!e.terminals[n]||!e.terminals[a])return e;let c=e.workspaces.map(m=>{const f=m.tabs.findIndex(C=>C.id===t);if(f<0)return m;const S=m.tabs[f];if(!S)return m;const y=po(S.root,n);if(!y){const C=m.tabs.filter((k,B)=>B!==f);return{...m,tabs:C}}const b={...S,root:y,activeTerminalId:Es(y)[0]??S.activeTerminalId},x=m.tabs.slice();return x[f]=b,{...m,tabs:x}});const d=o==="left"||o==="right"?"vertical":"horizontal",p=o==="left"||o==="top";return c=c.map(m=>{const f=m.tabs.findIndex(k=>Es(k.root).includes(a));if(f<0)return m;const S=m.tabs[f];if(!S)return m;const y={type:"pane",terminalId:n},b={type:"split",direction:d,ratio:.5,first:p?y:{type:"pane",terminalId:a},second:p?{type:"pane",terminalId:a}:y},x=fo(S.root,a,b),C=m.tabs.slice();return C[f]={...S,root:x,activeTerminalId:n},{...m,tabs:C,activeTabId:S.id}}),ww({...e,workspaces:c})}function pM(e,t,n,a){let o=-1,c=-1;for(let B=0;B<e.workspaces.length;B+=1){const R=e.workspaces[B].tabs.findIndex(re=>re.id===t);if(R>=0){o=B,c=R;break}}if(o<0)return e;const d=e.workspaces[o],p=d.tabs[c],m=Es(p.root);if(!m.includes(n))return e;if(m.length===1)return yw(e,t,a);const f=po(p.root,n);if(!f)return e;const S={...p,root:f,activeTerminalId:Es(f)[0]??p.activeTerminalId},y=e.terminals[n],b={id:`tab-${Date.now().toString(36)}-${n.slice(0,8)}`,title:y?.title??"",activeTerminalId:n,root:{type:"pane",terminalId:n}},x=d.tabs.slice();x[c]=S;const C=Math.max(0,Math.min(x.length,a));x.splice(C,0,b);const k=e.workspaces.slice();return k[o]={...d,tabs:x,activeTabId:b.id},{...e,workspaces:k}}function mM(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.id!==t[n]?.id)return!1;return!0}function _M(e,t,n){const a=n.trim();if(!a)return e;let o=!1;const c=e.workspaces.map(d=>{let p=!1;const m=d.tabs.map(f=>f.id!==t||f.title===a?f:(o=!0,p=!0,{...f,title:a}));return p?{...d,tabs:m}:d});return o?{...e,workspaces:c}:e}function vM(e,t){const n=e.workspaces.find(o=>o.tabs.some(c=>mo(c.root,t))),a=n?.tabs.find(o=>mo(o.root,t));return!n||!a?e:{...e,activeWorkspaceId:n.id,workspaces:e.workspaces.map(o=>o.id===n.id?{...o,activeTabId:a.id,tabs:o.tabs.map(c=>c.id===a.id?{...c,activeTerminalId:t}:c)}:o)}}function gM(e,t,n){const a=Kr(e),o=a?zu(a):void 0;if(!a||!o)return e;const c=Kp(o.root,t,xw(n));return c===o.root?e:{...e,workspaces:e.workspaces.map(d=>d.id===a.id?{...d,tabs:d.tabs.map(p=>p.id===o.id?{...p,root:c}:p)}:d)}}function zp(e,t,n,a){const o=Object.fromEntries(e.map(S=>[S.id,S])),c=new Set(e.map(S=>S.id)),d=new Set;let p=EM(t,n,c,d);p.length===0&&(p=[ju()]);const m=typeof a=="string"&&p.some(S=>S.id===a)?a:p[0]?.id??null,f=m??p[0]?.id??Am;for(const S of e){if(d.has(S.id))continue;const y=Cw(S);p=TM(p,f,y),d.add(S.id)}return{workspaces:p.map(Do),activeWorkspaceId:m,terminals:o}}function Nm(e){return Es(e.root)}function yM(e){return Ip(e.root)}function SM(e){return e.tabs.flatMap(t=>Es(t.root))}function Cf(e){const t=e.workspaces.map(n=>{const a=n.tabs.flatMap(o=>{const c=Up(o.root);return c?[{...o,root:c}]:[]});return Do({...n,tabs:a})});return{activeWorkspaceId:t.some(n=>n.id===e.activeWorkspaceId)?e.activeWorkspaceId:t[0]?.id??null,workspaces:t}}function bM(e,t){return{...e,terminals:{...e.terminals,[t.id]:t},workspaces:e.workspaces.map(n=>({...n,tabs:n.tabs.map(a=>mo(a.root,t.id)?{...a,title:a.title||t.title}:a)}))}}function wM(e,t,n){const a=e.terminals[t];return a?{...e,terminals:{...e.terminals,[t]:{...a,status:"exited",exitCode:n}}}:e}function Sw(e,t){const n={...e.terminals};return delete n[t],bw(e,t,n)}function CM(e,t){return e.terminals[t]?bw(e,t,{...e.terminals}):e}function bw(e,t,n){const a=e.workspaces.map(c=>{const d=[];for(const p of c.tabs){const m=po(p.root,t);if(!m)continue;const f=Es(m),S=f.includes(p.activeTerminalId)?p.activeTerminalId:f[0];S&&d.push({...p,root:m,activeTerminalId:S})}return Do({...c,tabs:d})}),o=a.some(c=>c.id===e.activeWorkspaceId);return{workspaces:a,activeWorkspaceId:o?e.activeWorkspaceId:a[0]?.id??null,terminals:n}}function xM(e,t){const n=e.workspaces.map(o=>{const c=[];for(const d of o.tabs){const p=jp(d.root,t);if(!p)continue;const m=Es(p),f=m.includes(d.activeTerminalId)?d.activeTerminalId:m[0];f&&c.push({...d,root:p,activeTerminalId:f})}return Do({...o,tabs:c})}),a=n.some(o=>o.id===e.activeWorkspaceId);return{...e,workspaces:n,activeWorkspaceId:a?e.activeWorkspaceId:n[0]?.id??null}}function EM(e,t,n,a){if(t&&t.length>0){const o=[];for(const c of t)kM(c)&&o.push(nb(c,n,a));if(o.length>0)return o}return[nb({...ju(),tabs:e??[]},n,a)]}function nb(e,t,n){const a=[];for(const o of e.tabs){if(!DM(o))continue;const c=Hp(o.root,t);if(!c)continue;const d=Es(c);for(const m of d)n.add(m);const p=d.includes(o.activeTerminalId)?o.activeTerminalId:d[0];p&&a.push({...o,root:c,activeTerminalId:p})}return Do({...e,tabs:a})}function ww(e){return Kr(e)?e:{...e,workspaces:[ju()],activeWorkspaceId:Am}}function Kr(e){return e.workspaces.find(t=>t.id===e.activeWorkspaceId)??e.workspaces[0]}function zu(e){return e.tabs.find(t=>t.id===e.activeTabId)??e.tabs[0]}function ju(){return{id:Am,title:sM,tabs:[],activeTabId:null}}function Do(e){const t=e.tabs.some(n=>n.id===e.activeTabId);return{...e,activeTabId:t?e.activeTabId:e.tabs[0]?.id??null}}function TM(e,t,n){return e.map(a=>a.id===t?{...a,tabs:[...a.tabs,n],activeTabId:a.activeTabId??n.id}:a)}function Cw(e){return{id:`tab-${e.id}`,title:e.title||e.id,root:{type:"pane",terminalId:e.id},activeTerminalId:e.id}}function fo(e,t,n){return e.type==="pane"?e.terminalId===t?n:e:e.type==="editor"?e:{...e,first:fo(e.first,t,n),second:fo(e.second,t,n)}}function po(e,t){if(e.type==="pane")return e.terminalId===t?null:e;if(e.type==="editor")return e;const n=po(e.first,t),a=po(e.second,t);return n&&a?{...e,first:n,second:a}:n??a}function jp(e,t){if(e.type==="editor")return e.editorId===t?null:e;if(e.type==="pane")return e;const n=jp(e.first,t),a=jp(e.second,t);return n&&a?{...e,first:n,second:a}:n??a}function Hp(e,t){if(e.type==="pane")return t.has(e.terminalId)?e:null;if(e.type==="editor")return null;const n=Hp(e.first,t),a=Hp(e.second,t);return n&&a?{...e,ratio:xw(e.ratio),first:n,second:a}:n??a}function Up(e){if(e.type==="editor")return null;if(e.type==="pane")return e;const t=Up(e.first),n=Up(e.second);return t&&n?{...e,first:t,second:n}:t??n}function kM(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&typeof t.title=="string"&&(typeof t.activeTabId=="string"||t.activeTabId===null)&&Array.isArray(t.tabs)}function DM(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&typeof t.title=="string"&&typeof t.activeTerminalId=="string"&&Pp(t.root)}function Pp(e){if(!e||typeof e!="object")return!1;const t=e;return t.type==="pane"?typeof t.terminalId=="string":t.type==="editor"?typeof t.editorId=="string"&&typeof t.title=="string":t.type==="split"?(t.direction==="horizontal"||t.direction==="vertical")&&Pp(t.first)&&Pp(t.second):!1}function Kp(e,t,n){if(e.type==="pane"||e.type==="editor")return e;if(t.length===0)return e.ratio===n?e:{...e,ratio:n};const[a,...o]=t;if(a===0){const c=Kp(e.first,o,n);return c===e.first?e:{...e,first:c}}if(a===1){const c=Kp(e.second,o,n);return c===e.second?e:{...e,second:c}}return e}function xw(e){return Number.isFinite(e)?Math.min(.9,Math.max(.1,e)):.5}function mo(e,t){return e.type==="pane"?e.terminalId===t:e.type==="editor"?!1:mo(e.first,t)||mo(e.second,t)}function Es(e){return e.type==="pane"?[e.terminalId]:e.type==="editor"?[]:[...Es(e.first),...Es(e.second)]}function Ip(e){return e.type==="pane"||e.type==="editor"?1:Ip(e.first)+Ip(e.second)}const ur=new Map,_o=new Map,vo=new Map;function Pa(e){return e??"__local__"}function RM(e){return{agentId:e,state:nM(),editors:{},loaded:!1,error:null,layoutRevision:null,lastPersistedLayoutJson:null,unreadCompletions:new Set,mutable:{editorIdCounter:0,saveCoord:{pendingLayoutSave:null,saveTimer:null,persistChain:Promise.resolve(),nextPersistQueued:!1,nextPersistLayout:null,queuedBaseRevision:void 0}}}}function Ft(e){const t=Pa(e);let n=ur.get(t);return n||(n=RM(e),ur.set(t,n)),n}function Ew(e,t){const n=Pa(e);let a=_o.get(n);return a||(a=new Set,_o.set(n,a)),a.add(t),()=>{a.delete(t)}}function MM(e){const t=Pa(e),n=_o.get(t);if(n)for(const a of Array.from(n))a()}function Ka(e,t){ur.set(Pa(e),t),MM(e)}const Fp=new Set;function AM(e){return Fp.add(e),()=>{Fp.delete(e)}}function Ul(e,t){const n=Ft(e),a=Pa(e);t.type==="workspace.hydrated"&&vo.delete(a);const o=rM(n.state,t);let c=n.unreadCompletions,d=null;if(t.type==="terminal.updated"){const f=n.state.terminals[t.terminal.id],S=f?.activity==="busy",y=t.terminal.activity==="busy",b=t.terminal.activity==="idle",x=HM(a);if(t.notifyCompletion===!0&&y&&x.add(t.terminal.id),t.notifyCompletion===!0&&S&&b&&x.has(t.terminal.id)){const C=NM(o,t.terminal.id);C&&(d={terminalId:t.terminal.id,tabId:C.tab.id,commandName:f?.currentCommand??null},C.workspace.activeTabId!==C.tab.id&&(c.has(C.tab.id)||(c=new Set(c),c.add(C.tab.id))))}(b||t.terminal.status==="exited")&&x.delete(t.terminal.id)}t.type==="tab.selected"&&c.has(t.tabId)&&(c=new Set(c),c.delete(t.tabId));const p=o!==n.state,m=c!==n.unreadCompletions;if((p||m)&&Ka(e,{...n,state:o,unreadCompletions:c}),m&&Bm(),d)for(const f of Array.from(Fp))f({agentId:e,...d})}function NM(e,t){for(const n of e.workspaces)for(const a of n.tabs)if(Es(a.root).includes(t))return{workspace:n,tab:a};return null}const qp=new Set;function BM(e){return qp.add(e),()=>{qp.delete(e)}}function LM(){let e=0;for(const t of ur.values())e+=t.unreadCompletions.size;return e}function Bm(){for(const e of Array.from(qp))e()}function OM(e,t){const n=Ft(e);if(!n.unreadCompletions.has(t))return;const a=new Set(n.unreadCompletions);a.delete(t),Ka(e,{...n,unreadCompletions:a}),Bm()}function rb(e,t){const n=Ft(e);t!==n.state&&Ka(e,{...n,state:t})}function ab(e,t){const n=Ft(e),a=t(n.editors);a!==n.editors&&Ka(e,{...n,editors:a})}function Ta(e,t,n){const a=Ft(e);a.loaded===t&&a.error===n||Ka(e,{...a,loaded:t,error:n})}function Xc(e,t,n){const a=Ft(e);a.layoutRevision===t&&a.lastPersistedLayoutJson===n||Ka(e,{...a,layoutRevision:t,lastPersistedLayoutJson:n})}function zM(e){const t=Ft(e);return t.mutable.editorIdCounter+=1,t.mutable.editorIdCounter}function jM(e){const t=Pa(e),n=ur.get(t);n&&n.mutable.saveCoord.saveTimer!==null&&window.clearTimeout(n.mutable.saveCoord.saveTimer);const a=n?n.unreadCompletions.size>0:!1;ur.delete(t),_o.delete(t),vo.delete(t),a&&Bm()}function lb(){for(const e of ur.values()){const t=e.mutable.saveCoord.saveTimer;t!==null&&window.clearTimeout(t),e.unreadCompletions.size>0}ur.clear(),_o.clear(),vo.clear()}function HM(e){let t=vo.get(e);return t||(t=new Set,vo.set(e,t)),t}function UM(e,t){let n=!1,a=!1,o=null,c=!1;for(const d of Nm(e)){const p=t[d];if(p){if(p.status==="exited"){c=!0,n=!0;continue}p.activity==="busy"?(a=!0,n=!0,!o&&p.currentCommand&&(o=p.currentCommand)):p.activity==="idle"&&(n=!0)}}return n?c?{state:"exited",commandName:null}:a?{state:"busy",commandName:o}:{state:"idle",commandName:null}:null}function PM(e){return e?e.state==="busy"?e.commandName?`running: ${e.commandName}`:"running":e.state==="exited"?"exited":"idle":""}function KM({tabs:e,activeTabId:t,terminals:n,unreadCompletionTabIds:a,detachedTerminals:o,onSelectTab:c,onCreateTab:d,onToggleWorkspaces:p,onCloseTerminals:m,onReattachTerminal:f,onDeleteTerminal:S,onSplitVertical:y,onSplitHorizontal:b,onRenameTab:x,activePaneAvailable:C}){const[k,B]=g.useState(null),[R,re]=g.useState(null),F=g.useRef(null);g.useEffect(()=>{F.current?.focus(),F.current?.select()},[k?.tabId]);function J(I,ie){B({tabId:I,title:ie})}function ce(){if(!k)return;const I=k.title.trim();I&&x(k.tabId,I),B(null)}function q(){return _.jsxs("div",{className:"terminal-pane-actions","aria-label":"Pane actions",children:[_.jsx("button",{type:"button",className:"pane-action-button","aria-label":"Split right",title:`Split right - ${YE()}`,onClick:y,disabled:!C,children:_.jsx("span",{className:"split-icon split-icon-right","aria-hidden":"true"})}),_.jsx("button",{type:"button",className:"pane-action-button","aria-label":"Split down",title:`Split down - ${$E()}`,onClick:b,disabled:!C,children:_.jsx("span",{className:"split-icon split-icon-down","aria-hidden":"true"})})]})}return _.jsxs(_.Fragment,{children:[_.jsxs("nav",{className:"terminal-tabs","aria-label":"Terminal tabs",children:[_.jsx("button",{type:"button",className:"mobile-menu-button","aria-label":"Toggle workspaces",title:"Workspaces",onClick:p,children:_.jsxs("span",{className:"hamburger-lines","aria-hidden":"true",children:[_.jsx("span",{}),_.jsx("span",{}),_.jsx("span",{})]})}),_.jsxs("div",{className:"terminal-tab-list",children:[e.map((I,ie)=>{const de=Nm(I),j=yM(I),$=n[I.activeTerminalId],H=I.title||$?.title||I.activeTerminalId,L=I.id===t,X=k?.tabId===I.id,G=UM(I,n),M=a?.has(I.id)??!1;return _.jsxs(xi.Fragment,{children:[_.jsx(ob,{index:ie}),_.jsx(IM,{tab:I,active:L,editing:X,title:H,paneCount:j,terminalIds:de,canClose:e.length>1,editValue:X?k.title:null,editInputRef:X?F:null,activity:G,unread:M,onSelect:()=>c(I.id),onBeginRename:()=>J(I.id,H),onCloseAll:()=>m(de),onCommitRename:ce,onCancelRename:()=>B(null),onRenameChange:V=>B({tabId:I.id,title:V})})]},I.id)}),_.jsx(ob,{index:e.length}),_.jsx("button",{type:"button",className:"tab-add-button","aria-label":"New tab",title:"New tab",onClick:d,children:"+"}),(o?.length??0)>0?_.jsx("div",{className:"terminal-detached-pills","aria-label":"Detached terminals",children:(o??[]).map(I=>_.jsx(FM,{terminal:I,onReattach:()=>f?.(I.id),onDelete:()=>re(I)},I.id))}):null]}),C?q():null]}),R?_.jsx(qM,{terminal:R,onCancel:()=>re(null),onConfirm:()=>{S?.(R.id),re(null)}}):null]})}function IM({tab:e,active:t,editing:n,title:a,paneCount:o,canClose:c,editValue:d,editInputRef:p,activity:m,unread:f,onSelect:S,onBeginRename:y,onCloseAll:b,onCommitRename:x,onCancelRename:C,onRenameChange:k}){const{attributes:B,listeners:R,setNodeRef:re,transform:F,isDragging:J}=Fb({id:`tab-${e.id}`,data:{kind:"tab",tabId:e.id,terminalId:e.activeTerminalId},disabled:n}),ce={transform:Tf.Translate.toString(F),opacity:J?.4:void 0,zIndex:J?2:void 0};return _.jsxs("div",{ref:re,className:"terminal-tab","data-active":t,"data-dragging":J,"data-unread":f?"true":void 0,style:ce,...B,...R,children:[m?_.jsx("span",{className:"terminal-tab-status-dot","data-activity":m.state,"aria-hidden":"true",title:PM(m)}):null,n&&p&&d!==null?_.jsxs("form",{className:"terminal-tab-editor",onSubmit:q=>{q.preventDefault(),x()},children:[_.jsx("input",{ref:p,"aria-label":`Rename ${a}`,value:d,onBlur:x,onChange:q=>k(q.target.value),onKeyDown:q=>{if(q.key==="Enter"){q.preventDefault(),x();return}q.key==="Escape"&&(q.preventDefault(),C())}}),_.jsx("small",{children:o})]}):_.jsxs("button",{type:"button",className:"terminal-tab-select","aria-label":`Select ${a}`,title:a,onClick:S,onDoubleClick:q=>{q.preventDefault(),y()},children:[_.jsx("span",{children:a}),_.jsxs("small",{children:[o," pane",o===1?"":"s"]})]}),c&&!n?_.jsx("button",{type:"button",className:"icon-button","aria-label":`Close ${a}`,title:`Close ${a}`,onPointerDown:q=>q.stopPropagation(),onClick:q=>{q.stopPropagation(),b()},children:"x"}):null]})}function ob({index:e}){const{setNodeRef:t,isOver:n}=qb({id:`tab-position-${e}`,data:{kind:"tab-position",index:e}});return _.jsx("div",{ref:t,className:"terminal-tab-drop-slot","data-over":n,"aria-hidden":"true"})}function FM({terminal:e,onReattach:t,onDelete:n}){const a=e.title||e.cwd||e.id.slice(0,8),o=`${e.title||"Terminal"}
43
43
  ${e.cwd}
44
- (detached — click to re-open, × to delete)`;return _.jsxs("span",{className:"terminal-detached-pill",title:o,children:[_.jsx("button",{type:"button",className:"terminal-detached-pill-open","aria-label":`Re-open ${a}`,onClick:t,children:a}),_.jsx("button",{type:"button",className:"terminal-detached-pill-delete","aria-label":`Delete ${a}`,title:`Delete ${a} — this destroys the underlying shell session.`,onClick:c=>{c.stopPropagation(),n()},children:"×"})]})}function FM({terminal:e,onCancel:t,onConfirm:n}){const a=e.title||e.cwd||e.id.slice(0,8);return _.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"delete-terminal-title",onClick:t,children:_.jsxs("div",{className:"security-panel terminal-delete-dialog",onClick:o=>o.stopPropagation(),children:[_.jsxs("header",{className:"security-panel-header",children:[_.jsx("h2",{id:"delete-terminal-title",children:"Delete Terminal"}),_.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:t,children:"×"})]}),_.jsxs("section",{className:"terminal-delete-dialog-body",children:[_.jsx("p",{children:"Delete this terminal?"}),_.jsx("span",{children:a}),_.jsx("small",{children:"The shell session and scrollback will be destroyed."})]}),_.jsxs("div",{className:"terminal-delete-dialog-actions",children:[_.jsx("button",{type:"button",className:"secondary-button",onClick:t,children:"Cancel"}),_.jsx("button",{type:"button",className:"terminal-delete-confirm",onClick:n,children:"Delete"})]})]})})}function qM({uploads:e,onDismiss:t,onDismissAll:n,onRetry:a,onCancel:o}){if(e.length===0)return null;const d=e.some(m=>m.status==="failed"||m.status==="partial")?"alert":"status",p=e.filter(m=>m.status==="queued"||m.status==="uploading").length;return _.jsxs("aside",{className:`upload-toast upload-toast-${XM(e)}`,role:d,"aria-live":d==="alert"?"assertive":"polite",children:[_.jsxs("header",{className:"upload-toast-header",children:[_.jsx("strong",{children:e.length===1?su(e[0]):`Uploads ${p>0?`(${p} active)`:`(${e.length})`}`}),_.jsx("button",{type:"button","aria-label":"Dismiss upload status",onClick:n,children:"x"})]}),_.jsx("div",{className:"upload-toast-body upload-queue-body",children:e.map(m=>_.jsx(WM,{upload:m,compact:e.length>1,onDismiss:()=>t(m.id),onRetry:()=>a(m.id),onCancel:()=>o(m.id)},m.id))})]})}function WM({upload:e,compact:t,onDismiss:n,onRetry:a,onCancel:o}){const c="response"in e?e.response:void 0,d=e.status==="failed"||e.status==="partial",p=e.status==="queued"||e.status==="uploading";return _.jsxs("section",{className:"upload-queue-item","data-status":e.status,"aria-label":su(e),children:[_.jsxs("div",{className:"upload-queue-item-header",children:[_.jsx("strong",{children:su(e)}),_.jsxs("div",{className:"upload-queue-actions",children:[p?_.jsx("button",{type:"button",onClick:o,children:"Cancel"}):null,d?_.jsx("button",{type:"button",onClick:a,children:"Retry"}):null,_.jsx("button",{type:"button","aria-label":`Dismiss ${su(e)}`,onClick:n,children:"x"})]})]}),e.status==="queued"?_.jsx("p",{children:e.message??"Queued"}):null,e.status==="uploading"?_.jsx(YM,{toast:e}):null,c&&"message"in e&&e.message?_.jsx("p",{className:"upload-toast-muted",children:e.message}):null,c?_.jsx($M,{response:c,compact:t}):null,e.status==="failed"&&!c&&e.message?_.jsx("p",{children:e.message}):null]})}function YM({toast:e}){const t=e.percent===null?GM(e.loaded):`${e.percent}%`;return _.jsxs(_.Fragment,{children:[_.jsxs("div",{className:"upload-progress-row",children:[_.jsxs("span",{children:[e.fileCount," file",e.fileCount===1?"":"s"]}),_.jsx("span",{children:t})]}),_.jsx("div",{className:"upload-progress-track","aria-hidden":"true",children:_.jsx("span",{style:{width:e.percent===null?"100%":`${e.percent}%`}})})]})}function $M({response:e,compact:t}){const n=e.results.filter(d=>d.status==="failed"),a=e.results.filter(d=>d.status==="uploaded"),o=t?3:6,c=[...n,...a].slice(0,o);return _.jsxs(_.Fragment,{children:[_.jsx("p",{className:"upload-toast-destination",children:e.destinationCwd}),c.length>0?_.jsx("ul",{className:"upload-result-list",children:c.map((d,p)=>_.jsx(VM,{result:d},`${d.relativePath}-${p}`))}):null,e.results.length>c.length?_.jsxs("p",{className:"upload-toast-muted",children:["+",e.results.length-c.length," more"]}):null]})}function VM({result:e}){const t=e.savedRelativePath??e.relativePath,n=e.status==="uploaded"&&e.savedRelativePath!==void 0&&e.savedRelativePath!==e.relativePath;return _.jsxs("li",{"data-status":e.status,children:[_.jsx("span",{className:"upload-result-path",children:t}),n?_.jsx("span",{className:"upload-result-renamed",children:"renamed"}):null,e.status==="failed"&&e.error?_.jsx("span",{className:"upload-result-error",children:e.error}):null]})}function su(e){if(e.status==="queued")return"Preparing upload";if(e.status==="uploading")return`Uploading ${e.fileCount} file${e.fileCount===1?"":"s"}`;if(e.status==="success"){const t=e.response?.uploaded??e.fileCount;return`Uploaded ${t} file${t===1?"":"s"}`}if(e.status==="partial"){const t=e.response?.uploaded??0,n=(e.response?.uploaded??0)+(e.response?.failed??0)||e.fileCount;return`Uploaded ${t} of ${n} files`}return"Upload failed"}function XM(e){return e.some(t=>t.status==="failed")?"failed":e.some(t=>t.status==="partial")?"partial":e.some(t=>t.status==="uploading")?"uploading":e.some(t=>t.status==="queued")?"queued":"success"}function GM(e){return e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${Math.round(e/(1024*1024))} MB`}function ZM({toast:e,onActivate:t,onDismiss:n}){if(!e)return null;const a=e,o=a.commandName?`${a.commandName} finished`:"Command finished";function c(p){p.stopPropagation(),n()}function d(p){p.key!=="Enter"&&p.key!==" "||(p.preventDefault(),t(a))}return _.jsxs("aside",{className:"completion-toast",role:"status","aria-live":"polite",tabIndex:0,onClick:()=>t(a),onKeyDown:d,children:[_.jsx("video",{className:"completion-toast-character",src:a.assetSrc,muted:!0,autoPlay:!0,loop:!0,playsInline:!0,"aria-hidden":"true"}),_.jsxs("div",{className:"completion-toast-copy",children:[_.jsx("strong",{children:a.tabTitle}),_.jsx("span",{children:o})]}),_.jsx("button",{type:"button","aria-label":"Dismiss completion alert",onClick:c,children:"x"})]})}const QM=Xl(0,0,1,1),vn=1e-6;function JM(e){return Tw(e).map(t=>t.terminalId)}function Tw(e){return Vl(e,QM).sort(sA).map((t,n)=>({...t,index:n+1}))}function eA(e,t,n){const a=Tw(e),o=a.find(d=>d.terminalId===t);return o?a.filter(d=>d.terminalId!==t).map(d=>iA(o,d,n)).filter(d=>d!==null).sort(nA)[0]?.entry.terminalId??null:null}function tA(e,t){return!Number.isInteger(t)||t<1?null:JM(e)[t-1]??null}function Vl(e,t){if(e.type==="pane")return[{terminalId:e.terminalId,bounds:t}];if(e.type==="editor")return[];const n=rA(e.ratio);if(e.direction==="vertical"){const o=t.left+(t.right-t.left)*n;return[...Vl(e.first,Xl(t.left,t.top,o,t.bottom)),...Vl(e.second,Xl(o,t.top,t.right,t.bottom))]}const a=t.top+(t.bottom-t.top)*n;return[...Vl(e.first,Xl(t.left,t.top,t.right,a)),...Vl(e.second,Xl(t.left,a,t.right,t.bottom))]}function iA(e,t,n){const a=e.bounds,o=t.bounds,c=cb(a.left,a.right,o.left,o.right),d=cb(a.top,a.bottom,o.top,o.bottom);switch(n){case"left":return o.centerX>=a.centerX-vn||d<=vn?null:{entry:t,primaryDistance:Math.max(0,a.left-o.right),perpendicularDistance:Math.abs(a.centerY-o.centerY),overlap:d};case"right":return o.centerX<=a.centerX+vn||d<=vn?null:{entry:t,primaryDistance:Math.max(0,o.left-a.right),perpendicularDistance:Math.abs(a.centerY-o.centerY),overlap:d};case"up":return o.centerY>=a.centerY-vn||c<=vn?null:{entry:t,primaryDistance:Math.max(0,a.top-o.bottom),perpendicularDistance:Math.abs(a.centerX-o.centerX),overlap:c};case"down":return o.centerY<=a.centerY+vn||c<=vn?null:{entry:t,primaryDistance:Math.max(0,o.top-a.bottom),perpendicularDistance:Math.abs(a.centerX-o.centerX),overlap:c};default:return null}}function sA(e,t){return Ma(e.bounds.top,t.bounds.top)||Ma(e.bounds.left,t.bounds.left)}function nA(e,t){return Ma(e.primaryDistance,t.primaryDistance)||Ma(e.perpendicularDistance,t.perpendicularDistance)||Ma(t.overlap,e.overlap)||Ma(e.entry.index,t.entry.index)}function Ma(e,t){const n=e-t;return Math.abs(n)<=vn?0:n}function cb(e,t,n,a){return Math.max(0,Math.min(t,a)-Math.max(e,n))}function Xl(e,t,n,a){return{left:e,top:t,right:n,bottom:a,centerX:e+(n-e)/2,centerY:t+(a-t)/2}}function rA(e){return Number.isFinite(e)?Math.min(.9,Math.max(.1,e)):.5}class aA extends Error{constructor(t){super(t),this.name="UploadDropError"}}function ub(e){return e?Array.from(e.types??[]).includes("Files")||Mw(e.items).some(n=>n.kind==="file")?!0:Aw(e.files).length>0:!1}async function lA(e){const t=Mw(e.items).filter(n=>n.kind==="file");return t.length>0?oA(t):cA(e.files)}async function oA(e){const t=[];for(const n of e){const a=fA(n);if(a){await kw(a,"",t);continue}const o=n.getAsFile();if(o){t.push({relativePath:Dw(o),file:o});continue}throw new aA("Folder upload is not supported by this browser.")}return t}function cA(e){return Aw(e).map(t=>({relativePath:Dw(t),file:t}))}async function kw(e,t,n){const a=mA(t,e.name);if(e.isFile){const d=await uA(e);n.push({relativePath:a,file:d});return}if(!e.isDirectory)return;const o=e.createReader(),c=await hA(o);for(const d of c)await kw(d,a,n)}function uA(e){return new Promise((t,n)=>{e.file(t,a=>n(a))})}async function hA(e){const t=[];for(;;){const n=await dA(e);if(n.length===0)return t;t.push(...n)}}function dA(e){return new Promise((t,n)=>{e.readEntries(t,a=>n(a))})}function Dw(e){const t=e.webkitRelativePath;return Rw(typeof t=="string"&&t?t:e.name)}function fA(e){const t=e.webkitGetAsEntry?.();return pA(t)?t:null}function pA(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.name=="string"&&typeof t.isFile=="boolean"&&typeof t.isDirectory=="boolean"}function mA(e,t){return Rw(e?`${e}/${t}`:t)}function Rw(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").split("/").filter(Boolean).join("/")}function Mw(e){return e?Array.from(e):[]}function Aw(e){return e?Array.from(e):[]}const hb="nterminal.terminalWorkspaces.v2",Nw="nterminal.sidebarCollapsed.v1",_A=75,db=Yb.map(e=>e.url),vA=Yb[0].url;function gA({api:e,serverApi:t,activeAgentId:n=null,onSelectServer:a,sessionExpiresAt:o=null,onLogout:c=async()=>{},onSessionInvalid:d}){const p=g.useMemo(()=>e??Eu(),[e]),m=g.useMemo(()=>t??io(null),[t]),f=g.useMemo(()=>AA(n),[n]),S=g.useMemo(()=>T=>Ew(n,T),[n]),y=g.useMemo(()=>()=>Ft(n),[n]),b=g.useSyncExternalStore(S,y,y),x=b.state,C=b.editors,k=!b.loaded,B=b.error,[R,re]=g.useState(!1),[F,J]=g.useState(()=>zA()),[ce,q]=g.useState("servers"),[I,ie]=g.useState(!1),de=g.useSyncExternalStore(a2,Yy,Yy);g.useSyncExternalStore(s0,Wy,Wy);const[j,$]=g.useState(()=>[null]),[H,L]=g.useState(0),[X,G]=g.useState(()=>[n]),[M,V]=g.useState(()=>new Set),[Q,ve]=g.useState({}),[Se,E]=g.useState(null),W=g.useRef(null);g.useRef(!1);const ee=g.useRef(0),[he,ge]=g.useState(null),me=dx(ky(Hb,{activationConstraint:{distance:8}}),ky(Ub,{activationConstraint:{delay:250,tolerance:5}}));g.useEffect(()=>l2(p),[p]);function Ce(T){const A=T.active.data.current;if(A){if(A.kind==="tab"&&typeof A.tabId=="string"&&typeof A.terminalId=="string"){ge({tabId:A.tabId,terminalId:A.terminalId});return}A.kind==="pane"&&typeof A.sourceTabId=="string"&&typeof A.terminalId=="string"&&ge({tabId:A.sourceTabId,terminalId:A.terminalId})}}function ze(T){ge(null);const A=T.active.data.current,K=T.over?.data.current;if(!(!A||!K||typeof A.terminalId!="string")){if(A.kind==="tab"&&typeof A.tabId=="string"){if(K.kind==="tab-position"&&typeof K.index=="number"){Ge({type:"tab.reordered",sourceTabId:A.tabId,targetIndex:K.index});return}K.kind==="pane-zone"&&typeof K.terminalId=="string"&&(K.side==="top"||K.side==="right"||K.side==="bottom"||K.side==="left")&&Ge({type:"tab.dropped_into_pane",sourceTabId:A.tabId,sourceTerminalId:A.terminalId,targetTerminalId:K.terminalId,side:K.side});return}if(A.kind==="pane"&&typeof A.sourceTabId=="string"){if(K.kind==="tab-position"&&typeof K.index=="number"){Ge({type:"terminal.extracted_to_tab",sourceTabId:A.sourceTabId,sourceTerminalId:A.terminalId,targetIndex:K.index});return}K.kind==="pane-zone"&&typeof K.terminalId=="string"&&(K.side==="top"||K.side==="right"||K.side==="bottom"||K.side==="left")&&Ge({type:"tab.dropped_into_pane",sourceTabId:A.sourceTabId,sourceTerminalId:A.terminalId,targetTerminalId:K.terminalId,side:K.side})}}}function Ne(){ge(null)}const Re=x.workspaces.find(T=>T.id===x.activeWorkspaceId)??x.workspaces[0],Pe=Re?.tabs.find(T=>T.id===Re.activeTabId)??Re?.tabs[0],Ye=Pe?.activeTerminalId??null,Be=Ye?x.terminals[Ye]:void 0,ae=DA("(max-width: 760px)"),Ee=g.useMemo(()=>Pe?wu(Pe.root):[],[Pe]),xe=Re&&Pe?ru(n,Re.id,Pe.id):null,Ke=Pe?Bw(Ee,Pe.activeTerminalId,xe?Q[xe]:void 0):null,Xe=ae&&Ee.length>1,gt=g.useMemo(()=>{const T=new Set;for(const A of x.workspaces)for(const K of A.tabs)for(const ue of Nm(K))T.add(ue);return Object.values(x.terminals).filter(A=>!T.has(A.id))},[x.terminals,x.workspaces]),[yt,mi]=g.useState([]),te=g.useRef([]),je=g.useRef(null),[He,_i]=g.useState(null),[Vi,ai]=g.useState([]),[kt,ji]=g.useState(()=>zr()),Ti=g.useRef(0),Nt=g.useRef(n),$s=g.useRef(db),Hi=g.useRef(kt),qt=g.useRef(()=>{});qt.current=cs;const Jt=g.useCallback(async()=>{try{const T=await p.listNotificationAssets();ai(T.assets.filter(A=>A.enabled).map(A=>A.url))}catch{ai([])}},[p]);g.useEffect(()=>{G(T=>T.some(A=>mn(A,n))?T:[...T,n])},[n]);const Dt=g.useCallback(T=>{const A=Ft(T),K=io(T);for(const ue of Object.keys(A.state.terminals))Ap(K.createWebSocketUrl(ue)),$S(ue);zM(T),G(ue=>ue.filter(pe=>!mn(pe,T))),V(ue=>{const pe=`${nu(T)}:`;let ke=!1;const De=new Set;for(const rt of ue){if(rt.startsWith(pe)){ke=!0;continue}De.add(rt)}return ke?De:ue}),ve(ue=>{const pe=`${nu(T)}:`;let ke=!1;const De={};for(const[rt,ut]of Object.entries(ue)){if(rt.startsWith(pe)){ke=!0;continue}De[rt]=ut}return ke?De:ue})},[]);g.useEffect(()=>{let T=!1;return p.listAgents().then(A=>{if(!T){const K=A.agents.map(pe=>pe.id),ue=[null,...K];n!==null&&!K.includes(n)&&(Dt(n),a?.(null)),$(ue)}}).catch(()=>{}),()=>{T=!0}},[n,p,Dt,a,H]);const Cn=g.useCallback(T=>{Dt(T),L(A=>A+1),mn(T,Nt.current)&&a?.(null)},[Dt,a]);g.useEffect(()=>{$(T=>T.some(A=>mn(A,n))?T:[...T,n])},[n]),g.useEffect(()=>{Nt.current=n},[n]),g.useEffect(()=>{Jt()},[Jt]),g.useEffect(()=>Xb(()=>ji(zr())),[]),g.useEffect(()=>{const T=A=>{qt.current(A)};return window.addEventListener("keydown",T,!0),()=>window.removeEventListener("keydown",T,!0)},[]),g.useEffect(()=>{$s.current=Vi.length>0?Vi:db},[Vi]),g.useEffect(()=>{Hi.current=kt},[kt]),g.useEffect(()=>{if(!b.loaded||!Re||!Pe)return;const T=ru(n,Re.id,Pe.id);V(A=>{if(A.has(T))return A;const K=new Set(A);return K.add(T),K})},[n,b.loaded,Re?.id,Pe?.id]),g.useEffect(()=>()=>{Ir()},[]),g.useEffect(()=>MM(T=>{const A=Ft(T.agentId).state,K=A.workspaces.flatMap(De=>De.tabs).find(De=>De.id===T.tabId),ue=A.terminals[T.terminalId],pe=K?.title?.trim()||ue?.title||T.commandName||"terminal",ke=document.visibilityState==="visible"&&mn(T.agentId,Nt.current)&&T.tabId===MA(A);if(ke||zE({tabTitle:pe,commandName:T.commandName,terminalId:T.terminalId}),!ke&&document.visibilityState==="visible"&&Hi.current.enabled){const De=Ti.current+1;Ti.current=De;const rt=$s.current;_i({id:De,agentId:T.agentId,terminalId:T.terminalId,tabId:T.tabId,tabTitle:pe,commandName:T.commandName,assetSrc:rt[Math.floor(Math.random()*rt.length)]??vA})}}),[]),g.useEffect(()=>{if(!He||kt.persistUntilDismissed)return;const T=window.setTimeout(()=>{_i(A=>A?.id===He.id?null:A)},kt.durationSeconds*1e3);return()=>window.clearTimeout(T)},[He,kt]),g.useEffect(()=>{W.current?.focus(),W.current?.select()},[Se?.workspaceId]),g.useEffect(()=>{jA(F),F&&E(null)},[F]),g.useEffect(()=>{let T=!1;async function A(){if(!Ft(n).loaded){Ta(n,!1,null);try{const ue=NA(f),[pe,ke]=await Promise.all([m.listTerminals(),m.getTerminalLayout()]),De=pe.terminals.length>0?pe.terminals:[(await m.createTerminal({cols:80,rows:24})).terminal];if(!T){const rt=ke.layout?Ow(ke.layout):null,ut=rt??ue??{},yi=zp(De,void 0,ut.savedWorkspaces,ut.savedActiveWorkspaceId),Fr=Cf(yi);rb(n,yi),Xc(n,ke.revision,JSON.stringify(Fr)),Ta(n,!0,null),!rt&&ue&&Ui(Fr,{baseRevision:ke.revision})}}catch(ue){!T&&!bt(ue)&&Ta(n,!0,Kl(ue))}}}return A(),()=>{T=!0}},[n,m]);async function Bs(){await Wt(async()=>{const T=await m.createTerminal({cols:80,rows:24});Ge({type:"terminal.created",terminal:T.terminal})})}async function Vs(T){await Wt(async()=>{const A=Ye?{parentTerminalId:Ye,cols:80,rows:24}:{cols:80,rows:24},K=await m.createTerminal(A);Ge({type:"terminal.split",terminal:K.terminal,direction:T})})}async function Ts(T){if(!Ye)throw new Error("No active pane is available.");const A=await m.readFile(T),K=`editor-${Date.now().toString(36)}-${OM(n)}`,ue=OA(A.path);ab(n,pe=>({...pe,[K]:{id:K,title:ue,rootToken:T.rootToken,path:A.path,read:A}})),xe&&ve(pe=>({...pe,[xe]:Lw(K)})),Ge({type:"editor.split",editorId:K,title:ue,direction:"vertical"})}function ks(T){ab(n,A=>{const K={...A};return delete K[T],K}),Ge({type:"editor.closed",editorId:T})}function ot(T){St([T])}function St(T){for(const A of T)Ge({type:"terminal.detached",terminalId:A})}async function Rt(T){await Wt(async()=>{await Bt(T),Ap(m.createWebSocketUrl(T)),$S(T),Ge({type:"terminal.closed",terminalId:T})})}async function li(T,A){const K=A.trim();if(!K)return;let ue=null;for(const pe of x.workspaces){const ke=pe.tabs.find(De=>De.id===T);if(ke){ue=ke.activeTerminalId;break}}if(Ge({type:"tab.renamed",tabId:T,title:K}),!!ue)try{const pe=await m.renameTerminal(ue,K);ct({type:"terminal.updated",terminal:pe.terminal})}catch(pe){Ta(n,!0,Kl(pe))}}function ei(T){const A=x.terminals[T];A&&Ge({type:"terminal.created",terminal:A})}async function Bt(T){try{await m.closeTerminal(T)}catch(A){if(A instanceof yn&&A.status===404)return;throw A}}async function nt(){await Wt(async()=>{await c()})}async function Wt(T){Ta(n,!0,null);try{await T()}catch(A){if(bt(A))return;Ta(n,!0,Kl(A))}}function bt(T){return T instanceof yn&&T.status===401&&!m.isAgent&&d?(d(),!0):!1}function Ge(T){Ul(n,T);const A=Ft(n),K=A.state;if(!A.loaded||K.workspaces.length===0)return;const ue=Cf(K);JSON.stringify(ue)!==A.lastPersistedLayoutJson&&Qi(ue)}function ct(T){Ul(n,T)}function vi(T,A,K,ue){const pe=ru(T,A,K);ve(ke=>({...ke,[pe]:ue}))}function Ai(T){xe&&ve(A=>({...A,[xe]:T}))}function Ni(T,A){const K=Cu(T);A?vi(n,A.workspaceId,A.tabId,K):Ai(K),Ge({type:"pane.selected",terminalId:T})}function ki(T){Ai(T.key),T.type==="terminal"&&Ge({type:"pane.selected",terminalId:T.terminalId})}function cs(T){if(I||T.isComposing||T.key==="Process"||xA(T.target))return;const A=SA(T);if(!A)return;if(T.preventDefault(),T.stopPropagation(),A.type==="server.previous"||A.type==="server.next"){gi(A.type==="server.next"?1:-1);return}const K=Ft(n).state,ue=K.workspaces.find(De=>De.id===K.activeWorkspaceId)??K.workspaces[0],pe=ue?.tabs.find(De=>De.id===ue.activeTabId)??ue?.tabs[0];if(A.type==="split"){if(!pe)return;Vs(A.direction);return}if(!ue||!pe)return;if(A.type==="tab.previous"||A.type==="tab.next"){const De=CA(ue.tabs,pe.id,A.type==="tab.next"?1:-1);De&&Ge({type:"tab.selected",tabId:De.id});return}if(A.type==="tab.index"){const De=ue.tabs[A.index-1];De&&Ge({type:"tab.selected",tabId:De.id});return}const ke=bA(pe.root,pe.activeTerminalId,A);ke&&Ni(ke,{workspaceId:ue.id,tabId:pe.id})}function gi(T){if(!a||j.length===0)return;const A=j.findIndex(ke=>mn(ke,n)),ue=((A===-1?0:A)+T+j.length)%j.length,pe=j[ue]??null;mn(pe,n)||a(pe)}function mt(T){ub(T.dataTransfer)&&(T.preventDefault(),T.dataTransfer.dropEffect="copy")}function Yt(T){if(!ub(T.dataTransfer))return;T.preventDefault();const A=BA(Ft(n).state),K=ee.current+1;if(ee.current=K,!A){hr({id:K,status:"failed",fileCount:0,message:"No active running terminal is available for upload."});return}hr({id:K,status:"queued",fileCount:0,terminalId:A.id,message:"Preparing upload..."}),us(K,A.id,T.dataTransfer)}async function us(T,A,K){try{const ue=await lA(K);if(ue.length===0)throw new Error("No files were found in the drop.");Xi(T,{id:T,status:"queued",fileCount:ue.length,message:"Queued"},{terminalId:A,files:ue})}catch(ue){Xi(T,{id:T,status:"failed",fileCount:0,message:Kl(ue)},{terminalId:A})}finally{xn()}}async function Xs(T){const A=te.current.find(ke=>ke.id===T);if(!A?.terminalId||!A.files||A.files.length===0)return;const K=A.terminalId,ue=A.files,pe=new AbortController;je.current=T,Xi(T,{id:T,status:"uploading",fileCount:ue.length,loaded:0,total:null,percent:null},{terminalId:K,files:ue,abortController:pe});try{const ke=await g2({terminalId:K,files:ue,signal:pe.signal,onProgress:yi=>{Xi(T,{id:T,status:"uploading",fileCount:ue.length,loaded:yi.loaded,total:yi.total,percent:yi.percent},{terminalId:K,files:ue,abortController:pe})}}),De=ke.failed>0?ke.uploaded>0?"partial":"failed":"success",rt=ke.failed>0?LA(ke):void 0,ut={id:T,status:De,fileCount:ue.length,response:ke};rt&&(ut.message=rt),Xi(T,ut,{terminalId:K,files:ue})}catch(ke){Xi(T,{id:T,status:"failed",fileCount:ue.length,message:pe.signal.aborted?"Upload canceled.":Kl(ke)},{terminalId:K,files:ue})}finally{je.current===T&&(je.current=null),xn()}}function xn(){if(je.current!==null)return;const T=te.current.find(A=>A.status==="queued");T?.terminalId&&T.files&&T.files.length>0&&Xs(T.id)}function hr(T){Gi(A=>[...A,T])}function Xi(T,A,K={}){Gi(ue=>ue.map(pe=>{if(pe.id!==T)return pe;const ke={...A},De=K.terminalId??pe.terminalId,rt=K.files??pe.files;return De!==void 0&&(ke.terminalId=De),rt!==void 0&&(ke.files=rt),K.abortController!==void 0&&(ke.abortController=K.abortController),ke}))}function Gi(T){const A=T(te.current);te.current=A,mi(A)}function En(T){te.current.find(K=>K.id===T)?.abortController?.abort(),je.current===T&&(je.current=null),Gi(K=>K.filter(ue=>ue.id!==T)),xn()}function Ls(){for(const T of te.current)T.abortController?.abort();je.current=null,Gi(()=>[])}function Os(T){const A=te.current.find(K=>K.id===T);if(A){if(A.status==="queued"){En(T);return}A.abortController?.abort()}}function Ds(T){const A=te.current.find(ue=>ue.id===T);if(!A?.terminalId||!A.files||A.files.length===0)return;const K=Zi(A);if(K.length===0){Xi(T,{id:T,status:"failed",fileCount:A.fileCount,message:"No failed files are available to retry."},{terminalId:A.terminalId,files:A.files});return}Xi(T,{id:T,status:"queued",fileCount:K.length,message:"Queued"},{terminalId:A.terminalId,files:K}),xn()}function Zi(T){const A=T.files??[],K="response"in T?T.response:void 0;if(!K)return A;const ue=K.results.filter(De=>De.status==="failed").map(De=>De.relativePath);if(ue.length===0)return[];const pe=new Map;for(const De of A){const rt=pe.get(De.relativePath)??[];rt.push(De),pe.set(De.relativePath,rt)}const ke=[];for(const De of ue){const ut=pe.get(De)?.shift();ut&&ke.push(ut)}return ke}function Lt(T){const K=Ft(T.agentId).state.workspaces.find(ue=>ue.tabs.some(pe=>pe.id===T.tabId));K&&vi(T.agentId,K.id,T.tabId,Cu(T.terminalId)),Ul(T.agentId,{type:"pane.selected",terminalId:T.terminalId}),LM(T.agentId,T.tabId),mn(T.agentId,n)||a?.(T.agentId),_i(null)}function Qi(T){const A=Ft(n).mutable.saveCoord;A.pendingLayoutSave=T,Pl(T,f),A.saveTimer!==null&&window.clearTimeout(A.saveTimer),A.saveTimer=window.setTimeout(()=>{A.saveTimer=null;const K=A.pendingLayoutSave;A.pendingLayoutSave=null,K&&Ui(K)},_A)}function Ir(){const T=Ft(n).mutable.saveCoord;T.saveTimer!==null&&(window.clearTimeout(T.saveTimer),T.saveTimer=null);const A=T.pendingLayoutSave;T.pendingLayoutSave=null,A&&(Pl(A,f),Ui(A))}function Ui(T,A={}){const K=Ft(n).mutable.saveCoord;K.nextPersistLayout=T,A.baseRevision!==void 0&&(K.queuedBaseRevision=A.baseRevision),!K.nextPersistQueued&&(K.nextPersistQueued=!0,K.persistChain=K.persistChain.then(async()=>{K.nextPersistQueued=!1;const ue=K.nextPersistLayout,pe=K.queuedBaseRevision;K.nextPersistLayout=null,K.queuedBaseRevision=void 0,ue&&await zs(ue,pe!==void 0?{baseRevision:pe}:{})}))}async function zs(T,A={}){const K=Ft(n),ue=A.baseRevision??K.layoutRevision,pe={layout:T,...typeof ue=="number"?{baseRevision:ue}:{}};try{const ke=await m.saveTerminalLayout(pe),De=ke.layout??T;Xc(n,ke.revision,JSON.stringify(De)),Pl(De,f);return}catch(ke){if(ke instanceof yn&&ke.status===409)try{const De=await m.getTerminalLayout();if(De.layout){const rt=Ft(n).state,ut=zp(Object.values(rt.terminals),void 0,De.layout.workspaces,De.layout.activeWorkspaceId),yi=Cf(ut);rb(n,ut),Xc(n,De.revision,JSON.stringify(yi)),Pl(yi,f)}else Xc(n,De.revision,K.lastPersistedLayoutJson);return}catch{}Pl(T,f)}}const O=HA(o),fe=!F||R,Oe=fe?ce:"servers";return _.jsx(dE,{sensors:me,onDragStart:Ce,onDragEnd:ze,onDragCancel:Ne,children:_.jsxs("main",{className:"terminal-shell","data-collapsed":F,"data-sidebar-open":R,onDragOver:mt,onDrop:Yt,children:[_.jsx("button",{type:"button",className:"workspace-backdrop","aria-label":"Close workspaces",onClick:()=>re(!1)}),_.jsxs("aside",{className:"workspace-sidebar",children:[_.jsxs("header",{className:"workspace-brand",children:[fe?_.jsx(Cb,{height:20}):_.jsx(wb,{size:24}),_.jsx("button",{type:"button",className:"sidebar-collapse-button","aria-label":F?"Expand sidebar":"Collapse sidebar",title:F?"Expand sidebar":"Collapse sidebar",onClick:()=>J(T=>!T),children:F?">":"<"}),_.jsx("button",{type:"button",className:"sidebar-drawer-close-button","aria-label":"Close workspaces",title:"Close workspaces",onClick:()=>re(!1),children:"x"})]}),_.jsxs("div",{className:"workspace-sidebar-content",children:[fe?_.jsxs("div",{className:"workspace-sidebar-tabs",role:"tablist","aria-label":"Sidebar mode",children:[_.jsx("button",{type:"button",role:"tab","aria-selected":ce==="servers",onClick:()=>{q("servers"),E(null)},children:"Servers"}),_.jsx("button",{type:"button",role:"tab","aria-selected":ce==="files",onClick:()=>{q("files"),E(null)},children:"Files"})]}):null,Oe==="servers"&&fe?_.jsx("nav",{className:"workspace-nav","aria-label":"Servers",children:_.jsx(ef,{api:p,activeAgentId:n,onSelectServer:a??(()=>{}),onSessionInvalid:d,refreshToken:H})}):null,fe?null:_.jsx("nav",{className:"workspace-nav workspace-nav--collapsed","aria-label":"Servers",children:_.jsx(ef,{api:p,activeAgentId:n,onSelectServer:a??(()=>{}),onSessionInvalid:d,refreshToken:H,compact:!0})}),Oe==="files"?_.jsxs(_.Fragment,{children:[fe?_.jsx("nav",{className:"workspace-nav workspace-nav--compact","aria-label":"Servers",children:_.jsx(ef,{api:p,activeAgentId:n,onSelectServer:a??(()=>{}),onSessionInvalid:d,refreshToken:H})}):null,_.jsx(C2,{api:m,activeTerminalId:Ye,activeTerminalCwd:Be?.cwd??null,onOpenFile:Ts})]}):null]}),fe?_.jsxs("div",{className:"workspace-sidebar-footer",children:[_.jsx("span",{children:O}),_.jsxs("div",{className:"workspace-sidebar-footer-actions",children:[_.jsxs("button",{type:"button",className:"workspace-footer-icon-button","aria-label":"settings",title:"Settings",onClick:()=>ie(!0),children:[_.jsx(pb,{name:"settings"}),de.hasUpdates?_.jsx("span",{className:"update-pulse-dot","aria-hidden":"true"}):null]}),_.jsx("button",{type:"button",className:"workspace-footer-icon-button","aria-label":"logout",title:"Logout",onClick:()=>{nt()},children:_.jsx(pb,{name:"logout"})})]})]}):null]}),I?_.jsx(_2,{api:p,onClose:()=>ie(!1),updateAvailable:de.hasUpdates,onNotificationAssetsChanged:()=>{Jt()},onAgentRemoved:Cn}):null,_.jsxs("section",{className:"terminal-main","aria-label":"Terminal workspace","data-mobile-pane-switcher":Xe?"true":void 0,children:[_.jsx(PM,{tabs:Re?.tabs??[],activeTabId:Re?.activeTabId??null,terminals:x.terminals,unreadCompletionTabIds:b.unreadCompletions,detachedTerminals:gt,onSelectTab:T=>Ge({type:"tab.selected",tabId:T}),onCreateTab:()=>{Bs()},onToggleWorkspaces:()=>re(T=>!T),onCloseTerminals:T=>St(T),onReattachTerminal:T=>ei(T),onDeleteTerminal:T=>{Rt(T)},onSplitVertical:()=>{Vs("vertical")},onSplitHorizontal:()=>{Vs("horizontal")},onRenameTab:(T,A)=>{li(T,A)},activePaneAvailable:!!Ye}),Xe?_.jsx(TA,{targets:Ee,activeLeafKey:Ke,terminals:x.terminals,editors:C,onSelect:ki}):null,B?_.jsx("div",{className:"workspace-error",children:B}):null,_.jsxs("section",{className:"workspace-body","aria-busy":k,children:[k?_.jsx("div",{className:"workspace-placeholder",children:"Opening shell..."}):null,!k&&!Pe?_.jsx(EA,{onCreate:()=>{Bs()}}):null,X.map(T=>{const A=mn(T,n);return _.jsx(yA,{agentId:T,active:A,activeServerApi:A?m:void 0,visitedTabKeys:M,refreshCwdOnEnter:A&&Oe==="files",draggingTab:A?he:null,mobileSplitFocus:ae,mobileFocusedLeafByTabKey:Q,onSelect:K=>{A&&Ni(K)},onClose:K=>{A&&ot(K)},onCloseEditor:K=>{A&&ks(K)},onResize:(K,ue)=>{A&&Ge({type:"pane.resized",path:K,ratio:ue})},onExit:(K,ue)=>{A?ct({type:"terminal.exited",terminalId:K,exitCode:ue}):Ul(T,{type:"terminal.exited",terminalId:K,exitCode:ue})},onSnapshot:(K,ue)=>{const pe={type:"terminal.updated",terminal:K,notifyCompletion:ue?.notifyCompletion===!0};A?ct(pe):Ul(T,pe)},...T===null&&d?{onAuthClose:d}:{}},nu(T))})]}),_.jsx(ZM,{toast:He,onActivate:Lt,onDismiss:()=>_i(null)}),_.jsx(qM,{uploads:yt,onDismiss:En,onDismissAll:Ls,onRetry:Ds,onCancel:Os})]})]})})}function yA({agentId:e,active:t,activeServerApi:n,visitedTabKeys:a,refreshCwdOnEnter:o,draggingTab:c,mobileSplitFocus:d,mobileFocusedLeafByTabKey:p,onSelect:m,onClose:f,onCloseEditor:S,onResize:y,onExit:b,onSnapshot:x,onAuthClose:C}){const k=g.useMemo(()=>de=>Ew(e,de),[e]),B=g.useMemo(()=>()=>Ft(e),[e]),R=g.useSyncExternalStore(k,B,B),re=g.useMemo(()=>io(e),[e]),F=n??re,J=R.state,ce=J.workspaces.find(de=>de.id===J.activeWorkspaceId)??J.workspaces[0],q=ce?.id??null,ie=(ce?.tabs.find(de=>de.id===ce.activeTabId)??ce?.tabs[0])?.id??null;return!R.loaded||J.workspaces.length===0?null:_.jsx("div",{className:"workspace-server-surface","data-active":t,"aria-hidden":!t,children:J.workspaces.flatMap(de=>de.tabs.map(j=>{const $=t&&de.id===q&&j.id===ie,H=ru(e,de.id,j.id),L=wu(j.root),X=d&&L.length>1?Bw(L,j.activeTerminalId,p[H]):null;return!$&&!a.has(H)?null:_.jsx("div",{className:"workspace-tab-surface","data-active":$,"aria-hidden":!$,children:_.jsx(Bp,{node:j.root,terminals:J.terminals,editors:R.editors,api:F,activeTerminalId:j.activeTerminalId,visible:$,refreshCwdOnEnter:$&&o,tabId:j.id,dropZoneActive:$&&c!==null,draggingTerminalId:$?c?.terminalId??null:null,mobileFocusLeafKey:X,onSelect:m,onClose:f,onCloseEditor:S,onResize:y,onExit:b,onSnapshot:x,...C?{onAuthClose:C}:{}})},`${de.id}:${j.id}`)}))})}function SA(e){const t=WE(e);if(t)switch(t.id){case"server.previous":case"server.next":case"tab.previous":case"tab.next":return{type:t.id};case"tab.index":case"pane.index":return t.index===null?null:{type:t.id,index:t.index};case"split.right":return{type:"split",direction:"vertical"};case"split.down":return{type:"split",direction:"horizontal"};default:return null}if(e.ctrlKey&&e.altKey&&!e.metaKey&&!e.shiftKey){const n=wA(e.key);return n?{type:"pane.direction",direction:n}:null}return null}function bA(e,t,n){switch(n.type){case"pane.direction":return eA(e,t,n.direction);case"pane.index":return tA(e,n.index);default:return null}}function wA(e){switch(e){case"ArrowLeft":return"left";case"ArrowRight":return"right";case"ArrowUp":return"up";case"ArrowDown":return"down";default:return null}}function CA(e,t,n){if(e.length===0)return null;const a=e.findIndex(c=>c.id===t);return e[((a===-1?0:a)+n+e.length)%e.length]??null}function wu(e){return e.type==="pane"?[{key:Cu(e.terminalId),type:"terminal",terminalId:e.terminalId}]:e.type==="editor"?[{key:Lw(e.editorId),type:"editor",editorId:e.editorId,title:e.title}]:[...wu(e.first),...wu(e.second)]}function Bw(e,t,n){if(n&&e.some(o=>o.key===n))return n;const a=t?Cu(t):null;return a&&e.some(o=>o.key===a)?a:e[0]?.key??null}function Cu(e){return`terminal:${e}`}function Lw(e){return`editor:${e}`}function xA(e){if(!(e instanceof HTMLElement)||e.closest(".xterm"))return!1;if(e.closest('input, textarea, select, [role="textbox"]'))return!0;const t=e.closest("[contenteditable]");return t instanceof HTMLElement&&t.getAttribute("contenteditable")?.toLowerCase()!=="false"}function EA({onCreate:e}){return _.jsxs("div",{className:"empty-workspace",children:[_.jsx("span",{children:"No terminal is open."}),_.jsx("button",{type:"button",onClick:e,children:"New tab"})]})}function TA({targets:e,activeLeafKey:t,terminals:n,editors:a,onSelect:o}){const[c,d]=g.useState(!1);if(e.length<=1)return null;const p=t?e.findIndex(b=>b.key===t):-1,m=p>=0?p:0,f=e[m]??e[0],S=fb(f,n,a);function y(b){const x=(m+b+e.length)%e.length,C=e[x];C&&o(C)}return _.jsxs("div",{className:"mobile-pane-switcher",role:"group","aria-label":"Pane switcher",children:[_.jsx("button",{type:"button","aria-label":"Previous pane",onClick:()=>y(-1),children:"<"}),_.jsxs("button",{type:"button",className:"mobile-pane-current","aria-label":"Open pane switcher","aria-haspopup":"dialog","aria-expanded":c,title:S,onClick:()=>d(!0),children:["Pane ",m+1,"/",e.length," | ",S]}),_.jsx("button",{type:"button","aria-label":"Next pane",onClick:()=>y(1),children:">"}),c?_.jsx("div",{className:"mobile-pane-sheet-backdrop",onClick:()=>d(!1),children:_.jsxs("section",{className:"mobile-pane-sheet",role:"dialog","aria-modal":"true","aria-label":"Pane switcher",onClick:b=>b.stopPropagation(),children:[_.jsxs("header",{children:[_.jsx("strong",{children:"Panes"}),_.jsx("button",{type:"button","aria-label":"Close pane switcher",onClick:()=>d(!1),children:"x"})]}),_.jsx("div",{className:"mobile-pane-sheet-list",children:e.map((b,x)=>{const C=fb(b,n,a),k=kA(b,n,a),B=b.key===f.key;return _.jsxs("button",{type:"button","data-active":B,onClick:()=>{o(b),d(!1)},children:[_.jsx("span",{className:"mobile-pane-sheet-index",children:x+1}),_.jsxs("span",{className:"mobile-pane-sheet-copy",children:[_.jsx("strong",{children:C}),_.jsx("small",{children:k})]}),_.jsx("span",{className:"mobile-pane-sheet-type",children:b.type})]},b.key)})})]})}):null]})}function fb(e,t,n){if(e.type==="editor")return n[e.editorId]?.title||e.title||e.editorId;const a=t[e.terminalId];return a?.title||a?.cwd||e.terminalId}function kA(e,t,n){if(e.type==="editor"){const c=n[e.editorId];return c?.path?`editor | ${c.path}`:"editor"}const a=t[e.terminalId];return a?`${a.activity==="busy"?`busy${a.currentCommand?`: ${a.currentCommand}`:""}`:a.activity==="idle"?"idle":a.status} | ${a.cwd}`:"terminal"}function DA(e){const[t,n]=g.useState(()=>RA(e));return g.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function"){n(!1);return}const a=window.matchMedia(e),o=()=>n(a.matches);return o(),typeof a.addEventListener=="function"?(a.addEventListener("change",o),()=>a.removeEventListener("change",o)):(a.addListener(o),()=>a.removeListener(o))},[e]),t}function RA(e){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(e).matches}function mn(e,t){return e===t}function MA(e){const t=e.workspaces.find(a=>a.id===e.activeWorkspaceId)??e.workspaces[0];return(t?.tabs.find(a=>a.id===t.activeTabId)??t?.tabs[0])?.id??null}function nu(e){return e??"__local__"}function ru(e,t,n){return`${nu(e)}:${t}:${n}`}function AA(e){return e?{workspaceKey:`${hb}:${e}`}:{workspaceKey:hb}}function NA(e){const t=localStorage.getItem(e.workspaceKey);if(!t)return null;try{const n=JSON.parse(t),a=Wb(n);return a?Ow(a):null}catch{return null}}function Ow(e){const t=Wb(e);return t?{savedWorkspaces:t.workspaces,savedActiveWorkspaceId:t.activeWorkspaceId}:null}function Pl(e,t){if(e.workspaces.length>0){localStorage.setItem(t.workspaceKey,JSON.stringify(e));return}localStorage.removeItem(t.workspaceKey)}function BA(e){const t=e.workspaces.find(o=>o.id===e.activeWorkspaceId)??e.workspaces[0],n=t?.tabs.find(o=>o.id===t.activeTabId)??t?.tabs[0],a=n?e.terminals[n.activeTerminalId]:void 0;return a?.status==="running"?a:null}function LA(e){return e.results.find(t=>t.status==="failed"&&t.error)?.error}function OA(e){return e.split("/").filter(Boolean).pop()??e}function zA(){try{return localStorage.getItem(Nw)==="true"}catch{return!1}}function jA(e){try{localStorage.setItem(Nw,e?"true":"false")}catch{}}function HA(e){if(!e)return"session · local";const t=Date.parse(e);if(!Number.isFinite(t))return"session · local";const n=t-Date.now();if(n<=0)return"session · expired";const a=Math.max(1,Math.floor(n/6e4));return a<60?`session · ${a}m left`:`session · ${Math.floor(a/60)}h left`}function pb({name:e}){return _.jsxs("svg",{className:"workspace-footer-icon",viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[e==="settings"?_.jsxs(_.Fragment,{children:[_.jsx("path",{d:"M4 7h9"}),_.jsx("path",{d:"M17 7h3"}),_.jsx("circle",{cx:"15",cy:"7",r:"2"}),_.jsx("path",{d:"M4 12h3"}),_.jsx("path",{d:"M11 12h9"}),_.jsx("circle",{cx:"9",cy:"12",r:"2"}),_.jsx("path",{d:"M4 17h9"}),_.jsx("path",{d:"M17 17h3"}),_.jsx("circle",{cx:"15",cy:"17",r:"2"})]}):null,e==="logout"?_.jsxs(_.Fragment,{children:[_.jsx("path",{d:"M10 6H6v12h4"}),_.jsx("path",{d:"M13 8l4 4-4 4"}),_.jsx("path",{d:"M8 12h9"})]}):null]})}function Kl(e){return e instanceof Error?e.message:"Request failed"}function UA({api:e,onDone:t}){const[n,a]=g.useState(null),[o,c]=g.useState(null),[d,p]=g.useState(""),[m,f]=g.useState(!1),[S,y]=g.useState(null),[b,x]=g.useState(null);g.useEffect(()=>{let k=!1;return e.setupTotp().then(B=>{k||(a(B.qrDataUrl),c(B.secret))}).catch(B=>{k||x(B instanceof Error?B.message:"Failed to generate QR code")}),()=>{k=!0}},[e]);async function C(k){if(k.preventDefault(),!!o){f(!0),y(null);try{await e.activateTotp({secret:o,otp:d}),t()}catch(B){y(B instanceof Error?B.message:"Verification failed")}finally{f(!1)}}}return b?_.jsx("p",{className:"form-error",children:b}):!n||!o?_.jsx("p",{className:"muted",children:"Generating authenticator setup..."}):_.jsxs("div",{className:"totp-setup",children:[_.jsx("p",{className:"totp-setup-instructions",children:"Scan this QR code with an authenticator app (Google Authenticator, Authy, 1Password, etc.), then enter the 6-digit code to confirm."}),_.jsx("div",{className:"totp-qr-container",children:_.jsx("img",{src:n,alt:"TOTP QR code",width:192,height:192})}),_.jsxs("details",{className:"totp-secret-details",children:[_.jsx("summary",{children:"Can't scan? Enter manually"}),_.jsx("p",{className:"totp-secret-text",children:o})]}),_.jsxs("form",{className:"auth-form",onSubmit:C,children:[_.jsxs("label",{children:["Verification code",_.jsx("input",{autoFocus:!0,type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:d,onChange:k=>p(k.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}),S?_.jsx("p",{className:"form-error",children:S}):null,_.jsx("button",{type:"submit",disabled:m||d.length!==6,children:"Activate 2FA"})]})]})}function PA({api:e,serverApi:t,activeAgentId:n=null,onSelectServer:a}){const o=g.useMemo(()=>e??Eu(),[e]),c=g.useMemo(()=>t??io(null),[t]),[d,p]=g.useState(null),[m,f]=g.useState(null);g.useEffect(()=>{let C=!1;return o.getSession().then(k=>{C||(p(k),f(null))}).catch(k=>{C||(f(go(k)),p(null))}),()=>{C=!0}},[o]);const S=qA(d);async function y(){const C=await o.getSession();p(C),f(null)}async function b(){ZS(),lb(),iR(),f(null),p(null);try{await y()}catch(C){f(go(C))}}if(S==="workspace")return _.jsx(gA,{api:o,serverApi:c,activeAgentId:n,onSelectServer:a,sessionExpiresAt:d?.expiresAt??null,onSessionInvalid:()=>{b()},onLogout:async()=>{ZS(),lb();const C=await o.logout();p(C)}});const x={loading:"Terminal",setup_password:"Set password",setup_totp:"Set up 2FA",login:"Unlock terminal",reauth:"Verify it’s you",workspace:"Terminal"};return _.jsxs("main",{className:"auth-screen",children:[_.jsxs("div",{className:"auth-background","aria-hidden":"true",children:[_.jsx("div",{className:"auth-grid"}),_.jsx("div",{className:"auth-glow"})]}),_.jsxs("section",{className:"auth-panel","aria-busy":S==="loading",children:[_.jsxs("header",{className:"auth-header",children:[_.jsxs("div",{className:"auth-brand",children:[_.jsx(wb,{size:26}),_.jsxs("div",{children:[_.jsx(Cb,{height:17}),_.jsx("p",{className:"auth-host",children:"local terminal"})]})]}),_.jsx("h1",{children:x[S]})]}),m?_.jsx("p",{className:"form-error",children:m}):null,S==="loading"?_.jsx("p",{className:"muted",children:"Checking session..."}):null,S==="loading"&&m?_.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{b()},children:"Retry"}):null,S==="setup_password"?_.jsx(KA,{api:o,onSession:C=>{p(C)}}):null,S==="setup_totp"?_.jsx(UA,{api:o,onDone:()=>{y()}}):null,S==="login"?_.jsx(IA,{api:o,session:d,onSession:p,onRefresh:y}):null,S==="reauth"?_.jsx(FA,{api:o,session:d,onSession:p,onFullLogin:()=>p(C=>C&&{...C,deviceTrusted:!1})}):null]})]})}function KA({api:e,onSession:t}){const[n,a]=g.useState(""),[o,c]=g.useState(""),[d,p]=g.useState(!1),[m,f]=g.useState(null);async function S(y){y.preventDefault(),p(!0),f(null);try{if(n!==o){f("Passwords do not match");return}t(await e.setupPassword({password:n}))}catch(b){f(go(b))}finally{p(!1)}}return _.jsxs("form",{className:"auth-form",onSubmit:S,children:[_.jsxs("label",{children:["Password",_.jsx("input",{autoFocus:!0,value:n,onChange:y=>a(y.currentTarget.value),type:"password",minLength:8,required:!0})]}),_.jsxs("label",{children:["Confirm password",_.jsx("input",{value:o,onChange:y=>c(y.currentTarget.value),type:"password",minLength:8,required:!0})]}),m?_.jsx("p",{className:"form-error",children:m}):null,_.jsx("button",{type:"submit",disabled:d||n.length<8||o.length<8,children:"Set password"})]})}function IA({api:e,session:t,onSession:n,onRefresh:a}){const[o,c]=g.useState(""),[d,p]=g.useState(""),[m,f]=g.useState(!1),[S,y]=g.useState(!1),[b,x]=g.useState(null),C=t?.totpEnabled??!1,k=t?.currentIpWhitelisted??!1;async function B(R){R.preventDefault(),y(!0),x(null);try{n(await e.login({password:o,...C?{otp:d}:{},rememberNetwork:m}))}catch(re){x(go(re))}finally{y(!1)}}return _.jsxs("form",{className:"auth-form",onSubmit:B,children:[_.jsxs("label",{children:["Password",_.jsx("input",{autoFocus:!0,type:"password",value:o,onChange:R=>c(R.currentTarget.value),required:!0})]}),C?_.jsxs("label",{children:["Authenticator code",_.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:d,onChange:R=>p(R.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}):null,k?null:_.jsxs("label",{className:"auth-checkbox",children:[_.jsx("input",{type:"checkbox",checked:m,onChange:R=>f(R.currentTarget.checked)}),"Remember this network (skip 2FA here next time)"]}),b?_.jsx("p",{className:"form-error",children:b}):null,_.jsxs("div",{className:"button-row",children:[_.jsx("button",{type:"submit",disabled:S||o.length===0||C&&d.length!==6,children:"Unlock"}),_.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{a()},disabled:S,children:"Refresh"})]})]})}function FA({api:e,session:t,onSession:n,onFullLogin:a}){const o=t?.currentIpWhitelisted??!1,[c,d]=g.useState(""),[p,m]=g.useState(!1),[f,S]=g.useState(!1),[y,b]=g.useState(null),x=xi.useRef(!1),C=xi.useCallback(async(B,R)=>{S(!0),b(null);try{n(await e.reauth({...B?{otp:B}:{},rememberNetwork:R}))}catch(re){b(go(re))}finally{S(!1)}},[e,n]);g.useEffect(()=>{o&&!x.current&&(x.current=!0,C(void 0,!1))},[o,C]);async function k(B){B.preventDefault(),await C(c,p)}return o&&!y?_.jsx("p",{className:"muted",children:"Reconnecting from a trusted network…"}):_.jsxs("form",{className:"auth-form",onSubmit:k,children:[_.jsx("p",{className:"muted",children:"This device is remembered. Enter your authenticator code to continue."}),_.jsxs("label",{children:["Authenticator code",_.jsx("input",{autoFocus:!0,type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:c,onChange:B=>d(B.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}),_.jsxs("label",{className:"auth-checkbox",children:[_.jsx("input",{type:"checkbox",checked:p,onChange:B=>m(B.currentTarget.checked)}),"Remember this network (skip 2FA here next time)"]}),y?_.jsx("p",{className:"form-error",children:y}):null,_.jsxs("div",{className:"button-row",children:[_.jsx("button",{type:"submit",disabled:f||c.length!==6,children:"Continue"}),_.jsx("button",{type:"button",className:"secondary-button",onClick:a,disabled:f,children:"Use password instead"})]})]})}function qA(e){return e?e.passwordSet?e.authenticated&&!e.totpEnabled?"setup_totp":e.authenticated?"workspace":e.deviceTrusted&&e.totpEnabled?"reauth":"login":"setup_password":"loading"}function go(e){return e instanceof Error?e.message:"Request failed"}const mb="NTerminal",Wp="nterminal.activeAgentId";function WA(){const[e,t]=g.useState(()=>YA()),n=g.useMemo(()=>Eu(),[]),a=g.useMemo(()=>io(e),[e]);g.useEffect(()=>{const c=()=>{const d=BM();document.title=d>0?`(${d}) ${mb}`:mb};return c(),NM(c)},[]);function o(c){$A(c),t(c)}return _.jsx(PA,{api:n,activeAgentId:e,serverApi:a,onSelectServer:o})}function YA(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Wp);return e&&e.trim()?e:null}catch{return null}}function $A(e){if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(Wp,e);return}window.localStorage.removeItem(Wp)}catch{}}const _b=["gesturestart","gesturechange","gestureend"],VA=[".workspace-list",".terminal-tab-list",".mobile-terminal-key-bar",".upload-toast-body",".file-tree",".file-detail",".file-editor",".file-markdown-preview",".editor-markdown-preview"].join(",");function XA(e=window){if(!ZA(e))return()=>{};const t={passive:!1},n=e.document;function a(c){c.cancelable&&c.preventDefault()}function o(c){if(c.defaultPrevented)return;const d=c.touches;!d||d.length===0||(d.length>1||!GA(c.target))&&a(c)}for(const c of _b)n.addEventListener(c,a,t);return n.addEventListener("touchmove",o,t),n.addEventListener("dblclick",a,t),()=>{for(const c of _b)n.removeEventListener(c,a,t);n.removeEventListener("touchmove",o,t),n.removeEventListener("dblclick",a,t)}}function GA(e){return e instanceof Element&&e.closest(VA)!==null}function ZA(e){return e.navigator.maxTouchPoints>0?!0:typeof e.matchMedia=="function"&&e.matchMedia("(pointer: coarse)").matches}const vb="--nterminal-viewport-height",gb="--nterminal-keyboard-inset-bottom",yb="data-nterminal-keyboard-visible",QA=120;function JA(e=window){const t=e.document.documentElement,n=e.visualViewport;function a(){const o=eN(e);o!==null&&t.style.setProperty(vb,`${o}px`),t.style.setProperty(gb,`${zw(e)}px`),t.setAttribute(yb,String(tN(e)))}return a(),n?.addEventListener("resize",a),n?.addEventListener("scroll",a),e.addEventListener("resize",a),e.addEventListener("orientationchange",a),e.addEventListener("pageshow",a),e.document.addEventListener("visibilitychange",a),()=>{n?.removeEventListener("resize",a),n?.removeEventListener("scroll",a),e.removeEventListener("resize",a),e.removeEventListener("orientationchange",a),e.removeEventListener("pageshow",a),e.document.removeEventListener("visibilitychange",a),t.style.removeProperty(vb),t.style.removeProperty(gb),t.removeAttribute(yb)}}function eN(e){const t=e.visualViewport?.height;return xu(t)?t:xu(e.innerHeight)?e.innerHeight:null}function xu(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function tN(e){return zw(e)>QA}function zw(e){const t=e.visualViewport?.height;if(!xu(t)||!xu(e.innerHeight))return 0;const n=typeof e.visualViewport?.offsetTop=="number"?e.visualViewport.offsetTop:0;return Math.max(0,Math.round(e.innerHeight-t-n))}JA();XA();pm();ZC.createRoot(document.getElementById("root")).render(_.jsx(xi.StrictMode,{children:_.jsx(WA,{})}));export{IC as g,_ as j};
44
+ (detached — click to re-open, × to delete)`;return _.jsxs("span",{className:"terminal-detached-pill",title:o,children:[_.jsx("button",{type:"button",className:"terminal-detached-pill-open","aria-label":`Re-open ${a}`,onClick:t,children:a}),_.jsx("button",{type:"button",className:"terminal-detached-pill-delete","aria-label":`Delete ${a}`,title:`Delete ${a} — this destroys the underlying shell session.`,onClick:c=>{c.stopPropagation(),n()},children:"×"})]})}function qM({terminal:e,onCancel:t,onConfirm:n}){const a=e.title||e.cwd||e.id.slice(0,8);return _.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"delete-terminal-title",onClick:t,children:_.jsxs("div",{className:"security-panel terminal-delete-dialog",onClick:o=>o.stopPropagation(),children:[_.jsxs("header",{className:"security-panel-header",children:[_.jsx("h2",{id:"delete-terminal-title",children:"Delete Terminal"}),_.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:t,children:"×"})]}),_.jsxs("section",{className:"terminal-delete-dialog-body",children:[_.jsx("p",{children:"Delete this terminal?"}),_.jsx("span",{children:a}),_.jsx("small",{children:"The shell session and scrollback will be destroyed."})]}),_.jsxs("div",{className:"terminal-delete-dialog-actions",children:[_.jsx("button",{type:"button",className:"secondary-button",onClick:t,children:"Cancel"}),_.jsx("button",{type:"button",className:"terminal-delete-confirm",onClick:n,children:"Delete"})]})]})})}function WM({uploads:e,onDismiss:t,onDismissAll:n,onRetry:a,onCancel:o}){if(e.length===0)return null;const d=e.some(m=>m.status==="failed"||m.status==="partial")?"alert":"status",p=e.filter(m=>m.status==="queued"||m.status==="uploading").length;return _.jsxs("aside",{className:`upload-toast upload-toast-${GM(e)}`,role:d,"aria-live":d==="alert"?"assertive":"polite",children:[_.jsxs("header",{className:"upload-toast-header",children:[_.jsx("strong",{children:e.length===1?su(e[0]):`Uploads ${p>0?`(${p} active)`:`(${e.length})`}`}),_.jsx("button",{type:"button","aria-label":"Dismiss upload status",onClick:n,children:"x"})]}),_.jsx("div",{className:"upload-toast-body upload-queue-body",children:e.map(m=>_.jsx(YM,{upload:m,compact:e.length>1,onDismiss:()=>t(m.id),onRetry:()=>a(m.id),onCancel:()=>o(m.id)},m.id))})]})}function YM({upload:e,compact:t,onDismiss:n,onRetry:a,onCancel:o}){const c="response"in e?e.response:void 0,d=e.status==="failed"||e.status==="partial",p=e.status==="queued"||e.status==="uploading";return _.jsxs("section",{className:"upload-queue-item","data-status":e.status,"aria-label":su(e),children:[_.jsxs("div",{className:"upload-queue-item-header",children:[_.jsx("strong",{children:su(e)}),_.jsxs("div",{className:"upload-queue-actions",children:[p?_.jsx("button",{type:"button",onClick:o,children:"Cancel"}):null,d?_.jsx("button",{type:"button",onClick:a,children:"Retry"}):null,_.jsx("button",{type:"button","aria-label":`Dismiss ${su(e)}`,onClick:n,children:"x"})]})]}),e.status==="queued"?_.jsx("p",{children:e.message??"Queued"}):null,e.status==="uploading"?_.jsx($M,{toast:e}):null,c&&"message"in e&&e.message?_.jsx("p",{className:"upload-toast-muted",children:e.message}):null,c?_.jsx(VM,{response:c,compact:t}):null,e.status==="failed"&&!c&&e.message?_.jsx("p",{children:e.message}):null]})}function $M({toast:e}){const t=e.percent===null?ZM(e.loaded):`${e.percent}%`;return _.jsxs(_.Fragment,{children:[_.jsxs("div",{className:"upload-progress-row",children:[_.jsxs("span",{children:[e.fileCount," file",e.fileCount===1?"":"s"]}),_.jsx("span",{children:t})]}),_.jsx("div",{className:"upload-progress-track","aria-hidden":"true",children:_.jsx("span",{style:{width:e.percent===null?"100%":`${e.percent}%`}})})]})}function VM({response:e,compact:t}){const n=e.results.filter(d=>d.status==="failed"),a=e.results.filter(d=>d.status==="uploaded"),o=t?3:6,c=[...n,...a].slice(0,o);return _.jsxs(_.Fragment,{children:[_.jsx("p",{className:"upload-toast-destination",children:e.destinationCwd}),c.length>0?_.jsx("ul",{className:"upload-result-list",children:c.map((d,p)=>_.jsx(XM,{result:d},`${d.relativePath}-${p}`))}):null,e.results.length>c.length?_.jsxs("p",{className:"upload-toast-muted",children:["+",e.results.length-c.length," more"]}):null]})}function XM({result:e}){const t=e.savedRelativePath??e.relativePath,n=e.status==="uploaded"&&e.savedRelativePath!==void 0&&e.savedRelativePath!==e.relativePath;return _.jsxs("li",{"data-status":e.status,children:[_.jsx("span",{className:"upload-result-path",children:t}),n?_.jsx("span",{className:"upload-result-renamed",children:"renamed"}):null,e.status==="failed"&&e.error?_.jsx("span",{className:"upload-result-error",children:e.error}):null]})}function su(e){if(e.status==="queued")return"Preparing upload";if(e.status==="uploading")return`Uploading ${e.fileCount} file${e.fileCount===1?"":"s"}`;if(e.status==="success"){const t=e.response?.uploaded??e.fileCount;return`Uploaded ${t} file${t===1?"":"s"}`}if(e.status==="partial"){const t=e.response?.uploaded??0,n=(e.response?.uploaded??0)+(e.response?.failed??0)||e.fileCount;return`Uploaded ${t} of ${n} files`}return"Upload failed"}function GM(e){return e.some(t=>t.status==="failed")?"failed":e.some(t=>t.status==="partial")?"partial":e.some(t=>t.status==="uploading")?"uploading":e.some(t=>t.status==="queued")?"queued":"success"}function ZM(e){return e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${Math.round(e/(1024*1024))} MB`}function QM({toast:e,onActivate:t,onDismiss:n}){if(!e)return null;const a=e,o=a.commandName?`${a.commandName} finished`:"Command finished";function c(p){p.stopPropagation(),n()}function d(p){p.key!=="Enter"&&p.key!==" "||(p.preventDefault(),t(a))}return _.jsxs("aside",{className:"completion-toast",role:"status","aria-live":"polite",tabIndex:0,onClick:()=>t(a),onKeyDown:d,children:[_.jsx("video",{className:"completion-toast-character",src:a.assetSrc,muted:!0,autoPlay:!0,loop:!0,playsInline:!0,"aria-hidden":"true"}),_.jsxs("div",{className:"completion-toast-copy",children:[_.jsx("strong",{children:a.tabTitle}),_.jsx("span",{children:o})]}),_.jsx("button",{type:"button","aria-label":"Dismiss completion alert",onClick:c,children:"x"})]})}const JM=Xl(0,0,1,1),vn=1e-6;function eA(e){return Tw(e).map(t=>t.terminalId)}function Tw(e){return Vl(e,JM).sort(nA).map((t,n)=>({...t,index:n+1}))}function tA(e,t,n){const a=Tw(e),o=a.find(d=>d.terminalId===t);return o?a.filter(d=>d.terminalId!==t).map(d=>sA(o,d,n)).filter(d=>d!==null).sort(rA)[0]?.entry.terminalId??null:null}function iA(e,t){return!Number.isInteger(t)||t<1?null:eA(e)[t-1]??null}function Vl(e,t){if(e.type==="pane")return[{terminalId:e.terminalId,bounds:t}];if(e.type==="editor")return[];const n=aA(e.ratio);if(e.direction==="vertical"){const o=t.left+(t.right-t.left)*n;return[...Vl(e.first,Xl(t.left,t.top,o,t.bottom)),...Vl(e.second,Xl(o,t.top,t.right,t.bottom))]}const a=t.top+(t.bottom-t.top)*n;return[...Vl(e.first,Xl(t.left,t.top,t.right,a)),...Vl(e.second,Xl(t.left,a,t.right,t.bottom))]}function sA(e,t,n){const a=e.bounds,o=t.bounds,c=cb(a.left,a.right,o.left,o.right),d=cb(a.top,a.bottom,o.top,o.bottom);switch(n){case"left":return o.centerX>=a.centerX-vn||d<=vn?null:{entry:t,primaryDistance:Math.max(0,a.left-o.right),perpendicularDistance:Math.abs(a.centerY-o.centerY),overlap:d};case"right":return o.centerX<=a.centerX+vn||d<=vn?null:{entry:t,primaryDistance:Math.max(0,o.left-a.right),perpendicularDistance:Math.abs(a.centerY-o.centerY),overlap:d};case"up":return o.centerY>=a.centerY-vn||c<=vn?null:{entry:t,primaryDistance:Math.max(0,a.top-o.bottom),perpendicularDistance:Math.abs(a.centerX-o.centerX),overlap:c};case"down":return o.centerY<=a.centerY+vn||c<=vn?null:{entry:t,primaryDistance:Math.max(0,o.top-a.bottom),perpendicularDistance:Math.abs(a.centerX-o.centerX),overlap:c};default:return null}}function nA(e,t){return Ma(e.bounds.top,t.bounds.top)||Ma(e.bounds.left,t.bounds.left)}function rA(e,t){return Ma(e.primaryDistance,t.primaryDistance)||Ma(e.perpendicularDistance,t.perpendicularDistance)||Ma(t.overlap,e.overlap)||Ma(e.entry.index,t.entry.index)}function Ma(e,t){const n=e-t;return Math.abs(n)<=vn?0:n}function cb(e,t,n,a){return Math.max(0,Math.min(t,a)-Math.max(e,n))}function Xl(e,t,n,a){return{left:e,top:t,right:n,bottom:a,centerX:e+(n-e)/2,centerY:t+(a-t)/2}}function aA(e){return Number.isFinite(e)?Math.min(.9,Math.max(.1,e)):.5}class lA extends Error{constructor(t){super(t),this.name="UploadDropError"}}function ub(e){return e?Array.from(e.types??[]).includes("Files")||Mw(e.items).some(n=>n.kind==="file")?!0:Aw(e.files).length>0:!1}async function oA(e){const t=Mw(e.items).filter(n=>n.kind==="file");return t.length>0?cA(t):uA(e.files)}async function cA(e){const t=[];for(const n of e){const a=pA(n);if(a){await kw(a,"",t);continue}const o=n.getAsFile();if(o){t.push({relativePath:Dw(o),file:o});continue}throw new lA("Folder upload is not supported by this browser.")}return t}function uA(e){return Aw(e).map(t=>({relativePath:Dw(t),file:t}))}async function kw(e,t,n){const a=_A(t,e.name);if(e.isFile){const d=await hA(e);n.push({relativePath:a,file:d});return}if(!e.isDirectory)return;const o=e.createReader(),c=await dA(o);for(const d of c)await kw(d,a,n)}function hA(e){return new Promise((t,n)=>{e.file(t,a=>n(a))})}async function dA(e){const t=[];for(;;){const n=await fA(e);if(n.length===0)return t;t.push(...n)}}function fA(e){return new Promise((t,n)=>{e.readEntries(t,a=>n(a))})}function Dw(e){const t=e.webkitRelativePath;return Rw(typeof t=="string"&&t?t:e.name)}function pA(e){const t=e.webkitGetAsEntry?.();return mA(t)?t:null}function mA(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.name=="string"&&typeof t.isFile=="boolean"&&typeof t.isDirectory=="boolean"}function _A(e,t){return Rw(e?`${e}/${t}`:t)}function Rw(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").split("/").filter(Boolean).join("/")}function Mw(e){return e?Array.from(e):[]}function Aw(e){return e?Array.from(e):[]}const hb="nterminal.terminalWorkspaces.v2",Nw="nterminal.sidebarCollapsed.v1",vA=75,db=Yb.map(e=>e.url),gA=Yb[0].url;function yA({api:e,serverApi:t,activeAgentId:n=null,onSelectServer:a,sessionExpiresAt:o=null,onLogout:c=async()=>{},onSessionInvalid:d}){const p=g.useMemo(()=>e??Eu(),[e]),m=g.useMemo(()=>t??io(null),[t]),f=g.useMemo(()=>NA(n),[n]),S=g.useMemo(()=>T=>Ew(n,T),[n]),y=g.useMemo(()=>()=>Ft(n),[n]),b=g.useSyncExternalStore(S,y,y),x=b.state,C=b.editors,k=!b.loaded,B=b.error,[R,re]=g.useState(!1),[F,J]=g.useState(()=>jA()),[ce,q]=g.useState("servers"),[I,ie]=g.useState(!1),de=g.useSyncExternalStore(a2,Yy,Yy);g.useSyncExternalStore(s0,Wy,Wy);const[j,$]=g.useState(()=>[null]),[H,L]=g.useState(0),[X,G]=g.useState(()=>[n]),[M,V]=g.useState(()=>new Set),[Q,ve]=g.useState({}),[Se,E]=g.useState(null),W=g.useRef(null);g.useRef(!1);const ee=g.useRef(0),[he,ge]=g.useState(null),me=dx(ky(Hb,{activationConstraint:{distance:8}}),ky(Ub,{activationConstraint:{delay:250,tolerance:5}}));g.useEffect(()=>l2(p),[p]);function Ce(T){const A=T.active.data.current;if(A){if(A.kind==="tab"&&typeof A.tabId=="string"&&typeof A.terminalId=="string"){ge({tabId:A.tabId,terminalId:A.terminalId});return}A.kind==="pane"&&typeof A.sourceTabId=="string"&&typeof A.terminalId=="string"&&ge({tabId:A.sourceTabId,terminalId:A.terminalId})}}function ze(T){ge(null);const A=T.active.data.current,K=T.over?.data.current;if(!(!A||!K||typeof A.terminalId!="string")){if(A.kind==="tab"&&typeof A.tabId=="string"){if(K.kind==="tab-position"&&typeof K.index=="number"){Ge({type:"tab.reordered",sourceTabId:A.tabId,targetIndex:K.index});return}K.kind==="pane-zone"&&typeof K.terminalId=="string"&&(K.side==="top"||K.side==="right"||K.side==="bottom"||K.side==="left")&&Ge({type:"tab.dropped_into_pane",sourceTabId:A.tabId,sourceTerminalId:A.terminalId,targetTerminalId:K.terminalId,side:K.side});return}if(A.kind==="pane"&&typeof A.sourceTabId=="string"){if(K.kind==="tab-position"&&typeof K.index=="number"){Ge({type:"terminal.extracted_to_tab",sourceTabId:A.sourceTabId,sourceTerminalId:A.terminalId,targetIndex:K.index});return}K.kind==="pane-zone"&&typeof K.terminalId=="string"&&(K.side==="top"||K.side==="right"||K.side==="bottom"||K.side==="left")&&Ge({type:"tab.dropped_into_pane",sourceTabId:A.sourceTabId,sourceTerminalId:A.terminalId,targetTerminalId:K.terminalId,side:K.side})}}}function Ne(){ge(null)}const Re=x.workspaces.find(T=>T.id===x.activeWorkspaceId)??x.workspaces[0],Pe=Re?.tabs.find(T=>T.id===Re.activeTabId)??Re?.tabs[0],Ye=Pe?.activeTerminalId??null,Be=Ye?x.terminals[Ye]:void 0,ae=RA("(max-width: 760px)"),Ee=g.useMemo(()=>Pe?wu(Pe.root):[],[Pe]),xe=Re&&Pe?ru(n,Re.id,Pe.id):null,Ke=Pe?Bw(Ee,Pe.activeTerminalId,xe?Q[xe]:void 0):null,Xe=ae&&Ee.length>1,gt=g.useMemo(()=>{const T=new Set;for(const A of x.workspaces)for(const K of A.tabs)for(const ue of Nm(K))T.add(ue);return Object.values(x.terminals).filter(A=>!T.has(A.id))},[x.terminals,x.workspaces]),[yt,mi]=g.useState([]),te=g.useRef([]),je=g.useRef(null),[He,_i]=g.useState(null),[Vi,ai]=g.useState([]),[kt,ji]=g.useState(()=>zr()),Ti=g.useRef(0),Nt=g.useRef(n),$s=g.useRef(db),Hi=g.useRef(kt),qt=g.useRef(()=>{});qt.current=cs;const Jt=g.useCallback(async()=>{try{const T=await p.listNotificationAssets();ai(T.assets.filter(A=>A.enabled).map(A=>A.url))}catch{ai([])}},[p]);g.useEffect(()=>{G(T=>T.some(A=>mn(A,n))?T:[...T,n])},[n]);const Dt=g.useCallback(T=>{const A=Ft(T),K=io(T);for(const ue of Object.keys(A.state.terminals))Ap(K.createWebSocketUrl(ue)),$S(ue);jM(T),G(ue=>ue.filter(pe=>!mn(pe,T))),V(ue=>{const pe=`${nu(T)}:`;let ke=!1;const De=new Set;for(const rt of ue){if(rt.startsWith(pe)){ke=!0;continue}De.add(rt)}return ke?De:ue}),ve(ue=>{const pe=`${nu(T)}:`;let ke=!1;const De={};for(const[rt,ut]of Object.entries(ue)){if(rt.startsWith(pe)){ke=!0;continue}De[rt]=ut}return ke?De:ue})},[]);g.useEffect(()=>{let T=!1;return p.listAgents().then(A=>{if(!T){const K=A.agents.map(pe=>pe.id),ue=[null,...K];n!==null&&!K.includes(n)&&(Dt(n),a?.(null)),$(ue)}}).catch(()=>{}),()=>{T=!0}},[n,p,Dt,a,H]);const Cn=g.useCallback(T=>{Dt(T),L(A=>A+1),mn(T,Nt.current)&&a?.(null)},[Dt,a]);g.useEffect(()=>{$(T=>T.some(A=>mn(A,n))?T:[...T,n])},[n]),g.useEffect(()=>{Nt.current=n},[n]),g.useEffect(()=>{Jt()},[Jt]),g.useEffect(()=>Xb(()=>ji(zr())),[]),g.useEffect(()=>{const T=A=>{qt.current(A)};return window.addEventListener("keydown",T,!0),()=>window.removeEventListener("keydown",T,!0)},[]),g.useEffect(()=>{$s.current=Vi.length>0?Vi:db},[Vi]),g.useEffect(()=>{Hi.current=kt},[kt]),g.useEffect(()=>{if(!b.loaded||!Re||!Pe)return;const T=ru(n,Re.id,Pe.id);V(A=>{if(A.has(T))return A;const K=new Set(A);return K.add(T),K})},[n,b.loaded,Re?.id,Pe?.id]),g.useEffect(()=>()=>{Ir()},[]),g.useEffect(()=>AM(T=>{const A=Ft(T.agentId).state,K=A.workspaces.flatMap(De=>De.tabs).find(De=>De.id===T.tabId),ue=A.terminals[T.terminalId],pe=K?.title?.trim()||ue?.title||T.commandName||"terminal",ke=document.visibilityState==="visible"&&mn(T.agentId,Nt.current)&&T.tabId===AA(A);if(ke||zE({tabTitle:pe,commandName:T.commandName,terminalId:T.terminalId}),!ke&&document.visibilityState==="visible"&&Hi.current.enabled){const De=Ti.current+1;Ti.current=De;const rt=$s.current;_i({id:De,agentId:T.agentId,terminalId:T.terminalId,tabId:T.tabId,tabTitle:pe,commandName:T.commandName,assetSrc:rt[Math.floor(Math.random()*rt.length)]??gA})}}),[]),g.useEffect(()=>{if(!He||kt.persistUntilDismissed)return;const T=window.setTimeout(()=>{_i(A=>A?.id===He.id?null:A)},kt.durationSeconds*1e3);return()=>window.clearTimeout(T)},[He,kt]),g.useEffect(()=>{W.current?.focus(),W.current?.select()},[Se?.workspaceId]),g.useEffect(()=>{HA(F),F&&E(null)},[F]),g.useEffect(()=>{let T=!1;async function A(){if(!Ft(n).loaded){Ta(n,!1,null);try{const ue=BA(f),[pe,ke]=await Promise.all([m.listTerminals(),m.getTerminalLayout()]),De=pe.terminals.length>0?pe.terminals:[(await m.createTerminal({cols:80,rows:24})).terminal];if(!T){const rt=ke.layout?Ow(ke.layout):null,ut=rt??ue??{},yi=zp(De,void 0,ut.savedWorkspaces,ut.savedActiveWorkspaceId),Fr=Cf(yi);rb(n,yi),Xc(n,ke.revision,JSON.stringify(Fr)),Ta(n,!0,null),!rt&&ue&&Ui(Fr,{baseRevision:ke.revision})}}catch(ue){!T&&!bt(ue)&&Ta(n,!0,Kl(ue))}}}return A(),()=>{T=!0}},[n,m]);async function Bs(){await Wt(async()=>{const T=await m.createTerminal({cols:80,rows:24});Ge({type:"terminal.created",terminal:T.terminal})})}async function Vs(T){await Wt(async()=>{const A=Ye?{parentTerminalId:Ye,cols:80,rows:24}:{cols:80,rows:24},K=await m.createTerminal(A);Ge({type:"terminal.split",terminal:K.terminal,direction:T})})}async function Ts(T){if(!Ye)throw new Error("No active pane is available.");const A=await m.readFile(T),K=`editor-${Date.now().toString(36)}-${zM(n)}`,ue=zA(A.path);ab(n,pe=>({...pe,[K]:{id:K,title:ue,rootToken:T.rootToken,path:A.path,read:A}})),xe&&ve(pe=>({...pe,[xe]:Lw(K)})),Ge({type:"editor.split",editorId:K,title:ue,direction:"vertical"})}function ks(T){ab(n,A=>{const K={...A};return delete K[T],K}),Ge({type:"editor.closed",editorId:T})}function ot(T){St([T])}function St(T){for(const A of T)Ge({type:"terminal.detached",terminalId:A})}async function Rt(T){await Wt(async()=>{await Bt(T),Ap(m.createWebSocketUrl(T)),$S(T),Ge({type:"terminal.closed",terminalId:T})})}async function li(T,A){const K=A.trim();if(!K)return;let ue=null;for(const pe of x.workspaces){const ke=pe.tabs.find(De=>De.id===T);if(ke){ue=ke.activeTerminalId;break}}if(Ge({type:"tab.renamed",tabId:T,title:K}),!!ue)try{const pe=await m.renameTerminal(ue,K);ct({type:"terminal.updated",terminal:pe.terminal})}catch(pe){Ta(n,!0,Kl(pe))}}function ei(T){const A=x.terminals[T];A&&Ge({type:"terminal.created",terminal:A})}async function Bt(T){try{await m.closeTerminal(T)}catch(A){if(A instanceof yn&&A.status===404)return;throw A}}async function nt(){await Wt(async()=>{await c()})}async function Wt(T){Ta(n,!0,null);try{await T()}catch(A){if(bt(A))return;Ta(n,!0,Kl(A))}}function bt(T){return T instanceof yn&&T.status===401&&!m.isAgent&&d?(d(),!0):!1}function Ge(T){Ul(n,T);const A=Ft(n),K=A.state;if(!A.loaded||K.workspaces.length===0)return;const ue=Cf(K);JSON.stringify(ue)!==A.lastPersistedLayoutJson&&Qi(ue)}function ct(T){Ul(n,T)}function vi(T,A,K,ue){const pe=ru(T,A,K);ve(ke=>({...ke,[pe]:ue}))}function Ai(T){xe&&ve(A=>({...A,[xe]:T}))}function Ni(T,A){const K=Cu(T);A?vi(n,A.workspaceId,A.tabId,K):Ai(K),Ge({type:"pane.selected",terminalId:T})}function ki(T){Ai(T.key),T.type==="terminal"&&Ge({type:"pane.selected",terminalId:T.terminalId})}function cs(T){if(I||T.isComposing||T.key==="Process"||EA(T.target))return;const A=bA(T);if(!A)return;if(T.preventDefault(),T.stopPropagation(),A.type==="server.previous"||A.type==="server.next"){gi(A.type==="server.next"?1:-1);return}const K=Ft(n).state,ue=K.workspaces.find(De=>De.id===K.activeWorkspaceId)??K.workspaces[0],pe=ue?.tabs.find(De=>De.id===ue.activeTabId)??ue?.tabs[0];if(A.type==="split"){if(!pe)return;Vs(A.direction);return}if(!ue||!pe)return;if(A.type==="tab.previous"||A.type==="tab.next"){const De=xA(ue.tabs,pe.id,A.type==="tab.next"?1:-1);De&&Ge({type:"tab.selected",tabId:De.id});return}if(A.type==="tab.index"){const De=ue.tabs[A.index-1];De&&Ge({type:"tab.selected",tabId:De.id});return}const ke=wA(pe.root,pe.activeTerminalId,A);ke&&Ni(ke,{workspaceId:ue.id,tabId:pe.id})}function gi(T){if(!a||j.length===0)return;const A=j.findIndex(ke=>mn(ke,n)),ue=((A===-1?0:A)+T+j.length)%j.length,pe=j[ue]??null;mn(pe,n)||a(pe)}function mt(T){ub(T.dataTransfer)&&(T.preventDefault(),T.dataTransfer.dropEffect="copy")}function Yt(T){if(!ub(T.dataTransfer))return;T.preventDefault();const A=LA(Ft(n).state),K=ee.current+1;if(ee.current=K,!A){hr({id:K,status:"failed",fileCount:0,message:"No active running terminal is available for upload."});return}hr({id:K,status:"queued",fileCount:0,terminalId:A.id,message:"Preparing upload..."}),us(K,A.id,T.dataTransfer)}async function us(T,A,K){try{const ue=await oA(K);if(ue.length===0)throw new Error("No files were found in the drop.");Xi(T,{id:T,status:"queued",fileCount:ue.length,message:"Queued"},{terminalId:A,files:ue})}catch(ue){Xi(T,{id:T,status:"failed",fileCount:0,message:Kl(ue)},{terminalId:A})}finally{xn()}}async function Xs(T){const A=te.current.find(ke=>ke.id===T);if(!A?.terminalId||!A.files||A.files.length===0)return;const K=A.terminalId,ue=A.files,pe=new AbortController;je.current=T,Xi(T,{id:T,status:"uploading",fileCount:ue.length,loaded:0,total:null,percent:null},{terminalId:K,files:ue,abortController:pe});try{const ke=await g2({terminalId:K,files:ue,signal:pe.signal,onProgress:yi=>{Xi(T,{id:T,status:"uploading",fileCount:ue.length,loaded:yi.loaded,total:yi.total,percent:yi.percent},{terminalId:K,files:ue,abortController:pe})}}),De=ke.failed>0?ke.uploaded>0?"partial":"failed":"success",rt=ke.failed>0?OA(ke):void 0,ut={id:T,status:De,fileCount:ue.length,response:ke};rt&&(ut.message=rt),Xi(T,ut,{terminalId:K,files:ue})}catch(ke){Xi(T,{id:T,status:"failed",fileCount:ue.length,message:pe.signal.aborted?"Upload canceled.":Kl(ke)},{terminalId:K,files:ue})}finally{je.current===T&&(je.current=null),xn()}}function xn(){if(je.current!==null)return;const T=te.current.find(A=>A.status==="queued");T?.terminalId&&T.files&&T.files.length>0&&Xs(T.id)}function hr(T){Gi(A=>[...A,T])}function Xi(T,A,K={}){Gi(ue=>ue.map(pe=>{if(pe.id!==T)return pe;const ke={...A},De=K.terminalId??pe.terminalId,rt=K.files??pe.files;return De!==void 0&&(ke.terminalId=De),rt!==void 0&&(ke.files=rt),K.abortController!==void 0&&(ke.abortController=K.abortController),ke}))}function Gi(T){const A=T(te.current);te.current=A,mi(A)}function En(T){te.current.find(K=>K.id===T)?.abortController?.abort(),je.current===T&&(je.current=null),Gi(K=>K.filter(ue=>ue.id!==T)),xn()}function Ls(){for(const T of te.current)T.abortController?.abort();je.current=null,Gi(()=>[])}function Os(T){const A=te.current.find(K=>K.id===T);if(A){if(A.status==="queued"){En(T);return}A.abortController?.abort()}}function Ds(T){const A=te.current.find(ue=>ue.id===T);if(!A?.terminalId||!A.files||A.files.length===0)return;const K=Zi(A);if(K.length===0){Xi(T,{id:T,status:"failed",fileCount:A.fileCount,message:"No failed files are available to retry."},{terminalId:A.terminalId,files:A.files});return}Xi(T,{id:T,status:"queued",fileCount:K.length,message:"Queued"},{terminalId:A.terminalId,files:K}),xn()}function Zi(T){const A=T.files??[],K="response"in T?T.response:void 0;if(!K)return A;const ue=K.results.filter(De=>De.status==="failed").map(De=>De.relativePath);if(ue.length===0)return[];const pe=new Map;for(const De of A){const rt=pe.get(De.relativePath)??[];rt.push(De),pe.set(De.relativePath,rt)}const ke=[];for(const De of ue){const ut=pe.get(De)?.shift();ut&&ke.push(ut)}return ke}function Lt(T){const K=Ft(T.agentId).state.workspaces.find(ue=>ue.tabs.some(pe=>pe.id===T.tabId));K&&vi(T.agentId,K.id,T.tabId,Cu(T.terminalId)),Ul(T.agentId,{type:"pane.selected",terminalId:T.terminalId}),OM(T.agentId,T.tabId),mn(T.agentId,n)||a?.(T.agentId),_i(null)}function Qi(T){const A=Ft(n).mutable.saveCoord;A.pendingLayoutSave=T,Pl(T,f),A.saveTimer!==null&&window.clearTimeout(A.saveTimer),A.saveTimer=window.setTimeout(()=>{A.saveTimer=null;const K=A.pendingLayoutSave;A.pendingLayoutSave=null,K&&Ui(K)},vA)}function Ir(){const T=Ft(n).mutable.saveCoord;T.saveTimer!==null&&(window.clearTimeout(T.saveTimer),T.saveTimer=null);const A=T.pendingLayoutSave;T.pendingLayoutSave=null,A&&(Pl(A,f),Ui(A))}function Ui(T,A={}){const K=Ft(n).mutable.saveCoord;K.nextPersistLayout=T,A.baseRevision!==void 0&&(K.queuedBaseRevision=A.baseRevision),!K.nextPersistQueued&&(K.nextPersistQueued=!0,K.persistChain=K.persistChain.then(async()=>{K.nextPersistQueued=!1;const ue=K.nextPersistLayout,pe=K.queuedBaseRevision;K.nextPersistLayout=null,K.queuedBaseRevision=void 0,ue&&await zs(ue,pe!==void 0?{baseRevision:pe}:{})}))}async function zs(T,A={}){const K=Ft(n),ue=A.baseRevision??K.layoutRevision,pe={layout:T,...typeof ue=="number"?{baseRevision:ue}:{}};try{const ke=await m.saveTerminalLayout(pe),De=ke.layout??T;Xc(n,ke.revision,JSON.stringify(De)),Pl(De,f);return}catch(ke){if(ke instanceof yn&&ke.status===409)try{const De=await m.getTerminalLayout();if(De.layout){const rt=Ft(n).state,ut=zp(Object.values(rt.terminals),void 0,De.layout.workspaces,De.layout.activeWorkspaceId),yi=Cf(ut);rb(n,ut),Xc(n,De.revision,JSON.stringify(yi)),Pl(yi,f)}else Xc(n,De.revision,K.lastPersistedLayoutJson);return}catch{}Pl(T,f)}}const O=UA(o),fe=!F||R,Oe=fe?ce:"servers";return _.jsx(dE,{sensors:me,onDragStart:Ce,onDragEnd:ze,onDragCancel:Ne,children:_.jsxs("main",{className:"terminal-shell","data-collapsed":F,"data-sidebar-open":R,onDragOver:mt,onDrop:Yt,children:[_.jsx("button",{type:"button",className:"workspace-backdrop","aria-label":"Close workspaces",onClick:()=>re(!1)}),_.jsxs("aside",{className:"workspace-sidebar",children:[_.jsxs("header",{className:"workspace-brand",children:[fe?_.jsx(Cb,{height:20}):_.jsx(wb,{size:24}),_.jsx("button",{type:"button",className:"sidebar-collapse-button","aria-label":F?"Expand sidebar":"Collapse sidebar",title:F?"Expand sidebar":"Collapse sidebar",onClick:()=>J(T=>!T),children:F?">":"<"}),_.jsx("button",{type:"button",className:"sidebar-drawer-close-button","aria-label":"Close workspaces",title:"Close workspaces",onClick:()=>re(!1),children:"x"})]}),_.jsxs("div",{className:"workspace-sidebar-content",children:[fe?_.jsxs("div",{className:"workspace-sidebar-tabs",role:"tablist","aria-label":"Sidebar mode",children:[_.jsx("button",{type:"button",role:"tab","aria-selected":ce==="servers",onClick:()=>{q("servers"),E(null)},children:"Servers"}),_.jsx("button",{type:"button",role:"tab","aria-selected":ce==="files",onClick:()=>{q("files"),E(null)},children:"Files"})]}):null,Oe==="servers"&&fe?_.jsx("nav",{className:"workspace-nav","aria-label":"Servers",children:_.jsx(ef,{api:p,activeAgentId:n,onSelectServer:a??(()=>{}),onSessionInvalid:d,refreshToken:H})}):null,fe?null:_.jsx("nav",{className:"workspace-nav workspace-nav--collapsed","aria-label":"Servers",children:_.jsx(ef,{api:p,activeAgentId:n,onSelectServer:a??(()=>{}),onSessionInvalid:d,refreshToken:H,compact:!0})}),Oe==="files"?_.jsxs(_.Fragment,{children:[fe?_.jsx("nav",{className:"workspace-nav workspace-nav--compact","aria-label":"Servers",children:_.jsx(ef,{api:p,activeAgentId:n,onSelectServer:a??(()=>{}),onSessionInvalid:d,refreshToken:H})}):null,_.jsx(C2,{api:m,activeTerminalId:Ye,activeTerminalCwd:Be?.cwd??null,onOpenFile:Ts})]}):null]}),fe?_.jsxs("div",{className:"workspace-sidebar-footer",children:[_.jsx("span",{children:O}),_.jsxs("div",{className:"workspace-sidebar-footer-actions",children:[_.jsxs("button",{type:"button",className:"workspace-footer-icon-button","aria-label":"settings",title:"Settings",onClick:()=>ie(!0),children:[_.jsx(pb,{name:"settings"}),de.hasUpdates?_.jsx("span",{className:"update-pulse-dot","aria-hidden":"true"}):null]}),_.jsx("button",{type:"button",className:"workspace-footer-icon-button","aria-label":"logout",title:"Logout",onClick:()=>{nt()},children:_.jsx(pb,{name:"logout"})})]})]}):null]}),I?_.jsx(_2,{api:p,onClose:()=>ie(!1),updateAvailable:de.hasUpdates,onNotificationAssetsChanged:()=>{Jt()},onAgentRemoved:Cn}):null,_.jsxs("section",{className:"terminal-main","aria-label":"Terminal workspace","data-mobile-pane-switcher":Xe?"true":void 0,children:[_.jsx(KM,{tabs:Re?.tabs??[],activeTabId:Re?.activeTabId??null,terminals:x.terminals,unreadCompletionTabIds:b.unreadCompletions,detachedTerminals:gt,onSelectTab:T=>Ge({type:"tab.selected",tabId:T}),onCreateTab:()=>{Bs()},onToggleWorkspaces:()=>re(T=>!T),onCloseTerminals:T=>St(T),onReattachTerminal:T=>ei(T),onDeleteTerminal:T=>{Rt(T)},onSplitVertical:()=>{Vs("vertical")},onSplitHorizontal:()=>{Vs("horizontal")},onRenameTab:(T,A)=>{li(T,A)},activePaneAvailable:!!Ye}),Xe?_.jsx(kA,{targets:Ee,activeLeafKey:Ke,terminals:x.terminals,editors:C,onSelect:ki}):null,B?_.jsx("div",{className:"workspace-error",children:B}):null,_.jsxs("section",{className:"workspace-body","aria-busy":k,children:[k?_.jsx("div",{className:"workspace-placeholder",children:"Opening shell..."}):null,!k&&!Pe?_.jsx(TA,{onCreate:()=>{Bs()}}):null,X.map(T=>{const A=mn(T,n);return _.jsx(SA,{agentId:T,active:A,activeServerApi:A?m:void 0,visitedTabKeys:M,refreshCwdOnEnter:A&&Oe==="files",draggingTab:A?he:null,mobileSplitFocus:ae,mobileFocusedLeafByTabKey:Q,onSelect:K=>{A&&Ni(K)},onClose:K=>{A&&ot(K)},onCloseEditor:K=>{A&&ks(K)},onResize:(K,ue)=>{A&&Ge({type:"pane.resized",path:K,ratio:ue})},onExit:(K,ue)=>{A?ct({type:"terminal.exited",terminalId:K,exitCode:ue}):Ul(T,{type:"terminal.exited",terminalId:K,exitCode:ue})},onSnapshot:(K,ue)=>{const pe={type:"terminal.updated",terminal:K,notifyCompletion:ue?.notifyCompletion===!0};A?ct(pe):Ul(T,pe)},...T===null&&d?{onAuthClose:d}:{}},nu(T))})]}),_.jsx(QM,{toast:He,onActivate:Lt,onDismiss:()=>_i(null)}),_.jsx(WM,{uploads:yt,onDismiss:En,onDismissAll:Ls,onRetry:Ds,onCancel:Os})]})]})})}function SA({agentId:e,active:t,activeServerApi:n,visitedTabKeys:a,refreshCwdOnEnter:o,draggingTab:c,mobileSplitFocus:d,mobileFocusedLeafByTabKey:p,onSelect:m,onClose:f,onCloseEditor:S,onResize:y,onExit:b,onSnapshot:x,onAuthClose:C}){const k=g.useMemo(()=>de=>Ew(e,de),[e]),B=g.useMemo(()=>()=>Ft(e),[e]),R=g.useSyncExternalStore(k,B,B),re=g.useMemo(()=>io(e),[e]),F=n??re,J=R.state,ce=J.workspaces.find(de=>de.id===J.activeWorkspaceId)??J.workspaces[0],q=ce?.id??null,ie=(ce?.tabs.find(de=>de.id===ce.activeTabId)??ce?.tabs[0])?.id??null;return!R.loaded||J.workspaces.length===0?null:_.jsx("div",{className:"workspace-server-surface","data-active":t,"aria-hidden":!t,children:J.workspaces.flatMap(de=>de.tabs.map(j=>{const $=t&&de.id===q&&j.id===ie,H=ru(e,de.id,j.id),L=wu(j.root),X=d&&L.length>1?Bw(L,j.activeTerminalId,p[H]):null;return!$&&!a.has(H)?null:_.jsx("div",{className:"workspace-tab-surface","data-active":$,"aria-hidden":!$,children:_.jsx(Bp,{node:j.root,terminals:J.terminals,editors:R.editors,api:F,activeTerminalId:j.activeTerminalId,visible:$,refreshCwdOnEnter:$&&o,tabId:j.id,dropZoneActive:$&&c!==null,draggingTerminalId:$?c?.terminalId??null:null,mobileFocusLeafKey:X,onSelect:m,onClose:f,onCloseEditor:S,onResize:y,onExit:b,onSnapshot:x,...C?{onAuthClose:C}:{}})},`${de.id}:${j.id}`)}))})}function bA(e){const t=WE(e);if(t)switch(t.id){case"server.previous":case"server.next":case"tab.previous":case"tab.next":return{type:t.id};case"tab.index":case"pane.index":return t.index===null?null:{type:t.id,index:t.index};case"split.right":return{type:"split",direction:"vertical"};case"split.down":return{type:"split",direction:"horizontal"};default:return null}if(e.ctrlKey&&e.altKey&&!e.metaKey&&!e.shiftKey){const n=CA(e.key);return n?{type:"pane.direction",direction:n}:null}return null}function wA(e,t,n){switch(n.type){case"pane.direction":return tA(e,t,n.direction);case"pane.index":return iA(e,n.index);default:return null}}function CA(e){switch(e){case"ArrowLeft":return"left";case"ArrowRight":return"right";case"ArrowUp":return"up";case"ArrowDown":return"down";default:return null}}function xA(e,t,n){if(e.length===0)return null;const a=e.findIndex(c=>c.id===t);return e[((a===-1?0:a)+n+e.length)%e.length]??null}function wu(e){return e.type==="pane"?[{key:Cu(e.terminalId),type:"terminal",terminalId:e.terminalId}]:e.type==="editor"?[{key:Lw(e.editorId),type:"editor",editorId:e.editorId,title:e.title}]:[...wu(e.first),...wu(e.second)]}function Bw(e,t,n){if(n&&e.some(o=>o.key===n))return n;const a=t?Cu(t):null;return a&&e.some(o=>o.key===a)?a:e[0]?.key??null}function Cu(e){return`terminal:${e}`}function Lw(e){return`editor:${e}`}function EA(e){if(!(e instanceof HTMLElement)||e.closest(".xterm"))return!1;if(e.closest('input, textarea, select, [role="textbox"]'))return!0;const t=e.closest("[contenteditable]");return t instanceof HTMLElement&&t.getAttribute("contenteditable")?.toLowerCase()!=="false"}function TA({onCreate:e}){return _.jsxs("div",{className:"empty-workspace",children:[_.jsx("span",{children:"No terminal is open."}),_.jsx("button",{type:"button",onClick:e,children:"New tab"})]})}function kA({targets:e,activeLeafKey:t,terminals:n,editors:a,onSelect:o}){const[c,d]=g.useState(!1);if(e.length<=1)return null;const p=t?e.findIndex(b=>b.key===t):-1,m=p>=0?p:0,f=e[m]??e[0],S=fb(f,n,a);function y(b){const x=(m+b+e.length)%e.length,C=e[x];C&&o(C)}return _.jsxs("div",{className:"mobile-pane-switcher",role:"group","aria-label":"Pane switcher",children:[_.jsx("button",{type:"button","aria-label":"Previous pane",onClick:()=>y(-1),children:"<"}),_.jsxs("button",{type:"button",className:"mobile-pane-current","aria-label":"Open pane switcher","aria-haspopup":"dialog","aria-expanded":c,title:S,onClick:()=>d(!0),children:["Pane ",m+1,"/",e.length," | ",S]}),_.jsx("button",{type:"button","aria-label":"Next pane",onClick:()=>y(1),children:">"}),c?_.jsx("div",{className:"mobile-pane-sheet-backdrop",onClick:()=>d(!1),children:_.jsxs("section",{className:"mobile-pane-sheet",role:"dialog","aria-modal":"true","aria-label":"Pane switcher",onClick:b=>b.stopPropagation(),children:[_.jsxs("header",{children:[_.jsx("strong",{children:"Panes"}),_.jsx("button",{type:"button","aria-label":"Close pane switcher",onClick:()=>d(!1),children:"x"})]}),_.jsx("div",{className:"mobile-pane-sheet-list",children:e.map((b,x)=>{const C=fb(b,n,a),k=DA(b,n,a),B=b.key===f.key;return _.jsxs("button",{type:"button","data-active":B,onClick:()=>{o(b),d(!1)},children:[_.jsx("span",{className:"mobile-pane-sheet-index",children:x+1}),_.jsxs("span",{className:"mobile-pane-sheet-copy",children:[_.jsx("strong",{children:C}),_.jsx("small",{children:k})]}),_.jsx("span",{className:"mobile-pane-sheet-type",children:b.type})]},b.key)})})]})}):null]})}function fb(e,t,n){if(e.type==="editor")return n[e.editorId]?.title||e.title||e.editorId;const a=t[e.terminalId];return a?.title||a?.cwd||e.terminalId}function DA(e,t,n){if(e.type==="editor"){const c=n[e.editorId];return c?.path?`editor | ${c.path}`:"editor"}const a=t[e.terminalId];return a?`${a.activity==="busy"?`busy${a.currentCommand?`: ${a.currentCommand}`:""}`:a.activity==="idle"?"idle":a.status} | ${a.cwd}`:"terminal"}function RA(e){const[t,n]=g.useState(()=>MA(e));return g.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function"){n(!1);return}const a=window.matchMedia(e),o=()=>n(a.matches);return o(),typeof a.addEventListener=="function"?(a.addEventListener("change",o),()=>a.removeEventListener("change",o)):(a.addListener(o),()=>a.removeListener(o))},[e]),t}function MA(e){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(e).matches}function mn(e,t){return e===t}function AA(e){const t=e.workspaces.find(a=>a.id===e.activeWorkspaceId)??e.workspaces[0];return(t?.tabs.find(a=>a.id===t.activeTabId)??t?.tabs[0])?.id??null}function nu(e){return e??"__local__"}function ru(e,t,n){return`${nu(e)}:${t}:${n}`}function NA(e){return e?{workspaceKey:`${hb}:${e}`}:{workspaceKey:hb}}function BA(e){const t=localStorage.getItem(e.workspaceKey);if(!t)return null;try{const n=JSON.parse(t),a=Wb(n);return a?Ow(a):null}catch{return null}}function Ow(e){const t=Wb(e);return t?{savedWorkspaces:t.workspaces,savedActiveWorkspaceId:t.activeWorkspaceId}:null}function Pl(e,t){if(e.workspaces.length>0){localStorage.setItem(t.workspaceKey,JSON.stringify(e));return}localStorage.removeItem(t.workspaceKey)}function LA(e){const t=e.workspaces.find(o=>o.id===e.activeWorkspaceId)??e.workspaces[0],n=t?.tabs.find(o=>o.id===t.activeTabId)??t?.tabs[0],a=n?e.terminals[n.activeTerminalId]:void 0;return a?.status==="running"?a:null}function OA(e){return e.results.find(t=>t.status==="failed"&&t.error)?.error}function zA(e){return e.split("/").filter(Boolean).pop()??e}function jA(){try{return localStorage.getItem(Nw)==="true"}catch{return!1}}function HA(e){try{localStorage.setItem(Nw,e?"true":"false")}catch{}}function UA(e){if(!e)return"session · local";const t=Date.parse(e);if(!Number.isFinite(t))return"session · local";const n=t-Date.now();if(n<=0)return"session · expired";const a=Math.max(1,Math.floor(n/6e4));return a<60?`session · ${a}m left`:`session · ${Math.floor(a/60)}h left`}function pb({name:e}){return _.jsxs("svg",{className:"workspace-footer-icon",viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[e==="settings"?_.jsxs(_.Fragment,{children:[_.jsx("path",{d:"M4 7h9"}),_.jsx("path",{d:"M17 7h3"}),_.jsx("circle",{cx:"15",cy:"7",r:"2"}),_.jsx("path",{d:"M4 12h3"}),_.jsx("path",{d:"M11 12h9"}),_.jsx("circle",{cx:"9",cy:"12",r:"2"}),_.jsx("path",{d:"M4 17h9"}),_.jsx("path",{d:"M17 17h3"}),_.jsx("circle",{cx:"15",cy:"17",r:"2"})]}):null,e==="logout"?_.jsxs(_.Fragment,{children:[_.jsx("path",{d:"M10 6H6v12h4"}),_.jsx("path",{d:"M13 8l4 4-4 4"}),_.jsx("path",{d:"M8 12h9"})]}):null]})}function Kl(e){return e instanceof Error?e.message:"Request failed"}function PA({api:e,onDone:t}){const[n,a]=g.useState(null),[o,c]=g.useState(null),[d,p]=g.useState(""),[m,f]=g.useState(!1),[S,y]=g.useState(null),[b,x]=g.useState(null);g.useEffect(()=>{let k=!1;return e.setupTotp().then(B=>{k||(a(B.qrDataUrl),c(B.secret))}).catch(B=>{k||x(B instanceof Error?B.message:"Failed to generate QR code")}),()=>{k=!0}},[e]);async function C(k){if(k.preventDefault(),!!o){f(!0),y(null);try{await e.activateTotp({secret:o,otp:d}),t()}catch(B){y(B instanceof Error?B.message:"Verification failed")}finally{f(!1)}}}return b?_.jsx("p",{className:"form-error",children:b}):!n||!o?_.jsx("p",{className:"muted",children:"Generating authenticator setup..."}):_.jsxs("div",{className:"totp-setup",children:[_.jsx("p",{className:"totp-setup-instructions",children:"Scan this QR code with an authenticator app (Google Authenticator, Authy, 1Password, etc.), then enter the 6-digit code to confirm."}),_.jsx("div",{className:"totp-qr-container",children:_.jsx("img",{src:n,alt:"TOTP QR code",width:192,height:192})}),_.jsxs("details",{className:"totp-secret-details",children:[_.jsx("summary",{children:"Can't scan? Enter manually"}),_.jsx("p",{className:"totp-secret-text",children:o})]}),_.jsxs("form",{className:"auth-form",onSubmit:C,children:[_.jsxs("label",{children:["Verification code",_.jsx("input",{autoFocus:!0,type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:d,onChange:k=>p(k.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}),S?_.jsx("p",{className:"form-error",children:S}):null,_.jsx("button",{type:"submit",disabled:m||d.length!==6,children:"Activate 2FA"})]})]})}function KA({api:e,serverApi:t,activeAgentId:n=null,onSelectServer:a}){const o=g.useMemo(()=>e??Eu(),[e]),c=g.useMemo(()=>t??io(null),[t]),[d,p]=g.useState(null),[m,f]=g.useState(null);g.useEffect(()=>{let C=!1;return o.getSession().then(k=>{C||(p(k),f(null))}).catch(k=>{C||(f(go(k)),p(null))}),()=>{C=!0}},[o]);const S=WA(d);async function y(){const C=await o.getSession();p(C),f(null)}async function b(){ZS(),lb(),iR(),f(null),p(null);try{await y()}catch(C){f(go(C))}}if(S==="workspace")return _.jsx(yA,{api:o,serverApi:c,activeAgentId:n,onSelectServer:a,sessionExpiresAt:d?.expiresAt??null,onSessionInvalid:()=>{b()},onLogout:async()=>{ZS(),lb();const C=await o.logout();p(C)}});const x={loading:"Terminal",setup_password:"Set password",setup_totp:"Set up 2FA",login:"Unlock terminal",reauth:"Verify it’s you",workspace:"Terminal"};return _.jsxs("main",{className:"auth-screen",children:[_.jsxs("div",{className:"auth-background","aria-hidden":"true",children:[_.jsx("div",{className:"auth-grid"}),_.jsx("div",{className:"auth-glow"})]}),_.jsxs("section",{className:"auth-panel","aria-busy":S==="loading",children:[_.jsxs("header",{className:"auth-header",children:[_.jsxs("div",{className:"auth-brand",children:[_.jsx(wb,{size:26}),_.jsxs("div",{children:[_.jsx(Cb,{height:17}),_.jsx("p",{className:"auth-host",children:"local terminal"})]})]}),_.jsx("h1",{children:x[S]})]}),m?_.jsx("p",{className:"form-error",children:m}):null,S==="loading"?_.jsx("p",{className:"muted",children:"Checking session..."}):null,S==="loading"&&m?_.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{b()},children:"Retry"}):null,S==="setup_password"?_.jsx(IA,{api:o,onSession:C=>{p(C)}}):null,S==="setup_totp"?_.jsx(PA,{api:o,onDone:()=>{y()}}):null,S==="login"?_.jsx(FA,{api:o,session:d,onSession:p,onRefresh:y}):null,S==="reauth"?_.jsx(qA,{api:o,session:d,onSession:p,onFullLogin:()=>p(C=>C&&{...C,deviceTrusted:!1})}):null]})]})}function IA({api:e,onSession:t}){const[n,a]=g.useState(""),[o,c]=g.useState(""),[d,p]=g.useState(!1),[m,f]=g.useState(null);async function S(y){y.preventDefault(),p(!0),f(null);try{if(n!==o){f("Passwords do not match");return}t(await e.setupPassword({password:n}))}catch(b){f(go(b))}finally{p(!1)}}return _.jsxs("form",{className:"auth-form",onSubmit:S,children:[_.jsxs("label",{children:["Password",_.jsx("input",{autoFocus:!0,value:n,onChange:y=>a(y.currentTarget.value),type:"password",minLength:8,required:!0})]}),_.jsxs("label",{children:["Confirm password",_.jsx("input",{value:o,onChange:y=>c(y.currentTarget.value),type:"password",minLength:8,required:!0})]}),m?_.jsx("p",{className:"form-error",children:m}):null,_.jsx("button",{type:"submit",disabled:d||n.length<8||o.length<8,children:"Set password"})]})}function FA({api:e,session:t,onSession:n,onRefresh:a}){const[o,c]=g.useState(""),[d,p]=g.useState(""),[m,f]=g.useState(!1),[S,y]=g.useState(!1),[b,x]=g.useState(null),C=t?.totpEnabled??!1,k=t?.currentIpWhitelisted??!1;async function B(R){R.preventDefault(),y(!0),x(null);try{n(await e.login({password:o,...C?{otp:d}:{},rememberNetwork:m}))}catch(re){x(go(re))}finally{y(!1)}}return _.jsxs("form",{className:"auth-form",onSubmit:B,children:[_.jsxs("label",{children:["Password",_.jsx("input",{autoFocus:!0,type:"password",value:o,onChange:R=>c(R.currentTarget.value),required:!0})]}),C?_.jsxs("label",{children:["Authenticator code",_.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:d,onChange:R=>p(R.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}):null,k?null:_.jsxs("label",{className:"auth-checkbox",children:[_.jsx("input",{type:"checkbox",checked:m,onChange:R=>f(R.currentTarget.checked)}),"Remember this network (skip 2FA here next time)"]}),b?_.jsx("p",{className:"form-error",children:b}):null,_.jsxs("div",{className:"button-row",children:[_.jsx("button",{type:"submit",disabled:S||o.length===0||C&&d.length!==6,children:"Unlock"}),_.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{a()},disabled:S,children:"Refresh"})]})]})}function qA({api:e,session:t,onSession:n,onFullLogin:a}){const o=t?.currentIpWhitelisted??!1,[c,d]=g.useState(""),[p,m]=g.useState(!1),[f,S]=g.useState(!1),[y,b]=g.useState(null),x=xi.useRef(!1),C=xi.useCallback(async(B,R)=>{S(!0),b(null);try{n(await e.reauth({...B?{otp:B}:{},rememberNetwork:R}))}catch(re){b(go(re))}finally{S(!1)}},[e,n]);g.useEffect(()=>{o&&!x.current&&(x.current=!0,C(void 0,!1))},[o,C]);async function k(B){B.preventDefault(),await C(c,p)}return o&&!y?_.jsx("p",{className:"muted",children:"Reconnecting from a trusted network…"}):_.jsxs("form",{className:"auth-form",onSubmit:k,children:[_.jsx("p",{className:"muted",children:"This device is remembered. Enter your authenticator code to continue."}),_.jsxs("label",{children:["Authenticator code",_.jsx("input",{autoFocus:!0,type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:c,onChange:B=>d(B.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}),_.jsxs("label",{className:"auth-checkbox",children:[_.jsx("input",{type:"checkbox",checked:p,onChange:B=>m(B.currentTarget.checked)}),"Remember this network (skip 2FA here next time)"]}),y?_.jsx("p",{className:"form-error",children:y}):null,_.jsxs("div",{className:"button-row",children:[_.jsx("button",{type:"submit",disabled:f||c.length!==6,children:"Continue"}),_.jsx("button",{type:"button",className:"secondary-button",onClick:a,disabled:f,children:"Use password instead"})]})]})}function WA(e){return e?e.passwordSet?e.authenticated&&!e.totpEnabled?"setup_totp":e.authenticated?"workspace":e.deviceTrusted&&e.totpEnabled?"reauth":"login":"setup_password":"loading"}function go(e){return e instanceof Error?e.message:"Request failed"}const mb="NTerminal",Wp="nterminal.activeAgentId";function YA(){const[e,t]=g.useState(()=>$A()),n=g.useMemo(()=>Eu(),[]),a=g.useMemo(()=>io(e),[e]);g.useEffect(()=>{const c=()=>{const d=LM();document.title=d>0?`(${d}) ${mb}`:mb};return c(),BM(c)},[]);function o(c){VA(c),t(c)}return _.jsx(KA,{api:n,activeAgentId:e,serverApi:a,onSelectServer:o})}function $A(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Wp);return e&&e.trim()?e:null}catch{return null}}function VA(e){if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(Wp,e);return}window.localStorage.removeItem(Wp)}catch{}}const _b=["gesturestart","gesturechange","gestureend"],XA=[".workspace-list",".terminal-tab-list",".mobile-terminal-key-bar",".upload-toast-body",".file-tree",".file-detail",".file-editor",".file-markdown-preview",".editor-markdown-preview"].join(",");function GA(e=window){if(!QA(e))return()=>{};const t={passive:!1},n=e.document;function a(c){c.cancelable&&c.preventDefault()}function o(c){if(c.defaultPrevented)return;const d=c.touches;!d||d.length===0||(d.length>1||!ZA(c.target))&&a(c)}for(const c of _b)n.addEventListener(c,a,t);return n.addEventListener("touchmove",o,t),n.addEventListener("dblclick",a,t),()=>{for(const c of _b)n.removeEventListener(c,a,t);n.removeEventListener("touchmove",o,t),n.removeEventListener("dblclick",a,t)}}function ZA(e){return e instanceof Element&&e.closest(XA)!==null}function QA(e){return e.navigator.maxTouchPoints>0?!0:typeof e.matchMedia=="function"&&e.matchMedia("(pointer: coarse)").matches}const vb="--nterminal-viewport-height",gb="--nterminal-keyboard-inset-bottom",yb="data-nterminal-keyboard-visible",JA=120;function eN(e=window){const t=e.document.documentElement,n=e.visualViewport;function a(){const o=tN(e);o!==null&&t.style.setProperty(vb,`${o}px`),t.style.setProperty(gb,`${zw(e)}px`),t.setAttribute(yb,String(iN(e)))}return a(),n?.addEventListener("resize",a),n?.addEventListener("scroll",a),e.addEventListener("resize",a),e.addEventListener("orientationchange",a),e.addEventListener("pageshow",a),e.document.addEventListener("visibilitychange",a),()=>{n?.removeEventListener("resize",a),n?.removeEventListener("scroll",a),e.removeEventListener("resize",a),e.removeEventListener("orientationchange",a),e.removeEventListener("pageshow",a),e.document.removeEventListener("visibilitychange",a),t.style.removeProperty(vb),t.style.removeProperty(gb),t.removeAttribute(yb)}}function tN(e){const t=e.visualViewport?.height;return xu(t)?t:xu(e.innerHeight)?e.innerHeight:null}function xu(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function iN(e){return zw(e)>JA}function zw(e){const t=e.visualViewport?.height;if(!xu(t)||!xu(e.innerHeight))return 0;const n=typeof e.visualViewport?.offsetTop=="number"?e.visualViewport.offsetTop:0;return Math.max(0,Math.round(e.innerHeight-t-n))}eN();GA();pm();ZC.createRoot(document.getElementById("root")).render(_.jsx(xi.StrictMode,{children:_.jsx(YA,{})}));export{IC as g,_ as j};