hop2 0.11.7 → 0.11.8

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.
@@ -123,11 +123,11 @@ out vec4 outColor;
123
123
  void main() {
124
124
  outColor = v_color;
125
125
  }`,Zu=8,Qu=Zu*Float32Array.BYTES_PER_ELEMENT,$u=20*Zu,ed=class{constructor(){this.attributes=new Float32Array($u),this.count=0}},td=0,nd=0,rd=0,id=0,ad=0,od=0,sd=0,cd=class extends Nc{constructor(e,t,n,r){super(),this._terminal=e,this._gl=t,this._dimensions=n,this._themeService=r,this._vertices=new ed,this._verticesCursor=new ed;let i=this._gl;this._program=tl(Du(i,Yu,Xu)),this._register(Ac(()=>i.deleteProgram(this._program))),this._projectionLocation=tl(i.getUniformLocation(this._program,`u_projection`)),this._vertexArrayObject=i.createVertexArray(),i.bindVertexArray(this._vertexArrayObject);let a=new Float32Array([0,0,1,0,0,1,1,1]),o=i.createBuffer();this._register(Ac(()=>i.deleteBuffer(o))),i.bindBuffer(i.ARRAY_BUFFER,o),i.bufferData(i.ARRAY_BUFFER,a,i.STATIC_DRAW),i.enableVertexAttribArray(3),i.vertexAttribPointer(3,2,this._gl.FLOAT,!1,0,0);let s=new Uint8Array([0,1,2,3]),c=i.createBuffer();this._register(Ac(()=>i.deleteBuffer(c))),i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,c),i.bufferData(i.ELEMENT_ARRAY_BUFFER,s,i.STATIC_DRAW),this._attributesBuffer=tl(i.createBuffer()),this._register(Ac(()=>i.deleteBuffer(this._attributesBuffer))),i.bindBuffer(i.ARRAY_BUFFER,this._attributesBuffer),i.enableVertexAttribArray(0),i.vertexAttribPointer(0,2,i.FLOAT,!1,Qu,0),i.vertexAttribDivisor(0,1),i.enableVertexAttribArray(1),i.vertexAttribPointer(1,2,i.FLOAT,!1,Qu,2*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(1,1),i.enableVertexAttribArray(2),i.vertexAttribPointer(2,4,i.FLOAT,!1,Qu,4*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisor(2,1),this._updateCachedColors(r.colors),this._register(this._themeService.onChangeColors(e=>{this._updateCachedColors(e),this._updateViewportRectangle()}))}renderBackgrounds(){this._renderVertices(this._vertices)}renderCursor(){this._renderVertices(this._verticesCursor)}_renderVertices(e){let t=this._gl;t.useProgram(this._program),t.bindVertexArray(this._vertexArrayObject),t.uniformMatrix4fv(this._projectionLocation,!1,Eu),t.bindBuffer(t.ARRAY_BUFFER,this._attributesBuffer),t.bufferData(t.ARRAY_BUFFER,e.attributes,t.DYNAMIC_DRAW),t.drawElementsInstanced(this._gl.TRIANGLE_STRIP,4,t.UNSIGNED_BYTE,0,e.count)}handleResize(){this._updateViewportRectangle()}setDimensions(e){this._dimensions=e}_updateCachedColors(e){this._bgFloat=this._colorToFloat32Array(e.background),this._cursorFloat=this._colorToFloat32Array(e.cursor)}_updateViewportRectangle(){this._addRectangleFloat(this._vertices.attributes,0,0,0,this._terminal.cols*this._dimensions.device.cell.width,this._terminal.rows*this._dimensions.device.cell.height,this._bgFloat)}updateBackgrounds(e){let t=this._terminal,n=this._vertices,r=1,i,a,o,s,c,l,u,d,f,p,m;for(i=0;i<t.rows;i++){for(o=-1,s=0,c=0,l=!1,a=0;a<t.cols;a++)u=(i*t.cols+a)*Uu,d=e.cells[u+Wu],f=e.cells[u+Gu],p=!!(f&67108864),(d!==s||f!==c&&(l||p))&&((s!==0||l&&c!==0)&&(m=r++*Zu,this._updateRectangle(n,m,c,s,o,a,i)),o=a,s=d,c=f,l=p);(s!==0||l&&c!==0)&&(m=r++*Zu,this._updateRectangle(n,m,c,s,o,t.cols,i))}n.count=r}updateCursor(e){let t=this._verticesCursor,n=e.cursor;if(!n||n.style===`block`){t.count=0;return}let r,i=0;(n.style===`bar`||n.style===`outline`)&&(r=i++*Zu,this._addRectangleFloat(t.attributes,r,n.x*this._dimensions.device.cell.width,n.y*this._dimensions.device.cell.height,n.style===`bar`?n.dpr*n.cursorWidth:n.dpr,this._dimensions.device.cell.height,this._cursorFloat)),(n.style===`underline`||n.style===`outline`)&&(r=i++*Zu,this._addRectangleFloat(t.attributes,r,n.x*this._dimensions.device.cell.width,(n.y+1)*this._dimensions.device.cell.height-n.dpr,n.width*this._dimensions.device.cell.width,n.dpr,this._cursorFloat)),n.style===`outline`&&(r=i++*Zu,this._addRectangleFloat(t.attributes,r,n.x*this._dimensions.device.cell.width,n.y*this._dimensions.device.cell.height,n.width*this._dimensions.device.cell.width,n.dpr,this._cursorFloat),r=i++*Zu,this._addRectangleFloat(t.attributes,r,(n.x+n.width)*this._dimensions.device.cell.width-n.dpr,n.y*this._dimensions.device.cell.height,n.dpr,this._dimensions.device.cell.height,this._cursorFloat)),t.count=i}_updateRectangle(e,t,n,r,i,a,o){if(n&67108864)switch(n&50331648){case 16777216:case 33554432:td=this._themeService.colors.ansi[n&255].rgba;break;case 50331648:td=(n&16777215)<<8;break;case 0:default:td=this._themeService.colors.foreground.rgba}else switch(r&50331648){case 16777216:case 33554432:td=this._themeService.colors.ansi[r&255].rgba;break;case 50331648:td=(r&16777215)<<8;break;case 0:default:td=this._themeService.colors.background.rgba}e.attributes.length<t+4&&(e.attributes=ku(e.attributes,this._terminal.rows*this._terminal.cols*Zu)),nd=i*this._dimensions.device.cell.width,rd=o*this._dimensions.device.cell.height,id=(td>>24&255)/255,ad=(td>>16&255)/255,od=(td>>8&255)/255,sd=1,this._addRectangle(e.attributes,t,nd,rd,(a-i)*this._dimensions.device.cell.width,this._dimensions.device.cell.height,id,ad,od,sd)}_addRectangle(e,t,n,r,i,a,o,s,c,l){e[t]=n/this._dimensions.device.canvas.width,e[t+1]=r/this._dimensions.device.canvas.height,e[t+2]=i/this._dimensions.device.canvas.width,e[t+3]=a/this._dimensions.device.canvas.height,e[t+4]=o,e[t+5]=s,e[t+6]=c,e[t+7]=l}_addRectangleFloat(e,t,n,r,i,a,o){e[t]=n/this._dimensions.device.canvas.width,e[t+1]=r/this._dimensions.device.canvas.height,e[t+2]=i/this._dimensions.device.canvas.width,e[t+3]=a/this._dimensions.device.canvas.height,e[t+4]=o[0],e[t+5]=o[1],e[t+6]=o[2],e[t+7]=o[3]}_colorToFloat32Array(e){return new Float32Array([(e.rgba>>24&255)/255,(e.rgba>>16&255)/255,(e.rgba>>8&255)/255,(e.rgba&255)/255])}},ld=class extends Nc{constructor(e,t,n,r,i,a,o,s){super(),this._container=t,this._alpha=i,this._coreBrowserService=a,this._optionsService=o,this._themeService=s,this._deviceCharWidth=0,this._deviceCharHeight=0,this._deviceCellWidth=0,this._deviceCellHeight=0,this._deviceCharLeft=0,this._deviceCharTop=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-${n}-layer`),this._canvas.style.zIndex=r.toString(),this._initCanvas(),this._container.appendChild(this._canvas),this._register(this._themeService.onChangeColors(t=>{this._refreshCharAtlas(e,t),this.reset(e)})),this._register(Ac(()=>{this._canvas.remove()}))}_initCanvas(){this._ctx=tl(this._canvas.getContext(`2d`,{alpha:this._alpha})),this._alpha||this._clearAll()}handleBlur(e){}handleFocus(e){}handleCursorMove(e){}handleGridChanged(e,t,n){}handleSelectionChanged(e,t,n,r=!1){}_setTransparency(e,t){if(t===this._alpha)return;let n=this._canvas;this._alpha=t,this._canvas=this._canvas.cloneNode(),this._initCanvas(),this._container.replaceChild(this._canvas,n),this._refreshCharAtlas(e,this._themeService.colors),this.handleGridChanged(e,0,e.rows-1)}_refreshCharAtlas(e,t){this._deviceCharWidth<=0&&this._deviceCharHeight<=0||(this._charAtlas=yu(e,this._optionsService.rawOptions,t,this._deviceCellWidth,this._deviceCellHeight,this._deviceCharWidth,this._deviceCharHeight,this._coreBrowserService.dpr,2048),this._charAtlas.warmUp())}resize(e,t){this._deviceCellWidth=t.device.cell.width,this._deviceCellHeight=t.device.cell.height,this._deviceCharWidth=t.device.char.width,this._deviceCharHeight=t.device.char.height,this._deviceCharLeft=t.device.char.left,this._deviceCharTop=t.device.char.top,this._canvas.width=t.device.canvas.width,this._canvas.height=t.device.canvas.height,this._canvas.style.width=`${t.css.canvas.width}px`,this._canvas.style.height=`${t.css.canvas.height}px`,this._alpha||this._clearAll(),this._refreshCharAtlas(e,this._themeService.colors)}_fillBottomLineAtCells(e,t,n=1){this._ctx.fillRect(e*this._deviceCellWidth,(t+1)*this._deviceCellHeight-this._coreBrowserService.dpr-1,n*this._deviceCellWidth,this._coreBrowserService.dpr)}_clearAll(){this._alpha?this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height))}_clearCells(e,t,n,r){this._alpha?this._ctx.clearRect(e*this._deviceCellWidth,t*this._deviceCellHeight,n*this._deviceCellWidth,r*this._deviceCellHeight):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(e*this._deviceCellWidth,t*this._deviceCellHeight,n*this._deviceCellWidth,r*this._deviceCellHeight))}_fillCharTrueColor(e,t,n,r){this._ctx.font=this._getFont(e,!1,!1),this._ctx.textBaseline=xl,this._clipCell(n,r,t.getWidth()),this._ctx.fillText(t.getChars(),n*this._deviceCellWidth+this._deviceCharLeft,r*this._deviceCellHeight+this._deviceCharTop+this._deviceCharHeight)}_clipCell(e,t,n){this._ctx.beginPath(),this._ctx.rect(e*this._deviceCellWidth,t*this._deviceCellHeight,n*this._deviceCellWidth,this._deviceCellHeight),this._ctx.clip()}_getFont(e,t,n){let r=t?e.options.fontWeightBold:e.options.fontWeight;return`${n?`italic`:``} ${r} ${e.options.fontSize*this._coreBrowserService.dpr}px ${e.options.fontFamily}`}},ud=class extends ld{constructor(e,t,n,r,i,a,o){super(n,e,`link`,t,!0,i,a,o),this._register(r.onShowLinkUnderline(e=>this._handleShowLinkUnderline(e))),this._register(r.onHideLinkUnderline(e=>this._handleHideLinkUnderline(e)))}resize(e,t){super.resize(e,t),this._state=void 0}reset(e){this._clearCurrentLink()}_clearCurrentLink(){if(this._state){this._clearCells(this._state.x1,this._state.y1,this._state.cols-this._state.x1,1);let e=this._state.y2-this._state.y1-1;e>0&&this._clearCells(0,this._state.y1+1,this._state.cols,e),this._clearCells(0,this._state.y2,this._state.x2,1),this._state=void 0}}_handleShowLinkUnderline(e){if(e.fg===257?this._ctx.fillStyle=this._themeService.colors.background.css:e.fg!==void 0&&_u(e.fg)?this._ctx.fillStyle=this._themeService.colors.ansi[e.fg].css:this._ctx.fillStyle=this._themeService.colors.foreground.css,e.y1===e.y2)this._fillBottomLineAtCells(e.x1,e.y1,e.x2-e.x1);else{this._fillBottomLineAtCells(e.x1,e.y1,e.cols-e.x1);for(let t=e.y1+1;t<e.y2;t++)this._fillBottomLineAtCells(0,t,e.cols);this._fillBottomLineAtCells(0,e.y2,e.x2)}this._state=e}_handleHideLinkUnderline(e){this._clearCurrentLink()}},dd=typeof window==`object`?window:globalThis,fd=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new au,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new au,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};fd.INSTANCE=new fd;var pd=fd;function md(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}pd.INSTANCE.onDidChangeZoomLevel,pd.INSTANCE.onDidChangeFullscreen;var hd=typeof navigator==`object`?navigator.userAgent:``;hd.indexOf(`Firefox`);var gd=hd.indexOf(`AppleWebKit`)>=0;!(hd.indexOf(`Chrome`)>=0)&&hd.indexOf(`Safari`),hd.indexOf(`Electron/`),hd.indexOf(`Android`);var _d=!1;if(typeof dd.matchMedia==`function`){let e=dd.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=dd.matchMedia(`(display-mode: fullscreen)`);_d=e.matches,md(dd,e,({matches:e})=>{_d&&t.matches||(_d=e)})}function vd(){return _d}var yd=`en`,bd=!1,xd=!1,Sd=!1,Cd=yd,wd,Td=globalThis,K;typeof Td.vscode<`u`&&typeof Td.vscode.process<`u`?K=Td.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(K=process);var Ed=typeof K?.versions?.electron==`string`&&K?.type===`renderer`;if(typeof K==`object`){K.platform,K.platform,bd=K.platform===`linux`,bd&&K.env.SNAP&&K.env.SNAP_REVISION,K.env.CI||K.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Cd=yd;let e=K.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,Cd=t.resolvedLanguage||yd,t.languagePack?.translationsConfigFile}catch{}xd=!0}else typeof navigator==`object`&&!Ed?(wd=navigator.userAgent,wd.indexOf(`Windows`),wd.indexOf(`Macintosh`),(wd.indexOf(`Macintosh`)>=0||wd.indexOf(`iPad`)>=0||wd.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,bd=wd.indexOf(`Linux`)>=0,wd?.indexOf(`Mobi`),Sd=!0,Cd=globalThis._VSCODE_NLS_LANGUAGE||yd,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var Dd=xd;Sd&&typeof Td.importScripts==`function`&&Td.origin;var Od=wd,kd=Cd,Ad;(e=>{function t(){return kd}e.value=t;function n(){return kd.length===2?kd===`en`:kd.length>=3?kd[0]===`e`&&kd[1]===`n`&&kd[2]===`-`:!1}e.isDefaultVariant=n;function r(){return kd===`en`}e.isDefault=r})(Ad||={});var jd=typeof Td.postMessage==`function`&&!Td.importScripts;(()=>{if(jd){let e=[];Td.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),Td.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var Md=!!(Od&&Od.indexOf(`Chrome`)>=0);Od&&Od.indexOf(`Firefox`),!Md&&Od&&Od.indexOf(`Safari`),Od&&Od.indexOf(`Edg/`),Od&&Od.indexOf(`Android`);var Nd=typeof navigator==`object`?navigator:{};Dd||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||Nd&&Nd.clipboard&&Nd.clipboard.writeText,Dd||Nd&&Nd.clipboard&&Nd.clipboard.readText,Dd||vd()||Nd.keyboard,`ontouchstart`in dd||Nd.maxTouchPoints,dd.PointerEvent&&(`ontouchstart`in dd||navigator.maxTouchPoints);var Pd=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},Fd=new Pd,Id=new Pd,Ld=new Pd;Array(230);var Rd;(e=>{function t(e){return Fd.keyCodeToStr(e)}e.toString=t;function n(e){return Fd.strToKeyCode(e)}e.fromString=n;function r(e){return Id.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return Ld.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return Id.strToKeyCode(e)||Ld.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return Fd.keyCodeToStr(e)}e.toElectronAccelerator=o})(Rd||={});var zd=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),Bd;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof Vd?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Kl.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:zd})})(Bd||={});var Vd=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?zd:(this._emitter||=new au,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var Hd;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(Hd||={});var Ud=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new au,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await Kl.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};Ud.EMPTY=Ud.fromArray([]);function Wd(e){return 55296<=e&&e<=56319}function Gd(e){return 56320<=e&&e<=57343}function Kd(e,t){return(e-55296<<10)+(t-56320)+65536}function qd(e){return Jd(e,0)}function Jd(e,t){switch(typeof e){case`object`:return e===null?Yd(349,t):Array.isArray(e)?Qd(e,t):$d(e,t);case`string`:return Zd(e,t);case`boolean`:return Xd(e,t);case`number`:return Yd(e,t);case`undefined`:return Yd(937,t);default:return Yd(617,t)}}function Yd(e,t){return(t<<5)-t+e|0}function Xd(e,t){return Yd(e?433:863,t)}function Zd(e,t){t=Yd(149417,t);for(let n=0,r=e.length;n<r;n++)t=Yd(e.charCodeAt(n),t);return t}function Qd(e,t){return t=Yd(104579,t),e.reduce((e,t)=>Jd(t,e),t)}function $d(e,t){return t=Yd(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=Zd(n,t),Jd(e[n],t)),t)}function ef(e,t,n=32){let r=n-t,i=~((1<<r)-1);return(e<<t|(i&e)>>>r)>>>0}function tf(e,t=0,n=e.byteLength,r=0){for(let i=0;i<n;i++)e[t+i]=r}function nf(e,t,n=`0`){for(;e.length<t;)e=n+e;return e}function rf(e,t=32){return e instanceof ArrayBuffer?Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,`0`)).join(``):nf((e>>>0).toString(16),t/4)}var af=class e{constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(e){let t=e.length;if(t===0)return;let n=this._buff,r=this._buffLen,i=this._leftoverHighSurrogate,a,o;for(i===0?(a=e.charCodeAt(0),o=0):(a=i,o=-1,i=0);;){let s=a;if(Wd(a))if(o+1<t){let t=e.charCodeAt(o+1);Gd(t)?(o++,s=Kd(a,t)):s=65533}else{i=a;break}else Gd(a)&&(s=65533);if(r=this._push(n,r,s),o++,o<t)a=e.charCodeAt(o);else break}this._buffLen=r,this._leftoverHighSurrogate=i}_push(e,t,n){return n<128?e[t++]=n:n<2048?(e[t++]=192|(n&1984)>>>6,e[t++]=128|(n&63)>>>0):n<65536?(e[t++]=224|(n&61440)>>>12,e[t++]=128|(n&4032)>>>6,e[t++]=128|(n&63)>>>0):(e[t++]=240|(n&1835008)>>>18,e[t++]=128|(n&258048)>>>12,e[t++]=128|(n&4032)>>>6,e[t++]=128|(n&63)>>>0),t>=64&&(this._step(),t-=64,this._totalLen+=64,e[0]=e[64],e[1]=e[65],e[2]=e[66]),t}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),rf(this._h0)+rf(this._h1)+rf(this._h2)+rf(this._h3)+rf(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,tf(this._buff,this._buffLen),this._buffLen>56&&(this._step(),tf(this._buff));let e=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(e/4294967296),!1),this._buffDV.setUint32(60,e%4294967296,!1),this._step()}_step(){let t=e._bigBlock32,n=this._buffDV;for(let e=0;e<64;e+=4)t.setUint32(e,n.getUint32(e,!1),!1);for(let e=64;e<320;e+=4)t.setUint32(e,ef(t.getUint32(e-12,!1)^t.getUint32(e-32,!1)^t.getUint32(e-56,!1)^t.getUint32(e-64,!1),1),!1);let r=this._h0,i=this._h1,a=this._h2,o=this._h3,s=this._h4,c,l,u;for(let e=0;e<80;e++)e<20?(c=i&a|~i&o,l=1518500249):e<40?(c=i^a^o,l=1859775393):e<60?(c=i&a|i&o|a&o,l=2400959708):(c=i^a^o,l=3395469782),u=ef(r,5)+c+s+l+t.getUint32(e*4,!1)&4294967295,s=o,o=a,a=ef(i,30),i=r,r=u;this._h0=this._h0+r&4294967295,this._h1=this._h1+i&4294967295,this._h2=this._h2+a&4294967295,this._h3=this._h3+o&4294967295,this._h4=this._h4+s&4294967295}};af._bigBlock32=new DataView(new ArrayBuffer(320));var{registerWindow:of,getWindow:sf,getDocument:cf,getWindows:lf,getWindowsCount:uf,getWindowId:df,getWindowById:ff,hasWindow:pf,onDidRegisterWindow:mf,onWillUnregisterWindow:hf,onDidUnregisterWindow:gf}=function(){let e=new Map,t={window:dd,disposables:new Mc};e.set(dd.vscodeWindowId,t);let n=new au,r=new au,i=new au;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return Nc.None;let a=new Mc,o={window:t,disposables:a.add(new Mc)};return e.set(t.vscodeWindowId,o),a.add(Ac(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(vf(t,bf.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:dd},getDocument(e){return sf(e).document}}}(),_f=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function vf(e,t,n,r){return new _f(e,t,n,r)}var yf=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};yf.None=new yf(0,0),new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=qd(n),a=r.get(i);if(a)a.users+=1;else{let o=new au,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(Ac(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var bf={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:gd?`webkitAnimationStart`:`animationstart`,ANIMATION_END:gd?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:gd?`webkitAnimationIteration`:`animationiteration`},xf=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;function Sf(e,t,n,...r){let i=xf.exec(t);if(!i)throw Error(`Bad use of emmet`);let a=i[1]||`div`,o;return o=e===`http://www.w3.org/1999/xhtml`?document.createElement(a):document.createElementNS(e,a),i[3]&&(o.id=i[3]),i[4]&&(o.className=i[4].replace(/\./g,` `).trim()),n&&Object.entries(n).forEach(([e,t])=>{typeof t>`u`||(/^on\w+$/.test(e)?o[e]=t:e===`selected`?t&&o.setAttribute(e,`true`):o.setAttribute(e,t))}),o.append(...r),o}function Cf(e,t,...n){return Sf(`http://www.w3.org/1999/xhtml`,e,t,...n)}Cf.SVG=function(e,t,...n){return Sf(`http://www.w3.org/2000/svg`,e,t,...n)};var wf=class extends Nc{constructor(e,t,n,r,i,a,o,s,c){super(),this._terminal=e,this._characterJoinerService=t,this._charSizeService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._optionsService=o,this._themeService=s,this._cursorBlinkStateManager=new Pc,this._charAtlasDisposable=this._register(new Pc),this._observerDisposable=this._register(new Pc),this._model=new Ju,this._workCell=new Tu,this._workCell2=new Tu,this._rectangleRenderer=this._register(new Pc),this._glyphRenderer=this._register(new Pc),this._onChangeTextureAtlas=this._register(new au),this.onChangeTextureAtlas=this._onChangeTextureAtlas.event,this._onAddTextureAtlasCanvas=this._register(new au),this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=this._register(new au),this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._onRequestRedraw=this._register(new au),this.onRequestRedraw=this._onRequestRedraw.event,this._onContextLoss=this._register(new au),this.onContextLoss=this._onContextLoss.event,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`);let l={antialias:!1,depth:!1,preserveDrawingBuffer:c};if(this._gl=this._canvas.getContext(`webgl2`,l),!this._gl)throw Error(`WebGL2 not supported `+this._gl);this._register(this._themeService.onChangeColors(()=>this._handleColorChange())),this._cellColorResolver=new yl(this._terminal,this._optionsService,this._model.selection,this._decorationService,this._coreBrowserService,this._themeService),this._core=this._terminal._core,this._renderLayers=[new ud(this._core.screenElement,2,this._terminal,this._core.linkifier,this._coreBrowserService,o,this._themeService)],this.dimensions=ll(),this._devicePixelRatio=this._coreBrowserService.dpr,this._updateDimensions(),this._updateCursorBlink(),this._register(o.onOptionChange(()=>this._handleOptionsChanged())),this._deviceMaxTextureSize=this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),this._register(vf(this._canvas,`webglcontextlost`,e=>{console.log(`webglcontextlost event received`),e.preventDefault(),this._contextRestorationTimeout=setTimeout(()=>{this._contextRestorationTimeout=void 0,console.warn(`webgl context not restored; firing onContextLoss`),this._onContextLoss.fire(e)},3e3)})),this._register(vf(this._canvas,`webglcontextrestored`,e=>{console.warn(`webglcontextrestored event received`),clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0,bu(this._terminal),this._initializeWebGLState(),this._requestRedrawViewport()})),this._observerDisposable.value=Cu(this._canvas,this._coreBrowserService.window,(e,t)=>this._setCanvasDevicePixelDimensions(e,t)),this._register(this._coreBrowserService.onWindowChange(e=>{this._observerDisposable.value=Cu(this._canvas,e,(e,t)=>this._setCanvasDevicePixelDimensions(e,t))})),this._core.screenElement.appendChild(this._canvas),[this._rectangleRenderer.value,this._glyphRenderer.value]=this._initializeWebGLState(),this._isAttached=this._core.screenElement.isConnected,this._register(Ac(()=>{for(let e of this._renderLayers)e.dispose();this._canvas.parentElement?.removeChild(this._canvas),bu(this._terminal)}))}get textureAtlas(){return this._charAtlas?.pages[0].canvas}_handleColorChange(){this._refreshCharAtlas(),this._clearModel(!0)}handleDevicePixelRatioChange(){this._devicePixelRatio!==this._coreBrowserService.dpr&&(this._devicePixelRatio=this._coreBrowserService.dpr,this.handleResize(this._terminal.cols,this._terminal.rows))}handleResize(e,t){this._updateDimensions(),this._model.resize(this._terminal.cols,this._terminal.rows);for(let e of this._renderLayers)e.resize(this._terminal,this.dimensions);this._canvas.width=this.dimensions.device.canvas.width,this._canvas.height=this.dimensions.device.canvas.height,this._canvas.style.width=`${this.dimensions.css.canvas.width}px`,this._canvas.style.height=`${this.dimensions.css.canvas.height}px`,this._core.screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._core.screenElement.style.height=`${this.dimensions.css.canvas.height}px`,this._rectangleRenderer.value?.setDimensions(this.dimensions),this._rectangleRenderer.value?.handleResize(),this._glyphRenderer.value?.setDimensions(this.dimensions),this._glyphRenderer.value?.handleResize(),this._refreshCharAtlas(),this._clearModel(!1)}handleCharSizeChanged(){this.handleResize(this._terminal.cols,this._terminal.rows)}handleBlur(){for(let e of this._renderLayers)e.handleBlur(this._terminal);this._cursorBlinkStateManager.value?.pause(),this._requestRedrawViewport()}handleFocus(){for(let e of this._renderLayers)e.handleFocus(this._terminal);this._cursorBlinkStateManager.value?.resume(),this._requestRedrawViewport()}handleSelectionChanged(e,t,n){for(let r of this._renderLayers)r.handleSelectionChanged(this._terminal,e,t,n);this._model.selection.update(this._core,e,t,n),this._requestRedrawViewport()}handleCursorMove(){for(let e of this._renderLayers)e.handleCursorMove(this._terminal);this._cursorBlinkStateManager.value?.restartBlinkAnimation()}_handleOptionsChanged(){this._updateDimensions(),this._refreshCharAtlas(),this._updateCursorBlink()}_initializeWebGLState(){return this._rectangleRenderer.value=new cd(this._terminal,this._gl,this.dimensions,this._themeService),this._glyphRenderer.value=new Bu(this._terminal,this._gl,this.dimensions,this._optionsService),this.handleCharSizeChanged(),[this._rectangleRenderer.value,this._glyphRenderer.value]}_refreshCharAtlas(){if(this.dimensions.device.char.width<=0&&this.dimensions.device.char.height<=0){this._isAttached=!1;return}let e=yu(this._terminal,this._optionsService.rawOptions,this._themeService.colors,this.dimensions.device.cell.width,this.dimensions.device.cell.height,this.dimensions.device.char.width,this.dimensions.device.char.height,this._coreBrowserService.dpr,this._deviceMaxTextureSize);this._charAtlas!==e&&(this._onChangeTextureAtlas.fire(e.pages[0].canvas),this._charAtlasDisposable.value=kc(Kl.forward(e.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas),Kl.forward(e.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas))),this._charAtlas=e,this._charAtlas.warmUp(),this._glyphRenderer.value?.setAtlas(this._charAtlas)}_clearModel(e){this._model.clear(),e&&this._glyphRenderer.value?.clear()}clearTextureAtlas(){this._charAtlas?.clearTexture(),this._clearModel(!0),this._requestRedrawViewport()}clear(){this._clearModel(!0);for(let e of this._renderLayers)e.reset(this._terminal);this._cursorBlinkStateManager.value?.restartBlinkAnimation(),this._updateCursorBlink()}renderRows(e,t){if(!this._isAttached)if(this._core.screenElement?.isConnected&&this._charSizeService.width&&this._charSizeService.height)this._updateDimensions(),this._refreshCharAtlas(),this._isAttached=!0;else return;for(let n of this._renderLayers)n.handleGridChanged(this._terminal,e,t);!this._glyphRenderer.value||!this._rectangleRenderer.value||(this._glyphRenderer.value.beginFrame()?(this._clearModel(!0),this._updateModel(0,this._terminal.rows-1)):this._updateModel(e,t),this._rectangleRenderer.value.renderBackgrounds(),this._glyphRenderer.value.render(this._model),(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible)&&this._rectangleRenderer.value.renderCursor())}_updateCursorBlink(){this._coreService.decPrivateModes.cursorBlink??this._terminal.options.cursorBlink?this._cursorBlinkStateManager.value=new Su(()=>{this._requestRedrawCursor()},this._coreBrowserService):this._cursorBlinkStateManager.clear(),this._requestRedrawCursor()}_updateModel(e,t){let n=this._core,r=this._workCell,i,a,o,s,c,l,u=0,d=!0,f,p,m,h,g,_,v,y,b;e=Ef(e,n.rows-1,0),t=Ef(t,n.rows-1,0);let x=this._coreService.decPrivateModes.cursorStyle??n.options.cursorStyle??`block`,ee=this._terminal.buffer.active.baseY+this._terminal.buffer.active.cursorY,S=ee-n.buffer.ydisp,C=Math.min(this._terminal.buffer.active.cursorX,n.cols-1),w=-1,te=this._coreService.isCursorInitialized&&!this._coreService.isCursorHidden&&(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible);this._model.cursor=void 0;let T=!1;for(a=e;a<=t;a++)for(o=a+n.buffer.ydisp,s=n.buffer.lines.get(o),this._model.lineLengths[a]=0,m=ee===o,u=0,c=this._characterJoinerService.getJoinedCharacters(o),y=0;y<n.cols;y++){if(i=this._cellColorResolver.result.bg,s.loadCell(y,r),y===0&&(i=this._cellColorResolver.result.bg),l=!1,d=y>=u,f=y,c.length>0&&y===c[0][0]&&d){p=c.shift();let e=this._model.selection.isCellSelected(this._terminal,p[0],o);for(v=p[0]+1;v<p[1];v++)d&&=e===this._model.selection.isCellSelected(this._terminal,v,o);d&&=!m||C<p[0]||C>=p[1],d?(l=!0,r=new Tf(r,s.translateToString(!0,p[0],p[1]),p[1]-p[0]),f=p[1]-1):u=p[1]}if(h=r.getChars(),g=r.getCode(),v=(a*n.cols+y)*Uu,this._cellColorResolver.resolve(r,y,o,this.dimensions.device.cell.width),te&&o===ee&&(y===C&&(this._model.cursor={x:C,y:S,width:r.getWidth(),style:this._coreBrowserService.isFocused?x:n.options.cursorInactiveStyle,cursorWidth:n.options.cursorWidth,dpr:this._devicePixelRatio},w=C+r.getWidth()-1),y>=C&&y<=w&&(this._coreBrowserService.isFocused&&x===`block`||this._coreBrowserService.isFocused===!1&&n.options.cursorInactiveStyle===`block`)&&(this._cellColorResolver.result.fg=50331648|this._themeService.colors.cursorAccent.rgba>>8&16777215,this._cellColorResolver.result.bg=50331648|this._themeService.colors.cursor.rgba>>8&16777215)),g!==0&&(this._model.lineLengths[a]=y+1),!(this._model.cells[v]===g&&this._model.cells[v+Wu]===this._cellColorResolver.result.bg&&this._model.cells[v+Gu]===this._cellColorResolver.result.fg&&this._model.cells[v+Ku]===this._cellColorResolver.result.ext)&&(T=!0,h.length>1&&(g|=qu),this._model.cells[v]=g,this._model.cells[v+Wu]=this._cellColorResolver.result.bg,this._model.cells[v+Gu]=this._cellColorResolver.result.fg,this._model.cells[v+Ku]=this._cellColorResolver.result.ext,_=r.getWidth(),this._glyphRenderer.value.updateCell(y,a,g,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext,h,_,i),l)){for(r=this._workCell,y++;y<=f;y++)b=(a*n.cols+y)*Uu,this._glyphRenderer.value.updateCell(y,a,0,0,0,0,Hc,0,0),this._model.cells[b]=0,this._model.cells[b+Wu]=this._cellColorResolver.result.bg,this._model.cells[b+Gu]=this._cellColorResolver.result.fg,this._model.cells[b+Ku]=this._cellColorResolver.result.ext;y--}}T&&this._rectangleRenderer.value.updateBackgrounds(this._model),this._rectangleRenderer.value.updateCursor(this._model)}_updateDimensions(){!this._charSizeService.width||!this._charSizeService.height||(this.dimensions.device.char.width=Math.floor(this._charSizeService.width*this._devicePixelRatio),this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*this._devicePixelRatio),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.top=this._optionsService.rawOptions.lineHeight===1?0:Math.round((this.dimensions.device.cell.height-this.dimensions.device.char.height)/2),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.char.left=Math.floor(this._optionsService.rawOptions.letterSpacing/2),this.dimensions.device.canvas.height=this._terminal.rows*this.dimensions.device.cell.height,this.dimensions.device.canvas.width=this._terminal.cols*this.dimensions.device.cell.width,this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/this._devicePixelRatio),this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/this._devicePixelRatio),this.dimensions.css.cell.height=this.dimensions.device.cell.height/this._devicePixelRatio,this.dimensions.css.cell.width=this.dimensions.device.cell.width/this._devicePixelRatio)}_setCanvasDevicePixelDimensions(e,t){this._canvas.width===e&&this._canvas.height===t||(this._canvas.width=e,this._canvas.height=t,this._requestRedrawViewport())}_requestRedrawViewport(){this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1})}_requestRedrawCursor(){let e=this._terminal.buffer.active.cursorY;this._onRequestRedraw.fire({start:e,end:e})}},Tf=class extends Vl{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}};function Ef(e,t,n=0){return Math.max(Math.min(e,t),n)}var Df=`di$target`,Of=`di$dependencies`,kf=new Map;function Af(e){if(kf.has(e))return kf.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);jf(t,e,r)};return t._id=e,kf.set(e,t),t}function jf(e,t,n){t[Df]===t?t[Of].push({id:e,index:n}):(t[Of]=[{id:e,index:n}],t[Df]=t)}Af(`BufferService`),Af(`CoreMouseService`),Af(`CoreService`),Af(`CharsetService`),Af(`InstantiationService`),Af(`LogService`);var Mf=Af(`OptionsService`);Af(`OscLinkService`),Af(`UnicodeService`),Af(`DecorationService`);var Nf={trace:0,debug:1,info:2,warn:3,error:4,off:5},Pf=`xterm.js: `,Ff=class extends Nc{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),If=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=Nf[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:Pf)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};Ff=ac([oc(0,Mf)],Ff);var If,Lf=class extends Nc{constructor(e){if(Bc&&Vc()<16&&!document.createElement(`canvas`).getContext(`webgl2`,{antialias:!1,depth:!1,preserveDrawingBuffer:!0}))throw Error(`Webgl2 is only supported on Safari 16 and above`);super(),this._preserveDrawingBuffer=e,this._onChangeTextureAtlas=this._register(new au),this.onChangeTextureAtlas=this._onChangeTextureAtlas.event,this._onAddTextureAtlasCanvas=this._register(new au),this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=this._register(new au),this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._onContextLoss=this._register(new au),this.onContextLoss=this._onContextLoss.event}activate(e){let t=e._core;if(!e.element){this._register(t.onWillOpen(()=>this.activate(e)));return}this._terminal=e;let n=t.coreService,r=t.optionsService,i=t,a=i._renderService,o=i._characterJoinerService,s=i._charSizeService,c=i._coreBrowserService,l=i._decorationService;i._logService;let u=i._themeService;this._renderer=this._register(new wf(e,o,s,c,n,l,r,u,this._preserveDrawingBuffer)),this._register(Kl.forward(this._renderer.onContextLoss,this._onContextLoss)),this._register(Kl.forward(this._renderer.onChangeTextureAtlas,this._onChangeTextureAtlas)),this._register(Kl.forward(this._renderer.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas)),this._register(Kl.forward(this._renderer.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas)),a.setRenderer(this._renderer),this._register(Ac(()=>{if(this._terminal._core._store._isDisposed)return;let t=this._terminal._core._renderService;t.setRenderer(this._terminal._core._createRenderer()),t.handleResize(e.cols,e.rows)}))}get textureAtlas(){return this._renderer?.textureAtlas}clearTextureAtlas(){this._renderer?.clearTextureAtlas()}},Rf;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(Rf||={});var zf;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(zf||={});var q=Rf.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Bf=e=>{switch(typeof e){case`undefined`:return q.undefined;case`string`:return q.string;case`number`:return Number.isNaN(e)?q.nan:q.number;case`boolean`:return q.boolean;case`function`:return q.function;case`bigint`:return q.bigint;case`symbol`:return q.symbol;case`object`:return Array.isArray(e)?q.array:e===null?q.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?q.promise:typeof Map<`u`&&e instanceof Map?q.map:typeof Set<`u`&&e instanceof Set?q.set:typeof Date<`u`&&e instanceof Date?q.date:q.object;default:return q.unknown}},J=Rf.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]),Vf=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Rf.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Vf.create=e=>new Vf(e);var Hf=(e,t)=>{let n;switch(e.code){case J.invalid_type:n=e.received===q.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case J.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Rf.jsonStringifyReplacer)}`;break;case J.unrecognized_keys:n=`Unrecognized key(s) in object: ${Rf.joinValues(e.keys,`, `)}`;break;case J.invalid_union:n=`Invalid input`;break;case J.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Rf.joinValues(e.options)}`;break;case J.invalid_enum_value:n=`Invalid enum value. Expected ${Rf.joinValues(e.options)}, received '${e.received}'`;break;case J.invalid_arguments:n=`Invalid function arguments`;break;case J.invalid_return_type:n=`Invalid function return type`;break;case J.invalid_date:n=`Invalid date`;break;case J.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Rf.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case J.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case J.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case J.custom:n=`Invalid input`;break;case J.invalid_intersection_types:n=`Intersection results could not be merged`;break;case J.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case J.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,Rf.assertNever(e)}return{message:n}},Uf=Hf;function Wf(){return Uf}var Gf=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function Y(e,t){let n=Wf(),r=Gf({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Hf?void 0:Hf].filter(e=>!!e)});e.common.issues.push(r)}var Kf=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return X;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return X;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},X=Object.freeze({status:`aborted`}),qf=e=>({status:`dirty`,value:e}),Jf=e=>({status:`valid`,value:e}),Yf=e=>e.status===`aborted`,Xf=e=>e.status===`dirty`,Zf=e=>e.status===`valid`,Qf=e=>typeof Promise<`u`&&e instanceof Promise,Z;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(Z||={});var $f=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ep=(e,t)=>{if(Zf(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new Vf(e.common.issues);return this._error=t,this._error}}};function tp(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var np=class{get description(){return this._def.description}_getType(e){return Bf(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Bf(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Kf,ctx:{common:e.parent.common,data:e.data,parsedType:Bf(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Qf(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Bf(e)};return ep(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Bf(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Zf(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Zf(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Bf(e)},r=this._parse({data:e,path:n.path,parent:n});return ep(n,await(Qf(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:J.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new am({schema:this,typeName:Q.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return om.create(this,this._def)}nullable(){return sm.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Bp.create(this)}promise(){return im.create(this,this._def)}or(e){return Up.create([this,e],this._def)}and(e){return qp.create(this,e,this._def)}transform(e){return new am({...tp(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new cm({...tp(this._def),innerType:this,defaultValue:t,typeName:Q.ZodDefault})}brand(){return new dm({typeName:Q.ZodBranded,type:this,...tp(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new lm({...tp(this._def),innerType:this,catchValue:t,typeName:Q.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return fm.create(this,e)}readonly(){return pm.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},rp=/^c[^\s-]{8,}$/i,ip=/^[0-9a-z]+$/,ap=/^[0-9A-HJKMNP-TV-Z]{26}$/i,op=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sp=/^[a-z0-9_-]{21}$/i,cp=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,lp=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,up=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,dp=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,fp,pp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,mp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,hp=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,gp=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_p=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,vp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,yp=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,bp=RegExp(`^${yp}$`);function xp(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Sp(e){return RegExp(`^${xp(e)}$`)}function Cp(e){let t=`${yp}T${xp(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function wp(e,t){return!!((t===`v4`||!t)&&pp.test(e)||(t===`v6`||!t)&&hp.test(e))}function Tp(e,t){if(!cp.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Ep(e,t){return!!((t===`v4`||!t)&&mp.test(e)||(t===`v6`||!t)&&gp.test(e))}var Dp=class e extends np{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==q.string){let t=this._getOrReturnCtx(e);return Y(t,{code:J.invalid_type,expected:q.string,received:t.parsedType}),X}let t=new Kf,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),Y(n,{code:J.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),Y(n,{code:J.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?Y(n,{code:J.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&Y(n,{code:J.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)up.test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`email`,code:J.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)fp||=new RegExp(dp,`u`),fp.test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`emoji`,code:J.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)op.test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`uuid`,code:J.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)sp.test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`nanoid`,code:J.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)rp.test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`cuid`,code:J.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)ip.test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`cuid2`,code:J.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)ap.test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`ulid`,code:J.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),Y(n,{validation:`url`,code:J.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`regex`,code:J.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),Y(n,{code:J.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),Y(n,{code:J.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),Y(n,{code:J.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Cp(r).test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{code:J.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?bp.test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{code:J.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Sp(r).test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{code:J.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?lp.test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`duration`,code:J.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?wp(e.data,r.version)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`ip`,code:J.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Tp(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`jwt`,code:J.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Ep(e.data,r.version)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`cidr`,code:J.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?_p.test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`base64`,code:J.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?vp.test(e.data)||(n=this._getOrReturnCtx(e,n),Y(n,{validation:`base64url`,code:J.invalid_string,message:r.message}),t.dirty()):Rf.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:J.invalid_string,...Z.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...Z.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...Z.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...Z.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...Z.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...Z.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...Z.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...Z.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...Z.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...Z.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...Z.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...Z.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...Z.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...Z.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Z.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...Z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...Z.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...Z.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...Z.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...Z.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...Z.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...Z.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...Z.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...Z.errToObj(t)})}nonempty(e){return this.min(1,Z.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Dp.create=e=>new Dp({checks:[],typeName:Q.ZodString,coerce:e?.coerce??!1,...tp(e)});function Op(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var kp=class e extends np{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==q.number){let t=this._getOrReturnCtx(e);return Y(t,{code:J.invalid_type,expected:q.number,received:t.parsedType}),X}let t,n=new Kf;for(let r of this._def.checks)r.kind===`int`?Rf.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Y(t,{code:J.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),Y(t,{code:J.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),Y(t,{code:J.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Op(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),Y(t,{code:J.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Y(t,{code:J.not_finite,message:r.message}),n.dirty()):Rf.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,Z.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,Z.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,Z.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,Z.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Z.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:Z.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:Z.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:Z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:Z.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:Z.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:Z.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:Z.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&Rf.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};kp.create=e=>new kp({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...tp(e)});var Ap=class e extends np{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==q.bigint)return this._getInvalidInput(e);let t,n=new Kf;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),Y(t,{code:J.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),Y(t,{code:J.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),Y(t,{code:J.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):Rf.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return Y(t,{code:J.invalid_type,expected:q.bigint,received:t.parsedType}),X}gte(e,t){return this.setLimit(`min`,e,!0,Z.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,Z.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,Z.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,Z.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Z.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:Z.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:Z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:Z.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ap.create=e=>new Ap({checks:[],typeName:Q.ZodBigInt,coerce:e?.coerce??!1,...tp(e)});var jp=class extends np{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==q.boolean){let t=this._getOrReturnCtx(e);return Y(t,{code:J.invalid_type,expected:q.boolean,received:t.parsedType}),X}return Jf(e.data)}};jp.create=e=>new jp({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...tp(e)});var Mp=class e extends np{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==q.date){let t=this._getOrReturnCtx(e);return Y(t,{code:J.invalid_type,expected:q.date,received:t.parsedType}),X}if(Number.isNaN(e.data.getTime()))return Y(this._getOrReturnCtx(e),{code:J.invalid_date}),X;let t=new Kf,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),Y(n,{code:J.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),Y(n,{code:J.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):Rf.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:Z.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:Z.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Mp.create=e=>new Mp({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...tp(e)});var Np=class extends np{_parse(e){if(this._getType(e)!==q.symbol){let t=this._getOrReturnCtx(e);return Y(t,{code:J.invalid_type,expected:q.symbol,received:t.parsedType}),X}return Jf(e.data)}};Np.create=e=>new Np({typeName:Q.ZodSymbol,...tp(e)});var Pp=class extends np{_parse(e){if(this._getType(e)!==q.undefined){let t=this._getOrReturnCtx(e);return Y(t,{code:J.invalid_type,expected:q.undefined,received:t.parsedType}),X}return Jf(e.data)}};Pp.create=e=>new Pp({typeName:Q.ZodUndefined,...tp(e)});var Fp=class extends np{_parse(e){if(this._getType(e)!==q.null){let t=this._getOrReturnCtx(e);return Y(t,{code:J.invalid_type,expected:q.null,received:t.parsedType}),X}return Jf(e.data)}};Fp.create=e=>new Fp({typeName:Q.ZodNull,...tp(e)});var Ip=class extends np{constructor(){super(...arguments),this._any=!0}_parse(e){return Jf(e.data)}};Ip.create=e=>new Ip({typeName:Q.ZodAny,...tp(e)});var Lp=class extends np{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Jf(e.data)}};Lp.create=e=>new Lp({typeName:Q.ZodUnknown,...tp(e)});var Rp=class extends np{_parse(e){let t=this._getOrReturnCtx(e);return Y(t,{code:J.invalid_type,expected:q.never,received:t.parsedType}),X}};Rp.create=e=>new Rp({typeName:Q.ZodNever,...tp(e)});var zp=class extends np{_parse(e){if(this._getType(e)!==q.undefined){let t=this._getOrReturnCtx(e);return Y(t,{code:J.invalid_type,expected:q.void,received:t.parsedType}),X}return Jf(e.data)}};zp.create=e=>new zp({typeName:Q.ZodVoid,...tp(e)});var Bp=class e extends np{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==q.array)return Y(t,{code:J.invalid_type,expected:q.array,received:t.parsedType}),X;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(Y(t,{code:e?J.too_big:J.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(Y(t,{code:J.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(Y(t,{code:J.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new $f(t,e,t.path,n)))).then(e=>Kf.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new $f(t,e,t.path,n)));return Kf.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:Z.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:Z.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:Z.toString(n)}})}nonempty(e){return this.min(1,e)}};Bp.create=(e,t)=>new Bp({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...tp(t)});function Vp(e){if(e instanceof Hp){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=om.create(Vp(r))}return new Hp({...e._def,shape:()=>t})}else if(e instanceof Bp)return new Bp({...e._def,type:Vp(e.element)});else if(e instanceof om)return om.create(Vp(e.unwrap()));else if(e instanceof sm)return sm.create(Vp(e.unwrap()));else if(e instanceof Jp)return Jp.create(e.items.map(e=>Vp(e)));else return e}var Hp=class e extends np{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=Rf.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==q.object){let t=this._getOrReturnCtx(e);return Y(t,{code:J.invalid_type,expected:q.object,received:t.parsedType}),X}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Rp&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new $f(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Rp){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(Y(n,{code:J.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new $f(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Kf.mergeObjectSync(t,e)):Kf.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return Z.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:Z.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of Rf.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of Rf.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Vp(this)}partial(t){let n={};for(let e of Rf.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of Rf.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof om;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return tm(Rf.objectKeys(this.shape))}};Hp.create=(e,t)=>new Hp({shape:()=>e,unknownKeys:`strip`,catchall:Rp.create(),typeName:Q.ZodObject,...tp(t)}),Hp.strictCreate=(e,t)=>new Hp({shape:()=>e,unknownKeys:`strict`,catchall:Rp.create(),typeName:Q.ZodObject,...tp(t)}),Hp.lazycreate=(e,t)=>new Hp({shape:e,unknownKeys:`strip`,catchall:Rp.create(),typeName:Q.ZodObject,...tp(t)});var Up=class extends np{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new Vf(e.ctx.common.issues));return Y(t,{code:J.invalid_union,unionErrors:n}),X}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new Vf(e));return Y(t,{code:J.invalid_union,unionErrors:i}),X}}get options(){return this._def.options}};Up.create=(e,t)=>new Up({options:e,typeName:Q.ZodUnion,...tp(t)});var Wp=e=>e instanceof $p?Wp(e.schema):e instanceof am?Wp(e.innerType()):e instanceof em?[e.value]:e instanceof nm?e.options:e instanceof rm?Rf.objectValues(e.enum):e instanceof cm?Wp(e._def.innerType):e instanceof Pp?[void 0]:e instanceof Fp?[null]:e instanceof om?[void 0,...Wp(e.unwrap())]:e instanceof sm?[null,...Wp(e.unwrap())]:e instanceof dm||e instanceof pm?Wp(e.unwrap()):e instanceof lm?Wp(e._def.innerType):[],Gp=class e extends np{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==q.object)return Y(t,{code:J.invalid_type,expected:q.object,received:t.parsedType}),X;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(Y(t,{code:J.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),X)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=Wp(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...tp(r)})}};function Kp(e,t){let n=Bf(e),r=Bf(t);if(e===t)return{valid:!0,data:e};if(n===q.object&&r===q.object){let n=Rf.objectKeys(t),r=Rf.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Kp(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===q.array&&r===q.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Kp(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===q.date&&r===q.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var qp=class extends np{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Yf(e)||Yf(r))return X;let i=Kp(e.value,r.value);return i.valid?((Xf(e)||Xf(r))&&t.dirty(),{status:t.value,value:i.data}):(Y(n,{code:J.invalid_intersection_types}),X)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};qp.create=(e,t,n)=>new qp({left:e,right:t,typeName:Q.ZodIntersection,...tp(n)});var Jp=class e extends np{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.array)return Y(n,{code:J.invalid_type,expected:q.array,received:n.parsedType}),X;if(n.data.length<this._def.items.length)return Y(n,{code:J.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),X;!this._def.rest&&n.data.length>this._def.items.length&&(Y(n,{code:J.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new $f(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Kf.mergeArray(t,e)):Kf.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Jp.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Jp({items:e,typeName:Q.ZodTuple,rest:null,...tp(t)})};var Yp=class e extends np{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.object)return Y(n,{code:J.invalid_type,expected:q.object,received:n.parsedType}),X;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new $f(n,e,n.path,e)),value:a._parse(new $f(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Kf.mergeObjectAsync(t,r):Kf.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof np?new e({keyType:t,valueType:n,typeName:Q.ZodRecord,...tp(r)}):new e({keyType:Dp.create(),valueType:t,typeName:Q.ZodRecord,...tp(n)})}},Xp=class extends np{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.map)return Y(n,{code:J.invalid_type,expected:q.map,received:n.parsedType}),X;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new $f(n,e,n.path,[a,`key`])),value:i._parse(new $f(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return X;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return X;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Xp.create=(e,t,n)=>new Xp({valueType:t,keyType:e,typeName:Q.ZodMap,...tp(n)});var Zp=class e extends np{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.set)return Y(n,{code:J.invalid_type,expected:q.set,received:n.parsedType}),X;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(Y(n,{code:J.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(Y(n,{code:J.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return X;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new $f(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:Z.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:Z.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Zp.create=(e,t)=>new Zp({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...tp(t)});var Qp=class e extends np{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==q.function)return Y(t,{code:J.invalid_type,expected:q.function,received:t.parsedType}),X;function n(e,n){return Gf({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Wf(),Hf].filter(e=>!!e),issueData:{code:J.invalid_arguments,argumentsError:n}})}function r(e,n){return Gf({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Wf(),Hf].filter(e=>!!e),issueData:{code:J.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof im){let e=this;return Jf(async function(...t){let o=new Vf([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return Jf(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new Vf([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new Vf([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Jp.create(t).rest(Lp.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Jp.create([]).rest(Lp.create()),returns:n||Lp.create(),typeName:Q.ZodFunction,...tp(r)})}},$p=class extends np{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};$p.create=(e,t)=>new $p({getter:e,typeName:Q.ZodLazy,...tp(t)});var em=class extends np{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return Y(t,{received:t.data,code:J.invalid_literal,expected:this._def.value}),X}return{status:`valid`,value:e.data}}get value(){return this._def.value}};em.create=(e,t)=>new em({value:e,typeName:Q.ZodLiteral,...tp(t)});function tm(e,t){return new nm({values:e,typeName:Q.ZodEnum,...tp(t)})}var nm=class e extends np{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return Y(t,{expected:Rf.joinValues(n),received:t.parsedType,code:J.invalid_type}),X}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return Y(t,{received:t.data,code:J.invalid_enum_value,options:n}),X}return Jf(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};nm.create=tm;var rm=class extends np{_parse(e){let t=Rf.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==q.string&&n.parsedType!==q.number){let e=Rf.objectValues(t);return Y(n,{expected:Rf.joinValues(e),received:n.parsedType,code:J.invalid_type}),X}if(this._cache||=new Set(Rf.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=Rf.objectValues(t);return Y(n,{received:n.data,code:J.invalid_enum_value,options:e}),X}return Jf(e.data)}get enum(){return this._def.values}};rm.create=(e,t)=>new rm({values:e,typeName:Q.ZodNativeEnum,...tp(t)});var im=class extends np{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==q.promise&&t.common.async===!1?(Y(t,{code:J.invalid_type,expected:q.promise,received:t.parsedType}),X):Jf((t.parsedType===q.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};im.create=(e,t)=>new im({type:e,typeName:Q.ZodPromise,...tp(t)});var am=class extends np{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{Y(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return X;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?X:r.status===`dirty`||t.value===`dirty`?qf(r.value):r});{if(t.value===`aborted`)return X;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?X:r.status===`dirty`||t.value===`dirty`?qf(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?X:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?X:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Zf(e))return X;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Zf(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):X);Rf.assertNever(r)}};am.create=(e,t,n)=>new am({schema:e,typeName:Q.ZodEffects,effect:t,...tp(n)}),am.createWithPreprocess=(e,t,n)=>new am({schema:t,effect:{type:`preprocess`,transform:e},typeName:Q.ZodEffects,...tp(n)});var om=class extends np{_parse(e){return this._getType(e)===q.undefined?Jf(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};om.create=(e,t)=>new om({innerType:e,typeName:Q.ZodOptional,...tp(t)});var sm=class extends np{_parse(e){return this._getType(e)===q.null?Jf(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};sm.create=(e,t)=>new sm({innerType:e,typeName:Q.ZodNullable,...tp(t)});var cm=class extends np{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===q.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};cm.create=(e,t)=>new cm({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...tp(t)});var lm=class extends np{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Qf(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new Vf(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new Vf(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};lm.create=(e,t)=>new lm({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...tp(t)});var um=class extends np{_parse(e){if(this._getType(e)!==q.nan){let t=this._getOrReturnCtx(e);return Y(t,{code:J.invalid_type,expected:q.nan,received:t.parsedType}),X}return{status:`valid`,value:e.data}}};um.create=e=>new um({typeName:Q.ZodNaN,...tp(e)});var dm=class extends np{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},fm=class e extends np{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?X:e.status===`dirty`?(t.dirty(),qf(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?X:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Q.ZodPipeline})}},pm=class extends np{_parse(e){let t=this._def.innerType._parse(e),n=e=>(Zf(e)&&(e.value=Object.freeze(e.value)),e);return Qf(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};pm.create=(e,t)=>new pm({innerType:e,typeName:Q.ZodReadonly,...tp(t)}),Hp.lazycreate;var Q;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Q||={});var mm=Dp.create,hm=kp.create;um.create,Ap.create;var gm=jp.create;Mp.create,Np.create,Pp.create,Fp.create,Ip.create,Lp.create,Rp.create,zp.create;var _m=Bp.create,vm=Hp.create;Hp.strictCreate,Up.create;var ym=Gp.create;qp.create,Jp.create,Yp.create,Xp.create,Zp.create,Qp.create,$p.create;var bm=em.create,xm=nm.create;rm.create,im.create,am.create,om.create,sm.create,am.createWithPreprocess,fm.create,ym(`type`,[vm({type:bm(`input`),data:mm().min(1)}),vm({type:bm(`resize`),cols:hm().int().min(2),rows:hm().int().min(2),claim:xm([`attach`]).optional(),user:gm().optional()}),vm({type:bm(`typing`),active:gm()}),vm({type:bm(`toggle_collab`),enabled:gm()}),vm({type:bm(`take_control`)}),vm({type:bm(`release_control`)}),vm({type:bm(`ping`),t:hm()}),vm({type:bm(`kill_session`)})]);var Sm=vm({id:mm(),name:mm(),color:mm(),typing:gm(),lastActive:hm()}),Cm=ym(`type`,[vm({type:bm(`hello`),clientId:mm(),roomId:mm(),color:mm(),collabMode:gm(),controllerId:mm().nullable(),created:gm().optional()}),vm({type:bm(`presence`),clients:_m(Sm)}),vm({type:bm(`output`),data:mm()}),vm({type:bm(`snapshot`),data:mm(),alternateScreen:gm().optional(),cursorHidden:gm().optional(),keyboardEnhanced:gm().optional(),mouseReporting:gm().optional(),mouseSgr:gm().optional(),capped:gm().optional()}),vm({type:bm(`collab`),enabled:gm(),controllerId:mm().nullable()}),vm({type:bm(`input_rejected`),reason:mm()}),vm({type:bm(`error`),message:mm()}),vm({type:bm(`session_ended`),exitCode:hm().int().nullable(),signal:mm().nullable(),message:mm(),by:mm().optional()}),vm({type:bm(`session_renamed`),displayName:mm()}),vm({type:bm(`cwd_changed`),cwd:mm()}),vm({type:bm(`pong`),t:hm()}),vm({type:bm(`active_size`),clientId:mm(),cols:hm().int(),rows:hm().int()})]),wm=e=>{try{let t=JSON.parse(e),n=Cm.safeParse(t);return n.success?n.data:null}catch{return null}},Tm=(e,t)=>[...e].sort((e,n)=>t&&e.id===t?-1:t&&n.id===t?1:e.name.localeCompare(n.name)),Em=e=>e.typing?`typing`:(Date.now()-e.lastActive)/1e3<15?`active`:`idle`,Dm=800,Om=e=>{let t=e.charCodeAt(0);return t>=32&&t<=126},km=e=>{let t=``,n=0;for(;n<e.length;){let r=e[n];if(r===`\x1B`){if(n+=1,e[n]===`[`)for(n+=1;n<e.length;){let t=e.charCodeAt(n);if(t>=64&&t<=126){n+=1;break}n+=1}else n+=1;continue}Om(r)&&(t+=r),n+=1}return t},Am=(e={})=>{let t=e.maxPendingMs??Dm,n=e.now??(()=>Date.now()),r=``,i=0,a=0;return{onInput:(e,t)=>{if(!t)return``;let a=km(e);return a?(r+=a,i=n(),a):``},reconcileOutput:e=>{if(!r)return e;if(n()-i>t)return r=``,a=0,e;{let t=0,n=!1;for(;t<e.length;){if(e[t]===`\x1B`){if(e[t+1]===`[`){let r=t+2;for(;r<e.length;){let t=e.charCodeAt(r);if(r+=1,t>=64&&t<=126){e[r-1]!==`m`&&(n=!0);break}}t=r;continue}n=!0;break}t+=1}if(n)return r=``,a=0,e}let o=``,s=0,c=0,l=!1;for(;s<e.length;){let t=e[s];if(t===`\x1B`){let t=s+1;if(e[t]===`[`)for(t+=1;t<e.length;){let n=e.charCodeAt(t);if(t+=1,n>=64&&n<=126)break}else t+=1;o+=e.slice(s,t),s=t;continue}if(!l&&c<r.length&&Om(t)&&t===r[c]){c+=1,s+=1;continue}!l&&c<r.length&&Om(t)&&(l=!0),o+=t,s+=1}return c>0?(r=r.slice(c),a=0,o):(a+=1,a>=2&&(r=``,a=0),e)},reset:()=>{r=``,a=0},getPending:()=>r}},jm=(e,t)=>e.deltaMode===1?e.deltaY*t.linesPerNotch:e.deltaY/Math.max(1,t.lineHeightPx())*t.linesPerNotch,Mm=e=>e.buffer.active.type===`normal`&&(e.modes?.mouseTrackingMode??`none`)===`none`,Nm=e=>e.deltaMode===1||Math.abs(e.deltaY)>=40&&Number.isInteger(e.deltaY),Pm=(e,t,n)=>{let r=0,i=0,a=!1,o=0,s=0,c=0,l=0,u=0,d=()=>{l&&cancelAnimationFrame(l),u&&window.clearTimeout(u),l=0,u=0,r=0,i=0,o=0},f=0,p=0,m=0,h=0,g=0,_=0,v=null,y=null,b=()=>{m&&cancelAnimationFrame(m),h&&window.clearTimeout(h),m=0,h=0,f=0,p=0,g=0},x=()=>{d(),b()},ee=()=>{if(!(!v||!y)){a=!0;try{v.dispatchEvent(new WheelEvent(`wheel`,{deltaY:y.deltaY,deltaMode:0,clientX:y.clientX,clientY:y.clientY,bubbles:!0,cancelable:!0}))}catch{}finally{a=!1}}},S=e=>{m=0;let n=t();if(!n||Mm(n)||Math.abs(f)<4)return b();let r=c?Math.min(.05,(e-c)/1e3):.016;c=e,p+=Math.abs(f)*r;let i=Math.trunc(p);for(p-=i;i-->0;)ee();f*=Math.exp(-r/.35),m=requestAnimationFrame(S)},C=e=>{v=e.target,y={deltaY:e.deltaY,clientX:e.clientX,clientY:e.clientY},m&&=(cancelAnimationFrame(m),0);let t=e.timeStamp||performance.now(),n=t-_;_=t,n>250&&(g=0),g+=1;for(let e=1;e<3;e++)ee();let r=3/(Math.min(Math.max(n,30),200)/1e3),i=Math.sign(e.deltaY)*r;f=Math.sign(i)===Math.sign(f)?.6*i+.4*f:i,f=Math.max(-90,Math.min(90,f)),h&&window.clearTimeout(h),h=window.setTimeout(()=>{h=0,g>=3&&Math.abs(f)>=4?(c=0,m=requestAnimationFrame(S)):b()},80)},w=e=>{l=0;let n=t();if(!n||!Mm(n)||Math.abs(r)<8)return x();let a=c?Math.min(.05,(e-c)/1e3):.016;c=e,i+=r*a;let o=Math.trunc(i);if(o!==0){i-=o;let e=n.buffer.active.viewportY;if(n.scrollLines(o),n.buffer.active.viewportY===e)return x()}r*=Math.exp(-a/.35),l=requestAnimationFrame(w)},te=e=>{if(a)return;let i=t();if(!i)return;if(!Mm(i)){d(),Nm(e)?C(e):b();return}if(b(),!Nm(e))return x();l&&=(cancelAnimationFrame(l),0);let f=e.timeStamp||performance.now(),p=f-s;s=f,p>250&&(o=0),o+=1;let m=jm(e,n)/(Math.min(Math.max(p,30),200)/1e3);r=Math.sign(m)===Math.sign(r)?.6*m+.4*r:m,r=Math.max(-2500,Math.min(2500,r)),u&&window.clearTimeout(u),u=window.setTimeout(()=>{u=0,o>=3&&Math.abs(r)>=8?(c=0,l=requestAnimationFrame(w)):x()},80)},T=()=>x();return e.addEventListener(`wheel`,te,{capture:!0,passive:!0}),e.addEventListener(`mousedown`,T,!0),window.addEventListener(`keydown`,T,!0),()=>{x(),e.removeEventListener(`wheel`,te,{capture:!0}),e.removeEventListener(`mousedown`,T,!0),window.removeEventListener(`keydown`,T,!0)}},Fm=2e3,Im=(e,t)=>{if(!t)return[];let n=e.buffer.active,r=t.toLowerCase(),i=[];for(let e=0;e<n.length&&i.length<Fm;e++){let t=(n.getLine(e)?.translateToString(!0)??``).toLowerCase(),a=0;for(;i.length<Fm;){let n=t.indexOf(r,a);if(n===-1)break;i.push({row:e,col:n}),a=n+r.length}}return i},Lm=(e,t,n,r)=>{if(t.length===0)return-1;let i=(n%t.length+t.length)%t.length,a=t[i];return e.select(a.col,a.row,r),e.scrollToLine?.(Math.max(0,a.row-Math.floor(e.rows/2))),i},Rm=()=>window.SpeechRecognition||window.webkitSpeechRecognition,zm=e=>{let t=e.thresholdMs??550,n=0,r=!1,i=0,a=``,o=``,s=null,c=t=>{if(!r)return;r=!1,s=null,e.setOverlay(null);let n=(a||o).trim();a=``,o=``,t&&n&&e.send(n)},l=()=>{if(r)return;let t=Rm();if(!t)return;let n;try{n=new t}catch{return}r=!0,a=``,o=``;for(let t=0;t<Math.max(1,i);t++)e.send(``);i=0,n.lang=navigator.language||`en-US`,n.continuous=!0,n.interimResults=!0,n.onresult=t=>{let n=``;for(let e=t.resultIndex;e<t.results.length;e++){let r=t.results[e];r.isFinal?a+=r[0].transcript:n+=r[0].transcript}o=n,e.setOverlay((a+n).trim())},n.onerror=t=>{let n=t?.error||`unknown`;n===`not-allowed`||n===`service-not-allowed`?e.notify(`Microphone permission needed for voice input`):n===`network`?e.notify(`Voice recognition unreachable (browser speech service) — try again`):n===`no-speech`?e.notify(`No speech detected`):n!==`aborted`&&e.notify(`Voice input failed: ${n}`),c(!1)},n.onend=()=>c(!0),s=n,e.setOverlay(``);try{n.start()}catch{c(!1)}},u=()=>{let e=s;if(e)try{e.stop()}catch{c(!0)}else c(!0)};return{handleKey:a=>{if(a.code===`Space`&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.shiftKey&&Rm()&&(r||e.eligible()))return a.type===`keydown`?r||a.repeat?!1:(window.clearTimeout(n),i=1,n=window.setTimeout(l,t),!0):a.type===`keyup`?(window.clearTimeout(n),i=0,r?(u(),!1):!0):void 0;a.type===`keydown`&&a.code!==`Space`&&window.clearTimeout(n)},dispose:()=>{if(window.clearTimeout(n),r)try{s?.stop()}catch{}r=!1,s=null,e.setOverlay(null)},isActive:()=>r}},Bm=(e,t)=>e||!!t&&Vm(t),Vm=e=>{try{let t=e.buffer.active.baseY+e.rows,n=``;for(let r=Math.max(0,t-30);r<t;r++)n+=(e.buffer.active.getLine(r)?.translateToString(!0)??``)+`
126
- `;return/bypass permissions on|shift\+tab to cycle|esc to interrupt|\? for shortcuts/i.test(n)}catch{return!1}},Hm=/\x1b\[([<>=])[0-9;:]*u|\x1b\[>([0-9;]*)m/g,Um=(e,t)=>{let n=t;Hm.lastIndex=0;let r;for(;(r=Hm.exec(e))!==null;)if(r[1]!==void 0)n=r[1]!==`<`;else{let e=(r[2]??``).split(`;`);e[0]===`4`&&(n=(e[1]??`0`)!==`0`)}return n},Wm=e=>/Mac|iPhone|iPad/i.test(e)?`Browsers can't see file paths — select the file in Finder, press ⌘⌥C, then paste here.`:/Win/i.test(e)?`Browsers can't see file paths — select the file in Explorer, press Ctrl+Shift+C, then paste here.`:`Browsers can't see file paths — copy the path in your file manager, then paste here.`,Gm=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),Km=o(((e,t)=>{t.exports=Gm()})),qm=m(),$=Km(),Jm=()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent||``;return/iPad|iPhone|iPod/.test(e)},Ym={abc:[[`q`,`w`,`e`,`r`,`t`,`y`,`u`,`i`,`o`,`p`],[`a`,`s`,`d`,`f`,`g`,`h`,`j`,`k`,`l`],[`SHIFT`,`z`,`x`,`c`,`v`,`b`,`n`,`m`,`BKSP`],[`123`,`PASTE`,`SPACE`,`RET`]],num:[[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`0`],[`-`,`/`,`:`,`;`,`(`,`)`,`$`,`&`,`@`,`"`],[`#+=`,`.`,`,`,`?`,`!`,`'`,`BKSP`],[`ABC`,`PASTE`,`SPACE`,`RET`]],sym:[[`[`,`]`,`{`,`}`,`#`,`%`,`^`,`*`,`+`,`=`],[`_`,`\\`,`|`,`~`,`<`,`>`,"`"],[`123`,`.`,`,`,`?`,`!`,`'`,`BKSP`],[`ABC`,`PASTE`,`SPACE`,`RET`]]},Xm=[{label:`Esc`,key:`\x1B`},{label:`Tab`,key:` `},{label:`Ctrl`,mod:`ctrl`},{label:`Alt`,mod:`alt`},{label:`←`,key:`\x1B[D`},{label:`↓`,key:`\x1B[B`},{label:`↑`,key:`\x1B[A`},{label:`→`,key:`\x1B[C`},{label:`KB`,fn:`sysKb`}],Zm=({filled:e})=>(0,$.jsx)(`svg`,{viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:`1.5`,fill:e?`currentColor`:`none`,children:(0,$.jsx)(`path`,{d:`M12 4L4 16h16L12 4z`})}),Qm=()=>(0,$.jsxs)(`svg`,{viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:`1.5`,fill:`none`,children:[(0,$.jsx)(`path`,{d:`M21 4H8l-7 8 7 8h13a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2z`}),(0,$.jsx)(`line`,{x1:`18`,y1:`9`,x2:`12`,y2:`15`}),(0,$.jsx)(`line`,{x1:`12`,y1:`9`,x2:`18`,y2:`15`})]}),$m=()=>(0,$.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,children:[(0,$.jsx)(`rect`,{x:`2`,y:`6`,width:`20`,height:`12`,rx:`2`}),(0,$.jsx)(`line`,{x1:`6`,y1:`10`,x2:`6.01`,y2:`10`}),(0,$.jsx)(`line`,{x1:`10`,y1:`10`,x2:`10.01`,y2:`10`}),(0,$.jsx)(`line`,{x1:`14`,y1:`10`,x2:`14.01`,y2:`10`}),(0,$.jsx)(`line`,{x1:`18`,y1:`10`,x2:`18.01`,y2:`10`}),(0,$.jsx)(`line`,{x1:`8`,y1:`14`,x2:`16`,y2:`14`})]}),eh=()=>(0,$.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,children:[(0,$.jsx)(`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`}),(0,$.jsx)(`rect`,{x:`8`,y:`2`,width:`8`,height:`4`,rx:`1`,ry:`1`})]}),th=({onInput:e,visible:t,onToggle:n,onHeightChange:r,hapticsEnabled:i=!0,onPasteFailed:a})=>{let[o,s]=(0,_.useState)(`abc`),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(!1),[x,ee]=(0,_.useState)(!1),[S,C]=(0,_.useState)(``),w=(0,_.useRef)(0),te=(0,_.useRef)(null),T=(0,_.useRef)(null),E=(0,_.useRef)(null),ne=(0,_.useRef)(null),re=(0,_.useRef)(null),D=(()=>{try{return new URLSearchParams(window.location.search).get(`diag`)!==`0`}catch{return!0}})(),O=window.__hopKbDiag=window.__hopKbDiag||{taps:0,disp:0,sent:0,buf:0},[k,A]=(0,_.useState)({taps:0,disp:0,sent:0,buf:0});(0,_.useEffect)(()=>{if(!D)return;let e=window.setInterval(()=>A({...O}),300),t=``,n=window.setInterval(()=>{let e=JSON.stringify({...O,at:Date.now()});e.slice(0,e.lastIndexOf(`,`))!==t.slice(0,t.lastIndexOf(`,`))&&(t=e,fetch(`/api/diag`,{method:`POST`,body:e,keepalive:!0}).catch(()=>{}))},4e3);return()=>{window.clearInterval(e),window.clearInterval(n)}},[D]);let j=(0,_.useRef)(e),M=(0,_.useRef)(()=>{}),N=(0,_.useRef)(c),ie=(0,_.useRef)(u),ae=(0,_.useRef)(f),oe=(0,_.useRef)(m),se=(0,_.useRef)(a);j.current=e,N.current=c,ie.current=u,ae.current=f,oe.current=m,se.current=a,(0,_.useEffect)(()=>{if(!Jm())return;let e=document.createElement(`input`);e.type=`checkbox`,e.id=`hay-haptic-switch`,e.setAttribute(`switch`,``),e.style.position=`fixed`,e.style.left=`-9999px`,e.style.top=`-9999px`,e.style.opacity=`0`,e.style.pointerEvents=`none`,document.body.appendChild(e);let t=document.createElement(`label`);return t.htmlFor=`hay-haptic-switch`,t.style.position=`fixed`,t.style.left=`-9999px`,t.style.top=`-9999px`,t.style.opacity=`0`,t.style.pointerEvents=`none`,document.body.appendChild(t),ne.current=t,()=>{document.body.removeChild(e),document.body.removeChild(t),ne.current=null}},[]);let P=e=>{e.currentTarget.classList.add(`kb-pressed`)},F=e=>{e.currentTarget.classList.remove(`kb-pressed`)},I=(0,_.useCallback)(()=>{if(i)try{typeof navigator.vibrate==`function`?navigator.vibrate(8):Jm()&&ne.current?.click()}catch{}},[i]),ce=(0,_.useCallback)(e=>{let t=e;if(ae.current){if(e.length===1){let n=e.toUpperCase().charCodeAt(0);n>=65&&n<=90&&(t=String.fromCharCode(n-64))}p(!1)}oe.current&&(t.length===1&&(t=`\x1B`+t),h(!1)),O.disp++,j.current(t),N.current&&!ie.current&&t.length===1&&(w.current=0)},[]),le=(0,_.useCallback)(async()=>{try{if(navigator.clipboard&&navigator.clipboard.readText){let e=await navigator.clipboard.readText();e&&ce(e)}else se.current?.()}catch{se.current?.()}},[ce]),ue=(0,_.useCallback)(()=>{let e=E.current;if(!e)return;e.style.height=`auto`;let t=Math.min(window.innerHeight*.4,240);e.style.height=`${Math.min(e.scrollHeight,t)}px`},[]),de=(0,_.useCallback)(()=>{E.current?.blur(),v(!1)},[]),L=(0,_.useCallback)(()=>{let e=E.current;if(!e)return;try{e.focus({preventScroll:!0})}catch{e.focus()}let t=e.value.length;typeof e.setSelectionRange==`function`&&e.setSelectionRange(t,t),ue()},[ue]),fe=(0,_.useCallback)(()=>{(0,qm.flushSync)(()=>{v(!0)}),L()},[L]),pe=(0,_.useCallback)(()=>{g?de():fe()},[g,de,fe]),me=(0,_.useCallback)(()=>{let e=S;e&&(ce(e+`\r`),C(``)),E.current&&(E.current.style.height=``),de()},[ce,de,S]);(0,_.useEffect)(()=>{if(!g||!E.current)return;let e=()=>{L()},t=requestAnimationFrame(e),n=requestAnimationFrame(e);return()=>{cancelAnimationFrame(t),cancelAnimationFrame(n)}},[g,ue]),(0,_.useEffect)(()=>{g&&ue()},[S,g,ue]),(0,_.useEffect)(()=>{if(!t){r?.(0);return}let e=re.current;if(!e)return;let n=()=>{r?.(Math.ceil(e.getBoundingClientRect().height))};if(n(),window.addEventListener(`resize`,n),typeof ResizeObserver>`u`)return()=>{window.removeEventListener(`resize`,n)};let i=new ResizeObserver(n);return i.observe(e),()=>{i.disconnect(),window.removeEventListener(`resize`,n)}},[t,r]);let he=(0,_.useCallback)(()=>{let e=Date.now(),t=w.current&&e-w.current<300;u?(d(!1),l(!1),w.current=0):c?t?(d(!0),l(!1),w.current=0):(l(!1),w.current=e):(l(!0),w.current=e)},[u,c]),ge=(0,_.useCallback)(()=>{ce(``),te.current=window.setTimeout(()=>{T.current=window.setInterval(()=>{ce(``)},50)},500)},[ce]),_e=(0,_.useCallback)(()=>{te.current&&=(clearTimeout(te.current),null),T.current&&=(clearInterval(T.current),null)},[]);(0,_.useEffect)(()=>{if(t&&!y)try{localStorage.getItem(`hay-syskb-seen`)?b(!0):(b(!0),setTimeout(()=>{ee(!0),setTimeout(()=>{ee(!1),localStorage.setItem(`hay-syskb-seen`,`1`)},4e3)},1e3))}catch{b(!0)}},[t,y]);let ve=(0,_.useCallback)((e,t,n)=>{let r=document.elementFromPoint(t,n)?.closest?.(`.kb-key`);if(r&&!r.dataset.kbChar)return;let i=r?.dataset.kbChar??null;if(!i){let r=null;for(let i of e.querySelectorAll(`[data-kb-char]`)){let e=i.getBoundingClientRect(),a=Math.max(e.left-t,0,t-e.right),o=Math.max(e.top-n,0,n-e.bottom),s=Math.hypot(a,o);s<=30&&(!r||s<r.d)&&(r={key:i.dataset.kbChar,d:s})}i=r?.key??null}i&&M.current(i)},[]),ye=(0,_.useCallback)(e=>{let t=e.currentTarget;for(let n=0;n<e.changedTouches.length;n++){let r=e.changedTouches[n];O.taps++,ve(t,r.clientX,r.clientY)}},[ve]),be=(0,_.useCallback)(e=>{e.pointerType!==`touch`&&(O.taps++,ve(e.currentTarget,e.clientX,e.clientY))},[ve]);M.current=(0,_.useCallback)(e=>{let t=N.current||ie.current?e.toUpperCase():e;ce(t),N.current&&!ie.current&&l(!1)},[ce]);let R=(e,t,n)=>{let r=c||u;if(e===`SHIFT`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act${r?` kb-on`:``}`,style:{flexGrow:1.25},onTouchStart:e=>{e.preventDefault(),P(e),he()},onTouchEnd:F,onTouchCancel:F,onClick:I,children:(0,$.jsx)(Zm,{filled:r})},e);if(e===`BKSP`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act`,style:{flexGrow:1.25},onTouchStart:e=>{e.preventDefault(),P(e),ge()},onTouchEnd:e=>{F(e),_e()},onTouchCancel:e=>{F(e),_e()},onClick:I,children:(0,$.jsx)(Qm,{})},e);if(e===`PASTE`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act`,style:{flexGrow:1.25},onTouchStart:P,onTouchEnd:e=>{F(e),le()},onTouchCancel:F,onClick:I,children:(0,$.jsx)(eh,{})},e);if(e===`RET`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-pri kb-bottom`,style:{flexGrow:2.5},onTouchStart:e=>{e.preventDefault(),P(e),ce(`\r`)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:`return`},e);if(e===`SPACE`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-bottom`,style:{flexGrow:5},onTouchStart:e=>{e.preventDefault(),P(e),ce(` `)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:`space`},e);if(e===`123`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act${n?``:` kb-bottom`}`,style:{flexGrow:1.25},onTouchStart:e=>{e.preventDefault(),P(e),s(`num`)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:`123`},e);if(e===`#+=`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act`,style:{flexGrow:1.25},onTouchStart:e=>{e.preventDefault(),P(e),s(`sym`)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:`#+=`},e);if(e===`ABC`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act kb-bottom`,style:{flexGrow:1.25},onTouchStart:e=>{e.preventDefault(),P(e),s(`abc`)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:`ABC`},e);let i=c||u?e.toUpperCase():e;return(0,$.jsx)(`button`,{type:`button`,className:`kb-key`,"data-kb-char":e,onTouchStart:e=>{e.preventDefault(),P(e)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:i},`${e}-${t}`)};return t?(0,$.jsxs)($.Fragment,{children:[x&&(0,$.jsx)(`div`,{className:`kb-hint-overlay`,children:(0,$.jsxs)(`div`,{className:`kb-hint`,children:[`Tap the pulsing `,(0,$.jsx)(`strong`,{children:`KB`}),` button for smooth typing with native keyboard, spellcheck, autocomplete and dictation`]})}),g&&(0,$.jsx)(`div`,{className:`kb-sys-overlay`,onClick:pe,children:(0,$.jsx)(`div`,{className:`kb-sys-dialog`,onClick:e=>e.stopPropagation(),children:(0,$.jsx)(`textarea`,{ref:E,className:`kb-sys-input`,placeholder:`Type here — return runs it...`,autoCapitalize:`off`,autoComplete:`off`,autoCorrect:`off`,rows:1,value:S,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),me())},onChange:e=>{C(e.currentTarget.value)},onInput:ue})})}),(0,$.jsxs)(`div`,{ref:re,className:`mobile-keyboard`,children:[(0,$.jsx)(`div`,{className:`kb-acc-row`,children:Xm.map((e,t)=>e.mod?(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act kb-acc${(e.mod===`ctrl`?f:m)?` kb-on`:``}`,onTouchStart:t=>{t.preventDefault(),P(t),e.mod===`ctrl`?p(e=>!e):h(e=>!e)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:e.label},e.label):e.fn===`sysKb`?(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act kb-acc kb-syskb${x?` kb-pulse`:``}`,onTouchStart:e=>{e.preventDefault(),P(e);try{localStorage.setItem(`hay-syskb-seen`,`1`)}catch{}pe()},onTouchEnd:F,onTouchCancel:F,onClick:I,children:(0,$.jsx)($m,{})},e.label):(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act kb-acc`,onTouchStart:t=>{t.preventDefault(),P(t),e.key&&ce(e.key)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:e.label},e.label))}),D&&(0,$.jsxs)(`div`,{style:{position:`absolute`,top:2,left:8,zIndex:60,fontFamily:`monospace`,fontSize:12,lineHeight:`18px`,color:`#fff`,background:`rgba(0,0,0,0.65)`,borderRadius:6,padding:`1px 8px`,pointerEvents:`none`},children:[`taps `,k.taps,` · disp `,k.disp,` · sent `,k.sent,k.buf?` · buf ${k.buf}`:``]}),(0,$.jsx)(`div`,{className:`kb-keys`,onTouchStartCapture:ye,onPointerDown:be,children:Ym[o].map((e,t)=>{let n=t===2;return(0,$.jsx)(`div`,{className:`kb-row${t===1?` kb-r2`:``}${n?` kb-r3`:``}`,children:e.map((e,t)=>{let r=[];return(e===`SHIFT`||e===`#+=`||e===`123`)&&n?(r.push(R(e,t,n)),r.push((0,$.jsx)(`div`,{className:`kb-gap`},`gap-after-shift`)),r):e===`BKSP`&&n?(r.push((0,$.jsx)(`div`,{className:`kb-gap`},`gap-before-bksp`)),r.push(R(e,t,n)),r):R(e,t,n)})},t)})})]})]}):null},nh=e=>e.kind!==`separator`,rh=({request:e,onClose:t})=>{let n=(0,_.useRef)(null),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(0);return(0,_.useLayoutEffect)(()=>{if(!e){i(null);return}let t=n.current,r=t?.offsetWidth||200,a=t?.offsetHeight||200;i({left:Math.max(8,Math.min(e.x,window.innerWidth-r-8)),top:Math.max(8,Math.min(e.y,window.innerHeight-a-8))}),o(e.items.findIndex(nh))},[e]),(0,_.useEffect)(()=>{if(!e)return;let r=n=>{if(n.key===`Escape`){n.preventDefault(),t();return}let r=e.items.map((e,t)=>nh(e)&&!e.disabled?t:-1).filter(e=>e>=0);if(r.length!==0){if(n.key===`ArrowDown`||n.key===`ArrowUp`){n.preventDefault();let e=r.indexOf(a),t=n.key===`ArrowDown`?r[(e+1+r.length)%r.length]:r[(e-1+r.length)%r.length];o(t)}else if(n.key===`Enter`){n.preventDefault();let r=e.items[a];r&&nh(r)&&!r.disabled&&(t(),r.onSelect())}}},i=e=>{n.current?.contains(e.target)||t()};return window.addEventListener(`keydown`,r,!0),window.addEventListener(`mousedown`,i,!0),window.addEventListener(`resize`,t),window.addEventListener(`blur`,t),()=>{window.removeEventListener(`keydown`,r,!0),window.removeEventListener(`mousedown`,i,!0),window.removeEventListener(`resize`,t),window.removeEventListener(`blur`,t)}},[e,a,t]),e?(0,$.jsx)(`div`,{ref:n,className:`context-menu`,role:`menu`,style:r?{left:r.left,top:r.top}:{left:-9999,top:-9999},onContextMenu:e=>e.preventDefault(),children:e.items.map((e,n)=>nh(e)?(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`context-menu-item`+(e.danger?` danger`:``)+(n===a?` active`:``),disabled:e.disabled,onMouseEnter:()=>o(n),onClick:()=>{t(),e.onSelect()},children:[(0,$.jsx)(`span`,{children:e.label}),e.hint&&(0,$.jsx)(`kbd`,{children:e.hint})]},e.label+n):(0,$.jsx)(`div`,{className:`context-menu-separator`,role:`separator`},`sep`+n))}):null},ih=4,ah=e=>e.internalName||e.name,oh=(e,t)=>t!==null&&(e.internalName===t||e.name===t),sh=e=>e.lastActivityAt||0,ch=e=>e.bellUnseen?2:+!!e.unread,lh=(e,t)=>{let n=ch(t)-ch(e);return n===0?sh(t)-sh(e):n},uh=e=>{let t=e.match(/^(\/(?:Users|home)\/[^/]+)(\/.*)?$/);return t?`~`+(t[2]||``):e===`/root`?`~`:e.startsWith(`/root/`)?`~`+e.slice(5):e},dh=e=>{if(!e)return`Other`;let t=uh(e),n=t.startsWith(`~`)?`~`:``,r=t.replace(/^~\/?/,``).split(`/`).filter(Boolean).slice(0,n?2:3);return r.length===0?n||`/`:(n?n+`/`:`/`)+r.join(`/`)},fh=(e,t)=>{let n=(e.displayName||e.name).toLowerCase(),r=(e.cwd||``).toLowerCase(),i=e.cwd?uh(e.cwd).toLowerCase():``,a=(e.foregroundProcess||``).toLowerCase();return n===t?100:i===t?90:n.startsWith(t)?80:(i.split(`/`).filter(Boolean).pop()||``)===t?70:n.includes(t)?60:i.startsWith(t)?55:i.includes(t)||r.includes(t)?40:a.includes(t)?30:0},ph=(e,t)=>t===`all`?e:t===`agent`?e.filter(e=>e.createdBy===`agent`):e.filter(e=>e.createdBy!==`agent`),mh=(e,t=!1)=>{let n=new Map;for(let t of e){let e=t.type===`port`?`Ports`:dh(t.cwd),r=n.get(e);r?r.push(t):n.set(e,[t])}let r=(e,t)=>(e.displayName||e.name).localeCompare(t.displayName||t.name);return Array.from(n.entries()).map(([e,n])=>({label:e,rows:n.sort(t?r:lh)})).sort((e,n)=>e.label===`Ports`?1:n.label===`Ports`?-1:t?e.label.localeCompare(n.label):Math.max(...n.rows.map(sh))-Math.max(...e.rows.map(sh)))},hh=(e,t)=>{let n=new Map(t.map((e,t)=>[e,t])),r=(e,t)=>(e.displayName||e.name).localeCompare(t.displayName||t.name);return[...e].sort((e,t)=>{let i=n.get(ah(e)),a=n.get(ah(t));return i!==void 0&&a!==void 0?i-a:i===void 0?a===void 0?r(e,t):1:-1})},gh=(e,t,n)=>{let r=new Map(t.map(e=>[e.id,[]])),i=[];for(let t of e){let e=t.folderId?r.get(t.folderId):void 0;e?e.push(t):i.push(t)}return{folders:t.map(e=>({folder:e,rows:hh(r.get(e.id)||[],n)})),loose:hh(i,n)}},_h=(e,t,n,r=`recent`,i=[],a=[])=>{let o=n.trim();if(o){let t=o.toLowerCase(),n=e.filter(e=>fh(e,t)>0);if(r===`manual`){let e=gh(n,a,i);return{mode:`manual`,rows:e.loose,folders:e.folders}}return{mode:`filter`,rows:n.map(e=>({s:e,score:fh(e,t)})).sort((e,t)=>t.score-e.score||lh(e.s,t.s)).map(e=>e.s)}}if(r===`project`)return{mode:`project`,groups:mh(e,!0)};if(r===`manual`){let t=gh(e,a,i);return{mode:`manual`,rows:t.loose,folders:t.folders}}let s=e.find(e=>oh(e,t))??null,c=new Set,l=[],u=e=>{let t=ah(e);c.has(t)||(c.add(t),l.push(e))};s&&u(s),e.filter(e=>(e.bellUnseen||e.unread)&&!oh(e,t)).sort(lh).forEach(u),e.filter(e=>e.type!==`port`&&(e.active||e.starting)).sort((e,t)=>sh(t)-sh(e)).forEach(e=>{l.length<ih&&u(e)});let d=e.filter(e=>!c.has(ah(e))).sort(lh);return{mode:`tiers`,hero:l,groups:d.length>0?[{label:``,rows:d}]:[],currentInHero:s!==null}},vh=(e,t)=>{if(!e)return``;let n=Math.floor((t-e)/1e3);if(n<10)return`just now`;if(n<60)return`${n}s ago`;let r=Math.floor(n/60);if(r<60)return`${r}m ago`;let i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`},yh=450,bh=5e3,xh=10,Sh=[{min:100,h:`40px`,fs:`4px`},{min:120,h:`56px`,fs:`5px`},{min:150,h:`84px`,fs:`6px`},{min:210,h:`130px`,fs:`7.5px`},{min:300,h:`200px`,fs:`9.5px`},{min:420,h:`300px`,fs:`11px`},{min:560,h:`min(46vh, 480px)`,fs:`11px`},{min:720,h:`min(56vh, 640px)`,fs:`12px`},{min:900,h:`min(66vh, 820px)`,fs:`13px`}],Ch=5,wh=10,Th=2,Eh={s:1,m:2,l:4,xl:5},Dh=()=>{let e=document.activeElement;return!e||e===document.body||e.closest?.(`.switcher-live-tile, .switcher-focus-tile`)?!0:!e.matches?.(`input, textarea, [contenteditable]`)},Oh=e=>e.internalName||e.name,kh=/Resume from summary|Resuming the full session|Don't ask me again/i,Ah=e=>!!e&&kh.test(e.text),jh=12,Mh=76,Nh=()=>(0,$.jsxs)(`svg`,{viewBox:`0 0 12 12`,width:`10`,height:`10`,"aria-hidden":`true`,focusable:`false`,children:[(0,$.jsx)(`circle`,{cx:`6`,cy:`3.4`,r:`2.4`,fill:`currentColor`}),(0,$.jsx)(`path`,{d:`M1.4 11.2c0-2.6 2.1-4.2 4.6-4.2s4.6 1.6 4.6 4.2z`,fill:`currentColor`})]}),Ph=0,Fh=new Map;typeof document<`u`&&document.fonts?.ready?.then(()=>{Ph=0,Fh.clear(),zh.clear()}).catch(()=>{});var Ih=e=>{let t=Fh.get(e);if(t)return t;let n=document.createElement(`span`);n.style.cssText=`position:absolute;visibility:hidden;white-space:pre;font-size:${e}px;line-height:1`,n.style.fontFamily=`var(--font-terminal)`,n.textContent=`0`.repeat(100),document.body.appendChild(n);let r=n.getBoundingClientRect().width/100||e*.6;return n.remove(),Fh.set(e,r),r},Lh=()=>Ph||(Ph=Ih(jh),Ph),Rh=e=>{let t=Ih(e),n=typeof window<`u`&&window.devicePixelRatio||1;return Math.floor(t*n)/n-t},zh=new Map,Bh=e=>{let t=zh.get(e);if(t)return t;let n=document.createElement(`div`);n.style.cssText=`position:absolute;visibility:hidden;white-space:pre;line-height:normal;font-size:${e}px`,n.style.fontFamily=`var(--font-terminal)`,n.textContent=`W`,document.body.appendChild(n);let r=n.getBoundingClientRect().height||e*1.2;return n.remove(),zh.set(e,r),r},Vh=e=>{let t=typeof window<`u`&&window.devicePixelRatio||1;return Math.floor(Bh(e)*1.3*t)/t},Hh=e=>Math.max(6.5,Math.min(13,e/(Mh*(Lh()/jh)))),Uh=typeof ResizeObserver<`u`?new ResizeObserver(e=>{for(let t of e){let e=t.target,n=e.firstElementChild;if(!n)continue;let r=Hh(e.clientWidth),i=Vh(r);n.style.fontSize=r+`px`,n.style.lineHeight=i+`px`,n.style.letterSpacing=Rh(r)+`px`,n.style.setProperty(`--tile-row-h`,i+`px`)}}):null,Wh=({frame:e})=>{let t=(0,_.useRef)(null),n=e.rows||24;(0,_.useLayoutEffect)(()=>{let e=t.current;if(!(!e||!Uh))return Uh.observe(e),()=>Uh.unobserve(e)},[]);let r=e.color||[],i=r.length<n?[...r,...Array.from({length:n-r.length},()=>[])]:r;return(0,$.jsx)(`div`,{className:`switcher-preview-scalebox`,ref:t,children:(0,$.jsx)(`div`,{className:`switcher-preview-screen`,style:{fontSize:jh,lineHeight:`${Vh(jh)}px`,letterSpacing:`${Rh(jh)}px`,"--tile-row-h":`${Vh(jh)}px`},children:Gh(i)})})},Gh=e=>e.map((e,t)=>(0,$.jsx)(`div`,{className:`switcher-preview-row`,children:e.map((e,t)=>(0,$.jsx)(`span`,{style:{color:e.i?e.b||`var(--terminal-bg)`:e.f,background:e.i?e.f||`var(--ink)`:e.b,opacity:e.d?.6:void 0,fontWeight:e.o?600:void 0},children:e.t},t))},t)),Kh=new Set([`zsh`,`bash`,`sh`,`fish`,`dash`,`ksh`,`tcsh`,`nu`,`xonsh`,`login`]),qh=e=>{let t=(e.foregroundProcess||``).trim();return t&&!Kh.has(t.toLowerCase())?t:``},Jh=5e3,Yh=({wsBase:e,room:t,userName:n,theme:r,live:i,claudeApp:a,claimSize:o,activeCols:s,activeRows:c,onFullscreen:l,onUnfocus:u,onNotice:d})=>{let f=(0,_.useRef)(null),p=(0,_.useRef)(null),m=(0,_.useRef)(null),h=(0,_.useRef)(()=>{}),g=(0,_.useRef)(null),v=(0,_.useRef)(!1),[y,b]=(0,_.useState)(null),[ee,S]=(0,_.useState)(null),C=(0,_.useRef)(null),w=()=>Bm(P.current,p.current);C.current||=zm({send:e=>g.current?.(e),notify:e=>se.current?.(e),setOverlay:S,eligible:()=>w()});let[te,T]=(0,_.useState)(null),[E,ne]=(0,_.useState)(null),re=(0,_.useRef)(null),D=(0,_.useRef)(null),O=(0,_.useRef)(null),k=(0,_.useRef)(-1),A=(e,t=0)=>{let n=p.current;if(!n)return;if(!e){n.clearSelection(),k.current=-1,T(t=>t&&{...t,query:e,index:0,total:0});return}let r=Im(n,e),i=Lm(n,r,t===0?r.length-1:k.current+t,e.length);k.current=i,T({query:e,index:i+1,total:r.length})},j=()=>{T(null),k.current=-1,p.current?.clearSelection(),O.current?.blur(),window.setTimeout(()=>{Dh()&&p.current?.focus()},0)},M=(0,_.useRef)(null),[N,ie]=(0,_.useState)([]),[ae,oe]=(0,_.useState)(null),se=(0,_.useRef)(d);se.current=d;let P=(0,_.useRef)(a);P.current=a;let F=(0,_.useRef)(i);F.current=i;let I=(0,_.useRef)(l);I.current=l;let ce=(0,_.useRef)(u);ce.current=u,(0,_.useEffect)(()=>{let e=f.current;if(!e)return;let t=getComputedStyle(document.documentElement).getPropertyValue(`--font-terminal`).trim()||`monospace`,n=new nc({cols:s&&s>1?s:80,rows:c&&c>1?c:24,scrollback:2e3,scrollSensitivity:4,fastScrollSensitivity:12,fontSize:jh,lineHeight:1.3,fontFamily:t,cursorBlink:!1,disableStdin:!0,theme:r}),i=new x;n.loadAddon(i),n.open(e),p.current=n,m.current=i;let a=e.querySelector(`.xterm`),o=()=>{let t=e.querySelector(`.xterm-screen`),n=p.current;if(!a||!t||!n)return;let r=e.clientWidth,i=e.clientHeight;if(r<=0||i<=0)return;let o=t.offsetWidth,s=t.offsetHeight;if(o<=0||s<=0)return;let c=n.options.fontSize||jh,l=Hh(r);if(Math.abs(l-c)>=.25){n.options.fontSize=l,requestAnimationFrame(()=>h.current());return}a.style.transform=``,t.style.transform=``,a.style.transformOrigin=`bottom left`;let u=e.getBoundingClientRect(),d=t.getBoundingClientRect(),f=Math.max(0,Math.round(d.width-u.width)),m=Math.max(0,Math.round(d.height-u.height)),g=Math.round(u.bottom-d.bottom),_=D.current,v=_?Math.max(-f,Math.min(0,_.x)):0,y=_?Math.max(g,Math.min(0,_.y)):g;_&&(D.current={x:v,y}),(v!==0||y!==0)&&(a.style.transform=`translate(${v}px, ${y}px)`);let b=f>1||m>1?{x:f,y:m,cols:n.cols,rows:n.rows}:null,x=re.current;!b&&!x||b&&x&&b.x===x.x&&b.y===x.y&&b.cols===x.cols&&b.rows===x.rows||(re.current=b,ne(b))};h.current=o;let l=typeof ResizeObserver<`u`?new ResizeObserver(o):null;l?.observe(e);let u=e.querySelector(`.xterm-screen`);u?l?.observe(u):a&&l?.observe(a),window.setTimeout(o,30),document.fonts?.ready?.then(()=>o()).catch(()=>{}),n.attachCustomKeyEventHandler(e=>{if(!F.current)return!1;{let t=C.current?.handleKey(e);if(t!==void 0)return t}return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`?(e.type===`keydown`&&(T(e=>e??{query:``,index:0,total:0}),window.setTimeout(()=>O.current?.focus(),0)),!1):e.key===`Enter`&&e.shiftKey&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&(v.current||w())?(e.type===`keydown`&&g.current?.(`\x1B[13;2u`),!1):(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key===`Enter`?(e.type===`keydown`&&I.current(),!1):(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key===`.`?(e.type===`keydown`&&ce.current(),!1):!0});let d=n.onData(e=>g.current?.(e)),_=null,y=()=>{let t=e.querySelector(`.xterm-screen`);if(!t)return null;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{overflowX:Math.max(0,r.width-n.width),overflowY:Math.max(0,r.height-n.height),autoY:Math.round(n.bottom-r.bottom)}},b=t=>{if(!t.altKey||t.button!==0)return;let n=y();if(!n||n.overflowX<1&&n.overflowY<1)return;let r=D.current||{x:0,y:n.autoY};D.current=r,_={sx:t.clientX,sy:t.clientY,ox:r.x,oy:r.y};try{e.setPointerCapture(t.pointerId)}catch{}t.preventDefault(),t.stopPropagation()},ee=e=>{_&&(D.current={x:_.ox+(e.clientX-_.sx),y:_.oy+(e.clientY-_.sy)},h.current(),e.preventDefault())},S=t=>{if(_){_=null;try{e.releasePointerCapture(t.pointerId)}catch{}}},te=e=>{if(Math.abs(e.deltaX)<=Math.abs(e.deltaY))return;let t=y();if(!t||t.overflowX<1)return;let n=D.current||{x:0,y:t.autoY};D.current={x:n.x-e.deltaX,y:n.y},h.current(),e.preventDefault(),e.stopPropagation()};e.addEventListener(`wheel`,te,{capture:!0,passive:!1}),e.addEventListener(`pointerdown`,b,!0),e.addEventListener(`pointermove`,ee,!0),e.addEventListener(`pointerup`,S,!0),e.addEventListener(`pointercancel`,S,!0);let E=Pm(e,()=>p.current,{linesPerNotch:4,lineHeightPx:()=>Math.max(1,n._core?._renderService?.dimensions?.css?.cell?.height||jh*1.3)});return()=>{e.removeEventListener(`wheel`,te,{capture:!0}),e.removeEventListener(`pointerdown`,b,!0),e.removeEventListener(`pointermove`,ee,!0),e.removeEventListener(`pointerup`,S,!0),e.removeEventListener(`pointercancel`,S,!0),E(),l?.disconnect(),d.dispose(),n.dispose(),p.current=null,m.current=null}},[t,r]);let le=(0,_.useRef)(null),ue=r=>{if(!o)return;let i=m.current,a=f.current;if(!i||!a||a.clientWidth<60||a.clientHeight<40)return;let s=i.proposeDimensions();if(!s?.cols||!s?.rows||s.cols<20||s.rows<5)return;let c=le.current;if(c&&c.cols===s.cols&&c.rows===s.rows&&performance.now()-c.at<1500)return;let l=p.current;if(l){let e=Math.abs(l.cols-s.cols)<=Math.max(3,Math.round(s.cols*.15)),t=Math.abs(l.rows-s.rows)<=Math.max(2,Math.round(s.rows*.15));if(e&&t){le.current={cols:s.cols,rows:s.rows,at:performance.now()};return}}le.current={cols:s.cols,rows:s.rows,at:performance.now()};let u=e.includes(`?`)?`&`:`?`,d=new WebSocket(e+u+`room=`+encodeURIComponent(t)+`&name=`+encodeURIComponent((n||`user`)+` (wall)`)+`&replay=0&cols=`+s.cols+`&rows=`+s.rows);d.onopen=()=>{try{d.send(JSON.stringify({type:`resize`,cols:s.cols,rows:s.rows,claim:`attach`,user:!0}))}catch{}let e=!1,t=()=>{if(!e){e=!0;try{d.close()}catch{}r?.()}};d.onmessage=t,window.setTimeout(t,300)},d.onerror=()=>{try{d.close()}catch{}}},de=(0,_.useRef)(ue);return de.current=ue,(0,_.useEffect)(()=>{if(i)return;let e=!1,n=async()=>{if(!(e||document.hidden))try{let n=await fetch(`/api/sessions/screen?name=`+encodeURIComponent(t));if(!n.ok)return;let r=await n.json(),i=p.current;if(e||!i||typeof r.data!=`string`)return;Number.isInteger(r.cols)&&Number.isInteger(r.rows)&&(i.cols!==r.cols||i.rows!==r.rows)&&(i.resize(r.cols,r.rows),window.setTimeout(()=>h.current(),30)),i.write(`\x1Bc`+r.data,()=>{let e=p.current;e&&(e.scrollToBottom(),e.refresh(0,e.rows-1),h.current())})}catch{}},r=t=>{if(e)return;let i=le.current,a=p.current;!i||!a||a.cols===i.cols&&a.rows===i.rows||(n(),t<5&&window.setTimeout(()=>r(t+1),200+t*250))};de.current(()=>{r(0)}),n();let a=window.setInterval(n,Jh),o=0,s=typeof ResizeObserver<`u`?new ResizeObserver(()=>{window.clearTimeout(o),o=window.setTimeout(()=>{e||de.current(()=>{r(0)})},350)}):null;return f.current&&s?.observe(f.current),()=>{e=!0,window.clearInterval(a),window.clearTimeout(o),s?.disconnect()}},[i,t]),(0,_.useEffect)(()=>{if(!i)return;let r=p.current,a=f.current;if(!r||!a)return;r.options.disableStdin=!1,r.options.cursorBlink=!0;let o=null,s=!0,c=()=>{if(!(!s||o))try{o=new Lf,o.onContextLoss(()=>{o?.dispose(),o=null}),r.loadAddon(o),r.refresh(0,r.rows-1)}catch{try{o?.dispose()}catch{}o=null,s=!1}};b(`live`);let l=e.includes(`?`)?`&`:`?`,u=()=>e+l+`room=`+encodeURIComponent(t)+`&name=`+encodeURIComponent(n||`user`)+`&replay=65536&nudge=0&cols=`+r.cols+`&rows=`+r.rows,d=null,m=!1,_=0,y=0,x=[],ee=()=>{if(m)return;b(`down`),window.clearTimeout(_);let e=Math.min(1e3*2**y,15e3);y+=1,_=window.setTimeout(()=>S(),e)},S=()=>{if(m)return;if(window.clearTimeout(_),d)try{d.close()}catch{}let e=new WebSocket(u());d=e,e.onopen=()=>{if(m||d!==e)return;y=0,b(`live`),window.setTimeout(()=>h.current(),30);let t=Date.now()-15e3;for(let n of x)n.at>=t&&e.send(JSON.stringify({type:`input`,data:n.data}));x.length=0},e.onmessage=e=>{try{let t=JSON.parse(String(e.data));if(t.type===`snapshot`){let e=(t.mouseReporting?`\x1B[?1002h`+(t.mouseSgr?`\x1B[?1006h`:``):``)+(t.cursorHidden?`\x1B[?25l`:``);r.write(`\x1Bc`+t.data+e,()=>{r.scrollToBottom(),r.refresh(0,r.rows-1),h.current(),requestAnimationFrame(c)}),v.current=typeof t.keyboardEnhanced==`boolean`?t.keyboardEnhanced:Um(String(t.data||``),!1)}else if(t.type===`output`)r.write(t.data),v.current=Um(String(t.data||``),v.current);else if(t.type===`active_size`)(t.cols!==r.cols||t.rows!==r.rows)&&(r.resize(t.cols,t.rows),window.setTimeout(()=>h.current(),30));else if(t.type===`hello`)M.current=String(t.clientId||``);else if(t.type===`presence`&&Array.isArray(t.clients)){let e=t.clients.filter(e=>String(e.id||``)!==M.current);ie(e.map(e=>({name:String(e.name||`viewer`)})));let n=e.find(e=>e.typing);oe(n?{name:String(n.name||`someone`),color:String(n.color||`#8b5cf6`)}:null)}}catch{}},e.onclose=()=>{m||d!==e||ee()},e.onerror=()=>{try{e.close()}catch{}}};S(),g.current=e=>{if(!d||d.readyState!==WebSocket.OPEN){x.push({data:e,at:Date.now()}),x.length>200&&x.shift(),b(`down`),(!d||d.readyState===WebSocket.CLOSING||d.readyState===WebSocket.CLOSED)&&(y=0,S());return}d.send(JSON.stringify({type:`input`,data:e}))};let w={hiddenAt:0},te=()=>{if(document.hidden){w.hiddenAt=Date.now();return}requestAnimationFrame(()=>{let e=p.current;if(e)try{e.refresh(0,e.rows-1)}catch{}});let e=w.hiddenAt?Date.now()-w.hiddenAt:0;w.hiddenAt=0,(!d||d.readyState!==WebSocket.OPEN||e>6e4)&&(y=0,S())};document.addEventListener(`visibilitychange`,te);let E=()=>{(!d||d.readyState===WebSocket.CLOSING||d.readyState===WebSocket.CLOSED)&&(y=0,S())};window.addEventListener(`focus`,E);let ne=window.setTimeout(()=>{Dh()&&r.focus()},50);return()=>{m=!0;try{o?.dispose()}catch{}o=null,window.clearTimeout(ne),window.clearTimeout(_),document.removeEventListener(`visibilitychange`,te),window.removeEventListener(`focus`,E);try{d?.close()}catch{}g.current=null,r.options.disableStdin=!0,r.options.cursorBlink=!1,b(null),ie([]),oe(null),C.current?.dispose(),T(null),k.current=-1,r.blur()}},[i,e,t,n]),(0,$.jsxs)(`div`,{className:`switcher-live-tile`+(i?` is-live`:``),style:{background:r?.background},onClick:i?e=>e.stopPropagation():void 0,onPointerDown:i?e=>e.stopPropagation():void 0,children:[(0,$.jsx)(`div`,{className:`switcher-focus-term`,ref:f}),ee!==null&&(0,$.jsxs)(`div`,{className:`voice-overlay`,"aria-hidden":`true`,children:[(0,$.jsx)(`span`,{className:`voice-dot`}),(0,$.jsx)(`span`,{className:ee?`voice-text`:`voice-text muted`,children:ee||`Listening… release Space to insert`})]}),i&&(0,$.jsxs)(`div`,{className:`switcher-live-chrome`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`span`,{className:`switcher-focus-label`+(y===`down`?` down`:``),children:y===`down`?`reconnecting…`:`live`}),ae&&(0,$.jsxs)(`span`,{className:`switcher-live-driver`,title:ae.name+` is typing in this session`,children:[(0,$.jsx)(`span`,{className:`driver-dot`,style:{background:ae.color}}),ae.name]}),N.length>0&&(0,$.jsxs)(`span`,{className:`switcher-live-viewers`,title:N.map(e=>e.name).join(`, `)+` also connected`,children:[(0,$.jsx)(Nh,{}),N.length,N.some(e=>/agent|hopa|\(pane\)/i.test(e.name))&&(0,$.jsx)(`b`,{className:`viewer-agent`,children:`AI`})]}),E&&(0,$.jsxs)(`button`,{type:`button`,className:`switcher-tile-offgrid`,title:`This session's terminal is ${E.cols}×${E.rows}, larger than the tile`+(ae?` — ${ae.name} is using it right now`:N.length?` — another client holds the size`:``)+`.
127
- ⌥-drag to pan. Click to resize the session to fit this tile.`,onClick:e=>{e.stopPropagation(),D.current=null,de.current()},children:[(0,$.jsx)(`span`,{className:`offgrid-glyph`,"aria-hidden":`true`,children:`⤢`}),E.cols,`×`,E.rows]}),te&&(0,$.jsxs)(`span`,{className:`switcher-tile-find`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`input`,{ref:O,value:te.query,placeholder:`Find…`,onChange:e=>A(e.target.value),onKeyDown:e=>{e.stopPropagation(),e.key===`Escape`?(e.preventDefault(),j()):e.key===`Enter`&&(e.preventDefault(),A(te.query,e.shiftKey?-1:1))}}),(0,$.jsx)(`em`,{children:te.total>0?te.index+`/`+te.total:te.query?`0`:``}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Close find`,onClick:j,children:`✕`})]}),(0,$.jsx)(`button`,{type:`button`,title:`Full screen (⌘⏎)`,"aria-label":`Open session full screen`,onClick:l,children:`⛶`}),(0,$.jsx)(`button`,{type:`button`,title:`Unfocus`,"aria-label":`Unfocus tile`,onClick:u,children:`✕`})]})]})},Xh=({open:e,sessions:t,currentRoom:n,onClose:r,dismissable:i=!0,onSwitch:a,onRefresh:o,onNotice:s,tileWsBase:c,onFocusSession:l,folders:u=[],userName:d,terminalTheme:f,onOpenSettings:p,onToggleKeyboard:m,onFind:h})=>{let[g,v]=(0,_.useState)(()=>{try{return sessionStorage.getItem(`hay_switcher_filter`)||``}catch{return``}});(0,_.useEffect)(()=>{try{g?sessionStorage.setItem(`hay_switcher_filter`,g):sessionStorage.removeItem(`hay_switcher_filter`)}catch{}},[g]);let[y,b]=(0,_.useState)(`user`),[x,ee]=(0,_.useState)(()=>{let e=localStorage.getItem(`hay_tile_zoom`);if(e!==null&&/^\d+$/.test(e))return Math.min(Number(e),Sh.length-1);let t=localStorage.getItem(`hay_tile_size`);return t&&t in Eh?Eh[t]:Th}),S=(0,_.useRef)(null),C=(0,_.useRef)(!1);(0,_.useEffect)(()=>{let e=S.current;if(!e)return;let t=()=>{try{sessionStorage.setItem(`hay_switcher_scroll`,String(e.scrollTop))}catch{}};return e.addEventListener(`scroll`,t,{passive:!0}),()=>e.removeEventListener(`scroll`,t)},[e]),(0,_.useEffect)(()=>{if(!e||C.current)return;let t=0;try{t=Number(sessionStorage.getItem(`hay_switcher_scroll`)||0)}catch{}if(!t){C.current=!0;return}let n=0,r=()=>{let e=S.current;if(e){if(e.scrollHeight>e.clientHeight+t||n++>20){e.scrollTop=t,C.current=!0;return}requestAnimationFrame(r)}};requestAnimationFrame(r)},[e]);let[w,te]=(0,_.useState)(0);(0,_.useEffect)(()=>{if(!e)return;let t=S.current;if(!t)return;let n=()=>{let e=getComputedStyle(t),n=t.clientWidth-(parseFloat(e.paddingLeft)||0)-(parseFloat(e.paddingRight)||0);te(n>0?n:0)};if(n(),typeof ResizeObserver<`u`){let e=new ResizeObserver(n);return e.observe(t),()=>e.disconnect()}return window.addEventListener(`resize`,n),()=>window.removeEventListener(`resize`,n)},[e]);let T=(0,_.useMemo)(()=>{if(!w)return Sh.length-1;for(let e=0;e<Sh.length;e++)if(Math.floor((w+wh)/(Sh[e].min+wh))<=1)return e;return Sh.length-1},[w]),E=Math.min(x,T),ne=Sh[E],re=E>=Ch&&!!c,D=(0,_.useRef)(!1);(0,_.useEffect)(()=>{e&&(D.current=!1)},[e]);let O=e=>{let t=Math.max(0,Math.min(e,T));t!==E&&(t>=Ch&&E<Ch&&c&&!D.current&&(D.current=!0,s(`Tiles are interactive at this zoom — click one to type in it (⌘⏎ full screen, ⌘. release)`)),ee(t),localStorage.setItem(`hay_tile_zoom`,String(t)))},[k,A]=(0,_.useState)(()=>{let e=localStorage.getItem(`hay_sort_mode`);return e===`project`||e===`manual`?e:`recent`}),j=e=>{A(e),localStorage.setItem(`hay_sort_mode`,e),Ve.current=null},[M,N]=(0,_.useState)(()=>localStorage.getItem(`hay_project_compact`)===`1`),ie=e=>{N(e),localStorage.setItem(`hay_project_compact`,e?`1`:`0`)},[ae,oe]=(0,_.useState)(()=>{try{let e=JSON.parse(localStorage.getItem(`hay_manual_order_v1`)||`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}catch{return[]}}),se=e=>{oe(e);try{localStorage.setItem(`hay_manual_order_v1`,JSON.stringify(e))}catch{}},[P,F]=(0,_.useState)(null),[I,ce]=(0,_.useState)(null),[le,ue]=(0,_.useState)(null),de=e=>{e.target?.closest?.(`.switcher-card, .switcher-group-label, .switcher-top`)||(e.preventDefault(),ue({x:e.clientX,y:e.clientY,items:[{label:`New session`,onSelect:()=>Ee(!0)},...k===`manual`?[{label:`New folder`,onSelect:()=>{pe()}}]:[],{kind:`separator`},{label:`Sort by recent`,onSelect:()=>j(`recent`),disabled:k===`recent`},{label:`Group by project`,onSelect:()=>j(`project`),disabled:k===`project`},{label:`Manual order`,onSelect:()=>j(`manual`),disabled:k===`manual`},{kind:`separator`},{label:`Zoom in`,onSelect:()=>O(E+1),hint:`+`,disabled:E>=T},{label:`Zoom out`,onSelect:()=>O(E-1),hint:`−`,disabled:E<=0}]}))},L=(e,t)=>{e.preventDefault(),e.stopPropagation(),ue({x:e.clientX,y:e.clientY,items:[{label:`Rename folder…`,onSelect:()=>{me(t)}},{label:`Delete folder`,danger:!0,onSelect:()=>{he(t)}},{kind:`separator`},{label:`New folder`,onSelect:()=>{pe()}}]})},fe=async(e,t,n)=>{try{let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});return r.ok?(o(),!0):(s((await r.json().catch(()=>({}))).error||n),!1)}catch{return s(n),!1}},pe=async()=>{let e=window.prompt(`Folder name`)?.trim();e&&await fe(`/api/folders`,{name:e},`Could not create folder`)&&s(`Created ${e}`)},me=async e=>{let t=window.prompt(`Rename folder`,e.name)?.trim();!t||t===e.name||await fe(`/api/folders/rename`,{id:e.id,name:t},`Could not rename folder`)},he=async e=>{window.confirm(`Delete folder "${e.name}"? Its sessions move back to unfiled.`)&&await fe(`/api/folders/delete`,{id:e.id},`Could not delete folder`)},ge=async(e,t)=>{await fe(`/api/sessions/move`,{internalName:e,folderId:t},`Could not move session`)};(0,_.useEffect)(()=>{if(!P)return;let e=-1,t=0,n=t=>{e=t.clientY},r=()=>{let n=S.current;if(n&&e>=0){let t=n.getBoundingClientRect();e<t.top+110?n.scrollTop-=Math.ceil((t.top+110-e)/110*22):e>t.bottom-110&&(n.scrollTop+=Math.ceil((e-(t.bottom-110))/110*22))}t=requestAnimationFrame(r)};return window.addEventListener(`dragover`,n),t=requestAnimationFrame(r),()=>{window.removeEventListener(`dragover`,n),cancelAnimationFrame(t)}},[P]);let[_e,ve]=(0,_.useState)(null);(0,_.useEffect)(()=>{if(!_e)return;let e=()=>ve(null);return window.addEventListener(`pointerup`,e),window.addEventListener(`dragend`,e),()=>{window.removeEventListener(`pointerup`,e),window.removeEventListener(`dragend`,e)}},[_e]);let ye=(e,t)=>{if(!e||e===t)return;let n=Ze.current,r=ae.length?ae.slice():n.slice();for(let e of n)r.includes(e)||r.push(e);let i=r.indexOf(e),a=r.indexOf(t);i===-1||a===-1||i===a||(r.splice(i,1),r.splice(a,0,e),se(r))},[be,R]=(0,_.useState)(null),[xe,Se]=(0,_.useState)(()=>{try{return sessionStorage.getItem(`hay_switcher_focus`)}catch{return null}});(0,_.useEffect)(()=>{try{xe?sessionStorage.setItem(`hay_switcher_focus`,xe):sessionStorage.removeItem(`hay_switcher_focus`)}catch{}},[xe]),(0,_.useEffect)(()=>{e||Se(null)},[e]),(0,_.useEffect)(()=>{re||Se(null)},[re]);let[Ce,we]=(0,_.useState)(``),[Te,Ee]=(0,_.useState)(!1),[De,Oe]=(0,_.useState)(``),[ke,Ae]=(0,_.useState)(null),[,je]=(0,_.useState)(0),Me=(0,_.useRef)(null);if(!Me.current){let e=new Map;try{let t=JSON.parse(sessionStorage.getItem(`hop_preview_cache_v1`)||`[]`);for(let[n,r]of t)e.set(n,{text:r})}catch{}Me.current=e}let Ne=()=>{try{let e=Array.from(Me.current.entries()).map(([e,t])=>[e,t.text.length>4e3?t.text.slice(-4e3):t.text]);sessionStorage.setItem(`hop_preview_cache_v1`,JSON.stringify(e))}catch{}},Pe=(0,_.useRef)(null),Fe=(0,_.useRef)(!1),Ie=(0,_.useMemo)(()=>ph(t,y),[t,y]),Le=(0,_.useMemo)(()=>Ie.filter(e=>!e.parked),[Ie]),Re=(0,_.useMemo)(()=>Ie.filter(e=>e.parked),[Ie]),[ze,Be]=(0,_.useState)(!1),Ve=(0,_.useRef)(null);(0,_.useEffect)(()=>{e||(Ve.current=null)},[e]);let z=(0,_.useMemo)(()=>{let t=g.trim()?Ie:Le,r=_h(t,n,g,k,ae,u);if(!e||r.mode!==`tiers`&&r.mode!==`project`)return r;let i=Ve.current;if(!i||i.mode!==r.mode)return i=r.mode===`tiers`?{mode:`tiers`,hero:r.hero.map(Oh),groups:r.groups.map(e=>({label:e.label,rows:e.rows.map(Oh)}))}:{mode:`project`,hero:[],groups:r.groups.map(e=>({label:e.label,rows:e.rows.map(Oh)}))},Ve.current=i,r;let a=new Map(t.map(e=>[Oh(e),e])),o=new Set([...i.hero,...i.groups.flatMap(e=>e.rows)]),s=t.filter(e=>!o.has(Oh(e))),c=e=>e.map(e=>a.get(e)).filter(e=>!!e);if(r.mode===`tiers`)return{mode:`tiers`,hero:[...c(i.hero),...s],groups:i.groups.map(e=>({label:e.label,rows:c(e.rows)})).filter(e=>e.rows.length>0),currentInHero:r.currentInHero};let l=i.groups.map(e=>({label:e.label,rows:c(e.rows)}));for(let e of s){let t=e.type===`port`?`Ports`:dh(e.cwd),n=l.find(e=>e.label===t);n?n.rows.push(e):l.push({label:t,rows:[e]})}return{mode:`project`,groups:l.filter(e=>e.rows.length>0)}},[e,Ie,Le,n,g,k,ae,y]),He=(0,_.useRef)(null),[Ue,We]=(0,_.useState)(0),Ge=typeof window<`u`&&!!window.matchMedia?.(`(pointer: fine)`).matches,[Ke,qe]=(0,_.useState)([]);(0,_.useEffect)(()=>{let t=g.trim();if(!e||t.length<3){qe([]);return}let n=!1,r=window.setTimeout(async()=>{try{let e=await(await fetch(`/api/sessions/search?q=${encodeURIComponent(t)}`)).json();if(n)return;let r=new Map(Ie.map(e=>[e.internalName||e.name,e]));qe((Array.isArray(e?.matches)?e.matches:[]).map(e=>{let t=r.get(e.internalName||``)||r.get(e.name||``);return t?{session:t,snippet:e.snippet||``}:null}).filter(Boolean))}catch{n||qe([])}},250);return()=>{n=!0,window.clearTimeout(r)}},[e,g,Ie]);let Je=(0,_.useMemo)(()=>{if(!g.trim())return[];let e=new Set;return z.mode===`filter`?z.rows.forEach(t=>e.add(Oh(t))):z.mode===`manual`?(z.rows.forEach(t=>e.add(Oh(t))),z.folders.forEach(t=>t.rows.forEach(t=>e.add(Oh(t))))):(z.mode===`project`||z.hero.forEach(t=>e.add(Oh(t))),z.groups.forEach(t=>t.rows.forEach(t=>e.add(Oh(t))))),Ke.filter(t=>!e.has(Oh(t.session)))},[z,Ke,g]),Ye=(0,_.useMemo)(()=>z.mode===`filter`?[...z.rows,...Je.map(e=>e.session)]:z.mode===`manual`?[...z.folders.flatMap(e=>e.rows),...z.rows,...Je.map(e=>e.session)]:z.mode===`project`?z.groups.flatMap(e=>e.rows):[...z.hero,...z.groups.flatMap(e=>e.rows)],[z,Je]),Xe=(0,_.useMemo)(()=>{let e=new Map;return Ye.forEach((t,n)=>e.set(Oh(t),n)),e},[Ye]);(0,_.useEffect)(()=>{if(!e||xe||!n)return;let t=Ye.find(e=>(e.internalName||e.name)===n||e.name===n);if(!t)return;let r=Oh(t);Se(r);let i=Xe.get(r);typeof i==`number`&&(We(i),requestAnimationFrame(()=>{document.querySelector(`[data-nav-index="${i}"]`)?.scrollIntoView({block:`center`})}))},[e,n,Ye,Xe]);let Ze=(0,_.useRef)([]);{let e=_h(Le,n,``,`manual`,ae,u);Ze.current=e.mode===`manual`?[...e.folders.flatMap(e=>e.rows),...e.rows].map(Oh):[]}let Qe=(0,_.useRef)(Ye);Qe.current=Ye,(0,_.useEffect)(()=>{if(!e)return;let t=Ye.findIndex(e=>n!==null&&(e.internalName===n||e.name===n));We(g?0:Math.max(0,t)),document.querySelector(`.switcher-scroll`)?.scrollTo({top:0})},[e,g,y]),(0,_.useEffect)(()=>{We(e=>Math.min(e,Math.max(0,Ye.length-1)))},[Ye.length]),(0,_.useEffect)(()=>{if(!e||!Ge)return;let t=window.setTimeout(()=>He.current?.focus(),40);return()=>window.clearTimeout(t)},[e,Ge]);let $e=(0,_.useRef)((()=>{try{return sessionStorage.getItem(`hay_switcher_filter`)||``}catch{return``}})()),B=(0,_.useRef)(!1);(0,_.useLayoutEffect)(()=>{if(e){if(!B.current&&(B.current=!0,$e.current)){R(null),Ee(!1),Oe(``);return}b(`user`),v(``),R(null),Ee(!1),Oe(``)}},[e]),(0,_.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>je(e=>e+1),1e4);return()=>window.clearInterval(t)},[e]),(0,_.useEffect)(()=>{if(!e)return;let t=e=>{document.activeElement?.closest?.(`.switcher-live-tile, .switcher-focus-tile`)||e.key===`Escape`&&(e.preventDefault(),be?R(null):xe?Se(null):i&&r())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,be,xe]);let et=(0,_.useRef)(0);(0,_.useEffect)(()=>{if(!e)return;let t=!1,n=new Set(z.mode===`tiers`?z.hero.map(Oh):z.mode===`filter`?[...z.rows.map(Oh),...Ke.map(e=>Oh(e.session))]:[]),r=new Set,i=(z.mode===`tiers`?[...z.hero,...z.groups.flatMap(e=>e.rows)]:z.mode===`project`?z.groups.flatMap(e=>e.rows):z.mode===`filter`?[...z.rows,...Ke.map(e=>e.session)]:z.rows).filter(e=>{if(e.type===`port`)return!1;let t=Oh(e);return r.has(t)?!1:(r.add(t),!0)}),a=async()=>{if(t||document.hidden||i.length===0)return;let e=Date.now()-et.current>15e3,r=i.filter(t=>n.has(Oh(t))||e);await Promise.all(r.map(async e=>{let n=Oh(e);try{let e=await fetch(`/api/sessions/preview?name=${encodeURIComponent(n)}`);if(!e.ok)return;let r=await e.json(),i=typeof r.text==`string`?r.text.replace(/\s+$/,``):``;!t&&i.trim().length>0&&Me.current.set(n,{text:i,color:Array.isArray(r.color)?r.color:null,cols:Number.isInteger(r.cols)?r.cols:void 0,rows:Number.isInteger(r.rows)?r.rows:void 0})}catch{}})),!t&&(e&&(et.current=Date.now()),Ne(),je(e=>e+1))};a();let o=window.setInterval(a,bh);return()=>{t=!0,window.clearInterval(o)}},[e,z,Ke]);let tt=(e,t)=>{if(e.pointerType===`mouse`&&e.button!==0)return;nt();let n=e.clientX,r=e.clientY,i=window.setTimeout(()=>{Pe.current=null,Fe.current=!0,R({session:t,mode:`menu`,anchor:{x:n,y:r}})},yh);Pe.current={timer:i,startX:n,startY:r}},nt=()=>{Pe.current&&=(window.clearTimeout(Pe.current.timer),null)},rt=e=>{let t=Pe.current;t&&(Math.abs(e.clientX-t.startX)>10||Math.abs(e.clientY-t.startY)>10)&&nt()},it=e=>{let t=Oh(e);He.current?.blur(),Se(t),l?.(e);let n=Ye.findIndex(e=>Oh(e)===t);n>=0&&We(n)},at=e=>re&&e.active&&e.type!==`port`,ot=e=>{if(He.current?.blur(),nt(),Fe.current){Fe.current=!1;return}if(n!==null&&(e.internalName===n||e.name===n)){r();return}if(e.parked&&fetch(`/api/sessions/park`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:Oh(e),parked:!1})}).catch(()=>{}),e.type!==`port`&&!e.active&&re&&c){let t=Oh(e);try{let e=c.includes(`?`)?`&`:`?`,n=new WebSocket(c+e+`room=`+encodeURIComponent(t)+`&name=`+encodeURIComponent((d||`user`)+` (start)`)+`&replay=0&nudge=0&cols=80&rows=24`);n.onopen=()=>{window.setTimeout(()=>{try{n.close()}catch{}},400)},n.onerror=()=>{try{n.close()}catch{}}}catch{}s(`Starting `+(e.displayName||e.name)+`…`),Se(t),l?.(e),o();return}a(e)};(0,_.useEffect)(()=>{if(!e)return;let t=e=>{if(!(be||Te)){if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`){e.preventDefault(),Se(null),He.current?.focus(),We(-1);return}if(!document.activeElement?.closest?.(`.switcher-live-tile, .switcher-focus-tile`)){if(e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey){let t=Ye[Ue];t&&(e.preventDefault(),He.current?.blur(),a(t));return}if(e.altKey&&!e.metaKey&&!e.ctrlKey&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&k===`manual`){let t=Ye[Ue],n=Ye[Ue+(e.key===`ArrowUp`?-1:1)];t&&n&&(e.preventDefault(),ye(Oh(t),Oh(n)),We(t=>t+(e.key===`ArrowUp`?-1:1)));return}if(!(e.metaKey||e.ctrlKey||e.altKey)){if(document.activeElement!==He.current){if(e.key===`+`||e.key===`=`){e.preventDefault(),O(E+1);return}if(e.key===`-`){e.preventDefault(),O(E-1);return}}if(e.key===`ArrowDown`||e.key===`ArrowUp`||e.key===`ArrowLeft`||e.key===`ArrowRight`){if((e.key===`ArrowLeft`||e.key===`ArrowRight`)&&document.activeElement===He.current&&(He.current?.value||``).length>0)return;e.preventDefault(),We(t=>{if(t===-1)return e.key===`ArrowDown`?(requestAnimationFrame(()=>{document.querySelector(`[data-nav-index="0"]`)?.scrollIntoView({block:`nearest`})}),0):-1;let n=Array.from(document.querySelectorAll(`[data-nav-index]`));if(n.length===0)return 0;let r=(n.find(e=>Number(e.dataset.navIndex)===t)??n[0]).getBoundingClientRect(),i=r.left+r.width/2,a=r.top+r.height/2,o=null;for(let r of n){let n=Number(r.dataset.navIndex);if(n===t||Number.isNaN(n))continue;let s=r.getBoundingClientRect(),c=s.left+s.width/2-i,l=s.top+s.height/2-a,u,d;if(e.key===`ArrowDown`?(u=l,d=Math.abs(c)):e.key===`ArrowUp`?(u=-l,d=Math.abs(c)):e.key===`ArrowRight`?(u=c,d=Math.abs(l)):(u=-c,d=Math.abs(l)),u<4)continue;let f=u+d*3;(!o||f<o.score)&&(o={idx:n,score:f})}if(!o&&e.key===`ArrowUp`)return requestAnimationFrame(()=>He.current?.focus()),-1;let s=o?o.idx:t;return requestAnimationFrame(()=>{document.querySelector(`[data-nav-index="${s}"]`)?.scrollIntoView({block:`nearest`})}),s});return}if(e.key===`Enter`&&!e.shiftKey){let t=Ye[Ue];t&&(e.preventDefault(),at(t)?it(t):ot(t));return}document.activeElement!==He.current&&(e.key.length===1||e.key===`Backspace`)&&(e.preventDefault(),Se(null),He.current?.focus(),v(t=>e.key===`Backspace`?t.slice(0,-1):t+e.key))}}}};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,be,Te,Ye,Ue,E,T,re]);let st=(e,t)=>{nt(),R({session:e,mode:`menu`,anchor:t??{x:window.innerWidth/2+132,y:window.innerHeight/3}})},ct=async e=>{if(e.preventDefault(),!be)return;let t=Ce.trim(),n=be.session.displayName||be.session.name;if(!t||t===n){R(null);return}if(!/^[a-zA-Z0-9_-]+$/.test(t)){s(`Only letters, numbers, - and _ allowed`);return}try{let e=await fetch(`/api/sessions/rename`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({oldName:n,newName:t,internalName:Oh(be.session)})});if(!e.ok){s((await e.json().catch(()=>({}))).error||`Rename failed`);return}s(`Renamed to ${t}`),R(null),o()}catch{s(`Rename failed`)}},lt=async()=>{if(!be)return;let e=Oh(be.session),t=be.session.agentPermitted!==!0;try{if(!(await fetch(`/api/sessions/agent-permission`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:e,allowed:t})})).ok){s(`Failed to update agent access`);return}s(t?`Agent access enabled`:`Agent access disabled`),R(null),o()}catch{s(`Failed to update agent access`)}},ut=async e=>{let t=e.displayName||e.name;if(window.confirm(`Kill session "${t}" for all participants? Its running process is terminated.`))try{if(!(await fetch(`/api/sessions/delete`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:Oh(e)})})).ok){s(`Failed to kill session`);return}s(`Killed ${t}`),R(null),o()}catch{s(`Failed to kill session`)}},dt=async()=>{if(!be)return;let e=be.session.createdBy===`agent`?`user`:`agent`;try{if(!(await fetch(`/api/sessions/origin`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:Oh(be.session),createdBy:e})})).ok){s(`Failed to change session origin`);return}s(e===`user`?`Moved to user sessions`:`Moved to agent sessions`),R(null),o()}catch{s(`Failed to change session origin`)}},ft=async()=>{be&&await ut(be.session)},pt=async()=>{if(!be)return;let e=be.session.parked!==!0;try{if(!(await fetch(`/api/sessions/park`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:Oh(be.session),parked:e})})).ok){s(`Failed to update park state`);return}s(e?`Parked — find it under “parked” at the bottom`:`Back on the wall`),R(null),o()}catch{s(`Failed to update park state`)}},V=async()=>{if(be)try{let e=await fetch(`/api/sessions/archive`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:Oh(be.session)})});if(!e.ok){s((await e.json().catch(()=>({}))).error||`Failed to stop session`);return}s(`Stopped & parked — opening it later resumes the conversation`),R(null),o()}catch{s(`Failed to stop session`)}},mt=(e,t)=>{we(e.displayName||e.name),R({session:e,mode:`rename`,anchor:t??{x:window.innerWidth/2+132,y:window.innerHeight/3}})},ht=async e=>{e.preventDefault();let t=De.trim();if(t){if(!/^[a-zA-Z0-9_-]+$/.test(t)){s(`Only letters, numbers, - and _ allowed`);return}try{let e=await fetch(`/api/sessions`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,type:`terminal`,port:null})}),n=await e.json().catch(()=>({}));if(!e.ok||!n.name){let r=e.status===409?Le.find(e=>(e.displayName||e.name).toLowerCase()===t.toLowerCase()):null;if(r){let e=u.find(e=>e.id===r.folderId);s(`"${r.displayName||r.name}" already exists${e?` in ${e.name}`:``} — showing it`),Ee(!1),Oe(``),Ae(null);let t=Oh(r);Se(t);let n=Xe.get(t);typeof n==`number`&&(We(n),requestAnimationFrame(()=>{document.querySelector(`[data-nav-index="${n}"]`)?.scrollIntoView({block:`center`})}));return}s(n.error||`Failed to create session`);return}Ee(!1),Oe(``),ke&&(await fetch(`/api/sessions/move`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:n.name,folderId:ke.id})}).catch(()=>{}),Ae(null)),l?.({name:n.name,displayName:n.name,active:!1,starting:!0,internalName:n.name}),Se(n.name),o()}catch{s(`Failed to create session`)}}};if(!e)return null;let gt=Date.now(),_t=e=>(e.bellUnseen||e.unread)&&(0,$.jsx)(`span`,{className:`attention-dot ${e.bellUnseen?`bell`:`output`}`,title:e.bellUnseen?`Bell rung since last viewed`:`New output since last viewed`}),vt=e=>{let t=qh(e);return t?/^\d+\.\d+\.\d+$/.test(t)?`claude`:t:``},yt=e=>{let t=e.cwd||``;return t?t.replace(/^\/(?:Users|home)\/[^/]+(?=\/|$)/,`~`).replace(/^\/root(?=\/|$)/,`~`):``},bt=e=>{let t=[],n=vh(e.lastActivityAt||0,gt);n&&t.push(n);let r=vt(e);return r&&t.push(r),t.join(` · `)},xt=e=>n!==null&&(e.internalName===n||e.name===n),St=e=>({onPointerDown:t=>tt(t,e),onPointerUp:nt,onPointerLeave:nt,onPointerMove:rt,onContextMenu:t=>{t.preventDefault(),Fe.current=!1,st(e,{x:t.clientX,y:t.clientY})}}),Ct=(e,t)=>{let n=Oh(e),r=Me.current.get(n),i=xt(e),o=Xe.get(n)===Ue,l=!i&&gt-(e.lastActivityAt||0)<12e3,u=xe===n,p=k===`manual`&&(!u||_e===n);return(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"data-nav-index":Xe.get(n),className:`switcher-card${i?` current`:``}${l?` active-now`:``}${o?` kbd-selected`:``}${xe===n?` focused`:``}${P===n?` dragging`:``}${p?` draggable`:``}`,draggable:p,onDragStart:p?e=>{F(n),e.dataTransfer.effectAllowed=`move`}:void 0,onDragEnter:p?()=>{P&&P!==n&&ye(P,n)}:void 0,onDragOver:p?e=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`}:void 0,onDrop:p?e=>{e.preventDefault(),Fe.current=!0,F(null)}:void 0,onDragEnd:p?()=>{Fe.current=!0,F(null),window.setTimeout(()=>{Fe.current=!1},250)}:void 0,onClick:t=>{if(Fe.current){Fe.current=!1;return}t.target?.closest?.(`button, a, input`)||(at(e)?it(e):ot(e))},onKeyDown:t=>{if(t.key===`Enter`&&!t.shiftKey){if(t.metaKey||t.ctrlKey){a(e);return}at(e)?it(e):ot(e)}},...St(e),children:[(0,$.jsxs)(`div`,{className:`switcher-card-head${k===`manual`&&u?` drag-handle`:``}`,onPointerDown:k===`manual`&&u?()=>ve(n):void 0,children:[_t(e),(0,$.jsx)(`span`,{className:`switcher-card-name`,children:e.displayName}),i&&(0,$.jsx)(`span`,{className:`switcher-chip current`,children:`CURRENT`}),y===`all`&&e.createdBy===`agent`&&(0,$.jsxs)(`span`,{className:`switcher-chip agent`+(e.createdVia===`cli-agent-env`?` inferred`:``),title:e.createdVia===`mcp`?`Started by an agent over MCP`:e.createdVia===`hopa`?`Started by an agent via the hopa CLI`:e.createdVia===`cli-agent-env`?`Guessed from the hop CLI's environment (CLAUDECODE) — not a dedicated agent interface, so this label can be wrong`:`Marked as an agent session`,children:[`AGENT`,e.createdVia===`cli-agent-env`?`?`:``]}),!i&&e.starting&&!e.active&&(0,$.jsx)(`span`,{className:`switcher-chip starting`,children:`STARTING`}),Ah(r)&&(0,$.jsx)(`span`,{className:`switcher-chip waiting`,title:`Claude is asking how to resume this conversation — open it and choose`,children:`NEEDS YOU`}),wt(e)]}),e.tagline&&(0,$.jsx)(`div`,{className:`switcher-card-tagline`,title:e.tagline,children:e.tagline}),re&&c&&e.active&&e.type!==`port`?(0,$.jsx)(`div`,{className:`switcher-preview switcher-preview-live`,children:(0,$.jsx)(Yh,{wsBase:c,room:n,userName:d||`user`,theme:f,live:xe===n,claudeApp:vt(e)===`claude`,claimSize:e.hasLocalCli!==!0,activeCols:r?.cols,activeRows:r?.rows,onFullscreen:()=>a(e),onUnfocus:()=>Se(null),onNotice:s})}):(0,$.jsx)(`pre`,{className:`switcher-preview`,"aria-hidden":`true`,children:r?.color?.length&&r.cols&&r.rows&&E>=Ch?(0,$.jsx)(Wh,{frame:r}):r?.color?.length?Gh(r.color):r?.text||` `}),t&&(0,$.jsx)(`div`,{className:`switcher-card-snippet`,title:t,children:t}),(0,$.jsxs)(`div`,{className:`switcher-card-meta`,children:[(0,$.jsx)(`span`,{className:`switcher-card-dir`,title:e.cwd||void 0,children:yt(e)?`\u200E${yt(e)}\u200E`:`\xA0`}),(0,$.jsx)(`span`,{className:`switcher-card-when`,children:bt(e)})]})]},n)},wt=e=>(0,$.jsxs)(`span`,{className:`switcher-inline-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`switcher-icon-btn`,"aria-label":`Rename ${e.displayName}`,title:`Rename`,onClick:t=>{t.stopPropagation();let n=t.currentTarget.getBoundingClientRect();mt(e,{x:n.right,y:n.bottom})},onPointerDown:e=>e.stopPropagation(),children:(0,$.jsx)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,$.jsx)(`path`,{d:`M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z`})})}),(0,$.jsx)(`button`,{type:`button`,className:`switcher-icon-btn danger`,"aria-label":`Kill ${e.displayName}`,title:`Kill session`,onClick:t=>{t.stopPropagation(),ut(e)},onPointerDown:e=>e.stopPropagation(),children:(0,$.jsx)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,$.jsx)(`path`,{d:`M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6M10 11v6M14 11v6`})})}),(0,$.jsx)(`button`,{type:`button`,className:`switcher-icon-btn`,"aria-label":`More actions for ${e.displayName}`,title:`More`,onClick:t=>{t.stopPropagation();let n=t.currentTarget.getBoundingClientRect();st(e,{x:n.right,y:n.bottom})},onPointerDown:e=>e.stopPropagation(),children:`⋯`})]}),Tt=be?.session,Et=Tt?.agentPermitted===!0;return(0,$.jsxs)(`div`,{className:`switcher-overlay${ne.min<300?` tile-dense`:``}${ne.min<150?` tile-micro`:``}${i?``:` switcher-hub`}${i?` switcher-fullscreen`:``}`,style:{"--tile-min":`${ne.min}px`,"--tile-h":ne.h,"--tile-fs":ne.fs},role:`dialog`,"aria-label":`Sessions`,children:[(0,$.jsxs)(`div`,{className:`switcher-top`,children:[(0,$.jsxs)(`header`,{className:`switcher-header`,children:[(0,$.jsx)(`h2`,{children:`Sessions`}),(0,$.jsx)(`span`,{className:`switcher-count`,children:Ie.length}),y!==`agent`&&(0,$.jsxs)(`button`,{type:`button`,className:`switcher-new-top`,title:`New session`,"aria-label":`New session`,onClick:()=>Ee(!0),children:[`+`,(0,$.jsx)(`span`,{className:`switcher-new-label`,children:` New`})]}),(0,$.jsxs)(`div`,{className:`switcher-tilesize`,role:`group`,"aria-label":`Tile zoom`,children:[(0,$.jsx)(`button`,{type:`button`,"aria-label":`Smaller tiles`,title:`Smaller tiles (−)`,disabled:E<=0,onClick:()=>O(E-1),children:`−`}),(0,$.jsx)(`span`,{className:`switcher-zoom-readout`,"aria-hidden":`true`,children:E+1}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Bigger tiles`,title:E>=T?`Tiles already span the full width`:`Bigger tiles (+)`,disabled:E>=T,onClick:()=>O(E+1),children:`+`})]}),re&&(0,$.jsx)(`span`,{className:`switcher-chip live`,title:`Tiles are live terminals at this zoom — click one to type in it. ⌘⏎ opens it full screen, ⌘. releases it.`,children:`⌨ interactive`}),(0,$.jsx)(`span`,{className:`switcher-header-spacer`}),m&&(0,$.jsx)(`button`,{type:`button`,className:`switcher-action`,"aria-label":`Toggle keyboard`,title:`Toggle keyboard`,onClick:m,children:(0,$.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`rect`,{x:`2`,y:`4`,width:`20`,height:`14`,rx:`2`}),(0,$.jsx)(`path`,{d:`M6 8h.01M10 8h.01M14 8h.01M18 8h.01M6 12h.01M10 12h.01M14 12h.01M18 12h.01M8 16h8`})]})}),h&&(0,$.jsx)(`button`,{type:`button`,className:`switcher-action`,"aria-label":`Find in terminal`,title:`Find in terminal`,onClick:h,children:(0,$.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`circle`,{cx:`11`,cy:`11`,r:`7`}),(0,$.jsx)(`path`,{d:`M21 21l-4.3-4.3`})]})}),p&&(0,$.jsx)(`button`,{type:`button`,className:`switcher-action`,"aria-label":`Settings`,title:`Settings`,onClick:p,children:(0,$.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`circle`,{cx:`12`,cy:`12`,r:`3`}),(0,$.jsx)(`path`,{d:`M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.01a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51h.01a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.01a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z`})]})}),i&&(0,$.jsx)(`button`,{type:`button`,className:`switcher-close`,"aria-label":`Close switcher`,onClick:r,children:`✕`})]}),(0,$.jsxs)(`div`,{className:`switcher-filter-row`,children:[(0,$.jsx)(`div`,{className:`switcher-origin`,role:`group`,"aria-label":`Session origin`,children:[[`user`,`User`],[`agent`,`Agent`],[`all`,`All`]].map(([e,t])=>(0,$.jsx)(`button`,{type:`button`,className:y===e?`active`:``,"aria-pressed":y===e,onClick:()=>{b(e),Ee(!1),Ve.current=null},children:t},e))}),(0,$.jsx)(`div`,{className:`switcher-origin switcher-sort`,role:`group`,"aria-label":`Organize sessions by`,children:[[`recent`,`Recent`,`Most recently active first`],[`project`,`Project`,`Grouped by working directory`],[`manual`,`Manual`,`Your own drag order`]].map(([e,t,n])=>(0,$.jsx)(`button`,{type:`button`,className:k===e?`active`:``,"aria-pressed":k===e,title:n,onClick:()=>j(e),children:t},e))}),k===`project`&&(0,$.jsx)(`div`,{className:`switcher-origin switcher-density`,role:`group`,"aria-label":`Project view density`,children:[[!1,`Sections`,`A header per project`],[!0,`Compact`,`One continuous grid — the project is on each card`]].map(([e,t,n])=>(0,$.jsx)(`button`,{type:`button`,className:M===e?`active`:``,"aria-pressed":M===e,title:n,onClick:()=>ie(e),children:t},t))}),(0,$.jsx)(`input`,{ref:He,className:`switcher-filter${Ge||Ie.length>xh||g?``:` compact`}`,placeholder:`Filter…`,value:g,onChange:e=>{Se(null),v(e.target.value)},"aria-label":`Filter sessions`})]}),Te&&!ke&&(0,$.jsxs)(`form`,{className:`switcher-create-row inline-edit`,onSubmit:ht,children:[(0,$.jsx)(`input`,{placeholder:`session-name`,value:De,onChange:e=>Oe(e.target.value),maxLength:64,autoFocus:!0,"aria-label":`New session name`}),(0,$.jsx)(`button`,{type:`submit`,children:`Create`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{Ee(!1),Oe(``),Ae(null)},children:`✕`})]})]}),(0,$.jsxs)(`div`,{className:`switcher-scroll`,ref:S,onContextMenu:de,children:[z.mode===`filter`?(0,$.jsxs)($.Fragment,{children:[z.rows.length===0&&Je.length===0?(0,$.jsxs)(`div`,{className:`switcher-empty`,children:[`No sessions match “`,g.trim(),`”`]}):(0,$.jsx)(`div`,{className:`switcher-grid`,children:z.rows.map(e=>Ct(e))}),Je.length>0&&(0,$.jsxs)(`section`,{className:`switcher-group`,children:[(0,$.jsx)(`h3`,{className:`switcher-group-label`,children:`found in terminal output`}),(0,$.jsx)(`div`,{className:`switcher-grid`,children:Je.map(({session:e,snippet:t})=>Ct(e,t))})]})]}):z.mode===`project`?(0,$.jsxs)($.Fragment,{children:[y===`agent`&&Ie.length===0&&(0,$.jsx)(`div`,{className:`switcher-empty`,children:`No agent sessions`}),M?(0,$.jsx)(`div`,{className:`switcher-grid`,children:z.groups.flatMap(e=>e.rows).map(e=>Ct(e))}):z.groups.map(e=>(0,$.jsxs)(`section`,{className:`switcher-group`,children:[(0,$.jsx)(`h3`,{className:`switcher-group-label`,children:e.label}),(0,$.jsx)(`div`,{className:`switcher-grid`,children:e.rows.map(e=>Ct(e))})]},e.label))]}):z.mode===`manual`?(0,$.jsx)($.Fragment,{children:z.rows.length===0&&z.folders.every(e=>e.rows.length===0)?(0,$.jsx)(`div`,{className:`switcher-empty`,children:g.trim()?`No matches`:`No sessions`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{className:`switcher-hint`,children:[g.trim()?`Showing matches in your order — drag one next to another (or ⌥↑/⌥↓); the move applies to the full list`:`Drag tiles to reorder, or onto a folder to file them`,(0,$.jsx)(`button`,{type:`button`,className:`switcher-folder-new`,onClick:pe,children:`+ New folder`})]}),z.folders.map(({folder:e,rows:t})=>(0,$.jsxs)(`section`,{className:`switcher-group switcher-folder`+(I===e.id?` drop-target`:``),onDragOver:t=>{t.preventDefault(),ce(e.id)},onDragLeave:()=>ce(t=>t===e.id?null:t),onDrop:t=>{t.preventDefault(),ce(null),Fe.current=!0,P&&ge(P,e.id),F(null)},children:[(0,$.jsxs)(`h3`,{className:`switcher-group-label`,onContextMenu:t=>L(t,e),children:[e.name,(0,$.jsx)(`span`,{className:`switcher-folder-count`,children:t.length}),(0,$.jsx)(`button`,{type:`button`,className:`switcher-folder-add`,title:`New session in `+e.name,onClick:()=>{Ae(e),Ee(!0)},children:`+`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>me(e),title:`Rename folder`,children:`✎`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>he(e),title:`Delete folder`,children:`🗑`})]}),Te&&ke?.id===e.id&&(0,$.jsxs)(`form`,{className:`switcher-create-row inline-edit switcher-create-infolder`,onSubmit:ht,children:[(0,$.jsx)(`input`,{placeholder:`new session in `+e.name,value:De,onChange:e=>Oe(e.target.value),maxLength:64,autoFocus:!0,"aria-label":`New session name in `+e.name}),(0,$.jsx)(`button`,{type:`submit`,children:`Create`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{Ee(!1),Oe(``),Ae(null)},children:`✕`})]}),t.length===0?Te&&ke?.id===e.id?null:(0,$.jsx)(`p`,{className:`switcher-folder-empty`,children:`Drag a session here, or + to create one`}):(0,$.jsx)(`div`,{className:`switcher-grid`,children:t.map(e=>Ct(e))})]},e.id)),z.folders.length>0&&z.rows.length>0&&(0,$.jsx)(`h3`,{className:`switcher-group-label switcher-unfiled`+(I===``?` drop-target`:``),onDragOver:e=>{e.preventDefault(),ce(``)},onDragLeave:()=>ce(e=>e===``?null:e),onDrop:e=>{e.preventDefault(),ce(null),Fe.current=!0,P&&ge(P,null),F(null)},children:`Unfiled`}),(0,$.jsx)(`div`,{className:`switcher-grid`,children:z.rows.map(e=>Ct(e))})]})}):(0,$.jsxs)($.Fragment,{children:[y===`agent`&&Ie.length===0&&(0,$.jsx)(`div`,{className:`switcher-empty`,children:`No agent sessions`}),(0,$.jsxs)(`div`,{className:`switcher-grid`,children:[z.hero.map(e=>Ct(e)),y!==`agent`&&!Te&&(0,$.jsxs)(`button`,{type:`button`,className:`switcher-card new`,onClick:()=>Ee(!0),children:[(0,$.jsx)(`span`,{className:`switcher-new-plus`,children:`+`}),(0,$.jsx)(`span`,{children:`New session`})]})]}),z.groups.map(e=>(0,$.jsxs)(`section`,{className:`switcher-group`,children:[e.label&&(0,$.jsx)(`h3`,{className:`switcher-group-label`,children:e.label}),(0,$.jsx)(`div`,{className:`switcher-grid`,children:e.rows.map(e=>Ct(e))})]},e.label||`tail`))]}),z.mode!==`filter`&&Re.length>0&&(0,$.jsxs)(`section`,{className:`switcher-group switcher-parked`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`switcher-parked-toggle`,"aria-expanded":ze,onClick:()=>Be(e=>!e),children:[ze?`▾`:`▸`,` parked · `,Re.length]}),ze&&(0,$.jsx)(`div`,{className:`switcher-rows`,children:Re.map(e=>{let t=Oh(e);return(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,className:`switcher-row parked`,onClick:()=>ot(e),onKeyDown:t=>{t.key===`Enter`&&!t.shiftKey&&ot(e)},...St(e),children:[_t(e),(0,$.jsx)(`span`,{className:`switcher-row-name`,children:e.displayName}),(0,$.jsx)(`span`,{className:`switcher-chip`,children:e.active?`PARKED`:`STOPPED`}),e.tagline&&(0,$.jsx)(`span`,{className:`switcher-row-dir`,children:e.tagline}),(0,$.jsx)(`span`,{className:`switcher-row-meta`,children:bt(e)}),wt(e)]},t)})})]})]}),be&&Tt&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`switcher-sheet-backdrop`,onClick:()=>R(null)}),(0,$.jsxs)(`div`,{className:`switcher-sheet`,role:`menu`,"aria-label":`Actions for ${Tt.displayName}`,style:(()=>{let e=be.mode===`rename`?140:340,t=Math.min(Math.max(8,be.anchor.x-264),window.innerWidth-264-8),n=be.anchor.y+8;return n+e>window.innerHeight-8&&(n=Math.max(8,be.anchor.y-e-8)),{left:t,top:n}})(),children:[(0,$.jsx)(`p`,{className:`switcher-sheet-title`,children:Tt.displayName}),be.mode===`rename`?(0,$.jsxs)(`form`,{className:`inline-edit`,onSubmit:ct,children:[(0,$.jsx)(`input`,{value:Ce,onChange:e=>we(e.target.value),maxLength:64,autoFocus:!0,"aria-label":`New session name`}),(0,$.jsx)(`button`,{type:`submit`,children:`Save`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>R({session:Tt,mode:`menu`,anchor:be.anchor}),children:`✕`})]}):(0,$.jsxs)($.Fragment,{children:[!xt(Tt)&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{R(null),a(Tt)},children:`Open full screen`}),(0,$.jsx)(`button`,{type:`button`,onClick:async()=>{R(null),s(`Forking…`);try{let e=await fetch(`/api/sessions/fork`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:Oh(Tt)})}),t=await e.json().catch(()=>({}));if(!e.ok){s(t.error||`Fork failed`);return}s(t.kind===`claude`?`Forked conversation → ${t.name}`:t.kind===`codex`?`${t.name} opened — pick the conversation to resume`:`Forked → ${t.name} (new shell, same directory)`),o()}catch{s(`Fork failed`)}},children:`Fork session`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{we(Tt.displayName||Tt.name),R({session:Tt,mode:`rename`,anchor:be.anchor})},children:`Rename`}),Tt.type!==`port`&&(0,$.jsx)(`button`,{type:`button`,onClick:lt,children:Et?`Disable agent access`:`Enable agent access`}),Tt.type!==`port`&&(0,$.jsx)(`button`,{type:`button`,onClick:dt,children:Tt.createdBy===`agent`?`Move to user sessions`:`Move to agent sessions`}),Tt.type!==`port`&&(0,$.jsx)(`button`,{type:`button`,onClick:pt,children:Tt.parked?`Unpark session`:`Park session`}),Tt.type!==`port`&&Tt.active&&(0,$.jsx)(`button`,{type:`button`,onClick:V,children:`Stop & park (resumable)`}),(0,$.jsx)(`button`,{type:`button`,className:`danger`,onClick:ft,children:`Kill session`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>R(null),children:`Cancel`})]})]})]}),(0,$.jsx)(rh,{request:le,onClose:()=>ue(null)})]})},Zh=({sessionName:e,procLabel:t,wsUrl:n,userName:r,cols:i,rows:a,fontSize:o,theme:s,focused:c,onFocus:l,onClose:u,onPromote:d})=>{let f=(0,_.useRef)(null),p=(0,_.useRef)(null),m=(0,_.useRef)(null),h=(0,_.useRef)(null),[g,v]=(0,_.useState)(`connecting`),[y,b]=(0,_.useState)(1),[ee,S]=(0,_.useState)(!1),C=(0,_.useRef)({cols:i,rows:a}),w=(0,_.useRef)(c);w.current=c;let te=(0,_.useRef)(()=>{});return(0,_.useEffect)(()=>{if(!f.current)return;let t=new nc({cols:C.current.cols,rows:C.current.rows,fontSize:o,fontFamily:`ui-monospace, SFMono-Regular, Menlo, monospace`,theme:s,scrollback:2e3,convertEol:!1}),i=new x;t.loadAddon(i),t.open(f.current),m.current=t;let a=!0,c=null,l=0,u=()=>{let i=n.includes(`?`)?`&`:`?`,o=new WebSocket(`${n}${i}room=${encodeURIComponent(e)}&name=${encodeURIComponent(r+` (pane)`)}&cols=${C.current.cols}&rows=${C.current.rows}`);h.current=o,v(`connecting`),o.onopen=()=>v(`connected`),o.onmessage=e=>{let n=wm(String(e.data));if(n)if(n.type===`output`)t.write(n.data),!w.current&&n.data.trim()&&S(!0);else if(n.type===`snapshot`){t.reset();let e=``;n.alternateScreen&&(e+=`\x1B[?1049h`),e+=n.mouseReporting?`\x1B[?1002h`:`\x1B[?1000l\x1B[?1002l\x1B[?1003l`,e+=n.mouseSgr?`\x1B[?1006h`:`\x1B[?1006l`;let r=n.cursorHidden?`\x1B[?25l`:``;t.write(e+n.data+r,()=>t.scrollToBottom())}else n.type===`session_ended`?(a=!1,v(`ended`)):n.type===`active_size`&&n.cols>=2&&n.rows>=2&&!w.current&&(n.cols!==C.current.cols||n.rows!==C.current.rows)&&(C.current={cols:n.cols,rows:n.rows},t.resize(n.cols,n.rows),requestAnimationFrame(y))},o.onclose=()=>{a&&(v(`connecting`),l+=1,c=window.setTimeout(u,Math.min(1e3*2**l,15e3)))}};u();let d=t.onData(e=>{let t=h.current;t?.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:`input`,data:e}))}),g=()=>{let e=i.proposeDimensions();if(!e||!Number.isFinite(e.cols)||!Number.isFinite(e.rows))return;let n=Math.floor(e.cols),r=Math.floor(e.rows);if(!(n<20||n>320||r<6||r>120)){if(n!==C.current.cols||r!==C.current.rows){C.current={cols:n,rows:r},t.resize(n,r);let e=h.current;e?.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:`resize`,cols:n,rows:r}))}b(1)}},_=()=>{let e=p.current,t=f.current;if(!e||!t)return;let n=e.clientWidth-8,r=e.clientHeight-8,i=t.scrollWidth,a=t.scrollHeight;i>0&&a>0&&n>0&&r>0&&b(Math.min(n/i,r/a,1.4))},y=()=>w.current?g():_();te.current=y;let ee=new ResizeObserver(y);p.current&&ee.observe(p.current);let T=window.setTimeout(y,300);return()=>{a=!1,c&&window.clearTimeout(c),window.clearTimeout(T),ee.disconnect(),d.dispose();try{h.current?.close()}catch{}t.dispose(),m.current=null}},[e,n]),(0,_.useEffect)(()=>{m.current&&(m.current.options.fontSize=o)},[o]),(0,_.useEffect)(()=>{c&&(m.current?.focus(),S(!1)),requestAnimationFrame(()=>te.current())},[c]),(0,$.jsxs)(`div`,{className:`secondary-pane${c?` focused`:``}`,onMouseDown:l,children:[(0,$.jsxs)(`div`,{className:`secondary-pane-bar`,children:[ee&&!c&&(0,$.jsx)(`span`,{className:`secondary-pane-dot`,title:`New output`}),(0,$.jsx)(`span`,{className:`secondary-pane-name`,children:e}),t?(0,$.jsx)(`span`,{className:`secondary-pane-proc`,children:t}):null,(0,$.jsx)(`span`,{className:`secondary-pane-status ${g}`,children:g===`connected`?``:g}),d&&(0,$.jsx)(`button`,{type:`button`,"aria-label":`Swap ${e} with primary`,title:`Swap with primary (⌘⇧E)`,onClick:e=>{e.stopPropagation(),d()},children:`⇄`}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Close pane ${e}`,onClick:e=>{e.stopPropagation(),u()},children:`✕`})]}),(0,$.jsx)(`div`,{className:`secondary-pane-box`,ref:p,children:(0,$.jsx)(`div`,{className:`secondary-pane-scale`,style:{transform:`scale(${y})`},children:(0,$.jsx)(`div`,{ref:f})})})]})},Qh=()=>`room-${Math.random().toString(36).slice(2,7)}`,$h=/Mac|iPhone|iPad/i.test(navigator.platform||navigator.userAgent||``),eg=typeof navigator.vibrate==`function`,tg=typeof window<`u`&&`Notification`in window,ng=e=>{let t=e.match(/^\/s\/([^/]+)\/?$/);if(!t)return null;try{return decodeURIComponent(t[1])}catch{return t[1]}},rg=()=>ng(window.location.pathname)||new URLSearchParams(window.location.search).get(`room`),ig=e=>`/s/${encodeURIComponent(e)}/`,ag=()=>{let e=window.__HOP_SESSION__;if(e?.wsUrl){let{protocol:t,host:n}=window.location;return`${t===`https:`?`wss`:`ws`}://${n}${e.wsUrl}`}let{protocol:t,hostname:n,host:r}=window.location;return`${t===`https:`?`wss`:`ws`}://${r}/ws`},og=e=>{let t=Em(e);return t===`typing`?`typing`:t===`active`?`active`:`idle`},sg=e=>{let t=new URL(window.location.href);return t.searchParams.set(`room`,e),t.searchParams.delete(`name`),t.toString()},cg={background:`#0d1117`,foreground:`#e6edf3`,cursor:`#60a5fa`,cursorAccent:`#0d1117`,selectionBackground:`#264f78`,selectionForeground:`#e6edf3`,black:`#0d1117`,red:`#cd3131`,green:`#0dbc79`,yellow:`#e5e510`,blue:`#2472c8`,magenta:`#bc3fbc`,cyan:`#11a8cd`,white:`#e5e5e5`,brightBlack:`#6b7280`,brightRed:`#f14c4c`,brightGreen:`#23d18b`,brightYellow:`#f5f543`,brightBlue:`#3b8eea`,brightMagenta:`#d670d6`,brightCyan:`#29b8db`,brightWhite:`#ffffff`},lg={background:`#ffffff`,foreground:`#000000`,cursor:`#000000`,cursorAccent:`#ffffff`,selectionBackground:`#b5d5ff`,selectionForeground:`#000000`,selectionInactiveBackground:`#d0d0d0`,black:`#000000`,red:`#c91b00`,green:`#00a600`,yellow:`#c7c400`,blue:`#0225c7`,magenta:`#c930c7`,cyan:`#00a6b2`,white:`#c7c7c7`,brightBlack:`#676767`,brightRed:`#ff6d67`,brightGreen:`#5ff967`,brightYellow:`#fefb67`,brightBlue:`#6871ff`,brightMagenta:`#ff76ff`,brightCyan:`#5ffdff`,brightWhite:`#feffff`},ug=e=>1,dg=e=>e===`dark`?cg:e===`light`?lg:typeof window<`u`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?cg:lg,fg=()=>{if(typeof window>`u`)return!1;let e=navigator.userAgent||``;return/iPhone|iPad|iPod|Android/i.test(e)||window.innerWidth<768},pg=e=>{if(!e)return``;let t=e,n=e.match(/^(\/(?:Users|home)\/[^/]+)(\/.*)?$/);return n?t=`~`+(n[2]||``):e===`/root`?t=`~`:e.startsWith(`/root/`)&&(t=`~`+e.slice(5)),t},mg={kind:`leaf`,id:`primary`,session:null},hg=()=>`p${Math.random().toString(36).slice(2,8)}`,gg=e=>{let t=e;return!t||typeof t!=`object`?!1:t.kind===`leaf`?typeof t.id==`string`&&(t.session===null||typeof t.session==`string`):t.kind===`split`?(t.dir===`row`||t.dir===`col`)&&typeof t.ratio==`number`&&gg(t.a)&&gg(t.b):!1},_g=e=>e.kind===`leaf`?e.session===null:_g(e.a)||_g(e.b),vg=`instant`,yg=5e3,bg=15e3,xg=200,Sg=()=>window.__HOP_SESSION__,Cg=()=>!!Sg(),wg=()=>{let e=new URLSearchParams(window.location.search).get(`name`),t=localStorage.getItem(`hay_name`),n=Sg()?.name;return e??t??(n&&n!==`Guest`?n:null)??`User`},Tg=`hop_session_seen_v1`,Eg=()=>{try{let e=JSON.parse(localStorage.getItem(Tg)||`{}`);return e&&typeof e==`object`?e:{}}catch{return{}}},Dg=e=>{try{localStorage.setItem(Tg,JSON.stringify(e))}catch{}},Og=({size:e=34})=>(0,$.jsx)(`span`,{className:`ios-spinner`,style:{width:e,height:e},"aria-hidden":`true`,children:Array.from({length:12}).map((t,n)=>(0,$.jsx)(`span`,{style:{transform:`rotate(${n*30}deg) translate(0, -${e*.34}px)`,animationDelay:`${-(11-n)/12}s`}},n))}),kg=()=>{let e=Sg(),t=e?.room??rg()??Qh(),[n,r]=(0,_.useState)(()=>wg()),[i,a]=(0,_.useState)(()=>t),[o,s]=(0,_.useState)(()=>e?.room?{name:wg(),room:t}:null),[c,l]=(0,_.useState)(()=>t),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(`idle`),[m,h]=(0,_.useState)([]),[g,v]=(0,_.useState)(!0),[y,b]=(0,_.useState)(null),[ee,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(null),[te,E]=(0,_.useState)(null),ne=(0,_.useRef)(null),[re,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(0),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(!1),[ie,ae]=(0,_.useState)(``),[oe,se]=(0,_.useState)({index:0,total:0}),P=(0,_.useRef)([]),F=(0,_.useRef)(-1),I=(0,_.useRef)(null),ce=(0,_.useRef)(null),[le,ue]=(0,_.useState)({x:window.innerWidth-72,y:64}),de=(0,_.useRef)(null),[L,fe]=(0,_.useState)(()=>fg()),[pe,me]=(0,_.useState)(()=>fg()),[he,ge]=(0,_.useState)(0),[_e,ve]=(0,_.useState)(()=>localStorage.getItem(`hay_selection_mode`)===`true`),[ye,be]=(0,_.useState)(()=>localStorage.getItem(`hay_haptics_enabled`)!==`false`),[R,xe]=(0,_.useState)(()=>{let e=localStorage.getItem(`hay_notify_bells`);return tg&&e===`true`}),[Se,Ce]=(0,_.useState)(()=>localStorage.getItem(`hay_theme`)||`system`),[we,Te]=(0,_.useState)([]),[Ee,De]=(0,_.useState)(!1),[Oe,ke]=(0,_.useState)(!1),[Ae,je]=(0,_.useState)([]),[Me,Ne]=(0,_.useState)(!1),[Pe,Fe]=(0,_.useState)(!1),[Ie,Le]=(0,_.useState)(``),[Re,ze]=(0,_.useState)(!1),[Be,Ve]=(0,_.useState)(``),[z,He]=(0,_.useState)(!1),[Ue,We]=(0,_.useState)(``),[Ge,Ke]=(0,_.useState)(()=>Cg()?new URLSearchParams(window.location.search).has(`home`)||new URLSearchParams(window.location.search).get(`view`)===`wall`?!0:fg()&&!window.location.pathname.startsWith(`/s/`):!1),[qe,Je]=(0,_.useState)(()=>localStorage.getItem(`hay_session_switch_mode`)===`page`?`page`:vg);(0,_.useEffect)(()=>{o?.room&&l(o.room)},[o?.room]);let[Ye,Xe]=(0,_.useState)(()=>{let e=localStorage.getItem(`hay_font_size`);return e?parseInt(e,10):14}),[Ze,Qe]=(0,_.useState)(()=>{let e=localStorage.getItem(`hay_view_mode`);return e===`fit`||e===`full`?e:`fit`}),$e=(0,_.useRef)(null),B=(0,_.useRef)(null),et=(0,_.useRef)(null),tt=(0,_.useRef)(null),nt=(0,_.useRef)(null),rt=(0,_.useRef)(Am()),it=(0,_.useRef)(!1),at=(0,_.useRef)(null),ot=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=()=>fe(fg());return window.addEventListener(`resize`,e),window.addEventListener(`orientationchange`,e),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`orientationchange`,e)}},[]),(0,_.useEffect)(()=>{localStorage.setItem(`hay_selection_mode`,_e?`true`:`false`)},[_e]),(0,_.useEffect)(()=>{localStorage.setItem(`hay_haptics_enabled`,ye?`true`:`false`)},[ye]),(0,_.useEffect)(()=>{localStorage.setItem(`hay_notify_bells`,R?`true`:`false`)},[R]),(0,_.useEffect)(()=>{localStorage.setItem(`hay_theme`,Se);let e=document.documentElement;if(Se===`system`?e.removeAttribute(`data-theme`):e.setAttribute(`data-theme`,Se),B.current){let e=B.current,t=dg(Se);e.options.theme=t,e.options.minimumContrastRatio=ug(Se);let n=nt.current?.querySelector(`.xterm-viewport`);n&&(n.style.backgroundColor=t.background??``),typeof e.clearTextureAtlas==`function`&&e.clearTextureAtlas(),e.refresh(0,e.rows-1)}},[Se]),(0,_.useEffect)(()=>{localStorage.setItem(`hay_session_switch_mode`,qe)},[qe]);let st=(0,_.useRef)(!1),ct=(0,_.useRef)(null),lt=(0,_.useRef)(Ze),ut=(0,_.useRef)(0),dt=(0,_.useRef)(null),ft=(0,_.useRef)(!0),pt=(0,_.useRef)(0),V=(0,_.useRef)(!1),mt=(0,_.useRef)(null),ht=(0,_.useRef)(null),gt=(0,_.useRef)(null),_t=(0,_.useRef)(null),vt=(0,_.useRef)(null),yt=(0,_.useRef)(!1),bt=(0,_.useRef)(!1),xt=(0,_.useRef)(!1),St=(0,_.useRef)(!1),Ct=(0,_.useRef)(0),wt=(0,_.useRef)(null),Tt=(0,_.useRef)([]),Et=(0,_.useRef)(null),Dt=(0,_.useRef)(null),Ot=(0,_.useRef)(null),kt=(0,_.useRef)(null),[At,jt]=(0,_.useState)(!1),Mt=(0,_.useRef)(we);Mt.current=we;let Nt=(0,_.useRef)({at:0,value:!1}),H=()=>{let e=performance.now();if(e-Nt.current.at<1e3)return Nt.current.value;let t=!1,n=B.current;if(n)try{let e=n.buffer.active,r=e.baseY+n.rows,i=``;for(let t=Math.max(0,r-30);t<r;t++)i+=(e.getLine(t)?.translateToString(!0)??``)+`
126
+ `;return/bypass permissions on|shift\+tab to cycle|esc to interrupt|\? for shortcuts/i.test(n)}catch{return!1}},Hm=/\x1b\[([<>=])[0-9;:]*u|\x1b\[>([0-9;]*)m/g,Um=(e,t)=>{let n=t;Hm.lastIndex=0;let r;for(;(r=Hm.exec(e))!==null;)if(r[1]!==void 0)n=r[1]!==`<`;else{let e=(r[2]??``).split(`;`);e[0]===`4`&&(n=(e[1]??`0`)!==`0`)}return n},Wm=e=>/Mac|iPhone|iPad/i.test(e)?`Browsers can't see file paths — select the file in Finder, press ⌘⌥C, then paste here.`:/Win/i.test(e)?`Browsers can't see file paths — select the file in Explorer, press Ctrl+Shift+C, then paste here.`:`Browsers can't see file paths — copy the path in your file manager, then paste here.`,Gm=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),Km=o(((e,t)=>{t.exports=Gm()})),qm=m(),$=Km(),Jm=()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent||``;return/iPad|iPhone|iPod/.test(e)},Ym={abc:[[`q`,`w`,`e`,`r`,`t`,`y`,`u`,`i`,`o`,`p`],[`a`,`s`,`d`,`f`,`g`,`h`,`j`,`k`,`l`],[`SHIFT`,`z`,`x`,`c`,`v`,`b`,`n`,`m`,`BKSP`],[`123`,`PASTE`,`SPACE`,`RET`]],num:[[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`0`],[`-`,`/`,`:`,`;`,`(`,`)`,`$`,`&`,`@`,`"`],[`#+=`,`.`,`,`,`?`,`!`,`'`,`BKSP`],[`ABC`,`PASTE`,`SPACE`,`RET`]],sym:[[`[`,`]`,`{`,`}`,`#`,`%`,`^`,`*`,`+`,`=`],[`_`,`\\`,`|`,`~`,`<`,`>`,"`"],[`123`,`.`,`,`,`?`,`!`,`'`,`BKSP`],[`ABC`,`PASTE`,`SPACE`,`RET`]]},Xm=[{label:`Esc`,key:`\x1B`},{label:`Tab`,key:` `},{label:`Ctrl`,mod:`ctrl`},{label:`Alt`,mod:`alt`},{label:`←`,key:`\x1B[D`},{label:`↓`,key:`\x1B[B`},{label:`↑`,key:`\x1B[A`},{label:`→`,key:`\x1B[C`},{label:`KB`,fn:`sysKb`}],Zm=({filled:e})=>(0,$.jsx)(`svg`,{viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:`1.5`,fill:e?`currentColor`:`none`,children:(0,$.jsx)(`path`,{d:`M12 4L4 16h16L12 4z`})}),Qm=()=>(0,$.jsxs)(`svg`,{viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:`1.5`,fill:`none`,children:[(0,$.jsx)(`path`,{d:`M21 4H8l-7 8 7 8h13a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2z`}),(0,$.jsx)(`line`,{x1:`18`,y1:`9`,x2:`12`,y2:`15`}),(0,$.jsx)(`line`,{x1:`12`,y1:`9`,x2:`18`,y2:`15`})]}),$m=()=>(0,$.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,children:[(0,$.jsx)(`rect`,{x:`2`,y:`6`,width:`20`,height:`12`,rx:`2`}),(0,$.jsx)(`line`,{x1:`6`,y1:`10`,x2:`6.01`,y2:`10`}),(0,$.jsx)(`line`,{x1:`10`,y1:`10`,x2:`10.01`,y2:`10`}),(0,$.jsx)(`line`,{x1:`14`,y1:`10`,x2:`14.01`,y2:`10`}),(0,$.jsx)(`line`,{x1:`18`,y1:`10`,x2:`18.01`,y2:`10`}),(0,$.jsx)(`line`,{x1:`8`,y1:`14`,x2:`16`,y2:`14`})]}),eh=()=>(0,$.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,children:[(0,$.jsx)(`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`}),(0,$.jsx)(`rect`,{x:`8`,y:`2`,width:`8`,height:`4`,rx:`1`,ry:`1`})]}),th=({onInput:e,visible:t,onToggle:n,onHeightChange:r,hapticsEnabled:i=!0,onPasteFailed:a})=>{let[o,s]=(0,_.useState)(`abc`),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(!1),[x,ee]=(0,_.useState)(!1),[S,C]=(0,_.useState)(``),w=(0,_.useRef)(0),te=(0,_.useRef)(null),T=(0,_.useRef)(null),E=(0,_.useRef)(null),ne=(0,_.useRef)(null),re=(0,_.useRef)(null),D=(()=>{try{return new URLSearchParams(window.location.search).get(`diag`)!==`0`}catch{return!0}})(),O=window.__hopKbDiag=window.__hopKbDiag||{taps:0,disp:0,sent:0,buf:0},[k,A]=(0,_.useState)({taps:0,disp:0,sent:0,buf:0});(0,_.useEffect)(()=>{if(!D)return;let e=window.setInterval(()=>A({...O}),300),t=``,n=window.setInterval(()=>{let e=JSON.stringify({...O,at:Date.now()});e.slice(0,e.lastIndexOf(`,`))!==t.slice(0,t.lastIndexOf(`,`))&&(t=e,fetch(`/api/diag`,{method:`POST`,body:e,keepalive:!0}).catch(()=>{}))},4e3);return()=>{window.clearInterval(e),window.clearInterval(n)}},[D]);let j=(0,_.useRef)(e),M=(0,_.useRef)(()=>{}),N=(0,_.useRef)(c),ie=(0,_.useRef)(u),ae=(0,_.useRef)(f),oe=(0,_.useRef)(m),se=(0,_.useRef)(a);j.current=e,N.current=c,ie.current=u,ae.current=f,oe.current=m,se.current=a,(0,_.useEffect)(()=>{if(!Jm())return;let e=document.createElement(`input`);e.type=`checkbox`,e.id=`hay-haptic-switch`,e.setAttribute(`switch`,``),e.style.position=`fixed`,e.style.left=`-9999px`,e.style.top=`-9999px`,e.style.opacity=`0`,e.style.pointerEvents=`none`,document.body.appendChild(e);let t=document.createElement(`label`);return t.htmlFor=`hay-haptic-switch`,t.style.position=`fixed`,t.style.left=`-9999px`,t.style.top=`-9999px`,t.style.opacity=`0`,t.style.pointerEvents=`none`,document.body.appendChild(t),ne.current=t,()=>{document.body.removeChild(e),document.body.removeChild(t),ne.current=null}},[]);let P=e=>{e.currentTarget.classList.add(`kb-pressed`)},F=e=>{e.currentTarget.classList.remove(`kb-pressed`)},I=(0,_.useCallback)(()=>{if(i)try{typeof navigator.vibrate==`function`?navigator.vibrate(8):Jm()&&ne.current?.click()}catch{}},[i]),ce=(0,_.useCallback)(e=>{let t=e;if(ae.current){if(e.length===1){let n=e.toUpperCase().charCodeAt(0);n>=65&&n<=90&&(t=String.fromCharCode(n-64))}p(!1)}oe.current&&(t.length===1&&(t=`\x1B`+t),h(!1)),O.disp++,j.current(t),N.current&&!ie.current&&t.length===1&&(w.current=0)},[]),le=(0,_.useCallback)(async()=>{try{if(navigator.clipboard&&navigator.clipboard.readText){let e=await navigator.clipboard.readText();e&&ce(e)}else se.current?.()}catch{se.current?.()}},[ce]),ue=(0,_.useCallback)(()=>{let e=E.current;if(!e)return;e.style.height=`auto`;let t=Math.min(window.innerHeight*.4,240);e.style.height=`${Math.min(e.scrollHeight,t)}px`},[]),de=(0,_.useCallback)(()=>{E.current?.blur(),v(!1)},[]),L=(0,_.useCallback)(()=>{let e=E.current;if(!e)return;try{e.focus({preventScroll:!0})}catch{e.focus()}let t=e.value.length;typeof e.setSelectionRange==`function`&&e.setSelectionRange(t,t),ue()},[ue]),fe=(0,_.useCallback)(()=>{(0,qm.flushSync)(()=>{v(!0)}),L()},[L]),pe=(0,_.useCallback)(()=>{g?de():fe()},[g,de,fe]),me=(0,_.useCallback)(()=>{let e=S;e&&(ce(e+`\r`),C(``)),E.current&&(E.current.style.height=``),de()},[ce,de,S]);(0,_.useEffect)(()=>{if(!g||!E.current)return;let e=()=>{L()},t=requestAnimationFrame(e),n=requestAnimationFrame(e);return()=>{cancelAnimationFrame(t),cancelAnimationFrame(n)}},[g,ue]),(0,_.useEffect)(()=>{g&&ue()},[S,g,ue]),(0,_.useEffect)(()=>{if(!t){r?.(0);return}let e=re.current;if(!e)return;let n=()=>{r?.(Math.ceil(e.getBoundingClientRect().height))};if(n(),window.addEventListener(`resize`,n),typeof ResizeObserver>`u`)return()=>{window.removeEventListener(`resize`,n)};let i=new ResizeObserver(n);return i.observe(e),()=>{i.disconnect(),window.removeEventListener(`resize`,n)}},[t,r]);let he=(0,_.useCallback)(()=>{let e=Date.now(),t=w.current&&e-w.current<300;u?(d(!1),l(!1),w.current=0):c?t?(d(!0),l(!1),w.current=0):(l(!1),w.current=e):(l(!0),w.current=e)},[u,c]),ge=(0,_.useCallback)(()=>{ce(``),te.current=window.setTimeout(()=>{T.current=window.setInterval(()=>{ce(``)},50)},500)},[ce]),_e=(0,_.useCallback)(()=>{te.current&&=(clearTimeout(te.current),null),T.current&&=(clearInterval(T.current),null)},[]);(0,_.useEffect)(()=>{if(t&&!y)try{localStorage.getItem(`hay-syskb-seen`)?b(!0):(b(!0),setTimeout(()=>{ee(!0),setTimeout(()=>{ee(!1),localStorage.setItem(`hay-syskb-seen`,`1`)},4e3)},1e3))}catch{b(!0)}},[t,y]);let ve=(0,_.useCallback)((e,t,n)=>{let r=document.elementFromPoint(t,n)?.closest?.(`.kb-key`);if(r&&!r.dataset.kbChar)return;let i=r?.dataset.kbChar??null;if(!i){let r=null;for(let i of e.querySelectorAll(`[data-kb-char]`)){let e=i.getBoundingClientRect(),a=Math.max(e.left-t,0,t-e.right),o=Math.max(e.top-n,0,n-e.bottom),s=Math.hypot(a,o);s<=30&&(!r||s<r.d)&&(r={key:i.dataset.kbChar,d:s})}i=r?.key??null}i&&M.current(i)},[]),ye=(0,_.useCallback)(e=>{let t=e.currentTarget;for(let n=0;n<e.changedTouches.length;n++){let r=e.changedTouches[n];O.taps++,ve(t,r.clientX,r.clientY)}},[ve]),be=(0,_.useCallback)(e=>{e.pointerType!==`touch`&&(O.taps++,ve(e.currentTarget,e.clientX,e.clientY))},[ve]);M.current=(0,_.useCallback)(e=>{let t=N.current||ie.current?e.toUpperCase():e;ce(t),N.current&&!ie.current&&l(!1)},[ce]);let R=(e,t,n)=>{let r=c||u;if(e===`SHIFT`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act${r?` kb-on`:``}`,style:{flexGrow:1.25},onTouchStart:e=>{e.preventDefault(),P(e),he()},onTouchEnd:F,onTouchCancel:F,onClick:I,children:(0,$.jsx)(Zm,{filled:r})},e);if(e===`BKSP`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act`,style:{flexGrow:1.25},onTouchStart:e=>{e.preventDefault(),P(e),ge()},onTouchEnd:e=>{F(e),_e()},onTouchCancel:e=>{F(e),_e()},onClick:I,children:(0,$.jsx)(Qm,{})},e);if(e===`PASTE`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act`,style:{flexGrow:1.25},onTouchStart:P,onTouchEnd:e=>{F(e),le()},onTouchCancel:F,onClick:I,children:(0,$.jsx)(eh,{})},e);if(e===`RET`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-pri kb-bottom`,style:{flexGrow:2.5},onTouchStart:e=>{e.preventDefault(),P(e),ce(`\r`)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:`return`},e);if(e===`SPACE`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-bottom`,style:{flexGrow:5},onTouchStart:e=>{e.preventDefault(),P(e),ce(` `)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:`space`},e);if(e===`123`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act${n?``:` kb-bottom`}`,style:{flexGrow:1.25},onTouchStart:e=>{e.preventDefault(),P(e),s(`num`)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:`123`},e);if(e===`#+=`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act`,style:{flexGrow:1.25},onTouchStart:e=>{e.preventDefault(),P(e),s(`sym`)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:`#+=`},e);if(e===`ABC`)return(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act kb-bottom`,style:{flexGrow:1.25},onTouchStart:e=>{e.preventDefault(),P(e),s(`abc`)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:`ABC`},e);let i=c||u?e.toUpperCase():e;return(0,$.jsx)(`button`,{type:`button`,className:`kb-key`,"data-kb-char":e,onTouchStart:e=>{e.preventDefault(),P(e)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:i},`${e}-${t}`)};return t?(0,$.jsxs)($.Fragment,{children:[x&&(0,$.jsx)(`div`,{className:`kb-hint-overlay`,children:(0,$.jsxs)(`div`,{className:`kb-hint`,children:[`Tap the pulsing `,(0,$.jsx)(`strong`,{children:`KB`}),` button for smooth typing with native keyboard, spellcheck, autocomplete and dictation`]})}),g&&(0,$.jsx)(`div`,{className:`kb-sys-overlay`,onClick:pe,children:(0,$.jsx)(`div`,{className:`kb-sys-dialog`,onClick:e=>e.stopPropagation(),children:(0,$.jsx)(`textarea`,{ref:E,className:`kb-sys-input`,placeholder:`Type here — return runs it...`,autoCapitalize:`off`,autoComplete:`off`,autoCorrect:`off`,rows:1,value:S,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),me())},onChange:e=>{C(e.currentTarget.value)},onInput:ue})})}),(0,$.jsxs)(`div`,{ref:re,className:`mobile-keyboard`,children:[(0,$.jsx)(`div`,{className:`kb-acc-row`,children:Xm.map((e,t)=>e.mod?(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act kb-acc${(e.mod===`ctrl`?f:m)?` kb-on`:``}`,onTouchStart:t=>{t.preventDefault(),P(t),e.mod===`ctrl`?p(e=>!e):h(e=>!e)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:e.label},e.label):e.fn===`sysKb`?(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act kb-acc kb-syskb${x?` kb-pulse`:``}`,onTouchStart:e=>{e.preventDefault(),P(e);try{localStorage.setItem(`hay-syskb-seen`,`1`)}catch{}pe()},onTouchEnd:F,onTouchCancel:F,onClick:I,children:(0,$.jsx)($m,{})},e.label):(0,$.jsx)(`button`,{type:`button`,className:`kb-key kb-act kb-acc`,onTouchStart:t=>{t.preventDefault(),P(t),e.key&&ce(e.key)},onTouchEnd:F,onTouchCancel:F,onClick:I,children:e.label},e.label))}),D&&(0,$.jsxs)(`div`,{style:{position:`absolute`,top:2,left:8,zIndex:60,fontFamily:`monospace`,fontSize:12,lineHeight:`18px`,color:`#fff`,background:`rgba(0,0,0,0.65)`,borderRadius:6,padding:`1px 8px`,pointerEvents:`none`},children:[`taps `,k.taps,` · disp `,k.disp,` · sent `,k.sent,k.buf?` · buf ${k.buf}`:``]}),(0,$.jsx)(`div`,{className:`kb-keys`,onTouchStartCapture:ye,onPointerDown:be,children:Ym[o].map((e,t)=>{let n=t===2;return(0,$.jsx)(`div`,{className:`kb-row${t===1?` kb-r2`:``}${n?` kb-r3`:``}`,children:e.map((e,t)=>{let r=[];return(e===`SHIFT`||e===`#+=`||e===`123`)&&n?(r.push(R(e,t,n)),r.push((0,$.jsx)(`div`,{className:`kb-gap`},`gap-after-shift`)),r):e===`BKSP`&&n?(r.push((0,$.jsx)(`div`,{className:`kb-gap`},`gap-before-bksp`)),r.push(R(e,t,n)),r):R(e,t,n)})},t)})})]})]}):null},nh=e=>e.kind!==`separator`,rh=({request:e,onClose:t})=>{let n=(0,_.useRef)(null),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(0);return(0,_.useLayoutEffect)(()=>{if(!e){i(null);return}let t=n.current,r=t?.offsetWidth||200,a=t?.offsetHeight||200;i({left:Math.max(8,Math.min(e.x,window.innerWidth-r-8)),top:Math.max(8,Math.min(e.y,window.innerHeight-a-8))}),o(e.items.findIndex(nh))},[e]),(0,_.useEffect)(()=>{if(!e)return;let r=n=>{if(n.key===`Escape`){n.preventDefault(),t();return}let r=e.items.map((e,t)=>nh(e)&&!e.disabled?t:-1).filter(e=>e>=0);if(r.length!==0){if(n.key===`ArrowDown`||n.key===`ArrowUp`){n.preventDefault();let e=r.indexOf(a),t=n.key===`ArrowDown`?r[(e+1+r.length)%r.length]:r[(e-1+r.length)%r.length];o(t)}else if(n.key===`Enter`){n.preventDefault();let r=e.items[a];r&&nh(r)&&!r.disabled&&(t(),r.onSelect())}}},i=e=>{n.current?.contains(e.target)||t()};return window.addEventListener(`keydown`,r,!0),window.addEventListener(`mousedown`,i,!0),window.addEventListener(`resize`,t),window.addEventListener(`blur`,t),()=>{window.removeEventListener(`keydown`,r,!0),window.removeEventListener(`mousedown`,i,!0),window.removeEventListener(`resize`,t),window.removeEventListener(`blur`,t)}},[e,a,t]),e?(0,$.jsx)(`div`,{ref:n,className:`context-menu`,role:`menu`,style:r?{left:r.left,top:r.top}:{left:-9999,top:-9999},onContextMenu:e=>e.preventDefault(),children:e.items.map((e,n)=>nh(e)?(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`context-menu-item`+(e.danger?` danger`:``)+(n===a?` active`:``),disabled:e.disabled,onMouseEnter:()=>o(n),onClick:()=>{t(),e.onSelect()},children:[(0,$.jsx)(`span`,{children:e.label}),e.hint&&(0,$.jsx)(`kbd`,{children:e.hint})]},e.label+n):(0,$.jsx)(`div`,{className:`context-menu-separator`,role:`separator`},`sep`+n))}):null},ih=4,ah=e=>e.internalName||e.name,oh=(e,t)=>t!==null&&(e.internalName===t||e.name===t),sh=e=>e.lastActivityAt||0,ch=e=>e.bellUnseen?2:+!!e.unread,lh=(e,t)=>{let n=ch(t)-ch(e);return n===0?sh(t)-sh(e):n},uh=e=>{let t=e.match(/^(\/(?:Users|home)\/[^/]+)(\/.*)?$/);return t?`~`+(t[2]||``):e===`/root`?`~`:e.startsWith(`/root/`)?`~`+e.slice(5):e},dh=e=>{if(!e)return`Other`;let t=uh(e),n=t.startsWith(`~`)?`~`:``,r=t.replace(/^~\/?/,``).split(`/`).filter(Boolean).slice(0,n?2:3);return r.length===0?n||`/`:(n?n+`/`:`/`)+r.join(`/`)},fh=(e,t)=>{let n=(e.displayName||e.name).toLowerCase(),r=(e.cwd||``).toLowerCase(),i=e.cwd?uh(e.cwd).toLowerCase():``,a=(e.foregroundProcess||``).toLowerCase();return n===t?100:i===t?90:n.startsWith(t)?80:(i.split(`/`).filter(Boolean).pop()||``)===t?70:n.includes(t)?60:i.startsWith(t)?55:i.includes(t)||r.includes(t)?40:a.includes(t)?30:0},ph=(e,t)=>t===`all`?e:t===`agent`?e.filter(e=>e.createdBy===`agent`):e.filter(e=>e.createdBy!==`agent`),mh=(e,t=!1)=>{let n=new Map;for(let t of e){let e=t.type===`port`?`Ports`:dh(t.cwd),r=n.get(e);r?r.push(t):n.set(e,[t])}let r=(e,t)=>(e.displayName||e.name).localeCompare(t.displayName||t.name);return Array.from(n.entries()).map(([e,n])=>({label:e,rows:n.sort(t?r:lh)})).sort((e,n)=>e.label===`Ports`?1:n.label===`Ports`?-1:t?e.label.localeCompare(n.label):Math.max(...n.rows.map(sh))-Math.max(...e.rows.map(sh)))},hh=(e,t)=>{let n=new Map(t.map((e,t)=>[e,t])),r=(e,t)=>(e.displayName||e.name).localeCompare(t.displayName||t.name);return[...e].sort((e,t)=>{let i=n.get(ah(e)),a=n.get(ah(t));return i!==void 0&&a!==void 0?i-a:i===void 0?a===void 0?r(e,t):1:-1})},gh=(e,t,n)=>{let r=new Map(t.map(e=>[e.id,[]])),i=[];for(let t of e){let e=t.folderId?r.get(t.folderId):void 0;e?e.push(t):i.push(t)}return{folders:t.map(e=>({folder:e,rows:hh(r.get(e.id)||[],n)})),loose:hh(i,n)}},_h=(e,t,n,r=`recent`,i=[],a=[])=>{let o=n.trim();if(o){let t=o.toLowerCase(),n=e.filter(e=>fh(e,t)>0);if(r===`manual`){let e=gh(n,a,i);return{mode:`manual`,rows:e.loose,folders:e.folders}}return{mode:`filter`,rows:n.map(e=>({s:e,score:fh(e,t)})).sort((e,t)=>t.score-e.score||lh(e.s,t.s)).map(e=>e.s)}}if(r===`project`)return{mode:`project`,groups:mh(e,!0)};if(r===`manual`){let t=gh(e,a,i);return{mode:`manual`,rows:t.loose,folders:t.folders}}let s=e.find(e=>oh(e,t))??null,c=new Set,l=[],u=e=>{let t=ah(e);c.has(t)||(c.add(t),l.push(e))};s&&u(s),e.filter(e=>(e.bellUnseen||e.unread)&&!oh(e,t)).sort(lh).forEach(u),e.filter(e=>e.type!==`port`&&(e.active||e.starting)).sort((e,t)=>sh(t)-sh(e)).forEach(e=>{l.length<ih&&u(e)});let d=e.filter(e=>!c.has(ah(e))).sort(lh);return{mode:`tiers`,hero:l,groups:d.length>0?[{label:``,rows:d}]:[],currentInHero:s!==null}},vh=(e,t)=>{if(!e)return``;let n=Math.floor((t-e)/1e3);if(n<10)return`just now`;if(n<60)return`${n}s ago`;let r=Math.floor(n/60);if(r<60)return`${r}m ago`;let i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`},yh=450,bh=5e3,xh=10,Sh=[{min:100,h:`40px`,fs:`4px`},{min:120,h:`56px`,fs:`5px`},{min:150,h:`84px`,fs:`6px`},{min:210,h:`130px`,fs:`7.5px`},{min:300,h:`200px`,fs:`9.5px`},{min:420,h:`300px`,fs:`11px`},{min:560,h:`min(46vh, 480px)`,fs:`11px`},{min:720,h:`min(56vh, 640px)`,fs:`12px`},{min:900,h:`min(66vh, 820px)`,fs:`13px`}],Ch=5,wh=10,Th=2,Eh={s:1,m:2,l:4,xl:5},Dh=()=>{let e=document.activeElement;return!e||e===document.body||e.closest?.(`.switcher-live-tile, .switcher-focus-tile`)?!0:!e.matches?.(`input, textarea, [contenteditable]`)},Oh=e=>e.internalName||e.name,kh=/Resume from summary|Resuming the full session|Don't ask me again/i,Ah=e=>!!e&&kh.test(e.text),jh=12,Mh=76,Nh=()=>(0,$.jsxs)(`svg`,{viewBox:`0 0 12 12`,width:`10`,height:`10`,"aria-hidden":`true`,focusable:`false`,children:[(0,$.jsx)(`circle`,{cx:`6`,cy:`3.4`,r:`2.4`,fill:`currentColor`}),(0,$.jsx)(`path`,{d:`M1.4 11.2c0-2.6 2.1-4.2 4.6-4.2s4.6 1.6 4.6 4.2z`,fill:`currentColor`})]}),Ph=0,Fh=new Map;typeof document<`u`&&document.fonts?.ready?.then(()=>{Ph=0,Fh.clear(),zh.clear()}).catch(()=>{});var Ih=e=>{let t=Fh.get(e);if(t)return t;let n=document.createElement(`span`);n.style.cssText=`position:absolute;visibility:hidden;white-space:pre;font-size:${e}px;line-height:1`,n.style.fontFamily=`var(--font-terminal)`,n.textContent=`0`.repeat(100),document.body.appendChild(n);let r=n.getBoundingClientRect().width/100||e*.6;return n.remove(),Fh.set(e,r),r},Lh=()=>Ph||(Ph=Ih(jh),Ph),Rh=e=>{let t=Ih(e),n=typeof window<`u`&&window.devicePixelRatio||1;return Math.floor(t*n)/n-t},zh=new Map,Bh=e=>{let t=zh.get(e);if(t)return t;let n=document.createElement(`div`);n.style.cssText=`position:absolute;visibility:hidden;white-space:pre;line-height:normal;font-size:${e}px`,n.style.fontFamily=`var(--font-terminal)`,n.textContent=`W`,document.body.appendChild(n);let r=n.getBoundingClientRect().height||e*1.2;return n.remove(),zh.set(e,r),r},Vh=e=>{let t=typeof window<`u`&&window.devicePixelRatio||1;return Math.floor(Bh(e)*1.3*t)/t},Hh=e=>Math.max(6.5,Math.min(13,e/(Mh*(Lh()/jh)))),Uh=typeof ResizeObserver<`u`?new ResizeObserver(e=>{for(let t of e){let e=t.target,n=e.firstElementChild;if(!n)continue;let r=Hh(e.clientWidth),i=Vh(r);n.style.fontSize=r+`px`,n.style.lineHeight=i+`px`,n.style.letterSpacing=Rh(r)+`px`,n.style.setProperty(`--tile-row-h`,i+`px`)}}):null,Wh=({frame:e})=>{let t=(0,_.useRef)(null),n=e.rows||24;(0,_.useLayoutEffect)(()=>{let e=t.current;if(!(!e||!Uh))return Uh.observe(e),()=>Uh.unobserve(e)},[]);let r=e.color||[],i=r.length<n?[...r,...Array.from({length:n-r.length},()=>[])]:r;return(0,$.jsx)(`div`,{className:`switcher-preview-scalebox`,ref:t,children:(0,$.jsx)(`div`,{className:`switcher-preview-screen`,style:{fontSize:jh,lineHeight:`${Vh(jh)}px`,letterSpacing:`${Rh(jh)}px`,"--tile-row-h":`${Vh(jh)}px`},children:Gh(i)})})},Gh=e=>e.map((e,t)=>(0,$.jsx)(`div`,{className:`switcher-preview-row`,children:e.map((e,t)=>(0,$.jsx)(`span`,{style:{color:e.i?e.b||`var(--terminal-bg)`:e.f,background:e.i?e.f||`var(--ink)`:e.b,opacity:e.d?.6:void 0,fontWeight:e.o?600:void 0},children:e.t},t))},t)),Kh=new Set([`zsh`,`bash`,`sh`,`fish`,`dash`,`ksh`,`tcsh`,`nu`,`xonsh`,`login`]),qh=e=>{let t=(e.foregroundProcess||``).trim();return t&&!Kh.has(t.toLowerCase())?t:``},Jh=5e3,Yh=({wsBase:e,room:t,userName:n,theme:r,live:i,claudeApp:a,claimSize:o,activeCols:s,activeRows:c,onFullscreen:l,onUnfocus:u,onNotice:d})=>{let f=(0,_.useRef)(null),p=(0,_.useRef)(null),m=(0,_.useRef)(null),h=(0,_.useRef)(()=>{}),g=(0,_.useRef)(null),v=(0,_.useRef)(!1),[y,b]=(0,_.useState)(null),[ee,S]=(0,_.useState)(null),C=(0,_.useRef)(null),w=()=>Bm(P.current,p.current);C.current||=zm({send:e=>g.current?.(e),notify:e=>se.current?.(e),setOverlay:S,eligible:()=>w()});let[te,T]=(0,_.useState)(null),[E,ne]=(0,_.useState)(null),re=(0,_.useRef)(null),D=(0,_.useRef)(null),O=(0,_.useRef)(null),k=(0,_.useRef)(-1),A=(e,t=0)=>{let n=p.current;if(!n)return;if(!e){n.clearSelection(),k.current=-1,T(t=>t&&{...t,query:e,index:0,total:0});return}let r=Im(n,e),i=Lm(n,r,t===0?r.length-1:k.current+t,e.length);k.current=i,T({query:e,index:i+1,total:r.length})},j=()=>{T(null),k.current=-1,p.current?.clearSelection(),O.current?.blur(),window.setTimeout(()=>{Dh()&&p.current?.focus()},0)},M=(0,_.useRef)(null),[N,ie]=(0,_.useState)([]),[ae,oe]=(0,_.useState)(null),se=(0,_.useRef)(d);se.current=d;let P=(0,_.useRef)(a);P.current=a;let F=(0,_.useRef)(i);F.current=i;let I=(0,_.useRef)(l);I.current=l;let ce=(0,_.useRef)(u);ce.current=u,(0,_.useEffect)(()=>{let e=f.current;if(!e)return;let t=getComputedStyle(document.documentElement).getPropertyValue(`--font-terminal`).trim()||`monospace`,n=new nc({cols:s&&s>1?s:80,rows:c&&c>1?c:24,scrollback:2e3,scrollSensitivity:4,fastScrollSensitivity:12,fontSize:jh,lineHeight:1.3,fontFamily:t,cursorBlink:!1,disableStdin:!0,theme:r}),i=new x;n.loadAddon(i),n.open(e),p.current=n,m.current=i;let a=e.querySelector(`.xterm`),o=()=>{let t=e.querySelector(`.xterm-screen`),n=p.current;if(!a||!t||!n)return;let r=e.clientWidth,i=e.clientHeight;if(r<=0||i<=0)return;let o=t.offsetWidth,s=t.offsetHeight;if(o<=0||s<=0)return;let c=n.options.fontSize||jh,l=Hh(r);if(Math.abs(l-c)>=.25){n.options.fontSize=l;let e=n;typeof e.clearTextureAtlas==`function`&&e.clearTextureAtlas(),requestAnimationFrame(()=>h.current());return}a.style.transform=``,t.style.transform=``,a.style.transformOrigin=`bottom left`;let u=e.getBoundingClientRect(),d=t.getBoundingClientRect(),f=Math.max(0,Math.round(d.width-u.width)),m=Math.max(0,Math.round(d.height-u.height)),g=Math.round(u.bottom-d.bottom),_=D.current,v=_?Math.max(-f,Math.min(0,_.x)):0,y=_?Math.max(g,Math.min(0,_.y)):g;_&&(D.current={x:v,y}),(v!==0||y!==0)&&(a.style.transform=`translate(${v}px, ${y}px)`);let b=f>1||m>1?{x:f,y:m,cols:n.cols,rows:n.rows}:null,x=re.current;!b&&!x||b&&x&&b.x===x.x&&b.y===x.y&&b.cols===x.cols&&b.rows===x.rows||(re.current=b,ne(b))};h.current=o;let l=typeof ResizeObserver<`u`?new ResizeObserver(o):null;l?.observe(e);let u=e.querySelector(`.xterm-screen`);u?l?.observe(u):a&&l?.observe(a),window.setTimeout(o,30),document.fonts?.ready?.then(()=>o()).catch(()=>{}),n.attachCustomKeyEventHandler(e=>{if(!F.current)return!1;{let t=C.current?.handleKey(e);if(t!==void 0)return t}return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`?(e.type===`keydown`&&(T(e=>e??{query:``,index:0,total:0}),window.setTimeout(()=>O.current?.focus(),0)),!1):e.key===`Enter`&&e.shiftKey&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&(v.current||w())?(e.type===`keydown`&&g.current?.(`\x1B[13;2u`),!1):(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key===`Enter`?(e.type===`keydown`&&I.current(),!1):(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key===`.`?(e.type===`keydown`&&ce.current(),!1):!0});let d=n.onData(e=>g.current?.(e)),_=null,y=()=>{let t=e.querySelector(`.xterm-screen`);if(!t)return null;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{overflowX:Math.max(0,r.width-n.width),overflowY:Math.max(0,r.height-n.height),autoY:Math.round(n.bottom-r.bottom)}},b=t=>{if(!t.altKey||t.button!==0)return;let n=y();if(!n||n.overflowX<1&&n.overflowY<1)return;let r=D.current||{x:0,y:n.autoY};D.current=r,_={sx:t.clientX,sy:t.clientY,ox:r.x,oy:r.y};try{e.setPointerCapture(t.pointerId)}catch{}t.preventDefault(),t.stopPropagation()},ee=e=>{_&&(D.current={x:_.ox+(e.clientX-_.sx),y:_.oy+(e.clientY-_.sy)},h.current(),e.preventDefault())},S=t=>{if(_){_=null;try{e.releasePointerCapture(t.pointerId)}catch{}}},te=e=>{if(Math.abs(e.deltaX)<=Math.abs(e.deltaY))return;let t=y();if(!t||t.overflowX<1)return;let n=D.current||{x:0,y:t.autoY};D.current={x:n.x-e.deltaX,y:n.y},h.current(),e.preventDefault(),e.stopPropagation()};e.addEventListener(`wheel`,te,{capture:!0,passive:!1}),e.addEventListener(`pointerdown`,b,!0),e.addEventListener(`pointermove`,ee,!0),e.addEventListener(`pointerup`,S,!0),e.addEventListener(`pointercancel`,S,!0);let E=Pm(e,()=>p.current,{linesPerNotch:4,lineHeightPx:()=>Math.max(1,n._core?._renderService?.dimensions?.css?.cell?.height||jh*1.3)});return()=>{e.removeEventListener(`wheel`,te,{capture:!0}),e.removeEventListener(`pointerdown`,b,!0),e.removeEventListener(`pointermove`,ee,!0),e.removeEventListener(`pointerup`,S,!0),e.removeEventListener(`pointercancel`,S,!0),E(),l?.disconnect(),d.dispose(),n.dispose(),p.current=null,m.current=null}},[t,r]);let le=(0,_.useRef)(null),ue=r=>{if(!o)return;let i=m.current,a=f.current;if(!i||!a||a.clientWidth<60||a.clientHeight<40)return;let s=i.proposeDimensions();if(!s?.cols||!s?.rows||s.cols<20||s.rows<5)return;let c=le.current;if(c&&c.cols===s.cols&&c.rows===s.rows&&performance.now()-c.at<1500)return;let l=p.current;if(l){let e=Math.abs(l.cols-s.cols)<=Math.max(3,Math.round(s.cols*.15)),t=Math.abs(l.rows-s.rows)<=Math.max(2,Math.round(s.rows*.15));if(e&&t){le.current={cols:s.cols,rows:s.rows,at:performance.now()};return}}le.current={cols:s.cols,rows:s.rows,at:performance.now()};let u=e.includes(`?`)?`&`:`?`,d=new WebSocket(e+u+`room=`+encodeURIComponent(t)+`&name=`+encodeURIComponent((n||`user`)+` (wall)`)+`&replay=0&cols=`+s.cols+`&rows=`+s.rows);d.onopen=()=>{try{d.send(JSON.stringify({type:`resize`,cols:s.cols,rows:s.rows,claim:`attach`,user:!0}))}catch{}let e=!1,t=()=>{if(!e){e=!0;try{d.close()}catch{}r?.()}};d.onmessage=t,window.setTimeout(t,300)},d.onerror=()=>{try{d.close()}catch{}}},de=(0,_.useRef)(ue);return de.current=ue,(0,_.useEffect)(()=>{if(i)return;let e=!1,n=async()=>{if(!(e||document.hidden))try{let n=await fetch(`/api/sessions/screen?name=`+encodeURIComponent(t));if(!n.ok)return;let r=await n.json(),i=p.current;if(e||!i||typeof r.data!=`string`)return;Number.isInteger(r.cols)&&Number.isInteger(r.rows)&&(i.cols!==r.cols||i.rows!==r.rows)&&(i.resize(r.cols,r.rows),window.setTimeout(()=>h.current(),30)),i.write(`\x1Bc`+r.data,()=>{let e=p.current;e&&(e.scrollToBottom(),e.refresh(0,e.rows-1),h.current())})}catch{}},r=t=>{if(e)return;let i=le.current,a=p.current;!i||!a||a.cols===i.cols&&a.rows===i.rows||(n(),t<5&&window.setTimeout(()=>r(t+1),200+t*250))};de.current(()=>{r(0)}),n();let a=window.setInterval(n,Jh),o=0,s=typeof ResizeObserver<`u`?new ResizeObserver(()=>{window.clearTimeout(o),o=window.setTimeout(()=>{e||de.current(()=>{r(0)})},350)}):null;return f.current&&s?.observe(f.current),()=>{e=!0,window.clearInterval(a),window.clearTimeout(o),s?.disconnect()}},[i,t]),(0,_.useEffect)(()=>{if(!i)return;let r=p.current,a=f.current;if(!r||!a)return;r.options.disableStdin=!1,r.options.cursorBlink=!0;let o=null,s=!0,c=()=>{if(!(!s||o))try{o=new Lf,o.onContextLoss(()=>{o?.dispose(),o=null}),r.loadAddon(o),r.refresh(0,r.rows-1)}catch{try{o?.dispose()}catch{}o=null,s=!1}};b(`live`);let l=e.includes(`?`)?`&`:`?`,u=()=>e+l+`room=`+encodeURIComponent(t)+`&name=`+encodeURIComponent(n||`user`)+`&replay=65536&nudge=0&cols=`+r.cols+`&rows=`+r.rows,d=null,m=!1,_=0,y=0,x=[],ee=()=>{if(m)return;b(`down`),window.clearTimeout(_);let e=Math.min(1e3*2**y,15e3);y+=1,_=window.setTimeout(()=>S(),e)},S=()=>{if(m)return;if(window.clearTimeout(_),d)try{d.close()}catch{}let e=new WebSocket(u());d=e,e.onopen=()=>{if(m||d!==e)return;y=0,b(`live`),window.setTimeout(()=>h.current(),30);let t=Date.now()-15e3;for(let n of x)n.at>=t&&e.send(JSON.stringify({type:`input`,data:n.data}));x.length=0},e.onmessage=e=>{try{let t=JSON.parse(String(e.data));if(t.type===`snapshot`){let e=(t.mouseReporting?`\x1B[?1002h`+(t.mouseSgr?`\x1B[?1006h`:``):``)+(t.cursorHidden?`\x1B[?25l`:``);r.write(`\x1Bc`+t.data+e,()=>{r.scrollToBottom(),r.refresh(0,r.rows-1),h.current(),requestAnimationFrame(c)}),v.current=typeof t.keyboardEnhanced==`boolean`?t.keyboardEnhanced:Um(String(t.data||``),!1)}else if(t.type===`output`)r.write(t.data),v.current=Um(String(t.data||``),v.current);else if(t.type===`active_size`)(t.cols!==r.cols||t.rows!==r.rows)&&(r.resize(t.cols,t.rows),window.setTimeout(()=>h.current(),30));else if(t.type===`hello`)M.current=String(t.clientId||``);else if(t.type===`presence`&&Array.isArray(t.clients)){let e=t.clients.filter(e=>String(e.id||``)!==M.current);ie(e.map(e=>({name:String(e.name||`viewer`)})));let n=e.find(e=>e.typing);oe(n?{name:String(n.name||`someone`),color:String(n.color||`#8b5cf6`)}:null)}}catch{}},e.onclose=()=>{m||d!==e||ee()},e.onerror=()=>{try{e.close()}catch{}}};S(),g.current=e=>{if(!d||d.readyState!==WebSocket.OPEN){x.push({data:e,at:Date.now()}),x.length>200&&x.shift(),b(`down`),(!d||d.readyState===WebSocket.CLOSING||d.readyState===WebSocket.CLOSED)&&(y=0,S());return}d.send(JSON.stringify({type:`input`,data:e}))};let w={hiddenAt:0},te=()=>{if(document.hidden){w.hiddenAt=Date.now();return}requestAnimationFrame(()=>{let e=p.current;if(e)try{e.refresh(0,e.rows-1)}catch{}});let e=w.hiddenAt?Date.now()-w.hiddenAt:0;w.hiddenAt=0,(!d||d.readyState!==WebSocket.OPEN||e>6e4)&&(y=0,S())};document.addEventListener(`visibilitychange`,te);let E=()=>{(!d||d.readyState===WebSocket.CLOSING||d.readyState===WebSocket.CLOSED)&&(y=0,S())};window.addEventListener(`focus`,E);let ne=window.setTimeout(()=>{Dh()&&r.focus()},50);return()=>{m=!0;try{o?.dispose()}catch{}o=null,window.clearTimeout(ne),window.clearTimeout(_),document.removeEventListener(`visibilitychange`,te),window.removeEventListener(`focus`,E);try{d?.close()}catch{}g.current=null,r.options.disableStdin=!0,r.options.cursorBlink=!1,b(null),ie([]),oe(null),C.current?.dispose(),T(null),k.current=-1,r.blur()}},[i,e,t,n]),(0,$.jsxs)(`div`,{className:`switcher-live-tile`+(i?` is-live`:``),style:{background:r?.background},onClick:i?e=>e.stopPropagation():void 0,onPointerDown:i?e=>e.stopPropagation():void 0,children:[(0,$.jsx)(`div`,{className:`switcher-focus-term`,ref:f}),ee!==null&&(0,$.jsxs)(`div`,{className:`voice-overlay`,"aria-hidden":`true`,children:[(0,$.jsx)(`span`,{className:`voice-dot`}),(0,$.jsx)(`span`,{className:ee?`voice-text`:`voice-text muted`,children:ee||`Listening… release Space to insert`})]}),i&&(0,$.jsxs)(`div`,{className:`switcher-live-chrome`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`span`,{className:`switcher-focus-label`+(y===`down`?` down`:``),children:y===`down`?`reconnecting…`:`live`}),ae&&(0,$.jsxs)(`span`,{className:`switcher-live-driver`,title:ae.name+` is typing in this session`,children:[(0,$.jsx)(`span`,{className:`driver-dot`,style:{background:ae.color}}),ae.name]}),N.length>0&&(0,$.jsxs)(`span`,{className:`switcher-live-viewers`,title:N.map(e=>e.name).join(`, `)+` also connected`,children:[(0,$.jsx)(Nh,{}),N.length,N.some(e=>/agent|hopa|\(pane\)/i.test(e.name))&&(0,$.jsx)(`b`,{className:`viewer-agent`,children:`AI`})]}),E&&(0,$.jsxs)(`button`,{type:`button`,className:`switcher-tile-offgrid`,title:`This session's terminal is ${E.cols}×${E.rows}, larger than the tile`+(ae?` — ${ae.name} is using it right now`:N.length?` — another client holds the size`:``)+`.
127
+ ⌥-drag to pan. Click to resize the session to fit this tile.`,onClick:e=>{e.stopPropagation(),D.current=null,de.current()},children:[(0,$.jsx)(`span`,{className:`offgrid-glyph`,"aria-hidden":`true`,children:`⤢`}),E.cols,`×`,E.rows]}),te&&(0,$.jsxs)(`span`,{className:`switcher-tile-find`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`input`,{ref:O,value:te.query,placeholder:`Find…`,onChange:e=>A(e.target.value),onKeyDown:e=>{e.stopPropagation(),e.key===`Escape`?(e.preventDefault(),j()):e.key===`Enter`&&(e.preventDefault(),A(te.query,e.shiftKey?-1:1))}}),(0,$.jsx)(`em`,{children:te.total>0?te.index+`/`+te.total:te.query?`0`:``}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Close find`,onClick:j,children:`✕`})]}),(0,$.jsx)(`button`,{type:`button`,title:`Full screen (⌘⏎)`,"aria-label":`Open session full screen`,onClick:l,children:`⛶`}),(0,$.jsx)(`button`,{type:`button`,title:`Unfocus`,"aria-label":`Unfocus tile`,onClick:u,children:`✕`})]})]})},Xh=({open:e,sessions:t,currentRoom:n,onClose:r,dismissable:i=!0,onSwitch:a,onRefresh:o,onNotice:s,tileWsBase:c,onFocusSession:l,folders:u=[],userName:d,terminalTheme:f,onOpenSettings:p,onToggleKeyboard:m,onFind:h})=>{let[g,v]=(0,_.useState)(()=>{try{return sessionStorage.getItem(`hay_switcher_filter`)||``}catch{return``}});(0,_.useEffect)(()=>{try{g?sessionStorage.setItem(`hay_switcher_filter`,g):sessionStorage.removeItem(`hay_switcher_filter`)}catch{}},[g]);let[y,b]=(0,_.useState)(`user`),[x,ee]=(0,_.useState)(()=>{let e=localStorage.getItem(`hay_tile_zoom`);if(e!==null&&/^\d+$/.test(e))return Math.min(Number(e),Sh.length-1);let t=localStorage.getItem(`hay_tile_size`);return t&&t in Eh?Eh[t]:Th}),S=(0,_.useRef)(null),C=(0,_.useRef)(!1);(0,_.useEffect)(()=>{let e=S.current;if(!e)return;let t=()=>{try{sessionStorage.setItem(`hay_switcher_scroll`,String(e.scrollTop))}catch{}};return e.addEventListener(`scroll`,t,{passive:!0}),()=>e.removeEventListener(`scroll`,t)},[e]),(0,_.useEffect)(()=>{if(!e||C.current)return;let t=0;try{t=Number(sessionStorage.getItem(`hay_switcher_scroll`)||0)}catch{}if(!t){C.current=!0;return}let n=0,r=()=>{let e=S.current;if(e){if(e.scrollHeight>e.clientHeight+t||n++>20){e.scrollTop=t,C.current=!0;return}requestAnimationFrame(r)}};requestAnimationFrame(r)},[e]);let[w,te]=(0,_.useState)(0);(0,_.useEffect)(()=>{if(!e)return;let t=S.current;if(!t)return;let n=()=>{let e=getComputedStyle(t),n=t.clientWidth-(parseFloat(e.paddingLeft)||0)-(parseFloat(e.paddingRight)||0);te(n>0?n:0)};if(n(),typeof ResizeObserver<`u`){let e=new ResizeObserver(n);return e.observe(t),()=>e.disconnect()}return window.addEventListener(`resize`,n),()=>window.removeEventListener(`resize`,n)},[e]);let T=(0,_.useMemo)(()=>{if(!w)return Sh.length-1;for(let e=0;e<Sh.length;e++)if(Math.floor((w+wh)/(Sh[e].min+wh))<=1)return e;return Sh.length-1},[w]),E=Math.min(x,T),ne=Sh[E],re=E>=Ch&&!!c,D=(0,_.useRef)(!1);(0,_.useEffect)(()=>{e&&(D.current=!1)},[e]);let O=e=>{let t=Math.max(0,Math.min(e,T));t!==E&&(t>=Ch&&E<Ch&&c&&!D.current&&(D.current=!0,s(`Tiles are interactive at this zoom — click one to type in it (⌘⏎ full screen, ⌘. release)`)),ee(t),localStorage.setItem(`hay_tile_zoom`,String(t)))},[k,A]=(0,_.useState)(()=>{let e=localStorage.getItem(`hay_sort_mode`);return e===`project`||e===`manual`?e:`recent`}),j=e=>{A(e),localStorage.setItem(`hay_sort_mode`,e),Ve.current=null},[M,N]=(0,_.useState)(()=>localStorage.getItem(`hay_project_compact`)===`1`),ie=e=>{N(e),localStorage.setItem(`hay_project_compact`,e?`1`:`0`)},[ae,oe]=(0,_.useState)(()=>{try{let e=JSON.parse(localStorage.getItem(`hay_manual_order_v1`)||`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}catch{return[]}}),se=e=>{oe(e);try{localStorage.setItem(`hay_manual_order_v1`,JSON.stringify(e))}catch{}},[P,F]=(0,_.useState)(null),[I,ce]=(0,_.useState)(null),[le,ue]=(0,_.useState)(null),de=e=>{e.target?.closest?.(`.switcher-card, .switcher-group-label, .switcher-top`)||(e.preventDefault(),ue({x:e.clientX,y:e.clientY,items:[{label:`New session`,onSelect:()=>Ee(!0)},...k===`manual`?[{label:`New folder`,onSelect:()=>{pe()}}]:[],{kind:`separator`},{label:`Sort by recent`,onSelect:()=>j(`recent`),disabled:k===`recent`},{label:`Group by project`,onSelect:()=>j(`project`),disabled:k===`project`},{label:`Manual order`,onSelect:()=>j(`manual`),disabled:k===`manual`},{kind:`separator`},{label:`Zoom in`,onSelect:()=>O(E+1),hint:`+`,disabled:E>=T},{label:`Zoom out`,onSelect:()=>O(E-1),hint:`−`,disabled:E<=0}]}))},L=(e,t)=>{e.preventDefault(),e.stopPropagation(),ue({x:e.clientX,y:e.clientY,items:[{label:`Rename folder…`,onSelect:()=>{me(t)}},{label:`Delete folder`,danger:!0,onSelect:()=>{he(t)}},{kind:`separator`},{label:`New folder`,onSelect:()=>{pe()}}]})},fe=async(e,t,n)=>{try{let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});return r.ok?(o(),!0):(s((await r.json().catch(()=>({}))).error||n),!1)}catch{return s(n),!1}},pe=async()=>{let e=window.prompt(`Folder name`)?.trim();e&&await fe(`/api/folders`,{name:e},`Could not create folder`)&&s(`Created ${e}`)},me=async e=>{let t=window.prompt(`Rename folder`,e.name)?.trim();!t||t===e.name||await fe(`/api/folders/rename`,{id:e.id,name:t},`Could not rename folder`)},he=async e=>{window.confirm(`Delete folder "${e.name}"? Its sessions move back to unfiled.`)&&await fe(`/api/folders/delete`,{id:e.id},`Could not delete folder`)},ge=async(e,t)=>{await fe(`/api/sessions/move`,{internalName:e,folderId:t},`Could not move session`)};(0,_.useEffect)(()=>{if(!P)return;let e=-1,t=0,n=t=>{e=t.clientY},r=()=>{let n=S.current;if(n&&e>=0){let t=n.getBoundingClientRect();e<t.top+110?n.scrollTop-=Math.ceil((t.top+110-e)/110*22):e>t.bottom-110&&(n.scrollTop+=Math.ceil((e-(t.bottom-110))/110*22))}t=requestAnimationFrame(r)};return window.addEventListener(`dragover`,n),t=requestAnimationFrame(r),()=>{window.removeEventListener(`dragover`,n),cancelAnimationFrame(t)}},[P]);let[_e,ve]=(0,_.useState)(null);(0,_.useEffect)(()=>{if(!_e)return;let e=()=>ve(null);return window.addEventListener(`pointerup`,e),window.addEventListener(`dragend`,e),()=>{window.removeEventListener(`pointerup`,e),window.removeEventListener(`dragend`,e)}},[_e]);let ye=(e,t)=>{if(!e||e===t)return;let n=Qe.current,r=ae.length?ae.slice():n.slice();for(let e of n)r.includes(e)||r.push(e);let i=r.indexOf(e),a=r.indexOf(t);i===-1||a===-1||i===a||(r.splice(i,1),r.splice(a,0,e),se(r))},[be,R]=(0,_.useState)(null),[xe,Se]=(0,_.useState)(()=>{try{return sessionStorage.getItem(`hay_switcher_focus`)}catch{return null}});(0,_.useEffect)(()=>{try{xe?sessionStorage.setItem(`hay_switcher_focus`,xe):sessionStorage.removeItem(`hay_switcher_focus`)}catch{}},[xe]),(0,_.useEffect)(()=>{e||Se(null)},[e]),(0,_.useEffect)(()=>{re||Se(null)},[re]);let[Ce,we]=(0,_.useState)(``),[Te,Ee]=(0,_.useState)(!1),[De,Oe]=(0,_.useState)(``),[ke,Ae]=(0,_.useState)(null),[,je]=(0,_.useState)(0),Me=(0,_.useRef)(null);if(!Me.current){let e=new Map;try{let t=JSON.parse(sessionStorage.getItem(`hop_preview_cache_v1`)||`[]`);for(let[n,r]of t)e.set(n,{text:r})}catch{}Me.current=e}let Ne=()=>{try{let e=Array.from(Me.current.entries()).map(([e,t])=>[e,t.text.length>4e3?t.text.slice(-4e3):t.text]);sessionStorage.setItem(`hop_preview_cache_v1`,JSON.stringify(e))}catch{}},Pe=(0,_.useRef)(null),Fe=(0,_.useRef)(!1),Ie=(0,_.useMemo)(()=>ph(t,y),[t,y]),Le=(0,_.useMemo)(()=>Ie.filter(e=>!e.parked),[Ie]),Re=(0,_.useMemo)(()=>Ie.filter(e=>e.parked),[Ie]),[ze,Be]=(0,_.useState)(!1),Ve=(0,_.useRef)(null);(0,_.useEffect)(()=>{e||(Ve.current=null)},[e]);let z=(0,_.useMemo)(()=>{let t=g.trim()?Ie:Le,r=_h(t,n,g,k,ae,u);if(!e||r.mode!==`tiers`&&r.mode!==`project`)return r;let i=Ve.current;if(!i||i.mode!==r.mode)return i=r.mode===`tiers`?{mode:`tiers`,hero:r.hero.map(Oh),groups:r.groups.map(e=>({label:e.label,rows:e.rows.map(Oh)}))}:{mode:`project`,hero:[],groups:r.groups.map(e=>({label:e.label,rows:e.rows.map(Oh)}))},Ve.current=i,r;let a=new Map(t.map(e=>[Oh(e),e])),o=new Set([...i.hero,...i.groups.flatMap(e=>e.rows)]),s=t.filter(e=>!o.has(Oh(e))),c=e=>e.map(e=>a.get(e)).filter(e=>!!e);if(r.mode===`tiers`)return{mode:`tiers`,hero:[...c(i.hero),...s],groups:i.groups.map(e=>({label:e.label,rows:c(e.rows)})).filter(e=>e.rows.length>0),currentInHero:r.currentInHero};let l=i.groups.map(e=>({label:e.label,rows:c(e.rows)}));for(let e of s){let t=e.type===`port`?`Ports`:dh(e.cwd),n=l.find(e=>e.label===t);n?n.rows.push(e):l.push({label:t,rows:[e]})}return{mode:`project`,groups:l.filter(e=>e.rows.length>0)}},[e,Ie,Le,n,g,k,ae,y]),He=(0,_.useRef)(null),[Ue,We]=(0,_.useState)(0),Ge=typeof window<`u`&&!!window.matchMedia?.(`(pointer: fine)`).matches,[Ke,qe]=(0,_.useState)([]);(0,_.useEffect)(()=>{let t=g.trim();if(!e||t.length<3){qe([]);return}let n=!1,r=window.setTimeout(async()=>{try{let e=await(await fetch(`/api/sessions/search?q=${encodeURIComponent(t)}`)).json();if(n)return;let r=new Map(Ie.map(e=>[e.internalName||e.name,e]));qe((Array.isArray(e?.matches)?e.matches:[]).map(e=>{let t=r.get(e.internalName||``)||r.get(e.name||``);return t?{session:t,snippet:e.snippet||``}:null}).filter(Boolean))}catch{n||qe([])}},250);return()=>{n=!0,window.clearTimeout(r)}},[e,g,Ie]);let Je=(0,_.useMemo)(()=>{if(!g.trim())return[];let e=new Set;return z.mode===`filter`?z.rows.forEach(t=>e.add(Oh(t))):z.mode===`manual`?(z.rows.forEach(t=>e.add(Oh(t))),z.folders.forEach(t=>t.rows.forEach(t=>e.add(Oh(t))))):(z.mode===`project`||z.hero.forEach(t=>e.add(Oh(t))),z.groups.forEach(t=>t.rows.forEach(t=>e.add(Oh(t))))),Ke.filter(t=>!e.has(Oh(t.session)))},[z,Ke,g]),Ye=(0,_.useMemo)(()=>z.mode===`filter`?[...z.rows,...Je.map(e=>e.session)]:z.mode===`manual`?[...z.folders.flatMap(e=>e.rows),...z.rows,...Je.map(e=>e.session)]:z.mode===`project`?z.groups.flatMap(e=>e.rows):[...z.hero,...z.groups.flatMap(e=>e.rows)],[z,Je]),Xe=(0,_.useMemo)(()=>{let e=new Map;return Ye.forEach((t,n)=>e.set(Oh(t),n)),e},[Ye]),Ze=(0,_.useRef)(!1);(0,_.useEffect)(()=>{e||(Ze.current=!1)},[e]),(0,_.useEffect)(()=>{if(!e||xe||!n||Ze.current||g)return;let t=Ye.find(e=>(e.internalName||e.name)===n||e.name===n);if(!t)return;Ze.current=!0;let r=Oh(t);Se(r);let i=Xe.get(r);typeof i==`number`&&(We(i),requestAnimationFrame(()=>{document.querySelector(`[data-nav-index="${i}"]`)?.scrollIntoView({block:`center`})}))},[e,n,Ye,Xe,g,xe]);let Qe=(0,_.useRef)([]);{let e=_h(Le,n,``,`manual`,ae,u);Qe.current=e.mode===`manual`?[...e.folders.flatMap(e=>e.rows),...e.rows].map(Oh):[]}let $e=(0,_.useRef)(Ye);$e.current=Ye,(0,_.useEffect)(()=>{if(!e)return;let t=Ye.findIndex(e=>n!==null&&(e.internalName===n||e.name===n));We(g?0:Math.max(0,t)),document.querySelector(`.switcher-scroll`)?.scrollTo({top:0})},[e,g,y]),(0,_.useEffect)(()=>{We(e=>Math.min(e,Math.max(0,Ye.length-1)))},[Ye.length]),(0,_.useEffect)(()=>{if(!e||!Ge)return;let t=window.setTimeout(()=>He.current?.focus(),40);return()=>window.clearTimeout(t)},[e,Ge]);let B=(0,_.useRef)((()=>{try{return sessionStorage.getItem(`hay_switcher_filter`)||``}catch{return``}})()),et=(0,_.useRef)(!1);(0,_.useLayoutEffect)(()=>{if(e){if(!et.current&&(et.current=!0,B.current)){R(null),Ee(!1),Oe(``);return}b(`user`),v(``),R(null),Ee(!1),Oe(``)}},[e]),(0,_.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>je(e=>e+1),1e4);return()=>window.clearInterval(t)},[e]),(0,_.useEffect)(()=>{if(!e)return;let t=e=>{document.activeElement?.closest?.(`.switcher-live-tile, .switcher-focus-tile`)||e.key===`Escape`&&(e.preventDefault(),be?R(null):xe?Se(null):i&&r())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,be,xe]);let tt=(0,_.useRef)(0);(0,_.useEffect)(()=>{if(!e)return;let t=!1,n=new Set(z.mode===`tiers`?z.hero.map(Oh):z.mode===`filter`?[...z.rows.map(Oh),...Ke.map(e=>Oh(e.session))]:[]),r=new Set,i=(z.mode===`tiers`?[...z.hero,...z.groups.flatMap(e=>e.rows)]:z.mode===`project`?z.groups.flatMap(e=>e.rows):z.mode===`filter`?[...z.rows,...Ke.map(e=>e.session)]:z.rows).filter(e=>{if(e.type===`port`)return!1;let t=Oh(e);return r.has(t)?!1:(r.add(t),!0)}),a=async()=>{if(t||document.hidden||i.length===0)return;let e=Date.now()-tt.current>15e3,r=i.filter(t=>n.has(Oh(t))||e);await Promise.all(r.map(async e=>{let n=Oh(e);try{let e=await fetch(`/api/sessions/preview?name=${encodeURIComponent(n)}`);if(!e.ok)return;let r=await e.json(),i=typeof r.text==`string`?r.text.replace(/\s+$/,``):``;!t&&i.trim().length>0&&Me.current.set(n,{text:i,color:Array.isArray(r.color)?r.color:null,cols:Number.isInteger(r.cols)?r.cols:void 0,rows:Number.isInteger(r.rows)?r.rows:void 0})}catch{}})),!t&&(e&&(tt.current=Date.now()),Ne(),je(e=>e+1))};a();let o=window.setInterval(a,bh);return()=>{t=!0,window.clearInterval(o)}},[e,z,Ke]);let nt=(e,t)=>{if(e.pointerType===`mouse`&&e.button!==0)return;rt();let n=e.clientX,r=e.clientY,i=window.setTimeout(()=>{Pe.current=null,Fe.current=!0,R({session:t,mode:`menu`,anchor:{x:n,y:r}})},yh);Pe.current={timer:i,startX:n,startY:r}},rt=()=>{Pe.current&&=(window.clearTimeout(Pe.current.timer),null)},it=e=>{let t=Pe.current;t&&(Math.abs(e.clientX-t.startX)>10||Math.abs(e.clientY-t.startY)>10)&&rt()},at=e=>{let t=Oh(e);He.current?.blur(),Se(t),l?.(e);let n=Ye.findIndex(e=>Oh(e)===t);n>=0&&We(n)},ot=e=>re&&e.active&&e.type!==`port`,st=e=>{if(He.current?.blur(),rt(),Fe.current){Fe.current=!1;return}if(n!==null&&(e.internalName===n||e.name===n)){r();return}if(e.parked&&fetch(`/api/sessions/park`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:Oh(e),parked:!1})}).catch(()=>{}),e.type!==`port`&&!e.active&&re&&c){let t=Oh(e);try{let e=c.includes(`?`)?`&`:`?`,n=new WebSocket(c+e+`room=`+encodeURIComponent(t)+`&name=`+encodeURIComponent((d||`user`)+` (start)`)+`&replay=0&nudge=0&cols=80&rows=24`);n.onopen=()=>{window.setTimeout(()=>{try{n.close()}catch{}},400)},n.onerror=()=>{try{n.close()}catch{}}}catch{}s(`Starting `+(e.displayName||e.name)+`…`),Se(t),l?.(e),o();return}a(e)};(0,_.useEffect)(()=>{if(!e)return;let t=e=>{if(!(be||Te)){if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`){e.preventDefault(),Se(null),He.current?.focus(),We(-1);return}if(!document.activeElement?.closest?.(`.switcher-live-tile, .switcher-focus-tile`)){if(e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey){let t=Ye[Ue];t&&(e.preventDefault(),He.current?.blur(),a(t));return}if(e.altKey&&!e.metaKey&&!e.ctrlKey&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&k===`manual`){let t=Ye[Ue],n=Ye[Ue+(e.key===`ArrowUp`?-1:1)];t&&n&&(e.preventDefault(),ye(Oh(t),Oh(n)),We(t=>t+(e.key===`ArrowUp`?-1:1)));return}if(!(e.metaKey||e.ctrlKey||e.altKey)){if(document.activeElement!==He.current){if(e.key===`+`||e.key===`=`){e.preventDefault(),O(E+1);return}if(e.key===`-`){e.preventDefault(),O(E-1);return}}if(e.key===`ArrowDown`||e.key===`ArrowUp`||e.key===`ArrowLeft`||e.key===`ArrowRight`){if((e.key===`ArrowLeft`||e.key===`ArrowRight`)&&document.activeElement===He.current&&(He.current?.value||``).length>0)return;e.preventDefault(),We(t=>{if(t===-1)return e.key===`ArrowDown`?(requestAnimationFrame(()=>{document.querySelector(`[data-nav-index="0"]`)?.scrollIntoView({block:`nearest`})}),0):-1;let n=Array.from(document.querySelectorAll(`[data-nav-index]`));if(n.length===0)return 0;let r=(n.find(e=>Number(e.dataset.navIndex)===t)??n[0]).getBoundingClientRect(),i=r.left+r.width/2,a=r.top+r.height/2,o=null;for(let r of n){let n=Number(r.dataset.navIndex);if(n===t||Number.isNaN(n))continue;let s=r.getBoundingClientRect(),c=s.left+s.width/2-i,l=s.top+s.height/2-a,u,d;if(e.key===`ArrowDown`?(u=l,d=Math.abs(c)):e.key===`ArrowUp`?(u=-l,d=Math.abs(c)):e.key===`ArrowRight`?(u=c,d=Math.abs(l)):(u=-c,d=Math.abs(l)),u<4)continue;let f=u+d*3;(!o||f<o.score)&&(o={idx:n,score:f})}if(!o&&e.key===`ArrowUp`)return requestAnimationFrame(()=>He.current?.focus()),-1;let s=o?o.idx:t;return requestAnimationFrame(()=>{document.querySelector(`[data-nav-index="${s}"]`)?.scrollIntoView({block:`nearest`})}),s});return}if(e.key===`Enter`&&!e.shiftKey){let t=Ye[Ue];t&&(e.preventDefault(),ot(t)?at(t):st(t));return}document.activeElement!==He.current&&(e.key.length===1||e.key===`Backspace`)&&(e.preventDefault(),Se(null),He.current?.focus(),v(t=>e.key===`Backspace`?t.slice(0,-1):t+e.key))}}}};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,be,Te,Ye,Ue,E,T,re]);let ct=(e,t)=>{rt(),R({session:e,mode:`menu`,anchor:t??{x:window.innerWidth/2+132,y:window.innerHeight/3}})},lt=async e=>{if(e.preventDefault(),!be)return;let t=Ce.trim(),n=be.session.displayName||be.session.name;if(!t||t===n){R(null);return}if(!/^[a-zA-Z0-9_-]+$/.test(t)){s(`Only letters, numbers, - and _ allowed`);return}try{let e=await fetch(`/api/sessions/rename`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({oldName:n,newName:t,internalName:Oh(be.session)})});if(!e.ok){s((await e.json().catch(()=>({}))).error||`Rename failed`);return}s(`Renamed to ${t}`),R(null),o()}catch{s(`Rename failed`)}},ut=async()=>{if(!be)return;let e=Oh(be.session),t=be.session.agentPermitted!==!0;try{if(!(await fetch(`/api/sessions/agent-permission`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:e,allowed:t})})).ok){s(`Failed to update agent access`);return}s(t?`Agent access enabled`:`Agent access disabled`),R(null),o()}catch{s(`Failed to update agent access`)}},dt=async e=>{let t=e.displayName||e.name;if(window.confirm(`Kill session "${t}" for all participants? Its running process is terminated.`))try{if(!(await fetch(`/api/sessions/delete`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:Oh(e)})})).ok){s(`Failed to kill session`);return}s(`Killed ${t}`),R(null),o()}catch{s(`Failed to kill session`)}},ft=async()=>{if(!be)return;let e=be.session.createdBy===`agent`?`user`:`agent`;try{if(!(await fetch(`/api/sessions/origin`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:Oh(be.session),createdBy:e})})).ok){s(`Failed to change session origin`);return}s(e===`user`?`Moved to user sessions`:`Moved to agent sessions`),R(null),o()}catch{s(`Failed to change session origin`)}},pt=async()=>{be&&await dt(be.session)},V=async()=>{if(!be)return;let e=be.session.parked!==!0;try{if(!(await fetch(`/api/sessions/park`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:Oh(be.session),parked:e})})).ok){s(`Failed to update park state`);return}s(e?`Parked — find it under “parked” at the bottom`:`Back on the wall`),R(null),o()}catch{s(`Failed to update park state`)}},mt=async()=>{if(be)try{let e=await fetch(`/api/sessions/archive`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:Oh(be.session)})});if(!e.ok){s((await e.json().catch(()=>({}))).error||`Failed to stop session`);return}s(`Stopped & parked — opening it later resumes the conversation`),R(null),o()}catch{s(`Failed to stop session`)}},ht=(e,t)=>{we(e.displayName||e.name),R({session:e,mode:`rename`,anchor:t??{x:window.innerWidth/2+132,y:window.innerHeight/3}})},gt=async e=>{e.preventDefault();let t=De.trim();if(t){if(!/^[a-zA-Z0-9_-]+$/.test(t)){s(`Only letters, numbers, - and _ allowed`);return}try{let e=await fetch(`/api/sessions`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,type:`terminal`,port:null})}),n=await e.json().catch(()=>({}));if(!e.ok||!n.name){let r=e.status===409?Le.find(e=>(e.displayName||e.name).toLowerCase()===t.toLowerCase()):null;if(r){let e=u.find(e=>e.id===r.folderId);s(`"${r.displayName||r.name}" already exists${e?` in ${e.name}`:``} — showing it`),Ee(!1),Oe(``),Ae(null);let t=Oh(r);Se(t);let n=Xe.get(t);typeof n==`number`&&(We(n),requestAnimationFrame(()=>{document.querySelector(`[data-nav-index="${n}"]`)?.scrollIntoView({block:`center`})}));return}s(n.error||`Failed to create session`);return}Ee(!1),Oe(``),ke&&(await fetch(`/api/sessions/move`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:n.name,folderId:ke.id})}).catch(()=>{}),Ae(null)),l?.({name:n.name,displayName:n.name,active:!1,starting:!0,internalName:n.name}),Se(n.name),o()}catch{s(`Failed to create session`)}}};if(!e)return null;let _t=Date.now(),vt=e=>(e.bellUnseen||e.unread)&&(0,$.jsx)(`span`,{className:`attention-dot ${e.bellUnseen?`bell`:`output`}`,title:e.bellUnseen?`Bell rung since last viewed`:`New output since last viewed`}),yt=e=>{let t=qh(e);return t?/^\d+\.\d+\.\d+$/.test(t)?`claude`:t:``},bt=e=>{let t=e.cwd||``;return t?t.replace(/^\/(?:Users|home)\/[^/]+(?=\/|$)/,`~`).replace(/^\/root(?=\/|$)/,`~`):``},xt=e=>{let t=[],n=vh(e.lastActivityAt||0,_t);n&&t.push(n);let r=yt(e);return r&&t.push(r),t.join(` · `)},St=e=>n!==null&&(e.internalName===n||e.name===n),Ct=e=>({onPointerDown:t=>nt(t,e),onPointerUp:rt,onPointerLeave:rt,onPointerMove:it,onContextMenu:t=>{t.preventDefault(),Fe.current=!1,ct(e,{x:t.clientX,y:t.clientY})}}),wt=(e,t)=>{let n=Oh(e),r=Me.current.get(n),i=St(e),o=Xe.get(n)===Ue,l=!i&&_t-(e.lastActivityAt||0)<12e3,u=xe===n,p=k===`manual`&&(!u||_e===n);return(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"data-nav-index":Xe.get(n),className:`switcher-card${i?` current`:``}${l?` active-now`:``}${o?` kbd-selected`:``}${xe===n?` focused`:``}${P===n?` dragging`:``}${p?` draggable`:``}`,draggable:p,onDragStart:p?e=>{F(n),e.dataTransfer.effectAllowed=`move`}:void 0,onDragEnter:p?()=>{P&&P!==n&&ye(P,n)}:void 0,onDragOver:p?e=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`}:void 0,onDrop:p?e=>{e.preventDefault(),Fe.current=!0,F(null)}:void 0,onDragEnd:p?()=>{Fe.current=!0,F(null),window.setTimeout(()=>{Fe.current=!1},250)}:void 0,onClick:t=>{if(Fe.current){Fe.current=!1;return}t.target?.closest?.(`button, a, input`)||(ot(e)?at(e):st(e))},onKeyDown:t=>{if(t.key===`Enter`&&!t.shiftKey){if(t.metaKey||t.ctrlKey){a(e);return}ot(e)?at(e):st(e)}},...Ct(e),children:[(0,$.jsxs)(`div`,{className:`switcher-card-head${k===`manual`&&u?` drag-handle`:``}`,onPointerDown:k===`manual`&&u?()=>ve(n):void 0,children:[vt(e),(0,$.jsx)(`span`,{className:`switcher-card-name`,children:e.displayName}),i&&(0,$.jsx)(`span`,{className:`switcher-chip current`,children:`CURRENT`}),y===`all`&&e.createdBy===`agent`&&(0,$.jsxs)(`span`,{className:`switcher-chip agent`+(e.createdVia===`cli-agent-env`?` inferred`:``),title:e.createdVia===`mcp`?`Started by an agent over MCP`:e.createdVia===`hopa`?`Started by an agent via the hopa CLI`:e.createdVia===`cli-agent-env`?`Guessed from the hop CLI's environment (CLAUDECODE) — not a dedicated agent interface, so this label can be wrong`:`Marked as an agent session`,children:[`AGENT`,e.createdVia===`cli-agent-env`?`?`:``]}),!i&&e.starting&&!e.active&&(0,$.jsx)(`span`,{className:`switcher-chip starting`,children:`STARTING`}),Ah(r)&&(0,$.jsx)(`span`,{className:`switcher-chip waiting`,title:`Claude is asking how to resume this conversation — open it and choose`,children:`NEEDS YOU`}),Tt(e)]}),e.tagline&&(0,$.jsx)(`div`,{className:`switcher-card-tagline`,title:e.tagline,children:e.tagline}),re&&c&&e.active&&e.type!==`port`?(0,$.jsx)(`div`,{className:`switcher-preview switcher-preview-live`,children:(0,$.jsx)(Yh,{wsBase:c,room:n,userName:d||`user`,theme:f,live:xe===n,claudeApp:yt(e)===`claude`,claimSize:e.hasLocalCli!==!0,activeCols:r?.cols,activeRows:r?.rows,onFullscreen:()=>a(e),onUnfocus:()=>Se(null),onNotice:s})}):(0,$.jsx)(`pre`,{className:`switcher-preview`,"aria-hidden":`true`,children:r?.color?.length&&r.cols&&r.rows&&E>=Ch?(0,$.jsx)(Wh,{frame:r}):r?.color?.length?Gh(r.color):r?.text||` `}),t&&(0,$.jsx)(`div`,{className:`switcher-card-snippet`,title:t,children:t}),(0,$.jsxs)(`div`,{className:`switcher-card-meta`,children:[(0,$.jsx)(`span`,{className:`switcher-card-dir`,title:e.cwd||void 0,children:bt(e)?`\u200E${bt(e)}\u200E`:`\xA0`}),(0,$.jsx)(`span`,{className:`switcher-card-when`,children:xt(e)})]})]},n)},Tt=e=>(0,$.jsxs)(`span`,{className:`switcher-inline-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`switcher-icon-btn`,"aria-label":`Rename ${e.displayName}`,title:`Rename`,onClick:t=>{t.stopPropagation();let n=t.currentTarget.getBoundingClientRect();ht(e,{x:n.right,y:n.bottom})},onPointerDown:e=>e.stopPropagation(),children:(0,$.jsx)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,$.jsx)(`path`,{d:`M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z`})})}),(0,$.jsx)(`button`,{type:`button`,className:`switcher-icon-btn danger`,"aria-label":`Kill ${e.displayName}`,title:`Kill session`,onClick:t=>{t.stopPropagation(),dt(e)},onPointerDown:e=>e.stopPropagation(),children:(0,$.jsx)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,$.jsx)(`path`,{d:`M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6M10 11v6M14 11v6`})})}),(0,$.jsx)(`button`,{type:`button`,className:`switcher-icon-btn`,"aria-label":`More actions for ${e.displayName}`,title:`More`,onClick:t=>{t.stopPropagation();let n=t.currentTarget.getBoundingClientRect();ct(e,{x:n.right,y:n.bottom})},onPointerDown:e=>e.stopPropagation(),children:`⋯`})]}),Et=be?.session,Dt=Et?.agentPermitted===!0;return(0,$.jsxs)(`div`,{className:`switcher-overlay${ne.min<300?` tile-dense`:``}${ne.min<150?` tile-micro`:``}${i?``:` switcher-hub`}${i?` switcher-fullscreen`:``}`,style:{"--tile-min":`${ne.min}px`,"--tile-h":ne.h,"--tile-fs":ne.fs},role:`dialog`,"aria-label":`Sessions`,children:[(0,$.jsxs)(`div`,{className:`switcher-top`,children:[(0,$.jsxs)(`header`,{className:`switcher-header`,children:[(0,$.jsx)(`h2`,{children:`Sessions`}),(0,$.jsx)(`span`,{className:`switcher-count`,children:Ie.length}),y!==`agent`&&(0,$.jsxs)(`button`,{type:`button`,className:`switcher-new-top`,title:`New session`,"aria-label":`New session`,onClick:()=>Ee(!0),children:[`+`,(0,$.jsx)(`span`,{className:`switcher-new-label`,children:` New`})]}),(0,$.jsxs)(`div`,{className:`switcher-tilesize`,role:`group`,"aria-label":`Tile zoom`,children:[(0,$.jsx)(`button`,{type:`button`,"aria-label":`Smaller tiles`,title:`Smaller tiles (−)`,disabled:E<=0,onClick:()=>O(E-1),children:`−`}),(0,$.jsx)(`span`,{className:`switcher-zoom-readout`,"aria-hidden":`true`,children:E+1}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Bigger tiles`,title:E>=T?`Tiles already span the full width`:`Bigger tiles (+)`,disabled:E>=T,onClick:()=>O(E+1),children:`+`})]}),re&&(0,$.jsx)(`span`,{className:`switcher-chip live`,title:`Tiles are live terminals at this zoom — click one to type in it. ⌘⏎ opens it full screen, ⌘. releases it.`,children:`⌨ interactive`}),(0,$.jsx)(`span`,{className:`switcher-header-spacer`}),m&&(0,$.jsx)(`button`,{type:`button`,className:`switcher-action`,"aria-label":`Toggle keyboard`,title:`Toggle keyboard`,onClick:m,children:(0,$.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`rect`,{x:`2`,y:`4`,width:`20`,height:`14`,rx:`2`}),(0,$.jsx)(`path`,{d:`M6 8h.01M10 8h.01M14 8h.01M18 8h.01M6 12h.01M10 12h.01M14 12h.01M18 12h.01M8 16h8`})]})}),h&&(0,$.jsx)(`button`,{type:`button`,className:`switcher-action`,"aria-label":`Find in terminal`,title:`Find in terminal`,onClick:h,children:(0,$.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`circle`,{cx:`11`,cy:`11`,r:`7`}),(0,$.jsx)(`path`,{d:`M21 21l-4.3-4.3`})]})}),p&&(0,$.jsx)(`button`,{type:`button`,className:`switcher-action`,"aria-label":`Settings`,title:`Settings`,onClick:p,children:(0,$.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`circle`,{cx:`12`,cy:`12`,r:`3`}),(0,$.jsx)(`path`,{d:`M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.01a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51h.01a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.01a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z`})]})}),i&&(0,$.jsx)(`button`,{type:`button`,className:`switcher-close`,"aria-label":`Close switcher`,onClick:r,children:`✕`})]}),(0,$.jsxs)(`div`,{className:`switcher-filter-row`,children:[(0,$.jsx)(`div`,{className:`switcher-origin`,role:`group`,"aria-label":`Session origin`,children:[[`user`,`User`],[`agent`,`Agent`],[`all`,`All`]].map(([e,t])=>(0,$.jsx)(`button`,{type:`button`,className:y===e?`active`:``,"aria-pressed":y===e,onClick:()=>{b(e),Ee(!1),Ve.current=null},children:t},e))}),(0,$.jsx)(`div`,{className:`switcher-origin switcher-sort`,role:`group`,"aria-label":`Organize sessions by`,children:[[`recent`,`Recent`,`Most recently active first`],[`project`,`Project`,`Grouped by working directory`],[`manual`,`Manual`,`Your own drag order`]].map(([e,t,n])=>(0,$.jsx)(`button`,{type:`button`,className:k===e?`active`:``,"aria-pressed":k===e,title:n,onClick:()=>j(e),children:t},e))}),k===`project`&&(0,$.jsx)(`div`,{className:`switcher-origin switcher-density`,role:`group`,"aria-label":`Project view density`,children:[[!1,`Sections`,`A header per project`],[!0,`Compact`,`One continuous grid — the project is on each card`]].map(([e,t,n])=>(0,$.jsx)(`button`,{type:`button`,className:M===e?`active`:``,"aria-pressed":M===e,title:n,onClick:()=>ie(e),children:t},t))}),(0,$.jsx)(`input`,{ref:He,className:`switcher-filter${Ge||Ie.length>xh||g?``:` compact`}`,placeholder:`Filter…`,value:g,onChange:e=>{Se(null),v(e.target.value)},"aria-label":`Filter sessions`})]}),Te&&!ke&&(0,$.jsxs)(`form`,{className:`switcher-create-row inline-edit`,onSubmit:gt,children:[(0,$.jsx)(`input`,{placeholder:`session-name`,value:De,onChange:e=>Oe(e.target.value),maxLength:64,autoFocus:!0,"aria-label":`New session name`}),(0,$.jsx)(`button`,{type:`submit`,children:`Create`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{Ee(!1),Oe(``),Ae(null)},children:`✕`})]})]}),(0,$.jsxs)(`div`,{className:`switcher-scroll`,ref:S,onContextMenu:de,children:[z.mode===`filter`?(0,$.jsxs)($.Fragment,{children:[z.rows.length===0&&Je.length===0?(0,$.jsxs)(`div`,{className:`switcher-empty`,children:[`No sessions match “`,g.trim(),`”`]}):(0,$.jsx)(`div`,{className:`switcher-grid`,children:z.rows.map(e=>wt(e))}),Je.length>0&&(0,$.jsxs)(`section`,{className:`switcher-group`,children:[(0,$.jsx)(`h3`,{className:`switcher-group-label`,children:`found in terminal output`}),(0,$.jsx)(`div`,{className:`switcher-grid`,children:Je.map(({session:e,snippet:t})=>wt(e,t))})]})]}):z.mode===`project`?(0,$.jsxs)($.Fragment,{children:[y===`agent`&&Ie.length===0&&(0,$.jsx)(`div`,{className:`switcher-empty`,children:`No agent sessions`}),M?(0,$.jsx)(`div`,{className:`switcher-grid`,children:z.groups.flatMap(e=>e.rows).map(e=>wt(e))}):z.groups.map(e=>(0,$.jsxs)(`section`,{className:`switcher-group`,children:[(0,$.jsx)(`h3`,{className:`switcher-group-label`,children:e.label}),(0,$.jsx)(`div`,{className:`switcher-grid`,children:e.rows.map(e=>wt(e))})]},e.label))]}):z.mode===`manual`?(0,$.jsx)($.Fragment,{children:z.rows.length===0&&z.folders.every(e=>e.rows.length===0)?(0,$.jsx)(`div`,{className:`switcher-empty`,children:g.trim()?`No matches`:`No sessions`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{className:`switcher-hint`,children:[g.trim()?`Showing matches in your order — drag one next to another (or ⌥↑/⌥↓); the move applies to the full list`:`Drag tiles to reorder, or onto a folder to file them`,(0,$.jsx)(`button`,{type:`button`,className:`switcher-folder-new`,onClick:pe,children:`+ New folder`})]}),z.folders.map(({folder:e,rows:t})=>(0,$.jsxs)(`section`,{className:`switcher-group switcher-folder`+(I===e.id?` drop-target`:``),onDragOver:t=>{t.preventDefault(),ce(e.id)},onDragLeave:()=>ce(t=>t===e.id?null:t),onDrop:t=>{t.preventDefault(),ce(null),Fe.current=!0,P&&ge(P,e.id),F(null)},children:[(0,$.jsxs)(`h3`,{className:`switcher-group-label`,onContextMenu:t=>L(t,e),children:[e.name,(0,$.jsx)(`span`,{className:`switcher-folder-count`,children:t.length}),(0,$.jsx)(`button`,{type:`button`,className:`switcher-folder-add`,title:`New session in `+e.name,onClick:()=>{Ae(e),Ee(!0)},children:`+`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>me(e),title:`Rename folder`,children:`✎`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>he(e),title:`Delete folder`,children:`🗑`})]}),Te&&ke?.id===e.id&&(0,$.jsxs)(`form`,{className:`switcher-create-row inline-edit switcher-create-infolder`,onSubmit:gt,children:[(0,$.jsx)(`input`,{placeholder:`new session in `+e.name,value:De,onChange:e=>Oe(e.target.value),maxLength:64,autoFocus:!0,"aria-label":`New session name in `+e.name}),(0,$.jsx)(`button`,{type:`submit`,children:`Create`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{Ee(!1),Oe(``),Ae(null)},children:`✕`})]}),t.length===0?Te&&ke?.id===e.id?null:(0,$.jsx)(`p`,{className:`switcher-folder-empty`,children:`Drag a session here, or + to create one`}):(0,$.jsx)(`div`,{className:`switcher-grid`,children:t.map(e=>wt(e))})]},e.id)),z.folders.length>0&&z.rows.length>0&&(0,$.jsx)(`h3`,{className:`switcher-group-label switcher-unfiled`+(I===``?` drop-target`:``),onDragOver:e=>{e.preventDefault(),ce(``)},onDragLeave:()=>ce(e=>e===``?null:e),onDrop:e=>{e.preventDefault(),ce(null),Fe.current=!0,P&&ge(P,null),F(null)},children:`Unfiled`}),(0,$.jsx)(`div`,{className:`switcher-grid`,children:z.rows.map(e=>wt(e))})]})}):(0,$.jsxs)($.Fragment,{children:[y===`agent`&&Ie.length===0&&(0,$.jsx)(`div`,{className:`switcher-empty`,children:`No agent sessions`}),(0,$.jsxs)(`div`,{className:`switcher-grid`,children:[z.hero.map(e=>wt(e)),y!==`agent`&&!Te&&(0,$.jsxs)(`button`,{type:`button`,className:`switcher-card new`,onClick:()=>Ee(!0),children:[(0,$.jsx)(`span`,{className:`switcher-new-plus`,children:`+`}),(0,$.jsx)(`span`,{children:`New session`})]})]}),z.groups.map(e=>(0,$.jsxs)(`section`,{className:`switcher-group`,children:[e.label&&(0,$.jsx)(`h3`,{className:`switcher-group-label`,children:e.label}),(0,$.jsx)(`div`,{className:`switcher-grid`,children:e.rows.map(e=>wt(e))})]},e.label||`tail`))]}),z.mode!==`filter`&&Re.length>0&&(0,$.jsxs)(`section`,{className:`switcher-group switcher-parked`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`switcher-parked-toggle`,"aria-expanded":ze,onClick:()=>Be(e=>!e),children:[ze?`▾`:`▸`,` parked · `,Re.length]}),ze&&(0,$.jsx)(`div`,{className:`switcher-rows`,children:Re.map(e=>{let t=Oh(e);return(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,className:`switcher-row parked`,onClick:()=>st(e),onKeyDown:t=>{t.key===`Enter`&&!t.shiftKey&&st(e)},...Ct(e),children:[vt(e),(0,$.jsx)(`span`,{className:`switcher-row-name`,children:e.displayName}),(0,$.jsx)(`span`,{className:`switcher-chip`,children:e.active?`PARKED`:`STOPPED`}),e.tagline&&(0,$.jsx)(`span`,{className:`switcher-row-dir`,children:e.tagline}),(0,$.jsx)(`span`,{className:`switcher-row-meta`,children:xt(e)}),Tt(e)]},t)})})]})]}),be&&Et&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`switcher-sheet-backdrop`,onClick:()=>R(null)}),(0,$.jsxs)(`div`,{className:`switcher-sheet`,role:`menu`,"aria-label":`Actions for ${Et.displayName}`,style:(()=>{let e=be.mode===`rename`?140:340,t=Math.min(Math.max(8,be.anchor.x-264),window.innerWidth-264-8),n=be.anchor.y+8;return n+e>window.innerHeight-8&&(n=Math.max(8,be.anchor.y-e-8)),{left:t,top:n}})(),children:[(0,$.jsx)(`p`,{className:`switcher-sheet-title`,children:Et.displayName}),be.mode===`rename`?(0,$.jsxs)(`form`,{className:`inline-edit`,onSubmit:lt,children:[(0,$.jsx)(`input`,{value:Ce,onChange:e=>we(e.target.value),maxLength:64,autoFocus:!0,"aria-label":`New session name`}),(0,$.jsx)(`button`,{type:`submit`,children:`Save`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>R({session:Et,mode:`menu`,anchor:be.anchor}),children:`✕`})]}):(0,$.jsxs)($.Fragment,{children:[!St(Et)&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{R(null),a(Et)},children:`Open full screen`}),(0,$.jsx)(`button`,{type:`button`,onClick:async()=>{R(null),s(`Forking…`);try{let e=await fetch(`/api/sessions/fork`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({internalName:Oh(Et)})}),t=await e.json().catch(()=>({}));if(!e.ok){s(t.error||`Fork failed`);return}s(t.kind===`claude`?`Forked conversation → ${t.name}`:t.kind===`codex`?`${t.name} opened — pick the conversation to resume`:`Forked → ${t.name} (new shell, same directory)`),o()}catch{s(`Fork failed`)}},children:`Fork session`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{we(Et.displayName||Et.name),R({session:Et,mode:`rename`,anchor:be.anchor})},children:`Rename`}),Et.type!==`port`&&(0,$.jsx)(`button`,{type:`button`,onClick:ut,children:Dt?`Disable agent access`:`Enable agent access`}),Et.type!==`port`&&(0,$.jsx)(`button`,{type:`button`,onClick:ft,children:Et.createdBy===`agent`?`Move to user sessions`:`Move to agent sessions`}),Et.type!==`port`&&(0,$.jsx)(`button`,{type:`button`,onClick:V,children:Et.parked?`Unpark session`:`Park session`}),Et.type!==`port`&&Et.active&&(0,$.jsx)(`button`,{type:`button`,onClick:mt,children:`Stop & park (resumable)`}),(0,$.jsx)(`button`,{type:`button`,className:`danger`,onClick:pt,children:`Kill session`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>R(null),children:`Cancel`})]})]})]}),(0,$.jsx)(rh,{request:le,onClose:()=>ue(null)})]})},Zh=({sessionName:e,procLabel:t,wsUrl:n,userName:r,cols:i,rows:a,fontSize:o,theme:s,focused:c,onFocus:l,onClose:u,onPromote:d})=>{let f=(0,_.useRef)(null),p=(0,_.useRef)(null),m=(0,_.useRef)(null),h=(0,_.useRef)(null),[g,v]=(0,_.useState)(`connecting`),[y,b]=(0,_.useState)(1),[ee,S]=(0,_.useState)(!1),C=(0,_.useRef)({cols:i,rows:a}),w=(0,_.useRef)(c);w.current=c;let te=(0,_.useRef)(()=>{});return(0,_.useEffect)(()=>{if(!f.current)return;let t=new nc({cols:C.current.cols,rows:C.current.rows,fontSize:o,fontFamily:`ui-monospace, SFMono-Regular, Menlo, monospace`,theme:s,scrollback:2e3,convertEol:!1}),i=new x;t.loadAddon(i),t.open(f.current),m.current=t;let a=!0,c=null,l=0,u=()=>{let i=n.includes(`?`)?`&`:`?`,o=new WebSocket(`${n}${i}room=${encodeURIComponent(e)}&name=${encodeURIComponent(r+` (pane)`)}&cols=${C.current.cols}&rows=${C.current.rows}`);h.current=o,v(`connecting`),o.onopen=()=>v(`connected`),o.onmessage=e=>{let n=wm(String(e.data));if(n)if(n.type===`output`)t.write(n.data),!w.current&&n.data.trim()&&S(!0);else if(n.type===`snapshot`){t.reset();let e=``;n.alternateScreen&&(e+=`\x1B[?1049h`),e+=n.mouseReporting?`\x1B[?1002h`:`\x1B[?1000l\x1B[?1002l\x1B[?1003l`,e+=n.mouseSgr?`\x1B[?1006h`:`\x1B[?1006l`;let r=n.cursorHidden?`\x1B[?25l`:``;t.write(e+n.data+r,()=>t.scrollToBottom())}else n.type===`session_ended`?(a=!1,v(`ended`)):n.type===`active_size`&&n.cols>=2&&n.rows>=2&&!w.current&&(n.cols!==C.current.cols||n.rows!==C.current.rows)&&(C.current={cols:n.cols,rows:n.rows},t.resize(n.cols,n.rows),requestAnimationFrame(y))},o.onclose=()=>{a&&(v(`connecting`),l+=1,c=window.setTimeout(u,Math.min(1e3*2**l,15e3)))}};u();let d=t.onData(e=>{let t=h.current;t?.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:`input`,data:e}))}),g=()=>{let e=i.proposeDimensions();if(!e||!Number.isFinite(e.cols)||!Number.isFinite(e.rows))return;let n=Math.floor(e.cols),r=Math.floor(e.rows);if(!(n<20||n>320||r<6||r>120)){if(n!==C.current.cols||r!==C.current.rows){C.current={cols:n,rows:r},t.resize(n,r);let e=h.current;e?.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:`resize`,cols:n,rows:r}))}b(1)}},_=()=>{let e=p.current,t=f.current;if(!e||!t)return;let n=e.clientWidth-8,r=e.clientHeight-8,i=t.scrollWidth,a=t.scrollHeight;i>0&&a>0&&n>0&&r>0&&b(Math.min(n/i,r/a,1.4))},y=()=>w.current?g():_();te.current=y;let ee=new ResizeObserver(y);p.current&&ee.observe(p.current);let T=window.setTimeout(y,300);return()=>{a=!1,c&&window.clearTimeout(c),window.clearTimeout(T),ee.disconnect(),d.dispose();try{h.current?.close()}catch{}t.dispose(),m.current=null}},[e,n]),(0,_.useEffect)(()=>{m.current&&(m.current.options.fontSize=o)},[o]),(0,_.useEffect)(()=>{c&&(m.current?.focus(),S(!1)),requestAnimationFrame(()=>te.current())},[c]),(0,$.jsxs)(`div`,{className:`secondary-pane${c?` focused`:``}`,onMouseDown:l,children:[(0,$.jsxs)(`div`,{className:`secondary-pane-bar`,children:[ee&&!c&&(0,$.jsx)(`span`,{className:`secondary-pane-dot`,title:`New output`}),(0,$.jsx)(`span`,{className:`secondary-pane-name`,children:e}),t?(0,$.jsx)(`span`,{className:`secondary-pane-proc`,children:t}):null,(0,$.jsx)(`span`,{className:`secondary-pane-status ${g}`,children:g===`connected`?``:g}),d&&(0,$.jsx)(`button`,{type:`button`,"aria-label":`Swap ${e} with primary`,title:`Swap with primary (⌘⇧E)`,onClick:e=>{e.stopPropagation(),d()},children:`⇄`}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Close pane ${e}`,onClick:e=>{e.stopPropagation(),u()},children:`✕`})]}),(0,$.jsx)(`div`,{className:`secondary-pane-box`,ref:p,children:(0,$.jsx)(`div`,{className:`secondary-pane-scale`,style:{transform:`scale(${y})`},children:(0,$.jsx)(`div`,{ref:f})})})]})},Qh=()=>`room-${Math.random().toString(36).slice(2,7)}`,$h=/Mac|iPhone|iPad/i.test(navigator.platform||navigator.userAgent||``),eg=typeof navigator.vibrate==`function`,tg=typeof window<`u`&&`Notification`in window,ng=e=>{let t=e.match(/^\/s\/([^/]+)\/?$/);if(!t)return null;try{return decodeURIComponent(t[1])}catch{return t[1]}},rg=()=>ng(window.location.pathname)||new URLSearchParams(window.location.search).get(`room`),ig=e=>`/s/${encodeURIComponent(e)}/`,ag=()=>{let e=window.__HOP_SESSION__;if(e?.wsUrl){let{protocol:t,host:n}=window.location;return`${t===`https:`?`wss`:`ws`}://${n}${e.wsUrl}`}let{protocol:t,hostname:n,host:r}=window.location;return`${t===`https:`?`wss`:`ws`}://${r}/ws`},og=e=>{let t=Em(e);return t===`typing`?`typing`:t===`active`?`active`:`idle`},sg=e=>{let t=new URL(window.location.href);return t.searchParams.set(`room`,e),t.searchParams.delete(`name`),t.toString()},cg={background:`#0d1117`,foreground:`#e6edf3`,cursor:`#60a5fa`,cursorAccent:`#0d1117`,selectionBackground:`#264f78`,selectionForeground:`#e6edf3`,black:`#0d1117`,red:`#cd3131`,green:`#0dbc79`,yellow:`#e5e510`,blue:`#2472c8`,magenta:`#bc3fbc`,cyan:`#11a8cd`,white:`#e5e5e5`,brightBlack:`#6b7280`,brightRed:`#f14c4c`,brightGreen:`#23d18b`,brightYellow:`#f5f543`,brightBlue:`#3b8eea`,brightMagenta:`#d670d6`,brightCyan:`#29b8db`,brightWhite:`#ffffff`},lg={background:`#ffffff`,foreground:`#000000`,cursor:`#000000`,cursorAccent:`#ffffff`,selectionBackground:`#b5d5ff`,selectionForeground:`#000000`,selectionInactiveBackground:`#d0d0d0`,black:`#000000`,red:`#c91b00`,green:`#00a600`,yellow:`#c7c400`,blue:`#0225c7`,magenta:`#c930c7`,cyan:`#00a6b2`,white:`#c7c7c7`,brightBlack:`#676767`,brightRed:`#ff6d67`,brightGreen:`#5ff967`,brightYellow:`#fefb67`,brightBlue:`#6871ff`,brightMagenta:`#ff76ff`,brightCyan:`#5ffdff`,brightWhite:`#feffff`},ug=e=>1,dg=e=>e===`dark`?cg:e===`light`?lg:typeof window<`u`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?cg:lg,fg=()=>{if(typeof window>`u`)return!1;let e=navigator.userAgent||``;return/iPhone|iPad|iPod|Android/i.test(e)||window.innerWidth<768},pg=e=>{if(!e)return``;let t=e,n=e.match(/^(\/(?:Users|home)\/[^/]+)(\/.*)?$/);return n?t=`~`+(n[2]||``):e===`/root`?t=`~`:e.startsWith(`/root/`)&&(t=`~`+e.slice(5)),t},mg={kind:`leaf`,id:`primary`,session:null},hg=()=>`p${Math.random().toString(36).slice(2,8)}`,gg=e=>{let t=e;return!t||typeof t!=`object`?!1:t.kind===`leaf`?typeof t.id==`string`&&(t.session===null||typeof t.session==`string`):t.kind===`split`?(t.dir===`row`||t.dir===`col`)&&typeof t.ratio==`number`&&gg(t.a)&&gg(t.b):!1},_g=e=>e.kind===`leaf`?e.session===null:_g(e.a)||_g(e.b),vg=`instant`,yg=5e3,bg=15e3,xg=200,Sg=()=>window.__HOP_SESSION__,Cg=()=>!!Sg(),wg=()=>{let e=new URLSearchParams(window.location.search).get(`name`),t=localStorage.getItem(`hay_name`),n=Sg()?.name;return e??t??(n&&n!==`Guest`?n:null)??`User`},Tg=`hop_session_seen_v1`,Eg=()=>{try{let e=JSON.parse(localStorage.getItem(Tg)||`{}`);return e&&typeof e==`object`?e:{}}catch{return{}}},Dg=e=>{try{localStorage.setItem(Tg,JSON.stringify(e))}catch{}},Og=({size:e=34})=>(0,$.jsx)(`span`,{className:`ios-spinner`,style:{width:e,height:e},"aria-hidden":`true`,children:Array.from({length:12}).map((t,n)=>(0,$.jsx)(`span`,{style:{transform:`rotate(${n*30}deg) translate(0, -${e*.34}px)`,animationDelay:`${-(11-n)/12}s`}},n))}),kg=()=>{let e=Sg(),t=e?.room??rg()??Qh(),[n,r]=(0,_.useState)(()=>wg()),[i,a]=(0,_.useState)(()=>t),[o,s]=(0,_.useState)(()=>e?.room?{name:wg(),room:t}:null),[c,l]=(0,_.useState)(()=>t),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(`idle`),[m,h]=(0,_.useState)([]),[g,v]=(0,_.useState)(!0),[y,b]=(0,_.useState)(null),[ee,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(null),[te,E]=(0,_.useState)(null),ne=(0,_.useRef)(null),[re,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(0),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(!1),[ie,ae]=(0,_.useState)(``),[oe,se]=(0,_.useState)({index:0,total:0}),P=(0,_.useRef)([]),F=(0,_.useRef)(-1),I=(0,_.useRef)(null),ce=(0,_.useRef)(null),[le,ue]=(0,_.useState)({x:window.innerWidth-72,y:64}),de=(0,_.useRef)(null),[L,fe]=(0,_.useState)(()=>fg()),[pe,me]=(0,_.useState)(()=>fg()),[he,ge]=(0,_.useState)(0),[_e,ve]=(0,_.useState)(()=>localStorage.getItem(`hay_selection_mode`)===`true`),[ye,be]=(0,_.useState)(()=>localStorage.getItem(`hay_haptics_enabled`)!==`false`),[R,xe]=(0,_.useState)(()=>{let e=localStorage.getItem(`hay_notify_bells`);return tg&&e===`true`}),[Se,Ce]=(0,_.useState)(()=>localStorage.getItem(`hay_theme`)||`system`),[we,Te]=(0,_.useState)([]),[Ee,De]=(0,_.useState)(!1),[Oe,ke]=(0,_.useState)(!1),[Ae,je]=(0,_.useState)([]),[Me,Ne]=(0,_.useState)(!1),[Pe,Fe]=(0,_.useState)(!1),[Ie,Le]=(0,_.useState)(``),[Re,ze]=(0,_.useState)(!1),[Be,Ve]=(0,_.useState)(``),[z,He]=(0,_.useState)(!1),[Ue,We]=(0,_.useState)(``),[Ge,Ke]=(0,_.useState)(()=>Cg()?new URLSearchParams(window.location.search).has(`home`)||new URLSearchParams(window.location.search).get(`view`)===`wall`?!0:fg()&&!window.location.pathname.startsWith(`/s/`):!1),[qe,Je]=(0,_.useState)(()=>localStorage.getItem(`hay_session_switch_mode`)===`page`?`page`:vg);(0,_.useEffect)(()=>{o?.room&&l(o.room)},[o?.room]);let[Ye,Xe]=(0,_.useState)(()=>{let e=localStorage.getItem(`hay_font_size`);return e?parseInt(e,10):14}),[Ze,Qe]=(0,_.useState)(()=>{let e=localStorage.getItem(`hay_view_mode`);return e===`fit`||e===`full`?e:`fit`}),$e=(0,_.useRef)(null),B=(0,_.useRef)(null),et=(0,_.useRef)(null),tt=(0,_.useRef)(null),nt=(0,_.useRef)(null),rt=(0,_.useRef)(Am()),it=(0,_.useRef)(!1),at=(0,_.useRef)(null),ot=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=()=>fe(fg());return window.addEventListener(`resize`,e),window.addEventListener(`orientationchange`,e),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`orientationchange`,e)}},[]),(0,_.useEffect)(()=>{localStorage.setItem(`hay_selection_mode`,_e?`true`:`false`)},[_e]),(0,_.useEffect)(()=>{localStorage.setItem(`hay_haptics_enabled`,ye?`true`:`false`)},[ye]),(0,_.useEffect)(()=>{localStorage.setItem(`hay_notify_bells`,R?`true`:`false`)},[R]),(0,_.useEffect)(()=>{localStorage.setItem(`hay_theme`,Se);let e=document.documentElement;if(Se===`system`?e.removeAttribute(`data-theme`):e.setAttribute(`data-theme`,Se),B.current){let e=B.current,t=dg(Se);e.options.theme=t,e.options.minimumContrastRatio=ug(Se);let n=nt.current?.querySelector(`.xterm-viewport`);n&&(n.style.backgroundColor=t.background??``),typeof e.clearTextureAtlas==`function`&&e.clearTextureAtlas(),e.refresh(0,e.rows-1)}},[Se]),(0,_.useEffect)(()=>{localStorage.setItem(`hay_session_switch_mode`,qe)},[qe]);let st=(0,_.useRef)(!1),ct=(0,_.useRef)(null),lt=(0,_.useRef)(Ze),ut=(0,_.useRef)(0),dt=(0,_.useRef)(null),ft=(0,_.useRef)(!0),pt=(0,_.useRef)(0),V=(0,_.useRef)(!1),mt=(0,_.useRef)(null),ht=(0,_.useRef)(null),gt=(0,_.useRef)(null),_t=(0,_.useRef)(null),vt=(0,_.useRef)(null),yt=(0,_.useRef)(!1),bt=(0,_.useRef)(!1),xt=(0,_.useRef)(!1),St=(0,_.useRef)(!1),Ct=(0,_.useRef)(0),wt=(0,_.useRef)(null),Tt=(0,_.useRef)([]),Et=(0,_.useRef)(null),Dt=(0,_.useRef)(null),Ot=(0,_.useRef)(null),kt=(0,_.useRef)(null),[At,jt]=(0,_.useState)(!1),Mt=(0,_.useRef)(we);Mt.current=we;let Nt=(0,_.useRef)({at:0,value:!1}),H=()=>{let e=performance.now();if(e-Nt.current.at<1e3)return Nt.current.value;let t=!1,n=B.current;if(n)try{let e=n.buffer.active,r=e.baseY+n.rows,i=``;for(let t=Math.max(0,r-30);t<r;t++)i+=(e.getLine(t)?.translateToString(!0)??``)+`
128
128
  `;t=/bypass permissions on|shift\+tab to cycle|esc to interrupt|\? for shortcuts/i.test(i)}catch{}return Nt.current={at:e,value:t},t},Pt=()=>{let e=Ot.current;if(e){let t=(Mt.current.find(t=>(t.internalName||t.name)===e)?.foregroundProcess||``).trim();if(t===`claude`||/^\d+\.\d+\.\d+$/.test(t))return!0}return H()};gt.current=Pt;let Ft=(0,_.useRef)(A);Ft.current=A;let It=(0,_.useRef)(At);It.current=At;let[Lt,Rt]=(0,_.useState)(()=>{try{let e=localStorage.getItem(`hay_pane_tree`);if(e){let t=JSON.parse(e);if(gg(t)&&_g(t))return t}}catch{}return mg}),[zt,Bt]=(0,_.useState)(`primary`),Vt=(0,_.useRef)(zt);Vt.current=zt;let Ht=(0,_.useRef)(null);(0,_.useEffect)(()=>{try{Lt.kind===`leaf`?localStorage.removeItem(`hay_pane_tree`):localStorage.setItem(`hay_pane_tree`,JSON.stringify(Lt))}catch{}},[Lt]);let Ut=e=>{let t=hg(),n={kind:`leaf`,id:t,session:``};return Rt(t=>{let r=Vt.current;if(r===`primary`||t.kind===`leaf`)return t.kind===`leaf`?{kind:`split`,id:`root`,dir:e,ratio:.55,a:t,b:n}:{...t,b:{kind:`split`,id:hg(),dir:e,ratio:.5,a:t.b,b:n}};let i=!1,a=t=>t.kind===`leaf`?t.id!==r||i?t:(i=!0,{kind:`split`,id:hg(),dir:e,ratio:.5,a:t,b:n}):{...t,a:a(t.a),b:a(t.b)},o=a(t);return i?o:{...t,b:{kind:`split`,id:hg(),dir:e,ratio:.5,a:t.b,b:n}}}),t},Wt=(e,t)=>{Rt(n=>Xt(n,e,t))},Gt=e=>{let t=Ut(e);Bt(t),Ht.current=t,Ke(!0)},Kt=e=>{e!==`primary`&&(Bt(`primary`),Rt(t=>{let n=t=>{if(t.kind===`leaf`)return t.id===e?null:t;let r=n(t.a),i=n(t.b);return r&&i?{...t,a:r,b:i}:r||i};return n(t)||mg}))},qt=(e,t)=>{Rt(n=>{let r=n=>n.kind===`split`?n.id===e?{...n,ratio:t}:{...n,a:r(n.a),b:r(n.b)}:n;return r(n)})},Jt=(0,_.useRef)(Lt);Jt.current=Lt;let Yt=(e,t)=>e.kind===`leaf`?e.id===t?e.session:null:Yt(e.a,t)??Yt(e.b,t),Xt=(e,t,n)=>e.kind===`leaf`?e.id===t?{...e,session:n}:e:{...e,a:Xt(e.a,t,n),b:Xt(e.b,t,n)},Zt=e=>{let t=Yt(Jt.current,e),n=Ot.current;if(!t||!n||t===n)return;let r=Mt.current.find(e=>e.name===t||e.internalName===t);r&&(Rt(t=>Xt(t,e,n)),kt.current?.(r),Bt(`primary`))},Qt=(0,_.useRef)({splitAndPick:Gt,closePane:Kt,swapPaneWithPrimary:Zt});Qt.current={splitAndPick:Gt,closePane:Kt,swapPaneWithPrimary:Zt};let $t=e=>e.kind===`leaf`?[e.id]:[...$t(e.a),...$t(e.b)],en=(0,_.useRef)(null),tn=(0,_.useRef)(!1),nn=(0,_.useRef)(0),rn=(0,_.useRef)(0),an=(0,_.useRef)(R),on=(0,_.useRef)(c),sn=(0,_.useRef)({}),cn=(0,_.useRef)({});(0,_.useEffect)(()=>{an.current=R},[R]),(0,_.useEffect)(()=>{on.current=c},[c]);let ln=e=>{w(e),ct.current&&window.clearTimeout(ct.current),ct.current=window.setTimeout(()=>{w(null)},3e3)};ht.current=ln;let un=(e,t=2e3)=>{E(e),ne.current&&window.clearTimeout(ne.current),ne.current=window.setTimeout(()=>{E(null)},t)},dn=(e,t)=>{if(!(!tg||Notification.permission!==`granted`))try{let n=new Notification(e,{body:`Terminal bell`});n.onclick=()=>{window.focus(),t?.(),n.close()}}catch{}},fn=()=>{let e=B.current;if(!e)return``;let t=e.buffer.active,n=t.viewportY,r=Math.min(n+e.rows,t.length),i=[];for(let e=n;e<r;e++)i.push(t.getLine(e)?.translateToString(!0)??``);return i.join(`
129
129
  `).trimEnd()},pn=(e=0)=>{let t=B.current;if(!t)return``;let n=t.buffer.active,r=n.length,i=e>0?Math.max(0,r-e):0,a=[];for(let e=i;e<r;e++)a.push(n.getLine(e)?.translateToString(!0)??``);return a.join(`
130
130
  `).trimEnd()},mn=(e,t)=>{let n=B.current,r=P.current;if(!n||r.length===0)return;let i=Lm(n,r,e,t);i<0||(F.current=i,I.current={row:r[i].row,col:r[i].col},V.current=!0,se({index:i+1,total:r.length}))},hn=e=>{let t=B.current;return!t||!e?[]:Im(t,e)},gn=e=>{let t=B.current;F.current=-1,I.current=null;let n=hn(e);if(P.current=n,!t||!e){se({index:0,total:0}),t?.clearSelection();return}n.length>0?mn(n.length-1,e.length):(se({index:0,total:0}),t.clearSelection())},_n=e=>{let t=B.current,n=ie;if(!t||!n)return;let r=hn(n);if(P.current=r,r.length===0){F.current=-1,I.current=null,se({index:0,total:0}),t.clearSelection();return}let i=I.current;if(!i){mn(r.length-1,n.length);return}let a=r.findIndex(e=>e.row===i.row&&e.col===i.col);a===-1&&(a=r.findIndex(e=>e.row>i.row||e.row===i.row&&e.col>=i.col),a===-1&&(a=r.length-1)),mn(a+e,n.length)},vn=()=>{N(!0),setTimeout(()=>ce.current?.focus(),0)},yn=()=>{N(!1),ae(``),P.current=[],F.current=-1,I.current=null,se({index:0,total:0}),B.current?.clearSelection(),L||B.current?.focus()},bn=async(e,t)=>{try{await navigator.clipboard.writeText(e),ln(`${t} copied (${e.split(`
131
- `).length} lines)`)}catch{ln(`Copy failed`)}};(0,_.useEffect)(()=>{Ot.current=o?.room??null},[o?.room]);let xn=(0,_.useMemo)(()=>sg(o?c||o.room:i),[o,i,c]),Sn=(0,_.useMemo)(()=>Tm(m,ee),[m,ee]),Cn=(0,_.useMemo)(()=>y?m.find(e=>e.id===y)?.name??`Someone`:``,[m,y]),wn=f===`connected`&&!g&&y===ee;(0,_.useEffect)(()=>{it.current&&!wn&&rt.current.reset(),it.current=wn},[wn]),(0,_.useEffect)(()=>{if(lt.current=Ze,localStorage.setItem(`hay_view_mode`,Ze),Ze===`fit`&&B.current&&setTimeout(()=>{Xn(),Yn()},0),Ze===`full`&&B.current&&et.current){let{cols:e,rows:t}=et.current;(B.current.cols!==e||B.current.rows!==t)&&B.current.resize(e,t)}},[Ze]);let Tn=e=>{$e.current?.readyState===WebSocket.OPEN&&$e.current.send(JSON.stringify(e))},[En,Dn]=(0,_.useState)(!1),On=(0,_.useRef)(0),kn=`${navigator.platform||``} ${navigator.userAgent||``}`;(0,_.useEffect)(()=>{let e=e=>e.preventDefault();return window.addEventListener(`dragover`,e),window.addEventListener(`drop`,e),()=>{window.removeEventListener(`dragover`,e),window.removeEventListener(`drop`,e)}},[]);let An=e=>{Tn({type:`typing`,active:e})},[jn,Mn]=(0,_.useState)(null),Nn=(0,_.useRef)(null);Nn.current||=zm({send:e=>mt.current?.(e),notify:e=>ht.current?.(e),setOverlay:e=>Mn(e===null?null:{interim:e}),eligible:()=>gt.current?.()??!1});let Pn=e=>{V.current&&(V.current=!1,B.current?.scrollToBottom());let t=e.replace(/\x1b\[I/g,``).replace(/\x1b\[O/g,``);if(!t)return;if($e.current?.readyState!==WebSocket.OPEN){let e=Ot.current;e&&(Tt.current.push({room:e,data:t,at:Date.now()}),Tt.current.length>xg&&Tt.current.shift());let n=window.__hopKbDiag;n&&n.buf++;let r=Date.now();r-Ct.current>2e3&&(Ct.current=r,un(`Reconnecting — input buffered`));return}let n=rt.current.onInput(t,wn);n&&Qn(n),Tn({type:`input`,data:t});let r=window.__hopKbDiag;if(r&&r.sent++,lt.current===`fit`){let e=Date.now();if(e-In.current>500){In.current=e,Xn();let t=et.current,n=B.current;t&&n&&(t.cols!==n.cols||t.rows!==n.rows)&&(Jn.current=null),Yn()}}st.current||(st.current=!0,An(!0)),at.current&&window.clearTimeout(at.current),at.current=window.setTimeout(()=>{st.current=!1,An(!1)},1200)};mt.current=Pn;let Fn=(0,_.useRef)(!1),In=(0,_.useRef)(0),Ln=(0,_.useRef)(0),Rn=(0,_.useRef)(!1),zn=()=>{let e=B.current;if(e)try{e.refresh(0,e.rows-1)}catch{}},Bn=(0,_.useRef)(zn);Bn.current=zn;let Vn=(0,_.useRef)(!1);Vn.current=Ge;let Hn=(0,_.useRef)(new Set),Un=(0,_.useRef)(0),Wn=(0,_.useRef)(0),Gn=(0,_.useRef)(!1),Kn=(0,_.useRef)(null),qn=(0,_.useRef)(null),Jn=(0,_.useRef)(null),Yn=()=>{if(!B.current)return;let e=Fn.current?`attach`:void 0;Fn.current=!1;let t=B.current.cols,n=B.current.rows;if(!e&&Jn.current&&Jn.current.cols===t&&Jn.current.rows===n)return;Jn.current={cols:t,rows:n};let r=e===`attach`&&Rn.current;r&&(Rn.current=!1),Tn({type:`resize`,cols:t,rows:n,...e?{claim:e}:{},...r?{user:!0}:{}})},Xn=()=>{if(!B.current||!nt.current)return!1;let e=B.current,t=e._core;if(!t?._renderService?.dimensions?.css?.cell)return!1;let n=t._renderService.dimensions.css.cell.width,r=t._renderService.dimensions.css.cell.height;if(!n||!r)return!1;let i=nt.current.closest(`.terminal-scroll`);if(!i)return!1;let a=i.getBoundingClientRect();if(a.width<1||a.height<1)return!1;let o=window.getComputedStyle(i),s=parseFloat(o.paddingLeft)||0,c=parseFloat(o.paddingRight)||0,l=parseFloat(o.paddingTop)||0,u=parseFloat(o.paddingBottom)||0,d=a.width-s-c,f=a.height-l-u,p=Math.max(2,Math.floor(d/n)),m=Math.max(1,Math.floor(f/r));return(e.cols!==p||e.rows!==m)&&e.resize(p,m),!0},Zn=(e=12,t)=>{if(lt.current===`fit`){if(Xn()){Yn(),t?.();return}e>0&&requestAnimationFrame(()=>Zn(e-1,t))}},Qn=e=>{if(!B.current)return;let t=e.replace(/\x1b\[I/g,``).replace(/\x1b\[O/g,``);B.current.write(t,()=>{V.current||B.current?.scrollToBottom()})},$n=e=>{if(!ft.current)return;let t=Math.min(1e3*2**ut.current,3e4);ut.current+=1,ln(`Reconnecting in ${Math.round(t/1e3)}s...`),dt.current=window.setTimeout(()=>{dt.current=null,ft.current&&er(e)},t)},er=e=>{let t=e.room;dt.current&&=(window.clearTimeout(dt.current),null);let n=++pt.current;St.current=!1,yt.current=!1,bt.current=!1,xt.current=!1,et.current=null,rt.current.reset(),V.current=!1,B.current?.reset();let r=!1,i=performance.now();(wt.current===null||wt.current>250)&&fetch(`/api/sessions/screen?name=${encodeURIComponent(t)}`).then(e=>e.ok?e.json():null).then(e=>{if(!e||typeof e.data!=`string`||!e.data||n!==pt.current||Ot.current!==t||r||!B.current)return;let i=Number(e.cols),a=Number(e.rows);if(Number.isInteger(i)&&Number.isInteger(a)&&i>1&&a>1&&(B.current.cols!==i||B.current.rows!==a))try{B.current.resize(i,a)}catch{}B.current.write(e.data,()=>{let e=B.current;e&&(e.scrollToBottom(),e.refresh(0,e.rows-1))})}).catch(()=>{});let a=ag(),o=B.current?.cols??80,s=B.current?.rows??24,c=Hn.current.has(e.room)?1572864:393216,u=dg(Se),f=e=>(e||``).replace(`#`,``).slice(0,6),m=`${a}?room=${encodeURIComponent(e.room)}&name=${encodeURIComponent(e.name)}&cols=${o}&rows=${s}&replay=${c}&bg=${f(u.background)}&fg=${f(u.foreground)}`;$e.current?.close(),p(`connecting`),ft.current=!0;let g=new WebSocket(m);$e.current=g,g.addEventListener(`open`,()=>{if(n!==pt.current||Ot.current!==t){g.close();return}p(`connected`),ut.current=0,Jn.current=null,Yn();let e=Tt.current;if(Tt.current=[],e.length>0){let n=Date.now(),r=e.filter(e=>e.room===t),i=r.filter(e=>n-e.at<=bg);i.length>0&&(g.send(JSON.stringify({type:`input`,data:i.map(e=>e.data).join(``)})),un(`Reconnected — sent ${i.length} buffered keystroke${i.length===1?``:`s`}`)),r.length>i.length&&un(`Reconnected — stale buffered input discarded`)}}),g.addEventListener(`message`,e=>{if(n!==pt.current||Ot.current!==t)return;let a=wm(e.data);if(a)switch(a.type){case`hello`:S(a.clientId),v(a.collabMode),b(a.controllerId);break;case`presence`:Et.current===null?(h(a.clients),Et.current=window.setTimeout(()=>{Et.current=null,Dt.current&&=(h(Dt.current),null)},300)):Dt.current=a.clients;break;case`output`:{St.current=Um(a.data,St.current);let e=rt.current.reconcileOutput(a.data);e&&Qn(e)}break;case`snapshot`:r=!0,wt.current=performance.now()-i,St.current=typeof a.keyboardEnhanced==`boolean`?a.keyboardEnhanced:Um(a.data,!1),bt.current=a.mouseReporting===!0,xt.current=a.mouseSgr===!0,rt.current.reset(),V.current=!1,Gn.current=(a.capped===!0||typeof a.data==`string`&&a.data.length>=35e4)&&!Hn.current.has(Ot.current||``);let e=Kn.current&&Kn.current.room===Ot.current?Kn.current:null;if(Kn.current=null,B.current){let t=B.current,n=(a.mouseReporting?`\x1B[?1002h`+(a.mouseSgr?`\x1B[?1006h`:``):``)+(a.cursorHidden?`\x1B[?25l`:``);t.write(`\x1bc${a.data}${n}`,()=>{if(e){let n=Math.max(0,t.buffer.active.length-e.oldLen);t.scrollToLine(n),V.current=n<Math.max(0,t.buffer.active.length-t.rows)}else t.scrollToBottom(),V.current=!1;t.refresh(0,t.rows-1),Un.current=t.buffer.active.viewportY,Wn.current=performance.now()})}else Qn(a.data);typeof a.alternateScreen==`boolean`&&(yt.current=a.alternateScreen),B.current&&(typeof a.cursorHidden==`boolean`?B.current.write(a.cursorHidden?`\x1B[?25l`:`\x1B[?25h`):a.alternateScreen&&B.current.write(`\x1B[?25l`)),lt.current===`fit`&&(Fn.current=!0,Zn(12,()=>B.current?.scrollToBottom()));break;case`collab`:v(a.enabled),b(a.controllerId),ln(a.enabled?`Collaborative typing enabled`:`Control locked to a single editor`);break;case`input_rejected`:ln(a.reason);break;case`active_size`:if(et.current={cols:a.cols,rows:a.rows},B.current&&lt.current!==`fit`){let e=B.current.cols,t=B.current.rows;(a.cols!==e||a.rows!==t)&&B.current.resize(a.cols,a.rows)}break;case`session_ended`:ft.current=!1,ln(a.by?`${a.message} (by ${a.by})`:a.message),g.close(),p(`ended`),qn.current?.({showLoading:!1}),window.setTimeout(()=>Ke(!0),400);break;case`session_renamed`:l(a.displayName),ln(`Session renamed to ${a.displayName}`);break;case`cwd_changed`:d(a.cwd);break;default:break}}),g.addEventListener(`close`,()=>{n===pt.current&&Ot.current===t&&ft.current&&(rt.current.reset(),p(`disconnected`),$n(e))}),g.addEventListener(`error`,()=>{n===pt.current&&(Ot.current!==t||!ft.current||(rt.current.reset(),p(`disconnected`)))})};(0,_.useEffect)(()=>{!o||!re||Vn.current||er(o)},[o,re,O]),(0,_.useEffect)(()=>{if(!o||!nt.current||B.current)return;let e=new nc({fontFamily:getComputedStyle(document.documentElement).getPropertyValue(`--font-terminal`).trim()||`Menlo, Monaco, 'Courier New', monospace`,fontSize:Ye,lineHeight:1.3,cursorBlink:!0,scrollback:5e4,scrollSensitivity:4,fastScrollSensitivity:12,minimumContrastRatio:ug(Se),theme:dg(Se)}),t=new x;e.loadAddon(t),e.loadAddon(new T((e,t)=>{e.preventDefault(),window.open(t,`_blank`,`noopener`)})),e.open(nt.current);let n=null;try{n=new Lf,n.onContextLoss(()=>{n?.dispose(),n=null,requestAnimationFrame(()=>Bn.current())}),e.loadAddon(n)}catch{n?.dispose(),n=null}t.fit(),L||(e.__wheelCleanup=Pm(nt.current,()=>B.current,{linesPerNotch:4,lineHeightPx:()=>Math.max(1,e._core?._renderService?.dimensions?.css?.cell?.height||Ye*1.3)})),B.current=e,tt.current=t,Zn();for(let t of[4,10,11,12,52,104,110,111,112])e.parser.registerOscHandler(t,()=>!0);e.parser.registerCsiHandler({final:`I`},()=>!0),e.parser.registerCsiHandler({final:`O`},()=>!0),e.onBell(()=>{document.hidden&&(Ne(!0),an.current&&dn(on.current||Ot.current||`Terminal`))});let r=new Set([47,1047,1049]),i=new Set([1e3,1002,1003]),a=(e,t)=>{for(let n of e){let e=Array.isArray(n)?n[0]:n;r.has(e)&&(yt.current=t),i.has(e)&&(bt.current=t),e===1006&&(xt.current=t)}return!1};if(e.parser.registerCsiHandler({prefix:`?`,final:`h`},e=>a(e,!0)),e.parser.registerCsiHandler({prefix:`?`,final:`l`},e=>a(e,!1)),D(!0),L){let e=nt.current.querySelector(`textarea`);e&&(e.setAttribute(`readonly`,`true`),e.setAttribute(`tabindex`,`-1`),e.style.opacity=`0`,e.style.pointerEvents=`none`)}else e.onData(Pn);e.attachCustomKeyEventHandler(e=>{if(e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey)return e.type===`keydown`&&(e.preventDefault(),Ke(!0)),!1;{let t=Nn.current?.handleKey(e);if(t!==void 0)return t}if(e.key===`Enter`&&e.shiftKey&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&(St.current||Pt()))return e.type===`keydown`&&(e.preventDefault(),Pn(`\x1B[13;2u`)),!1;if(e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`q`){if(e.type===`keydown`){let e=Date.now();e>Ln.current?(Ln.current=e+2e3,ln(`Press Ctrl+Q again to kill this session for ALL participants`)):(Ln.current=0,Tn({type:`kill_session`}))}return!1}return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`?(e.type===`keydown`&&(e.preventDefault(),vn()),!1):e.ctrlKey&&e.shiftKey&&(e.key===`c`||e.key===`v`)?!1:(e.ctrlKey&&!e.altKey&&e.metaKey,!0)});let s=new ResizeObserver(()=>{lt.current===`fit`&&(Xn(),e.refresh(0,e.rows-1),Yn())});e.__resizeObserver=s;let c=nt.current.closest(`.terminal-scroll`);c&&s.observe(c);let l=()=>{let t=e.buffer.active;return{len:t.length,rows:e.rows,y:t.viewportY,base:t.baseY}},u=()=>{let t=_t.current,n=vt.current;if(!t||!n)return;let r=e.modes.mouseTrackingMode!==`none`||e.buffer.active.type===`alternate`,{len:i,rows:a,y:o}=l();if(r||i<=a+1){t.classList.remove(`visible`);return}t.classList.add(`visible`);let s=t.clientHeight,c=Math.max(24,Math.round(a/i*s)),u=Math.round(o/Math.max(1,i-a)*(s-c));n.style.height=c+`px`,n.style.transform=`translateY(`+u+`px)`};e.onScroll(()=>{let{y:t,base:n}=l();V.current=t<n;let r=Un.current>0,i=Wn.current>0&&performance.now()-Wn.current>600;if(Un.current=t,t===0&&r&&i&&Gn.current){let t=Ot.current;t&&!Hn.current.has(t)&&(Hn.current.add(t),Kn.current={room:t,oldLen:e.buffer.active.length},Gn.current=!1,k(e=>e+1))}u()});let d=window.setInterval(u,700);e.__overlayScrollbarCleanup=()=>window.clearInterval(d);let f=vt.current;f&&f.addEventListener(`pointerdown`,t=>{t.preventDefault(),t.stopPropagation();let n=_t.current;if(!n)return;n.classList.add(`dragging`);let r=t.clientY,i=l().y,a=t=>{let{len:a,rows:o}=l(),s=n.clientHeight,c=Math.max(24,Math.round(o/a*s)),u=i+(t.clientY-r)/Math.max(1,s-c)*(a-o);e.scrollToLine(Math.max(0,Math.min(a-o,Math.round(u))))},o=()=>{n.classList.remove(`dragging`),window.removeEventListener(`pointermove`,a),window.removeEventListener(`pointerup`,o)};window.addEventListener(`pointermove`,a),window.addEventListener(`pointerup`,o)})},[o]),(0,_.useEffect)(()=>{if(!L||!re)return;let e=B.current,t=nt.current?.closest(`.terminal-scroll`);if(!e||!t)return;if(e.__touchCleanup&&=(e.__touchCleanup(),null),_e){let n=()=>{let t=e._core,n=t?._renderService?.dimensions?.css?.cell?.width,r=t?._renderService?.dimensions?.css?.cell?.height;return{w:n&&n>0?n:9,h:r&&r>0?r:18}},r=()=>{let e=nt.current?.querySelector(`.xterm-screen`);return e?e.getBoundingClientRect():null},i=e=>{let t=r();if(!t)return null;let i=n(),a=Math.floor((e.clientX-t.left)/i.w),o=Math.floor((e.clientY-t.top)/i.h);return{col:Math.max(0,a),row:Math.max(0,o)}},a=null,o=null,s=!1,c=()=>{o!==null&&(clearInterval(o),o=null)},l=(t,n,r,i)=>{let a=e.buffer.active,o=a.viewportY+t,s=a.viewportY+r,c,l,u,d;if(o<s||o===s&&n<=i?(c=o,l=n,u=s,d=i):(c=s,l=i,u=o,d=n),c===u){let t=Math.max(1,d-l+1);e.select(l,c,t)}else e.selectLines(c,u)},u=t=>{if(t.touches.length!==1)return;t.cancelable&&t.preventDefault();let n=i(t.touches[0]);n&&(e.clearSelection(),a=n,t.touches[0].clientY,s=!1)},d=t=>{if(t.touches.length!==1||!a)return;t.cancelable&&t.preventDefault(),s=!0;let u=t.touches[0];u.clientY;let d=i(u);if(!d)return;let f=d.col;l(a.row,a.col,d.row,d.col);let p=r();if(!p)return;let m=n().h*2;c(),u.clientY<p.top+m?o=window.setInterval(()=>{e.scrollLines(-1),a&&(a.row+=1,l(a.row,a.col,0,f))},60):u.clientY>p.bottom-m&&(o=window.setInterval(()=>{e.scrollLines(1),a&&(--a.row,l(a.row,a.col,e.rows-1,f))},60))},f=t=>{if(c(),s&&e.hasSelection()){let t=e.getSelection();t&&navigator.clipboard.writeText(t).then(()=>un(`Copied ${t.split(`
132
- `).length} line(s)`),()=>un(`Copy failed`))}else e.clearSelection();a=null,s=!1};return t.addEventListener(`touchstart`,u,{passive:!1,capture:!0}),t.addEventListener(`touchmove`,d,{passive:!1,capture:!0}),t.addEventListener(`touchend`,f,{passive:!0,capture:!0}),t.addEventListener(`touchcancel`,f,{passive:!0,capture:!0}),e.__touchCleanup=()=>{c(),t.removeEventListener(`touchstart`,u,{capture:!0}),t.removeEventListener(`touchmove`,d,{capture:!0}),t.removeEventListener(`touchend`,f,{capture:!0}),t.removeEventListener(`touchcancel`,f,{capture:!0})},()=>{e.__touchCleanup&&=(e.__touchCleanup(),null)}}let n=0,r=0,i=[],a=0,o=0,s=0,c=!0,l=0,u=0,d=null,f=!1,p=!1,m=0,h=0,g=0,_=0,v=()=>{let t=e._core?._renderService?.dimensions?.css?.cell?.height;return t&&t>0?t:18},y=e=>{Tn({type:`input`,data:e})},b=()=>bt.current&&xt.current,x=e=>{if(e===0)return;let t=B.current,n=Math.max(1,Math.floor((t?.cols||80)/2)),r=Math.max(1,Math.floor((t?.rows||24)/2)),i=`\x1b[<${e>0?65:64};${n};${r}M`.repeat(Math.min(Math.abs(e),40));Tn({type:`input`,data:i})},ee=e=>({x:(e[0].clientX+e[1].clientX)/2,y:(e[0].clientY+e[1].clientY)/2}),S=.25,C=()=>{d!==null&&(cancelAnimationFrame(d),d=null),u=0},w=null,te=()=>{if(w=null,yt.current)if(b()){let e=Math.trunc(r/v());e!==0&&(x(e),r-=e*v())}else{let e=v()*3,t=Math.trunc(r/e);if(t!==0){let n=t>0?`\x1B[6~`:`\x1B[5~`;for(let e=0;e<Math.abs(t);e++)y(n);r-=t*e}}else{let t=Math.trunc(r/v());t!==0&&(e.scrollLines(t),r-=t*v())}},T=()=>{w===null&&(w=requestAnimationFrame(te))},E=()=>{if(Math.abs(u)<S){d=null;return}r+=u,te(),u*=.94,d=requestAnimationFrame(E)},ne=e=>{if(C(),e.cancelable&&e.preventDefault(),e.touches.length===2){p=!0;let t=ee(e.touches);g=t.x,_=t.y;let n=nt.current?.closest(`.terminal-scroll`);n&&(m=n.scrollLeft,h=n.scrollTop);return}if(e.touches.length!==1){p=!1,f=!1;return}p=!1,n=e.touches[0].clientY,l=Date.now(),r=0,i=[],f=!0,a=e.touches[0].clientX,o=e.touches[0].clientY,s=Date.now(),c=!1},D=e=>{if(e.touches.length===2){if(!p){p=!0;let t=ee(e.touches);g=t.x,_=t.y;let n=nt.current?.closest(`.terminal-scroll`);n&&(m=n.scrollLeft,h=n.scrollTop)}let t=ee(e.touches),n=g-t.x,r=_-t.y,i=nt.current?.closest(`.terminal-scroll`);i&&(i.scrollLeft=m+n,i.scrollTop=h+r),e.preventDefault();return}if(e.touches.length!==1)return;p&&(p=!1,f=!0);let t=e.touches[0].clientY,s=Date.now(),u=n-t,d=Math.max(1,s-l);!c&&(Math.abs(e.touches[0].clientX-a)>10||Math.abs(t-o)>10)&&(c=!0),d>0&&d<100&&(i.push(u/d),i.length>5&&i.shift()),e.preventDefault(),r+=u,T(),n=t,l=s},O=()=>{if(p){p=!1;return}if(!c&&Date.now()-s<400){c=!0;let e=B.current,t=nt.current?.querySelector(`.xterm-screen`);if(e&&t){let n=t.getBoundingClientRect(),r=Math.floor((a-n.left)/n.width*e.cols),i=Math.floor((o-n.top)/n.height*e.rows);if(r>=0&&r<e.cols&&i>=0&&i<e.rows){let t=wr(e.buffer.active.viewportY+i,r);t&&br({url:t,x:a,y:o})}}}if(f&&i.length>0&&(!yt.current||b())){let e=0;for(let t of i)Math.abs(t)>Math.abs(e)&&(e=t);u=e*16,Math.abs(u)>=S&&(d=requestAnimationFrame(E))}f=!1};return t.addEventListener(`touchstart`,ne,{passive:!1,capture:!0}),t.addEventListener(`touchmove`,D,{passive:!1,capture:!0}),t.addEventListener(`touchend`,O,{passive:!0,capture:!0}),t.addEventListener(`touchcancel`,O,{passive:!0,capture:!0}),e.__touchCleanup=()=>{C(),w!==null&&(cancelAnimationFrame(w),w=null),t.removeEventListener(`touchstart`,ne,{capture:!0}),t.removeEventListener(`touchmove`,D,{capture:!0}),t.removeEventListener(`touchend`,O,{capture:!0}),t.removeEventListener(`touchcancel`,O,{capture:!0})},()=>{e.__touchCleanup&&=(e.__touchCleanup(),null)}},[L,_e,re]),(0,_.useEffect)(()=>{if(!re||!L)return;let e=B.current;if(!e)return;let t=e._core?.viewport;if(t)return ot.current||={start:typeof t.handleTouchStart==`function`?t.handleTouchStart.bind(t):void 0,move:typeof t.handleTouchMove==`function`?t.handleTouchMove.bind(t):void 0},_e?(t.handleTouchStart=()=>{},t.handleTouchMove=()=>!0):ot.current&&(ot.current.start&&(t.handleTouchStart=ot.current.start),ot.current.move&&(t.handleTouchMove=ot.current.move)),()=>{ot.current&&(ot.current.start&&(t.handleTouchStart=ot.current.start),ot.current.move&&(t.handleTouchMove=ot.current.move))}},[re,L,_e]),(0,_.useEffect)(()=>{o||(ft.current=!1,dt.current&&=(window.clearTimeout(dt.current),null),$e.current?.close(),$e.current=null,rt.current.reset(),ut.current=0)},[o]),(0,_.useEffect)(()=>()=>{let e=B.current,t=e?.__resizeObserver;t&&t.disconnect(),e&&(e.__touchCleanup&&=(e.__touchCleanup(),null),e.__wheelCleanup&&=(e.__wheelCleanup(),null),e.__overlayScrollbarCleanup&&=(e.__overlayScrollbarCleanup(),null),e.dispose(),B.current=null,tt.current=null),ft.current=!1,dt.current&&window.clearTimeout(dt.current),$e.current?.close()},[]),(0,_.useEffect)(()=>{if(!Cg()||!o)return;let e=new URLSearchParams(window.location.search),t=e.get(`view`)===`wall`;if(Ge&&!t)e.set(`view`,`wall`),window.history.pushState({},``,window.location.pathname+`?`+e.toString());else if(!Ge&&t){e.delete(`view`);let t=e.toString();window.history.replaceState({},``,window.location.pathname+(t?`?`+t:``))}},[Ge]),(0,_.useEffect)(()=>{if(!o)return;let e=window.setInterval(()=>{if(document.hidden||Vn.current)return;let e=B.current;if(e)try{let t=e.buffer.active;!V.current&&t.viewportY<t.baseY&&e.scrollToBottom(),e.refresh(0,e.rows-1)}catch{}},1400);return()=>window.clearInterval(e)},[o]),(0,_.useEffect)(()=>{if(!o)return;let e=()=>{document.hidden||Vn.current||requestAnimationFrame(()=>Bn.current())};return document.addEventListener(`visibilitychange`,e),window.addEventListener(`focus`,e),window.addEventListener(`pageshow`,e),()=>{document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`focus`,e),window.removeEventListener(`pageshow`,e)}},[o]),(0,_.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get(`view`)===`wall`;Ke(e);let t=rg(),r=new URLSearchParams(window.location.search).get(`name`)??localStorage.getItem(`hay_name`)??n;if(!t){Cg()||s(null);return}a(t),s(e=>{let n=e?.name??r??`User`;return e?.room===t&&e.name===n?e:{name:n,room:t}})};return window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`popstate`,e)}},[n]);let[,tr]=(0,_.useState)(0);(0,_.useEffect)(()=>{if(m.length===0)return;let e=window.setInterval(()=>tr(e=>e+1),2e4);return()=>window.clearInterval(e)},[m.length]),(0,_.useEffect)(()=>{let e=()=>{ue(e=>({x:Math.max(0,Math.min(window.innerWidth-56,e.x)),y:Math.max(0,Math.min(window.innerHeight-56,e.y))}))};return window.addEventListener(`resize`,e),window.addEventListener(`orientationchange`,e),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`orientationchange`,e)}},[]);let nr=(0,_.useCallback)(async(e={})=>{let{showLoading:t=!0}=e;t&&De(!0);let n=++rn.current;try{let e=await(await fetch(`/api/sessions`)).json(),t=new Map;for(let n of e.sessions||[])t.set(n.name,{name:n.name,displayName:n.displayName||n.name,active:(e.active||[]).includes(n.name),starting:(e.starting||[]).includes(n.name),type:n.type,port:n.port,cwd:n.cwd,internalName:n.internalName||n.name,lastActivityAt:Number(n.lastActivityAt)||0,bellSeq:Number(n.bellSeq)||0,foregroundProcess:n.foregroundProcess,agentPermitted:n.agentPermitted===!0,createdBy:n.createdBy===`agent`?`agent`:`user`,createdVia:typeof n.createdVia==`string`?n.createdVia:null,cols:Number.isInteger(n.cols)?n.cols:void 0,rows:Number.isInteger(n.rows)?n.rows:void 0,tagline:typeof n.tagline==`string`?n.tagline:void 0,parked:n.parked===!0,archived:n.archived===!0,hasLocalCli:n.hasLocalCli===!0,folderId:typeof n.folderId==`string`?n.folderId:null});let r=new Set;for(let t of e.sessions||[])t.name&&r.add(String(t.name)),t.internalName&&r.add(String(t.internalName)),t.displayName&&r.add(String(t.displayName));for(let n of e.active||[])!r.has(n)&&!t.has(n)&&t.set(n,{name:n,displayName:n,active:!0,starting:!1,internalName:n,createdBy:`user`});let i=Eg(),a=Ot.current,o=document.visibilityState===`visible`,s=!1,c=Array.from(t.values()).map(e=>{let t=e.internalName||e.name,n=e.lastActivityAt||0,r=e.bellSeq||0,c=a!==null&&(e.internalName===a||e.name===a),l=i[t];return l?c&&o&&(l.out!==n||l.bell!==r)&&(l={out:n,bell:r},i[t]=l,s=!0):(l={out:n,bell:r},i[t]=l,s=!0),{...e,unread:!c&&n>l.out,bellUnseen:!c&&r>l.bell}});if(c.length>0){let e=new Set(c.map(e=>e.internalName||e.name));for(let t of Object.keys(i))e.has(t)||(delete i[t],s=!0)}if(s&&Dg(i),n!==rn.current)return;je(Array.isArray(e.folders)?e.folders.filter(e=>e&&e.id&&e.name).map(e=>({id:String(e.id),name:String(e.name)})):[]),Te(c),ke(!1),tn.current=!0,nn.current=Date.now()}catch(e){console.error(`Failed to fetch sessions:`,e),ke(!0)}finally{t&&De(!1)}},[]);qn.current=nr,(0,_.useEffect)(()=>{if(A){let e=Date.now()-nn.current<=yg;(!tn.current||!e)&&nr({showLoading:!tn.current})}},[A,nr]),(0,_.useEffect)(()=>{nr()},[nr]),(0,_.useEffect)(()=>{if(!o)return;let e=window.setInterval(()=>nr({showLoading:!1}),5e3);return()=>window.clearInterval(e)},[o,nr]),(0,_.useEffect)(()=>{let e=()=>{document.visibilityState===`visible`&&(Ne(!1),nr({showLoading:!1}))};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[nr]);let rr=(0,_.useMemo)(()=>{let e=o?.room??null,t=!1,n=!1;for(let r of we)e&&(r.internalName===e||r.name===e)||(r.bellUnseen?t=!0:r.unread&&(n=!0));return{bell:t,output:n}},[we,o?.room]);(0,_.useEffect)(()=>{let e=c||o?.room||`hop`,t=Me||rr.bell;document.title=`${t?`● `:``}${e}`},[Me,rr.bell,c,o?.room]),(0,_.useEffect)(()=>{let e=sn.current,t={};for(let n of we){let r=n.internalName||n.name;if(t[r]=n.bellUnseen===!0,!R||!n.bellUnseen||e[r])continue;let i=n.bellSeq||0;(cn.current[r]??0)>=i||(cn.current[r]=i,dn(n.displayName,()=>ar(n)))}sn.current=t},[we,R]),(0,_.useEffect)(()=>{B.current&&(B.current.options.fontSize=Ye,lt.current===`fit`?(Xn(),Yn()):B.current.refresh(0,B.current.rows-1)),localStorage.setItem(`hay_font_size`,String(Ye))},[Ye]),(0,_.useEffect)(()=>{if(!L||!re||!pe||he<=0)return;let e=window.requestAnimationFrame(()=>{lt.current===`fit`&&(Xn(),Yn())});return()=>{window.cancelAnimationFrame(e)}},[L,re,pe,he]);let ir=e=>{let t=e.internalName||e.name;if((o?.room??null)===t)return;let r=Eg();r[t]={out:e.lastActivityAt||0,bell:e.bellSeq||0},Dg(r),Tt.current=[],h([]),b(null),S(null),d(null),p(`connecting`),a(t),l(e.displayName||e.name),s(e=>({name:e?.name??n.trim()??`User`,room:t})),window.history.pushState({},``,ig(t)+`?view=wall`)},ar=e=>{let t=e.internalName||e.name,r=ig(t),i=o?.room??c,u=qe===`instant`&&e.type!==`port`;Rn.current=!0;let f=Eg();if(f[e.internalName||e.name]={out:e.lastActivityAt||0,bell:e.bellSeq||0},Dg(f),!u){window.location.href=r;return}if(i===t){j(!1);return}rt.current.reset(),Tt.current=[],h([]),b(null),S(null),d(null),p(`connecting`),a(t),l(e.displayName||e.name),s(e=>({name:e?.name??n.trim()??`User`,room:t})),window.history.pushState({},``,r),j(!1)};kt.current=ar,(0,_.useEffect)(()=>{if(!o||!Cg())return;let e=$e.current,t=!!e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING);if(Ge){if(t){ft.current=!1;try{e.close()}catch{}}}else ft.current=!0,Rn.current=!0,requestAnimationFrame(()=>Bn.current()),t||k(e=>e+1)},[Ge]),(0,_.useEffect)(()=>{if(L||!o||Ge||A||At||M||Re||z||zt!==`primary`)return;let e=window.setTimeout(()=>B.current?.focus(),30);return()=>window.clearTimeout(e)},[Ge,A,At,M,Re,z,o,zt]);let or=e=>{if(e.preventDefault(),!n.trim()||!i.trim()){ln(`Enter a name and room to start.`);return}localStorage.setItem(`hay_name`,n.trim()),s({name:n.trim(),room:i.trim()})},sr=e=>{e.preventDefault();let t=Ie.trim();Fe(!1),!(!t||t===n)&&(localStorage.setItem(`hay_name`,t),r(t),s(e=>e&&{...e,name:t}),ln(`Display name set to ${t}`))},cr=async e=>{e.preventDefault();let t=Be.trim(),n=c||o?.room||``;if(!t||t===n){ze(!1);return}if(!/^[a-zA-Z0-9_-]+$/.test(t)){ln(`Only letters, numbers, - and _ allowed`);return}try{let e=await fetch(`/api/sessions/rename`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({oldName:n,newName:t})});if(!e.ok){let t=await e.json().catch(()=>({}));ln(t.error||`Rename failed`);return}ze(!1),nr({showLoading:!1})}catch{ln(`Rename failed`)}},lr=()=>{let e=c||o?.room||`this session`;window.confirm(`Kill session "${e}" for all participants? Its running process is terminated.`)&&(Tn({type:`kill_session`}),j(!1))},ur=async()=>{try{await navigator.clipboard.writeText(xn),ln(`Share link copied.`)}catch{ln(`Copy failed. Select the link manually.`)}},dr=()=>{Tn({type:`toggle_collab`,enabled:!g})},fr=()=>{Tn({type:`take_control`})},U=()=>{Tn({type:`release_control`})},pr=e=>{if(!e){xe(!1);return}xe(!0),Notification.permission!==`granted`&&Notification.requestPermission().then(e=>{e!==`granted`&&(ln(`Notifications are blocked by the browser`),xe(!1))})},mr=(e,t)=>{de.current={dragging:!1,startX:e,startY:t,startPosX:le.x,startPosY:le.y}},hr=(e,t)=>{if(!de.current)return;let n=e-de.current.startX,r=t-de.current.startY;(Math.abs(n)>5||Math.abs(r)>5)&&(de.current.dragging=!0),de.current.dragging&&ue({x:Math.max(0,Math.min(window.innerWidth-56,de.current.startPosX+n)),y:Math.max(0,Math.min(window.innerHeight-56,de.current.startPosY+r))})},gr=()=>{de.current&&!de.current.dragging&&(L&&Cg()?Ke(!0):j(!0)),de.current=null},_r=(0,_.useCallback)(()=>{me(e=>!e),setTimeout(()=>{lt.current===`fit`&&(Xn(),Yn())},100)},[]),vr=(0,_.useCallback)(e=>{Pn(e)},[]),[yr,br]=(0,_.useState)(null),[xr,Sr]=(0,_.useState)(!1);(0,_.useEffect)(()=>{if(!Cg()||typeof window>`u`||!window.PublicKeyCredential||localStorage.getItem(`hay_passkey_nudge_done`)===`1`)return;let e=!1,t=window.setTimeout(async()=>{try{let t=await(await fetch(`/api/passkeys/login-options`,{method:`POST`})).json();!e&&t&&t.ok===!1&&Sr(!0)}catch{}},4e3);return()=>{e=!0,window.clearTimeout(t)}},[]);let Cr=()=>{localStorage.setItem(`hay_passkey_nudge_done`,`1`),Sr(!1)},wr=(0,_.useCallback)((e,t)=>{let n=B.current;if(!n)return null;let r=n.buffer.active,i=e;for(;i>0&&r.getLine(i)?.isWrapped;)i--;let a=``,o=-1;for(let s=i;s<r.length;s++){let c=r.getLine(s);if(!c||s>i&&!c.isWrapped)break;s===e&&(o=a.length+Math.min(t,n.cols-1)),a+=c.translateToString(!1)}if(o<0)return null;let s=/https?:\/\/[^\s"'`<>]+/g,c;for(;(c=s.exec(a))!==null;)if(o>=c.index&&o<=c.index+c[0].length)return c[0].replace(/[.,;:!?)\]}]+$/,``);return null},[]),Tr=(0,_.useCallback)(async()=>{let e=e=>Uint8Array.from(atob(e.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(Math.ceil(e.length/4)*4,`=`)),e=>e.charCodeAt(0)),t=e=>btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``);try{let n=await(await fetch(`/api/passkeys/register-options`,{method:`POST`})).json();if(!n.ok)throw Error(n.error||`Could not start enrollment`);let r=n.options;r.challenge=e(r.challenge),r.user.id=e(r.user.id),r.excludeCredentials=(r.excludeCredentials||[]).map(t=>({...t,id:e(t.id)}));let i=await navigator.credentials.create({publicKey:r}),a=i.response,o=await(await fetch(`/api/passkeys/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({token:n.token,response:{id:i.id,rawId:t(i.rawId),type:i.type,authenticatorAttachment:i.authenticatorAttachment||void 0,clientExtensionResults:i.getClientExtensionResults(),response:{clientDataJSON:t(a.clientDataJSON),attestationObject:t(a.attestationObject),transports:a.getTransports?.()||[]}}})})).json();un(o.ok?`Passkey added — biometric sign-in enabled on this domain`:`Passkey failed: ${o.error||`verification failed`}`,4e3)}catch(e){if(e.name===`NotAllowedError`)return;un(`Passkey: ${e.message}`,4e3)}},[]);(0,_.useEffect)(()=>{if(o||!Cg())return;nr({showLoading:!1});let e=window.setInterval(()=>{document.hidden||nr({showLoading:!1})},5e3),t=()=>{document.hidden||nr({showLoading:!1})};return document.addEventListener(`visibilitychange`,t),()=>{window.clearInterval(e),document.removeEventListener(`visibilitychange`,t)}},[o]),(0,_.useEffect)(()=>{if(!o||!Cg())return;let e=e=>{let t=[...Mt.current].filter(e=>e.type!==`port`).sort((e,t)=>(e.displayName||e.name).localeCompare(t.displayName||t.name));if(t.length<2)return;let n=t[(t.findIndex(e=>e.name===Ot.current||e.internalName===Ot.current)+e+t.length)%t.length];n&&kt.current?.(n)},t=t=>{if(!($h?t.metaKey&&!t.ctrlKey&&!t.altKey:t.ctrlKey&&t.shiftKey&&!t.metaKey&&!t.altKey)){t.key===`Escape`&&(Ft.current||It.current)&&(t.preventDefault(),t.stopPropagation(),j(!1),jt(!1));return}let n=t.key.toLowerCase(),r=t.shiftKey,i=()=>{t.preventDefault(),t.stopPropagation()};if(n===`k`&&(!$h||!r)){i(),Ke(e=>!e);return}if(n===`j`){i(),e(r?-1:1);return}if(n===`,`){i(),j(e=>!e);return}if(n===`/`||r&&n===`?`){i(),jt(e=>!e);return}if(r&&n===`e`){let e=$t(Jt.current).filter(e=>e!==`primary`),t=Vt.current===`primary`?e.length===1?e[0]:null:Vt.current;t&&(i(),Qt.current.swapPaneWithPrimary(t));return}if(n===`]`||n===`[`){let e=$t(Jt.current);if(e.length>1){i();let t=Math.max(0,e.indexOf(Vt.current));Bt(e[(t+(n===`]`?1:-1)+e.length)%e.length])}return}if(n===`\\`||n===`|`){i(),Qt.current.splitAndPick(r||n===`|`?`col`:`row`);return}if(r&&n===`k`&&Vt.current!==`primary`){i(),Qt.current.closePane(Vt.current);return}if($h&&!r){if(n===`=`||n===`+`){i(),Xe(e=>Math.min(24,e+1));return}if(n===`-`){i(),Xe(e=>Math.max(8,e-1));return}if(n===`0`){i(),Xe(14);return}}};return window.addEventListener(`keydown`,t,!0),()=>window.removeEventListener(`keydown`,t,!0)},[o]);let Er=L?{"--mobile-keyboard-height":`${pe?he:0}px`}:void 0;return(0,$.jsxs)(`div`,{className:`app`,children:[(0,$.jsxs)(`header`,{className:`topbar`,children:[(0,$.jsx)(`div`,{className:`brand`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`p`,{className:`brand-title`,children:[Cg()?`hop`:`hay`,(0,$.jsx)(`span`,{className:`brand-cursor`,"aria-hidden":`true`})]}),(0,$.jsx)(`p`,{className:`brand-subtitle`,children:Cg()?`terminals for humans and agents.`:`Collaborative terminal sharing for Hop.`})]})}),(0,$.jsxs)(`div`,{className:`presence-strip`,children:[Sn.map(e=>(0,$.jsxs)(`div`,{className:`presence-chip ${e.id===ee?`self`:``}`,title:`${e.name} · ${og(e)}`,children:[(0,$.jsx)(`span`,{className:`presence-dot`,style:{backgroundColor:e.color}}),(0,$.jsx)(`span`,{className:`presence-name`,children:e.name}),!g&&y===e.id&&(0,$.jsx)(`span`,{className:`presence-control`,title:`Has control`,children:`control`}),(0,$.jsx)(`span`,{className:`presence-status ${og(e)}`,children:og(e)})]},e.id)),Sn.length===0&&(0,$.jsx)(`span`,{className:`presence-empty`,children:`No viewers yet`})]}),!L&&o&&Cg()&&(0,$.jsxs)(`div`,{className:`topbar-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`topbar-sessions-btn`,title:`Sessions (${$h?`⌘K`:`Ctrl+Shift+K`})`,onClick:()=>Ke(!0),children:[`Sessions`,(0,$.jsx)(`kbd`,{children:$h?`⌘K`:`⌃⇧K`})]}),(0,$.jsx)(`button`,{type:`button`,className:`topbar-sessions-btn`,"aria-label":`Session settings`,title:`Session settings`,onClick:()=>j(!0),children:(0,$.jsxs)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,$.jsx)(`circle`,{cx:`12`,cy:`12`,r:`3`}),(0,$.jsx)(`path`,{d:`M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.01a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51h.01a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.01a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z`})]})})]})]}),!o&&Cg()?(0,$.jsxs)(`main`,{className:`hub`,children:[(0,$.jsx)(Xh,{open:!0,sessions:we,currentRoom:null,dismissable:!1,folders:Ae,onClose:()=>{},onSwitch:e=>{window.location.href=ig(e.displayName||e.name)},onRefresh:()=>nr({showLoading:!1}),onNotice:un,tileWsBase:ag(),userName:n,terminalTheme:dg(Se)}),te&&(0,$.jsx)(`div`,{className:`terminal-toast`,role:`status`,"aria-live":`polite`,children:te})]}):o?(0,$.jsxs)(`main`,{className:`session${L&&pe?` has-keyboard`:``}${_e?` selection-mode`:``}`,style:Er,children:[f!==`connected`&&f!==`idle`&&(0,$.jsxs)(`div`,{className:`connection-banner${f===`ended`?` ended`:``}`,role:`status`,"aria-live":`polite`,children:[(0,$.jsx)(`span`,{children:f===`connecting`?`Connecting…`:f===`ended`?`Session ended`:`Disconnected — reconnecting…`}),(f===`disconnected`||f===`ended`)&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>k(e=>e+1),children:`Reconnect now`})]}),(0,$.jsxs)(`button`,{type:`button`,"aria-label":`Open menu`,className:`drawer-toggle`,style:{left:le.x,top:le.y,bottom:`auto`},onMouseDown:e=>mr(e.clientX,e.clientY),onMouseMove:e=>hr(e.clientX,e.clientY),onMouseUp:gr,onMouseLeave:gr,onTouchStart:e=>mr(e.touches[0].clientX,e.touches[0].clientY),onTouchMove:e=>hr(e.touches[0].clientX,e.touches[0].clientY),onTouchEnd:gr,children:[(0,$.jsxs)(`svg`,{width:`22`,height:`22`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[(0,$.jsx)(`line`,{x1:`4`,y1:`6`,x2:`20`,y2:`6`}),(0,$.jsx)(`circle`,{cx:`9`,cy:`6`,r:`2`,fill:`currentColor`}),(0,$.jsx)(`line`,{x1:`4`,y1:`12`,x2:`20`,y2:`12`}),(0,$.jsx)(`circle`,{cx:`15`,cy:`12`,r:`2`,fill:`currentColor`}),(0,$.jsx)(`line`,{x1:`4`,y1:`18`,x2:`20`,y2:`18`}),(0,$.jsx)(`circle`,{cx:`11`,cy:`18`,r:`2`,fill:`currentColor`})]}),(rr.bell||rr.output)&&(0,$.jsx)(`span`,{className:`fab-attention${rr.bell?` bell`:``}`,"aria-hidden":`true`})]}),A&&(0,$.jsx)(`div`,{className:`drawer-overlay`,onClick:()=>j(!1)}),(0,$.jsxs)(`section`,{className:`controls ${A?`open`:``}`,children:[(0,$.jsx)(`button`,{type:`button`,"aria-label":`Close menu`,className:`drawer-close`,onClick:()=>j(!1),children:`✕`}),(0,$.jsxs)(`div`,{className:`room-info`,children:[(0,$.jsx)(`p`,{className:`room-label`,children:`Session`}),Re?(0,$.jsxs)(`form`,{className:`inline-edit`,onSubmit:cr,children:[(0,$.jsx)(`input`,{value:Be,onChange:e=>Ve(e.target.value),maxLength:64,autoFocus:!0,"aria-label":`New session name`}),(0,$.jsx)(`button`,{type:`submit`,children:`Save`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>ze(!1),children:`✕`})]}):(0,$.jsxs)(`div`,{className:`room-title-row`,children:[(0,$.jsx)(`h2`,{children:c||o.room}),Cg()&&(0,$.jsx)(`button`,{type:`button`,className:`icon-btn-inline`,title:`Rename session`,"aria-label":`Rename session`,onClick:()=>{Ve(c||o.room),ze(!0)},children:`✎`})]}),u&&(0,$.jsx)(`p`,{className:`room-cwd`,title:u,children:pg(u)}),(0,$.jsx)(`p`,{className:`room-meta`,children:f===`connected`?`Live`:f===`connecting`?`Connecting`:f===`ended`?`Ended`:`Offline`})]}),(0,$.jsxs)(`div`,{className:`quick-actions`,children:[(0,$.jsxs)(`div`,{className:`quick-group`,children:[L&&(0,$.jsx)(`button`,{type:`button`,className:`quick-btn icon-btn`,onClick:()=>{_r(),j(!1)},title:pe?`Hide keyboard`:`Show keyboard`,"aria-label":pe?`Hide keyboard`:`Show keyboard`,children:(0,$.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`rect`,{x:`2`,y:`4`,width:`20`,height:`14`,rx:`2`}),(0,$.jsx)(`path`,{d:`M6 8h.01M10 8h.01M14 8h.01M18 8h.01M6 12h.01M10 12h.01M14 12h.01M18 12h.01M8 16h8`})]})}),(0,$.jsx)(`button`,{type:`button`,className:`quick-btn icon-btn`,onClick:ur,title:`Copy share link`,"aria-label":`Copy share link`,children:(0,$.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`path`,{d:`M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71`}),(0,$.jsx)(`path`,{d:`M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71`})]})}),L&&(0,$.jsx)(`button`,{type:`button`,className:`quick-btn icon-btn`,title:`Find in scrollback`,"aria-label":`Find in terminal`,onClick:()=>{j(!1),vn()},children:(0,$.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`circle`,{cx:`11`,cy:`11`,r:`7`}),(0,$.jsx)(`path`,{d:`M21 21l-4.3-4.3`})]})})]}),(0,$.jsxs)(`div`,{className:`quick-group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,onClick:()=>{Xn(),Yn()},children:`Fit`}),L&&Cg()?(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,onClick:()=>{j(!1),Ke(!0)},children:`Sessions`}):(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,onClick:()=>{window.open(`/sessions.html`,`_blank`)},children:`Manage`}),(0,$.jsx)(`button`,{type:`button`,className:`quick-btn danger`,onClick:lr,children:`Kill`}),(f===`disconnected`||f===`ended`)&&(0,$.jsx)(`button`,{type:`button`,className:`quick-btn primary`,onClick:()=>k(e=>e+1),children:`Reconnect`})]})]}),(0,$.jsxs)(`div`,{className:`drawer-group`,children:[(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Name`}),Pe?(0,$.jsxs)(`form`,{className:`inline-edit`,onSubmit:sr,children:[(0,$.jsx)(`input`,{value:Ie,onChange:e=>Le(e.target.value),maxLength:24,autoFocus:!0,"aria-label":`Display name`}),(0,$.jsx)(`button`,{type:`submit`,children:`Save`})]}):(0,$.jsxs)(`button`,{type:`button`,className:`name-edit-toggle`,title:`Change your display name`,onClick:()=>{Le(n),Fe(!0)},children:[n,` `,(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`✎`})]})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Control`}),(0,$.jsx)(`span`,{className:`control-state`,children:g?`Everyone can type`:y===ee?`You have control`:Cn?`Locked by ${Cn}`:`Locked`})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Typing`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:g?`active`:``,onClick:()=>{g||dr()},children:`Everyone`}),(0,$.jsx)(`button`,{type:`button`,className:g?``:`active`,onClick:()=>{g&&dr()},children:`One user`})]})]}),!g&&(0,$.jsx)(`div`,{className:`drawer-row`,children:y===ee?(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,onClick:U,children:`Release control`}):(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,onClick:fr,children:`Take control`})})]}),(0,$.jsxs)(`div`,{className:`drawer-group`,children:[(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Theme`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:Se===`system`?`active`:``,onClick:()=>Ce(`system`),children:`Auto`}),(0,$.jsx)(`button`,{type:`button`,className:Se===`light`?`active`:``,onClick:()=>Ce(`light`),children:`Light`}),(0,$.jsx)(`button`,{type:`button`,className:Se===`dark`?`active`:``,onClick:()=>Ce(`dark`),children:`Dark`})]})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Font`}),(0,$.jsxs)(`div`,{className:`font-size-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>Xe(e=>Math.max(8,e-1)),children:`−`}),(0,$.jsxs)(`span`,{children:[Ye,`px`]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>Xe(e=>Math.min(24,e+1)),children:`+`})]})]}),L&&(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Touch`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:_e?``:`active`,onClick:()=>ve(!1),children:`Scroll`}),(0,$.jsx)(`button`,{type:`button`,className:_e?`active`:``,onClick:()=>ve(!0),children:`Select`})]})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Copy`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>bn(fn(),`Visible text`),children:`Screen`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>bn(pn(),`Full buffer`),children:`All`})]})]})]}),(0,$.jsxs)(`details`,{className:`drawer-details`,children:[(0,$.jsx)(`summary`,{children:`More settings`}),(0,$.jsxs)(`div`,{className:`drawer-group`,children:[Cg()&&typeof window<`u`&&`PublicKeyCredential`in window&&(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Passkey`}),(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,onClick:Tr,children:`Add Touch ID / passkey`})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`View`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:Ze===`fit`?`active`:``,onClick:()=>Qe(`fit`),children:`Auto-fit`}),(0,$.jsx)(`button`,{type:`button`,className:Ze===`full`?`active`:``,onClick:()=>Qe(`full`),children:`Manual`})]})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Switch`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:qe===`page`?`active`:``,onClick:()=>Je(`page`),children:`Page`}),(0,$.jsx)(`button`,{type:`button`,className:qe===`instant`?`active`:``,onClick:()=>Je(`instant`),children:`Instant`})]})]}),tg&&(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Notify`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:R?``:`active`,onClick:()=>pr(!1),children:`Off`}),(0,$.jsx)(`button`,{type:`button`,className:R?`active`:``,onClick:()=>pr(!0),children:`On`})]})]}),L&&eg&&(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Haptics`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:ye?`active`:``,onClick:()=>be(!0),children:`On`}),(0,$.jsx)(`button`,{type:`button`,className:ye?``:`active`,onClick:()=>be(!1),children:`Off`})]})]})]})]}),C&&(0,$.jsx)(`p`,{className:`notice`,role:`status`,"aria-live":`polite`,children:C}),(0,$.jsxs)(`button`,{type:`button`,className:`quick-btn drawer-sessions-btn`,onClick:()=>{j(!1),Ke(!0)},children:[`Sessions`,!L&&(0,$.jsx)(`kbd`,{style:{marginLeft:8},children:$h?`⌘K`:`⌃⇧K`})]}),(0,$.jsxs)(`p`,{className:`build-stamp`,children:[`build `,`5695616 · 2026-08-03`]})]}),(()=>{let e=()=>(0,$.jsxs)(`section`,{inert:Ge,style:Ge?{visibility:`hidden`}:void 0,className:`terminal${f===`disconnected`||f===`ended`?` degraded`:``}`,children:[(0,$.jsxs)(`div`,{className:`terminal-frame`,onClick:()=>{L||B.current?.focus()},onDragEnter:e=>{Array.from(e.dataTransfer?.types||[]).includes(`Files`)&&(e.preventDefault(),On.current+=1,Dn(!0))},onDragOver:e=>e.preventDefault(),onDragLeave:()=>{On.current>0&&--On.current===0&&Dn(!1)},onDrop:e=>{if(e.preventDefault(),On.current=0,Dn(!1),(e.dataTransfer?.files?.length||0)>0){ln(Wm(kn));return}let t=e.dataTransfer?.getData(`text/plain`);t&&B.current?.paste(t)},children:[(0,$.jsx)(`div`,{className:`terminal-scroll`,children:(0,$.jsx)(`div`,{className:`terminal-inner`,ref:nt})}),!L&&(0,$.jsx)(`div`,{className:`term-scrollbar`,ref:_t,"aria-hidden":`true`,children:(0,$.jsx)(`div`,{className:`term-scrollbar-thumb`,ref:vt})}),jn&&(0,$.jsxs)(`div`,{className:`voice-overlay`,"aria-hidden":`true`,children:[(0,$.jsx)(`span`,{className:`voice-dot`}),(0,$.jsx)(`span`,{className:jn.interim?`voice-text`:`voice-text muted`,children:jn.interim||`Listening… release Space to insert`})]}),En&&(0,$.jsx)(`div`,{className:`terminal-drop-overlay`,"aria-hidden":`true`,children:(0,$.jsx)(`span`,{children:Wm(kn)})}),L&&f===`connecting`&&(0,$.jsxs)(`div`,{className:`terminal-loading`,role:`status`,"aria-live":`polite`,children:[(0,$.jsx)(Og,{}),(0,$.jsx)(`span`,{className:`terminal-loading-label`,children:`Loading session…`})]}),M&&(0,$.jsxs)(`div`,{className:`terminal-find`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`input`,{ref:ce,className:`terminal-find-input`,placeholder:`Find in scrollback…`,value:ie,onChange:e=>{ae(e.target.value),gn(e.target.value)},onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),_n(e.shiftKey?-1:1)):e.key===`Escape`&&(e.preventDefault(),yn())}}),(0,$.jsx)(`span`,{className:`terminal-find-count`,children:oe.total>0?`${oe.index}/${oe.total}`:ie?`0/0`:``}),(0,$.jsx)(`button`,{type:`button`,className:`terminal-find-btn`,onClick:()=>_n(-1),"aria-label":`Previous match`,children:`↑`}),(0,$.jsx)(`button`,{type:`button`,className:`terminal-find-btn`,onClick:()=>_n(1),"aria-label":`Next match`,children:`↓`}),(0,$.jsx)(`button`,{type:`button`,className:`terminal-find-btn`,onClick:yn,"aria-label":`Close search`,children:`✕`})]})]}),(0,$.jsxs)(`div`,{className:`terminal-footer`,children:[(0,$.jsx)(`span`,{className:`footer-chip`,children:c||o.room}),u?(0,$.jsx)(`span`,{className:`footer-cwd`,children:u}):null,(0,$.jsx)(`span`,{className:`footer-spacer`}),f===`connected`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,className:`footer-find-toggle`,"aria-label":`Find in terminal`,onClick:vn,children:[$h?`⌘F`:`Ctrl+F`,` find`]}),!L&&(0,$.jsxs)(`button`,{type:`button`,className:`footer-find-toggle`,"aria-label":`Keyboard shortcuts`,onClick:()=>jt(!0),children:[$h?`⌘/`:`Ctrl+Shift+/`,` keys`]}),(0,$.jsx)(`span`,{title:Sn.map(e=>e.name).join(`, `),children:(()=>{let e=Sn.find(e=>e.id!==ee&&e.typing);return e?`${e.name} is typing…`:`${Sn.length} viewer${Sn.length===1?``:`s`}`})()})]}):f===`idle`?(0,$.jsx)(`span`,{children:`awaiting connection`}):f===`ended`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`ended-label`,children:`session ended`}),(0,$.jsx)(`button`,{type:`button`,className:`footer-reconnect`,onClick:()=>k(e=>e+1),children:`Reconnect`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`reconnecting`,children:[`⟳ `,f===`connecting`?`Connecting…`:`Reconnecting…`]}),(0,$.jsx)(`button`,{type:`button`,className:`footer-reconnect`,onClick:()=>k(e=>e+1),children:`Reconnect now`})]}),(0,$.jsx)(`span`,{className:`footer-dot ${f}`,"aria-hidden":`true`,children:`●`})]})]}),t=e=>(0,$.jsx)(`div`,{className:`pane-divider`,onPointerDown:t=>{let n=t.currentTarget.parentElement;n&&(en.current={id:e.id,dir:e.dir,rect:n.getBoundingClientRect()},t.currentTarget.setPointerCapture(t.pointerId))},onPointerMove:t=>{let n=en.current;if(!n||n.id!==e.id)return;let r=n.dir===`row`?(t.clientX-n.rect.left)/Math.max(1,n.rect.width):(t.clientY-n.rect.top)/Math.max(1,n.rect.height);qt(n.id,Math.min(.85,Math.max(.15,r)))},onPointerUp:()=>{en.current=null}},`div-${e.id}`),r=i=>{if(i.kind===`leaf`){if(i.session===null)return(0,$.jsx)(`div`,{className:`primary-pane-wrap`,onMouseDownCapture:()=>Bt(`primary`),children:e()},`primary`);if(i.session===``)return(0,$.jsxs)(`div`,{className:`empty-pane${zt===i.id?` focused`:``}`,onMouseDown:()=>Bt(i.id),children:[(0,$.jsxs)(`button`,{type:`button`,className:`empty-pane-pick`,onClick:()=>{Bt(i.id),Ht.current=i.id,Ke(!0)},children:[(0,$.jsx)(`span`,{className:`empty-pane-plus`,children:`+`}),(0,$.jsxs)(`span`,{children:[`Pick a session `,(0,$.jsx)(`kbd`,{children:$h?`⌘K`:`Ctrl+Shift+K`})]})]}),(0,$.jsx)(`button`,{type:`button`,className:`empty-pane-close`,"aria-label":`Close empty pane`,onClick:e=>{e.stopPropagation(),Kt(i.id)},children:`✕`})]},i.id);let t=(we.find(e=>e.name===i.session||e.internalName===i.session)?.foregroundProcess||``).replace(/^-/,``),r=/^\d+\.\d+\.\d+$/.test(t)?`claude`:t;return(0,$.jsx)(Zh,{sessionName:i.session,procLabel:r===`zsh`||r===`bash`?``:r,wsUrl:ag(),userName:n,cols:120,rows:30,fontSize:Ye,theme:dg(Se),focused:zt===i.id,onFocus:()=>Bt(i.id),onClose:()=>Kt(i.id),onPromote:()=>Zt(i.id)},i.id)}return(0,$.jsxs)(`div`,{className:`pane-split ${i.dir===`row`?`dir-row`:`dir-col`}`,children:[(0,$.jsx)(`div`,{className:`pane-cell`,style:{flexGrow:i.ratio,flexBasis:0},children:r(i.a)}),t(i),(0,$.jsx)(`div`,{className:`pane-cell`,style:{flexGrow:1-i.ratio,flexBasis:0},children:r(i.b)})]},i.id)},i=(0,$.jsx)(`div`,{className:`primary-pane-wrap`,onMouseDownCapture:()=>Bt(`primary`),children:e()},`primary`);if(L)return e();let a=Lt.kind===`split`?Lt:null;return(0,$.jsx)(`div`,{className:`pane-root`,inert:Ge,style:Ge?{visibility:`hidden`}:void 0,children:(0,$.jsxs)(`div`,{className:`pane-split ${a?.dir===`col`?`dir-col`:`dir-row`}`,children:[(0,$.jsx)(`div`,{className:`pane-cell`,style:{flexGrow:a?a.ratio:1,flexBasis:0},children:a&&a.a.kind!==`leaf`?r(a.a):i},`cell-a`),a&&t(a),a&&(0,$.jsx)(`div`,{className:`pane-cell`,style:{flexGrow:1-a.ratio,flexBasis:0},children:r(a.b)},`cell-b`)]},`rootsplit`)})})(),(0,$.jsx)(Xh,{open:Ge,sessions:we,currentRoom:f===`ended`?null:o.room,onClose:()=>{Ht.current=null,Ke(!1)},onSwitch:e=>{let t=Ht.current;t?(Ht.current=null,Wt(t,e.name)):ar(e),Ke(!1)},onRefresh:()=>nr({showLoading:!1}),onNotice:un,tileWsBase:ag(),onFocusSession:ir,folders:Ae,userName:n,terminalTheme:dg(Se),onOpenSettings:()=>{Ke(!1),j(!0)},onToggleKeyboard:L?()=>{Ke(!1),_r()}:void 0,onFind:L?()=>{Ke(!1),vn()}:void 0}),At&&!L&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`drawer-overlay`,onClick:()=>jt(!1)}),(0,$.jsxs)(`div`,{className:`shortcut-help`,role:`dialog`,"aria-label":`Keyboard shortcuts`,children:[(0,$.jsx)(`h3`,{children:`Keyboard shortcuts`}),[[$h?`⌘K`:`Ctrl+Shift+K`,`session palette (type to filter, ↑↓, ⏎)`],[$h?`⌘J / ⌘⇧J`:`Ctrl+Shift+J / +⇧`,`next / previous session`],[$h?`⌘,`:`Ctrl+Shift+,`,`settings drawer`],[$h?`⌘F`:`Ctrl+Shift+F`,`find in terminal`],...$h?[[`⌘+ / ⌘− / ⌘0`,`terminal font size`]]:[],[`Ctrl+Shift+C / V`,`copy / paste`],[`Shift+PgUp / PgDn`,`scrollback`],[$h?`⌘\\ / ⌘⇧\\`:`Ctrl+Shift+\\ / +|`,`split pane — side / stacked`],[$h?`⌘⇧K`:`Ctrl+Shift+K`,`close focused pane`],[$h?`⌘] / ⌘[`:`Ctrl+Shift+] / [`,`next / previous pane`],[$h?`⌘⇧E`:`Ctrl+Shift+E`,`swap pane with primary`],[$h?`⌘/`:`Ctrl+Shift+/`,`this help`],[`Esc`,`close panels`]].map(([e,t])=>(0,$.jsxs)(`div`,{className:`shortcut-help-row`,children:[(0,$.jsx)(`kbd`,{children:e}),(0,$.jsx)(`span`,{children:t})]},e))]})]}),xr&&(0,$.jsxs)(`div`,{className:`link-prompt passkey-nudge`,role:`dialog`,"aria-label":`Enable biometric sign-in`,children:[(0,$.jsx)(`span`,{className:`link-prompt-url`,children:$h?`Sign in with Touch ID / Face ID next time?`:`Sign in with a passkey next time?`}),(0,$.jsx)(`button`,{type:`button`,className:`link-prompt-open`,onClick:async()=>{Cr(),await Tr()},children:`Enable`}),(0,$.jsx)(`button`,{type:`button`,onClick:Cr,children:`Not now`})]}),yr&&(0,$.jsxs)(`div`,{className:`context-menu link-menu`,role:`menu`,"aria-label":`Open link`,style:{left:Math.max(8,Math.min(yr.x,window.innerWidth-268)),top:Math.max(8,Math.min(yr.y+10,window.innerHeight-150))},children:[(0,$.jsx)(`span`,{className:`context-menu-title`,children:yr.url}),(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:`context-menu-item`,onClick:()=>{window.open(yr.url,`_blank`,`noopener`),br(null)},children:(0,$.jsx)(`span`,{children:`Open link`})}),(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:`context-menu-item`,onClick:async()=>{try{await navigator.clipboard.writeText(yr.url),un(`Link copied`)}catch{un(`Clipboard denied — long-press the URL text instead`)}br(null)},children:(0,$.jsx)(`span`,{children:`Copy link`})}),(0,$.jsx)(`div`,{className:`context-menu-separator`,role:`separator`}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`context-menu-item`,onClick:()=>br(null),children:[(0,$.jsx)(`span`,{children:`Cancel`}),(0,$.jsx)(`kbd`,{children:`esc`})]})]}),L&&(0,$.jsx)(th,{onInput:vr,visible:pe&&!Ge,onToggle:_r,onHeightChange:ge,hapticsEnabled:ye,onPasteFailed:()=>un(`Clipboard access denied — long-press the terminal to paste instead.`,3500)}),te&&(0,$.jsx)(`div`,{className:`terminal-toast`,role:`status`,"aria-live":`polite`,children:te})]}):(0,$.jsx)(`main`,{className:`join`,children:(0,$.jsxs)(`div`,{className:`join-card`,children:[(0,$.jsx)(`h1`,{children:`Terminal session`}),(0,$.jsx)(`p`,{children:`Connect to an existing session or start a new one.`}),(0,$.jsxs)(`form`,{onSubmit:or,className:`join-form`,children:[(0,$.jsxs)(`label`,{children:[`Display name`,(0,$.jsx)(`input`,{value:n,onChange:e=>r(e.target.value),placeholder:`Casey`})]}),(0,$.jsxs)(`label`,{children:[`Session`,(0,$.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),placeholder:`my-session`})]}),(0,$.jsx)(`button`,{type:`submit`,className:`primary`,children:`Connect`})]})]})})]})},Ag=document.getElementById(`root`);Ag&&(0,v.createRoot)(Ag).render((0,$.jsx)(_.StrictMode,{children:(0,$.jsx)(kg,{})}));
133
- //# sourceMappingURL=index-bmNjFOSa.js.map
131
+ `).length} lines)`)}catch{ln(`Copy failed`)}};(0,_.useEffect)(()=>{Ot.current=o?.room??null},[o?.room]);let xn=(0,_.useMemo)(()=>sg(o?c||o.room:i),[o,i,c]),Sn=(0,_.useMemo)(()=>Tm(m,ee),[m,ee]),Cn=(0,_.useMemo)(()=>y?m.find(e=>e.id===y)?.name??`Someone`:``,[m,y]),wn=f===`connected`&&!g&&y===ee;(0,_.useEffect)(()=>{it.current&&!wn&&rt.current.reset(),it.current=wn},[wn]),(0,_.useEffect)(()=>{if(lt.current=Ze,localStorage.setItem(`hay_view_mode`,Ze),Ze===`fit`&&B.current&&setTimeout(()=>{Qn(),Zn()},0),Ze===`full`&&B.current&&et.current){let{cols:e,rows:t}=et.current;(B.current.cols!==e||B.current.rows!==t)&&B.current.resize(e,t)}},[Ze]);let Tn=e=>{$e.current?.readyState===WebSocket.OPEN&&$e.current.send(JSON.stringify(e))},[En,Dn]=(0,_.useState)(!1),On=(0,_.useRef)(0),kn=`${navigator.platform||``} ${navigator.userAgent||``}`;(0,_.useEffect)(()=>{let e=e=>e.preventDefault();return window.addEventListener(`dragover`,e),window.addEventListener(`drop`,e),()=>{window.removeEventListener(`dragover`,e),window.removeEventListener(`drop`,e)}},[]);let An=e=>{Tn({type:`typing`,active:e})},[jn,Mn]=(0,_.useState)(null),Nn=(0,_.useRef)(null);Nn.current||=zm({send:e=>mt.current?.(e),notify:e=>ht.current?.(e),setOverlay:e=>Mn(e===null?null:{interim:e}),eligible:()=>gt.current?.()??!1});let Pn=e=>{V.current&&(V.current=!1,B.current?.scrollToBottom());let t=e.replace(/\x1b\[I/g,``).replace(/\x1b\[O/g,``);if(!t)return;if($e.current?.readyState!==WebSocket.OPEN){let e=Ot.current;e&&(Tt.current.push({room:e,data:t,at:Date.now()}),Tt.current.length>xg&&Tt.current.shift());let n=window.__hopKbDiag;n&&n.buf++;let r=Date.now();r-Ct.current>2e3&&(Ct.current=r,un(`Reconnecting — input buffered`));return}let n=rt.current.onInput(t,wn);n&&er(n),Tn({type:`input`,data:t});let r=window.__hopKbDiag;if(r&&r.sent++,lt.current===`fit`){let e=Date.now();if(e-In.current>500){In.current=e,Qn();let t=et.current,n=B.current;t&&n&&(t.cols!==n.cols||t.rows!==n.rows)&&(Xn.current=null),Zn()}}st.current||(st.current=!0,An(!0)),at.current&&window.clearTimeout(at.current),at.current=window.setTimeout(()=>{st.current=!1,An(!1)},1200)};mt.current=Pn;let Fn=(0,_.useRef)(!1),In=(0,_.useRef)(0),Ln=(0,_.useRef)(0),Rn=(0,_.useRef)(!1),zn=()=>{let e=B.current;if(e)try{let t=e;typeof t.clearTextureAtlas==`function`&&t.clearTextureAtlas(),e.refresh(0,e.rows-1)}catch{}},Bn=(0,_.useRef)(zn);Bn.current=zn;let Vn=()=>{Bn.current();let e=B.current;if(!e||!bt.current)return;let t=1+Math.floor((e.cols||2)/2),n=1+Math.floor((e.rows||2)/2),r=xt.current?`\x1b[<64;${t};${n}M\x1b[<65;${t};${n}M`:``;r&&mt.current?.(r)},Hn=(0,_.useRef)(Vn);Hn.current=Vn;let Un=(0,_.useRef)(!1);Un.current=Ge;let Wn=(0,_.useRef)(new Set),Gn=(0,_.useRef)(0),Kn=(0,_.useRef)(0),qn=(0,_.useRef)(!1),Jn=(0,_.useRef)(null),Yn=(0,_.useRef)(null),Xn=(0,_.useRef)(null),Zn=()=>{if(!B.current)return;let e=Fn.current?`attach`:void 0;Fn.current=!1;let t=B.current.cols,n=B.current.rows;if(!e&&Xn.current&&Xn.current.cols===t&&Xn.current.rows===n)return;Xn.current={cols:t,rows:n};let r=e===`attach`&&Rn.current;r&&(Rn.current=!1),Tn({type:`resize`,cols:t,rows:n,...e?{claim:e}:{},...r?{user:!0}:{}})},Qn=()=>{if(!B.current||!nt.current)return!1;let e=B.current,t=e._core;if(!t?._renderService?.dimensions?.css?.cell)return!1;let n=t._renderService.dimensions.css.cell.width,r=t._renderService.dimensions.css.cell.height;if(!n||!r)return!1;let i=nt.current.closest(`.terminal-scroll`);if(!i)return!1;let a=i.getBoundingClientRect();if(a.width<1||a.height<1)return!1;let o=window.getComputedStyle(i),s=parseFloat(o.paddingLeft)||0,c=parseFloat(o.paddingRight)||0,l=parseFloat(o.paddingTop)||0,u=parseFloat(o.paddingBottom)||0,d=a.width-s-c,f=a.height-l-u,p=Math.max(2,Math.floor(d/n)),m=Math.max(1,Math.floor(f/r));return(e.cols!==p||e.rows!==m)&&e.resize(p,m),!0},$n=(e=12,t)=>{if(lt.current===`fit`){if(Qn()){Zn(),t?.();return}e>0&&requestAnimationFrame(()=>$n(e-1,t))}},er=e=>{if(!B.current)return;let t=e.replace(/\x1b\[I/g,``).replace(/\x1b\[O/g,``);B.current.write(t,()=>{V.current||B.current?.scrollToBottom()})},tr=e=>{if(!ft.current)return;let t=Math.min(1e3*2**ut.current,3e4);ut.current+=1,ln(`Reconnecting in ${Math.round(t/1e3)}s...`),dt.current=window.setTimeout(()=>{dt.current=null,ft.current&&nr(e)},t)},nr=e=>{let t=e.room;dt.current&&=(window.clearTimeout(dt.current),null);let n=++pt.current;St.current=!1,yt.current=!1,bt.current=!1,xt.current=!1,et.current=null,rt.current.reset(),V.current=!1,B.current?.reset();let r=!1,i=performance.now();(wt.current===null||wt.current>250)&&fetch(`/api/sessions/screen?name=${encodeURIComponent(t)}`).then(e=>e.ok?e.json():null).then(e=>{if(!e||typeof e.data!=`string`||!e.data||n!==pt.current||Ot.current!==t||r||!B.current)return;let i=Number(e.cols),a=Number(e.rows);if(Number.isInteger(i)&&Number.isInteger(a)&&i>1&&a>1&&(B.current.cols!==i||B.current.rows!==a))try{B.current.resize(i,a)}catch{}B.current.write(e.data,()=>{let e=B.current;e&&(e.scrollToBottom(),e.refresh(0,e.rows-1))})}).catch(()=>{});let a=ag(),o=B.current?.cols??80,s=B.current?.rows??24,c=Wn.current.has(e.room)?1572864:393216,u=dg(Se),f=e=>(e||``).replace(`#`,``).slice(0,6),m=`${a}?room=${encodeURIComponent(e.room)}&name=${encodeURIComponent(e.name)}&cols=${o}&rows=${s}&replay=${c}&bg=${f(u.background)}&fg=${f(u.foreground)}`;$e.current?.close(),p(`connecting`),ft.current=!0;let g=new WebSocket(m);$e.current=g,g.addEventListener(`open`,()=>{if(n!==pt.current||Ot.current!==t){g.close();return}p(`connected`),ut.current=0,Xn.current=null,Zn();let e=Tt.current;if(Tt.current=[],e.length>0){let n=Date.now(),r=e.filter(e=>e.room===t),i=r.filter(e=>n-e.at<=bg);i.length>0&&(g.send(JSON.stringify({type:`input`,data:i.map(e=>e.data).join(``)})),un(`Reconnected — sent ${i.length} buffered keystroke${i.length===1?``:`s`}`)),r.length>i.length&&un(`Reconnected — stale buffered input discarded`)}}),g.addEventListener(`message`,e=>{if(n!==pt.current||Ot.current!==t)return;let a=wm(e.data);if(a)switch(a.type){case`hello`:S(a.clientId),v(a.collabMode),b(a.controllerId);break;case`presence`:Et.current===null?(h(a.clients),Et.current=window.setTimeout(()=>{Et.current=null,Dt.current&&=(h(Dt.current),null)},300)):Dt.current=a.clients;break;case`output`:{St.current=Um(a.data,St.current);let e=rt.current.reconcileOutput(a.data);e&&er(e)}break;case`snapshot`:r=!0,wt.current=performance.now()-i,St.current=typeof a.keyboardEnhanced==`boolean`?a.keyboardEnhanced:Um(a.data,!1),bt.current=a.mouseReporting===!0,xt.current=a.mouseSgr===!0,rt.current.reset(),V.current=!1,qn.current=(a.capped===!0||typeof a.data==`string`&&a.data.length>=35e4)&&!Wn.current.has(Ot.current||``);let e=Jn.current&&Jn.current.room===Ot.current?Jn.current:null;if(Jn.current=null,B.current){let t=B.current,n=(a.mouseReporting?`\x1B[?1002h`+(a.mouseSgr?`\x1B[?1006h`:``):``)+(a.cursorHidden?`\x1B[?25l`:``);t.write(`\x1bc${a.data}${n}`,()=>{if(e){let n=Math.max(0,t.buffer.active.length-e.oldLen);t.scrollToLine(n),V.current=n<Math.max(0,t.buffer.active.length-t.rows)}else t.scrollToBottom(),V.current=!1;t.refresh(0,t.rows-1),Gn.current=t.buffer.active.viewportY,Kn.current=performance.now()})}else er(a.data);typeof a.alternateScreen==`boolean`&&(yt.current=a.alternateScreen),B.current&&(typeof a.cursorHidden==`boolean`?B.current.write(a.cursorHidden?`\x1B[?25l`:`\x1B[?25h`):a.alternateScreen&&B.current.write(`\x1B[?25l`)),lt.current===`fit`&&(Fn.current=!0,$n(12,()=>B.current?.scrollToBottom()));break;case`collab`:v(a.enabled),b(a.controllerId),ln(a.enabled?`Collaborative typing enabled`:`Control locked to a single editor`);break;case`input_rejected`:ln(a.reason);break;case`active_size`:if(et.current={cols:a.cols,rows:a.rows},B.current&&lt.current!==`fit`){let e=B.current.cols,t=B.current.rows;(a.cols!==e||a.rows!==t)&&B.current.resize(a.cols,a.rows)}break;case`session_ended`:ft.current=!1,ln(a.by?`${a.message} (by ${a.by})`:a.message),g.close(),p(`ended`),Yn.current?.({showLoading:!1}),window.setTimeout(()=>Ke(!0),400);break;case`session_renamed`:l(a.displayName),ln(`Session renamed to ${a.displayName}`);break;case`cwd_changed`:d(a.cwd);break;default:break}}),g.addEventListener(`close`,()=>{n===pt.current&&Ot.current===t&&ft.current&&(rt.current.reset(),p(`disconnected`),tr(e))}),g.addEventListener(`error`,()=>{n===pt.current&&(Ot.current!==t||!ft.current||(rt.current.reset(),p(`disconnected`)))})};(0,_.useEffect)(()=>{!o||!re||Un.current||nr(o)},[o,re,O]),(0,_.useEffect)(()=>{if(!o||!nt.current||B.current)return;let e=new nc({fontFamily:getComputedStyle(document.documentElement).getPropertyValue(`--font-terminal`).trim()||`Menlo, Monaco, 'Courier New', monospace`,fontSize:Ye,lineHeight:1.3,cursorBlink:!0,scrollback:5e4,scrollSensitivity:4,fastScrollSensitivity:12,minimumContrastRatio:ug(Se),theme:dg(Se)}),t=new x;e.loadAddon(t),e.loadAddon(new T((e,t)=>{e.preventDefault(),window.open(t,`_blank`,`noopener`)})),e.open(nt.current);let n=null;try{n=new Lf,n.onContextLoss(()=>{n?.dispose(),n=null,requestAnimationFrame(()=>Bn.current())}),e.loadAddon(n)}catch{n?.dispose(),n=null}t.fit(),L||(e.__wheelCleanup=Pm(nt.current,()=>B.current,{linesPerNotch:4,lineHeightPx:()=>Math.max(1,e._core?._renderService?.dimensions?.css?.cell?.height||Ye*1.3)})),B.current=e,tt.current=t,$n();for(let t of[4,10,11,12,52,104,110,111,112])e.parser.registerOscHandler(t,()=>!0);e.parser.registerCsiHandler({final:`I`},()=>!0),e.parser.registerCsiHandler({final:`O`},()=>!0),e.onBell(()=>{document.hidden&&(Ne(!0),an.current&&dn(on.current||Ot.current||`Terminal`))});let r=new Set([47,1047,1049]),i=new Set([1e3,1002,1003]),a=(e,t)=>{for(let n of e){let e=Array.isArray(n)?n[0]:n;r.has(e)&&(yt.current=t),i.has(e)&&(bt.current=t),e===1006&&(xt.current=t)}return!1};if(e.parser.registerCsiHandler({prefix:`?`,final:`h`},e=>a(e,!0)),e.parser.registerCsiHandler({prefix:`?`,final:`l`},e=>a(e,!1)),D(!0),L){let e=nt.current.querySelector(`textarea`);e&&(e.setAttribute(`readonly`,`true`),e.setAttribute(`tabindex`,`-1`),e.style.opacity=`0`,e.style.pointerEvents=`none`)}else e.onData(Pn);e.attachCustomKeyEventHandler(e=>{if(e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey)return e.type===`keydown`&&(e.preventDefault(),Ke(!0)),!1;{let t=Nn.current?.handleKey(e);if(t!==void 0)return t}if(e.key===`Enter`&&e.shiftKey&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&(St.current||Pt()))return e.type===`keydown`&&(e.preventDefault(),Pn(`\x1B[13;2u`)),!1;if(e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`q`){if(e.type===`keydown`){let e=Date.now();e>Ln.current?(Ln.current=e+2e3,ln(`Press Ctrl+Q again to kill this session for ALL participants`)):(Ln.current=0,Tn({type:`kill_session`}))}return!1}return(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`?(e.type===`keydown`&&(e.preventDefault(),vn()),!1):e.ctrlKey&&e.shiftKey&&(e.key===`c`||e.key===`v`)?!1:(e.ctrlKey&&!e.altKey&&e.metaKey,!0)});let s=new ResizeObserver(()=>{lt.current===`fit`&&(Qn(),e.refresh(0,e.rows-1),Zn())});e.__resizeObserver=s;let c=nt.current.closest(`.terminal-scroll`);c&&s.observe(c);let l=()=>{let t=e.buffer.active;return{len:t.length,rows:e.rows,y:t.viewportY,base:t.baseY}},u=()=>{let t=_t.current,n=vt.current;if(!t||!n)return;let r=e.modes.mouseTrackingMode!==`none`||e.buffer.active.type===`alternate`,{len:i,rows:a,y:o}=l();if(r||i<=a+1){t.classList.remove(`visible`);return}t.classList.add(`visible`);let s=t.clientHeight,c=Math.max(24,Math.round(a/i*s)),u=Math.round(o/Math.max(1,i-a)*(s-c));n.style.height=c+`px`,n.style.transform=`translateY(`+u+`px)`};e.onScroll(()=>{let{y:t,base:n}=l();V.current=t<n;let r=Gn.current>0,i=Kn.current>0&&performance.now()-Kn.current>600;if(Gn.current=t,t===0&&r&&i&&qn.current){let t=Ot.current;t&&!Wn.current.has(t)&&(Wn.current.add(t),Jn.current={room:t,oldLen:e.buffer.active.length},qn.current=!1,k(e=>e+1))}u()});let d=window.setInterval(u,700);e.__overlayScrollbarCleanup=()=>window.clearInterval(d);let f=vt.current;f&&f.addEventListener(`pointerdown`,t=>{t.preventDefault(),t.stopPropagation();let n=_t.current;if(!n)return;n.classList.add(`dragging`);let r=t.clientY,i=l().y,a=t=>{let{len:a,rows:o}=l(),s=n.clientHeight,c=Math.max(24,Math.round(o/a*s)),u=i+(t.clientY-r)/Math.max(1,s-c)*(a-o);e.scrollToLine(Math.max(0,Math.min(a-o,Math.round(u))))},o=()=>{n.classList.remove(`dragging`),window.removeEventListener(`pointermove`,a),window.removeEventListener(`pointerup`,o)};window.addEventListener(`pointermove`,a),window.addEventListener(`pointerup`,o)})},[o]),(0,_.useEffect)(()=>{if(!L||!re)return;let e=B.current,t=nt.current?.closest(`.terminal-scroll`);if(!e||!t)return;if(e.__touchCleanup&&=(e.__touchCleanup(),null),_e){let n=()=>{let t=e._core,n=t?._renderService?.dimensions?.css?.cell?.width,r=t?._renderService?.dimensions?.css?.cell?.height;return{w:n&&n>0?n:9,h:r&&r>0?r:18}},r=()=>{let e=nt.current?.querySelector(`.xterm-screen`);return e?e.getBoundingClientRect():null},i=e=>{let t=r();if(!t)return null;let i=n(),a=Math.floor((e.clientX-t.left)/i.w),o=Math.floor((e.clientY-t.top)/i.h);return{col:Math.max(0,a),row:Math.max(0,o)}},a=null,o=null,s=!1,c=()=>{o!==null&&(clearInterval(o),o=null)},l=(t,n,r,i)=>{let a=e.buffer.active,o=a.viewportY+t,s=a.viewportY+r,c,l,u,d;if(o<s||o===s&&n<=i?(c=o,l=n,u=s,d=i):(c=s,l=i,u=o,d=n),c===u){let t=Math.max(1,d-l+1);e.select(l,c,t)}else e.selectLines(c,u)},u=t=>{if(t.touches.length!==1)return;t.cancelable&&t.preventDefault();let n=i(t.touches[0]);n&&(e.clearSelection(),a=n,t.touches[0].clientY,s=!1)},d=t=>{if(t.touches.length!==1||!a)return;t.cancelable&&t.preventDefault(),s=!0;let u=t.touches[0];u.clientY;let d=i(u);if(!d)return;let f=d.col;l(a.row,a.col,d.row,d.col);let p=r();if(!p)return;let m=n().h*2;c(),u.clientY<p.top+m?o=window.setInterval(()=>{e.scrollLines(-1),a&&(a.row+=1,l(a.row,a.col,0,f))},60):u.clientY>p.bottom-m&&(o=window.setInterval(()=>{e.scrollLines(1),a&&(--a.row,l(a.row,a.col,e.rows-1,f))},60))},f=t=>{if(c(),s&&e.hasSelection()){let t=e.getSelection();t&&navigator.clipboard.writeText(t).then(()=>un(`Copied ${t.split(`
132
+ `).length} line(s)`),()=>un(`Copy failed`))}else e.clearSelection();a=null,s=!1};return t.addEventListener(`touchstart`,u,{passive:!1,capture:!0}),t.addEventListener(`touchmove`,d,{passive:!1,capture:!0}),t.addEventListener(`touchend`,f,{passive:!0,capture:!0}),t.addEventListener(`touchcancel`,f,{passive:!0,capture:!0}),e.__touchCleanup=()=>{c(),t.removeEventListener(`touchstart`,u,{capture:!0}),t.removeEventListener(`touchmove`,d,{capture:!0}),t.removeEventListener(`touchend`,f,{capture:!0}),t.removeEventListener(`touchcancel`,f,{capture:!0})},()=>{e.__touchCleanup&&=(e.__touchCleanup(),null)}}let n=0,r=0,i=[],a=0,o=0,s=0,c=!0,l=0,u=0,d=null,f=!1,p=!1,m=0,h=0,g=0,_=0,v=()=>{let t=e._core?._renderService?.dimensions?.css?.cell?.height;return t&&t>0?t:18},y=e=>{Tn({type:`input`,data:e})},b=()=>bt.current&&xt.current,x=e=>{if(e===0)return;let t=B.current,n=Math.max(1,Math.floor((t?.cols||80)/2)),r=Math.max(1,Math.floor((t?.rows||24)/2)),i=`\x1b[<${e>0?65:64};${n};${r}M`.repeat(Math.min(Math.abs(e),40));Tn({type:`input`,data:i})},ee=e=>({x:(e[0].clientX+e[1].clientX)/2,y:(e[0].clientY+e[1].clientY)/2}),S=.25,C=()=>{d!==null&&(cancelAnimationFrame(d),d=null),u=0},w=null,te=()=>{if(w=null,yt.current)if(b()){let e=Math.trunc(r/v());e!==0&&(x(e),r-=e*v())}else{let e=v()*3,t=Math.trunc(r/e);if(t!==0){let n=t>0?`\x1B[6~`:`\x1B[5~`;for(let e=0;e<Math.abs(t);e++)y(n);r-=t*e}}else{let t=Math.trunc(r/v());t!==0&&(e.scrollLines(t),r-=t*v())}},T=()=>{w===null&&(w=requestAnimationFrame(te))},E=()=>{if(Math.abs(u)<S){d=null;return}r+=u,te(),u*=.94,d=requestAnimationFrame(E)},ne=e=>{if(C(),e.cancelable&&e.preventDefault(),e.touches.length===2){p=!0;let t=ee(e.touches);g=t.x,_=t.y;let n=nt.current?.closest(`.terminal-scroll`);n&&(m=n.scrollLeft,h=n.scrollTop);return}if(e.touches.length!==1){p=!1,f=!1;return}p=!1,n=e.touches[0].clientY,l=Date.now(),r=0,i=[],f=!0,a=e.touches[0].clientX,o=e.touches[0].clientY,s=Date.now(),c=!1},D=e=>{if(e.touches.length===2){if(!p){p=!0;let t=ee(e.touches);g=t.x,_=t.y;let n=nt.current?.closest(`.terminal-scroll`);n&&(m=n.scrollLeft,h=n.scrollTop)}let t=ee(e.touches),n=g-t.x,r=_-t.y,i=nt.current?.closest(`.terminal-scroll`);i&&(i.scrollLeft=m+n,i.scrollTop=h+r),e.preventDefault();return}if(e.touches.length!==1)return;p&&(p=!1,f=!0);let t=e.touches[0].clientY,s=Date.now(),u=n-t,d=Math.max(1,s-l);!c&&(Math.abs(e.touches[0].clientX-a)>10||Math.abs(t-o)>10)&&(c=!0),d>0&&d<100&&(i.push(u/d),i.length>5&&i.shift()),e.preventDefault(),r+=u,T(),n=t,l=s},O=()=>{if(p){p=!1;return}if(!c&&Date.now()-s<400){c=!0;let e=B.current,t=nt.current?.querySelector(`.xterm-screen`);if(e&&t){let n=t.getBoundingClientRect(),r=Math.floor((a-n.left)/n.width*e.cols),i=Math.floor((o-n.top)/n.height*e.rows);if(r>=0&&r<e.cols&&i>=0&&i<e.rows){let t=Er(e.buffer.active.viewportY+i,r);t&&Sr({url:t,x:a,y:o})}}}if(f&&i.length>0&&(!yt.current||b())){let e=0;for(let t of i)Math.abs(t)>Math.abs(e)&&(e=t);u=e*16,Math.abs(u)>=S&&(d=requestAnimationFrame(E))}f=!1};return t.addEventListener(`touchstart`,ne,{passive:!1,capture:!0}),t.addEventListener(`touchmove`,D,{passive:!1,capture:!0}),t.addEventListener(`touchend`,O,{passive:!0,capture:!0}),t.addEventListener(`touchcancel`,O,{passive:!0,capture:!0}),e.__touchCleanup=()=>{C(),w!==null&&(cancelAnimationFrame(w),w=null),t.removeEventListener(`touchstart`,ne,{capture:!0}),t.removeEventListener(`touchmove`,D,{capture:!0}),t.removeEventListener(`touchend`,O,{capture:!0}),t.removeEventListener(`touchcancel`,O,{capture:!0})},()=>{e.__touchCleanup&&=(e.__touchCleanup(),null)}},[L,_e,re]),(0,_.useEffect)(()=>{if(!re||!L)return;let e=B.current;if(!e)return;let t=e._core?.viewport;if(t)return ot.current||={start:typeof t.handleTouchStart==`function`?t.handleTouchStart.bind(t):void 0,move:typeof t.handleTouchMove==`function`?t.handleTouchMove.bind(t):void 0},_e?(t.handleTouchStart=()=>{},t.handleTouchMove=()=>!0):ot.current&&(ot.current.start&&(t.handleTouchStart=ot.current.start),ot.current.move&&(t.handleTouchMove=ot.current.move)),()=>{ot.current&&(ot.current.start&&(t.handleTouchStart=ot.current.start),ot.current.move&&(t.handleTouchMove=ot.current.move))}},[re,L,_e]),(0,_.useEffect)(()=>{o||(ft.current=!1,dt.current&&=(window.clearTimeout(dt.current),null),$e.current?.close(),$e.current=null,rt.current.reset(),ut.current=0)},[o]),(0,_.useEffect)(()=>()=>{let e=B.current,t=e?.__resizeObserver;t&&t.disconnect(),e&&(e.__touchCleanup&&=(e.__touchCleanup(),null),e.__wheelCleanup&&=(e.__wheelCleanup(),null),e.__overlayScrollbarCleanup&&=(e.__overlayScrollbarCleanup(),null),e.dispose(),B.current=null,tt.current=null),ft.current=!1,dt.current&&window.clearTimeout(dt.current),$e.current?.close()},[]),(0,_.useEffect)(()=>{if(!Cg()||!o)return;let e=new URLSearchParams(window.location.search),t=e.get(`view`)===`wall`;if(Ge&&!t)e.set(`view`,`wall`),window.history.pushState({},``,window.location.pathname+`?`+e.toString());else if(!Ge&&t){e.delete(`view`);let t=e.toString();window.history.replaceState({},``,window.location.pathname+(t?`?`+t:``))}},[Ge]),(0,_.useEffect)(()=>{if(!o)return;let e=window.setInterval(()=>{if(document.hidden||Un.current)return;let e=B.current;if(e)try{let t=e.buffer.active;!V.current&&t.viewportY<t.baseY&&e.scrollToBottom(),e.refresh(0,e.rows-1)}catch{}},1400);return()=>window.clearInterval(e)},[o]),(0,_.useEffect)(()=>{if(!o)return;let e=()=>{document.hidden||Un.current||requestAnimationFrame(()=>Bn.current())};return document.addEventListener(`visibilitychange`,e),window.addEventListener(`focus`,e),window.addEventListener(`pageshow`,e),()=>{document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`focus`,e),window.removeEventListener(`pageshow`,e)}},[o]),(0,_.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get(`view`)===`wall`;Ke(e);let t=rg(),r=new URLSearchParams(window.location.search).get(`name`)??localStorage.getItem(`hay_name`)??n;if(!t){Cg()||s(null);return}a(t),s(e=>{let n=e?.name??r??`User`;return e?.room===t&&e.name===n?e:{name:n,room:t}})};return window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`popstate`,e)}},[n]);let[,rr]=(0,_.useState)(0);(0,_.useEffect)(()=>{if(m.length===0)return;let e=window.setInterval(()=>rr(e=>e+1),2e4);return()=>window.clearInterval(e)},[m.length]),(0,_.useEffect)(()=>{let e=()=>{ue(e=>({x:Math.max(0,Math.min(window.innerWidth-56,e.x)),y:Math.max(0,Math.min(window.innerHeight-56,e.y))}))};return window.addEventListener(`resize`,e),window.addEventListener(`orientationchange`,e),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`orientationchange`,e)}},[]);let ir=(0,_.useCallback)(async(e={})=>{let{showLoading:t=!0}=e;t&&De(!0);let n=++rn.current;try{let e=await(await fetch(`/api/sessions`)).json(),t=new Map;for(let n of e.sessions||[])t.set(n.name,{name:n.name,displayName:n.displayName||n.name,active:(e.active||[]).includes(n.name),starting:(e.starting||[]).includes(n.name),type:n.type,port:n.port,cwd:n.cwd,internalName:n.internalName||n.name,lastActivityAt:Number(n.lastActivityAt)||0,bellSeq:Number(n.bellSeq)||0,foregroundProcess:n.foregroundProcess,agentPermitted:n.agentPermitted===!0,createdBy:n.createdBy===`agent`?`agent`:`user`,createdVia:typeof n.createdVia==`string`?n.createdVia:null,cols:Number.isInteger(n.cols)?n.cols:void 0,rows:Number.isInteger(n.rows)?n.rows:void 0,tagline:typeof n.tagline==`string`?n.tagline:void 0,parked:n.parked===!0,archived:n.archived===!0,hasLocalCli:n.hasLocalCli===!0,folderId:typeof n.folderId==`string`?n.folderId:null});let r=new Set;for(let t of e.sessions||[])t.name&&r.add(String(t.name)),t.internalName&&r.add(String(t.internalName)),t.displayName&&r.add(String(t.displayName));for(let n of e.active||[])!r.has(n)&&!t.has(n)&&t.set(n,{name:n,displayName:n,active:!0,starting:!1,internalName:n,createdBy:`user`});let i=Eg(),a=Ot.current,o=document.visibilityState===`visible`,s=!1,c=Array.from(t.values()).map(e=>{let t=e.internalName||e.name,n=e.lastActivityAt||0,r=e.bellSeq||0,c=a!==null&&(e.internalName===a||e.name===a),l=i[t];return l?c&&o&&(l.out!==n||l.bell!==r)&&(l={out:n,bell:r},i[t]=l,s=!0):(l={out:n,bell:r},i[t]=l,s=!0),{...e,unread:!c&&n>l.out,bellUnseen:!c&&r>l.bell}});if(c.length>0){let e=new Set(c.map(e=>e.internalName||e.name));for(let t of Object.keys(i))e.has(t)||(delete i[t],s=!0)}if(s&&Dg(i),n!==rn.current)return;je(Array.isArray(e.folders)?e.folders.filter(e=>e&&e.id&&e.name).map(e=>({id:String(e.id),name:String(e.name)})):[]),Te(c),ke(!1),tn.current=!0,nn.current=Date.now()}catch(e){console.error(`Failed to fetch sessions:`,e),ke(!0)}finally{t&&De(!1)}},[]);Yn.current=ir,(0,_.useEffect)(()=>{if(A){let e=Date.now()-nn.current<=yg;(!tn.current||!e)&&ir({showLoading:!tn.current})}},[A,ir]),(0,_.useEffect)(()=>{ir()},[ir]),(0,_.useEffect)(()=>{if(!o)return;let e=window.setInterval(()=>ir({showLoading:!1}),5e3);return()=>window.clearInterval(e)},[o,ir]),(0,_.useEffect)(()=>{let e=()=>{document.visibilityState===`visible`&&(Ne(!1),ir({showLoading:!1}))};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[ir]);let ar=(0,_.useMemo)(()=>{let e=o?.room??null,t=!1,n=!1;for(let r of we)e&&(r.internalName===e||r.name===e)||(r.bellUnseen?t=!0:r.unread&&(n=!0));return{bell:t,output:n}},[we,o?.room]);(0,_.useEffect)(()=>{let e=c||o?.room||`hop`,t=Me||ar.bell;document.title=`${t?`● `:``}${e}`},[Me,ar.bell,c,o?.room]),(0,_.useEffect)(()=>{let e=sn.current,t={};for(let n of we){let r=n.internalName||n.name;if(t[r]=n.bellUnseen===!0,!R||!n.bellUnseen||e[r])continue;let i=n.bellSeq||0;(cn.current[r]??0)>=i||(cn.current[r]=i,dn(n.displayName,()=>sr(n)))}sn.current=t},[we,R]),(0,_.useEffect)(()=>{B.current&&(B.current.options.fontSize=Ye,lt.current===`fit`?(Qn(),Zn()):B.current.refresh(0,B.current.rows-1)),localStorage.setItem(`hay_font_size`,String(Ye))},[Ye]),(0,_.useEffect)(()=>{if(!L||!re||!pe||he<=0)return;let e=window.requestAnimationFrame(()=>{lt.current===`fit`&&(Qn(),Zn())});return()=>{window.cancelAnimationFrame(e)}},[L,re,pe,he]);let or=e=>{let t=e.internalName||e.name;if((o?.room??null)===t)return;let r=Eg();r[t]={out:e.lastActivityAt||0,bell:e.bellSeq||0},Dg(r),Tt.current=[],h([]),b(null),S(null),d(null),p(`connecting`),a(t),l(e.displayName||e.name),s(e=>({name:e?.name??n.trim()??`User`,room:t})),window.history.pushState({},``,ig(t)+`?view=wall`)},sr=e=>{let t=e.internalName||e.name,r=ig(t),i=o?.room??c,u=qe===`instant`&&e.type!==`port`;Rn.current=!0;let f=Eg();if(f[e.internalName||e.name]={out:e.lastActivityAt||0,bell:e.bellSeq||0},Dg(f),!u){window.location.href=r;return}if(i===t){j(!1);return}rt.current.reset(),Tt.current=[],h([]),b(null),S(null),d(null),p(`connecting`),a(t),l(e.displayName||e.name),s(e=>({name:e?.name??n.trim()??`User`,room:t})),window.history.pushState({},``,r),j(!1)};kt.current=sr,(0,_.useEffect)(()=>{if(!o||!Cg())return;let e=$e.current,t=!!e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING);if(Ge){if(t){ft.current=!1;try{e.close()}catch{}}}else ft.current=!0,Rn.current=!0,requestAnimationFrame(()=>Bn.current()),t||k(e=>e+1)},[Ge]),(0,_.useEffect)(()=>{if(L||!o||Ge||A||At||M||Re||z||zt!==`primary`)return;let e=window.setTimeout(()=>B.current?.focus(),30);return()=>window.clearTimeout(e)},[Ge,A,At,M,Re,z,o,zt]);let cr=e=>{if(e.preventDefault(),!n.trim()||!i.trim()){ln(`Enter a name and room to start.`);return}localStorage.setItem(`hay_name`,n.trim()),s({name:n.trim(),room:i.trim()})},lr=e=>{e.preventDefault();let t=Ie.trim();Fe(!1),!(!t||t===n)&&(localStorage.setItem(`hay_name`,t),r(t),s(e=>e&&{...e,name:t}),ln(`Display name set to ${t}`))},ur=async e=>{e.preventDefault();let t=Be.trim(),n=c||o?.room||``;if(!t||t===n){ze(!1);return}if(!/^[a-zA-Z0-9_-]+$/.test(t)){ln(`Only letters, numbers, - and _ allowed`);return}try{let e=await fetch(`/api/sessions/rename`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({oldName:n,newName:t})});if(!e.ok){let t=await e.json().catch(()=>({}));ln(t.error||`Rename failed`);return}ze(!1),ir({showLoading:!1})}catch{ln(`Rename failed`)}},dr=()=>{let e=c||o?.room||`this session`;window.confirm(`Kill session "${e}" for all participants? Its running process is terminated.`)&&(Tn({type:`kill_session`}),j(!1))},fr=async()=>{try{await navigator.clipboard.writeText(xn),ln(`Share link copied.`)}catch{ln(`Copy failed. Select the link manually.`)}},U=()=>{Tn({type:`toggle_collab`,enabled:!g})},pr=()=>{Tn({type:`take_control`})},mr=()=>{Tn({type:`release_control`})},hr=e=>{if(!e){xe(!1);return}xe(!0),Notification.permission!==`granted`&&Notification.requestPermission().then(e=>{e!==`granted`&&(ln(`Notifications are blocked by the browser`),xe(!1))})},gr=(e,t)=>{de.current={dragging:!1,startX:e,startY:t,startPosX:le.x,startPosY:le.y}},_r=(e,t)=>{if(!de.current)return;let n=e-de.current.startX,r=t-de.current.startY;(Math.abs(n)>5||Math.abs(r)>5)&&(de.current.dragging=!0),de.current.dragging&&ue({x:Math.max(0,Math.min(window.innerWidth-56,de.current.startPosX+n)),y:Math.max(0,Math.min(window.innerHeight-56,de.current.startPosY+r))})},vr=()=>{de.current&&!de.current.dragging&&(L&&Cg()?Ke(!0):j(!0)),de.current=null},yr=(0,_.useCallback)(()=>{me(e=>!e),setTimeout(()=>{lt.current===`fit`&&(Qn(),Zn())},100)},[]),br=(0,_.useCallback)(e=>{Pn(e)},[]),[xr,Sr]=(0,_.useState)(null),[Cr,wr]=(0,_.useState)(!1);(0,_.useEffect)(()=>{if(!Cg()||typeof window>`u`||!window.PublicKeyCredential||localStorage.getItem(`hay_passkey_nudge_done`)===`1`)return;let e=!1,t=window.setTimeout(async()=>{try{let t=await(await fetch(`/api/passkeys/login-options`,{method:`POST`})).json();!e&&t&&t.ok===!1&&wr(!0)}catch{}},4e3);return()=>{e=!0,window.clearTimeout(t)}},[]);let Tr=()=>{localStorage.setItem(`hay_passkey_nudge_done`,`1`),wr(!1)},Er=(0,_.useCallback)((e,t)=>{let n=B.current;if(!n)return null;let r=n.buffer.active,i=e;for(;i>0&&r.getLine(i)?.isWrapped;)i--;let a=``,o=-1;for(let s=i;s<r.length;s++){let c=r.getLine(s);if(!c||s>i&&!c.isWrapped)break;s===e&&(o=a.length+Math.min(t,n.cols-1)),a+=c.translateToString(!1)}if(o<0)return null;let s=/https?:\/\/[^\s"'`<>]+/g,c;for(;(c=s.exec(a))!==null;)if(o>=c.index&&o<=c.index+c[0].length)return c[0].replace(/[.,;:!?)\]}]+$/,``);return null},[]),Dr=(0,_.useCallback)(async()=>{let e=e=>Uint8Array.from(atob(e.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(Math.ceil(e.length/4)*4,`=`)),e=>e.charCodeAt(0)),t=e=>btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``);try{let n=await(await fetch(`/api/passkeys/register-options`,{method:`POST`})).json();if(!n.ok)throw Error(n.error||`Could not start enrollment`);let r=n.options;r.challenge=e(r.challenge),r.user.id=e(r.user.id),r.excludeCredentials=(r.excludeCredentials||[]).map(t=>({...t,id:e(t.id)}));let i=await navigator.credentials.create({publicKey:r}),a=i.response,o=await(await fetch(`/api/passkeys/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({token:n.token,response:{id:i.id,rawId:t(i.rawId),type:i.type,authenticatorAttachment:i.authenticatorAttachment||void 0,clientExtensionResults:i.getClientExtensionResults(),response:{clientDataJSON:t(a.clientDataJSON),attestationObject:t(a.attestationObject),transports:a.getTransports?.()||[]}}})})).json();un(o.ok?`Passkey added — biometric sign-in enabled on this domain`:`Passkey failed: ${o.error||`verification failed`}`,4e3)}catch(e){if(e.name===`NotAllowedError`)return;un(`Passkey: ${e.message}`,4e3)}},[]);(0,_.useEffect)(()=>{if(o||!Cg())return;ir({showLoading:!1});let e=window.setInterval(()=>{document.hidden||ir({showLoading:!1})},5e3),t=()=>{document.hidden||ir({showLoading:!1})};return document.addEventListener(`visibilitychange`,t),()=>{window.clearInterval(e),document.removeEventListener(`visibilitychange`,t)}},[o]),(0,_.useEffect)(()=>{if(!o||!Cg())return;let e=e=>{let t=[...Mt.current].filter(e=>e.type!==`port`).sort((e,t)=>(e.displayName||e.name).localeCompare(t.displayName||t.name));if(t.length<2)return;let n=t[(t.findIndex(e=>e.name===Ot.current||e.internalName===Ot.current)+e+t.length)%t.length];n&&kt.current?.(n)},t=t=>{if(!($h?t.metaKey&&!t.ctrlKey&&!t.altKey:t.ctrlKey&&t.shiftKey&&!t.metaKey&&!t.altKey)){t.key===`Escape`&&(Ft.current||It.current)&&(t.preventDefault(),t.stopPropagation(),j(!1),jt(!1));return}let n=t.key.toLowerCase(),r=t.shiftKey,i=()=>{t.preventDefault(),t.stopPropagation()};if(n===`k`&&(!$h||!r)){i(),Ke(e=>!e);return}if(n===`j`){i(),e(r?-1:1);return}if(n===`,`){i(),j(e=>!e);return}if(n===`/`||r&&n===`?`){i(),jt(e=>!e);return}if(r&&n===`e`){let e=$t(Jt.current).filter(e=>e!==`primary`),t=Vt.current===`primary`?e.length===1?e[0]:null:Vt.current;t&&(i(),Qt.current.swapPaneWithPrimary(t));return}if(n===`]`||n===`[`){let e=$t(Jt.current);if(e.length>1){i();let t=Math.max(0,e.indexOf(Vt.current));Bt(e[(t+(n===`]`?1:-1)+e.length)%e.length])}return}if(n===`\\`||n===`|`){i(),Qt.current.splitAndPick(r||n===`|`?`col`:`row`);return}if(r&&n===`k`&&Vt.current!==`primary`){i(),Qt.current.closePane(Vt.current);return}if($h&&!r){if(n===`=`||n===`+`){i(),Xe(e=>Math.min(24,e+1));return}if(n===`-`){i(),Xe(e=>Math.max(8,e-1));return}if(n===`0`){i(),Xe(14);return}}};return window.addEventListener(`keydown`,t,!0),()=>window.removeEventListener(`keydown`,t,!0)},[o]);let Or=L?{"--mobile-keyboard-height":`${pe?he:0}px`}:void 0;return(0,$.jsxs)(`div`,{className:`app`,children:[(0,$.jsxs)(`header`,{className:`topbar`,children:[(0,$.jsx)(`div`,{className:`brand`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`p`,{className:`brand-title`,children:[Cg()?`hop`:`hay`,(0,$.jsx)(`span`,{className:`brand-cursor`,"aria-hidden":`true`})]}),(0,$.jsx)(`p`,{className:`brand-subtitle`,children:Cg()?`terminals for humans and agents.`:`Collaborative terminal sharing for Hop.`})]})}),(0,$.jsxs)(`div`,{className:`presence-strip`,children:[Sn.map(e=>(0,$.jsxs)(`div`,{className:`presence-chip ${e.id===ee?`self`:``}`,title:`${e.name} · ${og(e)}`,children:[(0,$.jsx)(`span`,{className:`presence-dot`,style:{backgroundColor:e.color}}),(0,$.jsx)(`span`,{className:`presence-name`,children:e.name}),!g&&y===e.id&&(0,$.jsx)(`span`,{className:`presence-control`,title:`Has control`,children:`control`}),(0,$.jsx)(`span`,{className:`presence-status ${og(e)}`,children:og(e)})]},e.id)),Sn.length===0&&(0,$.jsx)(`span`,{className:`presence-empty`,children:`No viewers yet`})]}),!L&&o&&Cg()&&(0,$.jsxs)(`div`,{className:`topbar-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`topbar-sessions-btn`,title:`Sessions (${$h?`⌘K`:`Ctrl+Shift+K`})`,onClick:()=>Ke(!0),children:[`Sessions`,(0,$.jsx)(`kbd`,{children:$h?`⌘K`:`⌃⇧K`})]}),(0,$.jsx)(`button`,{type:`button`,className:`topbar-sessions-btn`,"aria-label":`Session settings`,title:`Session settings`,onClick:()=>j(!0),children:(0,$.jsxs)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,$.jsx)(`circle`,{cx:`12`,cy:`12`,r:`3`}),(0,$.jsx)(`path`,{d:`M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.01a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51h.01a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.01a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z`})]})})]})]}),!o&&Cg()?(0,$.jsxs)(`main`,{className:`hub`,children:[(0,$.jsx)(Xh,{open:!0,sessions:we,currentRoom:null,dismissable:!1,folders:Ae,onClose:()=>{},onSwitch:e=>{window.location.href=ig(e.displayName||e.name)},onRefresh:()=>ir({showLoading:!1}),onNotice:un,tileWsBase:ag(),userName:n,terminalTheme:dg(Se)}),te&&(0,$.jsx)(`div`,{className:`terminal-toast`,role:`status`,"aria-live":`polite`,children:te})]}):o?(0,$.jsxs)(`main`,{className:`session${L&&pe?` has-keyboard`:``}${_e?` selection-mode`:``}`,style:Or,children:[f!==`connected`&&f!==`idle`&&(0,$.jsxs)(`div`,{className:`connection-banner${f===`ended`?` ended`:``}`,role:`status`,"aria-live":`polite`,children:[(0,$.jsx)(`span`,{children:f===`connecting`?`Connecting…`:f===`ended`?`Session ended`:`Disconnected — reconnecting…`}),(f===`disconnected`||f===`ended`)&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>k(e=>e+1),children:`Reconnect now`})]}),(0,$.jsxs)(`button`,{type:`button`,"aria-label":`Open menu`,className:`drawer-toggle`,style:{left:le.x,top:le.y,bottom:`auto`},onMouseDown:e=>gr(e.clientX,e.clientY),onMouseMove:e=>_r(e.clientX,e.clientY),onMouseUp:vr,onMouseLeave:vr,onTouchStart:e=>gr(e.touches[0].clientX,e.touches[0].clientY),onTouchMove:e=>_r(e.touches[0].clientX,e.touches[0].clientY),onTouchEnd:vr,children:[(0,$.jsxs)(`svg`,{width:`22`,height:`22`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[(0,$.jsx)(`line`,{x1:`4`,y1:`6`,x2:`20`,y2:`6`}),(0,$.jsx)(`circle`,{cx:`9`,cy:`6`,r:`2`,fill:`currentColor`}),(0,$.jsx)(`line`,{x1:`4`,y1:`12`,x2:`20`,y2:`12`}),(0,$.jsx)(`circle`,{cx:`15`,cy:`12`,r:`2`,fill:`currentColor`}),(0,$.jsx)(`line`,{x1:`4`,y1:`18`,x2:`20`,y2:`18`}),(0,$.jsx)(`circle`,{cx:`11`,cy:`18`,r:`2`,fill:`currentColor`})]}),(ar.bell||ar.output)&&(0,$.jsx)(`span`,{className:`fab-attention${ar.bell?` bell`:``}`,"aria-hidden":`true`})]}),A&&(0,$.jsx)(`div`,{className:`drawer-overlay`,onClick:()=>j(!1)}),(0,$.jsxs)(`section`,{className:`controls ${A?`open`:``}`,children:[(0,$.jsx)(`button`,{type:`button`,"aria-label":`Close menu`,className:`drawer-close`,onClick:()=>j(!1),children:`✕`}),(0,$.jsxs)(`div`,{className:`room-info`,children:[(0,$.jsx)(`p`,{className:`room-label`,children:`Session`}),Re?(0,$.jsxs)(`form`,{className:`inline-edit`,onSubmit:ur,children:[(0,$.jsx)(`input`,{value:Be,onChange:e=>Ve(e.target.value),maxLength:64,autoFocus:!0,"aria-label":`New session name`}),(0,$.jsx)(`button`,{type:`submit`,children:`Save`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>ze(!1),children:`✕`})]}):(0,$.jsxs)(`div`,{className:`room-title-row`,children:[(0,$.jsx)(`h2`,{children:c||o.room}),Cg()&&(0,$.jsx)(`button`,{type:`button`,className:`icon-btn-inline`,title:`Rename session`,"aria-label":`Rename session`,onClick:()=>{Ve(c||o.room),ze(!0)},children:`✎`})]}),u&&(0,$.jsx)(`p`,{className:`room-cwd`,title:u,children:pg(u)}),(0,$.jsx)(`p`,{className:`room-meta`,children:f===`connected`?`Live`:f===`connecting`?`Connecting`:f===`ended`?`Ended`:`Offline`})]}),(0,$.jsxs)(`div`,{className:`quick-actions`,children:[(0,$.jsxs)(`div`,{className:`quick-group`,children:[L&&(0,$.jsx)(`button`,{type:`button`,className:`quick-btn icon-btn`,onClick:()=>{yr(),j(!1)},title:pe?`Hide keyboard`:`Show keyboard`,"aria-label":pe?`Hide keyboard`:`Show keyboard`,children:(0,$.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`rect`,{x:`2`,y:`4`,width:`20`,height:`14`,rx:`2`}),(0,$.jsx)(`path`,{d:`M6 8h.01M10 8h.01M14 8h.01M18 8h.01M6 12h.01M10 12h.01M14 12h.01M18 12h.01M8 16h8`})]})}),(0,$.jsx)(`button`,{type:`button`,className:`quick-btn icon-btn`,onClick:fr,title:`Copy share link`,"aria-label":`Copy share link`,children:(0,$.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`path`,{d:`M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71`}),(0,$.jsx)(`path`,{d:`M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71`})]})}),L&&(0,$.jsx)(`button`,{type:`button`,className:`quick-btn icon-btn`,title:`Find in scrollback`,"aria-label":`Find in terminal`,onClick:()=>{j(!1),vn()},children:(0,$.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`circle`,{cx:`11`,cy:`11`,r:`7`}),(0,$.jsx)(`path`,{d:`M21 21l-4.3-4.3`})]})})]}),(0,$.jsxs)(`div`,{className:`quick-group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,onClick:()=>{Qn(),Zn()},children:`Fit`}),L&&Cg()?(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,onClick:()=>{j(!1),Ke(!0)},children:`Sessions`}):(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,onClick:()=>{window.open(`/sessions.html`,`_blank`)},children:`Manage`}),(0,$.jsx)(`button`,{type:`button`,className:`quick-btn danger`,onClick:dr,children:`Kill`}),(f===`disconnected`||f===`ended`)&&(0,$.jsx)(`button`,{type:`button`,className:`quick-btn primary`,onClick:()=>k(e=>e+1),children:`Reconnect`})]})]}),(0,$.jsxs)(`div`,{className:`drawer-group`,children:[(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Name`}),Pe?(0,$.jsxs)(`form`,{className:`inline-edit`,onSubmit:lr,children:[(0,$.jsx)(`input`,{value:Ie,onChange:e=>Le(e.target.value),maxLength:24,autoFocus:!0,"aria-label":`Display name`}),(0,$.jsx)(`button`,{type:`submit`,children:`Save`})]}):(0,$.jsxs)(`button`,{type:`button`,className:`name-edit-toggle`,title:`Change your display name`,onClick:()=>{Le(n),Fe(!0)},children:[n,` `,(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`✎`})]})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Control`}),(0,$.jsx)(`span`,{className:`control-state`,children:g?`Everyone can type`:y===ee?`You have control`:Cn?`Locked by ${Cn}`:`Locked`})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Redraw`}),(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,title:`Repaint the screen — rebuilds local glyphs and, in apps like Claude, asks the app itself to repaint (what a scroll does)`,onClick:()=>Hn.current(),children:`Redraw screen`})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Typing`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:g?`active`:``,onClick:()=>{g||U()},children:`Everyone`}),(0,$.jsx)(`button`,{type:`button`,className:g?``:`active`,onClick:()=>{g&&U()},children:`One user`})]})]}),!g&&(0,$.jsx)(`div`,{className:`drawer-row`,children:y===ee?(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,onClick:mr,children:`Release control`}):(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,onClick:pr,children:`Take control`})})]}),(0,$.jsxs)(`div`,{className:`drawer-group`,children:[(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Theme`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:Se===`system`?`active`:``,onClick:()=>Ce(`system`),children:`Auto`}),(0,$.jsx)(`button`,{type:`button`,className:Se===`light`?`active`:``,onClick:()=>Ce(`light`),children:`Light`}),(0,$.jsx)(`button`,{type:`button`,className:Se===`dark`?`active`:``,onClick:()=>Ce(`dark`),children:`Dark`})]})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Font`}),(0,$.jsxs)(`div`,{className:`font-size-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>Xe(e=>Math.max(8,e-1)),children:`−`}),(0,$.jsxs)(`span`,{children:[Ye,`px`]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>Xe(e=>Math.min(24,e+1)),children:`+`})]})]}),L&&(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Touch`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:_e?``:`active`,onClick:()=>ve(!1),children:`Scroll`}),(0,$.jsx)(`button`,{type:`button`,className:_e?`active`:``,onClick:()=>ve(!0),children:`Select`})]})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Copy`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>bn(fn(),`Visible text`),children:`Screen`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>bn(pn(),`Full buffer`),children:`All`})]})]})]}),(0,$.jsxs)(`details`,{className:`drawer-details`,children:[(0,$.jsx)(`summary`,{children:`More settings`}),(0,$.jsxs)(`div`,{className:`drawer-group`,children:[Cg()&&typeof window<`u`&&`PublicKeyCredential`in window&&(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Passkey`}),(0,$.jsx)(`button`,{type:`button`,className:`quick-btn`,onClick:Dr,children:`Add Touch ID / passkey`})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`View`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:Ze===`fit`?`active`:``,onClick:()=>Qe(`fit`),children:`Auto-fit`}),(0,$.jsx)(`button`,{type:`button`,className:Ze===`full`?`active`:``,onClick:()=>Qe(`full`),children:`Manual`})]})]}),(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Switch`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:qe===`page`?`active`:``,onClick:()=>Je(`page`),children:`Page`}),(0,$.jsx)(`button`,{type:`button`,className:qe===`instant`?`active`:``,onClick:()=>Je(`instant`),children:`Instant`})]})]}),tg&&(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Notify`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:R?``:`active`,onClick:()=>hr(!1),children:`Off`}),(0,$.jsx)(`button`,{type:`button`,className:R?`active`:``,onClick:()=>hr(!0),children:`On`})]})]}),L&&eg&&(0,$.jsxs)(`div`,{className:`drawer-row`,children:[(0,$.jsx)(`label`,{children:`Haptics`}),(0,$.jsxs)(`div`,{className:`view-mode-buttons`,children:[(0,$.jsx)(`button`,{type:`button`,className:ye?`active`:``,onClick:()=>be(!0),children:`On`}),(0,$.jsx)(`button`,{type:`button`,className:ye?``:`active`,onClick:()=>be(!1),children:`Off`})]})]})]})]}),C&&(0,$.jsx)(`p`,{className:`notice`,role:`status`,"aria-live":`polite`,children:C}),(0,$.jsxs)(`button`,{type:`button`,className:`quick-btn drawer-sessions-btn`,onClick:()=>{j(!1),Ke(!0)},children:[`Sessions`,!L&&(0,$.jsx)(`kbd`,{style:{marginLeft:8},children:$h?`⌘K`:`⌃⇧K`})]}),(0,$.jsxs)(`p`,{className:`build-stamp`,children:[`build `,`e688018 · 2026-08-04`]})]}),(()=>{let e=()=>(0,$.jsxs)(`section`,{inert:Ge,style:Ge?{visibility:`hidden`}:void 0,className:`terminal${f===`disconnected`||f===`ended`?` degraded`:``}`,children:[(0,$.jsxs)(`div`,{className:`terminal-frame`,onClick:()=>{L||B.current?.focus()},onDragEnter:e=>{Array.from(e.dataTransfer?.types||[]).includes(`Files`)&&(e.preventDefault(),On.current+=1,Dn(!0))},onDragOver:e=>e.preventDefault(),onDragLeave:()=>{On.current>0&&--On.current===0&&Dn(!1)},onDrop:e=>{if(e.preventDefault(),On.current=0,Dn(!1),(e.dataTransfer?.files?.length||0)>0){ln(Wm(kn));return}let t=e.dataTransfer?.getData(`text/plain`);t&&B.current?.paste(t)},children:[(0,$.jsx)(`div`,{className:`terminal-scroll`,children:(0,$.jsx)(`div`,{className:`terminal-inner`,ref:nt})}),!L&&(0,$.jsx)(`div`,{className:`term-scrollbar`,ref:_t,"aria-hidden":`true`,children:(0,$.jsx)(`div`,{className:`term-scrollbar-thumb`,ref:vt})}),jn&&(0,$.jsxs)(`div`,{className:`voice-overlay`,"aria-hidden":`true`,children:[(0,$.jsx)(`span`,{className:`voice-dot`}),(0,$.jsx)(`span`,{className:jn.interim?`voice-text`:`voice-text muted`,children:jn.interim||`Listening… release Space to insert`})]}),En&&(0,$.jsx)(`div`,{className:`terminal-drop-overlay`,"aria-hidden":`true`,children:(0,$.jsx)(`span`,{children:Wm(kn)})}),L&&f===`connecting`&&(0,$.jsxs)(`div`,{className:`terminal-loading`,role:`status`,"aria-live":`polite`,children:[(0,$.jsx)(Og,{}),(0,$.jsx)(`span`,{className:`terminal-loading-label`,children:`Loading session…`})]}),M&&(0,$.jsxs)(`div`,{className:`terminal-find`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`input`,{ref:ce,className:`terminal-find-input`,placeholder:`Find in scrollback…`,value:ie,onChange:e=>{ae(e.target.value),gn(e.target.value)},onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),_n(e.shiftKey?-1:1)):e.key===`Escape`&&(e.preventDefault(),yn())}}),(0,$.jsx)(`span`,{className:`terminal-find-count`,children:oe.total>0?`${oe.index}/${oe.total}`:ie?`0/0`:``}),(0,$.jsx)(`button`,{type:`button`,className:`terminal-find-btn`,onClick:()=>_n(-1),"aria-label":`Previous match`,children:`↑`}),(0,$.jsx)(`button`,{type:`button`,className:`terminal-find-btn`,onClick:()=>_n(1),"aria-label":`Next match`,children:`↓`}),(0,$.jsx)(`button`,{type:`button`,className:`terminal-find-btn`,onClick:yn,"aria-label":`Close search`,children:`✕`})]})]}),(0,$.jsxs)(`div`,{className:`terminal-footer`,children:[(0,$.jsx)(`span`,{className:`footer-chip`,children:c||o.room}),u?(0,$.jsx)(`span`,{className:`footer-cwd`,children:u}):null,(0,$.jsx)(`span`,{className:`footer-spacer`}),f===`connected`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,className:`footer-find-toggle`,"aria-label":`Find in terminal`,onClick:vn,children:[$h?`⌘F`:`Ctrl+F`,` find`]}),!L&&(0,$.jsxs)(`button`,{type:`button`,className:`footer-find-toggle`,"aria-label":`Keyboard shortcuts`,onClick:()=>jt(!0),children:[$h?`⌘/`:`Ctrl+Shift+/`,` keys`]}),(0,$.jsx)(`button`,{type:`button`,className:`footer-find-toggle`,"aria-label":`Redraw the screen`,title:`Repaint the screen — rebuilds local glyphs and, in apps like Claude, asks the app itself to repaint (what a scroll does)`,onClick:()=>Hn.current(),children:`redraw`}),(0,$.jsx)(`span`,{title:Sn.map(e=>e.name).join(`, `),children:(()=>{let e=Sn.find(e=>e.id!==ee&&e.typing);return e?`${e.name} is typing…`:`${Sn.length} viewer${Sn.length===1?``:`s`}`})()})]}):f===`idle`?(0,$.jsx)(`span`,{children:`awaiting connection`}):f===`ended`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`ended-label`,children:`session ended`}),(0,$.jsx)(`button`,{type:`button`,className:`footer-reconnect`,onClick:()=>k(e=>e+1),children:`Reconnect`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`reconnecting`,children:[`⟳ `,f===`connecting`?`Connecting…`:`Reconnecting…`]}),(0,$.jsx)(`button`,{type:`button`,className:`footer-reconnect`,onClick:()=>k(e=>e+1),children:`Reconnect now`})]}),(0,$.jsx)(`span`,{className:`footer-dot ${f}`,"aria-hidden":`true`,children:`●`})]})]}),t=e=>(0,$.jsx)(`div`,{className:`pane-divider`,onPointerDown:t=>{let n=t.currentTarget.parentElement;n&&(en.current={id:e.id,dir:e.dir,rect:n.getBoundingClientRect()},t.currentTarget.setPointerCapture(t.pointerId))},onPointerMove:t=>{let n=en.current;if(!n||n.id!==e.id)return;let r=n.dir===`row`?(t.clientX-n.rect.left)/Math.max(1,n.rect.width):(t.clientY-n.rect.top)/Math.max(1,n.rect.height);qt(n.id,Math.min(.85,Math.max(.15,r)))},onPointerUp:()=>{en.current=null}},`div-${e.id}`),r=i=>{if(i.kind===`leaf`){if(i.session===null)return(0,$.jsx)(`div`,{className:`primary-pane-wrap`,onMouseDownCapture:()=>Bt(`primary`),children:e()},`primary`);if(i.session===``)return(0,$.jsxs)(`div`,{className:`empty-pane${zt===i.id?` focused`:``}`,onMouseDown:()=>Bt(i.id),children:[(0,$.jsxs)(`button`,{type:`button`,className:`empty-pane-pick`,onClick:()=>{Bt(i.id),Ht.current=i.id,Ke(!0)},children:[(0,$.jsx)(`span`,{className:`empty-pane-plus`,children:`+`}),(0,$.jsxs)(`span`,{children:[`Pick a session `,(0,$.jsx)(`kbd`,{children:$h?`⌘K`:`Ctrl+Shift+K`})]})]}),(0,$.jsx)(`button`,{type:`button`,className:`empty-pane-close`,"aria-label":`Close empty pane`,onClick:e=>{e.stopPropagation(),Kt(i.id)},children:`✕`})]},i.id);let t=(we.find(e=>e.name===i.session||e.internalName===i.session)?.foregroundProcess||``).replace(/^-/,``),r=/^\d+\.\d+\.\d+$/.test(t)?`claude`:t;return(0,$.jsx)(Zh,{sessionName:i.session,procLabel:r===`zsh`||r===`bash`?``:r,wsUrl:ag(),userName:n,cols:120,rows:30,fontSize:Ye,theme:dg(Se),focused:zt===i.id,onFocus:()=>Bt(i.id),onClose:()=>Kt(i.id),onPromote:()=>Zt(i.id)},i.id)}return(0,$.jsxs)(`div`,{className:`pane-split ${i.dir===`row`?`dir-row`:`dir-col`}`,children:[(0,$.jsx)(`div`,{className:`pane-cell`,style:{flexGrow:i.ratio,flexBasis:0},children:r(i.a)}),t(i),(0,$.jsx)(`div`,{className:`pane-cell`,style:{flexGrow:1-i.ratio,flexBasis:0},children:r(i.b)})]},i.id)},i=(0,$.jsx)(`div`,{className:`primary-pane-wrap`,onMouseDownCapture:()=>Bt(`primary`),children:e()},`primary`);if(L)return e();let a=Lt.kind===`split`?Lt:null;return(0,$.jsx)(`div`,{className:`pane-root`,inert:Ge,style:Ge?{visibility:`hidden`}:void 0,children:(0,$.jsxs)(`div`,{className:`pane-split ${a?.dir===`col`?`dir-col`:`dir-row`}`,children:[(0,$.jsx)(`div`,{className:`pane-cell`,style:{flexGrow:a?a.ratio:1,flexBasis:0},children:a&&a.a.kind!==`leaf`?r(a.a):i},`cell-a`),a&&t(a),a&&(0,$.jsx)(`div`,{className:`pane-cell`,style:{flexGrow:1-a.ratio,flexBasis:0},children:r(a.b)},`cell-b`)]},`rootsplit`)})})(),(0,$.jsx)(Xh,{open:Ge,sessions:we,currentRoom:f===`ended`?null:o.room,onClose:()=>{Ht.current=null,Ke(!1)},onSwitch:e=>{let t=Ht.current;t?(Ht.current=null,Wt(t,e.name)):sr(e),Ke(!1)},onRefresh:()=>ir({showLoading:!1}),onNotice:un,tileWsBase:ag(),onFocusSession:or,folders:Ae,userName:n,terminalTheme:dg(Se),onOpenSettings:()=>{Ke(!1),j(!0)},onToggleKeyboard:L?()=>{Ke(!1),yr()}:void 0,onFind:L?()=>{Ke(!1),vn()}:void 0}),At&&!L&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`drawer-overlay`,onClick:()=>jt(!1)}),(0,$.jsxs)(`div`,{className:`shortcut-help`,role:`dialog`,"aria-label":`Keyboard shortcuts`,children:[(0,$.jsx)(`h3`,{children:`Keyboard shortcuts`}),[[$h?`⌘K`:`Ctrl+Shift+K`,`session palette (type to filter, ↑↓, ⏎)`],[$h?`⌘J / ⌘⇧J`:`Ctrl+Shift+J / +⇧`,`next / previous session`],[$h?`⌘,`:`Ctrl+Shift+,`,`settings drawer`],[$h?`⌘F`:`Ctrl+Shift+F`,`find in terminal`],...$h?[[`⌘+ / ⌘− / ⌘0`,`terminal font size`]]:[],[`Ctrl+Shift+C / V`,`copy / paste`],[`Shift+PgUp / PgDn`,`scrollback`],[$h?`⌘\\ / ⌘⇧\\`:`Ctrl+Shift+\\ / +|`,`split pane — side / stacked`],[$h?`⌘⇧K`:`Ctrl+Shift+K`,`close focused pane`],[$h?`⌘] / ⌘[`:`Ctrl+Shift+] / [`,`next / previous pane`],[$h?`⌘⇧E`:`Ctrl+Shift+E`,`swap pane with primary`],[$h?`⌘/`:`Ctrl+Shift+/`,`this help`],[`Esc`,`close panels`]].map(([e,t])=>(0,$.jsxs)(`div`,{className:`shortcut-help-row`,children:[(0,$.jsx)(`kbd`,{children:e}),(0,$.jsx)(`span`,{children:t})]},e))]})]}),Cr&&(0,$.jsxs)(`div`,{className:`link-prompt passkey-nudge`,role:`dialog`,"aria-label":`Enable biometric sign-in`,children:[(0,$.jsx)(`span`,{className:`link-prompt-url`,children:$h?`Sign in with Touch ID / Face ID next time?`:`Sign in with a passkey next time?`}),(0,$.jsx)(`button`,{type:`button`,className:`link-prompt-open`,onClick:async()=>{Tr(),await Dr()},children:`Enable`}),(0,$.jsx)(`button`,{type:`button`,onClick:Tr,children:`Not now`})]}),xr&&(0,$.jsxs)(`div`,{className:`context-menu link-menu`,role:`menu`,"aria-label":`Open link`,style:{left:Math.max(8,Math.min(xr.x,window.innerWidth-268)),top:Math.max(8,Math.min(xr.y+10,window.innerHeight-150))},children:[(0,$.jsx)(`span`,{className:`context-menu-title`,children:xr.url}),(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:`context-menu-item`,onClick:()=>{window.open(xr.url,`_blank`,`noopener`),Sr(null)},children:(0,$.jsx)(`span`,{children:`Open link`})}),(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:`context-menu-item`,onClick:async()=>{try{await navigator.clipboard.writeText(xr.url),un(`Link copied`)}catch{un(`Clipboard denied — long-press the URL text instead`)}Sr(null)},children:(0,$.jsx)(`span`,{children:`Copy link`})}),(0,$.jsx)(`div`,{className:`context-menu-separator`,role:`separator`}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`context-menu-item`,onClick:()=>Sr(null),children:[(0,$.jsx)(`span`,{children:`Cancel`}),(0,$.jsx)(`kbd`,{children:`esc`})]})]}),L&&(0,$.jsx)(th,{onInput:br,visible:pe&&!Ge,onToggle:yr,onHeightChange:ge,hapticsEnabled:ye,onPasteFailed:()=>un(`Clipboard access denied — long-press the terminal to paste instead.`,3500)}),te&&(0,$.jsx)(`div`,{className:`terminal-toast`,role:`status`,"aria-live":`polite`,children:te})]}):(0,$.jsx)(`main`,{className:`join`,children:(0,$.jsxs)(`div`,{className:`join-card`,children:[(0,$.jsx)(`h1`,{children:`Terminal session`}),(0,$.jsx)(`p`,{children:`Connect to an existing session or start a new one.`}),(0,$.jsxs)(`form`,{onSubmit:cr,className:`join-form`,children:[(0,$.jsxs)(`label`,{children:[`Display name`,(0,$.jsx)(`input`,{value:n,onChange:e=>r(e.target.value),placeholder:`Casey`})]}),(0,$.jsxs)(`label`,{children:[`Session`,(0,$.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),placeholder:`my-session`})]}),(0,$.jsx)(`button`,{type:`submit`,className:`primary`,children:`Connect`})]})]})})]})},Ag=document.getElementById(`root`);Ag&&(0,v.createRoot)(Ag).render((0,$.jsx)(_.StrictMode,{children:(0,$.jsx)(kg,{})}));
133
+ //# sourceMappingURL=index-ClpDI5hp.js.map