nterminal 1.2.59 → 1.2.60

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.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownPreview-BqsqJZK7.js","assets/index-D4qe1kk0.js","assets/TranscriptMarkdownBody-hbar9gNN.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownPreview-jgdUGtLt.js","assets/index-DuPhXutl.js","assets/TranscriptMarkdownBody-J4Bk7GDH.js"])))=>i.map(i=>d[i]);
2
2
  (function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const c of o)if(c.type==="childList")for(const h of c.addedNodes)h.tagName==="LINK"&&h.rel==="modulepreload"&&r(h)}).observe(document,{childList:!0,subtree:!0});function s(o){const c={};return o.integrity&&(c.integrity=o.integrity),o.referrerPolicy&&(c.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?c.credentials="include":o.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function r(o){if(o.ep)return;o.ep=!0;const c=s(o);fetch(o.href,c)}})();function eE(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Nf={exports:{}},bo={};var oy;function tE(){if(oy)return bo;oy=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function s(r,o,c){var h=null;if(c!==void 0&&(h=""+c),o.key!==void 0&&(h=""+o.key),"key"in o){c={};for(var f in o)f!=="key"&&(c[f]=o[f])}else c=o;return o=c.ref,{$$typeof:e,type:r,key:h,ref:o!==void 0?o:null,props:c}}return bo.Fragment=t,bo.jsx=s,bo.jsxs=s,bo}var cy;function iE(){return cy||(cy=1,Nf.exports=tE()),Nf.exports}var m=iE(),Af={exports:{}},Ve={};var uy;function nE(){if(uy)return Ve;uy=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),h=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),b=Symbol.for("react.activity"),w=Symbol.iterator;function S(R){return R===null||typeof R!="object"?null:(R=w&&R[w]||R["@@iterator"],typeof R=="function"?R:null)}var E={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},T=Object.assign,A={};function O(R,H,Q){this.props=R,this.context=H,this.refs=A,this.updater=Q||E}O.prototype.isReactComponent={},O.prototype.setState=function(R,H){if(typeof R!="object"&&typeof R!="function"&&R!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,R,H,"setState")},O.prototype.forceUpdate=function(R){this.updater.enqueueForceUpdate(this,R,"forceUpdate")};function L(){}L.prototype=O.prototype;function U(R,H,Q){this.props=R,this.context=H,this.refs=A,this.updater=Q||E}var I=U.prototype=new L;I.constructor=U,T(I,O.prototype),I.isPureReactComponent=!0;var te=Array.isArray;function ee(){}var ae={H:null,A:null,T:null,S:null},ue=Object.prototype.hasOwnProperty;function be(R,H,Q){var de=Q.ref;return{$$typeof:e,type:R,key:H,ref:de!==void 0?de:null,props:Q}}function we(R,H){return be(R.type,H,R.props)}function ne(R){return typeof R=="object"&&R!==null&&R.$$typeof===e}function ie(R){var H={"=":"=0",":":"=2"};return"$"+R.replace(/[=:]/g,function(Q){return H[Q]})}var Y=/\/+/g;function K(R,H){return typeof R=="object"&&R!==null&&R.key!=null?ie(""+R.key):H.toString(36)}function re(R){switch(R.status){case"fulfilled":return R.value;case"rejected":throw R.reason;default:switch(typeof R.status=="string"?R.then(ee,ee):(R.status="pending",R.then(function(H){R.status==="pending"&&(R.status="fulfilled",R.value=H)},function(H){R.status==="pending"&&(R.status="rejected",R.reason=H)})),R.status){case"fulfilled":return R.value;case"rejected":throw R.reason}}throw R}function B(R,H,Q,de,ke){var xe=typeof R;(xe==="undefined"||xe==="boolean")&&(R=null);var Re=!1;if(R===null)Re=!0;else switch(xe){case"bigint":case"string":case"number":Re=!0;break;case"object":switch(R.$$typeof){case e:case t:Re=!0;break;case y:return Re=R._init,B(Re(R._payload),H,Q,de,ke)}}if(Re)return ke=ke(R),Re=de===""?"."+K(R,0):de,te(ke)?(Q="",Re!=null&&(Q=Re.replace(Y,"$&/")+"/"),B(ke,H,Q,"",function(G){return G})):ke!=null&&(ne(ke)&&(ke=we(ke,Q+(ke.key==null||R&&R.key===ke.key?"":(""+ke.key).replace(Y,"$&/")+"/")+Re)),H.push(ke)),1;Re=0;var Xe=de===""?".":de+":";if(te(R))for(var ge=0;ge<R.length;ge++)de=R[ge],xe=Xe+K(de,ge),Re+=B(de,H,Q,xe,ke);else if(ge=S(R),typeof ge=="function")for(R=ge.call(R),ge=0;!(de=R.next()).done;)de=de.value,xe=Xe+K(de,ge++),Re+=B(de,H,Q,xe,ke);else if(xe==="object"){if(typeof R.then=="function")return B(re(R),H,Q,de,ke);throw H=String(R),Error("Objects are not valid as a React child (found: "+(H==="[object Object]"?"object with keys {"+Object.keys(R).join(", ")+"}":H)+"). If you meant to render a collection of children, use an array instead.")}return Re}function $(R,H,Q){if(R==null)return R;var de=[],ke=0;return B(R,de,"","",function(xe){return H.call(Q,xe,ke++)}),de}function D(R){if(R._status===-1){var H=R._result;H=H(),H.then(function(Q){(R._status===0||R._status===-1)&&(R._status=1,R._result=Q)},function(Q){(R._status===0||R._status===-1)&&(R._status=2,R._result=Q)}),R._status===-1&&(R._status=0,R._result=H)}if(R._status===1)return R._result.default;throw R._result}var X=typeof reportError=="function"?reportError:function(R){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var H=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof R=="object"&&R!==null&&typeof R.message=="string"?String(R.message):String(R),error:R});if(!window.dispatchEvent(H))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",R);return}console.error(R)},_e={map:$,forEach:function(R,H,Q){$(R,function(){H.apply(this,arguments)},Q)},count:function(R){var H=0;return $(R,function(){H++}),H},toArray:function(R){return $(R,function(H){return H})||[]},only:function(R){if(!ne(R))throw Error("React.Children.only expected to receive a single React element child.");return R}};return Ve.Activity=b,Ve.Children=_e,Ve.Component=O,Ve.Fragment=s,Ve.Profiler=o,Ve.PureComponent=U,Ve.StrictMode=r,Ve.Suspense=g,Ve.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=ae,Ve.__COMPILER_RUNTIME={__proto__:null,c:function(R){return ae.H.useMemoCache(R)}},Ve.cache=function(R){return function(){return R.apply(null,arguments)}},Ve.cacheSignal=function(){return null},Ve.cloneElement=function(R,H,Q){if(R==null)throw Error("The argument must be a React element, but you passed "+R+".");var de=T({},R.props),ke=R.key;if(H!=null)for(xe in H.key!==void 0&&(ke=""+H.key),H)!ue.call(H,xe)||xe==="key"||xe==="__self"||xe==="__source"||xe==="ref"&&H.ref===void 0||(de[xe]=H[xe]);var xe=arguments.length-2;if(xe===1)de.children=Q;else if(1<xe){for(var Re=Array(xe),Xe=0;Xe<xe;Xe++)Re[Xe]=arguments[Xe+2];de.children=Re}return be(R.type,ke,de)},Ve.createContext=function(R){return R={$$typeof:h,_currentValue:R,_currentValue2:R,_threadCount:0,Provider:null,Consumer:null},R.Provider=R,R.Consumer={$$typeof:c,_context:R},R},Ve.createElement=function(R,H,Q){var de,ke={},xe=null;if(H!=null)for(de in H.key!==void 0&&(xe=""+H.key),H)ue.call(H,de)&&de!=="key"&&de!=="__self"&&de!=="__source"&&(ke[de]=H[de]);var Re=arguments.length-2;if(Re===1)ke.children=Q;else if(1<Re){for(var Xe=Array(Re),ge=0;ge<Re;ge++)Xe[ge]=arguments[ge+2];ke.children=Xe}if(R&&R.defaultProps)for(de in Re=R.defaultProps,Re)ke[de]===void 0&&(ke[de]=Re[de]);return be(R,xe,ke)},Ve.createRef=function(){return{current:null}},Ve.forwardRef=function(R){return{$$typeof:f,render:R}},Ve.isValidElement=ne,Ve.lazy=function(R){return{$$typeof:y,_payload:{_status:-1,_result:R},_init:D}},Ve.memo=function(R,H){return{$$typeof:p,type:R,compare:H===void 0?null:H}},Ve.startTransition=function(R){var H=ae.T,Q={};ae.T=Q;try{var de=R(),ke=ae.S;ke!==null&&ke(Q,de),typeof de=="object"&&de!==null&&typeof de.then=="function"&&de.then(ee,X)}catch(xe){X(xe)}finally{H!==null&&Q.types!==null&&(H.types=Q.types),ae.T=H}},Ve.unstable_useCacheRefresh=function(){return ae.H.useCacheRefresh()},Ve.use=function(R){return ae.H.use(R)},Ve.useActionState=function(R,H,Q){return ae.H.useActionState(R,H,Q)},Ve.useCallback=function(R,H){return ae.H.useCallback(R,H)},Ve.useContext=function(R){return ae.H.useContext(R)},Ve.useDebugValue=function(){},Ve.useDeferredValue=function(R,H){return ae.H.useDeferredValue(R,H)},Ve.useEffect=function(R,H){return ae.H.useEffect(R,H)},Ve.useEffectEvent=function(R){return ae.H.useEffectEvent(R)},Ve.useId=function(){return ae.H.useId()},Ve.useImperativeHandle=function(R,H,Q){return ae.H.useImperativeHandle(R,H,Q)},Ve.useInsertionEffect=function(R,H){return ae.H.useInsertionEffect(R,H)},Ve.useLayoutEffect=function(R,H){return ae.H.useLayoutEffect(R,H)},Ve.useMemo=function(R,H){return ae.H.useMemo(R,H)},Ve.useOptimistic=function(R,H){return ae.H.useOptimistic(R,H)},Ve.useReducer=function(R,H,Q){return ae.H.useReducer(R,H,Q)},Ve.useRef=function(R){return ae.H.useRef(R)},Ve.useState=function(R){return ae.H.useState(R)},Ve.useSyncExternalStore=function(R,H,Q){return ae.H.useSyncExternalStore(R,H,Q)},Ve.useTransition=function(){return ae.H.useTransition()},Ve.version="19.2.6",Ve}var hy;function Um(){return hy||(hy=1,Af.exports=nE()),Af.exports}var v=Um();const Si=eE(v);var Lf={exports:{}},yo={},Bf={exports:{}},Of={};var dy;function sE(){return dy||(dy=1,(function(e){function t(B,$){var D=B.length;B.push($);e:for(;0<D;){var X=D-1>>>1,_e=B[X];if(0<o(_e,$))B[X]=$,B[D]=_e,D=X;else break e}}function s(B){return B.length===0?null:B[0]}function r(B){if(B.length===0)return null;var $=B[0],D=B.pop();if(D!==$){B[0]=D;e:for(var X=0,_e=B.length,R=_e>>>1;X<R;){var H=2*(X+1)-1,Q=B[H],de=H+1,ke=B[de];if(0>o(Q,D))de<_e&&0>o(ke,Q)?(B[X]=ke,B[de]=D,X=de):(B[X]=Q,B[H]=D,X=H);else if(de<_e&&0>o(ke,D))B[X]=ke,B[de]=D,X=de;else break e}}return $}function o(B,$){var D=B.sortIndex-$.sortIndex;return D!==0?D:B.id-$.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var c=performance;e.unstable_now=function(){return c.now()}}else{var h=Date,f=h.now();e.unstable_now=function(){return h.now()-f}}var g=[],p=[],y=1,b=null,w=3,S=!1,E=!1,T=!1,A=!1,O=typeof setTimeout=="function"?setTimeout:null,L=typeof clearTimeout=="function"?clearTimeout:null,U=typeof setImmediate<"u"?setImmediate:null;function I(B){for(var $=s(p);$!==null;){if($.callback===null)r(p);else if($.startTime<=B)r(p),$.sortIndex=$.expirationTime,t(g,$);else break;$=s(p)}}function te(B){if(T=!1,I(B),!E)if(s(g)!==null)E=!0,ee||(ee=!0,ie());else{var $=s(p);$!==null&&re(te,$.startTime-B)}}var ee=!1,ae=-1,ue=5,be=-1;function we(){return A?!0:!(e.unstable_now()-be<ue)}function ne(){if(A=!1,ee){var B=e.unstable_now();be=B;var $=!0;try{e:{E=!1,T&&(T=!1,L(ae),ae=-1),S=!0;var D=w;try{t:{for(I(B),b=s(g);b!==null&&!(b.expirationTime>B&&we());){var X=b.callback;if(typeof X=="function"){b.callback=null,w=b.priorityLevel;var _e=X(b.expirationTime<=B);if(B=e.unstable_now(),typeof _e=="function"){b.callback=_e,I(B),$=!0;break t}b===s(g)&&r(g),I(B)}else r(g);b=s(g)}if(b!==null)$=!0;else{var R=s(p);R!==null&&re(te,R.startTime-B),$=!1}}break e}finally{b=null,w=D,S=!1}$=void 0}}finally{$?ie():ee=!1}}}var ie;if(typeof U=="function")ie=function(){U(ne)};else if(typeof MessageChannel<"u"){var Y=new MessageChannel,K=Y.port2;Y.port1.onmessage=ne,ie=function(){K.postMessage(null)}}else ie=function(){O(ne,0)};function re(B,$){ae=O(function(){B(e.unstable_now())},$)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(B){B.callback=null},e.unstable_forceFrameRate=function(B){0>B||125<B?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):ue=0<B?Math.floor(1e3/B):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function(B){switch(w){case 1:case 2:case 3:var $=3;break;default:$=w}var D=w;w=$;try{return B()}finally{w=D}},e.unstable_requestPaint=function(){A=!0},e.unstable_runWithPriority=function(B,$){switch(B){case 1:case 2:case 3:case 4:case 5:break;default:B=3}var D=w;w=B;try{return $()}finally{w=D}},e.unstable_scheduleCallback=function(B,$,D){var X=e.unstable_now();switch(typeof D=="object"&&D!==null?(D=D.delay,D=typeof D=="number"&&0<D?X+D:X):D=X,B){case 1:var _e=-1;break;case 2:_e=250;break;case 5:_e=1073741823;break;case 4:_e=1e4;break;default:_e=5e3}return _e=D+_e,B={id:y++,callback:$,priorityLevel:B,startTime:D,expirationTime:_e,sortIndex:-1},D>X?(B.sortIndex=D,t(p,B),s(g)===null&&B===s(p)&&(T?(L(ae),ae=-1):T=!0,re(te,D-X))):(B.sortIndex=_e,t(g,B),E||S||(E=!0,ee||(ee=!0,ie()))),B},e.unstable_shouldYield=we,e.unstable_wrapCallback=function(B){var $=w;return function(){var D=w;w=$;try{return B.apply(this,arguments)}finally{w=D}}}})(Of)),Of}var fy;function rE(){return fy||(fy=1,Bf.exports=sE()),Bf.exports}var zf={exports:{}},Xi={};var py;function aE(){if(py)return Xi;py=1;var e=Um();function t(g){var p="https://react.dev/errors/"+g;if(1<arguments.length){p+="?args[]="+encodeURIComponent(arguments[1]);for(var y=2;y<arguments.length;y++)p+="&args[]="+encodeURIComponent(arguments[y])}return"Minified React error #"+g+"; visit "+p+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(){}var r={d:{f:s,r:function(){throw Error(t(522))},D:s,C:s,L:s,m:s,X:s,S:s,M:s},p:0,findDOMNode:null},o=Symbol.for("react.portal");function c(g,p,y){var b=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:o,key:b==null?null:""+b,children:g,containerInfo:p,implementation:y}}var h=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function f(g,p){if(g==="font")return"";if(typeof p=="string")return p==="use-credentials"?p:""}return Xi.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Xi.createPortal=function(g,p){var y=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!p||p.nodeType!==1&&p.nodeType!==9&&p.nodeType!==11)throw Error(t(299));return c(g,p,null,y)},Xi.flushSync=function(g){var p=h.T,y=r.p;try{if(h.T=null,r.p=2,g)return g()}finally{h.T=p,r.p=y,r.d.f()}},Xi.preconnect=function(g,p){typeof g=="string"&&(p?(p=p.crossOrigin,p=typeof p=="string"?p==="use-credentials"?p:"":void 0):p=null,r.d.C(g,p))},Xi.prefetchDNS=function(g){typeof g=="string"&&r.d.D(g)},Xi.preinit=function(g,p){if(typeof g=="string"&&p&&typeof p.as=="string"){var y=p.as,b=f(y,p.crossOrigin),w=typeof p.integrity=="string"?p.integrity:void 0,S=typeof p.fetchPriority=="string"?p.fetchPriority:void 0;y==="style"?r.d.S(g,typeof p.precedence=="string"?p.precedence:void 0,{crossOrigin:b,integrity:w,fetchPriority:S}):y==="script"&&r.d.X(g,{crossOrigin:b,integrity:w,fetchPriority:S,nonce:typeof p.nonce=="string"?p.nonce:void 0})}},Xi.preinitModule=function(g,p){if(typeof g=="string")if(typeof p=="object"&&p!==null){if(p.as==null||p.as==="script"){var y=f(p.as,p.crossOrigin);r.d.M(g,{crossOrigin:y,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0})}}else p==null&&r.d.M(g)},Xi.preload=function(g,p){if(typeof g=="string"&&typeof p=="object"&&p!==null&&typeof p.as=="string"){var y=p.as,b=f(y,p.crossOrigin);r.d.L(g,y,{crossOrigin:b,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0,type:typeof p.type=="string"?p.type:void 0,fetchPriority:typeof p.fetchPriority=="string"?p.fetchPriority:void 0,referrerPolicy:typeof p.referrerPolicy=="string"?p.referrerPolicy:void 0,imageSrcSet:typeof p.imageSrcSet=="string"?p.imageSrcSet:void 0,imageSizes:typeof p.imageSizes=="string"?p.imageSizes:void 0,media:typeof p.media=="string"?p.media:void 0})}},Xi.preloadModule=function(g,p){if(typeof g=="string")if(p){var y=f(p.as,p.crossOrigin);r.d.m(g,{as:typeof p.as=="string"&&p.as!=="script"?p.as:void 0,crossOrigin:y,integrity:typeof p.integrity=="string"?p.integrity:void 0})}else r.d.m(g)},Xi.requestFormReset=function(g){r.d.r(g)},Xi.unstable_batchedUpdates=function(g,p){return g(p)},Xi.useFormState=function(g,p,y){return h.H.useFormState(g,p,y)},Xi.useFormStatus=function(){return h.H.useHostTransitionStatus()},Xi.version="19.2.6",Xi}var my;function v0(){if(my)return zf.exports;my=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),zf.exports=aE(),zf.exports}var gy;function lE(){if(gy)return yo;gy=1;var e=rE(),t=Um(),s=v0();function r(i){var n="https://react.dev/errors/"+i;if(1<arguments.length){n+="?args[]="+encodeURIComponent(arguments[1]);for(var a=2;a<arguments.length;a++)n+="&args[]="+encodeURIComponent(arguments[a])}return"Minified React error #"+i+"; visit "+n+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function o(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function c(i){var n=i,a=i;if(i.alternate)for(;n.return;)n=n.return;else{i=n;do n=i,(n.flags&4098)!==0&&(a=n.return),i=n.return;while(i)}return n.tag===3?a:null}function h(i){if(i.tag===13){var n=i.memoizedState;if(n===null&&(i=i.alternate,i!==null&&(n=i.memoizedState)),n!==null)return n.dehydrated}return null}function f(i){if(i.tag===31){var n=i.memoizedState;if(n===null&&(i=i.alternate,i!==null&&(n=i.memoizedState)),n!==null)return n.dehydrated}return null}function g(i){if(c(i)!==i)throw Error(r(188))}function p(i){var n=i.alternate;if(!n){if(n=c(i),n===null)throw Error(r(188));return n!==i?null:i}for(var a=i,l=n;;){var u=a.return;if(u===null)break;var d=u.alternate;if(d===null){if(l=u.return,l!==null){a=l;continue}break}if(u.child===d.child){for(d=u.child;d;){if(d===a)return g(u),i;if(d===l)return g(u),n;d=d.sibling}throw Error(r(188))}if(a.return!==l.return)a=u,l=d;else{for(var _=!1,C=u.child;C;){if(C===a){_=!0,a=u,l=d;break}if(C===l){_=!0,l=u,a=d;break}C=C.sibling}if(!_){for(C=d.child;C;){if(C===a){_=!0,a=d,l=u;break}if(C===l){_=!0,l=d,a=u;break}C=C.sibling}if(!_)throw Error(r(189))}}if(a.alternate!==l)throw Error(r(190))}if(a.tag!==3)throw Error(r(188));return a.stateNode.current===a?i:n}function y(i){var n=i.tag;if(n===5||n===26||n===27||n===6)return i;for(i=i.child;i!==null;){if(n=y(i),n!==null)return n;i=i.sibling}return null}var b=Object.assign,w=Symbol.for("react.element"),S=Symbol.for("react.transitional.element"),E=Symbol.for("react.portal"),T=Symbol.for("react.fragment"),A=Symbol.for("react.strict_mode"),O=Symbol.for("react.profiler"),L=Symbol.for("react.consumer"),U=Symbol.for("react.context"),I=Symbol.for("react.forward_ref"),te=Symbol.for("react.suspense"),ee=Symbol.for("react.suspense_list"),ae=Symbol.for("react.memo"),ue=Symbol.for("react.lazy"),be=Symbol.for("react.activity"),we=Symbol.for("react.memo_cache_sentinel"),ne=Symbol.iterator;function ie(i){return i===null||typeof i!="object"?null:(i=ne&&i[ne]||i["@@iterator"],typeof i=="function"?i:null)}var Y=Symbol.for("react.client.reference");function K(i){if(i==null)return null;if(typeof i=="function")return i.$$typeof===Y?null:i.displayName||i.name||null;if(typeof i=="string")return i;switch(i){case T:return"Fragment";case O:return"Profiler";case A:return"StrictMode";case te:return"Suspense";case ee:return"SuspenseList";case be:return"Activity"}if(typeof i=="object")switch(i.$$typeof){case E:return"Portal";case U:return i.displayName||"Context";case L:return(i._context.displayName||"Context")+".Consumer";case I:var n=i.render;return i=i.displayName,i||(i=n.displayName||n.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case ae:return n=i.displayName||null,n!==null?n:K(i.type)||"Memo";case ue:n=i._payload,i=i._init;try{return K(i(n))}catch{}}return null}var re=Array.isArray,B=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,$=s.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,D={pending:!1,data:null,method:null,action:null},X=[],_e=-1;function R(i){return{current:i}}function H(i){0>_e||(i.current=X[_e],X[_e]=null,_e--)}function Q(i,n){_e++,X[_e]=i.current,i.current=n}var de=R(null),ke=R(null),xe=R(null),Re=R(null);function Xe(i,n){switch(Q(xe,n),Q(ke,i),Q(de,null),n.nodeType){case 9:case 11:i=(i=n.documentElement)&&(i=i.namespaceURI)?Nb(i):0;break;default:if(i=n.tagName,n=n.namespaceURI)n=Nb(n),i=Ab(n,i);else switch(i){case"svg":i=1;break;case"math":i=2;break;default:i=0}}H(de),Q(de,i)}function ge(){H(de),H(ke),H(xe)}function G(i){i.memoizedState!==null&&Q(Re,i);var n=de.current,a=Ab(n,i.type);n!==a&&(Q(ke,i),Q(de,a))}function ce(i){ke.current===i&&(H(de),H(ke)),Re.current===i&&(H(Re),mo._currentValue=D)}var Ce,ye;function De(i){if(Ce===void 0)try{throw Error()}catch(a){var n=a.stack.trim().match(/\n( *(at )?)/);Ce=n&&n[1]||"",ye=-1<a.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<a.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+Ce+i+ye}var Be=!1;function Ke(i,n){if(!i||Be)return"";Be=!0;var a=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var l={DetermineComponentFrameRoot:function(){try{if(n){var fe=function(){throw Error()};if(Object.defineProperty(fe.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(fe,[])}catch(Z){var V=Z}Reflect.construct(i,[],fe)}else{try{fe.call()}catch(Z){V=Z}i.call(fe.prototype)}}else{try{throw Error()}catch(Z){V=Z}(fe=i())&&typeof fe.catch=="function"&&fe.catch(function(){})}}catch(Z){if(Z&&V&&typeof Z.stack=="string")return[Z.stack,V.stack]}return[null,null]}};l.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var u=Object.getOwnPropertyDescriptor(l.DetermineComponentFrameRoot,"name");u&&u.configurable&&Object.defineProperty(l.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var d=l.DetermineComponentFrameRoot(),_=d[0],C=d[1];if(_&&C){var N=_.split(`
@@ -12,7 +12,7 @@ Error generating stack: `+l.message+`
12
12
  While dragging, use the arrow keys to move the item.
13
13
  Press space again to drop the item in its new position, or press escape to cancel.
14
14
  `},TE={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:s}=e;return s?"Draggable item "+t.id+" was moved over droppable area "+s.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:s}=e;return s?"Draggable item "+t.id+" was dropped over droppable area "+s.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function DE(e){let{announcements:t=TE,container:s,hiddenTextDescribedById:r,screenReaderInstructions:o=kE}=e;const{announce:c,announcement:h}=CE(),f=gh("DndLiveRegion"),[g,p]=v.useState(!1);if(v.useEffect(()=>{p(!0)},[]),xE(v.useMemo(()=>({onDragStart(b){let{active:w}=b;c(t.onDragStart({active:w}))},onDragMove(b){let{active:w,over:S}=b;t.onDragMove&&c(t.onDragMove({active:w,over:S}))},onDragOver(b){let{active:w,over:S}=b;c(t.onDragOver({active:w,over:S}))},onDragEnd(b){let{active:w,over:S}=b;c(t.onDragEnd({active:w,over:S}))},onDragCancel(b){let{active:w,over:S}=b;c(t.onDragCancel({active:w,over:S}))}}),[c,t])),!g)return null;const y=Si.createElement(Si.Fragment,null,Si.createElement(SE,{id:r,value:o.draggable}),Si.createElement(wE,{id:f,announcement:h}));return s?Ao.createPortal(y,s):y}var yi;(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"})(yi||(yi={}));function Gu(){}function Sy(e,t){return v.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function RE(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];return v.useMemo(()=>[...t].filter(r=>r!=null),[...t])}const hs=Object.freeze({x:0,y:0});function ME(e,t){let{data:{value:s}}=e,{data:{value:r}}=t;return r-s}function NE(e,t){if(!e||e.length===0)return null;const[s]=e;return s[t]}function AE(e,t){const s=Math.max(t.top,e.top),r=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),h=o-r,f=c-s;if(r<o&&s<c){const g=t.width*t.height,p=e.width*e.height,y=h*f,b=y/(g+p-y);return Number(b.toFixed(4))}return 0}const LE=e=>{let{collisionRect:t,droppableRects:s,droppableContainers:r}=e;const o=[];for(const c of r){const{id:h}=c,f=s.get(h);if(f){const g=AE(f,t);g>0&&o.push({id:h,data:{droppableContainer:c,value:g}})}}return o.sort(ME)};function BE(e,t,s){return{...e,scaleX:t&&s?t.width/s.width:1,scaleY:t&&s?t.height/s.height:1}}function D0(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:hs}function OE(e){return function(s){for(var r=arguments.length,o=new Array(r>1?r-1:0),c=1;c<r;c++)o[c-1]=arguments[c];return o.reduce((h,f)=>({...h,top:h.top+e*f.y,bottom:h.bottom+e*f.y,left:h.left+e*f.x,right:h.right+e*f.x}),{...s})}}const zE=OE(1);function jE(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 HE(e,t,s){const r=jE(t);if(!r)return e;const{scaleX:o,scaleY:c,x:h,y:f}=r,g=e.left-h-(1-o)*parseFloat(s),p=e.top-f-(1-c)*parseFloat(s.slice(s.indexOf(" ")+1)),y=o?e.width/o:e.width,b=c?e.height/c:e.height;return{width:y,height:b,top:p,right:g+y,bottom:p+b,left:g}}const PE={ignoreTransform:!1};function hc(e,t){t===void 0&&(t=PE);let s=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:p,transformOrigin:y}=pn(e).getComputedStyle(e);p&&(s=HE(s,p,y))}const{top:r,left:o,width:c,height:h,bottom:f,right:g}=s;return{top:r,left:o,width:c,height:h,bottom:f,right:g}}function wy(e){return hc(e,{ignoreTransform:!0})}function UE(e){const t=e.innerWidth,s=e.innerHeight;return{top:0,left:0,right:t,bottom:s,width:t,height:s}}function IE(e,t){return t===void 0&&(t=pn(e).getComputedStyle(e)),t.position==="fixed"}function KE(e,t){t===void 0&&(t=pn(e).getComputedStyle(e));const s=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(o=>{const c=t[o];return typeof c=="string"?s.test(c):!1})}function Xm(e,t){const s=[];function r(o){if(t!=null&&s.length>=t||!o)return s;if(Ym(o)&&o.scrollingElement!=null&&!s.includes(o.scrollingElement))return s.push(o.scrollingElement),s;if(!cc(o)||x0(o)||s.includes(o))return s;const c=pn(e).getComputedStyle(o);return o!==e&&KE(o,c)&&s.push(o),IE(o,c)?s:r(o.parentNode)}return e?r(e):s}function R0(e){const[t]=Xm(e,1);return t??null}function Pf(e){return!mh||!e?null:xl(e)?e:$m(e)?Ym(e)||e===El(e).scrollingElement?window:cc(e)?e:null:null}function M0(e){return xl(e)?e.scrollX:e.scrollLeft}function N0(e){return xl(e)?e.scrollY:e.scrollTop}function vp(e){return{x:M0(e),y:N0(e)}}var Ri;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(Ri||(Ri={}));function A0(e){return!mh||!e?!1:e===document.scrollingElement}function L0(e){const t={x:0,y:0},s=A0(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-s.width,y:e.scrollHeight-s.height},o=e.scrollTop<=t.y,c=e.scrollLeft<=t.x,h=e.scrollTop>=r.y,f=e.scrollLeft>=r.x;return{isTop:o,isLeft:c,isBottom:h,isRight:f,maxScroll:r,minScroll:t}}const FE={x:.2,y:.2};function WE(e,t,s,r,o){let{top:c,left:h,right:f,bottom:g}=s;r===void 0&&(r=10),o===void 0&&(o=FE);const{isTop:p,isBottom:y,isLeft:b,isRight:w}=L0(e),S={x:0,y:0},E={x:0,y:0},T={height:t.height*o.y,width:t.width*o.x};return!p&&c<=t.top+T.height?(S.y=Ri.Backward,E.y=r*Math.abs((t.top+T.height-c)/T.height)):!y&&g>=t.bottom-T.height&&(S.y=Ri.Forward,E.y=r*Math.abs((t.bottom-T.height-g)/T.height)),!w&&f>=t.right-T.width?(S.x=Ri.Forward,E.x=r*Math.abs((t.right-T.width-f)/T.width)):!b&&h<=t.left+T.width&&(S.x=Ri.Backward,E.x=r*Math.abs((t.left+T.width-h)/T.width)),{direction:S,speed:E}}function qE(e){if(e===document.scrollingElement){const{innerWidth:c,innerHeight:h}=window;return{top:0,left:0,right:c,bottom:h,width:c,height:h}}const{top:t,left:s,right:r,bottom:o}=e.getBoundingClientRect();return{top:t,left:s,right:r,bottom:o,width:e.clientWidth,height:e.clientHeight}}function B0(e){return e.reduce((t,s)=>gl(t,vp(s)),hs)}function $E(e){return e.reduce((t,s)=>t+M0(s),0)}function YE(e){return e.reduce((t,s)=>t+N0(s),0)}function VE(e,t){if(t===void 0&&(t=hc),!e)return;const{top:s,left:r,bottom:o,right:c}=t(e);R0(e)&&(o<=0||c<=0||s>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const XE=[["x",["left","right"],$E],["y",["top","bottom"],YE]];class Gm{constructor(t,s){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 r=Xm(s),o=B0(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[c,h,f]of XE)for(const g of h)Object.defineProperty(this,g,{get:()=>{const p=f(r),y=o[c]-p;return this.rect[g]+y},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Fo{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(s=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...s)})},this.target=t}add(t,s,r){var o;(o=this.target)==null||o.addEventListener(t,s,r),this.listeners.push([t,s,r])}}function GE(e){const{EventTarget:t}=pn(e);return e instanceof t?e:El(e)}function Uf(e,t){const s=Math.abs(e.x),r=Math.abs(e.y);return typeof t=="number"?Math.sqrt(s**2+r**2)>t:"x"in t&&"y"in t?s>t.x&&r>t.y:"x"in t?s>t.x:"y"in t?r>t.y:!1}var Vn;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Vn||(Vn={}));function Cy(e){e.preventDefault()}function ZE(e){e.stopPropagation()}var Nt;(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"})(Nt||(Nt={}));const O0={start:[Nt.Space,Nt.Enter],cancel:[Nt.Esc],end:[Nt.Space,Nt.Enter,Nt.Tab]},QE=(e,t)=>{let{currentCoordinates:s}=t;switch(e.code){case Nt.Right:return{...s,x:s.x+25};case Nt.Left:return{...s,x:s.x-25};case Nt.Down:return{...s,y:s.y+25};case Nt.Up:return{...s,y:s.y-25}}};class z0{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:s}}=t;this.props=t,this.listeners=new Fo(El(s)),this.windowListeners=new Fo(pn(s)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Vn.Resize,this.handleCancel),this.windowListeners.add(Vn.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Vn.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:s}=this.props,r=t.node.current;r&&VE(r),s(hs)}handleKeyDown(t){if(k0(t)){const{active:s,context:r,options:o}=this.props,{keyboardCodes:c=O0,coordinateGetter:h=QE,scrollBehavior:f="smooth"}=o,{code:g}=t;if(c.end.includes(g)){this.handleEnd(t);return}if(c.cancel.includes(g)){this.handleCancel(t);return}const{collisionRect:p}=r.current,y=p?{x:p.left,y:p.top}:hs;this.referenceCoordinates||(this.referenceCoordinates=y);const b=h(t,{active:s,context:r.current,currentCoordinates:y});if(b){const w=Xu(b,y),S={x:0,y:0},{scrollableAncestors:E}=r.current;for(const T of E){const A=t.code,{isTop:O,isRight:L,isLeft:U,isBottom:I,maxScroll:te,minScroll:ee}=L0(T),ae=qE(T),ue={x:Math.min(A===Nt.Right?ae.right-ae.width/2:ae.right,Math.max(A===Nt.Right?ae.left:ae.left+ae.width/2,b.x)),y:Math.min(A===Nt.Down?ae.bottom-ae.height/2:ae.bottom,Math.max(A===Nt.Down?ae.top:ae.top+ae.height/2,b.y))},be=A===Nt.Right&&!L||A===Nt.Left&&!U,we=A===Nt.Down&&!I||A===Nt.Up&&!O;if(be&&ue.x!==b.x){const ne=T.scrollLeft+w.x,ie=A===Nt.Right&&ne<=te.x||A===Nt.Left&&ne>=ee.x;if(ie&&!w.y){T.scrollTo({left:ne,behavior:f});return}ie?S.x=T.scrollLeft-ne:S.x=A===Nt.Right?T.scrollLeft-te.x:T.scrollLeft-ee.x,S.x&&T.scrollBy({left:-S.x,behavior:f});break}else if(we&&ue.y!==b.y){const ne=T.scrollTop+w.y,ie=A===Nt.Down&&ne<=te.y||A===Nt.Up&&ne>=ee.y;if(ie&&!w.x){T.scrollTo({top:ne,behavior:f});return}ie?S.y=T.scrollTop-ne:S.y=A===Nt.Down?T.scrollTop-te.y:T.scrollTop-ee.y,S.y&&T.scrollBy({top:-S.y,behavior:f});break}}this.handleMove(t,gl(Xu(b,this.referenceCoordinates),S))}}}handleMove(t,s){const{onMove:r}=this.props;t.preventDefault(),r(s)}handleEnd(t){const{onEnd:s}=this.props;t.preventDefault(),this.detach(),s()}handleCancel(t){const{onCancel:s}=this.props;t.preventDefault(),this.detach(),s()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}z0.activators=[{eventName:"onKeyDown",handler:(e,t,s)=>{let{keyboardCodes:r=O0,onActivation:o}=t,{active:c}=s;const{code:h}=e.nativeEvent;if(r.start.includes(h)){const f=c.activatorNode.current;return f&&e.target!==f?!1:(e.preventDefault(),o?.({event:e.nativeEvent}),!0)}return!1}}];function xy(e){return!!(e&&"distance"in e)}function Ey(e){return!!(e&&"delay"in e)}class Zm{constructor(t,s,r){var o;r===void 0&&(r=GE(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=s;const{event:c}=t,{target:h}=c;this.props=t,this.events=s,this.document=El(h),this.documentListeners=new Fo(this.document),this.listeners=new Fo(r),this.windowListeners=new Fo(pn(h)),this.initialCoordinates=(o=gp(c))!=null?o:hs,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:s,bypassActivationConstraint:r}}}=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(Vn.Resize,this.handleCancel),this.windowListeners.add(Vn.DragStart,Cy),this.windowListeners.add(Vn.VisibilityChange,this.handleCancel),this.windowListeners.add(Vn.ContextMenu,Cy),this.documentListeners.add(Vn.Keydown,this.handleKeydown),s){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Ey(s)){this.timeoutId=setTimeout(this.handleStart,s.delay),this.handlePending(s);return}if(xy(s)){this.handlePending(s);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,s){const{active:r,onPending:o}=this.props;o(r,t,this.initialCoordinates,s)}handleStart(){const{initialCoordinates:t}=this,{onStart:s}=this.props;t&&(this.activated=!0,this.documentListeners.add(Vn.Click,ZE,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Vn.SelectionChange,this.removeTextSelection),s(t))}handleMove(t){var s;const{activated:r,initialCoordinates:o,props:c}=this,{onMove:h,options:{activationConstraint:f}}=c;if(!o)return;const g=(s=gp(t))!=null?s:hs,p=Xu(o,g);if(!r&&f){if(xy(f)){if(f.tolerance!=null&&Uf(p,f.tolerance))return this.handleCancel();if(Uf(p,f.distance))return this.handleStart()}if(Ey(f)&&Uf(p,f.tolerance))return this.handleCancel();this.handlePending(f,p);return}t.cancelable&&t.preventDefault(),h(g)}handleEnd(){const{onAbort:t,onEnd:s}=this.props;this.detach(),this.activated||t(this.props.active),s()}handleCancel(){const{onAbort:t,onCancel:s}=this.props;this.detach(),this.activated||t(this.props.active),s()}handleKeydown(t){t.code===Nt.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const JE={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class j0 extends Zm{constructor(t){const{event:s}=t,r=El(s.target);super(t,JE,r)}}j0.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:s}=e,{onActivation:r}=t;return!s.isPrimary||s.button!==0?!1:(r?.({event:s}),!0)}}];const e2={move:{name:"mousemove"},end:{name:"mouseup"}};var bp;(function(e){e[e.RightClick=2]="RightClick"})(bp||(bp={}));class H0 extends Zm{constructor(t){super(t,e2,El(t.event.target))}}H0.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:s}=e,{onActivation:r}=t;return s.button===bp.RightClick?!1:(r?.({event:s}),!0)}}];const If={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class P0 extends Zm{constructor(t){super(t,If)}static setup(){return window.addEventListener(If.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(If.move.name,t)};function t(){}}}P0.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:s}=e,{onActivation:r}=t;const{touches:o}=s;return o.length>1?!1:(r?.({event:s}),!0)}}];var Wo;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Wo||(Wo={}));var Zu;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(Zu||(Zu={}));function t2(e){let{acceleration:t,activator:s=Wo.Pointer,canScroll:r,draggingRect:o,enabled:c,interval:h=5,order:f=Zu.TreeOrder,pointerCoordinates:g,scrollableAncestors:p,scrollableAncestorRects:y,delta:b,threshold:w}=e;const S=n2({delta:b,disabled:!c}),[E,T]=gE(),A=v.useRef({x:0,y:0}),O=v.useRef({x:0,y:0}),L=v.useMemo(()=>{switch(s){case Wo.Pointer:return g?{top:g.y,bottom:g.y,left:g.x,right:g.x}:null;case Wo.DraggableRect:return o}},[s,o,g]),U=v.useRef(null),I=v.useCallback(()=>{const ee=U.current;if(!ee)return;const ae=A.current.x*O.current.x,ue=A.current.y*O.current.y;ee.scrollBy(ae,ue)},[]),te=v.useMemo(()=>f===Zu.TreeOrder?[...p].reverse():p,[f,p]);v.useEffect(()=>{if(!c||!p.length||!L){T();return}for(const ee of te){if(r?.(ee)===!1)continue;const ae=p.indexOf(ee),ue=y[ae];if(!ue)continue;const{direction:be,speed:we}=WE(ee,ue,L,t,w);for(const ne of["x","y"])S[ne][be[ne]]||(we[ne]=0,be[ne]=0);if(we.x>0||we.y>0){T(),U.current=ee,E(I,h),A.current=we,O.current=be;return}}A.current={x:0,y:0},O.current={x:0,y:0},T()},[t,I,r,T,c,h,JSON.stringify(L),JSON.stringify(S),E,p,te,y,JSON.stringify(w)])}const i2={x:{[Ri.Backward]:!1,[Ri.Forward]:!1},y:{[Ri.Backward]:!1,[Ri.Forward]:!1}};function n2(e){let{delta:t,disabled:s}=e;const r=mp(t);return uc(o=>{if(s||!r||!o)return i2;const c={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[Ri.Backward]:o.x[Ri.Backward]||c.x===-1,[Ri.Forward]:o.x[Ri.Forward]||c.x===1},y:{[Ri.Backward]:o.y[Ri.Backward]||c.y===-1,[Ri.Forward]:o.y[Ri.Forward]||c.y===1}}},[s,t,r])}function s2(e,t){const s=t!=null?e.get(t):void 0,r=s?s.node.current:null;return uc(o=>{var c;return t==null?null:(c=r??o)!=null?c:null},[r,t])}function r2(e,t){return v.useMemo(()=>e.reduce((s,r)=>{const{sensor:o}=r,c=o.activators.map(h=>({eventName:h.eventName,handler:t(h.handler,r)}));return[...s,...c]},[]),[e,t])}var Qo;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Qo||(Qo={}));var yp;(function(e){e.Optimized="optimized"})(yp||(yp={}));const ky=new Map;function a2(e,t){let{dragging:s,dependencies:r,config:o}=t;const[c,h]=v.useState(null),{frequency:f,measure:g,strategy:p}=o,y=v.useRef(e),b=A(),w=Zo(b),S=v.useCallback(function(O){O===void 0&&(O=[]),!w.current&&h(L=>L===null?O:L.concat(O.filter(U=>!L.includes(U))))},[w]),E=v.useRef(null),T=uc(O=>{if(b&&!s)return ky;if(!O||O===ky||y.current!==e||c!=null){const L=new Map;for(let U of e){if(!U)continue;if(c&&c.length>0&&!c.includes(U.id)&&U.rect.current){L.set(U.id,U.rect.current);continue}const I=U.node.current,te=I?new Gm(g(I),I):null;U.rect.current=te,te&&L.set(U.id,te)}return L}return O},[e,c,s,b,g]);return v.useEffect(()=>{y.current=e},[e]),v.useEffect(()=>{b||S()},[s,b]),v.useEffect(()=>{c&&c.length>0&&h(null)},[JSON.stringify(c)]),v.useEffect(()=>{b||typeof f!="number"||E.current!==null||(E.current=setTimeout(()=>{S(),E.current=null},f))},[f,b,S,...r]),{droppableRects:T,measureDroppableContainers:S,measuringScheduled:c!=null};function A(){switch(p){case Qo.Always:return!1;case Qo.BeforeDragging:return s;default:return!s}}}function U0(e,t){return uc(s=>e?s||(typeof t=="function"?t(e):e):null,[t,e])}function l2(e,t){return U0(e,t)}function o2(e){let{callback:t,disabled:s}=e;const r=Vm(t),o=v.useMemo(()=>{if(s||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:c}=window;return new c(r)},[r,s]);return v.useEffect(()=>()=>o?.disconnect(),[o]),o}function _h(e){let{callback:t,disabled:s}=e;const r=Vm(t),o=v.useMemo(()=>{if(s||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:c}=window;return new c(r)},[s]);return v.useEffect(()=>()=>o?.disconnect(),[o]),o}function c2(e){return new Gm(hc(e),e)}function Ty(e,t,s){t===void 0&&(t=c2);const[r,o]=v.useState(null);function c(){o(g=>{if(!e)return null;if(e.isConnected===!1){var p;return(p=g??s)!=null?p:null}const y=t(e);return JSON.stringify(g)===JSON.stringify(y)?g:y})}const h=o2({callback(g){if(e)for(const p of g){const{type:y,target:b}=p;if(y==="childList"&&b instanceof HTMLElement&&b.contains(e)){c();break}}}}),f=_h({callback:c});return zr(()=>{c(),e?(f?.observe(e),h?.observe(document.body,{childList:!0,subtree:!0})):(f?.disconnect(),h?.disconnect())},[e]),r}function u2(e){const t=U0(e);return D0(e,t)}const Dy=[];function h2(e){const t=v.useRef(e),s=uc(r=>e?r&&r!==Dy&&e&&t.current&&e.parentNode===t.current.parentNode?r:Xm(e):Dy,[e]);return v.useEffect(()=>{t.current=e},[e]),s}function d2(e){const[t,s]=v.useState(null),r=v.useRef(e),o=v.useCallback(c=>{const h=Pf(c.target);h&&s(f=>f?(f.set(h,vp(h)),new Map(f)):null)},[]);return v.useEffect(()=>{const c=r.current;if(e!==c){h(c);const f=e.map(g=>{const p=Pf(g);return p?(p.addEventListener("scroll",o,{passive:!0}),[p,vp(p)]):null}).filter(g=>g!=null);s(f.length?new Map(f):null),r.current=e}return()=>{h(e),h(c)};function h(f){f.forEach(g=>{const p=Pf(g);p?.removeEventListener("scroll",o)})}},[o,e]),v.useMemo(()=>e.length?t?Array.from(t.values()).reduce((c,h)=>gl(c,h),hs):B0(e):hs,[e,t])}function Ry(e,t){t===void 0&&(t=[]);const s=v.useRef(null);return v.useEffect(()=>{s.current=null},t),v.useEffect(()=>{const r=e!==hs;r&&!s.current&&(s.current=e),!r&&s.current&&(s.current=null)},[e]),s.current?Xu(e,s.current):hs}function f2(e){v.useEffect(()=>{if(!mh)return;const t=e.map(s=>{let{sensor:r}=s;return r.setup==null?void 0:r.setup()});return()=>{for(const s of t)s?.()}},e.map(t=>{let{sensor:s}=t;return s}))}function p2(e,t){return v.useMemo(()=>e.reduce((s,r)=>{let{eventName:o,handler:c}=r;return s[o]=h=>{c(h,t)},s},{}),[e,t])}function I0(e){return v.useMemo(()=>e?UE(e):null,[e])}const My=[];function m2(e,t){t===void 0&&(t=hc);const[s]=e,r=I0(s?pn(s):null),[o,c]=v.useState(My);function h(){c(()=>e.length?e.map(g=>A0(g)?r:new Gm(t(g),g)):My)}const f=_h({callback:h});return zr(()=>{f?.disconnect(),h(),e.forEach(g=>f?.observe(g))},[e]),o}function g2(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return cc(t)?t:e}function _2(e){let{measure:t}=e;const[s,r]=v.useState(null),o=v.useCallback(p=>{for(const{target:y}of p)if(cc(y)){r(b=>{const w=t(y);return b?{...b,width:w.width,height:w.height}:w});break}},[t]),c=_h({callback:o}),h=v.useCallback(p=>{const y=g2(p);c?.disconnect(),y&&c?.observe(y),r(y?t(y):null)},[t,c]),[f,g]=Vu(h);return v.useMemo(()=>({nodeRef:f,rect:s,setRef:g}),[s,f,g])}const v2=[{sensor:j0,options:{}},{sensor:z0,options:{}}],b2={current:{}},Ou={draggable:{measure:wy},droppable:{measure:wy,strategy:Qo.WhileDragging,frequency:yp.Optimized},dragOverlay:{measure:hc}};class qo extends Map{get(t){var s;return t!=null&&(s=super.get(t))!=null?s:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:s}=t;return!s})}getNodeFor(t){var s,r;return(s=(r=this.get(t))==null?void 0:r.node.current)!=null?s:void 0}}const y2={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new qo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Gu},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Ou,measureDroppableContainers:Gu,windowRect:null,measuringScheduled:!1},S2={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Gu,draggableNodes:new Map,over:null,measureDroppableContainers:Gu},vh=v.createContext(S2),w2=v.createContext(y2);function C2(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new qo}}}function x2(e,t){switch(t.type){case yi.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case yi.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 yi.DragEnd:case yi.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case yi.RegisterDroppable:{const{element:s}=t,{id:r}=s,o=new qo(e.droppable.containers);return o.set(r,s),{...e,droppable:{...e.droppable,containers:o}}}case yi.SetDroppableDisabled:{const{id:s,key:r,disabled:o}=t,c=e.droppable.containers.get(s);if(!c||r!==c.key)return e;const h=new qo(e.droppable.containers);return h.set(s,{...c,disabled:o}),{...e,droppable:{...e.droppable,containers:h}}}case yi.UnregisterDroppable:{const{id:s,key:r}=t,o=e.droppable.containers.get(s);if(!o||r!==o.key)return e;const c=new qo(e.droppable.containers);return c.delete(s),{...e,droppable:{...e.droppable,containers:c}}}default:return e}}function E2(e){let{disabled:t}=e;const{active:s,activatorEvent:r,draggableNodes:o}=v.useContext(vh),c=mp(r),h=mp(s?.id);return v.useEffect(()=>{if(!t&&!r&&c&&h!=null){if(!k0(c)||document.activeElement===c.target)return;const f=o.get(h);if(!f)return;const{activatorNode:g,node:p}=f;if(!g.current&&!p.current)return;requestAnimationFrame(()=>{for(const y of[g.current,p.current]){if(!y)continue;const b=bE(y);if(b){b.focus();break}}})}},[r,t,o,h,c]),null}function k2(e,t){let{transform:s,...r}=t;return e!=null&&e.length?e.reduce((o,c)=>c({transform:o,...r}),s):s}function T2(e){return v.useMemo(()=>({draggable:{...Ou.draggable,...e?.draggable},droppable:{...Ou.droppable,...e?.droppable},dragOverlay:{...Ou.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function D2(e){let{activeNode:t,measure:s,initialRect:r,config:o=!0}=e;const c=v.useRef(!1),{x:h,y:f}=typeof o=="boolean"?{x:o,y:o}:o;zr(()=>{if(!h&&!f||!t){c.current=!1;return}if(c.current||!r)return;const p=t?.node.current;if(!p||p.isConnected===!1)return;const y=s(p),b=D0(y,r);if(h||(b.x=0),f||(b.y=0),c.current=!0,Math.abs(b.x)>0||Math.abs(b.y)>0){const w=R0(p);w&&w.scrollBy({top:b.y,left:b.x})}},[t,h,f,r,s])}const K0=v.createContext({...hs,scaleX:1,scaleY:1});var Rr;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(Rr||(Rr={}));const R2=v.memo(function(t){var s,r,o,c;let{id:h,accessibility:f,autoScroll:g=!0,children:p,sensors:y=v2,collisionDetection:b=LE,measuring:w,modifiers:S,...E}=t;const T=v.useReducer(x2,void 0,C2),[A,O]=T,[L,U]=EE(),[I,te]=v.useState(Rr.Uninitialized),ee=I===Rr.Initialized,{draggable:{active:ae,nodes:ue,translate:be},droppable:{containers:we}}=A,ne=ae!=null?ue.get(ae):null,ie=v.useRef({initial:null,translated:null}),Y=v.useMemo(()=>{var gt;return ae!=null?{id:ae,data:(gt=ne?.data)!=null?gt:b2,rect:ie}:null},[ae,ne]),K=v.useRef(null),[re,B]=v.useState(null),[$,D]=v.useState(null),X=Zo(E,Object.values(E)),_e=gh("DndDescribedBy",h),R=v.useMemo(()=>we.getEnabled(),[we]),H=T2(w),{droppableRects:Q,measureDroppableContainers:de,measuringScheduled:ke}=a2(R,{dragging:ee,dependencies:[be.x,be.y],config:H.droppable}),xe=s2(ue,ae),Re=v.useMemo(()=>$?gp($):null,[$]),Xe=Zi(),ge=l2(xe,H.draggable.measure);D2({activeNode:ae!=null?ue.get(ae):null,config:Xe.layoutShiftCompensation,initialRect:ge,measure:H.draggable.measure});const G=Ty(xe,H.draggable.measure,ge),ce=Ty(xe?xe.parentElement:null),Ce=v.useRef({activatorEvent:null,active:null,activeNode:xe,collisionRect:null,collisions:null,droppableRects:Q,draggableNodes:ue,draggingNode:null,draggingNodeRect:null,droppableContainers:we,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ye=we.getNodeFor((s=Ce.current.over)==null?void 0:s.id),De=_2({measure:H.dragOverlay.measure}),Be=(r=De.nodeRef.current)!=null?r:xe,Ke=ee?(o=De.rect)!=null?o:G:null,le=!!(De.nodeRef.current&&De.rect),Ee=u2(le?null:G),Le=I0(Be?pn(Be):null),Oe=h2(ee?ye??xe:null),He=m2(Oe),_t=k2(S,{transform:{x:be.x-Ee.x,y:be.y-Ee.y,scaleX:1,scaleY:1},activatorEvent:$,active:Y,activeNodeRect:G,containerNodeRect:ce,draggingNodeRect:Ke,over:Ce.current.over,overlayNodeRect:De.rect,scrollableAncestors:Oe,scrollableAncestorRects:He,windowRect:Le}),Ye=Re?gl(Re,be):null,rt=d2(Oe),Oi=Ry(rt),$i=Ry(rt,[G]),Ci=gl(_t,Oi),ri=Ke?zE(Ke,_t):null,zi=Y&&ri?b({active:Y,collisionRect:ri,droppableRects:Q,droppableContainers:R,pointerCoordinates:Ye}):null,sn=NE(zi,"id"),[F,qe]=v.useState(null),dt=le?_t:gl(_t,$i),vt=BE(dt,(c=F?.rect)!=null?c:null,G),pi=v.useRef(null),St=v.useCallback((gt,Tt)=>{let{sensor:Dt,options:mi}=Tt;if(K.current==null)return;const gi=ue.get(K.current);if(!gi)return;const Ut=gt.nativeEvent,ei=new Dt({active:K.current,activeNode:gi,event:Ut,options:mi,context:Ce,onAbort(Lt){if(!ue.get(Lt))return;const{onDragAbort:It}=X.current,Yi={id:Lt};It?.(Yi),L({type:"onDragAbort",event:Yi})},onPending(Lt,xi,It,Yi){if(!ue.get(Lt))return;const{onDragPending:an}=X.current,Qi={id:Lt,constraint:xi,initialCoordinates:It,offset:Yi};an?.(Qi),L({type:"onDragPending",event:Qi})},onStart(Lt){const xi=K.current;if(xi==null)return;const It=ue.get(xi);if(!It)return;const{onDragStart:Yi}=X.current,rn={activatorEvent:Ut,active:{id:xi,data:It.data,rect:ie}};Ao.unstable_batchedUpdates(()=>{Yi?.(rn),te(Rr.Initializing),O({type:yi.DragStart,initialCoordinates:Lt,active:xi}),L({type:"onDragStart",event:rn}),B(pi.current),D(Ut)})},onMove(Lt){O({type:yi.DragMove,coordinates:Lt})},onEnd:ji(yi.DragEnd),onCancel:ji(yi.DragCancel)});pi.current=ei;function ji(Lt){return async function(){const{active:It,collisions:Yi,over:rn,scrollAdjustedTranslate:an}=Ce.current;let Qi=null;if(It&&an){const{cancelDrop:gn}=X.current;Qi={activatorEvent:Ut,active:It,collisions:Yi,delta:an,over:rn},Lt===yi.DragEnd&&typeof gn=="function"&&await Promise.resolve(gn(Qi))&&(Lt=yi.DragCancel)}K.current=null,Ao.unstable_batchedUpdates(()=>{O({type:Lt}),te(Rr.Uninitialized),qe(null),B(null),D(null),pi.current=null;const gn=Lt===yi.DragEnd?"onDragEnd":"onDragCancel";if(Qi){const Hi=X.current[gn];Hi?.(Qi),L({type:gn,event:Qi})}})}}},[ue]),mn=v.useCallback((gt,Tt)=>(Dt,mi)=>{const gi=Dt.nativeEvent,Ut=ue.get(mi);if(K.current!==null||!Ut||gi.dndKit||gi.defaultPrevented)return;const ei={active:Ut};gt(Dt,Tt.options,ei)===!0&&(gi.dndKit={capturedBy:Tt.sensor},K.current=mi,St(Dt,Tt))},[ue,St]),Ln=r2(y,mn);f2(y),zr(()=>{G&&I===Rr.Initializing&&te(Rr.Initialized)},[G,I]),v.useEffect(()=>{const{onDragMove:gt}=X.current,{active:Tt,activatorEvent:Dt,collisions:mi,over:gi}=Ce.current;if(!Tt||!Dt)return;const Ut={active:Tt,activatorEvent:Dt,collisions:mi,delta:{x:Ci.x,y:Ci.y},over:gi};Ao.unstable_batchedUpdates(()=>{gt?.(Ut),L({type:"onDragMove",event:Ut})})},[Ci.x,Ci.y]),v.useEffect(()=>{const{active:gt,activatorEvent:Tt,collisions:Dt,droppableContainers:mi,scrollAdjustedTranslate:gi}=Ce.current;if(!gt||K.current==null||!Tt||!gi)return;const{onDragOver:Ut}=X.current,ei=mi.get(sn),ji=ei&&ei.rect.current?{id:ei.id,rect:ei.rect.current,data:ei.data,disabled:ei.disabled}:null,Lt={active:gt,activatorEvent:Tt,collisions:Dt,delta:{x:gi.x,y:gi.y},over:ji};Ao.unstable_batchedUpdates(()=>{qe(ji),Ut?.(Lt),L({type:"onDragOver",event:Lt})})},[sn]),zr(()=>{Ce.current={activatorEvent:$,active:Y,activeNode:xe,collisionRect:ri,collisions:zi,droppableRects:Q,draggableNodes:ue,draggingNode:Be,draggingNodeRect:Ke,droppableContainers:we,over:F,scrollableAncestors:Oe,scrollAdjustedTranslate:Ci},ie.current={initial:Ke,translated:ri}},[Y,xe,zi,ri,ue,Be,Ke,Q,we,F,Oe,Ci]),t2({...Xe,delta:be,draggingRect:ri,pointerCoordinates:Ye,scrollableAncestors:Oe,scrollableAncestorRects:He});const Jt=v.useMemo(()=>({active:Y,activeNode:xe,activeNodeRect:G,activatorEvent:$,collisions:zi,containerNodeRect:ce,dragOverlay:De,draggableNodes:ue,droppableContainers:we,droppableRects:Q,over:F,measureDroppableContainers:de,scrollableAncestors:Oe,scrollableAncestorRects:He,measuringConfiguration:H,measuringScheduled:ke,windowRect:Le}),[Y,xe,G,$,zi,ce,De,ue,we,Q,F,de,Oe,He,H,ke,Le]),ai=v.useMemo(()=>({activatorEvent:$,activators:Ln,active:Y,activeNodeRect:G,ariaDescribedById:{draggable:_e},dispatch:O,draggableNodes:ue,over:F,measureDroppableContainers:de}),[$,Ln,Y,G,O,_e,ue,F,de]);return Si.createElement(T0.Provider,{value:U},Si.createElement(vh.Provider,{value:ai},Si.createElement(w2.Provider,{value:Jt},Si.createElement(K0.Provider,{value:vt},p)),Si.createElement(E2,{disabled:f?.restoreFocus===!1})),Si.createElement(DE,{...f,hiddenTextDescribedById:_e}));function Zi(){const gt=re?.autoScrollEnabled===!1,Tt=typeof g=="object"?g.enabled===!1:g===!1,Dt=ee&&!gt&&!Tt;return typeof g=="object"?{...g,enabled:Dt}:{enabled:Dt}}}),M2=v.createContext(null),Ny="button",N2="Draggable";function F0(e){let{id:t,data:s,disabled:r=!1,attributes:o}=e;const c=gh(N2),{activators:h,activatorEvent:f,active:g,activeNodeRect:p,ariaDescribedById:y,draggableNodes:b,over:w}=v.useContext(vh),{role:S=Ny,roleDescription:E="draggable",tabIndex:T=0}=o??{},A=g?.id===t,O=v.useContext(A?K0:M2),[L,U]=Vu(),[I,te]=Vu(),ee=p2(h,t),ae=Zo(s);zr(()=>(b.set(t,{id:t,key:c,node:L,activatorNode:I,data:ae}),()=>{const be=b.get(t);be&&be.key===c&&b.delete(t)}),[b,t]);const ue=v.useMemo(()=>({role:S,tabIndex:T,"aria-disabled":r,"aria-pressed":A&&S===Ny?!0:void 0,"aria-roledescription":E,"aria-describedby":y.draggable}),[r,S,T,A,E,y.draggable]);return{active:g,activatorEvent:f,activeNodeRect:p,attributes:ue,isDragging:A,listeners:r?void 0:ee,node:L,over:w,setNodeRef:U,setActivatorNodeRef:te,transform:O}}const A2="Droppable",L2={timeout:25};function Qm(e){let{data:t,disabled:s=!1,id:r,resizeObserverConfig:o}=e;const c=gh(A2),{active:h,dispatch:f,over:g,measureDroppableContainers:p}=v.useContext(vh),y=v.useRef({disabled:s}),b=v.useRef(!1),w=v.useRef(null),S=v.useRef(null),{disabled:E,updateMeasurementsFor:T,timeout:A}={...L2,...o},O=Zo(T??r),L=v.useCallback(()=>{if(!b.current){b.current=!0;return}S.current!=null&&clearTimeout(S.current),S.current=setTimeout(()=>{p(Array.isArray(O.current)?O.current:[O.current]),S.current=null},A)},[A]),U=_h({callback:L,disabled:E||!h}),I=v.useCallback((ue,be)=>{U&&(be&&(U.unobserve(be),b.current=!1),ue&&U.observe(ue))},[U]),[te,ee]=Vu(I),ae=Zo(t);return v.useEffect(()=>{!U||!te.current||(U.disconnect(),b.current=!1,U.observe(te.current))},[te,U]),v.useEffect(()=>(f({type:yi.RegisterDroppable,element:{id:r,key:c,disabled:s,node:te,rect:w,data:ae}}),()=>f({type:yi.UnregisterDroppable,key:c,id:r})),[r]),v.useEffect(()=>{s!==y.current.disabled&&(f({type:yi.SetDroppableDisabled,id:r,key:c,disabled:s}),y.current.disabled=s)},[r,c,s,f]),{active:h,rect:w,isOver:g?.id===r,node:te,over:g,setNodeRef:ee}}const B2=128,O2=512,kl=100,z2="too_many_detached_terminals",j2=64,H2=4096;function W0(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>B2)return null;const s=t.workspaces.map(P2);return s.some(r=>r===null)?null:{activeWorkspaceId:t.activeWorkspaceId,workspaces:s}}function q0(e){if(!e||typeof e!="object")return!1;const t=e;return Array.isArray(t.workspaces)?t.workspaces.some(s=>{if(!s||typeof s!="object")return!1;const r=s.detachedTerminalIds;return Array.isArray(r)&&r.length>kl}):!1}function P2(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>O2)return null;const s=t.tabs.map(U2);if(s.some(o=>o===null))return null;const r=W2(t.detachedTerminalIds,kl);return r===null?null:{id:t.id,title:t.title,defaultCwd:F2(t.defaultCwd),detachedTerminalIds:r,activeTabId:t.activeTabId,tabs:s}}function U2(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 s=I2(t.root);return s?{id:t.id,title:t.title,activeTerminalId:t.activeTerminalId,root:s}:null}function I2(e){if(!e||typeof e!="object")return null;let t=0;return Sp(e,1,()=>(t+=1,t<=H2))}function Sp(e,t,s){if(!e||typeof e!="object"||t>j2||!s())return null;const r=e;if(r.type==="pane")return typeof r.terminalId=="string"?{type:"pane",terminalId:r.terminalId}:null;if(r.type!=="split"||r.direction!=="horizontal"&&r.direction!=="vertical")return null;const o=Sp(r.first,t+1,s),c=Sp(r.second,t+1,s);return!o||!c?null:{type:"split",direction:r.direction,ratio:K2(r.ratio),first:o,second:c}}function K2(e){return typeof e=="number"&&Number.isFinite(e)?Math.min(.9,Math.max(.1,e)):.5}function F2(e){if(typeof e!="string")return null;const t=e.trim();return t||null}function W2(e,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>t)return null;const s=new Set,r=[];for(const o of e)typeof o!="string"||!o||s.has(o)||(s.add(o),r.push(o));return r}const $0=[{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"}],Nr="__main__";function q2(e){return e===void 0?"unknown":e==="error"?"offline":"ok"}function $2(e){const t=e.trim();return t?t.charAt(0).toUpperCase():"?"}const Ay="Local",Y2=3e4,V2=2,X2=6,Y0="nterminal.serverList.viewMode.v1";function G2(){try{return window.localStorage.getItem(Y0)==="list"?"list":"stats"}catch{return"stats"}}function Z2(e){try{window.localStorage.setItem(Y0,e)}catch{}}function ha(e,t){const s=[Nr,...t.map(h=>h.id)],r=new Set(s),o=new Set,c=[];for(const h of e??[])!r.has(h)||o.has(h)||(o.add(h),c.push(h));for(const h of s)o.has(h)||c.push(h);return c}function Q2(e,t){const s=new Map(e.map(r=>[r.id,r]));return ha(t,e).flatMap(r=>{if(r===Nr)return[{kind:"main",id:Nr}];const o=s.get(r);return o?[{kind:"agent",id:r,agent:o}]:[]})}function Ly(e,t){return e.length===t.length&&e.every((s,r)=>s===t[r])}function V0(e){return e===void 0?"":e==="error"?"offline":[`CPU ${Gn(e.cpuPercent)} ${Jm(e)}`,`MEM ${Gn(e.memoryPercent)} ${Xs(e.memoryUsedBytes,e.memoryTotalBytes)}`,`DISK ${Gn(e.diskPercent)} ${Xs(e.diskUsedBytes,e.diskTotalBytes)}`,`SWAP ${Gn(e.swapPercent)} ${Xs(e.swapUsedBytes,e.swapTotalBytes)}`].join(" · ")}function J2(e){if(!(e===void 0||e==="error"))return[`CPU ${Gn(e.cpuPercent)} (${Jm(e)})`,`RAM ${Gn(e.memoryPercent)} (${Xs(e.memoryUsedBytes,e.memoryTotalBytes)})`,`Disk ${Gn(e.diskPercent)} (${Xs(e.diskUsedBytes,e.diskTotalBytes)})`,`Swap ${Gn(e.swapPercent)} (${Xs(e.swapUsedBytes,e.swapTotalBytes)})`].join(" · ")}function ek(e,t){const s=V0(t);return`${e}${s?` — ${s}`:""}. Double-click to rename.`}function Gn(e){return typeof e=="number"&&Number.isFinite(e)?`${Math.round(e)}%`:"–"}function Jm(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`:`${wp(e.cpuPercent/100*t)}/${t} cores`}function Xs(e,t){return!By(e)||!By(t)?"–/–":tk(e,t)}function tk(e,t){const s=t>=1073741824?"GB":t>=1048576?"MB":"KB",r=s==="GB"?1024**3:s==="MB"?1024**2:1024;return`${wp(e/r)}/${wp(t/r)} ${s}`}function wp(e){return e>=10||Number.isInteger(e)?e.toFixed(0):e.toFixed(1)}function By(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function wu(e){return typeof e!="number"||!Number.isFinite(e)?"normal":e>95?"danger":e>90?"warning":"normal"}function ik(e){return[{label:"CPU",percent:Gn(e.cpuPercent),detail:Jm(e),tone:wu(e.cpuPercent)},{label:"MEM",percent:Gn(e.memoryPercent),detail:Xs(e.memoryUsedBytes,e.memoryTotalBytes),tone:wu(e.memoryPercent)},{label:"DISK",percent:Gn(e.diskPercent),detail:Xs(e.diskUsedBytes,e.diskTotalBytes),tone:wu(e.diskPercent)},{label:"SWAP",percent:Gn(e.swapPercent),detail:Xs(e.swapUsedBytes,e.swapTotalBytes),tone:wu(e.swapPercent)}]}function nk({entry:e}){return e==="error"?m.jsx("span",{className:"server-list-stats server-list-stats--offline",children:"offline"}):e===void 0?m.jsx("span",{className:"server-list-stats server-list-stats-grid","aria-hidden":"true",children:["CPU","MEM","DISK","SWAP"].map(t=>m.jsxs("span",{className:"server-list-stat-cell",children:[m.jsxs("span",{className:"server-list-stat-head",children:[m.jsx("span",{className:"server-list-stat-label",children:t}),m.jsx("span",{className:"server-list-stat-value",children:"–"})]}),m.jsx("span",{className:"server-list-stat-detail",children:"–"})]},t))}):m.jsx("span",{className:"server-list-stats server-list-stats-grid",title:J2(e),children:ik(e).map(t=>m.jsxs("span",{className:"server-list-stat-cell",children:[m.jsxs("span",{className:"server-list-stat-head",children:[m.jsx("span",{className:"server-list-stat-label",children:t.label}),m.jsx("span",{className:"server-list-stat-value","data-tone":t.tone,children:t.percent})]}),m.jsx("span",{className:"server-list-stat-detail",children:t.detail})]},t.label))})}function Oy({api:e,activeAgentId:t,onSelectServer:s,onSessionInvalid:r,refreshToken:o=0,renderServerChildren:c,compact:h=!1}){const[f,g]=v.useState([]),[p,y]=v.useState([Nr]),[b,w]=v.useState(null),[S,E]=v.useState(null),[T,A]=v.useState(""),O=v.useRef(null),[L,U]=v.useState(()=>G2()),[I,te]=v.useState(null),[ee,ae]=v.useState(null),[ue,be]=v.useState({}),we=v.useRef({}),ne=v.useRef(0),ie=v.useRef([]),Y=v.useRef([Nr]),K=v.useRef(null);v.useEffect(()=>{ie.current=f},[f]),v.useEffect(()=>{const G=ha(p,f);Y.current=G,Ly(G,p)||y(G)},[f,p]),v.useEffect(()=>{let G=!1;return e.listAgents().then(ce=>{G||(g(ce.agents),y(ha(ce.serverOrder,ce.agents)))}).catch(()=>{}),e.getMainInfo().then(ce=>{G||w(ce.name)}).catch(()=>{}),()=>{G=!0}},[e,o]),v.useEffect(()=>{S&&(O.current?.focus(),O.current?.select())},[S]),v.useEffect(()=>{let G=!1;function ce(){const ye=[{key:"__main__",load:()=>e.getMainStats()},...f.map(Be=>({key:Be.id,load:()=>e.getAgentStats(Be.id)}))],De=new Set(ye.map(Be=>Be.key));for(const Be of Object.keys(we.current))De.has(Be)||delete we.current[Be];be(Be=>{const Ke={};for(const le of De)le in Be&&(Ke[le]=Be[le]);return Ke});for(const Be of ye)Be.load().then(Ke=>{G||(we.current[Be.key]=0,be(le=>De.has(Be.key)?{...le,[Be.key]:Ke}:le))}).catch(Ke=>{if(G)return;if(Ke instanceof us&&Ke.status===401&&Be.key==="__main__"){r?.({source:"main-stats-401",status:401,activeAgentId:null});return}const le=(we.current[Be.key]??0)+1;we.current[Be.key]=le,le>=V2&&be(Ee=>De.has(Be.key)?{...Ee,[Be.key]:"error"}:Ee)})}ce();const Ce=window.setInterval(ce,Y2);return()=>{G=!0,window.clearInterval(Ce)}},[e,f,r]);function re(G){G==="main"?(A(b??""),E({kind:"main"})):(A(G.name),E({kind:"agent",id:G.id}))}async function B(){if(!S)return;const G=T.trim(),ce=S;if(E(null),ce.kind==="main"){const Ce=G||"";try{const ye=await e.renameMain(Ce);w(ye.name)}catch{}}else{if(!G)return;const Ce=f.find(ye=>ye.id===ce.id)?.name;g(ye=>ye.map(De=>De.id===ce.id?{...De,name:G}:De));try{await e.renameAgent(ce.id,G)}catch{Ce!==void 0&&g(ye=>ye.map(De=>De.id===ce.id?{...De,name:Ce}:De))}}}function $(){E(null)}function D(G){U(G),Z2(G)}function X(G,ce,Ce){if(G===ce)return;const ye=ha(Y.current,ie.current),De=ye.findIndex(He=>He===G),Be=ye.findIndex(He=>He===ce);if(De<0||Be<0)return;const Ke=[...ye],[le]=Ke.splice(De,1);if(!le)return;const Ee=Ke.findIndex(He=>He===ce);if(Ee<0)return;const Le=Ce==="before"?Ee:Ee+1;if(Ke.splice(Le,0,le),Ly(Ke,ye))return;const Oe=ne.current+1;ne.current=Oe,Y.current=Ke,y(Ke),e.reorderAgents(Ke).then(He=>{if(ne.current===Oe){ie.current=He.agents;const _t=ha(He.serverOrder,He.agents);Y.current=_t,g(He.agents),y(_t)}}).catch(async()=>{if(ne.current===Oe)try{const He=await e.listAgents();if(ne.current===Oe){ie.current=He.agents;const _t=ha(He.serverOrder,He.agents);Y.current=_t,g(He.agents),y(_t)}}catch{ne.current===Oe&&(Y.current=ye,y(ye))}})}function _e(G,ce){const Ce=ha(Y.current,ie.current),ye=Ce.findIndex(Be=>Be===G),De=Ce[ye+ce];ye<0||!De||X(G,De,ce<0?"before":"after")}function R(G,ce){ce.pointerType==="mouse"&&ce.button!==0||(ce.stopPropagation(),K.current={sourceId:G,pointerId:ce.pointerId,startX:ce.clientX,startY:ce.clientY,active:!1,targetId:null,placement:"after"},ce.currentTarget.setPointerCapture?.(ce.pointerId))}function H(G){const ce=K.current;if(!ce||ce.pointerId!==G.pointerId)return;const Ce=Math.hypot(G.clientX-ce.startX,G.clientY-ce.startY);if(!ce.active){if(Ce<X2)return;ce.active=!0,te(ce.sourceId)}const De=document.elementFromPoint(G.clientX,G.clientY)?.closest("[data-server-id]"),Be=De?.dataset.serverId??null;if(!De||!Be||Be===ce.sourceId){ce.targetId=null,ae(null);return}const Ke=De.getBoundingClientRect(),le=G.clientY<Ke.top+Ke.height/2?"before":"after";ce.targetId=Be,ce.placement=le,ae({serverId:Be,placement:le})}function Q(G){const ce=K.current;!ce||ce.pointerId!==G.pointerId||(G.stopPropagation(),G.currentTarget.releasePointerCapture?.(G.pointerId),K.current=null,te(null),ae(null),ce.active&&ce.targetId&&X(ce.sourceId,ce.targetId,ce.placement))}function de(G){const ce=K.current;ce&&ce.pointerId===G.pointerId&&G.currentTarget.releasePointerCapture?.(G.pointerId),K.current=null,te(null),ae(null)}const ke=b?.trim()||Ay,xe=S?.kind==="main",Re=L==="stats",Xe=Q2(f,p),ge=Xe.length>1;return h?m.jsx("div",{className:"server-list server-list--compact",children:Xe.map(G=>{const ce=G.kind==="main",Ce=ce?ke:G.agent.name,ye=ce?Nr:G.id,De=ue[ye],Be=V0(De);return m.jsxs("button",{type:"button",className:`server-list-chip${(ce?t===null:t===G.id)?" server-list-chip--active":""}`,onClick:()=>s(ce?null:G.id),"aria-label":Ce,title:`${Ce}${Be?` — ${Be}`:""}`,children:[m.jsx("span",{className:"server-list-chip-initial",children:$2(Ce)}),m.jsx("span",{className:"server-list-chip-pip","data-status":q2(De)})]},G.id)})}):m.jsxs("div",{className:`server-list server-list--${L}`,children:[m.jsxs("div",{className:"server-list-toolbar","aria-label":"Server list display",children:[m.jsx("button",{type:"button",className:"server-list-view-button","aria-pressed":L==="list",onClick:()=>D("list"),title:"Show server names only",children:"List"}),m.jsx("button",{type:"button",className:"server-list-view-button","aria-pressed":L==="stats",onClick:()=>D("stats"),title:"Show resource usage",children:"Stats"})]}),Xe.map(G=>{const ce=G.kind==="main",Ce=ce?ke:G.agent.name,ye=ce?Nr:G.id,De=ce?t===null:t===G.id,Be=ce?xe:S?.kind==="agent"&&S.id===G.id,Ke=c?.({agentId:ce?null:G.id,serverId:G.id,label:Ce,active:De}),le=ee?.serverId===G.id&&I!==G.id?` server-list-section--drop-target server-list-section--drop-${ee.placement}`:"";return m.jsxs("section",{className:`server-list-section${le}`,"aria-label":`${Ce} server`,children:[m.jsx("div",{className:["server-list-row",I===G.id?"server-list-row--dragging":"",ee?.serverId===G.id&&I!==G.id?"server-list-row--drop-target":""].filter(Boolean).join(" "),"data-server-id":G.id,children:Be?m.jsxs(m.Fragment,{children:[ge?m.jsx("span",{className:"server-list-drag-spacer","aria-hidden":"true"}):null,m.jsx("form",{className:"server-list-editor",onSubmit:Ee=>{Ee.preventDefault(),B()},children:m.jsx("input",{ref:O,"aria-label":ce?"Rename main server":`Rename ${Ce}`,value:T,onChange:Ee=>A(Ee.target.value),onBlur:()=>{B()},onKeyDown:Ee=>{Ee.key==="Escape"&&(Ee.preventDefault(),$())},placeholder:ce?Ay:void 0})})]}):m.jsxs(m.Fragment,{children:[ge?m.jsx("button",{type:"button",className:"server-list-drag-handle","data-server-drag-handle":G.id,title:"Drag to reorder","aria-label":`Reorder ${Ce}`,"aria-grabbed":I===G.id,onPointerDown:Ee=>R(G.id,Ee),onPointerMove:H,onPointerUp:Q,onPointerCancel:de,onKeyDown:Ee=>{(Ee.key==="ArrowUp"||Ee.key==="ArrowDown")&&(Ee.preventDefault(),Ee.stopPropagation(),_e(G.id,Ee.key==="ArrowUp"?-1:1))},onClick:Ee=>Ee.stopPropagation(),children:"::"}):null,m.jsxs("button",{type:"button",className:`server-list-item${De?" server-list-item--active":""}`,onClick:()=>s(ce?null:G.id),onDoubleClick:Ee=>{Ee.preventDefault(),re(ce?"main":{id:G.id,name:Ce})},title:ek(Ce,ue[ye]),children:[m.jsxs("span",{className:"server-list-item-header",children:[m.jsx("span",{className:"server-list-dot"}),m.jsx("span",{className:"server-list-name",title:ce?void 0:G.agent.url,children:Ce})]}),Re?m.jsx(nk,{entry:ue[ye]}):null]})]})}),Ke?m.jsx("div",{className:"server-list-children",children:Ke}):null]},G.id)})]})}function sk({api:e}){const[t,s]=v.useState([]),[r,o]=v.useState([]),[c,h]=v.useState(!1),[f,g]=v.useState(null),[p,y]=v.useState(""),[b,w]=v.useState("");async function S(){try{const[O,L,U]=await Promise.all([e.listDevices(),e.listNetworks(),e.getSession()]);s(O.devices),o(L.networks),h(U.totpEnabled),g(null)}catch(O){g(O instanceof Error?O.message:"Failed to load")}}v.useEffect(()=>{S()},[]);async function E(O){await e.revokeDevice(O),await S()}async function T(O){await e.removeNetwork(O),await S()}async function A(O){O.preventDefault(),g(null);try{await e.addNetwork({value:p.trim(),label:b.trim()}),y(""),w(""),await S()}catch(L){g(L instanceof Error?L.message:"Failed to add network")}}return m.jsxs(m.Fragment,{children:[f?m.jsx("p",{className:"form-error",children:f}):null,m.jsxs("section",{className:"security-section",children:[m.jsx("h3",{children:"Trusted devices"}),m.jsx("p",{className:"muted",children:"Devices that can re-authenticate with a 2FA code only (no password) for 30 days."}),t.length===0?m.jsx("p",{className:"muted",children:"No trusted devices."}):m.jsx("ul",{className:"security-list",children:t.map(O=>m.jsxs("li",{children:[m.jsxs("div",{children:[m.jsxs("span",{className:"security-item-label",children:[O.label,O.current?m.jsx("span",{className:"security-badge",children:"this device"}):null]}),m.jsxs("span",{className:"security-item-meta",children:["last seen ",new Date(O.lastSeenAt).toLocaleString()]})]}),m.jsx("button",{type:"button",className:"security-remove",onClick:()=>{E(O.id)},children:"revoke"})]},O.id))})]}),m.jsxs("section",{className:"security-section",children:[m.jsx("h3",{children:"Trusted networks"}),m.jsx("p",{className:"muted",children:"Sessions from these IPs/ranges skip the 2FA re-auth prompt."}),r.length===0?m.jsx("p",{className:"muted",children:"No trusted networks."}):m.jsx("ul",{className:"security-list",children:r.map(O=>m.jsxs("li",{children:[m.jsxs("div",{children:[m.jsx("span",{className:"security-item-label",children:O.value}),O.label!==O.value?m.jsx("span",{className:"security-item-meta",children:O.label}):null]}),m.jsx("button",{type:"button",className:"security-remove",onClick:()=>{T(O.id)},children:"remove"})]},O.id))}),m.jsxs("form",{className:"security-add-form",onSubmit:A,children:[m.jsx("input",{type:"text",placeholder:"IP or CIDR (e.g. 203.0.113.4 or 192.168.0.0/24)",value:p,onChange:O=>y(O.currentTarget.value),required:!0}),m.jsx("input",{type:"text",placeholder:"Label (optional)",value:b,onChange:O=>w(O.currentTarget.value)}),m.jsx("button",{type:"submit",disabled:!p.trim(),children:"Add"})]})]}),c?m.jsxs("section",{className:"security-section",children:[m.jsx("h3",{children:"Two-factor authentication"}),m.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."}),m.jsx("button",{type:"button",className:"security-remove",onClick:async()=>{await e.disableTotp(),await S()},children:"Disable 2FA"})]}):null]})}const eg="nterminal.clientDiagnostics.v1",X0=150,rk=24,ak=160;let zy=!1,So=null;function lk(){zy||typeof window>"u"||(zy=!0,Nn("page.load",{navigation:yk(),visibility:document.visibilityState,online:navigator.onLine,viewport:Z0(),standalone:bk()}),document.addEventListener("visibilitychange",()=>{Nn("page.visibility",{visibility:document.visibilityState,online:navigator.onLine})}),window.addEventListener("pageshow",e=>{Nn("page.show",{persisted:e.persisted,visibility:document.visibilityState,online:navigator.onLine})}),window.addEventListener("pagehide",e=>{Nn("page.hide",{persisted:e.persisted,visibility:document.visibilityState,online:navigator.onLine})}),window.addEventListener("online",()=>Nn("network.online")),window.addEventListener("offline",()=>Nn("network.offline")),window.addEventListener("focus",()=>Nn("window.focus")),window.addEventListener("blur",()=>Nn("window.blur")),window.addEventListener("error",e=>{Nn("runtime.error",{message:e.message,source:Sk(e.filename),line:e.lineno||null})}),window.addEventListener("unhandledrejection",e=>{Nn("runtime.unhandledrejection",{reason:wk(e.reason)})}))}function Nn(e,t={}){const s={at:new Date().toISOString(),event:yh(e,80),data:G0({...t,visibility:t.visibility??_k(),online:t.online??vk(),viewport:t.viewport??Z0()})},r=ma();return r.push(s),hk(r.slice(-X0)),s}function ma(){try{const e=window.localStorage.getItem(eg);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.map(dk).filter(s=>s!==null).slice(-X0):[]}catch{return[]}}function ok(){try{window.localStorage.removeItem(eg)}catch{}}function ck(){const e=ma();return JSON.stringify({generatedAt:new Date().toISOString(),eventCount:e.length,events:e},null,2)}async function uk(){const e=ck();return navigator.clipboard?.writeText?(await navigator.clipboard.writeText(e),!0):Ck(e)}async function bh(e,t=fetch){if(So)return So;const s=ma(),r={reason:yh(e,80),events:s},o=JSON.stringify(r);So=(async()=>{const c=await t("/api/client-diagnostics",{method:"POST",headers:{"content-type":"application/json"},credentials:"same-origin",keepalive:o.length<48e3,body:o});if(!c.ok)throw new Error(`diagnostics_send_failed_${c.status}`);return c.json()})();try{return await So}finally{So=null}}function hk(e){try{window.localStorage.setItem(eg,JSON.stringify(e))}catch{}}function dk(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.at!="string"||typeof t.event!="string"?null:{at:t.at.slice(0,40),event:yh(t.event,80),...t.data&&typeof t.data=="object"?{data:G0(t.data)}:{}}}function G0(e){const t={};for(const[s,r]of Object.entries(e).slice(0,rk)){const o=yh(s,64);if(!o||fk(o))continue;const c=pk(r);c!==void 0&&(t[o]=c)}return t}function fk(e){return/(?:password|secret|token|cookie|authorization|sessionid|session_id|nterminal_session|nterminal_device)/i.test(e)}function pk(e){if(typeof e=="string")return mk(e,ak);if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="boolean"||e===null)return e}function yh(e,t){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_").slice(0,t)}function mk(e,t){return gk(e).replace(/[\r\n\t]+/g," ").replace(/[^\x20-\x7E]/g,"_").slice(0,t)}function gk(e){return e.replace(/https?:\/\/[^\s"'<>]+/gi,"[url]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,"Bearer [redacted]").replace(/\b[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,"[redacted]").replace(/\b((?:auth|authorization|cookie|password|secret|session|sessionid|session_id|token)[a-z0-9_.:-]*\s*[:=]\s*)[^\s&,;]+/gi,"$1[redacted]").replace(/\b(nterminal_session|nterminal_device)\s*=\s*[^\s;,]+/gi,"$1=[redacted]").replace(/\b[A-Za-z0-9+/_=-]{48,}\b/g,"[redacted]")}function _k(){return typeof document>"u"?void 0:document.visibilityState}function vk(){return typeof navigator>"u"?void 0:navigator.onLine}function Z0(){if(typeof window>"u")return;const e=window.innerWidth||0;return e<640?"mobile":e<1024?"tablet":"desktop"}function bk(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches===!0||navigator.standalone===!0}function yk(){return performance.getEntriesByType?.("navigation")?.[0]?.type??"unknown"}function Sk(e){if(!e)return null;try{const t=new URL(e);return t.pathname.split("/").pop()||t.pathname}catch{return e.split("/").pop()??e}}function wk(e){return e instanceof Error?e.message||e.name:typeof e=="string"?e:typeof e}function Ck(e){const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.left="-9999px",document.body.appendChild(t),t.select();let s=!1;try{s=document.execCommand("copy")}finally{document.body.removeChild(t)}return s}const Q0="nterminal.notifications.completionEnabled",tg="nterminal.notifications.completionToastEnabled",ig="nterminal.notifications.completionToastDurationSeconds",ng="nterminal.notifications.completionToastPersistent",Cp="nterminal:completion-toast-display",$o=6.5,xp=2,Ep=60;function Sh(){return typeof window<"u"&&"Notification"in window}function J0(){try{return window.localStorage.getItem(Q0)==="true"}catch{return!1}}function jy(e){try{window.localStorage.setItem(Q0,e?"true":"false")}catch{}}function ya(){return{enabled:Tk(),durationSeconds:kk(),persistUntilDismissed:Dk()}}function xk(e){if(typeof window<"u"){try{window.localStorage.setItem(tg,e?"true":"false")}catch{}rg()}return ya()}function Hy(e){const t=tw(e);if(typeof window<"u"){try{window.localStorage.setItem(ig,String(t))}catch{}rg()}return ya()}function Ek(e){if(typeof window<"u"){try{window.localStorage.setItem(ng,e?"true":"false")}catch{}rg()}return ya()}function ew(e){if(typeof window>"u")return()=>{};const t=s=>{(s.key===tg||s.key===ig||s.key===ng)&&e()};return window.addEventListener(Cp,e),window.addEventListener("storage",t),()=>{window.removeEventListener(Cp,e),window.removeEventListener("storage",t)}}function sg(){return Sh()?window.Notification.permission:"unsupported"}function kk(){if(typeof window>"u")return $o;try{const e=window.localStorage.getItem(ig);return e===null?$o:tw(Number(e))}catch{return $o}}function Tk(){if(typeof window>"u")return!0;try{return window.localStorage.getItem(tg)!=="false"}catch{return!0}}function Dk(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(ng)==="true"}catch{return!1}}function tw(e){if(!Number.isFinite(e))return $o;const t=Math.round(e*2)/2;return Math.max(xp,Math.min(Ep,t))}function rg(){typeof window<"u"&&window.dispatchEvent(new CustomEvent(Cp))}async function Rk(){if(!Sh())return"unsupported";try{return await window.Notification.requestPermission()}catch{return sg()}}function Mk(e){if(!Sh()||sg()!=="granted"||!J0()||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 Nk=1500,ag="nterminal.terminal.fontSize",lg="nterminal.terminal.fontFamily",kp="nterminal:terminal-font-size",Tp="nterminal:terminal-font-family",Dp=11,Rp=20,_a=14,Qu=[{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:[]}],bl="meslo";Mp(bl);async function Kf(e=_a,t=bl){if(typeof document>"u"||!document.fonts)return;const s=sw(t).webFontFamilies;if(s.length===0)return;const r=Promise.all(s.map(o=>document.fonts.load(`${e}px ${o}`))).then(()=>{}).catch(()=>{});await Promise.race([r,new Promise(o=>{globalThis.setTimeout(o,Nk)})])}function iw(e){const t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return _a;const s=Math.round(t);return Math.max(Dp,Math.min(Rp,s))}function nw(e){return Qu.some(t=>t.id===e)?e:bl}function Mp(e){return sw(e).cssFamily}function sw(e){return Qu.find(t=>t.id===e)??Qu[0]}function Np(){if(typeof window>"u")return _a;try{const e=window.localStorage.getItem(ag);return e?iw(e):_a}catch{return _a}}function Ap(){if(typeof window>"u")return bl;try{return nw(window.localStorage.getItem(lg))}catch{return bl}}function Cu(e){const t=iw(e);if(typeof window>"u")return t;try{window.localStorage.setItem(ag,String(t))}catch{}return window.dispatchEvent(new CustomEvent(kp,{detail:t})),t}function Ak(e){const t=nw(e);if(typeof window>"u")return t;try{window.localStorage.setItem(lg,t)}catch{}return window.dispatchEvent(new CustomEvent(Tp,{detail:t})),t}function rw(e){if(typeof window>"u")return()=>{};const t=s=>{s.key===ag&&e()};return window.addEventListener(kp,e),window.addEventListener("storage",t),()=>{window.removeEventListener(kp,e),window.removeEventListener("storage",t)}}function aw(e){if(typeof window>"u")return()=>{};const t=s=>{s.key===lg&&e()};return window.addEventListener(Tp,e),window.addEventListener("storage",t),()=>{window.removeEventListener(Tp,e),window.removeEventListener("storage",t)}}const og="nterminal.terminal.showScrollProgress",Lp="nterminal:terminal-scroll-progress";function Bp(){if(typeof window>"u")return!0;try{return window.localStorage.getItem(og)!=="false"}catch{return!0}}function Lk(e){if(typeof window<"u"){try{window.localStorage.setItem(og,e?"true":"false")}catch{}window.dispatchEvent(new CustomEvent(Lp,{detail:e}))}return e}function lw(e){if(typeof window>"u")return()=>{};const t=s=>{s.key===og&&e()};return window.addEventListener(Lp,e),window.addEventListener("storage",t),()=>{window.removeEventListener(Lp,e),window.removeEventListener("storage",t)}}const cg="nterminal.shortcuts.workspace.v1",Op="nterminal:workspace-shortcuts",Jo=[{id:"server.previous",label:"Previous workspace",group:"Workspaces"},{id:"server.next",label:"Next workspace",group:"Workspaces"},{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"},{id:"history.toggle",label:"Toggle view history",group:"Panes",requiresPrimaryModifier:!0}],wh={"server.previous":Di("ArrowUp",{ctrlKey:!0}),"server.next":Di("ArrowDown",{ctrlKey:!0}),"tab.previous":Di("ArrowLeft",{ctrlKey:!0}),"tab.next":Di("ArrowRight",{ctrlKey:!0}),"tab.index":Di("Digit",{ctrlKey:!0,altKey:!0}),"pane.index":Di("Digit",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"split.right":Di("ArrowRight",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"split.down":Di("ArrowDown",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"history.toggle":Di("KeyH",{altKey:!0})},Bk={"server.previous":Di("BracketLeft",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"server.next":Di("BracketRight",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"tab.previous":Di("BracketLeft",{ctrlKey:!0,altKey:!0}),"tab.next":Di("BracketRight",{ctrlKey:!0,altKey:!0}),"tab.index":Di("Digit",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"pane.index":Di("Digit",{ctrlKey:!0,altKey:!0}),"split.right":Di("ArrowRight",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"split.down":Di("ArrowDown",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"history.toggle":Di("KeyH",{altKey:!0})};function Sa(){const e=uw(wh);if(typeof window>"u")return e;try{const t=window.localStorage.getItem(cg);if(!t)return e;const s=JSON.parse(t);for(const r of Jo){const o=s[r.id];if(Kk(o)){const c=hw(o,r);Ik(c,Bk[r.id])||(e[r.id]=c)}}}catch{return e}return e}function Py(){return JSON.stringify(Sa())}function Ok(e,t){const s=Sa(),r=Jo.find(o=>o.id===e);return r&&(s[e]=hw(t,r),dg(s)),s}function zk(e){const t=Sa();return t[e]={...wh[e]},dg(t),t}function jk(){const e=uw(wh);return dg(e),e}function ug(e){if(typeof window>"u")return()=>{};const t=s=>{s.key===cg&&e()};return window.addEventListener(Op,e),window.addEventListener("storage",t),()=>{window.removeEventListener(Op,e),window.removeEventListener("storage",t)}}function Hk(e,t){const s=pw(e);return!s||Wk(s)||t.indexed&&fw(e)===null||t.requiresPrimaryModifier&&!dw(e)?null:{ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey,metaKey:e.metaKey,code:t.indexed?"Digit":s}}function ow(e){const t=Sa();for(const s of Jo){const r=t[s.id];if(!(!r||!Fk(e,r))){if(s.indexed){if(r.code!=="Digit")continue;const o=fw(e);if(o!==null)return{id:s.id,index:o};continue}if(pw(e)===r.code)return{id:s.id,index:null}}}return null}function hg(e){return cw(Sa()[e])}function cw(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(qk(e.code)),t.join("+")}const Pk=()=>hg("split.right"),Uk=()=>hg("split.down");function Di(e,t){return{ctrlKey:t.ctrlKey??!1,altKey:t.altKey??!1,shiftKey:t.shiftKey??!1,metaKey:t.metaKey??!1,code:e}}function uw(e){return Object.fromEntries(Object.entries(e).map(([t,s])=>[t,{...s}]))}function Ik(e,t){return e.ctrlKey===t.ctrlKey&&e.altKey===t.altKey&&e.shiftKey===t.shiftKey&&e.metaKey===t.metaKey&&e.code===t.code}function dg(e){if(!(typeof window>"u")){try{window.localStorage.setItem(cg,JSON.stringify(e))}catch{}window.dispatchEvent(new CustomEvent(Op))}}function hw(e,t){return t.requiresPrimaryModifier&&!dw(e)?{...wh[t.id]}:{ctrlKey:!!e.ctrlKey,altKey:!!e.altKey,shiftKey:!!e.shiftKey,metaKey:!!e.metaKey,code:t.indexed?"Digit":e.code}}function dw(e){return e.ctrlKey||e.altKey||e.metaKey}function Kk(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 Fk(e,t){return e.ctrlKey===t.ctrlKey&&e.altKey===t.altKey&&e.shiftKey===t.shiftKey&&e.metaKey===t.metaKey}function fw(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 pw(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 Wk(e){return e==="ControlLeft"||e==="ControlRight"||e==="AltLeft"||e==="AltRight"||e==="ShiftLeft"||e==="ShiftRight"||e==="MetaLeft"||e==="MetaRight"}function qk(e){if(e==="Digit")return"1-9";const t=/^Digit([0-9])$/.exec(e);if(t?.[1])return t[1];const s=/^Key([A-Z])$/.exec(e);if(s?.[1])return s[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 $k="Automatic update needs write access to the global npm install. Run this from a normal NTerminal runtime-user shell; only the npm install step uses sudo.";function Yk(e="nterminal",t=new Date){return{reason:"permission",message:$k,command:`sudo npm i -g ${e}@latest --prefer-online && nterminal restart-after-update`,detectedAt:t.toISOString()}}function Vk(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 mw=3600*1e3,Xk="local",zp=new Set,Lr=new Map;let jr={checking:!1,hasUpdates:!1,lastCheckedAt:null},fg=null,Yo=null,Ju=0,Dr=null;function Gk(e){return zp.add(e),()=>{zp.delete(e)}}function Uy(){return jr}function Zk(e){const t=iT();fg=e,pg(),jp(e,t);const s=()=>{if(document.visibilityState!=="visible"||!Hr(e,t))return;const r=jr.lastCheckedAt;(r===null||Date.now()-r>=mw)&&jp(e,t)};return document.addEventListener("visibilitychange",s),()=>{document.removeEventListener("visibilitychange",s),Hr(e,t)&&tT()}}function Qk(e,t){Lr.set(e,gw(t)),yl({...jr,hasUpdates:mg(),lastCheckedAt:Date.now()})}function Ff(e){e===void 0?Lr.clear():Lr.set(e,!1),yl({...jr,hasUpdates:mg()})}async function jp(e,t){if(!Hr(e,t))return;if(Dr&&Dr.api===e&&Dr.runId===t)return Dr.promise;yl({...jr,checking:!0});const s=Jk(e,t).finally(()=>{Dr?.promise===s&&(Dr=null),Hr(e,t)&&(yl({...jr,checking:!1,lastCheckedAt:Date.now()}),eT(e,t))});return Dr={api:e,runId:t,promise:s},s}async function Jk(e,t){try{const s=await e.listAgents();if(!Hr(e,t))return;const r=[{key:Xk,check:()=>e.checkUpdate()},...s.agents.map(c=>({key:c.id,check:()=>e.checkAgentUpdate(c.id)}))],o=new Map;if(await Promise.all(r.map(async c=>{try{const h=await c.check();o.set(c.key,gw(h))}catch{o.set(c.key,Lr.get(c.key)??!1)}})),!Hr(e,t))return;Lr.clear();for(const[c,h]of o)Lr.set(c,h);yl({...jr,hasUpdates:mg()})}catch{}}function eT(e,t){Hr(e,t)&&(pg(),Yo=window.setTimeout(()=>{Yo=null,Hr(e,t)&&jp(e,t)},mw))}function tT(){Ju+=1,pg(),fg=null,Dr=null,Lr.clear(),yl({checking:!1,hasUpdates:!1,lastCheckedAt:null})}function pg(){Yo!==null&&(window.clearTimeout(Yo),Yo=null)}function iT(){return Ju+=1,Ju}function Hr(e,t){return fg===e&&Ju===t}function gw(e){return e.updateAvailable===!0}function mg(){return Array.from(Lr.values()).some(Boolean)}function yl(e){jr=e;for(const t of Array.from(zp))t()}const nT=e=>new Promise(t=>setTimeout(t,e));function sT({api:e,onAgentRemoved:t}){const[s,r]=v.useState([{key:"local",id:null,name:"Local (main)"}]),[o,c]=v.useState({}),[h,f]=v.useState(!1),[g,p]=v.useState(null),[y,b]=v.useState(!1),[w,S]=v.useState(null),[E,T]=v.useState(!1),[A,O]=v.useState(null);function L(D,X){c(_e=>({..._e,[D]:{..._e[D],...X}}))}const U=D=>D.id===null?e.getVersion():e.getAgentVersion(D.id),I=D=>D.id===null?e.checkUpdate():e.checkAgentUpdate(D.id),te=D=>D.id===null?e.runUpdate():e.runAgentUpdate(D.id);v.useEffect(()=>{let D=!1;e.listAgents().then(_e=>{if(D)return;const R=[{key:"local",id:null,name:"Local (main)"},..._e.agents.map(H=>({key:H.id,id:H.id,name:H.name}))];r(R);for(const H of R)U(H).then(Q=>L(H.key,{version:Q,manualUpdate:Q.manualUpdate??null})).catch(Q=>L(H.key,{error:Q instanceof Error?Q.message:"unreachable"}))}).catch(()=>{});const X=e.getDistributedCallSettings;return typeof X=="function"&&X().then(_e=>{D||S(_e)}).catch(_e=>{D||O(_e instanceof Error?_e.message:"failed to load distributed call settings")}),()=>{D=!0}},[]);async function ee(D){L(D.key,{busy:!0,status:"checking…",error:void 0});try{const X=await I(D);Qk(D.key,X),L(D.key,{latestVersion:X.latestVersion,updateAvailable:X.updateAvailable,status:Y(X),...X.updateAvailable===!1?{manualUpdate:null}:{},busy:!1})}catch(X){L(D.key,{busy:!1,error:X instanceof Error?X.message:"check failed"})}}async function ae(){f(!0),await Promise.all(s.map(D=>ee(D))),f(!1)}async function ue(D,X){const _e=Date.now()+18e4;for(;Date.now()<_e;){await nT(3e3);try{const R=await U(D);if(X&&R.runningVersion!==X.runningVersion)return R}catch{}}return null}async function be(D){let X=o[D.key]?.version;if(!X)try{X=await U(D),L(D.key,{version:X,manualUpdate:X.manualUpdate??null})}catch(H){return L(D.key,{busy:!1,error:H instanceof Error?H.message:"version check failed"}),"failed"}L(D.key,{busy:!0,status:"updating…",error:void 0});let _e;try{_e=await te(D)}catch(H){return L(D.key,{busy:!1,error:H instanceof Error?H.message:"update failed"}),"failed"}if(!_e.ok){const H=_e.manualUpdate??(Vk(_e.message)?Yk():null);return H?(L(D.key,{busy:!1,status:"manual update required",error:void 0,manualUpdate:H}),"manual"):(L(D.key,{busy:!1,status:void 0,error:_e.message}),"failed")}if(!_e.changed)return L(D.key,{busy:!1,status:"already up to date",updateAvailable:!1,manualUpdate:null}),Ff(D.key),"unchanged";L(D.key,{status:"restarting…"});const R=await ue(D,X);return R?(L(D.key,{busy:!1,version:R,updateAvailable:!1,status:"updated",manualUpdate:R.manualUpdate??null}),Ff(D.key),D.id===null&&(b(!0),p("Main server updated. Reload the page to use the new client.")),"updated"):(L(D.key,{busy:!1,status:void 0,error:"timed out — check the server log"}),"failed")}async function we(D){if(!(D.id===null||!window.confirm([`Delete secondary server "${D.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(`
15
- `)))){L(D.key,{busy:!0,status:"deleting…",error:void 0}),p(null);try{const _e=await e.uninstallAgent(D.id);r(R=>R.filter(H=>H.key!==D.key)),c(R=>{const H={...R};return delete H[D.key],H}),Ff(D.key),t?.(D.id),p(_e.message)}catch(_e){L(D.key,{busy:!1,status:void 0,error:_e instanceof Error?_e.message:"delete failed"})}}}async function ne(){f(!0),p(null);const D=s.filter(de=>de.id!==null),X=s.find(de=>de.id===null),_e=await Promise.all(D.map(de=>be(de))),R=_e.filter(de=>de==="failed").length;let H=_e.filter(de=>de==="manual").length,Q=null;if(X&&(Q=await be(X),Q==="manual"&&(H+=1),Q==="updated")){R>0&&p("Main server updated. Reload the page to use the new client. Some secondary servers failed; check their rows and retry."),f(!1);return}R>0&&H>0?p("Some servers failed and some need manual update. Check each marked row."):R>0?p("Some secondary servers failed to update. Check their rows and retry."):H>0&&p("Some servers need manual update. Copy and run the command shown on each marked server."),f(!1)}function ie(D){return D?D.error?D.error:D.status?D.status:D.manualUpdate?"manual update required":D.version?`v${D.version.version}`:"…":"…"}function Y(D){return D.error?D.error:typeof D.updateAvailable=="boolean"?D.updateAvailable?`latest v${D.latestVersion??"available"}`:"up to date":"unknown"}function K(D){const X=D?.version;return X?`npm package v${X.runningVersion}`:""}async function re(D,X){try{await rT(X),L(D,{copiedCommand:!0}),window.setTimeout(()=>L(D,{copiedCommand:!1}),1800)}catch(_e){L(D,{error:_e instanceof Error?_e.message:"copy failed"})}}async function B(D){if(!(!w||E)){T(!0),O(null);try{const X=await e.updateDistributedCallSettings(D);S(X)}catch(X){O(X instanceof Error?X.message:"failed to save distributed call settings")}finally{T(!1)}}}function $(D,X){if(!w)return;const _e=new Set(w.settings.workerIds);X?_e.add(D):_e.delete(D),B({workerIds:Array.from(_e)})}return m.jsxs("section",{className:"security-section",children:[m.jsx("h3",{children:"Servers"}),m.jsxs("div",{className:"update-actions",children:[m.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{ae()},disabled:h,children:"Check for updates"}),m.jsx("button",{type:"button",onClick:()=>{ne()},disabled:h,children:"Update all"})]}),g?m.jsx("p",{className:"settings-status",children:g}):null,y?m.jsxs("div",{className:"server-reload-required",role:"status",children:[m.jsx("span",{children:"Main server update is ready."}),m.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:"Reload page"})]}):null,m.jsxs("div",{className:"server-addon-panel",children:[m.jsxs("div",{className:"server-addon-header",children:[m.jsxs("div",{children:[m.jsx("span",{className:"security-item-label",children:"Distributed calls"}),m.jsx("span",{className:"security-item-meta",children:"Programmatic worker fan-out for trusted NTerminal servers."})]}),m.jsxs("label",{className:"auth-checkbox server-addon-toggle",children:[m.jsx("input",{type:"checkbox",checked:w?.settings.enabled??!1,disabled:!w||E,onChange:D=>{B({enabled:D.currentTarget.checked})}}),"Enabled"]})]}),m.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[m.jsx("input",{type:"checkbox",checked:w?.settings.allowPrivateTargets??!1,disabled:!w||E||!(w?.settings.enabled??!1),onChange:D=>{B({allowPrivateTargets:D.currentTarget.checked})}}),"Allow private network targets when the CLI also requests it"]}),w?m.jsx("div",{className:"server-addon-workers","aria-label":"Distributed call workers",children:w.workers.map(D=>m.jsxs("label",{className:"auth-checkbox server-addon-worker",children:[m.jsx("input",{type:"checkbox",checked:D.enabled,disabled:E||!w.settings.enabled,onChange:X=>$(D.id,X.currentTarget.checked)}),m.jsx("span",{children:D.id===Nr?"Local (main)":D.name})]},D.id))}):null,A?m.jsx("p",{className:"settings-status settings-status-error",children:A}):null]}),m.jsx("ul",{className:"security-list",children:s.map(D=>{const X=o[D.key],_e=K(X),R=X?.manualUpdate??null,H=X?.version!==void 0&&X?.updateAvailable!==!1&&!X?.busy&&!h,Q=D.id!==null&&!X?.busy&&!h;return m.jsxs("li",{children:[m.jsxs("div",{className:"server-row-main",children:[m.jsxs("div",{children:[m.jsx("span",{className:"security-item-label",children:D.name}),m.jsxs("span",{className:"security-item-meta",children:[_e?`${_e} — `:"",ie(X)]})]}),R?m.jsxs("div",{className:"server-manual-update",children:[m.jsx("span",{children:R.message}),m.jsxs("div",{className:"server-manual-command",children:[m.jsx("code",{children:R.command}),m.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{re(D.key,R.command)},children:X?.copiedCommand?"Copied":"Copy"})]})]}):null]}),m.jsxs("div",{className:"server-row-actions",children:[m.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{be(D)},disabled:!H,children:X?.busy?"…":"Update"}),D.id!==null?m.jsx("button",{type:"button",className:"server-delete-button",onClick:()=>{we(D)},disabled:!Q,children:"Delete"}):null]})]},D.key)})})]})}async function rT(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 xu=[{id:"appearance",label:"Appearance"},{id:"shortcuts",label:"Shortcuts"},{id:"notifications",label:"Notifications"},{id:"security",label:"Security"},{id:"diagnostics",label:"Diagnostics"},{id:"servers",label:"Servers"}];function aT({onClose:e,api:t,updateAvailable:s=!1,onNotificationAssetsChanged:r,onAgentRemoved:o}){const c=v.useMemo(()=>t??fh(),[t]),[h,f]=v.useState(()=>Np()),[g,p]=v.useState(()=>Ap()),[y,b]=v.useState(()=>Bp()),[w,S]=v.useState(()=>Or()),[E,T]=v.useState(()=>Sa()),[A,O]=v.useState(null),[L,U]=v.useState(null),[I,te]=v.useState("appearance"),[ee,ae]=v.useState(()=>J0()),[ue,be]=v.useState(()=>ya()),[we,ne]=v.useState(()=>sg()),[ie,Y]=v.useState([]),[K,re]=v.useState([]),[B,$]=v.useState([]),[D,X]=v.useState(5*1024*1024),[_e,R]=v.useState(!1),[H,Q]=v.useState(null),[de,ke]=v.useState(()=>ma()),[xe,Re]=v.useState(!1),[Xe,ge]=v.useState(null),G=v.useRef(null),ce=v.useRef(null),Ce=v.useRef({appearance:null,shortcuts:null,notifications:null,security:null,diagnostics:null,servers:null}),ye=v.useMemo(()=>new Set(K),[K]),De=!uT(K,B);v.useEffect(()=>rw(()=>f(Np())),[]),v.useEffect(()=>aw(()=>p(Ap())),[]),v.useEffect(()=>lw(()=>b(Bp())),[]),v.useEffect(()=>qm(()=>S(Or())),[]),v.useEffect(()=>ug(()=>T(Sa())),[]),v.useEffect(()=>ew(()=>be(ya())),[]),v.useEffect(()=>{const F=()=>ke(ma());F();const qe=window.setInterval(F,1500);return()=>window.clearInterval(qe)},[]),v.useEffect(()=>{if(!A)return;const F=Jo.find(dt=>dt.id===A);if(!F)return;const qe=dt=>{if(dt.preventDefault(),dt.stopPropagation(),dt.key==="Escape"){O(null),U(null);return}const vt=Hk(dt,F);if(!vt){U(cT(F));return}T(Ok(A,vt)),O(null),U(null)};return window.addEventListener("keydown",qe,!0),()=>window.removeEventListener("keydown",qe,!0)},[A]),v.useEffect(()=>{let F=!1;return c.listNotificationAssets().then(qe=>{F||He(qe)}).catch(qe=>{F||Q(ol(qe))}),()=>{F=!0}},[c]);function Be(F){f(Cu(Number(F)))}function Ke(F){be(Hy(Number(F)))}function le(F){te(F);const qe=ce.current,dt=Ce.current[F];if(!qe||!dt)return;const vt=Math.max(0,Iy(dt,qe)-12);typeof qe.scrollTo=="function"?qe.scrollTo({top:vt,behavior:"smooth"}):qe.scrollTop=vt}function Ee(){const F=ce.current;if(!F)return;if(F.scrollTop+F.clientHeight>=F.scrollHeight-2){te(xu[xu.length-1].id);return}let qe="appearance";const dt=F.scrollTop+Math.min(180,Math.max(48,F.clientHeight*.28));for(const vt of xu){const pi=Ce.current[vt.id];pi&&Iy(pi,F)<=dt&&(qe=vt.id)}te(qe)}function Le(F){T(zk(F)),O(null),U(null)}function Oe(){T(jk()),O(null),U(null)}function He(F){const qe=F.assets.filter(dt=>dt.enabled).map(dt=>dt.id);Y(F.assets),re(qe),$(qe),X(F.maxFileBytes),Q(null)}async function _t(){if(ee){jy(!1),ae(!1);return}let F=we;F==="default"&&(F=await Rk(),ne(F)),F==="granted"&&(jy(!0),ae(!0))}async function Ye(F){const qe=F?.[0];if(qe){if(qe.size>D){Q(`File must be ${Wf(D)} or smaller.`),Oi();return}if(qe.type!=="video/mp4"&&qe.type!=="video/webm"){Q("Upload an MP4 or WebM video."),Oi();return}R(!0),Q(null);try{await c.uploadNotificationAsset(qe),He(await c.listNotificationAssets()),r?.()}catch(dt){Q(ol(dt))}finally{R(!1),Oi()}}}async function rt(F){R(!0),Q(null);try{await c.deleteNotificationAsset(F),He(await c.listNotificationAssets()),r?.()}catch(qe){Q(ol(qe))}finally{R(!1)}}function Oi(){G.current&&(G.current.value="")}function $i(F,qe){const dt=new Set(K);if(qe?dt.add(F):dt.delete(F),dt.size===0){Q("Keep at least one toast video selected.");return}Q(null),re(Array.from(dt))}async function Ci(){if(K.length===0){Q("Keep at least one toast video selected.");return}R(!0),Q(null);try{const F=await c.updateNotificationAssetSelection({enabledAssetIds:K});He(F),r?.()}catch(F){Q(ol(F))}finally{R(!1)}}async function ri(){ge(null),Re(!0);try{const F=await uk();ge(F?"Diagnostics copied.":"Copy failed in this browser."),ke(ma())}catch(F){ge(ol(F))}finally{Re(!1)}}async function zi(){ge(null),Re(!0);try{const F=await bh("manual-settings");ge(`Sent ${F.accepted} diagnostic events.`),ke(ma())}catch(F){ge(ol(F))}finally{Re(!1)}}function sn(){ok(),ke([]),ge("Diagnostics cleared.")}return m.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-label":"Settings",onClick:e,children:m.jsxs("div",{className:"security-panel settings-panel",onClick:F=>F.stopPropagation(),children:[m.jsxs("header",{className:"security-panel-header",children:[m.jsx("h2",{children:"Settings"}),m.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:e,children:"×"})]}),m.jsxs("div",{className:"settings-layout",children:[m.jsx("nav",{className:"settings-nav","aria-label":"Settings categories",children:xu.map(F=>m.jsxs("button",{type:"button","data-active":I===F.id?"true":"false","aria-current":I===F.id?"true":void 0,onClick:()=>le(F.id),children:[F.label,F.id==="servers"&&s?m.jsx("span",{className:"update-pulse-dot settings-update-dot","aria-hidden":"true"}):null]},F.id))}),m.jsxs("div",{ref:ce,className:"settings-content",onScroll:Ee,children:[m.jsxs("section",{id:"settings-appearance",ref:F=>{Ce.current.appearance=F},className:"security-section settings-section",children:[m.jsx("h3",{children:"Appearance"}),m.jsx("div",{className:"settings-section-heading",children:m.jsxs("div",{children:[m.jsx("span",{className:"settings-control-title",children:"Theme"}),m.jsx("p",{className:"muted settings-control-description",children:"Choose the workspace and terminal color preset."})]})}),m.jsx("div",{className:"settings-theme-picker",role:"radiogroup","aria-label":"Interface theme",children:Yu.map(F=>m.jsxs("button",{type:"button",className:"settings-theme-card",role:"radio","aria-checked":w===F.id,"data-active":w===F.id?"true":"false",onClick:()=>S(hE(F.id)),style:{"--settings-theme-bg":F.tokens.bg,"--settings-theme-bg-2":F.tokens.bg2,"--settings-theme-sidebar":F.tokens.bgSidebar,"--settings-theme-line":F.tokens.line,"--settings-theme-fg":F.tokens.fg,"--settings-theme-fg-2":F.tokens.fg2,"--settings-theme-accent":F.tokens.accent,"--settings-theme-xterm-bg":F.xterm.background,"--settings-theme-xterm-fg":F.xterm.foreground,"--settings-theme-xterm-selection":F.xterm.selectionBackground},children:[m.jsxs("span",{className:"settings-theme-preview","aria-hidden":"true",children:[m.jsxs("span",{className:"settings-theme-preview-sidebar",children:[m.jsx("span",{}),m.jsx("span",{}),m.jsx("span",{})]}),m.jsxs("span",{className:"settings-theme-preview-main",children:[m.jsxs("span",{className:"settings-theme-preview-tabs",children:[m.jsx("span",{}),m.jsx("span",{})]}),m.jsxs("span",{className:"settings-theme-preview-terminal",children:[m.jsx("span",{}),m.jsx("span",{}),m.jsx("span",{})]})]})]}),m.jsxs("span",{className:"settings-theme-card-copy",children:[m.jsx("strong",{children:F.label}),m.jsx("small",{children:F.description})]})]},F.id))}),m.jsxs("label",{className:"settings-control",children:[m.jsx("span",{children:"Font size"}),m.jsxs("span",{className:"settings-control-value",children:[h,"px"]}),m.jsx("input",{type:"range",min:Dp,max:Rp,step:1,value:h,"aria-label":"Terminal font size",onChange:F=>Be(F.currentTarget.value)})]}),m.jsxs("div",{className:"settings-stepper-row",children:[m.jsx("button",{type:"button",className:"secondary-button settings-stepper-button",onClick:()=>f(Cu(h-1)),children:"-"}),m.jsx("input",{type:"number",min:Dp,max:Rp,step:1,value:h,"aria-label":"Terminal font size value",onChange:F=>Be(F.currentTarget.value)}),m.jsx("button",{type:"button",className:"secondary-button settings-stepper-button",onClick:()=>f(Cu(h+1)),children:"+"}),m.jsx("button",{type:"button",className:"secondary-button settings-reset-button",onClick:()=>f(Cu(_a)),children:"Reset"})]}),m.jsxs("label",{className:"settings-control",children:[m.jsx("span",{children:"Font family"}),m.jsx("select",{value:g,"aria-label":"Terminal font family",onChange:F=>p(Ak(F.currentTarget.value)),children:Qu.map(F=>m.jsx("option",{value:F.id,children:F.label},F.id))})]}),m.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[m.jsx("input",{type:"checkbox",checked:y,onChange:F=>b(Lk(F.currentTarget.checked))}),"Show scroll progress"]})]}),m.jsxs("section",{id:"settings-shortcuts",ref:F=>{Ce.current.shortcuts=F},className:"security-section settings-section",children:[m.jsxs("div",{className:"settings-section-heading",children:[m.jsx("h3",{children:"Shortcuts"}),m.jsx("button",{type:"button",className:"secondary-button settings-reset-button",onClick:Oe,children:"Reset all"})]}),m.jsx("p",{className:"muted",children:"Defaults avoid Chrome's browser-tab shortcuts. Click a shortcut, then press the new key combo."}),L?m.jsx("p",{className:"settings-error",children:L}):null,m.jsx("ul",{className:"settings-shortcut-list","aria-label":"Workspace shortcuts",children:Jo.map(F=>{const qe=A===F.id;return m.jsxs("li",{children:[m.jsxs("div",{children:[m.jsx("span",{className:"settings-shortcut-label",children:F.label}),m.jsx("span",{className:"settings-shortcut-group",children:F.group})]}),m.jsxs("div",{className:"settings-shortcut-actions",children:[m.jsx("button",{type:"button",className:"settings-shortcut-recorder","data-recording":qe?"true":"false",onClick:()=>{O(F.id),U(null)},children:qe?"Press keys…":cw(E[F.id])}),m.jsx("button",{type:"button",className:"secondary-button settings-shortcut-reset",onClick:()=>Le(F.id),children:"Reset"})]})]},F.id)})})]}),m.jsxs("section",{id:"settings-notifications",ref:F=>{Ce.current.notifications=F},className:"security-section settings-section",children:[m.jsx("h3",{children:"Notifications"}),Sh()?m.jsxs(m.Fragment,{children:[m.jsxs("label",{className:"auth-checkbox",children:[m.jsx("input",{type:"checkbox",checked:ee&&we==="granted",onChange:()=>{_t()},disabled:we==="denied"}),"System notification when page is hidden"]}),we==="denied"?m.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."}):m.jsx("p",{className:"muted",children:"Uses browser notifications only when this page isn't visible. Animated toast is controlled separately below."})]}):m.jsx("p",{className:"muted",children:"This browser doesn't expose the Notification API; animated toast and in-app badges can still work."}),m.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[m.jsx("input",{type:"checkbox",checked:ue.enabled,onChange:F=>be(xk(F.currentTarget.checked))}),"Show animated completion toast"]}),m.jsxs("label",{className:"settings-control",children:[m.jsx("span",{children:"Toast duration"}),m.jsx("span",{className:"settings-control-value",children:ue.persistUntilDismissed?"Until closed":`${ue.durationSeconds}s`}),m.jsx("input",{type:"range",min:xp,max:Ep,step:.5,value:ue.durationSeconds,disabled:!ue.enabled||ue.persistUntilDismissed,"aria-label":"Completion toast duration",onChange:F=>Ke(F.currentTarget.value)})]}),m.jsxs("div",{className:"settings-stepper-row settings-duration-row",children:[m.jsx("input",{type:"number",min:xp,max:Ep,step:.5,value:ue.durationSeconds,disabled:!ue.enabled||ue.persistUntilDismissed,"aria-label":"Completion toast duration value",onChange:F=>Ke(F.currentTarget.value)}),m.jsx("button",{type:"button",className:"secondary-button settings-reset-button",disabled:!ue.enabled||ue.persistUntilDismissed,onClick:()=>be(Hy($o)),children:"Reset"})]}),m.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[m.jsx("input",{type:"checkbox",checked:ue.persistUntilDismissed,disabled:!ue.enabled,onChange:F=>be(Ek(F.currentTarget.checked))}),"Keep toast until dismissed"]}),m.jsxs("div",{className:"settings-assets-header",children:[m.jsx("span",{children:"Toast videos"}),m.jsxs("span",{children:[Wf(D)," max"]})]}),m.jsx("input",{ref:G,type:"file",accept:"video/mp4,video/webm",className:"settings-asset-input","aria-label":"Upload toast video",onChange:F=>{Ye(F.currentTarget.files)}}),m.jsx("button",{type:"button",className:"secondary-button settings-upload-button",disabled:_e,onClick:()=>G.current?.click(),children:"Upload video"}),H?m.jsx("p",{className:"settings-error",children:H}):null,ie.length>0?m.jsx("ul",{className:"settings-asset-list","aria-label":"Toast videos",children:ie.map(F=>m.jsxs("li",{"data-enabled":ye.has(F.id)?"true":"false",children:[m.jsxs("label",{className:"settings-asset-choice",children:[m.jsx("input",{type:"checkbox",checked:ye.has(F.id),disabled:_e,"aria-label":`Use ${F.filename}`,onChange:qe=>$i(F.id,qe.currentTarget.checked)}),m.jsx("video",{src:F.url,muted:!0,autoPlay:!0,loop:!0,playsInline:!0,"aria-hidden":"true"}),m.jsxs("span",{className:"settings-asset-copy",children:[m.jsx("span",{children:F.filename}),m.jsx("small",{children:F.source==="built-in"?"Built-in":Wf(F.size)})]})]}),F.source==="uploaded"?m.jsx("button",{type:"button",className:"secondary-button settings-asset-delete",disabled:_e,"aria-label":`Delete ${F.filename}`,onClick:()=>{rt(F.id)},children:"x"}):null]},F.id))}):m.jsx("p",{className:"muted",children:"Built-in videos will be used."}),m.jsx("button",{type:"button",className:"secondary-button settings-save-assets-button",disabled:_e||ie.length===0||!De,onClick:()=>{Ci()},children:"Save selected videos"})]}),m.jsx("div",{id:"settings-security",ref:F=>{Ce.current.security=F},className:"settings-section-group",children:m.jsx(sk,{api:c})}),m.jsxs("section",{id:"settings-diagnostics",ref:F=>{Ce.current.diagnostics=F},className:"security-section settings-section",children:[m.jsxs("div",{className:"settings-section-heading",children:[m.jsxs("div",{children:[m.jsx("h3",{children:"Diagnostics"}),m.jsx("p",{className:"muted settings-control-description",children:"Recent browser lifecycle and auth transition events for troubleshooting."})]}),m.jsx("span",{className:"settings-diagnostics-count",children:de.length})]}),m.jsxs("div",{className:"settings-diagnostics-actions",children:[m.jsx("button",{type:"button",className:"secondary-button",disabled:xe||de.length===0,onClick:()=>{ri()},children:"Copy"}),m.jsx("button",{type:"button",className:"secondary-button",disabled:xe||de.length===0,onClick:()=>{zi()},children:"Send"}),m.jsx("button",{type:"button",className:"secondary-button",disabled:xe||de.length===0,onClick:sn,children:"Clear"})]}),Xe?m.jsx("p",{className:"settings-status",children:Xe}):null,de.length>0?m.jsx("ol",{className:"settings-diagnostics-list","aria-label":"Recent diagnostics",children:de.slice(-8).reverse().map((F,qe)=>m.jsxs("li",{children:[m.jsx("span",{children:lT(F.at)}),m.jsx("strong",{children:F.event}),F.data?m.jsx("code",{children:oT(F.data)}):null]},`${F.at}:${F.event}:${qe}`))}):m.jsx("p",{className:"muted",children:"No diagnostics recorded yet."})]}),m.jsx("div",{id:"settings-servers",ref:F=>{Ce.current.servers=F},className:"settings-section-group",children:m.jsx(sT,{api:c,...o?{onAgentRemoved:o}:{}})})]})]})]})})}function Iy(e,t){const s=e.getBoundingClientRect(),r=t.getBoundingClientRect();return s.top-r.top+t.scrollTop}function Wf(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 ol(e){return e instanceof Error?e.message:"Request failed."}function lT(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function oT(e){return Object.entries(e).slice(0,5).map(([t,s])=>`${t}=${String(s)}`).join(" ")}function cT(e){return e.indexed?"Press a shortcut ending in a number from 1 to 9.":e.requiresPrimaryModifier?"Use Ctrl, Alt, or Meta with another key.":"Press a complete shortcut."}function uT(e,t){if(e.length!==t.length)return!1;const s=new Set(t);return e.every(r=>s.has(r))}class oa extends Error{constructor(t,s){super(s),this.status=t,this.name="UploadClientError"}status}function hT(e){const t=e.createXhr?.()??new XMLHttpRequest,s=new FormData,r=e.files.map((o,c)=>({fieldName:`file${c}`,relativePath:o.relativePath,size:o.file.size}));s.append("manifest",JSON.stringify({terminalId:e.terminalId,entries:r}));for(const[o,c]of e.files.entries())s.append(`file${o}`,c.file);return new Promise((o,c)=>{let h=!1;const f=()=>{e.signal?.removeEventListener("abort",y)},g=b=>{h||(h=!0,f(),o(b))},p=b=>{h||(h=!0,f(),c(b))},y=()=>{t.abort(),p(new oa(0,"Upload aborted."))};if(e.signal?.aborted){p(new oa(0,"Upload aborted."));return}e.signal?.addEventListener("abort",y,{once:!0}),t.open("POST","/api/uploads"),t.withCredentials=!0,t.upload.onprogress=b=>{if(e.onProgress){if(b.lengthComputable&&b.total>0){e.onProgress({loaded:b.loaded,total:b.total,percent:Math.round(b.loaded/b.total*100)});return}e.onProgress({loaded:b.loaded,total:null,percent:null})}},t.onload=()=>{if(t.status>=200&&t.status<300){try{g(JSON.parse(t.responseText))}catch{p(new oa(t.status,"Invalid upload response."))}return}p(new oa(t.status,dT(t.responseText,t.statusText||`HTTP ${t.status}`)))},t.onerror=()=>p(new oa(0,"Upload failed.")),t.onabort=()=>p(new oa(0,"Upload aborted.")),t.ontimeout=()=>p(new oa(0,"Upload timed out.")),t.send(s)})}function dT(e,t){try{const s=JSON.parse(e),r=typeof s.error=="string"?s.error:s.message;if(typeof r=="string"&&r.trim())return r}catch{}return t}const fT="modulepreload",pT=function(e){return"/"+e},Ky={},gg=function(t,s,r){let o=Promise.resolve();if(s&&s.length>0){let g=function(p){return Promise.all(p.map(y=>Promise.resolve(y).then(b=>({status:"fulfilled",value:b}),b=>({status:"rejected",reason:b}))))};document.getElementsByTagName("link");const h=document.querySelector("meta[property=csp-nonce]"),f=h?.nonce||h?.getAttribute("nonce");o=g(s.map(p=>{if(p=pT(p),p in Ky)return;Ky[p]=!0;const y=p.endsWith(".css"),b=y?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${b}`))return;const w=document.createElement("link");if(w.rel=y?"stylesheet":fT,y||(w.as="script"),w.crossOrigin="",w.href=p,f&&w.setAttribute("nonce",f),document.head.appendChild(w),y)return new Promise((S,E)=>{w.addEventListener("load",S),w.addEventListener("error",()=>E(new Error(`Unable to preload CSS for ${p}`)))})}))}function c(h){const f=new Event("vite:preloadError",{cancelable:!0});if(f.payload=h,window.dispatchEvent(f),!f.defaultPrevented)throw h}return o.then(h=>{for(const f of h||[])f.status==="rejected"&&c(f.reason);return t().catch(c)})},mT=v.lazy(()=>gg(()=>import("./MarkdownPreview-BqsqJZK7.js"),__vite__mapDeps([0,1])));function gT({api:e,activeTerminalId:t,activeTerminalCwd:s,workspaceRootPath:r=null,onOpenFile:o}){const[c,h]=v.useState(null),[f,g]=v.useState(""),[p,y]=v.useState({}),[b,w]=v.useState(()=>new Set),[S,E]=v.useState(null),[T,A]=v.useState({type:"empty"}),[O,L]=v.useState("idle"),[U,I]=v.useState(null),te=v.useRef(null),ee=v.useRef(null),ae=v.useRef(!1),ue=v.useRef(0),be=v.useRef(null);be.current===null&&t&&(be.current=t);const we=be.current,ne=r?vT(r):t?Fy(t,s):null,ie=c?[c.rootPath,f].filter(Boolean).join("/"):"",Y=S?.path??null;v.useEffect(()=>(ae.current=!0,()=>{ae.current=!1,ue.current+=1,ce()}),[]),v.useEffect(()=>{be.current=t,ee.current=null,K(ne)},[e]),v.useEffect(()=>{r&&ne!==ee.current&&re(r,ne)},[r,ne]),v.useEffect(()=>{if(r||!we||t!==we)return;const le=Fy(we,s);le!==ee.current&&B(we,le)},[we,t,s,r]);async function K(le=ne){if(r){await re(r,le);return}await B(t,le)}async function re(le,Ee=ne){const Le=Ce();if(ee.current=Ee,ce(),h(null),g(""),y({}),w(new Set),E(null),A({type:"empty"}),I(null),!le){L("idle");return}L("loading");try{const Oe=await e.createFileRoot({path:le});if(!ye(Le))return;h({rootToken:Oe.rootToken,rootPath:Oe.rootPath});const He=await e.listFiles({rootToken:Oe.rootToken,path:""});if(!ye(Le))return;X(He),L("idle")}catch(Oe){ye(Le)&&(I(Ws(Oe)),L("idle"))}}async function B(le,Ee=ne){const Le=Ce();if(ee.current=Ee,ce(),h(null),g(""),y({}),w(new Set),E(null),A({type:"empty"}),I(null),!le){L("idle");return}L("loading");try{const Oe=await e.createFileRoot({terminalId:le});if(!ye(Le))return;h({rootToken:Oe.rootToken,rootPath:Oe.rootPath});const He=await e.listFiles({rootToken:Oe.rootToken,path:""});if(!ye(Le))return;X(He),L("idle")}catch(Oe){if(await De(Oe,Le))return;ye(Le)&&(I(Ws(Oe)),L("idle"))}}async function $(le=f,Ee=c){if(!Ee)return;const Le=Ce();L("loading"),I(null);try{const Oe=await e.listFiles({rootToken:Ee.rootToken,path:le});if(!ye(Le))return;X(Oe),L("idle")}catch(Oe){if(await De(Oe,Le))return;ye(Le)&&(I(Ws(Oe)),L("idle"))}}async function D(){if(r){await re(r,ne);return}be.current=t,await B(t,ne)}function X(le){y(Ee=>({...Ee,[le.path]:bT(le.entries)}))}async function _e(le){if(!(!qf(le)||!c)){if(E(le),I(null),le.kind==="directory"){g(le.path),G(),await H(le);return}if(g(ca(le.path)),le.editable){await de(le);return}le.previewKind!=="none"&&await xe(le,le.previewKind)}}async function R(le){if(!(!qf(le)||!c)){if(E(le),I(null),le.kind==="directory"){g(le.path),G(),await H(le);return}if(g(ca(le.path)),le.editable){await ke(le);return}le.previewKind!=="none"&&await xe(le,le.previewKind)}}async function H(le){if(b.has(le.path)){w(Ee=>{const Le=new Set(Ee);return Le.delete(le.path),Le});return}w(Ee=>new Set(Ee).add(le.path)),await $(le.path)}function Q(le,Ee){le.key==="Enter"&&(le.preventDefault(),R(Ee))}async function de(le){if(!c)return;const Ee=Ce();L("loading"),ce();try{const Le=await e.readFile({rootToken:c.rootToken,path:le.path});if(!ye(Ee))return;A({type:"text-preview",file:le,read:Le}),L("idle")}catch(Le){if(await De(Le,Ee))return;ye(Ee)&&(I(Ws(Le)),L("idle"))}}async function ke(le){if(!c)return;const Ee=Ce();L("loading");try{await o({rootToken:c.rootToken,path:le.path,...t?{terminalId:t}:{}}),ye(Ee)&&L("idle")}catch(Le){if(await De(Le,Ee))return;ye(Ee)&&(I(Ws(Le)),L("idle"))}}async function xe(le,Ee){if(!c)return;const Le=Ce();L("loading"),ce();try{const Oe=await e.previewFile({rootToken:c.rootToken,path:le.path});if(!ye(Le))return;const He=URL.createObjectURL(Oe);if(!ye(Le)){URL.revokeObjectURL(He);return}te.current=He,A({type:"preview",file:le,previewKind:Ee,url:He}),L("idle")}catch(Oe){if(await De(Oe,Le))return;ye(Le)&&(I(Ws(Oe)),L("idle"))}}async function Re(le){if(!c)return;const Ee=le==="file"?"New file":"New folder",Le=window.prompt(Ee,""),Oe=S?S.kind==="directory"?S.path:ca(S.path):f,He=Wy(Le,Oe);if(He){I(null);try{const _t=await e.createFileEntry({rootToken:c.rootToken,path:He,kind:le});E(_t.entry),await $(Oe)}catch(_t){if(await De(_t))return;I(Ws(_t))}}}async function Xe(){if(!c||!S)return;const le=window.prompt("Move selected entry",S.path),Ee=Wy(le,"");if(!Ee||Ee===S.path)return;const Le=ca(S.path),Oe=ca(Ee);I(null);try{const He=await e.moveFileEntry({rootToken:c.rootToken,sourcePath:S.path,destinationPath:Ee});E(He.entry),g(He.entry.kind==="directory"?He.entry.path:ca(He.entry.path)),G(),await $(Le),Oe!==Le&&await $(Oe)}catch(He){if(await De(He))return;I(Ws(He))}}async function ge(){if(!c||!S)return;const le=S.path,Ee=ca(le);I(null);try{const Le=await e.previewDeleteFileEntry({rootToken:c.rootToken,path:S.path}),Oe=Le.descendantCount>0?` and ${Le.descendantCount} nested item${Le.descendantCount===1?"":"s"}`:"";if(!window.confirm(`Delete ${Le.path}${Oe}?`))return;await e.deleteFileEntry({rootToken:c.rootToken,path:S.path,previewToken:Le.previewToken}),E(null),g(Ee),w(He=>{const _t=new Set(He);for(const Ye of He)(Ye===le||Ye.startsWith(`${le}/`))&&_t.delete(Ye);return _t}),G(),await $(Ee)}catch(Le){if(await De(Le))return;I(Ws(Le))}}function G(){ue.current+=1,ce(),A({type:"empty"})}function ce(){te.current&&(URL.revokeObjectURL(te.current),te.current=null)}function Ce(){return ue.current+=1,ue.current}function ye(le){return ae.current&&le===ue.current}async function De(le,Ee){return yT(le)?(Ee!==void 0&&!ye(Ee)||await K(ne),!0):!1}function Be(le,Ee){const Le=qf(le),Oe=le.kind==="directory"&&b.has(le.path),He=p[le.path]??[],_t={"--file-tree-depth":Ee};return m.jsxs(Si.Fragment,{children:[m.jsxs("button",{type:"button",className:"file-entry-button","data-kind":le.kind,"data-expanded":Oe,"data-active":Y===le.path,disabled:!Le,style:_t,"aria-expanded":le.kind==="directory"?Oe:void 0,"aria-label":`${le.kind==="directory"?"Open folder":"Open file"} ${le.name}`,title:le.kind==="directory"?"Expand or collapse folder":"Click to preview. Double-click or press Enter to open.",onClick:()=>{_e(le)},onDoubleClick:()=>{R(le)},onKeyDown:Ye=>Q(Ye,le),children:[m.jsx("span",{className:"file-entry-disclosure","aria-hidden":"true",children:le.kind==="directory"?Oe?"▾":"▸":""}),m.jsx("span",{className:"file-entry-name",children:le.name}),m.jsx("small",{children:_T(le)})]}),Oe?m.jsx("div",{className:"file-tree-children",role:"group",children:He.map(Ye=>Be(Ye,Ee+1))}):null]},le.path)}const Ke=p[""]??[];return m.jsxs("section",{className:"file-explorer","aria-label":"Files","aria-busy":O==="loading",children:[m.jsxs("header",{className:"file-explorer-header",children:[m.jsx("div",{className:"file-explorer-path",title:ie,children:ie||"No active pane"}),m.jsxs("div",{className:"file-explorer-toolbar","aria-label":"File actions",children:[m.jsx("button",{type:"button","aria-label":"Refresh files",title:"Refresh",disabled:!r&&!t,onClick:()=>{D()},children:"↻"}),m.jsx("button",{type:"button","aria-label":"New file",title:"New file",disabled:!c,onClick:()=>{Re("file")},children:"+"}),m.jsx("button",{type:"button","aria-label":"New folder",title:"New folder",disabled:!c,onClick:()=>{Re("directory")},children:"▣"})]})]}),U?m.jsx("div",{className:"file-explorer-alert",role:"alert",children:U}):null,m.jsxs("div",{className:"file-explorer-layout",children:[m.jsx("div",{className:"file-tree","aria-label":ie?`Files in ${ie}`:"Files",children:Ke.map(le=>Be(le,0))}),m.jsxs("section",{className:"file-detail","aria-label":"File detail",children:[m.jsxs("div",{className:"file-detail-header",children:[m.jsx("strong",{children:S?.name??"detail"}),m.jsxs("div",{className:"file-detail-actions",children:[m.jsx("button",{type:"button","aria-label":"Move selected entry",disabled:!S,onClick:()=>{Xe()},children:"Move"}),m.jsx("button",{type:"button","aria-label":"Delete selected entry",disabled:!S,onClick:()=>{ge()},children:"Delete"})]})]}),O==="loading"?m.jsx("div",{className:"file-detail-empty",children:"loading"}):null,T.type==="empty"&&O!=="loading"?m.jsx("div",{className:"file-detail-empty",children:"No file selected"}):null,T.type==="preview"?m.jsxs("div",{className:"file-preview-frame",children:[T.previewKind==="image"?m.jsx("img",{src:T.url,alt:T.file.name}):null,T.previewKind==="pdf"?m.jsx("iframe",{src:T.url,title:T.file.name}):null]}):null,T.type==="text-preview"&&T.read.language==="markdown"?m.jsx("div",{className:"file-markdown-preview","aria-label":`Preview for ${T.file.name}`,children:m.jsx(v.Suspense,{fallback:m.jsx("div",{className:"file-markdown-preview-loading",children:"loading preview"}),children:m.jsx(mT,{content:T.read.content})})}):null,T.type==="text-preview"&&T.read.language==="text"?m.jsx("pre",{className:"file-text-preview","aria-label":`Preview for ${T.file.name}`,children:T.read.content}):null]})]})]})}function qf(e){return e.kind==="directory"||e.editable||e.previewKind!=="none"}function _T(e){return e.kind==="directory"?"dir":e.editable?"edit":e.previewKind!=="none"?e.previewKind:"unsupported"}function Fy(e,t){return`${e}\0${t??""}`}function vT(e){return`workspace\0${e}`}function bT(e){return[...e].sort((t,s)=>t.kind==="directory"&&s.kind!=="directory"?-1:t.kind!=="directory"&&s.kind==="directory"?1:t.name.localeCompare(s.name))}function ca(e){const t=e.split("/").filter(Boolean);return t.pop(),t.join("/")}function Wy(e,t){if(e===null)return null;const s=e.trim().replace(/^\/+/,"").replace(/\/{2,}/g,"/").replace(/\/$/,"");return s?!t||s.includes("/")?s:`${t}/${s}`:null}function Ws(e){return e instanceof Error?e.message:"Request failed"}function yT(e){return e instanceof us&&e.status===409&&e.message==="terminal_cwd_changed"}const ST=v.lazy(()=>gg(()=>import("./MarkdownPreview-BqsqJZK7.js"),__vite__mapDeps([0,1])));function qy({api:e,editor:t,canClose:s,onClose:r}){const[o,c]=v.useState(t.read),[h,f]=v.useState(t.read.content),[g,p]=v.useState("idle"),[y,b]=v.useState(null),[w,S]=v.useState(!1),[E,T]=v.useState("edit"),A=v.useRef(t),O=v.useRef(t.read),L=v.useRef(t.read.content),U=v.useRef(!1),I=v.useRef(!1),te=v.useRef(0),ee=h!==o.content&&g!=="saving"&&!w;v.useEffect(()=>(I.current=!0,()=>{I.current=!1,te.current+=1}),[]),v.useEffect(()=>{te.current+=1,U.current=!1,A.current=t,O.current=t.read,L.current=t.read.content,c(t.read),f(t.read.content),p("idle"),b(null),S(!1),T("edit")},[t.id,t.read]),v.useEffect(()=>{A.current=t},[t]),v.useEffect(()=>{O.current=o},[o]),v.useEffect(()=>{L.current=h},[h]),v.useEffect(()=>{if(h===o.content||w)return;const ne=window.setInterval(()=>{!U.current&&L.current!==O.current.content&&ae()},1e3);return()=>window.clearInterval(ne)},[h===o.content,w,t.id]);async function ae(){if(U.current)return;const ne=L.current,ie=O.current;if(ne===ie.content)return;const Y=A.current,K=te.current;U.current=!0,p("saving"),b(null),S(!1);try{const re=await e.writeFile({rootToken:Y.rootToken,path:Y.path,content:ne,expectedVersion:ie.version});if(!I.current||K!==te.current)return;const B={...ie,content:ne,version:re.version};O.current=B,c(B),p(L.current===ne?"saved":"idle")}catch(re){if(!I.current||K!==te.current)return;if(re instanceof us&&re.status===409){S(!0),p("idle");return}b(wT(re)),p("idle")}finally{K===te.current&&(U.current=!1)}}const ue=g==="saving"?"saving":g==="saved"?"saved":o.language,be=o.language==="markdown",we=be&&E==="preview";return m.jsxs("section",{className:"editor-pane","aria-label":`Editor pane ${t.title}`,children:[m.jsxs("header",{className:"editor-pane-header",children:[m.jsx("span",{className:"terminal-pane-dot","aria-hidden":"true"}),m.jsx("strong",{children:t.title}),m.jsx("span",{className:"terminal-pane-spacer"}),m.jsx("span",{className:"terminal-pane-state",children:ue}),m.jsx("button",{type:"button","aria-label":`Save ${t.title}`,disabled:!ee,onClick:()=>{ae()},children:"Save"}),be?m.jsx("button",{type:"button","aria-label":`${we?"Edit":"Preview"} ${t.title}`,onClick:()=>T(ne=>ne==="preview"?"edit":"preview"),children:we?"Edit":"Preview"}):null,s?m.jsx("button",{type:"button",className:"terminal-pane-close","aria-label":`Close editor ${t.title}`,onClick:r,children:"x"}):null]}),y?m.jsx("div",{className:"editor-pane-alert",role:"alert",children:y}):null,w?m.jsx("div",{className:"editor-pane-alert",role:"alert",children:"File changed on disk."}):null,we?m.jsx("div",{className:"editor-markdown-preview","aria-label":`Markdown preview for ${t.title}`,children:m.jsx(v.Suspense,{fallback:m.jsx("div",{className:"editor-markdown-preview-loading",children:"loading preview"}),children:m.jsx(ST,{content:h})})}):m.jsx("textarea",{className:"editor-pane-textarea","aria-label":`Editor for ${t.title}`,spellCheck:!1,value:h,onChange:ne=>{const ie=ne.target.value;L.current=ie,f(ie),p("idle"),b(null),S(!1)}})]})}function wT(e){return e instanceof Error?e.message:"Request failed"}var CT=2,xT=1,ET=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,s=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(s.getPropertyValue("height")),o=Math.max(0,parseInt(s.getPropertyValue("width"))),c=window.getComputedStyle(this._terminal.element),h={top:parseInt(c.getPropertyValue("padding-top")),bottom:parseInt(c.getPropertyValue("padding-bottom")),right:parseInt(c.getPropertyValue("padding-right")),left:parseInt(c.getPropertyValue("padding-left"))},f=h.top+h.bottom,g=h.right+h.left,p=r-f,y=o-g-t;return{cols:Math.max(CT,Math.floor(y/e.css.cell.width)),rows:Math.max(xT,Math.floor(p/e.css.cell.height))}}};var _w=Object.defineProperty,kT=Object.getOwnPropertyDescriptor,TT=(e,t)=>{for(var s in t)_w(e,s,{get:t[s],enumerable:!0})},Qt=(e,t,s,r)=>{for(var o=r>1?void 0:r?kT(t,s):t,c=e.length-1,h;c>=0;c--)(h=e[c])&&(o=(r?h(t,s,o):h(o))||o);return r&&o&&_w(t,s,o),o},Me=(e,t)=>(s,r)=>t(s,r,e),$y="Terminal input",Hp={get:()=>$y,set:e=>$y=e},Yy="Too much output to announce, navigate to rows manually to read",Pp={get:()=>Yy,set:e=>Yy=e};function DT(e){return e.replace(/\r?\n/g,"\r")}function RT(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function MT(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function NT(e,t,s,r){if(e.stopPropagation(),e.clipboardData){let o=e.clipboardData.getData("text/plain");vw(o,t,s,r)}}function vw(e,t,s,r){e=DT(e),e=RT(e,s.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),s.triggerDataEvent(e,!0),t.value=""}function bw(e,t,s){let r=s.getBoundingClientRect(),o=e.clientX-r.left-10,c=e.clientY-r.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 Vy(e,t,s,r,o){bw(e,t,s),o&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Mr(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Ch(e,t=0,s=e.length){let r="";for(let o=t;o<s;++o){let c=e[o];c>65535?(c-=65536,r+=String.fromCharCode((c>>10)+55296)+String.fromCharCode(c%1024+56320)):r+=String.fromCharCode(c)}return r}var AT=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let s=e.length;if(!s)return 0;let r=0,o=0;if(this._interim){let c=e.charCodeAt(o++);56320<=c&&c<=57343?t[r++]=(this._interim-55296)*1024+c-56320+65536:(t[r++]=this._interim,t[r++]=c),this._interim=0}for(let c=o;c<s;++c){let h=e.charCodeAt(c);if(55296<=h&&h<=56319){if(++c>=s)return this._interim=h,r;let f=e.charCodeAt(c);56320<=f&&f<=57343?t[r++]=(h-55296)*1024+f-56320+65536:(t[r++]=h,t[r++]=f);continue}h!==65279&&(t[r++]=h)}return r}},LT=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let s=e.length;if(!s)return 0;let r=0,o,c,h,f,g=0,p=0;if(this.interim[0]){let w=!1,S=this.interim[0];S&=(S&224)===192?31:(S&240)===224?15:7;let E=0,T;for(;(T=this.interim[++E]&63)&&E<4;)S<<=6,S|=T;let A=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,O=A-E;for(;p<O;){if(p>=s)return 0;if(T=e[p++],(T&192)!==128){p--,w=!0;break}else this.interim[E++]=T,S<<=6,S|=T&63}w||(A===2?S<128?p--:t[r++]=S:A===3?S<2048||S>=55296&&S<=57343||S===65279||(t[r++]=S):S<65536||S>1114111||(t[r++]=S)),this.interim.fill(0)}let y=s-4,b=p;for(;b<s;){for(;b<y&&!((o=e[b])&128)&&!((c=e[b+1])&128)&&!((h=e[b+2])&128)&&!((f=e[b+3])&128);)t[r++]=o,t[r++]=c,t[r++]=h,t[r++]=f,b+=4;if(o=e[b++],o<128)t[r++]=o;else if((o&224)===192){if(b>=s)return this.interim[0]=o,r;if(c=e[b++],(c&192)!==128){b--;continue}if(g=(o&31)<<6|c&63,g<128){b--;continue}t[r++]=g}else if((o&240)===224){if(b>=s)return this.interim[0]=o,r;if(c=e[b++],(c&192)!==128){b--;continue}if(b>=s)return this.interim[0]=o,this.interim[1]=c,r;if(h=e[b++],(h&192)!==128){b--;continue}if(g=(o&15)<<12|(c&63)<<6|h&63,g<2048||g>=55296&&g<=57343||g===65279)continue;t[r++]=g}else if((o&248)===240){if(b>=s)return this.interim[0]=o,r;if(c=e[b++],(c&192)!==128){b--;continue}if(b>=s)return this.interim[0]=o,this.interim[1]=c,r;if(h=e[b++],(h&192)!==128){b--;continue}if(b>=s)return this.interim[0]=o,this.interim[1]=c,this.interim[2]=h,r;if(f=e[b++],(f&192)!==128){b--;continue}if(g=(o&7)<<18|(c&63)<<12|(h&63)<<6|f&63,g<65536||g>1114111)continue;t[r++]=g}}return r}},yw="",Ar=" ",dc=class Sw{constructor(){this.fg=0,this.bg=0,this.extended=new eh}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 Sw;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}},eh=class ww{constructor(t=0,s=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=s}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 ww(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Zn=class Cw extends dc{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new eh,this.combinedData=""}static fromCharData(t){let s=new Cw;return s.setFromCharData(t),s}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Mr(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 s=!1;if(t[1].length>2)s=!0;else if(t[1].length===2){let r=t[1].charCodeAt(0);if(55296<=r&&r<=56319){let o=t[1].charCodeAt(1);56320<=o&&o<=57343?this.content=(r-55296)*1024+o-56320+65536|t[2]<<22:s=!0}else s=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;s&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Xy="di$target",Up="di$dependencies",$f=new Map;function BT(e){return e[Up]||[]}function Bi(e){if($f.has(e))return $f.get(e);let t=function(s,r,o){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");OT(t,s,o)};return t._id=e,$f.set(e,t),t}function OT(e,t,s){t[Xy]===t?t[Up].push({id:e,index:s}):(t[Up]=[{id:e,index:s}],t[Xy]=t)}var tn=Bi("BufferService"),xw=Bi("CoreMouseService"),Ea=Bi("CoreService"),zT=Bi("CharsetService"),_g=Bi("InstantiationService"),Ew=Bi("LogService"),nn=Bi("OptionsService"),kw=Bi("OscLinkService"),jT=Bi("UnicodeService"),fc=Bi("DecorationService"),Ip=class{constructor(e,t,s){this._bufferService=e,this._optionsService=t,this._oscLinkService=s}provideLinks(e,t){let s=this._bufferService.buffer.lines.get(e-1);if(!s){t(void 0);return}let r=[],o=this._optionsService.rawOptions.linkHandler,c=new Zn,h=s.getTrimmedLength(),f=-1,g=-1,p=!1;for(let y=0;y<h;y++)if(!(g===-1&&!s.hasContent(y))){if(s.loadCell(y,c),c.hasExtendedAttrs()&&c.extended.urlId)if(g===-1){g=y,f=c.extended.urlId;continue}else p=c.extended.urlId!==f;else g!==-1&&(p=!0);if(p||g!==-1&&y===h-1){let b=this._oscLinkService.getLinkData(f)?.uri;if(b){let w={start:{x:g+1,y:e},end:{x:y+(!p&&y===h-1?1:0),y:e}},S=!1;if(!o?.allowNonHttpProtocols)try{let E=new URL(b);["http:","https:"].includes(E.protocol)||(S=!0)}catch{S=!0}S||r.push({text:b,range:w,activate:(E,T)=>o?o.activate(E,T,w):HT(E,T),hover:(E,T)=>o?.hover?.(E,T,w),leave:(E,T)=>o?.leave?.(E,T,w)})}p=!1,c.hasExtendedAttrs()&&c.extended.urlId?(g=y,f=c.extended.urlId):(g=-1,f=-1)}}t(r)}};Ip=Qt([Me(0,tn),Me(1,nn),Me(2,kw)],Ip);function HT(e,t){if(confirm(`Do you want to navigate to ${t}?
15
+ `)))){L(D.key,{busy:!0,status:"deleting…",error:void 0}),p(null);try{const _e=await e.uninstallAgent(D.id);r(R=>R.filter(H=>H.key!==D.key)),c(R=>{const H={...R};return delete H[D.key],H}),Ff(D.key),t?.(D.id),p(_e.message)}catch(_e){L(D.key,{busy:!1,status:void 0,error:_e instanceof Error?_e.message:"delete failed"})}}}async function ne(){f(!0),p(null);const D=s.filter(de=>de.id!==null),X=s.find(de=>de.id===null),_e=await Promise.all(D.map(de=>be(de))),R=_e.filter(de=>de==="failed").length;let H=_e.filter(de=>de==="manual").length,Q=null;if(X&&(Q=await be(X),Q==="manual"&&(H+=1),Q==="updated")){R>0&&p("Main server updated. Reload the page to use the new client. Some secondary servers failed; check their rows and retry."),f(!1);return}R>0&&H>0?p("Some servers failed and some need manual update. Check each marked row."):R>0?p("Some secondary servers failed to update. Check their rows and retry."):H>0&&p("Some servers need manual update. Copy and run the command shown on each marked server."),f(!1)}function ie(D){return D?D.error?D.error:D.status?D.status:D.manualUpdate?"manual update required":D.version?`v${D.version.version}`:"…":"…"}function Y(D){return D.error?D.error:typeof D.updateAvailable=="boolean"?D.updateAvailable?`latest v${D.latestVersion??"available"}`:"up to date":"unknown"}function K(D){const X=D?.version;return X?`npm package v${X.runningVersion}`:""}async function re(D,X){try{await rT(X),L(D,{copiedCommand:!0}),window.setTimeout(()=>L(D,{copiedCommand:!1}),1800)}catch(_e){L(D,{error:_e instanceof Error?_e.message:"copy failed"})}}async function B(D){if(!(!w||E)){T(!0),O(null);try{const X=await e.updateDistributedCallSettings(D);S(X)}catch(X){O(X instanceof Error?X.message:"failed to save distributed call settings")}finally{T(!1)}}}function $(D,X){if(!w)return;const _e=new Set(w.settings.workerIds);X?_e.add(D):_e.delete(D),B({workerIds:Array.from(_e)})}return m.jsxs("section",{className:"security-section",children:[m.jsx("h3",{children:"Servers"}),m.jsxs("div",{className:"update-actions",children:[m.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{ae()},disabled:h,children:"Check for updates"}),m.jsx("button",{type:"button",onClick:()=>{ne()},disabled:h,children:"Update all"})]}),g?m.jsx("p",{className:"settings-status",children:g}):null,y?m.jsxs("div",{className:"server-reload-required",role:"status",children:[m.jsx("span",{children:"Main server update is ready."}),m.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:"Reload page"})]}):null,m.jsxs("div",{className:"server-addon-panel",children:[m.jsxs("div",{className:"server-addon-header",children:[m.jsxs("div",{children:[m.jsx("span",{className:"security-item-label",children:"Distributed calls"}),m.jsx("span",{className:"security-item-meta",children:"Programmatic worker fan-out for trusted NTerminal servers."})]}),m.jsxs("label",{className:"auth-checkbox server-addon-toggle",children:[m.jsx("input",{type:"checkbox",checked:w?.settings.enabled??!1,disabled:!w||E,onChange:D=>{B({enabled:D.currentTarget.checked})}}),"Enabled"]})]}),m.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[m.jsx("input",{type:"checkbox",checked:w?.settings.allowPrivateTargets??!1,disabled:!w||E||!(w?.settings.enabled??!1),onChange:D=>{B({allowPrivateTargets:D.currentTarget.checked})}}),"Allow private network targets when the CLI also requests it"]}),w?m.jsx("div",{className:"server-addon-workers","aria-label":"Distributed call workers",children:w.workers.map(D=>m.jsxs("label",{className:"auth-checkbox server-addon-worker",children:[m.jsx("input",{type:"checkbox",checked:D.enabled,disabled:E||!w.settings.enabled,onChange:X=>$(D.id,X.currentTarget.checked)}),m.jsx("span",{children:D.id===Nr?"Local (main)":D.name})]},D.id))}):null,A?m.jsx("p",{className:"settings-status settings-status-error",children:A}):null]}),m.jsx("ul",{className:"security-list",children:s.map(D=>{const X=o[D.key],_e=K(X),R=X?.manualUpdate??null,H=X?.version!==void 0&&X?.updateAvailable!==!1&&!X?.busy&&!h,Q=D.id!==null&&!X?.busy&&!h;return m.jsxs("li",{children:[m.jsxs("div",{className:"server-row-main",children:[m.jsxs("div",{children:[m.jsx("span",{className:"security-item-label",children:D.name}),m.jsxs("span",{className:"security-item-meta",children:[_e?`${_e} — `:"",ie(X)]})]}),R?m.jsxs("div",{className:"server-manual-update",children:[m.jsx("span",{children:R.message}),m.jsxs("div",{className:"server-manual-command",children:[m.jsx("code",{children:R.command}),m.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{re(D.key,R.command)},children:X?.copiedCommand?"Copied":"Copy"})]})]}):null]}),m.jsxs("div",{className:"server-row-actions",children:[m.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{be(D)},disabled:!H,children:X?.busy?"…":"Update"}),D.id!==null?m.jsx("button",{type:"button",className:"server-delete-button",onClick:()=>{we(D)},disabled:!Q,children:"Delete"}):null]})]},D.key)})})]})}async function rT(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 xu=[{id:"appearance",label:"Appearance"},{id:"shortcuts",label:"Shortcuts"},{id:"notifications",label:"Notifications"},{id:"security",label:"Security"},{id:"diagnostics",label:"Diagnostics"},{id:"servers",label:"Servers"}];function aT({onClose:e,api:t,updateAvailable:s=!1,onNotificationAssetsChanged:r,onAgentRemoved:o}){const c=v.useMemo(()=>t??fh(),[t]),[h,f]=v.useState(()=>Np()),[g,p]=v.useState(()=>Ap()),[y,b]=v.useState(()=>Bp()),[w,S]=v.useState(()=>Or()),[E,T]=v.useState(()=>Sa()),[A,O]=v.useState(null),[L,U]=v.useState(null),[I,te]=v.useState("appearance"),[ee,ae]=v.useState(()=>J0()),[ue,be]=v.useState(()=>ya()),[we,ne]=v.useState(()=>sg()),[ie,Y]=v.useState([]),[K,re]=v.useState([]),[B,$]=v.useState([]),[D,X]=v.useState(5*1024*1024),[_e,R]=v.useState(!1),[H,Q]=v.useState(null),[de,ke]=v.useState(()=>ma()),[xe,Re]=v.useState(!1),[Xe,ge]=v.useState(null),G=v.useRef(null),ce=v.useRef(null),Ce=v.useRef({appearance:null,shortcuts:null,notifications:null,security:null,diagnostics:null,servers:null}),ye=v.useMemo(()=>new Set(K),[K]),De=!uT(K,B);v.useEffect(()=>rw(()=>f(Np())),[]),v.useEffect(()=>aw(()=>p(Ap())),[]),v.useEffect(()=>lw(()=>b(Bp())),[]),v.useEffect(()=>qm(()=>S(Or())),[]),v.useEffect(()=>ug(()=>T(Sa())),[]),v.useEffect(()=>ew(()=>be(ya())),[]),v.useEffect(()=>{const F=()=>ke(ma());F();const qe=window.setInterval(F,1500);return()=>window.clearInterval(qe)},[]),v.useEffect(()=>{if(!A)return;const F=Jo.find(dt=>dt.id===A);if(!F)return;const qe=dt=>{if(dt.preventDefault(),dt.stopPropagation(),dt.key==="Escape"){O(null),U(null);return}const vt=Hk(dt,F);if(!vt){U(cT(F));return}T(Ok(A,vt)),O(null),U(null)};return window.addEventListener("keydown",qe,!0),()=>window.removeEventListener("keydown",qe,!0)},[A]),v.useEffect(()=>{let F=!1;return c.listNotificationAssets().then(qe=>{F||He(qe)}).catch(qe=>{F||Q(ol(qe))}),()=>{F=!0}},[c]);function Be(F){f(Cu(Number(F)))}function Ke(F){be(Hy(Number(F)))}function le(F){te(F);const qe=ce.current,dt=Ce.current[F];if(!qe||!dt)return;const vt=Math.max(0,Iy(dt,qe)-12);typeof qe.scrollTo=="function"?qe.scrollTo({top:vt,behavior:"smooth"}):qe.scrollTop=vt}function Ee(){const F=ce.current;if(!F)return;if(F.scrollTop+F.clientHeight>=F.scrollHeight-2){te(xu[xu.length-1].id);return}let qe="appearance";const dt=F.scrollTop+Math.min(180,Math.max(48,F.clientHeight*.28));for(const vt of xu){const pi=Ce.current[vt.id];pi&&Iy(pi,F)<=dt&&(qe=vt.id)}te(qe)}function Le(F){T(zk(F)),O(null),U(null)}function Oe(){T(jk()),O(null),U(null)}function He(F){const qe=F.assets.filter(dt=>dt.enabled).map(dt=>dt.id);Y(F.assets),re(qe),$(qe),X(F.maxFileBytes),Q(null)}async function _t(){if(ee){jy(!1),ae(!1);return}let F=we;F==="default"&&(F=await Rk(),ne(F)),F==="granted"&&(jy(!0),ae(!0))}async function Ye(F){const qe=F?.[0];if(qe){if(qe.size>D){Q(`File must be ${Wf(D)} or smaller.`),Oi();return}if(qe.type!=="video/mp4"&&qe.type!=="video/webm"){Q("Upload an MP4 or WebM video."),Oi();return}R(!0),Q(null);try{await c.uploadNotificationAsset(qe),He(await c.listNotificationAssets()),r?.()}catch(dt){Q(ol(dt))}finally{R(!1),Oi()}}}async function rt(F){R(!0),Q(null);try{await c.deleteNotificationAsset(F),He(await c.listNotificationAssets()),r?.()}catch(qe){Q(ol(qe))}finally{R(!1)}}function Oi(){G.current&&(G.current.value="")}function $i(F,qe){const dt=new Set(K);if(qe?dt.add(F):dt.delete(F),dt.size===0){Q("Keep at least one toast video selected.");return}Q(null),re(Array.from(dt))}async function Ci(){if(K.length===0){Q("Keep at least one toast video selected.");return}R(!0),Q(null);try{const F=await c.updateNotificationAssetSelection({enabledAssetIds:K});He(F),r?.()}catch(F){Q(ol(F))}finally{R(!1)}}async function ri(){ge(null),Re(!0);try{const F=await uk();ge(F?"Diagnostics copied.":"Copy failed in this browser."),ke(ma())}catch(F){ge(ol(F))}finally{Re(!1)}}async function zi(){ge(null),Re(!0);try{const F=await bh("manual-settings");ge(`Sent ${F.accepted} diagnostic events.`),ke(ma())}catch(F){ge(ol(F))}finally{Re(!1)}}function sn(){ok(),ke([]),ge("Diagnostics cleared.")}return m.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-label":"Settings",onClick:e,children:m.jsxs("div",{className:"security-panel settings-panel",onClick:F=>F.stopPropagation(),children:[m.jsxs("header",{className:"security-panel-header",children:[m.jsx("h2",{children:"Settings"}),m.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:e,children:"×"})]}),m.jsxs("div",{className:"settings-layout",children:[m.jsx("nav",{className:"settings-nav","aria-label":"Settings categories",children:xu.map(F=>m.jsxs("button",{type:"button","data-active":I===F.id?"true":"false","aria-current":I===F.id?"true":void 0,onClick:()=>le(F.id),children:[F.label,F.id==="servers"&&s?m.jsx("span",{className:"update-pulse-dot settings-update-dot","aria-hidden":"true"}):null]},F.id))}),m.jsxs("div",{ref:ce,className:"settings-content",onScroll:Ee,children:[m.jsxs("section",{id:"settings-appearance",ref:F=>{Ce.current.appearance=F},className:"security-section settings-section",children:[m.jsx("h3",{children:"Appearance"}),m.jsx("div",{className:"settings-section-heading",children:m.jsxs("div",{children:[m.jsx("span",{className:"settings-control-title",children:"Theme"}),m.jsx("p",{className:"muted settings-control-description",children:"Choose the workspace and terminal color preset."})]})}),m.jsx("div",{className:"settings-theme-picker",role:"radiogroup","aria-label":"Interface theme",children:Yu.map(F=>m.jsxs("button",{type:"button",className:"settings-theme-card",role:"radio","aria-checked":w===F.id,"data-active":w===F.id?"true":"false",onClick:()=>S(hE(F.id)),style:{"--settings-theme-bg":F.tokens.bg,"--settings-theme-bg-2":F.tokens.bg2,"--settings-theme-sidebar":F.tokens.bgSidebar,"--settings-theme-line":F.tokens.line,"--settings-theme-fg":F.tokens.fg,"--settings-theme-fg-2":F.tokens.fg2,"--settings-theme-accent":F.tokens.accent,"--settings-theme-xterm-bg":F.xterm.background,"--settings-theme-xterm-fg":F.xterm.foreground,"--settings-theme-xterm-selection":F.xterm.selectionBackground},children:[m.jsxs("span",{className:"settings-theme-preview","aria-hidden":"true",children:[m.jsxs("span",{className:"settings-theme-preview-sidebar",children:[m.jsx("span",{}),m.jsx("span",{}),m.jsx("span",{})]}),m.jsxs("span",{className:"settings-theme-preview-main",children:[m.jsxs("span",{className:"settings-theme-preview-tabs",children:[m.jsx("span",{}),m.jsx("span",{})]}),m.jsxs("span",{className:"settings-theme-preview-terminal",children:[m.jsx("span",{}),m.jsx("span",{}),m.jsx("span",{})]})]})]}),m.jsxs("span",{className:"settings-theme-card-copy",children:[m.jsx("strong",{children:F.label}),m.jsx("small",{children:F.description})]})]},F.id))}),m.jsxs("label",{className:"settings-control",children:[m.jsx("span",{children:"Font size"}),m.jsxs("span",{className:"settings-control-value",children:[h,"px"]}),m.jsx("input",{type:"range",min:Dp,max:Rp,step:1,value:h,"aria-label":"Terminal font size",onChange:F=>Be(F.currentTarget.value)})]}),m.jsxs("div",{className:"settings-stepper-row",children:[m.jsx("button",{type:"button",className:"secondary-button settings-stepper-button",onClick:()=>f(Cu(h-1)),children:"-"}),m.jsx("input",{type:"number",min:Dp,max:Rp,step:1,value:h,"aria-label":"Terminal font size value",onChange:F=>Be(F.currentTarget.value)}),m.jsx("button",{type:"button",className:"secondary-button settings-stepper-button",onClick:()=>f(Cu(h+1)),children:"+"}),m.jsx("button",{type:"button",className:"secondary-button settings-reset-button",onClick:()=>f(Cu(_a)),children:"Reset"})]}),m.jsxs("label",{className:"settings-control",children:[m.jsx("span",{children:"Font family"}),m.jsx("select",{value:g,"aria-label":"Terminal font family",onChange:F=>p(Ak(F.currentTarget.value)),children:Qu.map(F=>m.jsx("option",{value:F.id,children:F.label},F.id))})]}),m.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[m.jsx("input",{type:"checkbox",checked:y,onChange:F=>b(Lk(F.currentTarget.checked))}),"Show scroll progress"]})]}),m.jsxs("section",{id:"settings-shortcuts",ref:F=>{Ce.current.shortcuts=F},className:"security-section settings-section",children:[m.jsxs("div",{className:"settings-section-heading",children:[m.jsx("h3",{children:"Shortcuts"}),m.jsx("button",{type:"button",className:"secondary-button settings-reset-button",onClick:Oe,children:"Reset all"})]}),m.jsx("p",{className:"muted",children:"Defaults avoid Chrome's browser-tab shortcuts. Click a shortcut, then press the new key combo."}),L?m.jsx("p",{className:"settings-error",children:L}):null,m.jsx("ul",{className:"settings-shortcut-list","aria-label":"Workspace shortcuts",children:Jo.map(F=>{const qe=A===F.id;return m.jsxs("li",{children:[m.jsxs("div",{children:[m.jsx("span",{className:"settings-shortcut-label",children:F.label}),m.jsx("span",{className:"settings-shortcut-group",children:F.group})]}),m.jsxs("div",{className:"settings-shortcut-actions",children:[m.jsx("button",{type:"button",className:"settings-shortcut-recorder","data-recording":qe?"true":"false",onClick:()=>{O(F.id),U(null)},children:qe?"Press keys…":cw(E[F.id])}),m.jsx("button",{type:"button",className:"secondary-button settings-shortcut-reset",onClick:()=>Le(F.id),children:"Reset"})]})]},F.id)})})]}),m.jsxs("section",{id:"settings-notifications",ref:F=>{Ce.current.notifications=F},className:"security-section settings-section",children:[m.jsx("h3",{children:"Notifications"}),Sh()?m.jsxs(m.Fragment,{children:[m.jsxs("label",{className:"auth-checkbox",children:[m.jsx("input",{type:"checkbox",checked:ee&&we==="granted",onChange:()=>{_t()},disabled:we==="denied"}),"System notification when page is hidden"]}),we==="denied"?m.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."}):m.jsx("p",{className:"muted",children:"Uses browser notifications only when this page isn't visible. Animated toast is controlled separately below."})]}):m.jsx("p",{className:"muted",children:"This browser doesn't expose the Notification API; animated toast and in-app badges can still work."}),m.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[m.jsx("input",{type:"checkbox",checked:ue.enabled,onChange:F=>be(xk(F.currentTarget.checked))}),"Show animated completion toast"]}),m.jsxs("label",{className:"settings-control",children:[m.jsx("span",{children:"Toast duration"}),m.jsx("span",{className:"settings-control-value",children:ue.persistUntilDismissed?"Until closed":`${ue.durationSeconds}s`}),m.jsx("input",{type:"range",min:xp,max:Ep,step:.5,value:ue.durationSeconds,disabled:!ue.enabled||ue.persistUntilDismissed,"aria-label":"Completion toast duration",onChange:F=>Ke(F.currentTarget.value)})]}),m.jsxs("div",{className:"settings-stepper-row settings-duration-row",children:[m.jsx("input",{type:"number",min:xp,max:Ep,step:.5,value:ue.durationSeconds,disabled:!ue.enabled||ue.persistUntilDismissed,"aria-label":"Completion toast duration value",onChange:F=>Ke(F.currentTarget.value)}),m.jsx("button",{type:"button",className:"secondary-button settings-reset-button",disabled:!ue.enabled||ue.persistUntilDismissed,onClick:()=>be(Hy($o)),children:"Reset"})]}),m.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[m.jsx("input",{type:"checkbox",checked:ue.persistUntilDismissed,disabled:!ue.enabled,onChange:F=>be(Ek(F.currentTarget.checked))}),"Keep toast until dismissed"]}),m.jsxs("div",{className:"settings-assets-header",children:[m.jsx("span",{children:"Toast videos"}),m.jsxs("span",{children:[Wf(D)," max"]})]}),m.jsx("input",{ref:G,type:"file",accept:"video/mp4,video/webm",className:"settings-asset-input","aria-label":"Upload toast video",onChange:F=>{Ye(F.currentTarget.files)}}),m.jsx("button",{type:"button",className:"secondary-button settings-upload-button",disabled:_e,onClick:()=>G.current?.click(),children:"Upload video"}),H?m.jsx("p",{className:"settings-error",children:H}):null,ie.length>0?m.jsx("ul",{className:"settings-asset-list","aria-label":"Toast videos",children:ie.map(F=>m.jsxs("li",{"data-enabled":ye.has(F.id)?"true":"false",children:[m.jsxs("label",{className:"settings-asset-choice",children:[m.jsx("input",{type:"checkbox",checked:ye.has(F.id),disabled:_e,"aria-label":`Use ${F.filename}`,onChange:qe=>$i(F.id,qe.currentTarget.checked)}),m.jsx("video",{src:F.url,muted:!0,autoPlay:!0,loop:!0,playsInline:!0,"aria-hidden":"true"}),m.jsxs("span",{className:"settings-asset-copy",children:[m.jsx("span",{children:F.filename}),m.jsx("small",{children:F.source==="built-in"?"Built-in":Wf(F.size)})]})]}),F.source==="uploaded"?m.jsx("button",{type:"button",className:"secondary-button settings-asset-delete",disabled:_e,"aria-label":`Delete ${F.filename}`,onClick:()=>{rt(F.id)},children:"x"}):null]},F.id))}):m.jsx("p",{className:"muted",children:"Built-in videos will be used."}),m.jsx("button",{type:"button",className:"secondary-button settings-save-assets-button",disabled:_e||ie.length===0||!De,onClick:()=>{Ci()},children:"Save selected videos"})]}),m.jsx("div",{id:"settings-security",ref:F=>{Ce.current.security=F},className:"settings-section-group",children:m.jsx(sk,{api:c})}),m.jsxs("section",{id:"settings-diagnostics",ref:F=>{Ce.current.diagnostics=F},className:"security-section settings-section",children:[m.jsxs("div",{className:"settings-section-heading",children:[m.jsxs("div",{children:[m.jsx("h3",{children:"Diagnostics"}),m.jsx("p",{className:"muted settings-control-description",children:"Recent browser lifecycle and auth transition events for troubleshooting."})]}),m.jsx("span",{className:"settings-diagnostics-count",children:de.length})]}),m.jsxs("div",{className:"settings-diagnostics-actions",children:[m.jsx("button",{type:"button",className:"secondary-button",disabled:xe||de.length===0,onClick:()=>{ri()},children:"Copy"}),m.jsx("button",{type:"button",className:"secondary-button",disabled:xe||de.length===0,onClick:()=>{zi()},children:"Send"}),m.jsx("button",{type:"button",className:"secondary-button",disabled:xe||de.length===0,onClick:sn,children:"Clear"})]}),Xe?m.jsx("p",{className:"settings-status",children:Xe}):null,de.length>0?m.jsx("ol",{className:"settings-diagnostics-list","aria-label":"Recent diagnostics",children:de.slice(-8).reverse().map((F,qe)=>m.jsxs("li",{children:[m.jsx("span",{children:lT(F.at)}),m.jsx("strong",{children:F.event}),F.data?m.jsx("code",{children:oT(F.data)}):null]},`${F.at}:${F.event}:${qe}`))}):m.jsx("p",{className:"muted",children:"No diagnostics recorded yet."})]}),m.jsx("div",{id:"settings-servers",ref:F=>{Ce.current.servers=F},className:"settings-section-group",children:m.jsx(sT,{api:c,...o?{onAgentRemoved:o}:{}})})]})]})]})})}function Iy(e,t){const s=e.getBoundingClientRect(),r=t.getBoundingClientRect();return s.top-r.top+t.scrollTop}function Wf(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 ol(e){return e instanceof Error?e.message:"Request failed."}function lT(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function oT(e){return Object.entries(e).slice(0,5).map(([t,s])=>`${t}=${String(s)}`).join(" ")}function cT(e){return e.indexed?"Press a shortcut ending in a number from 1 to 9.":e.requiresPrimaryModifier?"Use Ctrl, Alt, or Meta with another key.":"Press a complete shortcut."}function uT(e,t){if(e.length!==t.length)return!1;const s=new Set(t);return e.every(r=>s.has(r))}class oa extends Error{constructor(t,s){super(s),this.status=t,this.name="UploadClientError"}status}function hT(e){const t=e.createXhr?.()??new XMLHttpRequest,s=new FormData,r=e.files.map((o,c)=>({fieldName:`file${c}`,relativePath:o.relativePath,size:o.file.size}));s.append("manifest",JSON.stringify({terminalId:e.terminalId,entries:r}));for(const[o,c]of e.files.entries())s.append(`file${o}`,c.file);return new Promise((o,c)=>{let h=!1;const f=()=>{e.signal?.removeEventListener("abort",y)},g=b=>{h||(h=!0,f(),o(b))},p=b=>{h||(h=!0,f(),c(b))},y=()=>{t.abort(),p(new oa(0,"Upload aborted."))};if(e.signal?.aborted){p(new oa(0,"Upload aborted."));return}e.signal?.addEventListener("abort",y,{once:!0}),t.open("POST","/api/uploads"),t.withCredentials=!0,t.upload.onprogress=b=>{if(e.onProgress){if(b.lengthComputable&&b.total>0){e.onProgress({loaded:b.loaded,total:b.total,percent:Math.round(b.loaded/b.total*100)});return}e.onProgress({loaded:b.loaded,total:null,percent:null})}},t.onload=()=>{if(t.status>=200&&t.status<300){try{g(JSON.parse(t.responseText))}catch{p(new oa(t.status,"Invalid upload response."))}return}p(new oa(t.status,dT(t.responseText,t.statusText||`HTTP ${t.status}`)))},t.onerror=()=>p(new oa(0,"Upload failed.")),t.onabort=()=>p(new oa(0,"Upload aborted.")),t.ontimeout=()=>p(new oa(0,"Upload timed out.")),t.send(s)})}function dT(e,t){try{const s=JSON.parse(e),r=typeof s.error=="string"?s.error:s.message;if(typeof r=="string"&&r.trim())return r}catch{}return t}const fT="modulepreload",pT=function(e){return"/"+e},Ky={},gg=function(t,s,r){let o=Promise.resolve();if(s&&s.length>0){let g=function(p){return Promise.all(p.map(y=>Promise.resolve(y).then(b=>({status:"fulfilled",value:b}),b=>({status:"rejected",reason:b}))))};document.getElementsByTagName("link");const h=document.querySelector("meta[property=csp-nonce]"),f=h?.nonce||h?.getAttribute("nonce");o=g(s.map(p=>{if(p=pT(p),p in Ky)return;Ky[p]=!0;const y=p.endsWith(".css"),b=y?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${b}`))return;const w=document.createElement("link");if(w.rel=y?"stylesheet":fT,y||(w.as="script"),w.crossOrigin="",w.href=p,f&&w.setAttribute("nonce",f),document.head.appendChild(w),y)return new Promise((S,E)=>{w.addEventListener("load",S),w.addEventListener("error",()=>E(new Error(`Unable to preload CSS for ${p}`)))})}))}function c(h){const f=new Event("vite:preloadError",{cancelable:!0});if(f.payload=h,window.dispatchEvent(f),!f.defaultPrevented)throw h}return o.then(h=>{for(const f of h||[])f.status==="rejected"&&c(f.reason);return t().catch(c)})},mT=v.lazy(()=>gg(()=>import("./MarkdownPreview-jgdUGtLt.js"),__vite__mapDeps([0,1])));function gT({api:e,activeTerminalId:t,activeTerminalCwd:s,workspaceRootPath:r=null,onOpenFile:o}){const[c,h]=v.useState(null),[f,g]=v.useState(""),[p,y]=v.useState({}),[b,w]=v.useState(()=>new Set),[S,E]=v.useState(null),[T,A]=v.useState({type:"empty"}),[O,L]=v.useState("idle"),[U,I]=v.useState(null),te=v.useRef(null),ee=v.useRef(null),ae=v.useRef(!1),ue=v.useRef(0),be=v.useRef(null);be.current===null&&t&&(be.current=t);const we=be.current,ne=r?vT(r):t?Fy(t,s):null,ie=c?[c.rootPath,f].filter(Boolean).join("/"):"",Y=S?.path??null;v.useEffect(()=>(ae.current=!0,()=>{ae.current=!1,ue.current+=1,ce()}),[]),v.useEffect(()=>{be.current=t,ee.current=null,K(ne)},[e]),v.useEffect(()=>{r&&ne!==ee.current&&re(r,ne)},[r,ne]),v.useEffect(()=>{if(r||!we||t!==we)return;const le=Fy(we,s);le!==ee.current&&B(we,le)},[we,t,s,r]);async function K(le=ne){if(r){await re(r,le);return}await B(t,le)}async function re(le,Ee=ne){const Le=Ce();if(ee.current=Ee,ce(),h(null),g(""),y({}),w(new Set),E(null),A({type:"empty"}),I(null),!le){L("idle");return}L("loading");try{const Oe=await e.createFileRoot({path:le});if(!ye(Le))return;h({rootToken:Oe.rootToken,rootPath:Oe.rootPath});const He=await e.listFiles({rootToken:Oe.rootToken,path:""});if(!ye(Le))return;X(He),L("idle")}catch(Oe){ye(Le)&&(I(Ws(Oe)),L("idle"))}}async function B(le,Ee=ne){const Le=Ce();if(ee.current=Ee,ce(),h(null),g(""),y({}),w(new Set),E(null),A({type:"empty"}),I(null),!le){L("idle");return}L("loading");try{const Oe=await e.createFileRoot({terminalId:le});if(!ye(Le))return;h({rootToken:Oe.rootToken,rootPath:Oe.rootPath});const He=await e.listFiles({rootToken:Oe.rootToken,path:""});if(!ye(Le))return;X(He),L("idle")}catch(Oe){if(await De(Oe,Le))return;ye(Le)&&(I(Ws(Oe)),L("idle"))}}async function $(le=f,Ee=c){if(!Ee)return;const Le=Ce();L("loading"),I(null);try{const Oe=await e.listFiles({rootToken:Ee.rootToken,path:le});if(!ye(Le))return;X(Oe),L("idle")}catch(Oe){if(await De(Oe,Le))return;ye(Le)&&(I(Ws(Oe)),L("idle"))}}async function D(){if(r){await re(r,ne);return}be.current=t,await B(t,ne)}function X(le){y(Ee=>({...Ee,[le.path]:bT(le.entries)}))}async function _e(le){if(!(!qf(le)||!c)){if(E(le),I(null),le.kind==="directory"){g(le.path),G(),await H(le);return}if(g(ca(le.path)),le.editable){await de(le);return}le.previewKind!=="none"&&await xe(le,le.previewKind)}}async function R(le){if(!(!qf(le)||!c)){if(E(le),I(null),le.kind==="directory"){g(le.path),G(),await H(le);return}if(g(ca(le.path)),le.editable){await ke(le);return}le.previewKind!=="none"&&await xe(le,le.previewKind)}}async function H(le){if(b.has(le.path)){w(Ee=>{const Le=new Set(Ee);return Le.delete(le.path),Le});return}w(Ee=>new Set(Ee).add(le.path)),await $(le.path)}function Q(le,Ee){le.key==="Enter"&&(le.preventDefault(),R(Ee))}async function de(le){if(!c)return;const Ee=Ce();L("loading"),ce();try{const Le=await e.readFile({rootToken:c.rootToken,path:le.path});if(!ye(Ee))return;A({type:"text-preview",file:le,read:Le}),L("idle")}catch(Le){if(await De(Le,Ee))return;ye(Ee)&&(I(Ws(Le)),L("idle"))}}async function ke(le){if(!c)return;const Ee=Ce();L("loading");try{await o({rootToken:c.rootToken,path:le.path,...t?{terminalId:t}:{}}),ye(Ee)&&L("idle")}catch(Le){if(await De(Le,Ee))return;ye(Ee)&&(I(Ws(Le)),L("idle"))}}async function xe(le,Ee){if(!c)return;const Le=Ce();L("loading"),ce();try{const Oe=await e.previewFile({rootToken:c.rootToken,path:le.path});if(!ye(Le))return;const He=URL.createObjectURL(Oe);if(!ye(Le)){URL.revokeObjectURL(He);return}te.current=He,A({type:"preview",file:le,previewKind:Ee,url:He}),L("idle")}catch(Oe){if(await De(Oe,Le))return;ye(Le)&&(I(Ws(Oe)),L("idle"))}}async function Re(le){if(!c)return;const Ee=le==="file"?"New file":"New folder",Le=window.prompt(Ee,""),Oe=S?S.kind==="directory"?S.path:ca(S.path):f,He=Wy(Le,Oe);if(He){I(null);try{const _t=await e.createFileEntry({rootToken:c.rootToken,path:He,kind:le});E(_t.entry),await $(Oe)}catch(_t){if(await De(_t))return;I(Ws(_t))}}}async function Xe(){if(!c||!S)return;const le=window.prompt("Move selected entry",S.path),Ee=Wy(le,"");if(!Ee||Ee===S.path)return;const Le=ca(S.path),Oe=ca(Ee);I(null);try{const He=await e.moveFileEntry({rootToken:c.rootToken,sourcePath:S.path,destinationPath:Ee});E(He.entry),g(He.entry.kind==="directory"?He.entry.path:ca(He.entry.path)),G(),await $(Le),Oe!==Le&&await $(Oe)}catch(He){if(await De(He))return;I(Ws(He))}}async function ge(){if(!c||!S)return;const le=S.path,Ee=ca(le);I(null);try{const Le=await e.previewDeleteFileEntry({rootToken:c.rootToken,path:S.path}),Oe=Le.descendantCount>0?` and ${Le.descendantCount} nested item${Le.descendantCount===1?"":"s"}`:"";if(!window.confirm(`Delete ${Le.path}${Oe}?`))return;await e.deleteFileEntry({rootToken:c.rootToken,path:S.path,previewToken:Le.previewToken}),E(null),g(Ee),w(He=>{const _t=new Set(He);for(const Ye of He)(Ye===le||Ye.startsWith(`${le}/`))&&_t.delete(Ye);return _t}),G(),await $(Ee)}catch(Le){if(await De(Le))return;I(Ws(Le))}}function G(){ue.current+=1,ce(),A({type:"empty"})}function ce(){te.current&&(URL.revokeObjectURL(te.current),te.current=null)}function Ce(){return ue.current+=1,ue.current}function ye(le){return ae.current&&le===ue.current}async function De(le,Ee){return yT(le)?(Ee!==void 0&&!ye(Ee)||await K(ne),!0):!1}function Be(le,Ee){const Le=qf(le),Oe=le.kind==="directory"&&b.has(le.path),He=p[le.path]??[],_t={"--file-tree-depth":Ee};return m.jsxs(Si.Fragment,{children:[m.jsxs("button",{type:"button",className:"file-entry-button","data-kind":le.kind,"data-expanded":Oe,"data-active":Y===le.path,disabled:!Le,style:_t,"aria-expanded":le.kind==="directory"?Oe:void 0,"aria-label":`${le.kind==="directory"?"Open folder":"Open file"} ${le.name}`,title:le.kind==="directory"?"Expand or collapse folder":"Click to preview. Double-click or press Enter to open.",onClick:()=>{_e(le)},onDoubleClick:()=>{R(le)},onKeyDown:Ye=>Q(Ye,le),children:[m.jsx("span",{className:"file-entry-disclosure","aria-hidden":"true",children:le.kind==="directory"?Oe?"▾":"▸":""}),m.jsx("span",{className:"file-entry-name",children:le.name}),m.jsx("small",{children:_T(le)})]}),Oe?m.jsx("div",{className:"file-tree-children",role:"group",children:He.map(Ye=>Be(Ye,Ee+1))}):null]},le.path)}const Ke=p[""]??[];return m.jsxs("section",{className:"file-explorer","aria-label":"Files","aria-busy":O==="loading",children:[m.jsxs("header",{className:"file-explorer-header",children:[m.jsx("div",{className:"file-explorer-path",title:ie,children:ie||"No active pane"}),m.jsxs("div",{className:"file-explorer-toolbar","aria-label":"File actions",children:[m.jsx("button",{type:"button","aria-label":"Refresh files",title:"Refresh",disabled:!r&&!t,onClick:()=>{D()},children:"↻"}),m.jsx("button",{type:"button","aria-label":"New file",title:"New file",disabled:!c,onClick:()=>{Re("file")},children:"+"}),m.jsx("button",{type:"button","aria-label":"New folder",title:"New folder",disabled:!c,onClick:()=>{Re("directory")},children:"▣"})]})]}),U?m.jsx("div",{className:"file-explorer-alert",role:"alert",children:U}):null,m.jsxs("div",{className:"file-explorer-layout",children:[m.jsx("div",{className:"file-tree","aria-label":ie?`Files in ${ie}`:"Files",children:Ke.map(le=>Be(le,0))}),m.jsxs("section",{className:"file-detail","aria-label":"File detail",children:[m.jsxs("div",{className:"file-detail-header",children:[m.jsx("strong",{children:S?.name??"detail"}),m.jsxs("div",{className:"file-detail-actions",children:[m.jsx("button",{type:"button","aria-label":"Move selected entry",disabled:!S,onClick:()=>{Xe()},children:"Move"}),m.jsx("button",{type:"button","aria-label":"Delete selected entry",disabled:!S,onClick:()=>{ge()},children:"Delete"})]})]}),O==="loading"?m.jsx("div",{className:"file-detail-empty",children:"loading"}):null,T.type==="empty"&&O!=="loading"?m.jsx("div",{className:"file-detail-empty",children:"No file selected"}):null,T.type==="preview"?m.jsxs("div",{className:"file-preview-frame",children:[T.previewKind==="image"?m.jsx("img",{src:T.url,alt:T.file.name}):null,T.previewKind==="pdf"?m.jsx("iframe",{src:T.url,title:T.file.name}):null]}):null,T.type==="text-preview"&&T.read.language==="markdown"?m.jsx("div",{className:"file-markdown-preview","aria-label":`Preview for ${T.file.name}`,children:m.jsx(v.Suspense,{fallback:m.jsx("div",{className:"file-markdown-preview-loading",children:"loading preview"}),children:m.jsx(mT,{content:T.read.content})})}):null,T.type==="text-preview"&&T.read.language==="text"?m.jsx("pre",{className:"file-text-preview","aria-label":`Preview for ${T.file.name}`,children:T.read.content}):null]})]})]})}function qf(e){return e.kind==="directory"||e.editable||e.previewKind!=="none"}function _T(e){return e.kind==="directory"?"dir":e.editable?"edit":e.previewKind!=="none"?e.previewKind:"unsupported"}function Fy(e,t){return`${e}\0${t??""}`}function vT(e){return`workspace\0${e}`}function bT(e){return[...e].sort((t,s)=>t.kind==="directory"&&s.kind!=="directory"?-1:t.kind!=="directory"&&s.kind==="directory"?1:t.name.localeCompare(s.name))}function ca(e){const t=e.split("/").filter(Boolean);return t.pop(),t.join("/")}function Wy(e,t){if(e===null)return null;const s=e.trim().replace(/^\/+/,"").replace(/\/{2,}/g,"/").replace(/\/$/,"");return s?!t||s.includes("/")?s:`${t}/${s}`:null}function Ws(e){return e instanceof Error?e.message:"Request failed"}function yT(e){return e instanceof us&&e.status===409&&e.message==="terminal_cwd_changed"}const ST=v.lazy(()=>gg(()=>import("./MarkdownPreview-jgdUGtLt.js"),__vite__mapDeps([0,1])));function qy({api:e,editor:t,canClose:s,onClose:r}){const[o,c]=v.useState(t.read),[h,f]=v.useState(t.read.content),[g,p]=v.useState("idle"),[y,b]=v.useState(null),[w,S]=v.useState(!1),[E,T]=v.useState("edit"),A=v.useRef(t),O=v.useRef(t.read),L=v.useRef(t.read.content),U=v.useRef(!1),I=v.useRef(!1),te=v.useRef(0),ee=h!==o.content&&g!=="saving"&&!w;v.useEffect(()=>(I.current=!0,()=>{I.current=!1,te.current+=1}),[]),v.useEffect(()=>{te.current+=1,U.current=!1,A.current=t,O.current=t.read,L.current=t.read.content,c(t.read),f(t.read.content),p("idle"),b(null),S(!1),T("edit")},[t.id,t.read]),v.useEffect(()=>{A.current=t},[t]),v.useEffect(()=>{O.current=o},[o]),v.useEffect(()=>{L.current=h},[h]),v.useEffect(()=>{if(h===o.content||w)return;const ne=window.setInterval(()=>{!U.current&&L.current!==O.current.content&&ae()},1e3);return()=>window.clearInterval(ne)},[h===o.content,w,t.id]);async function ae(){if(U.current)return;const ne=L.current,ie=O.current;if(ne===ie.content)return;const Y=A.current,K=te.current;U.current=!0,p("saving"),b(null),S(!1);try{const re=await e.writeFile({rootToken:Y.rootToken,path:Y.path,content:ne,expectedVersion:ie.version});if(!I.current||K!==te.current)return;const B={...ie,content:ne,version:re.version};O.current=B,c(B),p(L.current===ne?"saved":"idle")}catch(re){if(!I.current||K!==te.current)return;if(re instanceof us&&re.status===409){S(!0),p("idle");return}b(wT(re)),p("idle")}finally{K===te.current&&(U.current=!1)}}const ue=g==="saving"?"saving":g==="saved"?"saved":o.language,be=o.language==="markdown",we=be&&E==="preview";return m.jsxs("section",{className:"editor-pane","aria-label":`Editor pane ${t.title}`,children:[m.jsxs("header",{className:"editor-pane-header",children:[m.jsx("span",{className:"terminal-pane-dot","aria-hidden":"true"}),m.jsx("strong",{children:t.title}),m.jsx("span",{className:"terminal-pane-spacer"}),m.jsx("span",{className:"terminal-pane-state",children:ue}),m.jsx("button",{type:"button","aria-label":`Save ${t.title}`,disabled:!ee,onClick:()=>{ae()},children:"Save"}),be?m.jsx("button",{type:"button","aria-label":`${we?"Edit":"Preview"} ${t.title}`,onClick:()=>T(ne=>ne==="preview"?"edit":"preview"),children:we?"Edit":"Preview"}):null,s?m.jsx("button",{type:"button",className:"terminal-pane-close","aria-label":`Close editor ${t.title}`,onClick:r,children:"x"}):null]}),y?m.jsx("div",{className:"editor-pane-alert",role:"alert",children:y}):null,w?m.jsx("div",{className:"editor-pane-alert",role:"alert",children:"File changed on disk."}):null,we?m.jsx("div",{className:"editor-markdown-preview","aria-label":`Markdown preview for ${t.title}`,children:m.jsx(v.Suspense,{fallback:m.jsx("div",{className:"editor-markdown-preview-loading",children:"loading preview"}),children:m.jsx(ST,{content:h})})}):m.jsx("textarea",{className:"editor-pane-textarea","aria-label":`Editor for ${t.title}`,spellCheck:!1,value:h,onChange:ne=>{const ie=ne.target.value;L.current=ie,f(ie),p("idle"),b(null),S(!1)}})]})}function wT(e){return e instanceof Error?e.message:"Request failed"}var CT=2,xT=1,ET=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,s=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(s.getPropertyValue("height")),o=Math.max(0,parseInt(s.getPropertyValue("width"))),c=window.getComputedStyle(this._terminal.element),h={top:parseInt(c.getPropertyValue("padding-top")),bottom:parseInt(c.getPropertyValue("padding-bottom")),right:parseInt(c.getPropertyValue("padding-right")),left:parseInt(c.getPropertyValue("padding-left"))},f=h.top+h.bottom,g=h.right+h.left,p=r-f,y=o-g-t;return{cols:Math.max(CT,Math.floor(y/e.css.cell.width)),rows:Math.max(xT,Math.floor(p/e.css.cell.height))}}};var _w=Object.defineProperty,kT=Object.getOwnPropertyDescriptor,TT=(e,t)=>{for(var s in t)_w(e,s,{get:t[s],enumerable:!0})},Qt=(e,t,s,r)=>{for(var o=r>1?void 0:r?kT(t,s):t,c=e.length-1,h;c>=0;c--)(h=e[c])&&(o=(r?h(t,s,o):h(o))||o);return r&&o&&_w(t,s,o),o},Me=(e,t)=>(s,r)=>t(s,r,e),$y="Terminal input",Hp={get:()=>$y,set:e=>$y=e},Yy="Too much output to announce, navigate to rows manually to read",Pp={get:()=>Yy,set:e=>Yy=e};function DT(e){return e.replace(/\r?\n/g,"\r")}function RT(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function MT(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function NT(e,t,s,r){if(e.stopPropagation(),e.clipboardData){let o=e.clipboardData.getData("text/plain");vw(o,t,s,r)}}function vw(e,t,s,r){e=DT(e),e=RT(e,s.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),s.triggerDataEvent(e,!0),t.value=""}function bw(e,t,s){let r=s.getBoundingClientRect(),o=e.clientX-r.left-10,c=e.clientY-r.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 Vy(e,t,s,r,o){bw(e,t,s),o&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Mr(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Ch(e,t=0,s=e.length){let r="";for(let o=t;o<s;++o){let c=e[o];c>65535?(c-=65536,r+=String.fromCharCode((c>>10)+55296)+String.fromCharCode(c%1024+56320)):r+=String.fromCharCode(c)}return r}var AT=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let s=e.length;if(!s)return 0;let r=0,o=0;if(this._interim){let c=e.charCodeAt(o++);56320<=c&&c<=57343?t[r++]=(this._interim-55296)*1024+c-56320+65536:(t[r++]=this._interim,t[r++]=c),this._interim=0}for(let c=o;c<s;++c){let h=e.charCodeAt(c);if(55296<=h&&h<=56319){if(++c>=s)return this._interim=h,r;let f=e.charCodeAt(c);56320<=f&&f<=57343?t[r++]=(h-55296)*1024+f-56320+65536:(t[r++]=h,t[r++]=f);continue}h!==65279&&(t[r++]=h)}return r}},LT=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let s=e.length;if(!s)return 0;let r=0,o,c,h,f,g=0,p=0;if(this.interim[0]){let w=!1,S=this.interim[0];S&=(S&224)===192?31:(S&240)===224?15:7;let E=0,T;for(;(T=this.interim[++E]&63)&&E<4;)S<<=6,S|=T;let A=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,O=A-E;for(;p<O;){if(p>=s)return 0;if(T=e[p++],(T&192)!==128){p--,w=!0;break}else this.interim[E++]=T,S<<=6,S|=T&63}w||(A===2?S<128?p--:t[r++]=S:A===3?S<2048||S>=55296&&S<=57343||S===65279||(t[r++]=S):S<65536||S>1114111||(t[r++]=S)),this.interim.fill(0)}let y=s-4,b=p;for(;b<s;){for(;b<y&&!((o=e[b])&128)&&!((c=e[b+1])&128)&&!((h=e[b+2])&128)&&!((f=e[b+3])&128);)t[r++]=o,t[r++]=c,t[r++]=h,t[r++]=f,b+=4;if(o=e[b++],o<128)t[r++]=o;else if((o&224)===192){if(b>=s)return this.interim[0]=o,r;if(c=e[b++],(c&192)!==128){b--;continue}if(g=(o&31)<<6|c&63,g<128){b--;continue}t[r++]=g}else if((o&240)===224){if(b>=s)return this.interim[0]=o,r;if(c=e[b++],(c&192)!==128){b--;continue}if(b>=s)return this.interim[0]=o,this.interim[1]=c,r;if(h=e[b++],(h&192)!==128){b--;continue}if(g=(o&15)<<12|(c&63)<<6|h&63,g<2048||g>=55296&&g<=57343||g===65279)continue;t[r++]=g}else if((o&248)===240){if(b>=s)return this.interim[0]=o,r;if(c=e[b++],(c&192)!==128){b--;continue}if(b>=s)return this.interim[0]=o,this.interim[1]=c,r;if(h=e[b++],(h&192)!==128){b--;continue}if(b>=s)return this.interim[0]=o,this.interim[1]=c,this.interim[2]=h,r;if(f=e[b++],(f&192)!==128){b--;continue}if(g=(o&7)<<18|(c&63)<<12|(h&63)<<6|f&63,g<65536||g>1114111)continue;t[r++]=g}}return r}},yw="",Ar=" ",dc=class Sw{constructor(){this.fg=0,this.bg=0,this.extended=new eh}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 Sw;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}},eh=class ww{constructor(t=0,s=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=s}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 ww(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Zn=class Cw extends dc{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new eh,this.combinedData=""}static fromCharData(t){let s=new Cw;return s.setFromCharData(t),s}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Mr(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 s=!1;if(t[1].length>2)s=!0;else if(t[1].length===2){let r=t[1].charCodeAt(0);if(55296<=r&&r<=56319){let o=t[1].charCodeAt(1);56320<=o&&o<=57343?this.content=(r-55296)*1024+o-56320+65536|t[2]<<22:s=!0}else s=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;s&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Xy="di$target",Up="di$dependencies",$f=new Map;function BT(e){return e[Up]||[]}function Bi(e){if($f.has(e))return $f.get(e);let t=function(s,r,o){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");OT(t,s,o)};return t._id=e,$f.set(e,t),t}function OT(e,t,s){t[Xy]===t?t[Up].push({id:e,index:s}):(t[Up]=[{id:e,index:s}],t[Xy]=t)}var tn=Bi("BufferService"),xw=Bi("CoreMouseService"),Ea=Bi("CoreService"),zT=Bi("CharsetService"),_g=Bi("InstantiationService"),Ew=Bi("LogService"),nn=Bi("OptionsService"),kw=Bi("OscLinkService"),jT=Bi("UnicodeService"),fc=Bi("DecorationService"),Ip=class{constructor(e,t,s){this._bufferService=e,this._optionsService=t,this._oscLinkService=s}provideLinks(e,t){let s=this._bufferService.buffer.lines.get(e-1);if(!s){t(void 0);return}let r=[],o=this._optionsService.rawOptions.linkHandler,c=new Zn,h=s.getTrimmedLength(),f=-1,g=-1,p=!1;for(let y=0;y<h;y++)if(!(g===-1&&!s.hasContent(y))){if(s.loadCell(y,c),c.hasExtendedAttrs()&&c.extended.urlId)if(g===-1){g=y,f=c.extended.urlId;continue}else p=c.extended.urlId!==f;else g!==-1&&(p=!0);if(p||g!==-1&&y===h-1){let b=this._oscLinkService.getLinkData(f)?.uri;if(b){let w={start:{x:g+1,y:e},end:{x:y+(!p&&y===h-1?1:0),y:e}},S=!1;if(!o?.allowNonHttpProtocols)try{let E=new URL(b);["http:","https:"].includes(E.protocol)||(S=!0)}catch{S=!0}S||r.push({text:b,range:w,activate:(E,T)=>o?o.activate(E,T,w):HT(E,T),hover:(E,T)=>o?.hover?.(E,T,w),leave:(E,T)=>o?.leave?.(E,T,w)})}p=!1,c.hasExtendedAttrs()&&c.extended.urlId?(g=y,f=c.extended.urlId):(g=-1,f=-1)}}t(r)}};Ip=Qt([Me(0,tn),Me(1,nn),Me(2,kw)],Ip);function HT(e,t){if(confirm(`Do you want to navigate to ${t}?
16
16
 
17
17
  WARNING: This link could potentially be dangerous`)){let s=window.open();if(s){try{s.opener=null}catch{}s.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var xh=Bi("CharSizeService"),Gs=Bi("CoreBrowserService"),vg=Bi("MouseService"),Zs=Bi("RenderService"),PT=Bi("SelectionService"),Tw=Bi("CharacterJoinerService"),Tl=Bi("ThemeService"),Dw=Bi("LinkProviderService"),UT=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Gy.isErrorNoTelemetry(e)?new Gy(e.message+`
18
18
 
@@ -29,7 +29,7 @@ WARNING: This link could potentially be dangerous`)){let s=window.open();if(s){t
29
29
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===HS+1&&(this._liveRegion.textContent+=Pp.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 s=this._terminal.buffer,r=s.lines.length.toString();for(let o=e;o<=t;o++){let c=s.lines.get(s.ydisp+o),h=[],f=c?.translateToString(!0,void 0,void 0,h)||"",g=(s.ydisp+o+1).toString(),p=this._rowElements[o];p&&(f.length===0?(p.textContent=" ",this._rowColumns.set(p,[0,1])):(p.textContent=f,this._rowColumns.set(p,h)),p.setAttribute("aria-posinset",g),p.setAttribute("aria-setsize",r),this._alignRowWidth(p))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let s=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2],o=s.getAttribute("aria-posinset"),c=t===0?"1":`${this._terminal.buffer.lines.length}`;if(o===c||e.relatedTarget!==r)return;let h,f;if(t===0?(h=s,f=this._rowElements.pop(),this._rowContainer.removeChild(f)):(h=this._rowElements.shift(),f=s,this._rowContainer.removeChild(h)),h.removeEventListener("focus",this._topBoundaryFocusListener),f.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let g=this._createAccessibilityTreeNode();this._rowElements.unshift(g),this._rowContainer.insertAdjacentElement("afterbegin",g)}else{let g=this._createAccessibilityTreeNode();this._rowElements.push(g),this._rowContainer.appendChild(g)}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},s={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(s.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===s.node&&t.offset>s.offset)&&([t,s]=[s,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 r=this._rowElements.slice(-1)[0];if(s.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(s={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(s.node))return;let o=({node:f,offset:g})=>{let p=f instanceof Text?f.parentNode:f,y=parseInt(p?.getAttribute("aria-posinset"),10)-1;if(isNaN(y))return console.warn("row is invalid. Race condition?"),null;let b=this._rowColumns.get(p);if(!b)return console.warn("columns is null. Race condition?"),null;let w=g<b.length?b[g]:b.slice(-1)[0]+1;return w>=this._terminal.cols&&(++y,w=0),{row:y,column:w}},c=o(t),h=o(s);if(!(!c||!h)){if(c.row>h.row||c.row===h.row&&c.column>=h.column)throw new Error("invalid range");this._terminal.select(c.column,c.row,(h.row-c.row)*this._terminal.cols-c.column+h.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,s=this._rowColumns.get(e)?.slice(-1)?.[0];if(!s)return;let r=s*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};rh=Qt([Me(1,_g),Me(2,Gs),Me(3,Zs)],rh);var ym=class extends tt{constructor(e,t,s,r,o){super(),this._element=e,this._mouseService=t,this._renderService=s,this._bufferService=r,this._linkProviderService=o,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new Te),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new Te),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(Pt(()=>{wa(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($e(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register($e(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register($e(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register($e(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 s=e.composedPath();for(let r=0;r<s.length;r++){let o=s[r];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(r=>{r?.forEach(o=>{o.link.dispose&&o.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let s=!1;for(let[r,o]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(s=this._checkLinkProviderResult(r,e,s)):o.provideLinks(e.y,c=>{if(this._isMouseOut)return;let h=c?.map(f=>({link:f}));this._activeProviderReplies?.set(r,h),s=this._checkLinkProviderResult(r,e,s),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let s=new Set;for(let r=0;r<t.size;r++){let o=t.get(r);if(o)for(let c=0;c<o.length;c++){let h=o[c],f=h.link.range.start.y<e?0:h.link.range.start.x,g=h.link.range.end.y>e?this._bufferService.cols:h.link.range.end.x;for(let p=f;p<=g;p++){if(s.has(p)){o.splice(c--,1);break}s.add(p)}}}}_checkLinkProviderResult(e,t,s){if(!this._activeProviderReplies)return s;let r=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&&r){let c=r.find(h=>this._linkAtPosition(h.link,t));c&&(s=!0,this._handleNewLink(c))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!s)for(let c=0;c<this._activeProviderReplies.size;c++){let h=this._activeProviderReplies.get(c)?.find(f=>this._linkAtPosition(f.link,t));if(h){s=!0,this._handleNewLink(h);break}}return s}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&EM(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,wa(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:s=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==s&&(this._currentLink.state.decorations.pointerCursor=s,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",s))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:s=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==s&&(this._currentLink.state.decorations.underline=s,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,s))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(s=>{if(!this._currentLink)return;let r=s.start===0?0:s.start+1+this._bufferService.buffer.ydisp,o=this._bufferService.buffer.ydisp+1+s.end;if(this._currentLink.link.range.start.y>=r&&this._currentLink.link.range.end.y<=o&&(this._clearCurrentLink(r,o),this._lastMouseEvent)){let c=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);c&&this._askForLink(c,!1)}})))}_linkHover(e,t,s){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(s,t.text)}_fireUnderlineEvent(e,t){let s=e.range,r=this._bufferService.buffer.ydisp,o=this._createLinkUnderlineEvent(s.start.x-1,s.start.y-r-1,s.end.x,s.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(o)}_linkLeave(e,t,s){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(s,t.text)}_linkAtPosition(e,t){let s=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,o=t.y*this._bufferService.cols+t.x;return s<=o&&o<=r}_positionFromMouseEvent(e,t,s){let r=s.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,s,r,o){return{x1:e,y1:t,x2:s,y2:r,cols:this._bufferService.cols,fg:o}}};ym=Qt([Me(1,vg),Me(2,Zs),Me(3,tn),Me(4,Dw)],ym);function EM(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 kM=class extends _M{constructor(e={}){super(e),this._linkifier=this._register(new Sl),this.browser=Yw,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Sl),this._onCursorMove=this._register(new Te),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Te),this.onKey=this._onKey.event,this._onRender=this._register(new Te),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Te),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Te),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Te),this.onBell=this._onBell.event,this._onFocus=this._register(new Te),this._onBlur=this._register(new Te),this._onA11yCharEmitter=this._register(new Te),this._onA11yTabEmitter=this._register(new Te),this._onWillOpen=this._register(new Te),this._setup(),this._decorationService=this._instantiationService.createInstance(SM),this._instantiationService.setService(fc,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(mR),this._instantiationService.setService(Dw,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Ip)),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(qi.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(qi.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(qi.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(qi.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(Pt(()=>{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 s,r="";switch(t.index){case 256:s="foreground",r="10";break;case 257:s="background",r="11";break;case 258:s="cursor",r="12";break;default:s="ansi",r="4;"+t.index}switch(t.type){case 0:let o=jt.toColorRGB(s==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[s]);this.coreService.triggerDataEvent(`${pe.ESC}]${r};${hM(o)}${qw.ST}`);break;case 1:if(s==="ansi")this._themeService.modifyColors(c=>c.ansi[t.index]=fi.toColor(...t.color));else{let c=s;this._themeService.modifyColors(h=>h[c]=fi.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(rh,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.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(pe.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 s=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,o=t.getWidth(s),c=this._renderService.dimensions.css.cell.width*o,h=this.buffer.y*this._renderService.dimensions.css.cell.height,f=s*this._renderService.dimensions.css.cell.width;this.textarea.style.left=f+"px",this.textarea.style.top=h+"px",this.textarea.style.width=c+"px",this.textarea.style.height=r+"px",this.textarea.style.lineHeight=r+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register($e(this.element,"copy",t=>{this.hasSelection()&&MT(t,this._selectionService)}));let e=t=>NT(t,this.textarea,this.coreService,this.optionsService);this._register($e(this.textarea,"paste",e)),this._register($e(this.element,"paste",e)),Vw?this._register($e(this.element,"mousedown",t=>{t.button===2&&Vy(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register($e(this.element,"contextmenu",t=>{Vy(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),kg&&this._register($e(this.element,"auxclick",t=>{t.button===1&&bw(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register($e(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register($e(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register($e(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register($e(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register($e(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register($e(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register($e(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($e(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 s=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Hp.get()),Zw||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>s.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(fR,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(Gs,this._coreBrowserService),this._register($e(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register($e(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(om,this._document,this._helperContainer),this._instantiationService.setService(xh,this._charSizeService),this._themeService=this._instantiationService.createInstance(dm),this._instantiationService.setService(Tl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(ih),this._instantiationService.setService(Tw,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(um,this.rows,this.screenElement)),this._instantiationService.setService(Zs,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(rm,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(cm),this._instantiationService.setService(vg,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(ym,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(nm,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(hm,this.element,this.screenElement,r)),this._instantiationService.setService(PT,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(qi.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(sm,this.screenElement)),this._register($e(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(rh,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(th,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(th,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(lm,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function s(c){let h=e._mouseService.getMouseReportCoords(c,e.screenElement);if(!h)return!1;let f,g;switch(c.overrideType||c.type){case"mousemove":g=32,c.buttons===void 0?(f=3,c.button!==void 0&&(f=c.button<3?c.button:3)):f=c.buttons&1?0:c.buttons&4?1:c.buttons&2?2:3;break;case"mouseup":g=0,f=c.button<3?c.button:3;break;case"mousedown":g=1,f=c.button<3?c.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(c)===!1)return!1;let p=c.deltaY;if(p===0||e.coreMouseService.consumeWheelEvent(c,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;g=p<0?0:1,f=4;break;default:return!1}return g===void 0||f===void 0||f>4?!1:e.coreMouseService.triggerMouseEvent({col:h.col,row:h.row,x:h.x,y:h.y,button:f,action:g,ctrl:c.ctrlKey,alt:c.altKey,shift:c.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},o={mouseup:c=>(s(c),c.buttons||(this._document.removeEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.removeEventListener("mousemove",r.mousedrag)),this.cancel(c)),wheel:c=>(s(c),this.cancel(c,!0)),mousedrag:c=>{c.buttons&&s(c)},mousemove:c=>{c.buttons||s(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?r.mousemove||(t.addEventListener("mousemove",o.mousemove),r.mousemove=o.mousemove):(t.removeEventListener("mousemove",r.mousemove),r.mousemove=null),c&16?r.wheel||(t.addEventListener("wheel",o.wheel,{passive:!1}),r.wheel=o.wheel):(t.removeEventListener("wheel",r.wheel),r.wheel=null),c&2?r.mouseup||(r.mouseup=o.mouseup):(this._document.removeEventListener("mouseup",r.mouseup),r.mouseup=null),c&4?r.mousedrag||(r.mousedrag=o.mousedrag):(this._document.removeEventListener("mousemove",r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register($e(t,"mousedown",c=>{if(c.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(c)))return s(c),r.mouseup&&this._document.addEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.addEventListener("mousemove",r.mousedrag),this.cancel(c)})),this._register($e(t,"wheel",c=>{if(!r.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 h=pe.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(c.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(h,!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){vw(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,s){this._selectionService.setSelection(e,t,s)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,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 s=bM(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),s.type===3||s.type===2){let r=this.rows-1;return this.scrollLines(s.type===2?-r:r),this.cancel(e,!0)}if(s.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(s.cancel&&this.cancel(e,!0),!s.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((s.key===pe.ETX||s.key===pe.CR)&&(this.textarea.value=""),this._onKey.fire({key:s.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(s.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let s=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"?s:s&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(TM(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(di));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(pe.ESC+"[I"):this.coreService.triggerDataEvent(pe.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let t=this._renderService.dimensions.css.canvas.width.toFixed(0),s=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${pe.ESC}[4;${s};${t}t`);break;case 1:let r=this._renderService.dimensions.css.cell.width.toFixed(0),o=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${pe.ESC}[6;${o};${r}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function TM(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var DM=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let s={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(s),t.dispose=()=>this._wrappedAddonDispose(s),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let s=0;s<this._addons.length;s++)if(this._addons[s]===e){t=s;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)}},RM=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 Zn)}translateToString(e,t,s){return this._line.translateToString(e,t,s)}},PS=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 RM(t)}getNullCell(){return new Zn}},MM=class extends tt{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Te),this.onBufferChange=this._onBufferChange.event,this._normal=new PS(this._core.buffers.normal,"normal"),this._alternate=new PS(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)}},NM=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,s=>t(s.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(s,r)=>t(s,r.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)}},AM=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}},LM=["cols","rows"],Ss=0,BM=class extends tt{constructor(e){super(),this._core=this._register(new kM(e)),this._addonManager=this._register(new DM),this._publicOptions={...this._core.options};let t=r=>this._core.options[r],s=(r,o)=>{this._checkReadonlyOptions(r),this._core.options[r]=o};for(let r in this._core.options){let o={get:t.bind(this,r),set:s.bind(this,r)};Object.defineProperty(this._publicOptions,r,o)}}_checkReadonlyOptions(e){if(LM.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 NM(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new AM(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 MM(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,s){this._verifyIntegers(e,t,s),this._core.select(e,t,s)}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
30
30
  `,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 Hp.get()},set promptLabel(e){Hp.set(e)},get tooMuchOutput(){return Pp.get()},set tooMuchOutput(e){Pp.set(e)}}}_verifyIntegers(...e){for(Ss of e)if(Ss===1/0||isNaN(Ss)||Ss%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Ss of e)if(Ss&&(Ss===1/0||isNaN(Ss)||Ss%1!==0||Ss<0))throw new Error("This API only accepts positive integers")}};class OM{pending=null;accept(t){let s="";for(const r of t)s+=this.acceptChar(r);return s}acceptChar(t){return t===""?this.acceptBackspace():u1.has(t)?this.acceptConsonant(t):h1.has(t)?this.acceptVowel(t):PM(t)&&this.canReplacePendingWith(t)?(this.pending=IS(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(d1.has(t))return this.pending.final=t,"";const o=this.flushPending();return this.pending={initial:t},o}const s=HM.get(`${this.pending.final}${t}`);if(s)return this.pending.final=s,"";const r=this.flushPending();return this.pending={initial:t},r}acceptVowel(t){if(!this.pending)return t;if(!this.pending.vowel)return this.pending.vowel=t,"";if(!this.pending.final){const c=jM.get(`${this.pending.vowel}${t}`);return c?(this.pending.vowel=c,""):this.flushPending()+t}const s=US.get(this.pending.final);if(s){this.pending.final=s[0];const c=this.flushPending();return this.pending={initial:s[1],vowel:t},c}const r=this.pending.final,o=KS({initial:this.pending.initial,vowel:this.pending.vowel});return this.pending={initial:r,vowel:t},o}acceptBackspace(){if(!this.pending)return"";if(this.pending.final){const t=US.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 s=IS(t);return s.initial===this.pending.initial&&(!this.pending.vowel||s.vowel===this.pending.vowel)&&(!this.pending.final||s.final===this.pending.final)}flushPending(){if(!this.pending)return"";const t=KS(this.pending);return this.pending=null,t}}const ah=44032,lh=21,fl=28,zM=19*lh*fl,l1=["ㄱ","ㄲ","ㄴ","ㄷ","ㄸ","ㄹ","ㅁ","ㅂ","ㅃ","ㅅ","ㅆ","ㅇ","ㅈ","ㅉ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"],o1=["ㅏ","ㅐ","ㅑ","ㅒ","ㅓ","ㅔ","ㅕ","ㅖ","ㅗ","ㅘ","ㅙ","ㅚ","ㅛ","ㅜ","ㅝ","ㅞ","ㅟ","ㅠ","ㅡ","ㅢ","ㅣ"],c1=["","ㄱ","ㄲ","ㄳ","ㄴ","ㄵ","ㄶ","ㄷ","ㄹ","ㄺ","ㄻ","ㄼ","ㄽ","ㄾ","ㄿ","ㅀ","ㅁ","ㅂ","ㅄ","ㅅ","ㅆ","ㅇ","ㅈ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"],u1=Tg(l1),h1=Tg(o1),d1=Tg(c1),jM=new Map([["ㅗㅏ","ㅘ"],["ㅗㅐ","ㅙ"],["ㅗㅣ","ㅚ"],["ㅜㅓ","ㅝ"],["ㅜㅔ","ㅞ"],["ㅜㅣ","ㅟ"],["ㅡㅣ","ㅢ"]]),f1=[["ㄱㅅ","ㄳ"],["ㄴㅈ","ㄵ"],["ㄴㅎ","ㄶ"],["ㄹㄱ","ㄺ"],["ㄹㅁ","ㄻ"],["ㄹㅂ","ㄼ"],["ㄹㅅ","ㄽ"],["ㄹㅌ","ㄾ"],["ㄹㅍ","ㄿ"],["ㄹㅎ","ㅀ"],["ㅂㅅ","ㅄ"]],HM=new Map(f1),US=new Map(f1.map(([e,t])=>[t,[e[0],e[1]]]));function Tg(e){return new Map(e.map((t,s)=>[t,s]))}function PM(e){const t=e.codePointAt(0);return t!==void 0&&t>=ah&&t<ah+zM}function IS(e){const t=e.codePointAt(0)-ah,s=Math.floor(t/(lh*fl)),r=Math.floor(t%(lh*fl)/fl),o=t%fl,c={initial:l1[s],vowel:o1[r]};return o===0?c:{...c,final:c1[o]}}function KS(e){if(!e.vowel)return e.initial;const t=u1.get(e.initial),s=h1.get(e.vowel),r=e.final?d1.get(e.final):0;return t===void 0||s===void 0||r===void 0?`${e.initial}${e.vowel}${e.final??""}`:String.fromCodePoint(ah+(t*lh+s)*fl+r)}const UM=[{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 IM({ctrlActive:e,onCtrl:t,onStandaloneKey:s,onPreserveFocus:r,onHide:o}){function c(h){h.stopPropagation(),r()}return m.jsxs("div",{className:"mobile-terminal-key-bar",role:"toolbar","aria-label":"Mobile terminal keys",onMouseDown:c,onPointerDown:c,children:[m.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"}),UM.map(h=>m.jsx("button",{type:"button",className:"mobile-terminal-key","aria-label":h.ariaLabel,onClick:()=>s(h.key),children:h.label},h.key)),m.jsx("button",{type:"button",className:"mobile-terminal-key mobile-terminal-key-hide","aria-label":"Hide terminal control keys",title:"Hide",onClick:o,children:"×"})]})}const KM={escape:"\x1B",tab:" ",arrowUp:"\x1B[A",arrowDown:"\x1B[B",arrowRight:"\x1B[C",arrowLeft:"\x1B[D"};function FM(e){return KM[e]}function WM(e){return/^[a-z]$/i.test(e)?String.fromCharCode(e.toUpperCase().charCodeAt(0)-64):null}const FS="--nterminal-viewport-height",WS="--nterminal-keyboard-inset-bottom",qS="data-nterminal-keyboard-visible",Th="data-nterminal-compose-open",nc="nterminal:viewport-refresh",qM=120;function $M(e=window){const t=e.document.documentElement,s=e.visualViewport;function r(){const o=YM(e);o!==null&&t.style.setProperty(FS,`${o}px`),t.style.setProperty(WS,`${p1(e)}px`),t.setAttribute(qS,String(VM(e)))}return r(),s?.addEventListener("resize",r),s?.addEventListener("scroll",r),e.addEventListener("resize",r),e.addEventListener(nc,r),e.addEventListener("orientationchange",r),e.addEventListener("pageshow",r),e.document.addEventListener("visibilitychange",r),()=>{s?.removeEventListener("resize",r),s?.removeEventListener("scroll",r),e.removeEventListener("resize",r),e.removeEventListener(nc,r),e.removeEventListener("orientationchange",r),e.removeEventListener("pageshow",r),e.document.removeEventListener("visibilitychange",r),t.style.removeProperty(FS),t.style.removeProperty(WS),t.removeAttribute(qS)}}function YM(e){if(e.document.documentElement.hasAttribute(Th)&&Xo(e.innerHeight))return e.innerHeight;const t=e.visualViewport?.height;return Xo(t)?t:Xo(e.innerHeight)?e.innerHeight:null}function Xo(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function VM(e){return p1(e)>qM}function p1(e){const t=e.visualViewport?.height;if(!Xo(t)||!Xo(e.innerHeight))return 0;const s=typeof e.visualViewport?.offsetTop=="number"?e.visualViewport.offsetTop:0;return Math.max(0,Math.round(e.innerHeight-t-s))}const gc=new Map,sc=new Map,XM=Object.freeze({open:!1,text:""});function GM(e){let t=sc.get(e);return t||(t=new Set,sc.set(e,t)),t}function m1(e){const t=sc.get(e);if(t)for(const s of Array.from(t))s()}function Dg(e){return gc.get(e)??XM}function ZM(e,t){const s=GM(e);return s.add(t),()=>{s.delete(t)}}function QM(e,t){const s=Dg(e);s.open!==t&&(gc.set(e,{...s,open:t}),m1(e))}function JM(e,t){const s=Dg(e);s.text!==t&&(gc.set(e,{...s,text:t}),m1(e))}function Nu(e){gc.delete(e),sc.delete(e)}function $S(){gc.clear(),sc.clear()}const g1=120,eN="\x1B[200~",tN="\x1B[201~";function YS(e,t){const s=t.stripTrailingLineBreaks===!1?e:Rg(e),r=nN(s);return r?t.bracketedPasteMode?`${eN}${r}${tN}`:r:""}function iN(e){return e==="queue"?" ":"\r"}function Rg(e){return e.replace(/(?:\r\n|\r|\n)+$/,"")}function nN(e){return e.replace(/\r\n/g,`
31
31
  `).replace(/\r/g,`
32
- `).replace(/\n/g,"\r")}const sN=420,Ku=new Set;let _l=null;function rN({terminalId:e,onSubmit:t,queueAvailable:s=!1,disabled:r=!1}){const o=v.useMemo(()=>A=>ZM(e,A),[e]),c=v.useMemo(()=>()=>Dg(e),[e]),h=v.useSyncExternalStore(o,c,c),{open:f,text:g}=h,p=v.useRef(null),y=v.useRef(null),b=v.useRef(null);v.useLayoutEffect(()=>{if(!(!f||!Sm()))return lN(e),()=>oN(e)},[f,e]),v.useLayoutEffect(()=>{const A=p.current?.closest(".terminal-pane");if(!A)return;function O(){A?.removeAttribute("data-compose-open"),A?.style.removeProperty("--compose-drawer-panel-height")}if(!f){O();return}const L=y.current;A.setAttribute("data-compose-open","true");function U(){const ae=L?.getBoundingClientRect().height??0;ae>0&&A?.style.setProperty("--compose-drawer-panel-height",`${Math.ceil(ae)}px`)}U();const I=[window.setTimeout(U,0),window.setTimeout(U,180),window.setTimeout(U,260)],te=window.requestAnimationFrame?.(U)??null,ee=typeof ResizeObserver=="function"&&L?new ResizeObserver(U):null;return ee&&L&&ee.observe(L),()=>{for(const ae of I)window.clearTimeout(ae);te!==null&&window.cancelAnimationFrame?.(te),ee?.disconnect(),O()}},[f]),v.useEffect(()=>{f&&b.current?.focus()},[f]);function w(A){QM(e,A)}function S(A){JM(e,A)}function E(){aN(p.current),w(!1),VS()}function T(A="send"){if(!(r||!g)){if(t(g,A),S(""),Sm()){b.current?.blur(),VS();return}window.setTimeout(()=>b.current?.focus(),g1+20)}}return m.jsxs("div",{ref:p,className:"compose-drawer","data-open":f?"true":"false",children:[m.jsxs("button",{type:"button",className:"compose-drawer-handle","aria-label":"Open compose drawer","aria-hidden":f?"true":void 0,tabIndex:f?-1:0,title:"Compose long input — type without per-keystroke latency, send with Cmd/Ctrl+Enter",onClick:()=>w(!0),children:[m.jsx("span",{"aria-hidden":"true",children:"▴"}),m.jsx("span",{children:"compose"}),g?m.jsx("span",{className:"compose-drawer-handle-dot","aria-label":"draft saved"}):null]}),m.jsxs("div",{ref:y,className:"compose-drawer-panel","aria-hidden":f?void 0:"true",children:[m.jsxs("button",{type:"button",className:"compose-drawer-header","aria-label":"Collapse compose drawer",tabIndex:f?0:-1,title:"Click to collapse — Esc also closes when focus is in the textarea",onClick:E,children:[m.jsx("span",{"aria-hidden":"true",children:"▾"}),m.jsx("span",{className:"compose-drawer-title",children:"compose"}),m.jsx("span",{className:"compose-drawer-hint","aria-hidden":"true",children:s?"Cmd/Ctrl+Enter to send · Cmd/Ctrl+Shift+Enter to queue · Esc to close":"Cmd/Ctrl+Enter to send · Enter for newline · Esc to close"}),m.jsx("span",{className:"compose-drawer-close","aria-hidden":"true",children:"×"})]}),m.jsx("textarea",{ref:b,className:"compose-drawer-input","aria-label":"Compose input",tabIndex:f?0:-1,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",value:g,onChange:A=>S(A.target.value),onKeyDown:A=>{if(A.key==="Enter"&&(A.metaKey||A.ctrlKey)){if(A.preventDefault(),A.shiftKey){s&&T("queue");return}T("send");return}A.key==="Escape"&&(A.preventDefault(),E())},placeholder:s?"Type a longer command here, then send or queue it.":"Type a longer command here, then Cmd/Ctrl+Enter to send."}),m.jsxs("div",{className:"compose-drawer-actions",children:[m.jsx("button",{type:"button",className:"compose-drawer-clear",tabIndex:f?0:-1,onClick:()=>{S(""),b.current?.focus()},disabled:!g,children:"Clear"}),s?m.jsx("button",{type:"button",className:"compose-drawer-queue",tabIndex:f?0:-1,title:"Queue in Codex with Cmd/Ctrl+Shift+Enter",onClick:()=>T("queue"),disabled:r||!g,children:"Queue"}):null,m.jsx("button",{type:"button",className:"compose-drawer-send",tabIndex:f?0:-1,onClick:()=>T("send"),disabled:r||!g,children:"Send"})]})]})]})}function aN(e){const t=document.activeElement;t instanceof HTMLElement&&(!e||e.contains(t))&&t.blur()}function Sm(){return navigator.maxTouchPoints>0?!0:typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}function VS(){if(!Sm())return;const e=()=>{window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0,pl()};e(),window.requestAnimationFrame?.(e),window.setTimeout(e,120),window.setTimeout(e,320)}function lN(e){_l!==null&&(window.clearTimeout(_l),_l=null),Ku.add(e),document.documentElement.setAttribute(Th,"true"),pl()}function oN(e){if(Ku.delete(e),Ku.size>0||_l!==null){pl();return}_l=window.setTimeout(()=>{if(_l=null,Ku.size>0){pl();return}document.documentElement.removeAttribute(Th),pl()},sN),pl()}function pl(){window.dispatchEvent(new Event(nc))}function cN(e,t){e.attachCustomKeyEventHandler(c=>{if(uN(c)){const h=XS(e);return h?(c.preventDefault(),c.stopPropagation(),GS(h),!1):!0}return hN(c)?(c.preventDefault(),c.stopPropagation(),dN(e,t),!1):!0});const s=e.element;if(!s)return{dispose(){e.attachCustomKeyEventHandler(()=>!0)}};const r=c=>{const h=XS(e);if(h){if(c.clipboardData){c.clipboardData.setData("text/plain",h),c.preventDefault();return}c.preventDefault(),GS(h)}},o=c=>{const h=c.clipboardData?.getData("text/plain");if(!h)return;const f=Rg(h);c.preventDefault(),c.stopImmediatePropagation(),_1(e,f,t)};return s.addEventListener("copy",r,!0),s.addEventListener("paste",o,!0),{dispose(){s.removeEventListener("copy",r,!0),s.removeEventListener("paste",o,!0),e.attachCustomKeyEventHandler(()=>!0)}}}function uN(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 hN(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 dN(e,t){if(navigator.clipboard?.readText)try{const s=await navigator.clipboard.readText();if(!s)return;_1(e,Rg(s),t)}catch{}}function _1(e,t,s){if(t){if(s){s(t);return}e.paste(t)}}function XS(e){return e.hasSelection()?e.getSelection():""}async function GS(e){if(navigator.clipboard?.writeText)try{await navigator.clipboard.writeText(e);return}catch{}fN(e)}function fN(e){const t=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("textarea");s.value=e,s.setAttribute("readonly","true"),s.style.position="fixed",s.style.left="-9999px",s.style.top="0",s.style.opacity="0",document.body.appendChild(s),s.focus({preventScroll:!0}),s.select();try{typeof document.execCommand=="function"&&document.execCommand("copy")}finally{s.remove(),t?.focus({preventScroll:!0})}}const pN=[4,10,11,12];function mN(e,t){const s=[e.parser.registerCsiHandler({final:"c"},r=>ZS(r)),e.parser.registerCsiHandler({prefix:">",final:"c"},r=>ZS(r)),e.parser.registerCsiHandler({final:"n"},r=>gN(r)),e.parser.registerCsiHandler({prefix:"?",final:"n"},r=>_N(r)),e.parser.registerCsiHandler({final:"t"},r=>vN(r)),e.parser.registerDcsHandler({intermediates:"$",final:"q"},()=>!0),...pN.map(r=>e.parser.registerOscHandler(r,o=>bN(o)))];return{dispose(){for(const r of s)r.dispose()}}}function ZS(e){return Dh(e)===0}function gN(e){const t=Dh(e);return t===5||t===6}function _N(e){return Dh(e)===6}function vN(e){const t=Dh(e);return t===14||t===16||t===18}function bN(e){return e.split(";").some(t=>t==="?")}function Dh(e){const t=e[0];return typeof t=="number"?t:0}const xa=new Map,yN=2*1024*1024,SN=1500,wN=25e3;function CN(e,t){let s=xa.get(e);s||(s=kN(e),xa.set(e,s),Rh(s)),s.listeners.add(t);const r=c=>AN(s,c),o=()=>{s.listeners.delete(t)};return{status:s.status,snapshot:s.snapshot,output:s.output.slice(),history:s.history,send:r,detach:o}}function Ho(e){const t=xa.get(e);t&&(LN(t),xa.delete(e))}function xN(e,t={}){const s=xa.get(e);if(!s)return!1;s.exited=!1,s.reconnectEnabled=!0,t.preserveCachedOutputOnNextSnapshot&&(s.preserveCachedOutputOnNextSnapshot=!0),s.reconnectTimer!==null&&(window.clearTimeout(s.reconnectTimer),s.reconnectTimer=null),_c(s);const r=s.socket;return s.socket=null,pa(s,"reconnecting"),r&&(r.readyState===WebSocket.OPEN||r.readyState===WebSocket.CONNECTING)&&r.close(),Rh(s),!0}function EN(){for(const e of xa.values()){if(e.status!=="unauthorized"||e.exited)continue;e.reconnectTimer!==null&&(window.clearTimeout(e.reconnectTimer),e.reconnectTimer=null),_c(e);const t=e.socket;e.socket=null,e.reconnectEnabled=!0,pa(e,"reconnecting"),t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),Rh(e)}}function rp(){for(const e of Array.from(xa.keys()))Ho(e)}function kN(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,preserveCachedOutputOnNextSnapshot:!1}}function Rh(e){if(!e.reconnectEnabled)return;pa(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){pa(e,"connected");for(const s of e.pendingOut)t.send(JSON.stringify(s));e.pendingOut.length=0,e.isAlive=!0,TN(e)}}),t.addEventListener("message",s=>{if(e.socket!==t)return;const r=typeof s.data=="string"?s.data:"";if(!r)return;let o=null;try{o=JSON.parse(r)}catch{return}if(!o||typeof o.type!="string")return;if(o.type==="pong"){e.isAlive=!0;return}const c=RN(e,o);v1(e,{type:"message",message:c})}),t.addEventListener("close",s=>{if(e.socket===t){if(e.socket=null,_c(e),s.code===1008){e.reconnectEnabled=!1,pa(e,DN(s.reason)?"unauthorized":"closed");return}if(e.exited||!e.reconnectEnabled){pa(e,"closed");return}pa(e,"reconnecting"),e.reconnectTimer=window.setTimeout(()=>{e.reconnectTimer=null,Rh(e)},SN)}}),t.addEventListener("error",()=>{})}function TN(e){_c(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)}))}},wN)}function _c(e){e.heartbeat!==null&&(window.clearInterval(e.heartbeat),e.heartbeat=null)}function DN(e){return e.trim().toLowerCase()==="unauthorized"}function RN(e,t){return t.type==="snapshot"?(e.snapshot=t.terminal,e.history=t.history??null,e.exited=t.terminal.status==="exited",e.preserveCachedOutputOnNextSnapshot?(e.preserveCachedOutputOnNextSnapshot=!1,MN(e,t.output),ap(e),{...t,output:e.output.slice(),history:e.history}):(e.output=t.output.slice(),e.outputBytes=e.output.reduce((s,r)=>s+r.length,0),ap(e),t)):t.type==="output"?(e.output.push(t.data),e.outputBytes+=t.data.length,ap(e),t):t.type==="terminal_updated"?(e.snapshot=t.terminal,t.terminal.status==="exited"&&(e.exited=!0),t):(t.type==="exit"&&(e.exited=!0,e.snapshot&&e.snapshot.id===t.terminalId&&(e.snapshot={...e.snapshot,status:"exited",exitCode:t.exitCode})),t)}function MN(e,t){const s=NN(e.output,t);if(s===0)return;const r=t.slice(s);for(const o of r)e.output.push(o),e.outputBytes+=o.length}function NN(e,t){const s=Math.min(e.length,t.length);for(let r=s;r>0;r-=1){let o=!0;for(let c=0;c<r;c+=1)if(e[e.length-r+c]!==t[c]){o=!1;break}if(o)return r}return 0}function ap(e){for(;e.outputBytes>yN&&e.output.length>1;){const t=e.output.shift();e.outputBytes-=t.length}}function pa(e,t){e.status!==t&&(e.status=t,v1(e,{type:"status",status:t}))}function v1(e,t){for(const s of Array.from(e.listeners))s(t)}function AN(e,t){const s=e.socket;return s&&s.readyState===WebSocket.OPEN?(s.send(JSON.stringify(t)),!0):(t.type==="input"&&e.pendingOut.push(t),!1)}function LN(e){e.reconnectEnabled=!1,e.reconnectTimer!==null&&(window.clearTimeout(e.reconnectTimer),e.reconnectTimer=null),_c(e);const t=e.socket;e.socket=null,t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),e.listeners.clear()}const BN=[0,50,150,350],ON=120,zN=2,jN=[300,1200,2500],HN=1e3,PN=1e5,wm="\x1B[?1049l\x1B[?1047l\x1B[?47l",UN=new Set(["47","1047","1049"]),IN=400,KN=3,FN=3,WN=32,qN=1.42,$N=2,YN=24,VN=240,XN=60,GN=420,ZN=6,QN=2,QS=[500,1500,3e3,5e3,8e3],JS=15e3,JN=Si.lazy(()=>gg(()=>import("./TranscriptMarkdownBody-hbar9gNN.js"),__vite__mapDeps([2,1])));function e0({terminal:e,serverApi:t,active:s,visible:r=!0,canClose:o,refreshCwdOnEnter:c=!1,tabId:h,onSelect:f,onClose:g,onExit:p,onSnapshot:y,onAuthClose:b}){const w=v.useSyncExternalStore(rw,Np,()=>_a),S=v.useSyncExternalStore(aw,Ap,()=>bl),E=v.useSyncExternalStore(lw,Bp,()=>!0),T=v.useSyncExternalStore(qm,Or,()=>vl),A=v.useSyncExternalStore(ug,()=>hg("history.toggle"),()=>"Alt+H"),O=v.useRef(null),L=v.useRef(null),U=v.useRef(null),I=v.useRef(null),te=v.useRef({onExit:p,onSnapshot:y}),ee=v.useRef(t.createWebSocketUrl),ae=v.useRef(b),ue=v.useRef(null),be=v.useRef(null),we=v.useRef(!1),ne=v.useRef(new Map),ie=v.useRef([]),Y=v.useRef([]),K=v.useRef([]),re=v.useRef(0),B=v.useRef(!1),$=v.useRef(null),D=v.useRef(0),X=v.useRef(null),_e=v.useRef(null),R=v.useRef(!1),H=v.useRef(!1),Q=v.useRef(!1),de=v.useRef(!1),ke=v.useRef(null),xe=v.useRef(null),Re=v.useRef(!1),Xe=v.useRef(!1),ge=v.useRef(!1),G=v.useRef(!1),ce=v.useRef(!1),Ce=v.useRef(!1),ye=v.useRef(!1),De=v.useRef(s),Be=v.useRef(r),Ke=v.useRef(c),le=v.useRef(w),Ee=v.useRef(S),Le=v.useRef(!1),Oe=v.useRef(null),He=v.useRef(null),_t=v.useRef(!1),Ye=v.useRef(null),[,rt]=v.useState("connecting"),[Oi,$i]=v.useState(!1),[Ci,ri]=v.useState(null),[zi,sn]=v.useState(!1),[F,qe]=v.useState(null),[dt,vt]=v.useState(!1),[pi,St]=v.useState(!1),[mn,Ln]=v.useState(!1),[Jt,ai]=v.useState(null),[Zi,gt]=v.useState(!1),Tt=!!Jt||Fu(e.currentCommand),[Dt,mi]=v.useState(!1);v.useLayoutEffect(()=>{De.current=s},[s]),v.useLayoutEffect(()=>{Be.current=r},[r]),v.useLayoutEffect(()=>{Ke.current=c},[c]),v.useLayoutEffect(()=>{le.current=w},[w]),v.useLayoutEffect(()=>{Ee.current=S},[S]),v.useLayoutEffect(()=>{Le.current=Zi},[Zi]),v.useLayoutEffect(()=>{Oe.current=Jt},[Jt]),v.useLayoutEffect(()=>{_t.current=Tt},[Tt]),v.useEffect(()=>{r&&s&&e.status==="running"&&(At(),bn())},[s,r,e.status]),v.useEffect(()=>{te.current={onExit:p,onSnapshot:y}},[p,y]),v.useEffect(()=>{ee.current=t.createWebSocketUrl,ae.current=b},[t,b]),v.useEffect(()=>{let M=!1,J=null,je=0;const Fe=p3(e.currentCommand),Ie=Fu(e.currentCommand);function Ge(){J!==null&&(window.clearTimeout(J),J=null)}function Ft(wt){if(M)return;let Bt;if(wt){if(!Ie)return;Bt=JS}else if(je<QS.length){if(!Fe)return;Bt=QS[je++]}else{if(!Ie)return;Bt=JS}J=window.setTimeout(()=>{J=null,li()},Bt)}async function li(){try{const wt=await t.getTerminalTranscriptSource(e.id);if(M)return;ai(Bt=>Bt&&wt.source&&Bt.provider===wt.source.provider&&Bt.sessionId===wt.source.sessionId?Bt:wt.source),Ft(!!wt.source)}catch(wt){if(M)return;lp(wt)&&ai(null),Ft(!1)}}return ai(null),e.status!=="running"?()=>{M=!0,Ge()}:(li(),()=>{M=!0,Ge()})},[t,e.currentCommand,e.id,e.status]),v.useEffect(()=>{const M=Jt?`${e.id}:${Jt.provider}:${Jt.sessionId}`:null,J=He.current;J!==null&&M!==null&&J!==M&&Le.current&&gt(!1),He.current=M},[e.id,Jt?.provider,Jt?.sessionId]),v.useEffect(()=>{function M(J){!De.current||!Be.current||!Oe.current||J.isComposing||J.key==="Process"||i3(J.target)||ow(J)?.id!=="history.toggle"||(J.preventDefault(),J.stopPropagation(),gt(Fe=>!Fe))}return window.addEventListener("keydown",M,!0),()=>window.removeEventListener("keydown",M,!0)},[]),v.useEffect(()=>{const M=L.current;M&&(M.options.disableStdin=e.status==="exited"),e.status==="exited"&&rt("closed")},[e.status]),v.useEffect(()=>{const M=L.current;M&&(M.options.fontSize=w,Kf(w,Ee.current).then(()=>{le.current===w&&At()}))},[w]),v.useEffect(()=>{const M=L.current;M&&(M.options.fontFamily=Mp(S),Kf(le.current,S).then(()=>{Ee.current===S&&At()}))},[S]),v.useEffect(()=>{const M=L.current;M&&(M.options.theme=t0(T))},[T]),v.useEffect(()=>{const M=O.current;if(!M)return;let J=!1,je=null,Fe=null,Ie=null,Ge=null,Ft=null,li=null,wt=null;ue.current=null,ce.current=!1,Ce.current=!1,de.current=!1,es(),Ut();const Bt=le.current,Ui=Ee.current,Wt=new BM({cursorBlink:!0,convertEol:!1,disableStdin:e.status==="exited",fontFamily:Mp(Ui),fontSize:Bt,fontWeight:400,fontWeightBold:700,macOptionClickForcesSelection:!0,scrollback:PN,theme:{...t0(Or())}}),Sn=new ET;return Wt.loadAddon(Sn),Ge=mN(Wt),L.current=Wt,U.current=Sn,Kf(Bt,Ui).then(()=>{if(J)return;Wt.open(M),ce.current=!0,je=cN(Wt,Na),Be.current&&De.current&&e.status==="running"&&bn(),At(),Ft=C3(M,Wt,()=>le.current*1.2,Vi,x=>{It(x)},Ts,it),li=y3(M,Wt,Vi,x=>{It(x)},Ts,it);const jn=new OM;Fe=Wt.onData(x=>{if(ye.current){const j=WM(x);if(j){yn(!1),rs(j);return}}const k=jn.accept(x);k&&rs(k)}),Ie=Wt.onScroll(x=>{if(Xe.current||G.current||ge.current){ot();return}_n(),cs(Wt)&&On({scrollToBottom:!0}),Vi(),x<=3&&It()}),wt=new ResizeObserver(()=>{Hi()}),wt.observe(M),Ce.current&&(Lt(),Ce.current=!1,At()),fs()}),()=>{J=!0,ce.current=!1,Ce.current=!1,es(),be.current=null,we.current=!1,ts(),Ur(),ge.current=!1,Ft?.(),li?.(),wt?.disconnect(),je?.dispose(),Fe?.dispose(),Ie?.dispose(),Ge?.dispose(),Wt.dispose(),L.current=null,U.current=null}},[e.id]),v.useEffect(()=>{const M=ee.current(e.id),J=CN(M,gi);return I.current=J.send,rt(J.status),J.status==="connected"&&At(),J.snapshot&&(te.current.onSnapshot(J.snapshot,{notifyCompletion:!1}),L.current&&(At(),ei(J.output,J.history),At())),()=>{J.detach(),I.current=null}},[e.id,e.status]);function gi(M){if(M.type==="status"){rt(M.status),M.status==="unauthorized"&&ae.current?.({source:"terminal-ws-1008",terminalId:e.id}),M.status==="connected"&&At();return}Qi(M.message)}function Ut(M=[],J=null){Y.current=[],K.current=Au(M),re.current=0,B.current=!1,$.current=null,ge.current=!1,D.current+=1,X.current=J,_e.current=null,R.current=!1,H.current=!1,Q.current=!1,Ce.current=!1,Ye.current=null,ke.current=null,Re.current=!1,$i(!1),ri(null),sn(!1),qe(null),vt(!1),St(!1)}function ei(M=[],J=null){Ut(M,J),ji()}function ji(){if(!L.current||!ce.current){Ce.current=!0;return}Ce.current=!1,Lt()}async function Lt(){const M=L.current;if(!M)return;const J=Lu(M,Re.current),je=J?K.current.length:re.current;await xi(M,{liveOutputLimit:je,scrollToBottom:J}),L.current===M&&ot()}function xi(M,J={}){return new Promise(je=>{ge.current=!0,B.current=!1;const Fe=D.current+1;D.current=Fe;const Ie=Math.max(0,Math.min(J.liveOutputLimit??K.current.length,K.current.length)),Ge=J.historyPages??Y.current,Ft=()=>{if(L.current!==M||D.current!==Fe){je(!1);return}try{re.current=Ie,J.scrollToBottom&&ss(M)}finally{ge.current=!1;const wt=Ir();wt?On(wt):J.applyDeferredSnapshot!==!1&&Yt(),je(!0)}},li=()=>{if(L.current!==M||D.current!==Fe){je(!1);return}M.clear();const wt=Au([...Ge,...K.current.slice(0,Ie)]);if(wt.length===0){Ft();return}for(let Bt=0;Bt<wt.length;Bt+=1){const Ui=wt[Bt];Bt===wt.length-1?M.write(Ui,Ft):M.write(Ui)}};if(M.buffer.active.type==="alternate"){M.write(wm,li);return}li()})}async function It(M=0){const J=L.current;if(Q.current||!J)return;if(Kr(J)){ot();return}const je=X.current;Q.current=!0,$i(!0);const Fe=J.buffer.active.viewportY;try{let Ie=!!(je&&!je.hasMore);if(!Ie)try{const Ge=await t.getTerminalHistory(e.id,{beforeLine:je?.startLine??0,limit:HN}),Ft={startLine:Ge.startLine,endLine:Ge.endLine,hasMore:Ge.hasMore};if(Ge.output.length>0){await rn(J,Ge.output,Fe,M)&&(X.current=Ft);return}X.current=Ft,Ie=!Ge.hasMore}catch(Ge){Ie=lp(Ge)}if(Ie){if(Kr(J)){ot();return}await Yi(J,Fe,M)}}catch{}finally{Q.current=!1,$i(!1)}}async function Yi(M,J,je){if(!(R.current||H.current))try{const Fe=_e.current,Ie=await t.getTerminalTranscriptHistory(e.id,{...Fe?{cursor:Fe}:{},limit:IN}),Ge=Ie.output.map(S1);if(!Ie.source)return;if(Ge.length===0){ai(Ie.source),_e.current=Ie.cursor,H.current=!Ie.hasMore||!Ie.cursor;return}await rn(M,Ge,J,je)&&(ai(Ie.source),_e.current=Ie.cursor,H.current=!Ie.hasMore||!Ie.cursor)}catch(Fe){lp(Fe)&&(R.current=!0)}}async function rn(M,J,je,Fe){if(Kr(M))return ot(),!1;const Ie=[...J,...Y.current],Ge=v3(J);return!await xi(M,{liveOutputLimit:re.current,scrollToBottom:!1,historyPages:Ie,applyDeferredSnapshot:!1})||L.current!==M?!1:(Y.current=Ie,Fr(M,Math.max(0,je+Ge+Math.min(0,Fe))),Re.current=!cs(M),Vi(),!0)}v.useEffect(()=>{const M=window.visualViewport;function J(){document.visibilityState==="visible"&&At()}function je(){At()}function Fe(){Hi()}function Ie(){Ei()}return document.addEventListener("visibilitychange",J),window.addEventListener("pageshow",je),window.addEventListener("resize",Fe),window.addEventListener(nc,Ie),M?.addEventListener("resize",Fe),M?.addEventListener("scroll",Fe),()=>{document.removeEventListener("visibilitychange",J),window.removeEventListener("pageshow",je),window.removeEventListener("resize",Fe),window.removeEventListener(nc,Ie),M?.removeEventListener("resize",Fe),M?.removeEventListener("scroll",Fe)}},[e.id]);function an(){const M=ee.current(e.id);de.current=!0,Ye.current=null,rt("reconnecting"),At(),xN(M,{preserveCachedOutputOnNextSnapshot:!0})}function Qi(M){if(M.type==="snapshot"&&M.terminal.id===e.id){te.current.onSnapshot(M.terminal,{notifyCompletion:!1});const je=L.current;if(!je)return;At();const Fe=de.current;if(de.current=!1,Fe){X.current=M.history??X.current,ot(),At();return}if(Qs(je,M.terminal)){vn(M.output,M.history??null),ot(),At();return}ei(M.output,M.history??null),At();return}if(M.type==="terminal_updated"&&M.terminal.id===e.id){te.current.onSnapshot(M.terminal,{notifyCompletion:!0});return}if(M.type==="output"&&M.terminalId===e.id){const je=x1(M.data);if(!je)return;K.current.push(je),L.current&&ce.current?On({scrollToBottom:!0}):Ce.current=!0;return}const J=L.current;if(J){if(M.type==="exit"&&M.terminalId===e.id){te.current.onExit(M.exitCode),rt("closed");return}M.type==="error"&&J.writeln(`\r
32
+ `).replace(/\n/g,"\r")}const sN=420,Ku=new Set;let _l=null;function rN({terminalId:e,onSubmit:t,queueAvailable:s=!1,disabled:r=!1}){const o=v.useMemo(()=>A=>ZM(e,A),[e]),c=v.useMemo(()=>()=>Dg(e),[e]),h=v.useSyncExternalStore(o,c,c),{open:f,text:g}=h,p=v.useRef(null),y=v.useRef(null),b=v.useRef(null);v.useLayoutEffect(()=>{if(!(!f||!Sm()))return lN(e),()=>oN(e)},[f,e]),v.useLayoutEffect(()=>{const A=p.current?.closest(".terminal-pane");if(!A)return;function O(){A?.removeAttribute("data-compose-open"),A?.style.removeProperty("--compose-drawer-panel-height")}if(!f){O();return}const L=y.current;A.setAttribute("data-compose-open","true");function U(){const ae=L?.getBoundingClientRect().height??0;ae>0&&A?.style.setProperty("--compose-drawer-panel-height",`${Math.ceil(ae)}px`)}U();const I=[window.setTimeout(U,0),window.setTimeout(U,180),window.setTimeout(U,260)],te=window.requestAnimationFrame?.(U)??null,ee=typeof ResizeObserver=="function"&&L?new ResizeObserver(U):null;return ee&&L&&ee.observe(L),()=>{for(const ae of I)window.clearTimeout(ae);te!==null&&window.cancelAnimationFrame?.(te),ee?.disconnect(),O()}},[f]),v.useEffect(()=>{f&&b.current?.focus()},[f]);function w(A){QM(e,A)}function S(A){JM(e,A)}function E(){aN(p.current),w(!1),VS()}function T(A="send"){if(!(r||!g)){if(t(g,A),S(""),Sm()){b.current?.blur(),VS();return}window.setTimeout(()=>b.current?.focus(),g1+20)}}return m.jsxs("div",{ref:p,className:"compose-drawer","data-open":f?"true":"false",children:[m.jsxs("button",{type:"button",className:"compose-drawer-handle","aria-label":"Open compose drawer","aria-hidden":f?"true":void 0,tabIndex:f?-1:0,title:"Compose long input — type without per-keystroke latency, send with Cmd/Ctrl+Enter",onClick:()=>w(!0),children:[m.jsx("span",{"aria-hidden":"true",children:"▴"}),m.jsx("span",{children:"compose"}),g?m.jsx("span",{className:"compose-drawer-handle-dot","aria-label":"draft saved"}):null]}),m.jsxs("div",{ref:y,className:"compose-drawer-panel","aria-hidden":f?void 0:"true",children:[m.jsxs("button",{type:"button",className:"compose-drawer-header","aria-label":"Collapse compose drawer",tabIndex:f?0:-1,title:"Click to collapse — Esc also closes when focus is in the textarea",onClick:E,children:[m.jsx("span",{"aria-hidden":"true",children:"▾"}),m.jsx("span",{className:"compose-drawer-title",children:"compose"}),m.jsx("span",{className:"compose-drawer-hint","aria-hidden":"true",children:s?"Cmd/Ctrl+Enter to send · Cmd/Ctrl+Shift+Enter to queue · Esc to close":"Cmd/Ctrl+Enter to send · Enter for newline · Esc to close"}),m.jsx("span",{className:"compose-drawer-close","aria-hidden":"true",children:"×"})]}),m.jsx("textarea",{ref:b,className:"compose-drawer-input","aria-label":"Compose input",tabIndex:f?0:-1,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",value:g,onChange:A=>S(A.target.value),onKeyDown:A=>{if(A.key==="Enter"&&(A.metaKey||A.ctrlKey)){if(A.preventDefault(),A.shiftKey){s&&T("queue");return}T("send");return}A.key==="Escape"&&(A.preventDefault(),E())},placeholder:s?"Type a longer command here, then send or queue it.":"Type a longer command here, then Cmd/Ctrl+Enter to send."}),m.jsxs("div",{className:"compose-drawer-actions",children:[m.jsx("button",{type:"button",className:"compose-drawer-clear",tabIndex:f?0:-1,onClick:()=>{S(""),b.current?.focus()},disabled:!g,children:"Clear"}),s?m.jsx("button",{type:"button",className:"compose-drawer-queue",tabIndex:f?0:-1,title:"Queue in Codex with Cmd/Ctrl+Shift+Enter",onClick:()=>T("queue"),disabled:r||!g,children:"Queue"}):null,m.jsx("button",{type:"button",className:"compose-drawer-send",tabIndex:f?0:-1,onClick:()=>T("send"),disabled:r||!g,children:"Send"})]})]})]})}function aN(e){const t=document.activeElement;t instanceof HTMLElement&&(!e||e.contains(t))&&t.blur()}function Sm(){return navigator.maxTouchPoints>0?!0:typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}function VS(){if(!Sm())return;const e=()=>{window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0,pl()};e(),window.requestAnimationFrame?.(e),window.setTimeout(e,120),window.setTimeout(e,320)}function lN(e){_l!==null&&(window.clearTimeout(_l),_l=null),Ku.add(e),document.documentElement.setAttribute(Th,"true"),pl()}function oN(e){if(Ku.delete(e),Ku.size>0||_l!==null){pl();return}_l=window.setTimeout(()=>{if(_l=null,Ku.size>0){pl();return}document.documentElement.removeAttribute(Th),pl()},sN),pl()}function pl(){window.dispatchEvent(new Event(nc))}function cN(e,t){e.attachCustomKeyEventHandler(c=>{if(uN(c)){const h=XS(e);return h?(c.preventDefault(),c.stopPropagation(),GS(h),!1):!0}return hN(c)?(c.preventDefault(),c.stopPropagation(),dN(e,t),!1):!0});const s=e.element;if(!s)return{dispose(){e.attachCustomKeyEventHandler(()=>!0)}};const r=c=>{const h=XS(e);if(h){if(c.clipboardData){c.clipboardData.setData("text/plain",h),c.preventDefault();return}c.preventDefault(),GS(h)}},o=c=>{const h=c.clipboardData?.getData("text/plain");if(!h)return;const f=Rg(h);c.preventDefault(),c.stopImmediatePropagation(),_1(e,f,t)};return s.addEventListener("copy",r,!0),s.addEventListener("paste",o,!0),{dispose(){s.removeEventListener("copy",r,!0),s.removeEventListener("paste",o,!0),e.attachCustomKeyEventHandler(()=>!0)}}}function uN(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 hN(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 dN(e,t){if(navigator.clipboard?.readText)try{const s=await navigator.clipboard.readText();if(!s)return;_1(e,Rg(s),t)}catch{}}function _1(e,t,s){if(t){if(s){s(t);return}e.paste(t)}}function XS(e){return e.hasSelection()?e.getSelection():""}async function GS(e){if(navigator.clipboard?.writeText)try{await navigator.clipboard.writeText(e);return}catch{}fN(e)}function fN(e){const t=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("textarea");s.value=e,s.setAttribute("readonly","true"),s.style.position="fixed",s.style.left="-9999px",s.style.top="0",s.style.opacity="0",document.body.appendChild(s),s.focus({preventScroll:!0}),s.select();try{typeof document.execCommand=="function"&&document.execCommand("copy")}finally{s.remove(),t?.focus({preventScroll:!0})}}const pN=[4,10,11,12];function mN(e,t){const s=[e.parser.registerCsiHandler({final:"c"},r=>ZS(r)),e.parser.registerCsiHandler({prefix:">",final:"c"},r=>ZS(r)),e.parser.registerCsiHandler({final:"n"},r=>gN(r)),e.parser.registerCsiHandler({prefix:"?",final:"n"},r=>_N(r)),e.parser.registerCsiHandler({final:"t"},r=>vN(r)),e.parser.registerDcsHandler({intermediates:"$",final:"q"},()=>!0),...pN.map(r=>e.parser.registerOscHandler(r,o=>bN(o)))];return{dispose(){for(const r of s)r.dispose()}}}function ZS(e){return Dh(e)===0}function gN(e){const t=Dh(e);return t===5||t===6}function _N(e){return Dh(e)===6}function vN(e){const t=Dh(e);return t===14||t===16||t===18}function bN(e){return e.split(";").some(t=>t==="?")}function Dh(e){const t=e[0];return typeof t=="number"?t:0}const xa=new Map,yN=2*1024*1024,SN=1500,wN=25e3;function CN(e,t){let s=xa.get(e);s||(s=kN(e),xa.set(e,s),Rh(s)),s.listeners.add(t);const r=c=>AN(s,c),o=()=>{s.listeners.delete(t)};return{status:s.status,snapshot:s.snapshot,output:s.output.slice(),history:s.history,send:r,detach:o}}function Ho(e){const t=xa.get(e);t&&(LN(t),xa.delete(e))}function xN(e,t={}){const s=xa.get(e);if(!s)return!1;s.exited=!1,s.reconnectEnabled=!0,t.preserveCachedOutputOnNextSnapshot&&(s.preserveCachedOutputOnNextSnapshot=!0),s.reconnectTimer!==null&&(window.clearTimeout(s.reconnectTimer),s.reconnectTimer=null),_c(s);const r=s.socket;return s.socket=null,pa(s,"reconnecting"),r&&(r.readyState===WebSocket.OPEN||r.readyState===WebSocket.CONNECTING)&&r.close(),Rh(s),!0}function EN(){for(const e of xa.values()){if(e.status!=="unauthorized"||e.exited)continue;e.reconnectTimer!==null&&(window.clearTimeout(e.reconnectTimer),e.reconnectTimer=null),_c(e);const t=e.socket;e.socket=null,e.reconnectEnabled=!0,pa(e,"reconnecting"),t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),Rh(e)}}function rp(){for(const e of Array.from(xa.keys()))Ho(e)}function kN(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,preserveCachedOutputOnNextSnapshot:!1}}function Rh(e){if(!e.reconnectEnabled)return;pa(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){pa(e,"connected");for(const s of e.pendingOut)t.send(JSON.stringify(s));e.pendingOut.length=0,e.isAlive=!0,TN(e)}}),t.addEventListener("message",s=>{if(e.socket!==t)return;const r=typeof s.data=="string"?s.data:"";if(!r)return;let o=null;try{o=JSON.parse(r)}catch{return}if(!o||typeof o.type!="string")return;if(o.type==="pong"){e.isAlive=!0;return}const c=RN(e,o);v1(e,{type:"message",message:c})}),t.addEventListener("close",s=>{if(e.socket===t){if(e.socket=null,_c(e),s.code===1008){e.reconnectEnabled=!1,pa(e,DN(s.reason)?"unauthorized":"closed");return}if(e.exited||!e.reconnectEnabled){pa(e,"closed");return}pa(e,"reconnecting"),e.reconnectTimer=window.setTimeout(()=>{e.reconnectTimer=null,Rh(e)},SN)}}),t.addEventListener("error",()=>{})}function TN(e){_c(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)}))}},wN)}function _c(e){e.heartbeat!==null&&(window.clearInterval(e.heartbeat),e.heartbeat=null)}function DN(e){return e.trim().toLowerCase()==="unauthorized"}function RN(e,t){return t.type==="snapshot"?(e.snapshot=t.terminal,e.history=t.history??null,e.exited=t.terminal.status==="exited",e.preserveCachedOutputOnNextSnapshot?(e.preserveCachedOutputOnNextSnapshot=!1,MN(e,t.output),ap(e),{...t,output:e.output.slice(),history:e.history}):(e.output=t.output.slice(),e.outputBytes=e.output.reduce((s,r)=>s+r.length,0),ap(e),t)):t.type==="output"?(e.output.push(t.data),e.outputBytes+=t.data.length,ap(e),t):t.type==="terminal_updated"?(e.snapshot=t.terminal,t.terminal.status==="exited"&&(e.exited=!0),t):(t.type==="exit"&&(e.exited=!0,e.snapshot&&e.snapshot.id===t.terminalId&&(e.snapshot={...e.snapshot,status:"exited",exitCode:t.exitCode})),t)}function MN(e,t){const s=NN(e.output,t);if(s===0)return;const r=t.slice(s);for(const o of r)e.output.push(o),e.outputBytes+=o.length}function NN(e,t){const s=Math.min(e.length,t.length);for(let r=s;r>0;r-=1){let o=!0;for(let c=0;c<r;c+=1)if(e[e.length-r+c]!==t[c]){o=!1;break}if(o)return r}return 0}function ap(e){for(;e.outputBytes>yN&&e.output.length>1;){const t=e.output.shift();e.outputBytes-=t.length}}function pa(e,t){e.status!==t&&(e.status=t,v1(e,{type:"status",status:t}))}function v1(e,t){for(const s of Array.from(e.listeners))s(t)}function AN(e,t){const s=e.socket;return s&&s.readyState===WebSocket.OPEN?(s.send(JSON.stringify(t)),!0):(t.type==="input"&&e.pendingOut.push(t),!1)}function LN(e){e.reconnectEnabled=!1,e.reconnectTimer!==null&&(window.clearTimeout(e.reconnectTimer),e.reconnectTimer=null),_c(e);const t=e.socket;e.socket=null,t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),e.listeners.clear()}const BN=[0,50,150,350],ON=120,zN=2,jN=[300,1200,2500],HN=1e3,PN=1e5,wm="\x1B[?1049l\x1B[?1047l\x1B[?47l",UN=new Set(["47","1047","1049"]),IN=400,KN=3,FN=3,WN=32,qN=1.42,$N=2,YN=24,VN=240,XN=60,GN=420,ZN=6,QN=2,QS=[500,1500,3e3,5e3,8e3],JS=15e3,JN=Si.lazy(()=>gg(()=>import("./TranscriptMarkdownBody-J4Bk7GDH.js"),__vite__mapDeps([2,1])));function e0({terminal:e,serverApi:t,active:s,visible:r=!0,canClose:o,refreshCwdOnEnter:c=!1,tabId:h,onSelect:f,onClose:g,onExit:p,onSnapshot:y,onAuthClose:b}){const w=v.useSyncExternalStore(rw,Np,()=>_a),S=v.useSyncExternalStore(aw,Ap,()=>bl),E=v.useSyncExternalStore(lw,Bp,()=>!0),T=v.useSyncExternalStore(qm,Or,()=>vl),A=v.useSyncExternalStore(ug,()=>hg("history.toggle"),()=>"Alt+H"),O=v.useRef(null),L=v.useRef(null),U=v.useRef(null),I=v.useRef(null),te=v.useRef({onExit:p,onSnapshot:y}),ee=v.useRef(t.createWebSocketUrl),ae=v.useRef(b),ue=v.useRef(null),be=v.useRef(null),we=v.useRef(!1),ne=v.useRef(new Map),ie=v.useRef([]),Y=v.useRef([]),K=v.useRef([]),re=v.useRef(0),B=v.useRef(!1),$=v.useRef(null),D=v.useRef(0),X=v.useRef(null),_e=v.useRef(null),R=v.useRef(!1),H=v.useRef(!1),Q=v.useRef(!1),de=v.useRef(!1),ke=v.useRef(null),xe=v.useRef(null),Re=v.useRef(!1),Xe=v.useRef(!1),ge=v.useRef(!1),G=v.useRef(!1),ce=v.useRef(!1),Ce=v.useRef(!1),ye=v.useRef(!1),De=v.useRef(s),Be=v.useRef(r),Ke=v.useRef(c),le=v.useRef(w),Ee=v.useRef(S),Le=v.useRef(!1),Oe=v.useRef(null),He=v.useRef(null),_t=v.useRef(!1),Ye=v.useRef(null),[,rt]=v.useState("connecting"),[Oi,$i]=v.useState(!1),[Ci,ri]=v.useState(null),[zi,sn]=v.useState(!1),[F,qe]=v.useState(null),[dt,vt]=v.useState(!1),[pi,St]=v.useState(!1),[mn,Ln]=v.useState(!1),[Jt,ai]=v.useState(null),[Zi,gt]=v.useState(!1),Tt=!!Jt||Fu(e.currentCommand),[Dt,mi]=v.useState(!1);v.useLayoutEffect(()=>{De.current=s},[s]),v.useLayoutEffect(()=>{Be.current=r},[r]),v.useLayoutEffect(()=>{Ke.current=c},[c]),v.useLayoutEffect(()=>{le.current=w},[w]),v.useLayoutEffect(()=>{Ee.current=S},[S]),v.useLayoutEffect(()=>{Le.current=Zi},[Zi]),v.useLayoutEffect(()=>{Oe.current=Jt},[Jt]),v.useLayoutEffect(()=>{_t.current=Tt},[Tt]),v.useEffect(()=>{r&&s&&e.status==="running"&&(At(),bn())},[s,r,e.status]),v.useEffect(()=>{te.current={onExit:p,onSnapshot:y}},[p,y]),v.useEffect(()=>{ee.current=t.createWebSocketUrl,ae.current=b},[t,b]),v.useEffect(()=>{let M=!1,J=null,je=0;const Fe=p3(e.currentCommand),Ie=Fu(e.currentCommand);function Ge(){J!==null&&(window.clearTimeout(J),J=null)}function Ft(wt){if(M)return;let Bt;if(wt){if(!Ie)return;Bt=JS}else if(je<QS.length){if(!Fe)return;Bt=QS[je++]}else{if(!Ie)return;Bt=JS}J=window.setTimeout(()=>{J=null,li()},Bt)}async function li(){try{const wt=await t.getTerminalTranscriptSource(e.id);if(M)return;ai(Bt=>Bt&&wt.source&&Bt.provider===wt.source.provider&&Bt.sessionId===wt.source.sessionId?Bt:wt.source),Ft(!!wt.source)}catch(wt){if(M)return;lp(wt)&&ai(null),Ft(!1)}}return ai(null),e.status!=="running"?()=>{M=!0,Ge()}:(li(),()=>{M=!0,Ge()})},[t,e.currentCommand,e.id,e.status]),v.useEffect(()=>{const M=Jt?`${e.id}:${Jt.provider}:${Jt.sessionId}`:null,J=He.current;J!==null&&M!==null&&J!==M&&Le.current&&gt(!1),He.current=M},[e.id,Jt?.provider,Jt?.sessionId]),v.useEffect(()=>{function M(J){!De.current||!Be.current||!Oe.current||J.isComposing||J.key==="Process"||i3(J.target)||ow(J)?.id!=="history.toggle"||(J.preventDefault(),J.stopPropagation(),gt(Fe=>!Fe))}return window.addEventListener("keydown",M,!0),()=>window.removeEventListener("keydown",M,!0)},[]),v.useEffect(()=>{const M=L.current;M&&(M.options.disableStdin=e.status==="exited"),e.status==="exited"&&rt("closed")},[e.status]),v.useEffect(()=>{const M=L.current;M&&(M.options.fontSize=w,Kf(w,Ee.current).then(()=>{le.current===w&&At()}))},[w]),v.useEffect(()=>{const M=L.current;M&&(M.options.fontFamily=Mp(S),Kf(le.current,S).then(()=>{Ee.current===S&&At()}))},[S]),v.useEffect(()=>{const M=L.current;M&&(M.options.theme=t0(T))},[T]),v.useEffect(()=>{const M=O.current;if(!M)return;let J=!1,je=null,Fe=null,Ie=null,Ge=null,Ft=null,li=null,wt=null;ue.current=null,ce.current=!1,Ce.current=!1,de.current=!1,es(),Ut();const Bt=le.current,Ui=Ee.current,Wt=new BM({cursorBlink:!0,convertEol:!1,disableStdin:e.status==="exited",fontFamily:Mp(Ui),fontSize:Bt,fontWeight:400,fontWeightBold:700,macOptionClickForcesSelection:!0,scrollback:PN,theme:{...t0(Or())}}),Sn=new ET;return Wt.loadAddon(Sn),Ge=mN(Wt),L.current=Wt,U.current=Sn,Kf(Bt,Ui).then(()=>{if(J)return;Wt.open(M),ce.current=!0,je=cN(Wt,Na),Be.current&&De.current&&e.status==="running"&&bn(),At(),Ft=C3(M,Wt,()=>le.current*1.2,Vi,x=>{It(x)},Ts,it),li=y3(M,Wt,Vi,x=>{It(x)},Ts,it);const jn=new OM;Fe=Wt.onData(x=>{if(ye.current){const j=WM(x);if(j){yn(!1),rs(j);return}}const k=jn.accept(x);k&&rs(k)}),Ie=Wt.onScroll(x=>{if(Xe.current||G.current||ge.current){ot();return}_n(),cs(Wt)&&On({scrollToBottom:!0}),Vi(),x<=3&&It()}),wt=new ResizeObserver(()=>{Hi()}),wt.observe(M),Ce.current&&(Lt(),Ce.current=!1,At()),fs()}),()=>{J=!0,ce.current=!1,Ce.current=!1,es(),be.current=null,we.current=!1,ts(),Ur(),ge.current=!1,Ft?.(),li?.(),wt?.disconnect(),je?.dispose(),Fe?.dispose(),Ie?.dispose(),Ge?.dispose(),Wt.dispose(),L.current=null,U.current=null}},[e.id]),v.useEffect(()=>{const M=ee.current(e.id),J=CN(M,gi);return I.current=J.send,rt(J.status),J.status==="connected"&&At(),J.snapshot&&(te.current.onSnapshot(J.snapshot,{notifyCompletion:!1}),L.current&&(At(),ei(J.output,J.history),At())),()=>{J.detach(),I.current=null}},[e.id,e.status]);function gi(M){if(M.type==="status"){rt(M.status),M.status==="unauthorized"&&ae.current?.({source:"terminal-ws-1008",terminalId:e.id}),M.status==="connected"&&At();return}Qi(M.message)}function Ut(M=[],J=null){Y.current=[],K.current=Au(M),re.current=0,B.current=!1,$.current=null,ge.current=!1,D.current+=1,X.current=J,_e.current=null,R.current=!1,H.current=!1,Q.current=!1,Ce.current=!1,Ye.current=null,ke.current=null,Re.current=!1,$i(!1),ri(null),sn(!1),qe(null),vt(!1),St(!1)}function ei(M=[],J=null){Ut(M,J),ji()}function ji(){if(!L.current||!ce.current){Ce.current=!0;return}Ce.current=!1,Lt()}async function Lt(){const M=L.current;if(!M)return;const J=Lu(M,Re.current),je=J?K.current.length:re.current;await xi(M,{liveOutputLimit:je,scrollToBottom:J}),L.current===M&&ot()}function xi(M,J={}){return new Promise(je=>{ge.current=!0,B.current=!1;const Fe=D.current+1;D.current=Fe;const Ie=Math.max(0,Math.min(J.liveOutputLimit??K.current.length,K.current.length)),Ge=J.historyPages??Y.current,Ft=()=>{if(L.current!==M||D.current!==Fe){je(!1);return}try{re.current=Ie,J.scrollToBottom&&ss(M)}finally{ge.current=!1;const wt=Ir();wt?On(wt):J.applyDeferredSnapshot!==!1&&Yt(),je(!0)}},li=()=>{if(L.current!==M||D.current!==Fe){je(!1);return}M.clear();const wt=Au([...Ge,...K.current.slice(0,Ie)]);if(wt.length===0){Ft();return}for(let Bt=0;Bt<wt.length;Bt+=1){const Ui=wt[Bt];Bt===wt.length-1?M.write(Ui,Ft):M.write(Ui)}};if(M.buffer.active.type==="alternate"){M.write(wm,li);return}li()})}async function It(M=0){const J=L.current;if(Q.current||!J)return;if(Kr(J)){ot();return}const je=X.current;Q.current=!0,$i(!0);const Fe=J.buffer.active.viewportY;try{let Ie=!!(je&&!je.hasMore);if(!Ie)try{const Ge=await t.getTerminalHistory(e.id,{beforeLine:je?.startLine??0,limit:HN}),Ft={startLine:Ge.startLine,endLine:Ge.endLine,hasMore:Ge.hasMore};if(Ge.output.length>0){await rn(J,Ge.output,Fe,M)&&(X.current=Ft);return}X.current=Ft,Ie=!Ge.hasMore}catch(Ge){Ie=lp(Ge)}if(Ie){if(Kr(J)){ot();return}await Yi(J,Fe,M)}}catch{}finally{Q.current=!1,$i(!1)}}async function Yi(M,J,je){if(!(R.current||H.current))try{const Fe=_e.current,Ie=await t.getTerminalTranscriptHistory(e.id,{...Fe?{cursor:Fe}:{},limit:IN}),Ge=Ie.output.map(S1);if(!Ie.source)return;if(Ge.length===0){ai(Ie.source),_e.current=Ie.cursor,H.current=!Ie.hasMore||!Ie.cursor;return}await rn(M,Ge,J,je)&&(ai(Ie.source),_e.current=Ie.cursor,H.current=!Ie.hasMore||!Ie.cursor)}catch(Fe){lp(Fe)&&(R.current=!0)}}async function rn(M,J,je,Fe){if(Kr(M))return ot(),!1;const Ie=[...J,...Y.current],Ge=v3(J);return!await xi(M,{liveOutputLimit:re.current,scrollToBottom:!1,historyPages:Ie,applyDeferredSnapshot:!1})||L.current!==M?!1:(Y.current=Ie,Fr(M,Math.max(0,je+Ge+Math.min(0,Fe))),Re.current=!cs(M),Vi(),!0)}v.useEffect(()=>{const M=window.visualViewport;function J(){document.visibilityState==="visible"&&At()}function je(){At()}function Fe(){Hi()}function Ie(){Ei()}return document.addEventListener("visibilitychange",J),window.addEventListener("pageshow",je),window.addEventListener("resize",Fe),window.addEventListener(nc,Ie),M?.addEventListener("resize",Fe),M?.addEventListener("scroll",Fe),()=>{document.removeEventListener("visibilitychange",J),window.removeEventListener("pageshow",je),window.removeEventListener("resize",Fe),window.removeEventListener(nc,Ie),M?.removeEventListener("resize",Fe),M?.removeEventListener("scroll",Fe)}},[e.id]);function an(){const M=ee.current(e.id);de.current=!0,Ye.current=null,rt("reconnecting"),At(),xN(M,{preserveCachedOutputOnNextSnapshot:!0})}function Qi(M){if(M.type==="snapshot"&&M.terminal.id===e.id){te.current.onSnapshot(M.terminal,{notifyCompletion:!1});const je=L.current;if(!je)return;At();const Fe=de.current;if(de.current=!1,Fe){X.current=M.history??X.current,ot(),At();return}if(Qs(je,M.terminal)){vn(M.output,M.history??null),ot(),At();return}ei(M.output,M.history??null),At();return}if(M.type==="terminal_updated"&&M.terminal.id===e.id){te.current.onSnapshot(M.terminal,{notifyCompletion:!0});return}if(M.type==="output"&&M.terminalId===e.id){const je=x1(M.data);if(!je)return;K.current.push(je),L.current&&ce.current?On({scrollToBottom:!0}):Ce.current=!0;return}const J=L.current;if(J){if(M.type==="exit"&&M.terminalId===e.id){te.current.onExit(M.exitCode),rt("closed");return}M.type==="error"&&J.writeln(`\r
33
33
  [nterminal] ${M.message}`)}}function gn(M=25){if(document.visibilityState==="hidden"||!Be.current||ne.current.has(M))return;const J=window.setTimeout(()=>{ne.current.delete(M),!Kt()&&$r()},M);ne.current.set(M,J)}function Hi(){Kt()||fs()}function Kt(){const M=ks();return M&&Bn(M)?(we.current=!0,!0):((!M||!M.composeOpen&&!M.keyboardVisible)&&(we.current=!1),!1)}function Ei(){if(!we.current)return;const M=ks();M&&(M.composeOpen||M.keyboardVisible)||(we.current=!1,fs())}function Bn(M){if(!M.mobileLike||!M.composeOpen&&!M.keyboardVisible)return!1;const J=be.current;return J?Jn(M.windowWidth,J.windowWidth)&&Jn(M.visualViewportWidth,J.visualViewportWidth)&&Jn(M.containerWidth,J.containerWidth):!1}function ks(){const M=O.current;if(!M||M.isConnected===!1)return null;const J=M.getBoundingClientRect(),je=Qn(window.innerWidth)??0,Fe=Qn(window.visualViewport?.width)??je,Ie=Qn(J.width)??Qn(M.clientWidth)??je;if(je<=0||Fe<=0||Ie<=0)return null;const Ge=Nl()>ON,Ft=document.documentElement.hasAttribute(Th),li=Da()||Ge;return{windowWidth:je,visualViewportWidth:Fe,containerWidth:Ie,composeOpen:Ft,keyboardVisible:Ge,mobileLike:li}}function Nl(){const M=Qn(window.visualViewport?.height),J=Qn(window.innerHeight);if(M===null||J===null)return 0;const je=typeof window.visualViewport?.offsetTop=="number"?window.visualViewport.offsetTop:0;return Math.max(0,Math.round(J-M-je))}function Da(){return navigator.maxTouchPoints>0?!0:typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}function Qn(M){return typeof M=="number"&&Number.isFinite(M)&&M>0?M:null}function Jn(M,J){return Math.abs(M-J)<=zN}function fs(){for(const M of BN)gn(M)}function At(){ue.current=null,fs()}function es(){for(const M of ne.current.values())window.clearTimeout(M);ne.current.clear()}function ts(){for(const M of ie.current)window.clearTimeout(M);ie.current=[]}function Vi(){if(ot(),!ke.current){sn(!1);return}sn(!0),Ur(),xe.current=window.setTimeout(()=>{xe.current=null,sn(!1)},1200)}function ot(){const M=L.current,J=M?b3(M):null;if(ke.current=J,ri(J),St(!!(M&&J)),vt(!!(M&&J&&!cs(M))),J||!M||!Ra()){qe(null);return}qe({alternate:M.buffer.active.type==="alternate"})}function Ra(){const M=X.current;return Y.current.length>0||!!M?.hasMore}function Ur(){xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)}function _n(){const M=L.current;M&&(Re.current=!cs(M),ot())}function is(M){$.current=op($.current,M)}function Al(M){const J=$.current;return $.current=null,op(J,M)}function Ir(){const M=$.current;return $.current=null,M}function On(M={}){const J=L.current;if(!J||!ce.current){Ce.current=!0;return}if(ge.current){is(M);return}if(B.current){is(M);return}const je=Al(M);if(!je.force&&!Lu(J,Re.current)){ot();return}B.current=!0;const Fe=D.current,Ie=()=>{if(L.current!==J||D.current!==Fe){B.current=!1;return}if(!je.force&&!Lu(J,Re.current)){B.current=!1,ot();return}const Ge=re.current,Ft=K.current[Ge];if(Ft===void 0){B.current=!1,je.scrollToBottom&&ss(J),ot();const li=Ir();li?On(op(je,li)):Yt();return}J.write(Ft,()=>{if(L.current!==J||D.current!==Fe){B.current=!1;return}re.current=Ge+1,Ie()})};Ie()}function Kr(M){return!cs(M)&&(ns()||B.current||ge.current)}function Qs(M,J){return(_t.current||Fu(J?.currentCommand))&&!cs(M)}function ns(){return re.current<K.current.length}function vn(M,J){Ye.current={output:M,history:J,appendFromLiveOutputIndex:re.current}}function Yt(){const M=L.current,J=Ye.current;if(!M||!J||!cs(M)||ns()||B.current||ge.current)return;const je=Au(J.output),Fe=Au(K.current.slice(J.appendFromLiveOutputIndex));Ye.current=null,ei(_3(je,Fe),J.history),At()}function Ts(){G.current=!0}function it(){_n(),G.current=!1;const M=L.current;M&&cs(M)&&On({scrollToBottom:!0})}function ss(M){ps(()=>a0(M))&&(Re.current=!1)}function Fr(M,J){ps(()=>(M.scrollToLine(J),!0))}function ps(M){Xe.current=!0;try{return M()}finally{Xe.current=!1}}function Ma(){const M=L.current;if(!M)return;const J=()=>{a0(M),Re.current=!1,ot(),On({force:!0,scrollToBottom:!0}),bn()};if(M.buffer.active.type==="alternate"){M.write(wm,J);return}J()}function Pi(M){const J=L.current,je=O.current;if(!J||!je)return;const Fe=je.getBoundingClientRect();if(Fe.height<=0)return;const Ie=Math.max(0,Math.min(1,(M-Fe.top)/Fe.height)),Ge=Math.round(J.buffer.active.baseY*Ie);Ts();try{J.scrollToLine(Ge)}finally{it()}Re.current=!cs(J),ot(),Vi(),Ge<=3&&It()}function Wr(M){M.preventDefault(),M.stopPropagation(),M.currentTarget.setPointerCapture?.(M.pointerId),Pi(M.clientY)}function qr(M){(M.buttons&1)!==0&&(M.preventDefault(),M.stopPropagation(),Pi(M.clientY))}function $r(){const M=L.current,J=U.current;if(!(!M||!J)&&!(document.visibilityState==="hidden"||!Be.current||O.current?.isConnected===!1))try{const je=Lu(M,Re.current),Fe=ks();J.fit(),Fe&&(be.current=Fe),je&&ss(M),M.refresh(0,Math.max(0,M.rows-1)),ot();const Ie={cols:M.cols,rows:M.rows},Ge=ue.current;if(Ge&&Ge.cols===Ie.cols&&Ge.rows===Ie.rows)return;zn({type:"resize",terminalId:e.id,cols:Ie.cols,rows:Ie.rows})&&(ue.current=Ie)}catch{}}function zn(M){const J=I.current;return J?J(M):!1}function rs(M){On({force:!0,scrollToBottom:!0}),zn({type:"input",terminalId:e.id,data:M})&&d3(M)&&Ll()}function Na(M){const J=YS(M,{bracketedPasteMode:L.current?.modes.bracketedPasteMode===!0,stripTrailingLineBreaks:!0});J&&rs(J)}function ms(M,J){const je=YS(M,{bracketedPasteMode:L.current?.modes.bracketedPasteMode===!0,stripTrailingLineBreaks:!1});je&&rs(je),window.setTimeout(()=>rs(iN(J)),g1)}function Ll(){!Ke.current||!De.current||(ts(),ie.current=jN.map(M=>{const J=window.setTimeout(()=>{ie.current=ie.current.filter(je=>je!==J),Ke.current&&De.current&&zn({type:"refresh_cwd",terminalId:e.id})},M);return J}))}function bn(){Le.current||L.current?.focus()}const Ds=v.useCallback(()=>{gt(!1)},[]);function Js(){Ln(M=>{const J=!M;return ye.current=J,J}),bn()}function yn(M){ye.current=M,Ln(M)}function er(M){ye.current&&yn(!1),rs(FM(M)),bn()}return m.jsxs("section",{className:"terminal-pane","data-active":s,onMouseDown:()=>{s||f()},children:[m.jsx(n3,{terminal:e,canClose:o,tabId:h,transcriptSource:Jt,transcriptShortcutLabel:A,onOpenTranscript:()=>gt(!0),onReload:an,onClose:g}),m.jsx("div",{className:"xterm-container",ref:O}),Oi?m.jsx("div",{className:"terminal-history-loader",role:"status","aria-label":"Loading older terminal output",children:m.jsx("span",{"aria-hidden":"true"})}):null,E&&Ci?m.jsxs("div",{className:"terminal-scroll-progress","data-active":zi,"aria-hidden":"true",children:[Ci.current,"/",Ci.total]}):E&&F?m.jsxs("div",{className:"terminal-scroll-progress","data-active":!1,"data-pending":"true","data-buffer":F.alternate?"alternate":"normal","aria-hidden":"true",children:[F.alternate?"alt ":"","0/?"]}):null,dt?m.jsx("button",{type:"button",className:"terminal-scroll-bottom-button","aria-label":"Scroll terminal to bottom",title:"Scroll to bottom",onPointerDown:M=>M.stopPropagation(),onMouseDown:M=>M.stopPropagation(),onClick:M=>{M.stopPropagation(),Ma()},children:"↓"}):null,pi?m.jsx("button",{type:"button",className:"terminal-scroll-handle","aria-label":"Drag terminal scroll handle",title:"Drag to scroll",onPointerDown:Wr,onPointerMove:qr,children:m.jsx("span",{"aria-hidden":"true"})}):null,s&&e.status==="running"?Dt?m.jsx(IM,{ctrlActive:mn,onCtrl:Js,onStandaloneKey:er,onPreserveFocus:bn,onHide:()=>mi(!1)}):m.jsx("button",{type:"button",className:"mobile-terminal-key-toggle","aria-label":"Show terminal control keys",title:"Show Ctrl / Esc / Tab / arrows",onMouseDown:M=>{M.stopPropagation(),bn()},onPointerDown:M=>{M.stopPropagation(),bn()},onClick:()=>mi(!0),children:"⌨"}):null,m.jsx(rN,{terminalId:e.id,onSubmit:ms,queueAvailable:Jt?.provider==="codex"||y1(e.currentCommand),disabled:e.status!=="running"}),Zi&&Jt?m.jsx(s3,{terminalId:e.id,serverApi:t,source:Jt,fontSize:w,onClose:Ds}):null]})}function t0(e){return dE(e)}function e3(e,t,s){const r=t3(e,t),o=i0(r*Math.max(1,s),XN,GN);return{limit:i0(Math.ceil(o/$N),YN,VN),maxLines:o}}function t3(e,t){const s=e?.clientHeight??0;if(s<=0)return WN;const r=Math.max(10,t*qN);return Math.max(1,Math.floor(s/r))}function i0(e,t,s){return Math.max(t,Math.min(s,Math.floor(e)))}function i3(e){return e instanceof HTMLElement?!!e.closest(".security-panel:not(.transcript-dialog)"):!1}function n3({terminal:e,canClose:t,tabId:s,transcriptSource:r,transcriptShortcutLabel:o,onOpenTranscript:c,onReload:h,onClose:f}){const g=F0({id:`pane-${e.id}`,disabled:!s,...s?{data:{kind:"pane",sourceTabId:s,terminalId:e.id}}:{}}),p={cursor:s?"grab":"default",opacity:g.isDragging?.5:void 0};return m.jsxs("header",{ref:g.setNodeRef,className:"terminal-pane-header",style:p,"data-dragging":g.isDragging,...g.attributes,...g.listeners,children:[m.jsx("span",{className:"terminal-pane-dot","aria-hidden":"true"}),m.jsx("span",{className:"terminal-pane-cwd",title:e.cwd,children:e.cwd}),m.jsx("span",{className:"terminal-pane-spacer"}),r?m.jsxs("button",{type:"button",className:"terminal-pane-transcript","data-provider":r.provider,title:`View ${oh(r.provider)} transcript history`,"aria-label":`View ${oh(r.provider)} transcript history`,onPointerDown:y=>y.stopPropagation(),onMouseDown:y=>y.stopPropagation(),onClick:y=>{y.stopPropagation(),c()},children:[m.jsx("span",{children:"View history"}),m.jsx("kbd",{children:o})]}):null,m.jsx("span",{className:`terminal-pane-state terminal-pane-state-${e.status}`,children:e.status}),e.status==="running"?m.jsx("button",{type:"button",className:"terminal-pane-reload","aria-label":`Reload pane ${e.title}`,title:"Reload pane output",onPointerDown:y=>y.stopPropagation(),onMouseDown:y=>y.stopPropagation(),onClick:y=>{y.stopPropagation(),h()},children:"↻"}):null,t?m.jsx("button",{type:"button",className:"terminal-pane-close","aria-label":`Close pane ${e.title}`,title:"Close pane",onPointerDown:y=>y.stopPropagation(),onMouseDown:y=>y.stopPropagation(),onClick:y=>{y.stopPropagation(),f()},children:"x"}):null]})}const s3=Si.memo(function({terminalId:t,serverApi:s,source:r,fontSize:o,onClose:c}){const h=v.useRef(null),f=v.useRef(0),g=v.useRef(!1),p=v.useRef(!1),y=v.useRef(null),b=v.useRef(""),[w,S]=v.useState([]),[E,T]=v.useState(!1),[A,O]=v.useState(""),[L,U]=v.useState(-1),[I,te]=v.useState(null),[ee,ae]=v.useState(!1),[ue,be]=v.useState(!0),[we,ne]=v.useState(!1),[ie,Y]=v.useState(null);v.useEffect(()=>{function ge(G){G.key==="Escape"&&(G.preventDefault(),G.stopPropagation(),c())}return document.addEventListener("keydown",ge,!0),()=>document.removeEventListener("keydown",ge,!0)},[c]),v.useEffect(()=>{f.current+=1;const ge=f.current;return g.current=!1,p.current=!0,y.current=null,S([]),te(null),ae(!1),Y(null),de(null,"initial",ge),()=>{f.current===ge&&(f.current+=1)}},[s,E,r.provider,r.sessionId,t]),v.useLayoutEffect(()=>{const ge=h.current;if(!ge)return;if(p.current){if(ue||w.length===0)return;p.current=!1;const ce=()=>{ge.scrollTop=ge.scrollHeight};ce(),window.requestAnimationFrame?.(ce);return}const G=y.current;G!==null&&(y.current=null,ge.scrollTop+=ge.scrollHeight-G)},[w,ue,E]);const K=oh(r.provider),re=r0(w,E),B=l3(re),$=u3(B,A),D=$.length,X=D>0?L>=0&&L<D?L:0:-1,_e=X>=0?$[X]?.entryIndex??null:null,R=X>=0?$[X]??null:null,H=re?re.split(`
34
34
  `).length-1:0,Q=A.trim()?D>0?`${X+1}/${D} ${D===1?"match":"matches"} · ${H} ${H===1?"line":"lines"}`:`0 matches · ${H} ${H===1?"line":"lines"}`:H>0?`${H} lines`:"0 lines";v.useEffect(()=>{const ge=A.trim().toLowerCase();U(G=>!ge||D===0?-1:b.current!==ge?0:G>=0&&G<D?G:0),b.current=ge},[A,D]);async function de(ge,G,ce=f.current){if(!g.current){g.current=!0,G==="initial"?be(!0):(ne(!0),y.current=h.current?.scrollHeight??null),Y(null);try{await ke(ge,G,ce)}catch(Ce){if(f.current!==ce)return;Y(Ce instanceof Error?Ce.message:"Failed to load transcript history.")}finally{f.current===ce&&(g.current=!1,be(!1),ne(!1))}}}async function ke(ge,G,ce){let Ce=ge,ye=0,De=[];const Be=G==="initial"&&r.provider!=="claude"?QN:ZN;for(;f.current===ce;){const Ke=await s.getTerminalTranscriptHistory(t,{...Ce?{cursor:Ce}:{},...e3(h.current,o,G==="initial"?KN:FN),includeTools:E});if(f.current!==ce)return;const le=s0(Ke.output,r.provider,{includeTools:E}),Ee=xe(Ke,G,De,le);if(le&&(De=[le,...De],Ee))return;if(!Ke.hasMore||!Ke.cursor||ye>=Be){De.length>0&&S(Le=>G==="older"?[...De,...Le]:De);return}Ce=Ke.cursor,ye+=1}}function xe(ge,G,ce,Ce=s0(ge.output,r.provider,{includeTools:E})){if(te(ge.cursor),ae(!!(ge.hasMore&&ge.cursor)),!Ce)return!1;const ye=[Ce,...ce];return r0(ye,E)?(S(De=>G==="older"?[...ye,...De]:ye),!0):!1}function Re(){const ge=h.current;!ge||ge.scrollTop>72||!ee||!I||g.current||de(I,"older")}function Xe(ge){D!==0&&U(G=>{const ce=X>=0?X:ge>0?-1:0;return((G>=0&&G<D?G:ce)+ge+D)%D})}return m.jsx("div",{className:"security-overlay transcript-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"transcript-dialog-title",onPointerDown:ge=>ge.stopPropagation(),onMouseDown:ge=>ge.stopPropagation(),onClick:ge=>{ge.stopPropagation(),c()},children:m.jsxs("div",{className:"security-panel transcript-dialog",onPointerDown:ge=>ge.stopPropagation(),onMouseDown:ge=>ge.stopPropagation(),onClick:ge=>ge.stopPropagation(),children:[m.jsxs("header",{className:"security-panel-header",children:[m.jsxs("div",{className:"transcript-dialog-title",children:[m.jsxs("h2",{id:"transcript-dialog-title",children:[K," JSONL"]}),m.jsx("span",{title:r.sessionId,children:r.sessionId})]}),m.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:c,children:"×"})]}),m.jsxs("div",{className:"transcript-dialog-controls",children:[m.jsxs("label",{className:"auth-checkbox transcript-tool-toggle",children:[m.jsx("input",{type:"checkbox",checked:E,onChange:ge=>T(ge.currentTarget.checked)}),"Show tool output"]}),m.jsxs("label",{className:"transcript-search",children:[m.jsx("span",{children:"Search"}),m.jsx("input",{type:"search",value:A,"aria-label":"Search JSONL transcript",placeholder:"Find in history",onChange:ge=>O(ge.currentTarget.value),onKeyDown:ge=>{ge.key==="Enter"&&(ge.preventDefault(),Xe(ge.shiftKey?-1:1))}})]}),m.jsxs("div",{className:"transcript-search-actions","aria-label":"Search result navigation",children:[m.jsx("button",{type:"button",onClick:()=>Xe(-1),disabled:D===0,children:"Prev"}),m.jsx("button",{type:"button",onClick:()=>Xe(1),disabled:D===0,children:"Next"})]}),m.jsx("span",{className:"transcript-result-count",children:Q})]}),m.jsxs("div",{ref:h,className:"transcript-dialog-scroll","aria-label":"JSONL transcript output",onScroll:Re,children:[we?m.jsx("div",{className:"transcript-dialog-status",children:"Loading older entries..."}):null,!ue&&ee?m.jsx("div",{className:"transcript-dialog-hint",children:"Scroll up for older entries"}):null,re?m.jsx(r3,{entries:B,searchQuery:A,activeEntryIndex:_e,activeSearchMatch:R,fontSize:o}):null,ue?m.jsx("div",{className:"transcript-dialog-status",children:"Loading transcript..."}):null,!ue&&!re&&!ie?ee&&I?m.jsxs("div",{className:"transcript-dialog-status",children:[E?"The latest entries are hidden record types.":"The latest entries contain only hidden tool output."," ",m.jsx("button",{type:"button",onClick:()=>{de(I,"older")},disabled:we,children:"Search earlier entries"})]}):m.jsx("div",{className:"transcript-dialog-status",children:"No transcript entries found."}):null,ie?m.jsx("div",{className:"transcript-dialog-error",children:ie}):null]})]})})});function r3({entries:e,searchQuery:t,activeEntryIndex:s,activeSearchMatch:r,fontSize:o}){const c=v.useRef(new Map);return v.useEffect(()=>{if(s===null)return;const h=c.current.get(s);if(!h||typeof h.scrollIntoView!="function")return;const f=h.querySelectorAll(".transcript-search-hit");((r?.entryIndex===s?f[r.matchIndexInEntry]:null)??h).scrollIntoView({block:"center",inline:"nearest"})},[s,r,t]),m.jsx("div",{className:"transcript-output transcript-formatted-output",style:{fontSize:o},children:e.map((h,f)=>m.jsxs("section",{ref:g=>{g?c.current.set(f,g):c.current.delete(f)},className:`transcript-entry transcript-entry-${h.kind}${s===f?" transcript-entry-search-active":""}`,children:[h.header?m.jsx("div",{className:"transcript-entry-header",children:b1(h.header,t)}):null,h.body?m.jsx("div",{className:"transcript-entry-body",children:h.kind==="tool"?m.jsx(n0,{text:h.body,searchQuery:t}):m.jsx(Si.Suspense,{fallback:m.jsx(n0,{text:h.body,searchQuery:t}),children:m.jsx(JN,{text:h.body,searchQuery:t})})}):null]},`${h.header??"plain"}-${f}`))})}function n0({text:e,searchQuery:t}){const s=e.endsWith(`
35
35
  `)?e.slice(0,-1).split(`
@@ -52,4 +52,4 @@ ${o.body}`:o.body,h=a3(c,t);for(let f=0;f<h;f+=1)s.push({entryIndex:r,matchIndex
52
52
 
53
53
  `).trimEnd()}function g3(e){const t=e.replace(/^\[[^\]]+\]\s+/,"");return/^Tool (?:call(?::|$)|output$)/.test(t)?"tool":/^(?:User|Codex|Claude|System)$/.test(t)?"message":null}function C1(e){return/^\[tool (?:call(?::|])|output\])/.test(e.trim())}function _3(e,t){if(t.length===0)return e;let s=0;const r=Math.min(e.length,t.length);for(let o=r;o>0;o-=1){let c=!0;for(let h=0;h<o;h+=1)if(e[e.length-o+h]!==t[h]){c=!1;break}if(c){s=o;break}}return[...e,...t.slice(s)]}function v3(e){let t=0;for(const s of e){if(!s)continue;const r=s.match(/\r\n|\r|\n/g);t+=r?.length??1}return Math.max(1,t)}function Au(e){const t=[];for(const s of e){const r=x1(s);r&&t.push(r)}return t}function x1(e){return e.replace(/\x1b\[\?([0-9;:]*)([hl])/g,(t,s,r)=>{const o=s.split(";").filter(Boolean).filter(c=>!UN.has(c.split(":")[0]??""));return o.length>0?`\x1B[?${o.join(";")}${r}`:""})}function op(e,t={}){const s={};return(e?.force||t.force)&&(s.force=!0),(e?.scrollToBottom||t.scrollToBottom)&&(s.scrollToBottom=!0),s}function b3(e){const t=e.buffer.active,s=t.baseY+e.rows;return s<=e.rows?null:{current:Math.max(1,Math.min(s,t.viewportY+1)),total:s}}function cs(e){return e.buffer.active.viewportY>=Math.max(0,e.buffer.active.baseY-1)}function Lu(e,t){return!t||cs(e)}function a0(e){return cs(e)?!1:(e.scrollToLine(Math.max(0,e.buffer.active.baseY)),!0)}function y3(e,t,s,r,o,c){const h=f=>{const g=w3(f);g!==0&&(f.cancelable&&f.preventDefault(),f.stopPropagation(),S3(t,g,s,r,o,c))};return e.addEventListener("wheel",h,{capture:!0,passive:!1}),()=>{e.removeEventListener("wheel",h,{capture:!0})}}function S3(e,t,s,r,o,c){const h=()=>{o();try{e.scrollLines(t)}finally{c()}s(),t<0&&e.buffer.active.viewportY<=3&&r(t)};if(e.buffer.active.type==="alternate"){e.write(wm,h);return}h()}function w3(e){const s=e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?e.deltaY/24:e.deltaMode===WheelEvent.DOM_DELTA_PAGE?e.deltaY*24:e.deltaY;if(s===0)return 0;const r=s<0?Math.floor(s):Math.ceil(s);return Math.max(-30,Math.min(30,r))}function C3(e,t,s,r,o,c,h){let f=null,g=0;const p={passive:!1};function y(S){f=cp(S),g=0}function b(S){const E=cp(S);if(E===null){f=null,g=0;return}if(f===null){f=E;return}const T=E.clientY-f.clientY;if(f=E,S.cancelable&&S.preventDefault(),T===0)return;if(x3(t)&&E3(t,E,-T)){g=0;return}g-=T/s();const A=g<0?Math.ceil(g):Math.floor(g);if(A!==0){g-=A,c();try{t.scrollLines(A)}finally{h()}r(),A<0&&t.buffer.active.viewportY<=3&&o(A)}}function w(S){if(S.touches.length>0){f=cp(S);return}f=null,g=0}return e.addEventListener("touchstart",y,p),e.addEventListener("touchmove",b,p),e.addEventListener("touchend",w),e.addEventListener("touchcancel",w),()=>{e.removeEventListener("touchstart",y,p),e.removeEventListener("touchmove",b,p),e.removeEventListener("touchend",w),e.removeEventListener("touchcancel",w)}}function cp(e){if(e.touches.length!==1)return null;const t=e.touches[0];return t?{clientX:t.clientX,clientY:t.clientY}:null}function x3(e){return e.buffer.active.type==="alternate"||e.modes.mouseTrackingMode!=="none"}function E3(e,t,s){const r=e.element;return r?(r.dispatchEvent(k3(t,s)),!0):!1}function k3(e,t){const s=typeof WheelEvent=="function"?WheelEvent.DOM_DELTA_PIXEL:0,r={bubbles:!0,cancelable:!0,clientX:e.clientX,clientY:e.clientY,deltaX:0,deltaY:t,deltaMode:s};if(typeof WheelEvent=="function")return new WheelEvent("wheel",r);const o=new Event("wheel",r);return Object.defineProperties(o,{clientX:{value:e.clientX},clientY:{value:e.clientY},deltaX:{value:0},deltaY:{value:t},deltaMode:{value:0}}),o}function Cm({node:e,terminals:t,editors:s,api:r,activeTerminalId:o,visible:c=!0,refreshCwdOnEnter:h=!1,tabId:f,dropZoneActive:g=!1,draggingTerminalId:p=null,mobileFocusLeafKey:y=null,path:b=[],totalPanes:w,onSelect:S,onClose:E,onResize:T,onExit:A,onSnapshot:O,onCloseEditor:L,onAuthClose:U}){const I=w??xm(e);if(b.length===0&&y){const ue=Em(e),be=ue.some(we=>we.key===y)?y:ue[0]?.key;if(ue.length>1&&be)return m.jsx("div",{className:"mobile-focused-split",children:ue.map(we=>{const ne=we.key===be;if(we.type==="editor"){const Y=s[we.editorId];return m.jsx("div",{className:"mobile-focused-pane","data-active":ne,"aria-hidden":!ne,children:Y?m.jsx(qy,{api:r,editor:Y,canClose:I>1,onClose:()=>L(we.editorId)}):m.jsx("div",{className:"missing-pane",children:"Editor unavailable"})},we.key)}const ie=t[we.terminalId];return ie?m.jsx("div",{className:"mobile-focused-pane","data-active":ne,"aria-hidden":!ne,children:m.jsx(e0,{terminal:ie,serverApi:r,active:ne,visible:c&&ne,canClose:I>1,refreshCwdOnEnter:h&&ne,tabId:f,onSelect:()=>S(we.terminalId),onClose:()=>E(we.terminalId),onExit:Y=>A(we.terminalId,Y),onSnapshot:O,...U?{onAuthClose:U}:{}})},we.key):m.jsx("div",{className:"mobile-focused-pane","data-active":ne,"aria-hidden":!ne,children:m.jsx("div",{className:"missing-pane",children:"Terminal unavailable"})},we.key)})})}if(e.type==="pane"){const ue=t[e.terminalId];if(!ue)return m.jsx("div",{className:"missing-pane",children:"Terminal unavailable"});const be=m.jsx(e0,{terminal:ue,serverApi:r,active:e.terminalId===o,visible:c,canClose:I>1,refreshCwdOnEnter:h&&e.terminalId===o,tabId:f,onSelect:()=>S(e.terminalId),onClose:()=>E(e.terminalId),onExit:ne=>A(e.terminalId,ne),onSnapshot:O,...U?{onAuthClose:U}:{}});return g&&p!==e.terminalId?m.jsxs("div",{className:"pane-drop-host",children:[be,m.jsx(Bu,{terminalId:e.terminalId,side:"top"}),m.jsx(Bu,{terminalId:e.terminalId,side:"right"}),m.jsx(Bu,{terminalId:e.terminalId,side:"bottom"}),m.jsx(Bu,{terminalId:e.terminalId,side:"left"})]}):be}if(e.type==="editor"){const ue=s[e.editorId];return ue?m.jsx(qy,{api:r,editor:ue,canClose:I>1,onClose:()=>L(e.editorId)}):m.jsx("div",{className:"missing-pane",children:"Editor unavailable"})}const te=Math.max(.1,Math.min(.9,e.ratio)),ee=1-te,ae=e.direction==="vertical"?{gridTemplateColumns:`minmax(0, ${te}fr) 1px minmax(0, ${ee}fr)`}:{gridTemplateRows:`minmax(0, ${te}fr) 1px minmax(0, ${ee}fr)`};return m.jsxs("div",{className:"split-pane","data-direction":e.direction,style:ae,children:[m.jsx("div",{className:"split-cell",children:m.jsx(Cm,{node:e.first,terminals:t,editors:s,api:r,activeTerminalId:o,visible:c,refreshCwdOnEnter:h,tabId:f,dropZoneActive:g,draggingTerminalId:p,mobileFocusLeafKey:y,path:[...b,0],totalPanes:I,onSelect:S,onClose:E,onResize:T,onExit:A,onSnapshot:O,onCloseEditor:L,...U?{onAuthClose:U}:{}})}),m.jsx(T3,{direction:e.direction,path:b,onResize:T}),m.jsx("div",{className:"split-cell",children:m.jsx(Cm,{node:e.second,terminals:t,editors:s,api:r,activeTerminalId:o,visible:c,refreshCwdOnEnter:h,tabId:f,dropZoneActive:g,draggingTerminalId:p,mobileFocusLeafKey:y,path:[...b,1],totalPanes:I,onSelect:S,onClose:E,onResize:T,onExit:A,onSnapshot:O,onCloseEditor:L,...U?{onAuthClose:U}:{}})})]})}function Bu({terminalId:e,side:t}){const{setNodeRef:s,isOver:r}=Qm({id:`pane-${e}-${t}`,data:{kind:"pane-zone",terminalId:e,side:t}});return m.jsx("div",{ref:s,className:`pane-drop-zone pane-drop-zone--${t}`,"data-over":r,"aria-hidden":"true"})}function T3({direction:e,path:t,onResize:s}){function r(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 h=c.parentElement;if(!h)return;const f=h.getBoundingClientRect();function g(y){const b=e==="vertical"?(y.clientX-f.left)/f.width:(y.clientY-f.top)/f.height;s(t,Math.min(.9,Math.max(.1,b)))}function p(){window.removeEventListener("pointermove",g),window.removeEventListener("pointerup",p),c.classList.remove("is-dragging"),document.body.style.cursor=""}window.addEventListener("pointermove",g),window.addEventListener("pointerup",p)}return m.jsx("div",{"aria-label":"Resize panes","aria-orientation":e==="vertical"?"vertical":"horizontal",className:"split-divider","data-direction":e,onPointerDown:r,role:"separator",children:m.jsx("span",{className:"split-divider-handle","aria-hidden":"true"})})}function xm(e){return e.type==="pane"||e.type==="editor"?1:xm(e.first)+xm(e.second)}function Em(e){return e.type==="pane"?[{key:D3(e.terminalId),type:"terminal",terminalId:e.terminalId}]:e.type==="editor"?[{key:R3(e.editorId),type:"editor",editorId:e.editorId}]:[...Em(e.first),...Em(e.second)]}function D3(e){return`terminal:${e}`}function R3(e){return`editor:${e}`}const Mh="workspace-default",M3="NTerminal";function N3(){return{workspaces:[],activeWorkspaceId:null,terminals:{}}}function A3(e,t){switch(t.type){case"workspace.hydrated":return km(t.terminals,t.savedTabs,t.savedWorkspaces,t.savedActiveWorkspaceId);case"workspace.created":return L3(e,{id:t.workspaceId,title:t.title,defaultCwd:t.defaultCwd??null});case"workspace.closed":return j3(e,t.workspaceId);case"workspace.selected":return E1(e,t.workspaceId);case"workspace.renamed":return B3(e,t.workspaceId,t.title);case"workspace.defaultCwdChanged":return O3(e,t.workspaceId,t.defaultCwd);case"workspace.reordered":return z3(e,t.sourceWorkspaceId,t.targetWorkspaceId,t.placement);case"terminal.created":return k1(e,t.terminal);case"terminal.split":return H3(e,t.terminal,t.direction);case"terminal.updated":return X3(e,t.terminal);case"terminal.exited":return G3(e,t.terminalId,t.exitCode);case"terminal.closed":return R1(e,t.terminalId);case"terminal.detached":return Z3(e,t.terminalId,t.workspaceId);case"editor.split":return P3(e,t.editorId,t.title,t.direction);case"editor.closed":return Q3(e,t.editorId);case"pane.selected":return Y3(e,t.terminalId);case"pane.resized":return V3(e,t.path,t.ratio);case"tab.selected":return I3(e,t.tabId);case"tab.renamed":return $3(e,t.tabId,t.title);case"tab.reordered":return Mg(e,t.sourceTabId,t.targetIndex);case"tab.dropped_into_pane":return K3(e,t.sourceTabId,t.sourceTerminalId,t.targetTerminalId,t.side);case"terminal.extracted_to_tab":return T1(e,t.sourceTabId,t.sourceTerminalId,t.targetIndex);case"tab.moved_to_workspace":return D1(e,t.sourceTabId,t.targetWorkspaceId,t.targetIndex);case"terminal.extracted_to_workspace":return F3(e,t.sourceTabId,t.sourceTerminalId,t.targetWorkspaceId,t.targetIndex);case"activePane.closed":return U3(e);default:return e}}function L3(e,t){if(e.workspaces.some(r=>r.id===t.id))return E1(e,t.id);const s={id:t.id,title:t.title,defaultCwd:ds(t.defaultCwd),detachedTerminalIds:[],tabs:[],activeTabId:null};return{...e,workspaces:[...e.workspaces,s],activeWorkspaceId:s.id}}function E1(e,t){return e.workspaces.some(s=>s.id===t)?{...e,activeWorkspaceId:t}:e}function B3(e,t,s){const r=s.trim();if(!r)return e;let o=!1;const c=e.workspaces.map(h=>h.id!==t||h.title===r?h:(o=!0,{...h,title:r}));return o?{...e,workspaces:c}:e}function O3(e,t,s){const r=ds(s);let o=!1;const c=e.workspaces.map(h=>h.id!==t||h.defaultCwd===r?h:(o=!0,{...h,defaultCwd:r}));return o?{...e,workspaces:c}:e}function z3(e,t,s,r){if(t===s)return e;const o=e.workspaces.findIndex(b=>b.id===t),c=e.workspaces.findIndex(b=>b.id===s);if(o<0||c<0)return e;const h=e.workspaces.slice(),[f]=h.splice(o,1);if(!f)return e;const g=h.findIndex(b=>b.id===s);if(g<0)return e;const p=r==="before"?g:g+1,y=h.slice();return y.splice(p,0,f),q3(e.workspaces,y)?e:{...e,workspaces:y}}function j3(e,t){if(e.workspaces.length<=1||!e.workspaces.some(f=>f.id===t))return e;const s=e.workspaces.find(f=>f.id===t),r=new Set(s?ch(s):[]),o={...e.terminals};for(const f of r)delete o[f];const c=e.workspaces.filter(f=>f.id!==t),h=e.activeWorkspaceId===t?c[0]?.id??null:e.activeWorkspaceId;return{workspaces:c,activeWorkspaceId:h,terminals:o}}function k1(e,t){const s=N1(e),r=ka(s)??Ah(),o=z1(t);return{...s,activeWorkspaceId:r.id,terminals:{...s.terminals,[t.id]:t},workspaces:s.workspaces.map(c=>c.id===r.id?{...c,defaultCwd:c.defaultCwd??ds(t.cwd),detachedTerminalIds:c.detachedTerminalIds.filter(h=>h!==t.id),tabs:[...c.tabs,o],activeTabId:o.id}:O1(c,t.id))}}function H3(e,t,s){const r=ka(e),o=r?Nh(r):void 0;if(!r||!o)return k1(e,t);const c=o.activeTerminalId,h=ac(o.root,c,{type:"split",direction:s,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(f=>f.id===r.id?{...f,defaultCwd:f.defaultCwd??ds(t.cwd),detachedTerminalIds:f.detachedTerminalIds.filter(g=>g!==t.id),tabs:f.tabs.map(g=>g.id===o.id?{...g,root:h,activeTerminalId:t.id}:g)}:O1(f,t.id))}}function P3(e,t,s,r){const o=ka(e),c=o?Nh(o):void 0;if(!o||!c)return e;const h=c.activeTerminalId,f=ac(c.root,h,{type:"split",direction:r,ratio:.5,first:{type:"pane",terminalId:h},second:{type:"editor",editorId:t,title:s}});return{...e,workspaces:e.workspaces.map(g=>g.id===o.id?{...g,tabs:g.tabs.map(p=>p.id===c.id?{...p,root:f,activeTerminalId:h}:p)}:g)}}function U3(e){const t=ka(e),s=t?Nh(t):void 0;return s?R1(e,s.activeTerminalId):e}function I3(e,t){const s=ka(e);return!s||!s.tabs.some(r=>r.id===t)?e:{...e,workspaces:e.workspaces.map(r=>r.id===s.id?{...r,activeTabId:t}:r)}}function Mg(e,t,s){const r=e.workspaces.map(o=>{const c=o.tabs.findIndex(y=>y.id===t);if(c<0)return o;const h=o.tabs.slice(),[f]=h.splice(c,1);if(!f)return o;const g=Math.max(0,Math.min(h.length,s)),p=h.slice();return p.splice(g,0,f),W3(o.tabs,p)?o:{...o,tabs:p}});return r.every((o,c)=>o===e.workspaces[c])?e:{...e,workspaces:r}}function K3(e,t,s,r,o){if(s===r||!e.terminals[s]||!e.terminals[r])return e;let c=e.workspaces.map(g=>{const p=g.tabs.findIndex(E=>E.id===t);if(p<0)return g;const y=g.tabs[p];if(!y)return g;const b=wl(y.root,s);if(!b){const E=g.tabs.filter((T,A)=>A!==p);return{...g,tabs:E}}const w={...y,root:b,activeTerminalId:Li(b)[0]??y.activeTerminalId},S=g.tabs.slice();return S[p]=w,{...g,tabs:S}});const h=o==="left"||o==="right"?"vertical":"horizontal",f=o==="left"||o==="top";return c=c.map(g=>{const p=g.tabs.findIndex(T=>Li(T.root).includes(r));if(p<0)return g;const y=g.tabs[p];if(!y)return g;const b={type:"pane",terminalId:s},w={type:"split",direction:h,ratio:.5,first:f?b:{type:"pane",terminalId:r},second:f?{type:"pane",terminalId:r}:b},S=ac(y.root,r,w),E=g.tabs.slice();return E[p]={...y,root:S,activeTerminalId:s},{...g,tabs:E,activeTabId:y.id}}),N1({...e,workspaces:c})}function T1(e,t,s,r){let o=-1,c=-1;for(let A=0;A<e.workspaces.length;A+=1){const O=e.workspaces[A].tabs.findIndex(L=>L.id===t);if(O>=0){o=A,c=O;break}}if(o<0)return e;const h=e.workspaces[o],f=h.tabs[c],g=Li(f.root);if(!g.includes(s))return e;if(g.length===1)return Mg(e,t,r);const p=wl(f.root,s);if(!p)return e;const y={...f,root:p,activeTerminalId:Li(p)[0]??f.activeTerminalId},b=e.terminals[s],w={id:`tab-${Date.now().toString(36)}-${s.slice(0,8)}`,title:b?.title??"",activeTerminalId:s,root:{type:"pane",terminalId:s}},S=h.tabs.slice();S[c]=y;const E=Math.max(0,Math.min(S.length,r));S.splice(E,0,w);const T=e.workspaces.slice();return T[o]={...h,tabs:S,activeTabId:w.id},{...e,workspaces:T}}function D1(e,t,s,r=Number.MAX_SAFE_INTEGER){const o=A1(e.workspaces,t),c=e.workspaces.find(p=>p.id===s);if(!o||!c)return e;if(o.workspace.id===s)return r===Number.MAX_SAFE_INTEGER?e:Mg(e,t,r);const h=Li(o.tab.root),f=h.map(p=>e.terminals[p]).find(Boolean),g=e.workspaces.map(p=>{if(p.id===o.workspace.id)return Ta({...p,tabs:p.tabs.filter(y=>y.id!==t)});if(p.id===s){const y=p.tabs.slice(),b=Math.max(0,Math.min(y.length,r));return y.splice(b,0,o.tab),{...p,defaultCwd:p.defaultCwd??ds(f?.cwd),detachedTerminalIds:p.detachedTerminalIds.filter(w=>!h.includes(w)),tabs:y,activeTabId:o.tab.id}}return p});return{...e,workspaces:g,activeWorkspaceId:s}}function F3(e,t,s,r,o=Number.MAX_SAFE_INTEGER){const c=e.workspaces.find(S=>S.id===r),h=A1(e.workspaces,t);if(!c||!h||!e.terminals[s]||!Li(h.tab.root).includes(s))return e;if(h.workspace.id===r)return T1(e,t,s,o);if(Li(h.tab.root).length===1)return D1(e,t,r,o);const g=wl(h.tab.root,s);if(!g)return e;const p={...h.tab,root:g,activeTerminalId:Li(g)[0]??h.tab.activeTerminalId},y=e.terminals[s],b={id:`tab-${Date.now().toString(36)}-${s.slice(0,8)}`,title:y.title??s,activeTerminalId:s,root:{type:"pane",terminalId:s}},w=e.workspaces.map(S=>{if(S.id===h.workspace.id)return Ta({...S,tabs:S.tabs.map(E=>E.id===t?p:E)});if(S.id===r){const E=S.tabs.slice(),T=Math.max(0,Math.min(E.length,o));return E.splice(T,0,b),{...S,defaultCwd:S.defaultCwd??ds(y.cwd),detachedTerminalIds:S.detachedTerminalIds.filter(A=>A!==s),tabs:E,activeTabId:b.id}}return S});return{...e,workspaces:w,activeWorkspaceId:r}}function W3(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]?.id!==t[s]?.id)return!1;return!0}function q3(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]?.id!==t[s]?.id)return!1;return!0}function $3(e,t,s){const r=s.trim();if(!r)return e;let o=!1;const c=e.workspaces.map(h=>{let f=!1;const g=h.tabs.map(p=>p.id!==t||p.title===r?p:(o=!0,f=!0,{...p,title:r}));return f?{...h,tabs:g}:h});return o?{...e,workspaces:c}:e}function Y3(e,t){const s=e.workspaces.find(o=>o.tabs.some(c=>Cl(c.root,t))),r=s?.tabs.find(o=>Cl(o.root,t));return!s||!r?e:{...e,activeWorkspaceId:s.id,workspaces:e.workspaces.map(o=>o.id===s.id?{...o,activeTabId:r.id,tabs:o.tabs.map(c=>c.id===r.id?{...c,activeTerminalId:t}:c)}:o)}}function V3(e,t,s){const r=ka(e),o=r?Nh(r):void 0;if(!r||!o)return e;const c=Am(o.root,t,P1(s));return c===o.root?e:{...e,workspaces:e.workspaces.map(h=>h.id===r.id?{...h,tabs:h.tabs.map(f=>f.id===o.id?{...f,root:c}:f)}:h)}}function km(e,t,s,r){const o=Object.fromEntries(e.map(b=>[b.id,b])),c=new Set(e.map(b=>b.id)),h=new Set,f=!!(s&&s.some(b=>j1(b))||t&&t.some(b=>H1(b)));let g=J3(t,s,c,h);g.length===0&&(g=[Ah()]);const p=typeof r=="string"&&g.some(b=>b.id===r)?r:g[0]?.id??null,y=p??g[0]?.id??Mh;for(const b of e)if(!h.has(b.id)){if(f)g=iA(g,y,b.id,b);else{const w=z1(b);g=sA(g,y,w,b)}h.add(b.id)}return{workspaces:g.map(b=>Ta(nA(b,o))),activeWorkspaceId:p,terminals:o}}function rc(e){return Li(e.root)}function Tm(e){return Lm(e.root)}function ch(e){return Ng([...e.tabs.flatMap(t=>Li(t.root)),...e.detachedTerminalIds])}function up(e){const t=e.workspaces.map(s=>{const r=s.tabs.flatMap(o=>{const c=Mm(o.root);return c?[{...o,root:c}]:[]});return Ta({...s,tabs:r})});return{activeWorkspaceId:t.some(s=>s.id===e.activeWorkspaceId)?e.activeWorkspaceId:t[0]?.id??null,workspaces:t}}function X3(e,t){return{...e,terminals:{...e.terminals,[t.id]:t},workspaces:e.workspaces.map(s=>({...s,tabs:s.tabs.map(r=>Cl(r.root,t.id)?{...r,title:r.title||t.title}:r)}))}}function G3(e,t,s){const r=e.terminals[t];return r?{...e,terminals:{...e.terminals,[t]:{...r,status:"exited",exitCode:s}}}:e}function R1(e,t){const s={...e.terminals};return delete s[t],M1(e,t,s)}function Z3(e,t,s){if(!e.terminals[t])return e;const r=(s&&e.workspaces.some(c=>c.id===s)?s:null)??eA(e,t)?.id??tA(e,t)?.id??e.activeWorkspaceId??e.workspaces[0]?.id??Mh,o=e.workspaces.find(c=>c.id===r);return!o||!B1(o,t)?e:M1(e,t,{...e.terminals},{detachToWorkspaceId:r})}function M1(e,t,s,r={}){let o=e.workspaces.map(h=>{const f=[];for(const g of h.tabs){const p=wl(g.root,t);if(!p)continue;const y=Li(p),b=y.includes(g.activeTerminalId)?g.activeTerminalId:y[0];b&&f.push({...g,root:p,activeTerminalId:b})}return Ta({...h,detachedTerminalIds:h.detachedTerminalIds.filter(g=>g!==t),tabs:f})});r.detachToWorkspaceId&&s[t]&&(o=o.map(h=>h.id===r.detachToWorkspaceId?L1(h,t,s[t]):h));const c=o.some(h=>h.id===e.activeWorkspaceId);return{workspaces:o,activeWorkspaceId:c?e.activeWorkspaceId:o[0]?.id??null,terminals:s}}function Q3(e,t){const s=e.workspaces.map(o=>{const c=[];for(const h of o.tabs){const f=Dm(h.root,t);if(!f)continue;const g=Li(f),p=g.includes(h.activeTerminalId)?h.activeTerminalId:g[0];p&&c.push({...h,root:f,activeTerminalId:p})}return Ta({...o,tabs:c})}),r=s.some(o=>o.id===e.activeWorkspaceId);return{...e,workspaces:s,activeWorkspaceId:r?e.activeWorkspaceId:s[0]?.id??null}}function J3(e,t,s,r){if(t&&t.length>0){const o=[];for(const c of t)j1(c)&&o.push(l0(c,s,r));if(o.length>0)return o}return[l0({...Ah(),tabs:e??[]},s,r)]}function l0(e,t,s){const r=[];for(const c of e.tabs){if(!H1(c))continue;const h=Rm(c.root,t);if(!h)continue;const f=Li(h);for(const p of f)s.add(p);const g=f.includes(c.activeTerminalId)?c.activeTerminalId:f[0];g&&r.push({...c,root:h,activeTerminalId:g})}const o=[];for(const c of e.detachedTerminalIds??[])!t.has(c)||s.has(c)||(s.add(c),o.push(c));return Ta({...e,defaultCwd:ds(e.defaultCwd),detachedTerminalIds:o,tabs:r})}function N1(e){return ka(e)?e:{...e,workspaces:[Ah()],activeWorkspaceId:Mh}}function ka(e){return e.workspaces.find(t=>t.id===e.activeWorkspaceId)??e.workspaces[0]}function Nh(e){return e.tabs.find(t=>t.id===e.activeTabId)??e.tabs[0]}function A1(e,t){for(const s of e){const r=s.tabs.findIndex(o=>o.id===t);if(r>=0)return{workspace:s,tab:s.tabs[r],tabIndex:r}}return null}function eA(e,t){return e.workspaces.find(s=>s.tabs.some(r=>Cl(r.root,t)))}function tA(e,t){return e.workspaces.find(s=>s.detachedTerminalIds.includes(t))}function iA(e,t,s,r){return e.map(o=>o.id===t?L1(o,s,r):o)}function L1(e,t,s){return B1(e,t)?{...e,defaultCwd:e.defaultCwd??ds(s?.cwd),detachedTerminalIds:Ng([...e.detachedTerminalIds.filter(r=>r!==t),t])}:e}function B1(e,t){return e.detachedTerminalIds.includes(t)||e.detachedTerminalIds.length<kl}function O1(e,t){return e.detachedTerminalIds.includes(t)?{...e,detachedTerminalIds:e.detachedTerminalIds.filter(s=>s!==t)}:e}function nA(e,t){if(e.defaultCwd)return e;const s=ch(e).find(o=>!!t[o]),r=s?ds(t[s]?.cwd):null;return r?{...e,defaultCwd:r}:e}function Ah(){return{id:Mh,title:M3,defaultCwd:null,detachedTerminalIds:[],tabs:[],activeTabId:null}}function Ta(e){const t=e.tabs.some(s=>s.id===e.activeTabId);return{...e,defaultCwd:ds(e.defaultCwd),detachedTerminalIds:Ng(e.detachedTerminalIds??[]),activeTabId:t?e.activeTabId:e.tabs[0]?.id??null}}function sA(e,t,s,r){const o=Li(s.root);return e.map(c=>c.id===t?{...c,defaultCwd:c.defaultCwd??ds(r?.cwd),detachedTerminalIds:c.detachedTerminalIds.filter(h=>!o.includes(h)),tabs:[...c.tabs,s],activeTabId:c.activeTabId??s.id}:c)}function z1(e){return{id:`tab-${e.id}`,title:e.title||e.id,root:{type:"pane",terminalId:e.id},activeTerminalId:e.id}}function ac(e,t,s){return e.type==="pane"?e.terminalId===t?s:e:e.type==="editor"?e:{...e,first:ac(e.first,t,s),second:ac(e.second,t,s)}}function wl(e,t){if(e.type==="pane")return e.terminalId===t?null:e;if(e.type==="editor")return e;const s=wl(e.first,t),r=wl(e.second,t);return s&&r?{...e,first:s,second:r}:s??r}function Dm(e,t){if(e.type==="editor")return e.editorId===t?null:e;if(e.type==="pane")return e;const s=Dm(e.first,t),r=Dm(e.second,t);return s&&r?{...e,first:s,second:r}:s??r}function Rm(e,t){if(e.type==="pane")return t.has(e.terminalId)?e:null;if(e.type==="editor")return null;const s=Rm(e.first,t),r=Rm(e.second,t);return s&&r?{...e,ratio:P1(e.ratio),first:s,second:r}:s??r}function Mm(e){if(e.type==="editor")return null;if(e.type==="pane")return e;const t=Mm(e.first),s=Mm(e.second);return t&&s?{...e,first:t,second:s}:t??s}function j1(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 H1(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&typeof t.title=="string"&&typeof t.activeTerminalId=="string"&&Nm(t.root)}function Nm(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")&&Nm(t.first)&&Nm(t.second):!1}function Am(e,t,s){if(e.type==="pane"||e.type==="editor")return e;if(t.length===0)return e.ratio===s?e:{...e,ratio:s};const[r,...o]=t;if(r===0){const c=Am(e.first,o,s);return c===e.first?e:{...e,first:c}}if(r===1){const c=Am(e.second,o,s);return c===e.second?e:{...e,second:c}}return e}function P1(e){return Number.isFinite(e)?Math.min(.9,Math.max(.1,e)):.5}function ds(e){if(typeof e!="string")return null;const t=e.trim();return t||null}function Ng(e){const t=new Set,s=[];for(const r of e)!r||t.has(r)||(t.add(r),s.push(r));return s}function Cl(e,t){return e.type==="pane"?e.terminalId===t:e.type==="editor"?!1:Cl(e.first,t)||Cl(e.second,t)}function Li(e){return e.type==="pane"?[e.terminalId]:e.type==="editor"?[]:[...Li(e.first),...Li(e.second)]}function Lm(e){return e.type==="pane"||e.type==="editor"?1:Lm(e.first)+Lm(e.second)}const Pr=new Map,lc=new Map,oc=new Map;function Rl(e){return e??"__local__"}function rA(e){return{agentId:e,state:N3(),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 Mt(e){const t=Rl(e);let s=Pr.get(t);return s||(s=rA(e),Pr.set(t,s)),s}function U1(e,t){const s=Rl(e);let r=lc.get(s);return r||(r=new Set,lc.set(s,r)),r.add(t),()=>{r.delete(t)}}function aA(e){const t=Rl(e),s=lc.get(t);if(s)for(const r of Array.from(s))r()}function Ml(e,t){Pr.set(Rl(e),t),aA(e)}const Bm=new Set;function lA(e){return Bm.add(e),()=>{Bm.delete(e)}}function Ro(e,t){const s=Mt(e),r=Rl(e);t.type==="workspace.hydrated"&&oc.delete(r);const o=A3(s.state,t);let c=s.unreadCompletions,h=null;if(t.type==="terminal.updated"){const p=s.state.terminals[t.terminal.id],y=p?.activity==="busy",b=t.terminal.activity==="busy",w=t.terminal.activity==="idle",S=mA(r);if(t.notifyCompletion===!0&&b&&S.add(t.terminal.id),t.notifyCompletion===!0&&y&&w&&S.has(t.terminal.id)){const E=oA(o,t.terminal.id);E&&(h={terminalId:t.terminal.id,tabId:E.tab.id,commandName:p?.currentCommand??null},(E.workspace.activeTabId!==E.tab.id||E.workspace.id!==o.activeWorkspaceId)&&(c.has(t.terminal.id)||(c=new Set(c),c.add(t.terminal.id))))}(w||t.terminal.status==="exited")&&S.delete(t.terminal.id)}if(t.type==="tab.selected"||t.type==="workspace.selected"){let p=null;if(t.type==="tab.selected")p=cA(o,t.tabId)?.tab??null;else{const b=o.workspaces.find(w=>w.id===t.workspaceId);p=b?.tabs.find(w=>w.id===b.activeTabId)??null}const y=p?Li(p.root):[];if(y.some(b=>c.has(b))){const b=new Set(c);for(const w of y)b.delete(w);c=b}}const f=o!==s.state,g=c!==s.unreadCompletions;if((f||g)&&Ml(e,{...s,state:o,unreadCompletions:c}),g&&Ag(),h)for(const p of Array.from(Bm))p({agentId:e,...h})}function oA(e,t){for(const s of e.workspaces)for(const r of s.tabs)if(Li(r.root).includes(t))return{workspace:s,tab:r};return null}function cA(e,t){for(const s of e.workspaces){const r=s.tabs.find(o=>o.id===t);if(r)return{workspace:s,tab:r}}return null}const Om=new Set;function uA(e){return Om.add(e),()=>{Om.delete(e)}}function hA(){let e=0;for(const t of Pr.values())e+=t.unreadCompletions.size;return e}function Ag(){for(const e of Array.from(Om))e()}function dA(e,t){const s=Mt(e);if(!s.unreadCompletions.has(t))return;const r=new Set(s.unreadCompletions);r.delete(t),Ml(e,{...s,unreadCompletions:r}),Ag()}function o0(e,t){const s=Mt(e);t!==s.state&&Ml(e,{...s,state:t})}function hp(e,t){const s=Mt(e),r=t(s.editors);r!==s.editors&&Ml(e,{...s,editors:r})}function kr(e,t,s){const r=Mt(e);r.loaded===t&&r.error===s||Ml(e,{...r,loaded:t,error:s})}function Mo(e,t,s){const r=Mt(e);r.layoutRevision===t&&r.lastPersistedLayoutJson===s||Ml(e,{...r,layoutRevision:t,lastPersistedLayoutJson:s})}function fA(e){const t=Mt(e);return t.mutable.editorIdCounter+=1,t.mutable.editorIdCounter}function pA(e){const t=Rl(e),s=Pr.get(t);s&&s.mutable.saveCoord.saveTimer!==null&&window.clearTimeout(s.mutable.saveCoord.saveTimer);const r=s?s.unreadCompletions.size>0:!1;Pr.delete(t),lc.delete(t),oc.delete(t),r&&Ag()}function dp(){for(const e of Pr.values()){const t=e.mutable.saveCoord.saveTimer;t!==null&&window.clearTimeout(t),e.unreadCompletions.size>0}Pr.clear(),lc.clear(),oc.clear()}function mA(e){let t=oc.get(e);return t||(t=new Set,oc.set(e,t)),t}function zm(e,t){let s=!1,r=!1,o=null,c=!1;for(const h of rc(e)){const f=t[h];if(f){if(f.status==="exited"){c=!0,s=!0;continue}f.activity==="busy"?(r=!0,s=!0,!o&&f.currentCommand&&(o=f.currentCommand)):f.activity==="idle"&&(s=!0)}}return s?c?{state:"exited",commandName:null}:r?{state:"busy",commandName:o}:{state:"idle",commandName:null}:null}function Lg(e){return e?e.state==="busy"?e.commandName?`running: ${e.commandName}`:"running":e.state==="exited"?"exited":"idle":""}function jm(e,t){const s=t[e.activeTerminalId];return e.title||s?.title||e.activeTerminalId}function gA(e,t,s,r){return r?.state==="busy"?r.commandName?`running: ${r.commandName}`:"running":r?.state==="exited"?"exited":t[e.activeTerminalId]?.cwd||`${s} pane${s===1?"":"s"}`}function _A({tabs:e,activeTabId:t,terminals:s,unreadCompletionTabIds:r,detachedTerminals:o,onSelectTab:c,onCreateTab:h,onToggleWorkspaces:f,onCloseTerminals:g,onReattachTerminal:p,onDeleteTerminal:y,onSplitVertical:b,onSplitHorizontal:w,onRenameTab:S,activePaneAvailable:E}){const[T,A]=v.useState(null),[O,L]=v.useState(!1),[U,I]=v.useState(null),te=v.useRef(null),ee=e.findIndex(K=>K.id===t),ae=ee>=0?e[ee]:e[0]??null,ue=ae?zm(ae,s):null,be=ae?Tm(ae):0,we=ae?jm(ae,s):"No tab";v.useEffect(()=>{te.current?.focus(),te.current?.select()},[T?.tabId]),v.useEffect(()=>{if(!O)return;const K=re=>{re.key==="Escape"&&L(!1)};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[O]),v.useEffect(()=>{O&&e.length===0&&L(!1)},[O,e.length]);function ne(K,re){A({tabId:K,title:re})}function ie(){if(!T)return;const K=T.title.trim();K&&S(T.tabId,K),A(null)}function Y(){return m.jsxs("div",{className:"terminal-pane-actions","aria-label":"Pane actions",children:[m.jsx("button",{type:"button",className:"pane-action-button","aria-label":"Split right",title:`Split right - ${Pk()}`,onClick:b,disabled:!E,children:m.jsx("span",{className:"split-icon split-icon-right","aria-hidden":"true"})}),m.jsx("button",{type:"button",className:"pane-action-button","aria-label":"Split down",title:`Split down - ${Uk()}`,onClick:w,disabled:!E,children:m.jsx("span",{className:"split-icon split-icon-down","aria-hidden":"true"})})]})}return m.jsxs(m.Fragment,{children:[m.jsxs("nav",{className:"terminal-tabs","aria-label":"Terminal tabs",children:[m.jsx("button",{type:"button",className:"mobile-menu-button","aria-label":"Toggle workspaces",title:"Workspaces",onClick:f,children:m.jsxs("span",{className:"hamburger-lines","aria-hidden":"true",children:[m.jsx("span",{}),m.jsx("span",{}),m.jsx("span",{})]})}),m.jsxs("button",{type:"button",className:"mobile-tab-current-button","aria-label":"Open tab switcher",title:we,onClick:()=>L(!0),disabled:e.length===0,children:[ue?m.jsx("span",{className:"terminal-tab-status-dot","data-activity":ue.state,"aria-hidden":"true",title:Lg(ue)}):null,m.jsx("span",{children:we}),m.jsxs("small",{children:[ee>=0?ee+1:0,"/",e.length||0,be>1?` / ${be}`:""]})]}),m.jsxs("div",{className:"terminal-tab-list",children:[e.map((K,re)=>{const B=rc(K),$=Tm(K),D=jm(K,s),X=K.id===t,_e=T?.tabId===K.id,R=zm(K,s),H=r?.has(K.id)??!1;return m.jsxs(Si.Fragment,{children:[m.jsx(c0,{index:re}),m.jsx(vA,{tab:K,active:X,editing:_e,title:D,paneCount:$,terminalIds:B,canClose:e.length>1,editValue:_e?T.title:null,editInputRef:_e?te:null,activity:R,unread:H,onSelect:()=>c(K.id),onBeginRename:()=>ne(K.id,D),onCloseAll:()=>g(B),onCommitRename:ie,onCancelRename:()=>A(null),onRenameChange:Q=>A({tabId:K.id,title:Q})})]},K.id)}),m.jsx(c0,{index:e.length}),m.jsx("button",{type:"button",className:"tab-add-button","aria-label":"New tab",title:"New tab",onClick:h,children:"+"}),(o?.length??0)>0?m.jsx("div",{className:"terminal-detached-pills","aria-label":"Detached terminals",children:(o??[]).map(K=>m.jsx(yA,{terminal:K,onReattach:()=>p?.(K.id),onDelete:()=>I(K)},K.id))}):null]}),m.jsx("button",{type:"button",className:"mobile-tab-add-button","aria-label":"Create new tab",title:"New tab",onClick:h,children:"+"}),E?Y():null]}),O?m.jsx(bA,{tabs:e,activeTabId:t,terminals:s,unreadCompletionTabIds:r,detachedTerminals:o,editingTab:T,editInputRef:te,onClose:()=>L(!1),onSelectTab:K=>{c(K),L(!1)},onCreateTab:()=>{h(),L(!1)},onBeginRename:ne,onCloseTerminals:K=>{g(K),L(!1)},onCommitRename:ie,onCancelRename:()=>A(null),onRenameChange:(K,re)=>A({tabId:K,title:re}),onReattachTerminal:K=>{p?.(K),L(!1)},onDeleteTerminal:K=>{I(K),L(!1)}}):null,U?m.jsx(SA,{terminal:U,onCancel:()=>I(null),onConfirm:()=>{y?.(U.id),I(null)}}):null]})}function vA({tab:e,active:t,editing:s,title:r,paneCount:o,canClose:c,editValue:h,editInputRef:f,activity:g,unread:p,onSelect:y,onBeginRename:b,onCloseAll:w,onCommitRename:S,onCancelRename:E,onRenameChange:T}){const{attributes:A,listeners:O,setNodeRef:L,transform:U,isDragging:I}=F0({id:`tab-${e.id}`,data:{kind:"tab",tabId:e.id,terminalId:e.activeTerminalId},disabled:s}),te={transform:_p.Translate.toString(U),opacity:I?.4:void 0,zIndex:I?2:void 0};return m.jsxs("div",{ref:L,className:"terminal-tab","data-active":t,"data-dragging":I,"data-unread":p?"true":void 0,style:te,...A,...O,children:[g?m.jsx("span",{className:"terminal-tab-status-dot","data-activity":g.state,"aria-hidden":"true",title:Lg(g)}):null,s&&f&&h!==null?m.jsxs("form",{className:"terminal-tab-editor",onSubmit:ee=>{ee.preventDefault(),S()},children:[m.jsx("input",{ref:f,"aria-label":`Rename ${r}`,value:h,onBlur:S,onChange:ee=>T(ee.target.value),onKeyDown:ee=>{if(ee.key==="Enter"){ee.preventDefault(),S();return}ee.key==="Escape"&&(ee.preventDefault(),E())}}),m.jsx("small",{children:o})]}):m.jsxs("button",{type:"button",className:"terminal-tab-select","aria-label":`Select ${r}`,title:r,onClick:y,onDoubleClick:ee=>{ee.preventDefault(),b()},children:[m.jsx("span",{children:r}),m.jsxs("small",{children:[o," pane",o===1?"":"s"]})]}),c&&!s?m.jsx("button",{type:"button",className:"icon-button","aria-label":`Close ${r}`,title:`Close ${r}`,onPointerDown:ee=>ee.stopPropagation(),onClick:ee=>{ee.stopPropagation(),w()},children:"x"}):null]})}function bA({tabs:e,activeTabId:t,terminals:s,unreadCompletionTabIds:r,detachedTerminals:o,editingTab:c,editInputRef:h,onClose:f,onSelectTab:g,onCreateTab:p,onBeginRename:y,onCloseTerminals:b,onCommitRename:w,onCancelRename:S,onRenameChange:E,onReattachTerminal:T,onDeleteTerminal:A}){const O=v.useRef(null);return v.useEffect(()=>{O.current?.scrollIntoView?.({block:"nearest"})},[t]),m.jsx("div",{className:"mobile-tab-sheet-backdrop",role:"dialog","aria-modal":"true","aria-labelledby":"mobile-tab-sheet-title",onClick:f,children:m.jsxs("section",{className:"mobile-tab-sheet",onClick:L=>L.stopPropagation(),children:[m.jsxs("header",{children:[m.jsxs("div",{children:[m.jsx("strong",{id:"mobile-tab-sheet-title",children:"Switch Tabs"}),m.jsxs("small",{children:[e.length," open"]})]}),m.jsxs("div",{className:"mobile-tab-sheet-header-actions",children:[m.jsx("button",{type:"button","aria-label":"New tab",title:"New tab",onClick:p,children:"+"}),m.jsx("button",{type:"button","aria-label":"Close tab switcher",title:"Close",onClick:f,children:"×"})]})]}),m.jsxs("div",{className:"mobile-tab-sheet-list",children:[e.map((L,U)=>{const I=rc(L),te=Tm(L),ee=jm(L,s),ae=L.id===t,ue=c?.tabId===L.id,be=zm(L,s),we=r?.has(L.id)??!1;return m.jsxs("div",{ref:ae?O:null,className:"mobile-tab-sheet-row","data-active":ae,"data-unread":we?"true":void 0,children:[ue&&c?m.jsx("form",{className:"mobile-tab-sheet-editor",onSubmit:ne=>{ne.preventDefault(),w()},children:m.jsx("input",{ref:h,"aria-label":`Rename ${ee}`,value:c.title,onBlur:w,onChange:ne=>E(L.id,ne.target.value),onKeyDown:ne=>{if(ne.key==="Enter"){ne.preventDefault(),w();return}ne.key==="Escape"&&(ne.preventDefault(),S())}})}):m.jsxs("button",{type:"button",className:"mobile-tab-sheet-select","aria-label":`Switch to ${ee}`,onClick:()=>g(L.id),children:[m.jsx("span",{className:"mobile-tab-sheet-index",children:U+1}),m.jsxs("span",{className:"mobile-tab-sheet-copy",children:[m.jsx("strong",{children:ee}),m.jsx("small",{children:gA(L,s,te,be)})]}),m.jsxs("span",{className:"mobile-tab-sheet-meta",children:[be?m.jsx("span",{className:"terminal-tab-status-dot","data-activity":be.state,"aria-hidden":"true",title:Lg(be)}):null,m.jsx("span",{children:te})]})]}),m.jsxs("div",{className:"mobile-tab-sheet-actions",children:[ue?m.jsx("button",{type:"button","aria-label":`Done renaming ${ee}`,onClick:w,children:"Done"}):m.jsx("button",{type:"button","aria-label":`Rename ${ee}`,onClick:()=>y(L.id,ee),children:"Rename"}),e.length>1?m.jsx("button",{type:"button",className:"mobile-tab-sheet-close","aria-label":`Close ${ee}`,onClick:()=>b(I),children:"×"}):null]})]},L.id)}),(o?.length??0)>0?m.jsxs("div",{className:"mobile-tab-sheet-detached","aria-label":"Detached terminals",children:[m.jsx("span",{children:"Detached"}),(o??[]).map(L=>{const U=L.title||L.cwd||L.id.slice(0,8);return m.jsxs("div",{className:"mobile-tab-sheet-row mobile-tab-sheet-row-detached",children:[m.jsxs("button",{type:"button",className:"mobile-tab-sheet-select","aria-label":`Re-open ${U}`,onClick:()=>T(L.id),children:[m.jsx("span",{className:"mobile-tab-sheet-index",children:"+"}),m.jsxs("span",{className:"mobile-tab-sheet-copy",children:[m.jsx("strong",{children:U}),m.jsx("small",{children:L.cwd})]}),m.jsx("span",{className:"mobile-tab-sheet-type",children:"detached"})]}),m.jsx("div",{className:"mobile-tab-sheet-actions",children:m.jsx("button",{type:"button",className:"mobile-tab-sheet-close","aria-label":`Delete ${U}`,onClick:()=>A(L),children:"×"})})]},L.id)})]}):null]})]})})}function c0({index:e}){const{setNodeRef:t,isOver:s}=Qm({id:`tab-position-${e}`,data:{kind:"tab-position",index:e}});return m.jsx("div",{ref:t,className:"terminal-tab-drop-slot","data-over":s,"aria-hidden":"true"})}function yA({terminal:e,onReattach:t,onDelete:s}){const r=e.title||e.cwd||e.id.slice(0,8),o=`${e.title||"Terminal"}
54
54
  ${e.cwd}
55
- (detached — click to re-open, × to delete)`;return m.jsxs("span",{className:"terminal-detached-pill",title:o,children:[m.jsx("button",{type:"button",className:"terminal-detached-pill-open","aria-label":`Re-open ${r}`,onClick:t,children:r}),m.jsx("button",{type:"button",className:"terminal-detached-pill-delete","aria-label":`Delete ${r}`,title:`Delete ${r} — this destroys the underlying shell session.`,onClick:c=>{c.stopPropagation(),s()},children:"×"})]})}function SA({terminal:e,onCancel:t,onConfirm:s}){const r=e.title||e.cwd||e.id.slice(0,8);return m.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"delete-terminal-title",onClick:t,children:m.jsxs("div",{className:"security-panel terminal-delete-dialog",onClick:o=>o.stopPropagation(),children:[m.jsxs("header",{className:"security-panel-header",children:[m.jsx("h2",{id:"delete-terminal-title",children:"Delete Terminal"}),m.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:t,children:"×"})]}),m.jsxs("section",{className:"terminal-delete-dialog-body",children:[m.jsx("p",{children:"Delete this terminal?"}),m.jsx("span",{children:r}),m.jsx("small",{children:"The shell session and scrollback will be destroyed."})]}),m.jsxs("div",{className:"terminal-delete-dialog-actions",children:[m.jsx("button",{type:"button",className:"secondary-button",onClick:t,children:"Cancel"}),m.jsx("button",{type:"button",className:"terminal-delete-confirm",onClick:s,children:"Delete"})]})]})})}function wA({uploads:e,onDismiss:t,onDismissAll:s,onRetry:r,onCancel:o}){if(e.length===0)return null;const h=e.some(g=>g.status==="failed"||g.status==="partial")?"alert":"status",f=e.filter(g=>g.status==="queued"||g.status==="uploading").length;return m.jsxs("aside",{className:`upload-toast upload-toast-${TA(e)}`,role:h,"aria-live":h==="alert"?"assertive":"polite",children:[m.jsxs("header",{className:"upload-toast-header",children:[m.jsx("strong",{children:e.length===1?Wu(e[0]):`Uploads ${f>0?`(${f} active)`:`(${e.length})`}`}),m.jsx("button",{type:"button","aria-label":"Dismiss upload status",onClick:s,children:"x"})]}),m.jsx("div",{className:"upload-toast-body upload-queue-body",children:e.map(g=>m.jsx(CA,{upload:g,compact:e.length>1,onDismiss:()=>t(g.id),onRetry:()=>r(g.id),onCancel:()=>o(g.id)},g.id))})]})}function CA({upload:e,compact:t,onDismiss:s,onRetry:r,onCancel:o}){const c="response"in e?e.response:void 0,h=e.status==="failed"||e.status==="partial",f=e.status==="queued"||e.status==="uploading";return m.jsxs("section",{className:"upload-queue-item","data-status":e.status,"aria-label":Wu(e),children:[m.jsxs("div",{className:"upload-queue-item-header",children:[m.jsx("strong",{children:Wu(e)}),m.jsxs("div",{className:"upload-queue-actions",children:[f?m.jsx("button",{type:"button",onClick:o,children:"Cancel"}):null,h?m.jsx("button",{type:"button",onClick:r,children:"Retry"}):null,m.jsx("button",{type:"button","aria-label":`Dismiss ${Wu(e)}`,onClick:s,children:"x"})]})]}),e.status==="queued"?m.jsx("p",{children:e.message??"Queued"}):null,e.status==="uploading"?m.jsx(xA,{toast:e}):null,c&&"message"in e&&e.message?m.jsx("p",{className:"upload-toast-muted",children:e.message}):null,c?m.jsx(EA,{response:c,compact:t}):null,e.status==="failed"&&!c&&e.message?m.jsx("p",{children:e.message}):null]})}function xA({toast:e}){const t=e.percent===null?DA(e.loaded):`${e.percent}%`;return m.jsxs(m.Fragment,{children:[m.jsxs("div",{className:"upload-progress-row",children:[m.jsxs("span",{children:[e.fileCount," file",e.fileCount===1?"":"s"]}),m.jsx("span",{children:t})]}),m.jsx("div",{className:"upload-progress-track","aria-hidden":"true",children:m.jsx("span",{style:{width:e.percent===null?"100%":`${e.percent}%`}})})]})}function EA({response:e,compact:t}){const s=e.results.filter(h=>h.status==="failed"),r=e.results.filter(h=>h.status==="uploaded"),o=t?3:6,c=[...s,...r].slice(0,o);return m.jsxs(m.Fragment,{children:[m.jsx("p",{className:"upload-toast-destination",children:e.destinationCwd}),c.length>0?m.jsx("ul",{className:"upload-result-list",children:c.map((h,f)=>m.jsx(kA,{result:h},`${h.relativePath}-${f}`))}):null,e.results.length>c.length?m.jsxs("p",{className:"upload-toast-muted",children:["+",e.results.length-c.length," more"]}):null]})}function kA({result:e}){const t=e.savedRelativePath??e.relativePath,s=e.status==="uploaded"&&e.savedRelativePath!==void 0&&e.savedRelativePath!==e.relativePath;return m.jsxs("li",{"data-status":e.status,children:[m.jsx("span",{className:"upload-result-path",children:t}),s?m.jsx("span",{className:"upload-result-renamed",children:"renamed"}):null,e.status==="failed"&&e.error?m.jsx("span",{className:"upload-result-error",children:e.error}):null]})}function Wu(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,s=(e.response?.uploaded??0)+(e.response?.failed??0)||e.fileCount;return`Uploaded ${t} of ${s} files`}return"Upload failed"}function TA(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 DA(e){return e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${Math.round(e/(1024*1024))} MB`}function RA({toast:e,onActivate:t,onDismiss:s}){if(!e)return null;const r=e,o=r.commandName?`${r.commandName} finished`:"Command finished";function c(f){f.stopPropagation(),s()}function h(f){f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),t(r))}return m.jsxs("aside",{className:"completion-toast",role:"status","aria-live":"polite",tabIndex:0,onClick:()=>t(r),onKeyDown:h,children:[m.jsx("video",{className:"completion-toast-character",src:r.assetSrc,muted:!0,autoPlay:!0,loop:!0,playsInline:!0,"aria-hidden":"true"}),m.jsxs("div",{className:"completion-toast-copy",children:[m.jsx("strong",{children:r.tabTitle}),m.jsx("span",{children:o})]}),m.jsx("button",{type:"button","aria-label":"Dismiss completion alert",onClick:c,children:"x"})]})}const MA=Uo(0,0,1,1),Ys=1e-6;function NA(e){return I1(e).map(t=>t.terminalId)}function I1(e){return Po(e,MA).sort(OA).map((t,s)=>({...t,index:s+1}))}function AA(e,t,s){const r=I1(e),o=r.find(h=>h.terminalId===t);return o?r.filter(h=>h.terminalId!==t).map(h=>BA(o,h,s)).filter(h=>h!==null).sort(zA)[0]?.entry.terminalId??null:null}function LA(e,t){return!Number.isInteger(t)||t<1?null:NA(e)[t-1]??null}function Po(e,t){if(e.type==="pane")return[{terminalId:e.terminalId,bounds:t}];if(e.type==="editor")return[];const s=jA(e.ratio);if(e.direction==="vertical"){const o=t.left+(t.right-t.left)*s;return[...Po(e.first,Uo(t.left,t.top,o,t.bottom)),...Po(e.second,Uo(o,t.top,t.right,t.bottom))]}const r=t.top+(t.bottom-t.top)*s;return[...Po(e.first,Uo(t.left,t.top,t.right,r)),...Po(e.second,Uo(t.left,r,t.right,t.bottom))]}function BA(e,t,s){const r=e.bounds,o=t.bounds,c=u0(r.left,r.right,o.left,o.right),h=u0(r.top,r.bottom,o.top,o.bottom);switch(s){case"left":return o.centerX>=r.centerX-Ys||h<=Ys?null:{entry:t,primaryDistance:Math.max(0,r.left-o.right),perpendicularDistance:Math.abs(r.centerY-o.centerY),overlap:h};case"right":return o.centerX<=r.centerX+Ys||h<=Ys?null:{entry:t,primaryDistance:Math.max(0,o.left-r.right),perpendicularDistance:Math.abs(r.centerY-o.centerY),overlap:h};case"up":return o.centerY>=r.centerY-Ys||c<=Ys?null:{entry:t,primaryDistance:Math.max(0,r.top-o.bottom),perpendicularDistance:Math.abs(r.centerX-o.centerX),overlap:c};case"down":return o.centerY<=r.centerY+Ys||c<=Ys?null:{entry:t,primaryDistance:Math.max(0,o.top-r.bottom),perpendicularDistance:Math.abs(r.centerX-o.centerX),overlap:c};default:return null}}function OA(e,t){return ml(e.bounds.top,t.bounds.top)||ml(e.bounds.left,t.bounds.left)}function zA(e,t){return ml(e.primaryDistance,t.primaryDistance)||ml(e.perpendicularDistance,t.perpendicularDistance)||ml(t.overlap,e.overlap)||ml(e.entry.index,t.entry.index)}function ml(e,t){const s=e-t;return Math.abs(s)<=Ys?0:s}function u0(e,t,s,r){return Math.max(0,Math.min(t,r)-Math.max(e,s))}function Uo(e,t,s,r){return{left:e,top:t,right:s,bottom:r,centerX:e+(s-e)/2,centerY:t+(r-t)/2}}function jA(e){return Number.isFinite(e)?Math.min(.9,Math.max(.1,e)):.5}class HA extends Error{constructor(t){super(t),this.name="UploadDropError"}}function h0(e){return e?Array.from(e.types??[]).includes("Files")||q1(e.items).some(s=>s.kind==="file")?!0:$1(e.files).length>0:!1}async function PA(e){const t=q1(e.items).filter(s=>s.kind==="file");return t.length>0?UA(t):IA(e.files)}async function UA(e){const t=[];for(const s of e){const r=qA(s);if(r){await K1(r,"",t);continue}const o=s.getAsFile();if(o){t.push({relativePath:F1(o),file:o});continue}throw new HA("Folder upload is not supported by this browser.")}return t}function IA(e){return $1(e).map(t=>({relativePath:F1(t),file:t}))}async function K1(e,t,s){const r=YA(t,e.name);if(e.isFile){const h=await KA(e);s.push({relativePath:r,file:h});return}if(!e.isDirectory)return;const o=e.createReader(),c=await FA(o);for(const h of c)await K1(h,r,s)}function KA(e){return new Promise((t,s)=>{e.file(t,r=>s(r))})}async function FA(e){const t=[];for(;;){const s=await WA(e);if(s.length===0)return t;t.push(...s)}}function WA(e){return new Promise((t,s)=>{e.readEntries(t,r=>s(r))})}function F1(e){const t=e.webkitRelativePath;return W1(typeof t=="string"&&t?t:e.name)}function qA(e){const t=e.webkitGetAsEntry?.();return $A(t)?t:null}function $A(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 YA(e,t){return W1(e?`${e}/${t}`:t)}function W1(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").split("/").filter(Boolean).join("/")}function q1(e){return e?Array.from(e):[]}function $1(e){return e?Array.from(e):[]}const d0="nterminal.terminalWorkspaces.v2",Y1="nterminal.sidebarCollapsed.v1",VA=75,f0=$0.map(e=>e.url),XA=$0[0].url,GA=6;function ZA({api:e,serverApi:t,activeAgentId:s=null,onSelectServer:r,sessionExpiresAt:o=null,onLogout:c=async()=>{},onSessionInvalid:h}){const f=v.useMemo(()=>e??fh(),[e]),g=v.useMemo(()=>t??Go(null),[t]),p=v.useMemo(()=>m5(s),[s]),y=v.useMemo(()=>x=>U1(s,x),[s]),b=v.useMemo(()=>()=>Mt(s),[s]),w=v.useSyncExternalStore(y,b,b),S=w.state,E=w.editors,T=!w.loaded,A=w.error,[O,L]=v.useState(!1),[U,I]=v.useState(()=>w5()),[te,ee]=v.useState("servers"),[ae,ue]=v.useState(!1),be=v.useSyncExternalStore(Gk,Uy,Uy);v.useSyncExternalStore(ug,Py,Py);const[we,ne]=v.useState(0),[ie,Y]=v.useState(null),[K,re]=v.useState(()=>[null]),[B,$]=v.useState(0),[D,X]=v.useState(()=>[s]),[_e,R]=v.useState(()=>new Set),[H,Q]=v.useState({}),[de,ke]=v.useState(null),xe=v.useRef(0),Re=v.useRef(0),[Xe,ge]=v.useState(null),[G,ce]=v.useState(null),Ce=v.useRef(null),ye=v.useRef(0),De=v.useRef(null),Be=v.useRef(null),Ke=v.useRef(null),[le,Ee]=v.useState(null),Le=RE(Sy(H0,{activationConstraint:{distance:8}}),Sy(P0,{activationConstraint:{delay:250,tolerance:5}}));v.useEffect(()=>Zk(f),[f]);function Oe(x){const k=x.active.data.current;if(k){if(k.kind==="tab"&&typeof k.tabId=="string"&&typeof k.terminalId=="string"){Ee({tabId:k.tabId,terminalId:k.terminalId});return}k.kind==="pane"&&typeof k.sourceTabId=="string"&&typeof k.terminalId=="string"&&Ee({tabId:k.sourceTabId,terminalId:k.terminalId})}}function He(x){Ee(null);const k=x.active.data.current,j=x.over?.data.current;if(!(!k||!j||typeof k.terminalId!="string")){if(k.kind==="tab"&&typeof k.tabId=="string"){if(j.kind==="tab-position"&&typeof j.index=="number"){it({type:"tab.reordered",sourceTabId:k.tabId,targetIndex:j.index});return}if(j.kind==="workspace"&&typeof j.workspaceId=="string"){it({type:"tab.moved_to_workspace",sourceTabId:k.tabId,targetWorkspaceId:j.workspaceId});return}j.kind==="pane-zone"&&typeof j.terminalId=="string"&&(j.side==="top"||j.side==="right"||j.side==="bottom"||j.side==="left")&&it({type:"tab.dropped_into_pane",sourceTabId:k.tabId,sourceTerminalId:k.terminalId,targetTerminalId:j.terminalId,side:j.side});return}if(k.kind==="pane"&&typeof k.sourceTabId=="string"){if(j.kind==="tab-position"&&typeof j.index=="number"){it({type:"terminal.extracted_to_tab",sourceTabId:k.sourceTabId,sourceTerminalId:k.terminalId,targetIndex:j.index});return}if(j.kind==="workspace"&&typeof j.workspaceId=="string"){it({type:"terminal.extracted_to_workspace",sourceTabId:k.sourceTabId,sourceTerminalId:k.terminalId,targetWorkspaceId:j.workspaceId});return}j.kind==="pane-zone"&&typeof j.terminalId=="string"&&(j.side==="top"||j.side==="right"||j.side==="bottom"||j.side==="left")&&it({type:"tab.dropped_into_pane",sourceTabId:k.sourceTabId,sourceTerminalId:k.terminalId,targetTerminalId:j.terminalId,side:j.side})}}}function _t(){Ee(null)}const Ye=S.workspaces.find(x=>x.id===S.activeWorkspaceId)??S.workspaces[0],rt=Ye?.tabs.find(x=>x.id===Ye.activeTabId)??Ye?.tabs[0],Oi=rt?.activeTerminalId??null,$i=Oi?S.terminals[Oi]:void 0,Ci=d5("(max-width: 760px)"),ri=v.useMemo(()=>rt?uh(rt.root):[],[rt]),zi=Ye&&rt?Io(s,Ye.id,rt.id):null,sn=rt?V1(ri,rt.activeTerminalId,zi?H[zi]:void 0):null,F=Ci&&ri.length>1,qe=v.useMemo(()=>(Ye?.detachedTerminalIds??[]).flatMap(x=>{const k=S.terminals[x];return k?[k]:[]}),[Ye?.detachedTerminalIds,S.terminals]),dt=v.useMemo(()=>{const x=new Set;for(const k of Ye?.tabs??[])rc(k).some(j=>w.unreadCompletions.has(j))&&x.add(k.id);return x},[Ye?.tabs,w.unreadCompletions]),[vt,pi]=v.useState([]),St=v.useRef([]),mn=v.useRef(null),[Ln,Jt]=v.useState(null),[ai,Zi]=v.useState(null),[gt,Tt]=v.useState([]),[Dt,mi]=v.useState(()=>ya()),gi=v.useRef(0),Ut=v.useRef(s),ei=v.useRef(f0),ji=v.useRef(Dt),Lt=v.useRef(()=>{});Lt.current=Wr;const xi=v.useCallback(async()=>{try{const x=await f.listNotificationAssets();Tt(x.assets.filter(k=>k.enabled).map(k=>k.url))}catch{Tt([])}},[f]);v.useEffect(()=>{X(x=>x.some(k=>fn(k,s))?x:[...x,s])},[s]);const It=v.useCallback(x=>{const k=Mt(x),j=Go(x);for(const se of Object.keys(k.state.terminals))Ho(j.createWebSocketUrl(se)),Nu(se);pA(x),X(se=>se.filter(ve=>!fn(ve,x))),R(se=>{const ve=`${$u(x)}:`;let me=!1;const Se=new Set;for(const Pe of se){if(Pe.startsWith(ve)){me=!0;continue}Se.add(Pe)}return me?Se:se}),Q(se=>{const ve=`${$u(x)}:`;let me=!1;const Se={};for(const[Pe,nt]of Object.entries(se)){if(Pe.startsWith(ve)){me=!0;continue}Se[Pe]=nt}return me?Se:se})},[]);v.useEffect(()=>{let x=!1;return f.listAgents().then(k=>{if(!x){const j=k.agents.map(ve=>ve.id),se=[null,...j];s!==null&&!j.includes(s)&&(It(s),r?.(null)),re(se)}}).catch(()=>{}),()=>{x=!0}},[s,f,It,r,B]);const Yi=v.useCallback(x=>{It(x),$(k=>k+1),fn(x,Ut.current)&&r?.(null)},[It,r]);v.useEffect(()=>{re(x=>x.some(k=>fn(k,s))?x:[...x,s])},[s]),v.useEffect(()=>{Ut.current=s},[s]),v.useEffect(()=>{Y(null)},[s]),v.useEffect(()=>{const x=De.current;if(!x)return;if(!fn(x.agentId,s)){De.current=null;return}if(!w.loaded||S.workspaces.length===0)return;De.current=null;const k=x.edge==="first"?S.workspaces[0]:S.workspaces[S.workspaces.length-1];k&&k.id!==S.activeWorkspaceId&&it({type:"workspace.selected",workspaceId:k.id})},[s,w.loaded,S.activeWorkspaceId,S.workspaces]),v.useEffect(()=>{const x=Be.current;if(x){if(!fn(x.agentId,s)){Be.current=null;return}w.loaded&&(Be.current=null,S.workspaces.some(k=>k.id===x.workspaceId)&&it({type:"workspace.selected",workspaceId:x.workspaceId}))}},[s,w.loaded,S.workspaces]),v.useEffect(()=>{const x=Ke.current;if(x){if(!fn(x.agentId,s)){Ke.current=null;return}w.loaded&&(Ke.current=null,w.error||gn())}},[s,w.error,w.loaded]),v.useEffect(()=>{xi()},[xi]),v.useEffect(()=>ew(()=>mi(ya())),[]),v.useEffect(()=>{const x=k=>{Lt.current(k)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[]),v.useEffect(()=>{ei.current=gt.length>0?gt:f0},[gt]),v.useEffect(()=>{ji.current=Dt},[Dt]),v.useEffect(()=>{if(!w.loaded||!Ye||!rt)return;const x=Io(s,Ye.id,rt.id);R(k=>{if(k.has(x))return k;const j=new Set(k);return j.add(x),j})},[s,w.loaded,Ye?.id,rt?.id]),v.useEffect(()=>()=>{li()},[]),v.useEffect(()=>lA(x=>{const k=Mt(x.agentId).state,j=k.workspaces.flatMap(Se=>Se.tabs).find(Se=>Se.id===x.tabId),se=k.terminals[x.terminalId],ve=j?.title?.trim()||se?.title||x.commandName||"terminal",me=document.visibilityState==="visible"&&fn(x.agentId,Ut.current)&&x.tabId===p5(k);if(me||Mk({tabTitle:ve,commandName:x.commandName,terminalId:x.terminalId}),!me&&document.visibilityState==="visible"&&ji.current.enabled){const Se=gi.current+1;gi.current=Se;const Pe=ei.current;Jt({id:Se,agentId:x.agentId,terminalId:x.terminalId,tabId:x.tabId,tabTitle:ve,commandName:x.commandName,assetSrc:Pe[Math.floor(Math.random()*Pe.length)]??XA})}}),[]),v.useEffect(()=>{if(!Ln||Dt.persistUntilDismissed)return;const x=window.setTimeout(()=>{Jt(k=>k?.id===Ln.id?null:k)},Dt.durationSeconds*1e3);return()=>window.clearTimeout(x)},[Ln,Dt]),v.useEffect(()=>{C5(U),U&&an()},[U]),v.useEffect(()=>{let x=!1;async function k(){if(!Mt(s).loaded){kr(s,!1,null);try{let se=null,ve=null;try{se=g5(p)}catch(nt){if(!(nt instanceof dh))throw nt;ve=nt}const[me,Se]=await Promise.all([g.listTerminals(),g.getTerminalLayout()]),Pe=me.terminals.length>0?me.terminals:[(await g.createTerminal({cols:80,rows:24})).terminal];if(!x){const nt=Se.layout?G1(Se.layout):null;if(!nt&&ve)throw ve;const Vt=nt??se??{},ti=km(Pe,void 0,Vt.savedWorkspaces,Vt.savedActiveWorkspaceId),Aa=up(ti);o0(s,ti),Mo(s,Se.revision,JSON.stringify(Aa)),kr(s,!0,null),!nt&&se&&wt(Aa,{baseRevision:Se.revision})}}catch(se){!x&&!Ts(se)&&kr(s,!0,Tr(se))}}}return k(),()=>{x=!0}},[s,g,we]);function rn(){kr(s,!1,null),ne(x=>x+1)}function an(){xe.current+=1,Re.current+=1,ke(null)}function Qi(x){xe.current+=1,Re.current+=1,ke(k=>k&&{...k,cwd:x,browseRoot:null,browseEntries:[],browseStatus:"idle",submitStatus:"idle",error:null})}function gn(){xe.current+=1,Re.current+=1;const x=S.workspaces.length+1,k=Ei();ke({mode:"create",workspaceId:null,title:`Workspace ${x}`,cwd:k,browseRoot:null,browseEntries:[],browseStatus:"idle",submitStatus:"idle",error:null}),k&&Bn(k)}function Hi(x){if(fn(x,s)){gn();return}Ke.current={agentId:x},r?.(x)}function Kt(x){if(U&&!O)return;const k=S.workspaces.find(se=>se.id===x);if(!k)return;xe.current+=1,Re.current+=1;const j=k.defaultCwd??$i?.cwd??"";ke({mode:"edit",workspaceId:x,title:k.title,cwd:j,browseRoot:null,browseEntries:[],browseStatus:"idle",submitStatus:"idle",error:null}),j&&Bn(j)}function Ei(){return Ye?.defaultCwd??$i?.cwd??""}async function Bn(x){const k=xe.current+1;xe.current=k;const j=x.trim();if(ke(se=>se&&{...se,cwd:x,browseStatus:j?"loading":"idle",browseRoot:null,browseEntries:[],error:j?null:"Choose a default working directory."}),!!j)try{const se=await g.createFileRoot({path:j}),ve=await g.listFiles({rootToken:se.rootToken,path:""});if(xe.current!==k)return;ke(me=>me&&{...me,cwd:se.rootPath,browseRoot:{rootToken:se.rootToken,rootPath:se.rootPath},browseEntries:ve.entries.filter(Se=>Se.kind==="directory"),browseStatus:"idle",error:null})}catch(se){if(xe.current!==k)return;ke(ve=>ve&&{...ve,browseStatus:"idle",error:Tr(se)})}}async function ks(){const x=de;if(!x)return;const k=x.title.trim(),j=x.cwd.trim();if(!k||!j){ke({...x,submitStatus:"idle",error:k?"Choose a default working directory.":"Workspace name is required."});return}const se=Re.current+1;Re.current=se,ke({...x,submitStatus:"submitting",error:null});try{const ve=await g.createFileRoot({path:j});if(Re.current!==se)return;if(x.mode==="create"){const me=S.workspaces.length+1;it({type:"workspace.created",workspaceId:`workspace-${Date.now().toString(36)}-${me}`,title:k,defaultCwd:ve.rootPath})}else x.workspaceId&&(it({type:"workspace.renamed",workspaceId:x.workspaceId,title:k}),it({type:"workspace.defaultCwdChanged",workspaceId:x.workspaceId,defaultCwd:ve.rootPath}));ke(null)}catch(ve){if(Re.current!==se)return;ke(me=>me&&{...me,submitStatus:"idle",error:Tr(ve)})}}function Nl(x){Re.current+=1,ke(x)}function Da(x,k,j){if(x===k)return;const se=S.workspaces.some(me=>me.id===x),ve=S.workspaces.some(me=>me.id===k);!se||!ve||it({type:"workspace.reordered",sourceWorkspaceId:x,targetWorkspaceId:k,placement:j})}function Qn(x,k){const j=S.workspaces.findIndex(ve=>ve.id===x),se=S.workspaces[j+k];j<0||!se||Da(x,se.id,k<0?"before":"after")}function Jn(x,k){k.pointerType==="mouse"&&k.button!==0||(k.preventDefault(),k.stopPropagation(),Ce.current={sourceId:x,pointerId:k.pointerId,startX:k.clientX,startY:k.clientY,active:!1,targetId:null,placement:"after"},k.currentTarget.setPointerCapture?.(k.pointerId))}function fs(x){const k=Ce.current;if(!k||k.pointerId!==x.pointerId)return;const j=Math.hypot(x.clientX-k.startX,x.clientY-k.startY);if(!k.active){if(j<GA)return;k.active=!0,ge(k.sourceId)}const ve=document.elementFromPoint(x.clientX,x.clientY)?.closest("[data-workspace-id]"),me=ve?.dataset.workspaceId??null;if(!ve||!me||me===k.sourceId||!S.workspaces.some(nt=>nt.id===me)){k.targetId=null,ce(null);return}const Se=ve.getBoundingClientRect(),Pe=x.clientY<Se.top+Se.height/2?"before":"after";k.targetId=me,k.placement=Pe,ce({workspaceId:me,placement:Pe})}function At(x){const k=Ce.current;!k||k.pointerId!==x.pointerId||(x.preventDefault(),x.stopPropagation(),x.currentTarget.releasePointerCapture?.(x.pointerId),Ce.current=null,ge(null),ce(null),k.active&&k.targetId&&Da(k.sourceId,k.targetId,k.placement))}function es(x){const k=Ce.current;k&&k.pointerId===x.pointerId&&x.currentTarget.releasePointerCapture?.(x.pointerId),Ce.current=null,ge(null),ce(null)}async function ts(){await Yt(async()=>{const x=Ye?.defaultCwd?{cols:80,rows:24,cwd:Ye.defaultCwd}:{cols:80,rows:24},k=await g.createTerminal(x);it({type:"terminal.created",terminal:k.terminal})})}async function Vi(x){await Yt(async()=>{const k=Oi?{parentTerminalId:Oi,cols:80,rows:24}:Ye?.defaultCwd?{cols:80,rows:24,cwd:Ye.defaultCwd}:{cols:80,rows:24},j=await g.createTerminal(k);it({type:"terminal.split",terminal:j.terminal,direction:x})})}async function ot(x){let k=Oi,j=zi;const se=Ye?.defaultCwd?.trim();if(!k&&!se)throw new Error("No active pane is available.");const ve=await g.readFile(x);if(!k&&se){const Pe=await g.createTerminal({cols:80,rows:24,cwd:se});k=Pe.terminal.id,it({type:"terminal.created",terminal:Pe.terminal})}if(k){it({type:"pane.selected",terminalId:k});const Pe=Mt(s).state,nt=Pe.workspaces.find(ti=>ti.id===Pe.activeWorkspaceId)??Pe.workspaces[0],Vt=nt?.tabs.find(ti=>ti.id===nt.activeTabId)??nt?.tabs[0];j=nt&&Vt?Io(s,nt.id,Vt.id):null}const me=`editor-${Date.now().toString(36)}-${fA(s)}`,Se=S5(ve.path);hp(s,Pe=>({...Pe,[me]:{id:me,title:Se,rootToken:x.rootToken,path:ve.path,read:ve}})),j&&Q(Pe=>({...Pe,[j]:X1(me)})),it({type:"editor.split",editorId:me,title:Se,direction:"vertical"})}function Ra(x){hp(s,k=>{const j={...k};return delete j[x],j}),it({type:"editor.closed",editorId:x})}function Ur(x){_n([x])}function _n(x){const k=[...new Set(x)].filter(se=>S.terminals[se]);if(k.length===0)return;const j=k.length===1?S.terminals[k[0]]?.title||S.terminals[k[0]]?.cwd||k[0]:`${k.length} panes`;Y(null),Zi({terminalIds:k,label:j,workspaceId:Ye?.id??S.activeWorkspaceId??null})}function is(x,k){const j=rs(x,k);if(!j)return!1;const se=x.filter(ve=>!j.detachedTerminalIds.includes(ve));if(j.detachedTerminalIds.length+se.length>kl)return Y(v5(j.detachedTerminalIds.length)),!1;Y(null);for(const ve of x)it(j.id?{type:"terminal.detached",terminalId:ve,workspaceId:j.id}:{type:"terminal.detached",terminalId:ve});return!0}async function Al(x){await Yt(async()=>{for(const k of x)await ns(k),Ho(g.createWebSocketUrl(k)),Nu(k),it({type:"terminal.closed",terminalId:k})})}async function Ir(x){const k=S.workspaces.find(j=>j.id===x);!k||S.workspaces.length<=1||window.confirm(`Delete workspace "${k.title}" and close all terminal sessions inside it? This cannot be undone.`)&&await Yt(async()=>{const j=ch(k),se=[];let ve=null;for(const Se of j)try{await ns(Se)}catch(Pe){se.push(Tr(Pe)),Pe instanceof us&&Pe.status===401&&!g.isAgent&&(ve=Pe)}finally{Ho(g.createWebSocketUrl(Se)),Nu(Se)}const me=k.tabs.flatMap(Se=>Hm(Se.root));if(me.length>0){const Se=new Set(me);hp(s,Pe=>{const nt={...Pe};for(const Vt of Se)delete nt[Vt];return nt})}if(it({type:"workspace.closed",workspaceId:x}),ve)throw ve;if(se.length>0)throw new Error(`Workspace was removed, but ${se.length} terminal session${se.length===1?"":"s"} may still be running. ${se[0]}`)})}async function On(x){await Yt(async()=>{await ns(x),Ho(g.createWebSocketUrl(x)),Nu(x),it({type:"terminal.closed",terminalId:x})})}async function Kr(x,k){const j=k.trim();if(!j)return;let se=null;for(const ve of S.workspaces){const me=ve.tabs.find(Se=>Se.id===x);if(me){se=me.activeTerminalId;break}}if(it({type:"tab.renamed",tabId:x,title:j}),!!se)try{const ve=await g.renameTerminal(se,j);ss({type:"terminal.updated",terminal:ve.terminal})}catch(ve){kr(s,!0,Tr(ve))}}function Qs(x){const k=S.terminals[x];k&&it({type:"terminal.created",terminal:k})}async function ns(x){try{await g.closeTerminal(x)}catch(k){if(k instanceof us&&k.status===404)return;throw k}}async function vn(){await Yt(async()=>{await c()})}async function Yt(x){kr(s,!0,null);try{await x()}catch(k){if(Ts(k))return;kr(s,!0,Tr(k))}}function Ts(x){return x instanceof us&&x.status===401&&!g.isAgent&&h?(h({source:"workspace-api-401",status:401,activeAgentId:s}),!0):!1}function it(x){Ro(s,x);const k=Mt(s),j=k.state;if(!k.loaded||j.workspaces.length===0)return;const se=up(j);JSON.stringify(se)!==k.lastPersistedLayoutJson&&Ft(se)}function ss(x){Ro(s,x)}function Fr(x,k,j,se){const ve=Io(x,k,j);Q(me=>({...me,[ve]:se}))}function ps(x){zi&&Q(k=>({...k,[zi]:x}))}function Ma(x,k){const j=hh(x);k?Fr(s,k.workspaceId,k.tabId,j):ps(j),it({type:"pane.selected",terminalId:x})}function Pi(x){ps(x.key),x.type==="terminal"&&it({type:"pane.selected",terminalId:x.terminalId})}function Wr(x){if(ae||ai||x.isComposing||x.key==="Process"||n5(x.target))return;const k=JA(x);if(!k)return;if(x.preventDefault(),x.stopPropagation(),k.type==="server.previous"||k.type==="server.next"){$r(k.type==="server.next"?1:-1);return}const j=Mt(s).state,se=j.workspaces.find(Se=>Se.id===j.activeWorkspaceId)??j.workspaces[0],ve=se?.tabs.find(Se=>Se.id===se.activeTabId)??se?.tabs[0];if(k.type==="split"){if(!ve)return;Vi(k.direction);return}if(!se||!ve)return;if(k.type==="tab.previous"||k.type==="tab.next"){const Se=i5(se.tabs,ve.id,k.type==="tab.next"?1:-1);Se&&it({type:"tab.selected",tabId:Se.id});return}if(k.type==="tab.index"){const Se=se.tabs[k.index-1];Se&&it({type:"tab.selected",tabId:Se.id});return}const me=e5(ve.root,ve.activeTerminalId,k);me&&Ma(me,{workspaceId:se.id,tabId:ve.id})}function qr(x,k){if(!r||K.length===0)return;const j=K.findIndex(Se=>fn(Se,s)),ve=((j===-1?0:j)+x+K.length)%K.length,me=K[ve]??null;fn(me,s)||(k&&(De.current={agentId:me,edge:k}),r(me))}function $r(x){const k=Mt(s).state,j=k.workspaces;if(j.length===0){qr(x,x===1?"first":"last");return}const se=j.findIndex(Se=>Se.id===k.activeWorkspaceId),me=(se===-1?0:se)+x;if(me>=0&&me<j.length){it({type:"workspace.selected",workspaceId:j[me].id});return}qr(x,x===1?"first":"last")}function zn(x,k){if(fn(x,s)){it({type:"workspace.selected",workspaceId:k});return}Be.current={agentId:x,workspaceId:k},r?.(x)}function rs(x,k){if(k)return S.workspaces.find(j=>j.id===k)??null;for(const j of x){const se=S.workspaces.find(me=>me.tabs.some(Se=>rc(Se).includes(j)));if(se)return se;const ve=S.workspaces.find(me=>me.detachedTerminalIds.includes(j));if(ve)return ve}return S.workspaces.find(j=>j.id===S.activeWorkspaceId)??S.workspaces[0]??null}function Na(x){h0(x.dataTransfer)&&(x.preventDefault(),x.dataTransfer.dropEffect="copy")}function ms(x){if(!h0(x.dataTransfer))return;x.preventDefault();const k=b5(Mt(s).state),j=ye.current+1;if(ye.current=j,!k){Js({id:j,status:"failed",fileCount:0,message:"No active running terminal is available for upload."});return}Js({id:j,status:"queued",fileCount:0,terminalId:k.id,message:"Preparing upload..."}),Ll(j,k.id,x.dataTransfer)}async function Ll(x,k,j){try{const se=await PA(j);if(se.length===0)throw new Error("No files were found in the drop.");yn(x,{id:x,status:"queued",fileCount:se.length,message:"Queued"},{terminalId:k,files:se})}catch(se){yn(x,{id:x,status:"failed",fileCount:0,message:Tr(se)},{terminalId:k})}finally{Ds()}}async function bn(x){const k=St.current.find(me=>me.id===x);if(!k?.terminalId||!k.files||k.files.length===0)return;const j=k.terminalId,se=k.files,ve=new AbortController;mn.current=x,yn(x,{id:x,status:"uploading",fileCount:se.length,loaded:0,total:null,percent:null},{terminalId:j,files:se,abortController:ve});try{const me=await hT({terminalId:j,files:se,signal:ve.signal,onProgress:Vt=>{yn(x,{id:x,status:"uploading",fileCount:se.length,loaded:Vt.loaded,total:Vt.total,percent:Vt.percent},{terminalId:j,files:se,abortController:ve})}}),Se=me.failed>0?me.uploaded>0?"partial":"failed":"success",Pe=me.failed>0?y5(me):void 0,nt={id:x,status:Se,fileCount:se.length,response:me};Pe&&(nt.message=Pe),yn(x,nt,{terminalId:j,files:se})}catch(me){yn(x,{id:x,status:"failed",fileCount:se.length,message:ve.signal.aborted?"Upload canceled.":Tr(me)},{terminalId:j,files:se})}finally{mn.current===x&&(mn.current=null),Ds()}}function Ds(){if(mn.current!==null)return;const x=St.current.find(k=>k.status==="queued");x?.terminalId&&x.files&&x.files.length>0&&bn(x.id)}function Js(x){er(k=>[...k,x])}function yn(x,k,j={}){er(se=>se.map(ve=>{if(ve.id!==x)return ve;const me={...k},Se=j.terminalId??ve.terminalId,Pe=j.files??ve.files;return Se!==void 0&&(me.terminalId=Se),Pe!==void 0&&(me.files=Pe),j.abortController!==void 0&&(me.abortController=j.abortController),me}))}function er(x){const k=x(St.current);St.current=k,pi(k)}function M(x){St.current.find(j=>j.id===x)?.abortController?.abort(),mn.current===x&&(mn.current=null),er(j=>j.filter(se=>se.id!==x)),Ds()}function J(){for(const x of St.current)x.abortController?.abort();mn.current=null,er(()=>[])}function je(x){const k=St.current.find(j=>j.id===x);if(k){if(k.status==="queued"){M(x);return}k.abortController?.abort()}}function Fe(x){const k=St.current.find(se=>se.id===x);if(!k?.terminalId||!k.files||k.files.length===0)return;const j=Ie(k);if(j.length===0){yn(x,{id:x,status:"failed",fileCount:k.fileCount,message:"No failed files are available to retry."},{terminalId:k.terminalId,files:k.files});return}yn(x,{id:x,status:"queued",fileCount:j.length,message:"Queued"},{terminalId:k.terminalId,files:j}),Ds()}function Ie(x){const k=x.files??[],j="response"in x?x.response:void 0;if(!j)return k;const se=j.results.filter(Se=>Se.status==="failed").map(Se=>Se.relativePath);if(se.length===0)return[];const ve=new Map;for(const Se of k){const Pe=ve.get(Se.relativePath)??[];Pe.push(Se),ve.set(Se.relativePath,Pe)}const me=[];for(const Se of se){const nt=ve.get(Se)?.shift();nt&&me.push(nt)}return me}function Ge(x){const j=Mt(x.agentId).state.workspaces.find(se=>se.tabs.some(ve=>ve.id===x.tabId));j&&Fr(x.agentId,j.id,x.tabId,hh(x.terminalId)),Ro(x.agentId,{type:"pane.selected",terminalId:x.terminalId}),dA(x.agentId,x.terminalId),fn(x.agentId,s)||r?.(x.agentId),Jt(null)}function Ft(x){const k=Mt(s).mutable.saveCoord;k.pendingLayoutSave=x,No(x,p),k.saveTimer!==null&&window.clearTimeout(k.saveTimer),k.saveTimer=window.setTimeout(()=>{k.saveTimer=null;const j=k.pendingLayoutSave;k.pendingLayoutSave=null,j&&wt(j)},VA)}function li(){const x=Mt(s).mutable.saveCoord;x.saveTimer!==null&&(window.clearTimeout(x.saveTimer),x.saveTimer=null);const k=x.pendingLayoutSave;x.pendingLayoutSave=null,k&&(No(k,p),wt(k))}function wt(x,k={}){const j=Mt(s).mutable.saveCoord;j.nextPersistLayout=x,k.baseRevision!==void 0&&(j.queuedBaseRevision=k.baseRevision),!j.nextPersistQueued&&(j.nextPersistQueued=!0,j.persistChain=j.persistChain.then(async()=>{j.nextPersistQueued=!1;const se=j.nextPersistLayout,ve=j.queuedBaseRevision;j.nextPersistLayout=null,j.queuedBaseRevision=void 0,se&&await Bt(se,ve!==void 0?{baseRevision:ve}:{})}))}async function Bt(x,k={}){const j=Mt(s),se=k.baseRevision??j.layoutRevision,ve={layout:x,...typeof se=="number"?{baseRevision:se}:{}};try{const me=await g.saveTerminalLayout(ve),Se=me.layout??x;Mo(s,me.revision,JSON.stringify(Se)),No(Se,p);return}catch(me){if(me instanceof us&&me.status===400&&me.message===z2){_5(s,p),kr(s,!0,Z1());return}if(me instanceof us&&me.status===409)try{const Se=await g.getTerminalLayout(),Pe=Mt(s).mutable.saveCoord;if(Pe.nextPersistLayout||Pe.pendingLayoutSave){const nt=Se.layout?JSON.stringify(Se.layout):Mt(s).lastPersistedLayoutJson;Mo(s,Se.revision,nt);return}if(Se.layout){const nt=Mt(s).state,Vt=km(Object.values(nt.terminals),void 0,Se.layout.workspaces,Se.layout.activeWorkspaceId),ti=up(Vt);o0(s,Vt),Mo(s,Se.revision,JSON.stringify(ti)),No(ti,p)}else Mo(s,Se.revision,j.lastPersistedLayoutJson);return}catch{}No(x,p)}}const Ui=x5(o),Wt=!U||O,Sn=Wt?te:"servers";function jn(x){const k=x.active?w:Mt(x.agentId),j=x.active?S:k.state,se=x.active?w.loaded:k.loaded,ve=x.active?A:k.error;return m.jsxs("div",{className:`workspace-list-panel${x.active?" workspace-list-panel--active-server":""}`,"aria-label":`${x.label} workspaces`,children:[m.jsxs("div",{className:"workspace-list-header",children:[m.jsx("span",{children:"Workspaces"}),m.jsx("button",{type:"button","aria-label":`New workspace on ${x.label}`,title:"New workspace",onClick:()=>Hi(x.agentId),children:"+"})]}),se?ve?m.jsx("button",{type:"button",className:"workspace-list-placeholder workspace-list-placeholder--error",onClick:()=>r?.(x.agentId),children:ve}):m.jsx("div",{className:"workspace-list-items",children:j.workspaces.map(me=>{const Se=x.active&&me.id===Ye?.id,Pe=ch(me).length,nt=x.active&&j.workspaces.length>1,Vt=G?.workspaceId===me.id&&Xe!==me.id?G.placement:null;return m.jsxs(o5,{workspaceId:me.id,active:Se,disabled:!x.active,reorderable:nt,dragging:Xe===me.id,dropPlacement:Vt,children:[nt?m.jsx("button",{type:"button",className:"workspace-list-drag-handle","data-workspace-drag-handle":me.id,title:"Drag to reorder","aria-label":`Reorder ${me.title}`,"aria-grabbed":Xe===me.id,onPointerDown:ti=>Jn(me.id,ti),onPointerMove:fs,onPointerUp:At,onPointerCancel:es,onKeyDown:ti=>{(ti.key==="ArrowUp"||ti.key==="ArrowDown")&&(ti.preventDefault(),ti.stopPropagation(),Qn(me.id,ti.key==="ArrowUp"?-1:1))},onClick:ti=>ti.stopPropagation(),children:"::"}):null,m.jsxs("button",{type:"button",className:"workspace-list-select","aria-current":Se?"page":void 0,title:me.defaultCwd??void 0,onClick:()=>zn(x.agentId,me.id),onDoubleClick:()=>{x.active&&Kt(me.id)},children:[m.jsx("span",{className:"workspace-list-name",children:me.title}),m.jsxs("small",{children:[me.defaultCwd??"No folder"," · ",Pe," ",Pe===1?"session":"sessions"]})]}),x.active?m.jsxs("div",{className:"workspace-list-actions",children:[m.jsx("button",{type:"button",className:"workspace-list-edit","aria-label":`Edit ${me.title}`,title:"Edit workspace",onClick:()=>Kt(me.id),children:"..."}),m.jsx("button",{type:"button",className:"workspace-list-delete","aria-label":`Delete ${me.title}`,title:"Delete workspace",disabled:j.workspaces.length<=1,onClick:()=>{Ir(me.id)},children:"x"})]}):null]},me.id)})}):m.jsx("button",{type:"button",className:"workspace-list-placeholder",onClick:()=>r?.(x.agentId),children:"Open server to load workspaces"})]})}return m.jsx(R2,{sensors:Le,onDragStart:Oe,onDragEnd:He,onDragCancel:_t,children:m.jsxs("main",{className:"terminal-shell","data-collapsed":U,"data-sidebar-open":O,onDragOver:Na,onDrop:ms,children:[m.jsx("button",{type:"button",className:"workspace-backdrop","aria-label":"Close workspaces",onClick:()=>L(!1)}),m.jsxs("aside",{className:"workspace-sidebar",children:[m.jsxs("header",{className:"workspace-brand",children:[Wt?m.jsx(C0,{height:20}):m.jsx(w0,{size:24}),m.jsx("button",{type:"button",className:"sidebar-collapse-button","aria-label":U?"Expand sidebar":"Collapse sidebar",title:U?"Expand sidebar":"Collapse sidebar",onClick:()=>I(x=>!x),children:U?">":"<"}),m.jsx("button",{type:"button",className:"sidebar-drawer-close-button","aria-label":"Close workspaces",title:"Close workspaces",onClick:()=>L(!1),children:"x"})]}),m.jsxs("div",{className:`workspace-sidebar-content workspace-sidebar-content--${Sn==="files"?"files":"servers"}`,children:[Wt?m.jsxs("div",{className:"workspace-sidebar-tabs",role:"tablist","aria-label":"Sidebar mode",children:[m.jsx("button",{type:"button",role:"tab","aria-selected":te==="servers",onClick:()=>{ee("servers")},children:"Workspaces"}),m.jsx("button",{type:"button",role:"tab","aria-selected":te==="files",onClick:()=>{ee("files")},children:"Files"})]}):null,Sn==="servers"&&Wt?m.jsx("nav",{className:"workspace-nav","aria-label":"Workspaces",children:m.jsx(Oy,{api:f,activeAgentId:s,onSelectServer:r??(()=>{}),onSessionInvalid:h,refreshToken:B,renderServerChildren:jn})}):null,Wt?null:m.jsx("nav",{className:"workspace-nav workspace-nav--collapsed","aria-label":"Servers",children:m.jsx(Oy,{api:f,activeAgentId:s,onSelectServer:r??(()=>{}),onSessionInvalid:h,refreshToken:B,compact:!0})}),Sn==="files"?m.jsx(gT,{api:g,activeTerminalId:Oi,activeTerminalCwd:$i?.cwd??null,workspaceRootPath:Ye?.defaultCwd??$i?.cwd??null,onOpenFile:ot}):null]}),m.jsxs("div",{className:"workspace-sidebar-footer",children:[Wt?m.jsx("span",{children:Ui}):null,m.jsxs("div",{className:"workspace-sidebar-footer-actions",children:[m.jsxs("button",{type:"button",className:"workspace-footer-icon-button","aria-label":"settings",title:"Settings",onClick:()=>ue(!0),children:[m.jsx(m0,{name:"settings"}),be.hasUpdates?m.jsx("span",{className:"update-pulse-dot","aria-hidden":"true"}):null]}),Wt?m.jsx("button",{type:"button",className:"workspace-footer-icon-button","aria-label":"logout",title:"Logout",onClick:()=>{vn()},children:m.jsx(m0,{name:"logout"})}):null]})]})]}),ae?m.jsx(aT,{api:f,onClose:()=>ue(!1),updateAvailable:be.hasUpdates,onNotificationAssetsChanged:()=>{xi()},onAgentRemoved:Yi}):null,de?m.jsx(s5,{dialog:de,activePaneCwd:$i?.cwd??null,activeWorkspaceCwd:Ye?.defaultCwd??null,onChange:Nl,onManualCwdChange:Qi,onBrowse:Bn,onCancel:an,onSubmit:()=>{ks()}}):null,m.jsxs("section",{className:"terminal-main","aria-label":"Terminal workspace","data-mobile-pane-switcher":F?"true":void 0,children:[m.jsx(_A,{tabs:Ye?.tabs??[],activeTabId:Ye?.activeTabId??null,terminals:S.terminals,unreadCompletionTabIds:dt,detachedTerminals:qe,onSelectTab:x=>it({type:"tab.selected",tabId:x}),onCreateTab:()=>{ts()},onToggleWorkspaces:()=>L(x=>!x),onCloseTerminals:x=>_n(x),onReattachTerminal:x=>Qs(x),onDeleteTerminal:x=>{On(x)},onSplitVertical:()=>{Vi("vertical")},onSplitHorizontal:()=>{Vi("horizontal")},onRenameTab:(x,k)=>{Kr(x,k)},activePaneAvailable:!!Oi}),F?m.jsx(u5,{targets:ri,activeLeafKey:sn,terminals:S.terminals,editors:E,onSelect:Pi}):null,A?m.jsxs("div",{className:"workspace-error",role:"alert",children:[m.jsx("span",{children:A}),m.jsxs("div",{className:"workspace-error-actions",children:[m.jsx("button",{type:"button",onClick:rn,children:"Retry"}),s!==null&&r?m.jsx("button",{type:"button",onClick:()=>r(null),children:"Main server"}):null]})]}):null,m.jsxs("section",{className:"workspace-body","aria-busy":T,children:[T?m.jsx("div",{className:"workspace-placeholder",children:"Opening shell..."}):null,!T&&!rt?m.jsx(l5,{onCreate:()=>{ts()}}):null,D.map(x=>{const k=fn(x,s);return m.jsx(QA,{agentId:x,active:k,activeServerApi:k?g:void 0,visitedTabKeys:_e,refreshCwdOnEnter:k&&Sn==="files",draggingTab:k?le:null,mobileSplitFocus:Ci,mobileFocusedLeafByTabKey:H,onSelect:j=>{k&&Ma(j)},onClose:j=>{k&&Ur(j)},onCloseEditor:j=>{k&&Ra(j)},onResize:(j,se)=>{k&&it({type:"pane.resized",path:j,ratio:se})},onExit:(j,se)=>{k?ss({type:"terminal.exited",terminalId:j,exitCode:se}):Ro(x,{type:"terminal.exited",terminalId:j,exitCode:se})},onSnapshot:(j,se)=>{const ve={type:"terminal.updated",terminal:j,notifyCompletion:se?.notifyCompletion===!0};k?ss(ve):Ro(x,ve)},...x===null&&h?{onAuthClose:j=>h({...j,source:j?.source??"terminal-ws-1008",activeAgentId:x})}:{}},$u(x))})]}),ai?m.jsx(c5,{label:ai.label,count:ai.terminalIds.length,warning:ie,onCancel:()=>{Y(null),Zi(null)},onHide:()=>{is(ai.terminalIds,ai.workspaceId)&&Zi(null)},onDelete:()=>{const x=ai.terminalIds;Y(null),Zi(null),Al(x)}}):null,m.jsx(RA,{toast:Ln,onActivate:Ge,onDismiss:()=>Jt(null)}),m.jsx(wA,{uploads:vt,onDismiss:M,onDismissAll:J,onRetry:Fe,onCancel:je})]})]})})}function QA({agentId:e,active:t,activeServerApi:s,visitedTabKeys:r,refreshCwdOnEnter:o,draggingTab:c,mobileSplitFocus:h,mobileFocusedLeafByTabKey:f,onSelect:g,onClose:p,onCloseEditor:y,onResize:b,onExit:w,onSnapshot:S,onAuthClose:E}){const T=v.useMemo(()=>be=>U1(e,be),[e]),A=v.useMemo(()=>()=>Mt(e),[e]),O=v.useSyncExternalStore(T,A,A),L=v.useMemo(()=>Go(e),[e]),U=s??L,I=O.state,te=I.workspaces.find(be=>be.id===I.activeWorkspaceId)??I.workspaces[0],ee=te?.id??null,ue=(te?.tabs.find(be=>be.id===te.activeTabId)??te?.tabs[0])?.id??null;return!O.loaded||I.workspaces.length===0?null:m.jsx("div",{className:"workspace-server-surface","data-active":t,"aria-hidden":!t,children:I.workspaces.flatMap(be=>be.tabs.map(we=>{const ne=t&&be.id===ee&&we.id===ue,ie=Io(e,be.id,we.id),Y=uh(we.root),K=h&&Y.length>1?V1(Y,we.activeTerminalId,f[ie]):null;return!ne&&!r.has(ie)?null:m.jsx("div",{className:"workspace-tab-surface","data-active":ne,"aria-hidden":!ne,children:m.jsx(Cm,{node:we.root,terminals:I.terminals,editors:O.editors,api:U,activeTerminalId:we.activeTerminalId,visible:ne,refreshCwdOnEnter:ne&&o,tabId:we.id,dropZoneActive:ne&&c!==null,draggingTerminalId:ne?c?.terminalId??null:null,mobileFocusLeafKey:K,onSelect:g,onClose:p,onCloseEditor:y,onResize:b,onExit:w,onSnapshot:S,...E?{onAuthClose:E}:{}})},`${be.id}:${we.id}`)}))})}function JA(e){const t=ow(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 s=t5(e.key);return s?{type:"pane.direction",direction:s}:null}return null}function e5(e,t,s){switch(s.type){case"pane.direction":return AA(e,t,s.direction);case"pane.index":return LA(e,s.index);default:return null}}function t5(e){switch(e){case"ArrowLeft":return"left";case"ArrowRight":return"right";case"ArrowUp":return"up";case"ArrowDown":return"down";default:return null}}function i5(e,t,s){if(e.length===0)return null;const r=e.findIndex(c=>c.id===t);return e[((r===-1?0:r)+s+e.length)%e.length]??null}function uh(e){return e.type==="pane"?[{key:hh(e.terminalId),type:"terminal",terminalId:e.terminalId}]:e.type==="editor"?[{key:X1(e.editorId),type:"editor",editorId:e.editorId,title:e.title}]:[...uh(e.first),...uh(e.second)]}function Hm(e){return e.type==="pane"?[]:e.type==="editor"?[e.editorId]:[...Hm(e.first),...Hm(e.second)]}function V1(e,t,s){if(s&&e.some(o=>o.key===s))return s;const r=t?hh(t):null;return r&&e.some(o=>o.key===r)?r:e[0]?.key??null}function hh(e){return`terminal:${e}`}function X1(e){return`editor:${e}`}function n5(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 s5({dialog:e,activePaneCwd:t,activeWorkspaceCwd:s,onChange:r,onManualCwdChange:o,onBrowse:c,onCancel:h,onSubmit:f}){const g=e.browseRoot?.rootPath??e.cwd,p=e.browseEntries.filter(S=>S.kind==="directory"),y=e.submitStatus==="submitting";function b(S){r(E=>E&&{...E,...S})}function w(S){S&&(b({cwd:S,error:null}),c(S))}return m.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-dialog-title",onClick:h,children:m.jsxs("form",{className:"security-panel workspace-dialog",onClick:S=>S.stopPropagation(),onSubmit:S=>{S.preventDefault(),y||f()},children:[m.jsxs("header",{className:"security-panel-header",children:[m.jsx("h2",{id:"workspace-dialog-title",children:e.mode==="create"?"New Workspace":"Edit Workspace"}),m.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:h,children:"x"})]}),m.jsxs("section",{className:"workspace-dialog-body",children:[m.jsxs("label",{className:"workspace-dialog-field",children:[m.jsx("span",{children:"Name"}),m.jsx("input",{value:e.title,autoFocus:!0,disabled:y,onChange:S=>b({title:S.currentTarget.value,error:null}),placeholder:"Workspace name"})]}),m.jsxs("label",{className:"workspace-dialog-field",children:[m.jsx("span",{children:"Default cwd"}),m.jsxs("div",{className:"workspace-dialog-path-row",children:[m.jsx("input",{value:e.cwd,disabled:y,onChange:S=>o(S.currentTarget.value),placeholder:"/home/user/project"}),m.jsx("button",{type:"button",onClick:()=>{c(e.cwd)},disabled:y||!e.cwd.trim()||e.browseStatus==="loading",children:"Browse"})]})]}),m.jsxs("div",{className:"workspace-dialog-quick-actions",children:[m.jsx("button",{type:"button",onClick:()=>w(t),disabled:y||!t,children:"Use active pane"}),m.jsx("button",{type:"button",onClick:()=>w(s),disabled:y||!s,children:"Use current workspace"})]}),m.jsxs("div",{className:"workspace-dialog-browser","aria-label":"Workspace folder browser","aria-busy":e.browseStatus==="loading",children:[m.jsxs("div",{className:"workspace-dialog-browser-header",children:[m.jsx("span",{title:g,children:g||"No folder selected"}),m.jsx("button",{type:"button",onClick:()=>{c(a5(g))},disabled:y||!g||g==="/"||e.browseStatus==="loading",children:"Up"})]}),e.browseStatus==="loading"?m.jsx("div",{className:"workspace-dialog-empty",children:"Loading..."}):null,e.browseStatus!=="loading"&&p.length===0?m.jsx("div",{className:"workspace-dialog-empty",children:"No folders"}):null,e.browseStatus!=="loading"&&p.length>0?m.jsx("div",{className:"workspace-dialog-folder-list",children:p.map(S=>m.jsxs("button",{type:"button","aria-label":`Choose folder ${S.name}`,disabled:y,onClick:()=>{c(r5(g,S.path))},children:[m.jsx("span",{children:S.name}),m.jsx("small",{children:S.path})]},S.path))}):null]}),e.error?m.jsx("div",{className:"workspace-dialog-error",role:"alert",children:e.error}):null]}),m.jsxs("div",{className:"workspace-dialog-actions",children:[m.jsx("button",{type:"button",className:"secondary-button",onClick:h,children:"Cancel"}),m.jsx("button",{type:"submit",className:"primary-button",disabled:y||e.browseStatus==="loading",children:y?"Saving...":e.mode==="create"?"Create":"Save"})]})]})})}function r5(e,t){return t?t.startsWith("/")?qu(t):qu(`${e||"/"}/${t}`):qu(e)}function a5(e){const t=qu(e);if(!t||t==="/")return"/";const s=t.lastIndexOf("/");return s<=0?"/":t.slice(0,s)}function qu(e){const t=e.trim();if(!t)return"";const s=t.replace(/\/+/g,"/");return s==="/"?"/":s.endsWith("/")?s.slice(0,-1):s}function l5({onCreate:e}){return m.jsxs("div",{className:"empty-workspace",children:[m.jsx("span",{children:"No terminal is open."}),m.jsx("button",{type:"button",onClick:e,children:"New tab"})]})}function o5({workspaceId:e,active:t,disabled:s=!1,reorderable:r=!1,dragging:o=!1,dropPlacement:c=null,children:h}){const{setNodeRef:f,isOver:g}=Qm({id:`workspace-drop:${e}`,data:{kind:"workspace",workspaceId:e},disabled:s}),p=["workspace-list-item",t?"workspace-list-item--active":"",r?"workspace-list-item--reorderable":"",o?"workspace-list-item--dragging":"",c?"workspace-list-item--drop-target":"",c?`workspace-list-item--drop-${c}`:""].filter(Boolean).join(" ");return m.jsx("div",{ref:f,className:p,"data-workspace-id":e,"data-drop-over":g?"true":void 0,children:h})}function c5({label:e,count:t,warning:s,onCancel:r,onHide:o,onDelete:c}){return m.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"close-terminal-title",onClick:r,children:m.jsxs("div",{className:"security-panel terminal-delete-dialog",onClick:h=>h.stopPropagation(),children:[m.jsxs("header",{className:"security-panel-header",children:[m.jsx("h2",{id:"close-terminal-title",children:"Close Terminal"}),m.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:r,children:"x"})]}),m.jsxs("section",{className:"terminal-delete-dialog-body",children:[m.jsx("p",{children:t===1?"What should happen to this terminal?":`What should happen to these ${t} panes?`}),m.jsx("span",{children:e}),m.jsx("small",{children:"Hide keeps the shell running in this workspace. Delete destroys the underlying session."}),s?m.jsx("div",{className:"terminal-delete-warning",role:"alert",children:s}):null]}),m.jsxs("div",{className:"terminal-delete-dialog-actions",children:[m.jsx("button",{type:"button",className:"secondary-button",onClick:r,children:"Cancel"}),m.jsx("button",{type:"button",className:"secondary-button",onClick:o,children:"Hide"}),m.jsx("button",{type:"button",className:"terminal-delete-confirm",onClick:c,children:"Delete"})]})]})})}function u5({targets:e,activeLeafKey:t,terminals:s,editors:r,onSelect:o}){const[c,h]=v.useState(!1);if(e.length<=1)return null;const f=t?e.findIndex(w=>w.key===t):-1,g=f>=0?f:0,p=e[g]??e[0],y=p0(p,s,r);function b(w){const S=(g+w+e.length)%e.length,E=e[S];E&&o(E)}return m.jsxs("div",{className:"mobile-pane-switcher",role:"group","aria-label":"Pane switcher",children:[m.jsx("button",{type:"button","aria-label":"Previous pane",onClick:()=>b(-1),children:"<"}),m.jsxs("button",{type:"button",className:"mobile-pane-current","aria-label":"Open pane switcher","aria-haspopup":"dialog","aria-expanded":c,title:y,onClick:()=>h(!0),children:["Pane ",g+1,"/",e.length," | ",y]}),m.jsx("button",{type:"button","aria-label":"Next pane",onClick:()=>b(1),children:">"}),c?m.jsx("div",{className:"mobile-pane-sheet-backdrop",onClick:()=>h(!1),children:m.jsxs("section",{className:"mobile-pane-sheet",role:"dialog","aria-modal":"true","aria-label":"Pane switcher",onClick:w=>w.stopPropagation(),children:[m.jsxs("header",{children:[m.jsx("strong",{children:"Panes"}),m.jsx("button",{type:"button","aria-label":"Close pane switcher",onClick:()=>h(!1),children:"x"})]}),m.jsx("div",{className:"mobile-pane-sheet-list",children:e.map((w,S)=>{const E=p0(w,s,r),T=h5(w,s,r),A=w.key===p.key;return m.jsxs("button",{type:"button","data-active":A,onClick:()=>{o(w),h(!1)},children:[m.jsx("span",{className:"mobile-pane-sheet-index",children:S+1}),m.jsxs("span",{className:"mobile-pane-sheet-copy",children:[m.jsx("strong",{children:E}),m.jsx("small",{children:T})]}),m.jsx("span",{className:"mobile-pane-sheet-type",children:w.type})]},w.key)})})]})}):null]})}function p0(e,t,s){if(e.type==="editor")return s[e.editorId]?.title||e.title||e.editorId;const r=t[e.terminalId];return r?.title||r?.cwd||e.terminalId}function h5(e,t,s){if(e.type==="editor"){const c=s[e.editorId];return c?.path?`editor | ${c.path}`:"editor"}const r=t[e.terminalId];return r?`${r.activity==="busy"?`busy${r.currentCommand?`: ${r.currentCommand}`:""}`:r.activity==="idle"?"idle":r.status} | ${r.cwd}`:"terminal"}function d5(e){const[t,s]=v.useState(()=>f5(e));return v.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function"){s(!1);return}const r=window.matchMedia(e),o=()=>s(r.matches);return o(),typeof r.addEventListener=="function"?(r.addEventListener("change",o),()=>r.removeEventListener("change",o)):(r.addListener(o),()=>r.removeListener(o))},[e]),t}function f5(e){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(e).matches}function fn(e,t){return e===t}function p5(e){const t=e.workspaces.find(r=>r.id===e.activeWorkspaceId)??e.workspaces[0];return(t?.tabs.find(r=>r.id===t.activeTabId)??t?.tabs[0])?.id??null}function $u(e){return e??"__local__"}function Io(e,t,s){return`${$u(e)}:${t}:${s}`}class dh extends Error{constructor(){super(Z1())}}function m5(e){return e?{workspaceKey:`${d0}:${e}`}:{workspaceKey:d0}}function g5(e){const t=localStorage.getItem(e.workspaceKey);if(!t)return null;try{const s=JSON.parse(t);if(q0(s))throw new dh;const r=W0(s);return r?G1(r):null}catch(s){if(s instanceof dh)throw s;return null}}function G1(e){if(q0(e))throw new dh;const t=W0(e);return t?{savedWorkspaces:t.workspaces,savedActiveWorkspaceId:t.activeWorkspaceId}:null}function No(e,t){if(e.workspaces.length>0){localStorage.setItem(t.workspaceKey,JSON.stringify(e));return}localStorage.removeItem(t.workspaceKey)}function _5(e,t){const s=Mt(e).lastPersistedLayoutJson;if(s){localStorage.setItem(t.workspaceKey,s);return}localStorage.removeItem(t.workspaceKey)}function v5(e){return`This workspace already has ${e} hidden terminal session${e===1?"":"s"}; the limit is ${kl}. Re-open or delete hidden sessions before hiding more.`}function Z1(){return`A saved terminal layout has more than ${kl} hidden terminal sessions in one workspace. Re-open or delete hidden sessions, then save the layout again.`}function b5(e){const t=e.workspaces.find(o=>o.id===e.activeWorkspaceId)??e.workspaces[0],s=t?.tabs.find(o=>o.id===t.activeTabId)??t?.tabs[0],r=s?e.terminals[s.activeTerminalId]:void 0;return r?.status==="running"?r:null}function y5(e){return e.results.find(t=>t.status==="failed"&&t.error)?.error}function S5(e){return e.split("/").filter(Boolean).pop()??e}function w5(){try{return localStorage.getItem(Y1)==="true"}catch{return!1}}function C5(e){try{localStorage.setItem(Y1,e?"true":"false")}catch{}}function x5(e){if(!e)return"session · local";const t=Date.parse(e);if(!Number.isFinite(t))return"session · local";const s=t-Date.now();if(s<=0)return"session · expired";const r=Math.max(1,Math.floor(s/6e4));return r<60?`session · ${r}m left`:`session · ${Math.floor(r/60)}h left`}function m0({name:e}){return m.jsxs("svg",{className:"workspace-footer-icon",viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[e==="settings"?m.jsxs(m.Fragment,{children:[m.jsx("path",{d:"M4 7h9"}),m.jsx("path",{d:"M17 7h3"}),m.jsx("circle",{cx:"15",cy:"7",r:"2"}),m.jsx("path",{d:"M4 12h3"}),m.jsx("path",{d:"M11 12h9"}),m.jsx("circle",{cx:"9",cy:"12",r:"2"}),m.jsx("path",{d:"M4 17h9"}),m.jsx("path",{d:"M17 17h3"}),m.jsx("circle",{cx:"15",cy:"17",r:"2"})]}):null,e==="logout"?m.jsxs(m.Fragment,{children:[m.jsx("path",{d:"M10 6H6v12h4"}),m.jsx("path",{d:"M13 8l4 4-4 4"}),m.jsx("path",{d:"M8 12h9"})]}):null]})}function Tr(e){return e instanceof Error?e.message:"Request failed"}function E5({api:e,onDone:t}){const[s,r]=v.useState(null),[o,c]=v.useState(null),[h,f]=v.useState(""),[g,p]=v.useState(!1),[y,b]=v.useState(null),[w,S]=v.useState(null);v.useEffect(()=>{let T=!1;return e.setupTotp().then(A=>{T||(r(A.qrDataUrl),c(A.secret))}).catch(A=>{T||S(A instanceof Error?A.message:"Failed to generate QR code")}),()=>{T=!0}},[e]);async function E(T){if(T.preventDefault(),!!o){p(!0),b(null);try{await e.activateTotp({secret:o,otp:h}),t()}catch(A){b(A instanceof Error?A.message:"Verification failed")}finally{p(!1)}}}return w?m.jsx("p",{className:"form-error",children:w}):!s||!o?m.jsx("p",{className:"muted",children:"Generating authenticator setup..."}):m.jsxs("div",{className:"totp-setup",children:[m.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."}),m.jsx("div",{className:"totp-qr-container",children:m.jsx("img",{src:s,alt:"TOTP QR code",width:192,height:192})}),m.jsxs("details",{className:"totp-secret-details",children:[m.jsx("summary",{children:"Can't scan? Enter manually"}),m.jsx("p",{className:"totp-secret-text",children:o})]}),m.jsxs("form",{className:"auth-form",onSubmit:E,children:[m.jsxs("label",{children:["Verification code",m.jsx("input",{autoFocus:!0,type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:h,onChange:T=>f(T.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}),y?m.jsx("p",{className:"form-error",children:y}):null,m.jsx("button",{type:"submit",disabled:g||h.length!==6,children:"Activate 2FA"})]})]})}function k5(e){return{source:fp(e?.source)||"unknown",...typeof e?.status=="number"?{status:e.status}:{},...e?.activeAgentId!==void 0?{activeAgentId:e.activeAgentId}:{},...e?.terminalId?{terminalId:fp(e.terminalId)}:{},...e?.detail?{detail:fp(e.detail)}:{}}}function T5(e){return{invalidationSource:e.source}}function D5(e){Nn("auth.session_invalid.request",Q1(e)),!(typeof console>"u"||typeof console.warn!="function")&&(console.warn("[nterminal] session invalid requested",e),bh("session-invalid-request").catch(()=>{}))}function R5(e,t){Nn("auth.session_invalid.result",{...Q1(e),authenticated:t}),!(typeof console>"u"||typeof console.warn!="function")&&(console.warn("[nterminal] session invalid check result",{...e,authenticated:t}),bh("session-invalid-result").catch(()=>{}))}function Q1(e){return{source:e.source,...typeof e.status=="number"?{status:e.status}:{},...e.activeAgentId!==void 0?{activeAgentId:e.activeAgentId}:{},...e.terminalId?{terminalId:e.terminalId}:{},...e.detail?{detail:e.detail}:{}}}function fp(e){return e?e.replace(/[^a-zA-Z0-9_.:-]/g,"_").slice(0,96):""}function M5({api:e,serverApi:t,activeAgentId:s=null,onSelectServer:r}){const o=v.useMemo(()=>e??fh(),[e]),c=v.useMemo(()=>t??Go(null),[t]),[h,f]=v.useState(null),[g,p]=v.useState(null),y=v.useRef(null),b=v.useRef("loading");v.useEffect(()=>{let O=!1;return o.getSession().then(L=>{O||(f(L),p(null))}).catch(L=>{O||(p(ba(L)),f(null))}),()=>{O=!0}},[o]);const w=B5(h);v.useEffect(()=>{const O=b.current;Nn("auth.view",{view:w,previousView:O,authenticated:h?.authenticated??null,passwordSet:h?.passwordSet??null,totpEnabled:h?.totpEnabled??null,deviceTrusted:h?.deviceTrusted??null,currentIpWhitelisted:h?.currentIpWhitelisted??null}),O==="workspace"&&w!=="workspace"&&bh(`auth-left-workspace-${w}`).catch(()=>{}),b.current=w},[h,w]);async function S(){const O=await o.getSession();f(O),p(null)}async function E(){rp(),dp(),$S(),p(null),f(null);try{await S()}catch(O){p(ba(O))}}function T(O){const L=k5(O);if(D5(L),y.current)return y.current;const U=(async()=>{p(null);try{const I=await o.getSession(T5(L));if(R5(L,I.authenticated),f(I),I.authenticated){EN();return}rp(),dp(),$S()}catch(I){p(ba(I))}finally{y.current=null}})();return y.current=U,U}if(w==="workspace")return m.jsx(ZA,{api:o,serverApi:c,activeAgentId:s,onSelectServer:r,sessionExpiresAt:h?.expiresAt??null,onSessionInvalid:O=>{T(O)},onLogout:async()=>{rp(),dp();const O=await o.logout();f(O)}});const A={loading:"Terminal",setup_password:"Set password",setup_totp:"Set up 2FA",login:"Unlock terminal",reauth:"Verify it’s you",workspace:"Terminal"};return m.jsxs("main",{className:"auth-screen",children:[m.jsxs("div",{className:"auth-background","aria-hidden":"true",children:[m.jsx("div",{className:"auth-grid"}),m.jsx("div",{className:"auth-glow"})]}),m.jsxs("section",{className:"auth-panel","aria-busy":w==="loading",children:[m.jsxs("header",{className:"auth-header",children:[m.jsxs("div",{className:"auth-brand",children:[m.jsx(w0,{size:26}),m.jsxs("div",{children:[m.jsx(C0,{height:17}),m.jsx("p",{className:"auth-host",children:"local terminal"})]})]}),m.jsx("h1",{children:A[w]})]}),g?m.jsx("p",{className:"form-error",children:g}):null,w==="loading"?m.jsx("p",{className:"muted",children:"Checking session..."}):null,w==="loading"&&g?m.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{E()},children:"Retry"}):null,w==="setup_password"?m.jsx(N5,{api:o,onSession:O=>{f(O)}}):null,w==="setup_totp"?m.jsx(E5,{api:o,onDone:()=>{S()}}):null,w==="login"?m.jsx(A5,{api:o,session:h,onSession:f,onRefresh:S}):null,w==="reauth"?m.jsx(L5,{api:o,session:h,onSession:f,onFullLogin:()=>f(O=>O&&{...O,deviceTrusted:!1})}):null]})]})}function N5({api:e,onSession:t}){const[s,r]=v.useState(""),[o,c]=v.useState(""),[h,f]=v.useState(!1),[g,p]=v.useState(null);async function y(b){b.preventDefault(),f(!0),p(null);try{if(s!==o){p("Passwords do not match");return}t(await e.setupPassword({password:s}))}catch(w){p(ba(w))}finally{f(!1)}}return m.jsxs("form",{className:"auth-form",onSubmit:y,children:[m.jsxs("label",{children:["Password",m.jsx("input",{autoFocus:!0,value:s,onChange:b=>r(b.currentTarget.value),type:"password",minLength:8,required:!0})]}),m.jsxs("label",{children:["Confirm password",m.jsx("input",{value:o,onChange:b=>c(b.currentTarget.value),type:"password",minLength:8,required:!0})]}),g?m.jsx("p",{className:"form-error",children:g}):null,m.jsx("button",{type:"submit",disabled:h||s.length<8||o.length<8,children:"Set password"})]})}function A5({api:e,session:t,onSession:s,onRefresh:r}){const[o,c]=v.useState(""),[h,f]=v.useState(""),[g,p]=v.useState(!1),[y,b]=v.useState(!1),[w,S]=v.useState(null),E=t?.totpEnabled??!1,T=t?.currentIpWhitelisted??!1;async function A(O){O.preventDefault(),b(!0),S(null);try{s(await e.login({password:o,...E?{otp:h}:{},rememberNetwork:g}))}catch(L){S(ba(L))}finally{b(!1)}}return m.jsxs("form",{className:"auth-form",onSubmit:A,children:[m.jsxs("label",{children:["Password",m.jsx("input",{autoFocus:!0,type:"password",value:o,onChange:O=>c(O.currentTarget.value),required:!0})]}),E?m.jsxs("label",{children:["Authenticator code",m.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:h,onChange:O=>f(O.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}):null,T?null:m.jsxs("label",{className:"auth-checkbox",children:[m.jsx("input",{type:"checkbox",checked:g,onChange:O=>p(O.currentTarget.checked)}),"Remember this network (skip 2FA here next time)"]}),w?m.jsx("p",{className:"form-error",children:w}):null,m.jsxs("div",{className:"button-row",children:[m.jsx("button",{type:"submit",disabled:y||o.length===0||E&&h.length!==6,children:"Unlock"}),m.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{r()},disabled:y,children:"Refresh"})]})]})}function L5({api:e,session:t,onSession:s,onFullLogin:r}){const o=t?.currentIpWhitelisted??!1,[c,h]=v.useState(""),[f,g]=v.useState(!1),[p,y]=v.useState(!1),[b,w]=v.useState(!1),[S,E]=v.useState(!1),[T,A]=v.useState(null),O=Si.useCallback(async(U,I)=>{y(!0),A(null);try{s(await e.reauth({...U?{otp:U}:{},rememberNetwork:I}))}catch(te){A(ba(te))}finally{y(!1)}},[e,s]);v.useEffect(()=>{if(o){let U=!1;w(!0),E(!1),A(null);const I=window.setTimeout(()=>{U||E(!0)},6e3);return e.reauth({rememberNetwork:!1}).then(te=>{U||s(te)}).catch(te=>{U||(A(ba(te)),E(!0))}).finally(()=>{window.clearTimeout(I),U||w(!1)}),()=>{U=!0,window.clearTimeout(I)}}},[e,o,s]);async function L(U){U.preventDefault(),await O(c,f)}return o&&b&&!S&&!T?m.jsx("p",{className:"muted",children:"Reconnecting from a trusted network…"}):m.jsxs("form",{className:"auth-form",onSubmit:L,children:[o&&S&&!T?m.jsx("p",{className:"muted",children:"Automatic verification is taking longer than expected. You can enter a code or use password login."}):null,m.jsx("p",{className:"muted",children:"This device is remembered. Enter your authenticator code to continue."}),m.jsxs("label",{children:["Authenticator code",m.jsx("input",{autoFocus:!0,type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:c,onChange:U=>h(U.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}),m.jsxs("label",{className:"auth-checkbox",children:[m.jsx("input",{type:"checkbox",checked:f,onChange:U=>g(U.currentTarget.checked)}),"Remember this network (skip 2FA here next time)"]}),T?m.jsx("p",{className:"form-error",children:T}):null,m.jsxs("div",{className:"button-row",children:[m.jsx("button",{type:"submit",disabled:p||c.length!==6,children:"Continue"}),m.jsx("button",{type:"button",className:"secondary-button",onClick:r,disabled:p,children:"Use password instead"})]})]})}function B5(e){return e?e.passwordSet?e.authenticated&&!e.totpEnabled?"setup_totp":e.authenticated?"workspace":e.deviceTrusted&&e.totpEnabled?"reauth":"login":"setup_password":"loading"}function ba(e){return e instanceof Error?e.message:"Request failed"}const g0="NTerminal",Pm="nterminal.activeAgentId";function O5(){const[e,t]=v.useState(()=>z5()),s=v.useMemo(()=>fh(),[]),r=v.useMemo(()=>Go(e),[e]);v.useEffect(()=>{const c=()=>{const h=hA();document.title=h>0?`(${h}) ${g0}`:g0};return c(),uA(c)},[]);function o(c){j5(c),t(c)}return m.jsx(M5,{api:s,activeAgentId:e,serverApi:r,onSelectServer:o})}function z5(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Pm);return e&&e.trim()?e:null}catch{return null}}function j5(e){if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(Pm,e);return}window.localStorage.removeItem(Pm)}catch{}}const _0=["gesturestart","gesturechange","gestureend"],H5=[".workspace-list",".workspace-nav",".server-list",".terminal-tab-list",".mobile-terminal-key-bar",".upload-toast-body",".file-tree",".file-detail",".file-editor",".file-markdown-preview",".editor-markdown-preview",".settings-content",".settings-nav",".transcript-dialog-scroll",".transcript-filter-group"].join(",");function P5(e=window){if(!I5(e))return()=>{};const t={passive:!1},s=e.document;function r(c){c.cancelable&&c.preventDefault()}function o(c){if(c.defaultPrevented)return;const h=c.touches;!h||h.length===0||(h.length>1||!U5(c.target))&&r(c)}for(const c of _0)s.addEventListener(c,r,t);return s.addEventListener("touchmove",o,t),s.addEventListener("dblclick",r,t),()=>{for(const c of _0)s.removeEventListener(c,r,t);s.removeEventListener("touchmove",o,t),s.removeEventListener("dblclick",r,t)}}function U5(e){return e instanceof Element&&e.closest(H5)!==null}function I5(e){return e.navigator.maxTouchPoints>0?!0:typeof e.matchMedia=="function"&&e.matchMedia("(pointer: coarse)").matches}lk();$M();P5();Wm();cE.createRoot(document.getElementById("root")).render(m.jsx(Si.StrictMode,{children:m.jsx(O5,{})}));export{Si as R,eE as g,m as j};
55
+ (detached — click to re-open, × to delete)`;return m.jsxs("span",{className:"terminal-detached-pill",title:o,children:[m.jsx("button",{type:"button",className:"terminal-detached-pill-open","aria-label":`Re-open ${r}`,onClick:t,children:r}),m.jsx("button",{type:"button",className:"terminal-detached-pill-delete","aria-label":`Delete ${r}`,title:`Delete ${r} — this destroys the underlying shell session.`,onClick:c=>{c.stopPropagation(),s()},children:"×"})]})}function SA({terminal:e,onCancel:t,onConfirm:s}){const r=e.title||e.cwd||e.id.slice(0,8);return m.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"delete-terminal-title",onClick:t,children:m.jsxs("div",{className:"security-panel terminal-delete-dialog",onClick:o=>o.stopPropagation(),children:[m.jsxs("header",{className:"security-panel-header",children:[m.jsx("h2",{id:"delete-terminal-title",children:"Delete Terminal"}),m.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:t,children:"×"})]}),m.jsxs("section",{className:"terminal-delete-dialog-body",children:[m.jsx("p",{children:"Delete this terminal?"}),m.jsx("span",{children:r}),m.jsx("small",{children:"The shell session and scrollback will be destroyed."})]}),m.jsxs("div",{className:"terminal-delete-dialog-actions",children:[m.jsx("button",{type:"button",className:"secondary-button",onClick:t,children:"Cancel"}),m.jsx("button",{type:"button",className:"terminal-delete-confirm",onClick:s,children:"Delete"})]})]})})}function wA({uploads:e,onDismiss:t,onDismissAll:s,onRetry:r,onCancel:o}){if(e.length===0)return null;const h=e.some(g=>g.status==="failed"||g.status==="partial")?"alert":"status",f=e.filter(g=>g.status==="queued"||g.status==="uploading").length;return m.jsxs("aside",{className:`upload-toast upload-toast-${TA(e)}`,role:h,"aria-live":h==="alert"?"assertive":"polite",children:[m.jsxs("header",{className:"upload-toast-header",children:[m.jsx("strong",{children:e.length===1?Wu(e[0]):`Uploads ${f>0?`(${f} active)`:`(${e.length})`}`}),m.jsx("button",{type:"button","aria-label":"Dismiss upload status",onClick:s,children:"x"})]}),m.jsx("div",{className:"upload-toast-body upload-queue-body",children:e.map(g=>m.jsx(CA,{upload:g,compact:e.length>1,onDismiss:()=>t(g.id),onRetry:()=>r(g.id),onCancel:()=>o(g.id)},g.id))})]})}function CA({upload:e,compact:t,onDismiss:s,onRetry:r,onCancel:o}){const c="response"in e?e.response:void 0,h=e.status==="failed"||e.status==="partial",f=e.status==="queued"||e.status==="uploading";return m.jsxs("section",{className:"upload-queue-item","data-status":e.status,"aria-label":Wu(e),children:[m.jsxs("div",{className:"upload-queue-item-header",children:[m.jsx("strong",{children:Wu(e)}),m.jsxs("div",{className:"upload-queue-actions",children:[f?m.jsx("button",{type:"button",onClick:o,children:"Cancel"}):null,h?m.jsx("button",{type:"button",onClick:r,children:"Retry"}):null,m.jsx("button",{type:"button","aria-label":`Dismiss ${Wu(e)}`,onClick:s,children:"x"})]})]}),e.status==="queued"?m.jsx("p",{children:e.message??"Queued"}):null,e.status==="uploading"?m.jsx(xA,{toast:e}):null,c&&"message"in e&&e.message?m.jsx("p",{className:"upload-toast-muted",children:e.message}):null,c?m.jsx(EA,{response:c,compact:t}):null,e.status==="failed"&&!c&&e.message?m.jsx("p",{children:e.message}):null]})}function xA({toast:e}){const t=e.percent===null?DA(e.loaded):`${e.percent}%`;return m.jsxs(m.Fragment,{children:[m.jsxs("div",{className:"upload-progress-row",children:[m.jsxs("span",{children:[e.fileCount," file",e.fileCount===1?"":"s"]}),m.jsx("span",{children:t})]}),m.jsx("div",{className:"upload-progress-track","aria-hidden":"true",children:m.jsx("span",{style:{width:e.percent===null?"100%":`${e.percent}%`}})})]})}function EA({response:e,compact:t}){const s=e.results.filter(h=>h.status==="failed"),r=e.results.filter(h=>h.status==="uploaded"),o=t?3:6,c=[...s,...r].slice(0,o);return m.jsxs(m.Fragment,{children:[m.jsx("p",{className:"upload-toast-destination",children:e.destinationCwd}),c.length>0?m.jsx("ul",{className:"upload-result-list",children:c.map((h,f)=>m.jsx(kA,{result:h},`${h.relativePath}-${f}`))}):null,e.results.length>c.length?m.jsxs("p",{className:"upload-toast-muted",children:["+",e.results.length-c.length," more"]}):null]})}function kA({result:e}){const t=e.savedRelativePath??e.relativePath,s=e.status==="uploaded"&&e.savedRelativePath!==void 0&&e.savedRelativePath!==e.relativePath;return m.jsxs("li",{"data-status":e.status,children:[m.jsx("span",{className:"upload-result-path",children:t}),s?m.jsx("span",{className:"upload-result-renamed",children:"renamed"}):null,e.status==="failed"&&e.error?m.jsx("span",{className:"upload-result-error",children:e.error}):null]})}function Wu(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,s=(e.response?.uploaded??0)+(e.response?.failed??0)||e.fileCount;return`Uploaded ${t} of ${s} files`}return"Upload failed"}function TA(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 DA(e){return e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${Math.round(e/(1024*1024))} MB`}function RA({toast:e,onActivate:t,onDismiss:s}){if(!e)return null;const r=e,o=r.commandName?`${r.commandName} finished`:"Command finished";function c(f){f.stopPropagation(),s()}function h(f){f.target===f.currentTarget&&(f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),t(r)))}return m.jsxs("aside",{className:"completion-toast",role:"status","aria-live":"polite",tabIndex:0,onClick:()=>t(r),onKeyDown:h,children:[m.jsxs("header",{className:"completion-toast-header",children:[m.jsxs("div",{className:"completion-toast-copy",children:[m.jsx("strong",{children:r.tabTitle}),m.jsx("span",{children:o})]}),m.jsx("button",{type:"button","aria-label":"Dismiss completion alert",onClick:c,onPointerDown:f=>f.stopPropagation(),children:"x"})]}),m.jsx("video",{className:"completion-toast-character",src:r.assetSrc,muted:!0,autoPlay:!0,loop:!0,playsInline:!0,"aria-hidden":"true"})]})}const MA=Uo(0,0,1,1),Ys=1e-6;function NA(e){return I1(e).map(t=>t.terminalId)}function I1(e){return Po(e,MA).sort(OA).map((t,s)=>({...t,index:s+1}))}function AA(e,t,s){const r=I1(e),o=r.find(h=>h.terminalId===t);return o?r.filter(h=>h.terminalId!==t).map(h=>BA(o,h,s)).filter(h=>h!==null).sort(zA)[0]?.entry.terminalId??null:null}function LA(e,t){return!Number.isInteger(t)||t<1?null:NA(e)[t-1]??null}function Po(e,t){if(e.type==="pane")return[{terminalId:e.terminalId,bounds:t}];if(e.type==="editor")return[];const s=jA(e.ratio);if(e.direction==="vertical"){const o=t.left+(t.right-t.left)*s;return[...Po(e.first,Uo(t.left,t.top,o,t.bottom)),...Po(e.second,Uo(o,t.top,t.right,t.bottom))]}const r=t.top+(t.bottom-t.top)*s;return[...Po(e.first,Uo(t.left,t.top,t.right,r)),...Po(e.second,Uo(t.left,r,t.right,t.bottom))]}function BA(e,t,s){const r=e.bounds,o=t.bounds,c=u0(r.left,r.right,o.left,o.right),h=u0(r.top,r.bottom,o.top,o.bottom);switch(s){case"left":return o.centerX>=r.centerX-Ys||h<=Ys?null:{entry:t,primaryDistance:Math.max(0,r.left-o.right),perpendicularDistance:Math.abs(r.centerY-o.centerY),overlap:h};case"right":return o.centerX<=r.centerX+Ys||h<=Ys?null:{entry:t,primaryDistance:Math.max(0,o.left-r.right),perpendicularDistance:Math.abs(r.centerY-o.centerY),overlap:h};case"up":return o.centerY>=r.centerY-Ys||c<=Ys?null:{entry:t,primaryDistance:Math.max(0,r.top-o.bottom),perpendicularDistance:Math.abs(r.centerX-o.centerX),overlap:c};case"down":return o.centerY<=r.centerY+Ys||c<=Ys?null:{entry:t,primaryDistance:Math.max(0,o.top-r.bottom),perpendicularDistance:Math.abs(r.centerX-o.centerX),overlap:c};default:return null}}function OA(e,t){return ml(e.bounds.top,t.bounds.top)||ml(e.bounds.left,t.bounds.left)}function zA(e,t){return ml(e.primaryDistance,t.primaryDistance)||ml(e.perpendicularDistance,t.perpendicularDistance)||ml(t.overlap,e.overlap)||ml(e.entry.index,t.entry.index)}function ml(e,t){const s=e-t;return Math.abs(s)<=Ys?0:s}function u0(e,t,s,r){return Math.max(0,Math.min(t,r)-Math.max(e,s))}function Uo(e,t,s,r){return{left:e,top:t,right:s,bottom:r,centerX:e+(s-e)/2,centerY:t+(r-t)/2}}function jA(e){return Number.isFinite(e)?Math.min(.9,Math.max(.1,e)):.5}class HA extends Error{constructor(t){super(t),this.name="UploadDropError"}}function h0(e){return e?Array.from(e.types??[]).includes("Files")||q1(e.items).some(s=>s.kind==="file")?!0:$1(e.files).length>0:!1}async function PA(e){const t=q1(e.items).filter(s=>s.kind==="file");return t.length>0?UA(t):IA(e.files)}async function UA(e){const t=[];for(const s of e){const r=qA(s);if(r){await K1(r,"",t);continue}const o=s.getAsFile();if(o){t.push({relativePath:F1(o),file:o});continue}throw new HA("Folder upload is not supported by this browser.")}return t}function IA(e){return $1(e).map(t=>({relativePath:F1(t),file:t}))}async function K1(e,t,s){const r=YA(t,e.name);if(e.isFile){const h=await KA(e);s.push({relativePath:r,file:h});return}if(!e.isDirectory)return;const o=e.createReader(),c=await FA(o);for(const h of c)await K1(h,r,s)}function KA(e){return new Promise((t,s)=>{e.file(t,r=>s(r))})}async function FA(e){const t=[];for(;;){const s=await WA(e);if(s.length===0)return t;t.push(...s)}}function WA(e){return new Promise((t,s)=>{e.readEntries(t,r=>s(r))})}function F1(e){const t=e.webkitRelativePath;return W1(typeof t=="string"&&t?t:e.name)}function qA(e){const t=e.webkitGetAsEntry?.();return $A(t)?t:null}function $A(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 YA(e,t){return W1(e?`${e}/${t}`:t)}function W1(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").split("/").filter(Boolean).join("/")}function q1(e){return e?Array.from(e):[]}function $1(e){return e?Array.from(e):[]}const d0="nterminal.terminalWorkspaces.v2",Y1="nterminal.sidebarCollapsed.v1",VA=75,f0=$0.map(e=>e.url),XA=$0[0].url,GA=6;function ZA({api:e,serverApi:t,activeAgentId:s=null,onSelectServer:r,sessionExpiresAt:o=null,onLogout:c=async()=>{},onSessionInvalid:h}){const f=v.useMemo(()=>e??fh(),[e]),g=v.useMemo(()=>t??Go(null),[t]),p=v.useMemo(()=>m5(s),[s]),y=v.useMemo(()=>x=>U1(s,x),[s]),b=v.useMemo(()=>()=>Mt(s),[s]),w=v.useSyncExternalStore(y,b,b),S=w.state,E=w.editors,T=!w.loaded,A=w.error,[O,L]=v.useState(!1),[U,I]=v.useState(()=>w5()),[te,ee]=v.useState("servers"),[ae,ue]=v.useState(!1),be=v.useSyncExternalStore(Gk,Uy,Uy);v.useSyncExternalStore(ug,Py,Py);const[we,ne]=v.useState(0),[ie,Y]=v.useState(null),[K,re]=v.useState(()=>[null]),[B,$]=v.useState(0),[D,X]=v.useState(()=>[s]),[_e,R]=v.useState(()=>new Set),[H,Q]=v.useState({}),[de,ke]=v.useState(null),xe=v.useRef(0),Re=v.useRef(0),[Xe,ge]=v.useState(null),[G,ce]=v.useState(null),Ce=v.useRef(null),ye=v.useRef(0),De=v.useRef(null),Be=v.useRef(null),Ke=v.useRef(null),[le,Ee]=v.useState(null),Le=RE(Sy(H0,{activationConstraint:{distance:8}}),Sy(P0,{activationConstraint:{delay:250,tolerance:5}}));v.useEffect(()=>Zk(f),[f]);function Oe(x){const k=x.active.data.current;if(k){if(k.kind==="tab"&&typeof k.tabId=="string"&&typeof k.terminalId=="string"){Ee({tabId:k.tabId,terminalId:k.terminalId});return}k.kind==="pane"&&typeof k.sourceTabId=="string"&&typeof k.terminalId=="string"&&Ee({tabId:k.sourceTabId,terminalId:k.terminalId})}}function He(x){Ee(null);const k=x.active.data.current,j=x.over?.data.current;if(!(!k||!j||typeof k.terminalId!="string")){if(k.kind==="tab"&&typeof k.tabId=="string"){if(j.kind==="tab-position"&&typeof j.index=="number"){it({type:"tab.reordered",sourceTabId:k.tabId,targetIndex:j.index});return}if(j.kind==="workspace"&&typeof j.workspaceId=="string"){it({type:"tab.moved_to_workspace",sourceTabId:k.tabId,targetWorkspaceId:j.workspaceId});return}j.kind==="pane-zone"&&typeof j.terminalId=="string"&&(j.side==="top"||j.side==="right"||j.side==="bottom"||j.side==="left")&&it({type:"tab.dropped_into_pane",sourceTabId:k.tabId,sourceTerminalId:k.terminalId,targetTerminalId:j.terminalId,side:j.side});return}if(k.kind==="pane"&&typeof k.sourceTabId=="string"){if(j.kind==="tab-position"&&typeof j.index=="number"){it({type:"terminal.extracted_to_tab",sourceTabId:k.sourceTabId,sourceTerminalId:k.terminalId,targetIndex:j.index});return}if(j.kind==="workspace"&&typeof j.workspaceId=="string"){it({type:"terminal.extracted_to_workspace",sourceTabId:k.sourceTabId,sourceTerminalId:k.terminalId,targetWorkspaceId:j.workspaceId});return}j.kind==="pane-zone"&&typeof j.terminalId=="string"&&(j.side==="top"||j.side==="right"||j.side==="bottom"||j.side==="left")&&it({type:"tab.dropped_into_pane",sourceTabId:k.sourceTabId,sourceTerminalId:k.terminalId,targetTerminalId:j.terminalId,side:j.side})}}}function _t(){Ee(null)}const Ye=S.workspaces.find(x=>x.id===S.activeWorkspaceId)??S.workspaces[0],rt=Ye?.tabs.find(x=>x.id===Ye.activeTabId)??Ye?.tabs[0],Oi=rt?.activeTerminalId??null,$i=Oi?S.terminals[Oi]:void 0,Ci=d5("(max-width: 760px)"),ri=v.useMemo(()=>rt?uh(rt.root):[],[rt]),zi=Ye&&rt?Io(s,Ye.id,rt.id):null,sn=rt?V1(ri,rt.activeTerminalId,zi?H[zi]:void 0):null,F=Ci&&ri.length>1,qe=v.useMemo(()=>(Ye?.detachedTerminalIds??[]).flatMap(x=>{const k=S.terminals[x];return k?[k]:[]}),[Ye?.detachedTerminalIds,S.terminals]),dt=v.useMemo(()=>{const x=new Set;for(const k of Ye?.tabs??[])rc(k).some(j=>w.unreadCompletions.has(j))&&x.add(k.id);return x},[Ye?.tabs,w.unreadCompletions]),[vt,pi]=v.useState([]),St=v.useRef([]),mn=v.useRef(null),[Ln,Jt]=v.useState(null),[ai,Zi]=v.useState(null),[gt,Tt]=v.useState([]),[Dt,mi]=v.useState(()=>ya()),gi=v.useRef(0),Ut=v.useRef(s),ei=v.useRef(f0),ji=v.useRef(Dt),Lt=v.useRef(()=>{});Lt.current=Wr;const xi=v.useCallback(async()=>{try{const x=await f.listNotificationAssets();Tt(x.assets.filter(k=>k.enabled).map(k=>k.url))}catch{Tt([])}},[f]);v.useEffect(()=>{X(x=>x.some(k=>fn(k,s))?x:[...x,s])},[s]);const It=v.useCallback(x=>{const k=Mt(x),j=Go(x);for(const se of Object.keys(k.state.terminals))Ho(j.createWebSocketUrl(se)),Nu(se);pA(x),X(se=>se.filter(ve=>!fn(ve,x))),R(se=>{const ve=`${$u(x)}:`;let me=!1;const Se=new Set;for(const Pe of se){if(Pe.startsWith(ve)){me=!0;continue}Se.add(Pe)}return me?Se:se}),Q(se=>{const ve=`${$u(x)}:`;let me=!1;const Se={};for(const[Pe,nt]of Object.entries(se)){if(Pe.startsWith(ve)){me=!0;continue}Se[Pe]=nt}return me?Se:se})},[]);v.useEffect(()=>{let x=!1;return f.listAgents().then(k=>{if(!x){const j=k.agents.map(ve=>ve.id),se=[null,...j];s!==null&&!j.includes(s)&&(It(s),r?.(null)),re(se)}}).catch(()=>{}),()=>{x=!0}},[s,f,It,r,B]);const Yi=v.useCallback(x=>{It(x),$(k=>k+1),fn(x,Ut.current)&&r?.(null)},[It,r]);v.useEffect(()=>{re(x=>x.some(k=>fn(k,s))?x:[...x,s])},[s]),v.useEffect(()=>{Ut.current=s},[s]),v.useEffect(()=>{Y(null)},[s]),v.useEffect(()=>{const x=De.current;if(!x)return;if(!fn(x.agentId,s)){De.current=null;return}if(!w.loaded||S.workspaces.length===0)return;De.current=null;const k=x.edge==="first"?S.workspaces[0]:S.workspaces[S.workspaces.length-1];k&&k.id!==S.activeWorkspaceId&&it({type:"workspace.selected",workspaceId:k.id})},[s,w.loaded,S.activeWorkspaceId,S.workspaces]),v.useEffect(()=>{const x=Be.current;if(x){if(!fn(x.agentId,s)){Be.current=null;return}w.loaded&&(Be.current=null,S.workspaces.some(k=>k.id===x.workspaceId)&&it({type:"workspace.selected",workspaceId:x.workspaceId}))}},[s,w.loaded,S.workspaces]),v.useEffect(()=>{const x=Ke.current;if(x){if(!fn(x.agentId,s)){Ke.current=null;return}w.loaded&&(Ke.current=null,w.error||gn())}},[s,w.error,w.loaded]),v.useEffect(()=>{xi()},[xi]),v.useEffect(()=>ew(()=>mi(ya())),[]),v.useEffect(()=>{const x=k=>{Lt.current(k)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[]),v.useEffect(()=>{ei.current=gt.length>0?gt:f0},[gt]),v.useEffect(()=>{ji.current=Dt},[Dt]),v.useEffect(()=>{if(!w.loaded||!Ye||!rt)return;const x=Io(s,Ye.id,rt.id);R(k=>{if(k.has(x))return k;const j=new Set(k);return j.add(x),j})},[s,w.loaded,Ye?.id,rt?.id]),v.useEffect(()=>()=>{li()},[]),v.useEffect(()=>lA(x=>{const k=Mt(x.agentId).state,j=k.workspaces.flatMap(Se=>Se.tabs).find(Se=>Se.id===x.tabId),se=k.terminals[x.terminalId],ve=j?.title?.trim()||se?.title||x.commandName||"terminal",me=document.visibilityState==="visible"&&fn(x.agentId,Ut.current)&&x.tabId===p5(k);if(me||Mk({tabTitle:ve,commandName:x.commandName,terminalId:x.terminalId}),!me&&document.visibilityState==="visible"&&ji.current.enabled){const Se=gi.current+1;gi.current=Se;const Pe=ei.current;Jt({id:Se,agentId:x.agentId,terminalId:x.terminalId,tabId:x.tabId,tabTitle:ve,commandName:x.commandName,assetSrc:Pe[Math.floor(Math.random()*Pe.length)]??XA})}}),[]),v.useEffect(()=>{if(!Ln||Dt.persistUntilDismissed)return;const x=window.setTimeout(()=>{Jt(k=>k?.id===Ln.id?null:k)},Dt.durationSeconds*1e3);return()=>window.clearTimeout(x)},[Ln,Dt]),v.useEffect(()=>{C5(U),U&&an()},[U]),v.useEffect(()=>{let x=!1;async function k(){if(!Mt(s).loaded){kr(s,!1,null);try{let se=null,ve=null;try{se=g5(p)}catch(nt){if(!(nt instanceof dh))throw nt;ve=nt}const[me,Se]=await Promise.all([g.listTerminals(),g.getTerminalLayout()]),Pe=me.terminals.length>0?me.terminals:[(await g.createTerminal({cols:80,rows:24})).terminal];if(!x){const nt=Se.layout?G1(Se.layout):null;if(!nt&&ve)throw ve;const Vt=nt??se??{},ti=km(Pe,void 0,Vt.savedWorkspaces,Vt.savedActiveWorkspaceId),Aa=up(ti);o0(s,ti),Mo(s,Se.revision,JSON.stringify(Aa)),kr(s,!0,null),!nt&&se&&wt(Aa,{baseRevision:Se.revision})}}catch(se){!x&&!Ts(se)&&kr(s,!0,Tr(se))}}}return k(),()=>{x=!0}},[s,g,we]);function rn(){kr(s,!1,null),ne(x=>x+1)}function an(){xe.current+=1,Re.current+=1,ke(null)}function Qi(x){xe.current+=1,Re.current+=1,ke(k=>k&&{...k,cwd:x,browseRoot:null,browseEntries:[],browseStatus:"idle",submitStatus:"idle",error:null})}function gn(){xe.current+=1,Re.current+=1;const x=S.workspaces.length+1,k=Ei();ke({mode:"create",workspaceId:null,title:`Workspace ${x}`,cwd:k,browseRoot:null,browseEntries:[],browseStatus:"idle",submitStatus:"idle",error:null}),k&&Bn(k)}function Hi(x){if(fn(x,s)){gn();return}Ke.current={agentId:x},r?.(x)}function Kt(x){if(U&&!O)return;const k=S.workspaces.find(se=>se.id===x);if(!k)return;xe.current+=1,Re.current+=1;const j=k.defaultCwd??$i?.cwd??"";ke({mode:"edit",workspaceId:x,title:k.title,cwd:j,browseRoot:null,browseEntries:[],browseStatus:"idle",submitStatus:"idle",error:null}),j&&Bn(j)}function Ei(){return Ye?.defaultCwd??$i?.cwd??""}async function Bn(x){const k=xe.current+1;xe.current=k;const j=x.trim();if(ke(se=>se&&{...se,cwd:x,browseStatus:j?"loading":"idle",browseRoot:null,browseEntries:[],error:j?null:"Choose a default working directory."}),!!j)try{const se=await g.createFileRoot({path:j}),ve=await g.listFiles({rootToken:se.rootToken,path:""});if(xe.current!==k)return;ke(me=>me&&{...me,cwd:se.rootPath,browseRoot:{rootToken:se.rootToken,rootPath:se.rootPath},browseEntries:ve.entries.filter(Se=>Se.kind==="directory"),browseStatus:"idle",error:null})}catch(se){if(xe.current!==k)return;ke(ve=>ve&&{...ve,browseStatus:"idle",error:Tr(se)})}}async function ks(){const x=de;if(!x)return;const k=x.title.trim(),j=x.cwd.trim();if(!k||!j){ke({...x,submitStatus:"idle",error:k?"Choose a default working directory.":"Workspace name is required."});return}const se=Re.current+1;Re.current=se,ke({...x,submitStatus:"submitting",error:null});try{const ve=await g.createFileRoot({path:j});if(Re.current!==se)return;if(x.mode==="create"){const me=S.workspaces.length+1;it({type:"workspace.created",workspaceId:`workspace-${Date.now().toString(36)}-${me}`,title:k,defaultCwd:ve.rootPath})}else x.workspaceId&&(it({type:"workspace.renamed",workspaceId:x.workspaceId,title:k}),it({type:"workspace.defaultCwdChanged",workspaceId:x.workspaceId,defaultCwd:ve.rootPath}));ke(null)}catch(ve){if(Re.current!==se)return;ke(me=>me&&{...me,submitStatus:"idle",error:Tr(ve)})}}function Nl(x){Re.current+=1,ke(x)}function Da(x,k,j){if(x===k)return;const se=S.workspaces.some(me=>me.id===x),ve=S.workspaces.some(me=>me.id===k);!se||!ve||it({type:"workspace.reordered",sourceWorkspaceId:x,targetWorkspaceId:k,placement:j})}function Qn(x,k){const j=S.workspaces.findIndex(ve=>ve.id===x),se=S.workspaces[j+k];j<0||!se||Da(x,se.id,k<0?"before":"after")}function Jn(x,k){k.pointerType==="mouse"&&k.button!==0||(k.preventDefault(),k.stopPropagation(),Ce.current={sourceId:x,pointerId:k.pointerId,startX:k.clientX,startY:k.clientY,active:!1,targetId:null,placement:"after"},k.currentTarget.setPointerCapture?.(k.pointerId))}function fs(x){const k=Ce.current;if(!k||k.pointerId!==x.pointerId)return;const j=Math.hypot(x.clientX-k.startX,x.clientY-k.startY);if(!k.active){if(j<GA)return;k.active=!0,ge(k.sourceId)}const ve=document.elementFromPoint(x.clientX,x.clientY)?.closest("[data-workspace-id]"),me=ve?.dataset.workspaceId??null;if(!ve||!me||me===k.sourceId||!S.workspaces.some(nt=>nt.id===me)){k.targetId=null,ce(null);return}const Se=ve.getBoundingClientRect(),Pe=x.clientY<Se.top+Se.height/2?"before":"after";k.targetId=me,k.placement=Pe,ce({workspaceId:me,placement:Pe})}function At(x){const k=Ce.current;!k||k.pointerId!==x.pointerId||(x.preventDefault(),x.stopPropagation(),x.currentTarget.releasePointerCapture?.(x.pointerId),Ce.current=null,ge(null),ce(null),k.active&&k.targetId&&Da(k.sourceId,k.targetId,k.placement))}function es(x){const k=Ce.current;k&&k.pointerId===x.pointerId&&x.currentTarget.releasePointerCapture?.(x.pointerId),Ce.current=null,ge(null),ce(null)}async function ts(){await Yt(async()=>{const x=Ye?.defaultCwd?{cols:80,rows:24,cwd:Ye.defaultCwd}:{cols:80,rows:24},k=await g.createTerminal(x);it({type:"terminal.created",terminal:k.terminal})})}async function Vi(x){await Yt(async()=>{const k=Oi?{parentTerminalId:Oi,cols:80,rows:24}:Ye?.defaultCwd?{cols:80,rows:24,cwd:Ye.defaultCwd}:{cols:80,rows:24},j=await g.createTerminal(k);it({type:"terminal.split",terminal:j.terminal,direction:x})})}async function ot(x){let k=Oi,j=zi;const se=Ye?.defaultCwd?.trim();if(!k&&!se)throw new Error("No active pane is available.");const ve=await g.readFile(x);if(!k&&se){const Pe=await g.createTerminal({cols:80,rows:24,cwd:se});k=Pe.terminal.id,it({type:"terminal.created",terminal:Pe.terminal})}if(k){it({type:"pane.selected",terminalId:k});const Pe=Mt(s).state,nt=Pe.workspaces.find(ti=>ti.id===Pe.activeWorkspaceId)??Pe.workspaces[0],Vt=nt?.tabs.find(ti=>ti.id===nt.activeTabId)??nt?.tabs[0];j=nt&&Vt?Io(s,nt.id,Vt.id):null}const me=`editor-${Date.now().toString(36)}-${fA(s)}`,Se=S5(ve.path);hp(s,Pe=>({...Pe,[me]:{id:me,title:Se,rootToken:x.rootToken,path:ve.path,read:ve}})),j&&Q(Pe=>({...Pe,[j]:X1(me)})),it({type:"editor.split",editorId:me,title:Se,direction:"vertical"})}function Ra(x){hp(s,k=>{const j={...k};return delete j[x],j}),it({type:"editor.closed",editorId:x})}function Ur(x){_n([x])}function _n(x){const k=[...new Set(x)].filter(se=>S.terminals[se]);if(k.length===0)return;const j=k.length===1?S.terminals[k[0]]?.title||S.terminals[k[0]]?.cwd||k[0]:`${k.length} panes`;Y(null),Zi({terminalIds:k,label:j,workspaceId:Ye?.id??S.activeWorkspaceId??null})}function is(x,k){const j=rs(x,k);if(!j)return!1;const se=x.filter(ve=>!j.detachedTerminalIds.includes(ve));if(j.detachedTerminalIds.length+se.length>kl)return Y(v5(j.detachedTerminalIds.length)),!1;Y(null);for(const ve of x)it(j.id?{type:"terminal.detached",terminalId:ve,workspaceId:j.id}:{type:"terminal.detached",terminalId:ve});return!0}async function Al(x){await Yt(async()=>{for(const k of x)await ns(k),Ho(g.createWebSocketUrl(k)),Nu(k),it({type:"terminal.closed",terminalId:k})})}async function Ir(x){const k=S.workspaces.find(j=>j.id===x);!k||S.workspaces.length<=1||window.confirm(`Delete workspace "${k.title}" and close all terminal sessions inside it? This cannot be undone.`)&&await Yt(async()=>{const j=ch(k),se=[];let ve=null;for(const Se of j)try{await ns(Se)}catch(Pe){se.push(Tr(Pe)),Pe instanceof us&&Pe.status===401&&!g.isAgent&&(ve=Pe)}finally{Ho(g.createWebSocketUrl(Se)),Nu(Se)}const me=k.tabs.flatMap(Se=>Hm(Se.root));if(me.length>0){const Se=new Set(me);hp(s,Pe=>{const nt={...Pe};for(const Vt of Se)delete nt[Vt];return nt})}if(it({type:"workspace.closed",workspaceId:x}),ve)throw ve;if(se.length>0)throw new Error(`Workspace was removed, but ${se.length} terminal session${se.length===1?"":"s"} may still be running. ${se[0]}`)})}async function On(x){await Yt(async()=>{await ns(x),Ho(g.createWebSocketUrl(x)),Nu(x),it({type:"terminal.closed",terminalId:x})})}async function Kr(x,k){const j=k.trim();if(!j)return;let se=null;for(const ve of S.workspaces){const me=ve.tabs.find(Se=>Se.id===x);if(me){se=me.activeTerminalId;break}}if(it({type:"tab.renamed",tabId:x,title:j}),!!se)try{const ve=await g.renameTerminal(se,j);ss({type:"terminal.updated",terminal:ve.terminal})}catch(ve){kr(s,!0,Tr(ve))}}function Qs(x){const k=S.terminals[x];k&&it({type:"terminal.created",terminal:k})}async function ns(x){try{await g.closeTerminal(x)}catch(k){if(k instanceof us&&k.status===404)return;throw k}}async function vn(){await Yt(async()=>{await c()})}async function Yt(x){kr(s,!0,null);try{await x()}catch(k){if(Ts(k))return;kr(s,!0,Tr(k))}}function Ts(x){return x instanceof us&&x.status===401&&!g.isAgent&&h?(h({source:"workspace-api-401",status:401,activeAgentId:s}),!0):!1}function it(x){Ro(s,x);const k=Mt(s),j=k.state;if(!k.loaded||j.workspaces.length===0)return;const se=up(j);JSON.stringify(se)!==k.lastPersistedLayoutJson&&Ft(se)}function ss(x){Ro(s,x)}function Fr(x,k,j,se){const ve=Io(x,k,j);Q(me=>({...me,[ve]:se}))}function ps(x){zi&&Q(k=>({...k,[zi]:x}))}function Ma(x,k){const j=hh(x);k?Fr(s,k.workspaceId,k.tabId,j):ps(j),it({type:"pane.selected",terminalId:x})}function Pi(x){ps(x.key),x.type==="terminal"&&it({type:"pane.selected",terminalId:x.terminalId})}function Wr(x){if(ae||ai||x.isComposing||x.key==="Process"||n5(x.target))return;const k=JA(x);if(!k)return;if(x.preventDefault(),x.stopPropagation(),k.type==="server.previous"||k.type==="server.next"){$r(k.type==="server.next"?1:-1);return}const j=Mt(s).state,se=j.workspaces.find(Se=>Se.id===j.activeWorkspaceId)??j.workspaces[0],ve=se?.tabs.find(Se=>Se.id===se.activeTabId)??se?.tabs[0];if(k.type==="split"){if(!ve)return;Vi(k.direction);return}if(!se||!ve)return;if(k.type==="tab.previous"||k.type==="tab.next"){const Se=i5(se.tabs,ve.id,k.type==="tab.next"?1:-1);Se&&it({type:"tab.selected",tabId:Se.id});return}if(k.type==="tab.index"){const Se=se.tabs[k.index-1];Se&&it({type:"tab.selected",tabId:Se.id});return}const me=e5(ve.root,ve.activeTerminalId,k);me&&Ma(me,{workspaceId:se.id,tabId:ve.id})}function qr(x,k){if(!r||K.length===0)return;const j=K.findIndex(Se=>fn(Se,s)),ve=((j===-1?0:j)+x+K.length)%K.length,me=K[ve]??null;fn(me,s)||(k&&(De.current={agentId:me,edge:k}),r(me))}function $r(x){const k=Mt(s).state,j=k.workspaces;if(j.length===0){qr(x,x===1?"first":"last");return}const se=j.findIndex(Se=>Se.id===k.activeWorkspaceId),me=(se===-1?0:se)+x;if(me>=0&&me<j.length){it({type:"workspace.selected",workspaceId:j[me].id});return}qr(x,x===1?"first":"last")}function zn(x,k){if(fn(x,s)){it({type:"workspace.selected",workspaceId:k});return}Be.current={agentId:x,workspaceId:k},r?.(x)}function rs(x,k){if(k)return S.workspaces.find(j=>j.id===k)??null;for(const j of x){const se=S.workspaces.find(me=>me.tabs.some(Se=>rc(Se).includes(j)));if(se)return se;const ve=S.workspaces.find(me=>me.detachedTerminalIds.includes(j));if(ve)return ve}return S.workspaces.find(j=>j.id===S.activeWorkspaceId)??S.workspaces[0]??null}function Na(x){h0(x.dataTransfer)&&(x.preventDefault(),x.dataTransfer.dropEffect="copy")}function ms(x){if(!h0(x.dataTransfer))return;x.preventDefault();const k=b5(Mt(s).state),j=ye.current+1;if(ye.current=j,!k){Js({id:j,status:"failed",fileCount:0,message:"No active running terminal is available for upload."});return}Js({id:j,status:"queued",fileCount:0,terminalId:k.id,message:"Preparing upload..."}),Ll(j,k.id,x.dataTransfer)}async function Ll(x,k,j){try{const se=await PA(j);if(se.length===0)throw new Error("No files were found in the drop.");yn(x,{id:x,status:"queued",fileCount:se.length,message:"Queued"},{terminalId:k,files:se})}catch(se){yn(x,{id:x,status:"failed",fileCount:0,message:Tr(se)},{terminalId:k})}finally{Ds()}}async function bn(x){const k=St.current.find(me=>me.id===x);if(!k?.terminalId||!k.files||k.files.length===0)return;const j=k.terminalId,se=k.files,ve=new AbortController;mn.current=x,yn(x,{id:x,status:"uploading",fileCount:se.length,loaded:0,total:null,percent:null},{terminalId:j,files:se,abortController:ve});try{const me=await hT({terminalId:j,files:se,signal:ve.signal,onProgress:Vt=>{yn(x,{id:x,status:"uploading",fileCount:se.length,loaded:Vt.loaded,total:Vt.total,percent:Vt.percent},{terminalId:j,files:se,abortController:ve})}}),Se=me.failed>0?me.uploaded>0?"partial":"failed":"success",Pe=me.failed>0?y5(me):void 0,nt={id:x,status:Se,fileCount:se.length,response:me};Pe&&(nt.message=Pe),yn(x,nt,{terminalId:j,files:se})}catch(me){yn(x,{id:x,status:"failed",fileCount:se.length,message:ve.signal.aborted?"Upload canceled.":Tr(me)},{terminalId:j,files:se})}finally{mn.current===x&&(mn.current=null),Ds()}}function Ds(){if(mn.current!==null)return;const x=St.current.find(k=>k.status==="queued");x?.terminalId&&x.files&&x.files.length>0&&bn(x.id)}function Js(x){er(k=>[...k,x])}function yn(x,k,j={}){er(se=>se.map(ve=>{if(ve.id!==x)return ve;const me={...k},Se=j.terminalId??ve.terminalId,Pe=j.files??ve.files;return Se!==void 0&&(me.terminalId=Se),Pe!==void 0&&(me.files=Pe),j.abortController!==void 0&&(me.abortController=j.abortController),me}))}function er(x){const k=x(St.current);St.current=k,pi(k)}function M(x){St.current.find(j=>j.id===x)?.abortController?.abort(),mn.current===x&&(mn.current=null),er(j=>j.filter(se=>se.id!==x)),Ds()}function J(){for(const x of St.current)x.abortController?.abort();mn.current=null,er(()=>[])}function je(x){const k=St.current.find(j=>j.id===x);if(k){if(k.status==="queued"){M(x);return}k.abortController?.abort()}}function Fe(x){const k=St.current.find(se=>se.id===x);if(!k?.terminalId||!k.files||k.files.length===0)return;const j=Ie(k);if(j.length===0){yn(x,{id:x,status:"failed",fileCount:k.fileCount,message:"No failed files are available to retry."},{terminalId:k.terminalId,files:k.files});return}yn(x,{id:x,status:"queued",fileCount:j.length,message:"Queued"},{terminalId:k.terminalId,files:j}),Ds()}function Ie(x){const k=x.files??[],j="response"in x?x.response:void 0;if(!j)return k;const se=j.results.filter(Se=>Se.status==="failed").map(Se=>Se.relativePath);if(se.length===0)return[];const ve=new Map;for(const Se of k){const Pe=ve.get(Se.relativePath)??[];Pe.push(Se),ve.set(Se.relativePath,Pe)}const me=[];for(const Se of se){const nt=ve.get(Se)?.shift();nt&&me.push(nt)}return me}function Ge(x){const j=Mt(x.agentId).state.workspaces.find(se=>se.tabs.some(ve=>ve.id===x.tabId));j&&Fr(x.agentId,j.id,x.tabId,hh(x.terminalId)),Ro(x.agentId,{type:"pane.selected",terminalId:x.terminalId}),dA(x.agentId,x.terminalId),fn(x.agentId,s)||r?.(x.agentId),Jt(null)}function Ft(x){const k=Mt(s).mutable.saveCoord;k.pendingLayoutSave=x,No(x,p),k.saveTimer!==null&&window.clearTimeout(k.saveTimer),k.saveTimer=window.setTimeout(()=>{k.saveTimer=null;const j=k.pendingLayoutSave;k.pendingLayoutSave=null,j&&wt(j)},VA)}function li(){const x=Mt(s).mutable.saveCoord;x.saveTimer!==null&&(window.clearTimeout(x.saveTimer),x.saveTimer=null);const k=x.pendingLayoutSave;x.pendingLayoutSave=null,k&&(No(k,p),wt(k))}function wt(x,k={}){const j=Mt(s).mutable.saveCoord;j.nextPersistLayout=x,k.baseRevision!==void 0&&(j.queuedBaseRevision=k.baseRevision),!j.nextPersistQueued&&(j.nextPersistQueued=!0,j.persistChain=j.persistChain.then(async()=>{j.nextPersistQueued=!1;const se=j.nextPersistLayout,ve=j.queuedBaseRevision;j.nextPersistLayout=null,j.queuedBaseRevision=void 0,se&&await Bt(se,ve!==void 0?{baseRevision:ve}:{})}))}async function Bt(x,k={}){const j=Mt(s),se=k.baseRevision??j.layoutRevision,ve={layout:x,...typeof se=="number"?{baseRevision:se}:{}};try{const me=await g.saveTerminalLayout(ve),Se=me.layout??x;Mo(s,me.revision,JSON.stringify(Se)),No(Se,p);return}catch(me){if(me instanceof us&&me.status===400&&me.message===z2){_5(s,p),kr(s,!0,Z1());return}if(me instanceof us&&me.status===409)try{const Se=await g.getTerminalLayout(),Pe=Mt(s).mutable.saveCoord;if(Pe.nextPersistLayout||Pe.pendingLayoutSave){const nt=Se.layout?JSON.stringify(Se.layout):Mt(s).lastPersistedLayoutJson;Mo(s,Se.revision,nt);return}if(Se.layout){const nt=Mt(s).state,Vt=km(Object.values(nt.terminals),void 0,Se.layout.workspaces,Se.layout.activeWorkspaceId),ti=up(Vt);o0(s,Vt),Mo(s,Se.revision,JSON.stringify(ti)),No(ti,p)}else Mo(s,Se.revision,j.lastPersistedLayoutJson);return}catch{}No(x,p)}}const Ui=x5(o),Wt=!U||O,Sn=Wt?te:"servers";function jn(x){const k=x.active?w:Mt(x.agentId),j=x.active?S:k.state,se=x.active?w.loaded:k.loaded,ve=x.active?A:k.error;return m.jsxs("div",{className:`workspace-list-panel${x.active?" workspace-list-panel--active-server":""}`,"aria-label":`${x.label} workspaces`,children:[m.jsxs("div",{className:"workspace-list-header",children:[m.jsx("span",{children:"Workspaces"}),m.jsx("button",{type:"button","aria-label":`New workspace on ${x.label}`,title:"New workspace",onClick:()=>Hi(x.agentId),children:"+"})]}),se?ve?m.jsx("button",{type:"button",className:"workspace-list-placeholder workspace-list-placeholder--error",onClick:()=>r?.(x.agentId),children:ve}):m.jsx("div",{className:"workspace-list-items",children:j.workspaces.map(me=>{const Se=x.active&&me.id===Ye?.id,Pe=ch(me).length,nt=x.active&&j.workspaces.length>1,Vt=G?.workspaceId===me.id&&Xe!==me.id?G.placement:null;return m.jsxs(o5,{workspaceId:me.id,active:Se,disabled:!x.active,reorderable:nt,dragging:Xe===me.id,dropPlacement:Vt,children:[nt?m.jsx("button",{type:"button",className:"workspace-list-drag-handle","data-workspace-drag-handle":me.id,title:"Drag to reorder","aria-label":`Reorder ${me.title}`,"aria-grabbed":Xe===me.id,onPointerDown:ti=>Jn(me.id,ti),onPointerMove:fs,onPointerUp:At,onPointerCancel:es,onKeyDown:ti=>{(ti.key==="ArrowUp"||ti.key==="ArrowDown")&&(ti.preventDefault(),ti.stopPropagation(),Qn(me.id,ti.key==="ArrowUp"?-1:1))},onClick:ti=>ti.stopPropagation(),children:"::"}):null,m.jsxs("button",{type:"button",className:"workspace-list-select","aria-current":Se?"page":void 0,title:me.defaultCwd??void 0,onClick:()=>zn(x.agentId,me.id),onDoubleClick:()=>{x.active&&Kt(me.id)},children:[m.jsx("span",{className:"workspace-list-name",children:me.title}),m.jsxs("small",{children:[me.defaultCwd??"No folder"," · ",Pe," ",Pe===1?"session":"sessions"]})]}),x.active?m.jsxs("div",{className:"workspace-list-actions",children:[m.jsx("button",{type:"button",className:"workspace-list-edit","aria-label":`Edit ${me.title}`,title:"Edit workspace",onClick:()=>Kt(me.id),children:"..."}),m.jsx("button",{type:"button",className:"workspace-list-delete","aria-label":`Delete ${me.title}`,title:"Delete workspace",disabled:j.workspaces.length<=1,onClick:()=>{Ir(me.id)},children:"x"})]}):null]},me.id)})}):m.jsx("button",{type:"button",className:"workspace-list-placeholder",onClick:()=>r?.(x.agentId),children:"Open server to load workspaces"})]})}return m.jsx(R2,{sensors:Le,onDragStart:Oe,onDragEnd:He,onDragCancel:_t,children:m.jsxs("main",{className:"terminal-shell","data-collapsed":U,"data-sidebar-open":O,onDragOver:Na,onDrop:ms,children:[m.jsx("button",{type:"button",className:"workspace-backdrop","aria-label":"Close workspaces",onClick:()=>L(!1)}),m.jsxs("aside",{className:"workspace-sidebar",children:[m.jsxs("header",{className:"workspace-brand",children:[Wt?m.jsx(C0,{height:20}):m.jsx(w0,{size:24}),m.jsx("button",{type:"button",className:"sidebar-collapse-button","aria-label":U?"Expand sidebar":"Collapse sidebar",title:U?"Expand sidebar":"Collapse sidebar",onClick:()=>I(x=>!x),children:U?">":"<"}),m.jsx("button",{type:"button",className:"sidebar-drawer-close-button","aria-label":"Close workspaces",title:"Close workspaces",onClick:()=>L(!1),children:"x"})]}),m.jsxs("div",{className:`workspace-sidebar-content workspace-sidebar-content--${Sn==="files"?"files":"servers"}`,children:[Wt?m.jsxs("div",{className:"workspace-sidebar-tabs",role:"tablist","aria-label":"Sidebar mode",children:[m.jsx("button",{type:"button",role:"tab","aria-selected":te==="servers",onClick:()=>{ee("servers")},children:"Workspaces"}),m.jsx("button",{type:"button",role:"tab","aria-selected":te==="files",onClick:()=>{ee("files")},children:"Files"})]}):null,Sn==="servers"&&Wt?m.jsx("nav",{className:"workspace-nav","aria-label":"Workspaces",children:m.jsx(Oy,{api:f,activeAgentId:s,onSelectServer:r??(()=>{}),onSessionInvalid:h,refreshToken:B,renderServerChildren:jn})}):null,Wt?null:m.jsx("nav",{className:"workspace-nav workspace-nav--collapsed","aria-label":"Servers",children:m.jsx(Oy,{api:f,activeAgentId:s,onSelectServer:r??(()=>{}),onSessionInvalid:h,refreshToken:B,compact:!0})}),Sn==="files"?m.jsx(gT,{api:g,activeTerminalId:Oi,activeTerminalCwd:$i?.cwd??null,workspaceRootPath:Ye?.defaultCwd??$i?.cwd??null,onOpenFile:ot}):null]}),m.jsxs("div",{className:"workspace-sidebar-footer",children:[Wt?m.jsx("span",{children:Ui}):null,m.jsxs("div",{className:"workspace-sidebar-footer-actions",children:[m.jsxs("button",{type:"button",className:"workspace-footer-icon-button","aria-label":"settings",title:"Settings",onClick:()=>ue(!0),children:[m.jsx(m0,{name:"settings"}),be.hasUpdates?m.jsx("span",{className:"update-pulse-dot","aria-hidden":"true"}):null]}),Wt?m.jsx("button",{type:"button",className:"workspace-footer-icon-button","aria-label":"logout",title:"Logout",onClick:()=>{vn()},children:m.jsx(m0,{name:"logout"})}):null]})]})]}),ae?m.jsx(aT,{api:f,onClose:()=>ue(!1),updateAvailable:be.hasUpdates,onNotificationAssetsChanged:()=>{xi()},onAgentRemoved:Yi}):null,de?m.jsx(s5,{dialog:de,activePaneCwd:$i?.cwd??null,activeWorkspaceCwd:Ye?.defaultCwd??null,onChange:Nl,onManualCwdChange:Qi,onBrowse:Bn,onCancel:an,onSubmit:()=>{ks()}}):null,m.jsxs("section",{className:"terminal-main","aria-label":"Terminal workspace","data-mobile-pane-switcher":F?"true":void 0,children:[m.jsx(_A,{tabs:Ye?.tabs??[],activeTabId:Ye?.activeTabId??null,terminals:S.terminals,unreadCompletionTabIds:dt,detachedTerminals:qe,onSelectTab:x=>it({type:"tab.selected",tabId:x}),onCreateTab:()=>{ts()},onToggleWorkspaces:()=>L(x=>!x),onCloseTerminals:x=>_n(x),onReattachTerminal:x=>Qs(x),onDeleteTerminal:x=>{On(x)},onSplitVertical:()=>{Vi("vertical")},onSplitHorizontal:()=>{Vi("horizontal")},onRenameTab:(x,k)=>{Kr(x,k)},activePaneAvailable:!!Oi}),F?m.jsx(u5,{targets:ri,activeLeafKey:sn,terminals:S.terminals,editors:E,onSelect:Pi}):null,A?m.jsxs("div",{className:"workspace-error",role:"alert",children:[m.jsx("span",{children:A}),m.jsxs("div",{className:"workspace-error-actions",children:[m.jsx("button",{type:"button",onClick:rn,children:"Retry"}),s!==null&&r?m.jsx("button",{type:"button",onClick:()=>r(null),children:"Main server"}):null]})]}):null,m.jsxs("section",{className:"workspace-body","aria-busy":T,children:[T?m.jsx("div",{className:"workspace-placeholder",children:"Opening shell..."}):null,!T&&!rt?m.jsx(l5,{onCreate:()=>{ts()}}):null,D.map(x=>{const k=fn(x,s);return m.jsx(QA,{agentId:x,active:k,activeServerApi:k?g:void 0,visitedTabKeys:_e,refreshCwdOnEnter:k&&Sn==="files",draggingTab:k?le:null,mobileSplitFocus:Ci,mobileFocusedLeafByTabKey:H,onSelect:j=>{k&&Ma(j)},onClose:j=>{k&&Ur(j)},onCloseEditor:j=>{k&&Ra(j)},onResize:(j,se)=>{k&&it({type:"pane.resized",path:j,ratio:se})},onExit:(j,se)=>{k?ss({type:"terminal.exited",terminalId:j,exitCode:se}):Ro(x,{type:"terminal.exited",terminalId:j,exitCode:se})},onSnapshot:(j,se)=>{const ve={type:"terminal.updated",terminal:j,notifyCompletion:se?.notifyCompletion===!0};k?ss(ve):Ro(x,ve)},...x===null&&h?{onAuthClose:j=>h({...j,source:j?.source??"terminal-ws-1008",activeAgentId:x})}:{}},$u(x))})]}),ai?m.jsx(c5,{label:ai.label,count:ai.terminalIds.length,warning:ie,onCancel:()=>{Y(null),Zi(null)},onHide:()=>{is(ai.terminalIds,ai.workspaceId)&&Zi(null)},onDelete:()=>{const x=ai.terminalIds;Y(null),Zi(null),Al(x)}}):null,m.jsx(RA,{toast:Ln,onActivate:Ge,onDismiss:()=>Jt(null)}),m.jsx(wA,{uploads:vt,onDismiss:M,onDismissAll:J,onRetry:Fe,onCancel:je})]})]})})}function QA({agentId:e,active:t,activeServerApi:s,visitedTabKeys:r,refreshCwdOnEnter:o,draggingTab:c,mobileSplitFocus:h,mobileFocusedLeafByTabKey:f,onSelect:g,onClose:p,onCloseEditor:y,onResize:b,onExit:w,onSnapshot:S,onAuthClose:E}){const T=v.useMemo(()=>be=>U1(e,be),[e]),A=v.useMemo(()=>()=>Mt(e),[e]),O=v.useSyncExternalStore(T,A,A),L=v.useMemo(()=>Go(e),[e]),U=s??L,I=O.state,te=I.workspaces.find(be=>be.id===I.activeWorkspaceId)??I.workspaces[0],ee=te?.id??null,ue=(te?.tabs.find(be=>be.id===te.activeTabId)??te?.tabs[0])?.id??null;return!O.loaded||I.workspaces.length===0?null:m.jsx("div",{className:"workspace-server-surface","data-active":t,"aria-hidden":!t,children:I.workspaces.flatMap(be=>be.tabs.map(we=>{const ne=t&&be.id===ee&&we.id===ue,ie=Io(e,be.id,we.id),Y=uh(we.root),K=h&&Y.length>1?V1(Y,we.activeTerminalId,f[ie]):null;return!ne&&!r.has(ie)?null:m.jsx("div",{className:"workspace-tab-surface","data-active":ne,"aria-hidden":!ne,children:m.jsx(Cm,{node:we.root,terminals:I.terminals,editors:O.editors,api:U,activeTerminalId:we.activeTerminalId,visible:ne,refreshCwdOnEnter:ne&&o,tabId:we.id,dropZoneActive:ne&&c!==null,draggingTerminalId:ne?c?.terminalId??null:null,mobileFocusLeafKey:K,onSelect:g,onClose:p,onCloseEditor:y,onResize:b,onExit:w,onSnapshot:S,...E?{onAuthClose:E}:{}})},`${be.id}:${we.id}`)}))})}function JA(e){const t=ow(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 s=t5(e.key);return s?{type:"pane.direction",direction:s}:null}return null}function e5(e,t,s){switch(s.type){case"pane.direction":return AA(e,t,s.direction);case"pane.index":return LA(e,s.index);default:return null}}function t5(e){switch(e){case"ArrowLeft":return"left";case"ArrowRight":return"right";case"ArrowUp":return"up";case"ArrowDown":return"down";default:return null}}function i5(e,t,s){if(e.length===0)return null;const r=e.findIndex(c=>c.id===t);return e[((r===-1?0:r)+s+e.length)%e.length]??null}function uh(e){return e.type==="pane"?[{key:hh(e.terminalId),type:"terminal",terminalId:e.terminalId}]:e.type==="editor"?[{key:X1(e.editorId),type:"editor",editorId:e.editorId,title:e.title}]:[...uh(e.first),...uh(e.second)]}function Hm(e){return e.type==="pane"?[]:e.type==="editor"?[e.editorId]:[...Hm(e.first),...Hm(e.second)]}function V1(e,t,s){if(s&&e.some(o=>o.key===s))return s;const r=t?hh(t):null;return r&&e.some(o=>o.key===r)?r:e[0]?.key??null}function hh(e){return`terminal:${e}`}function X1(e){return`editor:${e}`}function n5(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 s5({dialog:e,activePaneCwd:t,activeWorkspaceCwd:s,onChange:r,onManualCwdChange:o,onBrowse:c,onCancel:h,onSubmit:f}){const g=e.browseRoot?.rootPath??e.cwd,p=e.browseEntries.filter(S=>S.kind==="directory"),y=e.submitStatus==="submitting";function b(S){r(E=>E&&{...E,...S})}function w(S){S&&(b({cwd:S,error:null}),c(S))}return m.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-dialog-title",onClick:h,children:m.jsxs("form",{className:"security-panel workspace-dialog",onClick:S=>S.stopPropagation(),onSubmit:S=>{S.preventDefault(),y||f()},children:[m.jsxs("header",{className:"security-panel-header",children:[m.jsx("h2",{id:"workspace-dialog-title",children:e.mode==="create"?"New Workspace":"Edit Workspace"}),m.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:h,children:"x"})]}),m.jsxs("section",{className:"workspace-dialog-body",children:[m.jsxs("label",{className:"workspace-dialog-field",children:[m.jsx("span",{children:"Name"}),m.jsx("input",{value:e.title,autoFocus:!0,disabled:y,onChange:S=>b({title:S.currentTarget.value,error:null}),placeholder:"Workspace name"})]}),m.jsxs("label",{className:"workspace-dialog-field",children:[m.jsx("span",{children:"Default cwd"}),m.jsxs("div",{className:"workspace-dialog-path-row",children:[m.jsx("input",{value:e.cwd,disabled:y,onChange:S=>o(S.currentTarget.value),placeholder:"/home/user/project"}),m.jsx("button",{type:"button",onClick:()=>{c(e.cwd)},disabled:y||!e.cwd.trim()||e.browseStatus==="loading",children:"Browse"})]})]}),m.jsxs("div",{className:"workspace-dialog-quick-actions",children:[m.jsx("button",{type:"button",onClick:()=>w(t),disabled:y||!t,children:"Use active pane"}),m.jsx("button",{type:"button",onClick:()=>w(s),disabled:y||!s,children:"Use current workspace"})]}),m.jsxs("div",{className:"workspace-dialog-browser","aria-label":"Workspace folder browser","aria-busy":e.browseStatus==="loading",children:[m.jsxs("div",{className:"workspace-dialog-browser-header",children:[m.jsx("span",{title:g,children:g||"No folder selected"}),m.jsx("button",{type:"button",onClick:()=>{c(a5(g))},disabled:y||!g||g==="/"||e.browseStatus==="loading",children:"Up"})]}),e.browseStatus==="loading"?m.jsx("div",{className:"workspace-dialog-empty",children:"Loading..."}):null,e.browseStatus!=="loading"&&p.length===0?m.jsx("div",{className:"workspace-dialog-empty",children:"No folders"}):null,e.browseStatus!=="loading"&&p.length>0?m.jsx("div",{className:"workspace-dialog-folder-list",children:p.map(S=>m.jsxs("button",{type:"button","aria-label":`Choose folder ${S.name}`,disabled:y,onClick:()=>{c(r5(g,S.path))},children:[m.jsx("span",{children:S.name}),m.jsx("small",{children:S.path})]},S.path))}):null]}),e.error?m.jsx("div",{className:"workspace-dialog-error",role:"alert",children:e.error}):null]}),m.jsxs("div",{className:"workspace-dialog-actions",children:[m.jsx("button",{type:"button",className:"secondary-button",onClick:h,children:"Cancel"}),m.jsx("button",{type:"submit",className:"primary-button",disabled:y||e.browseStatus==="loading",children:y?"Saving...":e.mode==="create"?"Create":"Save"})]})]})})}function r5(e,t){return t?t.startsWith("/")?qu(t):qu(`${e||"/"}/${t}`):qu(e)}function a5(e){const t=qu(e);if(!t||t==="/")return"/";const s=t.lastIndexOf("/");return s<=0?"/":t.slice(0,s)}function qu(e){const t=e.trim();if(!t)return"";const s=t.replace(/\/+/g,"/");return s==="/"?"/":s.endsWith("/")?s.slice(0,-1):s}function l5({onCreate:e}){return m.jsxs("div",{className:"empty-workspace",children:[m.jsx("span",{children:"No terminal is open."}),m.jsx("button",{type:"button",onClick:e,children:"New tab"})]})}function o5({workspaceId:e,active:t,disabled:s=!1,reorderable:r=!1,dragging:o=!1,dropPlacement:c=null,children:h}){const{setNodeRef:f,isOver:g}=Qm({id:`workspace-drop:${e}`,data:{kind:"workspace",workspaceId:e},disabled:s}),p=["workspace-list-item",t?"workspace-list-item--active":"",r?"workspace-list-item--reorderable":"",o?"workspace-list-item--dragging":"",c?"workspace-list-item--drop-target":"",c?`workspace-list-item--drop-${c}`:""].filter(Boolean).join(" ");return m.jsx("div",{ref:f,className:p,"data-workspace-id":e,"data-drop-over":g?"true":void 0,children:h})}function c5({label:e,count:t,warning:s,onCancel:r,onHide:o,onDelete:c}){return m.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"close-terminal-title",onClick:r,children:m.jsxs("div",{className:"security-panel terminal-delete-dialog",onClick:h=>h.stopPropagation(),children:[m.jsxs("header",{className:"security-panel-header",children:[m.jsx("h2",{id:"close-terminal-title",children:"Close Terminal"}),m.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:r,children:"x"})]}),m.jsxs("section",{className:"terminal-delete-dialog-body",children:[m.jsx("p",{children:t===1?"What should happen to this terminal?":`What should happen to these ${t} panes?`}),m.jsx("span",{children:e}),m.jsx("small",{children:"Hide keeps the shell running in this workspace. Delete destroys the underlying session."}),s?m.jsx("div",{className:"terminal-delete-warning",role:"alert",children:s}):null]}),m.jsxs("div",{className:"terminal-delete-dialog-actions",children:[m.jsx("button",{type:"button",className:"secondary-button",onClick:r,children:"Cancel"}),m.jsx("button",{type:"button",className:"secondary-button",onClick:o,children:"Hide"}),m.jsx("button",{type:"button",className:"terminal-delete-confirm",onClick:c,children:"Delete"})]})]})})}function u5({targets:e,activeLeafKey:t,terminals:s,editors:r,onSelect:o}){const[c,h]=v.useState(!1);if(e.length<=1)return null;const f=t?e.findIndex(w=>w.key===t):-1,g=f>=0?f:0,p=e[g]??e[0],y=p0(p,s,r);function b(w){const S=(g+w+e.length)%e.length,E=e[S];E&&o(E)}return m.jsxs("div",{className:"mobile-pane-switcher",role:"group","aria-label":"Pane switcher",children:[m.jsx("button",{type:"button","aria-label":"Previous pane",onClick:()=>b(-1),children:"<"}),m.jsxs("button",{type:"button",className:"mobile-pane-current","aria-label":"Open pane switcher","aria-haspopup":"dialog","aria-expanded":c,title:y,onClick:()=>h(!0),children:["Pane ",g+1,"/",e.length," | ",y]}),m.jsx("button",{type:"button","aria-label":"Next pane",onClick:()=>b(1),children:">"}),c?m.jsx("div",{className:"mobile-pane-sheet-backdrop",onClick:()=>h(!1),children:m.jsxs("section",{className:"mobile-pane-sheet",role:"dialog","aria-modal":"true","aria-label":"Pane switcher",onClick:w=>w.stopPropagation(),children:[m.jsxs("header",{children:[m.jsx("strong",{children:"Panes"}),m.jsx("button",{type:"button","aria-label":"Close pane switcher",onClick:()=>h(!1),children:"x"})]}),m.jsx("div",{className:"mobile-pane-sheet-list",children:e.map((w,S)=>{const E=p0(w,s,r),T=h5(w,s,r),A=w.key===p.key;return m.jsxs("button",{type:"button","data-active":A,onClick:()=>{o(w),h(!1)},children:[m.jsx("span",{className:"mobile-pane-sheet-index",children:S+1}),m.jsxs("span",{className:"mobile-pane-sheet-copy",children:[m.jsx("strong",{children:E}),m.jsx("small",{children:T})]}),m.jsx("span",{className:"mobile-pane-sheet-type",children:w.type})]},w.key)})})]})}):null]})}function p0(e,t,s){if(e.type==="editor")return s[e.editorId]?.title||e.title||e.editorId;const r=t[e.terminalId];return r?.title||r?.cwd||e.terminalId}function h5(e,t,s){if(e.type==="editor"){const c=s[e.editorId];return c?.path?`editor | ${c.path}`:"editor"}const r=t[e.terminalId];return r?`${r.activity==="busy"?`busy${r.currentCommand?`: ${r.currentCommand}`:""}`:r.activity==="idle"?"idle":r.status} | ${r.cwd}`:"terminal"}function d5(e){const[t,s]=v.useState(()=>f5(e));return v.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function"){s(!1);return}const r=window.matchMedia(e),o=()=>s(r.matches);return o(),typeof r.addEventListener=="function"?(r.addEventListener("change",o),()=>r.removeEventListener("change",o)):(r.addListener(o),()=>r.removeListener(o))},[e]),t}function f5(e){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(e).matches}function fn(e,t){return e===t}function p5(e){const t=e.workspaces.find(r=>r.id===e.activeWorkspaceId)??e.workspaces[0];return(t?.tabs.find(r=>r.id===t.activeTabId)??t?.tabs[0])?.id??null}function $u(e){return e??"__local__"}function Io(e,t,s){return`${$u(e)}:${t}:${s}`}class dh extends Error{constructor(){super(Z1())}}function m5(e){return e?{workspaceKey:`${d0}:${e}`}:{workspaceKey:d0}}function g5(e){const t=localStorage.getItem(e.workspaceKey);if(!t)return null;try{const s=JSON.parse(t);if(q0(s))throw new dh;const r=W0(s);return r?G1(r):null}catch(s){if(s instanceof dh)throw s;return null}}function G1(e){if(q0(e))throw new dh;const t=W0(e);return t?{savedWorkspaces:t.workspaces,savedActiveWorkspaceId:t.activeWorkspaceId}:null}function No(e,t){if(e.workspaces.length>0){localStorage.setItem(t.workspaceKey,JSON.stringify(e));return}localStorage.removeItem(t.workspaceKey)}function _5(e,t){const s=Mt(e).lastPersistedLayoutJson;if(s){localStorage.setItem(t.workspaceKey,s);return}localStorage.removeItem(t.workspaceKey)}function v5(e){return`This workspace already has ${e} hidden terminal session${e===1?"":"s"}; the limit is ${kl}. Re-open or delete hidden sessions before hiding more.`}function Z1(){return`A saved terminal layout has more than ${kl} hidden terminal sessions in one workspace. Re-open or delete hidden sessions, then save the layout again.`}function b5(e){const t=e.workspaces.find(o=>o.id===e.activeWorkspaceId)??e.workspaces[0],s=t?.tabs.find(o=>o.id===t.activeTabId)??t?.tabs[0],r=s?e.terminals[s.activeTerminalId]:void 0;return r?.status==="running"?r:null}function y5(e){return e.results.find(t=>t.status==="failed"&&t.error)?.error}function S5(e){return e.split("/").filter(Boolean).pop()??e}function w5(){try{return localStorage.getItem(Y1)==="true"}catch{return!1}}function C5(e){try{localStorage.setItem(Y1,e?"true":"false")}catch{}}function x5(e){if(!e)return"session · local";const t=Date.parse(e);if(!Number.isFinite(t))return"session · local";const s=t-Date.now();if(s<=0)return"session · expired";const r=Math.max(1,Math.floor(s/6e4));return r<60?`session · ${r}m left`:`session · ${Math.floor(r/60)}h left`}function m0({name:e}){return m.jsxs("svg",{className:"workspace-footer-icon",viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[e==="settings"?m.jsxs(m.Fragment,{children:[m.jsx("path",{d:"M4 7h9"}),m.jsx("path",{d:"M17 7h3"}),m.jsx("circle",{cx:"15",cy:"7",r:"2"}),m.jsx("path",{d:"M4 12h3"}),m.jsx("path",{d:"M11 12h9"}),m.jsx("circle",{cx:"9",cy:"12",r:"2"}),m.jsx("path",{d:"M4 17h9"}),m.jsx("path",{d:"M17 17h3"}),m.jsx("circle",{cx:"15",cy:"17",r:"2"})]}):null,e==="logout"?m.jsxs(m.Fragment,{children:[m.jsx("path",{d:"M10 6H6v12h4"}),m.jsx("path",{d:"M13 8l4 4-4 4"}),m.jsx("path",{d:"M8 12h9"})]}):null]})}function Tr(e){return e instanceof Error?e.message:"Request failed"}function E5({api:e,onDone:t}){const[s,r]=v.useState(null),[o,c]=v.useState(null),[h,f]=v.useState(""),[g,p]=v.useState(!1),[y,b]=v.useState(null),[w,S]=v.useState(null);v.useEffect(()=>{let T=!1;return e.setupTotp().then(A=>{T||(r(A.qrDataUrl),c(A.secret))}).catch(A=>{T||S(A instanceof Error?A.message:"Failed to generate QR code")}),()=>{T=!0}},[e]);async function E(T){if(T.preventDefault(),!!o){p(!0),b(null);try{await e.activateTotp({secret:o,otp:h}),t()}catch(A){b(A instanceof Error?A.message:"Verification failed")}finally{p(!1)}}}return w?m.jsx("p",{className:"form-error",children:w}):!s||!o?m.jsx("p",{className:"muted",children:"Generating authenticator setup..."}):m.jsxs("div",{className:"totp-setup",children:[m.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."}),m.jsx("div",{className:"totp-qr-container",children:m.jsx("img",{src:s,alt:"TOTP QR code",width:192,height:192})}),m.jsxs("details",{className:"totp-secret-details",children:[m.jsx("summary",{children:"Can't scan? Enter manually"}),m.jsx("p",{className:"totp-secret-text",children:o})]}),m.jsxs("form",{className:"auth-form",onSubmit:E,children:[m.jsxs("label",{children:["Verification code",m.jsx("input",{autoFocus:!0,type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:h,onChange:T=>f(T.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}),y?m.jsx("p",{className:"form-error",children:y}):null,m.jsx("button",{type:"submit",disabled:g||h.length!==6,children:"Activate 2FA"})]})]})}function k5(e){return{source:fp(e?.source)||"unknown",...typeof e?.status=="number"?{status:e.status}:{},...e?.activeAgentId!==void 0?{activeAgentId:e.activeAgentId}:{},...e?.terminalId?{terminalId:fp(e.terminalId)}:{},...e?.detail?{detail:fp(e.detail)}:{}}}function T5(e){return{invalidationSource:e.source}}function D5(e){Nn("auth.session_invalid.request",Q1(e)),!(typeof console>"u"||typeof console.warn!="function")&&(console.warn("[nterminal] session invalid requested",e),bh("session-invalid-request").catch(()=>{}))}function R5(e,t){Nn("auth.session_invalid.result",{...Q1(e),authenticated:t}),!(typeof console>"u"||typeof console.warn!="function")&&(console.warn("[nterminal] session invalid check result",{...e,authenticated:t}),bh("session-invalid-result").catch(()=>{}))}function Q1(e){return{source:e.source,...typeof e.status=="number"?{status:e.status}:{},...e.activeAgentId!==void 0?{activeAgentId:e.activeAgentId}:{},...e.terminalId?{terminalId:e.terminalId}:{},...e.detail?{detail:e.detail}:{}}}function fp(e){return e?e.replace(/[^a-zA-Z0-9_.:-]/g,"_").slice(0,96):""}function M5({api:e,serverApi:t,activeAgentId:s=null,onSelectServer:r}){const o=v.useMemo(()=>e??fh(),[e]),c=v.useMemo(()=>t??Go(null),[t]),[h,f]=v.useState(null),[g,p]=v.useState(null),y=v.useRef(null),b=v.useRef("loading");v.useEffect(()=>{let O=!1;return o.getSession().then(L=>{O||(f(L),p(null))}).catch(L=>{O||(p(ba(L)),f(null))}),()=>{O=!0}},[o]);const w=B5(h);v.useEffect(()=>{const O=b.current;Nn("auth.view",{view:w,previousView:O,authenticated:h?.authenticated??null,passwordSet:h?.passwordSet??null,totpEnabled:h?.totpEnabled??null,deviceTrusted:h?.deviceTrusted??null,currentIpWhitelisted:h?.currentIpWhitelisted??null}),O==="workspace"&&w!=="workspace"&&bh(`auth-left-workspace-${w}`).catch(()=>{}),b.current=w},[h,w]);async function S(){const O=await o.getSession();f(O),p(null)}async function E(){rp(),dp(),$S(),p(null),f(null);try{await S()}catch(O){p(ba(O))}}function T(O){const L=k5(O);if(D5(L),y.current)return y.current;const U=(async()=>{p(null);try{const I=await o.getSession(T5(L));if(R5(L,I.authenticated),f(I),I.authenticated){EN();return}rp(),dp(),$S()}catch(I){p(ba(I))}finally{y.current=null}})();return y.current=U,U}if(w==="workspace")return m.jsx(ZA,{api:o,serverApi:c,activeAgentId:s,onSelectServer:r,sessionExpiresAt:h?.expiresAt??null,onSessionInvalid:O=>{T(O)},onLogout:async()=>{rp(),dp();const O=await o.logout();f(O)}});const A={loading:"Terminal",setup_password:"Set password",setup_totp:"Set up 2FA",login:"Unlock terminal",reauth:"Verify it’s you",workspace:"Terminal"};return m.jsxs("main",{className:"auth-screen",children:[m.jsxs("div",{className:"auth-background","aria-hidden":"true",children:[m.jsx("div",{className:"auth-grid"}),m.jsx("div",{className:"auth-glow"})]}),m.jsxs("section",{className:"auth-panel","aria-busy":w==="loading",children:[m.jsxs("header",{className:"auth-header",children:[m.jsxs("div",{className:"auth-brand",children:[m.jsx(w0,{size:26}),m.jsxs("div",{children:[m.jsx(C0,{height:17}),m.jsx("p",{className:"auth-host",children:"local terminal"})]})]}),m.jsx("h1",{children:A[w]})]}),g?m.jsx("p",{className:"form-error",children:g}):null,w==="loading"?m.jsx("p",{className:"muted",children:"Checking session..."}):null,w==="loading"&&g?m.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{E()},children:"Retry"}):null,w==="setup_password"?m.jsx(N5,{api:o,onSession:O=>{f(O)}}):null,w==="setup_totp"?m.jsx(E5,{api:o,onDone:()=>{S()}}):null,w==="login"?m.jsx(A5,{api:o,session:h,onSession:f,onRefresh:S}):null,w==="reauth"?m.jsx(L5,{api:o,session:h,onSession:f,onFullLogin:()=>f(O=>O&&{...O,deviceTrusted:!1})}):null]})]})}function N5({api:e,onSession:t}){const[s,r]=v.useState(""),[o,c]=v.useState(""),[h,f]=v.useState(!1),[g,p]=v.useState(null);async function y(b){b.preventDefault(),f(!0),p(null);try{if(s!==o){p("Passwords do not match");return}t(await e.setupPassword({password:s}))}catch(w){p(ba(w))}finally{f(!1)}}return m.jsxs("form",{className:"auth-form",onSubmit:y,children:[m.jsxs("label",{children:["Password",m.jsx("input",{autoFocus:!0,value:s,onChange:b=>r(b.currentTarget.value),type:"password",minLength:8,required:!0})]}),m.jsxs("label",{children:["Confirm password",m.jsx("input",{value:o,onChange:b=>c(b.currentTarget.value),type:"password",minLength:8,required:!0})]}),g?m.jsx("p",{className:"form-error",children:g}):null,m.jsx("button",{type:"submit",disabled:h||s.length<8||o.length<8,children:"Set password"})]})}function A5({api:e,session:t,onSession:s,onRefresh:r}){const[o,c]=v.useState(""),[h,f]=v.useState(""),[g,p]=v.useState(!1),[y,b]=v.useState(!1),[w,S]=v.useState(null),E=t?.totpEnabled??!1,T=t?.currentIpWhitelisted??!1;async function A(O){O.preventDefault(),b(!0),S(null);try{s(await e.login({password:o,...E?{otp:h}:{},rememberNetwork:g}))}catch(L){S(ba(L))}finally{b(!1)}}return m.jsxs("form",{className:"auth-form",onSubmit:A,children:[m.jsxs("label",{children:["Password",m.jsx("input",{autoFocus:!0,type:"password",value:o,onChange:O=>c(O.currentTarget.value),required:!0})]}),E?m.jsxs("label",{children:["Authenticator code",m.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:h,onChange:O=>f(O.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}):null,T?null:m.jsxs("label",{className:"auth-checkbox",children:[m.jsx("input",{type:"checkbox",checked:g,onChange:O=>p(O.currentTarget.checked)}),"Remember this network (skip 2FA here next time)"]}),w?m.jsx("p",{className:"form-error",children:w}):null,m.jsxs("div",{className:"button-row",children:[m.jsx("button",{type:"submit",disabled:y||o.length===0||E&&h.length!==6,children:"Unlock"}),m.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{r()},disabled:y,children:"Refresh"})]})]})}function L5({api:e,session:t,onSession:s,onFullLogin:r}){const o=t?.currentIpWhitelisted??!1,[c,h]=v.useState(""),[f,g]=v.useState(!1),[p,y]=v.useState(!1),[b,w]=v.useState(!1),[S,E]=v.useState(!1),[T,A]=v.useState(null),O=Si.useCallback(async(U,I)=>{y(!0),A(null);try{s(await e.reauth({...U?{otp:U}:{},rememberNetwork:I}))}catch(te){A(ba(te))}finally{y(!1)}},[e,s]);v.useEffect(()=>{if(o){let U=!1;w(!0),E(!1),A(null);const I=window.setTimeout(()=>{U||E(!0)},6e3);return e.reauth({rememberNetwork:!1}).then(te=>{U||s(te)}).catch(te=>{U||(A(ba(te)),E(!0))}).finally(()=>{window.clearTimeout(I),U||w(!1)}),()=>{U=!0,window.clearTimeout(I)}}},[e,o,s]);async function L(U){U.preventDefault(),await O(c,f)}return o&&b&&!S&&!T?m.jsx("p",{className:"muted",children:"Reconnecting from a trusted network…"}):m.jsxs("form",{className:"auth-form",onSubmit:L,children:[o&&S&&!T?m.jsx("p",{className:"muted",children:"Automatic verification is taking longer than expected. You can enter a code or use password login."}):null,m.jsx("p",{className:"muted",children:"This device is remembered. Enter your authenticator code to continue."}),m.jsxs("label",{children:["Authenticator code",m.jsx("input",{autoFocus:!0,type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:c,onChange:U=>h(U.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}),m.jsxs("label",{className:"auth-checkbox",children:[m.jsx("input",{type:"checkbox",checked:f,onChange:U=>g(U.currentTarget.checked)}),"Remember this network (skip 2FA here next time)"]}),T?m.jsx("p",{className:"form-error",children:T}):null,m.jsxs("div",{className:"button-row",children:[m.jsx("button",{type:"submit",disabled:p||c.length!==6,children:"Continue"}),m.jsx("button",{type:"button",className:"secondary-button",onClick:r,disabled:p,children:"Use password instead"})]})]})}function B5(e){return e?e.passwordSet?e.authenticated&&!e.totpEnabled?"setup_totp":e.authenticated?"workspace":e.deviceTrusted&&e.totpEnabled?"reauth":"login":"setup_password":"loading"}function ba(e){return e instanceof Error?e.message:"Request failed"}const g0="NTerminal",Pm="nterminal.activeAgentId";function O5(){const[e,t]=v.useState(()=>z5()),s=v.useMemo(()=>fh(),[]),r=v.useMemo(()=>Go(e),[e]);v.useEffect(()=>{const c=()=>{const h=hA();document.title=h>0?`(${h}) ${g0}`:g0};return c(),uA(c)},[]);function o(c){j5(c),t(c)}return m.jsx(M5,{api:s,activeAgentId:e,serverApi:r,onSelectServer:o})}function z5(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Pm);return e&&e.trim()?e:null}catch{return null}}function j5(e){if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(Pm,e);return}window.localStorage.removeItem(Pm)}catch{}}const _0=["gesturestart","gesturechange","gestureend"],H5=[".workspace-list",".workspace-nav",".server-list",".terminal-tab-list",".mobile-terminal-key-bar",".upload-toast-body",".file-tree",".file-detail",".file-editor",".file-markdown-preview",".editor-markdown-preview",".settings-content",".settings-nav",".transcript-dialog-scroll",".transcript-filter-group"].join(",");function P5(e=window){if(!I5(e))return()=>{};const t={passive:!1},s=e.document;function r(c){c.cancelable&&c.preventDefault()}function o(c){if(c.defaultPrevented)return;const h=c.touches;!h||h.length===0||(h.length>1||!U5(c.target))&&r(c)}for(const c of _0)s.addEventListener(c,r,t);return s.addEventListener("touchmove",o,t),s.addEventListener("dblclick",r,t),()=>{for(const c of _0)s.removeEventListener(c,r,t);s.removeEventListener("touchmove",o,t),s.removeEventListener("dblclick",r,t)}}function U5(e){return e instanceof Element&&e.closest(H5)!==null}function I5(e){return e.navigator.maxTouchPoints>0?!0:typeof e.matchMedia=="function"&&e.matchMedia("(pointer: coarse)").matches}lk();$M();P5();Wm();cE.createRoot(document.getElementById("root")).render(m.jsx(Si.StrictMode,{children:m.jsx(O5,{})}));export{Si as R,eE as g,m as j};