aicodeman 1.16.2 → 1.16.3

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 (116) hide show
  1. package/README.md +2 -1
  2. package/dist/search-service.d.ts +9 -1
  3. package/dist/search-service.d.ts.map +1 -1
  4. package/dist/search-service.js +13 -3
  5. package/dist/search-service.js.map +1 -1
  6. package/dist/services/unified-session-service.d.ts +9 -0
  7. package/dist/services/unified-session-service.d.ts.map +1 -1
  8. package/dist/services/unified-session-service.js +4 -1
  9. package/dist/services/unified-session-service.js.map +1 -1
  10. package/dist/types/search.d.ts +17 -3
  11. package/dist/types/search.d.ts.map +1 -1
  12. package/dist/web/public/admin-ui.js +35 -20
  13. package/dist/web/public/admin-ui.js.br +0 -0
  14. package/dist/web/public/admin-ui.js.gz +0 -0
  15. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  16. package/dist/web/public/{app.4d006245.js → app.f9c6aadd.js} +18 -18
  17. package/dist/web/public/app.f9c6aadd.js.br +0 -0
  18. package/dist/web/public/app.f9c6aadd.js.gz +0 -0
  19. package/dist/web/public/approvals-ui.js.gz +0 -0
  20. package/dist/web/public/{constants.7d0f4047.js → constants.53dc0fa1.js} +43 -0
  21. package/dist/web/public/constants.53dc0fa1.js.br +0 -0
  22. package/dist/web/public/constants.53dc0fa1.js.gz +0 -0
  23. package/dist/web/public/cron-ui.js.gz +0 -0
  24. package/dist/web/public/entrance-animations.js.gz +0 -0
  25. package/dist/web/public/home-sessions.js +119 -8
  26. package/dist/web/public/home-sessions.js.br +0 -0
  27. package/dist/web/public/home-sessions.js.gz +0 -0
  28. package/dist/web/public/i18n.1a8b3412.js +1 -0
  29. package/dist/web/public/i18n.1a8b3412.js.br +0 -0
  30. package/dist/web/public/i18n.1a8b3412.js.gz +0 -0
  31. package/dist/web/public/image-input.ee16ad88.js.gz +0 -0
  32. package/dist/web/public/index.html +807 -727
  33. package/dist/web/public/index.html.br +0 -0
  34. package/dist/web/public/index.html.gz +0 -0
  35. package/dist/web/public/input-cjk.63794d0b.js.gz +0 -0
  36. package/dist/web/public/{keyboard-accessory.1f35b482.js → keyboard-accessory.0f524637.js} +207 -5
  37. package/dist/web/public/keyboard-accessory.0f524637.js.br +0 -0
  38. package/dist/web/public/keyboard-accessory.0f524637.js.gz +0 -0
  39. package/dist/web/public/mobile-handlers.32fdd57f.js.gz +0 -0
  40. package/dist/web/public/mobile-overview.js.gz +0 -0
  41. package/dist/web/public/mobile.52b30b35.css +1 -0
  42. package/dist/web/public/mobile.52b30b35.css.br +0 -0
  43. package/dist/web/public/mobile.52b30b35.css.gz +0 -0
  44. package/dist/web/public/notification-manager.5d229063.js.gz +0 -0
  45. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  46. package/dist/web/public/{panels-ui.3df9cd95.js → panels-ui.54b0d004.js} +1 -1
  47. package/dist/web/public/panels-ui.54b0d004.js.br +0 -0
  48. package/dist/web/public/panels-ui.54b0d004.js.gz +0 -0
  49. package/dist/web/public/ralph-panel.6de2d0f8.js.gz +0 -0
  50. package/dist/web/public/ralph-wizard.13a1831e.js.gz +0 -0
  51. package/dist/web/public/readmymind-ui.js +80 -16
  52. package/dist/web/public/readmymind-ui.js.br +0 -0
  53. package/dist/web/public/readmymind-ui.js.gz +0 -0
  54. package/dist/web/public/respawn-ui.ff0dae4c.js.gz +0 -0
  55. package/dist/web/public/sanitize-html.bc7078d6.js.gz +0 -0
  56. package/dist/web/public/session-ui.f4fed187.js.gz +0 -0
  57. package/dist/web/public/{settings-ui.1c15649c.js → settings-ui.c674f367.js} +9 -9
  58. package/dist/web/public/settings-ui.c674f367.js.br +0 -0
  59. package/dist/web/public/settings-ui.c674f367.js.gz +0 -0
  60. package/dist/web/public/styles.2eb23e0f.css +1 -0
  61. package/dist/web/public/styles.2eb23e0f.css.br +0 -0
  62. package/dist/web/public/styles.2eb23e0f.css.gz +0 -0
  63. package/dist/web/public/subagent-windows.4cc8b005.js.gz +0 -0
  64. package/dist/web/public/sw.js.gz +0 -0
  65. package/dist/web/public/terminal-ui.61c7829d.js +4 -0
  66. package/dist/web/public/terminal-ui.61c7829d.js.br +0 -0
  67. package/dist/web/public/terminal-ui.61c7829d.js.gz +0 -0
  68. package/dist/web/public/ultracode-panel.js.gz +0 -0
  69. package/dist/web/public/ultracode-windows.js.gz +0 -0
  70. package/dist/web/public/upload.html.gz +0 -0
  71. package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
  72. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  73. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  74. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  75. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  76. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  77. package/dist/web/public/vendor/xterm-predictive-echo.6cec0fba.js.gz +0 -0
  78. package/dist/web/public/vendor/xterm-zerolag-input.137ad9f0.js.gz +0 -0
  79. package/dist/web/public/vendor/xterm.css.gz +0 -0
  80. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  81. package/dist/web/public/voice-input.e5461859.js.gz +0 -0
  82. package/dist/web/public/webview-tabs.js.gz +0 -0
  83. package/dist/web/routes/search-routes.d.ts +3 -1
  84. package/dist/web/routes/search-routes.d.ts.map +1 -1
  85. package/dist/web/routes/search-routes.js +34 -1
  86. package/dist/web/routes/search-routes.js.map +1 -1
  87. package/dist/web/routes/session-routes.d.ts.map +1 -1
  88. package/dist/web/routes/session-routes.js +151 -9
  89. package/dist/web/routes/session-routes.js.map +1 -1
  90. package/dist/web/session-history-index.d.ts +108 -0
  91. package/dist/web/session-history-index.d.ts.map +1 -0
  92. package/dist/web/session-history-index.js +118 -0
  93. package/dist/web/session-history-index.js.map +1 -0
  94. package/package.json +1 -1
  95. package/dist/web/public/app.4d006245.js.br +0 -0
  96. package/dist/web/public/app.4d006245.js.gz +0 -0
  97. package/dist/web/public/constants.7d0f4047.js.br +0 -0
  98. package/dist/web/public/constants.7d0f4047.js.gz +0 -0
  99. package/dist/web/public/i18n.ef50083f.js +0 -1
  100. package/dist/web/public/i18n.ef50083f.js.br +0 -0
  101. package/dist/web/public/i18n.ef50083f.js.gz +0 -0
  102. package/dist/web/public/keyboard-accessory.1f35b482.js.br +0 -0
  103. package/dist/web/public/keyboard-accessory.1f35b482.js.gz +0 -0
  104. package/dist/web/public/mobile.5d8c896c.css +0 -1
  105. package/dist/web/public/mobile.5d8c896c.css.br +0 -0
  106. package/dist/web/public/mobile.5d8c896c.css.gz +0 -0
  107. package/dist/web/public/panels-ui.3df9cd95.js.br +0 -0
  108. package/dist/web/public/panels-ui.3df9cd95.js.gz +0 -0
  109. package/dist/web/public/settings-ui.1c15649c.js.br +0 -0
  110. package/dist/web/public/settings-ui.1c15649c.js.gz +0 -0
  111. package/dist/web/public/styles.0024c22e.css +0 -1
  112. package/dist/web/public/styles.0024c22e.css.br +0 -0
  113. package/dist/web/public/styles.0024c22e.css.gz +0 -0
  114. package/dist/web/public/terminal-ui.e7c5d233.js +0 -4
  115. package/dist/web/public/terminal-ui.e7c5d233.js.br +0 -0
  116. package/dist/web/public/terminal-ui.e7c5d233.js.gz +0 -0
@@ -1,4 +0,0 @@
1
- "use strict";(function(e){const t=/^\x1b\[[\?>=]?[\d;]*[cnR]$/,s=/^\x1b\][\d;]*[^\x07\x1b]*(?:\x07|\x1b\\)$/,a=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?<>=!]*[ -/]*[@-~]|\x1b[()#][0-9A-Za-z]|\x1b[=>78M]/g,o="\x1B[5~",l="\x1B[6~",c=/^\x1b(?:\[(?:[ABCDHF]|1;[2-8][ABCDHF]|[1-8](?:;[2-8])?~)|O[ABCDHF])$/,p="\x1B[200~";function T(h){return c.test(h)}const C=/^› /;function I(h){const m=Array.from(h);if(m.length===1){const E=m[0].codePointAt(0);return E===127?"backspace":E>=32?"char":"clear"}return h.charCodeAt(0)===27?"clear":h.charCodeAt(0)>=32?"text":"clear"}function _(h){try{const m=h.buffer.active,E=m.getLine(m.baseY+m.cursorY);return!!E&&C.test(E.translateToString(!0))}catch{return!1}}function n(h){return t.test(h)||s.test(h)}function g(h){return n(h)}const u={og:{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"},"daylight-green":{background:"#161b23",foreground:"#dfe6ef",cursor:"#2fd3aa",cursorAccent:"#161b23",selection:"rgba(47,211,170,0.22)",black:"#161b23",red:"#ff8585",green:"#34d8a0",yellow:"#f0c25a",blue:"#5cc6e8",magenta:"#c79af2",cyan:"#2bcbbb",white:"#dfe6ef",brightBlack:"#5b6675",brightRed:"#ffa0a0",brightGreen:"#5fe6b8",brightYellow:"#ffd884",brightBlue:"#82d4ee",brightMagenta:"#d6b3f7",brightCyan:"#5ee0d4",brightWhite:"#f3f6fa"},"daylight-blue":{background:"#161b23",foreground:"#dfe6ef",cursor:"#38b6f0",cursorAccent:"#161b23",selection:"rgba(56,182,240,0.22)",black:"#161b23",red:"#ff8585",green:"#34d8a0",yellow:"#f0c25a",blue:"#5cc6e8",magenta:"#c79af2",cyan:"#2bcbbb",white:"#dfe6ef",brightBlack:"#5b6675",brightRed:"#ffa0a0",brightGreen:"#5fe6b8",brightYellow:"#ffd884",brightBlue:"#82d4ee",brightMagenta:"#d6b3f7",brightCyan:"#5ee0d4",brightWhite:"#f3f6fa"},"paper-gray":{background:"#f6f8fa",foreground:"#1f2328",cursor:"#0969da",cursorAccent:"#ffffff",selection:"rgba(9,105,218,0.2)",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#59636e",brightBlack:"#6e7781",brightRed:"#a40e26",brightGreen:"#116329",brightYellow:"#7d4e00",brightBlue:"#0550ae",brightMagenta:"#6639ba",brightCyan:"#116b75",brightWhite:"#1f2328"},"solarized-light":{background:"#fdf6e3",foreground:"#586e75",cursor:"#147ba3",cursorAccent:"#fdf6e3",selection:"rgba(38,139,210,0.2)",black:"#eee8d5",red:"#dc322f",green:"#758600",yellow:"#9b7800",blue:"#147ba3",magenta:"#d33682",cyan:"#2a9189",white:"#073642",brightBlack:"#93a1a1",brightRed:"#cb4b16",brightGreen:"#657b83",brightYellow:"#586e75",brightBlue:"#268bd2",brightMagenta:"#6c71c4",brightCyan:"#2aa198",brightWhite:"#002b36"},"catppuccin-latte":{background:"#eff1f5",foreground:"#4c4f69",cursor:"#1e66f5",cursorAccent:"#ffffff",selection:"rgba(30,102,245,0.18)",black:"#5c5f77",red:"#d20f39",green:"#3b8f2b",yellow:"#a86605",blue:"#1e66f5",magenta:"#8839ef",cyan:"#177f86",white:"#6c6f85",brightBlack:"#7c7f93",brightRed:"#b50930",brightGreen:"#2f7622",brightYellow:"#8b5604",brightBlue:"#174fbf",brightMagenta:"#6f2bc5",brightCyan:"#116b71",brightWhite:"#4c4f69"},"rose-pine-dawn":{background:"#faf4ed",foreground:"#575279",cursor:"#286983",cursorAccent:"#fffaf3",selection:"rgba(40,105,131,0.2)",black:"#575279",red:"#b4637a",green:"#286983",yellow:"#96681f",blue:"#477f91",magenta:"#907aa9",cyan:"#3f7f8b",white:"#6e6a86",brightBlack:"#797593",brightRed:"#984d66",brightGreen:"#1f5266",brightYellow:"#7d5417",brightBlue:"#386b7c",brightMagenta:"#765f90",brightCyan:"#326b76",brightWhite:"#575279"}},y=new Set(["paper-gray","solarized-light","catppuccin-latte","rose-pine-dawn"]);function b(){return typeof document<"u"&&document.documentElement.dataset.skin||"daylight-blue"}function w(){const h=b();return u[h]||u["daylight-blue"]}function v(h=b()){return y.has(h)}e.CodemanTerminalInput={isTerminalQueryResponse:n,shouldSuppressTerminalQueryResponse:g,isComposerNavKey:T,classifyPredictInput:I,isCodexComposerRow:_,CODEX_COMPOSER_ROW_RE:C,BRACKETED_PASTE_START:p,USER_SCROLL_STICKY_SUPPRESS_MS:1500,TOUCH_COMPAT_MOUSE_SUPPRESS_MS:450,REPLAY_ESCAPE_RE:a,KEY_PAGE_UP:o,KEY_PAGE_DOWN:l,PAGE_KEY_SCREEN_FRACTION:.5,PAGE_KEY_MAX_PER_BATCH:3},e.CODEMAN_XTERM_THEMES=u,e.codemanCurrentXtermTheme=w,e.codemanCurrentSkinIsLight=v})(window),Object.assign(CodemanApp.prototype,{initTerminal(){const e=parseInt(localStorage.getItem("codeman-scrollback")),t=Number.isFinite(e)&&e>0?Math.max(e,DEFAULT_SCROLLBACK):DEFAULT_SCROLLBACK;if(this.terminal=new Terminal({theme:{...window.codemanCurrentXtermTheme()},fontFamily:'"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, monospace',fontSize:MobileDetection.getDeviceType()==="mobile"?10:14,lineHeight:1.2,cursorBlink:!1,cursorStyle:"block",minimumContrastRatio:window.codemanCurrentSkinIsLight()?4.5:1,scrollback:t,allowTransparency:!0,allowProposedApi:!0}),this.fitAddon=new FitAddon.FitAddon,this.terminal.loadAddon(this.fitAddon),this._xtermSnapshots=new Map,typeof SerializeAddon<"u")try{this._serializeAddon=new SerializeAddon.SerializeAddon,this.terminal.loadAddon(this._serializeAddon)}catch{this._serializeAddon=null}if(typeof Unicode11Addon<"u")try{const n=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(n),this.terminal.unicode.activeVersion="11"}catch{}const s=document.getElementById("terminalContainer");this.terminal.open(s),this._installMobileTapMouseGuard(),this.terminal.attachCustomKeyEventHandler(n=>{if(n.isComposing||n.keyCode===229||n.altKey&&!n.ctrlKey&&!n.shiftKey&&/^(Digit[1-9]|BracketLeft|BracketRight|KeyK)$/.test(n.code||"")||n.type==="keydown"&&this.shouldOpenCommandPaletteFromShortcut?.(n))return!1;if(this.shouldCopyTerminalSelectionFromShortcut?.(n)){const g=this.terminal.hasSelection?.()?this.terminal.getSelection():"";return g?(n.preventDefault(),this.copyTerminalSelection(g),!1):n.shiftKey?(n.preventDefault(),!1):!0}if((n.ctrlKey||n.metaKey)&&n.key==="v"&&n.type==="keydown")return this.activeSessionId&&this._handleImagePaste&&this._handleImagePaste(),!1;if(n.key==="Enter"&&(n.shiftKey||n.ctrlKey)&&n.type==="keydown"){if(this.activeSessionId)if(this._localEchoEnabled){const g=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),g&&(this._pendingInput+=g,_()),setTimeout(()=>{fetch(`/api/sessions/${this.activeSessionId}/send-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:n.ctrlKey?"C-Enter":"S-Enter"})})},g?80:0)}else fetch(`/api/sessions/${this.activeSessionId}/send-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:n.ctrlKey?"C-Enter":"S-Enter"})});return!1}return!0});{const n=s.querySelector(".xterm-helper-textarea");if(n&&MobileDetection.isTouchDevice()){let g=!1,u=0;n.addEventListener("compositionstart",()=>{g=!0}),n.addEventListener("compositionend",()=>{g=!1}),n.addEventListener("keydown",y=>{!y.isComposing&&y.keyCode!==229&&(u=Date.now())}),n.addEventListener("input",y=>{if(g||y.isComposing||y.inputType!=="insertText"||!y.data||Date.now()-u<50)return;const b=y.data,w=this._localEchoOverlay?.pendingText||"";Promise.resolve().then(()=>{if(this._lastTerminalData?.data===b&&performance.now()-this._lastTerminalData.time<100){n.value="";return}const v=this._localEchoOverlay?.pendingText||"";if(this._localEchoEnabled&&v.length>w.length&&v.endsWith(b)){n.value="";return}const h=n.value;!h||h.trim()===""&&b!==" "||(this.terminal._core.coreService.triggerDataEvent(b,!0),n.value="")})})}}this._webglAddon=null;const i=new URLSearchParams(location.search),r=(()=>{try{const n=localStorage.getItem("codeman-webgl-disabled");if(!n)return!1;const{at:g}=JSON.parse(n);return Date.now()-g>WEBGL_FALLBACK.STICKY_EXPIRY_MS?(localStorage.removeItem("codeman-webgl-disabled"),!1):!0}catch{return!1}})(),a=this.loadAppSettingsFromStorage(),o=this.getDefaultSettings(),l=a.webglRendererEnabled??o.webglRendererEnabled,{skip:d,clearSticky:S}=shouldSkipWebGL({deviceType:MobileDetection.getDeviceType(),noWebglParam:i.has("nowebgl"),forceParam:i.get("webgl")==="force",stickyDisabled:r,userPrefEnabled:l});if(S)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}if(d&&r&&console.log("[CRASH-DIAG] WebGL sticky-disabled from prior stalls \u2014 DOM renderer in use. Re-enable: ?webgl=force"),!d)if(typeof WebglAddon<"u")this._initWebGL();else{const n=document.createElement("script");n.src="vendor/xterm-addon-webgl.min.js",n.onload=()=>this._initWebGL(),n.onerror=()=>console.warn("[CRASH-DIAG] Failed to load WebGL addon \u2014 using canvas renderer"),document.head.appendChild(n)}this._localEchoOverlay=new LocalEchoOverlay(this.terminal),this._predictiveEcho=typeof PredictiveEchoOverlay<"u"?new PredictiveEchoOverlay(this.terminal):null,this._predictiveEcho?.setPredictWhen(n=>window.CodemanTerminalInput.isCodexComposerRow(n)),MobileDetection.isTouchDevice()&&(this.terminal.onCursorMove(()=>this._syncMobileHelperTextareaToCursor()),this.terminal.onRender(()=>this._syncMobileHelperTextareaToCursor())),this._cjkInput=null,typeof CjkInput<"u"&&(this._cjkInput=CjkInput.init({send:n=>{this._handleCjkInput(n)}}));const c=this.terminal.focus.bind(this.terminal);this.terminal.focus=()=>{const n=document.getElementById("cjkInput");n?.classList.contains("cjk-input-visible")?n.focus():c()},MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this.registerFilePathLinkProvider(),s.addEventListener("wheel",n=>{const g=this.terminal?.modes?.mouseTrackingMode;if(g&&g!=="none"||this.terminal?.buffer?.active?.type==="alternate")return;if(n.preventDefault(),n.stopPropagation(),this._shouldForwardWheelToApp(n)){this._logScrollRouting("forward-sgr"),this._forwardScrollToApp(n.clientX,n.clientY,this._wheelScrollLines(n));return}const u=this._wheelScrollLinesFloat(n);this._maybePageCliTranscript(n,u)||(this._logScrollRouting("local-scrollback"),this._noteTerminalUserScroll(u),this._smoothScrollBy(u))},{passive:!1,capture:!0});{const n=()=>this.terminal._core?._renderService?.dimensions?.css?.cell?.height||13;let g=0,u=0,y=0,b=0,w=null,v=!1;const h=x=>{const L=b?(x-b)/16.67:1;if(b=x,!v&&Math.abs(y)>.3){const f=Math.round(y/n());f!==0&&(this._shouldForwardWheelToApp({shiftKey:!1})?this._forwardScrollToApp(g,u,f):this._maybePageCliTranscript({shiftKey:!1},f)||(this.terminal.scrollLines(f),this._maybeLoadMoreHistoryOnScroll(f))),y*=.92,w=requestAnimationFrame(h)}else v?w=requestAnimationFrame(h):(w=null,y=0)};let m=0,E=!1,k=0;const A=8;s.addEventListener("touchstart",x=>{x.touches.length===1&&(g=x.touches[0].clientX,u=x.touches[0].clientY,k=u,y=0,m=0,v=!0,E=!1,b=0,w&&(cancelAnimationFrame(w),w=null))},{passive:!0}),s.addEventListener("touchmove",x=>{if(x.touches.length===1&&v){const L=x.touches[0].clientY;if(!E&&Math.abs(L-k)>=A&&(E=!0),!E)return;x.preventDefault();const f=u-L;m+=f,y=f*1.2,g=x.touches[0].clientX,u=L;const M=n(),R=Math.trunc(m/M);R!==0&&(this._shouldForwardWheelToApp({shiftKey:!1})?(this._logScrollRouting("forward-sgr"),this._forwardScrollToApp(g,u,R)):this._maybePageCliTranscript({shiftKey:!1},R)||(this._logScrollRouting("local-scrollback"),this._noteTerminalUserScroll(R),this.terminal.scrollLines(R),this._maybeLoadMoreHistoryOnScroll(R)),m-=R*M)}},{passive:!1}),s.addEventListener("touchend",x=>{if(v=!1,!w&&Math.abs(y)>.3&&(w=requestAnimationFrame(h)),!E&&this.terminal){const L=x.changedTouches&&x.changedTouches[0],f=this.terminal.modes?.mouseTrackingMode,M=!!f&&f!=="none";L&&this._suppressTrustedTapMouseEvents(),L&&M?this._dispatchSyntheticTerminalClick(L.clientX,L.clientY):L&&this._sessionUsesServerMouseStrip()&&this._sendSyntheticSgrTap(L.clientX,L.clientY),this._syncMobileHelperTextareaToCursor();const R=document.getElementById("cjkInput");R?.classList.contains("cjk-input-visible")?R.focus():this.terminal.focus()}},{passive:!0}),s.addEventListener("touchcancel",()=>{v=!1,y=0,m=0},{passive:!0})}s.addEventListener("click",n=>this._handleDesktopTerminalClick(n)),this.showWelcome(),this.initImageInput(),this._chunkedWriteGen=0,this._bufferLoadSeq=0,this._bufferLoadOwner=null,this._lastUserScrollUpAt=null,this._resizeTimeout=null,this._lastResizeDims=null;const T=40,C=10,I=()=>{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 n=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;if(this.activeSessionId&&!n){const g=this.fitAddon.proposeDimensions(),u=g?Math.max(g.cols,T):T,y=g?Math.max(g.rows,C):C;if(!this._lastResizeDims||u!==this._lastResizeDims.cols||y!==this._lastResizeDims.rows){const b=this.activeSessionId?this.sessions.get(this.activeSessionId):null;b&&b.mode!=="shell"&&this.terminal&&this.isTerminalAtBottom()&&this.terminal.write("\x1B[3J\x1B[H\x1B[2J"),this._lastResizeDims={cols:u,rows:y};const w=typeof MobileDetection<"u"&&MobileDetection.getDeviceType?MobileDetection.getDeviceType():"desktop";let v=!1;if(this._wsReady&&this._wsSessionId===this.activeSessionId)try{this._ws.send(JSON.stringify({t:"z",c:u,r:y,v:w})),v=!0}catch{}v||fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:u,rows:y,viewportType:w})}).catch(()=>{})}}this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},300)};window.addEventListener("resize",I),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(I),this.terminalResizeObserver.observe(s),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const _=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const n=this._pendingInput,g=this.activeSessionId;this._pendingInput="",this._sendInputAsync(g,n)}};this.terminal.onData(n=>{if(!/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(n)&&(window.cjkActive||document.activeElement?.id==="cjkInput")){const u=document.getElementById("cjkInput");u?.classList.contains("cjk-input-visible")&&document.activeElement===this.terminal.textarea&&!window.CodemanTerminalInput?.shouldSuppressTerminalQueryResponse(n)&&(_crashDiag.log("CJK regain-focus (onData swallowed input)"),u.focus());return}if(this.activeSessionId){if(window.CodemanTerminalInput?.shouldSuppressTerminalQueryResponse(n))return;this._lastTerminalData={data:n,time:performance.now()};const u=this._localEchoEnabled&&this._echoPassthroughSessions?.has(this.activeSessionId);if(u&&(n==="\r"||n==="")&&this._echoPassthroughSessions.delete(this.activeSessionId),this._localEchoEnabled&&!u){if(n==="\x7F"){const b=this._localEchoOverlay?.removeChar();if(b==="flushed"){const{count:w,text:v}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(w===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,w),this._flushedTexts?.set(this.activeSessionId,v))),this._pendingInput+=n,_()}else b===!1&&(this._pendingInput+=n,_());return}if(/^[\r\n]+$/.test(n)){const b=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),b&&(this._pendingInput+=b,_()),setTimeout(()=>{this._pendingInput+="\r",_()},80);return}if(n.length>1&&n.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(n);return}if(n.charCodeAt(0)<32){if(n.length>1&&n.charCodeAt(0)===27){if(n.startsWith(window.CodemanTerminalInput.BRACKETED_PASTE_START)){const w=!!this._localEchoOverlay?.pendingText;this._flushLocalEchoPending(),w?(_(),setTimeout(()=>{this._pendingInput+=n,_()},80)):(this._pendingInput+=n,_());return}if(window.CodemanTerminalInput.isComposerNavKey(n)){this._flushLocalEchoPending(),this._echoPassthroughSessions||(this._echoPassthroughSessions=new Set),this._echoPassthroughSessions.add(this.activeSessionId),this._pendingInput+=n,_();return}this._pendingInput+=n,_();return}if(this._restoringFlushedState){this._pendingInput+=n,_();return}if(n===" "){const w=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),w&&(this._pendingInput+=w),this._pendingInput+=n,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let v="";try{const m=this._localEchoOverlay?.findPrompt?.();if(m){const E=this.terminal.buffer.active,k=E.getLine(E.viewportY+m.row);k&&(v=k.translateToString(!0).slice(m.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=v,_(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const h=this;this._tabCompletionFallback=setTimeout(()=>{if(h._tabCompletionFallback=null,!h._tabCompletionSessionId||h._tabCompletionSessionId!==h.activeSessionId)return;const m=h._localEchoOverlay;!m||m.pendingText||h.terminal.write("",()=>{if(!h._tabCompletionSessionId)return;m.resetBufferDetection();const E=m.detectBufferText();E&&E!==h._tabCompletionBaseText&&(h._tabCompletionSessionId=null,h._tabCompletionRetries=0,h._tabCompletionBaseText=null,m.rerender())})},300);return}const b=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),b&&(this._pendingInput+=b),this._pendingInput+=n,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),_();return}if(n.length===1&&n.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(n);return}}if(this._predictHookOnData(n),this._pendingInput+=n,n.charCodeAt(0)<32||n.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),_();return}const y=performance.now();y-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=y,_()):(this._lastKeystrokeTime=y,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(_,0)))}})},registerFilePathLinkProvider(){const e=this;let t=-1;this.terminal.registerLinkProvider({provideLinks(s,i){s!==t&&(t=s,console.debug("[LinkProvider] Checking line:",s));const r=e.terminal.buffer.active;if(!r.getLine(s-1)){i(void 0);return}const o=e.terminal.cols,l=m=>r.getLine(m-1),d=m=>{if(m<=1)return!1;if(l(m)?.isWrapped)return!0;const E=l(m-1);return!!E&&E.translateToString(!0).length>=o},S=12;let c=s;for(;c>1&&s-c<S&&d(c);)c--;let p=s;for(;p<r.length&&p-c<S&&d(p+1);)p++;const T=[];for(let m=c;m<=p;m++){const E=l(m);if(!E)break;T.push(E.translateToString(m===p))}const C=T.join(""),I=m=>{let E=m;for(let k=0;k<T.length-1;k++){if(E<T[k].length)return{x:E+1,y:c+k};E-=T[k].length}return{x:E+1,y:c+T.length-1}};if(!C||!C.includes("/")){i(void 0);return}const _=[],n=/https?:\/\/(?:[^\s"'<>|;&)\]\x00-\x1f]|&(?!&))+/g,g=(m,E)=>{const k=m.replace(/[.,;:!?)&]+$/,""),A=C.indexOf(k,E);if(A===-1)return;const x=I(A),L=I(A+k.length);_.some(f=>f.range.start.x===x.x&&f.range.start.y===x.y)||_.push({text:k,range:{start:x,end:L},decorations:{pointerCursor:!0,underline:!0},activate(f,M){window.open(M,"_blank","noopener,noreferrer")},hover(){e._linkHovered=!0},leave(){e._linkHovered=!1}})},u=/\b(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]+\s+){0,4}(\/[^\s"'<>|;&\n\x00-\x1f]+)/g,y=/(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\n\x00-\x1f]*\.(?:log|txt|json|md|yaml|yml|csv|xml|sh|py|ts|js|png|jpe?g|gif|webp|bmp|svg|pdf))\b/g,b=/Bash\([^)]*?(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\)\n\x00-\x1f]+)/g,w=new Set(["png","jpg","jpeg","gif","webp","bmp","svg","pdf"]),v=(m,E)=>{const k=C.indexOf(m,E);if(k===-1)return;const A=I(k),x=I(k+m.length);_.some(L=>L.range.start.x===A.x&&L.range.start.y===A.y)||_.push({text:m,range:{start:A,end:x},decorations:{pointerCursor:!0,underline:!0},activate(L,f){const M=(f.split(".").pop()||"").toLowerCase();if(w.has(M)){e.openFilePreview(f,e.activeSessionId);return}e.openLogViewerWindow(f,e.activeSessionId)},hover(){e._linkHovered=!0},leave(){e._linkHovered=!1}})};let h;for(n.lastIndex=0;(h=n.exec(C))!==null;)g(h[0],h.index);for(u.lastIndex=0;(h=u.exec(C))!==null;)v(h[2],h.index);for(y.lastIndex=0;(h=y.exec(C))!==null;)v(h[1],h.index);for(b.lastIndex=0;(h=b.exec(C))!==null;)v(h[1],h.index);_.length>0&&console.debug("[LinkProvider] Found links:",_.map(m=>m.text)),i(_.length>0?_:void 0)}}),console.log("[LinkProvider] File path link provider registered")},showWelcome(){if(this.shouldUseMobileOverview?.()){const t=document.getElementById("welcomeOverlay");t&&t.classList.remove("visible"),this.hideHomeSessions?.(),this.showMobileOverview(),this._updateCjkInputState?.();return}this.hideMobileOverview?.();const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus(),this.applyWelcomeCliVisibility(),this.loadHistorySessions(),this.initSearchPanel(),this.showHomeSessions?.()),this._updateCjkInputState?.()},hideWelcome(){this.hideMobileOverview?.(),this.hideHomeSessions?.();const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const t=document.getElementById("welcomeQr");t&&(clearTimeout(this._welcomeQrShrinkTimer),t.classList.remove("expanded")),this._updateCjkInputState?.()},async _fetchHistorySessions(){const s=(await(await fetch("/api/history/sessions")).json()).data?.sessions||[];if(s.length===0)return[];const i=new Map;for(const a of s){const o=a.projectKey||a.workingDir;i.has(o)||i.set(o,[]),i.get(o).push(a)}const r=[];for(const[,a]of i)r.push(...a.slice(0,3));return r.sort((a,o)=>new Date(o.lastModified)-new Date(a.lastModified)),r},async _fetchUnifiedSessions(e=60){const t=await fetch("/api/sessions/unified?limit="+e),s=await t.json().catch(()=>null);if(!t.ok||!s||s.success===!1||!s.data)throw new Error(s?.error||`unified sessions request failed (HTTP ${t.status})`);return s.data.sessions||[]},_resolveCaseLabel(e,t){if(!e)return"";let s=null;for(const i of t||[])if(!(!i||!i.path)){if(e===i.path)return`#${i.name}`;if(e.startsWith(i.path+"/")){const r=i.path.length;(!s||r>s.len)&&(s={name:i.name,suffix:e.slice(r),len:r})}}return s?`#${s.name}${s.suffix}`:e.split("/").pop()||e},_shortenHomePath(e){return(e||"").replace(/^\/home\/[^/]+\//,"~/").replace(/^\/Users\/[^/]+\//,"~/")},_buildHistoryItem(e,t,s){const i=s?.showViewAll!==!1,r=typeof e.sizeBytes=="number",a=r?e.sizeBytes<1024?`${e.sizeBytes}B`:e.sizeBytes<1048576?`${(e.sizeBytes/1024).toFixed(0)}K`:`${(e.sizeBytes/1048576).toFixed(1)}M`:"",o=typeof e.lastActivityAt=="number"?e.lastActivityAt:e.lastModified?Date.parse(e.lastModified):NaN;let l="";if(!Number.isNaN(o)){const f=new Date(o);l=f.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+f.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1})}const d=this._shortenHomePath(e.workingDir),S=this._resolveCaseLabel(e.workingDir,t),c=Array.isArray(e.sources)&&e.sources.includes("live"),p=e.pinned===!0,T=document.createElement("div");T.className="history-item"+(p?" is-pinned":""),T.title=e.workingDir||"";const C=document.createElement("div");C.className="history-item-main",C.addEventListener("click",s?.onActivate||(()=>{c&&this.sessions.has(e.sessionId)?this.selectSession(e.sessionId):this.resumeHistorySession(e.claudeSessionId||e.sessionId,e.workingDir||"",e.name)}));const I=document.createElement("div");I.className="history-item-text";const _=document.createElement("span");if(_.className="history-item-title",p){const f=document.createElement("span");f.className="history-item-pin",f.textContent="\u{1F4CC}",f.setAttribute("aria-label","Pinned"),f.title="Pinned",_.appendChild(f)}_.appendChild(document.createTextNode(e.name||e.firstPrompt||d));const n=document.createElement("div");if(n.className="history-item-badges",e.mode){const f=document.createElement("span");f.className="history-item-badge history-item-badge-mode",f.textContent=e.mode,n.appendChild(f)}if(c){const f=document.createElement("span");f.className="history-item-badge history-item-badge-live",f.textContent="LIVE",n.appendChild(f)}const g=document.createElement("span");g.className="history-item-subtitle",S.startsWith("#")&&g.classList.add("is-case"),g.textContent=S,I.append(_),n.childElementCount>0&&I.append(n),I.append(g);const u=document.createElement("span");u.className="history-item-meta",u.textContent=l;const y=document.createElement("button");y.className="history-item-expand",y.type="button",y.setAttribute("aria-haspopup","menu"),y.setAttribute("aria-label","Session actions"),y.setAttribute("aria-expanded","false"),y.textContent="\u22EF",C.append(I,u,y);const b=document.createElement("div");b.className="history-item-detail",b.hidden=!0;const w=document.createElement("div");w.className="history-detail-row";const v=document.createElement("span");v.className="history-detail-label",v.textContent="Prompt";const h=document.createElement("span");h.className="history-detail-value history-detail-prompt",h.textContent=e.firstPrompt||"(no prompt captured)",w.append(v,h);let m=null;if(e.lastPrompt&&e.lastPrompt!==e.firstPrompt){m=document.createElement("div"),m.className="history-detail-row";const f=document.createElement("span");f.className="history-detail-label",f.textContent="Last prompt";const M=document.createElement("span");M.className="history-detail-value history-detail-prompt",M.textContent=e.lastPrompt,m.append(f,M)}const E=document.createElement("div");E.className="history-detail-row";const k=document.createElement("span");k.className="history-detail-label",k.textContent="Path";const A=document.createElement("span");A.className="history-detail-value history-detail-path",A.textContent=d,E.append(k,A);const x=document.createElement("div");x.className="history-detail-row history-detail-meta";const L=[];if(l&&L.push(l),r&&L.push(a),L.push(e.sessionId.slice(0,8)),x.textContent=L.join(" \xB7 "),b.append(w),m&&b.append(m),b.append(E,x),i&&e.projectKey){const f=document.createElement("div");f.className="history-detail-row history-detail-actions";const M=document.createElement("button");M.type="button",M.className="history-view-all-btn",M.textContent="View all in this folder",M.addEventListener("click",R=>{R.stopPropagation(),this.openFolderHistoryModal(e.projectKey,e.workingDir,t)}),f.appendChild(M),b.appendChild(f)}return y.addEventListener("click",f=>{f.stopPropagation(),f.preventDefault(),this._openSessionRowMenu(f.currentTarget,e,t,T,b)}),T.append(C,b),T},_openSessionRowMenu(e,t,s,i,r){if(this._openRowMenuClose)try{this._openRowMenuClose()}catch{}const a=Array.isArray(t.sources)&&t.sources.includes("live")&&this.sessions.has(t.sessionId),o=document.createElement("div");o.className="session-row-menu",o.setAttribute("role","menu");let l=null,d=null,S=null;const c=()=>{document.removeEventListener("mousedown",l,!0),document.removeEventListener("keydown",d,!0),window.removeEventListener("scroll",S,!0),window.removeEventListener("resize",S,!0);try{o.remove()}catch{}this._openRowMenuEl===o&&(this._openRowMenuEl=null,this._openRowMenuClose=null)},p=(u,y,b)=>{const w=document.createElement("button");w.type="button",w.className="session-row-menu-item",w.setAttribute("role","menuitem");const v=document.createElement("span");if(v.className="session-row-menu-label",v.textContent=u,w.appendChild(v),b&&b.sublabel){const h=document.createElement("span");h.className="session-row-menu-sublabel",h.textContent=b.sublabel,w.appendChild(h)}w.addEventListener("click",async h=>{h.stopPropagation(),h.preventDefault(),await y()}),o.appendChild(w)};p(a?"Switch to session":"Resume session",()=>{a?this.selectSession(t.sessionId):this.resumeHistorySession(t.claudeSessionId||t.sessionId,t.workingDir||"",t.name),this.closeSessionManager?.(),c()});const T=t.pinned===!0;p(T?"Unpin session":"Pin to top",async()=>{await this._setSessionPinned(t.sessionId,!T)?(t.pinned=!T,this.showToast(T?"Unpinned":"Pinned to top","success")):this.showToast("Pin failed","error"),c()}),a&&p("Open folder",()=>{this.selectSession(t.sessionId),this.loadFileBrowser?.(t.sessionId),this.closeSessionManager?.(),c()}),t.workingDir&&p("Copy path",async()=>{const u=await this._copyText(t.workingDir);this.showToast(u?"Path copied":"Copy failed",u?"success":"error"),c()}),p("Show details",()=>{const u=i.classList.toggle("expanded");r.hidden=!u,e.setAttribute("aria-expanded",u?"true":"false"),c()}),document.body.appendChild(o);const C=e.getBoundingClientRect(),I=o.getBoundingClientRect(),_=4;let n=C.bottom+_;n+I.height>window.innerHeight&&C.top-_-I.height>=0&&(n=C.top-_-I.height);let g=C.right-I.width;g<_&&(g=_),g+I.width>window.innerWidth-_&&(g=Math.max(_,window.innerWidth-_-I.width)),o.style.top=`${Math.max(_,n)}px`,o.style.left=`${g}px`,l=u=>{o.contains(u.target)||e.contains(u.target)||c()},d=u=>{u.key==="Escape"&&(u.stopPropagation(),c())},S=()=>c(),document.addEventListener("mousedown",l,!0),document.addEventListener("keydown",d,!0),window.addEventListener("scroll",S,!0),window.addEventListener("resize",S,!0),this._openRowMenuEl=o,this._openRowMenuClose=c},async _setSessionPinned(e,t){try{const s=await fetch(`/api/sessions/${encodeURIComponent(e)}/pin`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({pinned:t})});return s.ok?(await s.json())?.success===!0:!1}catch(s){return console.error("[_setSessionPinned]",s),!1}},_HISTORY_INITIAL_COUNT:4,async loadHistorySessions(){const e=document.getElementById("historySessions"),t=document.getElementById("historyList");if(!(!e||!t))try{const s=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(()=>[]),[i,r]=await Promise.all([this._fetchUnifiedSessions(60),s]);if(i.length===0){e.style.display="none";return}t.replaceChildren();const a=this._HISTORY_INITIAL_COUNT;for(let o=0;o<Math.min(a,i.length);o++)t.appendChild(this._buildHistoryItem(i[o],r));if(i.length>a){const o=document.createElement("button");o.className="history-show-more",o.textContent=`Show ${i.length-a} more`,o.addEventListener("click",()=>{for(let l=a;l<i.length;l++)t.insertBefore(this._buildHistoryItem(i[l],r),o);o.remove()}),t.appendChild(o)}e.style.display=""}catch(s){console.error("[loadHistorySessions]",s),e.style.display="none"}},_FOLDER_HISTORY_PAGE_SIZE:20,openFolderHistoryModal(e,t,s){this._closeFolderHistoryModal();const i=document.createElement("div");i.className="modal active folder-history-modal",i.id="folderHistoryModal";const r=document.createElement("div");r.className="modal-backdrop",r.addEventListener("click",()=>this._closeFolderHistoryModal());const a=document.createElement("div");a.className="modal-content modal-lg";const o=document.createElement("div");o.className="modal-header";const l=document.createElement("h3");l.textContent="Folder History";const d=document.createElement("div");d.className="folder-history-subtitle",d.textContent=this._shortenHomePath(t);const S=document.createElement("button");S.className="modal-close",S.setAttribute("aria-label","Close"),S.innerHTML="&times;",S.addEventListener("click",()=>this._closeFolderHistoryModal()),o.append(l,S);const c=document.createElement("div");c.className="modal-body";const p=document.createElement("div");p.className="folder-history-list",p.setAttribute("data-loading","true"),p.textContent="Loading...",c.append(d,p),a.append(o,c),i.append(r,a),document.body.appendChild(i),this._folderHistoryState={projectKey:e,workingDir:t,cases:s||[],offset:0,total:null,list:p},this._folderHistoryEscHandler=T=>{T.key==="Escape"&&this._closeFolderHistoryModal()},document.addEventListener("keydown",this._folderHistoryEscHandler),this._loadFolderHistoryPage()},async _loadFolderHistoryPage(){const e=this._folderHistoryState;if(!e)return;const{projectKey:t,cases:s,list:i}=e,r=this._FOLDER_HISTORY_PAGE_SIZE,a=e.offset,o=i.querySelector(".folder-history-more");o&&o.remove(),a===0&&(i.replaceChildren(),i.removeAttribute("data-loading"));try{const l=`/api/history/sessions?projectKey=${encodeURIComponent(t)}&offset=${a}&limit=${r}`,S=await(await fetch(l)).json(),c=S.data?.sessions||[];if(e.total=typeof S.data?.total=="number"?S.data.total:c.length+a,a===0&&c.length===0){const p=document.createElement("div");p.className="folder-history-empty",p.textContent="No conversations found in this folder.",i.appendChild(p);return}for(const p of c)i.appendChild(this._buildHistoryItem(p,s,{showViewAll:!1}));if(e.offset=a+c.length,e.offset<e.total){const p=e.total-e.offset,T=document.createElement("button");T.className="history-show-more folder-history-more",T.textContent=`Show ${Math.min(r,p)} more (${p} remaining)`,T.addEventListener("click",()=>this._loadFolderHistoryPage()),i.appendChild(T)}}catch(l){console.error("[loadFolderHistoryPage]",l);const d=document.createElement("div");d.className="folder-history-empty",d.textContent="Failed to load folder history.",i.appendChild(d)}},_closeFolderHistoryModal(){const e=document.getElementById("folderHistoryModal");e&&e.remove(),this._folderHistoryEscHandler&&(document.removeEventListener("keydown",this._folderHistoryEscHandler),this._folderHistoryEscHandler=null),this._folderHistoryState=null},_resolveResumeName(e,t){if(typeof e=="string"&&e.trim())return e;const s=(t||"").split("/").pop()||"session";let i=1;for(const[,r]of this.sessions){const a=r.name&&r.name.match(/^w(\d+)-/);if(a){const o=parseInt(a[1]);o>=i&&(i=o+1)}}return`w${i}-${s}`},async resumeHistorySession(e,t,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=this._resolveResumeName(s,t),a=(this.cases||[]).find(T=>T.path===t)?.name||t.split("/").pop()||"",o=this.loadAppSettingsFromStorage(),l=this.buildEnvOverrides(this.getCaseSettings(a),o),d=this.getEffortSetting(o),c=await(await fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:t,name:i,resumeSessionId:e,...Object.keys(l).length>0?{envOverrides:l}:{},...d?{effort:d}:{}})})).json();if(!c.success)throw new Error(c.error);const p=c.data.session.id;await fetch(`/api/sessions/${p}/interactive`,{method:"POST"}),this.terminal.writeln(`\x1B[90m Session ${i} ready\x1B[0m`),await this.selectSession(p),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)},_maybeLoadMoreHistoryOnScroll(e){e>=0||this.terminal?.buffer?.active?.viewportY===0&&this._maybeRefetchFullHistory?.()},_estimateReplayRows(e,t){if(typeof e!="string"||!e)return 0;const s=t>0?t:80,i=e.replace(window.CodemanTerminalInput.REPLAY_ESCAPE_RE,"");let r=0;for(const a of i.split(`
2
- `)){const o=a.endsWith("\r")?a.length-1:a.length;r+=o>s?Math.ceil(o/s):1}return r},_replayWouldShrinkBuffer(e){const t=this.terminal,s=t?.buffer?.active?.length||0;if(!s)return!1;const i=t?.rows||24;return this._estimateReplayRows(e,t?.cols)+i<s},_smoothScrollBy(e){if(!e||(this._smoothScrollPending=(this._smoothScrollPending||0)+e,this._smoothScrollSession=this.activeSessionId,this._smoothScrollFrame))return;const t=()=>{this._smoothScrollFrame=null;const s=this._smoothScrollPending||0;if(!s)return;if(this.activeSessionId!==this._smoothScrollSession){this._smoothScrollPending=0;return}if(Math.abs(s)<1)return;const i=s*.22,r=s>0?Math.max(1,Math.floor(i)):Math.min(-1,Math.ceil(i));this._smoothScrollPending=s-r,this.terminal.scrollLines(r),this._maybeLoadMoreHistoryOnScroll(r),Math.abs(this._smoothScrollPending)>=1&&(this._smoothScrollFrame=requestAnimationFrame(t))};this._smoothScrollFrame=requestAnimationFrame(t)},_forwardScrollToApp(e,t,s){this._terminalViewportAtBottom()||this.terminal.scrollToBottom(),this._sendSyntheticSgrWheel(e,t,s)},_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._scheduleTerminalWriteFlush()},_scheduleTerminalWriteFlush(){this.writeFrameScheduled||this.pendingWrites.length===0||(this.writeFrameScheduled=!0,this._safeYield(()=>{this.writeFrameScheduled=!1,this.flushPendingWrites()}))},flushFlickerBuffer(){this.flickerFilterBuffer&&(this.pendingWrites.push(this.flickerFilterBuffer),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this._scheduleTerminalWriteFlush())},_flushLocalEchoPending(){const e=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),e&&(this._pendingInput+=e)},_updateLocalEchoState(){const e=this.loadAppSettingsFromStorage(),t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,s=e.localEchoEnabled??MobileDetection.isTouchDevice(),i=!!(s&&t);this._localEchoEnabled&&!i&&this._localEchoOverlay?.clear(),this._localEchoEnabled=i,this._localEchoOverlay&&t&&(t.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:a=>{try{const o=a.buffer.active,l=o.cursorY,d=o.getLine(o.viewportY+l);if(!d)return null;const c=d.translateToString(!0).indexOf("\u2503");return c>=0?{row:l,col:c}:null}catch{return null}}}):t.mode==="shell"||t.mode==="codex"?(this._localEchoOverlay.clear(),this._localEchoEnabled=!1):this._localEchoOverlay.setPrompt({type:"custom",offset:0,find:a=>{try{const o=a.buffer.active;for(let l=a.rows-1;l>=0;l--){const d=o.getLine(o.viewportY+l);if(!d)continue;const c=d.translateToString(!0).lastIndexOf("\u276F");if(c>=0)return{row:l,col:c+2}}return{row:Math.max(0,Math.min(a.rows-1,o.cursorY)),col:Math.max(0,Math.min(a.cols-1,o.cursorX))}}catch{return null}}}));let r="off";t&&s&&(t.mode==="codex"?r="predict":t.mode!=="shell"&&(r="buffer")),this._localEchoPolicy=r,r!=="predict"&&this._predictiveEcho?.clearPredictions()},_predictHookOnData(e){if(!(this._localEchoPolicy!=="predict"||!this._predictiveEcho))try{const t=window.CodemanTerminalInput.classifyPredictInput(e);t==="char"?this._predictiveEcho.predictChar(e):t==="backspace"?this._predictiveEcho.predictBackspace():this._predictiveEcho.clearPredictions()}catch{}},_handleCjkInput(e){if(!this.activeSessionId){_crashDiag.log(`CJK send DROP no-session len=${e.length}`);return}this._localEchoPolicy==="predict"&&this._predictiveEcho?.clearPredictions(),_crashDiag.log(`CJK send\u2192${this.activeSessionId.slice(0,8)} len=${e.length}`),this._sendInputAsync(this.activeSessionId,e)},flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=performance.now(),t=this.pendingWrites.join("");this.pendingWrites=[];const s=t.length;s>16384&&_crashDiag.log(`FLUSH: ${(s/1024).toFixed(0)}KB`);const r=(this.activeSessionId&&this.sessions?this.sessions.get(this.activeSessionId):null)?.mode==="codex"?32768:65536;let a=!1;const o=this._hasRecentUserScrollUp()&&this.terminal.buffer?.active?this.terminal.buffer.active.viewportY:null;s<=r?this.terminal.write(t):(this.terminal.write(t.slice(0,r)),this.pendingWrites.push(t.slice(r)),a=!0,this._scheduleTerminalWriteFlush()),o!==null&&this.terminal.buffer?.active?.viewportY!==o&&typeof this.terminal.scrollToLine=="function"&&this.terminal.scrollToLine(o);const l=a?r:s,d=performance.now()-e;if((d>100||a)&&console.warn(`[CRASH-DIAG] flushPendingWrites: ${d.toFixed(0)}ms, ${(l/1024).toFixed(0)}KB written${a?", rest deferred":""} (total ${(s/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 S=this._localEchoOverlay,c=this;this.terminal.write("",()=>{if(!c._tabCompletionSessionId)return;S.resetBufferDetection();const p=S.detectBufferText();p?p===c._tabCompletionBaseText?(S.undoDetection(),c._tabCompletionRetries=(c._tabCompletionRetries||0)+1,c._tabCompletionRetries>60&&(c._tabCompletionSessionId=null,c._tabCompletionRetries=0)):(c._tabCompletionSessionId=null,c._tabCompletionRetries=0,c._tabCompletionBaseText=null,c._tabCompletionFallback&&(clearTimeout(c._tabCompletionFallback),c._tabCompletionFallback=null),S.rerender()):(c._tabCompletionRetries=(c._tabCompletionRetries||0)+1,c._tabCompletionRetries>60&&(c._tabCompletionSessionId=null,c._tabCompletionRetries=0))})}},_safeYield(e){let t=!1;const s=()=>{t||(t=!0,e())};requestAnimationFrame(s),setTimeout(s,50),this._workerYield(s)},_workerYield(e){try{if(this._yieldWorker===void 0){const t="onmessage=()=>setTimeout(()=>postMessage(0),0);",s=new Blob([t],{type:"application/javascript"}),i=URL.createObjectURL(s);this._yieldWorker=new Worker(i),URL.revokeObjectURL(i),this._yieldQueue=[],this._yieldWorker.onmessage=()=>{const r=this._yieldQueue.shift();r&&r()}}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,t=e.baseY+e.length;let s=-1;for(let i=t-1;i>=0;i--)if(e.getLine(i)?.translateToString(!0).trim()){s=i;break}if(s>=0&&typeof this.terminal.scrollToLine=="function"){let i=Math.max(0,s-this.terminal.rows+2);const r=Math.max(0,s);for(;i<r&&!e.getLine(i)?.translateToString(!0).trim();)i++;this.terminal.scrollToLine(i)}else this.terminal.scrollToBottom()},chunkedTerminalWrite(e,t=TERMINAL_CHUNK_SIZE,s){const i=++this._chunkedWriteGen,r=this._beginBufferLoad(s);return new Promise(a=>{if(!e||e.length===0){this._finishBufferLoad(r),a();return}const o=e.replace(DEC_SYNC_STRIP_RE,""),l=()=>{this._chunkedWriteGen===i&&this._finishBufferLoad(r),a()};if(o.length<=t){this.terminal.write(o,l);return}let d=0;const S=performance.now();let c=0;const p=()=>{if(this._chunkedWriteGen!==i){a();return}if(d>=o.length){const _=performance.now()-S;console.log(`[CRASH-DIAG] chunkedTerminalWrite complete: ${o.length} bytes in ${c} chunks, ${_.toFixed(0)}ms total`),this._safeYield(l);return}const T=performance.now(),C=o.slice(d,d+t);this.terminal.write(C);const I=performance.now()-T;c++,I>50&&console.warn(`[CRASH-DIAG] chunk #${c} write took ${I.toFixed(0)}ms (${C.length} bytes at offset ${d})`),d+=t,this._safeYield(p)};this._safeYield(p)})},_beginBufferLoad(e){this._bufferLoadSeq===void 0&&(this._bufferLoadSeq=0);const t=e===void 0?`buffer-${++this._bufferLoadSeq}`:e;return this._bufferLoadOwner=t,this._isLoadingBuffer=!0,this._loadBufferQueue=[],t},_finishBufferLoad(e,t){if(e!==void 0&&this._bufferLoadOwner!==e)return!1;const s=this._loadBufferQueue;if(this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._bufferLoadOwner=null,t?.flushQueued&&s&&s.length)for(const i of s)this.batchTerminalWrite(i);return!0},clearTerminal(){this.terminal.clear()},insertTerminalText(e){!this.activeSessionId||!e||(this._localEchoPolicy==="predict"&&this._predictiveEcho?.clearPredictions(),this._localEchoEnabled&&this._localEchoOverlay&&!this._echoPassthroughSessions?.has(this.activeSessionId)?this._localEchoOverlay.appendText(e):this.sendInput(e).catch(()=>{}),this.terminal?.focus())},clearTerminalInput(){if(this.activeSessionId){if(typeof CjkInput<"u"&&CjkInput.clear(),this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._pendingInput="",this._localEchoPolicy==="predict"&&this._predictiveEcho?.clearPredictions(),this._localEchoEnabled&&this._localEchoOverlay){const e=this._localEchoOverlay.getFlushed?.()||{count:0,text:""};this._localEchoOverlay.clear(),this._localEchoOverlay.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),e.count>0&&this.sendInput("\x7F".repeat(e.count)).catch(()=>{})}else this.sendInput("").catch(()=>{});this.showToast?.("Input cleared","success"),this.terminal?.focus()}},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,{force:!0}),this.showToast(`Terminal restored to ${e.cols}x${e.rows}`,"success")}catch(t){console.error("Failed to restore terminal size:",t),this.showToast("Failed to restore terminal size","error")}},sendPendingCtrlL(e){},shouldCopyTerminalSelectionFromShortcut(e){if(!e||e.type!=="keydown"||!e.ctrlKey&&!e.metaKey&&!e.altKey)return!1;const s=typeof this.getShortcutRegistry=="function"&&typeof this.matchesShortcutEvent=="function"?this.getShortcutRegistry().find(i=>i.id==="copy-selection"):null;return s?!s.disabled&&this.matchesShortcutEvent(e,s):!e.altKey&&(e.key||"").toLowerCase()==="c"},async copyTerminalSelection(e){const t=e??(this.terminal.hasSelection?.()?this.terminal.getSelection():"");if(!t)return!1;const s=await this._copyText(t);return s?(this.terminal.clearSelection?.(),this.showToast("Copied to clipboard","success")):this.showToast("Failed to copy","error"),this.terminal.focus(),s},async copyTerminal(){try{const e=this.terminal.buffer.active;let t="";for(let s=0;s<e.length;s++){const i=e.getLine(s);i&&(t+=i.translateToString(!0)+`
3
- `)}await navigator.clipboard.writeText(t.replace(/\n+$/,`
4
- `)),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,t=this.terminal.element.querySelector(".xterm-cursor"),s=this.terminal.element.querySelector(".xterm-screen");if(!(e instanceof HTMLElement)||!(t instanceof HTMLElement)||!(s instanceof HTMLElement))return;const i=t.getBoundingClientRect(),r=s.getBoundingClientRect();if(!i.width&&!i.height)return;const a=Math.max(0,Math.round(i.left-r.left)),o=Math.max(0,Math.round(i.top-r.top));e.style.setProperty("--xterm-helper-left",`${a}px`),e.style.setProperty("--xterm-helper-top",`${o}px`)}catch{}},_dispatchSyntheticTerminalClick(e,t){const s=this.terminal?.element;if(!s||!Number.isFinite(e)||!Number.isFinite(t))return;const i={bubbles:!0,cancelable:!0,view:window,clientX:e,clientY:t,screenX:e,screenY:t,button:0,detail:1};try{s.dispatchEvent(new MouseEvent("mousedown",{...i,buttons:1})),s.dispatchEvent(new MouseEvent("mouseup",{...i,buttons:0}))}catch{}},_sessionUsesServerMouseStrip(){const e=this.sessions?.get(this.activeSessionId)?.mode||"claude";return e==="claude"||e==="codex"||e==="gemini"},_terminalViewportAtBottom(){const e=this.terminal?.buffer?.active;return!e||e.viewportY>=e.baseY},_clientPointToCell(e,t){if(!this.terminal||!Number.isFinite(e)||!Number.isFinite(t))return null;const s=this.terminal.element?.querySelector(".xterm-screen"),i=this.terminal._core?._renderService?.dimensions?.css?.cell;if(!s||!i?.width||!i?.height)return null;const r=s.getBoundingClientRect(),a=Math.max(1,Math.min(this.terminal.cols,Math.floor((e-r.left)/i.width)+1)),o=Math.max(1,Math.min(this.terminal.rows,Math.floor((t-r.top)/i.height)+1));return{col:a,row:o}},_sendSyntheticSgrTap(e,t){if(!this.activeSessionId||!this._terminalViewportAtBottom())return;const s=this._clientPointToCell(e,t);s&&this._sendInputAsync(this.activeSessionId,`\x1B[<0;${s.col};${s.row}M\x1B[<0;${s.col};${s.row}m`)},_cliVersionAtLeast(e,t){if(typeof e!="string")return!1;const s=e.trim().replace(/^v/,"").split(".").map(Number);if(s.length!==3||s.some(r=>!Number.isFinite(r)))return!1;const i=t.split(".").map(Number);for(let r=0;r<3;r++)if(s[r]!==i[r])return s[r]>i[r];return!0},_wheelScrollLines(e){const t=this._wheelScrollLinesFloat(e);return t?Math.round(t)||(t>0?1:-1):0},_wheelScrollLinesFloat(e){const t=e.shiftKey&&Math.abs(e.deltaX)>Math.abs(e.deltaY)?e.deltaX:e.deltaY;return t?e.deltaMode===1?t:e.deltaMode===2?t*(this.terminal?.rows||24):t/25:0},_shouldForwardWheelToApp(e){if(e.shiftKey||this.loadAppSettingsFromStorage?.()?.terminalWheelLocalScrollback)return!1;const t=this.terminal?.modes?.mouseTrackingMode;if(t&&t!=="none")return!1;const s=this.sessions?.get(this.activeSessionId);return!((s?.mode||"claude")!=="claude"||!this._cliVersionAtLeast(s?.cliVersion,"2.1.187"))},_sendSyntheticSgrWheel(e,t,s){if(!this.activeSessionId||!s)return;const i=this._clientPointToCell(e,t);if(!i)return;const r=s<0?64:65,a=Math.min(Math.abs(s),5);this._queueScrollBytes(`\x1B[<${r};${i.col};${i.row}M`.repeat(a))},_queueScrollBytes(e){if(!e||!this.activeSessionId)return;const t=this._wheelSgrQueue||"";t.length>512||(this._wheelSgrQueue=t+e,!this._wheelSgrFlushTimer&&(this._wheelSgrFlushTimer=setTimeout(()=>this._flushWheelSgrQueue(),40)))},_localScrollbackIsHollow(){if((this.sessions?.get(this.activeSessionId)?.mode||"claude")!=="claude")return!1;const t=this.terminal?.buffer?.active;return!t||t.type==="alternate"?!1:(t.baseY||0)===0},_maybePageCliTranscript(e,t){if(!t||e?.shiftKey||!this.activeSessionId||!this._localScrollbackIsHollow())return!1;this._pageKeySession!==this.activeSessionId&&(this._pageKeySession=this.activeSessionId,this._pageKeyPending=0);const s=window.CodemanTerminalInput,i=Math.max(2,Math.round((this.terminal?.rows||24)*s.PAGE_KEY_SCREEN_FRACTION)),r=(this._pageKeyPending||0)+t,a=Math.trunc(r/i);if(this._pageKeyPending=r-a*i,a){const o=a<0?s.KEY_PAGE_UP:s.KEY_PAGE_DOWN;this._queueScrollBytes(o.repeat(Math.min(Math.abs(a),s.PAGE_KEY_MAX_PER_BATCH)))}return this._logScrollRouting("page-keys"),!0},_logScrollRouting(e){const t=this.activeSessionId||"(none)",s=this.sessions?.get(t),i=!!this.loadAppSettingsFromStorage?.()?.terminalWheelLocalScrollback,r=this.terminal?.modes?.mouseTrackingMode||"none",a=this.terminal?.buffer?.active?.baseY??-1,o=`${e}|${s?.mode}|${s?.cliVersion}|${i}|${r}|${a>0}`;this._scrollRoutingLogged||(this._scrollRoutingLogged=new Map),this._scrollRoutingLogged.get(t)!==o&&(this._scrollRoutingLogged.set(t,o),console.log(`[scroll] ${t} \u2192 ${e} (mode=${s?.mode||"?"}, cliVersion=${s?.cliVersion||"unknown"}, localScrollbackOptOut=${i}, mouseTracking=${r}, localScrollbackRows=${a})`))},_flushWheelSgrQueue(){this._wheelSgrFlushTimer=null;const e=this._wheelSgrQueue;this._wheelSgrQueue="",e&&this.activeSessionId&&this._sendInputEphemeral(this.activeSessionId,e)},_handleDesktopTerminalClick(e){if(!this.terminal||!e?.isTrusted||e.button!==0||e.detail!==1||e.shiftKey||e.altKey||e.ctrlKey||e.metaKey)return;const t=this.terminal.modes?.mouseTrackingMode;t&&t!=="none"||this._sessionUsesServerMouseStrip()&&(this.terminal.hasSelection?.()||this._linkHovered||performance.now()<=(this._trustedTapMouseSuppressUntil||0)||e.target?.closest?.(".xterm-screen")&&this._sendSyntheticSgrTap(e.clientX,e.clientY))},_installMobileTapMouseGuard(){const e=this.terminal?.element;if(!e||e._codemanTapMouseGuardInstalled||typeof MobileDetection<"u"&&MobileDetection.isTouchDevice&&!MobileDetection.isTouchDevice())return;e._codemanTapMouseGuardInstalled=!0;const t=s=>{const i=this._trustedTapMouseSuppressUntil||0;!s.isTrusted||performance.now()>i||(s.preventDefault(),s.stopImmediatePropagation())};e.addEventListener("mousedown",t,!0),e.addEventListener("mouseup",t,!0)},_suppressTrustedTapMouseEvents(){const e=window.CodemanTerminalInput?.TOUCH_COMPAT_MOUSE_SUPPRESS_MS||450;this._trustedTapMouseSuppressUntil=performance.now()+e},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(),this._predictiveEcho?.refreshFont()},loadFontSize(){const e=localStorage.getItem("codeman-font-size");if(e){const t=parseInt(e,10);t>=10&&t<=24&&(this.terminal.options.fontSize=t,document.getElementById("fontSizeDisplay").textContent=t)}},getTerminalDimensions(){const s=this.fitAddon?.proposeDimensions();return s?{cols:Math.max(s.cols,40),rows:Math.max(s.rows,10)}:null},async sendResize(e,t={}){this.fitAddon&&this.fitAddon.fit();const s=this.getTerminalDimensions();if(!s)return!1;const i=this._lastResizeDims,r=!i||i.cols!==s.cols||i.rows!==s.rows;this._lastResizeDims={cols:s.cols,rows:s.rows};const a=typeof MobileDetection<"u"&&MobileDetection.getDeviceType?MobileDetection.getDeviceType():window.innerWidth<430?"mobile":window.innerWidth<768?"tablet":"desktop";if(!t.forceHttp&&this._wsReady&&this._wsSessionId===e)try{const l={t:"z",c:s.cols,r:s.rows,v:a};return t.force&&(l.f=!0),this._ws.send(JSON.stringify(l)),r}catch{}const o={...s,viewportType:a};return t.force&&(o.force=!0),await fetch(`/api/sessions/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),r},async sendInput(e){!this.activeSessionId||!e||this._sendInputAsync(this.activeSessionId,e,{useMux:!0})},toggleDirInput(){const e=document.querySelector("#dirDisplay").parentElement,t=document.getElementById("dirInput");t.classList.contains("hidden")&&(t.classList.remove("hidden"),e.style.display="none",t.focus())},hideDirInput(){const e=document.querySelector("#dirDisplay").parentElement,t=document.getElementById("dirInput");setTimeout(()=>{t.classList.add("hidden"),e.style.display="";const s=t.value.trim();document.getElementById("dirDisplay").textContent=s||"No directory"},100)},applyTerminalSkin(e){const t={...window.CODEMAN_XTERM_THEMES[e]||window.CODEMAN_XTERM_THEMES["daylight-blue"]},s=window.codemanCurrentSkinIsLight(e)?4.5:1;if(this.terminal){this.terminal.options.minimumContrastRatio=s,this.terminal.options.theme=t,this._localEchoOverlay?.refreshFont(),this._predictiveEcho?.refreshFont();try{this.terminal.refresh(0,this.terminal.rows-1)}catch{}}if(this.teammateTerminals){for(const[,i]of this.teammateTerminals)if(i&&i.terminal){i.terminal.options.minimumContrastRatio=s,i.terminal.options.theme={...t};try{i.terminal.refresh(0,i.terminal.rows-1)}catch{}}}}}),(function(e){const i={session:"Sessions",event:"Events",file:"Files"};function r(a){if(!Number.isFinite(a))return"";const o=new Date(a);return o.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+o.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1})}e.CodemanSearch={SEARCH_DEBOUNCE_MS:250,SEARCH_LIMIT:60,SOURCE_LABELS:i,formatSearchTime:r}})(window),Object.assign(CodemanApp.prototype,{initSearchPanel(){const e=document.getElementById("searchInput");if(!e||this._searchPanelWired){this._searchPanelWired&&this._populateSearchCaseFilter();return}this._searchPanelWired=!0,this._searchTypes=new Set(["session","event","file"]),this._searchSecondary={caseLabel:"",status:"",days:""},this._searchDebounceTimer=null,this._searchSeq=0,this._searchLastData=null;const t=document.getElementById("searchClearBtn"),s=document.getElementById("searchResults");e.addEventListener("input",()=>{t&&(t.hidden=e.value.length===0),this._scheduleSearch()}),e.addEventListener("keydown",o=>{o.key==="Escape"&&e.value&&(o.stopPropagation(),this._clearSearch())}),t&&t.addEventListener("click",()=>this._clearSearch()),document.querySelectorAll("#searchFilters .search-filter-chip").forEach(o=>{o.addEventListener("click",()=>{const l=o.dataset.typeFilter;this._searchTypes.has(l)&&this._searchTypes.size===1||(this._searchTypes.has(l)?(this._searchTypes.delete(l),o.classList.remove("active")):(this._searchTypes.add(l),o.classList.add("active")),this._runSearch())})});const i=document.getElementById("searchCaseFilter"),r=document.getElementById("searchStatusFilter"),a=document.getElementById("searchDateFilter");i&&i.addEventListener("change",()=>{this._searchSecondary.caseLabel=i.value,this._renderSearch(this._searchLastData)}),r&&r.addEventListener("change",()=>{this._searchSecondary.status=r.value,this._renderSearch(this._searchLastData)}),a&&a.addEventListener("change",()=>{this._searchSecondary.days=a.value,this._renderSearch(this._searchLastData)}),this._populateSearchCaseFilter(),s&&(s.hidden=!0)},_populateSearchCaseFilter(){const e=document.getElementById("searchCaseFilter");if(!e)return;const t=Array.isArray(this.cases)?this.cases:[],s=Array.from(new Set(t.map(a=>a&&a.name).filter(Boolean))).sort(),i=e.value;e.innerHTML="";const r=document.createElement("option");r.value="",r.textContent="All cases",e.appendChild(r);for(const a of s){const o=document.createElement("option");o.value=a,o.textContent="#"+a,e.appendChild(o)}i&&s.includes(i)&&(e.value=i)},_scheduleSearch(){clearTimeout(this._searchDebounceTimer),this._searchDebounceTimer=setTimeout(()=>this._runSearch(),window.CodemanSearch.SEARCH_DEBOUNCE_MS)},_clearSearch(){const e=document.getElementById("searchInput"),t=document.getElementById("searchClearBtn");e&&(e.value=""),t&&(t.hidden=!0),this._searchLastData=null,this._renderSearch(null)},async _runSearch(){const e=document.getElementById("searchInput");if(!e)return;const t=e.value.trim();if(t.length===0){this._searchLastData=null,this._renderSearch(null);return}const s=Array.from(this._searchTypes),i=new URLSearchParams;i.set("q",t.slice(0,200)),s.length>0&&s.length<3&&i.set("types",s.join(",")),i.set("limit",String(window.CodemanSearch.SEARCH_LIMIT));const r=++this._searchSeq,a=await this._apiJson("/api/search?"+i.toString());r===this._searchSeq&&(a?this._searchLastData=a:this._searchLastData={query:t,groups:[],totalResults:0,truncated:!1,_error:!0},this._renderSearch(this._searchLastData))},_applySecondaryFilters(e){const{caseLabel:t,status:s,days:i}=this._searchSecondary;let r=e;if(t){const a="#"+t;r=r.filter(o=>(o.sessionName||"").includes(a)||o.sessionName===t)}if(s){const a=new Set((this.sessionOrder||[]).concat(Object.keys(this.sessions||{})));r=r.filter(o=>{const l=a.has(o.sessionId);return s==="active"?l:!l})}if(i){const a=Date.now()-Number(i)*24*60*60*1e3;r=r.filter(o=>Number.isFinite(o.timestamp)&&o.timestamp>=a)}return r},_renderSearch(e){const t=document.getElementById("searchResults"),s=document.getElementById("historyTitle"),i=document.getElementById("historyList");if(!t)return;const r=!!e;if(s&&(s.style.display=r?"none":""),i&&(i.style.display=r?"none":""),t.innerHTML="",!e){t.hidden=!0;return}if(t.hidden=!1,e._error){const l=document.createElement("div");l.className="search-empty",l.textContent="Search unavailable \u2014 check the query and try again.",t.appendChild(l);return}const a=(e.groups||[]).map(l=>({type:l.type,results:this._applySecondaryFilters(l.results||[])})).filter(l=>l.results.length>0);if(a.reduce((l,d)=>l+d.results.length,0)===0){const l=document.createElement("div");l.className="search-empty",l.textContent='No results for "'+(e.query||"")+'"',t.appendChild(l);return}for(const l of a){const d=document.createElement("div");d.className="search-group-header";const S=document.createElement("span");S.className="search-group-label",S.textContent=window.CodemanSearch.SOURCE_LABELS[l.type]||l.type;const c=document.createElement("span");c.className="search-group-count",c.textContent=String(l.results.length),d.append(S,c),t.appendChild(d);for(const p of l.results)t.appendChild(this._buildSearchResultCard(p))}if(e.truncated){const l=document.createElement("div");l.className="search-truncated",l.textContent="Showing the top matches \u2014 refine your search to narrow results.",t.appendChild(l)}},_buildSearchResultCard(e){const t=document.createElement("div");t.className="search-result-card",t.dataset.type=e.type,t.tabIndex=0,t.setAttribute("role","button");const s=document.createElement("div");s.className="search-result-top";const i=document.createElement("span");i.className="search-result-badge search-badge-"+e.type,i.textContent=(window.CodemanSearch.SOURCE_LABELS[e.type]||e.type).replace(/s$/,"");const r=document.createElement("span");r.className="search-result-name",r.textContent=e.sessionName||e.sessionId||"(session)";const a=document.createElement("span");a.className="search-result-time",a.textContent=window.CodemanSearch.formatSearchTime(e.timestamp),s.append(i,r,a);const o=document.createElement("div");o.className="search-result-snippet",o.textContent=e.snippet||"",t.append(s,o);const l=()=>this._jumpToSearchResult(e);return t.addEventListener("click",l),t.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),l())}),t},_jumpToSearchResult(e){const t=e&&e.jumpTo;if(t){typeof this.hideWelcome=="function"&&this.hideWelcome();try{t.kind==="run-summary"?this.openRunSummary(t.sessionId):t.kind==="file-preview"?this.openFilePreview(t.relativePath||"",t.sessionId,t.targetId||null):this.selectSession(t.sessionId)}catch(s){console.error("[search] jump failed",s)}}}});