termdock 1.4.166 → 1.4.167

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.
Files changed (67) hide show
  1. package/dist/client/assets/{ModelPreview-DWT2tm1L.js → ModelPreview-BzNON-7A.js} +1 -1
  2. package/dist/client/assets/{abnfDiagram-VRR7QNED-BPq4Vh9M.js → abnfDiagram-VRR7QNED-evEaZuvk.js} +1 -1
  3. package/dist/client/assets/{app-BtwmJgSV.js → app-qUUCmslY.js} +4 -4
  4. package/dist/client/assets/{arc-OUAZjByL.js → arc-Cc4T1vtw.js} +1 -1
  5. package/dist/client/assets/{architectureDiagram-ZJ3FMSHR-DmO96AZY.js → architectureDiagram-ZJ3FMSHR-CA5578rJ.js} +1 -1
  6. package/dist/client/assets/{blockDiagram-677ZJIJ3-DxDpO4dM.js → blockDiagram-677ZJIJ3-CCyKnFX-.js} +1 -1
  7. package/dist/client/assets/{c4Diagram-LMCZKHZV-DIwIh_Q7.js → c4Diagram-LMCZKHZV-SjGfmHL4.js} +1 -1
  8. package/dist/client/assets/channel-DsQFJkms.js +1 -0
  9. package/dist/client/assets/{chunk-2Q5K7J3B-CR7Yk02s.js → chunk-2Q5K7J3B-mc5fifzP.js} +1 -1
  10. package/dist/client/assets/{chunk-32BRIVSS-zlp8RRVe.js → chunk-32BRIVSS-CF9O6bVF.js} +1 -1
  11. package/dist/client/assets/{chunk-5VM5RSS4-B6SnnElY.js → chunk-5VM5RSS4-BZB3rwoP.js} +1 -1
  12. package/dist/client/assets/{chunk-EX3LRPZG-CVpxJm5m.js → chunk-EX3LRPZG-Bvw9RqK9.js} +1 -1
  13. package/dist/client/assets/{chunk-JWPE2WC7-Bx1RKca1.js → chunk-JWPE2WC7-CSO1rP6P.js} +1 -1
  14. package/dist/client/assets/{chunk-MOJQB5TN-BLsUJzeE.js → chunk-MOJQB5TN-Ds4d9rRG.js} +1 -1
  15. package/dist/client/assets/{chunk-RYQCIY6F-CAjkCOSv.js → chunk-RYQCIY6F-DaVQTtgL.js} +1 -1
  16. package/dist/client/assets/{chunk-V7JOEXUC-DFfMzjE-.js → chunk-V7JOEXUC-DXbeWqbK.js} +1 -1
  17. package/dist/client/assets/{chunk-VR4S4FIN-D_odjozS.js → chunk-VR4S4FIN-DEcVDuQJ.js} +1 -1
  18. package/dist/client/assets/{chunk-XXDRQBXY-BqLlYL-7.js → chunk-XXDRQBXY-CQVKeEmY.js} +1 -1
  19. package/dist/client/assets/classDiagram-OUVF2IWQ-BiBG6J-j.js +1 -0
  20. package/dist/client/assets/classDiagram-v2-EOCWNBFH-BiBG6J-j.js +1 -0
  21. package/dist/client/assets/{cose-bilkent-JH36ORCC-zYYUnASz.js → cose-bilkent-JH36ORCC-CweTDwez.js} +1 -1
  22. package/dist/client/assets/{cynefin-VYW2F7L2-BVFh9cvi.js → cynefin-VYW2F7L2-B_1TU70O.js} +1 -1
  23. package/dist/client/assets/{cynefinDiagram-TSTJHNR4-BAFhJpYw.js → cynefinDiagram-TSTJHNR4-DGjbhF2-.js} +1 -1
  24. package/dist/client/assets/{dagre-VKFMJZFB-YpWGHEaC.js → dagre-VKFMJZFB-CoLOphm4.js} +1 -1
  25. package/dist/client/assets/{diagram-FQU43EPY-Dzkl2KaY.js → diagram-FQU43EPY-CA9ZCbUn.js} +1 -1
  26. package/dist/client/assets/{diagram-G47NLZAW-TWad9KTI.js → diagram-G47NLZAW-BpR2yCdT.js} +1 -1
  27. package/dist/client/assets/{diagram-NH7WQ7WH-CWaE4WOu.js → diagram-NH7WQ7WH-DIZpypfO.js} +1 -1
  28. package/dist/client/assets/{diagram-OA4YK3LP-5FZDOuQj.js → diagram-OA4YK3LP-S9oRNVSL.js} +1 -1
  29. package/dist/client/assets/{diagram-WEI45ONY-BQ1bDV6w.js → diagram-WEI45ONY-Dv-XqhXv.js} +1 -1
  30. package/dist/client/assets/{ebnfDiagram-CCIWWBDH-Cxw2dqmp.js → ebnfDiagram-CCIWWBDH-C01FJ1W6.js} +1 -1
  31. package/dist/client/assets/{erDiagram-Q63AITRT-D_aDB9Bp.js → erDiagram-Q63AITRT-CMDd2A57.js} +1 -1
  32. package/dist/client/assets/{flowDiagram-23GEKE2U-DAyPxKNU.js → flowDiagram-23GEKE2U-Bu5kfa1t.js} +1 -1
  33. package/dist/client/assets/{ganttDiagram-NO4QXBWP-DfWOR_pi.js → ganttDiagram-NO4QXBWP-tfVpOhLu.js} +1 -1
  34. package/dist/client/assets/{gitGraphDiagram-IHSO6WYX-CM3unTUk.js → gitGraphDiagram-IHSO6WYX-CWM8oPLo.js} +1 -1
  35. package/dist/client/assets/{index-CVP3VHP_.css → index-C13NrW5y.css} +1 -1
  36. package/dist/client/assets/{infoDiagram-FWYZ7A6U-CkytCZOT.js → infoDiagram-FWYZ7A6U-CYuG0BfG.js} +1 -1
  37. package/dist/client/assets/{ishikawaDiagram-FXEZZL3T-BoLKOapy.js → ishikawaDiagram-FXEZZL3T-B_RdP3jn.js} +1 -1
  38. package/dist/client/assets/{journeyDiagram-5HDEW3XC-CQGDZTe2.js → journeyDiagram-5HDEW3XC-B2nObc7o.js} +1 -1
  39. package/dist/client/assets/{kanban-definition-HUTT4EX6-1UG86eTQ.js → kanban-definition-HUTT4EX6-7b37SN5M.js} +1 -1
  40. package/dist/client/assets/{linear-C_FzA_5a.js → linear-6VNI0WmU.js} +1 -1
  41. package/dist/client/assets/{mermaid.core-gG9bkaTg.js → mermaid.core-BMGv3SNm.js} +4 -4
  42. package/dist/client/assets/{mindmap-definition-LN4V7U3C-D1SCz73_.js → mindmap-definition-LN4V7U3C-DjuOw0RL.js} +1 -1
  43. package/dist/client/assets/{pegDiagram-2B236MQR-CLDMtrvm.js → pegDiagram-2B236MQR-CflwKQn8.js} +1 -1
  44. package/dist/client/assets/{pieDiagram-ENE6RG2P-DzaZe41u.js → pieDiagram-ENE6RG2P-Dp5j3kXt.js} +1 -1
  45. package/dist/client/assets/{quadrantDiagram-ABIIQ3AL-DdsZReCr.js → quadrantDiagram-ABIIQ3AL-XlkePQlX.js} +1 -1
  46. package/dist/client/assets/{railroadDiagram-RFXS5EU6-C1jgJbmW.js → railroadDiagram-RFXS5EU6-Dzq5SEwb.js} +1 -1
  47. package/dist/client/assets/{requirementDiagram-TGXJPOKE-DBADTKAI.js → requirementDiagram-TGXJPOKE-DQzmk2Py.js} +1 -1
  48. package/dist/client/assets/{sankeyDiagram-HTMAVEWB-CInXnchG.js → sankeyDiagram-HTMAVEWB-Yuu-Dn7F.js} +1 -1
  49. package/dist/client/assets/{sequenceDiagram-DBY2YBRQ-DSvuRTCM.js → sequenceDiagram-DBY2YBRQ-COlWE5v4.js} +1 -1
  50. package/dist/client/assets/{sizeCapture-X5ZJPWSS-DMlI2q45.js → sizeCapture-X5ZJPWSS-BAyWY8FR.js} +1 -1
  51. package/dist/client/assets/{stateDiagram-2N3HPSRC-Dq7tT19G.js → stateDiagram-2N3HPSRC-DE_g6UKp.js} +1 -1
  52. package/dist/client/assets/stateDiagram-v2-6OUMAXLB-CuFHnjvX.js +1 -0
  53. package/dist/client/assets/{swimlanes-5IMT3BWC-CADiiU3R.js → swimlanes-5IMT3BWC-SdPYQWPe.js} +2 -2
  54. package/dist/client/assets/swimlanesDiagram-G3AALYLV-f7M07VuB.js +8 -0
  55. package/dist/client/assets/{timeline-definition-FHXFAJF6-BuqyIhSt.js → timeline-definition-FHXFAJF6-CBpp3qTq.js} +1 -1
  56. package/dist/client/assets/{vennDiagram-L72KCM5P-BcIuauNX.js → vennDiagram-L72KCM5P-Cfm5mfc0.js} +1 -1
  57. package/dist/client/assets/{wardleyDiagram-EHGQE667-BaYI_ZiN.js → wardleyDiagram-EHGQE667-BgYh502A.js} +1 -1
  58. package/dist/client/assets/{xychartDiagram-FW5EYKEG-Ce-ZpeM3.js → xychartDiagram-FW5EYKEG-mAm5oI6Y.js} +1 -1
  59. package/dist/client/index.html +2 -2
  60. package/dist/client/sw.js +1 -1
  61. package/package.json +1 -1
  62. package/runtime-manifest.json +2 -2
  63. package/dist/client/assets/channel-oI8-banc.js +0 -1
  64. package/dist/client/assets/classDiagram-OUVF2IWQ-B8WTGybm.js +0 -1
  65. package/dist/client/assets/classDiagram-v2-EOCWNBFH-B8WTGybm.js +0 -1
  66. package/dist/client/assets/stateDiagram-v2-6OUMAXLB-BoKZubhb.js +0 -1
  67. package/dist/client/assets/swimlanesDiagram-G3AALYLV-B8B3fqSS.js +0 -8
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Ca-rq7yX.js","assets/react-XDCjal2T.js","assets/ModelPreview-DWT2tm1L.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/katex-55ZPZeOF.css","assets/mermaid.core-gG9bkaTg.js","assets/purify.es-CC4Brkr_.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Ca-rq7yX.js","assets/react-XDCjal2T.js","assets/ModelPreview-BzNON-7A.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/katex-55ZPZeOF.css","assets/mermaid.core-BMGv3SNm.js","assets/purify.es-CC4Brkr_.js"])))=>i.map(i=>d[i]);
2
2
  import{r as Kg,a as q_,g as B7}from"./react-XDCjal2T.js";import{b as x,R as I,r as Ni,a as K_}from"./dnd-BCFAPC0L.js";import{L as Y_,l as X_}from"./terminal-C7X98Amf.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var cx={exports:{}},Af={};var I5;function Z_(){if(I5)return Af;I5=1;var e=Kg(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,s=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(c,u,f){var p,g={},y=null,v=null;f!==void 0&&(y=""+f),u.key!==void 0&&(y=""+u.key),u.ref!==void 0&&(v=u.ref);for(p in u)r.call(u,p)&&!i.hasOwnProperty(p)&&(g[p]=u[p]);if(c&&c.defaultProps)for(p in u=c.defaultProps,u)g[p]===void 0&&(g[p]=u[p]);return{$$typeof:t,type:c,key:y,ref:v,props:g,_owner:s.current}}return Af.Fragment=n,Af.jsx=a,Af.jsxs=a,Af}var R5;function J_(){return R5||(R5=1,cx.exports=Z_()),cx.exports}var o=J_(),$p={},N5;function eL(){if(N5)return $p;N5=1;var e=q_();return $p.createRoot=e.createRoot,$p.hydrateRoot=e.hydrateRoot,$p}var tL=eL();const nL=B7(tL);function M5(e){return e!==null&&typeof e=="object"&&"constructor"in e&&e.constructor===Object}function Vy(e={},t={}){const n=["__proto__","constructor","prototype"];Object.keys(t).filter(r=>n.indexOf(r)<0).forEach(r=>{typeof e[r]>"u"?e[r]=t[r]:M5(t[r])&&M5(e[r])&&Object.keys(t[r]).length>0&&Vy(e[r],t[r])})}const F7={body:{},addEventListener(){},removeEventListener(){},activeElement:{blur(){},nodeName:""},querySelector(){return null},querySelectorAll(){return[]},getElementById(){return null},createEvent(){return{initEvent(){}}},createElement(){return{children:[],childNodes:[],style:{},setAttribute(){},getElementsByTagName(){return[]}}},createElementNS(){return{}},importNode(){return null},location:{hash:"",host:"",hostname:"",href:"",origin:"",pathname:"",protocol:"",search:""}};function gd(){const e=typeof document<"u"?document:{};return Vy(e,F7),e}const rL={document:F7,navigator:{userAgent:""},location:{hash:"",host:"",hostname:"",href:"",origin:"",pathname:"",protocol:"",search:""},history:{replaceState(){},pushState(){},go(){},back(){}},CustomEvent:function(){return this},addEventListener(){},removeEventListener(){},getComputedStyle(){return{getPropertyValue(){return""}}},Image(){},Date(){},screen:{},setTimeout(){},clearTimeout(){},matchMedia(){return{}},requestAnimationFrame(e){return typeof setTimeout>"u"?(e(),null):setTimeout(e,0)},cancelAnimationFrame(e){typeof setTimeout>"u"||clearTimeout(e)}};function va(){const e=typeof window<"u"?window:{};return Vy(e,rL),e}function sL(e=""){return e.trim().split(" ").filter(t=>!!t.trim())}function iL(e){const t=e;Object.keys(t).forEach(n=>{try{t[n]=null}catch{}try{delete t[n]}catch{}})}function O7(e,t=0){return setTimeout(e,t)}function ag(){return Date.now()}function oL(e){const t=va();let n;return t.getComputedStyle&&(n=t.getComputedStyle(e,null)),!n&&e.currentStyle&&(n=e.currentStyle),n||(n=e.style),n}function aL(e,t="x"){const n=va();let r,s,i;const a=oL(e);return n.WebKitCSSMatrix?(s=a.transform||a.webkitTransform,s.split(",").length>6&&(s=s.split(", ").map(c=>c.replace(",",".")).join(", ")),i=new n.WebKitCSSMatrix(s==="none"?"":s)):(i=a.MozTransform||a.OTransform||a.MsTransform||a.msTransform||a.transform||a.getPropertyValue("transform").replace("translate(","matrix(1, 0, 0, 1,"),r=i.toString().split(",")),t==="x"&&(n.WebKitCSSMatrix?s=i.m41:r.length===16?s=parseFloat(r[12]):s=parseFloat(r[4])),t==="y"&&(n.WebKitCSSMatrix?s=i.m42:r.length===16?s=parseFloat(r[13]):s=parseFloat(r[5])),s||0}function Hp(e){return typeof e=="object"&&e!==null&&e.constructor&&Object.prototype.toString.call(e).slice(8,-1)==="Object"}function lL(e){return typeof window<"u"&&typeof window.HTMLElement<"u"?e instanceof HTMLElement:e&&(e.nodeType===1||e.nodeType===11)}function el(...e){const t=Object(e[0]);for(let n=1;n<e.length;n+=1){const r=e[n];if(r!=null&&!lL(r)){const s=Object.keys(Object(r)).filter(i=>i!=="__proto__"&&i!=="constructor"&&i!=="prototype");for(let i=0,a=s.length;i<a;i+=1){const c=s[i],u=Object.getOwnPropertyDescriptor(r,c);u!==void 0&&u.enumerable&&(Hp(t[c])&&Hp(r[c])?r[c].__swiper__?t[c]=r[c]:el(t[c],r[c]):!Hp(t[c])&&Hp(r[c])?(t[c]={},r[c].__swiper__?t[c]=r[c]:el(t[c],r[c])):t[c]=r[c])}}}return t}function $d(e,t,n){e.style.setProperty(t,n)}function Q7({swiper:e,targetPosition:t,side:n}){const r=va(),s=-e.translate;let i=null,a;const c=e.params.speed;e.wrapperEl.style.scrollSnapType="none",r.cancelAnimationFrame(e.cssModeFrameID);const u=t>s?"next":"prev",f=(g,y)=>u==="next"&&g>=y||u==="prev"&&g<=y,p=()=>{a=new Date().getTime(),i===null&&(i=a);const g=Math.max(Math.min((a-i)/c,1),0),y=.5-Math.cos(g*Math.PI)/2;let v=s+y*(t-s);if(f(v,t)&&(v=t),e.wrapperEl.scrollTo({[n]:v}),f(v,t)){e.wrapperEl.style.overflow="hidden",e.wrapperEl.style.scrollSnapType="",setTimeout(()=>{e.wrapperEl.style.overflow="",e.wrapperEl.scrollTo({[n]:v})}),r.cancelAnimationFrame(e.cssModeFrameID);return}e.cssModeFrameID=r.requestAnimationFrame(p)};p()}function Vc(e,t=""){const n=va(),r=[...e.children];return n.HTMLSlotElement&&e instanceof HTMLSlotElement&&r.push(...e.assignedElements()),t?r.filter(s=>s.matches(t)):r}function cL(e,t){const n=[t];for(;n.length>0;){const r=n.shift();if(e===r)return!0;n.push(...r.children,...r.shadowRoot?r.shadowRoot.children:[],...r.assignedElements?r.assignedElements():[])}}function uL(e,t){const n=va();let r=t.contains(e);return!r&&n.HTMLSlotElement&&t instanceof HTMLSlotElement&&(r=[...t.assignedElements()].includes(e),r||(r=cL(e,t))),r}function lg(e){try{console.warn(e);return}catch{}}function l2(e,t=[]){const n=document.createElement(e);return n.classList.add(...Array.isArray(t)?t:sL(t)),n}function dL(e,t){const n=[];for(;e.previousElementSibling;){const r=e.previousElementSibling;t?r.matches(t)&&n.push(r):n.push(r),e=r}return n}function fL(e,t){const n=[];for(;e.nextElementSibling;){const r=e.nextElementSibling;t?r.matches(t)&&n.push(r):n.push(r),e=r}return n}function xu(e,t){return va().getComputedStyle(e,null).getPropertyValue(t)}function D5(e){let t=e,n;if(t){for(n=0;(t=t.previousSibling)!==null;)t.nodeType===1&&(n+=1);return n}}function hL(e,t){const n=[];let r=e.parentElement;for(;r;)n.push(r),r=r.parentElement;return n}function j5(e,t,n){const r=va();return e[t==="width"?"offsetWidth":"offsetHeight"]+parseFloat(r.getComputedStyle(e,null).getPropertyValue(t==="width"?"margin-right":"margin-top"))+parseFloat(r.getComputedStyle(e,null).getPropertyValue(t==="width"?"margin-left":"margin-bottom"))}function P5(e,t=""){typeof trustedTypes<"u"?e.innerHTML=trustedTypes.createPolicy("html",{createHTML:n=>n}).createHTML(t):e.innerHTML=t}let ux;function pL(){const e=va(),t=gd();return{smoothScroll:t.documentElement&&t.documentElement.style&&"scrollBehavior"in t.documentElement.style,touch:!!("ontouchstart"in e||e.DocumentTouch&&t instanceof e.DocumentTouch)}}function $7(){return ux||(ux=pL()),ux}let dx;function mL({userAgent:e}={}){const t=$7(),n=va(),r=n.navigator.platform,s=e||n.navigator.userAgent,i={ios:!1,android:!1},a=n.screen.width,c=n.screen.height,u=s.match(/(Android);?[\s\/]+([\d.]+)?/);let f=s.match(/(iPad)(?!\1).*OS\s([\d_]+)/);const p=s.match(/(iPod)(.*OS\s([\d_]+))?/),g=!f&&s.match(/(iPhone\sOS|iOS)\s([\d_]+)/),y=r==="Win32";let v=r==="MacIntel";const S=["1024x1366","1366x1024","834x1194","1194x834","834x1112","1112x834","768x1024","1024x768","820x1180","1180x820","810x1080","1080x810"];return!f&&v&&t.touch&&S.indexOf(`${a}x${c}`)>=0&&(f=s.match(/(Version)\/([\d.]+)/),f||(f=[0,1,"13_0_0"]),v=!1),u&&!y&&(i.os="android",i.android=!0),(f||g||p)&&(i.os="ios",i.ios=!0),i}function H7(e={}){return dx||(dx=mL(e)),dx}let fx;function gL(){const e=va(),t=H7();let n=!1;function r(){const c=e.navigator.userAgent.toLowerCase();return c.indexOf("safari")>=0&&c.indexOf("chrome")<0&&c.indexOf("android")<0}if(r()){const c=String(e.navigator.userAgent);if(c.includes("Version/")){const[u,f]=c.split("Version/")[1].split(" ")[0].split(".").map(p=>Number(p));n=u<16||u===16&&f<2}}const s=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(e.navigator.userAgent),i=r(),a=i||s&&t.ios;return{isSafari:n||i,needPerspectiveFix:n,need3dFix:a,isWebView:s}}function z7(){return fx||(fx=gL()),fx}function xL({swiper:e,on:t,emit:n}){const r=va();let s=null,i=null;const a=()=>{!e||e.destroyed||!e.initialized||(n("beforeResize"),n("resize"))},c=()=>{!e||e.destroyed||!e.initialized||(s=new ResizeObserver(p=>{i=r.requestAnimationFrame(()=>{const{width:g,height:y}=e;let v=g,S=y;p.forEach(({contentBoxSize:A,contentRect:C,target:L})=>{L&&L!==e.el||(v=C?C.width:(A[0]||A).inlineSize,S=C?C.height:(A[0]||A).blockSize)}),(v!==g||S!==y)&&a()})}),s.observe(e.el))},u=()=>{i&&r.cancelAnimationFrame(i),s&&s.unobserve&&e.el&&(s.unobserve(e.el),s=null)},f=()=>{!e||e.destroyed||!e.initialized||n("orientationchange")};t("init",()=>{if(e.params.resizeObserver&&typeof r.ResizeObserver<"u"){c();return}r.addEventListener("resize",a),r.addEventListener("orientationchange",f)}),t("destroy",()=>{u(),r.removeEventListener("resize",a),r.removeEventListener("orientationchange",f)})}function bL({swiper:e,extendParams:t,on:n,emit:r}){const s=[],i=va(),a=(f,p={})=>{const g=i.MutationObserver||i.WebkitMutationObserver,y=new g(v=>{if(e.__preventObserver__)return;if(v.length===1){r("observerUpdate",v[0]);return}const S=function(){r("observerUpdate",v[0])};i.requestAnimationFrame?i.requestAnimationFrame(S):i.setTimeout(S,0)});y.observe(f,{attributes:typeof p.attributes>"u"?!0:p.attributes,childList:e.isElement||(typeof p.childList>"u"?!0:p).childList,characterData:typeof p.characterData>"u"?!0:p.characterData}),s.push(y)},c=()=>{if(e.params.observer){if(e.params.observeParents){const f=hL(e.hostEl);for(let p=0;p<f.length;p+=1)a(f[p])}a(e.hostEl,{childList:e.params.observeSlideChildren}),a(e.wrapperEl,{attributes:!1})}},u=()=>{s.forEach(f=>{f.disconnect()}),s.splice(0,s.length)};t({observer:!1,observeParents:!1,observeSlideChildren:!1}),n("init",c),n("destroy",u)}var yL={on(e,t,n){const r=this;if(!r.eventsListeners||r.destroyed||typeof t!="function")return r;const s=n?"unshift":"push";return e.split(" ").forEach(i=>{r.eventsListeners[i]||(r.eventsListeners[i]=[]),r.eventsListeners[i][s](t)}),r},once(e,t,n){const r=this;if(!r.eventsListeners||r.destroyed||typeof t!="function")return r;function s(...i){r.off(e,s),s.__emitterProxy&&delete s.__emitterProxy,t.apply(r,i)}return s.__emitterProxy=t,r.on(e,s,n)},onAny(e,t){const n=this;if(!n.eventsListeners||n.destroyed||typeof e!="function")return n;const r=t?"unshift":"push";return n.eventsAnyListeners.indexOf(e)<0&&n.eventsAnyListeners[r](e),n},offAny(e){const t=this;if(!t.eventsListeners||t.destroyed||!t.eventsAnyListeners)return t;const n=t.eventsAnyListeners.indexOf(e);return n>=0&&t.eventsAnyListeners.splice(n,1),t},off(e,t){const n=this;return!n.eventsListeners||n.destroyed||!n.eventsListeners||e.split(" ").forEach(r=>{typeof t>"u"?n.eventsListeners[r]=[]:n.eventsListeners[r]&&n.eventsListeners[r].forEach((s,i)=>{(s===t||s.__emitterProxy&&s.__emitterProxy===t)&&n.eventsListeners[r].splice(i,1)})}),n},emit(...e){const t=this;if(!t.eventsListeners||t.destroyed||!t.eventsListeners)return t;let n,r,s;return typeof e[0]=="string"||Array.isArray(e[0])?(n=e[0],r=e.slice(1,e.length),s=t):(n=e[0].events,r=e[0].data,s=e[0].context||t),r.unshift(s),(Array.isArray(n)?n:n.split(" ")).forEach(a=>{t.eventsAnyListeners&&t.eventsAnyListeners.length&&t.eventsAnyListeners.forEach(c=>{c.apply(s,[a,...r])}),t.eventsListeners&&t.eventsListeners[a]&&t.eventsListeners[a].forEach(c=>{c.apply(s,r)})}),t}};function vL(){const e=this;let t,n;const r=e.el;typeof e.params.width<"u"&&e.params.width!==null?t=e.params.width:t=r.clientWidth,typeof e.params.height<"u"&&e.params.height!==null?n=e.params.height:n=r.clientHeight,!(t===0&&e.isHorizontal()||n===0&&e.isVertical())&&(t=t-parseInt(xu(r,"padding-left")||0,10)-parseInt(xu(r,"padding-right")||0,10),n=n-parseInt(xu(r,"padding-top")||0,10)-parseInt(xu(r,"padding-bottom")||0,10),Number.isNaN(t)&&(t=0),Number.isNaN(n)&&(n=0),Object.assign(e,{width:t,height:n,size:e.isHorizontal()?t:n}))}function wL(){const e=this;function t(Y,W){return parseFloat(Y.getPropertyValue(e.getDirectionLabel(W))||0)}const n=e.params,{wrapperEl:r,slidesEl:s,rtlTranslate:i,wrongRTL:a}=e,c=e.virtual&&n.virtual.enabled,u=c?e.virtual.slides.length:e.slides.length,f=Vc(s,`.${e.params.slideClass}, swiper-slide`),p=c?e.virtual.slides.length:f.length;let g=[];const y=[],v=[];let S=n.slidesOffsetBefore;typeof S=="function"&&(S=n.slidesOffsetBefore.call(e));let A=n.slidesOffsetAfter;typeof A=="function"&&(A=n.slidesOffsetAfter.call(e));const C=e.snapGrid.length,L=e.slidesGrid.length,R=e.size-S-A;let M=n.spaceBetween,B=-S,F=0,N=0;if(typeof R>"u")return;typeof M=="string"&&M.indexOf("%")>=0?M=parseFloat(M.replace("%",""))/100*R:typeof M=="string"&&(M=parseFloat(M)),e.virtualSize=-M-S-A,f.forEach(Y=>{i?Y.style.marginLeft="":Y.style.marginRight="",Y.style.marginBottom="",Y.style.marginTop=""}),n.centeredSlides&&n.cssMode&&($d(r,"--swiper-centered-offset-before",""),$d(r,"--swiper-centered-offset-after","")),n.cssMode&&($d(r,"--swiper-slides-offset-before",`${S}px`),$d(r,"--swiper-slides-offset-after",`${A}px`));const T=n.grid&&n.grid.rows>1&&e.grid;T?e.grid.initSlides(f):e.grid&&e.grid.unsetSlides();let $;const O=n.slidesPerView==="auto"&&n.breakpoints&&Object.keys(n.breakpoints).filter(Y=>typeof n.breakpoints[Y].slidesPerView<"u").length>0;for(let Y=0;Y<p;Y+=1){$=0;const W=f[Y];if(!(W&&(T&&e.grid.updateSlide(Y,W,f),xu(W,"display")==="none"))){if(c&&n.slidesPerView==="auto")n.virtual.slidesPerViewAutoSlideSize&&($=n.virtual.slidesPerViewAutoSlideSize),$&&W&&(n.roundLengths&&($=Math.floor($)),W.style[e.getDirectionLabel("width")]=`${$}px`);else if(n.slidesPerView==="auto"){O&&(W.style[e.getDirectionLabel("width")]="");const ye=getComputedStyle(W),ce=W.style.transform,ve=W.style.webkitTransform;if(ce&&(W.style.transform="none"),ve&&(W.style.webkitTransform="none"),n.roundLengths)$=e.isHorizontal()?j5(W,"width"):j5(W,"height");else{const re=t(ye,"width"),ke=t(ye,"padding-left"),X=t(ye,"padding-right"),V=t(ye,"margin-left"),q=t(ye,"margin-right"),ue=ye.getPropertyValue("box-sizing");if(ue&&ue==="border-box")$=re+V+q;else{const{clientWidth:Ce,offsetWidth:ee}=W;$=re+ke+X+V+q+(ee-Ce)}}ce&&(W.style.transform=ce),ve&&(W.style.webkitTransform=ve),n.roundLengths&&($=Math.floor($))}else $=(R-(n.slidesPerView-1)*M)/n.slidesPerView,n.roundLengths&&($=Math.floor($)),W&&(W.style[e.getDirectionLabel("width")]=`${$}px`);W&&(W.swiperSlideSize=$),v.push($),n.centeredSlides?(B=B+$/2+F/2+M,F===0&&Y!==0&&(B=B-R/2-M),Y===0&&(B=B-R/2-M),Math.abs(B)<1/1e3&&(B=0),n.roundLengths&&(B=Math.floor(B)),N%n.slidesPerGroup===0&&g.push(B),y.push(B)):(n.roundLengths&&(B=Math.floor(B)),(N-Math.min(e.params.slidesPerGroupSkip,N))%e.params.slidesPerGroup===0&&g.push(B),y.push(B),B=B+$+M),e.virtualSize+=$+M,F=$,N+=1}}if(e.virtualSize=Math.max(e.virtualSize,R)+A,i&&a&&(n.effect==="slide"||n.effect==="coverflow")&&(r.style.width=`${e.virtualSize+M}px`),n.setWrapperSize&&(r.style[e.getDirectionLabel("width")]=`${e.virtualSize+M}px`),T&&e.grid.updateWrapperSize($,g),!n.centeredSlides){const Y=n.slidesPerView!=="auto"&&n.slidesPerView%1!==0,W=n.snapToSlideEdge&&!n.loop&&(n.slidesPerView==="auto"||Y);let ye=g.length;if(W){let ve;if(n.slidesPerView==="auto"){ve=1;let re=0;for(let ke=v.length-1;ke>=0&&(re+=v[ke]+(ke<v.length-1?M:0),re<=R);ke-=1)ve=v.length-ke}else ve=Math.floor(n.slidesPerView);ye=Math.max(p-ve,0)}const ce=[];for(let ve=0;ve<g.length;ve+=1){let re=g[ve];n.roundLengths&&(re=Math.floor(re)),W?ve<=ye&&ce.push(re):g[ve]<=e.virtualSize-R&&ce.push(re)}g=ce,Math.floor(e.virtualSize-R)-Math.floor(g[g.length-1])>1&&(W||g.push(e.virtualSize-R))}if(c&&n.loop){const Y=v[0]+M;if(n.slidesPerGroup>1){const W=Math.ceil((e.virtual.slidesBefore+e.virtual.slidesAfter)/n.slidesPerGroup),ye=Y*n.slidesPerGroup;for(let ce=0;ce<W;ce+=1)g.push(g[g.length-1]+ye)}for(let W=0;W<e.virtual.slidesBefore+e.virtual.slidesAfter;W+=1)n.slidesPerGroup===1&&g.push(g[g.length-1]+Y),y.push(y[y.length-1]+Y),e.virtualSize+=Y}if(g.length===0&&(g=[0]),M!==0){const Y=e.isHorizontal()&&i?"marginLeft":e.getDirectionLabel("marginRight");f.filter((W,ye)=>!n.cssMode||n.loop?!0:ye!==f.length-1).forEach(W=>{W.style[Y]=`${M}px`})}if(n.centeredSlides&&n.centeredSlidesBounds){let Y=0;v.forEach(ye=>{Y+=ye+(M||0)}),Y-=M;const W=Y>R?Y-R:0;g=g.map(ye=>ye<=0?-S:ye>W?W+A:ye)}if(n.centerInsufficientSlides){let Y=0;if(v.forEach(W=>{Y+=W+(M||0)}),Y-=M,Y<R){const W=(R-Y)/2;g.forEach((ye,ce)=>{g[ce]=ye-W}),y.forEach((ye,ce)=>{y[ce]=ye+W})}}if(Object.assign(e,{slides:f,snapGrid:g,slidesGrid:y,slidesSizesGrid:v}),n.centeredSlides&&n.cssMode&&!n.centeredSlidesBounds){$d(r,"--swiper-centered-offset-before",`${-g[0]}px`),$d(r,"--swiper-centered-offset-after",`${e.size/2-v[v.length-1]/2}px`);const Y=-e.snapGrid[0],W=-e.slidesGrid[0];e.snapGrid=e.snapGrid.map(ye=>ye+Y),e.slidesGrid=e.slidesGrid.map(ye=>ye+W)}if(p!==u&&e.emit("slidesLengthChange"),g.length!==C&&(e.params.watchOverflow&&e.checkOverflow(),e.emit("snapGridLengthChange")),y.length!==L&&e.emit("slidesGridLengthChange"),n.watchSlidesProgress&&e.updateSlidesOffset(),e.emit("slidesUpdated"),!c&&!n.cssMode&&(n.effect==="slide"||n.effect==="fade")){const Y=`${n.containerModifierClass}backface-hidden`,W=e.el.classList.contains(Y);p<=n.maxBackfaceHiddenSlides?W||e.el.classList.add(Y):W&&e.el.classList.remove(Y)}}function SL(e){const t=this,n=[],r=t.virtual&&t.params.virtual.enabled;let s=0,i;typeof e=="number"?t.setTransition(e):e===!0&&t.setTransition(t.params.speed);const a=c=>r?t.slides[t.getSlideIndexByData(c)]:t.slides[c];if(t.params.slidesPerView!=="auto"&&t.params.slidesPerView>1)if(t.params.centeredSlides)(t.visibleSlides||[]).forEach(c=>{n.push(c)});else for(i=0;i<Math.ceil(t.params.slidesPerView);i+=1){const c=t.activeIndex+i;if(c>t.slides.length&&!r)break;n.push(a(c))}else n.push(a(t.activeIndex));for(i=0;i<n.length;i+=1)if(typeof n[i]<"u"){const c=n[i].offsetHeight;s=c>s?c:s}(s||s===0)&&(t.wrapperEl.style.height=`${s}px`)}function AL(){const e=this,t=e.slides,n=e.isElement?e.isHorizontal()?e.wrapperEl.offsetLeft:e.wrapperEl.offsetTop:0;for(let r=0;r<t.length;r+=1)t[r].swiperSlideOffset=(e.isHorizontal()?t[r].offsetLeft:t[r].offsetTop)-n-e.cssOverflowAdjustment()}const B5=(e,t,n)=>{t&&!e.classList.contains(n)?e.classList.add(n):!t&&e.classList.contains(n)&&e.classList.remove(n)};function TL(e=this&&this.translate||0){const t=this,n=t.params,{slides:r,rtlTranslate:s,snapGrid:i}=t;if(r.length===0)return;typeof r[0].swiperSlideOffset>"u"&&t.updateSlidesOffset();let a=-e;s&&(a=e),t.visibleSlidesIndexes=[],t.visibleSlides=[];let c=n.spaceBetween;typeof c=="string"&&c.indexOf("%")>=0?c=parseFloat(c.replace("%",""))/100*t.size:typeof c=="string"&&(c=parseFloat(c));for(let u=0;u<r.length;u+=1){const f=r[u];let p=f.swiperSlideOffset;n.cssMode&&n.centeredSlides&&(p-=r[0].swiperSlideOffset);const g=(a+(n.centeredSlides?t.minTranslate():0)-p)/(f.swiperSlideSize+c),y=(a-i[0]+(n.centeredSlides?t.minTranslate():0)-p)/(f.swiperSlideSize+c),v=-(a-p),S=v+t.slidesSizesGrid[u],A=v>=0&&v<=t.size-t.slidesSizesGrid[u],C=v>=0&&v<t.size-1||S>1&&S<=t.size||v<=0&&S>=t.size;C&&(t.visibleSlides.push(f),t.visibleSlidesIndexes.push(u)),B5(f,C,n.slideVisibleClass),B5(f,A,n.slideFullyVisibleClass),f.progress=s?-g:g,f.originalProgress=s?-y:y}}function CL(e){const t=this;if(typeof e>"u"){const p=t.rtlTranslate?-1:1;e=t&&t.translate&&t.translate*p||0}const n=t.params,r=t.maxTranslate()-t.minTranslate();let{progress:s,isBeginning:i,isEnd:a,progressLoop:c}=t;const u=i,f=a;if(r===0)s=0,i=!0,a=!0;else{s=(e-t.minTranslate())/r;const p=Math.abs(e-t.minTranslate())<1,g=Math.abs(e-t.maxTranslate())<1;i=p||s<=0,a=g||s>=1,p&&(s=0),g&&(s=1)}if(n.loop){const p=t.getSlideIndexByData(0),g=t.getSlideIndexByData(t.slides.length-1),y=t.slidesGrid[p],v=t.slidesGrid[g],S=t.slidesGrid[t.slidesGrid.length-1],A=Math.abs(e);A>=y?c=(A-y)/S:c=(A+S-v)/S,c>1&&(c-=1)}Object.assign(t,{progress:s,progressLoop:c,isBeginning:i,isEnd:a}),(n.watchSlidesProgress||n.centeredSlides&&n.autoHeight)&&t.updateSlidesProgress(e),i&&!u&&t.emit("reachBeginning toEdge"),a&&!f&&t.emit("reachEnd toEdge"),(u&&!i||f&&!a)&&t.emit("fromEdge"),t.emit("progress",s)}const hx=(e,t,n)=>{t&&!e.classList.contains(n)?e.classList.add(n):!t&&e.classList.contains(n)&&e.classList.remove(n)};function kL(){const e=this,{slides:t,params:n,slidesEl:r,activeIndex:s}=e,i=e.virtual&&n.virtual.enabled,a=e.grid&&n.grid&&n.grid.rows>1,c=g=>Vc(r,`.${n.slideClass}${g}, swiper-slide${g}`)[0];let u,f,p;if(i)if(n.loop){let g=s-e.virtual.slidesBefore;g<0&&(g=e.virtual.slides.length+g),g>=e.virtual.slides.length&&(g-=e.virtual.slides.length),u=c(`[data-swiper-slide-index="${g}"]`)}else u=c(`[data-swiper-slide-index="${s}"]`);else a?(u=t.find(g=>g.column===s),p=t.find(g=>g.column===s+1),f=t.find(g=>g.column===s-1)):u=t[s];u&&(a||(p=fL(u,`.${n.slideClass}, swiper-slide`)[0],n.loop&&!p&&(p=t[0]),f=dL(u,`.${n.slideClass}, swiper-slide`)[0],n.loop&&!f===0&&(f=t[t.length-1]))),t.forEach(g=>{hx(g,g===u,n.slideActiveClass),hx(g,g===p,n.slideNextClass),hx(g,g===f,n.slidePrevClass)}),e.emitSlidesClasses()}const Dm=(e,t)=>{if(!e||e.destroyed||!e.params)return;const n=()=>e.isElement?"swiper-slide":`.${e.params.slideClass}`,r=t.closest(n());if(r){let s=r.querySelector(`.${e.params.lazyPreloaderClass}`);!s&&e.isElement&&(r.shadowRoot?s=r.shadowRoot.querySelector(`.${e.params.lazyPreloaderClass}`):requestAnimationFrame(()=>{r.shadowRoot&&(s=r.shadowRoot.querySelector(`.${e.params.lazyPreloaderClass}`),s&&!s.lazyPreloaderManaged&&s.remove())})),s&&!s.lazyPreloaderManaged&&s.remove()}},px=(e,t)=>{if(!e.slides[t])return;const n=e.slides[t].querySelector('[loading="lazy"]');n&&n.removeAttribute("loading")},c2=e=>{if(!e||e.destroyed||!e.params)return;let t=e.params.lazyPreloadPrevNext;const n=e.slides.length;if(!n||!t||t<0)return;t=Math.min(t,n);const r=e.params.slidesPerView==="auto"?e.slidesPerViewDynamic():Math.ceil(e.params.slidesPerView),s=e.activeIndex;if(e.params.grid&&e.params.grid.rows>1){const a=s,c=[a-t];c.push(...Array.from({length:t}).map((u,f)=>a+r+f)),e.slides.forEach((u,f)=>{c.includes(u.column)&&px(e,f)});return}const i=s+r-1;if(e.params.rewind||e.params.loop)for(let a=s-t;a<=i+t;a+=1){const c=(a%n+n)%n;(c<s||c>i)&&px(e,c)}else for(let a=Math.max(s-t,0);a<=Math.min(i+t,n-1);a+=1)a!==s&&(a>i||a<s)&&px(e,a)};function _L(e){const{slidesGrid:t,params:n}=e,r=e.rtlTranslate?e.translate:-e.translate;let s;for(let i=0;i<t.length;i+=1)typeof t[i+1]<"u"?r>=t[i]&&r<t[i+1]-(t[i+1]-t[i])/2?s=i:r>=t[i]&&r<t[i+1]&&(s=i+1):r>=t[i]&&(s=i);return n.normalizeSlideIndex&&(s<0||typeof s>"u")&&(s=0),s}function LL(e){const t=this,n=t.rtlTranslate?t.translate:-t.translate,{snapGrid:r,params:s,activeIndex:i,realIndex:a,snapIndex:c}=t;let u=e,f;const p=v=>{let S=v-t.virtual.slidesBefore;return S<0&&(S=t.virtual.slides.length+S),S>=t.virtual.slides.length&&(S-=t.virtual.slides.length),S};if(typeof u>"u"&&(u=_L(t)),r.indexOf(n)>=0)f=r.indexOf(n);else{const v=Math.min(s.slidesPerGroupSkip,u);f=v+Math.floor((u-v)/s.slidesPerGroup)}if(f>=r.length&&(f=r.length-1),u===i&&!t.params.loop){f!==c&&(t.snapIndex=f,t.emit("snapIndexChange"));return}if(u===i&&t.params.loop&&t.virtual&&t.params.virtual.enabled){t.realIndex=p(u);return}const g=t.grid&&s.grid&&s.grid.rows>1;let y;if(t.virtual&&s.virtual.enabled)s.loop?y=p(u):y=u;else if(g){const v=t.slides.find(A=>A.column===u);let S=parseInt(v.getAttribute("data-swiper-slide-index"),10);Number.isNaN(S)&&(S=Math.max(t.slides.indexOf(v),0)),y=Math.floor(S/s.grid.rows)}else if(t.slides[u]){const v=t.slides[u].getAttribute("data-swiper-slide-index");v?y=parseInt(v,10):y=u}else y=u;Object.assign(t,{previousSnapIndex:c,snapIndex:f,previousRealIndex:a,realIndex:y,previousIndex:i,activeIndex:u}),t.initialized&&c2(t),t.emit("activeIndexChange"),t.emit("snapIndexChange"),(t.initialized||t.params.runCallbacksOnInit)&&(a!==y&&t.emit("realIndexChange"),t.emit("slideChange"))}function EL(e,t){const n=this,r=n.params;let s=e.closest(`.${r.slideClass}, swiper-slide`);!s&&n.isElement&&t&&t.length>1&&t.includes(e)&&[...t.slice(t.indexOf(e)+1,t.length)].forEach(c=>{!s&&c.matches&&c.matches(`.${r.slideClass}, swiper-slide`)&&(s=c)});let i=!1,a;if(s){for(let c=0;c<n.slides.length;c+=1)if(n.slides[c]===s){i=!0,a=c;break}}if(s&&i)n.clickedSlide=s,n.virtual&&n.params.virtual.enabled?n.clickedIndex=parseInt(s.getAttribute("data-swiper-slide-index"),10):n.clickedIndex=a;else{n.clickedSlide=void 0,n.clickedIndex=void 0;return}r.slideToClickedSlide&&n.clickedIndex!==void 0&&n.clickedIndex!==n.activeIndex&&n.slideToClickedSlide()}var IL={updateSize:vL,updateSlides:wL,updateAutoHeight:SL,updateSlidesOffset:AL,updateSlidesProgress:TL,updateProgress:CL,updateSlidesClasses:kL,updateActiveIndex:LL,updateClickedSlide:EL};function RL(e=this.isHorizontal()?"x":"y"){const t=this,{params:n,rtlTranslate:r,translate:s,wrapperEl:i}=t;if(n.virtualTranslate)return r?-s:s;if(n.cssMode)return s;let a=aL(i,e);return a+=t.cssOverflowAdjustment(),r&&(a=-a),a||0}function NL(e,t){const n=this,{rtlTranslate:r,params:s,wrapperEl:i,progress:a}=n;let c=0,u=0;const f=0;n.isHorizontal()?c=r?-e:e:u=e,s.roundLengths&&(c=Math.floor(c),u=Math.floor(u)),n.previousTranslate=n.translate,n.translate=n.isHorizontal()?c:u,s.cssMode?i[n.isHorizontal()?"scrollLeft":"scrollTop"]=n.isHorizontal()?-c:-u:s.virtualTranslate||(n.isHorizontal()?c-=n.cssOverflowAdjustment():u-=n.cssOverflowAdjustment(),i.style.transform=`translate3d(${c}px, ${u}px, ${f}px)`);let p;const g=n.maxTranslate()-n.minTranslate();g===0?p=0:p=(e-n.minTranslate())/g,p!==a&&n.updateProgress(e),n.emit("setTranslate",n.translate,t)}function ML(){return-this.snapGrid[0]}function DL(){return-this.snapGrid[this.snapGrid.length-1]}function jL(e=0,t=this.params.speed,n=!0,r=!0,s){const i=this,{params:a,wrapperEl:c}=i;if(i.animating&&a.preventInteractionOnTransition)return!1;const u=i.minTranslate(),f=i.maxTranslate();let p;if(r&&e>u?p=u:r&&e<f?p=f:p=e,i.updateProgress(p),a.cssMode){const g=i.isHorizontal();if(t===0)c[g?"scrollLeft":"scrollTop"]=-p;else{if(!i.support.smoothScroll)return Q7({swiper:i,targetPosition:-p,side:g?"left":"top"}),!0;c.scrollTo({[g?"left":"top"]:-p,behavior:"smooth"})}return!0}return t===0?(i.setTransition(0),i.setTranslate(p),n&&(i.emit("beforeTransitionStart",t,s),i.emit("transitionEnd"))):(i.setTransition(t),i.setTranslate(p),n&&(i.emit("beforeTransitionStart",t,s),i.emit("transitionStart")),i.animating||(i.animating=!0,i.onTranslateToWrapperTransitionEnd||(i.onTranslateToWrapperTransitionEnd=function(y){!i||i.destroyed||y.target===this&&(i.wrapperEl.removeEventListener("transitionend",i.onTranslateToWrapperTransitionEnd),i.onTranslateToWrapperTransitionEnd=null,delete i.onTranslateToWrapperTransitionEnd,i.animating=!1,n&&i.emit("transitionEnd"))}),i.wrapperEl.addEventListener("transitionend",i.onTranslateToWrapperTransitionEnd))),!0}var PL={getTranslate:RL,setTranslate:NL,minTranslate:ML,maxTranslate:DL,translateTo:jL};function BL(e,t){const n=this;n.params.cssMode||(n.wrapperEl.style.transitionDuration=`${e}ms`,n.wrapperEl.style.transitionDelay=e===0?"0ms":""),n.emit("setTransition",e,t)}function U7({swiper:e,runCallbacks:t,direction:n,step:r}){const{activeIndex:s,previousIndex:i}=e;let a=n;a||(s>i?a="next":s<i?a="prev":a="reset"),e.emit(`transition${r}`),t&&a==="reset"?e.emit(`slideResetTransition${r}`):t&&s!==i&&(e.emit(`slideChangeTransition${r}`),a==="next"?e.emit(`slideNextTransition${r}`):e.emit(`slidePrevTransition${r}`))}function FL(e=!0,t){const n=this,{params:r}=n;r.cssMode||(r.autoHeight&&n.updateAutoHeight(),U7({swiper:n,runCallbacks:e,direction:t,step:"Start"}))}function OL(e=!0,t){const n=this,{params:r}=n;n.animating=!1,!r.cssMode&&(n.setTransition(0),U7({swiper:n,runCallbacks:e,direction:t,step:"End"}))}var QL={setTransition:BL,transitionStart:FL,transitionEnd:OL};function $L(e=0,t,n=!0,r,s){typeof e=="string"&&(e=parseInt(e,10));const i=this;let a=e;a<0&&(a=0);const{params:c,snapGrid:u,slidesGrid:f,previousIndex:p,activeIndex:g,rtlTranslate:y,wrapperEl:v,enabled:S}=i;if(!S&&!r&&!s||i.destroyed||i.animating&&c.preventInteractionOnTransition)return!1;typeof t>"u"&&(t=i.params.speed);const A=Math.min(i.params.slidesPerGroupSkip,a);let C=A+Math.floor((a-A)/i.params.slidesPerGroup);C>=u.length&&(C=u.length-1);const L=-u[C];if(c.normalizeSlideIndex)for(let T=0;T<f.length;T+=1){const $=-Math.floor(L*100),O=Math.floor(f[T]*100),Y=Math.floor(f[T+1]*100);typeof f[T+1]<"u"?$>=O&&$<Y-(Y-O)/2?a=T:$>=O&&$<Y&&(a=T+1):$>=O&&(a=T)}if(i.initialized&&a!==g&&(!i.allowSlideNext&&(y?L>i.translate&&L>i.minTranslate():L<i.translate&&L<i.minTranslate())||!i.allowSlidePrev&&L>i.translate&&L>i.maxTranslate()&&(g||0)!==a))return!1;a!==(p||0)&&n&&i.emit("beforeSlideChangeStart"),i.updateProgress(L);let R;a>g?R="next":a<g?R="prev":R="reset";const M=i.virtual&&i.params.virtual.enabled;if(!(M&&s)&&(y&&-L===i.translate||!y&&L===i.translate))return i.updateActiveIndex(a),c.autoHeight&&i.updateAutoHeight(),i.updateSlidesClasses(),c.effect!=="slide"&&i.setTranslate(L),R!=="reset"&&(i.transitionStart(n,R),i.transitionEnd(n,R)),!1;if(c.cssMode){const T=i.isHorizontal(),$=y?L:-L;if(t===0)M&&(i.wrapperEl.style.scrollSnapType="none",i._immediateVirtual=!0),M&&!i._cssModeVirtualInitialSet&&i.params.initialSlide>0?(i._cssModeVirtualInitialSet=!0,requestAnimationFrame(()=>{v[T?"scrollLeft":"scrollTop"]=$})):v[T?"scrollLeft":"scrollTop"]=$,M&&requestAnimationFrame(()=>{i.wrapperEl.style.scrollSnapType="",i._immediateVirtual=!1});else{if(!i.support.smoothScroll)return Q7({swiper:i,targetPosition:$,side:T?"left":"top"}),!0;v.scrollTo({[T?"left":"top"]:$,behavior:"smooth"})}return!0}const N=z7().isSafari;return M&&!s&&N&&i.isElement&&i.virtual.update(!1,!1,a),i.setTransition(t),i.setTranslate(L),i.updateActiveIndex(a),i.updateSlidesClasses(),i.emit("beforeTransitionStart",t,r),i.transitionStart(n,R),t===0?i.transitionEnd(n,R):i.animating||(i.animating=!0,i.onSlideToWrapperTransitionEnd||(i.onSlideToWrapperTransitionEnd=function($){!i||i.destroyed||$.target===this&&(i.wrapperEl.removeEventListener("transitionend",i.onSlideToWrapperTransitionEnd),i.onSlideToWrapperTransitionEnd=null,delete i.onSlideToWrapperTransitionEnd,i.transitionEnd(n,R))}),i.wrapperEl.addEventListener("transitionend",i.onSlideToWrapperTransitionEnd)),!0}function HL(e=0,t,n=!0,r){typeof e=="string"&&(e=parseInt(e,10));const s=this;if(s.destroyed)return;typeof t>"u"&&(t=s.params.speed);const i=s.grid&&s.params.grid&&s.params.grid.rows>1;let a=e;if(s.params.loop)if(s.virtual&&s.params.virtual.enabled)a=a+s.virtual.slidesBefore;else{let c;if(i){const A=a*s.params.grid.rows;c=s.slides.find(C=>C.getAttribute("data-swiper-slide-index")*1===A).column}else c=s.getSlideIndexByData(a);const u=i?Math.ceil(s.slides.length/s.params.grid.rows):s.slides.length,{centeredSlides:f,slidesOffsetBefore:p,slidesOffsetAfter:g}=s.params,y=f||!!p||!!g;let v=s.params.slidesPerView;v==="auto"?v=s.slidesPerViewDynamic():(v=Math.ceil(parseFloat(s.params.slidesPerView,10)),y&&v%2===0&&(v=v+1));let S=u-c<v;if(y&&(S=S||c<Math.ceil(v/2)),r&&y&&s.params.slidesPerView!=="auto"&&!i&&(S=!1),S){const A=y?c<s.activeIndex?"prev":"next":c-s.activeIndex-1<s.params.slidesPerView?"next":"prev";s.loopFix({direction:A,slideTo:!0,activeSlideIndex:A==="next"?c+1:c-u+1,slideRealIndex:A==="next"?s.realIndex:void 0})}if(i){const A=a*s.params.grid.rows;a=s.slides.find(C=>C.getAttribute("data-swiper-slide-index")*1===A).column}else a=s.getSlideIndexByData(a)}return requestAnimationFrame(()=>{s.slideTo(a,t,n,r)}),s}function zL(e,t=!0,n){const r=this,{enabled:s,params:i,animating:a}=r;if(!s||r.destroyed)return r;typeof e>"u"&&(e=r.params.speed);let c=i.slidesPerGroup;i.slidesPerView==="auto"&&i.slidesPerGroup===1&&i.slidesPerGroupAuto&&(c=Math.max(r.slidesPerViewDynamic("current",!0),1));const u=r.activeIndex<i.slidesPerGroupSkip?1:c,f=r.virtual&&i.virtual.enabled;if(i.loop){if(a&&!f&&i.loopPreventsSliding)return!1;if(r.loopFix({direction:"next"}),r._clientLeft=r.wrapperEl.clientLeft,r.activeIndex===r.slides.length-1&&i.cssMode)return requestAnimationFrame(()=>{r.slideTo(r.activeIndex+u,e,t,n)}),!0}return i.rewind&&r.isEnd?r.slideTo(0,e,t,n):r.slideTo(r.activeIndex+u,e,t,n)}function UL(e,t=!0,n){const r=this,{params:s,snapGrid:i,slidesGrid:a,rtlTranslate:c,enabled:u,animating:f}=r;if(!u||r.destroyed)return r;typeof e>"u"&&(e=r.params.speed);const p=r.virtual&&s.virtual.enabled;if(s.loop){if(f&&!p&&s.loopPreventsSliding)return!1;r.loopFix({direction:"prev"}),r._clientLeft=r.wrapperEl.clientLeft}const g=c?r.translate:-r.translate;function y(R){return R<0?-Math.floor(Math.abs(R)):Math.floor(R)}const v=y(g),S=i.map(R=>y(R)),A=s.freeMode&&s.freeMode.enabled;let C=i[S.indexOf(v)-1];if(typeof C>"u"&&(s.cssMode||A)){let R;i.forEach((M,B)=>{v>=M&&(R=B)}),typeof R<"u"&&(C=A?i[R]:i[R>0?R-1:R])}let L=0;if(typeof C<"u"&&(L=a.indexOf(C),L<0&&(L=r.activeIndex-1),s.slidesPerView==="auto"&&s.slidesPerGroup===1&&s.slidesPerGroupAuto&&(L=L-r.slidesPerViewDynamic("previous",!0)+1,L=Math.max(L,0))),s.rewind&&r.isBeginning){const R=r.params.virtual&&r.params.virtual.enabled&&r.virtual?r.virtual.slides.length-1:r.slides.length-1;return r.slideTo(R,e,t,n)}else if(s.loop&&r.activeIndex===0&&s.cssMode)return requestAnimationFrame(()=>{r.slideTo(L,e,t,n)}),!0;return r.slideTo(L,e,t,n)}function GL(e,t=!0,n){const r=this;if(!r.destroyed)return typeof e>"u"&&(e=r.params.speed),r.slideTo(r.activeIndex,e,t,n)}function WL(e,t=!0,n,r=.5){const s=this;if(s.destroyed)return;typeof e>"u"&&(e=s.params.speed);let i=s.activeIndex;const a=Math.min(s.params.slidesPerGroupSkip,i),c=a+Math.floor((i-a)/s.params.slidesPerGroup),u=s.rtlTranslate?s.translate:-s.translate;if(u>=s.snapGrid[c]){const f=s.snapGrid[c],p=s.snapGrid[c+1];u-f>(p-f)*r&&(i+=s.params.slidesPerGroup)}else{const f=s.snapGrid[c-1],p=s.snapGrid[c];u-f<=(p-f)*r&&(i-=s.params.slidesPerGroup)}return i=Math.max(i,0),i=Math.min(i,s.slidesGrid.length-1),s.slideTo(i,e,t,n)}function VL(){const e=this;if(e.destroyed)return;const{params:t,slidesEl:n}=e,r=t.slidesPerView==="auto"?e.slidesPerViewDynamic():t.slidesPerView;let s=e.getSlideIndexWhenGrid(e.clickedIndex),i;const a=e.isElement?"swiper-slide":`.${t.slideClass}`,c=e.grid&&e.params.grid&&e.params.grid.rows>1;if(t.loop){if(e.animating)return;i=parseInt(e.clickedSlide.getAttribute("data-swiper-slide-index"),10),t.centeredSlides?e.slideToLoop(i):s>(c?(e.slides.length-r)/2-(e.params.grid.rows-1):e.slides.length-r)?(e.loopFix(),s=e.getSlideIndex(Vc(n,`${a}[data-swiper-slide-index="${i}"]`)[0]),O7(()=>{e.slideTo(s)})):e.slideTo(s)}else e.slideTo(s)}var qL={slideTo:$L,slideToLoop:HL,slideNext:zL,slidePrev:UL,slideReset:GL,slideToClosest:WL,slideToClickedSlide:VL};function KL(e,t){const n=this,{params:r,slidesEl:s}=n;if(!r.loop||n.virtual&&n.params.virtual.enabled)return;const i=()=>{Vc(s,`.${r.slideClass}, swiper-slide`).forEach((S,A)=>{S.setAttribute("data-swiper-slide-index",A)})},a=()=>{const v=Vc(s,`.${r.slideBlankClass}`);v.forEach(S=>{S.remove()}),v.length>0&&(n.recalcSlides(),n.updateSlides())},c=n.grid&&r.grid&&r.grid.rows>1;r.loopAddBlankSlides&&(r.slidesPerGroup>1||c)&&a();const u=r.slidesPerGroup*(c?r.grid.rows:1),f=n.slides.length%u!==0,p=c&&n.slides.length%r.grid.rows!==0,g=v=>{for(let S=0;S<v;S+=1){const A=n.isElement?l2("swiper-slide",[r.slideBlankClass]):l2("div",[r.slideClass,r.slideBlankClass]);n.slidesEl.append(A)}};if(f){if(r.loopAddBlankSlides){const v=u-n.slides.length%u;g(v),n.recalcSlides(),n.updateSlides()}else lg("Swiper Loop Warning: The number of slides is not even to slidesPerGroup, loop mode may not function properly. You need to add more slides (or make duplicates, or empty slides)");i()}else if(p){if(r.loopAddBlankSlides){const v=r.grid.rows-n.slides.length%r.grid.rows;g(v),n.recalcSlides(),n.updateSlides()}else lg("Swiper Loop Warning: The number of slides is not even to grid.rows, loop mode may not function properly. You need to add more slides (or make duplicates, or empty slides)");i()}else i();const y=r.centeredSlides||!!r.slidesOffsetBefore||!!r.slidesOffsetAfter;n.loopFix({slideRealIndex:e,direction:y?void 0:"next",initial:t})}function YL({slideRealIndex:e,slideTo:t=!0,direction:n,setTranslate:r,activeSlideIndex:s,initial:i,byController:a,byMousewheel:c}={}){const u=this;if(!u.params.loop)return;u.emit("beforeLoopFix");const{slides:f,allowSlidePrev:p,allowSlideNext:g,slidesEl:y,params:v}=u,{centeredSlides:S,slidesOffsetBefore:A,slidesOffsetAfter:C,initialSlide:L}=v,R=S||!!A||!!C;if(u.allowSlidePrev=!0,u.allowSlideNext=!0,u.virtual&&v.virtual.enabled){t&&(!R&&u.snapIndex===0?u.slideTo(u.virtual.slides.length,0,!1,!0):R&&u.snapIndex<v.slidesPerView?u.slideTo(u.virtual.slides.length+u.snapIndex,0,!1,!0):u.snapIndex===u.snapGrid.length-1&&u.slideTo(u.virtual.slidesBefore,0,!1,!0)),u.allowSlidePrev=p,u.allowSlideNext=g,u.emit("loopFix");return}let M=v.slidesPerView;M==="auto"?M=u.slidesPerViewDynamic():(M=Math.ceil(parseFloat(v.slidesPerView,10)),R&&M%2===0&&(M=M+1));const B=v.slidesPerGroupAuto?M:v.slidesPerGroup;let F=R?Math.max(B,Math.ceil(M/2)):B;F%B!==0&&(F+=B-F%B),F+=v.loopAdditionalSlides,u.loopedSlides=F;const N=u.grid&&v.grid&&v.grid.rows>1;f.length<M+F||u.params.effect==="cards"&&f.length<M+F*2?lg("Swiper Loop Warning: The number of slides is not enough for loop mode, it will be disabled or not function properly. You need to add more slides (or make duplicates) or lower the values of slidesPerView and slidesPerGroup parameters"):N&&v.grid.fill==="row"&&lg("Swiper Loop Warning: Loop mode is not compatible with grid.fill = `row`");const T=[],$=[],O=N?Math.ceil(f.length/v.grid.rows):f.length,Y=i&&O-L<M&&!R;let W=Y?L:u.activeIndex;typeof s>"u"?s=u.getSlideIndex(f.find(V=>V.classList.contains(v.slideActiveClass))):W=s;const ye=n==="next"||!n,ce=n==="prev"||!n;let ve=0,re=0;const X=(N?f[s].column:s)+(R&&typeof r>"u"?-M/2+.5:0);if(X<F){ve=Math.max(F-X,B);for(let V=0;V<F-X;V+=1){const q=V-Math.floor(V/O)*O;if(N){const ue=O-q-1;for(let Ce=f.length-1;Ce>=0;Ce-=1)f[Ce].column===ue&&T.push(Ce)}else T.push(O-q-1)}}else if(X+M>O-F){re=Math.max(X-(O-F*2),B),Y&&(re=Math.max(re,M-O+L+1));for(let V=0;V<re;V+=1){const q=V-Math.floor(V/O)*O;N?f.forEach((ue,Ce)=>{ue.column===q&&$.push(Ce)}):$.push(q)}}if(u.__preventObserver__=!0,requestAnimationFrame(()=>{u.__preventObserver__=!1}),u.params.effect==="cards"&&f.length<M+F*2&&($.includes(s)&&$.splice($.indexOf(s),1),T.includes(s)&&T.splice(T.indexOf(s),1)),ce&&T.forEach(V=>{f[V].swiperLoopMoveDOM=!0,y.prepend(f[V]),f[V].swiperLoopMoveDOM=!1}),ye&&$.forEach(V=>{f[V].swiperLoopMoveDOM=!0,y.append(f[V]),f[V].swiperLoopMoveDOM=!1}),u.recalcSlides(),v.slidesPerView==="auto"?u.updateSlides():N&&(T.length>0&&ce||$.length>0&&ye)&&u.slides.forEach((V,q)=>{u.grid.updateSlide(q,V,u.slides)}),v.watchSlidesProgress&&u.updateSlidesOffset(),t){if(T.length>0&&ce){if(typeof e>"u"){const V=u.slidesGrid[W],ue=u.slidesGrid[W+ve]-V;c?u.setTranslate(u.translate-ue):(u.slideTo(W+Math.ceil(ve),0,!1,!0),r&&(u.touchEventsData.startTranslate=u.touchEventsData.startTranslate-ue,u.touchEventsData.currentTranslate=u.touchEventsData.currentTranslate-ue))}else if(r){const V=N?T.length/v.grid.rows:T.length;u.slideTo(u.activeIndex+V,0,!1,!0),u.touchEventsData.currentTranslate=u.translate}}else if($.length>0&&ye)if(typeof e>"u"){const V=u.slidesGrid[W],ue=u.slidesGrid[W-re]-V;c?u.setTranslate(u.translate-ue):(u.slideTo(W-re,0,!1,!0),r&&(u.touchEventsData.startTranslate=u.touchEventsData.startTranslate-ue,u.touchEventsData.currentTranslate=u.touchEventsData.currentTranslate-ue))}else{const V=N?$.length/v.grid.rows:$.length;u.slideTo(u.activeIndex-V,0,!1,!0)}}if(u.allowSlidePrev=p,u.allowSlideNext=g,u.controller&&u.controller.control&&!a){const V={slideRealIndex:e,direction:n,setTranslate:r,activeSlideIndex:s,byController:!0};Array.isArray(u.controller.control)?u.controller.control.forEach(q=>{!q.destroyed&&q.params.loop&&q.loopFix({...V,slideTo:q.params.slidesPerView===v.slidesPerView?t:!1})}):u.controller.control instanceof u.constructor&&u.controller.control.params.loop&&u.controller.control.loopFix({...V,slideTo:u.controller.control.params.slidesPerView===v.slidesPerView?t:!1})}u.emit("loopFix")}function XL(){const e=this,{params:t,slidesEl:n}=e;if(!t.loop||!n||e.virtual&&e.params.virtual.enabled)return;e.recalcSlides();const r=[];e.slides.forEach(s=>{const i=typeof s.swiperSlideIndex>"u"?s.getAttribute("data-swiper-slide-index")*1:s.swiperSlideIndex;r[i]=s}),e.slides.forEach(s=>{s.removeAttribute("data-swiper-slide-index")}),r.forEach(s=>{n.append(s)}),e.recalcSlides(),e.slideTo(e.realIndex,0)}var ZL={loopCreate:KL,loopFix:YL,loopDestroy:XL};function JL(e){const t=this;if(!t.params.simulateTouch||t.params.watchOverflow&&t.isLocked||t.params.cssMode)return;const n=t.params.touchEventsTarget==="container"?t.el:t.wrapperEl;t.isElement&&(t.__preventObserver__=!0),n.style.cursor="move",n.style.cursor=e?"grabbing":"grab",t.isElement&&requestAnimationFrame(()=>{t.__preventObserver__=!1})}function eE(){const e=this;e.params.watchOverflow&&e.isLocked||e.params.cssMode||(e.isElement&&(e.__preventObserver__=!0),e[e.params.touchEventsTarget==="container"?"el":"wrapperEl"].style.cursor="",e.isElement&&requestAnimationFrame(()=>{e.__preventObserver__=!1}))}var tE={setGrabCursor:JL,unsetGrabCursor:eE};function nE(e,t=this){function n(r){if(!r||r===gd()||r===va())return null;r.assignedSlot&&(r=r.assignedSlot);const s=r.closest(e);return!s&&!r.getRootNode?null:s||n(r.getRootNode().host)}return n(t)}function F5(e,t,n){const r=va(),{params:s}=e,i=s.edgeSwipeDetection,a=s.edgeSwipeThreshold;return i&&(n<=a||n>=r.innerWidth-a)?i==="prevent"?(t.preventDefault(),!0):!1:!0}function rE(e){const t=this;if(t.destroyed)return;const n=gd();let r=e;r.originalEvent&&(r=r.originalEvent);const s=t.touchEventsData;if(r.type==="pointerdown"){if(s.pointerId!==null&&s.pointerId!==r.pointerId)return;s.pointerId=r.pointerId}else r.type==="touchstart"&&r.targetTouches.length===1&&(s.touchId=r.targetTouches[0].identifier);if(r.type==="touchstart"){F5(t,r,r.targetTouches[0].pageX);return}const{params:i,touches:a,enabled:c}=t;if(!c||!i.simulateTouch&&r.pointerType==="mouse"||t.animating&&i.preventInteractionOnTransition)return;!t.animating&&i.cssMode&&i.loop&&t.loopFix();let u=r.target;if(i.touchEventsTarget==="wrapper"&&!uL(u,t.wrapperEl)||"which"in r&&r.which===3||"button"in r&&r.button>0||s.isTouched&&s.isMoved)return;const f=!!i.noSwipingClass&&i.noSwipingClass!=="",p=r.composedPath?r.composedPath():r.path;f&&r.target&&r.target.shadowRoot&&p&&(u=p[0]);const g=i.noSwipingSelector?i.noSwipingSelector:`.${i.noSwipingClass}`,y=!!(r.target&&r.target.shadowRoot);if(i.noSwiping&&(y?nE(g,u):u.closest(g))){t.allowClick=!0;return}if(i.swipeHandler&&!u.closest(i.swipeHandler))return;a.currentX=r.pageX,a.currentY=r.pageY;const v=a.currentX,S=a.currentY;if(!F5(t,r,v))return;Object.assign(s,{isTouched:!0,isMoved:!1,allowTouchCallbacks:!0,isScrolling:void 0,startMoving:void 0}),a.startX=v,a.startY=S,s.touchStartTime=ag(),t.allowClick=!0,t.updateSize(),t.swipeDirection=void 0,i.threshold>0&&(s.allowThresholdMove=!1);let A=!0;u.matches(s.focusableElements)&&(A=!1,u.nodeName==="SELECT"&&(s.isTouched=!1)),n.activeElement&&n.activeElement.matches(s.focusableElements)&&n.activeElement!==u&&(r.pointerType==="mouse"||r.pointerType!=="mouse"&&!u.matches(s.focusableElements))&&n.activeElement.blur();const C=A&&t.allowTouchMove&&i.touchStartPreventDefault;(i.touchStartForcePreventDefault||C)&&!u.isContentEditable&&r.preventDefault(),i.freeMode&&i.freeMode.enabled&&t.freeMode&&t.animating&&!i.cssMode&&t.freeMode.onTouchStart(),t.emit("touchStart",r)}function sE(e){const t=gd(),n=this;if(n.destroyed)return;const r=n.touchEventsData,{params:s,touches:i,rtlTranslate:a,enabled:c}=n;if(!c||!s.simulateTouch&&e.pointerType==="mouse")return;let u=e;if(u.originalEvent&&(u=u.originalEvent),u.type==="pointermove"&&(r.touchId!==null||u.pointerId!==r.pointerId))return;let f;if(u.type==="touchmove"){if(f=[...u.changedTouches].find(F=>F.identifier===r.touchId),!f||f.identifier!==r.touchId)return}else f=u;if(!r.isTouched){r.startMoving&&r.isScrolling&&n.emit("touchMoveOpposite",u);return}const p=f.pageX,g=f.pageY;if(u.preventedByNestedSwiper){i.startX=p,i.startY=g;return}if(!n.allowTouchMove){u.target.matches(r.focusableElements)||(n.allowClick=!1),r.isTouched&&(Object.assign(i,{startX:p,startY:g,currentX:p,currentY:g}),r.touchStartTime=ag());return}if(s.touchReleaseOnEdges&&!s.loop)if(n.isVertical()){if(g<i.startY&&n.translate<=n.maxTranslate()||g>i.startY&&n.translate>=n.minTranslate()){r.isTouched=!1,r.isMoved=!1;return}}else{if(a&&(p>i.startX&&-n.translate<=n.maxTranslate()||p<i.startX&&-n.translate>=n.minTranslate()))return;if(!a&&(p<i.startX&&n.translate<=n.maxTranslate()||p>i.startX&&n.translate>=n.minTranslate()))return}if(t.activeElement&&t.activeElement.matches(r.focusableElements)&&t.activeElement!==u.target&&u.pointerType!=="mouse"&&t.activeElement.blur(),t.activeElement&&u.target===t.activeElement&&u.target.matches(r.focusableElements)){r.isMoved=!0,n.allowClick=!1;return}r.allowTouchCallbacks&&n.emit("touchMove",u),i.previousX=i.currentX,i.previousY=i.currentY,i.currentX=p,i.currentY=g;const y=i.currentX-i.startX,v=i.currentY-i.startY;if(n.params.threshold&&Math.sqrt(y**2+v**2)<n.params.threshold)return;if(typeof r.isScrolling>"u"){let F;n.isHorizontal()&&i.currentY===i.startY||n.isVertical()&&i.currentX===i.startX?r.isScrolling=!1:y*y+v*v>=25&&(F=Math.atan2(Math.abs(v),Math.abs(y))*180/Math.PI,r.isScrolling=n.isHorizontal()?F>s.touchAngle:90-F>s.touchAngle)}if(r.isScrolling&&n.emit("touchMoveOpposite",u),typeof r.startMoving>"u"&&(i.currentX!==i.startX||i.currentY!==i.startY)&&(r.startMoving=!0),r.isScrolling||u.type==="touchmove"&&r.preventTouchMoveFromPointerMove){r.isTouched=!1;return}if(!r.startMoving)return;n.allowClick=!1,!s.cssMode&&u.cancelable&&u.preventDefault(),s.touchMoveStopPropagation&&!s.nested&&u.stopPropagation();let S=n.isHorizontal()?y:v,A=n.isHorizontal()?i.currentX-i.previousX:i.currentY-i.previousY;s.oneWayMovement&&(S=Math.abs(S)*(a?1:-1),A=Math.abs(A)*(a?1:-1)),i.diff=S,S*=s.touchRatio,a&&(S=-S,A=-A);const C=n.touchesDirection;n.swipeDirection=S>0?"prev":"next",n.touchesDirection=A>0?"prev":"next";const L=n.params.loop&&!s.cssMode,R=n.touchesDirection==="next"&&n.allowSlideNext||n.touchesDirection==="prev"&&n.allowSlidePrev;if(!r.isMoved){if(L&&R&&n.loopFix({direction:n.swipeDirection}),r.startTranslate=n.getTranslate(),n.setTransition(0),n.animating){const F=new window.CustomEvent("transitionend",{bubbles:!0,cancelable:!0,detail:{bySwiperTouchMove:!0}});n.wrapperEl.dispatchEvent(F)}r.allowMomentumBounce=!1,s.grabCursor&&(n.allowSlideNext===!0||n.allowSlidePrev===!0)&&n.setGrabCursor(!0),n.emit("sliderFirstMove",u)}if(new Date().getTime(),s._loopSwapReset!==!1&&r.isMoved&&r.allowThresholdMove&&C!==n.touchesDirection&&L&&R&&Math.abs(S)>=1){Object.assign(i,{startX:p,startY:g,currentX:p,currentY:g,startTranslate:r.currentTranslate}),r.loopSwapReset=!0,r.startTranslate=r.currentTranslate;return}n.emit("sliderMove",u),r.isMoved=!0,r.currentTranslate=S+r.startTranslate;let M=!0,B=s.resistanceRatio;if(s.touchReleaseOnEdges&&(B=0),S>0?(L&&R&&r.allowThresholdMove&&r.currentTranslate>(s.centeredSlides?n.minTranslate()-n.slidesSizesGrid[n.activeIndex+1]-(s.slidesPerView!=="auto"&&n.slides.length-s.slidesPerView>=2?n.slidesSizesGrid[n.activeIndex+1]+n.params.spaceBetween:0)-n.params.spaceBetween:n.minTranslate())&&n.loopFix({direction:"prev",setTranslate:!0,activeSlideIndex:0}),r.currentTranslate>n.minTranslate()&&(M=!1,s.resistance&&(r.currentTranslate=n.minTranslate()-1+(-n.minTranslate()+r.startTranslate+S)**B))):S<0&&(L&&R&&r.allowThresholdMove&&r.currentTranslate<(s.centeredSlides?n.maxTranslate()+n.slidesSizesGrid[n.slidesSizesGrid.length-1]+n.params.spaceBetween+(s.slidesPerView!=="auto"&&n.slides.length-s.slidesPerView>=2?n.slidesSizesGrid[n.slidesSizesGrid.length-1]+n.params.spaceBetween:0):n.maxTranslate())&&n.loopFix({direction:"next",setTranslate:!0,activeSlideIndex:n.slides.length-(s.slidesPerView==="auto"?n.slidesPerViewDynamic():Math.ceil(parseFloat(s.slidesPerView,10)))}),r.currentTranslate<n.maxTranslate()&&(M=!1,s.resistance&&(r.currentTranslate=n.maxTranslate()+1-(n.maxTranslate()-r.startTranslate-S)**B))),M&&(u.preventedByNestedSwiper=!0),!n.allowSlideNext&&n.swipeDirection==="next"&&r.currentTranslate<r.startTranslate&&(r.currentTranslate=r.startTranslate),!n.allowSlidePrev&&n.swipeDirection==="prev"&&r.currentTranslate>r.startTranslate&&(r.currentTranslate=r.startTranslate),!n.allowSlidePrev&&!n.allowSlideNext&&(r.currentTranslate=r.startTranslate),s.threshold>0)if(Math.abs(S)>s.threshold||r.allowThresholdMove){if(!r.allowThresholdMove){r.allowThresholdMove=!0,i.startX=i.currentX,i.startY=i.currentY,r.currentTranslate=r.startTranslate,i.diff=n.isHorizontal()?i.currentX-i.startX:i.currentY-i.startY;return}}else{r.currentTranslate=r.startTranslate;return}!s.followFinger||s.cssMode||((s.freeMode&&s.freeMode.enabled&&n.freeMode||s.watchSlidesProgress)&&(n.updateActiveIndex(),n.updateSlidesClasses()),s.freeMode&&s.freeMode.enabled&&n.freeMode&&n.freeMode.onTouchMove(),n.updateProgress(r.currentTranslate),n.setTranslate(r.currentTranslate))}function iE(e){const t=this;if(t.destroyed)return;const n=t.touchEventsData;let r=e;r.originalEvent&&(r=r.originalEvent);let s;if(r.type==="touchend"||r.type==="touchcancel"){if(s=[...r.changedTouches].find(F=>F.identifier===n.touchId),!s||s.identifier!==n.touchId)return}else{if(n.touchId!==null||r.pointerId!==n.pointerId)return;s=r}if(["pointercancel","pointerout","pointerleave","contextmenu"].includes(r.type)&&!(["pointercancel","contextmenu"].includes(r.type)&&(t.browser.isSafari||t.browser.isWebView)))return;n.pointerId=null,n.touchId=null;const{params:a,touches:c,rtlTranslate:u,slidesGrid:f,enabled:p}=t;if(!p||!a.simulateTouch&&r.pointerType==="mouse")return;if(n.allowTouchCallbacks&&t.emit("touchEnd",r),n.allowTouchCallbacks=!1,!n.isTouched){n.isMoved&&a.grabCursor&&t.setGrabCursor(!1),n.isMoved=!1,n.startMoving=!1;return}a.grabCursor&&n.isMoved&&n.isTouched&&(t.allowSlideNext===!0||t.allowSlidePrev===!0)&&t.setGrabCursor(!1);const g=ag(),y=g-n.touchStartTime;if(t.allowClick){const F=r.path||r.composedPath&&r.composedPath();t.updateClickedSlide(F&&F[0]||r.target,F),t.emit("tap click",r),y<300&&g-n.lastClickTime<300&&t.emit("doubleTap doubleClick",r)}if(n.lastClickTime=ag(),O7(()=>{t.destroyed||(t.allowClick=!0)}),!n.isTouched||!n.isMoved||!t.swipeDirection||c.diff===0&&!n.loopSwapReset||n.currentTranslate===n.startTranslate&&!n.loopSwapReset){n.isTouched=!1,n.isMoved=!1,n.startMoving=!1;return}n.isTouched=!1,n.isMoved=!1,n.startMoving=!1;let v;if(a.followFinger?v=u?t.translate:-t.translate:v=-n.currentTranslate,a.cssMode)return;if(a.freeMode&&a.freeMode.enabled){t.freeMode.onTouchEnd({currentPos:v});return}const S=v>=-t.maxTranslate()&&!t.params.loop;let A=0,C=t.slidesSizesGrid[0];for(let F=0;F<f.length;F+=F<a.slidesPerGroupSkip?1:a.slidesPerGroup){const N=F<a.slidesPerGroupSkip-1?1:a.slidesPerGroup;typeof f[F+N]<"u"?(S||v>=f[F]&&v<f[F+N])&&(A=F,C=f[F+N]-f[F]):(S||v>=f[F])&&(A=F,C=f[f.length-1]-f[f.length-2])}let L=null,R=null;a.rewind&&(t.isBeginning?R=a.virtual&&a.virtual.enabled&&t.virtual?t.virtual.slides.length-1:t.slides.length-1:t.isEnd&&(L=0));const M=(v-f[A])/C,B=A<a.slidesPerGroupSkip-1?1:a.slidesPerGroup;if(y>a.longSwipesMs){if(!a.longSwipes){t.slideTo(t.activeIndex);return}t.swipeDirection==="next"&&(M>=a.longSwipesRatio?t.slideTo(a.rewind&&t.isEnd?L:A+B):t.slideTo(A)),t.swipeDirection==="prev"&&(M>1-a.longSwipesRatio?t.slideTo(A+B):R!==null&&M<0&&Math.abs(M)>a.longSwipesRatio?t.slideTo(R):t.slideTo(A))}else{if(!a.shortSwipes){t.slideTo(t.activeIndex);return}t.navigation&&(r.target===t.navigation.nextEl||r.target===t.navigation.prevEl)?r.target===t.navigation.nextEl?t.slideTo(A+B):t.slideTo(A):(t.swipeDirection==="next"&&t.slideTo(L!==null?L:A+B),t.swipeDirection==="prev"&&t.slideTo(R!==null?R:A))}}function O5(){const e=this,{params:t,el:n}=e;if(n&&n.offsetWidth===0)return;t.breakpoints&&e.setBreakpoint();const{allowSlideNext:r,allowSlidePrev:s,snapGrid:i}=e,a=e.virtual&&e.params.virtual.enabled;e.allowSlideNext=!0,e.allowSlidePrev=!0,e.updateSize(),e.updateSlides(),e.updateSlidesClasses();const c=a&&t.loop;if((t.slidesPerView==="auto"||t.slidesPerView>1)&&e.isEnd&&!e.isBeginning&&!e.params.centeredSlides&&!c){const u=a?e.virtual.slides:e.slides;e.slideTo(u.length-1,0,!1,!0)}else e.params.loop&&!a?e.slideToLoop(e.realIndex,0,!1,!0):e.slideTo(e.activeIndex,0,!1,!0);e.autoplay&&e.autoplay.running&&e.autoplay.paused&&(clearTimeout(e.autoplay.resizeTimeout),e.autoplay.resizeTimeout=setTimeout(()=>{e.autoplay&&e.autoplay.running&&e.autoplay.paused&&e.autoplay.resume()},500)),e.allowSlidePrev=s,e.allowSlideNext=r,e.params.watchOverflow&&i!==e.snapGrid&&e.checkOverflow()}function oE(e){const t=this;t.destroyed||t.enabled&&(t.allowClick||(t.params.preventClicks&&e.preventDefault(),t.params.preventClicksPropagation&&t.animating&&(e.stopPropagation(),e.stopImmediatePropagation())))}function aE(){const e=this;if(e.destroyed)return;const{wrapperEl:t,rtlTranslate:n,enabled:r}=e;if(!r)return;e.previousTranslate=e.translate,e.isHorizontal()?e.translate=-t.scrollLeft:e.translate=-t.scrollTop,e.translate===0&&(e.translate=0),e.updateActiveIndex(),e.updateSlidesClasses();let s;const i=e.maxTranslate()-e.minTranslate();i===0?s=0:s=(e.translate-e.minTranslate())/i,s!==e.progress&&e.updateProgress(n?-e.translate:e.translate),e.emit("setTranslate",e.translate,!1)}function lE(e){const t=this;t.destroyed||(Dm(t,e.target),!(t.params.cssMode||t.params.slidesPerView!=="auto"&&!t.params.autoHeight)&&t.update())}function cE(){const e=this;e.destroyed||e.documentTouchHandlerProceeded||(e.documentTouchHandlerProceeded=!0,e.params.touchReleaseOnEdges&&(e.el.style.touchAction="auto"))}const G7=(e,t)=>{const n=gd(),{params:r,el:s,wrapperEl:i,device:a}=e,c=!!r.nested,u=t==="on"?"addEventListener":"removeEventListener",f=t;!s||typeof s=="string"||(n[u]("touchstart",e.onDocumentTouchStart,{passive:!1,capture:c}),s[u]("touchstart",e.onTouchStart,{passive:!1}),s[u]("pointerdown",e.onTouchStart,{passive:!1}),n[u]("touchmove",e.onTouchMove,{passive:!1,capture:c}),n[u]("pointermove",e.onTouchMove,{passive:!1,capture:c}),n[u]("touchend",e.onTouchEnd,{passive:!0}),n[u]("pointerup",e.onTouchEnd,{passive:!0}),n[u]("pointercancel",e.onTouchEnd,{passive:!0}),n[u]("touchcancel",e.onTouchEnd,{passive:!0}),n[u]("pointerout",e.onTouchEnd,{passive:!0}),n[u]("pointerleave",e.onTouchEnd,{passive:!0}),n[u]("contextmenu",e.onTouchEnd,{passive:!0}),(r.preventClicks||r.preventClicksPropagation)&&s[u]("click",e.onClick,!0),r.cssMode&&i[u]("scroll",e.onScroll),r.updateOnWindowResize?e[f](a.ios||a.android?"resize orientationchange observerUpdate":"resize observerUpdate",O5,!0):e[f]("observerUpdate",O5,!0),s[u]("load",e.onLoad,{capture:!0}))};function uE(){const e=this,{params:t}=e;e.onTouchStart=rE.bind(e),e.onTouchMove=sE.bind(e),e.onTouchEnd=iE.bind(e),e.onDocumentTouchStart=cE.bind(e),t.cssMode&&(e.onScroll=aE.bind(e)),e.onClick=oE.bind(e),e.onLoad=lE.bind(e),G7(e,"on")}function dE(){G7(this,"off")}var fE={attachEvents:uE,detachEvents:dE};const Q5=(e,t)=>e.grid&&t.grid&&t.grid.rows>1;function hE(){const e=this,{realIndex:t,initialized:n,params:r,el:s}=e,i=r.breakpoints;if(!i||i&&Object.keys(i).length===0)return;const a=gd(),c=r.breakpointsBase==="window"||!r.breakpointsBase?r.breakpointsBase:"container",u=["window","container"].includes(r.breakpointsBase)||!r.breakpointsBase?e.el:a.querySelector(r.breakpointsBase),f=e.getBreakpoint(i,c,u);if(!f||e.currentBreakpoint===f)return;const g=(f in i?i[f]:void 0)||e.originalParams,y=Q5(e,r),v=Q5(e,g),S=e.params.grabCursor,A=g.grabCursor,C=r.enabled;y&&!v?(s.classList.remove(`${r.containerModifierClass}grid`,`${r.containerModifierClass}grid-column`),e.emitContainerClasses()):!y&&v&&(s.classList.add(`${r.containerModifierClass}grid`),(g.grid.fill&&g.grid.fill==="column"||!g.grid.fill&&r.grid.fill==="column")&&s.classList.add(`${r.containerModifierClass}grid-column`),e.emitContainerClasses()),S&&!A?e.unsetGrabCursor():!S&&A&&e.setGrabCursor(),["navigation","pagination","scrollbar"].forEach(N=>{if(typeof g[N]>"u")return;const T=r[N]&&r[N].enabled,$=g[N]&&g[N].enabled;T&&!$&&e[N].disable(),!T&&$&&e[N].enable()});const L=g.direction&&g.direction!==r.direction,R=r.loop&&(g.slidesPerView!==r.slidesPerView||L),M=r.loop;L&&n&&e.changeDirection(),el(e.params,g);const B=e.params.enabled,F=e.params.loop;Object.assign(e,{allowTouchMove:e.params.allowTouchMove,allowSlideNext:e.params.allowSlideNext,allowSlidePrev:e.params.allowSlidePrev}),C&&!B?e.disable():!C&&B&&e.enable(),e.currentBreakpoint=f,e.emit("_beforeBreakpoint",g),n&&(R?(e.loopDestroy(),e.loopCreate(t),e.updateSlides()):!M&&F?(e.loopCreate(t),e.updateSlides()):M&&!F&&e.loopDestroy()),e.emit("breakpoint",g)}function pE(e,t="window",n){if(!e||t==="container"&&!n)return;let r=!1;const s=va(),i=t==="window"?s.innerHeight:n.clientHeight,a=Object.keys(e).map(c=>{if(typeof c=="string"&&c.indexOf("@")===0){const u=parseFloat(c.substr(1));return{value:i*u,point:c}}return{value:c,point:c}});a.sort((c,u)=>parseInt(c.value,10)-parseInt(u.value,10));for(let c=0;c<a.length;c+=1){const{point:u,value:f}=a[c];t==="window"?s.matchMedia(`(min-width: ${f}px)`).matches&&(r=u):f<=n.clientWidth&&(r=u)}return r||"max"}var mE={setBreakpoint:hE,getBreakpoint:pE};function gE(e,t){const n=[];return e.forEach(r=>{typeof r=="object"?Object.keys(r).forEach(s=>{r[s]&&n.push(t+s)}):typeof r=="string"&&n.push(t+r)}),n}function xE(){const e=this,{classNames:t,params:n,rtl:r,el:s,device:i}=e,a=gE(["initialized",n.direction,{"free-mode":e.params.freeMode&&n.freeMode.enabled},{autoheight:n.autoHeight},{rtl:r},{grid:n.grid&&n.grid.rows>1},{"grid-column":n.grid&&n.grid.rows>1&&n.grid.fill==="column"},{android:i.android},{ios:i.ios},{"css-mode":n.cssMode},{centered:n.cssMode&&n.centeredSlides},{"watch-progress":n.watchSlidesProgress}],n.containerModifierClass);t.push(...a),s.classList.add(...t),e.emitContainerClasses()}function bE(){const e=this,{el:t,classNames:n}=e;!t||typeof t=="string"||(t.classList.remove(...n),e.emitContainerClasses())}var yE={addClasses:xE,removeClasses:bE};function vE(){const e=this,{isLocked:t,params:n}=e,{slidesOffsetBefore:r}=n;if(r){const s=e.slides.length-1,i=e.slidesGrid[s]+e.slidesSizesGrid[s]+r*2;e.isLocked=e.size>i}else e.isLocked=e.snapGrid.length===1;n.allowSlideNext===!0&&(e.allowSlideNext=!e.isLocked),n.allowSlidePrev===!0&&(e.allowSlidePrev=!e.isLocked),t&&t!==e.isLocked&&(e.isEnd=!1),t!==e.isLocked&&e.emit(e.isLocked?"lock":"unlock")}var wE={checkOverflow:vE},u2={init:!0,direction:"horizontal",oneWayMovement:!1,swiperElementNodeName:"SWIPER-CONTAINER",touchEventsTarget:"wrapper",initialSlide:0,speed:300,cssMode:!1,updateOnWindowResize:!0,resizeObserver:!0,nested:!1,createElements:!1,eventsPrefix:"swiper",enabled:!0,focusableElements:"input, select, option, textarea, button, video, label",width:null,height:null,preventInteractionOnTransition:!1,userAgent:null,url:null,edgeSwipeDetection:!1,edgeSwipeThreshold:20,autoHeight:!1,setWrapperSize:!1,virtualTranslate:!1,effect:"slide",breakpoints:void 0,breakpointsBase:"window",spaceBetween:0,slidesPerView:1,slidesPerGroup:1,slidesPerGroupSkip:0,slidesPerGroupAuto:!1,centeredSlides:!1,centeredSlidesBounds:!1,slidesOffsetBefore:0,slidesOffsetAfter:0,normalizeSlideIndex:!0,centerInsufficientSlides:!1,snapToSlideEdge:!1,watchOverflow:!0,roundLengths:!1,touchRatio:1,touchAngle:45,simulateTouch:!0,shortSwipes:!0,longSwipes:!0,longSwipesRatio:.5,longSwipesMs:300,followFinger:!0,allowTouchMove:!0,threshold:5,touchMoveStopPropagation:!1,touchStartPreventDefault:!0,touchStartForcePreventDefault:!1,touchReleaseOnEdges:!1,uniqueNavElements:!0,resistance:!0,resistanceRatio:.85,watchSlidesProgress:!1,grabCursor:!1,preventClicks:!0,preventClicksPropagation:!0,slideToClickedSlide:!1,loop:!1,loopAddBlankSlides:!0,loopAdditionalSlides:0,loopPreventsSliding:!0,rewind:!1,allowSlidePrev:!0,allowSlideNext:!0,swipeHandler:null,noSwiping:!0,noSwipingClass:"swiper-no-swiping",noSwipingSelector:null,passiveListeners:!0,maxBackfaceHiddenSlides:10,containerModifierClass:"swiper-",slideClass:"swiper-slide",slideBlankClass:"swiper-slide-blank",slideActiveClass:"swiper-slide-active",slideVisibleClass:"swiper-slide-visible",slideFullyVisibleClass:"swiper-slide-fully-visible",slideNextClass:"swiper-slide-next",slidePrevClass:"swiper-slide-prev",wrapperClass:"swiper-wrapper",lazyPreloaderClass:"swiper-lazy-preloader",lazyPreloadPrevNext:0,runCallbacksOnInit:!0,_emitClasses:!1};function SE(e,t){return function(r={}){const s=Object.keys(r)[0],i=r[s];if(typeof i!="object"||i===null){el(t,r);return}if(e[s]===!0&&(e[s]={enabled:!0}),s==="navigation"&&e[s]&&e[s].enabled&&!e[s].prevEl&&!e[s].nextEl&&(e[s].auto=!0),["pagination","scrollbar"].indexOf(s)>=0&&e[s]&&e[s].enabled&&!e[s].el&&(e[s].auto=!0),!(s in e&&"enabled"in i)){el(t,r);return}typeof e[s]=="object"&&!("enabled"in e[s])&&(e[s].enabled=!0),e[s]||(e[s]={enabled:!1}),el(t,r)}}const mx={eventsEmitter:yL,update:IL,translate:PL,transition:QL,slide:qL,loop:ZL,grabCursor:tE,events:fE,breakpoints:mE,checkOverflow:wE,classes:yE},gx={};let qy=class Hc{constructor(...t){let n,r;t.length===1&&t[0].constructor&&Object.prototype.toString.call(t[0]).slice(8,-1)==="Object"?r=t[0]:[n,r]=t,r||(r={}),r=el({},r),n&&!r.el&&(r.el=n);const s=gd();if(r.el&&typeof r.el=="string"&&s.querySelectorAll(r.el).length>1){const u=[];return s.querySelectorAll(r.el).forEach(f=>{const p=el({},r,{el:f});u.push(new Hc(p))}),u}const i=this;i.__swiper__=!0,i.support=$7(),i.device=H7({userAgent:r.userAgent}),i.browser=z7(),i.eventsListeners={},i.eventsAnyListeners=[],i.modules=[...i.__modules__],r.modules&&Array.isArray(r.modules)&&r.modules.forEach(u=>{typeof u=="function"&&i.modules.indexOf(u)<0&&i.modules.push(u)});const a={};i.modules.forEach(u=>{u({params:r,swiper:i,extendParams:SE(r,a),on:i.on.bind(i),once:i.once.bind(i),off:i.off.bind(i),emit:i.emit.bind(i)})});const c=el({},u2,a);return i.params=el({},c,gx,r),i.originalParams=el({},i.params),i.passedParams=el({},r),i.params&&i.params.on&&Object.keys(i.params.on).forEach(u=>{i.on(u,i.params.on[u])}),i.params&&i.params.onAny&&i.onAny(i.params.onAny),Object.assign(i,{enabled:i.params.enabled,el:n,classNames:[],slides:[],slidesGrid:[],snapGrid:[],slidesSizesGrid:[],isHorizontal(){return i.params.direction==="horizontal"},isVertical(){return i.params.direction==="vertical"},activeIndex:0,realIndex:0,isBeginning:!0,isEnd:!1,translate:0,previousTranslate:0,progress:0,velocity:0,animating:!1,cssOverflowAdjustment(){return Math.trunc(this.translate/2**23)*2**23},allowSlideNext:i.params.allowSlideNext,allowSlidePrev:i.params.allowSlidePrev,touchEventsData:{isTouched:void 0,isMoved:void 0,allowTouchCallbacks:void 0,touchStartTime:void 0,isScrolling:void 0,currentTranslate:void 0,startTranslate:void 0,allowThresholdMove:void 0,focusableElements:i.params.focusableElements,lastClickTime:0,clickTimeout:void 0,velocities:[],allowMomentumBounce:void 0,startMoving:void 0,pointerId:null,touchId:null},allowClick:!0,allowTouchMove:i.params.allowTouchMove,touches:{startX:0,startY:0,currentX:0,currentY:0,diff:0},imagesToLoad:[],imagesLoaded:0}),i.emit("_swiper"),i.params.init&&i.init(),i}getDirectionLabel(t){return this.isHorizontal()?t:{width:"height","margin-top":"margin-left","margin-bottom ":"margin-right","margin-left":"margin-top","margin-right":"margin-bottom","padding-left":"padding-top","padding-right":"padding-bottom",marginRight:"marginBottom"}[t]}getSlideIndex(t){const{slidesEl:n,params:r}=this,s=Vc(n,`.${r.slideClass}, swiper-slide`),i=D5(s[0]);return D5(t)-i}getSlideIndexByData(t){return this.getSlideIndex(this.slides.find(n=>n.getAttribute("data-swiper-slide-index")*1===t))}getSlideIndexWhenGrid(t){return this.grid&&this.params.grid&&this.params.grid.rows>1&&(this.params.grid.fill==="column"?t=Math.floor(t/this.params.grid.rows):this.params.grid.fill==="row"&&(t=t%Math.ceil(this.slides.length/this.params.grid.rows))),t}recalcSlides(){const t=this,{slidesEl:n,params:r}=t;t.slides=Vc(n,`.${r.slideClass}, swiper-slide`)}enable(){const t=this;t.enabled||(t.enabled=!0,t.params.grabCursor&&t.setGrabCursor(),t.emit("enable"))}disable(){const t=this;t.enabled&&(t.enabled=!1,t.params.grabCursor&&t.unsetGrabCursor(),t.emit("disable"))}setProgress(t,n){const r=this;t=Math.min(Math.max(t,0),1);const s=r.minTranslate(),a=(r.maxTranslate()-s)*t+s;r.translateTo(a,typeof n>"u"?0:n),r.updateActiveIndex(),r.updateSlidesClasses()}emitContainerClasses(){const t=this;if(!t.params._emitClasses||!t.el)return;const n=t.el.className.split(" ").filter(r=>r.indexOf("swiper")===0||r.indexOf(t.params.containerModifierClass)===0);t.emit("_containerClasses",n.join(" "))}getSlideClasses(t){const n=this;return n.destroyed?"":t.className.split(" ").filter(r=>r.indexOf("swiper-slide")===0||r.indexOf(n.params.slideClass)===0).join(" ")}emitSlidesClasses(){const t=this;if(!t.params._emitClasses||!t.el)return;const n=[];t.slides.forEach(r=>{const s=t.getSlideClasses(r);n.push({slideEl:r,classNames:s}),t.emit("_slideClass",r,s)}),t.emit("_slideClasses",n)}slidesPerViewDynamic(t="current",n=!1){const r=this,{params:s,slides:i,slidesGrid:a,slidesSizesGrid:c,size:u,activeIndex:f}=r;let p=1;if(typeof s.slidesPerView=="number")return s.slidesPerView;if(s.centeredSlides){let g=i[f]?Math.ceil(i[f].swiperSlideSize):0,y;for(let v=f+1;v<i.length;v+=1)i[v]&&!y&&(g+=Math.ceil(i[v].swiperSlideSize),p+=1,g>u&&(y=!0));for(let v=f-1;v>=0;v-=1)i[v]&&!y&&(g+=i[v].swiperSlideSize,p+=1,g>u&&(y=!0))}else if(t==="current")for(let g=f+1;g<i.length;g+=1)(n?a[g]+c[g]-a[f]<u:a[g]-a[f]<u)&&(p+=1);else for(let g=f-1;g>=0;g-=1)a[f]-a[g]<u&&(p+=1);return p}update(){const t=this;if(!t||t.destroyed)return;const{snapGrid:n,params:r}=t;r.breakpoints&&t.setBreakpoint(),[...t.el.querySelectorAll('[loading="lazy"]')].forEach(a=>{a.complete&&Dm(t,a)}),t.updateSize(),t.updateSlides(),t.updateProgress(),t.updateSlidesClasses();function s(){const a=t.rtlTranslate?t.translate*-1:t.translate,c=Math.min(Math.max(a,t.maxTranslate()),t.minTranslate());t.setTranslate(c),t.updateActiveIndex(),t.updateSlidesClasses()}let i;if(r.freeMode&&r.freeMode.enabled&&!r.cssMode)s(),r.autoHeight&&t.updateAutoHeight();else{if((r.slidesPerView==="auto"||r.slidesPerView>1)&&t.isEnd&&!r.centeredSlides){const a=t.virtual&&r.virtual.enabled?t.virtual.slides:t.slides;i=t.slideTo(a.length-1,0,!1,!0)}else i=t.slideTo(t.activeIndex,0,!1,!0);i||s()}r.watchOverflow&&n!==t.snapGrid&&t.checkOverflow(),t.emit("update")}changeDirection(t,n=!0){const r=this,s=r.params.direction;return t||(t=s==="horizontal"?"vertical":"horizontal"),t===s||t!=="horizontal"&&t!=="vertical"||(r.el.classList.remove(`${r.params.containerModifierClass}${s}`),r.el.classList.add(`${r.params.containerModifierClass}${t}`),r.emitContainerClasses(),r.params.direction=t,r.slides.forEach(i=>{t==="vertical"?i.style.width="":i.style.height=""}),r.emit("changeDirection"),n&&r.update()),r}changeLanguageDirection(t){const n=this;n.rtl&&t==="rtl"||!n.rtl&&t==="ltr"||(n.rtl=t==="rtl",n.rtlTranslate=n.params.direction==="horizontal"&&n.rtl,n.rtl?(n.el.classList.add(`${n.params.containerModifierClass}rtl`),n.el.dir="rtl"):(n.el.classList.remove(`${n.params.containerModifierClass}rtl`),n.el.dir="ltr"),n.update())}mount(t){const n=this;if(n.mounted)return!0;let r=t||n.params.el;if(typeof r=="string"&&(r=document.querySelector(r)),!r)return!1;r.swiper=n,r.parentNode&&r.parentNode.host&&r.parentNode.host.nodeName===n.params.swiperElementNodeName.toUpperCase()&&(n.isElement=!0);const s=()=>`.${(n.params.wrapperClass||"").trim().split(" ").join(".")}`;let a=r&&r.shadowRoot&&r.shadowRoot.querySelector?r.shadowRoot.querySelector(s()):Vc(r,s())[0];return!a&&n.params.createElements&&(a=l2("div",n.params.wrapperClass),r.append(a),Vc(r,`.${n.params.slideClass}`).forEach(c=>{a.append(c)})),Object.assign(n,{el:r,wrapperEl:a,slidesEl:n.isElement&&!r.parentNode.host.slideSlots?r.parentNode.host:a,hostEl:n.isElement?r.parentNode.host:r,mounted:!0,rtl:r.dir.toLowerCase()==="rtl"||xu(r,"direction")==="rtl",rtlTranslate:n.params.direction==="horizontal"&&(r.dir.toLowerCase()==="rtl"||xu(r,"direction")==="rtl"),wrongRTL:xu(a,"display")==="-webkit-box"}),!0}init(t){const n=this;if(n.initialized||n.mount(t)===!1)return n;n.emit("beforeInit"),n.params.breakpoints&&n.setBreakpoint(),n.addClasses(),n.updateSize(),n.updateSlides(),n.params.watchOverflow&&n.checkOverflow(),n.params.grabCursor&&n.enabled&&n.setGrabCursor(),n.params.loop&&n.virtual&&n.params.virtual.enabled?n.slideTo(n.params.initialSlide+n.virtual.slidesBefore,0,n.params.runCallbacksOnInit,!1,!0):n.slideTo(n.params.initialSlide,0,n.params.runCallbacksOnInit,!1,!0),n.params.loop&&n.loopCreate(void 0,!0),n.attachEvents();const s=[...n.el.querySelectorAll('[loading="lazy"]')];return n.isElement&&s.push(...n.hostEl.querySelectorAll('[loading="lazy"]')),s.forEach(i=>{i.complete?Dm(n,i):i.addEventListener("load",a=>{Dm(n,a.target)})}),c2(n),n.initialized=!0,c2(n),n.emit("init"),n.emit("afterInit"),n}destroy(t=!0,n=!0){const r=this,{params:s,el:i,wrapperEl:a,slides:c}=r;return typeof r.params>"u"||r.destroyed||(r.emit("beforeDestroy"),r.initialized=!1,r.detachEvents(),s.loop&&r.loopDestroy(),n&&(r.removeClasses(),i&&typeof i!="string"&&i.removeAttribute("style"),a&&a.removeAttribute("style"),c&&c.length&&c.forEach(u=>{u.classList.remove(s.slideVisibleClass,s.slideFullyVisibleClass,s.slideActiveClass,s.slideNextClass,s.slidePrevClass),u.removeAttribute("style"),u.removeAttribute("data-swiper-slide-index")})),r.emit("destroy"),Object.keys(r.eventsListeners).forEach(u=>{r.off(u)}),t!==!1&&(r.el&&typeof r.el!="string"&&(r.el.swiper=null),iL(r)),r.destroyed=!0),null}static extendDefaults(t){el(gx,t)}static get extendedDefaults(){return gx}static get defaults(){return u2}static installModule(t){Hc.prototype.__modules__||(Hc.prototype.__modules__=[]);const n=Hc.prototype.__modules__;typeof t=="function"&&n.indexOf(t)<0&&n.push(t)}static use(t){return Array.isArray(t)?(t.forEach(n=>Hc.installModule(n)),Hc):(Hc.installModule(t),Hc)}};Object.keys(mx).forEach(e=>{Object.keys(mx[e]).forEach(t=>{qy.prototype[t]=mx[e][t]})});qy.use([xL,bL]);const W7=["eventsPrefix","injectStyles","injectStylesUrls","modules","init","_direction","oneWayMovement","swiperElementNodeName","touchEventsTarget","initialSlide","_speed","cssMode","updateOnWindowResize","resizeObserver","nested","focusableElements","_enabled","_width","_height","preventInteractionOnTransition","userAgent","url","_edgeSwipeDetection","_edgeSwipeThreshold","_freeMode","_autoHeight","setWrapperSize","virtualTranslate","_effect","breakpoints","breakpointsBase","_spaceBetween","_slidesPerView","maxBackfaceHiddenSlides","_grid","_slidesPerGroup","_slidesPerGroupSkip","_slidesPerGroupAuto","_centeredSlides","_centeredSlidesBounds","_slidesOffsetBefore","_slidesOffsetAfter","normalizeSlideIndex","_centerInsufficientSlides","_snapToSlideEdge","_watchOverflow","roundLengths","touchRatio","touchAngle","simulateTouch","_shortSwipes","_longSwipes","longSwipesRatio","longSwipesMs","_followFinger","allowTouchMove","_threshold","touchMoveStopPropagation","touchStartPreventDefault","touchStartForcePreventDefault","touchReleaseOnEdges","uniqueNavElements","_resistance","_resistanceRatio","_watchSlidesProgress","_grabCursor","preventClicks","preventClicksPropagation","_slideToClickedSlide","_loop","loopAdditionalSlides","loopAddBlankSlides","loopPreventsSliding","_rewind","_allowSlidePrev","_allowSlideNext","_swipeHandler","_noSwiping","noSwipingClass","noSwipingSelector","passiveListeners","containerModifierClass","slideClass","slideActiveClass","slideVisibleClass","slideFullyVisibleClass","slideNextClass","slidePrevClass","slideBlankClass","wrapperClass","lazyPreloaderClass","lazyPreloadPrevNext","runCallbacksOnInit","observer","observeParents","observeSlideChildren","a11y","_autoplay","_controller","coverflowEffect","cubeEffect","fadeEffect","flipEffect","creativeEffect","cardsEffect","hashNavigation","history","keyboard","mousewheel","_navigation","_pagination","parallax","_scrollbar","_thumbs","virtual","zoom","control"];function cd(e){return typeof e=="object"&&e!==null&&e.constructor&&Object.prototype.toString.call(e).slice(8,-1)==="Object"&&!e.__swiper__}function v0(e,t){const n=["__proto__","constructor","prototype"];Object.keys(t).filter(r=>n.indexOf(r)<0).forEach(r=>{typeof e[r]>"u"?e[r]=t[r]:cd(t[r])&&cd(e[r])&&Object.keys(t[r]).length>0?t[r].__swiper__?e[r]=t[r]:v0(e[r],t[r]):e[r]=t[r]})}function V7(e={}){return e.navigation&&typeof e.navigation.nextEl>"u"&&typeof e.navigation.prevEl>"u"}function q7(e={}){return e.pagination&&typeof e.pagination.el>"u"}function K7(e={}){return e.scrollbar&&typeof e.scrollbar.el>"u"}function Y7(e=""){const t=e.split(" ").map(r=>r.trim()).filter(r=>!!r),n=[];return t.forEach(r=>{n.indexOf(r)<0&&n.push(r)}),n.join(" ")}function AE(e=""){return e?e.includes("swiper-wrapper")?e:`swiper-wrapper ${e}`:"swiper-wrapper"}function TE({swiper:e,slides:t,passedParams:n,changedParams:r,nextEl:s,prevEl:i,scrollbarEl:a,paginationEl:c}){const u=r.filter($=>$!=="children"&&$!=="direction"&&$!=="wrapperClass"),{params:f,pagination:p,navigation:g,scrollbar:y,virtual:v,thumbs:S}=e;let A,C,L,R,M,B,F,N;r.includes("thumbs")&&n.thumbs&&n.thumbs.swiper&&!n.thumbs.swiper.destroyed&&f.thumbs&&(!f.thumbs.swiper||f.thumbs.swiper.destroyed)&&(A=!0),r.includes("controller")&&n.controller&&n.controller.control&&f.controller&&!f.controller.control&&(C=!0),r.includes("pagination")&&n.pagination&&(n.pagination.el||c)&&(f.pagination||f.pagination===!1)&&p&&!p.el&&(L=!0),r.includes("scrollbar")&&n.scrollbar&&(n.scrollbar.el||a)&&(f.scrollbar||f.scrollbar===!1)&&y&&!y.el&&(R=!0),r.includes("navigation")&&n.navigation&&(n.navigation.prevEl||i)&&(n.navigation.nextEl||s)&&(f.navigation||f.navigation===!1)&&g&&!g.prevEl&&!g.nextEl&&(M=!0);const T=$=>{e[$]&&(e[$].destroy(),$==="navigation"?(e.isElement&&(e[$].prevEl.remove(),e[$].nextEl.remove()),f[$].prevEl=void 0,f[$].nextEl=void 0,e[$].prevEl=void 0,e[$].nextEl=void 0):(e.isElement&&e[$].el.remove(),f[$].el=void 0,e[$].el=void 0))};r.includes("loop")&&e.isElement&&(f.loop&&!n.loop?B=!0:!f.loop&&n.loop?F=!0:N=!0),u.forEach($=>{if(cd(f[$])&&cd(n[$]))Object.assign(f[$],n[$]),($==="navigation"||$==="pagination"||$==="scrollbar")&&"enabled"in n[$]&&!n[$].enabled&&T($);else{const O=n[$];(O===!0||O===!1)&&($==="navigation"||$==="pagination"||$==="scrollbar")?O===!1&&T($):f[$]=n[$]}}),u.includes("controller")&&!C&&e.controller&&e.controller.control&&f.controller&&f.controller.control&&(e.controller.control=f.controller.control),r.includes("children")&&t&&v&&f.virtual.enabled?(v.slides=t,v.update(!0)):r.includes("virtual")&&v&&f.virtual.enabled&&(t&&(v.slides=t),v.update(!0)),r.includes("children")&&t&&f.loop&&(N=!0),A&&S.init()&&S.update(!0),C&&(e.controller.control=f.controller.control),L&&(e.isElement&&(!c||typeof c=="string")&&(c=document.createElement("div"),c.classList.add("swiper-pagination"),c.part.add("pagination"),e.el.appendChild(c)),c&&(f.pagination.el=c),p.init(),p.render(),p.update()),R&&(e.isElement&&(!a||typeof a=="string")&&(a=document.createElement("div"),a.classList.add("swiper-scrollbar"),a.part.add("scrollbar"),e.el.appendChild(a)),a&&(f.scrollbar.el=a),y.init(),y.updateSize(),y.setTranslate()),M&&(e.isElement&&((!s||typeof s=="string")&&(s=document.createElement("div"),s.classList.add("swiper-button-next"),P5(s,e.navigation.arrowSvg),s.part.add("button-next"),e.el.appendChild(s)),(!i||typeof i=="string")&&(i=document.createElement("div"),i.classList.add("swiper-button-prev"),P5(i,e.navigation.arrowSvg),i.part.add("button-prev"),e.el.appendChild(i))),s&&(f.navigation.nextEl=s),i&&(f.navigation.prevEl=i),g.init(),g.update()),r.includes("allowSlideNext")&&(e.allowSlideNext=n.allowSlideNext),r.includes("allowSlidePrev")&&(e.allowSlidePrev=n.allowSlidePrev),r.includes("direction")&&e.changeDirection(n.direction,!1),(B||N)&&e.loopDestroy(),(F||N)&&e.loopCreate(),e.update()}function CE(e={},t=!0){const n={on:{}},r={},s={};v0(n,u2),n._emitClasses=!0,n.init=!1;const i={},a=W7.map(u=>u.replace(/_/,"")),c=Object.assign({},e);return Object.keys(c).forEach(u=>{typeof e[u]>"u"||(a.indexOf(u)>=0?cd(e[u])?(n[u]={},s[u]={},v0(n[u],e[u]),v0(s[u],e[u])):(n[u]=e[u],s[u]=e[u]):u.search(/on[A-Z]/)===0&&typeof e[u]=="function"?t?r[`${u[2].toLowerCase()}${u.substr(3)}`]=e[u]:n.on[`${u[2].toLowerCase()}${u.substr(3)}`]=e[u]:i[u]=e[u])}),["navigation","pagination","scrollbar"].forEach(u=>{n[u]===!0&&(n[u]={}),n[u]===!1&&delete n[u]}),{params:n,passedParams:s,rest:i,events:r}}function kE({el:e,nextEl:t,prevEl:n,paginationEl:r,scrollbarEl:s,swiper:i},a){V7(a)&&t&&n&&(i.params.navigation.nextEl=t,i.originalParams.navigation.nextEl=t,i.params.navigation.prevEl=n,i.originalParams.navigation.prevEl=n),q7(a)&&r&&(i.params.pagination.el=r,i.originalParams.pagination.el=r),K7(a)&&s&&(i.params.scrollbar.el=s,i.originalParams.scrollbar.el=s),i.init(e)}function _E(e,t,n,r,s){const i=[];if(!t)return i;const a=u=>{i.indexOf(u)<0&&i.push(u)};if(n&&r){const u=r.map(s),f=n.map(s);u.join("")!==f.join("")&&a("children"),r.length!==n.length&&a("children")}return W7.filter(u=>u[0]==="_").map(u=>u.replace(/_/,"")).forEach(u=>{if(u in e&&u in t)if(cd(e[u])&&cd(t[u])){const f=Object.keys(e[u]),p=Object.keys(t[u]);f.length!==p.length?a(u):(f.forEach(g=>{e[u][g]!==t[u][g]&&a(u)}),p.forEach(g=>{e[u][g]!==t[u][g]&&a(u)}))}else e[u]!==t[u]&&a(u)}),i}const LE=e=>{!e||e.destroyed||!e.params.virtual||e.params.virtual&&!e.params.virtual.enabled||(e.updateSlides(),e.updateProgress(),e.updateSlidesClasses(),e.emit("_virtualUpdated"),e.parallax&&e.params.parallax&&e.params.parallax.enabled&&e.parallax.setTranslate())};function cg(){return cg=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},cg.apply(this,arguments)}function X7(e){return e.type&&e.type.displayName&&e.type.displayName.includes("SwiperSlide")}function Z7(e){const t=[];return I.Children.toArray(e).forEach(n=>{X7(n)?t.push(n):n.props&&n.props.children&&Z7(n.props.children).forEach(r=>t.push(r))}),t}function EE(e){const t=[],n={"container-start":[],"container-end":[],"wrapper-start":[],"wrapper-end":[]};return I.Children.toArray(e).forEach(r=>{if(X7(r))t.push(r);else if(r.props&&r.props.slot&&n[r.props.slot])n[r.props.slot].push(r);else if(r.props&&r.props.children){const s=Z7(r.props.children);s.length>0?s.forEach(i=>t.push(i)):n["container-end"].push(r)}else n["container-end"].push(r)}),{slides:t,slots:n}}function IE(e,t,n){if(!n)return null;const r=p=>{let g=p;return p<0?g=t.length+p:g>=t.length&&(g=g-t.length),g},s=e.isHorizontal()?{[e.rtlTranslate?"right":"left"]:`${n.offset}px`}:{top:`${n.offset}px`},{from:i,to:a}=n,c=e.params.loop?-t.length:0,u=e.params.loop?t.length*2:t.length,f=[];for(let p=c;p<u;p+=1)p>=i&&p<=a&&f.push(t[r(p)]);return f.map((p,g)=>I.cloneElement(p,{swiper:e,style:s,key:p.props.virtualIndex||p.key||`slide-${g}`}))}function yh(e,t){return typeof window>"u"?x.useEffect(e,t):x.useLayoutEffect(e,t)}const $5=x.createContext(null),RE=x.createContext(null),ep=x.forwardRef(({className:e,tag:t="div",wrapperTag:n="div",children:r,onSwiper:s,...i}={},a)=>{let c=!1;const[u,f]=x.useState("swiper"),[p,g]=x.useState(null),[y,v]=x.useState(!1),S=x.useRef(!1),A=x.useRef(null),C=x.useRef(null),L=x.useRef(null),R=x.useRef(null),M=x.useRef(null),B=x.useRef(null),F=x.useRef(null),N=x.useRef(null),{params:T,passedParams:$,rest:O,events:Y}=CE(i),{slides:W,slots:ye}=EE(r),ce=()=>{v(!y)};Object.assign(T.on,{_containerClasses(V,q){f(q)}});const ve=()=>{Object.assign(T.on,Y),c=!0;const V={...T};if(delete V.wrapperClass,C.current=new qy(V),C.current.virtual&&C.current.params.virtual.enabled){C.current.virtual.slides=W;const q={cache:!1,slides:W,renderExternal:g,renderExternalUpdate:!1};v0(C.current.params.virtual,q),v0(C.current.originalParams.virtual,q)}};A.current||ve(),C.current&&C.current.on("_beforeBreakpoint",ce);const re=()=>{c||!Y||!C.current||Object.keys(Y).forEach(V=>{C.current.on(V,Y[V])})},ke=()=>{!Y||!C.current||Object.keys(Y).forEach(V=>{C.current.off(V,Y[V])})};x.useEffect(()=>()=>{C.current&&C.current.off("_beforeBreakpoint",ce)}),x.useEffect(()=>{!S.current&&C.current&&(C.current.emitSlidesClasses(),S.current=!0)}),yh(()=>{if(a&&(a.current=A.current),!!A.current)return C.current.destroyed&&ve(),kE({el:A.current,nextEl:M.current,prevEl:B.current,paginationEl:F.current,scrollbarEl:N.current,swiper:C.current},T),s&&!C.current.destroyed&&s(C.current),()=>{C.current&&!C.current.destroyed&&C.current.destroy(!0,!1)}},[]),yh(()=>{re();const V=_E($,L.current,W,R.current,q=>q.key);return L.current=$,R.current=W,V.length&&C.current&&!C.current.destroyed&&TE({swiper:C.current,slides:W,passedParams:$,changedParams:V,nextEl:M.current,prevEl:B.current,scrollbarEl:N.current,paginationEl:F.current}),()=>{ke()}}),yh(()=>{LE(C.current)},[p]);function X(){return T.virtual?IE(C.current,W,p):W.map((V,q)=>I.cloneElement(V,{swiper:C.current,swiperSlideIndex:q}))}return I.createElement(t,cg({ref:A,className:Y7(`${u}${e?` ${e}`:""}`)},O),I.createElement(RE.Provider,{value:C.current},ye["container-start"],I.createElement(n,{className:AE(T.wrapperClass)},ye["wrapper-start"],X(),ye["wrapper-end"]),V7(T)&&I.createElement(I.Fragment,null,I.createElement("div",{ref:B,className:"swiper-button-prev"}),I.createElement("div",{ref:M,className:"swiper-button-next"})),K7(T)&&I.createElement("div",{ref:N,className:"swiper-scrollbar"}),q7(T)&&I.createElement("div",{ref:F,className:"swiper-pagination"}),ye["container-end"]))});ep.displayName="Swiper";const ud=x.forwardRef(({tag:e="div",children:t,className:n="",swiper:r,zoom:s,lazy:i,virtualIndex:a,swiperSlideIndex:c,...u}={},f)=>{const p=x.useRef(null),[g,y]=x.useState("swiper-slide"),[v,S]=x.useState(!1);function A(M,B,F){B===p.current&&y(F)}yh(()=>{if(typeof c<"u"&&(p.current.swiperSlideIndex=c),f&&(f.current=p.current),!(!p.current||!r)){if(r.destroyed){g!=="swiper-slide"&&y("swiper-slide");return}return r.on("_slideClass",A),()=>{r&&r.off("_slideClass",A)}}}),yh(()=>{r&&p.current&&!r.destroyed&&y(r.getSlideClasses(p.current))},[r]);const C={isActive:g.indexOf("swiper-slide-active")>=0,isVisible:g.indexOf("swiper-slide-visible")>=0,isFullyVisible:g.indexOf("swiper-slide-fully-visible")>=0,isPrev:g.indexOf("swiper-slide-prev")>=0,isNext:g.indexOf("swiper-slide-next")>=0},L=()=>typeof t=="function"?t(C):t,R=()=>{S(!0)};return I.createElement(e,cg({ref:p,className:Y7(`${g}${n?` ${n}`:""}`),"data-swiper-slide-index":a,onLoad:R},u),s&&I.createElement($5.Provider,{value:C},I.createElement("div",{className:"swiper-zoom-container","data-swiper-zoom":typeof s=="number"?s:void 0},L(),i&&!v&&I.createElement("div",{className:"swiper-lazy-preloader",ref:M=>{M&&(M.lazyPreloaderManaged=!0)}}))),!s&&I.createElement($5.Provider,{value:C},L(),i&&!v&&I.createElement("div",{className:"swiper-lazy-preloader",ref:M=>{M&&(M.lazyPreloaderManaged=!0)}})))});ud.displayName="SwiperSlide";const Bo=[];for(let e=0;e<256;++e)Bo.push((e+256).toString(16).slice(1));function NE(e,t=0){return(Bo[e[t+0]]+Bo[e[t+1]]+Bo[e[t+2]]+Bo[e[t+3]]+"-"+Bo[e[t+4]]+Bo[e[t+5]]+"-"+Bo[e[t+6]]+Bo[e[t+7]]+"-"+Bo[e[t+8]]+Bo[e[t+9]]+"-"+Bo[e[t+10]]+Bo[e[t+11]]+Bo[e[t+12]]+Bo[e[t+13]]+Bo[e[t+14]]+Bo[e[t+15]]).toLowerCase()}let xx;const ME=new Uint8Array(16);function DE(){if(!xx){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");xx=crypto.getRandomValues.bind(crypto)}return xx(ME)}const jE=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),H5={randomUUID:jE};function PE(e,t,n){e=e||{};const r=e.random??e.rng?.()??DE();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,NE(r)}function BE(e,t,n){return H5.randomUUID&&!e?H5.randomUUID():PE(e)}const FE={},z5=e=>{let t;const n=new Set,r=(p,g)=>{const y=typeof p=="function"?p(t):p;if(!Object.is(y,t)){const v=t;t=g??(typeof y!="object"||y===null)?y:Object.assign({},t,y),n.forEach(S=>S(t,v))}},s=()=>t,u={setState:r,getState:s,getInitialState:()=>f,subscribe:p=>(n.add(p),()=>n.delete(p)),destroy:()=>{(FE?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},f=t=e(r,s,u);return u},OE=e=>e?z5(e):z5;var bx={exports:{}},yx={},vx={exports:{}},wx={};var U5;function QE(){if(U5)return wx;U5=1;var e=Kg();function t(g,y){return g===y&&(g!==0||1/g===1/y)||g!==g&&y!==y}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,s=e.useEffect,i=e.useLayoutEffect,a=e.useDebugValue;function c(g,y){var v=y(),S=r({inst:{value:v,getSnapshot:y}}),A=S[0].inst,C=S[1];return i(function(){A.value=v,A.getSnapshot=y,u(A)&&C({inst:A})},[g,v,y]),s(function(){return u(A)&&C({inst:A}),g(function(){u(A)&&C({inst:A})})},[g]),a(v),v}function u(g){var y=g.getSnapshot;g=g.value;try{var v=y();return!n(g,v)}catch{return!0}}function f(g,y){return y()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:c;return wx.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,wx}var G5;function $E(){return G5||(G5=1,vx.exports=QE()),vx.exports}var W5;function HE(){if(W5)return yx;W5=1;var e=Kg(),t=$E();function n(f,p){return f===p&&(f!==0||1/f===1/p)||f!==f&&p!==p}var r=typeof Object.is=="function"?Object.is:n,s=t.useSyncExternalStore,i=e.useRef,a=e.useEffect,c=e.useMemo,u=e.useDebugValue;return yx.useSyncExternalStoreWithSelector=function(f,p,g,y,v){var S=i(null);if(S.current===null){var A={hasValue:!1,value:null};S.current=A}else A=S.current;S=c(function(){function L(N){if(!R){if(R=!0,M=N,N=y(N),v!==void 0&&A.hasValue){var T=A.value;if(v(T,N))return B=T}return B=N}if(T=B,r(M,N))return T;var $=y(N);return v!==void 0&&v(T,$)?(M=N,T):(M=N,B=$)}var R=!1,M,B,F=g===void 0?null:g;return[function(){return L(p())},F===null?void 0:function(){return L(F())}]},[p,g,y,v]);var C=s(f,S[0],S[1]);return a(function(){A.hasValue=!0,A.value=C},[C]),u(C),C},yx}var V5;function zE(){return V5||(V5=1,bx.exports=HE()),bx.exports}var UE=zE();const GE=B7(UE),J7={},{useDebugValue:WE}=I,{useSyncExternalStoreWithSelector:VE}=GE;let q5=!1;const qE=e=>e;function KE(e,t=qE,n){(J7?"production":void 0)!=="production"&&n&&!q5&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),q5=!0);const r=VE(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return WE(r),r}const K5=e=>{(J7?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?OE(e):e,n=(r,s)=>KE(t,r,s);return Object.assign(n,t),n},e8=e=>e?K5(e):K5,Nh="auth:unauthorized";let ed=null;class al extends Error{constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="TerminalApiError"}status;code}async function YE(){const e=await fetch("/api/terminal/update");if(!e.ok)throw new al("Failed to load update state",e.status);return e.json()}async function XE(){const e=await Sr(),t=await fetch("/api/terminal/update/check",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new al("Failed to check for updates",t.status);return t.json()}async function ZE(){const e=await Sr(),t=await fetch("/api/terminal/update/restart",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to restart Termdock"}));throw new al(n.error||"Failed to restart Termdock",t.status)}return t.json()}async function JE(){const e=await fetch("/api/terminal/quota");if(!e.ok)throw new al("Failed to fetch quota",e.status);return e.json()}async function eI(){const e=await Sr(),t=await fetch("/api/terminal/quota/refresh",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new al("Failed to refresh quota",t.status);return t.json()}const Lu=8e3,tI=32e3,_c=1e4,w0=45e3,nI=8e3,rI=8e3,sI=15e3,iI=1e4,E0=5e3;let oI=0;const jm=[];let Sx=!1;function lu(e,t={}){if(typeof window>"u")return;const n=JSON.stringify({level:e==="error"||e==="timeout_or_abort"||e==="response_body_timeout"||e==="response_body_parse_error"?"warn":"info",message:`DIFF_API ${e}`,data:{seq:++oI,ts:Date.now(),...t}});jm.push(n),aI()}async function aI(){if(!Sx){Sx=!0;try{for(;jm.length>0;){const e=jm[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}),jm.shift()}catch{break}}}finally{Sx=!1}}}function lI(e,t,n){const r=new AbortController;let s=setTimeout(()=>{r.abort(new DOMException(n,"TimeoutError"))},t);const i=()=>r.abort(e?.reason);return e&&(e.aborted?i():e.addEventListener("abort",i,{once:!0})),{signal:r.signal,cleanup:()=>{s&&(clearTimeout(s),s=null),e?.removeEventListener("abort",i)}}}async function Hs(e,t,n,r){const{signal:s,cleanup:i}=lI(t?.signal??void 0,n,r);try{return await fetch(e,{...t,signal:s})}catch(a){throw a instanceof DOMException&&a.name==="TimeoutError"?new Error(r):a}finally{i()}}async function t8(e,t,n){let r=null;const s=new Promise((i,a)=>{r=setTimeout(()=>a(new Error(n)),t)});try{return await Promise.race([e.text(),s])}finally{r&&clearTimeout(r)}}async function I0(e,t,n){const r=await t8(e,t,n);return JSON.parse(r)}if(typeof window<"u"&&!window.__termdockFetchPatched){window.__termdockFetchPatched=!0;const e=window.fetch.bind(window);window.fetch=async(...t)=>{const n=await e(...t);if(n.status===401){ed=null;try{window.dispatchEvent(new CustomEvent(Nh))}catch{}}return n}}async function Sr(){if(ed)return ed;const e=await Hs("/api/csrf-token",void 0,nI,"CSRF token request timed out");if(!e.ok)throw new Error("Failed to get CSRF token");const t=await I0(e,E0,"CSRF token response timed out");if(!t.csrfToken)throw new Error("Invalid CSRF token response");return ed=t.csrfToken,ed}function n8(){ed=null}const cI=2e4,Y5=8e3,uI=1500,zo=new Map,dI=24,fI=40,hI=40;function pI(e){return e.retryState.retryCount>=2||e.pendingInputs.length>=hI?"congested":e.retryState.retryCount>=1||e.pendingInputs.length>=8?"degraded":"good"}function X5(e){if(e.pendingInputs.length===0||e.ws.readyState!==WebSocket.OPEN)return;const t=e.pendingInputs.splice(0);for(const n of t)try{e.ws.send(JSON.stringify({type:"input",data:n}))}catch{}}function r8(e){if(e.ws.readyState!==WebSocket.OPEN)return;const t=pI(e);if(t==="good"){X5(e);return}if(e.inputFlushTimer)return;const n=t==="congested"?fI:dI;e.inputFlushTimer=setTimeout(()=>{e.inputFlushTimer=null,X5(e)},n)}const vh=new Map;function mI(e,t,n,r){const s=vh.get(e);s&&(vh.delete(e),t?s.resolve({success:!0,layout:n}):s.reject(new Error(r||"Tmux action failed")))}function gI(e,t){const r=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/terminal/${e}/ws`;return t>0?`${r}?since=${t}`:r}const Z5=new Map;async function xI(e){const t=await Sr(),n=await fetch("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({cols:e.cols||80,rows:e.rows||24,mode:e.mode||"shell",tmuxSessionName:e.tmuxSessionName,cwd:e.cwd,termType:e.termType})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(r.error||"Failed to create terminal session")}return n.json()}function bI(e,t,n,r={}){const{maxRetries:s=10,initialRetryDelay:i=1e3,maxRetryDelay:a=2e4,connectionTimeout:c=15e3}=r,u={maxRetries:s,initialDelayMs:i,maxDelayMs:a,connectionTimeoutMs:c,retryCount:0,retryTimeout:null,connectionTimeoutId:null,isClosed:!1,isSuspended:!1};let f=null,p=Z5.get(e)??0;Z5.delete(e);const g=[];let y=!1,v=null;const S=new WeakSet,A=()=>{u.retryTimeout&&(clearTimeout(u.retryTimeout),u.retryTimeout=null),u.connectionTimeoutId&&(clearTimeout(u.connectionTimeoutId),u.connectionTimeoutId=null),v&&(clearTimeout(v),v=null)},C=F=>{F.heartbeatTimer&&(clearInterval(F.heartbeatTimer),F.heartbeatTimer=null),F.pongTimer&&(clearTimeout(F.pongTimer),F.pongTimer=null),F.inputFlushTimer&&(clearTimeout(F.inputFlushTimer),F.inputFlushTimer=null)},L=F=>{C(F),F.heartbeatTimer=setInterval(()=>{if(F.ws.readyState===WebSocket.OPEN){try{F.ws.send(JSON.stringify({type:"ping"}))}catch{}F.pongTimer&&clearTimeout(F.pongTimer),F.pongTimer=setTimeout(()=>{if(Date.now()-F.lastInboundAt>=Y5)try{F.ws.close()}catch{}},Y5)}},cI)},R=()=>{if(u.isClosed=!0,A(),f){C(f),zo.delete(e);try{f.ws.close()}catch{}f=null}},M=()=>{if(u.isClosed)return;if(f){S.add(f.ws),C(f);try{f.ws.close()}catch{}}const F=gI(e,p),N=new WebSocket(F);y=!1,u.connectionTimeoutId=setTimeout(()=>{N.readyState!==WebSocket.OPEN&&(y=!0,N.close(),B(new Error("WebSocket connection timeout"),!1))},c);const T={ws:N,onEvent:t,onError:n,reconnectNow:()=>{if(!u.isClosed&&(u.isSuspended=!1,!v)){if(A(),f){S.add(f.ws),C(f);try{f.ws.close()}catch{}}t({type:"reconnecting",attempt:Math.min(u.retryCount+1,s),maxAttempts:s}),u.retryCount=Math.min(u.retryCount+1,s),y=!0,v=setTimeout(()=>{v=null,y=!1,M()},0)}},suspendReconnect:()=>{u.isClosed||(u.isSuspended=!0,u.retryTimeout&&(clearTimeout(u.retryTimeout),u.retryTimeout=null))},retryState:u,lastSeq:p,pendingInputs:g,inputFlushTimer:null,heartbeatTimer:null,pongTimer:null,lastInboundAt:Date.now(),inboundSequence:0};N.onopen=()=>{A(),u.retryCount=0,T.lastInboundAt=Date.now(),T.inboundSequence+=1,L(T),r8(T)},N.onmessage=$=>{T.lastInboundAt=Date.now(),T.inboundSequence+=1;try{const O=JSON.parse($.data);if(O.type==="pong"){T.pongTimer&&(clearTimeout(T.pongTimer),T.pongTimer=null);return}if(O.type==="tmux-result"&&O.reqId){mI(O.reqId,O.success!==!1,O.layout,O.error);return}if(O.type==="tmux-layout"&&O.layout){t({type:"tmux-layout",layout:O.layout});return}if(O.type==="tmux-screen-sync"&&Array.isArray(O.chunks)){t({type:"tmux-screen-sync",chunks:O.chunks.filter(W=>typeof W=="string"),cols:typeof O.cols=="number"?O.cols:void 0,rows:typeof O.rows=="number"?O.rows:void 0,generation:typeof O.generation=="number"?O.generation:void 0});return}if(O.type==="active-program"){t({type:"active-program",activeProgram:O.activeProgram,activeProgramRaw:O.activeProgramRaw,activeProgramSource:O.activeProgramSource});return}if(O.type==="cwd"){t({type:"cwd",cwd:O.cwd});return}if(O.type==="agent-status"){t({type:"agent-status",agentStatus:O.agentStatus??null,agentIndicator:O.agentIndicator??null,agentStatusDetail:O.agentStatusDetail??null,agent:O.agent??null,agentMessage:O.agentMessage??null,agentNativeSessionId:O.agentNativeSessionId??null,agentResumeRecovered:O.agentResumeRecovered===!0,agentRich:O.agentRich===!0,agentActivity:typeof O.agentActivity=="number"?O.agentActivity:0,agentCwd:O.agentCwd??null,reviewed:typeof O.reviewed=="boolean"?O.reviewed:null});return}if(O.type==="git-status"){t({type:"git-status",gitStatus:O.gitStatus??null});return}if(O.type==="quota-status"&&Array.isArray(O.providers)){window.dispatchEvent(new CustomEvent("termdock:quota-update",{detail:O.providers}));return}if(O.type==="focus-mode"){t({type:"focus-mode",focusTrackingRequested:O.focusTrackingRequested===!0});return}if(O.type==="resize-ack"){t({type:"resize-ack",seq:typeof O.seq=="number"?O.seq:void 0,cols:typeof O.cols=="number"?O.cols:void 0,rows:typeof O.rows=="number"?O.rows:void 0,ok:O.ok!==!1,error:typeof O.error=="string"?O.error:void 0,screenSyncPending:O.screenSyncPending===!0,screenSyncGeneration:typeof O.screenSyncGeneration=="number"?O.screenSyncGeneration:void 0});return}if(O.type==="pty-size"){t({type:"pty-size",cols:typeof O.cols=="number"?O.cols:void 0,rows:typeof O.rows=="number"?O.rows:void 0,source:typeof O.source=="string"?O.source:void 0});return}if(O.type==="shell-title"){t({type:"shell-title",title:typeof O.title=="string"?O.title:""});return}if(O.type==="prompt-state"){t({type:"prompt-state",state:O.state==="running"?"running":"idle",exitCode:typeof O.exitCode=="number"?O.exitCode:void 0});return}const Y=O;if(Y.type==="connected"){typeof Y.replayLastSeq=="number"&&Y.replayLastSeq>0&&(p=Y.replayLastSeq,T.lastSeq=p),t(Y);return}if(Y.type==="exit"){R(),t(Y);return}t(Y),Y.type==="data"&&typeof Y.seq=="number"&&Number.isFinite(Y.seq)&&Y.seq>p&&(p=Y.seq,T.lastSeq=p)}catch(O){n?.(O,!1)}},N.onerror=()=>{S.has(N)||(A(),C(T),y||(y=!0,B(new Error("WebSocket connection error"),!1)))},N.onclose=$=>{if(!S.has(N)&&(A(),C(T),!u.isClosed&&!y)){if(y=!0,$.code===4001){console.warn("[Terminal] WS 4001: Session not found on server",{code:$.code,reason:$.reason,stack:new Error().stack}),B(new Error("Session not found on server"),!0);return}if($.code===4003||$.code===4401){try{window.dispatchEvent(new CustomEvent(Nh))}catch{}B(new Error("Authentication required"),!0);return}B(new Error("WebSocket connection closed"),!1)}},f=T,zo.set(e,f)},B=(F,N)=>{if(!u.isClosed)if(N)n?.(F,!0),R();else{u.retryCount=Math.min(u.retryCount+1,Math.max(1,s));const T=Math.min(i*Math.pow(2,u.retryCount-1),a);if(t({type:"reconnecting",attempt:u.retryCount,maxAttempts:s}),u.isSuspended)return;u.retryTimeout=setTimeout(()=>{u.isClosed||M()},T)}};return M(),R}async function s8(e,t){const n=zo.get(e);if(n){if(n.ws.readyState===WebSocket.OPEN){n.pendingInputs.push(t),r8(n);return}if(n.ws.readyState===WebSocket.CONNECTING){n.pendingInputs.push(t);return}}const r=await Sr(),s=await fetch(`/api/terminal/${e}/input`,{method:"POST",headers:{"Content-Type":"text/plain","X-XSRF-TOKEN":r},body:t});if(!s.ok){const i=await s.json().catch(()=>({error:"Failed to send input"}));throw new Error(i.error||"Failed to send terminal input")}}function yI(e,t){const n=zo.get(e);if(!n)return!1;if(n.retryState.isSuspended=!1,n.ws.readyState!==WebSocket.OPEN)return n.reconnectNow(),!0;const r=n.inboundSequence;try{n.ws.send(JSON.stringify({type:"ping"}))}catch{}return setTimeout(()=>{zo.get(e)!==n||n.retryState.isClosed||(n.inboundSequence<=r?n.reconnectNow():t?.())},uI),!0}function vI(e){const t=zo.get(e);return t?(t.reconnectNow(),!0):!1}function J5(){for(const e of zo.values())e.suspendReconnect()}function ew(e,t,n){const r=zo.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"focus",focused:t,reason:n}))}catch{}}function tw(e,t,n){const r=zo.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"viewing",viewing:t,reason:n}))}catch{}}function nw(e){const t=zo.get(e);if(!(!t||t.ws.readyState!==WebSocket.OPEN))try{t.ws.send(JSON.stringify({type:"agent-review-ack"}))}catch{}}function rw(e,t,n){const r=zo.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"flow-control",paused:t,reason:n}))}catch{}}async function wI(e,t,n,r){const s=zo.get(e);if(s&&s.ws.readyState===WebSocket.OPEN)try{s.ws.send(JSON.stringify({type:"resize",cols:t,rows:n,seq:r}));return}catch{}const i=await Sr(),a=await fetch(`/api/terminal/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":i},body:JSON.stringify({cols:t,rows:n,seq:r})});if(!a.ok){const u=await a.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(u.error||"Failed to resize terminal")}const c=await a.json().catch(()=>({success:!0}));if(c?.success===!1||c?.ok===!1)throw new Error(c?.error||"Failed to resize terminal")}async function SI(e,t){const n=zo.get(e);if(n&&n.ws.readyState===WebSocket.OPEN)return t.action==="scroll"?(n.ws.send(JSON.stringify({type:"tmux",...t})),{success:!0}):new Promise((i,a)=>{const c=Math.random().toString(36).substring(7);vh.set(c,{resolve:i,reject:a}),n.ws.send(JSON.stringify({type:"tmux",reqId:c,...t})),setTimeout(()=>{vh.has(c)&&(vh.delete(c),a(new Error("Tmux action timed out")))},3e4)});const r=await Sr(),s=await fetch(`/api/terminal/${e}/tmux`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)});if(!s.ok){const i=await s.json().catch(()=>({error:"Failed to execute tmux action"}));throw new Error(i.error||"Failed to execute tmux action")}return s.json()}async function i8(e){const t=zo.get(e);if(t){t.retryState.isClosed=!0;try{t.ws.close()}catch{}zo.delete(e)}const n=await Sr(),r=await fetch(`/api/terminal/${e}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(r.status!==404&&!r.ok){const s=await r.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(s.error||"Failed to close terminal")}}async function AI(e,t){const n=zo.get(e);if(n){n.retryState.isClosed=!0;try{n.ws.close()}catch{}zo.delete(e)}const r=await Sr(),s=await fetch(`/api/terminal/${e}/restart`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify({...t.cwd?{cwd:t.cwd}:{},cols:t.cols??80,rows:t.rows??24,mode:t.mode,tmuxSessionName:t.tmuxSessionName})});if(!s.ok){const i=await s.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(i.error||"Failed to restart terminal session")}return s.json()}async function TI(e){const t=await Hs(`/api/terminal/${e}/health`,{method:"GET"},rI,"Terminal health check timed out");if(!t.ok){if(t.status===404)return{healthy:!1,sessionId:e};const n=await I0(t,E0,"Terminal health error response timed out").catch(()=>({error:"Failed to check terminal health"}));throw new Error(n.error||"Failed to check terminal health")}return I0(t,E0,"Terminal health response timed out")}async function CI(e){const t=await Sr(),n=await Hs("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)},iI,"Terminal force-kill request timed out");if(!n.ok){const r=await I0(n,E0,"Terminal force-kill error response timed out").catch(()=>({error:"Failed to force kill terminal"}));throw new Error(r.error||"Failed to force kill terminal")}}async function d2(){const e=await fetch("/api/terminal/tmux/sessions",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to list tmux sessions"}));throw new Error(n.error||"Failed to list tmux sessions")}const t=await e.json();return Array.isArray(t.sessions)?t.sessions:[]}async function f2(){const e=await fetch("/api/terminal/tmux/status",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to get tmux status"}));throw new Error(t.error||"Failed to get tmux status")}return e.json()}async function o8(e){const t=e.trim();if(!t)throw new Error("tmux session name is required");const n=await Sr(),r=await fetch(`/api/terminal/tmux/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(!r.ok){const i=await r.json().catch(()=>({error:"Failed to kill tmux session"}));throw new Error(i.error||"Failed to kill tmux session")}const s=await r.json();return{cleanedSessions:Array.isArray(s.cleanedSessions)?s.cleanedSessions:[],alreadyGone:!!s.alreadyGone}}async function kI(){const e=await Sr(),t=await fetch("/api/terminal/tmux/recovery/restore-all",{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await t.json().catch(()=>({}));if(!t.ok)throw new al(n.error||"Failed to restore tmux Agent sessions",t.status);return n}async function _I(){const e=await Sr(),t=await fetch("/api/terminal/tmux/recovery",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new al("Failed to dismiss tmux recovery",t.status)}const zp=new Map;function LI(e){return JSON.stringify({preferredFrontendSessionId:e.preferredFrontendSessionId??null,mode:e.mode??null,tmuxSessionName:e.tmuxSessionName??null,cwd:e.cwd??null,termType:e.termType??null,createIfEmpty:e.createIfEmpty===!0,requireExisting:e.requireExisting===!0})}async function EI(){const e=await fetch("/api/terminal/session-inventory",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to load session inventory"}));throw new Error(t.error||"Failed to load session inventory")}return e.json()}async function a8(e){const t=LI(e),n=zp.get(t);if(n)return n;const r=await Sr(),s=Hs("/api/terminal/session-inventory/open",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)},sI,"Terminal session open request timed out").then(async i=>{if(!i.ok){const a=await I0(i,E0,"Terminal session open error response timed out").catch(()=>({error:"Failed to open session"}));throw new al(a.error||"Failed to open session",i.status,typeof a.code=="string"?a.code:void 0)}return I0(i,E0,"Terminal session open response timed out")}).finally(()=>{zp.get(t)===s&&zp.delete(t)});return zp.set(t,s),s}async function Pm(e,t){const n=await Sr(),r=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(t)});if(!r.ok){const s=await r.json().catch(()=>({error:"Failed to update session"}));throw new Error(s.error||"Failed to update session")}return r.json()}async function II(e){const t=await Sr(),n=await fetch("/api/terminal/session-inventory/reorder",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({sessionIds:e})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to reorder sessions"}));throw new Error(r.error||"Failed to reorder sessions")}return n.json()}async function RI(e){const t=await Sr(),n=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to remove session"}));throw new Error(r.error||"Failed to remove session")}}async function NI(){const e=await Sr(),t=await fetch("/api/terminal/session-inventory/sessions",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to clear sessions"}));throw new Error(n.error||"Failed to clear sessions")}}async function sw(){const e=await fetch("/api/terminal/toolbar-presets",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to load toolbar presets"}));throw new Error(t.error||"Failed to load toolbar presets")}return e.json()}async function MI(e){const t=await Sr(),n=await fetch("/api/terminal/toolbar-presets",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to save toolbar presets"})),s=new Error(r.error||"Failed to save toolbar presets");throw s.current=r.current,s.code=r.code,s}return n.json()}let Tf=null,lh=null;const l8=1500;function dd(){return lh&&Date.now()-lh.readAt<l8?Promise.resolve(lh.value):Tf||(Tf=(async()=>{const e=await fetch("/api/terminal/settings",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to load settings"}));throw new Error(n.error||"Failed to load settings")}const t=await e.json();return lh={value:t,readAt:Date.now()},t})().finally(()=>{Tf=null}),Tf)}async function yo(e){const t=await Sr(),n=await fetch("/api/terminal/settings",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const s=await n.json().catch(()=>({error:"Failed to update settings"}));throw new Error(s.error||"Failed to update settings")}const r=await n.json();return lh={value:r,readAt:Date.now()},r}async function Cf(e=!1){const t=await fetch(`/api/terminal/auto-title/catalog${e?"?refresh=1":""}`);if(!t.ok)throw new Error("Failed to discover title models");const n=await t.json();return Array.isArray(n?.namers)?n.namers:[]}let kf=null,ch=null;function DI(){return ch&&Date.now()-ch.readAt<l8?Promise.resolve(ch.value):kf||(kf=(async()=>{const e=await fetch("/api/terminal/context-draft",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to load context draft"}));throw new Error(n.error||"Failed to load context draft")}const t=await e.json();return ch={value:t,readAt:Date.now()},t})().finally(()=>{kf=null}),kf)}async function jI(e,t){const n=await Sr(),r=await fetch("/api/terminal/context-draft",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify({text:e,origin:t})});if(!r.ok){const i=await r.json().catch(()=>({error:"Failed to update context draft"}));throw new Error(i.error||"Failed to update context draft")}const s=await r.json();return ch={value:s,readAt:Date.now()},s}async function PI(){const e=await fetch("/api/auth/status");if(!e.ok)throw new Error("Failed to query auth status");return e.json()}async function BI(e){const t=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:e})});if(t.ok)return n8(),{ok:!0};const n=await t.json().catch(()=>null);return t.status===429?{ok:!1,rateLimited:!0,retryAfterMs:typeof n?.retryAfterMs=="number"?n.retryAfterMs:void 0,error:n?.error||"Too many failed attempts. Please wait and try again."}:{ok:!1,error:n?.error||"Login failed"}}async function FI(){const e=await Sr();await fetch("/api/auth/logout",{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n8()}async function c8(){const e=await fetch("/api/terminal/agent-launchers");if(!e.ok)throw new Error("Failed to detect agent launchers");const t=await e.json();return Array.isArray(t?.agents)?t.agents:[]}async function OI(){const e=await fetch("/api/terminal/agent-hooks");if(!e.ok)throw new Error("Failed to get agent hooks");const t=await e.json();return Array.isArray(t?.agents)?t.agents:[]}async function QI(e){const t=await Sr(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(e)}/install`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to install agent hooks");return{summary:r.summary??"Installed",devMode:r.devMode===!0}}async function $I(e){const t=await Sr(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(e)}/uninstall`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to uninstall agent hooks");return r.summary??"Removed"}class Ky extends Error{constructor(t,n,r){super(t),this.code=n,this.migration=r,this.name="AgentPluginManifestError"}code;migration}async function HI(){const e=await fetch("/api/terminal/agent-plugins");if(!e.ok)throw new Error("Failed to get agent plugins");return await e.json()}async function zI(e){const t=await Sr(),n=await fetch("/api/terminal/agent-plugins",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Ky(r.error||"Failed to create agent plugin",r.code,r.migration);return r}async function UI(e){const t=await Sr(),n=await fetch("/api/terminal/agent-plugins/install",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({source:e})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Ky(r.error||"Failed to install agent plugin",r.code,r.migration);return r}async function GI(e){const t=await Sr(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/check-update`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to check plugin updates");return r}async function WI(e){const t=await Sr(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/update`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to update plugin");return r}async function VI(e){const t=await Sr(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/doctor`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to diagnose plugin");return r}async function qI(e){const t=await Sr(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||"Failed to delete agent plugin")}}async function KI(e){const t=await Sr(),n=await fetch(`/api/terminal/${encodeURIComponent(e)}/agent-resume`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new al(r.error||"Failed to resume agent session",n.status,typeof r.code=="string"?r.code:void 0);return{command:r.command??""}}async function iw(){const e=await fetch("/api/terminal/agent-resume-history",{method:"GET"});if(!e.ok)throw new Error("Failed to load Agent resume history");const t=await e.json().catch(()=>({entries:[]}));return Array.isArray(t.entries)?t.entries:[]}async function u8(e){const t=await Sr(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(e)}/prepare`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new al(r.error||"Failed to prepare Agent session resume",n.status,typeof r.code=="string"?r.code:void 0);return r}async function YI(e){const t=await Sr(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok&&n.status!==404)throw new Error("Failed to remove Agent resume history")}async function Hd(e){const t=await Sr(),n=await fetch("/api/terminal/program-rules",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to update program rules"}));throw new Error(r.error||"Failed to update program rules")}return n.json()}async function XI(){const e=await Sr(),t=await fetch("/api/terminal/program-rules",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Error("Failed to reset program rules");return t.json()}async function ZI(){const e=await fetch("/api/terminal/program-detection");if(!e.ok)throw new Error("Failed to get program detection config");return e.json()}async function ow(e){const t=await Sr(),n=await fetch("/api/terminal/program-detection",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok)throw new Error("Failed to save program detection config");return n.json()}async function JI(){const e=await Sr(),t=await fetch("/api/terminal/program-detection",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Error("Failed to reset program detection config");return t.json()}const eR={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".bmp":"image/bmp",".ico":"image/x-icon",".svg":"image/svg+xml",".heic":"image/heic",".heif":"image/heif"};function Yy(e){const t=e.lastIndexOf(".");return t<0?null:eR[e.slice(t).toLowerCase()]??null}function Xy(e){return Yy(e)!==null}function d8(e){const t=Yy(e);return t==="image/heic"||t==="image/heif"}const tR={".mp4":"video/mp4",".m4v":"video/x-m4v",".webm":"video/webm",".mov":"video/quicktime",".ogv":"video/ogg",".mpeg":"video/mpeg",".mpg":"video/mpeg"};function f8(e){const t=e.lastIndexOf(".");return t<0?null:tR[e.slice(t).toLowerCase()]??null}function h8(e){return f8(e)!==null}function nR(e){return`/api/terminal/fs/video?path=${encodeURIComponent(e)}&action=view_file`}const rR=[".stl",".glb",".gltf"];function p8(e){const t=e.lastIndexOf(".");if(t<0)return null;const n=e.slice(t).toLowerCase();return rR.includes(n)?n:null}function m8(e){return p8(e)!==null}function g8(e){const t=e.toLowerCase();return t.endsWith(".kicad_sch")?".kicad_sch":t.endsWith(".kicad_pcb")?".kicad_pcb":null}function sR(e){return g8(e)!==null}function iR(e){return g8(e)===".kicad_pcb"?"pcb-front":"schematic"}const oR=[".html",".htm"];function _f(e){const t=e.lastIndexOf(".");if(t<0)return!1;const n=e.slice(t).toLowerCase();return oR.includes(n)}function aR(e){return`/api/terminal/fs/preview/${e.split(/[\\/]+/).filter(Boolean).map(n=>encodeURIComponent(n)).join("/")}`}const lR={".stl":"model/stl",".glb":"model/gltf-binary",".gltf":"model/gltf+json"};async function Yg(e,t,n,r="list_directory",s,i="name"){const a=new URLSearchParams({path:e});n&&a.set("showHidden","true"),i!=="name"&&a.set("sort",i),a.set("action",r),s&&a.set("requestSlotId",s);const c=await Hs(`/api/terminal/fs/list?${a}`,{signal:t},Lu,"Directory listing took too long. The folder may be on slow storage or blocked by another process.");if(!c.ok){const u=await c.json().catch(()=>({error:"Failed to list directory"}));throw new Error(u.error||"Failed to list directory")}return c.json()}async function cR(e,t,n,r,s,i="name",a,c={}){const u=new URLSearchParams({path:e,query:t,stream:"true"});s&&u.set("showHidden","true"),i==="content"&&u.set("mode","content"),a&&u.set("requestSlotId",a);for(const S of c.excludePatterns??[])u.append("exclude",S);c.caseSensitive&&u.set("caseSensitive","true"),c.wholeWord&&u.set("wholeWord","true"),c.regex&&u.set("regex","true");const f=await fetch(`/api/terminal/fs/search?${u}`,{signal:r});if(!f.ok||!f.body){const S=await f.json().catch(()=>({error:"Failed to search files"}));throw new Error(S.error||"Failed to search files")}const p=f.body.getReader(),g=new TextDecoder;let y="";const v=S=>{if(!S.trim())return;const A=JSON.parse(S);if(A.type==="meta")n({path:A.path,query:A.query,engine:A.engine,mode:A.mode,limited:A.limited});else if(A.type==="batch")n({entries:A.entries??[]});else if(A.type==="content-batch")n({contentEntries:A.contentEntries??[]});else{if(A.type==="error")throw new Error(A.message||"Search failed");A.type==="done"&&n({total:A.total,truncated:A.truncated,limited:A.limited,engine:A.engine,mode:A.mode,done:!0})}};for(;;){const{value:S,done:A}=await p.read();if(A)break;y+=g.decode(S,{stream:!0});let C=y.indexOf(`
3
3
  `);for(;C>=0;)v(y.slice(0,C)),y=y.slice(C+1),C=y.indexOf(`
4
4
  `)}y+=g.decode(),v(y)}async function uR(e,t,n){const r=new URLSearchParams;for(const p of e)r.append("root",p);const s=await fetch(`/api/terminal/fs/watch?${r}`,{signal:n});if(!s.ok||!s.body){const p=await s.json().catch(()=>({error:"Failed to watch files"}));throw new Error(p.error||"Failed to watch files")}const i=s.body.getReader(),a=new TextDecoder;let c="",u=null;const f=p=>{if(!p.trim())return;const g=JSON.parse(p);if(g.type==="events"&&g.events?.length){t(g.events);const y=g.events.find(v=>v.type==="rescan-required"&&v.reason!=="event-storm"&&v.reason!=="reconnected"&&v.reason!=="directory-rescan"&&v.reason!=="polling-fallback");y?.reason&&(u=y.reason)}};for(;;){const{value:p,done:g}=await i.read();if(g)break;c+=a.decode(p,{stream:!0});let y=c.indexOf(`
@@ -76,7 +76,7 @@ ${t.trim()}`:""].filter(Boolean).join(`
76
76
  `)}async function hQ(e){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{return document.execCommand("copy")}catch{return!1}finally{t.remove()}}function pQ({error:e,componentStack:t}){const{t:n}=ir(),[r,s]=I.useState("idle"),i=async()=>{const a=fQ(e,t,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});s(await hQ(a)?"copied":"failed")};return o.jsx("div",{className:"flex h-full items-center justify-center p-4",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[o.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:o.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("h3",{className:"font-medium text-foreground",children:n("errorBoundary.title")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e?.message||n("errorBoundary.unexpected")})]}),o.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[o.jsx("button",{type:"button",onClick:()=>{i()},className:"rounded-full bg-surface-2 px-5 py-2.5 text-sm font-medium text-foreground ring-1 ring-border/15 transition hover:bg-surface-elevated active:scale-[0.97]",children:n(r==="copied"?"errorBoundary.copied":r==="failed"?"errorBoundary.copyFailed":"errorBoundary.copyDetails")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-full bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.97]",children:n("errorBoundary.retry")})]})]})})}let _A=class extends I.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(t){return{hasError:!0,error:t,componentStack:""}}componentDidCatch(t,n){console.error("Terminal error caught by boundary:",t,n),this.setState({componentStack:n.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:o.jsx(pQ,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}};function P2(e,t){return e.label.trim().length>0?e.label:`Key ${t+1}`}const fh=15;function mQ(){return LA.map(e=>e.id)}const LA=[{id:"default",label:"Base",programs:[],includeAlt:!0,rowLayout:[3,3,3],actions:[],showOnDesktop:!1},{id:"opencode",label:"Code",programs:["opencode"],includeAlt:!1,rowLayout:[6],actions:[{id:"opencode-undo",label:"/undo",sequence:"/undo",doubleTapSequence:"/undo||\r"},{id:"opencode-new",label:"/new",sequence:"/new",doubleTapSequence:"/new||\r"},{id:"opencode-models",label:"/models",sequence:"/models",doubleTapSequence:"/models||\r"},{id:"opencode-compact",label:"/compact",sequence:"/compact",doubleTapSequence:"/compact||\r"}],showOnDesktop:!0},{id:"claude",label:"Claude",programs:["claude","claude-code"],includeAlt:!1,rowLayout:[6],actions:[{id:"claude-undo",label:"/undo",sequence:"/undo",doubleTapSequence:"/undo\r"},{id:"claude-clear",label:"/clear",sequence:"/clear",doubleTapSequence:"/clear\r"},{id:"claude-compact",label:"/compact",sequence:"/compact",doubleTapSequence:"/compact\r"}],showOnDesktop:!0},{id:"kimi",label:"Kimi",programs:["kimi","kimi-code"],includeAlt:!1,rowLayout:[6],actions:[{id:"kimi-undo",label:"/undo",sequence:"/undo",doubleTapSequence:"/undo\r"},{id:"kimi-new",label:"/new",sequence:"/new",doubleTapSequence:"/new\r"},{id:"kimi-sessions",label:"/sessions",sequence:"/sessions",doubleTapSequence:"/sessions\r"},{id:"kimi-compact",label:"/compact",sequence:"/compact",doubleTapSequence:"/compact\r"},{id:"kimi-goal",label:"/goal",sequence:"/goal",doubleTapSequence:"/goal\r"}],showOnDesktop:!0},{id:"codex",label:"Codex",programs:["codex"],includeAlt:!1,rowLayout:[6],actions:[{id:"codex-undo",label:"/undo",sequence:"/undo",doubleTapSequence:"/undo\r"},{id:"codex-clear",label:"/clear",sequence:"/clear",doubleTapSequence:"/clear\r"},{id:"codex-model",label:"/model",sequence:"/model",doubleTapSequence:"/model\r"},{id:"codex-compact",label:"/compact",sequence:"/compact",doubleTapSequence:"/compact\r"},{id:"codex-resume",label:"/resume",sequence:"/resume",doubleTapSequence:"/resume\r"}],showOnDesktop:!0},{id:"coco",label:"Coco",programs:["coco"],includeAlt:!1,rowLayout:[6],actions:[{id:"coco-undo",label:"/undo",sequence:"/||undo ",doubleTapSequence:"/||undo ||\r"},{id:"coco-clear",label:"/clear",sequence:"/||clear ",doubleTapSequence:"/||clear ||\r"},{id:"coco-model",label:"/model",sequence:"/||model ",doubleTapSequence:"/||model ||\r"},{id:"coco-resume",label:"/resume",sequence:"/||resume ",doubleTapSequence:"/||resume ||\r"}],showOnDesktop:!0},{id:"traex",label:"TraeX",programs:["traex","traecli"],includeAlt:!1,rowLayout:[6],actions:[{id:"traex-undo",label:"/undo",sequence:"/||undo ",doubleTapSequence:"/||undo ||\r"},{id:"traex-clear",label:"/clear",sequence:"/||clear ",doubleTapSequence:"/||clear ||\r"},{id:"traex-compact",label:"/compact",sequence:"/||compact ",doubleTapSequence:"/||compact ||\r"},{id:"traex-model",label:"/model",sequence:"/||model ",doubleTapSequence:"/||model ||\r"},{id:"traex-resume",label:"/resume",sequence:"/||resume ",doubleTapSequence:"/||resume ||\r"}],showOnDesktop:!0}];function jh(){return LA.map(e=>({...e,programs:[...e.programs],includeAlt:e.includeAlt,rowLayout:[...e.rowLayout],actions:e.actions.map(t=>({...t})),showOnDesktop:e.showOnDesktop}))}function xv(e){const t=Array.isArray(e)?e.map(n=>Math.min(20,Math.max(2,Math.floor(n)))).filter(n=>Number.isFinite(n)):[];return t.length>0?t:[3,3]}function EA(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t.length>0?t:null}const bv=/^\/(.+)\/([gimsuy]*)$/;function $3(e){return bv.test(e.trim())}function gg(e){const t=e.trim().match(bv);if(!t)return null;try{return new RegExp(t[1]??"",t[2]??"")}catch{return null}}function IA(e){if(typeof e!="string")return null;const t=e.trim();return t?bv.test(t)?gg(t)?t:null:t.toLowerCase():null}function H3(e){return e.replace(/\\u([0-9a-fA-F]{4})/g,(t,n)=>String.fromCharCode(Number.parseInt(n,16))).replace(/\\r/g,"\r").replace(/\\n/g,`
77
77
  `).replace(/\\t/g," ")}const z3="||",gQ=120;function xQ(e){return e.includes(z3)?e.split(z3).filter(t=>t.length>0):[e]}function x0(e){const t=new Set,n=e.map((s,i)=>{const a=typeof s.id=="string"&&s.id.trim().length>0?s.id.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-"):`preset-${i+1}`,c=t.has(a)?`${a}-${i+1}`:a;return t.add(c),{id:c,label:typeof s.label=="string"&&s.label.trim().length>0?s.label.trim():"Preset",programs:Array.isArray(s.programs)?s.programs.map(u=>IA(u)).filter(u=>!!u):[],includeAlt:typeof s.includeAlt=="boolean"?!!s.includeAlt:!1,rowLayout:xv(s.rowLayout),showOnDesktop:typeof s.showOnDesktop=="boolean"?!!s.showOnDesktop:!1,actions:Array.isArray(s.actions)?s.actions.map((u,f)=>{const p={id:typeof u.id=="string"&&u.id.trim().length>0?u.id:`${c}-action-${f+1}`,label:typeof u.label=="string"?u.label:`Key ${f+1}`,sequence:typeof u.sequence=="string"?u.sequence:""};return typeof u.doubleTapSequence=="string"&&(p.doubleTapSequence=u.doubleTapSequence),p}):[]}}).filter(s=>s.id!=="auto"),r=jh()[0];return r&&!n.some(s=>s.id==="default")&&n.unshift(r),n}function bQ(e,t){const n=EA(e);if(!n)return"default";for(const r of t)if(r.id!=="default")for(const s of r.programs){const i=gg(s);if(i){if(i.test(n))return r.id}else if(n.includes(s))return r.id}return"default"}function U3(e,t){return e.find(n=>n.id===t)??e.find(n=>n.id==="default")??jh()[0]}function yQ(e){return[{id:"auto",label:"Auto"},...e.map(t=>({id:t.id,label:t.label}))]}function vQ(e){return[{id:"auto",label:"Auto"},...e.filter(t=>t.showOnDesktop===!0).map(t=>({id:t.id,label:t.label}))]}function RA(e,t){const n=xv(t),r=[];let s=0,i=0;for(;s<e.length;){const a=n[Math.min(i,n.length-1)]??3;r.push({columns:a,items:e.slice(s,s+a)}),s+=a,i+=1}return r}const NA=28,MA=({mode:e,presetLabel:t,title:n,ariaLabel:r,disabled:s,onPointerDown:i,buttonRef:a})=>o.jsx("button",{ref:a,type:"button",onPointerDown:i,tabIndex:-1,disabled:s,className:"h-7 w-7 rounded-full bg-surface-2 shadow-sm text-[11px] font-medium active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",title:n,"aria-label":r??n,children:e==="auto"?o.jsx(ij,{size:14}):(t.charAt(0)||"?").toUpperCase()}),wQ={esc:"\x1B",enter:"\r",home:"\x1B[H",end:"\x1B[F","ctrl-c":"","ctrl-d":"","ctrl-w":"","ctrl-u":""},im=8;function SQ(e,t){return wQ[e]??null}const AQ=({visible:e,interactive:t=!0,presentation:n="mobile",activeModifier:r,lockedModifier:s,disabled:i,defaultShowExtended:a=!1,presetLabel:c,presetModeLabel:u,presetMode:f,presetOptions:p,includeAlt:g,presetRowLayout:y,extraActions:v,onKeyPress:S,onTextPress:A,onPastePress:C,onFilePress:L,fileUploadState:R="idle",fileUploadProgress:M=0,longPressMode:B="arrows",copyFeedback:F="idle",onLongPressModeToggle:N,onModifierToggle:T,onPresetSelect:$,onExpandedChange:O})=>{const{t:Y}=ir(),[W,ye]=I.useState(a),[ce,ve]=I.useState(!1),re=I.useRef(null),ke=n==="desktop-actions",X=ke||W,[V,q]=I.useState(!1),[ue,Ce]=I.useState(null),ee=i||!e||!t,Ee=i||!e,Ze=I.useRef(null),$e=I.useRef(null),Ue=I.useRef(null),ne=I.useRef(null),lt=I.useRef(null),Ye=I.useRef(F),me=I.useRef(null),se=I.useRef(0),_e=I.useCallback(ct=>{if(ee)return;const Rt=ct.target;if(!(Rt instanceof HTMLElement))return;const Lt=Rt.closest("button"),Xe=Lt?.hasAttribute("data-mobile-native-action")===!0;Lt&&!Xe?(ct.preventDefault(),Zl(im)):Lt&&Zl(im)},[ee]),he=I.useCallback(ct=>{ct.preventDefault()},[]),He=I.useCallback(ct=>{const Rt=ct.target;ee||Rt instanceof HTMLElement&&Rt.closest("button")&&Rt.blur()},[ee]);I.useEffect(()=>{ye(a)},[a]),I.useEffect(()=>{ke||O?.(W)},[ke,O,W]),I.useEffect(()=>{ee&&(me.current!==null&&(window.clearTimeout(me.current.timer),me.current=null),q(!1),Ce(null))},[ee]),I.useEffect(()=>{e||(q(!1),Ce(null))},[e]),I.useEffect(()=>{if(!V)return;const ct=()=>{const Rt=Ze.current?.getBoundingClientRect();Rt&&Ce({left:Math.max(8,Rt.left),top:Math.max(8,Rt.top-8)})};return ct(),window.addEventListener("resize",ct),window.addEventListener("scroll",ct,!0),()=>{window.removeEventListener("resize",ct),window.removeEventListener("scroll",ct,!0)}},[V]),I.useEffect(()=>{const ct=Ye.current;if(Ye.current=F,F==="idle"||F===ct)return;if(lt.current!==null&&window.clearTimeout(lt.current),!(typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches))if(F==="copied"){$e.current?.animate?.([{transform:"scale(1)"},{transform:"scale(1.16)",offset:.28},{transform:"scale(0.96)",offset:.62},{transform:"scale(1)"}],{duration:720,easing:"cubic-bezier(0.16, 1, 0.3, 1)"});const Lt=[{opacity:0,transform:"scale(0.65)"},{opacity:.75,transform:"scale(0.9)",offset:.18},{opacity:0,transform:"scale(1.65)"}];Ue.current?.animate?.(Lt,{duration:760,easing:"ease-out"}),ne.current?.animate?.(Lt,{duration:760,delay:130,easing:"ease-out"})}else $e.current?.animate?.([{transform:"translateX(0)"},{transform:"translateX(-2px)"},{transform:"translateX(2px)"},{transform:"translateX(0)"}],{duration:280,easing:"ease-out"});Zl(im),F==="copied"&&(lt.current=window.setTimeout(()=>{Zl(im),lt.current=null},90),B==="copy"&&N?.())},[F,B,N]),I.useEffect(()=>()=>{lt.current!==null&&window.clearTimeout(lt.current)},[]);const Je=I.useCallback((ct,Rt)=>{ee||(ct.preventDefault(),S(Rt))},[S,ee]),at=I.useCallback((ct,Rt)=>{ee||(ct.preventDefault(),T(Rt))},[T,ee]),ge=I.useCallback(ct=>{ee||(ct.preventDefault(),ye(Rt=>{const Lt=!Rt;return Lt&&(ve(!0),re.current!==null&&window.clearTimeout(re.current),re.current=window.setTimeout(()=>{ve(!1),re.current=null},350)),Lt}))},[ee]),Ie=I.useCallback(()=>{const ct=typeof performance<"u"?performance.now():Date.now();ct-se.current<350||(se.current=ct,C?.())},[C]),tt=I.useCallback(ct=>{ee||(ct.stopPropagation(),ct.pointerType!=="touch"&&(ct.preventDefault(),Ie()))},[ee,Ie]),Le=I.useCallback(ct=>{ee||(ct.preventDefault(),ct.stopPropagation(),Ie())},[ee,Ie]),fe=I.useCallback(ct=>{ee||R==="uploading"||!L||(ct.preventDefault(),ct.stopPropagation(),L())},[R,L,ee]),Qe=I.useCallback(ct=>{ee||ct.stopPropagation()},[ee]),ft=250,Mt=I.useCallback(()=>{me.current!==null&&(window.clearTimeout(me.current.timer),me.current=null)},[]);I.useEffect(()=>()=>{Mt(),re.current!==null&&(window.clearTimeout(re.current),re.current=null)},[Mt]);const cn=I.useCallback((ct,Rt)=>{if(ee)return;if(ct.preventDefault(),!Rt.doubleTapSequence){A(Rt.sequence);return}const Lt=me.current;if(Lt!==null&&Lt.actionId===Rt.id){window.clearTimeout(Lt.timer),me.current=null,A(Rt.doubleTapSequence);return}Mt();const Xe=window.setTimeout(()=>{me.current=null,A(Rt.sequence)},ft);me.current={actionId:Rt.id,timer:Xe}},[Mt,A,ee]),mt=I.useCallback(ct=>{ee||(ct.preventDefault(),ct.stopPropagation(),N?.())},[N,ee]),Bt=I.useCallback(ct=>{ee||ct.stopPropagation()},[ee]),Zt=I.useCallback(ct=>{if(ee)return;ct.preventDefault();const Rt=ct.currentTarget.getBoundingClientRect();Ce({left:Math.max(8,Rt.left),top:Math.max(8,Rt.top-8)}),q(Lt=>!Lt)},[ee]),It=I.useCallback((ct,Rt)=>{ee||(ct.preventDefault(),q(!1),Ce(null),$(Rt))},[$,ee]),nn=v.length>0,xe=I.useMemo(()=>{const ct=[{id:"preset",kind:"preset"}];if(!ke&&g&&ct.push({id:"alt",kind:"alt"}),nn){const Rt=v.map(Lt=>({id:Lt.id,kind:"text",action:Lt}));return ct.concat(Rt)}return ke?ct:ct.concat([{id:"home",kind:"key",keyName:"home"},{id:"end",kind:"key",keyName:"end"},{id:"ctrl-d",kind:"key",keyName:"ctrl-d"}])},[v,nn,g,ke]),et=I.useMemo(()=>RA(xe,y),[xe,y]),pt=`${ke?"space-y-1":"mt-1 space-y-1"}${ce?" pointer-events-none":""}`,Yt=V&&ue?Ni.createPortal(o.jsx("div",{className:"fixed z-popover min-w-28 -translate-y-full rounded-2xl bg-surface-elevated p-1.5 shadow-xl border border-border/15",style:{left:ue.left,top:ue.top},children:o.jsx("div",{className:"grid gap-1",children:p.map(ct=>o.jsx("button",{type:"button",onPointerDown:Rt=>It(Rt,ct.id),tabIndex:-1,disabled:Ee,className:`h-7 rounded-full px-3 text-left text-xs font-medium transition-colors disabled:opacity-50 ${ct.id===f?"bg-primary text-primary-foreground":"bg-surface-2 hover:bg-surface-elevated text-muted-foreground hover:text-foreground"}`,children:ct.label},ct.id))})}),document.body):null;return o.jsxs(o.Fragment,{children:[Yt,o.jsx("div",{"data-mobile-keyboard":"true",className:`z-chrome select-none overflow-hidden app-chrome-bg transition-all duration-150 ease-out px-1 py-0 ${e?ke?"max-h-24":"max-h-40":"max-h-0"} ${e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"} ${t?"":"[&_button]:pointer-events-none"}`,onMouseDownCapture:_e,onPointerDownCapture:_e,onContextMenuCapture:he,onFocusCapture:He,children:o.jsxs("div",{className:"rounded-2xl bg-surface-elevated p-0.5 space-y-0.5",children:[!ke&&o.jsxs("div",{"data-mobile-keyboard-primary-row":"true",className:"grid grid-cols-10 gap-1",children:[o.jsx("button",{type:"button",onPointerDown:ct=>Je(ct,"esc"),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"Esc"}),o.jsx("button",{type:"button",onPointerDown:ct=>at(ct,"ctrl"),tabIndex:-1,disabled:Ee,className:`h-7 w-full rounded-full shadow-sm text-xs disabled:opacity-50 flex items-center justify-center transition-all ${r==="ctrl"?"bg-primary text-primary-foreground scale-105 shadow-md shadow-primary/40":"bg-surface-2"} ${s==="ctrl"?"ring-2 ring-accent":""}`,children:o.jsx("span",{className:"font-medium",children:s==="ctrl"?"Ctrl*":"Ctrl"})}),o.jsx("button",{type:"button",onPointerDown:ct=>Je(ct,"ctrl-c"),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"C-C"}),o.jsx("button",{type:"button",onPointerDown:ct=>Je(ct,"ctrl-u"),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"C-U"}),o.jsxs("button",{type:"button","data-mobile-native-action":"true",onPointerDown:Qe,onTouchStart:Qe,onClick:fe,tabIndex:-1,disabled:Ee||!L||R==="uploading",title:R==="uploading"?`${Y("rightSidebar.uploading")} ${Math.round(M)}%`:Y(R==="inserted"?"rightSidebar.inserted":R==="failed"?"rightSidebar.uploadFailed":"rightSidebar.insertLocalFile"),"aria-label":Y("rightSidebar.insertLocalFile"),className:`relative h-7 w-full overflow-hidden rounded-full shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center ${R==="inserted"?"bg-primary/15 text-primary":R==="failed"?"bg-destructive/15 text-destructive":"bg-surface-2"}`,children:[R==="uploading"&&o.jsx("span",{"aria-hidden":"true","data-file-upload-progress":"true",className:"absolute inset-y-0 left-0 bg-primary/25 transition-[width] duration-150 ease-out",style:{width:`${Math.max(0,Math.min(100,M))}%`}}),o.jsx("span",{className:"relative z-10 flex items-center justify-center",children:R==="uploading"?o.jsx(tr,{size:15,className:"animate-spin"}):R==="inserted"?o.jsx(Fa,{size:15}):R==="failed"?o.jsx(ds,{size:15}):o.jsx(kM,{size:15})}),R!=="idle"&&o.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:R==="uploading"?`${Y("rightSidebar.uploading")} ${Math.round(M)}%`:Y(R==="inserted"?"rightSidebar.inserted":"rightSidebar.uploadFailed")})]}),o.jsx("button",{type:"button",onPointerDown:()=>A("/"),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"/"}),o.jsx("button",{type:"button",onPointerDown:ct=>Je(ct,"enter"),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",children:o.jsx(M8,{size:16})}),o.jsxs("button",{ref:$e,type:"button","data-mobile-copy-button":"true","data-mobile-native-action":"true",onPointerDown:Bt,onTouchStart:Bt,onClick:mt,tabIndex:-1,disabled:Ee,title:Y(F==="copied"?"terminal.copied":F==="failed"?"terminal.copyFailed":B==="copy"?"terminal.longPressSelectsText":"terminal.longPressSendsArrows"),"aria-label":Y(B==="copy"?"terminal.switchLongPressToArrows":"terminal.switchLongPressToCopy"),className:`relative isolate h-7 w-full overflow-visible rounded-full shadow-sm active:bg-accent active:text-accent-foreground transition-colors keyboard-button-active disabled:opacity-50 flex items-center justify-center ${F==="copied"?"bg-primary/15 text-primary":F==="failed"?"bg-destructive/15 text-destructive":B==="copy"?"bg-primary/15 text-primary":"bg-surface-2"}`,children:[o.jsx("span",{ref:Ue,"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-0 rounded-full border border-primary/70 opacity-0"}),o.jsx("span",{ref:ne,"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-0 rounded-full border border-primary/40 opacity-0"}),o.jsxs("span",{className:"relative z-10 h-4 w-4","aria-hidden":"true",children:[o.jsx(Fa,{size:16,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${F==="copied"?"scale-100 rotate-0 opacity-100":"scale-50 -rotate-45 opacity-0"}`}),o.jsx(ds,{size:16,className:`absolute inset-0 transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none ${F==="failed"?"scale-100 opacity-100":"scale-50 opacity-0"}`}),o.jsx(N8,{size:15,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${F==="idle"&&B==="copy"?"scale-100 opacity-100":"scale-50 opacity-0"}`}),o.jsx(dD,{size:15,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${F==="idle"&&B==="arrows"?"scale-100 rotate-0 opacity-100":"scale-50 rotate-45 opacity-0"}`})]}),F!=="idle"&&o.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:F==="copied"?`${Y("terminal.copied")} · ${Y("terminal.longPressSendsArrows")}`:`${Y("terminal.copyFailed")} · ${Y("terminal.longPressSelectsText")}`})]}),o.jsx("button",{type:"button","data-mobile-copy-button":"true","data-mobile-native-action":"true",onPointerDown:tt,onPointerUp:Qe,onTouchStart:Qe,onTouchEnd:Qe,onClick:Le,tabIndex:-1,disabled:Ee,title:Y("terminal.paste"),"aria-label":Y("terminal.paste"),className:"h-7 w-full rounded-full bg-surface-2 shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",children:o.jsx(iM,{size:15})}),o.jsx("button",{type:"button",onPointerDown:ge,tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",children:W?o.jsx(R8,{size:16}):o.jsx(Oa,{size:16})})]}),X&&o.jsx("div",{className:pt,children:et.map((ct,Rt)=>{const Lt=ct.items[0]?.kind==="preset",Xe=Math.max(2,ct.columns),rr=Lt?`${NA}px repeat(${Math.max(1,Xe-1)}, minmax(0, 1fr))`:`repeat(${Xe}, minmax(0, 1fr))`;return o.jsx("div",{className:"relative grid gap-1",style:{gridTemplateColumns:rr},children:ct.items.map(Ln=>Ln.kind==="preset"?o.jsx(MA,{buttonRef:Ln.id==="preset"?Ze:void 0,mode:f,presetLabel:c,title:u,disabled:Ee,onPointerDown:Zt},Ln.id):Ln.kind==="alt"?o.jsx("button",{type:"button",onPointerDown:qe=>at(qe,"alt"),tabIndex:-1,disabled:Ee,className:`h-7 w-full rounded-full shadow-sm text-xs disabled:opacity-50 flex items-center justify-center transition-all ${r==="alt"?"bg-primary text-primary-foreground scale-105 shadow-md shadow-primary/40":"bg-surface-2"} ${s==="alt"?"ring-2 ring-accent":""}`,children:o.jsx("span",{className:"font-medium",children:s==="alt"?"Alt*":"Alt"})},Ln.id):Ln.kind==="text"?o.jsxs("button",{type:"button",onPointerDown:qe=>cn(qe,Ln.action),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm px-1 text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 relative",children:[Ln.action.label,Ln.action.doubleTapSequence&&o.jsx("span",{className:"absolute top-0.5 right-1.5 h-1 w-1 rounded-full bg-accent/60"})]},Ln.id):o.jsx("button",{type:"button",onPointerDown:qe=>Je(qe,Ln.keyName),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:Ln.keyName==="ctrl-d"?"Ctrl-D":Ln.keyName==="home"?"Home":"End"},Ln.id))},`row-${Rt}`)})})]})})]})},TQ=({isMobile:e,isInputFocused:t,isIOS:n,isConnecting:r,connectionError:s,terminalSessionId:i})=>{if(typeof window>"u")return null;const a=window.visualViewport?Math.max(0,Math.round(window.innerHeight-window.visualViewport.height-window.visualViewport.offsetTop)):0;return o.jsxs("div",{className:"px-3 py-2 bg-surface text-foreground text-xs border-b border-border/15",children:[o.jsx("div",{className:"font-bold mb-2",children:"Debug Info"}),o.jsxs("div",{className:"grid grid-cols-2 gap-1 font-mono",children:[o.jsxs("div",{children:["isMobile: ",o.jsx("span",{className:e?"text-accent":"text-destructive",children:String(e)})]}),o.jsxs("div",{children:["touchPoints: ",navigator.maxTouchPoints]}),o.jsxs("div",{children:["innerWidth: ",window.innerWidth]}),o.jsxs("div",{children:["innerHeight: ",window.innerHeight]}),o.jsxs("div",{children:["viewportH:"," ",window.visualViewport?Math.round(window.visualViewport.height):"N/A"]}),o.jsxs("div",{children:["inputFocused: ",String(t)]}),o.jsxs("div",{children:["keyboard~: ",a,"px"]}),o.jsxs("div",{children:["connecting:"," ",o.jsx("span",{className:r?"text-muted-foreground":"text-accent",children:String(r)})]}),o.jsxs("div",{children:["sessionId:"," ",o.jsx("span",{className:i?"text-accent":"text-destructive",children:i?"✓":"✗"})]}),o.jsxs("div",{children:["error:"," ",o.jsx("span",{className:s?"text-destructive":"text-accent",children:s?"Yes":"No"})]}),o.jsxs("div",{children:["isIOS:"," ",o.jsx("span",{className:n?"text-muted-foreground":"text-accent",children:String(n)})]})]}),o.jsx("div",{className:"mt-2 pt-2 border-t border-border/15",children:o.jsx("div",{children:"Tip: Tap the status bar 3 times to toggle debug panel"})})]})},CQ=/^Reconnecting/i,kQ=({connectionError:e,isFatalError:t,isRestarting:n,isConnecting:r,onHardRestart:s})=>{const{t:i}=ir(),a=!!e&&CQ.test(e);return r&&!e||a?o.jsx("div",{className:"absolute inset-x-0 bottom-0 flex items-end justify-center pb-2 pointer-events-none",children:o.jsx("span",{className:"text-[11px] text-muted-foreground/60 animate-pulse tracking-wide",children:e||i("connection.reconnecting")})}):e?o.jsx("div",{className:"absolute inset-x-0 bottom-0 flex items-end justify-center pb-2",children:o.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-destructive/70",children:[o.jsx("span",{children:e}),t&&o.jsx("button",{type:"button",onClick:s,disabled:n,className:"text-[11px] text-destructive/90 hover:text-destructive underline underline-offset-2 transition-colors disabled:opacity-40",children:i("common.retry")})]})}):null};let hh=[],eb=!1;function Ja(e,t,n={}){typeof window>"u"||(hh.push(JSON.stringify({level:e,message:t,data:{ts:Date.now(),...n}})),_Q())}async function _Q(){if(!eb){eb=!0;try{for(;hh.length>0;){const e=hh[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}),hh.shift()}catch{hh=[];break}}}finally{eb=!1}}}const B2=80,LQ=60,EQ="termdock:viewport-keyboard-change",F2="termdock:viewport-layout-change",Xc=240,G3=640,W3=360,IQ=[50,150,300,500,800,1200],RQ=28,NQ=72,DA=500;function MQ({measuredHeight:e,documentVisible:t,editableFocused:n}){return t&&n&&e>=B2}function O2(){if(typeof document>"u")return!1;const e=document.activeElement;return e instanceof HTMLElement&&e.matches('input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])')}function DQ({measuredHeight:e,referenceHeight:t,keyboardOpenAgeMs:n,isIOS:r,isTerminalInputFocused:s}){const i=t-e,a=i>=RQ&&i<=NQ;return r&&s&&n>=DA&&a?t:e}const xg=e=>{const t=typeof e=="number"?e:Number.parseFloat(typeof e=="string"?e:"0");return Number.isFinite(t)&&t>0?Math.round(t):0},jA=(e,t)=>{const n=e.map(xg).filter(r=>r>0);return n.find(r=>r>=Xc)??n[0]??t},Th=()=>typeof window>"u"?G3:jA([window.innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,window.visualViewport?.height,window.screen?.availHeight,window.screen?.height],G3),PA=()=>typeof window>"u"?W3:jA([window.innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,window.visualViewport?.width,window.screen?.availWidth,window.screen?.width],W3),om=e=>{const t=Number.parseFloat(e||"0");return Number.isFinite(t)?Math.max(0,Math.round(t)):0},Q2=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,jQ=()=>typeof window>"u"?!1:navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)").matches===!0,BA=()=>{if(typeof window>"u"||!Q2()||!jQ())return{top:0,right:0,bottom:0,left:0};if(!(Th()>=PA()))return{top:0,right:0,bottom:0,left:0};const t=window.screen?.width||window.innerWidth,n=window.screen?.height||window.innerHeight,r=Math.min(t,n),s=Math.max(t,n);return r>=700?{top:20,right:0,bottom:20,left:0}:s<780?{top:20,right:0,bottom:0,left:0}:{top:s>=852?59:s>=844?47:44,right:0,bottom:34,left:0}};function PQ(e="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const t=xg(window.visualViewport?.height),n=Math.max(0,Math.round(window.visualViewport?.offsetTop??0)),r=Th(),i=t>=Xc?Math.min(r,t+n):r,a=Math.max(r,i),c=document.documentElement.style;c.setProperty(e,`${Math.max(i,Xc)}px`),c.setProperty("--app-base-vh",`${Math.max(a,Xc)}px`),c.setProperty("--app-visible-vh",`${Math.max(i,Xc)}px`),c.setProperty("--app-vv-offset-top",`${n}px`),c.setProperty("--kb-translate-y","0px"),c.setProperty("--kb-margin-top","0px"),c.setProperty("--kb-height","0px");const u=BA();u.top>0&&c.setProperty("--safe-top-inset",`${u.top}px`),u.right>0&&c.setProperty("--safe-right-inset",`${u.right}px`),u.bottom>0&&c.setProperty("--safe-bottom-inset",`${u.bottom}px`),u.left>0&&c.setProperty("--safe-left-inset",`${u.left}px`)}function BQ(e={}){const{cssVarName:t="--app-vh"}=e,n=I.useMemo(()=>pd("viewport"),[]),r=I.useCallback(()=>{if(typeof window>"u")return 0;const v=window.visualViewport,S=Th();if(!v)return S;const A=xg(v.height);if(A<Xc&&S>=Xc)return S;const C=v.offsetTop,R=A<S-1&&C>0&&C<=96?A+C:A,M=Math.max(0,Math.min(S,R));return M>0?Math.round(M):S},[]),[s,i]=I.useState(r),a=I.useRef([]),c=I.useRef(0),u=I.useRef(0),f=I.useRef(0),p=I.useRef(!1),g=I.useRef(null),y=I.useRef(new Map);return I.useEffect(()=>{if(typeof window>"u")return;let v=null,S=null;const A=new Set,C=(V,q,ue)=>[V,q,ue].sort((Ce,ee)=>Ce-ee)[1],L=()=>{if(S?.isConnected)return S;try{return S=document.createElement("div"),S.setAttribute("aria-hidden","true"),S.style.cssText=["position:fixed","top:0","left:0","width:0","height:0","visibility:hidden","pointer-events:none","padding-top:constant(safe-area-inset-top)","padding-top:env(safe-area-inset-top,0px)","padding-right:constant(safe-area-inset-right)","padding-right:env(safe-area-inset-right,0px)","padding-bottom:constant(safe-area-inset-bottom)","padding-bottom:env(safe-area-inset-bottom,0px)","padding-left:constant(safe-area-inset-left)","padding-left:env(safe-area-inset-left,0px)"].join(";"),(document.body||document.documentElement).appendChild(S),S}catch{}return null},R=()=>{let V={top:0,right:0,bottom:0,left:0};try{const Ce=L();if(Ce){const ee=getComputedStyle(Ce);V={top:om(ee.paddingTop),right:om(ee.paddingRight),bottom:om(ee.paddingBottom),left:om(ee.paddingLeft)}}}catch{}const q=BA(),ue={top:Math.max(V.top,q.top),right:Math.max(V.right,q.right),bottom:Math.max(V.bottom,q.bottom),left:Math.max(V.left,q.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${ue.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${ue.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${ue.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${ue.left}px`),ue},M=(V,q,ue,Ce)=>{const ee=Math.max(q,ue);if(c.current===0){c.current=ee,u.current=V,document.documentElement.style.setProperty("--app-base-vh",`${ee}px`);return}const Ee=Math.abs(V-u.current),Ze=Ce<=B2;(Ee>LQ||Ze)&&(c.current=ee,u.current=V,document.documentElement.style.setProperty("--app-base-vh",`${ee}px`))},B=(V="event")=>{v=null;const q=r(),ue=Math.round(window.visualViewport?.offsetTop??0),Ce=xg(window.visualViewport?.height),ee=Ce>=Xc?Ce:q,Ee=Th(),Ze=PA(),$e=Math.max(0,ee+ue),Ue=R(),ne=Ue.bottom,lt=Math.max(0,c.current-$e-ne);M(Ze,Ee,$e,lt);const Ye=a.current;Ye.push(q),Ye.length>3&&Ye.shift();let me=q;Ye.length===3&&q<=Ye[0]&&(me=C(Ye[0],Ye[1],Ye[2])),i(pt=>pt===q?pt:q);const se=Number.parseInt(document.documentElement.style.getPropertyValue(t)||"0",10);document.documentElement.style.setProperty(t,`${me}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${ue}px`);const _e=c.current,he=Math.min(me,ee),He=Math.max(0,Math.min(_e,$e)),Je=Math.max(0,Math.round(_e-He-ne)),at=O2(),ge=MQ({measuredHeight:Je,documentVisible:document.visibilityState==="visible",editableFocused:at}),Ie=ge,tt=performance.now();Ie&&g.current===null?g.current=tt:Ie||(g.current=null);const Le=g.current===null?0:Math.max(0,tt-g.current),fe=Ze>_e?"landscape":"portrait",Qe=Math.round(Ze/20)*20,ft=`${fe}:${Qe}`,Mt=y.current.get(ft)??0,cn=document.activeElement?.matches('[data-terminal-input-anchor="true"]')===!0,mt=ge?DQ({measuredHeight:Je,referenceHeight:Mt,keyboardOpenAgeMs:Le,isIOS:Q2(),isTerminalInputFocused:cn}):0,Bt=mt>=B2;Q2()&&cn&&Ie&&Le>=DA&&Je>Mt&&y.current.set(ft,Je);const Zt=-mt,It=mt;document.documentElement.style.setProperty("--kb-translate-y",`${Zt}px`),document.documentElement.style.setProperty("--kb-margin-top",`${It}px`),document.documentElement.style.setProperty("--kb-height",`${mt}px`),document.documentElement.style.setProperty("--app-visible-vh",`${He}px`);const nn=Math.abs(mt-f.current)>1,xe=Bt!==p.current;(nn||xe)&&(f.current=mt,p.current=Bt,document.dispatchEvent(new CustomEvent(EQ,{detail:{baseHeight:_e,visibleHeight:He,visualViewportHeight:ee,offsetTop:ue,keyboardHeight:mt,isOpen:Bt,source:V}}))),(se!==me||ue>0||nn||xe)&&n("sync",{cssVarName:t,innerHeight:Ee,baseHeight:_e,rawViewportHeight:ee,offsetTop:ue,visibleHeight:He,rawHeight:q,appliedHeight:me,keyboardViewportHeight:he,measuredKeyboardHeight:Je,editableFocused:at,applyKeyboardInset:ge,referenceKeyboardHeight:Mt,keyboardOpenAgeMs:Math.round(Le),correctedKeyboardToolbar:mt!==Je,keyboardHeight:mt,isKeyboardOpen:Bt,safeAreaInsets:Ue,filtered:me!==q,source:V}),document.dispatchEvent(new CustomEvent(F2,{detail:{height:me,baseHeight:_e,visibleHeight:He,offsetTop:ue,source:V}}))},F=(V="event")=>{(V.includes("visibilitychange")||V.includes("pageshow"))&&n("schedule",{source:V}),v===null&&(v=window.requestAnimationFrame(()=>B(V)))},N=V=>{F(`${V}:now`);for(const q of IQ){const ue=window.setTimeout(()=>{A.delete(ue),F(`${V}:${q}ms`)},q);A.add(ue)}};N("mount");const T=()=>F("resize"),$=()=>F("orientationchange"),O=()=>F("visualViewport.resize"),Y=()=>F("visualViewport.scroll"),W=()=>N("focusin"),ye=()=>N("focusout"),ce=V=>{const q=document.activeElement;q instanceof HTMLElement&&O2()&&q.blur(),g.current=null,f.current=0,p.current=!1,a.current=[];const ue=Math.max(c.current,Th(),Xc),Ce=document.documentElement.style;Ce.setProperty(t,`${ue}px`),Ce.setProperty("--app-visible-vh",`${ue}px`),Ce.setProperty("--app-vv-offset-top","0px"),Ce.setProperty("--kb-translate-y","0px"),Ce.setProperty("--kb-margin-top","0px"),Ce.setProperty("--kb-height","0px"),i(ee=>ee===ue?ee:ue),n("keyboard session reset",{source:V,baseHeight:ue})};window.addEventListener("resize",T),window.addEventListener("orientationchange",$),window.visualViewport?.addEventListener("resize",O),window.visualViewport?.addEventListener("scroll",Y),document.addEventListener("focusin",W),document.addEventListener("focusout",ye);const ve=V=>{n("resume",{source:V,innerHeight:Math.round(window.innerHeight),visualViewport:window.visualViewport?{width:Math.round(window.visualViewport.width),height:Math.round(window.visualViewport.height),offsetTop:Math.round(window.visualViewport.offsetTop)}:null,hidden:document.hidden}),N(V)},re=()=>{document.hidden?ce("visibilitychange:hidden"):ve("visibilitychange")},ke=()=>ve("pageshow"),X=()=>ce("pagehide");return document.addEventListener("visibilitychange",re),window.addEventListener("pageshow",ke),window.addEventListener("pagehide",X),()=>{window.removeEventListener("resize",T),window.removeEventListener("orientationchange",$),window.visualViewport?.removeEventListener("resize",O),window.visualViewport?.removeEventListener("scroll",Y),document.removeEventListener("focusin",W),document.removeEventListener("focusout",ye),document.removeEventListener("visibilitychange",re),window.removeEventListener("pageshow",ke),window.removeEventListener("pagehide",X),v!==null&&window.cancelAnimationFrame(v),A.forEach(V=>window.clearTimeout(V)),A.clear(),S?.remove()}},[t,n,r]),s}const FQ=120,OQ=80,QQ=400;function V3(){if(typeof window>"u"||document.visibilityState!=="visible"||!O2())return 0;const e=Number.parseFloat(document.documentElement.style.getPropertyValue("--kb-height")||"0");if(Number.isFinite(e)&&e>0)return Math.round(e);const t=window.visualViewport;if(!t)return 0;const n=Number.parseFloat(document.documentElement.style.getPropertyValue("--app-base-vh")||"0")||window.innerHeight,r=Number.parseFloat(document.documentElement.style.getPropertyValue("--safe-bottom-inset")||"0")||0,s=t.height+t.offsetTop;return Math.max(0,Math.round(n-s-r))}function FA(e){const{enabled:t,openThresholdPx:n=FQ,closeThresholdPx:r=OQ,settleDelayMs:s=QQ}=e,i=I.useMemo(()=>pd("keyboard"),[]),a=I.useRef(!1),c=I.useRef(null),u=I.useRef(0),[f,p]=I.useState({isOpen:!1,isSettled:!1,keyboardHeight:0});return I.useEffect(()=>{if(typeof window>"u"||!t){a.current=!1,c.current!==null&&(clearTimeout(c.current),c.current=null),p(N=>!N.isOpen&&!N.isSettled&&N.keyboardHeight===0?N:{isOpen:!1,isSettled:!1,keyboardHeight:0});return}let g=null;const y=()=>{g=null;const N=V3();let T=a.current;if(N>=n?T=!0:N<=r&&(T=!1),a.current=T,T){const $=Math.abs(N-u.current);u.current=N,$>10&&(c.current!==null&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,p(O=>O.isSettled?O:{...O,isSettled:!0})},s))}else c.current!==null&&(clearTimeout(c.current),c.current=null);p($=>{const O=T?$.isSettled:!1;return $.isOpen===T&&$.keyboardHeight===N&&$.isSettled===O?$:(i("sync",{keyboardHeight:N,isOpen:T,isSettled:O,visualViewport:window.visualViewport?{width:Math.round(window.visualViewport.width),height:Math.round(window.visualViewport.height),offsetTop:Math.round(window.visualViewport.offsetTop)}:null}),{isOpen:T,isSettled:O,keyboardHeight:N})})},v=(N="event")=>{(N.includes("visibilitychange")||N.includes("pageshow"))&&i("schedule",{source:N}),g===null&&(g=window.requestAnimationFrame(y))};v("mount");const S=()=>v("resize"),A=()=>v("orientationchange"),C=()=>v("visualViewport.resize"),L=()=>v("visualViewport.scroll"),R=()=>v("viewport-keyboard-change");window.addEventListener("resize",S),window.addEventListener("orientationchange",A),window.visualViewport?.addEventListener("resize",C),window.visualViewport?.addEventListener("scroll",L),document.addEventListener("termdock:viewport-keyboard-change",R);const M=N=>{i("resume",{source:N,keyboardHeight:V3(),hidden:document.hidden}),v(`${N}:now`),window.setTimeout(()=>v(`${N}:50ms`),50),window.setTimeout(()=>v(`${N}:200ms`),200)},B=()=>{document.hidden||M("visibilitychange")},F=()=>M("pageshow");return document.addEventListener("visibilitychange",B),window.addEventListener("pageshow",F),()=>{window.removeEventListener("resize",S),window.removeEventListener("orientationchange",A),window.visualViewport?.removeEventListener("resize",C),window.visualViewport?.removeEventListener("scroll",L),document.removeEventListener("termdock:viewport-keyboard-change",R),document.removeEventListener("visibilitychange",B),window.removeEventListener("pageshow",F),g!==null&&window.cancelAnimationFrame(g),c.current!==null&&(clearTimeout(c.current),c.current=null)}},[i,t,n,r,s]),f}const Wm=300,$Q=120,HQ=250,zQ=6e4;function tb(e,t){return t?e.find(n=>n.id===t||n.backendSessionId===t)?.id??null:null}function am(e){return e.prioritySessionId??e.activeSessionId??e.persistedActiveSessionId??e.firstSessionId}function UQ(e){return e.foregroundSessionId===null||e.sessionId===e.foregroundSessionId||e.foregroundReady}function GQ(e){return e.sessionId===e.foregroundSessionId||e.visibleSessionIds.has(e.sessionId)||e.deferredViewportSessionIds.has(e.sessionId)}function WQ(e){return e.isMobile&&(!e.viewportReady||!e.streamReady||!e.contentReady)}function VQ(e){return e.writtenChunkId!==null&&e.initialTargetChunkId!==null&&e.writtenChunkId>=e.initialTargetChunkId}function qQ(e){return!e.initialConnectionPending}function KQ(e){return!e}function YQ(e){return e.requestToken===0||e.foregroundSessionId===null||e.sessionId===e.foregroundSessionId||e.foregroundCompletedToken===e.requestToken}function XQ(e,t){return e===null||t-e>=HQ}function ZQ(e){return e.wasPageHidden||e.reason==="bfcache"||e.reason==="online"}function JQ(e){return!e.isActive||e.isStreamReady||e.reconnectStartedAt===null?null:Math.max(0,zQ-(e.now-e.reconnectStartedAt))}function e$(e,t){const n=new Map;let r=0;for(const s of e)if(!n.has(s)){if(t.has(s)){n.set(s,0);continue}n.set(s,Wm+r*$Q),r+=1}return n}const t$="Session not found on server",nb="Terminal session not found",n$="STALE_SESSION_RESTORE_REJECTED";function r$(e){return e?.message===t$}function q3(e){return e?.code===n$}function ph(e,t){if(!e||e.startsWith("/"))return e;const n=e.replace(/^\.\//,"");return t?`${t.replace(/\/+$/,"")}/${n}`:n}function u1(e,t){return ph(e,t).replace(/ /g,"\\ ")}function OA(e,t){return`${u1(e,t)} `}function $2(e,t){return u1(e,t)}function s$(e,t,n){if(!n)return $2(e,t);const r=n.start===n.end?`${n.start}`:`${n.start}-${n.end}`;return`${$2(e,t)}:${r}`}const i$="/tmp";async function QA(e,t,n){const s=(await t(i$,[e])).files[0];if(!s?.path)throw new Error("Upload did not return a file path");return n(s.path),s}const o$=QA;function Gr(e,t){if(typeof window>"u")return null;try{const n=window.localStorage.getItem(e);if(n===null||n==="")return null;const r=JSON.parse(n);return t(r)?r:null}catch{return null}}function Wn(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function rb(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(e)}catch{}}const Ch=new Map,kh=new Map,Vm=new Map;function C0(e,t,n){if(typeof window>"u")return;const r=Date.now(),s=Vm.get(e)??0,i=r-s;if(i>=n){Vm.set(e,r),Wn(e,t);return}if(kh.set(e,t),Ch.has(e))return;const a=n-i,c=setTimeout(()=>{Ch.delete(e);const u=kh.get(e);kh.delete(e),Vm.set(e,Date.now()),u!==void 0&&Wn(e,u)},a);Ch.set(e,c)}function c0(e){const t=Ch.get(e);t&&(clearTimeout(t),Ch.delete(e));const n=kh.get(e);n!==void 0&&(kh.delete(e),Vm.set(e,Date.now()),Wn(e,n))}function a$(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}const l$=600,Ph=320,c$=280,yv=5;function qm(e,t,n=0){const r=Math.max(Ph,t-Math.max(0,n)-yv*(n>0?2:1)-c$);return Math.min(r,Math.max(Ph,e))}const $A="termdock:right-sidebar:tabs-by-session:v2",HA="termdock:right-sidebar:explorer-roots-by-session:v2",vv="termdock:right-sidebar:pinned-explorer-roots:v1",zA="termdock:right-sidebar:selected-files-by-session:v2",UA="termdock:right-sidebar:show-hidden-files:v1",H2="termdock:right-sidebar:file-sort-modes:v1",K3="termdock-sidebar-group-by-folder",GA="termdock-sidebar-collapsed-folder-groups",WA="termdock-left-sidebar-pinned",VA="termdock-left-sidebar-width",qA="termdock-right-sidebar-pinned",KA="termdock-right-sidebar-width",wv="termdock:right-sidebar:widths-by-session:v1",YA="termdock:right-sidebar:split-state-initialized:v1",XA="termdock-right-sidebar-layout-preference";function u$(){if(typeof window>"u")return!0;try{const e=window.localStorage.getItem(WA);return e===null?!0:e==="1"}catch{return!0}}function Y3(e){if(!(typeof window>"u"))try{window.localStorage.setItem(WA,e?"1":"0")}catch{}}function d$(){if(typeof window>"u")return 300;try{const e=window.localStorage.getItem(VA);if(!e)return 300;const t=parseInt(e,10);return Number.isFinite(t)&&t>=200&&t<=500?t:300}catch{return 300}}function f$(e){if(!(typeof window>"u"))try{window.localStorage.setItem(VA,String(e))}catch{}}function h$(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(qA)==="1"}catch{return!1}}function X3(e){if(!(typeof window>"u"))try{window.localStorage.setItem(qA,e?"1":"0")}catch{}}function Km(){if(typeof window>"u")return 760;try{const e=window.localStorage.getItem(KA);if(!e)return 760;const t=parseInt(e,10);return Number.isFinite(t)&&t>=Ph?t:760}catch{return 760}}function p$(e){if(!(typeof window>"u"))try{window.localStorage.setItem(KA,String(e))}catch{}}function m$(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="number"&&Number.isFinite(t)&&t>=Ph)}function bg(){return Gr(wv,m$)??{}}function Z3(e,t){if(!e){p$(t);return}Wn(wv,{...bg(),[e]:t})}function g$(){if(typeof window>"u")return"auto";try{const e=window.localStorage.getItem(XA);return e==="narrow"||e==="wide"?e:"auto"}catch{return"auto"}}function x$(e){if(!(typeof window>"u"))try{window.localStorage.setItem(XA,e)}catch{}}function b$(e,t,n){return!t||n==="auto"?e<l$:n==="narrow"}function y$(){return!0}function J3(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(K3,"1"):window.localStorage.setItem(K3,"0")}catch{}}function v$(){if(typeof window>"u")return new Set;try{const e=window.localStorage.getItem(GA);if(!e)return new Set;const t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function w$(e){if(!(typeof window>"u"))try{window.localStorage.setItem(GA,JSON.stringify([...e]))}catch{}}function S$(e){return e==="git"||e==="files"||e==="diff"}function A$(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(S$)}function z2(){return Gr($A,A$)??{}}function sb(e,t){e&&Wn($A,{...z2(),[e]:t})}function T$(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function e6(){return Gr(HA,T$)??{}}function lm(e){Wn(HA,e)}function C$(e){return e!==null&&typeof e=="object"&&typeof e.path=="string"&&(e.kind==="file"||e.kind==="directory")}function k$(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>Array.isArray(t)&&t.every(n=>typeof n=="string"||C$(n)))}function ZA(e){const t=new Set,n=[];for(const r of e){const s=typeof r=="string"?{path:r,kind:"directory"}:r;!s.path||t.has(s.path)||(t.add(s.path),n.push(s))}return n}function _$(){const e=Gr(vv,k$)??{},t={};for(const[n,r]of Object.entries(e))t[n]=ZA(r);return t}function t6(e){Wn(vv,e)}function L$(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function U2(){return Gr(zA,L$)??{}}function Wf(e,t){if(!e)return;const n={...U2()};t?n[e]=t:delete n[e],Wn(zA,n)}function yg(e,t){return t?e?`${e}\0${t}`:t:null}function G2(e,t,n){return n?`split-workspace\0${n}`:yg(e,t)}function E$(e,t,n){const r=bg(),s=G2(e,t,n);if(s&&r[s]!==void 0)return r[s];if(n){const i=yg(e,t);if(i&&r[i]!==void 0)return r[i]}return Km()}function JA(){const e=Gr(YA,t=>Array.isArray(t)&&t.every(n=>typeof n=="string"));return new Set(e??[])}function I$(e){const t=JA();t.has(e)||(t.add(e),Wn(YA,[...t]))}function R$(e){return typeof e=="boolean"}function N$(){return Gr(UA,R$)??!1}function M$(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>t==="modified")}function D$(){return Gr(H2,M$)??{}}let Vf=null;const ib=new Map;let qf=null;const ob=globalThis.crypto?.randomUUID?.()??`pins-${Math.random().toString(36).slice(2)}`;function j$(e){const t=e.replace(/\/+$/,"")||"/";return t==="/"?"/":t.slice(0,t.lastIndexOf("/"))||"/"}function Zd(e,t){const n=e.replace(/\/+$/,"")||"/";return t===n||t.startsWith(`${n}/`)}function n6(e,t="name"){return[...e].sort((n,r)=>{if(n.type==="directory"&&r.type!=="directory")return-1;if(n.type!=="directory"&&r.type==="directory")return 1;if(t==="modified"){const s=Date.parse(r.modified??"")-Date.parse(n.modified??"");if(Number.isFinite(s)&&s!==0)return s}return n.name.localeCompare(r.name)})}function P$(e){return e.entry?{name:e.entry.name,path:e.entry.path,type:e.entry.type,isSymlink:e.entry.isSymlink,modified:e.entry.modified,expanded:!1,loaded:!1,children:e.entry.type==="directory"?[]:void 0}:null}const ht=e8(e=>({leftOpen:!1,rightOpen:!1,leftPinned:u$(),leftSidebarWidth:d$(),rightPinned:h$(),rightSidebarWidth:Km(),rightSidebarLayoutPreference:g$(),rightTab:"files",rightSearchOpen:!1,rootPath:null,contextKey:null,rightSidebarWidthContextKey:null,explorerRoot:null,explorerRootCache:e6(),pinnedExplorerRootsCache:_$(),pinnedExplorerRootsHydrated:!1,expandedPaths:new Set,selectedFilePath:null,directoryCache:new Map,fileSortModes:D$(),fileSortModesHydrated:!1,showHiddenFiles:N$(),groupByFolder:y$(),collapsedGroups:v$(),changedFiles:new Map,fileChangeVersions:new Map,fileWatchEpoch:0,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null,gitBundleError:null,gitBundleLastLoadedAt:null,gitBundleCacheInfo:null,projectStateCache:new Map,openLeft:()=>e({leftOpen:!0}),closeLeft:()=>e({leftOpen:!1}),toggleLeft:()=>e(t=>({leftOpen:!t.leftOpen,rightOpen:t.leftOpen?t.rightOpen:!1})),toggleLeftPinned:()=>e(t=>{const n=!t.leftPinned;return Y3(n),{leftPinned:n,leftOpen:!0}}),setLeftPinned:t=>e(()=>(Y3(t),{leftPinned:t})),setLeftSidebarWidth:t=>e(n=>{const r=Math.min(Math.max(t,200),500);return n.leftSidebarWidth===r?n:(f$(r),{leftSidebarWidth:r})}),toggleRightPinned:()=>e(t=>{const n=!t.rightPinned;return X3(n),{rightPinned:n,rightOpen:!0}}),setRightPinned:t=>e(()=>(X3(t),{rightPinned:t})),setRightSidebarWidth:t=>e(n=>{const r=Math.max(t,Ph);return n.rightSidebarWidth===r?n:(Z3(n.rightSidebarWidthContextKey,r),{rightSidebarWidth:r})}),setRightSidebarLayoutPreference:t=>e(n=>n.rightSidebarLayoutPreference===t?n:(x$(t),{rightSidebarLayoutPreference:t})),openRight:()=>e({rightOpen:!0}),closeRight:()=>e({rightOpen:!1,rightSearchOpen:!1}),toggleRight:()=>e(t=>({rightOpen:!t.rightOpen,rightSearchOpen:t.rightOpen?!1:t.rightSearchOpen,leftOpen:t.rightOpen?t.leftOpen:!1})),closeAll:()=>e({leftOpen:!1,rightOpen:!1,rightSearchOpen:!1}),setRightTab:t=>e(n=>(sb(n.contextKey,t),{rightTab:t})),openRightSearch:()=>e({rightSearchOpen:!0}),closeRightSearch:()=>e({rightSearchOpen:!1}),setRightSearchOpen:t=>e({rightSearchOpen:t}),setRootPath:(t,n=null,r=null)=>e(s=>{const i=yg(n,t),a=G2(n,t,r),c=r?a:i;if(s.contextKey===c&&s.rightSidebarWidthContextKey===a)return t===s.rootPath?s:{rootPath:t};const u=new Map(s.projectStateCache);s.contextKey&&u.set(s.contextKey,{rightTab:s.rightTab,explorerRoot:s.explorerRoot,expandedPaths:new Set(s.expandedPaths),selectedFilePath:s.selectedFilePath,directoryCache:new Map(s.directoryCache),changedFiles:new Map(s.changedFiles),gitBundleError:s.gitBundleError,gitBundleLastLoadedAt:s.gitBundleLastLoadedAt,gitBundleCacheInfo:s.gitBundleCacheInfo});const f=r?JA().has(r):!1;let p={...e6(),...s.explorerRootCache};const g=!!r&&!f,y=g&&i?s.contextKey===i?{rightTab:s.rightTab,explorerRoot:s.explorerRoot,expandedPaths:new Set(s.expandedPaths),selectedFilePath:s.selectedFilePath,directoryCache:new Map(s.directoryCache),changedFiles:new Map(s.changedFiles),gitBundleError:s.gitBundleError,gitBundleLastLoadedAt:s.gitBundleLastLoadedAt,gitBundleCacheInfo:s.gitBundleCacheInfo}:u.get(i):void 0;if(g&&r){const M=y?.rightTab??(i?z2()[i]:void 0)??"files",B=y?.explorerRoot??(i?s.explorerRootCache[i]:void 0)??t,F=y?.selectedFilePath??(i?U2()[i]:void 0)??null,N={rightTab:M,explorerRoot:B,expandedPaths:new Set(y?.expandedPaths??[]),selectedFilePath:F,directoryCache:new Map(y?.directoryCache??[]),changedFiles:new Map(y?.changedFiles??[]),gitBundleError:y?.gitBundleError??null,gitBundleLastLoadedAt:y?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:y?.gitBundleCacheInfo??null};c&&(u.set(c,N),sb(c,M),Wf(c,F),B&&(p={...p,[c]:B},lm(p))),I$(r)}const v=c?u.get(c):void 0,S=c?z2()[c]:void 0,A=bg();let C=a?A[a]:void 0;r&&a&&C===void 0&&(C=(i?A[i]:void 0)??Km(),Z3(a,C));const L=c?p[c]:void 0,R=c?U2()[c]:void 0;return{rootPath:t,contextKey:c,rightSidebarWidthContextKey:a,rightSidebarWidth:C??Km(),rightTab:v?.rightTab??S??"files",explorerRoot:v?.explorerRoot??L??t,expandedPaths:v?new Set(v.expandedPaths):new Set,selectedFilePath:v?.selectedFilePath??R??null,explorerRootCache:p,directoryCache:v?new Map(v.directoryCache):new Map,changedFiles:v?new Map(v.changedFiles):new Map,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null,gitBundleError:v?.gitBundleError??null,gitBundleLastLoadedAt:v?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:v?.gitBundleCacheInfo??null,projectStateCache:u}}),inheritRightSidebarStateFromSplitWorkspace:(t,n)=>e(r=>{if(!t||n.length===0)return r;const s=bg(),i=G2(null,null,t);if(!i)return r;const a=s[i]??(r.rightSidebarWidthContextKey===i?r.rightSidebarWidth:void 0),c=r.contextKey===i?{rightTab:r.rightTab,explorerRoot:r.explorerRoot,expandedPaths:new Set(r.expandedPaths),selectedFilePath:r.selectedFilePath,directoryCache:new Map(r.directoryCache),changedFiles:new Map(r.changedFiles),gitBundleError:r.gitBundleError,gitBundleLastLoadedAt:r.gitBundleLastLoadedAt,gitBundleCacheInfo:r.gitBundleCacheInfo}:r.projectStateCache.get(i);if(a===void 0&&!c)return r;const u={...s},f=new Map(r.projectStateCache),p={...r.explorerRootCache};for(const g of n){const y=yg(g.sessionId,g.rootPath);y&&(a!==void 0&&(u[y]=a),c&&(f.set(y,{...c,expandedPaths:new Set(c.expandedPaths),directoryCache:new Map(c.directoryCache),changedFiles:new Map(c.changedFiles)}),sb(y,c.rightTab),Wf(y,c.selectedFilePath),c.explorerRoot?p[y]=c.explorerRoot:delete p[y]))}return a!==void 0&&Wn(wv,u),c&&lm(p),{projectStateCache:f,explorerRootCache:p}}),setExplorerRoot:t=>e(n=>{if(n.explorerRoot===t)return n;const r={...n.explorerRootCache};return n.contextKey&&t&&(r[n.contextKey]=t,lm(r)),{explorerRoot:t,explorerRootCache:r}}),resetExplorerToProject:()=>e(t=>{if(t.explorerRoot===t.rootPath)return t;const n={...t.explorerRootCache};return t.contextKey&&t.rootPath&&(n[t.contextKey]=t.rootPath,lm(n)),{explorerRoot:t.rootPath,explorerRootCache:n}}),pinExplorerRoot:(t,n="directory")=>e(r=>{if(!r.rootPath||!t)return r;const s=r.rootPath,i=r.pinnedExplorerRootsCache[r.rootPath]??[];if(i.some(c=>c.path===t))return r;const a={...r.pinnedExplorerRootsCache,[r.rootPath]:[{path:t,kind:n},...i].slice(0,12)};return t6(a),(async()=>{try{await ht.getState().hydratePinnedExplorerRoots();const c=await yo({pinnedExplorerRoot:{rootPath:s,path:t,kind:n,pinned:!0},pinnedExplorerRootsOrigin:ob});ht.getState().syncPinnedExplorerRoots(c.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:a}}),unpinExplorerRoot:t=>e(n=>{if(!n.rootPath||!t)return n;const r=n.rootPath,s=n.pinnedExplorerRootsCache[n.rootPath]??[],i=s.find(u=>u.path===t);if(!s.some(u=>u.path===t))return n;const a=s.filter(u=>u.path!==t),c={...n.pinnedExplorerRootsCache};return a.length>0?c[n.rootPath]=a:delete c[n.rootPath],t6(c),(async()=>{try{await ht.getState().hydratePinnedExplorerRoots();const u=await yo({pinnedExplorerRoot:{rootPath:r,path:t,kind:i?.kind??"directory",pinned:!1},pinnedExplorerRootsOrigin:ob});ht.getState().syncPinnedExplorerRoots(u.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:c}}),hydratePinnedExplorerRoots:async()=>{if(!ht.getState().pinnedExplorerRootsHydrated)return qf||(qf=(async()=>{const t=ht.getState().pinnedExplorerRootsCache;let r=(await dd()).pinnedExplorerRoots??{};Object.keys(r).length===0&&Object.keys(t).length>0&&(r=(await yo({pinnedExplorerRoots:t,pinnedExplorerRootsOrigin:ob})).pinnedExplorerRoots??t),ht.getState().syncPinnedExplorerRoots(r)})().finally(()=>{qf=null}),qf)},syncPinnedExplorerRoots:t=>e(()=>{const n={};for(const[r,s]of Object.entries(t)){const i=ZA(s);i.length>0&&(n[r]=i.slice(0,12))}return rb(vv),{pinnedExplorerRootsCache:n,pinnedExplorerRootsHydrated:!0}}),toggleExpanded:t=>e(n=>{const r=new Set(n.expandedPaths);return r.has(t)?r.delete(t):r.add(t),{expandedPaths:r}}),selectFile:t=>e(n=>(Wf(n.contextKey,t),{selectedFilePath:t})),toggleShowHiddenFiles:()=>e(t=>{const n=!t.showHiddenFiles;Wn(UA,n);const r=new Map(t.projectStateCache);for(const[s,i]of r)r.set(s,{...i,directoryCache:new Map});return{showHiddenFiles:n,directoryCache:new Map,projectStateCache:r}}),toggleGroupByFolder:()=>e(t=>{const n=!t.groupByFolder;return J3(n),{groupByFolder:n}}),setGroupByFolder:t=>e(n=>n.groupByFolder===t?n:(J3(t),{groupByFolder:t})),toggleGroupCollapsed:t=>e(n=>{const r=new Set(n.collapsedGroups);return r.has(t)?r.delete(t):r.add(t),w$(r),{collapsedGroups:r}}),setDirectoryCache:(t,n)=>e(r=>{const s=new Map(r.directoryCache);return s.set(t,n),{directoryCache:s}}),reconcileDirectoryCache:(t,n)=>e(r=>{const s=r.directoryCache.get(t);if(!s)return r;const i=new Map(s.map(p=>[p.path,p])),a=new Set(n.map(p=>p.path)),c=new Map(r.directoryCache),u=n.map(p=>{const g=i.get(p.path);return{name:p.name,path:p.path,type:p.type,isSymlink:p.isSymlink,modified:p.modified,expanded:g?.expanded??!1,loaded:g?.loaded??!1,children:p.type==="directory"?g?.children??[]:void 0}});c.set(t,n6(u,r.fileSortModes[t]??"name"));for(const p of s)if(!a.has(p.path))for(const g of c.keys())Zd(p.path,g)&&c.delete(g);let f=r.selectedFilePath;return f&&s.find(g=>!a.has(g.path)&&Zd(g.path,f))&&(f=null,Wf(r.rootPath,null)),{directoryCache:c,selectedFilePath:f}}),hydrateFileSortModes:async()=>{if(!ht.getState().fileSortModesHydrated)return Vf||(Vf=(async()=>{const t=ht.getState().fileSortModes;let r=(await dd()).fileSortModes??{};Object.keys(r).length===0&&Object.keys(t).length>0&&(r=(await yo({fileSortModes:t})).fileSortModes??t),rb(H2),e({fileSortModes:r,fileSortModesHydrated:!0,directoryCache:new Map})})().finally(()=>{Vf=null}),Vf)},setDirectorySortMode:async(t,n)=>{try{await ht.getState().hydrateFileSortModes()}catch{}const r=ht.getState().fileSortModes[t]??"name",s=(ib.get(t)??0)+1;ib.set(t,s),e(i=>{const a={...i.fileSortModes};n==="modified"?a[t]=n:delete a[t];const c=new Map(i.directoryCache);return c.delete(t),{fileSortModes:a,fileSortModesHydrated:!0,directoryCache:c}});try{await yo({fileSortMode:{path:t,mode:n}}),rb(H2)}catch{if(ib.get(t)!==s)return;e(i=>{const a={...i.fileSortModes};r==="modified"?a[t]=r:delete a[t];const c=new Map(i.directoryCache);return c.delete(t),{fileSortModes:a,directoryCache:c}})}},invalidateDirectoryCache:(t,n=!1)=>e(r=>{const s=new Map(r.directoryCache);for(const i of s.keys())(i===t||n&&Zd(t,i))&&s.delete(i);return{directoryCache:s}}),applyFileWatchEvents:t=>e(n=>{if(t.length===0)return n;const r=new Map(n.directoryCache),s=new Map(n.fileChangeVersions);let i=n.selectedFilePath,a=!1,c=!1,u=!1;const f=p=>{s.set(p,(s.get(p)??0)+1),c=!0};for(const p of t){if(p.type==="rescan-required"){u=!0,i&&Zd(p.path,i)&&f(i);continue}const g=j$(p.path),y=r.get(g);if(p.type==="deleted"){if(f(p.path),i&&Zd(p.path,i)&&(i=null,Wf(n.rootPath,null)),y){const C=y.filter(L=>L.path!==p.path);C.length!==y.length&&(r.set(g,C),a=!0)}for(const C of r.keys())Zd(p.path,C)&&(r.delete(C),a=!0);continue}f(p.path);const v=P$(p);if(!v||!y)continue;const S=y.find(C=>C.path===v.path),A=n6(S?y.map(C=>C.path===v.path?{...C,...v,children:C.children}:C):[...y,v],n.fileSortModes[g]??"name");r.set(g,A),a=!0}return!a&&!c&&!u?n:{directoryCache:a?r:n.directoryCache,selectedFilePath:i,fileChangeVersions:c?s:n.fileChangeVersions,fileWatchEpoch:u?n.fileWatchEpoch+1:n.fileWatchEpoch}}),bumpFileWatchEpoch:()=>e(t=>({fileWatchEpoch:t.fileWatchEpoch+1})),setChangedFiles:t=>e({changedFiles:t}),beginGitBundleLoading:t=>e({gitBundleLoading:!0,gitBundleSlow:!1,gitBundleLoadingOwner:t}),setGitBundleSlowFor:(t,n)=>e(r=>r.gitBundleLoadingOwner===t?{gitBundleSlow:n}:r),finishGitBundleLoading:t=>e(n=>n.gitBundleLoadingOwner===t?{gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}:n),resetGitBundleLoading:()=>e({gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}),setGitBundleError:t=>e({gitBundleError:t}),markGitBundleLoaded:(t=null)=>e({gitBundleLastLoadedAt:Date.now(),gitBundleCacheInfo:t})})),B$=320,r6="termdock:mobile-keyboard-expanded",s6="termdock:mobile-keyboard-preset-mode",i6="termdock:mobile-long-press-mode",o6=80,F$=3e3;function ab(){return typeof window>"u"?!1:(navigator.maxTouchPoints>0||"ontouchstart"in window)&&window.innerWidth<768}const O$={retry:{maxRetries:60,initialDelayMs:1e3,maxDelayMs:2e4},connectionTimeoutMs:15e3},Q$=({sessionId:e,mode:t,tmuxSessionName:n=null,terminalSettings:r=pv(),colorTheme:s="dark",toolbarPresets:i=[],isActive:a=!0,focusSuspended:c=!1,deferCursorUntilPositioned:u=!1,isLayoutVisible:f=!0,focusRequestToken:p=0,resumeRequestToken:g=0,resumeRequestReason:y="visibility",resumeRequestDelayMs:v=0,forceResumeReconnect:S=!1,initialConnectDelayMs:A=0,initialConnectEnabled:C=!0,resumeRequestEnabled:L=!0,onStreamReadyChange:R,onStreamConnected:M,onViewportReadyChange:B,onContentReadyChange:F,onKeyboardVisibilityChange:N,suppressKeyboard:T=!1,keyboardPortalTarget:$=null,sharedMobileKeyboardLayout:O=!1,suppressPageFlipRefresh:Y=!1,showDebug:W,onStatusChange:ye})=>{const{t:ce}=ir(),[ve,re]=I.useState(r.fontSize),ke=I.useMemo(()=>iQ(),[]),X=I.useMemo(()=>pd("session"),[]),V=I.useMemo(()=>pd("keyboard"),[]),q=I.useRef(v);q.current=v;const ue=I.useRef(null);I.useEffect(()=>{re(r.fontSize)},[r.fontSize]);const Ce=I.useMemo(()=>({...r,fontSize:ve}),[r,ve]),[ee]=I.useState(e||BE()),[Ee,Ze]=I.useState(ab),[$e,Ue]=I.useState(!1),[ne,lt]=I.useState(!1),[Ye,me]=I.useState(!1),[se,_e]=I.useState(()=>typeof document>"u"?!0:!document.hidden),[he,He]=I.useState(()=>typeof document>"u"?!0:document.hasFocus()),[Je,at]=I.useState(!1),[ge,Ie]=I.useState(!1),[tt,Le]=I.useState(!1),[fe,Qe]=I.useState(!0),[ft,Mt]=I.useState(!1),[cn,mt]=I.useState(!0),{isOpen:Bt,keyboardHeight:Zt}=FA({enabled:Ee&&a}),[It,nn]=I.useState(null),[xe,et]=I.useState(null),[pt,Yt]=I.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(r6)==="true"),[ct,Rt]=I.useState(()=>{if(typeof window>"u")return"auto";const Ae=window.localStorage.getItem(s6);return Ae&&Ae.length>0?Ae:"auto"}),[Lt,Xe]=I.useState(()=>typeof window>"u"?"arrows":window.localStorage.getItem(i6)==="copy"?"copy":"arrows"),[rr,Ln]=I.useState("idle"),[qe,Mn]=I.useState("idle"),[zt,En]=I.useState(0),Hn=ns(Ae=>Ae.sessions.get(ee)),{setTerminalSession:fn,setConnecting:Un,appendToBuffer:cr,replaceBuffer:qr,clearTerminalSession:ss,removeTerminalSession:Oe,clearBuffer:te,setSessionActiveProgram:Tt,setSessionCwd:Fe,setSessionCopyMode:dn,setSessionAgentStatus:In,setSessionShellTitle:kt,setSessionPromptState:Pn,clearAgentNeedsReview:hr}=ns.getState(),wr=I.useMemo(()=>`wt-${ee.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,12)}`,[ee]),pr=Hn?.terminalSessionId??null,Ir=Hn?.mode??"shell",Br=Hn?.activeProgram??null,hn=I.useMemo(()=>x0(i),[i]),kr=Ir==="tmux",Ar=Hn?.bufferChunks??[],mr=Hn?.isConnecting??!1,Kn=pr,Zr=I.useCallback(async Ae=>{const nt=gO(Ae,Hn?.cwd||Hn?.directory);if(!nt)return;let yt=nt,rt="directory";try{yt=(await Yg(nt)).path}catch(_t){if(!(_t instanceof Error)||_t.message!=="Path is not a directory")return;rt="file"}try{const _t=ht.getState();_t.setRightTab("files"),_t.openRight(),window.dispatchEvent(new CustomEvent(j2,{detail:{path:yt,kind:rt}}))}catch{}},[Hn?.cwd,Hn?.directory]),Yn=t??Hn?.mode??"shell",or=Yn==="tmux"?n??Hn?.tmuxSessionName??null:null,[wn,ur]=I.useState(null),fs=I.useRef(!1),[li,Ct]=I.useState(!1),[Kt,J]=I.useState(!1),[we,Ke]=I.useState(null),[We,ut]=I.useState(0),[pe,Pe]=I.useState(null),ze=W!==void 0?W:!1,gt=I.useRef(null),Pt=I.useRef(null),bt=I.useRef(null),vt=I.useRef(null),Et=I.useRef(null),Bn=I.useRef(!1),bn=I.useRef(null),Nt=I.useRef([]),Tr=I.useRef(0),Wr=I.useRef(!1),Rr=I.useRef(null),Xn=I.useRef(null),is=I.useRef(-1),Fr=I.useRef(null),Ss=I.useRef(0),As=I.useRef(null),Gt=I.useRef(null),Sn=I.useRef(0),Lr=I.useRef(!1),Dr=I.useRef(null),Kr=I.useRef(null),Jr=I.useRef(!1),ie=I.useRef(0),Se=I.useRef(!1),Be=I.useRef(!1),it=I.useRef(!1),Ft=I.useRef(null),Dt=I.useRef(null),rn=I.useRef(null),on=I.useRef(null),ln=I.useRef(!1),Vn=I.useRef(!1),sr=I.useRef(null),ar=I.useRef(0),lr=I.useRef(null),Wt=I.useRef(null),Rn=I.useRef(null),pn=I.useRef(a);pn.current=a;const gn=I.useRef(c);gn.current=c;const Ot=I.useRef(Ee),kn=I.useRef(null),_n=I.useRef(null),mn=I.useRef(null),yn=I.useRef(null),xn=I.useRef(null),zr=I.useRef(null),zs=I.useRef(null),mi=I.useCallback(()=>{const Ae=++ie.current,nt=()=>{Ae===ie.current&&Ie(!0)};if(typeof window>"u"){nt();return}window.requestAnimationFrame(()=>window.requestAnimationFrame(nt))},[]),hs=I.useCallback(Ae=>{if(on.current=Ae.lastProcessedChunkId,ln.current&&Vn.current&&Ae.lastProcessedChunkId!==sr.current&&(Wt.current!==null&&(window.clearTimeout(Wt.current),Wt.current=null),Ae.x!==0||Ae.y<Ae.rows-1)){const nt=ar.current;Wt.current=window.setTimeout(()=>{Wt.current=null,nt===ar.current&&(ln.current=!1,Vn.current=!1,Rn.current!==null&&(window.clearTimeout(Rn.current),Rn.current=null),mt(!0))},o6)}if(Se.current){if(Dt.current!==null&&(window.clearTimeout(Dt.current),Dt.current=null),Ae.x===0&&Ae.y>=Ae.rows-1){Qe(!1);return}Dt.current=window.setTimeout(()=>{Dt.current=null,Qe(!0)},o6)}},[]),ll=I.useCallback(Ae=>{if(!Lr.current||!VQ({writtenChunkId:Ae,initialTargetChunkId:Dr.current}))return;const nt=Kr.current;Kr.current=null,nt!==null&&(Et.current?.notifyScreenSynchronized(nt),Vn.current=!0),Lr.current=!1,Dr.current=null,mi()},[mi]),Wi=I.useCallback(Ae=>{if(ln.current){const yt=lr.current;(!yt||yt.x!==Ae.x||yt.y!==Ae.y||yt.rows!==Ae.rows)&&(lr.current=Ae,Wt.current!==null&&(window.clearTimeout(Wt.current),Wt.current=null))}if(!Se.current)return;const nt=Ft.current;nt&&nt.x===Ae.x&&nt.y===Ae.y&&nt.rows===Ae.rows||(Ft.current=Ae,Dt.current!==null&&(window.clearTimeout(Dt.current),Dt.current=null),Ae.x===0&&Ae.y>=Ae.rows-1&&Qe(!1))},[]),Ai=I.useCallback(Ae=>{if(Mt(Ae),Yn!=="tmux"){mt(!0);return}if(Ae){ar.current+=1,ln.current=!0,Vn.current=!1,sr.current=on.current,lr.current=null,Wt.current!==null&&(window.clearTimeout(Wt.current),Wt.current=null),Rn.current!==null&&(window.clearTimeout(Rn.current),Rn.current=null),mt(!1);return}if(!ln.current)return;Vn.current||(ar.current+=1,sr.current=on.current,lr.current=null,Wt.current!==null&&(window.clearTimeout(Wt.current),Wt.current=null));const nt=ar.current;mt(!1),Rn.current=window.setTimeout(()=>{Rn.current=null,nt===ar.current&&(ln.current=!1,Vn.current=!1,mt(!0))},F$)},[Yn]);I.useEffect(()=>{if(!u){Be.current=!1;return}Be.current||(Be.current=!0,it.current=!1,Se.current=!0,Ft.current=null,Qe(!1),Dt.current!==null&&(window.clearTimeout(Dt.current),Dt.current=null),rn.current!==null&&window.clearTimeout(rn.current),rn.current=window.setTimeout(()=>{rn.current=null,Dt.current!==null&&typeof window<"u"&&window.clearTimeout(Dt.current),Dt.current=null,Se.current=!1,Qe(!0)},15e3))},[u]);const Vi=I.useCallback(()=>{yn.current=null;const Ae=mn.current;mn.current=null,Ae&&kt(Ae.sessionId,Ae.title)},[kt]),Mi=I.useCallback((Ae,nt)=>{if(mn.current={sessionId:Ae,title:nt},yn.current===null){if(typeof window>"u"){Vi();return}yn.current=window.requestAnimationFrame(Vi)}},[Vi]),ci=I.useCallback(()=>{yn.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(yn.current),yn.current=null,mn.current=null},[]),Ns=I.useCallback(async()=>{const Ae=Yn;return(await a8({preferredFrontendSessionId:ee,mode:Ae,tmuxSessionName:Ae==="tmux"?or||wr:void 0,termType:"xterm-256color",requireExisting:!0})).terminalSession},[Yn,or,wr,ee]),Cs=I.useRef(!1);I.useEffect(()=>{if(!a){Et.current?.blur(),Cs.current=!1;return}if(Cs.current)return;Cs.current=!0;const Ae=LF(Ee,Y);if(Ae==="single"){Et.current?.requestRefresh("focus",{skipResizePush:!0,skipScrollToBottom:!0});return}if(Ae==="none")return;const nt=Et.current?.getDimensions()??null;let yt=0,rt=0;yt=requestAnimationFrame(()=>{rt=requestAnimationFrame(()=>{Et.current?.requestRefresh("page-flip",{reconcileServerSize:!0,skipScrollToBottom:!0})})});const _t=window.setTimeout(()=>{const Zn=Et.current,qn=Zn?.getDimensions()??null;Zn?.requestRefresh("page-flip",{forceRedraw:SA(nt,qn),reconcileServerSize:!0})},360);return()=>{cancelAnimationFrame(yt),cancelAnimationFrame(rt),window.clearTimeout(_t)}},[a,Ee,Y,Kn]),I.useEffect(()=>{Ot.current=Ee},[Ee]);const Qr=I.useCallback(()=>{!pn.current||gn.current||Et.current?.focus()},[]);I.useLayoutEffect(()=>{c&&Et.current?.blur()},[c]),I.useEffect(()=>{if(!a||c||fe||it.current)return;it.current=!0;const Ae=window.requestAnimationFrame(()=>{Et.current?.requestPtyRedraw()});return()=>window.cancelAnimationFrame(Ae)},[c,a,fe]);const dr=I.useCallback(Ae=>{typeof window>"u"||typeof document>"u"||!pn.current||gn.current||Ot.current||document.hidden||(kn.current!==null&&window.clearTimeout(kn.current),kn.current=window.setTimeout(()=>{if(kn.current=null,!pn.current||gn.current||Ot.current||document.hidden)return;const nt=document.activeElement,yt=nt?.getAttribute("data-terminal-input-anchor")==="true";if((nt instanceof HTMLInputElement||nt instanceof HTMLTextAreaElement||nt instanceof HTMLSelectElement||nt?.isContentEditable===!0)&&!yt){V("desktop resume focus skipped: editable active",{reason:Ae});return}V("desktop resume focus",{reason:Ae}),Et.current?.requestRefresh("focus",{force:!0,forceRedraw:!0,skipResizePush:!0,skipScrollToBottom:!0}),Et.current?.focus()},50))},[V]);I.useEffect(()=>()=>{kn.current!==null&&typeof window<"u"&&window.clearTimeout(kn.current),kn.current=null,_n.current!==null&&typeof window<"u"&&window.clearTimeout(_n.current),_n.current=null,xn.current!==null&&typeof window<"u"&&window.clearTimeout(xn.current),xn.current=null,zr.current!==null&&typeof window<"u"&&window.clearTimeout(zr.current),zr.current=null,rn.current!==null&&typeof window<"u"&&window.clearTimeout(rn.current),rn.current=null,Dt.current!==null&&typeof window<"u"&&window.clearTimeout(Dt.current),Dt.current=null,Wt.current!==null&&typeof window<"u"&&window.clearTimeout(Wt.current),Wt.current=null,Rn.current!==null&&typeof window<"u"&&window.clearTimeout(Rn.current),Rn.current=null},[]),I.useEffect(()=>{if(typeof document>"u"||typeof window>"u")return;const Ae=()=>{_n.current!==null&&window.clearTimeout(_n.current),_n.current=window.setTimeout(()=>{_n.current=null;const nt=document.activeElement,rt=!(nt?.getAttribute("data-terminal-input-anchor")==="true")&&!!(nt&&(nt instanceof HTMLInputElement||nt instanceof HTMLTextAreaElement||nt instanceof HTMLSelectElement||nt.isContentEditable));nQ({isActive:pn.current&&!gn.current,isMobile:Ot.current,documentVisible:!document.hidden,activeElementIsEditable:rt})&&Qr()},0)};return document.addEventListener("pointerup",Ae),()=>{document.removeEventListener("pointerup",Ae),_n.current!==null&&(window.clearTimeout(_n.current),_n.current=null)}},[Qr]);const gs=I.useCallback(()=>{Pi.current=!1,ut(Ae=>Ae+1)},[]),Ao=I.useCallback((Ae,nt)=>{const yt=bt.current,rt=Date.now();if(yt&&nt&&vI(yt)){ue.current={startedAt:rt,strategy:"reconnect",reason:Ae},Ja("info","PWA_RESUME terminal-start",{frontendSessionId:ee,backendSessionId:yt,strategy:"reconnect",reason:Ae,active:pn.current});return}if(yt&&yI(yt,()=>{const _t=ue.current;Ja("info","PWA_RESUME terminal-responsive",{frontendSessionId:ee,backendSessionId:yt,durationMs:_t?Date.now()-_t.startedAt:null,strategy:_t?.strategy??"probe",reason:_t?.reason??Ae}),ue.current=null,M?.(ee)})){ue.current={startedAt:rt,strategy:"probe",reason:Ae},Ja("info","PWA_RESUME terminal-start",{frontendSessionId:ee,backendSessionId:yt,strategy:"probe",reason:Ae,active:pn.current}),X("[Terminal] resume probe sent",{reason:Ae,backendSessionId:yt,active:pn.current});return}if(X("[Terminal] resume probe missing connection, restarting ensureSession",{reason:Ae,backendSessionId:yt,active:pn.current}),!qQ({initialConnectionPending:Jr.current})){X("[Terminal] resume probe deferred during initial websocket handshake",{reason:Ae,backendSessionId:yt});return}gs()},[X,M,gs,ee]),Ti=I.useCallback((Ae,nt)=>{const yt=bt.current;yt&&bn.current!==Ae&&(bn.current=Ae,rw(yt,Ae,nt),X("[Terminal] flow-control state sent",{backendSessionId:yt,paused:Ae,reason:nt}))},[X]),Cr=I.useCallback((Ae,nt)=>{const yt=bt.current;yt&&As.current!==Ae&&(As.current=Ae,ew(yt,Ae,nt),X("[Terminal] focus state sent",{backendSessionId:yt,focused:Ae,reason:nt}))},[X]),Di=I.useCallback((Ae,nt)=>{const yt=bt.current;yt&&Gt.current!==Ae&&(Gt.current=Ae,tw(yt,Ae,nt),X("[Terminal] viewing state sent",{backendSessionId:yt,viewing:Ae,reason:nt}))},[X]),To=eQ({isActive:a&&!c,viewportFocused:Ye,documentVisible:se,windowFocused:he,streamReady:Je}),ks=tQ({isActive:a,documentVisible:se,windowFocused:he,streamReady:Je,isDesktop:so()!==null}),ji=I.useRef(To),Qa=I.useRef(ks);I.useEffect(()=>{ji.current=To,Cr(To,"logical-focus-change")},[To,Cr,Kn]),I.useEffect(()=>{Qa.current=ks,Di(ks,"logical-viewing-change")},[ks,Di,Kn]),I.useEffect(()=>{const Ae=nt=>{const rt=nt.detail;typeof rt=="number"&&rt>=8&&rt<=32&&re(rt)};return document.addEventListener("termfontchange",Ae),()=>document.removeEventListener("termfontchange",Ae)},[]),I.useEffect(()=>{const Ae=()=>{const _t=!document.hidden;_e(_t),_t&&a&&dr("visibility")},nt=_t=>{a&&dr(_t.persisted?"bfcache":"pageshow")},yt=()=>{He(!0),dr("window-focus")},rt=()=>He(!1);return document.addEventListener("visibilitychange",Ae),window.addEventListener("pageshow",nt),window.addEventListener("focus",yt),window.addEventListener("blur",rt),()=>{document.removeEventListener("visibilitychange",Ae),window.removeEventListener("pageshow",nt),window.removeEventListener("focus",yt),window.removeEventListener("blur",rt)}},[a,dr]),I.useEffect(()=>{if(!g||!L||!gi.current)return;const Ae=q.current,nt=()=>{Et.current?.requestRefresh(y),Ao(Ae>0?"global-resume-background":"global-resume-visible",Ae<=0&&S)};if(Ae<=0){nt();return}const yt=window.setTimeout(nt,Ae);return()=>window.clearTimeout(yt)},[g,y,L,S,Ao]);const Co=I.useRef(0);I.useEffect(()=>{if(Je){Co.current=0;return}if(!li||wn==="Authentication required"||wn===nb)return;const Ae=Co.current,nt=Math.min(2e3*Math.pow(2,Math.min(Ae,4)),3e4),yt=setTimeout(()=>{Co.current+=1,X("[Terminal] fatal self-heal: auto restarting ensureSession",{attempt:Co.current,backendSessionId:bt.current}),ur("Reconnecting..."),Ct(!1),gs()},nt);return()=>clearTimeout(yt)},[wn,li,Je,We,X,gs]),I.useEffect(()=>{if(typeof window>"u"){Ue(!1);return}const Ae=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;Ue(Ae)},[]),I.useEffect(()=>{(!a||!Ee)&&lt(!1),a||me(!1)},[a,Ee]),I.useEffect(()=>{bt.current=Kn,is.current=-1,Kr.current=null,As.current=null,Gt.current=null,bn.current=null},[Kn]),I.useEffect(()=>{R?.(ee,Je)},[Je,R,ee]),I.useEffect(()=>{F?.(ee,Je&&ge&&tt)},[ge,tt,Je,F,ee]),I.useEffect(()=>{kr||(Wr.current=!1,Rr.current=null,Xn.current&&(clearTimeout(Xn.current),Xn.current=null))},[kr]),I.useEffect(()=>{Kn&&Et.current?.requestRefresh("session-key-change",{force:!0})},[Kn]),I.useEffect(()=>{const Ae=a&&Ee&&Bt;V("visibility signal",{sessionId:ee,isActive:a,isMobile:Ee,isInputFocused:ne,isViewportKeyboardOpen:Bt,viewportKeyboardHeight:Zt,visible:Ae}),N?.(ee,Ae)},[N,ee,a,Ee,Bt,Zt,V]),I.useEffect(()=>{a&&p&&p!==Ss.current&&(Ss.current=p,Qr())},[p,Qr,a]),I.useEffect(()=>{vt.current=ee},[ee]),I.useEffect(()=>{!Ee&&(It!==null||xe!==null)&&(nn(null),et(null),Fr.current=null)},[Ee,It,xe]),I.useEffect(()=>{!Kn&&(It!==null||xe!==null)&&(nn(null),et(null),Fr.current=null)},[Kn,It,xe]),I.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(r6,pt?"true":"false")},[pt]),I.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(s6,ct)},[ct]),I.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(i6,Lt)},[Lt]),I.useEffect(()=>{Ze(ab());const Ae=()=>{Ze(ab())};return window.addEventListener("resize",Ae),()=>window.removeEventListener("resize",Ae)},[]);const Us=I.useCallback(()=>{Sn.current+=1,Vi(),ci();const Ae=gt.current;gt.current=null,Pt.current=null,Jr.current=!1,at(!1),Et.current?.setSessionReady(!1);const nt=bt.current;nt&&rw(nt,!1,"stream-disconnect"),Bn.current=!1,bn.current=null,Nt.current=[],Ae?.()},[ci,Vi]),ko=I.useCallback(Ae=>{if(Pt.current===Ae){X(`[startStream] Skipping - already connected to ${Ae}`);return}X(`[startStream] Starting stream for frontendSessionId=${ee} backendSessionId=${Ae}`),Ke(null),ie.current+=1,Lr.current=!1,Dr.current=null,Ie(!1),Le(!1),Us();const nt=Sn.current+1;Sn.current=nt,Jr.current=!0;const yt=ke.connect(Ae,{onEvent:rt=>{if(Sn.current!==nt)return;const _t=ee;if(_t)switch(rt.type){case"connected":{Jr.current=!1;const Zn=ue.current;Zn&&(Ja("info","PWA_RESUME terminal-connected",{frontendSessionId:_t,backendSessionId:bt.current,durationMs:Date.now()-Zn.startedAt,strategy:Zn.strategy,reason:Zn.reason}),ue.current=null),M?.(_t),(rt.runtime||rt.ptyBackend)&&X(`[Terminal] connected frontendSessionId=${_t} backendSessionId=${bt.current} runtime=${rt.runtime??"unknown"} pty=${rt.ptyBackend??"unknown"} cwd=${rt.cwd??"unknown"}`),Un(_t,!1),ur(null),Ct(!1),Ke(null),at(!0),bt.current&&(ew(bt.current,ji.current,"stream-connected"),tw(bt.current,Qa.current,"stream-connected")),Et.current?.setSessionReady(!0),bn.current=null,Ti(Bn.current,"stream-connected"),rt.tuiProgress!==void 0&&ns.getState().setSessionTuiProgress(_t,rt.tuiProgress??null),rt.shellTitle!==void 0&&ns.getState().setSessionShellTitle(_t,rt.shellTitle??null),rt.promptState!==void 0&&rt.promptState!==null&&ns.getState().setSessionPromptState(_t,rt.promptState);const qn=ns.getState().getTerminalSession(_t);if(qn?.terminalSessionId&&rt.mode&&ns.getState().setTerminalSession(_t,{sessionId:qn.terminalSessionId,cols:80,rows:24,mode:rt.mode,tmuxSessionName:rt.tmuxSessionName??null,cwd:rt.cwd??null}),rt.activeProgram!==void 0&&Tt(_t,rt.activeProgram??null,rt.activeProgramSource??null,rt.activeProgramRaw??null),requestAnimationFrame(()=>{requestAnimationFrame(()=>{Et.current?.requestRefresh("connected",{force:!0,reconcileServerSize:pn.current})})}),rt.mode!=="tmux"&&(Pe(null),dn(_t,!1)),X("[Terminal] Connected event received:",{frontendSessionId:_t,backendSessionId:bt.current,storeHasState:!!qn,storeTerminalId:qn?.terminalSessionId,hasHistoryInStore:!!qn?.history?.length,historyLength:qn?.history?.length??0}),qn?.history&&qn.history.length>0){X(`[Terminal] Restoring ${qn.history.length} history chunks to frontend session ${_t}`);const Er=qn.history.reduce((gr,fi)=>gr+fi.length,0),ti=Math.max(300,Math.min(2e3,Math.ceil(Er/200)));Tr.current=Date.now()+ti,qn.history.forEach(gr=>{cr(_t,gr,{markActivity:!1})}),ns.getState().setSessionHistory(_t,[]),X(`[Terminal] History restoration complete for ${_t}`)}else X(`[Terminal] No history to restore for ${_t}`);const vr=rt.replayChunks,un=!!qn?.history?.length||!!vr?.length;if(un?Lr.current=!0:mi(),vr&&vr.length>0){rt.replayOutOfWindow?(X(`[Terminal] Replay out-of-window, clearing buffer before replay (${vr.length} chunks)`),te(_t),Et.current?.clear()):X(`[Terminal] Replay incremental: ${vr.length} chunks`);const Er=vr.reduce((gr,fi)=>gr+fi.length,0),ti=Math.max(200,Math.min(1500,Math.ceil(Er/200)));Tr.current=Math.max(Tr.current,Date.now()+ti);for(const gr of vr)cr(_t,gr)}un&&(Dr.current=ns.getState().flushPendingBufferWrites(_t),Dr.current===null&&(Lr.current=!1,mi()));break}case"reconnecting":{Ke(Zn=>Zn??Date.now()),ur("Reconnecting..."),Ct(!1);break}case"data":{rt.data&&(Bn.current?Nt.current.push(rt.data):cr(_t,rt.data));break}case"tmux-layout":{Pe(rt.layout??null),rt.layout&&dn(_t,rt.layout.inCopyMode);break}case"tmux-screen-sync":{const Zn=rt.generation??0;if(Zn<is.current)break;is.current=Zn,ie.current+=1,Lr.current=!0,Ie(!1),Nt.current=[],Et.current?.clear({preserveKeyboardResizePresentation:!0}),Kr.current=Zn,Dr.current=qr(_t,rt.chunks??[]),(!rt.chunks?.length||Dr.current===null)&&(Kr.current=null,Et.current?.notifyScreenSynchronized(Zn),Lr.current=!1,mi()),typeof rt.cols=="number"&&typeof rt.rows=="number"&&Et.current?.notifyServerSize(rt.cols,rt.rows,"tmux-screen-sync");break}case"active-program":{Tt(_t,rt.activeProgram??null,rt.activeProgramSource??null,rt.activeProgramRaw??null);break}case"cwd":{Fe(_t,rt.cwd??null);break}case"agent-status":{In(_t,{agentStatus:rt.agentStatus??null,agentIndicator:rt.agentIndicator??null,agentStatusDetail:rt.agentStatusDetail??null,agent:rt.agent??null,agentMessage:rt.agentMessage??null,agentNativeSessionId:rt.agentNativeSessionId??null,agentResumeRecovered:rt.agentResumeRecovered===!0,agentRich:rt.agentRich===!0,agentActivity:rt.agentActivity??0,agentCwd:rt.agentCwd??null,reviewed:rt.reviewed??null});break}case"git-status":{ns.getState().setSessionGitStatus(_t,rt.gitStatus??null);break}case"focus-mode":{X("[Terminal] focus tracking mode",{backendSessionId:bt.current,requested:rt.focusTrackingRequested===!0});break}case"resize-ack":{Et.current?.acknowledgeResize({seq:rt.seq,ok:rt.ok!==!1,cols:rt.cols,rows:rt.rows,screenSyncPending:rt.screenSyncPending,screenSyncGeneration:rt.screenSyncGeneration});break}case"pty-size":{typeof rt.cols=="number"&&typeof rt.rows=="number"&&Et.current?.notifyServerSize(rt.cols,rt.rows,rt.source);break}case"shell-title":{Mi(_t,rt.title??null);break}case"prompt-state":{Pn(_t,rt.state??"idle",rt.exitCode??null);break}case"tui-progress":{ns.getState().setSessionTuiProgress(_t,rt.tuiProgress??null);break}case"exit":{const Zn=typeof rt.exitCode=="number"?rt.exitCode:null,qn=typeof rt.signal=="number"?rt.signal:null;cr(_t,`\r
78
78
  [Process exited${Zn!==null?` with code ${Zn}`:""}${qn!==null?` (signal ${qn})`:""}]\r
79
- `),ss(_t),Un(_t,!1),ur("Terminal session ended"),at(!1),Ct(!1),Ke(null),Pe(null),dn(_t,!1),Us();break}}},onError:(rt,_t)=>{if(Sn.current!==nt)return;const Zn=ee;if(!Zn)return;Jr.current=!1;const qn=_t&&rt.message==="Authentication required",vr=r$(rt),un=qn?rt.message:vr||_t?"Reconnecting...":rt.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${_t}):`,un),vr&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:bt.current,frontendSessionId:Zn,isActive:a,isMobile:Ee,fatal:_t,stack:new Error().stack}),ur(un),Ct(!!_t),_t&&(Ke(null),Un(Zn,!1),Us(),vr&&(X("[onError] Session lost, auto-recreating"),ur("Reconnecting..."),Ct(!1),ss(Zn),te(Zn),bt.current=null,Pi.current=!1,gs()))}},O$);gt.current=()=>{yt.close(),Sn.current===nt&&(Pt.current=null)},Pt.current=Ae},[cr,te,ss,X,Us,mi,M,Ti,gs,Mi,Un,Tt,In,dn,Fe,Pn,ke,ee]);I.useEffect(()=>{const Ae=JQ({isActive:a,isStreamReady:Je,reconnectStartedAt:we,now:Date.now()});if(Ae===null)return;const nt=window.setTimeout(()=>{X("[Terminal] visible reconnect watchdog expired",{backendSessionId:bt.current,reconnectStartedAt:we}),Us(),Un(ee,!1),ur("Reconnecting..."),Ct(!1),Ke(Date.now()),gs()},Ae);return()=>window.clearTimeout(nt)},[X,Us,a,Je,we,gs,ee,Un]);const Pi=I.useRef(!1),gi=I.useRef(!1),_s=I.useRef(0);I.useEffect(()=>()=>{_s.current+=1,Pi.current=!1,Us()},[Us]);const Ci=I.useRef(Yn),Bi=I.useRef(or);I.useEffect(()=>{const Ae=Ci.current,nt=Bi.current;Ci.current=Yn,Bi.current=or,vt.current===ee&&(Ae===Yn&&nt===or||(Pi.current=!1,Us(),ut(yt=>yt+1)))},[Yn,or,Us,ee]),I.useEffect(()=>{if(vt.current!==ee&&(X(`[useEffect] sessionId changed from ${vt.current} to ${ee}, allowing reinitialization`),Pi.current=!1,gi.current=!1),Pi.current&&vt.current===ee){X(`[useEffect] Already initialized for sessionId=${ee}, skipping`);return}const Ae=async Zn=>{if(X(`[ensureSession] Starting for sessionId=${ee}, runId=${Zn}`),!vt.current||vt.current!==ee){X(`[ensureSession] SessionId mismatch or stale run (current=${vt.current}, target=${ee}), skipping`);return}if(Zn!==_s.current){X(`[ensureSession] Stale run detected (runId=${Zn}, currentRunId=${_s.current}), skipping`);return}const qn=ns.getState(),vr=qn.getTerminalSession(ee),un=vr?.mode??Yn;X("[ensureSession] Current state from store:",{terminalSessionId:vr?.terminalSessionId,mode:vr?.mode,tmuxSessionName:vr?.tmuxSessionName,isConnecting:vr?.isConnecting});let Er=vr?.terminalSessionId??null,ti=!Er;if(Er&&un!==Yn?(X(`[ensureSession] Store mode mismatch for ${Er}: current=${un} desired=${Yn}, will create new session`),ti=!0,qn.clearTerminalSession(ee),Er=null):Er&&Yn==="tmux"&&or&&vr?.tmuxSessionName!==or&&(X(`[ensureSession] Store tmux name mismatch for ${Er}: current=${vr?.tmuxSessionName} desired=${or}, will create new session`),ti=!0,qn.clearTerminalSession(ee),Er=null),Er&&ke.checkHealth&&!pn.current){X(`[ensureSession] Checking health of existing session ${Er}`);try{const gr=await ke.checkHealth(Er);if(X("[ensureSession] Health check result:",gr),!gr.healthy)X(`[ensureSession] Session ${Er} is NOT healthy (healthy=${gr.healthy}), will create new session`),X("[ensureSession] Health check details:",gr),ti=!0,gr.mode&&vr?.terminalSessionId&&qn.setTerminalSession(ee,{sessionId:vr.terminalSessionId,cols:80,rows:24,mode:gr.mode,tmuxSessionName:gr.tmuxSessionName??null}),qn.clearTerminalSession(ee),X("[ensureSession] Cleared unhealthy session from store");else{X(`[ensureSession] Session ${Er} is healthy, reusing it, cwd=${gr.cwd}, clients=${gr.clients}, lastActivity=${Date.now()-(gr.lastActivity||0)}ms ago`),gr.mode&&vr?.terminalSessionId&&qn.setTerminalSession(ee,{sessionId:vr.terminalSessionId,cols:80,rows:24,mode:gr.mode,tmuxSessionName:gr.tmuxSessionName??null}),X(`[ensureSession] Setting terminalIdRef to ${Er} and starting stream`),bt.current=Er,ko(Er),X(`[ensureSession] Successfully reused healthy session ${Er}, returning early`);return}}catch(gr){X(`[ensureSession] Failed to check health of session ${Er}:`,gr),X("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(X(`[ensureSession] Decision: shouldCreateNewSession=${ti}, terminalId=${Er}`),ti){X(`[ensureSession] Creating new session, shouldCreateNewSession=${ti}, runId=${Zn}`),ur(null),Ct(!1),qn.setConnecting(ee,!0);const fi=ns.getState().getTerminalSession(ee),Xi=(fi?.mode??Yn)===Yn&&(Yn!=="tmux"||!or||fi?.tmuxSessionName===or);if(fi?.terminalSessionId&&Xi)X(`[ensureSession] Race condition avoided: another instance already created session ${fi.terminalSessionId}`),qn.setConnecting(ee,!1),Er=fi.terminalSessionId,ti=!1;else try{const Ur=await Ns();if(X(`[ensureSession] Opened managed backend session ${Ur.sessionId}`),Zn!==_s.current){X(`[ensureSession] Stale run after session creation (runId=${Zn}, currentRunId=${_s.current}), leaving ${Ur.sessionId} for sibling`);return}qn.setTerminalSession(ee,Ur),X(`[ensureSession] Updated store with new session ${Ur.sessionId}`),Er=Ur.sessionId}catch(Ur){if(Zn!==_s.current){X("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(Ur instanceof al&&q3(Ur)){X("[ensureSession] Confirmed missing persisted session:",{sessionId:ee,error:Ur.message}),qn.clearTerminalSession(ee),ur(nb),Ct(!0),qn.setConnecting(ee,!1);return}ur("Reconnecting..."),Ct(!0),qn.setConnecting(ee,!1);return}}if(Zn!==_s.current){X(`[ensureSession] Stale run before starting stream (runId=${Zn}, currentRunId=${_s.current}), skipping`);return}if(!Er){X(`[ensureSession] No terminalId, terminalId=${Er}`);return}X(`[ensureSession] Starting stream for session ${Er}`),bt.current=Er,ko(Er),X(`[ensureSession] ensureSession completed for sessionId=${ee}, terminalId=${Er}`)};let nt=null,yt=null;const rt=()=>{yt=null,!(Pi.current&&vt.current===ee)&&(X(`[useEffect] Running ensureSession for sessionId=${ee}, hasInitialized=${Pi.current}`),Pi.current=!0,gi.current=!0,nt=++_s.current,Ae(nt))};if(!C&&!gi.current){X(`[useEffect] Holding background connection until the selected session is ready: ${ee}`);return}const _t=gi.current?0:Math.max(0,A);return _t>0?(X(`[useEffect] Delaying initial connection for sessionId=${ee} by ${_t}ms`),yt=window.setTimeout(rt,_t)):rt(),()=>{yt!==null&&window.clearTimeout(yt),X(`[useEffect] Cleanup for sessionId=${ee}, runId=${nt??"pending"}`)}},[ee,We,ko,Us,ke,X,Yn,or,wr,A,C]);const Gs=I.useCallback(async()=>{if(ee&&!Kt){J(!0),ur(null),Ct(!1),Ke(null),Us();try{ke.forceKill&&await ke.forceKill({sessionId:ee})}catch{}Oe(ee),te(ee),Et.current?.clear(),await new Promise(Ae=>setTimeout(Ae,100));try{Un(ee,!0);const Ae=await Ns();fn(ee,Ae),bt.current=Ae.sessionId,ko(Ae.sessionId)}catch(Ae){ur(Ae instanceof al&&q3(Ae)?nb:"Reconnecting..."),Ct(!0),Un(ee,!1)}finally{J(!1)}}},[ee,Kt,Us,ke,Oe,te,Un,fn,ko,Ns]),qi=I.useCallback((Ae,nt)=>{if(!pn.current||!Ae)return;const yt=uQ(Ae),rt=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(Ae);if(kr&&rt&&(Wr.current=!0),Date.now()<Tr.current)return;let _t=Ae,Zn=nt?.consumeModifier??!1;if(!nt?.skipModifierTransform&&It&&Ae.length>0){const un=Ae[0];if(un.length===1&&/[a-zA-Z]/.test(un)){const Er=un.toUpperCase();It==="ctrl"?(_t=String.fromCharCode(Er.charCodeAt(0)&31),Zn=!0):It==="alt"&&(_t=`\x1B${Ae}`,Zn=!0)}Zn||(It==="alt"&&(_t=`\x1B${Ae}`),Zn=!0)}const qn=bt.current;if(!qn)return;(async()=>{try{if(kr&&!yt&&Wr.current&&ke.tmuxAction){Wr.current=!1;try{await ke.tmuxAction(qn,{action:"copy-mode",enabled:!1})}catch{}if(dQ(_t))return}await ke.sendInput(qn,_t),hr(ee)}catch(un){ur(un instanceof Error?un.message:"Failed to send input")}})(),Zn&&(xe||nn(null),Qr())},[It,hr,Qr,kr,xe,ke]);I.useEffect(()=>{const Ae=nt=>{if(!pn.current)return;const yt=nt,rt=yt.detail?.text;if(!rt)return;const _t=yt.detail?.nonce;if(fs.current){_t&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:_t,ok:!1}}));return}Et.current?.sendSequence(rt,{paste:yt.detail?.paste}),_t&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:_t,ok:!0}})),rQ(Ot.current,yt.detail?.focus!==!1)&&Qr()};return window.addEventListener("termdock-insert-reference",Ae),()=>window.removeEventListener("termdock-insert-reference",Ae)},[Qr]);const Js=I.useCallback((Ae,nt,yt)=>{const rt=bt.current;if(!rt){V("xterm resize push skipped: no terminalId",{cols:Ae,rows:nt});return}V("xterm resize push",{cols:Ae,rows:nt}),ke.resize({sessionId:rt,cols:Ae,rows:nt,seq:yt}).catch(_t=>{Et.current?.acknowledgeResize({seq:yt,ok:!1}),_t&&/session not found/i.test(String(_t.message||_t))&&console.warn("[Terminal] resize 404 session not found",{sessionId:rt,cols:Ae,rows:nt,stack:new Error().stack})})},[ke,V]),oo=I.useCallback(async Ae=>{const nt=bt.current;if(!(!nt||!ke.tmuxAction))try{const yt=await ke.tmuxAction(nt,Ae);yt.layout&&(Pe(yt.layout),Ae.action==="switch-session"&&(fn(ee,{sessionId:nt,cols:80,rows:24,mode:"tmux",tmuxSessionName:yt.layout.sessionName}),Pm(ee,{tmuxSessionName:yt.layout.sessionName}).catch(rt=>{console.warn("[Terminal] failed to update inventory after tmux switch",rt)})))}catch(yt){ur(yt instanceof Error?yt.message:"Failed to execute tmux action")}},[ee,fn,ke]);I.useEffect(()=>{if(!pe||!Kn)return;const nt=pe.windows.find(yt=>yt.id===pe.activeWindowId)?.panes.find(yt=>yt.id===pe.activePaneId);nt&&Et.current?.requestRefresh("tmux-layout",{candidateSize:{cols:nt.width,rows:nt.height},skipScrollToBottom:!0,dedupeKey:`${Kn}:${pe.sessionId}:${nt.id}:${nt.width}x${nt.height}`})},[pe,Kn]);const Ki=I.useCallback((Ae,nt=5)=>{const yt=Math.max(1,Math.min(Math.floor(nt)||1,40));Wr.current=!0;const rt=Rr.current;if(rt&&rt.direction===Ae){rt.lines+=yt;return}rt&&oo({action:"scroll",direction:rt.direction,lines:rt.lines}).finally(()=>{Qr()}),Rr.current={direction:Ae,lines:yt},Xn.current&&clearTimeout(Xn.current),Xn.current=setTimeout(()=>{const _t=Rr.current;_t&&(Rr.current=null,oo({action:"scroll",direction:_t.direction,lines:_t.lines}).finally(()=>{Qr()}))},0)},[Qr,oo]),$a=I.useCallback(Ae=>{const nt=Date.now(),yt=Fr.current,rt=yt!==null&&yt.modifier===Ae&&nt-yt.timestamp<=B$;if(Fr.current={modifier:Ae,timestamp:nt},xe===Ae){et(null),nn(null);return}if(rt){et(Ae),nn(Ae);return}xe!==null&&xe!==Ae&&et(null),nn(_t=>_t===Ae?null:Ae)},[xe]),wa=I.useCallback(Ae=>{if(me(Ae&&pn.current),V("input focus changed",{focused:Ae,isActive:pn.current,isMobile:Ot.current}),!Ot.current||!pn.current){lt(!1);return}lt(nt=>nt===Ae?nt:Ae)},[V]),Yi=I.useCallback(Ae=>{if(Bn.current=Ae,Ti(Ae,"viewport-watermark"),!Ae&&Nt.current.length>0){const nt=ee;if(nt){const yt=Nt.current;Nt.current=[];for(const rt of yt)cr(nt,rt)}}},[cr,Ti,ee]),_o=I.useCallback(Ae=>{pn.current&&Et.current?.ensureSizeMatches(Ae)},[]),Sa=I.useRef(null);I.useEffect(()=>{if(!a)return;const Ae=Sa.current;if(!Ae)return;const nt=()=>_o("pointerdown"),yt=()=>_o("keydown"),rt=()=>_o("touchstart"),_t=()=>_o("wheel");return Ae.addEventListener("pointerdown",nt),Ae.addEventListener("keydown",yt),Ae.addEventListener("touchstart",rt,{passive:!0}),Ae.addEventListener("wheel",_t,{passive:!0}),()=>{Ae.removeEventListener("pointerdown",nt),Ae.removeEventListener("keydown",yt),Ae.removeEventListener("touchstart",rt),Ae.removeEventListener("wheel",_t)}},[a,_o]);const Bl=I.useCallback(Ae=>{Et.current=Ae},[]),cl=I.useCallback(Ae=>{B?.(ee,Ae)},[B,ee]),ui=I.useCallback(Ae=>{const nt=SQ(Ae);if(!nt)return;const yt=It!==null;Et.current?.sendSequence(nt,{consumeModifier:yt})},[It]),Uo=I.useCallback(Ae=>{const nt=xQ(Ae);if(nt.length===0)return;const yt=It!==null;Et.current?.sendSequence(H3(nt[0]),{consumeModifier:yt});for(let rt=1;rt<nt.length;rt+=1){const _t=nt[rt];window.setTimeout(()=>{Et.current?.sendSequence(H3(_t))},gQ*rt)}},[It]),Aa=I.useCallback(()=>{Et.current?.pasteClipboardText()},[]),Go=I.useCallback(Ae=>{zr.current!==null&&(window.clearTimeout(zr.current),zr.current=null),Mn(Ae),(Ae==="inserted"||Ae==="failed")&&(zr.current=window.setTimeout(()=>{zr.current=null,Mn("idle")},1400))},[]),Fl=I.useCallback(()=>{Go("idle"),En(0),zs.current?.click()},[Go]),Ws=I.useCallback(Ae=>{const nt=Ae.currentTarget.files?.[0];Ae.currentTarget.value="",nt&&(En(0),Go("uploading"),QA(nt,(yt,rt)=>h2(yt,rt,void 0,En),yt=>{if(!pn.current||fs.current)throw new Error("Terminal unavailable");window.dispatchEvent(new CustomEvent("termdock-insert-reference",{detail:{text:OA(yt,null),focus:!0}}))}).then(()=>Go("inserted"),()=>Go("failed")))},[Go]),qt=mr||wn!==null;fs.current=qt;const xi=I.useRef(Br);qt||(xi.current=Br);const sa=qt?xi.current:Br,ul=I.useMemo(()=>bQ(sa,hn),[sa,hn]),Ta=I.useMemo(()=>U3(hn,ct),[ct,hn]),ki=!Ee&&ct!=="auto"&&Ta.showOnDesktop!==!0?"auto":ct,Me=ki==="auto"?ul:ki,ls=I.useMemo(()=>U3(hn,Me),[Me,hn]),xs=I.useMemo(()=>ls.actions.filter(Ae=>Ae.sequence.trim().length>0).map((Ae,nt)=>({...Ae,label:P2(Ae,nt)})),[ls.actions]),Vs=I.useMemo(()=>EA(Br),[Br]),Lo=ls.label,os=I.useMemo(()=>ki!=="auto"?`Manual preset: ${ls.label}`:Vs?`Auto preset · ${ls.label} (${Vs})`:"Auto preset",[Vs,ki,ls.label]),Ms=I.useCallback(Ae=>{Rt(Ae)},[]),ei=I.useCallback(()=>{Xe(Ae=>Ae==="copy"?"arrows":"copy"),Ln("idle")},[]),qs=I.useCallback(()=>{typeof window>"u"||(xn.current!==null&&window.clearTimeout(xn.current),xn.current=window.setTimeout(()=>{xn.current=null,Ln("idle")},1200))},[]),$r=I.useCallback(Ae=>{xn.current!==null&&typeof window<"u"&&(window.clearTimeout(xn.current),xn.current=null),Ln(Ae?"copied":"failed"),qs()},[qs]),bs=I.useCallback(Ae=>{Yt(Ae)},[]),Eo=I.useMemo(()=>Ee?yQ(hn):vQ(hn),[Ee,hn]),_i=I.useMemo(()=>XO(s),[s]),Dn=I.useMemo(()=>`terminal::${ee}`,[ee]);I.useEffect(()=>{ye?.({isConnecting:mr,isRestarting:Kt,hasError:!!wn,sessionId:Kn})},[mr,Kt,wn,Kn,ye]);const Fi=!Kn||mr||Kt,Or=I.useCallback((Ae,nt)=>{if(Fi)return;const yt=Math.max(1,Math.min(Math.floor(nt)||1,40));Ki(Ae,yt)},[Ki,Fi]);I.useEffect(()=>{if(!a||!Ee)return;Et.current?.requestRefresh("resize",{skipScrollToBottom:!Bt,force:!0})},[a,Ee,Bt,Zt,ee]),I.useEffect(()=>{if(!a||!Ee)return;const Ae=nt=>{const yt=nt.detail;Et.current?.requestRefresh("resize",{skipScrollToBottom:yt?.isOpen!==!0,force:!0})};return document.addEventListener("termdock:viewport-keyboard-change",Ae),()=>{document.removeEventListener("termdock:viewport-keyboard-change",Ae)}},[a,Ee,ee]);const Io=!T&&(Ee||ls.showOnDesktop===!0),Ro=a,Ha=Ee&&!O?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,ia=Ee&&!O?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0,Ls=o.jsx(AQ,{visible:Io,interactive:Ro,presentation:Ee?"mobile":"desktop-actions",activeModifier:It,lockedModifier:xe,disabled:Fi,defaultShowExtended:pt,presetLabel:Lo,presetModeLabel:os,presetMode:ki,presetOptions:Eo,includeAlt:ls.includeAlt,presetRowLayout:ls.rowLayout,extraActions:xs,onKeyPress:ui,onTextPress:Uo,onPastePress:Ee?Aa:void 0,onFilePress:Ee?Fl:void 0,fileUploadState:qe,fileUploadProgress:zt,longPressMode:Lt,copyFeedback:rr,onLongPressModeToggle:ei,onModifierToggle:$a,onPresetSelect:Ms,onExpandedChange:bs}),di=typeof window<"u"&&(navigator.maxTouchPoints>0||"ontouchstart"in window);return o.jsxs("div",{className:"relative flex h-full min-h-0 flex-col overflow-hidden",style:Ha,children:[o.jsx("input",{ref:zs,type:"file",className:"hidden",onChange:Ws}),ze&&o.jsx(TQ,{isMobile:Ee,isInputFocused:ne,isIOS:$e,isConnecting:mr,connectionError:wn,terminalSessionId:Kn}),o.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:_i.background,...ia},children:[o.jsx("div",{ref:Sa,className:"h-full w-full box-border",children:o.jsx(_A,{fallback:o.jsx("div",{className:"flex h-full items-center justify-center bg-background",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center rounded-2xl bg-surface-2 px-6 py-5 shadow-sm",children:[o.jsx("div",{className:"w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center",children:o.jsx("svg",{className:"w-5 h-5 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),o.jsx("span",{className:"text-sm text-muted-foreground",children:ce("terminal.componentFailed")})]})}),children:o.jsx(qO,{ref:Bl,sessionKey:Dn,isLayoutVisible:f,chunks:Ar,onInput:qi,onResize:Js,onFlowControl:Yi,onTmuxScroll:kr?Or:void 0,tmuxScrollSensitivity:.38,onDoubleTap:Ee?()=>{Et.current?.sendSequence(" ")}:void 0,onInputFocusChange:wa,onMobileLongPressCopyResult:$r,onReadyChange:cl,onSizeSynchronizedChange:Le,onKeyboardResizeSettlingChange:Ai,onWritesSettled:hs,onWriteProgress:ll,onCursorPositionChange:Wi,onDirectoryLinkActivate:Zr,terminalSettings:Ce,theme:_i,enableTouchScroll:Ee,mobileLongPressMode:Lt,autoFocus:!c&&!Ee&&!di,cursorVisible:!c&&fe&&!ft&&cn,suppressSmoothScroll:!ge||!tt,className:c||!fe||ft||!cn?"terminal-focus-suspended":void 0},Dn)})}),o.jsx(kQ,{connectionError:wn,isFatalError:li,isRestarting:Kt,isConnecting:mr,onHardRestart:Gs})]}),$?T?null:Ni.createPortal(Ls,$):Ls]})},$$=1e3,H$=2e4,z$=9e4,U$=5e3,Xr={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let cm=0,k0=null;function G$(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function eT(){Xr.idleCloseTimer&&(clearTimeout(Xr.idleCloseTimer),Xr.idleCloseTimer=null)}function W$(){eT(),!(Xr.ws&&Xr.ws.readyState===WebSocket.OPEN)&&(Xr.idleCloseTimer=setTimeout(()=>{Xr.idleCloseTimer=null,Xr.listeners.size===0&&V$()},U$))}function V$(){if(Xr.ws){try{Xr.ws.close()}catch{}Xr.ws=null}k0&&(clearInterval(k0),k0=null)}function a6(){if(Xr.reconnectTimer)return;const e=Math.min($$*Math.pow(2,Xr.reconnectAttempt),H$);Xr.reconnectAttempt+=1,Xr.reconnectTimer=setTimeout(()=>{Xr.reconnectTimer=null,tT()},e)}function tT(){const e=G$();if(!e||Xr.ws&&Xr.ws.readyState===WebSocket.OPEN)return;let t;try{t=new WebSocket(e)}catch{a6();return}Xr.ws=t,t.onopen=()=>{Xr.reconnectAttempt=0,cm=Date.now(),k0||(k0=setInterval(()=>{if(!(!Xr.ws||Xr.ws.readyState!==WebSocket.OPEN)&&cm>0&&Date.now()-cm>z$)try{Xr.ws.close()}catch{}},3e4),k0.unref?.())},t.onmessage=n=>{cm=Date.now();let r=null;try{r=JSON.parse(n.data)}catch{return}if(!r)return;if(r.type==="update-state"){const a=r.state;if(!a||typeof a.status!="string"||typeof a.currentVersion!="string")return;const c={type:"update-state",state:a};for(const u of Xr.listeners)try{u(c)}catch(f){console.error("[clientStateSync] listener threw:",f)}return}if(r.type==="context-draft"){if(typeof r.text!="string")return;const a={type:"context-draft",text:r.text,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const c of Xr.listeners)try{c(a)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(r.type==="pinned-explorer-roots"){if(!r.pinnedExplorerRoots||typeof r.pinnedExplorerRoots!="object"||Array.isArray(r.pinnedExplorerRoots))return;const a={type:"pinned-explorer-roots",pinnedExplorerRoots:r.pinnedExplorerRoots,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const c of Xr.listeners)try{c(a)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(r.type==="config-updated"){if(r.key!=="toolbar-presets"&&r.key!=="agent-rules"&&r.key!=="program-detection")return;const a={type:"config-updated",key:r.key,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0};for(const c of Xr.listeners)try{c(a)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(r.type!=="client-state"||!r.state)return;const s=r.state,i={type:"client-state",clientState:{sessions:Array.isArray(s.sessions)?s.sessions:[],updatedAt:typeof s.updatedAt=="number"?s.updatedAt:Date.now()},inventory:r.inventory,seq:typeof r.seq=="number"?r.seq:void 0};for(const a of Xr.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}},t.onclose=()=>{Xr.ws===t&&(Xr.ws=null),Xr.listeners.size>0&&a6()},t.onerror=()=>{}}function Bh(e){return Xr.listeners.add(e),eT(),Xr.ws||tT(),()=>{Xr.listeners.delete(e),Xr.listeners.size===0&&W$()}}function nT(e,t,n){const r=e.findIndex(s=>n(s)===t);return r<0?null:e[r+1]?n(e[r+1]):r>0?n(e[r-1]):null}const lb="termdock-sessions",W2="termdock-active-session",Sv="termdock-sessions-cache";function V2(){try{const e=localStorage.getItem(W2);return e&&e.trim().length>0?e:null}catch{return null}}function Jd(e){try{e?localStorage.setItem(W2,e):localStorage.removeItem(W2)}catch{}}function rT(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Sv);if(!e)return null;const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.sessionId=="string"&&typeof n.name=="string"):null}catch{return null}}function Gu(e){if(!(typeof window>"u"))try{localStorage.setItem(Sv,JSON.stringify(e))}catch{}}function l6(){if(!(typeof window>"u"))try{localStorage.removeItem(Sv)}catch{}}function sT(e){return e.map(t=>({...t,mode:t.mode==="tmux"?"tmux":"shell",tmuxSessionName:t.tmuxSessionName??null,customName:t.customName===!0}))}function c6(e){return sT(e.map(t=>({sessionId:t.sessionId,name:t.name,customName:t.customName===!0,backendSessionId:t.backendSessionId,mode:t.mode,tmuxSessionName:t.tmuxSessionName,createdAt:t.createdAt,lastActivity:t.lastActivity}))).map((t,n)=>({...t,activeProgram:e[n]?.activeProgram??null,cwd:e[n]?.cwd??null}))}function u6(e){return e.map(t=>`${t.sessionId}:${t.name}:${t.customName}:${t.backendSessionId}:${t.mode}:${t.tmuxSessionName}:${t.lastActivity}:${t.activeProgram??""}:${t.cwd??""}`).join("|")}function q2(e,t){return e.length===0?null:t&&e.some(n=>n.sessionId===t)?t:e[0]?.sessionId??null}function q$(){const e=rT()??[];return{sessions:e,activeSessionId:q2(e,V2())}}function K$(){const e=x.useRef(rT()).current,t=x.useRef(V2()).current,[n,r]=x.useState(e??[]),[s,i]=x.useState(null),[a,c]=x.useState(e&&e.length>0?q2(e,t):t),[u,f]=x.useState(e===null),p=x.useRef(!1),g=x.useRef(null),y=x.useRef(e===null),v=x.useRef(0),S=x.useRef(new Set),A=x.useRef(0);x.useEffect(()=>{y.current=u},[u]),x.useEffect(()=>{g.current=a},[a]);const C=x.useCallback(ve=>{const re=q2(ve,g.current??V2());return c(ke=>ke===re?ke:re),Jd(re),g.current=re,re},[]),L=x.useCallback((ve,re)=>{const ke=ve.filter(X=>!S.current.has(X.sessionId));r(X=>u6(X)===u6(ke)?X:ke),Gu(ke),re?.reconcileActive&&C(ke)},[C]),R=x.useCallback((ve,re)=>{const ke=S.current.size===0?ve:{...ve,clientSessions:ve.clientSessions.filter(X=>!S.current.has(X.sessionId))};i(ke),L(c6(ke.clientSessions),re)},[L]),M=x.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(lb)?(localStorage.removeItem(lb),l6(),Jd(null),r([]),c(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),B=x.useCallback(async()=>{if(typeof window>"u")return[];const ve=A.current;try{const re=await EI(),ke=c6(re.clientSessions);return ve!==A.current?(console.info("[session-inventory] ignored restore snapshot superseded by a local mutation"),ke.filter(X=>!S.current.has(X.sessionId))):(R(re,{reconcileActive:!0}),ke.length>0?ke:M())}catch(re){console.error("Failed to restore sessions from server:",re);try{return M()}catch(ke){console.error("Failed to discard legacy local sessions:",ke)}}finally{f(!1)}return[]},[R,M]),F=x.useCallback(async ve=>{const re=++A.current,ke=await a8(ve);return re===A.current&&(R(ke.inventory),c(ke.session.sessionId),Jd(ke.session.sessionId)),ke},[R]),N=x.useCallback(async(ve,re)=>{++A.current,S.current.add(ve),r(ke=>{const X=ke.filter(ue=>ue.sessionId!==ve),V=re!=null&&X.some(ue=>ue.sessionId===re),q=g.current===ve?V?re:nT(ke,ve,ue=>ue.sessionId):g.current;return c(q),Jd(q),Gu(X),X});try{await RI(ve)}catch(ke){console.error("Failed to remove session from inventory:",ke)}},[]),T=x.useCallback(ve=>{const re=Date.now();r(ke=>{const X=ke.map(V=>V.sessionId===ve?{...V,lastActivity:re}:V);return Gu(X),X})},[]),$=x.useCallback(ve=>{c(ve),Jd(ve)},[]),O=x.useCallback(async(ve,re)=>{const ke=re.trim();if(!ke)return;const X=++A.current;r(V=>{const q=V.map(ue=>ue.sessionId===ve?{...ue,name:ke,customName:!0}:ue);return Gu(q),q});try{const V=await Pm(ve,{name:ke,customName:!0});X===A.current&&R(V)}catch(V){console.error("Failed to rename session in inventory:",V)}},[R]),Y=x.useCallback(async ve=>{const re=++A.current;r(ke=>{const X=ke.map(V=>V.sessionId===ve?{...V,customName:!1}:V);return Gu(X),X});try{const ke=await Pm(ve,{customName:!1});re===A.current&&R(ke)}catch(ke){console.error("Failed to reset session name in inventory:",ke)}},[R]),W=x.useCallback(async ve=>{const re=++A.current;r(ke=>{const X=new Map(ke.map(ee=>[ee.sessionId,ee])),V=ve.map(ee=>X.get(ee)).filter(ee=>ee!==void 0),q=new Set(ve),ue=ke.filter(ee=>!q.has(ee.sessionId)),Ce=[...V,...ue];return Gu(Ce),Ce});try{const ke=await II(ve);re===A.current&&R(ke)}catch(ke){console.error("Failed to reorder sessions in inventory:",ke)}},[R]),ye=x.useCallback(async()=>{++A.current;for(const ve of n)S.current.add(ve.sessionId);r([]),i(null),c(null),Jd(null),l6(),typeof window<"u"&&localStorage.removeItem(lb);try{await NI()}catch(ve){console.error("Failed to clear session inventory:",ve)}},[n]),ce=x.useCallback(async(ve,re)=>{const ke=++A.current;r(X=>{const V=X.map(q=>q.sessionId===ve?{...q,backendSessionId:re}:q);return Gu(V),V});try{const X=await Pm(ve,{backendSessionId:re});ke===A.current&&R(X)}catch(X){console.error("Failed to update session backend in inventory:",X)}},[R]);return x.useEffect(()=>{p.current||(p.current=!0,B())},[B]),x.useEffect(()=>Bh(re=>{if(re.type!=="client-state"||y.current)return;const ke=typeof re.seq=="number"?re.seq:null;if(ke!==null){if(ke<v.current){console.warn("[session-inventory] ignored stale control snapshot",{seq:ke,latestSeq:v.current});return}v.current=ke}if(re.inventory){R(re.inventory,{reconcileActive:!0});return}const X=sT(re.clientState.sessions||[]);L(X,{reconcileActive:!0})}),[R,L]),{sessions:n,inventory:s,activeSessionId:a,isLoading:u,openSession:F,removeSession:N,updateSessionActivity:T,setActiveSession:$,updateSessionBackendId:ce,renameSession:O,resetSessionCustomName:Y,reorderSessions:W,clearAllSessions:ye,restoreSessions:B}}const Y$="termdock:startup:";function b0(e){if(typeof performance>"u"||typeof performance.mark!="function")return;const t=`${Y$}${e}`;performance.getEntriesByName(t,"mark").length>0||performance.mark(t)}function X$(e,t){e||Ni.flushSync(t)}const K2="horizontal";function kc(e){return e<=0?[]:Array.from({length:e},()=>1/e)}function id(e,t){if(!Array.isArray(e)||e.length!==t)return kc(t);const n=e.map(Number);if(n.some(s=>!Number.isFinite(s)||s<=0))return kc(t);const r=n.reduce((s,i)=>s+i,0);return r<=0?kc(t):n.map(s=>s/r)}function iT(e){const t=Math.max(1,Math.ceil(Math.sqrt(Math.max(1,e))));return{columns:t,rows:Math.max(1,Math.ceil(Math.max(1,e)/t))}}function Z$(e,t,n,r){if(t<0||t>=e.length-1)return e;const s=[...e],i=s.slice(0,t).reduce((f,p)=>f+p,0),a=s[t]+s[t+1],c=Math.max(0,Math.min(a/2,r)),u=Math.min(a-c,Math.max(c,n-i));return s[t]=u,s[t+1]=a-u,s}function J$(e){return e==="horizontal"||e==="vertical"||e==="grid"}function eH(e){if(!Array.isArray(e))return[];const t=new Set,n=new Set,r=[];for(const s of e){if(!s||typeof s!="object")continue;const i=s;if(typeof i.id!="string"||!i.id||n.has(i.id))continue;const a=Array.isArray(i.sessionIds)?i.sessionIds.filter(f=>typeof f=="string"&&!!f&&!t.has(f)):[],c=[...new Set(a)];if(c.length<2)continue;const u=iT(c.length);c.forEach(f=>t.add(f)),n.add(i.id),r.push({id:i.id,...typeof i.name=="string"&&i.name.trim()?{name:i.name.trim().slice(0,80)}:{},sessionIds:c,layout:J$(i.layout)?i.layout:K2,ratios:id(i.ratios,c.length),...i.gridColumnRatios!==void 0?{gridColumnRatios:id(i.gridColumnRatios,u.columns)}:{},...i.gridRowRatios!==void 0?{gridRowRatios:id(i.gridRowRatios,u.rows)}:{}})}return r}function tH(e,t){const n=new Set(t);return e.flatMap(r=>{const s=r.sessionIds.filter(i=>n.has(i));return s.length<2?[]:[{...r,sessionIds:s,ratios:s.length===r.sessionIds.length?id(r.ratios,s.length):kc(s.length)}]})}function Fh(e,t){if(t)return e.find(n=>n.sessionIds.includes(t))}function cb(e,t,n){if(!t||!n||t===n)return e;const r=Fh(e,t),s=Fh(e,n);if(r&&r.id===s?.id)return e;const i=[...r?.sessionIds??[t],...s?.sessionIds??[n]],a=[...new Set(i)],c={id:r?.id??`split:${t}`,...r?.name?{name:r.name}:{},sessionIds:a,layout:a.length>2&&(!r||r.layout===K2)?"grid":r?.layout??K2,ratios:kc(a.length)},u=new Set([r?.id,s?.id].filter(Boolean)),f=e.filter(g=>!u.has(g.id)),p=r?Math.max(0,e.findIndex(g=>g.id===r.id)):f.length;return f.splice(Math.min(p,f.length),0,c),f}function nH(e,t){const n=Fh(e,t);if(!n||!t)return e;if(n.sessionIds.length<=2)return e.filter(s=>s.id!==n.id);const r=n.sessionIds.filter(s=>s!==t);return e.map(s=>s.id===n.id?{...s,sessionIds:r,ratios:kc(r.length)}:s)}function rH(e,t){const n=Fh(e,t);return n?e.filter(r=>r.id!==n.id):e}function sH(e,t,n){return e.map(r=>{if(r.id!==t)return r;const s=[...new Set(n)],i=new Set(r.sessionIds);return s.length===r.sessionIds.length&&s.every(c=>i.has(c))?{...r,sessionIds:s}:r})}function iH(e,t,n){const r=n.trim().slice(0,80);return e.map(s=>s.id===t?{...s,...r?{name:r}:{name:void 0}}:s)}const Y2=320,oT=1,oH=Y2+120,X2="termdock:split-workspaces:v2",aT="termdock:split-workspace:v1",aH=.1,lH=.9,cH=.28,uH=300,dH=8,fH=280,hH=160;function ub(){if(typeof window>"u")return{mobile:!1,landscape:!1};const t=(navigator.maxTouchPoints>0||"ontouchstart"in window)&&Math.min(window.innerWidth,window.innerHeight)<768;return{mobile:t,landscape:t&&window.innerWidth>window.innerHeight}}function pH(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(X2);if(e)return eH(JSON.parse(e));const t=JSON.parse(window.localStorage.getItem(aT)||"null");if(t&&typeof t.primaryId=="string"&&typeof t.secondaryId=="string"&&t.primaryId!==t.secondaryId){const n=Math.min(lH,Math.max(aH,typeof t.ratio=="number"?t.ratio:.5));return[{id:`split:${t.primaryId}`,sessionIds:[t.primaryId,t.secondaryId],layout:t.direction==="vertical"?"vertical":"horizontal",ratios:[n,1-n]}]}}catch{}return[]}function mH(e,t){const n=new Map(e.map(a=>[a.id,a])),r=new Map;t.forEach(a=>a.sessionIds.forEach(c=>r.set(c,a)));const s=new Set,i=[];for(const a of e){const c=r.get(a.id);if(!c){i.push({key:a.id,sessions:[a]});continue}if(s.has(c.id))continue;s.add(c.id);const u=c.sessionIds.flatMap(f=>{const p=n.get(f);return p?[p]:[]});u.length>=2&&i.push({key:c.id,sessions:u,workspace:c})}return i}function d6(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(n=>n.cancel())}catch{}}function um(e,t){const n=vg(e,t);if(n===null)return;const r=e.wrapperEl;d6(e),r&&(r.style.transitionDuration="0ms");try{const s=e;s.setTransition?.(0),s.setTranslate?.(n),d6(e),r&&(r.style.transitionDuration="0ms",r.style.transform=`translate3d(${n}px, 0px, 0px)`)}catch{r&&(r.style.transitionDuration="0ms",r.style.transform=`translate3d(${n}px, 0px, 0px)`)}}function Z2(e){try{const t=typeof e.getTranslate=="function"?e.getTranslate():e.translate;return typeof t=="number"&&Number.isFinite(t)?t:null}catch{return typeof e.translate=="number"&&Number.isFinite(e.translate)?e.translate:null}}function vg(e,t){const n=e.snapGrid,r=Array.isArray(n)?n[t]:void 0;return typeof r!="number"||!Number.isFinite(r)?null:-r}function gH(e,t){const n=Z2(e),r=vg(e,t);return n!==null&&r!==null&&Math.abs(n-r)<=oT}function xH(e){const t=[],n=new Map,r=new Map,s=new Map;for(const i of e){const a=n.get(i.id)??[];if(a.push(i.id),n.set(i.id,a),i.sessionId){const c=r.get(i.sessionId)??[];c.push(i.id),r.set(i.sessionId,c)}if(i.mode==="tmux"&&i.tmuxSessionName){const c=s.get(i.tmuxSessionName)??[];c.push(i.id),s.set(i.tmuxSessionName,c)}}for(const[i,a]of n)a.length>1&&t.push({kind:"frontend",key:i,sessionIds:a});for(const[i,a]of r)a.length>1&&t.push({kind:"backend",key:i,sessionIds:a});for(const[i,a]of s)a.length>1&&t.push({kind:"tmux",key:i,sessionIds:a});return t}function lT(e){const t=new Map;for(const n of e)t.set(n.id,n);return Array.from(t.values())}function cT(e){return{id:e.sessionId,name:e.name,customName:e.customName===!0,sessionId:e.backendSessionId,mode:e.mode==="tmux"||e.mode==="shell"?e.mode:"shell",tmuxSessionName:e.tmuxSessionName??null}}function bH(e,t){const n=lT(e),r=n.findIndex(s=>s.id===t.id);if(r>=0){const s=[...n];return s[r]=t,s}return[...n,t]}function f6(e,t){const n=new Map(e.map(r=>[r.id,r]));return t.map(r=>{const s=n.get(r.sessionId);return{...cT(r),history:s?.history}})}function h6(e,t){return e.length===0?null:t&&e.some(n=>n.sessionId===t)?t:e[0]?.sessionId??null}function p6(e){if(!e||typeof e!="object")return"unknown";const t=e;if(typeof t.pointerType=="string"&&t.pointerType)return t.pointerType;if(typeof t.type=="string"){if(t.type.startsWith("touch"))return"touch";if(t.type.startsWith("mouse"))return"mouse";if(t.type.startsWith("pointer"))return"pointer"}return"unknown"}function m6(e){const t=new Map;for(const[n,r]of e)t.set(n,r.cwd??null);return t}function yH(e,t){if(e.size!==t.size)return!1;for(const[n,r]of t)if(e.get(n)!==r)return!1;return!0}function vH(e){const t="".toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,12);if(t)return`wt-${t}`;const n=Date.now().toString(36),r=Math.random().toString(36).slice(2,8);return`wt-${n}${r}`}const wH=({terminalSettings:e=pv(),colorTheme:t="dark",toolbarPresets:n=[],showDebug:r,terminalFocusAvailable:s=!0,defaultSessionMode:i="shell",defaultTmuxSessionName:a="",connectionPrioritySessionId:c=null,connectionPriorityReady:u=!0,desktopPinnedRightSidebar:f=!1,desktopPinnedRightSidebarWidth:p=0,desktopPinnedLeftSidebarWidth:g=0,desktopViewportWidth:y=0,onStatusChange:v,onSessionDataUpdate:S,onInitialViewportReady:A})=>{const{t:C}=ir(),L=x.useMemo(()=>pd("session"),[]),R=x.useMemo(()=>pd("terminal"),[]),[M,B]=x.useState([]),[F,N]=x.useState(null),[T,$]=x.useState(null),[O,Y]=x.useState(!0),[W,ye]=x.useState({token:0,reason:"visibility",forceForegroundReconnect:!1}),[ce,ve]=x.useState(()=>new Set),[re,ke]=x.useState(0),[X,V]=x.useState(()=>new Set),[q,ue]=x.useState(()=>new Set),[Ce,ee]=x.useState(()=>new Set),Ee=x.useRef(!1),Ze=x.useRef(null),$e=x.useRef({}),[Ue,ne]=x.useState(null),[lt,Ye]=x.useState(()=>pH()),[me,se]=x.useState(!1),[_e,he]=x.useState(null),[He,Je]=x.useState(null),[at,ge]=x.useState(null),[Ie,tt]=x.useState(!1),[Le,fe]=x.useState(()=>ub().mobile),[Qe,ft]=x.useState(()=>ub().landscape),[Mt,cn]=x.useState(null),[mt,Bt]=x.useState(null),Zt=x.useRef(s),It=x.useRef(!1),nn=x.useRef(null),xe=x.useRef(null),et=x.useRef(Le),pt=x.useRef(null),Yt=x.useRef(0),ct=x.useRef([]),Rt=x.useRef(0),Lt=x.useRef(null),Xe=x.useRef(!1),rr=x.useRef(!0),Ln=x.useRef(null),qe=x.useRef(""),Mn=x.useRef(null),zt=x.useRef(0);x.useEffect(()=>{if(typeof window>"u")return;const ie=()=>{const Se=ub();et.current=Se.mobile,fe(Se.mobile),ft(Se.landscape)};return ie(),window.addEventListener("resize",ie),()=>window.removeEventListener("resize",ie)},[]);const{sessions:En,inventory:Hn,activeSessionId:fn,isLoading:Un,openSession:cr,setActiveSession:qr,removeSession:ss,renameSession:Oe,resetSessionCustomName:te,reorderSessions:Tt,restoreSessions:Fe}=K$(),dn=Hn?.tmuxRecovery??null;x.useEffect(()=>{ge(null),Je(null)},[dn?.id]);const In=x.useCallback(async()=>{Je("restore"),ge(null);try{const ie=await kI();await Fe(),ie.failed>0&&ge(C("tab.tmuxRecoveryPartial",{restored:ie.restored,failed:ie.failed}))}catch{ge(C("tab.tmuxRecoveryFailed"))}finally{Je(null)}},[Fe,C]),kt=x.useCallback(async()=>{Je("dismiss"),ge(null);try{await _I(),await Fe()}catch{ge(C("tab.tmuxRecoveryDismissFailed"))}finally{Je(null)}},[Fe,C]),Pn=ht(ie=>ie.groupByFolder),hr=ht(ie=>ie.leftOpen||ie.rightOpen),[wr,pr]=x.useState(()=>m6(ns.getState().sessions));x.useEffect(()=>ns.subscribe(ie=>{const Se=m6(ie.sessions);pr(Be=>yH(Be,Se)?Be:Se)}),[]);const{arranged:Ir}=x.useMemo(()=>kA(M,ie=>wr.get(ie.id)??null,Pn,""),[M,wr,Pn]),Br=x.useRef(Ir);Br.current=Ir;const hn=x.useMemo(()=>mH(Ir,lt),[Ir,lt]),kr=x.useRef(hn);kr.current=hn;const Ar=x.useMemo(()=>Fh(lt,F),[F,lt]),mr=x.useMemo(()=>{const ie=hn.find(Se=>Se.sessions.some(Be=>Be.id===F));return new Set(ie?.sessions.map(Se=>Se.id)??[])},[F,hn]),Kn=x.useMemo(()=>{const ie=new Map;if(!f||y<=0)return ie;for(const Se of hn){const Be=Se.sessions[0];if(!Be)continue;const it=Se.sessions.some(Dt=>Dt.id===F)?p:E$(Be.id,wr.get(Be.id)??null,Se.workspace?.id??null),Ft=qm(it,y,g);ie.set(Se.key,Ft+yv)}return ie},[F,wr,g,f,p,y,hn]),Zr=x.useMemo(()=>tb(M.map(ie=>({id:ie.id,backendSessionId:ie.sessionId})),c),[c,M]),Yn=x.useMemo(()=>h6(En,fn),[fn,En]),or=am({prioritySessionId:Zr,activeSessionId:T??F,persistedActiveSessionId:Yn,firstSessionId:M[0]?.id??null}),wn=x.useMemo(()=>e$(hn.flatMap(ie=>ie.sessions.map(Se=>Se.id)),mr),[mr,hn]),ur=or!==null&&ce.has(or),fs=x.useCallback((ie,Se)=>{ve(Be=>{if(Be.has(ie)===Se)return Be;const Ft=new Set(Be);return Se?Ft.add(ie):Ft.delete(ie),Ft})},[]),li=x.useCallback(ie=>{const Se=Zr??T??pt.current;ie===Se&&(b0("foreground-stream-connected"),ke(Yt.current))},[T,Zr]),Ct=x.useCallback((ie,Se)=>{V(Be=>{if(Be.has(ie)===Se)return Be;const it=new Set(Be);return Se?it.add(ie):it.delete(ie),it})},[]),Kt=x.useCallback((ie,Se)=>{ue(Be=>{if(Be.has(ie)===Se)return Be;const it=new Set(Be);return Se?it.add(ie):it.delete(ie),it})},[]),J=or!==null&&X.has(or),we=or!==null&&q.has(or);x.useEffect(()=>{J&&b0("foreground-viewport-ready")},[J]),x.useEffect(()=>{we&&b0("foreground-content-ready")},[we]),x.useEffect(()=>{if(A){if(!O&&M.length===0){A();return}!J||!ur||!we||(b0("initial-viewport-presented"),A())}},[ur,we,J,O,A,M.length]),x.useEffect(()=>{if(mr.size===0)return;const ie=new Set(mr),Se=hn.findIndex(it=>it.sessions.some(Ft=>mr.has(Ft.id))),Be=Le?1:2;for(let it=-Be;it<=Be;it+=1)it!==0&&hn[Se+it]?.sessions.forEach(Ft=>ie.add(Ft.id));ee(it=>{let Ft=!1;const Dt=new Set(it);for(const rn of ie)Dt.has(rn)||(Dt.add(rn),Ft=!0);return Ft?Dt:it})},[Le,mr,hn]),x.useEffect(()=>{if(!T)return;if(!M.some(Se=>Se.id===T)){$(null);return}if(!X.has(T)||!ce.has(T)||!q.has(T))return;const ie=window.setTimeout(()=>{N(T),$(Se=>Se===T?null:Se),Zt.current&&!et.current&&ne({sessionId:T,token:Date.now()})},80);return()=>window.clearTimeout(ie)},[q,T,ce,M,X]),x.useEffect(()=>{typeof window>"u"||(lt.length>0?(window.localStorage.setItem(X2,JSON.stringify(lt)),window.localStorage.removeItem(aT)):window.localStorage.removeItem(X2))},[lt]),x.useEffect(()=>{Un||O||lt.length===0||Ye(ie=>tH(ie,M.map(Se=>Se.id)))},[Un,O,M,lt.length]),x.useEffect(()=>{if(!_e)return;const ie=window.setTimeout(()=>he(null),3200);return()=>window.clearTimeout(ie)},[_e]),x.useEffect(()=>()=>Mn.current?.(),[]),pt.current=F,Yt.current=W.token,ct.current=M,Lt.current=fn,Xe.current=Un,rr.current=O,Zt.current=s;const Ke=x.useCallback((ie=Ze.current)=>{const Se=Rt.current,Be=typeof window<"u"?window.visualViewport:null,it=ie?Z2(ie):null,Ft=ie?vg(ie,Se):null;return{sessionsLength:ct.current.length,workspaceSlidesLength:kr.current.length,sessionIds:ct.current.map(Dt=>Dt.id),activeSessionId:pt.current,activeSessionIndex:Se,persistedActiveId:Lt.current,isLoading:Xe.current,isRestoring:rr.current,activeIndex:ie?.activeIndex??null,previousIndex:ie?.previousIndex??null,animating:ie?.animating??null,allowTouchMove:ie?.allowTouchMove??null,width:ie?.width??null,translate:it,targetTranslate:Ft,translateDelta:it!==null&&Ft!==null?it-Ft:null,snapGridLength:ie?.snapGrid?.length??null,targetSnap:ie?.snapGrid?.[Se]??null,visualViewport:Be?{width:Math.round(Be.width),height:Math.round(Be.height),offsetTop:Math.round(Be.offsetTop)}:null}},[]),We=x.useCallback((ie,Se)=>{L(ie,{...Ke(),...Se})},[L,Ke]);x.useEffect(()=>{Un||O||F!==fn&&qr(F)},[F,Un,O,fn,qr]);const ut=x.useMemo(()=>{if(Ir.length===0||!F)return 0;const ie=hn.findIndex(Se=>Se.sessions.some(Be=>Be.id===F));return ie>=0?ie:0},[hn,F]);Rt.current=ut;const pe=x.useCallback(()=>{nn.current&&(clearTimeout(nn.current),nn.current=null)},[]),Pe=x.useCallback(ie=>{pe(),nn.current=setTimeout(()=>{nn.current=null,It.current=!1,We("[swiper:touch-guard-clear]",{reason:ie})},oH)},[pe,We]),ze=x.useCallback((ie,Se={})=>{const Be=Ze.current,it=Rt.current,Ft=kr.current;if(!Be||Ft.length===0||it<0||it>=Ft.length)return;if(It.current){We("[swiper:sync-skip-touch]",{reason:ie});return}if(Be.animating){We("[swiper:sync-skip-animating]",{reason:ie});return}const Dt=Z2(Be),rn=vg(Be,it),on=Dt!==null&&rn!==null&&Math.abs(Dt-rn)<=oT,ln=Be.activeIndex===it;if(We("[swiper:sync-check]",{reason:ie,activeIndexAligned:ln,translateAligned:on,immediate:Se.immediate===!0}),!(ln&&on)){if(ln){um(Be,it),We("[swiper:sync-forced-active]",{reason:ie,translateAligned:on,immediate:Se.immediate===!0});return}Se.immediate?(um(Be,it),Be.slideTo(it,0,!1),um(Be,it)):Be.slideTo(it,Y2,!1),We("[swiper:sync-applied]",{reason:ie,activeIndexAligned:ln,translateAligned:on,immediate:Se.immediate===!0})}},[We]);x.useEffect(()=>{const ie=Se=>{const Be=Se;Ze.current&&(Ze.current.allowTouchMove=!Be.detail.locked),We("[swiper:gesture-lock]",{locked:Be.detail.locked})};return document.addEventListener("termdock:gesture-lock",ie),()=>document.removeEventListener("termdock:gesture-lock",ie)},[We]),x.useEffect(()=>{if(M.length===0){F!==null&&N(null);return}if(!F){if(!u)return;N(am({prioritySessionId:Zr,activeSessionId:null,persistedActiveSessionId:Yn,firstSessionId:M[0]?.id??null}));return}M.some(Se=>Se.id===F)||N(M[0].id)},[M,F,u,Zr,Yn]);const gt=x.useCallback((ie,Se)=>{if(Se&&Date.now()<zt.current){$e.current[ie]=!1;return}$e.current[ie]=Se,Bt(Be=>Se?ie:Be===ie?null:Be)},[]),Pt=x.useCallback(ie=>{if(!It.current&&ie.activeIndex!==Rt.current){We("[swiper:slide-change-ignored-layout]",{instanceActiveIndex:ie.activeIndex,expectedActiveIndex:Rt.current}),requestAnimationFrame(()=>ze("ignored-layout-slide-change",{immediate:!0}));return}const Se=kr.current[ie.activeIndex],Be=Se?.sessions.some(Dt=>Dt.id===F)?F:Se?.sessions[0]?.id;if(We("[swiper:slide-change]",{nextSessionId:Be??null,instanceActiveIndex:ie.activeIndex}),!Be||Be===F)return;const it=!!F&&$e.current[F]===!0,Ft=Zt.current&&(!et.current||it);if(xe.current=Be,N(Be),Ft){ne({sessionId:Be,token:Date.now()});return}ne(null)},[M,F,We,ze]);x.useEffect(()=>{if(xe.current===F){We("[swiper:sync-skip-swiper-driven]",{activeSessionId:F}),xe.current=null;return}ze("active-session-index",{immediate:!0})},[F,ut,M.length,ze,We]),x.useEffect(()=>{const ie=Ze.current;if(!ie)return;const Se=hn.length>1&&!hr&&!me;ie.allowTouchMove!==Se&&(ie.allowTouchMove=Se,We("[swiper:allow-touch-sync]",{nextAllow:Se,sidebarOverlayOpen:hr}))},[hn.length,We,hr,me]);const bt=x.useCallback(ie=>{const Se=Ze.current;if(!Se)return;const Be=Se.el;if(We("[swiper:layout-before]",{reason:ie,scrollLeft:Be?.scrollLeft??null}),Be&&(Be.scrollLeft=0),Se.updateSize(),Se.updateSlides(),Se.updateProgress(),Se.updateSlidesClasses(),Be&&(Be.scrollLeft=0),We("[swiper:layout-after]",{reason:ie,scrollLeft:Be?.scrollLeft??null}),It.current||Se.animating){We("[swiper:layout-skip-sync-motion]",{reason:ie});return}ze(`layout:${ie}`,{immediate:!0}),requestAnimationFrame(()=>{const it=Ze.current;it&&(It.current||it.animating||um(it,Rt.current))})},[We,ze]);x.useEffect(()=>()=>pe(),[pe]);const vt=hn.map(ie=>ie.key).join("\0");x.useEffect(()=>{requestAnimationFrame(()=>bt("group-change"))},[Pn,vt,bt]),x.useEffect(()=>{let ie=null,Se="mount";const Be=on=>{Se=on,ie===null&&(ie=requestAnimationFrame(()=>{ie=null,bt(`viewport-change:${Se}`)}))},it=()=>Be("window-resize"),Ft=()=>Be("visual-viewport-resize"),Dt=()=>Be("visual-viewport-scroll"),rn=on=>{Be(`measured:${on.detail?.source??"unknown"}`)};return window.addEventListener("resize",it),window.visualViewport?.addEventListener("resize",Ft),window.visualViewport?.addEventListener("scroll",Dt),document.addEventListener(F2,rn),Be("mount"),()=>{window.removeEventListener("resize",it),window.visualViewport?.removeEventListener("resize",Ft),window.visualViewport?.removeEventListener("scroll",Dt),document.removeEventListener(F2,rn),ie!==null&&cancelAnimationFrame(ie)}},[bt]),x.useEffect(()=>{if(typeof document>"u")return;let ie=null,Se=null,Be=document.hidden;const it=Vn=>{if(Vn!=="online"&&document.hidden)return;const sr=performance.now();if(!XQ(Se,sr))return;Se=sr;const ar=Vn==="bfcache"||Vn==="online"?Vn:"visibility",lr=ZQ({wasPageHidden:Be,reason:Vn});Be=!1,Ja("info","PWA_RESUME scheduled",{source:Vn,forceForegroundReconnect:lr,activeSessionId:pt.current}),ye(Wt=>({token:Wt.token+1,reason:ar,forceForegroundReconnect:lr})),requestAnimationFrame(()=>bt(`resume:${Vn}:raf`)),ie&&clearTimeout(ie),ie=setTimeout(()=>{ie=null,bt(`resume:${Vn}:settled`)},320)},Ft=()=>{if(document.hidden){Be=!0,J5();return}it("visibility")},Dt=()=>{Be=!0,J5()},rn=Vn=>{it(Vn.persisted?"bfcache":"pageshow")},on=()=>it("online"),ln=()=>it("focus");return document.addEventListener("visibilitychange",Ft),window.addEventListener("pagehide",Dt),window.addEventListener("pageshow",rn),window.addEventListener("online",on),window.addEventListener("focus",ln),()=>{document.removeEventListener("visibilitychange",Ft),window.removeEventListener("pagehide",Dt),window.removeEventListener("pageshow",rn),window.removeEventListener("online",on),window.removeEventListener("focus",ln),ie&&clearTimeout(ie)}},[bt]),x.useEffect(()=>{if(!KQ(O))return;const ie=xH(M),Se=JSON.stringify(ie);ie.length>0&&Se!==qe.current?(qe.current=Se,console.warn("[session-invariant] duplicate mapping detected",ie)):ie.length===0&&qe.current&&(qe.current=""),S?.({sessions:M.map(Be=>({id:Be.id,name:Be.name,customName:Be.customName,mode:Be.mode,tmuxSessionName:Be.tmuxSessionName})),activeSessionId:F,splitWorkspaces:lt.map(({id:Be,name:it,sessionIds:Ft,layout:Dt})=>({id:Be,...it?{name:it}:{},sessionIds:Ft,layout:Dt}))})},[M,F,lt,S,O]),x.useEffect(()=>{if(Un||Ee.current)return;Ee.current=!0;const ie=tb(En.map(Dt=>({id:Dt.sessionId,backendSessionId:Dt.backendSessionId??null})),c),Se=h6(En,fn),Be=am({prioritySessionId:u?ie:null,activeSessionId:null,persistedActiveSessionId:Se,firstSessionId:En[0]?.sessionId??null}),it=lT(En.map(cT));if(L("[Session] Restoring",it.length,"persisted sessions (one-shot)"),We("[swiper:restore-start]",{persistedSessionIds:En.map(Dt=>Dt.sessionId),nextActiveSessionId:Be}),it.length>0){const Dt=ns.getState();it.forEach(on=>{on.sessionId&&Dt.setTerminalSession(on.id,{sessionId:on.sessionId,cols:80,rows:24,mode:on.mode,tmuxSessionName:on.tmuxSessionName,history:on.history})}),En.forEach(on=>{on.activeProgram!=null&&Dt.setSessionActiveProgram(on.sessionId,on.activeProgram),on.cwd!=null&&Dt.setSessionCwd(on.sessionId,on.cwd)}),B(it);const rn=Be||it[0]?.id||null;N(rn),We("[swiper:restore-complete]",{restoredSessionIds:it.map(on=>on.id),nextActiveSessionId:rn})}(async()=>(it.length===0&&await Ln.current?.({createIfEmpty:!0}),Y(!1),requestAnimationFrame(()=>ze("restore-finished",{immediate:!0}))))()},[Un,En,fn,L,We,ze,u,c]),x.useEffect(()=>{if(!u||O||M.length===0)return;const ie=tb(M.map(Be=>({id:Be.id,backendSessionId:Be.sessionId})),c),Se=am({prioritySessionId:ie,activeSessionId:pt.current,persistedActiveSessionId:Yn,firstSessionId:M[0]?.id??null});Se&&Se!==pt.current&&N(Se)},[u,c,O,Yn,M]);const Et=x.useRef([]),Bn=x.useRef(!1);pt.current=F,x.useEffect(()=>{if(O)return;const ie=Et.current,Se=En;if(!Bn.current){B(ln=>f6(ln,Se)),Et.current=Se,Bn.current=!0;return}const Be=new Set(ie.map(ln=>ln.sessionId)),it=new Set(Se.map(ln=>ln.sessionId)),Ft=new Map(ie.map(ln=>[ln.sessionId,ln.name]));Et.current=Se,B(ln=>{const Vn=f6(ln,Se);return(!pt.current||!Vn.some(sr=>sr.id===pt.current))&&N(Vn[0]?.id??null),Vn});const Dt=Se.filter(ln=>!Be.has(ln.sessionId)),rn=[...Be].filter(ln=>!it.has(ln)),on=Se.filter(ln=>Be.has(ln.sessionId)&&Ft.get(ln.sessionId)!==ln.name);(Dt.length>0||rn.length>0||on.length>0)&&L("[Session] Synced persisted sessions:",{newSessionIds:Dt.map(ln=>ln.sessionId),removedSessionIds:rn,renamedSessionIds:on.map(ln=>ln.sessionId),currentSessionIds:Se.map(ln=>ln.sessionId)});for(const ln of Se){if(!ln.backendSessionId)continue;ns.getState().setTerminalSession(ln.sessionId,{sessionId:ln.backendSessionId,cols:80,rows:24,mode:ln.mode,tmuxSessionName:ln.tmuxSessionName})}},[En,O,L]);const bn=x.useCallback(async ie=>{try{const Se=ie?.mode==="tmux"||ie?.mode==="shell"?ie.mode:i,Be=(ie?.tmuxSessionName||"").trim(),it=a.trim(),Ft=Se==="tmux"?Be||it||vH():null,Dt=typeof ie?.cwd=="string"?ie.cwd:null,rn=F?ns.getState().sessions.get(F)?.cwd??null:null,on=typeof Dt=="string"&&Dt.trim().length>0?Dt:typeof rn=="string"&&rn.trim().length>0?rn:void 0,ln=await cr({mode:Se,tmuxSessionName:Ft,cwd:on,termType:"xterm-256color",createIfEmpty:ie?.createIfEmpty===!0}),Vn=ln.session,sr=ln.terminalSession,ar={id:Vn.sessionId,name:Vn.name,customName:Vn.customName===!0,sessionId:sr.sessionId,mode:sr.mode??Vn.mode,tmuxSessionName:sr.tmuxSessionName??Vn.tmuxSessionName};B(Rn=>bH(Rn,ar)),N(ar.id),ns.getState().setTerminalSession(ar.id,{sessionId:sr.sessionId,cols:80,rows:24,mode:ar.mode,tmuxSessionName:ar.tmuxSessionName,activeProgram:sr.activeProgram,activeProgramRaw:sr.activeProgramRaw,activeProgramSource:sr.activeProgramSource,cwd:sr.cwd}),L("[Session] Inventory opened session:",{frontendSessionId:ar.id,backendSessionId:sr.sessionId,reused:ln.reused,mode:ar.mode,tmuxSessionName:ar.tmuxSessionName});const Wt=ie?.command?.trim();return Wt&&await s8(sr.sessionId,`${Wt}\r`),ar.id}catch(Se){return console.error("[Session] Failed to create new session:",Se),null}},[i,a,F,cr,L]);Ln.current=bn;const Nt=x.useCallback((ie,Se={})=>{const Be=pt.current,it=!!Be&&$e.current[Be]===!0;if(N(ie),et.current&&Se.preserveMobileKeyboard===!1){zt.current=Date.now()+600,Be&&($e.current[Be]=!1),Bt(null),ne(null);const Ft=document.activeElement;Ft instanceof HTMLTextAreaElement&&Ft.closest(".terminal-viewport-container")&&Ft.blur();return}it&&et.current&&Bt(ie),Zt.current&&(!et.current||it)&&ne({sessionId:ie,token:Date.now()})},[]),Tr=x.useCallback(ie=>{N(ie),se(!0),he(null)},[]),Wr=x.useCallback(ie=>{const Se=pt.current;!Se||Se===ie||(Ye(Be=>cb(Be,Se,ie)),se(!1),Nt(Se,{preserveMobileKeyboard:!1}))},[Nt]),Rr=x.useCallback(async()=>{const ie=pt.current;if(!ie||Ie)return;tt(!0);const Se=ns.getState().sessions.get(ie)?.cwd??void 0,Be=await bn({cwd:Se||void 0,mode:i});if(tt(!1),!Be){he(C("common.error"));return}Ye(it=>cb(it,ie,Be)),se(!1),Nt(ie,{preserveMobileKeyboard:!1})},[Nt,i,bn,Ie,C]),Xn=x.useCallback(ie=>{Ye(Se=>rH(Se,ie)),ie&&Nt(ie,{preserveMobileKeyboard:!1})},[Nt]),is=x.useCallback(ie=>{Ye(Se=>nH(Se,ie)),Nt(ie,{preserveMobileKeyboard:!1})},[Nt]),Fr=x.useCallback((ie,Se,Be,it,Ft,Dt="linear",rn)=>{ie.preventDefault(),ie.stopPropagation();const on=ie.currentTarget,ln=ie.pointerId,Vn={x:ie.clientX,y:ie.clientY};on.setPointerCapture?.(ln);const sr=Se.getBoundingClientRect();let ar=!Le,lr=null;const Wt=pn=>{if(pn.pointerId!==ln)return;if(!ar){Math.hypot(pn.clientX-Vn.x,pn.clientY-Vn.y)>dH&&lr!==null&&(window.clearTimeout(lr),lr=null);return}pn.preventDefault();const gn=Be?(pn.clientY-sr.top)/sr.height:(pn.clientX-sr.left)/sr.width,Ot=Be?sr.height:sr.width,kn=Le?0:Be?hH:fH;Ye(_n=>_n.map(mn=>{if(mn.id!==it)return mn;const yn=rn??mn.sessionIds.length,xn=Dt==="grid-columns"?mn.gridColumnRatios:Dt==="grid-rows"?mn.gridRowRatios:mn.ratios,zr=id(xn,yn),zs=zr[Ft]+zr[Ft+1],mi=kn>0?Math.min(zs/2,kn/Math.max(1,Ot)):Math.min(zs/2,cH),hs=Z$(zr,Ft,gn,mi);return Dt==="grid-columns"?{...mn,gridColumnRatios:hs}:Dt==="grid-rows"?{...mn,gridRowRatios:hs}:{...mn,ratios:hs}}))},Rn=()=>{lr!==null&&(window.clearTimeout(lr),lr=null),window.removeEventListener("pointermove",Wt),window.removeEventListener("pointerup",Rn),window.removeEventListener("pointercancel",Rn),on.classList.remove("bg-primary"),Le&&document.dispatchEvent(new CustomEvent("termdock:gesture-lock",{detail:{locked:!1}})),Mn.current=null};Mn.current?.(),Mn.current=Rn,window.addEventListener("pointermove",Wt),window.addEventListener("pointerup",Rn),window.addEventListener("pointercancel",Rn),Le&&(document.dispatchEvent(new CustomEvent("termdock:gesture-lock",{detail:{locked:!0}})),lr=window.setTimeout(()=>{lr=null,ar=!0,on.classList.add("bg-primary"),navigator.vibrate?.(8)},uH))},[Le]),Ss=x.useCallback(ie=>{if(M.find(Be=>Be.id===ie)){if(ie===pt.current)return;if(!WQ({isMobile:et.current,viewportReady:X.has(ie),streamReady:ce.has(ie),contentReady:q.has(ie)})){$(null),N(ie),Zt.current&&ne({sessionId:ie,token:Date.now()}),L("[Session] Switched to session:",ie);return}ee(it=>{if(it.has(ie))return it;const Ft=new Set(it);return Ft.add(ie),Ft}),$(ie),L("[Session] Switched to session:",ie)}},[q,L,ce,M,X]),As=x.useCallback((ie,Se)=>{Se.trim()&&(B(Be=>Be.map(it=>it.id===ie?{...it,name:Se.trim(),customName:!0}:it)),Oe(ie,Se.trim()))},[Oe]),Gt=x.useCallback(ie=>{B(Se=>Se.map(Be=>Be.id===ie?{...Be,customName:!1}:Be)),te(ie)},[te]),Sn=x.useCallback(ie=>{B(Se=>{const Be=new Map(Se.map(rn=>[rn.id,rn])),it=ie.map(rn=>Be.get(rn)).filter(rn=>rn!==void 0),Ft=new Set(ie),Dt=Se.filter(rn=>!Ft.has(rn.id));return[...it,...Dt]}),Tt(ie),L("[Session] Reordered sessions:",ie),requestAnimationFrame(()=>{Ze.current?.update()})},[Tt,L]),Lr=x.useCallback(async ie=>{const Se=typeof ie=="string"?ie:ie.sessionId,Be=typeof ie=="string"?"auto":ie.closeMode??"auto",it=M.find(Dt=>Dt.id===Se);if(!it)return;const Ft=nT(Ir,Se,Dt=>Dt.id);try{Be==="destroy"&&it.mode==="tmux"&&it.tmuxSessionName?(await o8(it.tmuxSessionName),L("[Session] Destroyed tmux session:",{frontendSessionId:it.id,tmuxSessionName:it.tmuxSessionName})):it.sessionId&&(await i8(it.sessionId),L("[Session] Closed backend terminal:",it.sessionId))}catch(Dt){console.error("[Session] Failed to close backend terminal:",Dt);return}B(Dt=>{const rn=Dt.filter(on=>on.id!==Se);return N(Ft),rn}),ss(Se,Ft),delete $e.current[Se],L("[Session] Closed session:",{sessionId:Se,closeMode:Be})},[M,Ir,ss,L]),Dr=x.useCallback(ie=>{if(!ie)return;const Se=M.filter(Be=>Be.sessionId===ie);if(Se.length!==0){Se.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:ie,frontendSessionIds:Se.map(Be=>Be.id)}),B(Be=>{const it=Be.filter(Ft=>Ft.sessionId!==ie);return it.length!==Be.length&&!it.some(Dt=>Dt.id===F)&&N(it.length>0?it[0].id:null),it});for(const Be of Se)ss(Be.id),delete $e.current[Be.id];L("[Session] Backend gone, dropped local session(s):",Se.map(Be=>Be.id))}},[M,F,ss,L]);x.useEffect(()=>{const ie=gn=>{bn(gn.detail)},Se=gn=>{Ss(gn.detail)},Be=()=>{const gn=pt.current;!gn||et.current||ne({sessionId:gn,token:Date.now()})},it=gn=>{const Ot=gn;Ot.detail&&Tr(Ot.detail)},Ft=gn=>{const Ot=gn.detail;Xn(Ot??pt.current??void 0)},Dt=gn=>{const Ot=gn.detail;Ot&&is(Ot)},rn=gn=>{const Ot=gn.detail,kn=typeof Ot=="string"?Ot:Ot?.layout,_n=typeof Ot=="string"?pt.current:Ot?.sessionId;kn!=="horizontal"&&kn!=="vertical"&&kn!=="grid"||Ye(mn=>mn.map(yn=>yn.sessionIds.includes(_n??"")?{...yn,layout:kn}:yn))},on=gn=>{const kn=gn.detail?.direction;if(kn!=="prev"&&kn!=="next")return;const _n=Br.current;if(_n.length<=1)return;const mn=pt.current,yn=mn?_n.findIndex(hs=>hs.id===mn):-1,zs=((yn>=0?yn:0)+(kn==="next"?1:-1)+_n.length)%_n.length,mi=_n[zs]?.id;mi&&mi!==mn&&Ss(mi)},ln=gn=>{Lr(gn.detail)},Vn=gn=>{Dr(gn.detail)},sr=gn=>{const Ot=gn;!Ot.detail?.sessionId||!Ot.detail?.name||As(Ot.detail.sessionId,Ot.detail.name)},ar=gn=>{const Ot=gn;Ot.detail?.sessionId&&Gt(Ot.detail.sessionId)},lr=gn=>{const Ot=gn;Ot.detail?.sessionIds&&Sn(Ot.detail.sessionIds)},Wt=gn=>{const Ot=gn.detail;!Ot?.workspaceId||!Array.isArray(Ot.sessionIds)||Ye(kn=>sH(kn,Ot.workspaceId,Ot.sessionIds))},Rn=gn=>{const Ot=gn.detail;!Ot?.workspaceId||typeof Ot.name!="string"||Ye(kn=>iH(kn,Ot.workspaceId,Ot.name))},pn=gn=>{const Ot=gn.detail;!Ot?.primaryId||!Ot.secondaryId||Ot.primaryId===Ot.secondaryId||(Ye(kn=>cb(kn,Ot.primaryId,Ot.secondaryId)),Nt(Ot.primaryId,{preserveMobileKeyboard:!1}))};return window.addEventListener("new-terminal-session",ie),window.addEventListener("switch-terminal-session",Se),window.addEventListener("focus-active-terminal-session",Be),window.addEventListener("open-terminal-split-chooser",it),window.addEventListener("close-terminal-split",Ft),window.addEventListener("remove-terminal-split-pane",Dt),window.addEventListener("set-terminal-split-direction",rn),window.addEventListener("cycle-terminal-session",on),window.addEventListener("close-terminal-session",ln),window.addEventListener("close-terminal-session-by-backend",Vn),window.addEventListener("rename-terminal-session",sr),window.addEventListener("reset-terminal-session-name",ar),window.addEventListener("reorder-terminal-session",lr),window.addEventListener("reorder-terminal-split-workspace",Wt),window.addEventListener("rename-terminal-split-workspace",Rn),window.addEventListener("combine-terminal-split-sessions",pn),()=>{window.removeEventListener("new-terminal-session",ie),window.removeEventListener("switch-terminal-session",Se),window.removeEventListener("focus-active-terminal-session",Be),window.removeEventListener("open-terminal-split-chooser",it),window.removeEventListener("close-terminal-split",Ft),window.removeEventListener("remove-terminal-split-pane",Dt),window.removeEventListener("set-terminal-split-direction",rn),window.removeEventListener("cycle-terminal-session",on),window.removeEventListener("close-terminal-session",ln),window.removeEventListener("close-terminal-session-by-backend",Vn),window.removeEventListener("rename-terminal-session",sr),window.removeEventListener("reset-terminal-session-name",ar),window.removeEventListener("reorder-terminal-session",lr),window.removeEventListener("reorder-terminal-split-workspace",Wt),window.removeEventListener("rename-terminal-split-workspace",Rn),window.removeEventListener("combine-terminal-split-sessions",pn)}},[Nt,bn,Ss,Tr,Xn,is,Lr,Dr,As,Gt,Sn]),x.useEffect(()=>{if(!Ar||Le)return;const ie=Se=>{if(!(Se.ctrlKey||Se.metaKey)||!Se.shiftKey)return;if(Ar.layout==="horizontal"?Se.key==="ArrowLeft"||Se.key==="ArrowRight":Ar.layout==="vertical"?Se.key==="ArrowUp"||Se.key==="ArrowDown":Se.key.startsWith("Arrow")){Se.preventDefault(),Se.stopPropagation();const it=Ar.sessionIds.indexOf(pt.current??""),Ft=Se.key==="ArrowLeft"||Se.key==="ArrowUp"?-1:1,Dt=(Math.max(0,it)+Ft+Ar.sessionIds.length)%Ar.sessionIds.length,rn=Ar.sessionIds[Dt];if(!rn)return;Nt(rn);return}Se.key==="Backspace"&&(Se.preventDefault(),Se.stopPropagation(),Xn(pt.current??void 0))};return window.addEventListener("keydown",ie,!0),()=>window.removeEventListener("keydown",ie,!0)},[Nt,Ar,Xn,Le]);const Kr=ie=>{const Se=ns.getState().sessions.get(ie.id);return zc(ie,Se?.activeProgram??null,Se?.cwd??null,void 0,Se?.shellTitle??null,Se?.promptState??null)},Jr=(ie,Se={})=>{const Be=ie.id===F,it=mr.has(ie.id)&&!Se.hidden,Ft=u&&GQ({sessionId:ie.id,foregroundSessionId:or,visibleSessionIds:mr,deferredViewportSessionIds:Ce}),Dt=UQ({sessionId:ie.id,foregroundSessionId:or,foregroundReady:ur})&&u,rn=YQ({sessionId:ie.id,foregroundSessionId:or,requestToken:W.token,foregroundCompletedToken:re})&&u,on=ie.id===or||Ce.has(ie.id)?0:wn.get(ie.id)??Wm;return o.jsx("div",{className:`relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden ${Se.hidden?"invisible pointer-events-none":""}`,style:Se.containerStyle,"aria-hidden":Se.hidden||void 0,onPointerDown:()=>{Be||Nt(ie.id)},onWheelCapture:()=>{X$(Be,()=>Nt(ie.id))},children:o.jsx("div",{className:"min-h-0 flex-1 app-chrome-bg",children:Ft&&o.jsx(Q$,{sessionId:ie.id,mode:ie.mode,tmuxSessionName:ie.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:n,isActive:Be,focusSuspended:T!==null,deferCursorUntilPositioned:T===ie.id||ie.mode==="tmux"&&!q.has(ie.id),isLayoutVisible:it,initialConnectEnabled:Dt,resumeRequestEnabled:rn,suppressKeyboard:Se.suppressKeyboard,keyboardPortalTarget:Se.keyboardPortalTarget,sharedMobileKeyboardLayout:Se.sharedMobileKeyboardLayout,suppressPageFlipRefresh:Se.suppressPageFlipRefresh,focusRequestToken:Ue?.sessionId===ie.id?Ue.token:0,resumeRequestToken:W.token,resumeRequestReason:W.reason,forceResumeReconnect:W.forceForegroundReconnect&&ie.id===or,resumeRequestDelayMs:ie.id===or?0:Se.hidden?Wm:wn.get(ie.id)??Wm,initialConnectDelayMs:on,onStreamReadyChange:fs,onStreamConnected:li,onViewportReadyChange:Ct,onContentReadyChange:Kt,onKeyboardVisibilityChange:gt,showDebug:r,onStatusChange:Be?v:void 0})})},ie.id)};return o.jsxs("div",{className:"relative h-full flex flex-col",children:[dn&&o.jsx("section",{className:"fixed inset-x-3 top-[calc(var(--safe-top-inset)+0.75rem)] z-toast mx-auto max-w-lg rounded-2xl border border-warning/30 bg-surface-elevated px-4 py-3.5 shadow-[0_20px_60px_var(--app-shadow-strong)]",role:"alert","aria-live":"assertive",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-warning/15 text-warning",children:o.jsx(o1,{size:18})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h2",{className:"text-[13px] font-semibold text-foreground",children:C("tab.tmuxRecoveryTitle",{count:dn.sessions.length})}),o.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:C("tab.tmuxRecoveryHint")}),o.jsx("p",{className:"mt-1.5 truncate text-[10px] text-foreground/70",children:dn.sessions.map(ie=>ie.name).join(" · ")}),at&&o.jsx("p",{className:"mt-2 text-[10px] text-destructive",children:at}),o.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[o.jsxs("button",{type:"button",disabled:He!==null,onClick:()=>{In()},className:"inline-flex min-h-9 items-center gap-1.5 rounded-lg bg-primary px-3 text-[11px] font-medium text-primary-foreground transition active:opacity-80 disabled:opacity-50",children:[o.jsx(F8,{size:13,className:He==="restore"?"animate-spin":""}),C(He==="restore"?"tab.tmuxRecoveryRestoring":"tab.tmuxRecoveryRestoreAll")]}),o.jsx("button",{type:"button",disabled:He!==null,onClick:()=>{kt()},className:"inline-flex min-h-9 items-center rounded-lg px-3 text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground disabled:opacity-50",children:C("tab.tmuxRecoveryDismiss")})]})]})]})}),o.jsx("div",{className:"flex-1 overflow-hidden",children:o.jsx(ep,{onSwiper:ie=>{Ze.current=ie,ie.allowTouchMove=hn.length>1&&!hr&&!me,We("[swiper:on-swiper]",{allowTouchMove:ie.allowTouchMove}),requestAnimationFrame(()=>bt("on-swiper"))},onSlideChange:Pt,onTouchStart:(ie,Se)=>{const Be=p6(Se),it=Be==="touch"||Be==="pen"||Be==="unknown";R("[swipe:touch-start]",{pointerType:Be,allowed:it}),We("[swiper:touch-start]",{pointerType:Be,allowed:it}),it&&(pe(),It.current=!0)},onTouchEnd:(ie,Se)=>{const Be=p6(Se),it=Be==="touch"||Be==="pen"||Be==="unknown";R("[swipe:touch-end]",{pointerType:Be,allowed:it}),We("[swiper:touch-end]",{pointerType:Be,allowed:it}),it&&Pe("touch-end")},onTransitionEnd:()=>{const ie=Ze.current;if(It.current&&ie&&!gH(ie,Rt.current)){We("[swiper:transition-end-deferred]");return}pe(),It.current=!1,We("[swiper:transition-end]")},initialSlide:Math.max(0,ut),speed:Y2,slidesPerView:1,resistanceRatio:.82,threshold:8,longSwipesRatio:.2,touchAngle:45,touchStartPreventDefault:!1,simulateTouch:!1,noSwiping:!0,noSwipingSelector:"[data-mobile-keyboard='true']",className:"h-full",children:hn.map(ie=>{const Se=ie.workspace,Be=!!Se&&ie.sessions.length>=2,it=Le?Qe?"horizontal":"vertical":Se?.layout??"horizontal",Ft=it==="vertical",Dt=Se?.ratios.length===ie.sessions.length?Se.ratios:kc(ie.sessions.length),rn=mt?ie.sessions.findIndex(kn=>kn.id===mt):-1,on=Le&&mt?ie.sessions.some(kn=>kn.id===mt):!1,ln=ie.sessions.some(kn=>kn.id===F)?F:ie.sessions[0]?.id,Vn=Dt.flatMap((kn,_n)=>[on&&_n!==rn?"0px":`minmax(0, ${kn}fr)`,..._n<Dt.length-1?[on?"0px":"1px"]:[]]).join(" "),{columns:sr,rows:ar}=iT(ie.sessions.length),lr=id(Se?.gridColumnRatios,sr),Wt=id(Se?.gridRowRatios,ar),Rn=lr.slice(0,-1).map((kn,_n)=>lr.slice(0,_n+1).reduce((mn,yn)=>mn+yn,0)),pn=Wt.slice(0,-1).map((kn,_n)=>Wt.slice(0,_n+1).reduce((mn,yn)=>mn+yn,0)),gn=ie.sessions.length%sr,Ot={...it==="grid"?{gridTemplateColumns:lr.map(kn=>`minmax(0, ${kn}fr)`).join(" "),gridTemplateRows:Wt.map(kn=>`minmax(0, ${kn}fr)`).join(" "),gap:"1px"}:Ft?{gridTemplateRows:Vn}:{gridTemplateColumns:Vn},...Le?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:{}};return o.jsx(ud,{className:"h-full",children:o.jsx("div",{className:"h-full min-w-0","data-pinned-right-sidebar-inset":Kn.get(ie.key)??0,style:{paddingRight:Kn.get(ie.key)??0},children:Be?o.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col bg-[var(--chrome-bg)]",style:Le?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,children:[o.jsxs("div",{"data-split-container":"true",className:"relative grid min-h-0 min-w-0 flex-1 overflow-hidden",style:Ot,children:[ie.sessions.map((kn,_n)=>o.jsxs(I.Fragment,{children:[Jr(kn,{suppressKeyboard:Le&&kn.id!==ln,keyboardPortalTarget:Le?Mt:null,sharedMobileKeyboardLayout:Le,suppressPageFlipRefresh:!0,hidden:on&&rn!==_n,containerStyle:it==="grid"&&gn>0&&_n===ie.sessions.length-1?{gridColumn:`span ${sr-gn+1}`}:void 0}),it!=="grid"&&_n<ie.sessions.length-1&&Se&&o.jsx("button",{type:"button",className:`swiper-no-swiping relative z-20 touch-none select-none bg-[var(--border-strong)] transition-colors hover:bg-primary active:bg-primary ${Ft?"cursor-row-resize":"cursor-col-resize"} ${on?"invisible pointer-events-none":""}`,onPointerDownCapture:mn=>{const yn=mn.currentTarget.closest('[data-split-container="true"]');yn instanceof HTMLDivElement&&Fr(mn,yn,Ft,Se.id,_n)},onDoubleClick:mn=>{Le||(mn.preventDefault(),mn.stopPropagation(),Ye(yn=>yn.map(xn=>xn.id===Se.id?{...xn,ratios:kc(xn.sessionIds.length)}:xn)))},onContextMenu:mn=>{Le&&mn.preventDefault()},"aria-label":C("tab.split"),children:o.jsx("span",{"aria-hidden":"true","data-split-divider-hitarea":"true",className:`absolute ${Ft?"inset-x-0":"inset-y-0"}`,style:Ft?{top:-12,bottom:-12}:{left:-12,right:-12}})})]},kn.id)),it==="grid"&&Se&&Rn.map((kn,_n)=>o.jsx("button",{type:"button","data-split-grid-column-divider":_n,className:"swiper-no-swiping absolute top-0 z-20 w-px -translate-x-1/2 touch-none select-none cursor-col-resize bg-[var(--border-strong)] transition-colors hover:bg-primary active:bg-primary",style:{left:`${kn*100}%`,bottom:gn===0||_n<gn-1?0:`${(Wt.at(-1)??0)*100}%`},onPointerDownCapture:mn=>{const yn=mn.currentTarget.closest('[data-split-container="true"]');yn instanceof HTMLDivElement&&Fr(mn,yn,!1,Se.id,_n,"grid-columns",sr)},onDoubleClick:mn=>{mn.preventDefault(),mn.stopPropagation(),Ye(yn=>yn.map(xn=>xn.id===Se.id?{...xn,gridColumnRatios:kc(sr)}:xn))},"aria-label":C("tab.split"),children:o.jsx("span",{"aria-hidden":"true","data-split-divider-hitarea":"true",className:"absolute inset-y-0",style:{left:-12,right:-12}})},`grid-column-divider:${_n}`)),it==="grid"&&Se&&pn.map((kn,_n)=>o.jsx("button",{type:"button","data-split-grid-row-divider":_n,className:"swiper-no-swiping absolute inset-x-0 z-20 h-px -translate-y-1/2 touch-none select-none cursor-row-resize bg-[var(--border-strong)] transition-colors hover:bg-primary active:bg-primary",style:{top:`${kn*100}%`},onPointerDownCapture:mn=>{const yn=mn.currentTarget.closest('[data-split-container="true"]');yn instanceof HTMLDivElement&&Fr(mn,yn,!0,Se.id,_n,"grid-rows",ar)},onDoubleClick:mn=>{mn.preventDefault(),mn.stopPropagation(),Ye(yn=>yn.map(xn=>xn.id===Se.id?{...xn,gridRowRatios:kc(ar)}:xn))},"aria-label":C("tab.split"),children:o.jsx("span",{"aria-hidden":"true","data-split-divider-hitarea":"true",className:"absolute inset-x-0",style:{top:-12,bottom:-12}})},`grid-row-divider:${_n}`))]}),Le&&o.jsx("div",{ref:cn,className:"relative shrink-0 app-chrome-bg","data-split-keyboard-host":"true"})]}):Jr(ie.sessions[0])})},ie.key)})})}),me&&F&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop-soft)] backdrop-blur-sm",onClick:()=>se(!1),"aria-label":C("common.close")}),o.jsxs("section",{className:"fixed inset-x-3 bottom-3 z-modal-panel mx-auto max-h-[min(78svh,620px)] max-w-md overflow-hidden rounded-2xl border border-border/20 bg-surface shadow-[0_24px_70px_var(--app-shadow-strong)] sm:bottom-auto sm:top-1/2 sm:-translate-y-1/2",style:{paddingBottom:"var(--safe-bottom-inset)"},role:"dialog","aria-modal":"true","aria-label":C("tab.splitTitle"),children:[o.jsxs("header",{className:"flex items-start gap-3 border-b border-border/20 px-4 py-3.5",children:[o.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:o.jsx(S0,{size:17})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h2",{className:"text-[14px] font-semibold text-foreground",children:C("tab.splitTitle")}),o.jsx("p",{className:"mt-0.5 text-[11px] leading-relaxed text-muted-foreground",children:C("tab.splitExistingHint")})]}),o.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground",onClick:()=>se(!1),"aria-label":C("common.close"),children:o.jsx(ds,{size:16})})]}),o.jsxs("div",{className:"max-h-[calc(min(78svh,620px)-72px)] overflow-y-auto overscroll-contain p-2",children:[o.jsxs("button",{type:"button",disabled:Ie,onClick:()=>{Rr()},className:"flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition hover:bg-surface-2 active:bg-surface-elevated disabled:opacity-60",children:[o.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:o.jsx(ya,{size:17})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block text-[13px] font-medium text-foreground",children:C("tab.splitNew")}),o.jsx("span",{className:"mt-0.5 block text-[11px] text-muted-foreground",children:C("tab.splitNewHint")})]})]}),lt.filter(ie=>ie.id!==Ar?.id).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:C("tab.splitExistingGroups")}),lt.filter(ie=>ie.id!==Ar?.id).map((ie,Se)=>{const Be=ie.sessionIds.flatMap(Dt=>{const rn=M.find(on=>on.id===Dt);return rn?[rn]:[]});if(Be.length<2)return null;const it=ie.name||`${C("tab.splitWorkspace")} ${Se+1}`,Ft=Be.map(Dt=>Kr(Dt).primary).join(" · ");return o.jsxs("button",{type:"button",onClick:()=>Wr(Be[0].id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[o.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:o.jsx(S0,{size:15})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium text-foreground",children:it}),o.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[9px] font-medium text-primary",children:C("tab.splitOccupied")})]}),o.jsxs("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:[C("tab.sessionCount",{count:Be.length})," · ",Ft]})]}),o.jsx(Fa,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},ie.id)})]}),o.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:C("tab.splitAvailableSessions")}),M.filter(ie=>!lt.some(Se=>Se.sessionIds.includes(ie.id))&&ie.id!==F).length===0&&lt.filter(ie=>ie.id!==Ar?.id).length===0?o.jsx("p",{className:"px-3 py-4 text-[12px] text-muted-foreground",children:C("tab.splitNoOtherSessions")}):M.filter(ie=>!lt.some(Se=>Se.sessionIds.includes(ie.id))&&ie.id!==F).map(ie=>{const Se=wr.get(ie.id)??null,Be=Kr(ie);return o.jsxs("button",{type:"button",onClick:()=>Wr(ie.id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[o.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground",children:Se?o.jsx(Cu,{size:15}):o.jsx(S0,{size:15})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:Be.primary}),o.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:Se?Cc(Se)??Se:ie.name})]}),o.jsx(Fa,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},ie.id)})]})]})]}),_e&&o.jsx("div",{className:"fixed inset-x-3 bottom-4 z-toast mx-auto max-w-md rounded-xl border border-border/20 bg-surface-elevated px-4 py-3 text-center text-[12px] text-foreground shadow-lg",children:_e})]})},SH={sm:"h-4 w-7",md:"h-6 w-10"},AH={sm:"h-3 w-3",md:"h-5 w-5"},TH={sm:"translate-x-3",md:"translate-x-4"};function Uc({checked:e,disabled:t=!1,size:n="md",className:r=""}){return o.jsx("span",{"aria-hidden":"true",className:`inline-flex shrink-0 items-center rounded-full transition ${SH[n]} ${e?"bg-primary":"bg-surface-elevated"} ${t?"opacity-50":""} ${r}`,children:o.jsx("span",{className:`mx-0.5 inline-block rounded-full bg-[var(--background)] shadow transition ${AH[n]} ${e?TH[n]:""}`})})}function ga(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var CH=typeof Symbol=="function"&&Symbol.observable||"@@observable",g6=CH,x6=()=>Math.random().toString(36).substring(7).split("").join("."),kH={INIT:`@@redux/INIT${x6()}`,REPLACE:`@@redux/REPLACE${x6()}`},b6=kH;function _H(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function uT(e,t,n){if(typeof e!="function")throw new Error(ga(2));if(typeof t=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(ga(0));if(typeof t=="function"&&typeof n>"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(ga(1));return n(uT)(e,t)}let r=e,s=t,i=new Map,a=i,c=0,u=!1;function f(){a===i&&(a=new Map,i.forEach((C,L)=>{a.set(L,C)}))}function p(){if(u)throw new Error(ga(3));return s}function g(C){if(typeof C!="function")throw new Error(ga(4));if(u)throw new Error(ga(5));let L=!0;f();const R=c++;return a.set(R,C),function(){if(L){if(u)throw new Error(ga(6));L=!1,f(),a.delete(R),i=null}}}function y(C){if(!_H(C))throw new Error(ga(7));if(typeof C.type>"u")throw new Error(ga(8));if(typeof C.type!="string")throw new Error(ga(17));if(u)throw new Error(ga(9));try{u=!0,s=r(s,C)}finally{u=!1}return(i=a).forEach(R=>{R()}),C}function v(C){if(typeof C!="function")throw new Error(ga(10));r=C,y({type:b6.REPLACE})}function S(){const C=g;return{subscribe(L){if(typeof L!="object"||L===null)throw new Error(ga(11));function R(){const B=L;B.next&&B.next(p())}return R(),{unsubscribe:C(R)}},[g6](){return this}}}return y({type:b6.INIT}),{dispatch:y,subscribe:g,getState:p,replaceReducer:v,[g6]:S}}function y6(e,t){return function(...n){return t(e.apply(this,n))}}function v6(e,t){if(typeof e=="function")return y6(e,t);if(typeof e!="object"||e===null)throw new Error(ga(16));const n={};for(const r in e){const s=e[r];typeof s=="function"&&(n[r]=y6(s,t))}return n}function dT(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,n)=>(...r)=>t(n(...r)))}function LH(...e){return t=>(n,r)=>{const s=t(n,r);let i=()=>{throw new Error(ga(15))};const a={getState:s.getState,dispatch:(u,...f)=>i(u,...f)},c=e.map(u=>u(a));return i=dT(...c)(s.dispatch),{...s,dispatch:i}}}var db={exports:{}},fb={};var w6;function EH(){if(w6)return fb;w6=1;var e=Kg();function t(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:t,r=e.useSyncExternalStore,s=e.useRef,i=e.useEffect,a=e.useMemo,c=e.useDebugValue;return fb.useSyncExternalStoreWithSelector=function(u,f,p,g,y){var v=s(null);if(v.current===null){var S={hasValue:!1,value:null};v.current=S}else S=v.current;v=a(function(){function C(F){if(!L){if(L=!0,R=F,F=g(F),y!==void 0&&S.hasValue){var N=S.value;if(y(N,F))return M=N}return M=F}if(N=M,n(R,F))return N;var T=g(F);return y!==void 0&&y(N,T)?(R=F,N):(R=F,M=T)}var L=!1,R,M,B=p===void 0?null:p;return[function(){return C(f())},B===null?void 0:function(){return C(B())}]},[f,p,g,y]);var A=r(u,v[0],v[1]);return i(function(){S.hasValue=!0,S.value=A},[A]),c(A),A},fb}var S6;function IH(){return S6||(S6=1,db.exports=EH()),db.exports}IH();var RH=x.version.startsWith("19"),NH=Symbol.for(RH?"react.transitional.element":"react.element"),MH=Symbol.for("react.portal"),DH=Symbol.for("react.fragment"),jH=Symbol.for("react.strict_mode"),PH=Symbol.for("react.profiler"),BH=Symbol.for("react.consumer"),FH=Symbol.for("react.context"),fT=Symbol.for("react.forward_ref"),OH=Symbol.for("react.suspense"),QH=Symbol.for("react.suspense_list"),Av=Symbol.for("react.memo"),$H=Symbol.for("react.lazy"),HH=fT,zH=Av;function UH(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case NH:switch(e=e.type,e){case DH:case PH:case jH:case OH:case QH:return e;default:switch(e=e&&e.$$typeof,e){case FH:case fT:case $H:case Av:return e;case BH:return e;default:return t}}case MH:return t}}}function GH(e){return UH(e)===Av}function WH(e,t,n,r,{areStatesEqual:s,areOwnPropsEqual:i,areStatePropsEqual:a}){let c=!1,u,f,p,g,y;function v(R,M){return u=R,f=M,p=e(u,f),g=t(r,f),y=n(p,g,f),c=!0,y}function S(){return p=e(u,f),t.dependsOnOwnProps&&(g=t(r,f)),y=n(p,g,f),y}function A(){return e.dependsOnOwnProps&&(p=e(u,f)),t.dependsOnOwnProps&&(g=t(r,f)),y=n(p,g,f),y}function C(){const R=e(u,f),M=!a(R,p);return p=R,M&&(y=n(p,g,f)),y}function L(R,M){const B=!i(M,f),F=!s(R,u,M,f);return u=R,f=M,B&&F?S():B?A():F?C():y}return function(M,B){return c?L(M,B):v(M,B)}}function VH(e,{initMapStateToProps:t,initMapDispatchToProps:n,initMergeProps:r,...s}){const i=t(e,s),a=n(e,s),c=r(e,s);return WH(i,a,c,e,s)}function qH(e,t){const n={};for(const r in e){const s=e[r];typeof s=="function"&&(n[r]=(...i)=>t(s(...i)))}return n}function J2(e){return function(n){const r=e(n);function s(){return r}return s.dependsOnOwnProps=!1,s}}function A6(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function hT(e,t){return function(r,{displayName:s}){const i=function(c,u){return i.dependsOnOwnProps?i.mapToProps(c,u):i.mapToProps(c,void 0)};return i.dependsOnOwnProps=!0,i.mapToProps=function(c,u){i.mapToProps=e,i.dependsOnOwnProps=A6(e);let f=i(c,u);return typeof f=="function"&&(i.mapToProps=f,i.dependsOnOwnProps=A6(f),f=i(c,u)),f},i}}function Tv(e,t){return(n,r)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${r.wrappedComponentName}.`)}}function KH(e){return e&&typeof e=="object"?J2(t=>qH(e,t)):e?typeof e=="function"?hT(e):Tv(e,"mapDispatchToProps"):J2(t=>({dispatch:t}))}function YH(e){return e?typeof e=="function"?hT(e):Tv(e,"mapStateToProps"):J2(()=>({}))}function XH(e,t,n){return{...n,...e,...t}}function ZH(e){return function(n,{displayName:r,areMergedPropsEqual:s}){let i=!1,a;return function(u,f,p){const g=e(u,f,p);return i?s(g,a)||(a=g):(i=!0,a=g),a}}}function JH(e){return e?typeof e=="function"?ZH(e):Tv(e,"mergeProps"):()=>XH}function ez(e){e()}function tz(){let e=null,t=null;return{clear(){e=null,t=null},notify(){ez(()=>{let n=e;for(;n;)n.callback(),n=n.next})},get(){const n=[];let r=e;for(;r;)n.push(r),r=r.next;return n},subscribe(n){let r=!0;const s=t={callback:n,next:null,prev:t};return s.prev?s.prev.next=s:e=s,function(){!r||e===null||(r=!1,s.next?s.next.prev=s.prev:t=s.prev,s.prev?s.prev.next=s.next:e=s.next)}}}}var T6={notify(){},get:()=>[]};function pT(e,t){let n,r=T6,s=0,i=!1;function a(A){p();const C=r.subscribe(A);let L=!1;return()=>{L||(L=!0,C(),g())}}function c(){r.notify()}function u(){S.onStateChange&&S.onStateChange()}function f(){return i}function p(){s++,n||(n=t?t.addNestedSub(u):e.subscribe(u),r=tz())}function g(){s--,n&&s===0&&(n(),n=void 0,r.clear(),r=T6)}function y(){i||(i=!0,p())}function v(){i&&(i=!1,g())}const S={addNestedSub:a,notifyNestedSubs:c,handleChangeWrapper:u,isSubscribed:f,trySubscribe:y,tryUnsubscribe:v,getListeners:()=>r};return S}var nz=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",rz=nz(),sz=()=>typeof navigator<"u"&&navigator.product==="ReactNative",iz=sz(),oz=()=>rz||iz?x.useLayoutEffect:x.useEffect,wg=oz();function C6(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function hb(e,t){if(C6(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s=0;s<n.length;s++)if(!Object.prototype.hasOwnProperty.call(t,n[s])||!C6(e[n[s]],t[n[s]]))return!1;return!0}var az={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},lz={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},cz={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},mT={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},uz={[HH]:cz,[zH]:mT};function k6(e){return GH(e)?mT:uz[e.$$typeof]||az}var dz=Object.defineProperty,fz=Object.getOwnPropertyNames,_6=Object.getOwnPropertySymbols,hz=Object.getOwnPropertyDescriptor,pz=Object.getPrototypeOf,L6=Object.prototype;function ey(e,t){if(typeof t!="string"){if(L6){const i=pz(t);i&&i!==L6&&ey(e,i)}let n=fz(t);_6&&(n=n.concat(_6(t)));const r=k6(e),s=k6(t);for(let i=0;i<n.length;++i){const a=n[i];if(!lz[a]&&!(s&&s[a])&&!(r&&r[a])){const c=hz(t,a);try{dz(e,a,c)}catch{}}}}return e}var mz=Symbol.for("react-redux-context"),gz=typeof globalThis<"u"?globalThis:{};function xz(){if(!x.createContext)return{};const e=gz[mz]??=new Map;let t=e.get(x.createContext);return t||(t=x.createContext(null),e.set(x.createContext,t)),t}var gT=xz(),bz=[null,null];function yz(e,t,n){wg(()=>e(...t),n)}function vz(e,t,n,r,s,i){e.current=r,n.current=!1,s.current&&(s.current=null,i())}function wz(e,t,n,r,s,i,a,c,u,f,p){if(!e)return()=>{};let g=!1,y=null;const v=()=>{if(g||!c.current)return;const A=t.getState();let C,L;try{C=r(A,s.current)}catch(R){L=R,y=R}L||(y=null),C===i.current?a.current||f():(i.current=C,u.current=C,a.current=!0,p())};return n.onStateChange=v,n.trySubscribe(),v(),()=>{if(g=!0,n.tryUnsubscribe(),n.onStateChange=null,y)throw y}}function Sz(e,t){return e===t}function Az(e,t,n,{pure:r,areStatesEqual:s=Sz,areOwnPropsEqual:i=hb,areStatePropsEqual:a=hb,areMergedPropsEqual:c=hb,forwardRef:u=!1,context:f=gT}={}){const p=f,g=YH(e),y=KH(t),v=JH(n),S=!!e;return C=>{const L=C.displayName||C.name||"Component",R=`Connect(${L})`,M={shouldHandleStateChanges:S,displayName:R,wrappedComponentName:L,WrappedComponent:C,initMapStateToProps:g,initMapDispatchToProps:y,initMergeProps:v,areStatesEqual:s,areStatePropsEqual:a,areOwnPropsEqual:i,areMergedPropsEqual:c};function B(T){const[$,O,Y]=x.useMemo(()=>{const{reactReduxForwardedRef:_e,...he}=T;return[T.context,_e,he]},[T]),W=x.useMemo(()=>{let _e=p;return $?.Consumer,_e},[$,p]),ye=x.useContext(W),ce=!!T.store&&!!T.store.getState&&!!T.store.dispatch,ve=!!ye&&!!ye.store,re=ce?T.store:ye.store,ke=ve?ye.getServerState:re.getState,X=x.useMemo(()=>VH(re.dispatch,M),[re]),[V,q]=x.useMemo(()=>{if(!S)return bz;const _e=pT(re,ce?void 0:ye.subscription),he=_e.notifyNestedSubs.bind(_e);return[_e,he]},[re,ce,ye]),ue=x.useMemo(()=>ce?ye:{...ye,subscription:V},[ce,ye,V]),Ce=x.useRef(void 0),ee=x.useRef(Y),Ee=x.useRef(void 0),Ze=x.useRef(!1),$e=x.useRef(!1),Ue=x.useRef(void 0);wg(()=>($e.current=!0,()=>{$e.current=!1}),[]);const ne=x.useMemo(()=>()=>Ee.current&&Y===ee.current?Ee.current:X(re.getState(),Y),[re,Y]),lt=x.useMemo(()=>he=>V?wz(S,re,V,X,ee,Ce,Ze,$e,Ee,q,he):()=>{},[V]);yz(vz,[ee,Ce,Ze,Y,Ee,q]);let Ye;try{Ye=x.useSyncExternalStore(lt,ne,ke?()=>X(ke(),Y):ne)}catch(_e){throw Ue.current&&(_e.message+=`
79
+ `),ss(_t),Un(_t,!1),ur("Terminal session ended"),at(!1),Ct(!1),Ke(null),Pe(null),dn(_t,!1),Us();break}}},onError:(rt,_t)=>{if(Sn.current!==nt)return;const Zn=ee;if(!Zn)return;Jr.current=!1;const qn=_t&&rt.message==="Authentication required",vr=r$(rt),un=qn?rt.message:vr||_t?"Reconnecting...":rt.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${_t}):`,un),vr&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:bt.current,frontendSessionId:Zn,isActive:a,isMobile:Ee,fatal:_t,stack:new Error().stack}),ur(un),Ct(!!_t),_t&&(Ke(null),Un(Zn,!1),Us(),vr&&(X("[onError] Session lost, auto-recreating"),ur("Reconnecting..."),Ct(!1),ss(Zn),te(Zn),bt.current=null,Pi.current=!1,gs()))}},O$);gt.current=()=>{yt.close(),Sn.current===nt&&(Pt.current=null)},Pt.current=Ae},[cr,te,ss,X,Us,mi,M,Ti,gs,Mi,Un,Tt,In,dn,Fe,Pn,ke,ee]);I.useEffect(()=>{const Ae=JQ({isActive:a,isStreamReady:Je,reconnectStartedAt:we,now:Date.now()});if(Ae===null)return;const nt=window.setTimeout(()=>{X("[Terminal] visible reconnect watchdog expired",{backendSessionId:bt.current,reconnectStartedAt:we}),Us(),Un(ee,!1),ur("Reconnecting..."),Ct(!1),Ke(Date.now()),gs()},Ae);return()=>window.clearTimeout(nt)},[X,Us,a,Je,we,gs,ee,Un]);const Pi=I.useRef(!1),gi=I.useRef(!1),_s=I.useRef(0);I.useEffect(()=>()=>{_s.current+=1,Pi.current=!1,Us()},[Us]);const Ci=I.useRef(Yn),Bi=I.useRef(or);I.useEffect(()=>{const Ae=Ci.current,nt=Bi.current;Ci.current=Yn,Bi.current=or,vt.current===ee&&(Ae===Yn&&nt===or||(Pi.current=!1,Us(),ut(yt=>yt+1)))},[Yn,or,Us,ee]),I.useEffect(()=>{if(vt.current!==ee&&(X(`[useEffect] sessionId changed from ${vt.current} to ${ee}, allowing reinitialization`),Pi.current=!1,gi.current=!1),Pi.current&&vt.current===ee){X(`[useEffect] Already initialized for sessionId=${ee}, skipping`);return}const Ae=async Zn=>{if(X(`[ensureSession] Starting for sessionId=${ee}, runId=${Zn}`),!vt.current||vt.current!==ee){X(`[ensureSession] SessionId mismatch or stale run (current=${vt.current}, target=${ee}), skipping`);return}if(Zn!==_s.current){X(`[ensureSession] Stale run detected (runId=${Zn}, currentRunId=${_s.current}), skipping`);return}const qn=ns.getState(),vr=qn.getTerminalSession(ee),un=vr?.mode??Yn;X("[ensureSession] Current state from store:",{terminalSessionId:vr?.terminalSessionId,mode:vr?.mode,tmuxSessionName:vr?.tmuxSessionName,isConnecting:vr?.isConnecting});let Er=vr?.terminalSessionId??null,ti=!Er;if(Er&&un!==Yn?(X(`[ensureSession] Store mode mismatch for ${Er}: current=${un} desired=${Yn}, will create new session`),ti=!0,qn.clearTerminalSession(ee),Er=null):Er&&Yn==="tmux"&&or&&vr?.tmuxSessionName!==or&&(X(`[ensureSession] Store tmux name mismatch for ${Er}: current=${vr?.tmuxSessionName} desired=${or}, will create new session`),ti=!0,qn.clearTerminalSession(ee),Er=null),Er&&ke.checkHealth&&!pn.current){X(`[ensureSession] Checking health of existing session ${Er}`);try{const gr=await ke.checkHealth(Er);if(X("[ensureSession] Health check result:",gr),!gr.healthy)X(`[ensureSession] Session ${Er} is NOT healthy (healthy=${gr.healthy}), will create new session`),X("[ensureSession] Health check details:",gr),ti=!0,gr.mode&&vr?.terminalSessionId&&qn.setTerminalSession(ee,{sessionId:vr.terminalSessionId,cols:80,rows:24,mode:gr.mode,tmuxSessionName:gr.tmuxSessionName??null}),qn.clearTerminalSession(ee),X("[ensureSession] Cleared unhealthy session from store");else{X(`[ensureSession] Session ${Er} is healthy, reusing it, cwd=${gr.cwd}, clients=${gr.clients}, lastActivity=${Date.now()-(gr.lastActivity||0)}ms ago`),gr.mode&&vr?.terminalSessionId&&qn.setTerminalSession(ee,{sessionId:vr.terminalSessionId,cols:80,rows:24,mode:gr.mode,tmuxSessionName:gr.tmuxSessionName??null}),X(`[ensureSession] Setting terminalIdRef to ${Er} and starting stream`),bt.current=Er,ko(Er),X(`[ensureSession] Successfully reused healthy session ${Er}, returning early`);return}}catch(gr){X(`[ensureSession] Failed to check health of session ${Er}:`,gr),X("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(X(`[ensureSession] Decision: shouldCreateNewSession=${ti}, terminalId=${Er}`),ti){X(`[ensureSession] Creating new session, shouldCreateNewSession=${ti}, runId=${Zn}`),ur(null),Ct(!1),qn.setConnecting(ee,!0);const fi=ns.getState().getTerminalSession(ee),Xi=(fi?.mode??Yn)===Yn&&(Yn!=="tmux"||!or||fi?.tmuxSessionName===or);if(fi?.terminalSessionId&&Xi)X(`[ensureSession] Race condition avoided: another instance already created session ${fi.terminalSessionId}`),qn.setConnecting(ee,!1),Er=fi.terminalSessionId,ti=!1;else try{const Ur=await Ns();if(X(`[ensureSession] Opened managed backend session ${Ur.sessionId}`),Zn!==_s.current){X(`[ensureSession] Stale run after session creation (runId=${Zn}, currentRunId=${_s.current}), leaving ${Ur.sessionId} for sibling`);return}qn.setTerminalSession(ee,Ur),X(`[ensureSession] Updated store with new session ${Ur.sessionId}`),Er=Ur.sessionId}catch(Ur){if(Zn!==_s.current){X("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(Ur instanceof al&&q3(Ur)){X("[ensureSession] Confirmed missing persisted session:",{sessionId:ee,error:Ur.message}),qn.clearTerminalSession(ee),ur(nb),Ct(!0),qn.setConnecting(ee,!1);return}ur("Reconnecting..."),Ct(!0),qn.setConnecting(ee,!1);return}}if(Zn!==_s.current){X(`[ensureSession] Stale run before starting stream (runId=${Zn}, currentRunId=${_s.current}), skipping`);return}if(!Er){X(`[ensureSession] No terminalId, terminalId=${Er}`);return}X(`[ensureSession] Starting stream for session ${Er}`),bt.current=Er,ko(Er),X(`[ensureSession] ensureSession completed for sessionId=${ee}, terminalId=${Er}`)};let nt=null,yt=null;const rt=()=>{yt=null,!(Pi.current&&vt.current===ee)&&(X(`[useEffect] Running ensureSession for sessionId=${ee}, hasInitialized=${Pi.current}`),Pi.current=!0,gi.current=!0,nt=++_s.current,Ae(nt))};if(!C&&!gi.current){X(`[useEffect] Holding background connection until the selected session is ready: ${ee}`);return}const _t=gi.current?0:Math.max(0,A);return _t>0?(X(`[useEffect] Delaying initial connection for sessionId=${ee} by ${_t}ms`),yt=window.setTimeout(rt,_t)):rt(),()=>{yt!==null&&window.clearTimeout(yt),X(`[useEffect] Cleanup for sessionId=${ee}, runId=${nt??"pending"}`)}},[ee,We,ko,Us,ke,X,Yn,or,wr,A,C]);const Gs=I.useCallback(async()=>{if(ee&&!Kt){J(!0),ur(null),Ct(!1),Ke(null),Us();try{ke.forceKill&&await ke.forceKill({sessionId:ee})}catch{}Oe(ee),te(ee),Et.current?.clear(),await new Promise(Ae=>setTimeout(Ae,100));try{Un(ee,!0);const Ae=await Ns();fn(ee,Ae),bt.current=Ae.sessionId,ko(Ae.sessionId)}catch(Ae){ur(Ae instanceof al&&q3(Ae)?nb:"Reconnecting..."),Ct(!0),Un(ee,!1)}finally{J(!1)}}},[ee,Kt,Us,ke,Oe,te,Un,fn,ko,Ns]),qi=I.useCallback((Ae,nt)=>{if(!pn.current||!Ae)return;const yt=uQ(Ae),rt=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(Ae);if(kr&&rt&&(Wr.current=!0),Date.now()<Tr.current)return;let _t=Ae,Zn=nt?.consumeModifier??!1;if(!nt?.skipModifierTransform&&It&&Ae.length>0){const un=Ae[0];if(un.length===1&&/[a-zA-Z]/.test(un)){const Er=un.toUpperCase();It==="ctrl"?(_t=String.fromCharCode(Er.charCodeAt(0)&31),Zn=!0):It==="alt"&&(_t=`\x1B${Ae}`,Zn=!0)}Zn||(It==="alt"&&(_t=`\x1B${Ae}`),Zn=!0)}const qn=bt.current;if(!qn)return;(async()=>{try{if(kr&&!yt&&Wr.current&&ke.tmuxAction){Wr.current=!1;try{await ke.tmuxAction(qn,{action:"copy-mode",enabled:!1})}catch{}if(dQ(_t))return}await ke.sendInput(qn,_t),hr(ee)}catch(un){ur(un instanceof Error?un.message:"Failed to send input")}})(),Zn&&(xe||nn(null),Qr())},[It,hr,Qr,kr,xe,ke]);I.useEffect(()=>{const Ae=nt=>{if(!pn.current)return;const yt=nt,rt=yt.detail?.text;if(!rt)return;const _t=yt.detail?.nonce;if(fs.current){_t&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:_t,ok:!1}}));return}Et.current?.sendSequence(rt,{paste:yt.detail?.paste}),_t&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:_t,ok:!0}})),rQ(Ot.current,yt.detail?.focus!==!1)&&Qr()};return window.addEventListener("termdock-insert-reference",Ae),()=>window.removeEventListener("termdock-insert-reference",Ae)},[Qr]);const Js=I.useCallback((Ae,nt,yt)=>{const rt=bt.current;if(!rt){V("xterm resize push skipped: no terminalId",{cols:Ae,rows:nt});return}V("xterm resize push",{cols:Ae,rows:nt}),ke.resize({sessionId:rt,cols:Ae,rows:nt,seq:yt}).catch(_t=>{Et.current?.acknowledgeResize({seq:yt,ok:!1}),_t&&/session not found/i.test(String(_t.message||_t))&&console.warn("[Terminal] resize 404 session not found",{sessionId:rt,cols:Ae,rows:nt,stack:new Error().stack})})},[ke,V]),oo=I.useCallback(async Ae=>{const nt=bt.current;if(!(!nt||!ke.tmuxAction))try{const yt=await ke.tmuxAction(nt,Ae);yt.layout&&(Pe(yt.layout),Ae.action==="switch-session"&&(fn(ee,{sessionId:nt,cols:80,rows:24,mode:"tmux",tmuxSessionName:yt.layout.sessionName}),Pm(ee,{tmuxSessionName:yt.layout.sessionName}).catch(rt=>{console.warn("[Terminal] failed to update inventory after tmux switch",rt)})))}catch(yt){ur(yt instanceof Error?yt.message:"Failed to execute tmux action")}},[ee,fn,ke]);I.useEffect(()=>{if(!pe||!Kn)return;const nt=pe.windows.find(yt=>yt.id===pe.activeWindowId)?.panes.find(yt=>yt.id===pe.activePaneId);nt&&Et.current?.requestRefresh("tmux-layout",{candidateSize:{cols:nt.width,rows:nt.height},skipScrollToBottom:!0,dedupeKey:`${Kn}:${pe.sessionId}:${nt.id}:${nt.width}x${nt.height}`})},[pe,Kn]);const Ki=I.useCallback((Ae,nt=5)=>{const yt=Math.max(1,Math.min(Math.floor(nt)||1,40));Wr.current=!0;const rt=Rr.current;if(rt&&rt.direction===Ae){rt.lines+=yt;return}rt&&oo({action:"scroll",direction:rt.direction,lines:rt.lines}).finally(()=>{Qr()}),Rr.current={direction:Ae,lines:yt},Xn.current&&clearTimeout(Xn.current),Xn.current=setTimeout(()=>{const _t=Rr.current;_t&&(Rr.current=null,oo({action:"scroll",direction:_t.direction,lines:_t.lines}).finally(()=>{Qr()}))},0)},[Qr,oo]),$a=I.useCallback(Ae=>{const nt=Date.now(),yt=Fr.current,rt=yt!==null&&yt.modifier===Ae&&nt-yt.timestamp<=B$;if(Fr.current={modifier:Ae,timestamp:nt},xe===Ae){et(null),nn(null);return}if(rt){et(Ae),nn(Ae);return}xe!==null&&xe!==Ae&&et(null),nn(_t=>_t===Ae?null:Ae)},[xe]),wa=I.useCallback(Ae=>{if(me(Ae&&pn.current),V("input focus changed",{focused:Ae,isActive:pn.current,isMobile:Ot.current}),!Ot.current||!pn.current){lt(!1);return}lt(nt=>nt===Ae?nt:Ae)},[V]),Yi=I.useCallback(Ae=>{if(Bn.current=Ae,Ti(Ae,"viewport-watermark"),!Ae&&Nt.current.length>0){const nt=ee;if(nt){const yt=Nt.current;Nt.current=[];for(const rt of yt)cr(nt,rt)}}},[cr,Ti,ee]),_o=I.useCallback(Ae=>{pn.current&&Et.current?.ensureSizeMatches(Ae)},[]),Sa=I.useRef(null);I.useEffect(()=>{if(!a)return;const Ae=Sa.current;if(!Ae)return;const nt=()=>_o("pointerdown"),yt=()=>_o("keydown"),rt=()=>_o("touchstart"),_t=()=>_o("wheel");return Ae.addEventListener("pointerdown",nt),Ae.addEventListener("keydown",yt),Ae.addEventListener("touchstart",rt,{passive:!0}),Ae.addEventListener("wheel",_t,{passive:!0}),()=>{Ae.removeEventListener("pointerdown",nt),Ae.removeEventListener("keydown",yt),Ae.removeEventListener("touchstart",rt),Ae.removeEventListener("wheel",_t)}},[a,_o]);const Bl=I.useCallback(Ae=>{Et.current=Ae},[]),cl=I.useCallback(Ae=>{B?.(ee,Ae)},[B,ee]),ui=I.useCallback(Ae=>{const nt=SQ(Ae);if(!nt)return;const yt=It!==null;Et.current?.sendSequence(nt,{consumeModifier:yt})},[It]),Uo=I.useCallback(Ae=>{const nt=xQ(Ae);if(nt.length===0)return;const yt=It!==null;Et.current?.sendSequence(H3(nt[0]),{consumeModifier:yt});for(let rt=1;rt<nt.length;rt+=1){const _t=nt[rt];window.setTimeout(()=>{Et.current?.sendSequence(H3(_t))},gQ*rt)}},[It]),Aa=I.useCallback(()=>{Et.current?.pasteClipboardText()},[]),Go=I.useCallback(Ae=>{zr.current!==null&&(window.clearTimeout(zr.current),zr.current=null),Mn(Ae),(Ae==="inserted"||Ae==="failed")&&(zr.current=window.setTimeout(()=>{zr.current=null,Mn("idle")},1400))},[]),Fl=I.useCallback(()=>{Go("idle"),En(0),zs.current?.click()},[Go]),Ws=I.useCallback(Ae=>{const nt=Ae.currentTarget.files?.[0];Ae.currentTarget.value="",nt&&(En(0),Go("uploading"),QA(nt,(yt,rt)=>h2(yt,rt,void 0,En),yt=>{if(!pn.current||fs.current)throw new Error("Terminal unavailable");window.dispatchEvent(new CustomEvent("termdock-insert-reference",{detail:{text:OA(yt,null),focus:!0}}))}).then(()=>Go("inserted"),()=>Go("failed")))},[Go]),qt=mr||wn!==null;fs.current=qt;const xi=I.useRef(Br);qt||(xi.current=Br);const sa=qt?xi.current:Br,ul=I.useMemo(()=>bQ(sa,hn),[sa,hn]),Ta=I.useMemo(()=>U3(hn,ct),[ct,hn]),ki=!Ee&&ct!=="auto"&&Ta.showOnDesktop!==!0?"auto":ct,Me=ki==="auto"?ul:ki,ls=I.useMemo(()=>U3(hn,Me),[Me,hn]),xs=I.useMemo(()=>ls.actions.filter(Ae=>Ae.sequence.trim().length>0).map((Ae,nt)=>({...Ae,label:P2(Ae,nt)})),[ls.actions]),Vs=I.useMemo(()=>EA(Br),[Br]),Lo=ls.label,os=I.useMemo(()=>ki!=="auto"?`Manual preset: ${ls.label}`:Vs?`Auto preset · ${ls.label} (${Vs})`:"Auto preset",[Vs,ki,ls.label]),Ms=I.useCallback(Ae=>{Rt(Ae)},[]),ei=I.useCallback(()=>{Xe(Ae=>Ae==="copy"?"arrows":"copy"),Ln("idle")},[]),qs=I.useCallback(()=>{typeof window>"u"||(xn.current!==null&&window.clearTimeout(xn.current),xn.current=window.setTimeout(()=>{xn.current=null,Ln("idle")},1200))},[]),$r=I.useCallback(Ae=>{xn.current!==null&&typeof window<"u"&&(window.clearTimeout(xn.current),xn.current=null),Ln(Ae?"copied":"failed"),qs()},[qs]),bs=I.useCallback(Ae=>{Yt(Ae)},[]),Eo=I.useMemo(()=>Ee?yQ(hn):vQ(hn),[Ee,hn]),_i=I.useMemo(()=>XO(s),[s]),Dn=I.useMemo(()=>`terminal::${ee}`,[ee]);I.useEffect(()=>{ye?.({isConnecting:mr,isRestarting:Kt,hasError:!!wn,sessionId:Kn})},[mr,Kt,wn,Kn,ye]);const Fi=!Kn||mr||Kt,Or=I.useCallback((Ae,nt)=>{if(Fi)return;const yt=Math.max(1,Math.min(Math.floor(nt)||1,40));Ki(Ae,yt)},[Ki,Fi]);I.useEffect(()=>{if(!a||!Ee)return;Et.current?.requestRefresh("resize",{skipScrollToBottom:!Bt,force:!0})},[a,Ee,Bt,Zt,ee]),I.useEffect(()=>{if(!a||!Ee)return;const Ae=nt=>{const yt=nt.detail;Et.current?.requestRefresh("resize",{skipScrollToBottom:yt?.isOpen!==!0,force:!0})};return document.addEventListener("termdock:viewport-keyboard-change",Ae),()=>{document.removeEventListener("termdock:viewport-keyboard-change",Ae)}},[a,Ee,ee]);const Io=!T&&(Ee||ls.showOnDesktop===!0),Ro=a,Ha=Ee&&!O?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,ia=Ee&&!O?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0,Ls=o.jsx(AQ,{visible:Io,interactive:Ro,presentation:Ee?"mobile":"desktop-actions",activeModifier:It,lockedModifier:xe,disabled:Fi,defaultShowExtended:pt,presetLabel:Lo,presetModeLabel:os,presetMode:ki,presetOptions:Eo,includeAlt:ls.includeAlt,presetRowLayout:ls.rowLayout,extraActions:xs,onKeyPress:ui,onTextPress:Uo,onPastePress:Ee?Aa:void 0,onFilePress:Ee?Fl:void 0,fileUploadState:qe,fileUploadProgress:zt,longPressMode:Lt,copyFeedback:rr,onLongPressModeToggle:ei,onModifierToggle:$a,onPresetSelect:Ms,onExpandedChange:bs}),di=typeof window<"u"&&(navigator.maxTouchPoints>0||"ontouchstart"in window);return o.jsxs("div",{className:"relative flex h-full min-h-0 flex-col overflow-hidden",style:Ha,children:[o.jsx("input",{ref:zs,type:"file",className:"hidden",onChange:Ws}),ze&&o.jsx(TQ,{isMobile:Ee,isInputFocused:ne,isIOS:$e,isConnecting:mr,connectionError:wn,terminalSessionId:Kn}),o.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:_i.background,...ia},children:[o.jsx("div",{ref:Sa,className:"h-full w-full box-border",children:o.jsx(_A,{fallback:o.jsx("div",{className:"flex h-full items-center justify-center bg-background",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center rounded-2xl bg-surface-2 px-6 py-5 shadow-sm",children:[o.jsx("div",{className:"w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center",children:o.jsx("svg",{className:"w-5 h-5 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),o.jsx("span",{className:"text-sm text-muted-foreground",children:ce("terminal.componentFailed")})]})}),children:o.jsx(qO,{ref:Bl,sessionKey:Dn,isLayoutVisible:f,chunks:Ar,onInput:qi,onResize:Js,onFlowControl:Yi,onTmuxScroll:kr?Or:void 0,tmuxScrollSensitivity:.38,onDoubleTap:Ee?()=>{Et.current?.sendSequence(" ")}:void 0,onInputFocusChange:wa,onMobileLongPressCopyResult:$r,onReadyChange:cl,onSizeSynchronizedChange:Le,onKeyboardResizeSettlingChange:Ai,onWritesSettled:hs,onWriteProgress:ll,onCursorPositionChange:Wi,onDirectoryLinkActivate:Zr,terminalSettings:Ce,theme:_i,enableTouchScroll:Ee,mobileLongPressMode:Lt,autoFocus:!c&&!Ee&&!di,cursorVisible:!c&&fe&&!ft&&cn,suppressSmoothScroll:!ge||!tt,className:c||!fe||ft||!cn?"terminal-focus-suspended":void 0},Dn)})}),o.jsx(kQ,{connectionError:wn,isFatalError:li,isRestarting:Kt,isConnecting:mr,onHardRestart:Gs})]}),$?T?null:Ni.createPortal(Ls,$):Ls]})},$$=1e3,H$=2e4,z$=9e4,U$=5e3,Xr={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let cm=0,k0=null;function G$(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function eT(){Xr.idleCloseTimer&&(clearTimeout(Xr.idleCloseTimer),Xr.idleCloseTimer=null)}function W$(){eT(),!(Xr.ws&&Xr.ws.readyState===WebSocket.OPEN)&&(Xr.idleCloseTimer=setTimeout(()=>{Xr.idleCloseTimer=null,Xr.listeners.size===0&&V$()},U$))}function V$(){if(Xr.ws){try{Xr.ws.close()}catch{}Xr.ws=null}k0&&(clearInterval(k0),k0=null)}function a6(){if(Xr.reconnectTimer)return;const e=Math.min($$*Math.pow(2,Xr.reconnectAttempt),H$);Xr.reconnectAttempt+=1,Xr.reconnectTimer=setTimeout(()=>{Xr.reconnectTimer=null,tT()},e)}function tT(){const e=G$();if(!e||Xr.ws&&Xr.ws.readyState===WebSocket.OPEN)return;let t;try{t=new WebSocket(e)}catch{a6();return}Xr.ws=t,t.onopen=()=>{Xr.reconnectAttempt=0,cm=Date.now(),k0||(k0=setInterval(()=>{if(!(!Xr.ws||Xr.ws.readyState!==WebSocket.OPEN)&&cm>0&&Date.now()-cm>z$)try{Xr.ws.close()}catch{}},3e4),k0.unref?.())},t.onmessage=n=>{cm=Date.now();let r=null;try{r=JSON.parse(n.data)}catch{return}if(!r)return;if(r.type==="update-state"){const a=r.state;if(!a||typeof a.status!="string"||typeof a.currentVersion!="string")return;const c={type:"update-state",state:a};for(const u of Xr.listeners)try{u(c)}catch(f){console.error("[clientStateSync] listener threw:",f)}return}if(r.type==="context-draft"){if(typeof r.text!="string")return;const a={type:"context-draft",text:r.text,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const c of Xr.listeners)try{c(a)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(r.type==="pinned-explorer-roots"){if(!r.pinnedExplorerRoots||typeof r.pinnedExplorerRoots!="object"||Array.isArray(r.pinnedExplorerRoots))return;const a={type:"pinned-explorer-roots",pinnedExplorerRoots:r.pinnedExplorerRoots,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const c of Xr.listeners)try{c(a)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(r.type==="config-updated"){if(r.key!=="toolbar-presets"&&r.key!=="agent-rules"&&r.key!=="program-detection")return;const a={type:"config-updated",key:r.key,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0};for(const c of Xr.listeners)try{c(a)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(r.type!=="client-state"||!r.state)return;const s=r.state,i={type:"client-state",clientState:{sessions:Array.isArray(s.sessions)?s.sessions:[],updatedAt:typeof s.updatedAt=="number"?s.updatedAt:Date.now()},inventory:r.inventory,seq:typeof r.seq=="number"?r.seq:void 0};for(const a of Xr.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}},t.onclose=()=>{Xr.ws===t&&(Xr.ws=null),Xr.listeners.size>0&&a6()},t.onerror=()=>{}}function Bh(e){return Xr.listeners.add(e),eT(),Xr.ws||tT(),()=>{Xr.listeners.delete(e),Xr.listeners.size===0&&W$()}}function nT(e,t,n){const r=e.findIndex(s=>n(s)===t);return r<0?null:e[r+1]?n(e[r+1]):r>0?n(e[r-1]):null}const lb="termdock-sessions",W2="termdock-active-session",Sv="termdock-sessions-cache";function V2(){try{const e=localStorage.getItem(W2);return e&&e.trim().length>0?e:null}catch{return null}}function Jd(e){try{e?localStorage.setItem(W2,e):localStorage.removeItem(W2)}catch{}}function rT(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Sv);if(!e)return null;const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.sessionId=="string"&&typeof n.name=="string"):null}catch{return null}}function Gu(e){if(!(typeof window>"u"))try{localStorage.setItem(Sv,JSON.stringify(e))}catch{}}function l6(){if(!(typeof window>"u"))try{localStorage.removeItem(Sv)}catch{}}function sT(e){return e.map(t=>({...t,mode:t.mode==="tmux"?"tmux":"shell",tmuxSessionName:t.tmuxSessionName??null,customName:t.customName===!0}))}function c6(e){return sT(e.map(t=>({sessionId:t.sessionId,name:t.name,customName:t.customName===!0,backendSessionId:t.backendSessionId,mode:t.mode,tmuxSessionName:t.tmuxSessionName,createdAt:t.createdAt,lastActivity:t.lastActivity}))).map((t,n)=>({...t,activeProgram:e[n]?.activeProgram??null,cwd:e[n]?.cwd??null}))}function u6(e){return e.map(t=>`${t.sessionId}:${t.name}:${t.customName}:${t.backendSessionId}:${t.mode}:${t.tmuxSessionName}:${t.lastActivity}:${t.activeProgram??""}:${t.cwd??""}`).join("|")}function q2(e,t){return e.length===0?null:t&&e.some(n=>n.sessionId===t)?t:e[0]?.sessionId??null}function q$(){const e=rT()??[];return{sessions:e,activeSessionId:q2(e,V2())}}function K$(){const e=x.useRef(rT()).current,t=x.useRef(V2()).current,[n,r]=x.useState(e??[]),[s,i]=x.useState(null),[a,c]=x.useState(e&&e.length>0?q2(e,t):t),[u,f]=x.useState(e===null),p=x.useRef(!1),g=x.useRef(null),y=x.useRef(e===null),v=x.useRef(0),S=x.useRef(new Set),A=x.useRef(0);x.useEffect(()=>{y.current=u},[u]),x.useEffect(()=>{g.current=a},[a]);const C=x.useCallback(ve=>{const re=q2(ve,g.current??V2());return c(ke=>ke===re?ke:re),Jd(re),g.current=re,re},[]),L=x.useCallback((ve,re)=>{const ke=ve.filter(X=>!S.current.has(X.sessionId));r(X=>u6(X)===u6(ke)?X:ke),Gu(ke),re?.reconcileActive&&C(ke)},[C]),R=x.useCallback((ve,re)=>{const ke=S.current.size===0?ve:{...ve,clientSessions:ve.clientSessions.filter(X=>!S.current.has(X.sessionId))};i(ke),L(c6(ke.clientSessions),re)},[L]),M=x.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(lb)?(localStorage.removeItem(lb),l6(),Jd(null),r([]),c(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),B=x.useCallback(async()=>{if(typeof window>"u")return[];const ve=A.current;try{const re=await EI(),ke=c6(re.clientSessions);return ve!==A.current?(console.info("[session-inventory] ignored restore snapshot superseded by a local mutation"),ke.filter(X=>!S.current.has(X.sessionId))):(R(re,{reconcileActive:!0}),ke.length>0?ke:M())}catch(re){console.error("Failed to restore sessions from server:",re);try{return M()}catch(ke){console.error("Failed to discard legacy local sessions:",ke)}}finally{f(!1)}return[]},[R,M]),F=x.useCallback(async ve=>{const re=++A.current,ke=await a8(ve);return re===A.current&&(R(ke.inventory),c(ke.session.sessionId),Jd(ke.session.sessionId)),ke},[R]),N=x.useCallback(async(ve,re)=>{++A.current,S.current.add(ve),r(ke=>{const X=ke.filter(ue=>ue.sessionId!==ve),V=re!=null&&X.some(ue=>ue.sessionId===re),q=g.current===ve?V?re:nT(ke,ve,ue=>ue.sessionId):g.current;return c(q),Jd(q),Gu(X),X});try{await RI(ve)}catch(ke){console.error("Failed to remove session from inventory:",ke)}},[]),T=x.useCallback(ve=>{const re=Date.now();r(ke=>{const X=ke.map(V=>V.sessionId===ve?{...V,lastActivity:re}:V);return Gu(X),X})},[]),$=x.useCallback(ve=>{c(ve),Jd(ve)},[]),O=x.useCallback(async(ve,re)=>{const ke=re.trim();if(!ke)return;const X=++A.current;r(V=>{const q=V.map(ue=>ue.sessionId===ve?{...ue,name:ke,customName:!0}:ue);return Gu(q),q});try{const V=await Pm(ve,{name:ke,customName:!0});X===A.current&&R(V)}catch(V){console.error("Failed to rename session in inventory:",V)}},[R]),Y=x.useCallback(async ve=>{const re=++A.current;r(ke=>{const X=ke.map(V=>V.sessionId===ve?{...V,customName:!1}:V);return Gu(X),X});try{const ke=await Pm(ve,{customName:!1});re===A.current&&R(ke)}catch(ke){console.error("Failed to reset session name in inventory:",ke)}},[R]),W=x.useCallback(async ve=>{const re=++A.current;r(ke=>{const X=new Map(ke.map(ee=>[ee.sessionId,ee])),V=ve.map(ee=>X.get(ee)).filter(ee=>ee!==void 0),q=new Set(ve),ue=ke.filter(ee=>!q.has(ee.sessionId)),Ce=[...V,...ue];return Gu(Ce),Ce});try{const ke=await II(ve);re===A.current&&R(ke)}catch(ke){console.error("Failed to reorder sessions in inventory:",ke)}},[R]),ye=x.useCallback(async()=>{++A.current;for(const ve of n)S.current.add(ve.sessionId);r([]),i(null),c(null),Jd(null),l6(),typeof window<"u"&&localStorage.removeItem(lb);try{await NI()}catch(ve){console.error("Failed to clear session inventory:",ve)}},[n]),ce=x.useCallback(async(ve,re)=>{const ke=++A.current;r(X=>{const V=X.map(q=>q.sessionId===ve?{...q,backendSessionId:re}:q);return Gu(V),V});try{const X=await Pm(ve,{backendSessionId:re});ke===A.current&&R(X)}catch(X){console.error("Failed to update session backend in inventory:",X)}},[R]);return x.useEffect(()=>{p.current||(p.current=!0,B())},[B]),x.useEffect(()=>Bh(re=>{if(re.type!=="client-state"||y.current)return;const ke=typeof re.seq=="number"?re.seq:null;if(ke!==null){if(ke<v.current){console.warn("[session-inventory] ignored stale control snapshot",{seq:ke,latestSeq:v.current});return}v.current=ke}if(re.inventory){R(re.inventory,{reconcileActive:!0});return}const X=sT(re.clientState.sessions||[]);L(X,{reconcileActive:!0})}),[R,L]),{sessions:n,inventory:s,activeSessionId:a,isLoading:u,openSession:F,removeSession:N,updateSessionActivity:T,setActiveSession:$,updateSessionBackendId:ce,renameSession:O,resetSessionCustomName:Y,reorderSessions:W,clearAllSessions:ye,restoreSessions:B}}const Y$="termdock:startup:";function b0(e){if(typeof performance>"u"||typeof performance.mark!="function")return;const t=`${Y$}${e}`;performance.getEntriesByName(t,"mark").length>0||performance.mark(t)}function X$(e,t){e||Ni.flushSync(t)}const K2="horizontal";function kc(e){return e<=0?[]:Array.from({length:e},()=>1/e)}function id(e,t){if(!Array.isArray(e)||e.length!==t)return kc(t);const n=e.map(Number);if(n.some(s=>!Number.isFinite(s)||s<=0))return kc(t);const r=n.reduce((s,i)=>s+i,0);return r<=0?kc(t):n.map(s=>s/r)}function iT(e){const t=Math.max(1,Math.ceil(Math.sqrt(Math.max(1,e))));return{columns:t,rows:Math.max(1,Math.ceil(Math.max(1,e)/t))}}function Z$(e,t,n,r){if(t<0||t>=e.length-1)return e;const s=[...e],i=s.slice(0,t).reduce((f,p)=>f+p,0),a=s[t]+s[t+1],c=Math.max(0,Math.min(a/2,r)),u=Math.min(a-c,Math.max(c,n-i));return s[t]=u,s[t+1]=a-u,s}function J$(e){return e==="horizontal"||e==="vertical"||e==="grid"}function eH(e){if(!Array.isArray(e))return[];const t=new Set,n=new Set,r=[];for(const s of e){if(!s||typeof s!="object")continue;const i=s;if(typeof i.id!="string"||!i.id||n.has(i.id))continue;const a=Array.isArray(i.sessionIds)?i.sessionIds.filter(f=>typeof f=="string"&&!!f&&!t.has(f)):[],c=[...new Set(a)];if(c.length<2)continue;const u=iT(c.length);c.forEach(f=>t.add(f)),n.add(i.id),r.push({id:i.id,...typeof i.name=="string"&&i.name.trim()?{name:i.name.trim().slice(0,80)}:{},sessionIds:c,layout:J$(i.layout)?i.layout:K2,ratios:id(i.ratios,c.length),...i.gridColumnRatios!==void 0?{gridColumnRatios:id(i.gridColumnRatios,u.columns)}:{},...i.gridRowRatios!==void 0?{gridRowRatios:id(i.gridRowRatios,u.rows)}:{}})}return r}function tH(e,t){const n=new Set(t);return e.flatMap(r=>{const s=r.sessionIds.filter(i=>n.has(i));return s.length<2?[]:[{...r,sessionIds:s,ratios:s.length===r.sessionIds.length?id(r.ratios,s.length):kc(s.length)}]})}function Fh(e,t){if(t)return e.find(n=>n.sessionIds.includes(t))}function cb(e,t,n){if(!t||!n||t===n)return e;const r=Fh(e,t),s=Fh(e,n);if(r&&r.id===s?.id)return e;const i=[...r?.sessionIds??[t],...s?.sessionIds??[n]],a=[...new Set(i)],c={id:r?.id??`split:${t}`,...r?.name?{name:r.name}:{},sessionIds:a,layout:a.length>2&&(!r||r.layout===K2)?"grid":r?.layout??K2,ratios:kc(a.length)},u=new Set([r?.id,s?.id].filter(Boolean)),f=e.filter(g=>!u.has(g.id)),p=r?Math.max(0,e.findIndex(g=>g.id===r.id)):f.length;return f.splice(Math.min(p,f.length),0,c),f}function nH(e,t){const n=Fh(e,t);if(!n||!t)return e;if(n.sessionIds.length<=2)return e.filter(s=>s.id!==n.id);const r=n.sessionIds.filter(s=>s!==t);return e.map(s=>s.id===n.id?{...s,sessionIds:r,ratios:kc(r.length)}:s)}function rH(e,t){const n=Fh(e,t);return n?e.filter(r=>r.id!==n.id):e}function sH(e,t,n){return e.map(r=>{if(r.id!==t)return r;const s=[...new Set(n)],i=new Set(r.sessionIds);return s.length===r.sessionIds.length&&s.every(c=>i.has(c))?{...r,sessionIds:s}:r})}function iH(e,t,n){const r=n.trim().slice(0,80);return e.map(s=>s.id===t?{...s,...r?{name:r}:{name:void 0}}:s)}const Y2=320,oT=1,oH=Y2+120,X2="termdock:split-workspaces:v2",aT="termdock:split-workspace:v1",aH=.1,lH=.9,cH=.28,uH=300,dH=8,fH=280,hH=160;function ub(){if(typeof window>"u")return{mobile:!1,landscape:!1};const t=(navigator.maxTouchPoints>0||"ontouchstart"in window)&&Math.min(window.innerWidth,window.innerHeight)<768;return{mobile:t,landscape:t&&window.innerWidth>window.innerHeight}}function pH(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(X2);if(e)return eH(JSON.parse(e));const t=JSON.parse(window.localStorage.getItem(aT)||"null");if(t&&typeof t.primaryId=="string"&&typeof t.secondaryId=="string"&&t.primaryId!==t.secondaryId){const n=Math.min(lH,Math.max(aH,typeof t.ratio=="number"?t.ratio:.5));return[{id:`split:${t.primaryId}`,sessionIds:[t.primaryId,t.secondaryId],layout:t.direction==="vertical"?"vertical":"horizontal",ratios:[n,1-n]}]}}catch{}return[]}function mH(e,t){const n=new Map(e.map(a=>[a.id,a])),r=new Map;t.forEach(a=>a.sessionIds.forEach(c=>r.set(c,a)));const s=new Set,i=[];for(const a of e){const c=r.get(a.id);if(!c){i.push({key:a.id,sessions:[a]});continue}if(s.has(c.id))continue;s.add(c.id);const u=c.sessionIds.flatMap(f=>{const p=n.get(f);return p?[p]:[]});u.length>=2&&i.push({key:c.id,sessions:u,workspace:c})}return i}function d6(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(n=>n.cancel())}catch{}}function um(e,t){const n=vg(e,t);if(n===null)return;const r=e.wrapperEl;d6(e),r&&(r.style.transitionDuration="0ms");try{const s=e;s.setTransition?.(0),s.setTranslate?.(n),d6(e),r&&(r.style.transitionDuration="0ms",r.style.transform=`translate3d(${n}px, 0px, 0px)`)}catch{r&&(r.style.transitionDuration="0ms",r.style.transform=`translate3d(${n}px, 0px, 0px)`)}}function Z2(e){try{const t=typeof e.getTranslate=="function"?e.getTranslate():e.translate;return typeof t=="number"&&Number.isFinite(t)?t:null}catch{return typeof e.translate=="number"&&Number.isFinite(e.translate)?e.translate:null}}function vg(e,t){const n=e.snapGrid,r=Array.isArray(n)?n[t]:void 0;return typeof r!="number"||!Number.isFinite(r)?null:-r}function gH(e,t){const n=Z2(e),r=vg(e,t);return n!==null&&r!==null&&Math.abs(n-r)<=oT}function xH(e){const t=[],n=new Map,r=new Map,s=new Map;for(const i of e){const a=n.get(i.id)??[];if(a.push(i.id),n.set(i.id,a),i.sessionId){const c=r.get(i.sessionId)??[];c.push(i.id),r.set(i.sessionId,c)}if(i.mode==="tmux"&&i.tmuxSessionName){const c=s.get(i.tmuxSessionName)??[];c.push(i.id),s.set(i.tmuxSessionName,c)}}for(const[i,a]of n)a.length>1&&t.push({kind:"frontend",key:i,sessionIds:a});for(const[i,a]of r)a.length>1&&t.push({kind:"backend",key:i,sessionIds:a});for(const[i,a]of s)a.length>1&&t.push({kind:"tmux",key:i,sessionIds:a});return t}function lT(e){const t=new Map;for(const n of e)t.set(n.id,n);return Array.from(t.values())}function cT(e){return{id:e.sessionId,name:e.name,customName:e.customName===!0,sessionId:e.backendSessionId,mode:e.mode==="tmux"||e.mode==="shell"?e.mode:"shell",tmuxSessionName:e.tmuxSessionName??null}}function bH(e,t){const n=lT(e),r=n.findIndex(s=>s.id===t.id);if(r>=0){const s=[...n];return s[r]=t,s}return[...n,t]}function f6(e,t){const n=new Map(e.map(r=>[r.id,r]));return t.map(r=>{const s=n.get(r.sessionId);return{...cT(r),history:s?.history}})}function h6(e,t){return e.length===0?null:t&&e.some(n=>n.sessionId===t)?t:e[0]?.sessionId??null}function p6(e){if(!e||typeof e!="object")return"unknown";const t=e;if(typeof t.pointerType=="string"&&t.pointerType)return t.pointerType;if(typeof t.type=="string"){if(t.type.startsWith("touch"))return"touch";if(t.type.startsWith("mouse"))return"mouse";if(t.type.startsWith("pointer"))return"pointer"}return"unknown"}function m6(e){const t=new Map;for(const[n,r]of e)t.set(n,r.cwd??null);return t}function yH(e,t){if(e.size!==t.size)return!1;for(const[n,r]of t)if(e.get(n)!==r)return!1;return!0}function vH(e){const t="".toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,12);if(t)return`wt-${t}`;const n=Date.now().toString(36),r=Math.random().toString(36).slice(2,8);return`wt-${n}${r}`}const wH=({terminalSettings:e=pv(),colorTheme:t="dark",toolbarPresets:n=[],showDebug:r,terminalFocusAvailable:s=!0,defaultSessionMode:i="shell",defaultTmuxSessionName:a="",connectionPrioritySessionId:c=null,connectionPriorityReady:u=!0,desktopPinnedRightSidebar:f=!1,desktopPinnedRightSidebarWidth:p=0,desktopPinnedLeftSidebarWidth:g=0,desktopViewportWidth:y=0,onStatusChange:v,onSessionDataUpdate:S,onInitialViewportReady:A})=>{const{t:C}=ir(),L=x.useMemo(()=>pd("session"),[]),R=x.useMemo(()=>pd("terminal"),[]),[M,B]=x.useState([]),[F,N]=x.useState(null),[T,$]=x.useState(null),[O,Y]=x.useState(!0),[W,ye]=x.useState({token:0,reason:"visibility",forceForegroundReconnect:!1}),[ce,ve]=x.useState(()=>new Set),[re,ke]=x.useState(0),[X,V]=x.useState(()=>new Set),[q,ue]=x.useState(()=>new Set),[Ce,ee]=x.useState(()=>new Set),Ee=x.useRef(!1),Ze=x.useRef(null),$e=x.useRef({}),[Ue,ne]=x.useState(null),[lt,Ye]=x.useState(()=>pH()),[me,se]=x.useState(!1),[_e,he]=x.useState(null),[He,Je]=x.useState(null),[at,ge]=x.useState(null),[Ie,tt]=x.useState(!1),[Le,fe]=x.useState(()=>ub().mobile),[Qe,ft]=x.useState(()=>ub().landscape),[Mt,cn]=x.useState(null),[mt,Bt]=x.useState(null),Zt=x.useRef(s),It=x.useRef(!1),nn=x.useRef(null),xe=x.useRef(null),et=x.useRef(Le),pt=x.useRef(null),Yt=x.useRef(0),ct=x.useRef([]),Rt=x.useRef(0),Lt=x.useRef(null),Xe=x.useRef(!1),rr=x.useRef(!0),Ln=x.useRef(null),qe=x.useRef(""),Mn=x.useRef(null),zt=x.useRef(0);x.useEffect(()=>{if(typeof window>"u")return;const ie=()=>{const Se=ub();et.current=Se.mobile,fe(Se.mobile),ft(Se.landscape)};return ie(),window.addEventListener("resize",ie),()=>window.removeEventListener("resize",ie)},[]);const{sessions:En,inventory:Hn,activeSessionId:fn,isLoading:Un,openSession:cr,setActiveSession:qr,removeSession:ss,renameSession:Oe,resetSessionCustomName:te,reorderSessions:Tt,restoreSessions:Fe}=K$(),dn=Hn?.tmuxRecovery??null;x.useEffect(()=>{ge(null),Je(null)},[dn?.id]);const In=x.useCallback(async()=>{Je("restore"),ge(null);try{const ie=await kI();await Fe(),ie.failed>0&&ge(C("tab.tmuxRecoveryPartial",{restored:ie.restored,failed:ie.failed}))}catch{ge(C("tab.tmuxRecoveryFailed"))}finally{Je(null)}},[Fe,C]),kt=x.useCallback(async()=>{Je("dismiss"),ge(null);try{await _I(),await Fe()}catch{ge(C("tab.tmuxRecoveryDismissFailed"))}finally{Je(null)}},[Fe,C]),Pn=ht(ie=>ie.groupByFolder),hr=ht(ie=>ie.leftOpen||ie.rightOpen),[wr,pr]=x.useState(()=>m6(ns.getState().sessions));x.useEffect(()=>ns.subscribe(ie=>{const Se=m6(ie.sessions);pr(Be=>yH(Be,Se)?Be:Se)}),[]);const{arranged:Ir}=x.useMemo(()=>kA(M,ie=>wr.get(ie.id)??null,Pn,""),[M,wr,Pn]),Br=x.useRef(Ir);Br.current=Ir;const hn=x.useMemo(()=>mH(Ir,lt),[Ir,lt]),kr=x.useRef(hn);kr.current=hn;const Ar=x.useMemo(()=>Fh(lt,F),[F,lt]),mr=x.useMemo(()=>{const ie=hn.find(Se=>Se.sessions.some(Be=>Be.id===F));return new Set(ie?.sessions.map(Se=>Se.id)??[])},[F,hn]),Kn=x.useMemo(()=>{const ie=new Map;if(!f||y<=0)return ie;for(const Se of hn){const Be=Se.sessions[0];if(!Be)continue;const it=Se.sessions.some(Dt=>Dt.id===F)?p:E$(Be.id,wr.get(Be.id)??null,Se.workspace?.id??null),Ft=qm(it,y,g);ie.set(Se.key,Ft+yv)}return ie},[F,wr,g,f,p,y,hn]),Zr=x.useMemo(()=>tb(M.map(ie=>({id:ie.id,backendSessionId:ie.sessionId})),c),[c,M]),Yn=x.useMemo(()=>h6(En,fn),[fn,En]),or=am({prioritySessionId:Zr,activeSessionId:T??F,persistedActiveSessionId:Yn,firstSessionId:M[0]?.id??null}),wn=x.useMemo(()=>e$(hn.flatMap(ie=>ie.sessions.map(Se=>Se.id)),mr),[mr,hn]),ur=or!==null&&ce.has(or),fs=x.useCallback((ie,Se)=>{ve(Be=>{if(Be.has(ie)===Se)return Be;const Ft=new Set(Be);return Se?Ft.add(ie):Ft.delete(ie),Ft})},[]),li=x.useCallback(ie=>{const Se=Zr??T??pt.current;ie===Se&&(b0("foreground-stream-connected"),ke(Yt.current))},[T,Zr]),Ct=x.useCallback((ie,Se)=>{V(Be=>{if(Be.has(ie)===Se)return Be;const it=new Set(Be);return Se?it.add(ie):it.delete(ie),it})},[]),Kt=x.useCallback((ie,Se)=>{ue(Be=>{if(Be.has(ie)===Se)return Be;const it=new Set(Be);return Se?it.add(ie):it.delete(ie),it})},[]),J=or!==null&&X.has(or),we=or!==null&&q.has(or);x.useEffect(()=>{J&&b0("foreground-viewport-ready")},[J]),x.useEffect(()=>{we&&b0("foreground-content-ready")},[we]),x.useEffect(()=>{if(A){if(!O&&M.length===0){A();return}!J||!ur||!we||(b0("initial-viewport-presented"),A())}},[ur,we,J,O,A,M.length]),x.useEffect(()=>{if(mr.size===0)return;const ie=new Set(mr),Se=hn.findIndex(it=>it.sessions.some(Ft=>mr.has(Ft.id))),Be=Le?1:2;for(let it=-Be;it<=Be;it+=1)it!==0&&hn[Se+it]?.sessions.forEach(Ft=>ie.add(Ft.id));ee(it=>{let Ft=!1;const Dt=new Set(it);for(const rn of ie)Dt.has(rn)||(Dt.add(rn),Ft=!0);return Ft?Dt:it})},[Le,mr,hn]),x.useEffect(()=>{if(!T)return;if(!M.some(Se=>Se.id===T)){$(null);return}if(!X.has(T)||!ce.has(T)||!q.has(T))return;const ie=window.setTimeout(()=>{N(T),$(Se=>Se===T?null:Se),Zt.current&&!et.current&&ne({sessionId:T,token:Date.now()})},80);return()=>window.clearTimeout(ie)},[q,T,ce,M,X]),x.useEffect(()=>{typeof window>"u"||(lt.length>0?(window.localStorage.setItem(X2,JSON.stringify(lt)),window.localStorage.removeItem(aT)):window.localStorage.removeItem(X2))},[lt]),x.useEffect(()=>{Un||O||lt.length===0||Ye(ie=>tH(ie,M.map(Se=>Se.id)))},[Un,O,M,lt.length]),x.useEffect(()=>{if(!_e)return;const ie=window.setTimeout(()=>he(null),3200);return()=>window.clearTimeout(ie)},[_e]),x.useEffect(()=>()=>Mn.current?.(),[]),pt.current=F,Yt.current=W.token,ct.current=M,Lt.current=fn,Xe.current=Un,rr.current=O,Zt.current=s;const Ke=x.useCallback((ie=Ze.current)=>{const Se=Rt.current,Be=typeof window<"u"?window.visualViewport:null,it=ie?Z2(ie):null,Ft=ie?vg(ie,Se):null;return{sessionsLength:ct.current.length,workspaceSlidesLength:kr.current.length,sessionIds:ct.current.map(Dt=>Dt.id),activeSessionId:pt.current,activeSessionIndex:Se,persistedActiveId:Lt.current,isLoading:Xe.current,isRestoring:rr.current,activeIndex:ie?.activeIndex??null,previousIndex:ie?.previousIndex??null,animating:ie?.animating??null,allowTouchMove:ie?.allowTouchMove??null,width:ie?.width??null,translate:it,targetTranslate:Ft,translateDelta:it!==null&&Ft!==null?it-Ft:null,snapGridLength:ie?.snapGrid?.length??null,targetSnap:ie?.snapGrid?.[Se]??null,visualViewport:Be?{width:Math.round(Be.width),height:Math.round(Be.height),offsetTop:Math.round(Be.offsetTop)}:null}},[]),We=x.useCallback((ie,Se)=>{L(ie,{...Ke(),...Se})},[L,Ke]);x.useEffect(()=>{Un||O||F!==fn&&qr(F)},[F,Un,O,fn,qr]);const ut=x.useMemo(()=>{if(Ir.length===0||!F)return 0;const ie=hn.findIndex(Se=>Se.sessions.some(Be=>Be.id===F));return ie>=0?ie:0},[hn,F]);Rt.current=ut;const pe=x.useCallback(()=>{nn.current&&(clearTimeout(nn.current),nn.current=null)},[]),Pe=x.useCallback(ie=>{pe(),nn.current=setTimeout(()=>{nn.current=null,It.current=!1,We("[swiper:touch-guard-clear]",{reason:ie})},oH)},[pe,We]),ze=x.useCallback((ie,Se={})=>{const Be=Ze.current,it=Rt.current,Ft=kr.current;if(!Be||Ft.length===0||it<0||it>=Ft.length)return;if(It.current){We("[swiper:sync-skip-touch]",{reason:ie});return}if(Be.animating){We("[swiper:sync-skip-animating]",{reason:ie});return}const Dt=Z2(Be),rn=vg(Be,it),on=Dt!==null&&rn!==null&&Math.abs(Dt-rn)<=oT,ln=Be.activeIndex===it;if(We("[swiper:sync-check]",{reason:ie,activeIndexAligned:ln,translateAligned:on,immediate:Se.immediate===!0}),!(ln&&on)){if(ln){um(Be,it),We("[swiper:sync-forced-active]",{reason:ie,translateAligned:on,immediate:Se.immediate===!0});return}Se.immediate?(um(Be,it),Be.slideTo(it,0,!1),um(Be,it)):Be.slideTo(it,Y2,!1),We("[swiper:sync-applied]",{reason:ie,activeIndexAligned:ln,translateAligned:on,immediate:Se.immediate===!0})}},[We]);x.useEffect(()=>{const ie=Se=>{const Be=Se;Ze.current&&(Ze.current.allowTouchMove=!Be.detail.locked),We("[swiper:gesture-lock]",{locked:Be.detail.locked})};return document.addEventListener("termdock:gesture-lock",ie),()=>document.removeEventListener("termdock:gesture-lock",ie)},[We]),x.useEffect(()=>{if(M.length===0){F!==null&&N(null);return}if(!F){if(!u)return;N(am({prioritySessionId:Zr,activeSessionId:null,persistedActiveSessionId:Yn,firstSessionId:M[0]?.id??null}));return}M.some(Se=>Se.id===F)||N(M[0].id)},[M,F,u,Zr,Yn]);const gt=x.useCallback((ie,Se)=>{if(Se&&Date.now()<zt.current){$e.current[ie]=!1;return}$e.current[ie]=Se,Bt(Be=>Se?ie:Be===ie?null:Be)},[]),Pt=x.useCallback(ie=>{if(!It.current&&ie.activeIndex!==Rt.current){We("[swiper:slide-change-ignored-layout]",{instanceActiveIndex:ie.activeIndex,expectedActiveIndex:Rt.current}),requestAnimationFrame(()=>ze("ignored-layout-slide-change",{immediate:!0}));return}const Se=kr.current[ie.activeIndex],Be=Se?.sessions.some(Dt=>Dt.id===F)?F:Se?.sessions[0]?.id;if(We("[swiper:slide-change]",{nextSessionId:Be??null,instanceActiveIndex:ie.activeIndex}),!Be||Be===F)return;const it=!!F&&$e.current[F]===!0,Ft=Zt.current&&(!et.current||it);if(xe.current=Be,N(Be),Ft){ne({sessionId:Be,token:Date.now()});return}ne(null)},[M,F,We,ze]);x.useEffect(()=>{if(xe.current===F){We("[swiper:sync-skip-swiper-driven]",{activeSessionId:F}),xe.current=null;return}ze("active-session-index",{immediate:!0})},[F,ut,M.length,ze,We]),x.useEffect(()=>{const ie=Ze.current;if(!ie)return;const Se=hn.length>1&&!hr&&!me;ie.allowTouchMove!==Se&&(ie.allowTouchMove=Se,We("[swiper:allow-touch-sync]",{nextAllow:Se,sidebarOverlayOpen:hr}))},[hn.length,We,hr,me]);const bt=x.useCallback(ie=>{const Se=Ze.current;if(!Se)return;const Be=Se.el;if(We("[swiper:layout-before]",{reason:ie,scrollLeft:Be?.scrollLeft??null}),Be&&(Be.scrollLeft=0),Se.updateSize(),Se.updateSlides(),Se.updateProgress(),Se.updateSlidesClasses(),Be&&(Be.scrollLeft=0),We("[swiper:layout-after]",{reason:ie,scrollLeft:Be?.scrollLeft??null}),It.current||Se.animating){We("[swiper:layout-skip-sync-motion]",{reason:ie});return}ze(`layout:${ie}`,{immediate:!0}),requestAnimationFrame(()=>{const it=Ze.current;it&&(It.current||it.animating||um(it,Rt.current))})},[We,ze]);x.useEffect(()=>()=>pe(),[pe]);const vt=hn.map(ie=>ie.key).join("\0");x.useEffect(()=>{requestAnimationFrame(()=>bt("group-change"))},[Pn,vt,bt]),x.useEffect(()=>{let ie=null,Se="mount";const Be=on=>{Se=on,ie===null&&(ie=requestAnimationFrame(()=>{ie=null,bt(`viewport-change:${Se}`)}))},it=()=>Be("window-resize"),Ft=()=>Be("visual-viewport-resize"),Dt=()=>Be("visual-viewport-scroll"),rn=on=>{Be(`measured:${on.detail?.source??"unknown"}`)};return window.addEventListener("resize",it),window.visualViewport?.addEventListener("resize",Ft),window.visualViewport?.addEventListener("scroll",Dt),document.addEventListener(F2,rn),Be("mount"),()=>{window.removeEventListener("resize",it),window.visualViewport?.removeEventListener("resize",Ft),window.visualViewport?.removeEventListener("scroll",Dt),document.removeEventListener(F2,rn),ie!==null&&cancelAnimationFrame(ie)}},[bt]),x.useEffect(()=>{if(typeof document>"u")return;let ie=null,Se=null,Be=document.hidden;const it=Vn=>{if(Vn!=="online"&&document.hidden)return;const sr=performance.now();if(!XQ(Se,sr))return;Se=sr;const ar=Vn==="bfcache"||Vn==="online"?Vn:"visibility",lr=ZQ({wasPageHidden:Be,reason:Vn});Be=!1,Ja("info","PWA_RESUME scheduled",{source:Vn,forceForegroundReconnect:lr,activeSessionId:pt.current}),ye(Wt=>({token:Wt.token+1,reason:ar,forceForegroundReconnect:lr})),requestAnimationFrame(()=>bt(`resume:${Vn}:raf`)),ie&&clearTimeout(ie),ie=setTimeout(()=>{ie=null,bt(`resume:${Vn}:settled`)},320)},Ft=()=>{if(document.hidden){Be=!0,J5();return}it("visibility")},Dt=()=>{Be=!0,J5()},rn=Vn=>{it(Vn.persisted?"bfcache":"pageshow")},on=()=>it("online"),ln=()=>it("focus");return document.addEventListener("visibilitychange",Ft),window.addEventListener("pagehide",Dt),window.addEventListener("pageshow",rn),window.addEventListener("online",on),window.addEventListener("focus",ln),()=>{document.removeEventListener("visibilitychange",Ft),window.removeEventListener("pagehide",Dt),window.removeEventListener("pageshow",rn),window.removeEventListener("online",on),window.removeEventListener("focus",ln),ie&&clearTimeout(ie)}},[bt]),x.useEffect(()=>{if(!KQ(O))return;const ie=xH(M),Se=JSON.stringify(ie);ie.length>0&&Se!==qe.current?(qe.current=Se,console.warn("[session-invariant] duplicate mapping detected",ie)):ie.length===0&&qe.current&&(qe.current=""),S?.({sessions:M.map(Be=>({id:Be.id,name:Be.name,customName:Be.customName,mode:Be.mode,tmuxSessionName:Be.tmuxSessionName})),activeSessionId:F,splitWorkspaces:lt.map(({id:Be,name:it,sessionIds:Ft,layout:Dt})=>({id:Be,...it?{name:it}:{},sessionIds:Ft,layout:Dt}))})},[M,F,lt,S,O]),x.useEffect(()=>{if(Un||Ee.current)return;Ee.current=!0;const ie=tb(En.map(Dt=>({id:Dt.sessionId,backendSessionId:Dt.backendSessionId??null})),c),Se=h6(En,fn),Be=am({prioritySessionId:u?ie:null,activeSessionId:null,persistedActiveSessionId:Se,firstSessionId:En[0]?.sessionId??null}),it=lT(En.map(cT));if(L("[Session] Restoring",it.length,"persisted sessions (one-shot)"),We("[swiper:restore-start]",{persistedSessionIds:En.map(Dt=>Dt.sessionId),nextActiveSessionId:Be}),it.length>0){const Dt=ns.getState();it.forEach(on=>{on.sessionId&&Dt.setTerminalSession(on.id,{sessionId:on.sessionId,cols:80,rows:24,mode:on.mode,tmuxSessionName:on.tmuxSessionName,history:on.history})}),En.forEach(on=>{on.activeProgram!=null&&Dt.setSessionActiveProgram(on.sessionId,on.activeProgram),on.cwd!=null&&Dt.setSessionCwd(on.sessionId,on.cwd)}),B(it);const rn=Be||it[0]?.id||null;N(rn),We("[swiper:restore-complete]",{restoredSessionIds:it.map(on=>on.id),nextActiveSessionId:rn})}(async()=>(it.length===0&&await Ln.current?.({createIfEmpty:!0}),Y(!1),requestAnimationFrame(()=>ze("restore-finished",{immediate:!0}))))()},[Un,En,fn,L,We,ze,u,c]),x.useEffect(()=>{if(!u||O||M.length===0)return;const ie=tb(M.map(Be=>({id:Be.id,backendSessionId:Be.sessionId})),c),Se=am({prioritySessionId:ie,activeSessionId:pt.current,persistedActiveSessionId:Yn,firstSessionId:M[0]?.id??null});Se&&Se!==pt.current&&N(Se)},[u,c,O,Yn,M]);const Et=x.useRef([]),Bn=x.useRef(!1);pt.current=F,x.useEffect(()=>{if(O)return;const ie=Et.current,Se=En;if(!Bn.current){B(ln=>f6(ln,Se)),Et.current=Se,Bn.current=!0;return}const Be=new Set(ie.map(ln=>ln.sessionId)),it=new Set(Se.map(ln=>ln.sessionId)),Ft=new Map(ie.map(ln=>[ln.sessionId,ln.name]));Et.current=Se,B(ln=>{const Vn=f6(ln,Se);return(!pt.current||!Vn.some(sr=>sr.id===pt.current))&&N(Vn[0]?.id??null),Vn});const Dt=Se.filter(ln=>!Be.has(ln.sessionId)),rn=[...Be].filter(ln=>!it.has(ln)),on=Se.filter(ln=>Be.has(ln.sessionId)&&Ft.get(ln.sessionId)!==ln.name);(Dt.length>0||rn.length>0||on.length>0)&&L("[Session] Synced persisted sessions:",{newSessionIds:Dt.map(ln=>ln.sessionId),removedSessionIds:rn,renamedSessionIds:on.map(ln=>ln.sessionId),currentSessionIds:Se.map(ln=>ln.sessionId)});for(const ln of Se){if(!ln.backendSessionId)continue;ns.getState().setTerminalSession(ln.sessionId,{sessionId:ln.backendSessionId,cols:80,rows:24,mode:ln.mode,tmuxSessionName:ln.tmuxSessionName})}},[En,O,L]);const bn=x.useCallback(async ie=>{try{const Se=ie?.mode==="tmux"||ie?.mode==="shell"?ie.mode:i,Be=(ie?.tmuxSessionName||"").trim(),it=a.trim(),Ft=Se==="tmux"?Be||it||vH():null,Dt=typeof ie?.cwd=="string"?ie.cwd:null,rn=F?ns.getState().sessions.get(F)?.cwd??null:null,on=typeof Dt=="string"&&Dt.trim().length>0?Dt:typeof rn=="string"&&rn.trim().length>0?rn:void 0,ln=await cr({mode:Se,tmuxSessionName:Ft,cwd:on,termType:"xterm-256color",createIfEmpty:ie?.createIfEmpty===!0}),Vn=ln.session,sr=ln.terminalSession,ar={id:Vn.sessionId,name:Vn.name,customName:Vn.customName===!0,sessionId:sr.sessionId,mode:sr.mode??Vn.mode,tmuxSessionName:sr.tmuxSessionName??Vn.tmuxSessionName};B(Rn=>bH(Rn,ar)),N(ar.id),ns.getState().setTerminalSession(ar.id,{sessionId:sr.sessionId,cols:80,rows:24,mode:ar.mode,tmuxSessionName:ar.tmuxSessionName,activeProgram:sr.activeProgram,activeProgramRaw:sr.activeProgramRaw,activeProgramSource:sr.activeProgramSource,cwd:sr.cwd}),L("[Session] Inventory opened session:",{frontendSessionId:ar.id,backendSessionId:sr.sessionId,reused:ln.reused,mode:ar.mode,tmuxSessionName:ar.tmuxSessionName});const Wt=ie?.command?.trim();return Wt&&await s8(sr.sessionId,`${Wt}\r`),ar.id}catch(Se){return console.error("[Session] Failed to create new session:",Se),null}},[i,a,F,cr,L]);Ln.current=bn;const Nt=x.useCallback((ie,Se={})=>{const Be=pt.current,it=!!Be&&$e.current[Be]===!0;if(N(ie),et.current&&Se.preserveMobileKeyboard===!1){zt.current=Date.now()+600,Be&&($e.current[Be]=!1),Bt(null),ne(null);const Ft=document.activeElement;Ft instanceof HTMLTextAreaElement&&Ft.closest(".terminal-viewport-container")&&Ft.blur();return}it&&et.current&&Bt(ie),Zt.current&&(!et.current||it)&&ne({sessionId:ie,token:Date.now()})},[]),Tr=x.useCallback(ie=>{N(ie),se(!0),he(null)},[]),Wr=x.useCallback(ie=>{const Se=pt.current;!Se||Se===ie||(Ye(Be=>cb(Be,Se,ie)),se(!1),Nt(Se,{preserveMobileKeyboard:!1}))},[Nt]),Rr=x.useCallback(async()=>{const ie=pt.current;if(!ie||Ie)return;tt(!0);const Se=ns.getState().sessions.get(ie)?.cwd??void 0,Be=await bn({cwd:Se||void 0,mode:i});if(tt(!1),!Be){he(C("common.error"));return}Ye(it=>cb(it,ie,Be)),se(!1),Nt(ie,{preserveMobileKeyboard:!1})},[Nt,i,bn,Ie,C]),Xn=x.useCallback(ie=>{Ye(Se=>rH(Se,ie)),ie&&Nt(ie,{preserveMobileKeyboard:!1})},[Nt]),is=x.useCallback(ie=>{Ye(Se=>nH(Se,ie)),Nt(ie,{preserveMobileKeyboard:!1})},[Nt]),Fr=x.useCallback((ie,Se,Be,it,Ft,Dt="linear",rn)=>{ie.preventDefault(),ie.stopPropagation();const on=ie.currentTarget,ln=ie.pointerId,Vn={x:ie.clientX,y:ie.clientY};on.setPointerCapture?.(ln);const sr=Se.getBoundingClientRect();let ar=!Le,lr=null;const Wt=pn=>{if(pn.pointerId!==ln)return;if(!ar){Math.hypot(pn.clientX-Vn.x,pn.clientY-Vn.y)>dH&&lr!==null&&(window.clearTimeout(lr),lr=null);return}pn.preventDefault();const gn=Be?(pn.clientY-sr.top)/sr.height:(pn.clientX-sr.left)/sr.width,Ot=Be?sr.height:sr.width,kn=Le?0:Be?hH:fH;Ye(_n=>_n.map(mn=>{if(mn.id!==it)return mn;const yn=rn??mn.sessionIds.length,xn=Dt==="grid-columns"?mn.gridColumnRatios:Dt==="grid-rows"?mn.gridRowRatios:mn.ratios,zr=id(xn,yn),zs=zr[Ft]+zr[Ft+1],mi=kn>0?Math.min(zs/2,kn/Math.max(1,Ot)):Math.min(zs/2,cH),hs=Z$(zr,Ft,gn,mi);return Dt==="grid-columns"?{...mn,gridColumnRatios:hs}:Dt==="grid-rows"?{...mn,gridRowRatios:hs}:{...mn,ratios:hs}}))},Rn=()=>{lr!==null&&(window.clearTimeout(lr),lr=null),window.removeEventListener("pointermove",Wt),window.removeEventListener("pointerup",Rn),window.removeEventListener("pointercancel",Rn),on.classList.remove("bg-primary"),Le&&document.dispatchEvent(new CustomEvent("termdock:gesture-lock",{detail:{locked:!1}})),Mn.current=null};Mn.current?.(),Mn.current=Rn,window.addEventListener("pointermove",Wt),window.addEventListener("pointerup",Rn),window.addEventListener("pointercancel",Rn),Le&&(document.dispatchEvent(new CustomEvent("termdock:gesture-lock",{detail:{locked:!0}})),lr=window.setTimeout(()=>{lr=null,ar=!0,on.classList.add("bg-primary"),navigator.vibrate?.(8)},uH))},[Le]),Ss=x.useCallback(ie=>{if(M.find(Be=>Be.id===ie)){if(ie===pt.current)return;if(!WQ({isMobile:et.current,viewportReady:X.has(ie),streamReady:ce.has(ie),contentReady:q.has(ie)})){$(null),N(ie),Zt.current&&ne({sessionId:ie,token:Date.now()}),L("[Session] Switched to session:",ie);return}ee(it=>{if(it.has(ie))return it;const Ft=new Set(it);return Ft.add(ie),Ft}),$(ie),L("[Session] Switched to session:",ie)}},[q,L,ce,M,X]),As=x.useCallback((ie,Se)=>{Se.trim()&&(B(Be=>Be.map(it=>it.id===ie?{...it,name:Se.trim(),customName:!0}:it)),Oe(ie,Se.trim()))},[Oe]),Gt=x.useCallback(ie=>{B(Se=>Se.map(Be=>Be.id===ie?{...Be,customName:!1}:Be)),te(ie)},[te]),Sn=x.useCallback(ie=>{B(Se=>{const Be=new Map(Se.map(rn=>[rn.id,rn])),it=ie.map(rn=>Be.get(rn)).filter(rn=>rn!==void 0),Ft=new Set(ie),Dt=Se.filter(rn=>!Ft.has(rn.id));return[...it,...Dt]}),Tt(ie),L("[Session] Reordered sessions:",ie),requestAnimationFrame(()=>{Ze.current?.update()})},[Tt,L]),Lr=x.useCallback(async ie=>{const Se=typeof ie=="string"?ie:ie.sessionId,Be=typeof ie=="string"?"auto":ie.closeMode??"auto",it=M.find(Dt=>Dt.id===Se);if(!it)return;const Ft=nT(Ir,Se,Dt=>Dt.id);try{Be==="destroy"&&it.mode==="tmux"&&it.tmuxSessionName?(await o8(it.tmuxSessionName),L("[Session] Destroyed tmux session:",{frontendSessionId:it.id,tmuxSessionName:it.tmuxSessionName})):it.sessionId&&(await i8(it.sessionId),L("[Session] Closed backend terminal:",it.sessionId))}catch(Dt){console.error("[Session] Failed to close backend terminal:",Dt);return}B(Dt=>{const rn=Dt.filter(on=>on.id!==Se);return N(Ft),rn}),ss(Se,Ft),delete $e.current[Se],L("[Session] Closed session:",{sessionId:Se,closeMode:Be})},[M,Ir,ss,L]),Dr=x.useCallback(ie=>{if(!ie)return;const Se=M.filter(Be=>Be.sessionId===ie);if(Se.length!==0){Se.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:ie,frontendSessionIds:Se.map(Be=>Be.id)}),B(Be=>{const it=Be.filter(Ft=>Ft.sessionId!==ie);return it.length!==Be.length&&!it.some(Dt=>Dt.id===F)&&N(it.length>0?it[0].id:null),it});for(const Be of Se)ss(Be.id),delete $e.current[Be.id];L("[Session] Backend gone, dropped local session(s):",Se.map(Be=>Be.id))}},[M,F,ss,L]);x.useEffect(()=>{const ie=gn=>{bn(gn.detail)},Se=gn=>{Ss(gn.detail)},Be=()=>{const gn=pt.current;!gn||et.current||ne({sessionId:gn,token:Date.now()})},it=gn=>{const Ot=gn;Ot.detail&&Tr(Ot.detail)},Ft=gn=>{const Ot=gn.detail;Xn(Ot??pt.current??void 0)},Dt=gn=>{const Ot=gn.detail;Ot&&is(Ot)},rn=gn=>{const Ot=gn.detail,kn=typeof Ot=="string"?Ot:Ot?.layout,_n=typeof Ot=="string"?pt.current:Ot?.sessionId;kn!=="horizontal"&&kn!=="vertical"&&kn!=="grid"||Ye(mn=>mn.map(yn=>yn.sessionIds.includes(_n??"")?{...yn,layout:kn}:yn))},on=gn=>{const kn=gn.detail?.direction;if(kn!=="prev"&&kn!=="next")return;const _n=Br.current;if(_n.length<=1)return;const mn=pt.current,yn=mn?_n.findIndex(hs=>hs.id===mn):-1,zs=((yn>=0?yn:0)+(kn==="next"?1:-1)+_n.length)%_n.length,mi=_n[zs]?.id;mi&&mi!==mn&&Ss(mi)},ln=gn=>{Lr(gn.detail)},Vn=gn=>{Dr(gn.detail)},sr=gn=>{const Ot=gn;!Ot.detail?.sessionId||!Ot.detail?.name||As(Ot.detail.sessionId,Ot.detail.name)},ar=gn=>{const Ot=gn;Ot.detail?.sessionId&&Gt(Ot.detail.sessionId)},lr=gn=>{const Ot=gn;Ot.detail?.sessionIds&&Sn(Ot.detail.sessionIds)},Wt=gn=>{const Ot=gn.detail;!Ot?.workspaceId||!Array.isArray(Ot.sessionIds)||Ye(kn=>sH(kn,Ot.workspaceId,Ot.sessionIds))},Rn=gn=>{const Ot=gn.detail;!Ot?.workspaceId||typeof Ot.name!="string"||Ye(kn=>iH(kn,Ot.workspaceId,Ot.name))},pn=gn=>{const Ot=gn.detail;!Ot?.primaryId||!Ot.secondaryId||Ot.primaryId===Ot.secondaryId||(Ye(kn=>cb(kn,Ot.primaryId,Ot.secondaryId)),Nt(Ot.primaryId,{preserveMobileKeyboard:!1}))};return window.addEventListener("new-terminal-session",ie),window.addEventListener("switch-terminal-session",Se),window.addEventListener("focus-active-terminal-session",Be),window.addEventListener("open-terminal-split-chooser",it),window.addEventListener("close-terminal-split",Ft),window.addEventListener("remove-terminal-split-pane",Dt),window.addEventListener("set-terminal-split-direction",rn),window.addEventListener("cycle-terminal-session",on),window.addEventListener("close-terminal-session",ln),window.addEventListener("close-terminal-session-by-backend",Vn),window.addEventListener("rename-terminal-session",sr),window.addEventListener("reset-terminal-session-name",ar),window.addEventListener("reorder-terminal-session",lr),window.addEventListener("reorder-terminal-split-workspace",Wt),window.addEventListener("rename-terminal-split-workspace",Rn),window.addEventListener("combine-terminal-split-sessions",pn),()=>{window.removeEventListener("new-terminal-session",ie),window.removeEventListener("switch-terminal-session",Se),window.removeEventListener("focus-active-terminal-session",Be),window.removeEventListener("open-terminal-split-chooser",it),window.removeEventListener("close-terminal-split",Ft),window.removeEventListener("remove-terminal-split-pane",Dt),window.removeEventListener("set-terminal-split-direction",rn),window.removeEventListener("cycle-terminal-session",on),window.removeEventListener("close-terminal-session",ln),window.removeEventListener("close-terminal-session-by-backend",Vn),window.removeEventListener("rename-terminal-session",sr),window.removeEventListener("reset-terminal-session-name",ar),window.removeEventListener("reorder-terminal-session",lr),window.removeEventListener("reorder-terminal-split-workspace",Wt),window.removeEventListener("rename-terminal-split-workspace",Rn),window.removeEventListener("combine-terminal-split-sessions",pn)}},[Nt,bn,Ss,Tr,Xn,is,Lr,Dr,As,Gt,Sn]),x.useEffect(()=>{if(!Ar||Le)return;const ie=Se=>{if(!(Se.ctrlKey||Se.metaKey)||!Se.shiftKey)return;if(Ar.layout==="horizontal"?Se.key==="ArrowLeft"||Se.key==="ArrowRight":Ar.layout==="vertical"?Se.key==="ArrowUp"||Se.key==="ArrowDown":Se.key.startsWith("Arrow")){Se.preventDefault(),Se.stopPropagation();const it=Ar.sessionIds.indexOf(pt.current??""),Ft=Se.key==="ArrowLeft"||Se.key==="ArrowUp"?-1:1,Dt=(Math.max(0,it)+Ft+Ar.sessionIds.length)%Ar.sessionIds.length,rn=Ar.sessionIds[Dt];if(!rn)return;Nt(rn);return}Se.key==="Backspace"&&(Se.preventDefault(),Se.stopPropagation(),Xn(pt.current??void 0))};return window.addEventListener("keydown",ie,!0),()=>window.removeEventListener("keydown",ie,!0)},[Nt,Ar,Xn,Le]);const Kr=ie=>{const Se=ns.getState().sessions.get(ie.id);return zc(ie,Se?.activeProgram??null,Se?.cwd??null,void 0,Se?.shellTitle??null,Se?.promptState??null)},Jr=(ie,Se={})=>{const Be=ie.id===F,it=mr.has(ie.id)&&!Se.hidden,Ft=u&&GQ({sessionId:ie.id,foregroundSessionId:or,visibleSessionIds:mr,deferredViewportSessionIds:Ce}),Dt=UQ({sessionId:ie.id,foregroundSessionId:or,foregroundReady:ur})&&u,rn=YQ({sessionId:ie.id,foregroundSessionId:or,requestToken:W.token,foregroundCompletedToken:re})&&u,on=ie.id===or||Ce.has(ie.id)?0:wn.get(ie.id)??Wm;return o.jsx("div",{className:`relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden ${Se.hidden?"invisible pointer-events-none":""}`,style:Se.containerStyle,"aria-hidden":Se.hidden||void 0,onPointerDown:()=>{Be||Nt(ie.id)},onWheelCapture:()=>{X$(Be,()=>Nt(ie.id))},children:o.jsx("div",{className:"min-h-0 flex-1 app-chrome-bg",children:Ft&&o.jsx(Q$,{sessionId:ie.id,mode:ie.mode,tmuxSessionName:ie.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:n,isActive:Be,focusSuspended:T!==null,deferCursorUntilPositioned:T===ie.id||ie.mode==="tmux"&&!q.has(ie.id),isLayoutVisible:it,initialConnectEnabled:Dt,resumeRequestEnabled:rn,suppressKeyboard:Se.suppressKeyboard,keyboardPortalTarget:Se.keyboardPortalTarget,sharedMobileKeyboardLayout:Se.sharedMobileKeyboardLayout,suppressPageFlipRefresh:Se.suppressPageFlipRefresh,focusRequestToken:Ue?.sessionId===ie.id?Ue.token:0,resumeRequestToken:W.token,resumeRequestReason:W.reason,forceResumeReconnect:W.forceForegroundReconnect&&ie.id===or,resumeRequestDelayMs:ie.id===or?0:Se.hidden?Wm:wn.get(ie.id)??Wm,initialConnectDelayMs:on,onStreamReadyChange:fs,onStreamConnected:li,onViewportReadyChange:Ct,onContentReadyChange:Kt,onKeyboardVisibilityChange:gt,showDebug:r,onStatusChange:Be?v:void 0})})},ie.id)};return o.jsxs("div",{className:"relative h-full flex flex-col",children:[dn&&o.jsx("section",{className:"fixed inset-x-3 top-[calc(var(--safe-top-inset)+0.75rem)] z-toast mx-auto max-w-lg rounded-2xl border border-warning/30 bg-surface-elevated px-4 py-3.5 shadow-[0_20px_60px_var(--app-shadow-strong)]",role:"alert","aria-live":"assertive",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-warning/15 text-warning",children:o.jsx(o1,{size:18})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h2",{className:"text-[13px] font-semibold text-foreground",children:C("tab.tmuxRecoveryTitle",{count:dn.sessions.length})}),o.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:C("tab.tmuxRecoveryHint")}),o.jsx("p",{className:"mt-1.5 truncate text-[10px] text-foreground/70",children:dn.sessions.map(ie=>ie.name).join(" · ")}),at&&o.jsx("p",{className:"mt-2 text-[10px] text-destructive",children:at}),o.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[o.jsxs("button",{type:"button",disabled:He!==null,onClick:()=>{In()},className:"inline-flex min-h-9 items-center gap-1.5 rounded-lg bg-primary px-3 text-[11px] font-medium text-primary-foreground transition active:opacity-80 disabled:opacity-50",children:[o.jsx(F8,{size:13,className:He==="restore"?"animate-spin":""}),C(He==="restore"?"tab.tmuxRecoveryRestoring":"tab.tmuxRecoveryRestoreAll")]}),o.jsx("button",{type:"button",disabled:He!==null,onClick:()=>{kt()},className:"inline-flex min-h-9 items-center rounded-lg px-3 text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground disabled:opacity-50",children:C("tab.tmuxRecoveryDismiss")})]})]})]})}),o.jsx("div",{className:"flex-1 overflow-hidden",children:o.jsx(ep,{onSwiper:ie=>{Ze.current=ie,ie.allowTouchMove=hn.length>1&&!hr&&!me,We("[swiper:on-swiper]",{allowTouchMove:ie.allowTouchMove}),requestAnimationFrame(()=>bt("on-swiper"))},onSlideChange:Pt,onTouchStart:(ie,Se)=>{const Be=p6(Se),it=Be==="touch"||Be==="pen"||Be==="unknown";R("[swipe:touch-start]",{pointerType:Be,allowed:it}),We("[swiper:touch-start]",{pointerType:Be,allowed:it}),it&&(pe(),It.current=!0)},onTouchEnd:(ie,Se)=>{const Be=p6(Se),it=Be==="touch"||Be==="pen"||Be==="unknown";R("[swipe:touch-end]",{pointerType:Be,allowed:it}),We("[swiper:touch-end]",{pointerType:Be,allowed:it}),it&&Pe("touch-end")},onTransitionEnd:()=>{const ie=Ze.current;if(It.current&&ie&&!gH(ie,Rt.current)){We("[swiper:transition-end-deferred]");return}pe(),It.current=!1,We("[swiper:transition-end]")},initialSlide:Math.max(0,ut),speed:Y2,slidesPerView:1,resistanceRatio:.82,threshold:8,longSwipesRatio:.2,touchAngle:45,touchStartPreventDefault:!1,simulateTouch:!1,noSwiping:!0,noSwipingSelector:"[data-mobile-keyboard='true']",className:"terminal-session-swiper h-full",children:hn.map(ie=>{const Se=ie.workspace,Be=!!Se&&ie.sessions.length>=2,it=Le?Qe?"horizontal":"vertical":Se?.layout??"horizontal",Ft=it==="vertical",Dt=Se?.ratios.length===ie.sessions.length?Se.ratios:kc(ie.sessions.length),rn=mt?ie.sessions.findIndex(kn=>kn.id===mt):-1,on=Le&&mt?ie.sessions.some(kn=>kn.id===mt):!1,ln=ie.sessions.some(kn=>kn.id===F)?F:ie.sessions[0]?.id,Vn=Dt.flatMap((kn,_n)=>[on&&_n!==rn?"0px":`minmax(0, ${kn}fr)`,..._n<Dt.length-1?[on?"0px":"1px"]:[]]).join(" "),{columns:sr,rows:ar}=iT(ie.sessions.length),lr=id(Se?.gridColumnRatios,sr),Wt=id(Se?.gridRowRatios,ar),Rn=lr.slice(0,-1).map((kn,_n)=>lr.slice(0,_n+1).reduce((mn,yn)=>mn+yn,0)),pn=Wt.slice(0,-1).map((kn,_n)=>Wt.slice(0,_n+1).reduce((mn,yn)=>mn+yn,0)),gn=ie.sessions.length%sr,Ot={...it==="grid"?{gridTemplateColumns:lr.map(kn=>`minmax(0, ${kn}fr)`).join(" "),gridTemplateRows:Wt.map(kn=>`minmax(0, ${kn}fr)`).join(" "),gap:"1px"}:Ft?{gridTemplateRows:Vn}:{gridTemplateColumns:Vn},...Le?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:{}};return o.jsx(ud,{className:"h-full",children:o.jsx("div",{className:"h-full min-w-0","data-pinned-right-sidebar-inset":Kn.get(ie.key)??0,style:{paddingRight:Kn.get(ie.key)??0},children:Be?o.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col bg-[var(--chrome-bg)]",style:Le?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,children:[o.jsxs("div",{"data-split-container":"true",className:"relative grid min-h-0 min-w-0 flex-1 overflow-hidden",style:Ot,children:[ie.sessions.map((kn,_n)=>o.jsxs(I.Fragment,{children:[Jr(kn,{suppressKeyboard:Le&&kn.id!==ln,keyboardPortalTarget:Le?Mt:null,sharedMobileKeyboardLayout:Le,suppressPageFlipRefresh:!0,hidden:on&&rn!==_n,containerStyle:it==="grid"&&gn>0&&_n===ie.sessions.length-1?{gridColumn:`span ${sr-gn+1}`}:void 0}),it!=="grid"&&_n<ie.sessions.length-1&&Se&&o.jsx("button",{type:"button",className:`swiper-no-swiping relative z-20 touch-none select-none bg-[var(--border-strong)] transition-colors hover:bg-primary active:bg-primary ${Ft?"cursor-row-resize":"cursor-col-resize"} ${on?"invisible pointer-events-none":""}`,onPointerDownCapture:mn=>{const yn=mn.currentTarget.closest('[data-split-container="true"]');yn instanceof HTMLDivElement&&Fr(mn,yn,Ft,Se.id,_n)},onDoubleClick:mn=>{Le||(mn.preventDefault(),mn.stopPropagation(),Ye(yn=>yn.map(xn=>xn.id===Se.id?{...xn,ratios:kc(xn.sessionIds.length)}:xn)))},onContextMenu:mn=>{Le&&mn.preventDefault()},"aria-label":C("tab.split"),children:o.jsx("span",{"aria-hidden":"true","data-split-divider-hitarea":"true",className:`absolute ${Ft?"inset-x-0":"inset-y-0"}`,style:Ft?{top:-12,bottom:-12}:{left:-12,right:-12}})})]},kn.id)),it==="grid"&&Se&&Rn.map((kn,_n)=>o.jsx("button",{type:"button","data-split-grid-column-divider":_n,className:"swiper-no-swiping absolute top-0 z-20 w-px -translate-x-1/2 touch-none select-none cursor-col-resize bg-[var(--border-strong)] transition-colors hover:bg-primary active:bg-primary",style:{left:`${kn*100}%`,bottom:gn===0||_n<gn-1?0:`${(Wt.at(-1)??0)*100}%`},onPointerDownCapture:mn=>{const yn=mn.currentTarget.closest('[data-split-container="true"]');yn instanceof HTMLDivElement&&Fr(mn,yn,!1,Se.id,_n,"grid-columns",sr)},onDoubleClick:mn=>{mn.preventDefault(),mn.stopPropagation(),Ye(yn=>yn.map(xn=>xn.id===Se.id?{...xn,gridColumnRatios:kc(sr)}:xn))},"aria-label":C("tab.split"),children:o.jsx("span",{"aria-hidden":"true","data-split-divider-hitarea":"true",className:"absolute inset-y-0",style:{left:-12,right:-12}})},`grid-column-divider:${_n}`)),it==="grid"&&Se&&pn.map((kn,_n)=>o.jsx("button",{type:"button","data-split-grid-row-divider":_n,className:"swiper-no-swiping absolute inset-x-0 z-20 h-px -translate-y-1/2 touch-none select-none cursor-row-resize bg-[var(--border-strong)] transition-colors hover:bg-primary active:bg-primary",style:{top:`${kn*100}%`},onPointerDownCapture:mn=>{const yn=mn.currentTarget.closest('[data-split-container="true"]');yn instanceof HTMLDivElement&&Fr(mn,yn,!0,Se.id,_n,"grid-rows",ar)},onDoubleClick:mn=>{mn.preventDefault(),mn.stopPropagation(),Ye(yn=>yn.map(xn=>xn.id===Se.id?{...xn,gridRowRatios:kc(ar)}:xn))},"aria-label":C("tab.split"),children:o.jsx("span",{"aria-hidden":"true","data-split-divider-hitarea":"true",className:"absolute inset-x-0",style:{top:-12,bottom:-12}})},`grid-row-divider:${_n}`))]}),Le&&o.jsx("div",{ref:cn,className:"relative shrink-0 app-chrome-bg","data-split-keyboard-host":"true"})]}):Jr(ie.sessions[0])})},ie.key)})})}),me&&F&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop-soft)] backdrop-blur-sm",onClick:()=>se(!1),"aria-label":C("common.close")}),o.jsxs("section",{className:"fixed inset-x-3 bottom-3 z-modal-panel mx-auto max-h-[min(78svh,620px)] max-w-md overflow-hidden rounded-2xl border border-border/20 bg-surface shadow-[0_24px_70px_var(--app-shadow-strong)] sm:bottom-auto sm:top-1/2 sm:-translate-y-1/2",style:{paddingBottom:"var(--safe-bottom-inset)"},role:"dialog","aria-modal":"true","aria-label":C("tab.splitTitle"),children:[o.jsxs("header",{className:"flex items-start gap-3 border-b border-border/20 px-4 py-3.5",children:[o.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:o.jsx(S0,{size:17})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h2",{className:"text-[14px] font-semibold text-foreground",children:C("tab.splitTitle")}),o.jsx("p",{className:"mt-0.5 text-[11px] leading-relaxed text-muted-foreground",children:C("tab.splitExistingHint")})]}),o.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground",onClick:()=>se(!1),"aria-label":C("common.close"),children:o.jsx(ds,{size:16})})]}),o.jsxs("div",{className:"max-h-[calc(min(78svh,620px)-72px)] overflow-y-auto overscroll-contain p-2",children:[o.jsxs("button",{type:"button",disabled:Ie,onClick:()=>{Rr()},className:"flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition hover:bg-surface-2 active:bg-surface-elevated disabled:opacity-60",children:[o.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:o.jsx(ya,{size:17})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block text-[13px] font-medium text-foreground",children:C("tab.splitNew")}),o.jsx("span",{className:"mt-0.5 block text-[11px] text-muted-foreground",children:C("tab.splitNewHint")})]})]}),lt.filter(ie=>ie.id!==Ar?.id).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:C("tab.splitExistingGroups")}),lt.filter(ie=>ie.id!==Ar?.id).map((ie,Se)=>{const Be=ie.sessionIds.flatMap(Dt=>{const rn=M.find(on=>on.id===Dt);return rn?[rn]:[]});if(Be.length<2)return null;const it=ie.name||`${C("tab.splitWorkspace")} ${Se+1}`,Ft=Be.map(Dt=>Kr(Dt).primary).join(" · ");return o.jsxs("button",{type:"button",onClick:()=>Wr(Be[0].id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[o.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:o.jsx(S0,{size:15})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium text-foreground",children:it}),o.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[9px] font-medium text-primary",children:C("tab.splitOccupied")})]}),o.jsxs("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:[C("tab.sessionCount",{count:Be.length})," · ",Ft]})]}),o.jsx(Fa,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},ie.id)})]}),o.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:C("tab.splitAvailableSessions")}),M.filter(ie=>!lt.some(Se=>Se.sessionIds.includes(ie.id))&&ie.id!==F).length===0&&lt.filter(ie=>ie.id!==Ar?.id).length===0?o.jsx("p",{className:"px-3 py-4 text-[12px] text-muted-foreground",children:C("tab.splitNoOtherSessions")}):M.filter(ie=>!lt.some(Se=>Se.sessionIds.includes(ie.id))&&ie.id!==F).map(ie=>{const Se=wr.get(ie.id)??null,Be=Kr(ie);return o.jsxs("button",{type:"button",onClick:()=>Wr(ie.id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[o.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground",children:Se?o.jsx(Cu,{size:15}):o.jsx(S0,{size:15})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:Be.primary}),o.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:Se?Cc(Se)??Se:ie.name})]}),o.jsx(Fa,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},ie.id)})]})]})]}),_e&&o.jsx("div",{className:"fixed inset-x-3 bottom-4 z-toast mx-auto max-w-md rounded-xl border border-border/20 bg-surface-elevated px-4 py-3 text-center text-[12px] text-foreground shadow-lg",children:_e})]})},SH={sm:"h-4 w-7",md:"h-6 w-10"},AH={sm:"h-3 w-3",md:"h-5 w-5"},TH={sm:"translate-x-3",md:"translate-x-4"};function Uc({checked:e,disabled:t=!1,size:n="md",className:r=""}){return o.jsx("span",{"aria-hidden":"true",className:`inline-flex shrink-0 items-center rounded-full transition ${SH[n]} ${e?"bg-primary":"bg-surface-elevated"} ${t?"opacity-50":""} ${r}`,children:o.jsx("span",{className:`mx-0.5 inline-block rounded-full bg-[var(--background)] shadow transition ${AH[n]} ${e?TH[n]:""}`})})}function ga(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var CH=typeof Symbol=="function"&&Symbol.observable||"@@observable",g6=CH,x6=()=>Math.random().toString(36).substring(7).split("").join("."),kH={INIT:`@@redux/INIT${x6()}`,REPLACE:`@@redux/REPLACE${x6()}`},b6=kH;function _H(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function uT(e,t,n){if(typeof e!="function")throw new Error(ga(2));if(typeof t=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(ga(0));if(typeof t=="function"&&typeof n>"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(ga(1));return n(uT)(e,t)}let r=e,s=t,i=new Map,a=i,c=0,u=!1;function f(){a===i&&(a=new Map,i.forEach((C,L)=>{a.set(L,C)}))}function p(){if(u)throw new Error(ga(3));return s}function g(C){if(typeof C!="function")throw new Error(ga(4));if(u)throw new Error(ga(5));let L=!0;f();const R=c++;return a.set(R,C),function(){if(L){if(u)throw new Error(ga(6));L=!1,f(),a.delete(R),i=null}}}function y(C){if(!_H(C))throw new Error(ga(7));if(typeof C.type>"u")throw new Error(ga(8));if(typeof C.type!="string")throw new Error(ga(17));if(u)throw new Error(ga(9));try{u=!0,s=r(s,C)}finally{u=!1}return(i=a).forEach(R=>{R()}),C}function v(C){if(typeof C!="function")throw new Error(ga(10));r=C,y({type:b6.REPLACE})}function S(){const C=g;return{subscribe(L){if(typeof L!="object"||L===null)throw new Error(ga(11));function R(){const B=L;B.next&&B.next(p())}return R(),{unsubscribe:C(R)}},[g6](){return this}}}return y({type:b6.INIT}),{dispatch:y,subscribe:g,getState:p,replaceReducer:v,[g6]:S}}function y6(e,t){return function(...n){return t(e.apply(this,n))}}function v6(e,t){if(typeof e=="function")return y6(e,t);if(typeof e!="object"||e===null)throw new Error(ga(16));const n={};for(const r in e){const s=e[r];typeof s=="function"&&(n[r]=y6(s,t))}return n}function dT(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,n)=>(...r)=>t(n(...r)))}function LH(...e){return t=>(n,r)=>{const s=t(n,r);let i=()=>{throw new Error(ga(15))};const a={getState:s.getState,dispatch:(u,...f)=>i(u,...f)},c=e.map(u=>u(a));return i=dT(...c)(s.dispatch),{...s,dispatch:i}}}var db={exports:{}},fb={};var w6;function EH(){if(w6)return fb;w6=1;var e=Kg();function t(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:t,r=e.useSyncExternalStore,s=e.useRef,i=e.useEffect,a=e.useMemo,c=e.useDebugValue;return fb.useSyncExternalStoreWithSelector=function(u,f,p,g,y){var v=s(null);if(v.current===null){var S={hasValue:!1,value:null};v.current=S}else S=v.current;v=a(function(){function C(F){if(!L){if(L=!0,R=F,F=g(F),y!==void 0&&S.hasValue){var N=S.value;if(y(N,F))return M=N}return M=F}if(N=M,n(R,F))return N;var T=g(F);return y!==void 0&&y(N,T)?(R=F,N):(R=F,M=T)}var L=!1,R,M,B=p===void 0?null:p;return[function(){return C(f())},B===null?void 0:function(){return C(B())}]},[f,p,g,y]);var A=r(u,v[0],v[1]);return i(function(){S.hasValue=!0,S.value=A},[A]),c(A),A},fb}var S6;function IH(){return S6||(S6=1,db.exports=EH()),db.exports}IH();var RH=x.version.startsWith("19"),NH=Symbol.for(RH?"react.transitional.element":"react.element"),MH=Symbol.for("react.portal"),DH=Symbol.for("react.fragment"),jH=Symbol.for("react.strict_mode"),PH=Symbol.for("react.profiler"),BH=Symbol.for("react.consumer"),FH=Symbol.for("react.context"),fT=Symbol.for("react.forward_ref"),OH=Symbol.for("react.suspense"),QH=Symbol.for("react.suspense_list"),Av=Symbol.for("react.memo"),$H=Symbol.for("react.lazy"),HH=fT,zH=Av;function UH(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case NH:switch(e=e.type,e){case DH:case PH:case jH:case OH:case QH:return e;default:switch(e=e&&e.$$typeof,e){case FH:case fT:case $H:case Av:return e;case BH:return e;default:return t}}case MH:return t}}}function GH(e){return UH(e)===Av}function WH(e,t,n,r,{areStatesEqual:s,areOwnPropsEqual:i,areStatePropsEqual:a}){let c=!1,u,f,p,g,y;function v(R,M){return u=R,f=M,p=e(u,f),g=t(r,f),y=n(p,g,f),c=!0,y}function S(){return p=e(u,f),t.dependsOnOwnProps&&(g=t(r,f)),y=n(p,g,f),y}function A(){return e.dependsOnOwnProps&&(p=e(u,f)),t.dependsOnOwnProps&&(g=t(r,f)),y=n(p,g,f),y}function C(){const R=e(u,f),M=!a(R,p);return p=R,M&&(y=n(p,g,f)),y}function L(R,M){const B=!i(M,f),F=!s(R,u,M,f);return u=R,f=M,B&&F?S():B?A():F?C():y}return function(M,B){return c?L(M,B):v(M,B)}}function VH(e,{initMapStateToProps:t,initMapDispatchToProps:n,initMergeProps:r,...s}){const i=t(e,s),a=n(e,s),c=r(e,s);return WH(i,a,c,e,s)}function qH(e,t){const n={};for(const r in e){const s=e[r];typeof s=="function"&&(n[r]=(...i)=>t(s(...i)))}return n}function J2(e){return function(n){const r=e(n);function s(){return r}return s.dependsOnOwnProps=!1,s}}function A6(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function hT(e,t){return function(r,{displayName:s}){const i=function(c,u){return i.dependsOnOwnProps?i.mapToProps(c,u):i.mapToProps(c,void 0)};return i.dependsOnOwnProps=!0,i.mapToProps=function(c,u){i.mapToProps=e,i.dependsOnOwnProps=A6(e);let f=i(c,u);return typeof f=="function"&&(i.mapToProps=f,i.dependsOnOwnProps=A6(f),f=i(c,u)),f},i}}function Tv(e,t){return(n,r)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${r.wrappedComponentName}.`)}}function KH(e){return e&&typeof e=="object"?J2(t=>qH(e,t)):e?typeof e=="function"?hT(e):Tv(e,"mapDispatchToProps"):J2(t=>({dispatch:t}))}function YH(e){return e?typeof e=="function"?hT(e):Tv(e,"mapStateToProps"):J2(()=>({}))}function XH(e,t,n){return{...n,...e,...t}}function ZH(e){return function(n,{displayName:r,areMergedPropsEqual:s}){let i=!1,a;return function(u,f,p){const g=e(u,f,p);return i?s(g,a)||(a=g):(i=!0,a=g),a}}}function JH(e){return e?typeof e=="function"?ZH(e):Tv(e,"mergeProps"):()=>XH}function ez(e){e()}function tz(){let e=null,t=null;return{clear(){e=null,t=null},notify(){ez(()=>{let n=e;for(;n;)n.callback(),n=n.next})},get(){const n=[];let r=e;for(;r;)n.push(r),r=r.next;return n},subscribe(n){let r=!0;const s=t={callback:n,next:null,prev:t};return s.prev?s.prev.next=s:e=s,function(){!r||e===null||(r=!1,s.next?s.next.prev=s.prev:t=s.prev,s.prev?s.prev.next=s.next:e=s.next)}}}}var T6={notify(){},get:()=>[]};function pT(e,t){let n,r=T6,s=0,i=!1;function a(A){p();const C=r.subscribe(A);let L=!1;return()=>{L||(L=!0,C(),g())}}function c(){r.notify()}function u(){S.onStateChange&&S.onStateChange()}function f(){return i}function p(){s++,n||(n=t?t.addNestedSub(u):e.subscribe(u),r=tz())}function g(){s--,n&&s===0&&(n(),n=void 0,r.clear(),r=T6)}function y(){i||(i=!0,p())}function v(){i&&(i=!1,g())}const S={addNestedSub:a,notifyNestedSubs:c,handleChangeWrapper:u,isSubscribed:f,trySubscribe:y,tryUnsubscribe:v,getListeners:()=>r};return S}var nz=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",rz=nz(),sz=()=>typeof navigator<"u"&&navigator.product==="ReactNative",iz=sz(),oz=()=>rz||iz?x.useLayoutEffect:x.useEffect,wg=oz();function C6(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function hb(e,t){if(C6(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s=0;s<n.length;s++)if(!Object.prototype.hasOwnProperty.call(t,n[s])||!C6(e[n[s]],t[n[s]]))return!1;return!0}var az={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},lz={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},cz={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},mT={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},uz={[HH]:cz,[zH]:mT};function k6(e){return GH(e)?mT:uz[e.$$typeof]||az}var dz=Object.defineProperty,fz=Object.getOwnPropertyNames,_6=Object.getOwnPropertySymbols,hz=Object.getOwnPropertyDescriptor,pz=Object.getPrototypeOf,L6=Object.prototype;function ey(e,t){if(typeof t!="string"){if(L6){const i=pz(t);i&&i!==L6&&ey(e,i)}let n=fz(t);_6&&(n=n.concat(_6(t)));const r=k6(e),s=k6(t);for(let i=0;i<n.length;++i){const a=n[i];if(!lz[a]&&!(s&&s[a])&&!(r&&r[a])){const c=hz(t,a);try{dz(e,a,c)}catch{}}}}return e}var mz=Symbol.for("react-redux-context"),gz=typeof globalThis<"u"?globalThis:{};function xz(){if(!x.createContext)return{};const e=gz[mz]??=new Map;let t=e.get(x.createContext);return t||(t=x.createContext(null),e.set(x.createContext,t)),t}var gT=xz(),bz=[null,null];function yz(e,t,n){wg(()=>e(...t),n)}function vz(e,t,n,r,s,i){e.current=r,n.current=!1,s.current&&(s.current=null,i())}function wz(e,t,n,r,s,i,a,c,u,f,p){if(!e)return()=>{};let g=!1,y=null;const v=()=>{if(g||!c.current)return;const A=t.getState();let C,L;try{C=r(A,s.current)}catch(R){L=R,y=R}L||(y=null),C===i.current?a.current||f():(i.current=C,u.current=C,a.current=!0,p())};return n.onStateChange=v,n.trySubscribe(),v(),()=>{if(g=!0,n.tryUnsubscribe(),n.onStateChange=null,y)throw y}}function Sz(e,t){return e===t}function Az(e,t,n,{pure:r,areStatesEqual:s=Sz,areOwnPropsEqual:i=hb,areStatePropsEqual:a=hb,areMergedPropsEqual:c=hb,forwardRef:u=!1,context:f=gT}={}){const p=f,g=YH(e),y=KH(t),v=JH(n),S=!!e;return C=>{const L=C.displayName||C.name||"Component",R=`Connect(${L})`,M={shouldHandleStateChanges:S,displayName:R,wrappedComponentName:L,WrappedComponent:C,initMapStateToProps:g,initMapDispatchToProps:y,initMergeProps:v,areStatesEqual:s,areStatePropsEqual:a,areOwnPropsEqual:i,areMergedPropsEqual:c};function B(T){const[$,O,Y]=x.useMemo(()=>{const{reactReduxForwardedRef:_e,...he}=T;return[T.context,_e,he]},[T]),W=x.useMemo(()=>{let _e=p;return $?.Consumer,_e},[$,p]),ye=x.useContext(W),ce=!!T.store&&!!T.store.getState&&!!T.store.dispatch,ve=!!ye&&!!ye.store,re=ce?T.store:ye.store,ke=ve?ye.getServerState:re.getState,X=x.useMemo(()=>VH(re.dispatch,M),[re]),[V,q]=x.useMemo(()=>{if(!S)return bz;const _e=pT(re,ce?void 0:ye.subscription),he=_e.notifyNestedSubs.bind(_e);return[_e,he]},[re,ce,ye]),ue=x.useMemo(()=>ce?ye:{...ye,subscription:V},[ce,ye,V]),Ce=x.useRef(void 0),ee=x.useRef(Y),Ee=x.useRef(void 0),Ze=x.useRef(!1),$e=x.useRef(!1),Ue=x.useRef(void 0);wg(()=>($e.current=!0,()=>{$e.current=!1}),[]);const ne=x.useMemo(()=>()=>Ee.current&&Y===ee.current?Ee.current:X(re.getState(),Y),[re,Y]),lt=x.useMemo(()=>he=>V?wz(S,re,V,X,ee,Ce,Ze,$e,Ee,q,he):()=>{},[V]);yz(vz,[ee,Ce,Ze,Y,Ee,q]);let Ye;try{Ye=x.useSyncExternalStore(lt,ne,ke?()=>X(ke(),Y):ne)}catch(_e){throw Ue.current&&(_e.message+=`
80
80
  The error may be correlated with this previous error:
81
81
  ${Ue.current.stack}
82
82
 
@@ -180,12 +180,12 @@ ${q.desc}`:""}`,"aria-pressed":C===q.key,onPointerEnter:()=>A(q.key),onPointerLe
180
180
 
181
181
  `;return`${e}${r}${n}`}function ste(e,t){const n=e.trim();return n?t?`${n}\r`:/\s$/.test(e)?e:`${n} `:""}const Ry="termdock:right-sidebar:html-view-mode-by-file:v1";function ite(e){return e==="preview"||e==="source"}function HC(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(ite)}function zC(e,t){if(!t)return null;const n=e&&!t.startsWith("/")?`${e}/${t}`:t;return e?`${e}::${n}`:n}function QS(e,t){const n=zC(e,t);return n?Gr(Ry,HC)?.[n]??"source":"source"}function ote(e,t,n){const r=zC(e,t);if(!r)return;const s=Gr(Ry,HC)??{};Wn(Ry,{...s,[r]:n})}function Hb(e){const t=Number.isFinite(e)&&e>0?Math.floor(e):0,n=Math.floor(t/3600),r=Math.floor(t%3600/60),s=t%60,i=String(r).padStart(2,"0"),a=String(s).padStart(2,"0");return n>0?`${n}:${i}:${a}`:`${i}:${a}`}function ate(e,t,n){return!Number.isFinite(n)||n<=0||!t.width?0:Math.min(1,Math.max(0,(e-t.left)/t.width))*n}const lte=350,cte=12,ute=90;function dte({url:e,onLoadError:t}){const{t:n}=ir(),r=x.useRef(null),s=x.useRef(null),i=x.useRef(null),a=x.useRef(null),c=x.useRef(!1),u=x.useRef(null),f=x.useRef(null),p=x.useRef(0),g=x.useRef(!1),y=x.useRef(!1),v=x.useRef(!1),S=x.useRef(null),A=x.useRef(null),C=x.useRef(!1),L=x.useRef(1),R=x.useRef(!1),[M,B]=x.useState(0),[F,N]=x.useState(0),[T,$]=x.useState(!1),[O,Y]=x.useState(!1),[W,ye]=x.useState(null),[ce,ve]=x.useState(!1),[re,ke]=x.useState(0),[X,V]=x.useState(!1),[q,ue]=x.useState({width:0,height:0}),Ce=x.useCallback(()=>{S.current!==null&&(clearTimeout(S.current),S.current=null)},[]),ee=x.useCallback(()=>{if(Ce(),A.current=null,!C.current)return!1;const Le=i.current;return Le&&(Le.playbackRate=L.current),C.current=!1,ve(!1),!0},[Ce]);x.useEffect(()=>()=>{u.current!==null&&cancelAnimationFrame(u.current),f.current!==null&&clearTimeout(f.current),Ce();const Le=i.current;Le&&C.current&&(Le.playbackRate=L.current)},[Ce]),x.useEffect(()=>{const Le=s.current;if(!Le||typeof ResizeObserver>"u")return;const fe=new ResizeObserver(([Qe])=>{Qe&&ue({width:Qe.contentRect.width,height:Qe.contentRect.height})});return fe.observe(Le),()=>fe.disconnect()},[]),x.useEffect(()=>{const Le=()=>V(document.fullscreenElement===r.current);return document.addEventListener("fullscreenchange",Le),()=>document.removeEventListener("fullscreenchange",Le)},[]);const Ee=x.useCallback((Le,fe=!1)=>{const Qe=i.current;if(!Qe)return!1;const ft=Number.isFinite(Qe.duration)?Qe.duration:Le,Mt=Math.min(Math.max(Le,0),ft);if(N(Mt),Math.abs(Qe.currentTime-Mt)<1/120)return!1;const cn=Qe.fastSeek;return fe&&typeof cn=="function"?cn.call(Qe,Mt):Qe.currentTime=Mt,!0},[]),Ze=x.useCallback(()=>{u.current===null&&(u.current=requestAnimationFrame(()=>{u.current=null;const Le=i.current;if(!Le||!g.current||y.current||Le.seeking)return;const fe=v.current;v.current=!1,y.current=Ee(p.current,!fe)}))},[Ee]),$e=x.useCallback(Le=>{const fe=a.current,Qe=i.current;if(!fe||!Qe)return;const ft=fe.getBoundingClientRect(),Mt=ate(Le,ft,Qe.duration);p.current=Mt,ye(Mt),v.current=!1,Ze(),f.current!==null&&clearTimeout(f.current),f.current=setTimeout(()=>{f.current=null,v.current=!0,Ze()},ute)},[Ze]),Ue=x.useCallback(()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),f.current!==null&&(clearTimeout(f.current),f.current=null),v.current=!1,y.current=!1,Ee(p.current)},[Ee]),ne=x.useCallback(Le=>{const fe=i.current;if(!(!fe||!Number.isFinite(fe.duration)||fe.duration<=0)){c.current=!fe.paused,fe.pause(),g.current=!0,Y(!0);try{Le.currentTarget.setPointerCapture(Le.pointerId)}catch{}$e(Le.clientX)}},[$e]),lt=x.useCallback(()=>{g.current=!1,Ue(),Y(!1),ye(null);const Le=i.current;Le&&c.current&&!Le.ended&&Le.play().catch(()=>{}),c.current=!1},[Ue]),Ye=x.useCallback(()=>{const Le=i.current;if(Le){if(R.current){R.current=!1;return}Le.paused?Le.play().catch(()=>{}):Le.pause()}},[]),me=x.useCallback(Le=>{const fe=i.current;!fe||fe.paused||Le.button!==0||(Ce(),A.current={id:Le.pointerId,x:Le.clientX,y:Le.clientY},S.current=setTimeout(()=>{S.current=null,L.current=fe.playbackRate,fe.playbackRate=2,C.current=!0,ve(!0)},lte))},[Ce]),se=x.useCallback(Le=>{const fe=A.current;!fe||fe.id!==Le.pointerId||C.current||Math.hypot(Le.clientX-fe.x,Le.clientY-fe.y)>cte&&(Ce(),A.current=null)},[Ce]),_e=x.useCallback(()=>{ee()&&(R.current=!0)},[ee]);x.useEffect(()=>(window.addEventListener("pointerup",_e),window.addEventListener("pointercancel",_e),window.addEventListener("blur",_e),()=>{window.removeEventListener("pointerup",_e),window.removeEventListener("pointercancel",_e),window.removeEventListener("blur",_e)}),[_e]);const he=x.useCallback(async()=>{const Le=r.current,fe=i.current;if(!(!Le||!fe))try{document.fullscreenElement===Le?await document.exitFullscreen():Le.requestFullscreen?await Le.requestFullscreen():fe.webkitEnterFullscreen?.()}catch{fe.webkitEnterFullscreen?.()}},[]),He=x.useCallback(()=>ke(Le=>(Le+90)%360),[]),Je=x.useCallback(Le=>{const fe=i.current;if(!fe||!Number.isFinite(fe.duration))return;const Qe=Le.shiftKey?10:5;let ft=null;Le.key==="ArrowLeft"?ft=fe.currentTime-Qe:Le.key==="ArrowRight"?ft=fe.currentTime+Qe:Le.key==="Home"?ft=0:Le.key==="End"&&(ft=fe.duration),ft!==null&&(Le.preventDefault(),Ee(ft))},[Ee]),at=O&&W!==null?W:F,ge=M>0?Math.min(1,Math.max(0,at/M)):0,tt=(re===90||re===270)&&q.width>0&&q.height>0?{width:`${q.height}px`,height:`${q.width}px`}:{width:"100%",height:"100%"};return o.jsxs("div",{ref:r,className:"flex h-full min-h-0 flex-col overflow-hidden rounded-lg bg-background fullscreen:h-screen fullscreen:w-screen fullscreen:rounded-none","data-testid":"file-preview-video-player","data-rotation":re,children:[o.jsxs("div",{ref:s,className:"relative min-h-0 flex-1 overflow-hidden bg-background",children:[o.jsx("video",{ref:i,"data-testid":"file-preview-video",className:"absolute left-1/2 top-1/2 max-w-none object-contain transition-transform duration-200",style:{...tt,transform:`translate(-50%, -50%) rotate(${re}deg)`},src:e,preload:"auto",playsInline:!0,onClick:Ye,onPointerDown:me,onPointerMove:se,onPointerUp:_e,onPointerCancel:_e,onContextMenu:Le=>{C.current&&Le.preventDefault()},onPlay:()=>$(!0),onPause:()=>$(!1),onTimeUpdate:Le=>N(Le.currentTarget.currentTime),onSeeked:Le=>{const fe=Le.currentTarget;if(N(fe.currentTime),y.current=!1,!g.current)return;const Qe=fe.requestVideoFrameCallback;typeof Qe=="function"?Qe.call(fe,()=>{g.current&&Ze()}):requestAnimationFrame(()=>{g.current&&Ze()})},onLoadedMetadata:Le=>B(Number.isFinite(Le.currentTarget.duration)?Le.currentTarget.duration:0),onDurationChange:Le=>B(Number.isFinite(Le.currentTarget.duration)?Le.currentTarget.duration:0),onError:t,children:n("rightSidebar.videoUnsupported")}),ce&&o.jsx("div",{className:"pointer-events-none absolute left-1/2 top-3 z-10 -translate-x-1/2 rounded-full bg-surface-elevated px-3 py-1 text-xs font-semibold tabular-nums text-foreground shadow-md",children:n("rightSidebar.videoLongPressSpeed")}),O&&W!==null&&o.jsx("div",{className:"pointer-events-none absolute bottom-1 z-10 -translate-x-1/2 rounded-md bg-surface-elevated px-2 py-1 text-[11px] font-medium text-foreground shadow-md",style:{left:`${ge*100}%`},"data-testid":"file-preview-video-scrub-time",children:Hb(W)})]}),o.jsx("div",{"data-testid":"file-preview-video-controls",className:`shrink-0 border-t border-border/60 bg-background px-2 py-1.5 ${j9}`,[P9]:"",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{type:"button",onClick:Ye,"aria-label":n(T?"rightSidebar.videoPause":"rightSidebar.videoPlay"),title:n(T?"rightSidebar.videoPause":"rightSidebar.videoPlay"),className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-foreground transition hover:bg-surface-elevated active:scale-95","data-testid":"file-preview-video-play",children:T?o.jsx(j8,{size:14}):o.jsx(S2,{size:14})}),o.jsxs("div",{ref:a,role:"slider","aria-label":"Seek","aria-valuemin":0,"aria-valuemax":Math.floor(M),"aria-valuenow":Math.floor(at),tabIndex:0,className:"group relative h-5 min-w-0 flex-1 cursor-pointer touch-none py-2","data-testid":"file-preview-video-track",onPointerDown:ne,onPointerMove:Le=>{O&&$e(Le.clientX)},onPointerUp:lt,onPointerCancel:lt,onKeyDown:Je,children:[o.jsx("div",{className:"h-1 w-full rounded-full bg-surface-elevated"}),o.jsx("div",{className:"absolute inset-y-0 left-0 my-auto h-1 rounded-full bg-primary",style:{width:`${ge*100}%`}}),o.jsx("div",{className:"absolute top-1/2 h-3 w-3 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary shadow",style:{left:`${ge*100}%`}})]}),o.jsxs("div",{className:"shrink-0 text-[11px] tabular-nums text-muted-foreground","data-testid":"file-preview-video-time",children:[Hb(at)," / ",Hb(M)]}),o.jsx("button",{type:"button",onClick:He,"aria-label":n("rightSidebar.videoRotate"),title:n("rightSidebar.videoRotate"),className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-foreground transition hover:bg-surface-elevated active:scale-95","data-testid":"file-preview-video-rotate",children:o.jsx(ID,{size:14})}),o.jsx("button",{type:"button",onClick:()=>{he()},"aria-label":n(X?"rightSidebar.videoFullscreenExit":"rightSidebar.videoFullscreenEnter"),title:n(X?"rightSidebar.videoFullscreenExit":"rightSidebar.videoFullscreenEnter"),className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-foreground transition hover:bg-surface-elevated active:scale-95","data-testid":"file-preview-video-fullscreen",children:X?o.jsx(iD,{size:14}):o.jsx(eD,{size:14})})]})})]})}function fte(e){const t=Math.max(0,Math.min(100,e.xPercent)),n=Math.max(0,Math.min(100,e.yPercent));return{...t<=50?{left:`calc(${t}% + 8px)`}:{right:`calc(${100-t}% + 8px)`},...n<=50?{top:`calc(${n}% + 8px)`}:{bottom:`calc(${100-n}% + 8px)`}}}function k1({anchor:e,children:t,disabled:n=!1,onClick:r,title:s}){return o.jsxs("button",{type:"button","data-floating-annotation-button":!0,disabled:n,onClick:i=>{i.stopPropagation(),r()},title:s,style:fte(e),className:"absolute z-30 inline-flex h-7 items-center gap-1 rounded-full bg-primary px-3 text-[11px] font-semibold text-primary-foreground shadow-lg ring-1 ring-primary/30 transition hover:bg-primary/90 active:scale-95 disabled:cursor-wait disabled:opacity-50",children:[o.jsx(nc,{size:11}),t]})}function hte(e,t,n,r){if(n.width<=0||n.height<=0||r.width<=0||r.height<=0)return null;const s=Math.min(n.width/r.width,n.height/r.height);if(!Number.isFinite(s)||s<=0)return null;const i=r.width*s,a=r.height*s,c=n.left+(n.width-i)/2,u=n.top+(n.height-a)/2,f=e-c,p=t-u;if(f<0||p<0||f>i||p>a)return null;const g=f/i*100,y=p/a*100;return{x:r.x+r.width*g/100,y:r.y+r.height*y/100,xPercent:g,yPercent:y}}function pte(e,t,n){const r=[`SVG标注: ${e}`,`视图: ${t}`,`SVG坐标: (${n.x.toFixed(2)},${n.y.toFixed(2)}) [viewBox坐标]`,`图片位置: (${n.xPercent.toFixed(1)}%,${n.yPercent.toFixed(1)}%) [相对内容边界左上角]`];return n.nearestText&&r.push(`最近文字: ${n.nearestText}`),`"${r.join(" / ")}"`}function mte(e){const t=new DOMParser().parseFromString(e,"image/svg+xml"),n=t.documentElement;if(n.nodeName.toLowerCase()!=="svg"||t.querySelector("parsererror"))throw new Error("Invalid SVG document");return t.querySelectorAll("script,foreignObject,iframe,object,embed").forEach(r=>r.remove()),t.querySelectorAll("*").forEach(r=>{for(const s of Array.from(r.attributes)){const i=s.name.toLowerCase(),a=s.value.trim();(i.startsWith("on")||(i==="href"||i.endsWith(":href"))&&a&&!a.startsWith("#"))&&r.removeAttribute(s.name)}}),n.removeAttribute("width"),n.removeAttribute("height"),n.setAttribute("preserveAspectRatio","xMidYMid meet"),new XMLSerializer().serializeToString(n)}function gte(e,t,n){let r=null;for(const s of Array.from(e.querySelectorAll("text"))){const i=(s.textContent??"").replace(/\s+/g," ").trim();if(!i)continue;const a=Number(s.getAttribute("x")),c=Number(s.getAttribute("y"));if(!Number.isFinite(a)||!Number.isFinite(c))continue;const u=Math.hypot(a-t,c-n);(!r||u<r.distance)&&(r={text:i,distance:u})}return r?.text.slice(0,120)}function UC({blobUrl:e,filePath:t,viewLabel:n,onInsertAnnotation:r}){const s=x.useRef(null),i=x.useRef(null),[a,c]=x.useState(null),[u,f]=x.useState(null),[p,g]=x.useState(1),[y,v]=x.useState(!1),[S,A]=x.useState(null),C=x.useRef(new Map),L=x.useRef(null),R=x.useRef(!1),M=x.useRef(null),B=x.useRef(p);B.current=p,x.useEffect(()=>{const X=new AbortController;return c(null),f(null),A(null),g(1),fetch(e,{signal:X.signal}).then(V=>V.text()).then(V=>c(mte(V))).catch(V=>{X.signal.aborted||f(V instanceof Error?V.message:"SVG preview failed")}),()=>X.abort()},[e]),x.useEffect(()=>{if(!y)return;const X=V=>{V.key==="Escape"&&v(!1)};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[y]),x.useLayoutEffect(()=>{const X=i.current,V=X?.querySelector("[data-svg-document] > svg");if(!X||!V)return;let q;try{q=V.getBBox()}catch{return}if(!q.width||!q.height)return;const ue=Math.max(2,Math.min(q.width,q.height)*.025);V.setAttribute("viewBox",`${q.x-ue} ${q.y-ue} ${q.width+2*ue} ${q.height+2*ue}`),V.style.width=`${p*100}%`,V.style.height=`${p*100}%`,V.style.minWidth=`${p*100}%`,V.style.minHeight=`${p*100}%`,V.style.display="block"},[a,p]);const F=x.useMemo(()=>S?pte(t,n,S):null,[t,S,n]),N=X=>{if(R.current){R.current=!1;return}const V=i.current,q=V?.querySelector("[data-svg-document] > svg"),ue=s.current;if(!V||!q||!ue)return;const Ce=q.viewBox.baseVal,ee=hte(X.clientX,X.clientY,q.getBoundingClientRect(),Ce);if(!ee)return;const Ee=ue.getBoundingClientRect();A({...ee,nearestText:gte(q,ee.x,ee.y),stageX:X.clientX-Ee.left,stageY:X.clientY-Ee.top,stageXPercent:(X.clientX-Ee.left)/Ee.width*100,stageYPercent:(X.clientY-Ee.top)/Ee.height*100})},T=X=>Math.max(1,Math.min(12,X)),$=(X,V)=>{const q=T(V),ue=X.querySelector("[data-svg-document] > svg");if(!ue)return q;const Ce=`${q*100}%`;return ue.style.width=Ce,ue.style.height=Ce,ue.style.minWidth=Ce,ue.style.minHeight=Ce,B.current=q,q},O=(X,V,q,ue)=>{const Ce=B.current,ee=X.getBoundingClientRect(),Ee=q-ee.left,Ze=ue-ee.top,$e=(X.scrollLeft+Ee)/Ce,Ue=(X.scrollTop+Ze)/Ce,ne=$(X,V);return X.scrollLeft=$e*ne-Ee,X.scrollTop=Ue*ne-Ze,ne},Y=()=>{const X=Array.from(C.current.values());return X.length>=2?Math.hypot(X[0].x-X[1].x,X[0].y-X[1].y):0},W=X=>{if(X.pointerType==="mouse"&&X.button!==0)return;const V=i.current;V&&(C.current.set(X.pointerId,{x:X.clientX,y:X.clientY}),V.setPointerCapture?.(X.pointerId),C.current.size>=2?(L.current={kind:"pinch",startX:X.clientX,startY:X.clientY,startScrollLeft:V.scrollLeft,startScrollTop:V.scrollTop,startDistance:Y(),startZoom:B.current,moved:!1},R.current=!0):B.current>1&&(L.current={kind:"pan",startX:X.clientX,startY:X.clientY,startScrollLeft:V.scrollLeft,startScrollTop:V.scrollTop,startZoom:B.current,moved:!1}))},ye=X=>{if(!C.current.has(X.pointerId))return;C.current.set(X.pointerId,{x:X.clientX,y:X.clientY});const V=i.current,q=L.current;if(!(!V||!q)){if(C.current.size>=2&&q.kind==="pinch"){const ue=Y();if(!q.startDistance||!ue)return;const Ce=T(q.startZoom*ue/q.startDistance);if(Math.abs(Ce-B.current)<.01)return;const ee=Array.from(C.current.values()),Ee=(ee[0].x+ee[1].x)/2,Ze=(ee[0].y+ee[1].y)/2;q.moved=!0,R.current=!0,O(V,Ce,Ee,Ze),X.preventDefault();return}if(q.kind==="pan"&&C.current.size===1){const ue=X.clientX-q.startX,Ce=X.clientY-q.startY;if(!q.moved&&Math.hypot(ue,Ce)<6)return;q.moved=!0,R.current=!0,V.scrollLeft=q.startScrollLeft-ue,V.scrollTop=q.startScrollTop-Ce,X.preventDefault()}}},ce=X=>{const V=i.current,q=L.current,ue=C.current.size===1&&!q?.moved;C.current.delete(X.pointerId);try{V?.releasePointerCapture?.(X.pointerId)}catch{}if(C.current.size===1&&q?.kind==="pinch"){const Ee=Array.from(C.current.values())[0];L.current=V?{kind:"pan",startX:Ee.x,startY:Ee.y,startScrollLeft:V.scrollLeft,startScrollTop:V.scrollTop,startZoom:B.current,moved:!1}:null;return}if(C.current.size>0||(L.current=null,q?.kind==="pinch"&&g(B.current),!ue||R.current))return;const Ce=Date.now(),ee=M.current;ee&&Ce-ee.time<350&&Math.hypot(X.clientX-ee.x,X.clientY-ee.y)<24?(M.current=null,R.current=!0,g(Ee=>Ee>1?1:2.5)):M.current={time:Ce,x:X.clientX,y:X.clientY}},ve=X=>{if(!X.ctrlKey&&!X.metaKey)return;const V=i.current;if(!V)return;X.preventDefault();const q=O(V,B.current*Math.exp(-X.deltaY*.01),X.clientX,X.clientY);g(q)},re=()=>{g(1),B.current=1,i.current&&(i.current.scrollLeft=0,i.current.scrollTop=0)},ke=o.jsxs("div",{className:y?"fixed inset-0 z-modal-panel flex min-h-0 flex-col bg-surface pt-[env(safe-area-inset-top,0px)]":"flex h-full min-h-0 flex-col bg-surface",children:[o.jsxs("div",{ref:s,className:"relative min-h-0 flex-1",children:[o.jsx("div",{ref:i,role:"button",tabIndex:0,onClick:N,onDoubleClick:X=>{X.preventDefault(),g(V=>V>1?1:2.5)},onPointerDown:W,onPointerMove:ye,onPointerUp:ce,onPointerCancel:ce,onWheel:ve,onScroll:()=>A(null),className:"h-full touch-none cursor-crosshair overflow-auto bg-white p-3 text-slate-900",children:u?o.jsx("div",{className:"p-4 text-sm text-destructive",children:u}):a?o.jsx("div",{"data-svg-document":!0,className:"h-full min-h-[240px] w-full",dangerouslySetInnerHTML:{__html:a}}):o.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading SVG…"})}),S&&o.jsx("span",{"data-svg-pick-marker":!0,className:"pointer-events-none absolute z-10 h-4 w-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-primary bg-white shadow-sm",style:{left:S.stageX,top:S.stageY}}),S&&F&&o.jsx(k1,{anchor:{xPercent:S.stageXPercent,yPercent:S.stageYPercent},title:"引用 SVG 标注",onClick:()=>{r?.(F,`svg:${S.x.toFixed(2)}:${S.y.toFixed(2)}`),A(null)},children:"引用 SVG 标注"}),o.jsxs("div",{"data-svg-toolbar":!0,className:"absolute right-2 top-2 z-20 flex gap-1",children:[p>1.001&&o.jsx("button",{type:"button","aria-label":"适合窗口",title:"适合窗口",onClick:X=>{X.stopPropagation(),re()},className:"inline-flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 bg-white/95 text-slate-600 shadow-sm backdrop-blur transition active:scale-95",children:o.jsx(MD,{size:14})}),o.jsx("button",{type:"button","aria-label":y?"退出全屏 SVG":"全屏 SVG",title:y?"退出全屏 SVG":"全屏 SVG",onClick:X=>{X.stopPropagation(),v(V=>!V)},className:"inline-flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 bg-white/95 text-slate-600 shadow-sm backdrop-blur transition active:scale-95",children:y?o.jsx(iv,{size:14}):o.jsx(sv,{size:14})})]})]}),o.jsx("div",{className:"flex shrink-0 items-center justify-between gap-3 border-t border-border/15 px-3 py-2",children:o.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:S?`SVG (${S.x.toFixed(2)}, ${S.y.toFixed(2)}) · ${S.nearestText??"附近无文字"}`:"点击 SVG 的问题位置生成精确引用"})})]});return y?Ni.createPortal(ke,document.body):ke}function sg(e){switch(e){case"schematic":return"原理图第1页";case"pcb-front":return"PCB正面";case"pcb-back":return"PCB背面(镜像)";case"pcb-3d":return"PCB 3D正面"}}function xte(e,t,n,r){const s=[`电子标注: ${e}`,`视图: ${sg(t)}`,`图片位置: (${n.xPercent.toFixed(1)}%,${n.yPercent.toFixed(1)}%) [相对渲染图左上角]`];if(r?.available&&r.xMm!==void 0&&r.yMm!==void 0&&(s.push(`PCB坐标: (${r.xMm.toFixed(2)},${r.yMm.toFixed(2)})mm [KiCad板坐标]`),r.layer&&s.push(`显示层: ${r.layer}`),r.nearest)){const i=[r.nearest.net?`网络 ${r.nearest.net}`:null,`对象层 ${r.nearest.layer}`,`距离 ${r.nearest.distanceMm.toFixed(2)}mm`].filter(Boolean).join(",");s.push(`最近对象: ${r.nearest.label}${i?`(${i})`:""}`)}return`"${s.join(" / ")}"`}function bte({blobUrl:e,filePath:t,view:n,board:r,onViewChange:s,onInsertAnnotation:i,onRefresh:a,interactive3d:c}){const{t:u}=ir(),f=x.useRef(null),p=x.useRef(null),g=x.useRef(null),[y,v]=x.useState(null),[S,A]=x.useState(!1);x.useEffect(()=>(g.current?.abort(),v(null),A(!1),()=>g.current?.abort()),[e,n]);const C=x.useMemo(()=>y?xte(t,n,y,y.inspection):null,[t,y,n]),L=M=>{const B=f.current,F=p.current;if(!B||!F||!F.naturalWidth||!F.naturalHeight)return;const N=B.getBoundingClientRect(),T=Math.min(N.width/F.naturalWidth,N.height/F.naturalHeight),$=F.naturalWidth*T,O=F.naturalHeight*T,Y=N.left+(N.width-$)/2,W=N.top+(N.height-O)/2,ye=M.clientX-Y,ce=M.clientY-W;if(ye<0||ce<0||ye>$||ce>O)return;const ve={xPercent:Math.max(0,Math.min(100,ye/$*100)),yPercent:Math.max(0,Math.min(100,ce/O*100)),stageXPercent:(M.clientX-N.left)/N.width*100,stageYPercent:(M.clientY-N.top)/N.height*100,inspecting:r&&n!=="pcb-3d"};if(v(ve),g.current?.abort(),!ve.inspecting)return;const re=new AbortController;g.current=re,hR(t,n,ve.xPercent,ve.yPercent,re.signal).then(ke=>v(X=>X===ve?{...X,inspection:ke,inspecting:!1}:X)).catch(()=>{re.signal.aborted||v(ke=>ke===ve?{...ke,inspection:{available:!1},inspecting:!1}:ke)})},R=r?["pcb-front","pcb-back","pcb-3d"]:["schematic"];return o.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-surface",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-b border-border/15 px-3 py-2",children:[o.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1 overflow-x-auto",children:R.map(M=>o.jsx("button",{type:"button",onClick:()=>s(M),className:`h-8 shrink-0 rounded-full px-3 text-xs font-semibold transition active:scale-95 ${M===n?"bg-primary/15 text-primary":"bg-surface-2 text-muted-foreground hover:bg-surface-elevated hover:text-foreground"}`,children:sg(M)},M))}),o.jsx("button",{type:"button",onClick:a,className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95",title:u("rightSidebar.edaRefresh"),"aria-label":u("rightSidebar.edaRefresh"),children:o.jsx(ai,{size:13})})]}),r&&c?o.jsx("div",{className:n==="pcb-3d"?"flex min-h-0 flex-1 flex-col overflow-hidden":"hidden",children:c}):null,r?n==="pcb-3d"?c?null:o.jsx("div",{className:"min-h-0 flex-1"}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{ref:f,role:"button",tabIndex:0,onClick:L,onKeyDown:M=>{M.key!=="Enter"&&M.key!==" "||(M.preventDefault(),v({xPercent:50,yPercent:50,stageXPercent:50,stageYPercent:50}))},className:"relative min-h-0 flex-1 cursor-crosshair overflow-hidden bg-surface p-3 outline-none",title:u("rightSidebar.edaPickHint"),children:[o.jsx("img",{ref:p,src:e,alt:`${t} ${sg(n)}`,onLoad:()=>A(!0),className:`pointer-events-none h-full w-full object-contain transition-opacity ${S?"opacity-100":"opacity-0"}`}),y&&o.jsx("span",{className:"pointer-events-none absolute h-4 w-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-primary bg-surface shadow-sm",style:{left:`${y.stageXPercent}%`,top:`${y.stageYPercent}%`}}),y&&C&&o.jsx(k1,{anchor:{xPercent:y.stageXPercent,yPercent:y.stageYPercent},disabled:y.inspecting,title:u("rightSidebar.edaInsertAnnotation"),onClick:()=>{i?.(C,`eda:${n}:${y.xPercent.toFixed(1)}:${y.yPercent.toFixed(1)}`),v(null)},children:u("rightSidebar.edaInsertAnnotation")})]}),o.jsx("div",{className:"flex shrink-0 items-center justify-between gap-3 border-t border-border/15 px-3 py-2",children:o.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:y?y.inspecting?u("rightSidebar.edaInspecting"):y.inspection?.available?u("rightSidebar.edaPickedBoardPosition",{x:y.inspection.xMm?.toFixed(2)??"—",y:y.inspection.yMm?.toFixed(2)??"—",object:y.inspection.nearest?.label??u("rightSidebar.edaNoNearbyObject")}):u("rightSidebar.edaPickedPosition",{x:y.xPercent.toFixed(1),y:y.yPercent.toFixed(1)}):u("rightSidebar.edaPickHint")})})]}):o.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:o.jsx(UC,{blobUrl:e,filePath:t,viewLabel:sg(n),onInsertAnnotation:i})})]})}function yte(e){const t=[];let n=[],r="",s=!1;for(let i=0;i<e.length;i+=1){const a=e[i];s?a==='"'&&e[i+1]==='"'?(r+='"',i+=1):a==='"'?s=!1:r+=a:a==='"'?s=!0:a===","?(n.push(r),r=""):a===`
182
182
  `?(n.push(r.replace(/\r$/,"")),t.push(n),n=[],r=""):r+=a}return(r||n.length>0)&&(n.push(r.replace(/\r$/,"")),t.push(n)),t}function vte(e,t,n,r,s){const i=t[s]||`第${s+1}列`,a=n[s]??"",c=t.map((u,f)=>`${u||`第${f+1}列`}=${n[f]??""}`).join(";");return`"表格标注: ${e} / 数据行: ${r+1} / 列: ${i} / 值: ${a} / 记录: ${c}"`}function wte({content:e,filePath:t,onInsertAnnotation:n}){const{t:r}=ir(),s=x.useMemo(()=>yte(e),[e]),i=s[0]??[],a=s.slice(1),c=x.useRef(null),[u,f]=x.useState(null),p=u?a[u.row]:null,g=u&&p?vte(t,i,p,u.row+1,u.column):null;return o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-surface",children:[o.jsxs("div",{ref:c,className:"relative min-h-0 flex-1",children:[o.jsx("div",{className:"h-full overflow-auto",children:o.jsxs("table",{className:"min-w-full border-separate border-spacing-0 text-left text-xs",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{className:"sticky left-0 top-0 z-20 border-b border-r border-border/20 bg-surface-elevated px-2 py-2 text-[10px] font-semibold text-muted-foreground",children:"#"}),i.map((y,v)=>o.jsx("th",{className:"sticky top-0 z-10 min-w-28 border-b border-r border-border/20 bg-surface-elevated px-3 py-2 font-semibold text-foreground",children:y||r("rightSidebar.csvUnnamedColumn",{index:v+1})},`${y}:${v}`))]})}),o.jsx("tbody",{children:a.map((y,v)=>o.jsxs("tr",{className:"hover:bg-surface-2",children:[o.jsx("th",{className:"sticky left-0 z-10 border-b border-r border-border/15 bg-surface px-2 py-2 text-right text-[10px] font-normal text-muted-foreground",children:v+1}),i.map((S,A)=>{const C=u?.row===v&&u.column===A;return o.jsx("td",{className:`border-b border-r border-border/15 p-0 ${C?"bg-primary/15":""}`,children:o.jsx("button",{type:"button",onClick:L=>{const R=c.current?.getBoundingClientRect(),M=L.currentTarget.getBoundingClientRect();if(!R?.width||!R.height)return;const B=L.clientX||M.left+M.width/2,F=L.clientY||M.top+M.height/2;f({row:v,column:A,xPercent:(B-R.left)/R.width*100,yPercent:(F-R.top)/R.height*100})},className:"block h-full min-h-9 w-full whitespace-pre-wrap px-3 py-2 text-left text-foreground outline-none hover:bg-primary/10 focus-visible:bg-primary/10",children:y[A]||" "})},`cell:${v}:${A}`)})]},`row:${v}`))})]})}),u&&g&&o.jsx(k1,{anchor:{xPercent:u.xPercent,yPercent:u.yPercent},title:r("rightSidebar.csvInsertAnnotation"),onClick:()=>{n?.(g,`csv:${t}:${u.row+1}:${u.column+1}`),f(null)},children:r("rightSidebar.csvInsertAnnotation")})]}),o.jsx("div",{className:"flex shrink-0 items-center justify-between gap-3 border-t border-border/15 px-3 py-2",children:o.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:u&&p?r("rightSidebar.csvSelectedCell",{row:u.row+1,column:i[u.column]||u.column+1}):r("rightSidebar.csvPickHint",{rows:a.length,columns:i.length})})})]})}function n0(e,t){let n=e;for(const r of t){if(!n||typeof n!="object")return;n=n[r]}return n}function Ste(e,t){const n=JSON.parse(e),r=n0(n,["meta","version"]);if(t)return[{label:"文件性质",value:"KiCad 本机界面状态,不属于电气设计源文件"},{label:"格式版本",value:String(r??"未知")},{label:"活动层编号",value:String(n0(n,["board","active_layer"])??"未知")},{label:"可见层掩码",value:String(n0(n,["board","visible_layers"])??"未知")},{label:"Git 集成",value:n0(n,["git","integration_disabled"])===!0?"已禁用":"未禁用"}];const s=n0(n,["net_settings","classes"]),i=Array.isArray(s)?s.find(c=>c&&typeof c=="object"&&c.name==="Default"):void 0,a=n0(n,["board","design_settings","drc_exclusions"]);return[{label:"文件性质",value:"KiCad 工程配置"},{label:"格式版本",value:String(r??"未知")},{label:"网络类数量",value:String(Array.isArray(s)?s.length:0)},{label:"默认间距",value:i?.clearance!==void 0?`${i.clearance} mm`:"未设置"},{label:"默认线宽",value:i?.track_width!==void 0?`${i.track_width} mm`:"未设置"},{label:"默认过孔",value:i?.via_diameter!==void 0?`${i.via_diameter} / ${i.via_drill??"—"} mm(外径/钻孔)`:"未设置"},{label:"DRC 排除项",value:String(Array.isArray(a)?a.length:0)}]}function Ate(e,t){return`"KiCad项目标注: ${e} / 项: ${t.label} / 值: ${t.value}"`}function Tte({content:e,filePath:t,localState:n,onInsertAnnotation:r}){const{t:s}=ir(),i=x.useRef(null),[a,c]=x.useState(null),u=x.useMemo(()=>{try{return{items:Ste(e,n),error:null}}catch(p){return{items:[],error:p instanceof Error?p.message:String(p)}}},[e,n]),f=a===null?null:u.items[a.index];return u.error?o.jsx("pre",{className:"min-h-0 flex-1 overflow-auto whitespace-pre-wrap p-3 font-mono text-xs text-foreground",children:e}):o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-surface",children:[n&&o.jsx("div",{className:"border-b border-[color:var(--warning)]/20 bg-[color:var(--warning)]/5 px-3 py-2 text-xs text-[color:var(--warning)]",children:s("rightSidebar.kicadLocalStateNotice")}),o.jsxs("div",{ref:i,className:"relative min-h-0 flex-1",children:[o.jsxs("div",{className:"h-full overflow-auto px-3 py-2",children:[o.jsx("div",{className:"divide-y divide-border/15",children:u.items.map((p,g)=>o.jsxs("button",{type:"button",onClick:y=>{const v=i.current?.getBoundingClientRect(),S=y.currentTarget.getBoundingClientRect();if(!v?.width||!v.height)return;const A=y.clientX||S.left+S.width/2,C=y.clientY||S.top+S.height/2;c({index:g,xPercent:(A-v.left)/v.width*100,yPercent:(C-v.top)/v.height*100})},className:`grid w-full grid-cols-[minmax(7rem,0.8fr)_minmax(0,1.4fr)] gap-3 px-2 py-3 text-left transition hover:bg-surface-2 ${a?.index===g?"bg-primary/10":""}`,children:[o.jsx("span",{className:"text-xs font-semibold text-muted-foreground",children:p.label}),o.jsx("span",{className:"break-words text-xs text-foreground",children:p.value})]},p.label))}),o.jsxs("details",{className:"mt-3 border-t border-border/15 pt-3",children:[o.jsx("summary",{className:"cursor-pointer text-xs font-semibold text-muted-foreground",children:s("rightSidebar.kicadShowRawJson")}),o.jsx("pre",{className:"mt-2 overflow-auto whitespace-pre p-2 font-mono text-[10px] leading-relaxed text-foreground",children:e})]})]}),f&&a&&o.jsx(k1,{anchor:{xPercent:a.xPercent,yPercent:a.yPercent},title:s("rightSidebar.kicadInsertSetting"),onClick:()=>{r?.(Ate(t,f),`kicad-project:${t}:${f.label}`),c(null)},children:s("rightSidebar.kicadInsertSetting")})]}),o.jsx("div",{className:"flex shrink-0 items-center justify-between gap-3 border-t border-border/15 px-3 py-2",children:o.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:f?`${f.label}: ${f.value}`:s("rightSidebar.kicadProjectPickHint")})})]})}const Cte=x.forwardRef(function({src:t,title:n,exitFullscreenLabel:r,onFullscreenChange:s},i){const a=x.useRef(null),[c,u]=x.useState(!1),[f,p]=x.useState(!1),g=c||f;x.useEffect(()=>{s?.(g)},[g,s]),x.useEffect(()=>{const S=()=>{u(document.fullscreenElement===a.current)};return document.addEventListener("fullscreenchange",S),()=>document.removeEventListener("fullscreenchange",S)},[]),x.useEffect(()=>{if(!f)return;const S=A=>{A.key==="Escape"&&p(!1)};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[f]);const y=x.useCallback(async()=>{const S=a.current;if(S){if(f){p(!1);return}if(document.fullscreenElement===S){await document.exitFullscreen();return}if(S.requestFullscreen&&document.fullscreenEnabled!==!1)try{await S.requestFullscreen();return}catch{}p(!0)}},[f]);x.useImperativeHandle(i,()=>({toggleFullscreen:y}),[y]);const v=o.jsxs("div",{ref:a,"data-html-preview-frame":!0,className:g?"fixed inset-0 z-modal-panel flex min-h-0 flex-col overflow-hidden bg-surface pt-[env(safe-area-inset-top,0px)] text-foreground":"flex h-full min-h-0 flex-col overflow-hidden bg-surface",children:[g&&o.jsxs("div",{className:"flex h-12 shrink-0 items-center justify-between gap-3 border-b border-border/15 bg-[var(--chrome-bg)] px-3",children:[o.jsx("span",{className:"min-w-0 truncate text-[12px] font-semibold",children:n}),o.jsx("button",{type:"button",onClick:()=>{y()},"aria-label":r,title:`${r} (Esc)`,className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95",children:o.jsx(iv,{size:15})})]}),o.jsx("iframe",{src:t,title:n,sandbox:"allow-scripts",className:"block min-h-0 w-full flex-1 border-0 bg-white"})]});return f?Ni.createPortal(v,document.body):v}),GC="termdock-file-search-match",Ny="termdock-file-search-current";function kte(e){const t=e.metaKey||e.ctrlKey,n=e.key.toLocaleLowerCase();return t&&n==="f"?"open":t&&n==="g"||e.key==="F3"?e.shiftKey?"previous":"next":e.key==="Escape"?"close":null}function _te(e){return e.parentElement?.closest("[data-markdown-preview-block-start], [data-file-preview-line]")??null}function Lte(e,t){const n=t.trim().toLocaleLowerCase();if(!n)return[];const r=[];let s="",i=null;const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(let p=a.nextNode();p;p=a.nextNode()){if(!(p instanceof Text)||!p.data)continue;const g=_te(p);if(!g)continue;i&&i!==g&&(s+=`
183
- `);const y=s.length;s+=p.data,r.push({node:p,start:y,end:s.length,group:g}),i=g}const c=s.toLocaleLowerCase(),u=[];let f=0;for(;f<=c.length-n.length;){const p=c.indexOf(n,f);if(p<0)break;const g=p+n.length,y=r.find(S=>S.start<=p&&S.end>p),v=r.find(S=>S.start<g&&S.end>=g);if(y&&v&&y.group===v.group){const S=document.createRange();S.setStart(y.node,p-y.start),S.setEnd(v.node,g-v.start),u.push(S)}f=p+Math.max(n.length,1)}return u}function WC(){return typeof CSS<"u"&&CSS.highlights?CSS.highlights:null}function Cm(){const e=WC();e?.delete(GC),e?.delete(Ny)}function $S(e,t){const n=WC();if(!n||typeof Highlight>"u")return;n.set(GC,new Highlight(...e));const r=e[t];r?n.set(Ny,new Highlight(r)):n.delete(Ny)}function HS(e){e?.startContainer.parentElement?.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}function Ete(e){return Array.from(new Set(e.split(/[\n,]/).map(t=>t.trim().replace(/^!+/,"")).filter(Boolean))).slice(0,24)}function Ite(e,t){const n=t.trim();return!n||n==="."?e:/^(?:[/\\]|[A-Za-z]:[/\\])/.test(n)?n.replace(/[\\/]+$/,""):`${e.replace(/[\\/]+$/,"")}/${n.replace(/^\.?[\\/]+/,"").replace(/[\\/]+$/,"")}`}function Rte(e,t){if(t===e)return".";const n=`${e.replace(/[\\/]+$/,"")}/`;return t.startsWith(n)?t.slice(n.length):t}function Nte(e,t,n){return t?e:Ni.createPortal(e,n)}const c5="termdock:right-sidebar:file-tree-scroll:v1",u5="termdock:right-sidebar:file-preview-reading-state:v1",xh="termdock:right-sidebar:file-tree-width:v1",VC="termdock:right-sidebar:markdown-view-mode:v1",qC="termdock:right-sidebar:diff-change-list-mode:v1",KC="termdock:right-sidebar:diff-wrap:v1",YC="termdock:diff-viewer:view-type:v1",XC="termdock:right-sidebar:file-search-mode:v1",zb="termdock:right-sidebar:collapsed-git-repo-groups:v1",zS="termdock:right-sidebar:collapsed-diff-directories:v1",Ub="termdock:right-sidebar:branch-audit-module-open:v1",ZC="termdock:right-sidebar:branch-audit-module:v1",Mte=150,JC="termdock:right-sidebar:active-git-repo:v1",US="termdock:right-sidebar:context-draft-enabled:v1",GS="termdock:right-sidebar:context-draft-collapsed:v1",WS="termdock:right-sidebar:context-draft-auto-collapse:v1",Gb="termdock:right-sidebar:context-draft-text:v1",Dte=300,jte=20,Pte=120,Bte=250,Fte=250,Ote=120,Qte=700,Wb=600,VS=[2e3,5e3,15e3,3e4],$te=320,Hte=500,zte=20,Ute=12e3,My=300,qS=240,Gte=560,ek="border-r px-2 py-1.5 sm:px-3 sm:py-2",Hg="max-w-[18rem] whitespace-normal break-words sm:max-w-[27rem]",tk=`${ek} border-b border-border/15 font-semibold last:border-r-0`,nk=`${ek} border-border/10 align-top text-muted-foreground last:border-r-0`,d5="termdock-file-preview-horizontal-scroll",KS=x.lazy(()=>$0(()=>import("./ModelPreview-DWT2tm1L.js"),__vite__mapDeps([2,3,1,4]))),rk=`${d5} termdock-md-table-scroll max-w-full overflow-x-auto overflow-y-hidden rounded-lg border border-border/20 bg-surface`;function Wte(e,t,n){return e&&!t?"unified":n}const Vte=new Set([".md",".markdown",".mdown",".mkdn",".mkd"]);function qte(e){return e==="preview"||e==="source"}function Kte(e){return e==="list"||e==="tree"||e==="ai"}function YS(){return Gr(VC,qte)??"preview"}function Yte(){return Gr(qC,Kte)??"tree"}function bh(e){return typeof e=="boolean"}function Xte(e){return typeof e=="string"}function Zte(){return Gr(KC,bh)??!0}function Jte(e){return e==="unified"||e==="split"}function ene(){return Gr(YC,Jte)??"unified"}function tne(e){return e==="name"||e==="content"||e==="regex"}function nne(){return Gr(XC,tne)??"name"}function sk(e){return e.repositories??(e.context?.root?[{id:e.context.root,root:e.context.root,relativeRoot:".",name:Jo(e.context.root)||e.context.root,depth:0,nested:!1,available:e.available,files:e.files,context:e.context,error:e.error}]:[])}function rne(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>t===null||typeof t=="string")}function ik(){return Gr(JC,rne)??{}}function XS(e){if(!e)return;const t=ik();return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0}function Vb(e,t){e&&Wn(JC,{...ik(),[e]:t})}function sne(e,t){if(!t)return null;const n=new Set((e.repoFilters??[]).map(r=>r.root));return n.has(t)?t:n.size>0?null:(e.repositories??[]).some(r=>r.root===t)?t:null}function Dy(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function ZS(e){const t=Gr(e,Dy);return t?new Set(t):new Set}function qb(e,t){Wn(e,[...t])}function ine(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.filePath=="string"&&typeof t.hunkHeader=="string"&&typeof t.hunkIndex=="number"&&typeof t.fingerprint=="string"&&typeof t.additions=="number"&&typeof t.deletions=="number"&&typeof t.diff=="string"&&(t.oldPath===void 0||t.oldPath===null||typeof t.oldPath=="string")&&(t.newPath===void 0||t.newPath===null||typeof t.newPath=="string")&&(t.source===void 0||t.source==="committed"||t.source==="uncommitted"||t.source==="unknown")&&(t.commit===void 0||t.commit===null||typeof t.commit=="string")}function one(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.available=="boolean"&&(t.repoRoot===void 0||typeof t.repoRoot=="string")&&(t.workspaceRoot===void 0||typeof t.workspaceRoot=="string")&&(t.baseRef===void 0||typeof t.baseRef=="string")&&(t.baseBranch===void 0||typeof t.baseBranch=="string")&&(t.currentBranch===void 0||t.currentBranch===null||typeof t.currentBranch=="string")&&(t.headRef===void 0||t.headRef===null||typeof t.headRef=="string")&&(t.diffFingerprint===void 0||typeof t.diffFingerprint=="string")&&(t.stat===void 0||typeof t.stat=="string")&&(t.files===void 0||Dy(t.files))&&(t.hunks===void 0||Array.isArray(t.hunks)&&t.hunks.every(ine))&&(t.commits===void 0||Dy(t.commits))&&(t.commitCount===void 0||typeof t.commitCount=="number")&&(t.diff===void 0||typeof t.diff=="string")&&(t.truncated===void 0||typeof t.truncated=="boolean")&&(t.error===void 0||typeof t.error=="string")}function ane(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.key=="string"&&one(t.diff)&&typeof t.repoLabel=="string"&&typeof t.createdAt=="number"}function lne(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;const n=t;return Array.isArray(n.selectedRepoRoots)&&n.selectedRepoRoots.every(r=>typeof r=="string")&&!!n.repoTargetBranches&&typeof n.repoTargetBranches=="object"&&!Array.isArray(n.repoTargetBranches)&&Object.values(n.repoTargetBranches).every(r=>typeof r=="string")&&(n.repoBaseBranches===void 0||!!n.repoBaseBranches&&typeof n.repoBaseBranches=="object"&&!Array.isArray(n.repoBaseBranches)&&Object.values(n.repoBaseBranches).every(r=>typeof r=="string"))&&(n.previewEntries===void 0||Array.isArray(n.previewEntries)&&n.previewEntries.every(ane))&&(n.selectedPreviewKey===void 0||n.selectedPreviewKey===null||typeof n.selectedPreviewKey=="string")&&(n.selectedPreviewFileKey===void 0||n.selectedPreviewFileKey===null||typeof n.selectedPreviewFileKey=="string")&&(n.previewDetailOpen===void 0||typeof n.previewDetailOpen=="boolean")&&(n.previewScrollTops===void 0||!!n.previewScrollTops&&typeof n.previewScrollTops=="object"&&!Array.isArray(n.previewScrollTops)&&Object.values(n.previewScrollTops).every(r=>typeof r=="number"))&&(n.previewMobileSlideIndex===void 0||typeof n.previewMobileSlideIndex=="number")&&(n.includeUncommitted===void 0||typeof n.includeUncommitted=="boolean")&&typeof n.updatedAt=="number"})}function JS(){return Gr(ZC,lne)??{}}function e7(e){return[e.repoRoot,e.baseRef,e.branchName??"",e.headRef??"",e.diffFingerprint??""].join("\0")}function t7(e){const t=e?.trim()??"",n=t.indexOf("/");return n>=0?t.slice(n+1):t}function ok(e,t){const n=e?.trim(),r=t?.trim();return!n||!r?!1:n===r||t7(n)===t7(r)}function n7(e){const t=e?.branch??null;return[e?.upstream,...e?.remoteBranches??[],...e?.branches??[]].find(r=>r&&!ok(r,t))??""}function jy(e,t){const n=Math.max(qS,t-320),r=Math.min(Gte,n);return Math.min(r,Math.max(qS,e))}function cne(e){return typeof e=="number"&&Number.isFinite(e)}function une(e){return jy(Gr(xh,cne)??My,e)}function ak(e){const t=e.split(/[\\/]/).pop()??e,n=t.lastIndexOf(".");return n>=0?t.slice(n).toLowerCase():""}function nh(e){return Vte.has(ak(e))}function lk(e){const t=e.trim().replace(/\s+/g,"");return/^-{3,}$/.test(t)||/^\*{3,}$/.test(t)||/^_{3,}$/.test(t)}function Py(e){const t=e.trim();return/^#{1,6}\s+/.test(t)||lk(e)||/^>\s?/.test(t)||/^(```|~~~)/.test(t)||/^(?:[-+*]|\d+[.)])\s+/.test(t)}function dne(e){const t=e.trim();return/^(https?:|mailto:|#|\/|\.\/|\.\.\/)/i.test(t)||!/^[a-z][a-z0-9+.-]*:/i.test(t)&&!/[<>]/.test(t)?t:null}const ck=x.createContext(null);function ig(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function uk(e){return e.replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1").replace(/[`*_~]/g,"").replace(/<[^>]+>/g,"").trim()}function dk(e){return e.replace(/\s+#+\s*$/,"").trim()}function By(e,t){const r=uk(e).toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu,"").trim().replace(/\s+/g,"-")||"section",s=t.headingSlugCounts.get(r)??0;return t.headingSlugCounts.set(r,s+1),s===0?r:`${r}-${s}`}function r7(e){return uk(e)||e.trim()}function zg(e){const t=e.match(/^\s{0,3}\[([^\]]+)\]:\s+(.+?)\s*$/);if(!t)return null;const n=Oy(t[2]);return n?{id:ig(t[1]),definition:{href:n.href,title:n.title}}:null}function fne(e){const t=new Map;for(const n of e){const r=zg(n);r&&t.set(r.id,r.definition)}return t}function fk(e){return e.trim().toLowerCase()}function hk(e){const t=e.match(/^\s{0,3}\[\^([^\]]+)\]:\s+(.+)\s*$/);return t?{id:fk(t[1]),text:t[2]}:null}function hne(e){const t=new Map;let n=null;for(const r of e){const s=hk(r);if(s){n=s.id,t.set(s.id,{id:s.id,text:s.text,index:t.size+1});continue}if(n&&/^\s{4,}\S/.test(r)){const i=t.get(n);i&&(i.text=`${i.text} ${r.trim()}`);continue}r.trim()&&(n=null)}return t}function pne(e){const t=new Set;let n=!1;return e.forEach((r,s)=>{if(hk(r)){t.add(s),n=!0;return}if(n&&/^\s{4,}\S/.test(r)){t.add(s);return}r.trim()&&(n=!1)}),t}function mne(e){const t=[...e];let n=0;const r=e[0]?.trim();if(r==="---"||r==="+++"){for(t[0]="",n=1;n<e.length&&e[n].trim()!==r;)t[n]="",n+=1;n<e.length&&(t[n]="",n+=1)}for(;n<e.length;){const s=e[n].trim();if(s.startsWith("<!--")){if(t[n]="",!s.includes("-->")){for(n+=1;n<e.length&&!e[n].includes("-->");)t[n]="",n+=1;n<e.length&&(t[n]="")}n+=1;continue}n+=1}return t}function pk(e){const t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");return n<=0?n===0?"/":"":t.slice(0,n)}function Rh(e){const t=e.split(/[?#]/,1)[0],n=t.startsWith("/"),r=[];for(const i of t.split("/"))if(!(!i||i===".")){if(i===".."){r.length>0&&r.pop();continue}r.push(i)}return`${n?"/":""}${r.join("/")}`||(n?"/":".")}function gne(e,t,n){const r=e.trim();if(!r||/^(?:https?:|mailto:|javascript:|data:|#)/i.test(r)||/^[a-z][a-z0-9+.-]*:/i.test(r))return null;const s=r.indexOf("#"),i=s>=0?r.slice(0,s):r,a=s>=0?r.slice(s+1):"",c=i.split("?",1)[0];if(!c)return null;let u,f=null;try{u=decodeURIComponent(c),f=a?decodeURIComponent(a):null}catch{return null}const p=n?Rh(n):null;let g;if(u.startsWith("/")){const y=p&&(u===p||u.startsWith(`${p}/`));g=Rh(p&&!y?`${p}/${u.slice(1)}`:u)}else{if(!t)return null;g=Rh(`${pk(t)}/${u}`)}return p&&g!==p&&!g.startsWith(`${p}/`)?null:{path:g,fragment:f,directory:/\/$/.test(c)}}function xne(e,t,n){const r=e.trim();if(!r||/^(?:javascript|data):/i.test(r))return null;if(/^https?:\/\//i.test(r))return r;if(!Xy(r.split(/[?#]/,1)[0]))return null;let s;if(r.startsWith("/")){const i=n&&(r===n||r.startsWith(`${n}/`));s=Rh(n&&!i?`${n}/${r.slice(1)}`:r)}else{if(!t)return null;s=Rh(`${pk(t)}/${r}`)}return`/api/terminal/fs/blob?path=${encodeURIComponent(s)}`}const Fy=128,bne=360,Kb=480;function f5(e){try{return/\.svg(?=$|[?#&])/i.test(decodeURIComponent(e))}catch{return!1}}function yne(e,t,n,r){if(!t||!n)return null;let s,i;return f5(e)?(i=Math.min(Math.max(n,Fy),bne),s=t*i/n):(s=t,i=n),r>0&&s>r&&(i=i*r/s,s=r),i>Kb&&(s=s*Kb/i,i=Kb),{width:Math.max(1,Math.round(s)),height:Math.max(1,Math.round(i))}}function vne(e){if(!e.startsWith("/api/terminal/fs/blob?"))return null;try{return new URLSearchParams(e.slice(e.indexOf("?"))).get("path")}catch{return null}}function mk(e){const t=vne(e),n=ht(r=>t?(r.fileChangeVersions.get(t)??0)+r.fileWatchEpoch:0);return t&&n>0?`${e}&v=${n}`:e}function wne({src:e,alt:t,title:n}){const r=f5(e),s=mk(e),i=x.useRef(null),[a,c]=x.useState(!1),[u,f]=x.useState(0),[p,g]=x.useState({status:"loading"}),[y,v]=x.useState(null);x.useLayoutEffect(()=>{const C=i.current,L=C?.parentElement?.parentElement??C?.parentElement;if(!L)return;const R=()=>f(L.clientWidth);if(R(),typeof ResizeObserver>"u")return;const M=new ResizeObserver(R);return M.observe(L),()=>M.disconnect()},[]),x.useEffect(()=>{if(a)return;const C=i.current;if(!C||typeof IntersectionObserver>"u"){c(!0);return}const L=new IntersectionObserver(R=>{R.some(M=>M.isIntersecting)&&(c(!0),L.disconnect())},{rootMargin:"400px"});return L.observe(C),()=>L.disconnect()},[a]),x.useEffect(()=>{if(!a)return;const C=new AbortController;let L=null;g({status:"loading"});const R=window.setTimeout(()=>{C.abort(new DOMException("Image fetch timed out","TimeoutError"))},15e3);return fetch(s,{signal:C.signal}).then(async M=>{if(!M.ok)throw new Error(`HTTP ${M.status}`);const B=Number(M.headers.get("X-Image-Width"))||0,F=Number(M.headers.get("X-Image-Height"))||0;return{blob:await M.blob(),width:B,height:F}}).then(({blob:M,width:B,height:F})=>{C.signal.aborted||(L=URL.createObjectURL(M),B>0&&F>0&&v({width:B,height:F}),g({status:"ready",objectUrl:L}))}).catch(()=>{const M=C.signal.reason;C.signal.aborted&&!(M instanceof DOMException&&M.name==="TimeoutError")||g({status:"fallback"})}).finally(()=>{window.clearTimeout(R)}),()=>{window.clearTimeout(R),C.abort(),L&&URL.revokeObjectURL(L)}},[a,s]);const S=yne(e,y?.width??0,y?.height??0,u),A=S??{width:Fy*2,height:Fy};return o.jsx("div",{ref:i,className:"block max-w-full",style:S?{width:S.width,height:S.height}:void 0,children:p.status==="ready"?o.jsx("img",{src:p.objectUrl,alt:t,title:n,decoding:"async",className:`${r?"":"termdock-fade-in "}block max-h-[480px] max-w-full object-contain`,style:S?{width:S.width,height:S.height}:void 0,onLoad:C=>{if(y)return;const L=C.currentTarget;L.naturalWidth>0&&L.naturalHeight>0&&v({width:L.naturalWidth,height:L.naturalHeight})}}):p.status==="fallback"?o.jsx("img",{src:s,alt:t,title:n,loading:"lazy",decoding:"async",className:"block max-h-[480px] max-w-full object-contain",style:S?{width:S.width,height:S.height}:void 0,onLoad:C=>{if(y)return;const L=C.currentTarget;L.naturalWidth>0&&L.naturalHeight>0&&v({width:L.naturalWidth,height:L.naturalHeight})}}):o.jsx("div",{"aria-hidden":!0,className:"flex max-w-full animate-pulse items-center justify-center rounded bg-surface-elevated/60",style:{width:A.width,height:A.height},children:o.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:t||"…"})})})}function Yb(e,t,n,r,s){const i=xne(n,s.markdownFilePath,s.rootPath);if(!i)return`![${t}](${n})`;const a=s.images.length;s.images.push({kind:"image",src:i,alt:t,title:r});const c=o.jsx(wne,{src:i,alt:t,title:r});return s.onImageOpen?o.jsx("button",{type:"button",className:"my-2 block max-w-full overflow-hidden rounded-md border border-border/20 bg-surface-2 text-left transition hover:border-border-strong focus:outline-none focus:ring-2 focus:ring-ring/45",title:r||t||"Open image",onClick:u=>{u.stopPropagation(),s.onImageOpen?.(a)},children:c},e):o.jsx("span",{className:"my-2 block max-w-full overflow-hidden rounded-md border border-border/20 bg-surface-2",children:c},e)}function Xb(e){let t=e,n="";for(;/[.,;:!?)]$/.test(t);)n=`${t.slice(-1)}${n}`,t=t.slice(0,-1);return{linkText:t,suffix:n}}function s7(e){return/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(e)}function Oy(e){const t=e.trim(),n=t.match(/^<([^>]+)>(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?$/);if(n)return{href:n[1],title:n[2]??n[3]??n[4]};const r=t.match(/^(\S+)(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?$/);return r?{href:r[1],title:r[2]??r[3]??r[4]}:null}const gk="",Sne=/\\([\\`*{}\[\]#+\-.!_|~>$])/g;function Ane(e){return e.replace(Sne,(t,n)=>`${gk}${n.charCodeAt(0).toString(16).padStart(4,"0")}`)}function i7(e){return e.replace(new RegExp(`${gk}([0-9a-f]{4})`,"g"),(t,n)=>String.fromCharCode(Number.parseInt(n,16))).replace(/\\([()])/g,"$1")}function Tne(e){const t=e.replace(/[\r\n]+/g," ");return/^ .+ $/.test(t)&&/[^ ]/.test(t.slice(1,-1))?t.slice(1,-1):t}const xk={ALLOWED_TAGS:["a","abbr","b","blockquote","br","code","del","details","div","em","i","kbd","li","mark","ol","p","pre","s","span","strong","sub","summary","sup","table","tbody","td","th","thead","tr","u","ul"],ALLOWED_ATTR:["href","title","class","id","colspan","rowspan"],ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!0};let km=null;function bk(){return km||(km=$0(()=>import("./purify.es-CC4Brkr_.js"),[]).then(e=>e.default??e).catch(e=>{throw km=null,e})),km}function yk({html:e}){const{t}=ir(),[n,r]=x.useState(null);return x.useEffect(()=>{let s=!1;return r(null),bk().then(i=>{s||r(i.sanitize(e,xk))}).catch(()=>{s||r("")}),()=>{s=!0}},[e]),n===null?o.jsx("div",{className:"py-2 text-xs text-muted-foreground",children:t("rightSidebar.renderingHtml")}):n?o.jsx("div",{className:"text-muted-foreground",dangerouslySetInnerHTML:{__html:n}}):null}function Cne({html:e}){const[t,n]=x.useState(null);return x.useEffect(()=>{let r=!1;return n(null),bk().then(s=>{r||n(s.sanitize(e,xk))}).catch(()=>{r||n("")}),()=>{r=!0}},[e]),t===null?null:t?o.jsx("span",{dangerouslySetInnerHTML:{__html:t}}):e}function vk(e){const t=e.trim().match(/^<(div|section|article|aside|table|p|ul|ol|li|blockquote|pre|figure|figcaption)\b[^>]*>/i);if(!t)return null;const n=t[1].toLowerCase();return{tag:n,selfContained:new RegExp(`</${n}>`,"i").test(e)}}let _m=null;function kne(){return _m||(_m=Promise.all([$0(()=>import("./katex-DnlPpQZa.js"),[]),$0(()=>Promise.resolve({}),__vite__mapDeps([5]))]).then(([e])=>e.default??e).catch(e=>{throw _m=null,e})),_m}function Zh({tex:e,display:t=!1}){const[n,r]=x.useState(null),[s,i]=x.useState(!1);if(x.useEffect(()=>{let c=!1;return r(null),i(!1),kne().then(u=>{c||r(u.renderToString(e,{displayMode:t,throwOnError:!1,trust:!1,strict:"ignore"}))}).catch(()=>{c||i(!0)}),()=>{c=!0}},[t,e]),s)return o.jsx("code",{className:"rounded bg-surface-2 px-1 py-0.5 font-mono text-[0.92em] text-foreground",children:t?`$$${e}$$`:`$${e}$`});if(!n)return o.jsx("span",{className:"text-muted-foreground/70",children:t?"Rendering formula...":e});const a=t?"my-2 overflow-auto rounded-md bg-surface-2 px-3 py-2 text-center":"inline-block align-middle";return o.jsx("span",{className:a,dangerouslySetInnerHTML:{__html:n}})}function _ne(e,t,n){if(/^<br\s*\/?>$/i.test(e))return o.jsx("br",{},t);const r=e.match(/^<(kbd|mark|sub|sup)>(.*?)<\/\1>$/i);if(!r)return/^<(a|abbr|span|b|strong|em|i|u|s|del|code)\b[\s\S]*<\/\1>$/i.test(e)?o.jsx(Cne,{html:e},t):null;const s=r[1].toLowerCase(),i=io(r[2],`${t}-${s}`,!0,n);return s==="kbd"?o.jsx("kbd",{className:"rounded border border-border/30 bg-surface-2 px-1.5 py-0.5 font-mono text-[0.85em] text-foreground shadow-sm",children:i},t):s==="mark"?o.jsx("mark",{className:"rounded bg-warning/25 px-0.5 text-foreground",children:i},t):s==="sub"?o.jsx("sub",{children:i},t):o.jsx("sup",{children:i},t)}function io(e,t,n=!0,r){const s=Ane(e),i=/(\\\([^)]*\\\)|\$[^$\n]+\$|<br\s*\/?>|<(?:a|abbr|span|b|strong|em|i|u|s|del|code|kbd|mark|sub|sup)\b[\s\S]*?<\/(?:a|abbr|span|b|strong|em|i|u|s|del|code|kbd|mark|sub|sup)>|!?\[[^\]]*\]\((?:<[^>]+>|(?:[^\s()]+|\([^()\s]*\))+)(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\)|!?\[[^\]]+\]\[[^\]]*\]|!?\[[^\]]+\]|\[\^[^\]]+\]|(`+)([\s\S]*?)\2|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|\*[^*\s][^*]*\*|_[^_\s][^_]*_|<https?:\/\/[^>\s]+>|<[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+>|https?:\/\/[^\s<]+|www\.[^\s<]+|[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+)/gi,a=[];let c=0,u;for(;(u=i.exec(s))!==null;){u.index>c&&a.push(i7(s.slice(c,u.index)));const f=u[0],p=`${t}-${u.index}`,g=f.startsWith("<")?_ne(f,p,r):null;if(g)a.push(g);else if(f.startsWith("\\(")&&f.endsWith("\\)"))a.push(o.jsx(Zh,{tex:f.slice(2,-2)},p));else if(f.startsWith("$")&&f.endsWith("$"))a.push(o.jsx(Zh,{tex:f.slice(1,-1)},p));else if(f.startsWith("`")){const y=f.match(/^`+/)?.[0].length??1;a.push(o.jsx("code",{className:`${n?"break-all":"whitespace-nowrap"} rounded bg-surface-2 px-1 py-0.5 font-mono text-[0.92em] text-foreground`,children:Tne(f.slice(y,-y))},p))}else if(f.startsWith("~~"))a.push(o.jsx("del",{className:"text-muted-foreground decoration-border-strong",children:io(f.slice(2,-2),`${p}-del`,n,r)},p));else if(f.startsWith("**")||f.startsWith("__"))a.push(o.jsx("strong",{className:"font-semibold text-foreground",children:io(f.slice(2,-2),`${p}-strong`,n,r)},p));else if(f.startsWith("*")||f.startsWith("_"))a.push(o.jsx("em",{className:"italic",children:io(f.slice(1,-1),`${p}-em`,n,r)},p));else if(f.startsWith("![")){const y=f.match(/^!\[([^\]]*)\]\((.*)\)$/),v=f.match(/^!\[([^\]]+)\]\[([^\]]*)\]$/),S=f.match(/^!\[([^\]]+)\]$/);if(y){const A=Oy(y[2]);a.push(A?Yb(p,y[1],A.href,A.title,r):f)}else if(v){const A=v[2]||v[1],C=r.referenceDefinitions.get(ig(A));a.push(C?Yb(p,v[1],C.href,C.title,r):f)}else if(S){const A=r.referenceDefinitions.get(ig(S[1]));a.push(A?Yb(p,S[1],A.href,A.title,r):f)}else a.push(f)}else if(f.startsWith("[^")){const y=fk(f.slice(2,-1)),v=r.footnoteDefinitions.get(y);a.push(v?o.jsx("sup",{id:`fnref-${v.id}`,title:v.text,className:"ml-0.5 rounded bg-surface-2 px-1 text-[0.72em] font-semibold text-primary",children:o.jsx("a",{href:`#fn-${v.id}`,className:"text-primary no-underline",children:v.index})},p):f)}else if(f.startsWith("<http")){const y=f.slice(1,-1);a.push(o.jsx("a",{href:y,target:"_blank",rel:"noreferrer",className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p))}else if(f.startsWith("<")&&f.endsWith(">")&&s7(f.slice(1,-1))){const y=f.slice(1,-1);a.push(o.jsx("a",{href:`mailto:${y}`,className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p))}else if(s7(Xb(f).linkText)){const{linkText:y,suffix:v}=Xb(f);a.push(o.jsx("a",{href:`mailto:${y}`,className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p)),v&&a.push(v)}else if(f.startsWith("http")||f.startsWith("www.")){const{linkText:y,suffix:v}=Xb(f),S=y.startsWith("www.")?`https://${y}`:y;a.push(o.jsx("a",{href:S,target:"_blank",rel:"noreferrer",className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p)),v&&a.push(v)}else{const y=f.match(/^\[([^\]]+)\]\((.*)\)$/),v=f.match(/^\[([^\]]+)\]\[([^\]]*)\]$/),S=f.match(/^\[([^\]]+)\]$/),A=v?v[2]||v[1]:S?.[1]??null,C=A?r.referenceDefinitions.get(ig(A)):null,L=y?Oy(y[2]):null,R=L?.href??C?.href??null,M=R?dne(R):null,B=y?.[1]??v?.[1]??S?.[1]??"";a.push(M?o.jsx("a",{href:M,title:L?.title??C?.title,target:"_blank",rel:"noreferrer",className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:io(B,`${p}-link`,n,r)},p):f)}c=i.lastIndex}return c<s.length&&a.push(i7(s.slice(c))),a.length>0?a:[e]}function wk(e){return/(?: {2,}|\\)$/.test(e)}function Sk(e){return e.replace(/(?: {2,}|\\)$/,"")}function Ug(e){return/^(?: {4}|\t)/.test(e)}function Ak(e){return e.startsWith(" ")?e.slice(1):e.replace(/^ {4}/,"")}function Tk(e,t,n){const r=[];return e.forEach((s,i)=>{const a=wk(s);r.push(...io(Sk(s),`${t}-${i}`,!0,n)),i<e.length-1&&r.push(a?o.jsx("br",{},`${t}-${i}-br`):" ")}),r}function Qy(e,t,n){const r=[],s=[];return e.forEach((i,a)=>{s.push(wk(i)),r.push(io(Sk(i),`${t}-${a}`,!0,n))}),{perLine:r,hardBreaks:s}}function $y(e,t,n,r,s){const i=[];return e.forEach((a,c)=>{const u=n[c]??0,f=!!(s&&u>=s.start&&u<=s.end);i.push(o.jsx("span",{"data-md-ref-start":u,"data-md-ref-end":u,"data-selected":f?"true":void 0,children:a},`${r}-ref-${c}`)),c<e.length-1&&i.push(t[c]?o.jsx("br",{},`${r}-${c}-br`):" ")}),i}function Jh(e){const t=e.trim().replace(/^\|/,"").replace(/\|$/,""),n=[];let r="",s=!1,i=0,a=0;for(let c=0;c<t.length;c+=1){const u=t[c];if(s){r+=u,s=!1;continue}if(u==="\\"){s=!0;continue}if(u==="`"){const f=c;for(;c+1<t.length&&t[c+1]==="`";)c+=1;const p=c-f+1;r+="`".repeat(p),i===0?i=p:i===p&&(i=0);continue}if(i===0&&u==="["?a+=1:i===0&&u==="]"&&a>0&&(a-=1),u==="|"&&i===0&&a===0){n.push(r.trim()),r="";continue}r+=u}return s&&(r+="\\"),n.push(r.trim()),n}function Ck(e){return Jh(e).map(t=>/^:-+:$/.test(t)?"center":/^-+:$/.test(t)?"right":/^:-+$/.test(t)?"left":null)}function Gg(e){return e==="center"?"text-center":e==="right"?"text-right":"text-left"}function Wg(e){return/^\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)*\|?$/.test(e.trim())}function Lne(e,t){return e>96||e>44&&t>.35}function h5(e){return(e.match(/^\s*/)?.[0]??"").replace(/\t/g," ").length}function p5(e){const t=e.trim().match(/^([-+*]|\d+[.)])\s+(.+)$/);if(!t)return null;const n=/^\d+[.)]$/.test(t[1]);return{ordered:n,start:n?Number.parseInt(t[1],10):void 0,content:t[2]}}function kk(e,t,n,r,s,i=new Set){const a=[],c=[];let u=t;for(;u<e.length;){const f=e[u];if(s&&(zg(f)||i.has(u))){u+=1;continue}const p=p5(f),g=h5(f);if(!p){if(g>n&&c.length>0){([...c].reverse().find(A=>A.indent<g)?.item??c[c.length-1].item).paragraphs.push(f.trim());for(const A of c)A.item.lineEnd=u+1;u+=1;continue}break}if(g<n||g===n&&p.ordered!==r)break;const y={content:p.content,ordered:p.ordered,start:p.start,children:[],paragraphs:[],lineStart:u+1,lineEnd:u+1};for(;c.length>0&&c[c.length-1].indent>=g;)c.pop();const v=c[c.length-1]?.item??null;v?v.children.push(y):a.push(y),c.push({indent:g,item:y});for(const S of c)S.item.lineEnd=u+1;u+=1}return{items:a,nextIndex:u}}function m5(e,t,n,r=0){return e.map((s,i)=>{const a=s.content.match(/^\[([ xX])\]\s+(.+)$/);return{key:`item-${i}`,taskItem:!!a,refStart:s.lineStart+r,refEnd:s.lineEnd+r,content:o.jsxs(o.Fragment,{children:[a?o.jsx("input",{type:"checkbox",checked:a[1].toLowerCase()==="x",readOnly:!0,className:"mr-2 align-[-2px] accent-primary"}):null,io(a?.[2]??s.content,`li-${t}-${i}`,!0,n),s.paragraphs.length>0&&o.jsx("div",{className:"mt-1 space-y-1 text-muted-foreground",children:s.paragraphs.map((c,u)=>o.jsx("p",{children:io(c,`li-${t}-${i}-p-${u}`,!0,n)},`paragraph-${u}`))})]}),groups:Ene(s.children,`${t}-${i}`,n,r)}})}function Ene(e,t,n,r=0){const s=[];for(const i of e){const a=s[s.length-1];a&&a.ordered===i.ordered?a.items.push(i):s.push({ordered:i.ordered,items:[i]})}return s.map((i,a)=>({ordered:i.ordered,start:i.ordered?i.items[0]?.start:void 0,items:m5(i.items,`${t}-g${a}`,n,r)}))}function g5(e,t){return e.map(n=>{const r=!!(t&&n.refStart<=t.end&&n.refEnd>=t.start);return o.jsxs("li",{className:n.taskItem?"list-none":void 0,"data-md-ref-start":n.refStart,"data-md-ref-end":n.refEnd,"data-selected":r?"true":void 0,children:[n.content,n.groups.length>0&&Ine(n.groups,t)]},n.key)})}function Ine(e,t){return e.map((n,r)=>{const s=n.ordered?"ol":"ul";return o.jsx(s,{start:n.start,className:`${n.ordered?"list-decimal":"list-disc"} mt-1 space-y-0.5 pl-4 marker:text-muted-foreground/60`,children:g5(n.items,t)},`nested-${r}`)})}function Rne(e){const t=Array.from(e.footnoteDefinitions.values()).sort((n,r)=>n.index-r.index);return t.length===0?null:o.jsxs("section",{className:"mt-3 border-t border-border/20 pt-2 text-[12px] leading-5 text-muted-foreground",children:[o.jsx("div",{className:"mb-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/80",children:e.footnotesLabel}),o.jsx("ol",{className:"list-decimal space-y-1 pl-5",children:t.map(n=>o.jsxs("li",{id:`fn-${n.id}`,children:[io(n.text,`footnote-${n.id}`,!0,e)," ",o.jsx("a",{href:`#fnref-${n.id}`,className:"text-primary no-underline","aria-label":e.backToFootnoteLabel(n.index),children:"↩"})]},n.id))})]})}function Nne(e,t,n,r){const s=[];let i=0;const a=c=>r?.[c]??c+1;for(;i<e.length;){const c=e[i],u=c.trim();if(!u){i+=1;continue}if(/^<details>\s*$/i.test(u)){const L=i;let R="Details";const M=[];for(i+=1;i<e.length&&!/^<\/details>\s*$/i.test(e[i].trim());){const B=e[i].trim().match(/^<summary>(.*?)<\/summary>\s*$/i);B?R=B[1].trim()||R:M.push(e[i].trimStart()),i+=1}i<e.length&&(i+=1),s.push({kind:"static",node:o.jsxs("details",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface px-3 py-2 text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer text-sm font-semibold text-foreground",children:io(R,`${t}-details-${L}-summary`,!0,n)}),M.length>0&&o.jsx("div",{className:"mt-2 text-sm leading-6",children:Tk(M,`${t}-details-${L}`,n)})]},`${t}-details-${L}`)});continue}const f=vk(c);if(f){const L=[c],R=i;for(i+=1;i<e.length&&!f.selfContained&&!new RegExp(`</${f.tag}>`,"i").test(e[i]);)L.push(e[i]),i+=1;i<e.length&&!f.selfContained&&(L.push(e[i]),i+=1),s.push({kind:"static",node:o.jsx(yk,{html:L.join(`
183
+ `);const y=s.length;s+=p.data,r.push({node:p,start:y,end:s.length,group:g}),i=g}const c=s.toLocaleLowerCase(),u=[];let f=0;for(;f<=c.length-n.length;){const p=c.indexOf(n,f);if(p<0)break;const g=p+n.length,y=r.find(S=>S.start<=p&&S.end>p),v=r.find(S=>S.start<g&&S.end>=g);if(y&&v&&y.group===v.group){const S=document.createRange();S.setStart(y.node,p-y.start),S.setEnd(v.node,g-v.start),u.push(S)}f=p+Math.max(n.length,1)}return u}function WC(){return typeof CSS<"u"&&CSS.highlights?CSS.highlights:null}function Cm(){const e=WC();e?.delete(GC),e?.delete(Ny)}function $S(e,t){const n=WC();if(!n||typeof Highlight>"u")return;n.set(GC,new Highlight(...e));const r=e[t];r?n.set(Ny,new Highlight(r)):n.delete(Ny)}function HS(e){e?.startContainer.parentElement?.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}function Ete(e){return Array.from(new Set(e.split(/[\n,]/).map(t=>t.trim().replace(/^!+/,"")).filter(Boolean))).slice(0,24)}function Ite(e,t){const n=t.trim();return!n||n==="."?e:/^(?:[/\\]|[A-Za-z]:[/\\])/.test(n)?n.replace(/[\\/]+$/,""):`${e.replace(/[\\/]+$/,"")}/${n.replace(/^\.?[\\/]+/,"").replace(/[\\/]+$/,"")}`}function Rte(e,t){if(t===e)return".";const n=`${e.replace(/[\\/]+$/,"")}/`;return t.startsWith(n)?t.slice(n.length):t}function Nte(e,t,n){return t?e:Ni.createPortal(e,n)}const c5="termdock:right-sidebar:file-tree-scroll:v1",u5="termdock:right-sidebar:file-preview-reading-state:v1",xh="termdock:right-sidebar:file-tree-width:v1",VC="termdock:right-sidebar:markdown-view-mode:v1",qC="termdock:right-sidebar:diff-change-list-mode:v1",KC="termdock:right-sidebar:diff-wrap:v1",YC="termdock:diff-viewer:view-type:v1",XC="termdock:right-sidebar:file-search-mode:v1",zb="termdock:right-sidebar:collapsed-git-repo-groups:v1",zS="termdock:right-sidebar:collapsed-diff-directories:v1",Ub="termdock:right-sidebar:branch-audit-module-open:v1",ZC="termdock:right-sidebar:branch-audit-module:v1",Mte=150,JC="termdock:right-sidebar:active-git-repo:v1",US="termdock:right-sidebar:context-draft-enabled:v1",GS="termdock:right-sidebar:context-draft-collapsed:v1",WS="termdock:right-sidebar:context-draft-auto-collapse:v1",Gb="termdock:right-sidebar:context-draft-text:v1",Dte=300,jte=20,Pte=120,Bte=250,Fte=250,Ote=120,Qte=700,Wb=600,VS=[2e3,5e3,15e3,3e4],$te=320,Hte=500,zte=20,Ute=12e3,My=300,qS=240,Gte=560,ek="border-r px-2 py-1.5 sm:px-3 sm:py-2",Hg="max-w-[18rem] whitespace-normal break-words sm:max-w-[27rem]",tk=`${ek} border-b border-border/15 font-semibold last:border-r-0`,nk=`${ek} border-border/10 align-top text-muted-foreground last:border-r-0`,d5="termdock-file-preview-horizontal-scroll",KS=x.lazy(()=>$0(()=>import("./ModelPreview-BzNON-7A.js"),__vite__mapDeps([2,3,1,4]))),rk=`${d5} termdock-md-table-scroll max-w-full overflow-x-auto overflow-y-hidden rounded-lg border border-border/20 bg-surface`;function Wte(e,t,n){return e&&!t?"unified":n}const Vte=new Set([".md",".markdown",".mdown",".mkdn",".mkd"]);function qte(e){return e==="preview"||e==="source"}function Kte(e){return e==="list"||e==="tree"||e==="ai"}function YS(){return Gr(VC,qte)??"preview"}function Yte(){return Gr(qC,Kte)??"tree"}function bh(e){return typeof e=="boolean"}function Xte(e){return typeof e=="string"}function Zte(){return Gr(KC,bh)??!0}function Jte(e){return e==="unified"||e==="split"}function ene(){return Gr(YC,Jte)??"unified"}function tne(e){return e==="name"||e==="content"||e==="regex"}function nne(){return Gr(XC,tne)??"name"}function sk(e){return e.repositories??(e.context?.root?[{id:e.context.root,root:e.context.root,relativeRoot:".",name:Jo(e.context.root)||e.context.root,depth:0,nested:!1,available:e.available,files:e.files,context:e.context,error:e.error}]:[])}function rne(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>t===null||typeof t=="string")}function ik(){return Gr(JC,rne)??{}}function XS(e){if(!e)return;const t=ik();return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0}function Vb(e,t){e&&Wn(JC,{...ik(),[e]:t})}function sne(e,t){if(!t)return null;const n=new Set((e.repoFilters??[]).map(r=>r.root));return n.has(t)?t:n.size>0?null:(e.repositories??[]).some(r=>r.root===t)?t:null}function Dy(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function ZS(e){const t=Gr(e,Dy);return t?new Set(t):new Set}function qb(e,t){Wn(e,[...t])}function ine(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.filePath=="string"&&typeof t.hunkHeader=="string"&&typeof t.hunkIndex=="number"&&typeof t.fingerprint=="string"&&typeof t.additions=="number"&&typeof t.deletions=="number"&&typeof t.diff=="string"&&(t.oldPath===void 0||t.oldPath===null||typeof t.oldPath=="string")&&(t.newPath===void 0||t.newPath===null||typeof t.newPath=="string")&&(t.source===void 0||t.source==="committed"||t.source==="uncommitted"||t.source==="unknown")&&(t.commit===void 0||t.commit===null||typeof t.commit=="string")}function one(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.available=="boolean"&&(t.repoRoot===void 0||typeof t.repoRoot=="string")&&(t.workspaceRoot===void 0||typeof t.workspaceRoot=="string")&&(t.baseRef===void 0||typeof t.baseRef=="string")&&(t.baseBranch===void 0||typeof t.baseBranch=="string")&&(t.currentBranch===void 0||t.currentBranch===null||typeof t.currentBranch=="string")&&(t.headRef===void 0||t.headRef===null||typeof t.headRef=="string")&&(t.diffFingerprint===void 0||typeof t.diffFingerprint=="string")&&(t.stat===void 0||typeof t.stat=="string")&&(t.files===void 0||Dy(t.files))&&(t.hunks===void 0||Array.isArray(t.hunks)&&t.hunks.every(ine))&&(t.commits===void 0||Dy(t.commits))&&(t.commitCount===void 0||typeof t.commitCount=="number")&&(t.diff===void 0||typeof t.diff=="string")&&(t.truncated===void 0||typeof t.truncated=="boolean")&&(t.error===void 0||typeof t.error=="string")}function ane(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.key=="string"&&one(t.diff)&&typeof t.repoLabel=="string"&&typeof t.createdAt=="number"}function lne(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;const n=t;return Array.isArray(n.selectedRepoRoots)&&n.selectedRepoRoots.every(r=>typeof r=="string")&&!!n.repoTargetBranches&&typeof n.repoTargetBranches=="object"&&!Array.isArray(n.repoTargetBranches)&&Object.values(n.repoTargetBranches).every(r=>typeof r=="string")&&(n.repoBaseBranches===void 0||!!n.repoBaseBranches&&typeof n.repoBaseBranches=="object"&&!Array.isArray(n.repoBaseBranches)&&Object.values(n.repoBaseBranches).every(r=>typeof r=="string"))&&(n.previewEntries===void 0||Array.isArray(n.previewEntries)&&n.previewEntries.every(ane))&&(n.selectedPreviewKey===void 0||n.selectedPreviewKey===null||typeof n.selectedPreviewKey=="string")&&(n.selectedPreviewFileKey===void 0||n.selectedPreviewFileKey===null||typeof n.selectedPreviewFileKey=="string")&&(n.previewDetailOpen===void 0||typeof n.previewDetailOpen=="boolean")&&(n.previewScrollTops===void 0||!!n.previewScrollTops&&typeof n.previewScrollTops=="object"&&!Array.isArray(n.previewScrollTops)&&Object.values(n.previewScrollTops).every(r=>typeof r=="number"))&&(n.previewMobileSlideIndex===void 0||typeof n.previewMobileSlideIndex=="number")&&(n.includeUncommitted===void 0||typeof n.includeUncommitted=="boolean")&&typeof n.updatedAt=="number"})}function JS(){return Gr(ZC,lne)??{}}function e7(e){return[e.repoRoot,e.baseRef,e.branchName??"",e.headRef??"",e.diffFingerprint??""].join("\0")}function t7(e){const t=e?.trim()??"",n=t.indexOf("/");return n>=0?t.slice(n+1):t}function ok(e,t){const n=e?.trim(),r=t?.trim();return!n||!r?!1:n===r||t7(n)===t7(r)}function n7(e){const t=e?.branch??null;return[e?.upstream,...e?.remoteBranches??[],...e?.branches??[]].find(r=>r&&!ok(r,t))??""}function jy(e,t){const n=Math.max(qS,t-320),r=Math.min(Gte,n);return Math.min(r,Math.max(qS,e))}function cne(e){return typeof e=="number"&&Number.isFinite(e)}function une(e){return jy(Gr(xh,cne)??My,e)}function ak(e){const t=e.split(/[\\/]/).pop()??e,n=t.lastIndexOf(".");return n>=0?t.slice(n).toLowerCase():""}function nh(e){return Vte.has(ak(e))}function lk(e){const t=e.trim().replace(/\s+/g,"");return/^-{3,}$/.test(t)||/^\*{3,}$/.test(t)||/^_{3,}$/.test(t)}function Py(e){const t=e.trim();return/^#{1,6}\s+/.test(t)||lk(e)||/^>\s?/.test(t)||/^(```|~~~)/.test(t)||/^(?:[-+*]|\d+[.)])\s+/.test(t)}function dne(e){const t=e.trim();return/^(https?:|mailto:|#|\/|\.\/|\.\.\/)/i.test(t)||!/^[a-z][a-z0-9+.-]*:/i.test(t)&&!/[<>]/.test(t)?t:null}const ck=x.createContext(null);function ig(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function uk(e){return e.replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1").replace(/[`*_~]/g,"").replace(/<[^>]+>/g,"").trim()}function dk(e){return e.replace(/\s+#+\s*$/,"").trim()}function By(e,t){const r=uk(e).toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu,"").trim().replace(/\s+/g,"-")||"section",s=t.headingSlugCounts.get(r)??0;return t.headingSlugCounts.set(r,s+1),s===0?r:`${r}-${s}`}function r7(e){return uk(e)||e.trim()}function zg(e){const t=e.match(/^\s{0,3}\[([^\]]+)\]:\s+(.+?)\s*$/);if(!t)return null;const n=Oy(t[2]);return n?{id:ig(t[1]),definition:{href:n.href,title:n.title}}:null}function fne(e){const t=new Map;for(const n of e){const r=zg(n);r&&t.set(r.id,r.definition)}return t}function fk(e){return e.trim().toLowerCase()}function hk(e){const t=e.match(/^\s{0,3}\[\^([^\]]+)\]:\s+(.+)\s*$/);return t?{id:fk(t[1]),text:t[2]}:null}function hne(e){const t=new Map;let n=null;for(const r of e){const s=hk(r);if(s){n=s.id,t.set(s.id,{id:s.id,text:s.text,index:t.size+1});continue}if(n&&/^\s{4,}\S/.test(r)){const i=t.get(n);i&&(i.text=`${i.text} ${r.trim()}`);continue}r.trim()&&(n=null)}return t}function pne(e){const t=new Set;let n=!1;return e.forEach((r,s)=>{if(hk(r)){t.add(s),n=!0;return}if(n&&/^\s{4,}\S/.test(r)){t.add(s);return}r.trim()&&(n=!1)}),t}function mne(e){const t=[...e];let n=0;const r=e[0]?.trim();if(r==="---"||r==="+++"){for(t[0]="",n=1;n<e.length&&e[n].trim()!==r;)t[n]="",n+=1;n<e.length&&(t[n]="",n+=1)}for(;n<e.length;){const s=e[n].trim();if(s.startsWith("<!--")){if(t[n]="",!s.includes("-->")){for(n+=1;n<e.length&&!e[n].includes("-->");)t[n]="",n+=1;n<e.length&&(t[n]="")}n+=1;continue}n+=1}return t}function pk(e){const t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");return n<=0?n===0?"/":"":t.slice(0,n)}function Rh(e){const t=e.split(/[?#]/,1)[0],n=t.startsWith("/"),r=[];for(const i of t.split("/"))if(!(!i||i===".")){if(i===".."){r.length>0&&r.pop();continue}r.push(i)}return`${n?"/":""}${r.join("/")}`||(n?"/":".")}function gne(e,t,n){const r=e.trim();if(!r||/^(?:https?:|mailto:|javascript:|data:|#)/i.test(r)||/^[a-z][a-z0-9+.-]*:/i.test(r))return null;const s=r.indexOf("#"),i=s>=0?r.slice(0,s):r,a=s>=0?r.slice(s+1):"",c=i.split("?",1)[0];if(!c)return null;let u,f=null;try{u=decodeURIComponent(c),f=a?decodeURIComponent(a):null}catch{return null}const p=n?Rh(n):null;let g;if(u.startsWith("/")){const y=p&&(u===p||u.startsWith(`${p}/`));g=Rh(p&&!y?`${p}/${u.slice(1)}`:u)}else{if(!t)return null;g=Rh(`${pk(t)}/${u}`)}return p&&g!==p&&!g.startsWith(`${p}/`)?null:{path:g,fragment:f,directory:/\/$/.test(c)}}function xne(e,t,n){const r=e.trim();if(!r||/^(?:javascript|data):/i.test(r))return null;if(/^https?:\/\//i.test(r))return r;if(!Xy(r.split(/[?#]/,1)[0]))return null;let s;if(r.startsWith("/")){const i=n&&(r===n||r.startsWith(`${n}/`));s=Rh(n&&!i?`${n}/${r.slice(1)}`:r)}else{if(!t)return null;s=Rh(`${pk(t)}/${r}`)}return`/api/terminal/fs/blob?path=${encodeURIComponent(s)}`}const Fy=128,bne=360,Kb=480;function f5(e){try{return/\.svg(?=$|[?#&])/i.test(decodeURIComponent(e))}catch{return!1}}function yne(e,t,n,r){if(!t||!n)return null;let s,i;return f5(e)?(i=Math.min(Math.max(n,Fy),bne),s=t*i/n):(s=t,i=n),r>0&&s>r&&(i=i*r/s,s=r),i>Kb&&(s=s*Kb/i,i=Kb),{width:Math.max(1,Math.round(s)),height:Math.max(1,Math.round(i))}}function vne(e){if(!e.startsWith("/api/terminal/fs/blob?"))return null;try{return new URLSearchParams(e.slice(e.indexOf("?"))).get("path")}catch{return null}}function mk(e){const t=vne(e),n=ht(r=>t?(r.fileChangeVersions.get(t)??0)+r.fileWatchEpoch:0);return t&&n>0?`${e}&v=${n}`:e}function wne({src:e,alt:t,title:n}){const r=f5(e),s=mk(e),i=x.useRef(null),[a,c]=x.useState(!1),[u,f]=x.useState(0),[p,g]=x.useState({status:"loading"}),[y,v]=x.useState(null);x.useLayoutEffect(()=>{const C=i.current,L=C?.parentElement?.parentElement??C?.parentElement;if(!L)return;const R=()=>f(L.clientWidth);if(R(),typeof ResizeObserver>"u")return;const M=new ResizeObserver(R);return M.observe(L),()=>M.disconnect()},[]),x.useEffect(()=>{if(a)return;const C=i.current;if(!C||typeof IntersectionObserver>"u"){c(!0);return}const L=new IntersectionObserver(R=>{R.some(M=>M.isIntersecting)&&(c(!0),L.disconnect())},{rootMargin:"400px"});return L.observe(C),()=>L.disconnect()},[a]),x.useEffect(()=>{if(!a)return;const C=new AbortController;let L=null;g({status:"loading"});const R=window.setTimeout(()=>{C.abort(new DOMException("Image fetch timed out","TimeoutError"))},15e3);return fetch(s,{signal:C.signal}).then(async M=>{if(!M.ok)throw new Error(`HTTP ${M.status}`);const B=Number(M.headers.get("X-Image-Width"))||0,F=Number(M.headers.get("X-Image-Height"))||0;return{blob:await M.blob(),width:B,height:F}}).then(({blob:M,width:B,height:F})=>{C.signal.aborted||(L=URL.createObjectURL(M),B>0&&F>0&&v({width:B,height:F}),g({status:"ready",objectUrl:L}))}).catch(()=>{const M=C.signal.reason;C.signal.aborted&&!(M instanceof DOMException&&M.name==="TimeoutError")||g({status:"fallback"})}).finally(()=>{window.clearTimeout(R)}),()=>{window.clearTimeout(R),C.abort(),L&&URL.revokeObjectURL(L)}},[a,s]);const S=yne(e,y?.width??0,y?.height??0,u),A=S??{width:Fy*2,height:Fy};return o.jsx("div",{ref:i,className:"block max-w-full",style:S?{width:S.width,height:S.height}:void 0,children:p.status==="ready"?o.jsx("img",{src:p.objectUrl,alt:t,title:n,decoding:"async",className:`${r?"":"termdock-fade-in "}block max-h-[480px] max-w-full object-contain`,style:S?{width:S.width,height:S.height}:void 0,onLoad:C=>{if(y)return;const L=C.currentTarget;L.naturalWidth>0&&L.naturalHeight>0&&v({width:L.naturalWidth,height:L.naturalHeight})}}):p.status==="fallback"?o.jsx("img",{src:s,alt:t,title:n,loading:"lazy",decoding:"async",className:"block max-h-[480px] max-w-full object-contain",style:S?{width:S.width,height:S.height}:void 0,onLoad:C=>{if(y)return;const L=C.currentTarget;L.naturalWidth>0&&L.naturalHeight>0&&v({width:L.naturalWidth,height:L.naturalHeight})}}):o.jsx("div",{"aria-hidden":!0,className:"flex max-w-full animate-pulse items-center justify-center rounded bg-surface-elevated/60",style:{width:A.width,height:A.height},children:o.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:t||"…"})})})}function Yb(e,t,n,r,s){const i=xne(n,s.markdownFilePath,s.rootPath);if(!i)return`![${t}](${n})`;const a=s.images.length;s.images.push({kind:"image",src:i,alt:t,title:r});const c=o.jsx(wne,{src:i,alt:t,title:r});return s.onImageOpen?o.jsx("button",{type:"button",className:"my-2 block max-w-full overflow-hidden rounded-md border border-border/20 bg-surface-2 text-left transition hover:border-border-strong focus:outline-none focus:ring-2 focus:ring-ring/45",title:r||t||"Open image",onClick:u=>{u.stopPropagation(),s.onImageOpen?.(a)},children:c},e):o.jsx("span",{className:"my-2 block max-w-full overflow-hidden rounded-md border border-border/20 bg-surface-2",children:c},e)}function Xb(e){let t=e,n="";for(;/[.,;:!?)]$/.test(t);)n=`${t.slice(-1)}${n}`,t=t.slice(0,-1);return{linkText:t,suffix:n}}function s7(e){return/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(e)}function Oy(e){const t=e.trim(),n=t.match(/^<([^>]+)>(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?$/);if(n)return{href:n[1],title:n[2]??n[3]??n[4]};const r=t.match(/^(\S+)(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?$/);return r?{href:r[1],title:r[2]??r[3]??r[4]}:null}const gk="",Sne=/\\([\\`*{}\[\]#+\-.!_|~>$])/g;function Ane(e){return e.replace(Sne,(t,n)=>`${gk}${n.charCodeAt(0).toString(16).padStart(4,"0")}`)}function i7(e){return e.replace(new RegExp(`${gk}([0-9a-f]{4})`,"g"),(t,n)=>String.fromCharCode(Number.parseInt(n,16))).replace(/\\([()])/g,"$1")}function Tne(e){const t=e.replace(/[\r\n]+/g," ");return/^ .+ $/.test(t)&&/[^ ]/.test(t.slice(1,-1))?t.slice(1,-1):t}const xk={ALLOWED_TAGS:["a","abbr","b","blockquote","br","code","del","details","div","em","i","kbd","li","mark","ol","p","pre","s","span","strong","sub","summary","sup","table","tbody","td","th","thead","tr","u","ul"],ALLOWED_ATTR:["href","title","class","id","colspan","rowspan"],ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!0};let km=null;function bk(){return km||(km=$0(()=>import("./purify.es-CC4Brkr_.js"),[]).then(e=>e.default??e).catch(e=>{throw km=null,e})),km}function yk({html:e}){const{t}=ir(),[n,r]=x.useState(null);return x.useEffect(()=>{let s=!1;return r(null),bk().then(i=>{s||r(i.sanitize(e,xk))}).catch(()=>{s||r("")}),()=>{s=!0}},[e]),n===null?o.jsx("div",{className:"py-2 text-xs text-muted-foreground",children:t("rightSidebar.renderingHtml")}):n?o.jsx("div",{className:"text-muted-foreground",dangerouslySetInnerHTML:{__html:n}}):null}function Cne({html:e}){const[t,n]=x.useState(null);return x.useEffect(()=>{let r=!1;return n(null),bk().then(s=>{r||n(s.sanitize(e,xk))}).catch(()=>{r||n("")}),()=>{r=!0}},[e]),t===null?null:t?o.jsx("span",{dangerouslySetInnerHTML:{__html:t}}):e}function vk(e){const t=e.trim().match(/^<(div|section|article|aside|table|p|ul|ol|li|blockquote|pre|figure|figcaption)\b[^>]*>/i);if(!t)return null;const n=t[1].toLowerCase();return{tag:n,selfContained:new RegExp(`</${n}>`,"i").test(e)}}let _m=null;function kne(){return _m||(_m=Promise.all([$0(()=>import("./katex-DnlPpQZa.js"),[]),$0(()=>Promise.resolve({}),__vite__mapDeps([5]))]).then(([e])=>e.default??e).catch(e=>{throw _m=null,e})),_m}function Zh({tex:e,display:t=!1}){const[n,r]=x.useState(null),[s,i]=x.useState(!1);if(x.useEffect(()=>{let c=!1;return r(null),i(!1),kne().then(u=>{c||r(u.renderToString(e,{displayMode:t,throwOnError:!1,trust:!1,strict:"ignore"}))}).catch(()=>{c||i(!0)}),()=>{c=!0}},[t,e]),s)return o.jsx("code",{className:"rounded bg-surface-2 px-1 py-0.5 font-mono text-[0.92em] text-foreground",children:t?`$$${e}$$`:`$${e}$`});if(!n)return o.jsx("span",{className:"text-muted-foreground/70",children:t?"Rendering formula...":e});const a=t?"my-2 overflow-auto rounded-md bg-surface-2 px-3 py-2 text-center":"inline-block align-middle";return o.jsx("span",{className:a,dangerouslySetInnerHTML:{__html:n}})}function _ne(e,t,n){if(/^<br\s*\/?>$/i.test(e))return o.jsx("br",{},t);const r=e.match(/^<(kbd|mark|sub|sup)>(.*?)<\/\1>$/i);if(!r)return/^<(a|abbr|span|b|strong|em|i|u|s|del|code)\b[\s\S]*<\/\1>$/i.test(e)?o.jsx(Cne,{html:e},t):null;const s=r[1].toLowerCase(),i=io(r[2],`${t}-${s}`,!0,n);return s==="kbd"?o.jsx("kbd",{className:"rounded border border-border/30 bg-surface-2 px-1.5 py-0.5 font-mono text-[0.85em] text-foreground shadow-sm",children:i},t):s==="mark"?o.jsx("mark",{className:"rounded bg-warning/25 px-0.5 text-foreground",children:i},t):s==="sub"?o.jsx("sub",{children:i},t):o.jsx("sup",{children:i},t)}function io(e,t,n=!0,r){const s=Ane(e),i=/(\\\([^)]*\\\)|\$[^$\n]+\$|<br\s*\/?>|<(?:a|abbr|span|b|strong|em|i|u|s|del|code|kbd|mark|sub|sup)\b[\s\S]*?<\/(?:a|abbr|span|b|strong|em|i|u|s|del|code|kbd|mark|sub|sup)>|!?\[[^\]]*\]\((?:<[^>]+>|(?:[^\s()]+|\([^()\s]*\))+)(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\)|!?\[[^\]]+\]\[[^\]]*\]|!?\[[^\]]+\]|\[\^[^\]]+\]|(`+)([\s\S]*?)\2|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|\*[^*\s][^*]*\*|_[^_\s][^_]*_|<https?:\/\/[^>\s]+>|<[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+>|https?:\/\/[^\s<]+|www\.[^\s<]+|[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+)/gi,a=[];let c=0,u;for(;(u=i.exec(s))!==null;){u.index>c&&a.push(i7(s.slice(c,u.index)));const f=u[0],p=`${t}-${u.index}`,g=f.startsWith("<")?_ne(f,p,r):null;if(g)a.push(g);else if(f.startsWith("\\(")&&f.endsWith("\\)"))a.push(o.jsx(Zh,{tex:f.slice(2,-2)},p));else if(f.startsWith("$")&&f.endsWith("$"))a.push(o.jsx(Zh,{tex:f.slice(1,-1)},p));else if(f.startsWith("`")){const y=f.match(/^`+/)?.[0].length??1;a.push(o.jsx("code",{className:`${n?"break-all":"whitespace-nowrap"} rounded bg-surface-2 px-1 py-0.5 font-mono text-[0.92em] text-foreground`,children:Tne(f.slice(y,-y))},p))}else if(f.startsWith("~~"))a.push(o.jsx("del",{className:"text-muted-foreground decoration-border-strong",children:io(f.slice(2,-2),`${p}-del`,n,r)},p));else if(f.startsWith("**")||f.startsWith("__"))a.push(o.jsx("strong",{className:"font-semibold text-foreground",children:io(f.slice(2,-2),`${p}-strong`,n,r)},p));else if(f.startsWith("*")||f.startsWith("_"))a.push(o.jsx("em",{className:"italic",children:io(f.slice(1,-1),`${p}-em`,n,r)},p));else if(f.startsWith("![")){const y=f.match(/^!\[([^\]]*)\]\((.*)\)$/),v=f.match(/^!\[([^\]]+)\]\[([^\]]*)\]$/),S=f.match(/^!\[([^\]]+)\]$/);if(y){const A=Oy(y[2]);a.push(A?Yb(p,y[1],A.href,A.title,r):f)}else if(v){const A=v[2]||v[1],C=r.referenceDefinitions.get(ig(A));a.push(C?Yb(p,v[1],C.href,C.title,r):f)}else if(S){const A=r.referenceDefinitions.get(ig(S[1]));a.push(A?Yb(p,S[1],A.href,A.title,r):f)}else a.push(f)}else if(f.startsWith("[^")){const y=fk(f.slice(2,-1)),v=r.footnoteDefinitions.get(y);a.push(v?o.jsx("sup",{id:`fnref-${v.id}`,title:v.text,className:"ml-0.5 rounded bg-surface-2 px-1 text-[0.72em] font-semibold text-primary",children:o.jsx("a",{href:`#fn-${v.id}`,className:"text-primary no-underline",children:v.index})},p):f)}else if(f.startsWith("<http")){const y=f.slice(1,-1);a.push(o.jsx("a",{href:y,target:"_blank",rel:"noreferrer",className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p))}else if(f.startsWith("<")&&f.endsWith(">")&&s7(f.slice(1,-1))){const y=f.slice(1,-1);a.push(o.jsx("a",{href:`mailto:${y}`,className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p))}else if(s7(Xb(f).linkText)){const{linkText:y,suffix:v}=Xb(f);a.push(o.jsx("a",{href:`mailto:${y}`,className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p)),v&&a.push(v)}else if(f.startsWith("http")||f.startsWith("www.")){const{linkText:y,suffix:v}=Xb(f),S=y.startsWith("www.")?`https://${y}`:y;a.push(o.jsx("a",{href:S,target:"_blank",rel:"noreferrer",className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p)),v&&a.push(v)}else{const y=f.match(/^\[([^\]]+)\]\((.*)\)$/),v=f.match(/^\[([^\]]+)\]\[([^\]]*)\]$/),S=f.match(/^\[([^\]]+)\]$/),A=v?v[2]||v[1]:S?.[1]??null,C=A?r.referenceDefinitions.get(ig(A)):null,L=y?Oy(y[2]):null,R=L?.href??C?.href??null,M=R?dne(R):null,B=y?.[1]??v?.[1]??S?.[1]??"";a.push(M?o.jsx("a",{href:M,title:L?.title??C?.title,target:"_blank",rel:"noreferrer",className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:io(B,`${p}-link`,n,r)},p):f)}c=i.lastIndex}return c<s.length&&a.push(i7(s.slice(c))),a.length>0?a:[e]}function wk(e){return/(?: {2,}|\\)$/.test(e)}function Sk(e){return e.replace(/(?: {2,}|\\)$/,"")}function Ug(e){return/^(?: {4}|\t)/.test(e)}function Ak(e){return e.startsWith(" ")?e.slice(1):e.replace(/^ {4}/,"")}function Tk(e,t,n){const r=[];return e.forEach((s,i)=>{const a=wk(s);r.push(...io(Sk(s),`${t}-${i}`,!0,n)),i<e.length-1&&r.push(a?o.jsx("br",{},`${t}-${i}-br`):" ")}),r}function Qy(e,t,n){const r=[],s=[];return e.forEach((i,a)=>{s.push(wk(i)),r.push(io(Sk(i),`${t}-${a}`,!0,n))}),{perLine:r,hardBreaks:s}}function $y(e,t,n,r,s){const i=[];return e.forEach((a,c)=>{const u=n[c]??0,f=!!(s&&u>=s.start&&u<=s.end);i.push(o.jsx("span",{"data-md-ref-start":u,"data-md-ref-end":u,"data-selected":f?"true":void 0,children:a},`${r}-ref-${c}`)),c<e.length-1&&i.push(t[c]?o.jsx("br",{},`${r}-${c}-br`):" ")}),i}function Jh(e){const t=e.trim().replace(/^\|/,"").replace(/\|$/,""),n=[];let r="",s=!1,i=0,a=0;for(let c=0;c<t.length;c+=1){const u=t[c];if(s){r+=u,s=!1;continue}if(u==="\\"){s=!0;continue}if(u==="`"){const f=c;for(;c+1<t.length&&t[c+1]==="`";)c+=1;const p=c-f+1;r+="`".repeat(p),i===0?i=p:i===p&&(i=0);continue}if(i===0&&u==="["?a+=1:i===0&&u==="]"&&a>0&&(a-=1),u==="|"&&i===0&&a===0){n.push(r.trim()),r="";continue}r+=u}return s&&(r+="\\"),n.push(r.trim()),n}function Ck(e){return Jh(e).map(t=>/^:-+:$/.test(t)?"center":/^-+:$/.test(t)?"right":/^:-+$/.test(t)?"left":null)}function Gg(e){return e==="center"?"text-center":e==="right"?"text-right":"text-left"}function Wg(e){return/^\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)*\|?$/.test(e.trim())}function Lne(e,t){return e>96||e>44&&t>.35}function h5(e){return(e.match(/^\s*/)?.[0]??"").replace(/\t/g," ").length}function p5(e){const t=e.trim().match(/^([-+*]|\d+[.)])\s+(.+)$/);if(!t)return null;const n=/^\d+[.)]$/.test(t[1]);return{ordered:n,start:n?Number.parseInt(t[1],10):void 0,content:t[2]}}function kk(e,t,n,r,s,i=new Set){const a=[],c=[];let u=t;for(;u<e.length;){const f=e[u];if(s&&(zg(f)||i.has(u))){u+=1;continue}const p=p5(f),g=h5(f);if(!p){if(g>n&&c.length>0){([...c].reverse().find(A=>A.indent<g)?.item??c[c.length-1].item).paragraphs.push(f.trim());for(const A of c)A.item.lineEnd=u+1;u+=1;continue}break}if(g<n||g===n&&p.ordered!==r)break;const y={content:p.content,ordered:p.ordered,start:p.start,children:[],paragraphs:[],lineStart:u+1,lineEnd:u+1};for(;c.length>0&&c[c.length-1].indent>=g;)c.pop();const v=c[c.length-1]?.item??null;v?v.children.push(y):a.push(y),c.push({indent:g,item:y});for(const S of c)S.item.lineEnd=u+1;u+=1}return{items:a,nextIndex:u}}function m5(e,t,n,r=0){return e.map((s,i)=>{const a=s.content.match(/^\[([ xX])\]\s+(.+)$/);return{key:`item-${i}`,taskItem:!!a,refStart:s.lineStart+r,refEnd:s.lineEnd+r,content:o.jsxs(o.Fragment,{children:[a?o.jsx("input",{type:"checkbox",checked:a[1].toLowerCase()==="x",readOnly:!0,className:"mr-2 align-[-2px] accent-primary"}):null,io(a?.[2]??s.content,`li-${t}-${i}`,!0,n),s.paragraphs.length>0&&o.jsx("div",{className:"mt-1 space-y-1 text-muted-foreground",children:s.paragraphs.map((c,u)=>o.jsx("p",{children:io(c,`li-${t}-${i}-p-${u}`,!0,n)},`paragraph-${u}`))})]}),groups:Ene(s.children,`${t}-${i}`,n,r)}})}function Ene(e,t,n,r=0){const s=[];for(const i of e){const a=s[s.length-1];a&&a.ordered===i.ordered?a.items.push(i):s.push({ordered:i.ordered,items:[i]})}return s.map((i,a)=>({ordered:i.ordered,start:i.ordered?i.items[0]?.start:void 0,items:m5(i.items,`${t}-g${a}`,n,r)}))}function g5(e,t){return e.map(n=>{const r=!!(t&&n.refStart<=t.end&&n.refEnd>=t.start);return o.jsxs("li",{className:n.taskItem?"list-none":void 0,"data-md-ref-start":n.refStart,"data-md-ref-end":n.refEnd,"data-selected":r?"true":void 0,children:[n.content,n.groups.length>0&&Ine(n.groups,t)]},n.key)})}function Ine(e,t){return e.map((n,r)=>{const s=n.ordered?"ol":"ul";return o.jsx(s,{start:n.start,className:`${n.ordered?"list-decimal":"list-disc"} mt-1 space-y-0.5 pl-4 marker:text-muted-foreground/60`,children:g5(n.items,t)},`nested-${r}`)})}function Rne(e){const t=Array.from(e.footnoteDefinitions.values()).sort((n,r)=>n.index-r.index);return t.length===0?null:o.jsxs("section",{className:"mt-3 border-t border-border/20 pt-2 text-[12px] leading-5 text-muted-foreground",children:[o.jsx("div",{className:"mb-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/80",children:e.footnotesLabel}),o.jsx("ol",{className:"list-decimal space-y-1 pl-5",children:t.map(n=>o.jsxs("li",{id:`fn-${n.id}`,children:[io(n.text,`footnote-${n.id}`,!0,e)," ",o.jsx("a",{href:`#fnref-${n.id}`,className:"text-primary no-underline","aria-label":e.backToFootnoteLabel(n.index),children:"↩"})]},n.id))})]})}function Nne(e,t,n,r){const s=[];let i=0;const a=c=>r?.[c]??c+1;for(;i<e.length;){const c=e[i],u=c.trim();if(!u){i+=1;continue}if(/^<details>\s*$/i.test(u)){const L=i;let R="Details";const M=[];for(i+=1;i<e.length&&!/^<\/details>\s*$/i.test(e[i].trim());){const B=e[i].trim().match(/^<summary>(.*?)<\/summary>\s*$/i);B?R=B[1].trim()||R:M.push(e[i].trimStart()),i+=1}i<e.length&&(i+=1),s.push({kind:"static",node:o.jsxs("details",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface px-3 py-2 text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer text-sm font-semibold text-foreground",children:io(R,`${t}-details-${L}-summary`,!0,n)}),M.length>0&&o.jsx("div",{className:"mt-2 text-sm leading-6",children:Tk(M,`${t}-details-${L}`,n)})]},`${t}-details-${L}`)});continue}const f=vk(c);if(f){const L=[c],R=i;for(i+=1;i<e.length&&!f.selfContained&&!new RegExp(`</${f.tag}>`,"i").test(e[i]);)L.push(e[i]),i+=1;i<e.length&&!f.selfContained&&(L.push(e[i]),i+=1),s.push({kind:"static",node:o.jsx(yk,{html:L.join(`
184
184
  `)},`${t}-html-${R}`)});continue}const p=u.match(/^(```|~~~)\s*(.*)$/);if(p){const L=[],R=p[1],M=p[2]?.trim(),B=i;for(i+=1;i<e.length&&!e[i].trim().startsWith(R);)L.push(e[i]),i+=1;i<e.length&&(i+=1),M.toLowerCase()==="mermaid"?s.push({kind:"static",node:o.jsx(Lk,{code:L.join(`
185
185
  `),blockKey:`${t}-code-${B}`},`${t}-code-${B}`)}):["math","latex","tex"].includes(M.toLowerCase())?s.push({kind:"static",node:o.jsx(Zh,{tex:L.join(`
186
186
  `),display:!0},`${t}-code-${B}`)}):s.push({kind:"code",key:`${t}-code-${B}`,code:L.join(`
187
187
  `),lang:M,blockKey:`${t}-code-${B}`,codeStartLine:a(B)+1});continue}if(Ug(c)){const L=[],R=i;for(;i<e.length&&(Ug(e[i])||!e[i].trim());)L.push(e[i].trim()?Ak(e[i]):""),i+=1;s.push({kind:"code",key:`${t}-indented-code-${R}`,code:L.join(`
188
- `).replace(/\n+$/,""),lang:"",blockKey:`${t}-indented-code-${R}`,codeStartLine:a(R)});continue}const g=u.match(/^(#{1,6})\s+(.+)$/);if(g){const R=`h${Math.min(6,g[1].length+1)}`,M=dk(g[2]),B=By(M,n);s.push({kind:"static",node:o.jsx(R,{id:B,className:"scroll-mt-16 font-semibold text-foreground",children:io(M,`${t}-heading-${i}`,!0,n)},`${t}-heading-${i}`)}),i+=1;continue}if(i+1<e.length&&c.includes("|")&&Wg(e[i+1])){const L=Jh(c),R=Ck(e[i+1]),M=[],B=i;for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim();)M.push(Jh(e[i])),i+=1;s.push({kind:"static",node:o.jsx("div",{className:rk,"data-markdown-table-scroll":!0,children:o.jsxs("table",{className:"w-max min-w-full max-w-none table-auto border-collapse text-left text-[11px] sm:text-xs",children:[o.jsx("thead",{className:"bg-surface-2 text-foreground",children:o.jsx("tr",{children:L.map((F,N)=>o.jsx("th",{className:`${tk} ${Gg(R[N]??null)}`,children:o.jsx("div",{className:Hg,children:io(F,`${t}-th-${B}-${N}`,!0,n)})},`h-${N}`))})}),o.jsx("tbody",{children:M.map((F,N)=>o.jsx("tr",{className:"border-t border-border/10",children:L.map((T,$)=>o.jsx("td",{className:`${nk} ${Gg(R[$]??null)}`,children:o.jsx("div",{className:Hg,children:io(F[$]??"",`${t}-td-${B}-${N}-${$}`,!0,n)})},`c-${$}`))},`r-${N}`))})]})},`${t}-table-${B}`)});continue}const y=p5(c);if(y){const L=y.ordered,R=h5(c),M=y.start,B=i,F=kk(e,i,R,L,!1);i=F.nextIndex,s.push({kind:"list",keyPrefix:`${t}-list-${B}`,ordered:L,start:L?M:void 0,renders:m5(F.items,`${t}-list-${B}`,n,a(0)-1)});continue}const v=[c.trimStart()],S=[a(i)],A=i;for(i+=1;i<e.length&&e[i].trim()&&!Py(e[i])&&!(i+1<e.length&&e[i].includes("|")&&Wg(e[i+1]));)v.push(e[i].trimStart()),S.push(a(i)),i+=1;const C=Qy(v,`${t}-p-${A}`,n);s.push({kind:"paragraph",keyPrefix:`${t}-p-${A}`,perLine:C.perLine,hardBreaks:C.hardBreaks,lineNums:S})}return s}function Mne(e,t){return e.map(n=>{switch(n.kind){case"static":return n.node;case"paragraph":return o.jsx("p",{children:$y(n.perLine,n.hardBreaks,n.lineNums,n.keyPrefix,t)},n.keyPrefix);case"list":{const r=n.ordered?"ol":"ul";return o.jsx(r,{start:n.start,className:`${n.ordered?"list-decimal":"list-disc"} space-y-0.5 pl-4 marker:text-muted-foreground/70`,children:g5(n.renders,t)},n.keyPrefix)}case"code":return o.jsx(Vg,{code:n.code,lang:n.lang,blockKey:n.blockKey,codeStartLine:n.codeStartLine,lineRange:t},n.key)}})}let Lm=null,o7=!1;const Em=16,_k=192;function Dne(){return Lm||(Lm=$0(()=>import("./mermaid.core-gG9bkaTg.js").then(e=>e.aJ),__vite__mapDeps([6,1,7])).then(e=>e.default??e).catch(e=>{throw Lm=null,e})),Lm}function jne(e){o7||(e.initialize({startOnLoad:!1,securityLevel:"strict",theme:"neutral"}),o7=!0)}function Pne(e){const t=e.match(/\sviewBox=(["'])([^"']+)\1/i);if(!t)return e;const[,,n]=t,r=n.trim().split(/[\s,]+/).map(Number),[,,s,i]=r;if(!Number.isFinite(s)||!Number.isFinite(i)||s<=0||i<=0)return e;const a=Math.max(_k,Math.ceil(s)),c=Math.ceil(a/s*i);return e.replace(/<svg\b([^>]*)>/i,(u,f)=>`<svg${f.replace(/\s(?:width|height)=(["']).*?\1/gi,"").replace(/\sstyle=(["']).*?\1/gi,"")} width="${a}" height="${c}">`)}function Bne(e){const t=e?.querySelector("svg");if(!t)return;let n;try{n=t.getBBox()}catch{return}if(!Number.isFinite(n.width)||!Number.isFinite(n.height)||n.width<=0||n.height<=0)return;const r=n.x-Em,s=n.y-Em,i=n.width+Em*2,a=n.height+Em*2,c=Math.max(_k,Math.ceil(i)),u=Math.ceil(c/i*a);t.setAttribute("viewBox",`${r} ${s} ${i} ${a}`),t.setAttribute("width",String(c)),t.setAttribute("height",String(u)),t.removeAttribute("style")}function Fne(e){const t=e.trim().split(/\s+/,1)[0]?.toLowerCase();if(!t)return null;const n=t.replace(/^language-/,"");return _0(`code.${n}`)??n}function Lk({code:e,blockKey:t}){const{t:n}=ir(),[r,s]=x.useState(null),[i,a]=x.useState(!1),c=x.useRef(null),u=x.useContext(ck);x.useEffect(()=>{let p=!1;return s(null),a(!1),Dne().then(async g=>{jne(g);const y=`termdock-md-mermaid-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`,{svg:v}=await g.render(y,e);p||s(Pne(v))}).catch(()=>{p||a(!0)}),()=>{p=!0}},[t,e]),x.useLayoutEffect(()=>{r&&Bne(c.current)},[r]);const f=x.useCallback(()=>{const p=c.current?.querySelector("svg")?.outerHTML??r;p&&u?.(p)},[u,r]);return i?o.jsx(Vg,{code:e,lang:"mermaid",blockKey:`${t}-fallback`}):o.jsxs("div",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface shadow-sm",children:[o.jsx("div",{className:"border-b border-border/15 bg-surface-2 px-3 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground",children:"mermaid"}),o.jsx("div",{className:"bg-surface p-3",children:r?o.jsx("button",{type:"button",className:"block max-w-full rounded text-left focus:outline-none focus:ring-2 focus:ring-ring/45",title:n("rightSidebar.openMermaidDiagram"),onClick:p=>{p.stopPropagation(),f()},children:o.jsx("span",{ref:c,role:"img","aria-label":n("rightSidebar.mermaidDiagram"),className:"block max-h-[70vh] max-w-full overflow-auto rounded bg-white p-2 text-slate-900 [&_svg]:block [&_svg]:h-auto [&_svg]:max-w-full",dangerouslySetInnerHTML:{__html:r}})}):o.jsx("div",{className:"py-6 text-center text-xs text-muted-foreground",children:n("rightSidebar.renderingDiagram")})})]})}function Vg({code:e,lang:t,blockKey:n,codeStartLine:r,lineRange:s}){const i=Fne(t),[a,c]=x.useState(null);x.useEffect(()=>{if(!i||!AC(e)){c(null);return}let f=!1;return TC().then(p=>{if(f||!p.registered(i)){f||c(null);return}try{c(CC(p,e,i))}catch{f||c(null)}}).catch(()=>{f||c(null)}),()=>{f=!0}},[n,e,i]);const u=a??(e||" ").split(`
188
+ `).replace(/\n+$/,""),lang:"",blockKey:`${t}-indented-code-${R}`,codeStartLine:a(R)});continue}const g=u.match(/^(#{1,6})\s+(.+)$/);if(g){const R=`h${Math.min(6,g[1].length+1)}`,M=dk(g[2]),B=By(M,n);s.push({kind:"static",node:o.jsx(R,{id:B,className:"scroll-mt-16 font-semibold text-foreground",children:io(M,`${t}-heading-${i}`,!0,n)},`${t}-heading-${i}`)}),i+=1;continue}if(i+1<e.length&&c.includes("|")&&Wg(e[i+1])){const L=Jh(c),R=Ck(e[i+1]),M=[],B=i;for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim();)M.push(Jh(e[i])),i+=1;s.push({kind:"static",node:o.jsx("div",{className:rk,"data-markdown-table-scroll":!0,children:o.jsxs("table",{className:"w-max min-w-full max-w-none table-auto border-collapse text-left text-[11px] sm:text-xs",children:[o.jsx("thead",{className:"bg-surface-2 text-foreground",children:o.jsx("tr",{children:L.map((F,N)=>o.jsx("th",{className:`${tk} ${Gg(R[N]??null)}`,children:o.jsx("div",{className:Hg,children:io(F,`${t}-th-${B}-${N}`,!0,n)})},`h-${N}`))})}),o.jsx("tbody",{children:M.map((F,N)=>o.jsx("tr",{className:"border-t border-border/10",children:L.map((T,$)=>o.jsx("td",{className:`${nk} ${Gg(R[$]??null)}`,children:o.jsx("div",{className:Hg,children:io(F[$]??"",`${t}-td-${B}-${N}-${$}`,!0,n)})},`c-${$}`))},`r-${N}`))})]})},`${t}-table-${B}`)});continue}const y=p5(c);if(y){const L=y.ordered,R=h5(c),M=y.start,B=i,F=kk(e,i,R,L,!1);i=F.nextIndex,s.push({kind:"list",keyPrefix:`${t}-list-${B}`,ordered:L,start:L?M:void 0,renders:m5(F.items,`${t}-list-${B}`,n,a(0)-1)});continue}const v=[c.trimStart()],S=[a(i)],A=i;for(i+=1;i<e.length&&e[i].trim()&&!Py(e[i])&&!(i+1<e.length&&e[i].includes("|")&&Wg(e[i+1]));)v.push(e[i].trimStart()),S.push(a(i)),i+=1;const C=Qy(v,`${t}-p-${A}`,n);s.push({kind:"paragraph",keyPrefix:`${t}-p-${A}`,perLine:C.perLine,hardBreaks:C.hardBreaks,lineNums:S})}return s}function Mne(e,t){return e.map(n=>{switch(n.kind){case"static":return n.node;case"paragraph":return o.jsx("p",{children:$y(n.perLine,n.hardBreaks,n.lineNums,n.keyPrefix,t)},n.keyPrefix);case"list":{const r=n.ordered?"ol":"ul";return o.jsx(r,{start:n.start,className:`${n.ordered?"list-decimal":"list-disc"} space-y-0.5 pl-4 marker:text-muted-foreground/70`,children:g5(n.renders,t)},n.keyPrefix)}case"code":return o.jsx(Vg,{code:n.code,lang:n.lang,blockKey:n.blockKey,codeStartLine:n.codeStartLine,lineRange:t},n.key)}})}let Lm=null,o7=!1;const Em=16,_k=192;function Dne(){return Lm||(Lm=$0(()=>import("./mermaid.core-BMGv3SNm.js").then(e=>e.aJ),__vite__mapDeps([6,1,7])).then(e=>e.default??e).catch(e=>{throw Lm=null,e})),Lm}function jne(e){o7||(e.initialize({startOnLoad:!1,securityLevel:"strict",theme:"neutral"}),o7=!0)}function Pne(e){const t=e.match(/\sviewBox=(["'])([^"']+)\1/i);if(!t)return e;const[,,n]=t,r=n.trim().split(/[\s,]+/).map(Number),[,,s,i]=r;if(!Number.isFinite(s)||!Number.isFinite(i)||s<=0||i<=0)return e;const a=Math.max(_k,Math.ceil(s)),c=Math.ceil(a/s*i);return e.replace(/<svg\b([^>]*)>/i,(u,f)=>`<svg${f.replace(/\s(?:width|height)=(["']).*?\1/gi,"").replace(/\sstyle=(["']).*?\1/gi,"")} width="${a}" height="${c}">`)}function Bne(e){const t=e?.querySelector("svg");if(!t)return;let n;try{n=t.getBBox()}catch{return}if(!Number.isFinite(n.width)||!Number.isFinite(n.height)||n.width<=0||n.height<=0)return;const r=n.x-Em,s=n.y-Em,i=n.width+Em*2,a=n.height+Em*2,c=Math.max(_k,Math.ceil(i)),u=Math.ceil(c/i*a);t.setAttribute("viewBox",`${r} ${s} ${i} ${a}`),t.setAttribute("width",String(c)),t.setAttribute("height",String(u)),t.removeAttribute("style")}function Fne(e){const t=e.trim().split(/\s+/,1)[0]?.toLowerCase();if(!t)return null;const n=t.replace(/^language-/,"");return _0(`code.${n}`)??n}function Lk({code:e,blockKey:t}){const{t:n}=ir(),[r,s]=x.useState(null),[i,a]=x.useState(!1),c=x.useRef(null),u=x.useContext(ck);x.useEffect(()=>{let p=!1;return s(null),a(!1),Dne().then(async g=>{jne(g);const y=`termdock-md-mermaid-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`,{svg:v}=await g.render(y,e);p||s(Pne(v))}).catch(()=>{p||a(!0)}),()=>{p=!0}},[t,e]),x.useLayoutEffect(()=>{r&&Bne(c.current)},[r]);const f=x.useCallback(()=>{const p=c.current?.querySelector("svg")?.outerHTML??r;p&&u?.(p)},[u,r]);return i?o.jsx(Vg,{code:e,lang:"mermaid",blockKey:`${t}-fallback`}):o.jsxs("div",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface shadow-sm",children:[o.jsx("div",{className:"border-b border-border/15 bg-surface-2 px-3 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground",children:"mermaid"}),o.jsx("div",{className:"bg-surface p-3",children:r?o.jsx("button",{type:"button",className:"block max-w-full rounded text-left focus:outline-none focus:ring-2 focus:ring-ring/45",title:n("rightSidebar.openMermaidDiagram"),onClick:p=>{p.stopPropagation(),f()},children:o.jsx("span",{ref:c,role:"img","aria-label":n("rightSidebar.mermaidDiagram"),className:"block max-h-[70vh] max-w-full overflow-auto rounded bg-white p-2 text-slate-900 [&_svg]:block [&_svg]:h-auto [&_svg]:max-w-full",dangerouslySetInnerHTML:{__html:r}})}):o.jsx("div",{className:"py-6 text-center text-xs text-muted-foreground",children:n("rightSidebar.renderingDiagram")})})]})}function Vg({code:e,lang:t,blockKey:n,codeStartLine:r,lineRange:s}){const i=Fne(t),[a,c]=x.useState(null);x.useEffect(()=>{if(!i||!AC(e)){c(null);return}let f=!1;return TC().then(p=>{if(f||!p.registered(i)){f||c(null);return}try{c(CC(p,e,i))}catch{f||c(null)}}).catch(()=>{f||c(null)}),()=>{f=!0}},[n,e,i]);const u=a??(e||" ").split(`
189
189
  `).map(f=>[f||" "]);return o.jsxs("div",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface shadow-sm",children:[t&&o.jsx("div",{className:"border-b border-border/15 bg-surface-2 px-3 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground",children:t}),o.jsx("pre",{className:`${d5} termdock-code overflow-auto p-3 text-[11px] leading-relaxed text-foreground`,children:o.jsx("code",{children:u.map((f,p)=>{const g=r!=null?r+p:null,y=!!(s&&g!=null&&g>=s.start&&g<=s.end);return o.jsxs("span",{"data-md-ref-start":g??void 0,"data-md-ref-end":g??void 0,"data-selected":y?"true":void 0,children:[f,p<u.length-1?`
190
190
  `:null]},`${n}-line-${p}`)})})})]})}function One(e,t,n,r,s){e=mne(e);const i=fne(e),a=pne(e),c=[],u={markdownFilePath:t,rootPath:n,referenceDefinitions:i,footnoteDefinitions:hne(e),headingSlugCounts:new Map,images:c,onImageOpen:r,footnotesLabel:s?.footnotes??"Footnotes",backToFootnoteLabel:s?.backToFootnote??(y=>`Back to footnote ${y}`)},f=[];let p=0;for(;p<e.length;){const y=e[p],v=y.trim();if(zg(y)||a.has(p)){p+=1;continue}if(!v){p+=1;continue}if(/^<details>\s*$/i.test(v)){const N=p;let T="Details";const $=[];for(p+=1;p<e.length&&!/^<\/details>\s*$/i.test(e[p].trim());){const O=e[p].trim().match(/^<summary>(.*?)<\/summary>\s*$/i);O?T=O[1].trim()||T:$.push(e[p].trimStart()),p+=1}p<e.length&&(p+=1),f.push({key:`details-${N}`,startLine:N+1,endLine:p,content:o.jsxs("details",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface px-3 py-2 text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer text-sm font-semibold text-foreground",children:io(T,`details-${N}-summary`,!0,u)}),$.length>0&&o.jsx("div",{className:"mt-2 text-sm leading-6",children:Tk($,`details-${N}`,u)})]})});continue}const S=vk(y);if(S){const N=[y],T=p;for(p+=1;p<e.length&&!S.selfContained&&!new RegExp(`</${S.tag}>`,"i").test(e[p]);)N.push(e[p]),p+=1;p<e.length&&!S.selfContained&&(N.push(e[p]),p+=1),f.push({key:`html-${T}`,startLine:T+1,endLine:p,content:o.jsx(yk,{html:N.join(`
191
191
  `)})});continue}const A=v.match(/^(```|~~~)\s*(.*)$/);if(A){const N=[],T=A[1],$=A[2]?.trim(),O=p;for(p+=1;p<e.length&&!e[p].trim().startsWith(T);)N.push(e[p]),p+=1;p<e.length&&(p+=1),f.push({key:`code-${O}`,startLine:O+1,endLine:p,fineGrained:$.toLowerCase()!=="mermaid"&&!["math","latex","tex"].includes($.toLowerCase()),content:$.toLowerCase()==="mermaid"?o.jsx(Lk,{code:N.join(`