aicodeman 0.9.14 → 1.1.0

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 (180) hide show
  1. package/README.md +5 -5
  2. package/dist/attachment-magic.d.ts +5 -0
  3. package/dist/attachment-magic.d.ts.map +1 -0
  4. package/dist/attachment-magic.js +34 -0
  5. package/dist/attachment-magic.js.map +1 -0
  6. package/dist/attachment-registry.d.ts +72 -0
  7. package/dist/attachment-registry.d.ts.map +1 -0
  8. package/dist/attachment-registry.js +166 -0
  9. package/dist/attachment-registry.js.map +1 -0
  10. package/dist/cli.d.ts.map +1 -1
  11. package/dist/cli.js +85 -0
  12. package/dist/cli.js.map +1 -1
  13. package/dist/config/attachment-guard.d.ts +71 -0
  14. package/dist/config/attachment-guard.d.ts.map +1 -0
  15. package/dist/config/attachment-guard.js +118 -0
  16. package/dist/config/attachment-guard.js.map +1 -0
  17. package/dist/document-conversion-limiter.d.ts +27 -0
  18. package/dist/document-conversion-limiter.d.ts.map +1 -0
  19. package/dist/document-conversion-limiter.js +64 -0
  20. package/dist/document-conversion-limiter.js.map +1 -0
  21. package/dist/document-preview-cache.d.ts +15 -0
  22. package/dist/document-preview-cache.d.ts.map +1 -0
  23. package/dist/document-preview-cache.js +261 -0
  24. package/dist/document-preview-cache.js.map +1 -0
  25. package/dist/document-thumbnailer.d.ts +9 -0
  26. package/dist/document-thumbnailer.d.ts.map +1 -0
  27. package/dist/document-thumbnailer.js +70 -0
  28. package/dist/document-thumbnailer.js.map +1 -0
  29. package/dist/hooks-config.d.ts +17 -0
  30. package/dist/hooks-config.d.ts.map +1 -1
  31. package/dist/hooks-config.js +164 -73
  32. package/dist/hooks-config.js.map +1 -1
  33. package/dist/image-watcher.d.ts +6 -1
  34. package/dist/image-watcher.d.ts.map +1 -1
  35. package/dist/image-watcher.js +52 -7
  36. package/dist/image-watcher.js.map +1 -1
  37. package/dist/session-attachment-history.d.ts +19 -0
  38. package/dist/session-attachment-history.d.ts.map +1 -0
  39. package/dist/session-attachment-history.js +63 -0
  40. package/dist/session-attachment-history.js.map +1 -0
  41. package/dist/session.d.ts +11 -0
  42. package/dist/session.d.ts.map +1 -1
  43. package/dist/session.js +45 -0
  44. package/dist/session.js.map +1 -1
  45. package/dist/tmux-manager.d.ts.map +1 -1
  46. package/dist/tmux-manager.js +6 -1
  47. package/dist/tmux-manager.js.map +1 -1
  48. package/dist/types/session.d.ts +35 -0
  49. package/dist/types/session.d.ts.map +1 -1
  50. package/dist/types/session.js.map +1 -1
  51. package/dist/types/tools.d.ts +35 -1
  52. package/dist/types/tools.d.ts.map +1 -1
  53. package/dist/types/tools.js +2 -1
  54. package/dist/types/tools.js.map +1 -1
  55. package/dist/usage-telemetry.d.ts +102 -0
  56. package/dist/usage-telemetry.d.ts.map +1 -0
  57. package/dist/usage-telemetry.js +130 -0
  58. package/dist/usage-telemetry.js.map +1 -0
  59. package/dist/web/middleware/auth.d.ts.map +1 -1
  60. package/dist/web/middleware/auth.js +4 -3
  61. package/dist/web/middleware/auth.js.map +1 -1
  62. package/dist/web/plan-usage-latest.d.ts +15 -0
  63. package/dist/web/plan-usage-latest.d.ts.map +1 -0
  64. package/dist/web/plan-usage-latest.js +20 -0
  65. package/dist/web/plan-usage-latest.js.map +1 -0
  66. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  67. package/dist/web/public/app.9daf49ad.js +37 -0
  68. package/dist/web/public/app.9daf49ad.js.br +0 -0
  69. package/dist/web/public/app.9daf49ad.js.gz +0 -0
  70. package/dist/web/public/{constants.8fa1a65f.js → constants.00fa5405.js} +2 -0
  71. package/dist/web/public/constants.00fa5405.js.br +0 -0
  72. package/dist/web/public/constants.00fa5405.js.gz +0 -0
  73. package/dist/web/public/fonts/jetbrains-mono-variable.woff2 +0 -0
  74. package/dist/web/public/fonts/manrope-variable.woff2 +0 -0
  75. package/dist/web/public/image-input.0ea86695.js.gz +0 -0
  76. package/dist/web/public/index.html +59 -35
  77. package/dist/web/public/index.html.br +0 -0
  78. package/dist/web/public/index.html.gz +0 -0
  79. package/dist/web/public/input-cjk.b8686b5e.js.gz +0 -0
  80. package/dist/web/public/keyboard-accessory.bc753cc7.js.gz +0 -0
  81. package/dist/web/public/mobile-handlers.763a7439.js.gz +0 -0
  82. package/dist/web/public/mobile.06b38d3a.css +1 -0
  83. package/dist/web/public/mobile.06b38d3a.css.br +0 -0
  84. package/dist/web/public/mobile.06b38d3a.css.gz +0 -0
  85. package/dist/web/public/notification-manager.9c984ac2.js.gz +0 -0
  86. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  87. package/dist/web/public/{panels-ui.6bb3169f.js → panels-ui.2f467969.js} +141 -87
  88. package/dist/web/public/panels-ui.2f467969.js.br +0 -0
  89. package/dist/web/public/panels-ui.2f467969.js.gz +0 -0
  90. package/dist/web/public/ralph-panel.6de2d0f8.js.gz +0 -0
  91. package/dist/web/public/ralph-wizard.13a1831e.js.gz +0 -0
  92. package/dist/web/public/respawn-ui.2d249da9.js.gz +0 -0
  93. package/dist/web/public/session-ui.1463b824.js +36 -0
  94. package/dist/web/public/session-ui.1463b824.js.br +0 -0
  95. package/dist/web/public/session-ui.1463b824.js.gz +0 -0
  96. package/dist/web/public/settings-ui.44b99ce0.js +55 -0
  97. package/dist/web/public/settings-ui.44b99ce0.js.br +0 -0
  98. package/dist/web/public/settings-ui.44b99ce0.js.gz +0 -0
  99. package/dist/web/public/styles.c13845d5.css +1 -0
  100. package/dist/web/public/styles.c13845d5.css.br +0 -0
  101. package/dist/web/public/styles.c13845d5.css.gz +0 -0
  102. package/dist/web/public/subagent-windows.a366a4ad.js.gz +0 -0
  103. package/dist/web/public/sw.js.gz +0 -0
  104. package/dist/web/public/terminal-ui.5bf97f7e.js +3 -0
  105. package/dist/web/public/terminal-ui.5bf97f7e.js.br +0 -0
  106. package/dist/web/public/terminal-ui.5bf97f7e.js.gz +0 -0
  107. package/dist/web/public/upload.html.gz +0 -0
  108. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  109. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  110. package/dist/web/public/vendor/xterm-addon-serialize.min.js +2 -0
  111. package/dist/web/public/vendor/xterm-addon-serialize.min.js.br +0 -0
  112. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  113. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  114. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  115. package/dist/web/public/vendor/xterm-zerolag-input.137ad9f0.js.gz +0 -0
  116. package/dist/web/public/vendor/xterm.css.gz +0 -0
  117. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  118. package/dist/web/public/voice-input.085e9e73.js.gz +0 -0
  119. package/dist/web/routes/file-routes.d.ts +2 -2
  120. package/dist/web/routes/file-routes.d.ts.map +1 -1
  121. package/dist/web/routes/file-routes.js +457 -17
  122. package/dist/web/routes/file-routes.js.map +1 -1
  123. package/dist/web/routes/index.d.ts +1 -0
  124. package/dist/web/routes/index.d.ts.map +1 -1
  125. package/dist/web/routes/index.js +1 -0
  126. package/dist/web/routes/index.js.map +1 -1
  127. package/dist/web/routes/session-routes.d.ts.map +1 -1
  128. package/dist/web/routes/session-routes.js +31 -2
  129. package/dist/web/routes/session-routes.js.map +1 -1
  130. package/dist/web/routes/status-telemetry-routes.d.ts +17 -0
  131. package/dist/web/routes/status-telemetry-routes.d.ts.map +1 -0
  132. package/dist/web/routes/status-telemetry-routes.js +57 -0
  133. package/dist/web/routes/status-telemetry-routes.js.map +1 -0
  134. package/dist/web/routes/system-routes.d.ts.map +1 -1
  135. package/dist/web/routes/system-routes.js +21 -1
  136. package/dist/web/routes/system-routes.js.map +1 -1
  137. package/dist/web/schemas.d.ts +30 -1
  138. package/dist/web/schemas.d.ts.map +1 -1
  139. package/dist/web/schemas.js +52 -0
  140. package/dist/web/schemas.js.map +1 -1
  141. package/dist/web/sensitive-path.d.ts +24 -0
  142. package/dist/web/sensitive-path.d.ts.map +1 -0
  143. package/dist/web/sensitive-path.js +39 -0
  144. package/dist/web/sensitive-path.js.map +1 -0
  145. package/dist/web/server.d.ts +13 -0
  146. package/dist/web/server.d.ts.map +1 -1
  147. package/dist/web/server.js +77 -2
  148. package/dist/web/server.js.map +1 -1
  149. package/dist/web/session-listener-wiring.d.ts +5 -1
  150. package/dist/web/session-listener-wiring.d.ts.map +1 -1
  151. package/dist/web/session-listener-wiring.js +9 -1
  152. package/dist/web/session-listener-wiring.js.map +1 -1
  153. package/dist/web/sse-events.d.ts +6 -0
  154. package/dist/web/sse-events.d.ts.map +1 -1
  155. package/dist/web/sse-events.js +6 -0
  156. package/dist/web/sse-events.js.map +1 -1
  157. package/package.json +2 -1
  158. package/scripts/postinstall.js +3 -0
  159. package/dist/web/public/app.a23f8bf6.js +0 -35
  160. package/dist/web/public/app.a23f8bf6.js.br +0 -0
  161. package/dist/web/public/app.a23f8bf6.js.gz +0 -0
  162. package/dist/web/public/constants.8fa1a65f.js.br +0 -0
  163. package/dist/web/public/constants.8fa1a65f.js.gz +0 -0
  164. package/dist/web/public/mobile.c7513aed.css +0 -1
  165. package/dist/web/public/mobile.c7513aed.css.br +0 -0
  166. package/dist/web/public/mobile.c7513aed.css.gz +0 -0
  167. package/dist/web/public/panels-ui.6bb3169f.js.br +0 -0
  168. package/dist/web/public/panels-ui.6bb3169f.js.gz +0 -0
  169. package/dist/web/public/session-ui.34f25fdf.js +0 -36
  170. package/dist/web/public/session-ui.34f25fdf.js.br +0 -0
  171. package/dist/web/public/session-ui.34f25fdf.js.gz +0 -0
  172. package/dist/web/public/settings-ui.3a341938.js +0 -55
  173. package/dist/web/public/settings-ui.3a341938.js.br +0 -0
  174. package/dist/web/public/settings-ui.3a341938.js.gz +0 -0
  175. package/dist/web/public/styles.c14ecd8a.css +0 -1
  176. package/dist/web/public/styles.c14ecd8a.css.br +0 -0
  177. package/dist/web/public/styles.c14ecd8a.css.gz +0 -0
  178. package/dist/web/public/terminal-ui.1f5b45cf.js +0 -3
  179. package/dist/web/public/terminal-ui.1f5b45cf.js.br +0 -0
  180. package/dist/web/public/terminal-ui.1f5b45cf.js.gz +0 -0
@@ -1,3 +0,0 @@
1
- "use strict";(function(e){const s=/^\x1b\[[\?>=]?[\d;]*[cnR]$/,i=/^\x1b\][\d;]*[^\x07\x1b]*(?:\x07|\x1b\\)$/;function l(o){return s.test(o)||i.test(o)}function r(o){return l(o)}e.CodemanTerminalInput={isTerminalQueryResponse:l,shouldSuppressTerminalQueryResponse:r,USER_SCROLL_STICKY_SUPPRESS_MS:1500}})(window),Object.assign(CodemanApp.prototype,{initTerminal(){const e=parseInt(localStorage.getItem("codeman-scrollback")),s=Number.isFinite(e)&&e>0?Math.max(e,DEFAULT_SCROLLBACK):DEFAULT_SCROLLBACK;if(this.terminal=new Terminal({theme:{background:"#0d0d0d",foreground:"#e0e0e0",cursor:"#e0e0e0",cursorAccent:"#0d0d0d",selection:"rgba(255, 255, 255, 0.3)",black:"#0d0d0d",red:"#ff6b6b",green:"#51cf66",yellow:"#ffd43b",blue:"#339af0",magenta:"#cc5de8",cyan:"#22b8cf",white:"#e0e0e0",brightBlack:"#495057",brightRed:"#ff8787",brightGreen:"#69db7c",brightYellow:"#ffe066",brightBlue:"#5c7cfa",brightMagenta:"#da77f2",brightCyan:"#66d9e8",brightWhite:"#ffffff"},fontFamily:'"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, monospace',fontSize:MobileDetection.getDeviceType()==="mobile"?10:14,lineHeight:1.2,cursorBlink:!1,cursorStyle:"block",scrollback:s,allowTransparency:!0,allowProposedApi:!0}),this.fitAddon=new FitAddon.FitAddon,this.terminal.loadAddon(this.fitAddon),typeof Unicode11Addon<"u")try{const t=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(t),this.terminal.unicode.activeVersion="11"}catch{}const i=document.getElementById("terminalContainer");this.terminal.open(i),this.terminal.attachCustomKeyEventHandler(t=>{if(t.isComposing||t.keyCode===229||t.altKey&&t.key>="0"&&t.key<="9")return!1;if((t.ctrlKey||t.metaKey)&&t.key==="v"&&t.type==="keydown")return this.activeSessionId&&this._handleImagePaste&&this._handleImagePaste(),!1;if(t.key==="Enter"&&(t.shiftKey||t.ctrlKey)&&t.type==="keydown"){if(this.activeSessionId)if(this._localEchoEnabled){const c=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),c&&(this._pendingInput+=c,a()),setTimeout(()=>{fetch(`/api/sessions/${this.activeSessionId}/send-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:t.ctrlKey?"C-Enter":"S-Enter"})})},c?80:0)}else fetch(`/api/sessions/${this.activeSessionId}/send-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:t.ctrlKey?"C-Enter":"S-Enter"})});return!1}return!0});{const t=i.querySelector(".xterm-helper-textarea");if(t&&MobileDetection.isTouchDevice()){let c=!1,u=0;t.addEventListener("compositionstart",()=>{c=!0}),t.addEventListener("compositionend",()=>{c=!1}),t.addEventListener("keydown",h=>{!h.isComposing&&h.keyCode!==229&&(u=Date.now())}),t.addEventListener("input",h=>{if(c||h.isComposing||h.inputType!=="insertText"||!h.data||Date.now()-u<50)return;const d=h.data,p=this._localEchoOverlay?.pendingText||"";Promise.resolve().then(()=>{if(this._lastTerminalData?.data===d&&performance.now()-this._lastTerminalData.time<100){t.value="";return}const _=this._localEchoOverlay?.pendingText||"";if(this._localEchoEnabled&&_.length>p.length&&_.endsWith(d)){t.value="";return}const g=t.value;!g||g.trim()===""&&d!==" "||(this.terminal._core.coreService.triggerDataEvent(d,!0),t.value="")})})}}this._webglAddon=null;const n=new URLSearchParams(location.search);if(n.get("webgl")==="force")try{localStorage.removeItem("codeman-webgl-disabled")}catch{}const l=(()=>{try{const t=localStorage.getItem("codeman-webgl-disabled");if(!t)return!1;const{at:c}=JSON.parse(t);return Date.now()-c>WEBGL_FALLBACK.STICKY_EXPIRY_MS?(localStorage.removeItem("codeman-webgl-disabled"),!1):!0}catch{return!1}})(),r=MobileDetection.getDeviceType()!=="desktop"||n.has("nowebgl")||l;if(l&&console.log("[CRASH-DIAG] WebGL sticky-disabled from prior stalls \u2014 DOM renderer in use. Re-enable: ?webgl=force"),!r)if(typeof WebglAddon<"u")this._initWebGL();else{const t=document.createElement("script");t.src="vendor/xterm-addon-webgl.min.js",t.onload=()=>this._initWebGL(),t.onerror=()=>console.warn("[CRASH-DIAG] Failed to load WebGL addon \u2014 using canvas renderer"),document.head.appendChild(t)}this._localEchoOverlay=new LocalEchoOverlay(this.terminal),MobileDetection.isTouchDevice()&&(this.terminal.onCursorMove(()=>this._syncMobileHelperTextareaToCursor()),this.terminal.onRender(()=>this._syncMobileHelperTextareaToCursor())),this._cjkInput=null,typeof CjkInput<"u"&&(this._cjkInput=CjkInput.init({send:t=>{this._handleCjkInput(t)}})),MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this.registerFilePathLinkProvider(),i.addEventListener("wheel",t=>{t.preventDefault();const c=Math.round(t.deltaY/25)||(t.deltaY>0?1:-1);this._noteTerminalUserScroll(c),this.terminal.scrollLines(c)},{passive:!1});{const t=()=>this.terminal._core?._renderService?.dimensions?.css?.cell?.height||13;let c=0,u=0,h=0,d=null,p=!1;const _=b=>{const E=h?(b-h)/16.67:1;if(h=b,!p&&Math.abs(u)>.3){const T=Math.round(u/t());T!==0&&this.terminal.scrollLines(T),u*=.92,d=requestAnimationFrame(_)}else p?d=requestAnimationFrame(_):(d=null,u=0)};let g=0,v=!1;i.addEventListener("touchstart",b=>{b.touches.length===1&&(c=b.touches[0].clientY,u=0,g=0,p=!0,v=!1,h=0,d&&(cancelAnimationFrame(d),d=null))},{passive:!0}),i.addEventListener("touchmove",b=>{if(b.touches.length===1&&p){b.preventDefault(),v=!0;const E=b.touches[0].clientY,T=c-E;g+=T,u=T*1.2,c=E;const I=t(),S=Math.trunc(g/I);S!==0&&(this._noteTerminalUserScroll(S),this.terminal.scrollLines(S),g-=S*I)}},{passive:!1}),i.addEventListener("touchend",()=>{if(p=!1,!d&&Math.abs(u)>.3&&(d=requestAnimationFrame(_)),!v&&this.terminal){const b=document.getElementById("cjkInput");b?.classList.contains("cjk-input-visible")?b.focus():(this._syncMobileHelperTextareaToCursor(),this.terminal.focus())}},{passive:!0}),i.addEventListener("touchcancel",()=>{p=!1,u=0,g=0},{passive:!0})}this.showWelcome(),this.initImageInput(),this._chunkedWriteGen=0,this._bufferLoadSeq=0,this._bufferLoadOwner=null,this._lastUserScrollUpAt=null,this._resizeTimeout=null,this._lastResizeDims=null;const f=40,y=10,m=()=>{this._resizeTimeout&&clearTimeout(this._resizeTimeout),this._resizeTimeout=setTimeout(()=>{this._resizeTimeout=null,this.fitAddon&&this.fitAddon.fit(),this.flickerFilterBuffer&&(this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flushFlickerBuffer());const t=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;if(this.activeSessionId&&!t){const c=this.fitAddon.proposeDimensions(),u=c?Math.max(c.cols,f):f,h=c?Math.max(c.rows,y):y;if(!this._lastResizeDims||u!==this._lastResizeDims.cols||h!==this._lastResizeDims.rows){const d=this.activeSessionId?this.sessions.get(this.activeSessionId):null;d&&d.mode!=="shell"&&this.terminal&&this.isTerminalAtBottom()&&this.terminal.write("\x1B[3J\x1B[H\x1B[2J"),this._lastResizeDims={cols:u,rows:h};const p=typeof MobileDetection<"u"&&MobileDetection.getDeviceType?MobileDetection.getDeviceType():"desktop";let _=!1;if(this._wsReady&&this._wsSessionId===this.activeSessionId)try{this._ws.send(JSON.stringify({t:"z",c:u,r:h,v:p})),_=!0}catch{}_||fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:u,rows:h,viewportType:p})}).catch(()=>{})}}this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},300)};window.addEventListener("resize",m),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(m),this.terminalResizeObserver.observe(i),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const a=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const t=this._pendingInput,c=this.activeSessionId;this._pendingInput="",this._sendInputAsync(c,t)}};this.terminal.onData(t=>{if(!(window.cjkActive||document.activeElement?.id==="cjkInput")&&this.activeSessionId){if(window.CodemanTerminalInput?.shouldSuppressTerminalQueryResponse(t))return;if(this._lastTerminalData={data:t,time:performance.now()},this._localEchoEnabled){if(t==="\x7F"){if(this._localEchoOverlay?.removeChar()==="flushed"){const{count:h,text:d}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(h===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,h),this._flushedTexts?.set(this.activeSessionId,d))),this._pendingInput+=t,a()}return}if(/^[\r\n]+$/.test(t)){const u=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),u&&(this._pendingInput+=u,a()),setTimeout(()=>{this._pendingInput+="\r",a()},80);return}if(t.length>1&&t.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(t);return}if(t.charCodeAt(0)<32){if(t.length>1&&t.charCodeAt(0)===27){this._pendingInput+=t,a();return}if(this._restoringFlushedState){this._pendingInput+=t,a();return}if(t===" "){const h=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),h&&(this._pendingInput+=h),this._pendingInput+=t,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let d="";try{const _=this._localEchoOverlay?.findPrompt?.();if(_){const g=this.terminal.buffer.active,v=g.getLine(g.viewportY+_.row);v&&(d=v.translateToString(!0).slice(_.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=d,a(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const p=this;this._tabCompletionFallback=setTimeout(()=>{if(p._tabCompletionFallback=null,!p._tabCompletionSessionId||p._tabCompletionSessionId!==p.activeSessionId)return;const _=p._localEchoOverlay;!_||_.pendingText||p.terminal.write("",()=>{if(!p._tabCompletionSessionId)return;_.resetBufferDetection();const g=_.detectBufferText();g&&g!==p._tabCompletionBaseText&&(p._tabCompletionSessionId=null,p._tabCompletionRetries=0,p._tabCompletionBaseText=null,_.rerender())})},300);return}const u=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),u&&(this._pendingInput+=u),this._pendingInput+=t,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}if(t.length===1&&t.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(t);return}}if(this._pendingInput+=t,t.charCodeAt(0)<32||t.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}const c=performance.now();c-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=c,a()):(this._lastKeystrokeTime=c,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(a,0)))}})},registerFilePathLinkProvider(){const e=this;let s=-1;this.terminal.registerLinkProvider({provideLinks(i,n){i!==s&&(s=i,console.debug("[LinkProvider] Checking line:",i));const r=e.terminal.buffer.active.getLine(i-1);if(!r){n(void 0);return}const o=r.translateToString(!0);if(!o||!o.includes("/")){n(void 0);return}const f=[],y=/https?:\/\/[^\s"'<>|;&)\]\x00-\x1f]+/g,m=(d,p)=>{const _=d.replace(/[.,;:!?)]+$/,""),g=o.indexOf(_,p);g!==-1&&(f.some(v=>v.range.start.x===g+1)||f.push({text:_,range:{start:{x:g+1,y:i},end:{x:g+_.length+1,y:i}},decorations:{pointerCursor:!0,underline:!0},activate(v,b){window.open(b,"_blank","noopener,noreferrer")}}))},a=/\b(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]+\s+){0,4}(\/[^\s"'<>|;&\n\x00-\x1f]+)/g,t=/(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\n\x00-\x1f]*\.(?:log|txt|json|md|yaml|yml|csv|xml|sh|py|ts|js))\b/g,c=/Bash\([^)]*?(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\)\n\x00-\x1f]+)/g,u=(d,p)=>{const _=o.indexOf(d,p);_!==-1&&(f.some(g=>g.range.start.x===_+1)||f.push({text:d,range:{start:{x:_+1,y:i},end:{x:_+d.length+1,y:i}},decorations:{pointerCursor:!0,underline:!0},activate(g,v){e.openLogViewerWindow(v,e.activeSessionId)}}))};let h;for(y.lastIndex=0;(h=y.exec(o))!==null;)m(h[0],h.index);for(a.lastIndex=0;(h=a.exec(o))!==null;)u(h[2],h.index);for(t.lastIndex=0;(h=t.exec(o))!==null;)u(h[1],h.index);for(c.lastIndex=0;(h=c.exec(o))!==null;)u(h[1],h.index);f.length>0&&console.debug("[LinkProvider] Found links:",f.map(d=>d.text)),n(f.length>0?f:void 0)}}),console.log("[LinkProvider] File path link provider registered")},showWelcome(){const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus(),this.loadHistorySessions())},hideWelcome(){const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const s=document.getElementById("welcomeQr");s&&(clearTimeout(this._welcomeQrShrinkTimer),s.classList.remove("expanded"))},async _fetchHistorySessions(){const i=(await(await fetch("/api/history/sessions")).json()).data?.sessions||[];if(i.length===0)return[];const n=new Map;for(const r of i){const o=r.projectKey||r.workingDir;n.has(o)||n.set(o,[]),n.get(o).push(r)}const l=[];for(const[,r]of n)l.push(...r.slice(0,3));return l.sort((r,o)=>new Date(o.lastModified)-new Date(r.lastModified)),l},_resolveCaseLabel(e,s){if(!e)return"";let i=null;for(const n of s||[])if(!(!n||!n.path)){if(e===n.path)return`#${n.name}`;if(e.startsWith(n.path+"/")){const l=n.path.length;(!i||l>i.len)&&(i={name:n.name,suffix:e.slice(l),len:l})}}return i?`#${i.name}${i.suffix}`:e.split("/").pop()||e},_shortenHomePath(e){return(e||"").replace(/^\/home\/[^/]+\//,"~/").replace(/^\/Users\/[^/]+\//,"~/")},_buildHistoryItem(e,s,i){const n=i?.showViewAll!==!1,l=e.sizeBytes<1024?`${e.sizeBytes}B`:e.sizeBytes<1048576?`${(e.sizeBytes/1024).toFixed(0)}K`:`${(e.sizeBytes/1048576).toFixed(1)}M`,r=new Date(e.lastModified),o=r.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+r.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1}),f=this._shortenHomePath(e.workingDir),y=this._resolveCaseLabel(e.workingDir,s),m=document.createElement("div");m.className="history-item",m.title=e.workingDir;const a=document.createElement("div");a.className="history-item-main",a.addEventListener("click",()=>this.resumeHistorySession(e.sessionId,e.workingDir));const t=document.createElement("div");t.className="history-item-text";const c=document.createElement("span");c.className="history-item-title",c.textContent=e.firstPrompt||f;const u=document.createElement("span");u.className="history-item-subtitle",y.startsWith("#")&&u.classList.add("is-case"),u.textContent=y,t.append(c,u);const h=document.createElement("span");h.className="history-item-meta",h.textContent=o;const d=document.createElement("button");d.className="history-item-expand",d.type="button",d.setAttribute("aria-label","Show details"),d.setAttribute("aria-expanded","false"),d.textContent="\u22EF",a.append(t,h,d);const p=document.createElement("div");p.className="history-item-detail",p.hidden=!0;const _=document.createElement("div");_.className="history-detail-row";const g=document.createElement("span");g.className="history-detail-label",g.textContent="Prompt";const v=document.createElement("span");v.className="history-detail-value history-detail-prompt",v.textContent=e.firstPrompt||"(no prompt captured)",_.append(g,v);const b=document.createElement("div");b.className="history-detail-row";const E=document.createElement("span");E.className="history-detail-label",E.textContent="Path";const T=document.createElement("span");T.className="history-detail-value history-detail-path",T.textContent=f,b.append(E,T);const I=document.createElement("div");if(I.className="history-detail-row history-detail-meta",I.textContent=`${o} \xB7 ${l} \xB7 ${e.sessionId.slice(0,8)}`,p.append(_,b,I),n&&e.projectKey){const S=document.createElement("div");S.className="history-detail-row history-detail-actions";const w=document.createElement("button");w.type="button",w.className="history-view-all-btn",w.textContent="View all in this folder",w.addEventListener("click",x=>{x.stopPropagation(),this.openFolderHistoryModal(e.projectKey,e.workingDir,s)}),S.appendChild(w),p.appendChild(S)}return d.addEventListener("click",S=>{S.stopPropagation();const w=m.classList.toggle("expanded");p.hidden=!w,d.setAttribute("aria-expanded",w?"true":"false")}),m.append(a,p),m},_HISTORY_INITIAL_COUNT:4,async loadHistorySessions(){const e=document.getElementById("historySessions"),s=document.getElementById("historyList");if(!(!e||!s))try{const i=Array.isArray(this.cases)&&this.cases.length>0?Promise.resolve(this.cases):fetch("/api/cases").then(o=>o.ok?o.json():null).then(o=>o?.data||[]).catch(()=>[]),[n,l]=await Promise.all([this._fetchHistorySessions(30),i]);if(n.length===0){e.style.display="none";return}s.replaceChildren();const r=this._HISTORY_INITIAL_COUNT;for(let o=0;o<Math.min(r,n.length);o++)s.appendChild(this._buildHistoryItem(n[o],l));if(n.length>r){const o=document.createElement("button");o.className="history-show-more",o.textContent=`Show ${n.length-r} more`,o.addEventListener("click",()=>{for(let f=r;f<n.length;f++)s.insertBefore(this._buildHistoryItem(n[f],l),o);o.remove()}),s.appendChild(o)}e.style.display=""}catch(i){console.error("[loadHistorySessions]",i),e.style.display="none"}},_FOLDER_HISTORY_PAGE_SIZE:20,openFolderHistoryModal(e,s,i){this._closeFolderHistoryModal();const n=document.createElement("div");n.className="modal active folder-history-modal",n.id="folderHistoryModal";const l=document.createElement("div");l.className="modal-backdrop",l.addEventListener("click",()=>this._closeFolderHistoryModal());const r=document.createElement("div");r.className="modal-content modal-lg";const o=document.createElement("div");o.className="modal-header";const f=document.createElement("h3");f.textContent="Folder History";const y=document.createElement("div");y.className="folder-history-subtitle",y.textContent=this._shortenHomePath(s);const m=document.createElement("button");m.className="modal-close",m.setAttribute("aria-label","Close"),m.innerHTML="&times;",m.addEventListener("click",()=>this._closeFolderHistoryModal()),o.append(f,m);const a=document.createElement("div");a.className="modal-body";const t=document.createElement("div");t.className="folder-history-list",t.setAttribute("data-loading","true"),t.textContent="Loading...",a.append(y,t),r.append(o,a),n.append(l,r),document.body.appendChild(n),this._folderHistoryState={projectKey:e,workingDir:s,cases:i||[],offset:0,total:null,list:t},this._folderHistoryEscHandler=c=>{c.key==="Escape"&&this._closeFolderHistoryModal()},document.addEventListener("keydown",this._folderHistoryEscHandler),this._loadFolderHistoryPage()},async _loadFolderHistoryPage(){const e=this._folderHistoryState;if(!e)return;const{projectKey:s,cases:i,list:n}=e,l=this._FOLDER_HISTORY_PAGE_SIZE,r=e.offset,o=n.querySelector(".folder-history-more");o&&o.remove(),r===0&&(n.replaceChildren(),n.removeAttribute("data-loading"));try{const f=`/api/history/sessions?projectKey=${encodeURIComponent(s)}&offset=${r}&limit=${l}`,m=await(await fetch(f)).json(),a=m.data?.sessions||[];if(e.total=typeof m.data?.total=="number"?m.data.total:a.length+r,r===0&&a.length===0){const t=document.createElement("div");t.className="folder-history-empty",t.textContent="No conversations found in this folder.",n.appendChild(t);return}for(const t of a)n.appendChild(this._buildHistoryItem(t,i,{showViewAll:!1}));if(e.offset=r+a.length,e.offset<e.total){const t=e.total-e.offset,c=document.createElement("button");c.className="history-show-more folder-history-more",c.textContent=`Show ${Math.min(l,t)} more (${t} remaining)`,c.addEventListener("click",()=>this._loadFolderHistoryPage()),n.appendChild(c)}}catch(f){console.error("[loadFolderHistoryPage]",f);const y=document.createElement("div");y.className="folder-history-empty",y.textContent="Failed to load folder history.",n.appendChild(y)}},_closeFolderHistoryModal(){const e=document.getElementById("folderHistoryModal");e&&e.remove(),this._folderHistoryEscHandler&&(document.removeEventListener("keydown",this._folderHistoryEscHandler),this._folderHistoryEscHandler=null),this._folderHistoryState=null},async resumeHistorySession(e,s){document.getElementById("runModeMenu")?.classList.remove("active"),this._closeFolderHistoryModal();try{this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Resuming conversation ${e.slice(0,8)}...\x1B[0m`);const i=s.split("/").pop()||"session";let n=1;for(const[,u]of this.sessions){const h=u.name&&u.name.match(/^w(\d+)-/);if(h){const d=parseInt(h[1]);d>=n&&(n=d+1)}}const l=`w${n}-${i}`,o=(this.cases||[]).find(u=>u.path===s)?.name||s.split("/").pop()||"",f=this.loadAppSettingsFromStorage(),y=this.buildEnvOverrides(this.getCaseSettings(o),f),m=this.getEffortSetting(f),t=await(await fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:s,name:l,resumeSessionId:e,...Object.keys(y).length>0?{envOverrides:y}:{},...m?{effort:m}:{}})})).json();if(!t.success)throw new Error(t.error);const c=t.data.session.id;await fetch(`/api/sessions/${c}/interactive`,{method:"POST"}),this.terminal.writeln(`\x1B[90m Session ${l} ready\x1B[0m`),await this.selectSession(c),this.terminal.focus()}catch(i){this.terminal.writeln(`\x1B[1;31m Error: ${i.message}\x1B[0m`)}},isTerminalAtBottom(){if(!this.terminal)return!0;const e=this.terminal.buffer.active;return e.viewportY>=e.baseY-2},_noteTerminalUserScroll(e){e<0?this._lastUserScrollUpAt=performance.now():this.isTerminalAtBottom()&&(this._lastUserScrollUpAt=null)},_hasRecentUserScrollUp(){return typeof this._lastUserScrollUpAt!="number"?!1:performance.now()-this._lastUserScrollUpAt<window.CodemanTerminalInput.USER_SCROLL_STICKY_SUPPRESS_MS},batchTerminalWrite(e){if(this._isLoadingBuffer){this._loadBufferQueue&&this._loadBufferQueue.push(e);return}if(this.writeFrameScheduled||(this._wasAtBottomBeforeWrite=this.isTerminalAtBottom()),(this.activeSessionId?this.sessions.get(this.activeSessionId):null)?.flickerFilterEnabled??!1){if(e.includes("\x1B[2J")||e.includes("\x1B[H\x1B[J")||e.includes("\x1B[H")&&e.includes("\x1B[?25l")){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(this.flickerFilterActive){this.flickerFilterBuffer+=e;return}}this.pendingWrites.push(e),this.writeFrameScheduled||(this.writeFrameScheduled=!0,this._safeYield(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1}))},flushFlickerBuffer(){this.flickerFilterBuffer&&(this.pendingWrites.push(this.flickerFilterBuffer),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.writeFrameScheduled||(this.writeFrameScheduled=!0,this._safeYield(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1})))},_updateLocalEchoState(){const e=this.loadAppSettingsFromStorage(),s=this.activeSessionId?this.sessions.get(this.activeSessionId):null,n=!!((e.localEchoEnabled??MobileDetection.isTouchDevice())&&s);this._localEchoEnabled&&!n&&this._localEchoOverlay?.clear(),this._localEchoEnabled=n,this._localEchoOverlay&&s&&(s.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:l=>{try{const r=l.buffer.active,o=r.cursorY,f=r.getLine(r.viewportY+o);if(!f)return null;const m=f.translateToString(!0).indexOf("\u2503");return m>=0?{row:o,col:m}:null}catch{return null}}}):s.mode==="shell"?(this._localEchoOverlay.clear(),this._localEchoEnabled=!1):this._localEchoOverlay.setPrompt({type:"custom",offset:0,find:l=>{try{const r=l.buffer.active;for(let o=l.rows-1;o>=0;o--){const f=r.getLine(r.viewportY+o);if(!f)continue;const m=f.translateToString(!0).lastIndexOf("\u276F");if(m>=0)return{row:o,col:m+2}}return{row:Math.max(0,Math.min(l.rows-1,r.cursorY)),col:Math.max(0,Math.min(l.cols-1,r.cursorX))}}catch{return null}}}))},_handleCjkInput(e){if(!this.activeSessionId)return;const s=this.activeSessionId,i=this.sessions.get(s);if(!!!(this._localEchoEnabled&&this._localEchoOverlay&&i?.mode!=="shell")){this._sendInputAsync(s,e);return}if(e==="\x7F"){if(this._localEchoOverlay.removeChar()==="flushed"){const{count:r,text:o}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(s)&&(r===0?(this._flushedOffsets.delete(s),this._flushedTexts?.delete(s)):(this._flushedOffsets.set(s,r),this._flushedTexts?.set(s,o))),this._sendInputAsync(s,e)}return}if(/[\r\n]+$/.test(e)){const l=e.replace(/[\r\n]+$/g,"");l&&this._localEchoOverlay.appendText(l);const r=this._localEchoOverlay.pendingText||"";this._localEchoOverlay.clear(),this._localEchoOverlay.suppressBufferDetection(),this._flushedOffsets?.delete(s),this._flushedTexts?.delete(s),r&&this._sendInputAsync(s,r),setTimeout(()=>this._sendInputAsync(s,"\r"),r?80:0);return}if(e.length>1&&e.charCodeAt(0)===27){this._sendInputAsync(s,e);return}if(e.length===1&&e.charCodeAt(0)<32){const l=this._localEchoOverlay.pendingText||"";this._localEchoOverlay.clear(),this._localEchoOverlay.suppressBufferDetection(),this._flushedOffsets?.delete(s),this._flushedTexts?.delete(s),l&&this._sendInputAsync(s,l),this._sendInputAsync(s,e);return}this._localEchoOverlay.appendText(e)},flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=performance.now(),s=this.pendingWrites.join("");this.pendingWrites=[];const i=s.length;i>16384&&_crashDiag.log(`FLUSH: ${(i/1024).toFixed(0)}KB`);const l=(this.activeSessionId&&this.sessions?this.sessions.get(this.activeSessionId):null)?.mode==="codex"?32768:65536;let r=!1;const o=this._hasRecentUserScrollUp()&&this.terminal.buffer?.active?this.terminal.buffer.active.viewportY:null;i<=l?this.terminal.write(s):(this.terminal.write(s.slice(0,l)),this.pendingWrites.push(s.slice(l)),r=!0,this.writeFrameScheduled||(this.writeFrameScheduled=!0,this._safeYield(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1}))),o!==null&&this.terminal.buffer?.active?.viewportY!==o&&typeof this.terminal.scrollToLine=="function"&&this.terminal.scrollToLine(o);const f=r?l:i,y=performance.now()-e;if((y>100||r)&&console.warn(`[CRASH-DIAG] flushPendingWrites: ${y.toFixed(0)}ms, ${(f/1024).toFixed(0)}KB written${r?", rest deferred":""} (total ${(i/1024).toFixed(0)}KB)`),this._wasAtBottomBeforeWrite&&!this._hasRecentUserScrollUp()&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const m=this._localEchoOverlay,a=this;this.terminal.write("",()=>{if(!a._tabCompletionSessionId)return;m.resetBufferDetection();const t=m.detectBufferText();t?t===a._tabCompletionBaseText?(m.undoDetection(),a._tabCompletionRetries=(a._tabCompletionRetries||0)+1,a._tabCompletionRetries>60&&(a._tabCompletionSessionId=null,a._tabCompletionRetries=0)):(a._tabCompletionSessionId=null,a._tabCompletionRetries=0,a._tabCompletionBaseText=null,a._tabCompletionFallback&&(clearTimeout(a._tabCompletionFallback),a._tabCompletionFallback=null),m.rerender()):(a._tabCompletionRetries=(a._tabCompletionRetries||0)+1,a._tabCompletionRetries>60&&(a._tabCompletionSessionId=null,a._tabCompletionRetries=0))})}},_safeYield(e){let s=!1;const i=()=>{s||(s=!0,e())};requestAnimationFrame(i),setTimeout(i,50),this._workerYield(i)},_workerYield(e){try{if(this._yieldWorker===void 0){const s="onmessage=()=>setTimeout(()=>postMessage(0),0);",i=new Blob([s],{type:"application/javascript"}),n=URL.createObjectURL(i);this._yieldWorker=new Worker(n),URL.revokeObjectURL(n),this._yieldQueue=[],this._yieldWorker.onmessage=()=>{const l=this._yieldQueue.shift();l&&l()}}if(!this._yieldWorker)return;this._yieldQueue.push(e),this._yieldWorker.postMessage(0)}catch{this._yieldWorker=null}},scrollToLastNonEmptyLine(){if(!this.terminal?.buffer?.active){this.terminal?.scrollToBottom?.();return}const e=this.terminal.buffer.active,s=e.baseY+e.length;let i=-1;for(let n=s-1;n>=0;n--)if(e.getLine(n)?.translateToString(!0).trim()){i=n;break}if(i>=0&&typeof this.terminal.scrollToLine=="function"){let n=Math.max(0,i-this.terminal.rows+2);const l=Math.max(0,i);for(;n<l&&!e.getLine(n)?.translateToString(!0).trim();)n++;this.terminal.scrollToLine(n)}else this.terminal.scrollToBottom()},chunkedTerminalWrite(e,s=TERMINAL_CHUNK_SIZE,i){const n=++this._chunkedWriteGen,l=this._beginBufferLoad(i);return new Promise(r=>{if(!e||e.length===0){this._finishBufferLoad(l),r();return}const o=e.replace(DEC_SYNC_STRIP_RE,""),f=()=>{this._chunkedWriteGen===n&&this._finishBufferLoad(l),r()};if(o.length<=s){this.terminal.write(o,f);return}let y=0;const m=performance.now();let a=0;const t=()=>{if(this._chunkedWriteGen!==n){r();return}if(y>=o.length){const d=performance.now()-m;console.log(`[CRASH-DIAG] chunkedTerminalWrite complete: ${o.length} bytes in ${a} chunks, ${d.toFixed(0)}ms total`),this._safeYield(f);return}const c=performance.now(),u=o.slice(y,y+s);this.terminal.write(u);const h=performance.now()-c;a++,h>50&&console.warn(`[CRASH-DIAG] chunk #${a} write took ${h.toFixed(0)}ms (${u.length} bytes at offset ${y})`),y+=s,this._safeYield(t)};this._safeYield(t)})},_beginBufferLoad(e){this._bufferLoadSeq===void 0&&(this._bufferLoadSeq=0);const s=e===void 0?`buffer-${++this._bufferLoadSeq}`:e;return this._bufferLoadOwner=s,this._isLoadingBuffer=!0,this._loadBufferQueue=[],s},_finishBufferLoad(e){return e!==void 0&&this._bufferLoadOwner!==e?!1:(this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._bufferLoadOwner=null,!0)},clearTerminal(){this.terminal.clear()},async restoreTerminalSize(){if(!this.activeSessionId){this.showToast("No active session","warning");return}const e=this.getTerminalDimensions();if(!e){this.showToast("Could not determine terminal size","error");return}try{await this.sendResize(this.activeSessionId),this.showToast(`Terminal restored to ${e.cols}x${e.rows}`,"success")}catch(s){console.error("Failed to restore terminal size:",s),this.showToast("Failed to restore terminal size","error")}},sendPendingCtrlL(e){},async copyTerminal(){try{const e=this.terminal.buffer.active;let s="";for(let i=0;i<e.length;i++){const n=e.getLine(i);n&&(s+=n.translateToString(!0)+`
2
- `)}await navigator.clipboard.writeText(s.replace(/\n+$/,`
3
- `)),this.showToast("Copied to clipboard","success")}catch{this.showToast("Failed to copy","error")}},_syncMobileHelperTextareaToCursor(){if(!(!MobileDetection.isTouchDevice()||!this.terminal?.element))try{const e=this.terminal.element,s=this.terminal.element.querySelector(".xterm-cursor"),i=this.terminal.element.querySelector(".xterm-screen");if(!(e instanceof HTMLElement)||!(s instanceof HTMLElement)||!(i instanceof HTMLElement))return;const n=s.getBoundingClientRect(),l=i.getBoundingClientRect();if(!n.width&&!n.height)return;const r=Math.max(0,Math.round(n.left-l.left)),o=Math.max(0,Math.round(n.top-l.top));e.style.setProperty("--xterm-helper-left",`${r}px`),e.style.setProperty("--xterm-helper-top",`${o}px`)}catch{}},increaseFontSize(){const e=this.terminal.options.fontSize||14;this.setFontSize(Math.min(e+2,24))},decreaseFontSize(){const e=this.terminal.options.fontSize||14;this.setFontSize(Math.max(e-2,10))},setFontSize(e){this.terminal.options.fontSize=e,document.getElementById("fontSizeDisplay").textContent=e,this.fitAddon.fit(),localStorage.setItem("codeman-font-size",e),this._localEchoOverlay?.refreshFont()},loadFontSize(){const e=localStorage.getItem("codeman-font-size");if(e){const s=parseInt(e,10);s>=10&&s<=24&&(this.terminal.options.fontSize=s,document.getElementById("fontSizeDisplay").textContent=s)}},getTerminalDimensions(){const i=this.fitAddon?.proposeDimensions();return i?{cols:Math.max(i.cols,40),rows:Math.max(i.rows,10)}:null},async sendResize(e,s={}){this.fitAddon&&this.fitAddon.fit();const i=this.getTerminalDimensions();if(!i)return!1;const n=this._lastResizeDims,l=!n||n.cols!==i.cols||n.rows!==i.rows;this._lastResizeDims={cols:i.cols,rows:i.rows};const r=typeof MobileDetection<"u"&&MobileDetection.getDeviceType?MobileDetection.getDeviceType():window.innerWidth<430?"mobile":window.innerWidth<768?"tablet":"desktop";if(!s.forceHttp&&this._wsReady&&this._wsSessionId===e)try{return this._ws.send(JSON.stringify({t:"z",c:i.cols,r:i.rows,v:r})),l}catch{}return await fetch(`/api/sessions/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...i,viewportType:r})}),l},async sendInput(e){this.activeSessionId&&await fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:e,useMux:!0})})},toggleDirInput(){const e=document.querySelector("#dirDisplay").parentElement,s=document.getElementById("dirInput");s.classList.contains("hidden")&&(s.classList.remove("hidden"),e.style.display="none",s.focus())},hideDirInput(){const e=document.querySelector("#dirDisplay").parentElement,s=document.getElementById("dirInput");setTimeout(()=>{s.classList.add("hidden"),e.style.display="";const i=s.value.trim();document.getElementById("dirDisplay").textContent=i||"No directory"},100)}});