aicodeman 1.18.0 → 1.18.2
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.
- package/README.md +4 -3
- package/README.zh-CN.md +3 -3
- package/dist/web/http-range.d.ts +44 -0
- package/dist/web/http-range.d.ts.map +1 -0
- package/dist/web/http-range.js +76 -0
- package/dist/web/http-range.js.map +1 -0
- package/dist/web/public/admin-ui.js.gz +0 -0
- package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
- package/dist/web/public/{app.a13ac13b.js → app.445f1584.js} +4 -6
- package/dist/web/public/app.445f1584.js.br +0 -0
- package/dist/web/public/app.445f1584.js.gz +0 -0
- package/dist/web/public/approvals-ui.js.gz +0 -0
- package/dist/web/public/{constants.42b8bbc9.js → constants.822a486d.js} +132 -35
- package/dist/web/public/constants.822a486d.js.br +0 -0
- package/dist/web/public/constants.822a486d.js.gz +0 -0
- package/dist/web/public/cron-ui.js.gz +0 -0
- package/dist/web/public/entrance-animations.js.gz +0 -0
- package/dist/web/public/home-sessions.js.gz +0 -0
- package/dist/web/public/i18n.86757605.js.gz +0 -0
- package/dist/web/public/image-input.ee16ad88.js.gz +0 -0
- package/dist/web/public/index.html +13 -8
- package/dist/web/public/index.html.br +0 -0
- package/dist/web/public/index.html.gz +0 -0
- package/dist/web/public/input-cjk.63794d0b.js.gz +0 -0
- package/dist/web/public/keyboard-accessory.0454a3e9.js.gz +0 -0
- package/dist/web/public/{mobile-handlers.32fdd57f.js → mobile-handlers.bc45f976.js} +55 -9
- package/dist/web/public/mobile-handlers.bc45f976.js.br +0 -0
- package/dist/web/public/mobile-handlers.bc45f976.js.gz +0 -0
- package/dist/web/public/mobile-overview.js.gz +0 -0
- package/dist/web/public/mobile.1eef31fe.css.gz +0 -0
- package/dist/web/public/notification-manager.5d229063.js.gz +0 -0
- package/dist/web/public/orchestrator-panel.js.gz +0 -0
- package/dist/web/public/{panels-ui.4255e1bc.js → panels-ui.1e4cb4b2.js} +1 -1
- package/dist/web/public/panels-ui.1e4cb4b2.js.br +0 -0
- package/dist/web/public/panels-ui.1e4cb4b2.js.gz +0 -0
- package/dist/web/public/ralph-panel.6de2d0f8.js.gz +0 -0
- package/dist/web/public/ralph-wizard.13a1831e.js.gz +0 -0
- package/dist/web/public/readmymind-ui.js.gz +0 -0
- package/dist/web/public/respawn-ui.ff0dae4c.js.gz +0 -0
- package/dist/web/public/sanitize-html.bc7078d6.js.gz +0 -0
- package/dist/web/public/session-lineage.js +3 -1
- package/dist/web/public/session-lineage.js.br +0 -0
- package/dist/web/public/session-lineage.js.gz +0 -0
- package/dist/web/public/session-ui.20be58fa.js.gz +0 -0
- package/dist/web/public/settings-ui.eacb4f92.js.gz +0 -0
- package/dist/web/public/styles.70bf9c2a.css +1 -0
- package/dist/web/public/styles.70bf9c2a.css.br +0 -0
- package/dist/web/public/styles.70bf9c2a.css.gz +0 -0
- package/dist/web/public/subagent-windows.2a192c3e.js.gz +0 -0
- package/dist/web/public/sw.js.gz +0 -0
- package/dist/web/public/{terminal-ui.5046620b.js → terminal-ui.c182a68d.js} +1 -1
- package/dist/web/public/{terminal-ui.5046620b.js.br → terminal-ui.c182a68d.js.br} +0 -0
- package/dist/web/public/{terminal-ui.5046620b.js.gz → terminal-ui.c182a68d.js.gz} +0 -0
- package/dist/web/public/ultracode-panel.js.gz +0 -0
- package/dist/web/public/ultracode-windows.js.gz +0 -0
- package/dist/web/public/upload.html.gz +0 -0
- package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
- package/dist/web/public/vendor/marked.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-predictive-echo.6cec0fba.js.gz +0 -0
- package/dist/web/public/vendor/xterm-zerolag-input.137ad9f0.js.gz +0 -0
- package/dist/web/public/vendor/xterm.css.gz +0 -0
- package/dist/web/public/vendor/xterm.min.js.gz +0 -0
- package/dist/web/public/voice-input.4ec670b0.js.gz +0 -0
- package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
- package/dist/web/public/webview-tabs.js.gz +0 -0
- package/dist/web/routes/file-routes.d.ts.map +1 -1
- package/dist/web/routes/file-routes.js +51 -18
- package/dist/web/routes/file-routes.js.map +1 -1
- package/dist/web/routes/session-routes.d.ts.map +1 -1
- package/dist/web/routes/session-routes.js +16 -0
- package/dist/web/routes/session-routes.js.map +1 -1
- package/package.json +1 -1
- package/skills/codeman/SKILL.md +251 -717
- package/skills/codeman/reference/endpoints.md +1 -1
- package/skills/codeman/reference/recipes.md +24 -11
- package/skills/codeman/reference/verbs.md +665 -0
- package/dist/web/public/app.a13ac13b.js.br +0 -0
- package/dist/web/public/app.a13ac13b.js.gz +0 -0
- package/dist/web/public/constants.42b8bbc9.js.br +0 -0
- package/dist/web/public/constants.42b8bbc9.js.gz +0 -0
- package/dist/web/public/mobile-handlers.32fdd57f.js.br +0 -0
- package/dist/web/public/mobile-handlers.32fdd57f.js.gz +0 -0
- package/dist/web/public/panels-ui.4255e1bc.js.br +0 -0
- package/dist/web/public/panels-ui.4255e1bc.js.gz +0 -0
- package/dist/web/public/styles.b6e8b4ae.css +0 -1
- package/dist/web/public/styles.b6e8b4ae.css.br +0 -0
- package/dist/web/public/styles.b6e8b4ae.css.gz +0 -0
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/dist/web/public/sw.js.gz
CHANGED
|
Binary file
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
"use strict";(function(e){const t=/^\x1b\[[\?>=]?[\d;]*[cnR]$/,s=/^\x1b\][\d;]*[^\x07\x1b]*(?:\x07|\x1b\\)$/,i=/^\x1b\[<\d+;\d+;\d+[Mm]$/,n=/^\x1b\[M[\s\S]{3}$/,r=/^\x1b\[[IO]$/,m=["input","textarea","select","button","a[href]",'[contenteditable=""]','[contenteditable="true"]','[tabindex]:not([tabindex="-1"])',".keyboard-accessory-bar",".path-picker-overlay"].join(","),c=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?<>=!]*[ -/]*[@-~]|\x1b[()#][0-9A-Za-z]|\x1b[=>78M]/g,h="\x1B[5~",T="\x1B[6~",M=.5,C=3,p=4,o=/^\x1b(?:\[(?:[ABCDHF]|1;[2-8][ABCDHF]|[1-8](?:;[2-8])?~)|O[ABCDHF])$/,_="\x1B[200~";function u(y){return o.test(y)}const w=/^› /;function b(y){const f=Array.from(y);if(f.length===1){const L=f[0].codePointAt(0);return L===127?"backspace":L>=32?"char":"clear"}return y.charCodeAt(0)===27?"clear":y.charCodeAt(0)>=32?"text":"clear"}function S(y){try{const f=y.buffer.active,L=f.getLine(f.baseY+f.cursorY);return!!L&&w.test(L.translateToString(!0))}catch{return!1}}function I(y){return t.test(y)||s.test(y)}function g(y){return I(y)}function E(y){return r.test(y)||i.test(y)||n.test(y)}const v={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"}},x=new Set(["paper-gray","solarized-light","catppuccin-latte","rose-pine-dawn"]);function k(){return typeof document<"u"&&document.documentElement.dataset.skin||"daylight-blue"}function R(){const y=k();return v[y]||v["daylight-blue"]}function A(y=k()){return x.has(y)}e.CodemanTerminalInput={isTerminalQueryResponse:I,shouldSuppressTerminalQueryResponse:g,isTerminalFocusOrMouseReport:E,isComposerNavKey:u,classifyPredictInput:b,isCodexComposerRow:S,CODEX_COMPOSER_ROW_RE:w,BRACKETED_PASTE_START:_,USER_SCROLL_STICKY_SUPPRESS_MS:1500,TOUCH_COMPAT_MOUSE_SUPPRESS_MS:450,REPLAY_ESCAPE_RE:c,KEY_PAGE_UP:h,KEY_PAGE_DOWN:T,PAGE_KEY_SCREEN_FRACTION:M,PAGE_KEY_MAX_PER_BATCH:C,TUI_PROMPT_DEFAULT_ROWS_FROM_BOTTOM:p,MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR:m,MOBILE_KEYBOARD_DISMISS_TAP_SLOP:8},e.CODEMAN_XTERM_THEMES=v,e.codemanCurrentXtermTheme=R,e.codemanCurrentSkinIsLight=A})(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 o=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(o),this.terminal.unicode.activeVersion="11"}catch{}const s=document.getElementById("terminalContainer");this.terminal.open(s),this._installMobileTapMouseGuard(),this.terminal.attachCustomKeyEventHandler(o=>{if(o.isComposing||o.keyCode===229||o.altKey&&!o.ctrlKey&&!o.shiftKey&&/^(Digit[1-9]|BracketLeft|BracketRight|KeyK)$/.test(o.code||"")||o.type==="keydown"&&this.shouldOpenCommandPaletteFromShortcut?.(o))return!1;if(this.shouldCopyTerminalSelectionFromShortcut?.(o)){const _=this.terminal.hasSelection?.()?this.terminal.getSelection():"";return _?(o.preventDefault(),this.copyTerminalSelection(_),!1):o.shiftKey?(o.preventDefault(),!1):!0}if((o.ctrlKey||o.metaKey)&&o.key==="v"&&o.type==="keydown")return this.activeSessionId&&this._handleImagePaste&&this._handleImagePaste(),!1;if(o.key==="Enter"&&(o.shiftKey||o.ctrlKey)&&o.type==="keydown"){if(this.activeSessionId)if(this._localEchoEnabled){const _=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),_&&(this._pendingInput+=_,p()),setTimeout(()=>{fetch(`/api/sessions/${this.activeSessionId}/send-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:o.ctrlKey?"C-Enter":"S-Enter"})})},_?80:0)}else fetch(`/api/sessions/${this.activeSessionId}/send-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:o.ctrlKey?"C-Enter":"S-Enter"})});return!1}return!0});{const o=s.querySelector(".xterm-helper-textarea");if(o&&MobileDetection.isTouchDevice()){let _=!1,u=0;o.addEventListener("compositionstart",()=>{_=!0}),o.addEventListener("compositionend",()=>{_=!1}),o.addEventListener("keydown",w=>{!w.isComposing&&w.keyCode!==229&&(u=Date.now())}),o.addEventListener("input",w=>{if(_||w.isComposing||w.inputType!=="insertText"||!w.data||Date.now()-u<50)return;const b=w.data,S=this._localEchoOverlay?.pendingText||"";Promise.resolve().then(()=>{if(this._lastTerminalData?.data===b&&performance.now()-this._lastTerminalData.time<100){o.value="";return}const I=this._localEchoOverlay?.pendingText||"";if(this._localEchoEnabled&&I.length>S.length&&I.endsWith(b)){o.value="";return}const g=o.value;!g||g.trim()===""&&b!==" "||(this.terminal._core.coreService.triggerDataEvent(b,!0),o.value="")})})}}this._webglAddon=null;const i=new URLSearchParams(location.search),n=(()=>{try{const o=localStorage.getItem("codeman-webgl-disabled");if(!o)return!1;const{at:_}=JSON.parse(o);return Date.now()-_>WEBGL_FALLBACK.STICKY_EXPIRY_MS?(localStorage.removeItem("codeman-webgl-disabled"),!1):!0}catch{return!1}})(),r=this.loadAppSettingsFromStorage(),a=this.getDefaultSettings(),l=r.webglRendererEnabled??a.webglRendererEnabled,{skip:d,clearSticky:m}=shouldSkipWebGL({deviceType:MobileDetection.getDeviceType(),noWebglParam:i.has("nowebgl"),forceParam:i.get("webgl")==="force",stickyDisabled:n,userPrefEnabled:l});if(m)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}if(d&&n&&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 o=document.createElement("script");o.src="vendor/xterm-addon-webgl.min.js",o.onload=()=>this._initWebGL(),o.onerror=()=>console.warn("[CRASH-DIAG] Failed to load WebGL addon \u2014 using canvas renderer"),document.head.appendChild(o)}this._localEchoOverlay=new LocalEchoOverlay(this.terminal),this._predictiveEcho=typeof PredictiveEchoOverlay<"u"?new PredictiveEchoOverlay(this.terminal):null,this._predictiveEcho?.setPredictWhen(o=>window.CodemanTerminalInput.isCodexComposerRow(o)),MobileDetection.isTouchDevice()&&(this.terminal.onCursorMove(()=>this._syncMobileHelperTextareaToCursor()),this.terminal.onRender(()=>this._syncMobileHelperTextareaToCursor())),this._cjkInput=null,typeof CjkInput<"u"&&(this._cjkInput=CjkInput.init({send:o=>{this._handleCjkInput(o)}}));const c=this.terminal.focus.bind(this.terminal);this.terminal.focus=()=>{const o=document.getElementById("cjkInput");o?.classList.contains("cjk-input-visible")?o.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",o=>{const _=this.terminal?.modes?.mouseTrackingMode;if(_&&_!=="none"||this.terminal?.buffer?.active?.type==="alternate")return;if(o.preventDefault(),o.stopPropagation(),this._shouldForwardWheelToApp(o)){this._logScrollRouting("forward-sgr"),this._forwardScrollToApp(o.clientX,o.clientY,this._wheelScrollLines(o));return}const u=this._wheelScrollLinesFloat(o);this._maybePageCliTranscript(o,u)||(this._logScrollRouting("local-scrollback"),this._noteTerminalUserScroll(u),this._smoothScrollBy(u))},{passive:!1,capture:!0});{const o=()=>this.terminal._core?._renderService?.dimensions?.css?.cell?.height||13;let _=0,u=0,w=0,b=0,S=null,I=!1;const g=y=>{const f=b?(y-b)/16.67:1;if(b=y,!I&&Math.abs(w)>.3){const L=Math.round(w/o());L!==0&&(this._shouldForwardWheelToApp({shiftKey:!1})?this._forwardScrollToApp(_,u,L):this._maybePageCliTranscript({shiftKey:!1},L)||(this.terminal.scrollLines(L),this._maybeLoadMoreHistoryOnScroll(L))),w*=.92,S=requestAnimationFrame(g)}else I?S=requestAnimationFrame(g):(S=null,w=0)};let E=0,v=!1,x=0,k=!1,R=null;const A=window.CodemanTerminalInput.MOBILE_KEYBOARD_DISMISS_TAP_SLOP;s.addEventListener("touchstart",y=>{if(y.touches.length===1){_=y.touches[0].clientX,u=y.touches[0].clientY,x=u,w=0,E=0,I=!0,v=!1,k=this._isMobileTerminalInputFocused();const f=this._classifyMobileTerminalTap(_,u);R={x:_,y:u,intent:f},f==="content"&&(y.preventDefault(),this._blurMobileTerminalInput()),b=0,S&&(cancelAnimationFrame(S),S=null)}},{passive:!1}),s.addEventListener("touchmove",y=>{if(y.touches.length===1&&I){const f=y.touches[0].clientY;if(!v&&Math.abs(f-x)>=A&&(v=!0),!v)return;y.preventDefault();const L=u-f;E+=L,w=L*1.2,_=y.touches[0].clientX,u=f;const P=o(),O=Math.trunc(E/P);O!==0&&(this._shouldForwardWheelToApp({shiftKey:!1})?(this._logScrollRouting("forward-sgr"),this._forwardScrollToApp(_,u,O)):this._maybePageCliTranscript({shiftKey:!1},O)||(this._logScrollRouting("local-scrollback"),this._noteTerminalUserScroll(O),this.terminal.scrollLines(O),this._maybeLoadMoreHistoryOnScroll(O)),E-=O*P)}},{passive:!1}),s.addEventListener("touchend",y=>{if(I=!1,!S&&Math.abs(w)>.3&&(S=requestAnimationFrame(g)),!v&&this.terminal){const f=y.changedTouches&&y.changedTouches[0];if(f){this._suppressTrustedTapMouseEvents();const L=R&&R.x===f.clientX&&R.y===f.clientY?R.intent:null;this._handleMobileTerminalTap(f,k,L)}}k=!1},{passive:!0}),s.addEventListener("touchcancel",()=>{I=!1,w=0,E=0,k=!1},{passive:!0})}s.addEventListener("click",o=>this._handleDesktopTerminalClick(o)),this._installMobileKeyboardDismiss(),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,M=10,C=()=>{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 o=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;if(this.activeSessionId&&!o){const _=this.fitAddon.proposeDimensions(),u=_?Math.max(_.cols,T):T,w=_?Math.max(_.rows,M):M;if(!this._lastResizeDims||u!==this._lastResizeDims.cols||w!==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:w};const S=typeof MobileDetection<"u"&&MobileDetection.getDeviceType?MobileDetection.getDeviceType():"desktop";let I=!1;if(this._wsReady&&this._wsSessionId===this.activeSessionId)try{this._ws.send(JSON.stringify({t:"z",c:u,r:w,v:S})),I=!0}catch{}I||fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:u,rows:w,viewportType:S})}).catch(()=>{})}}this.applyLineageLineSettings?.(),this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},300)};window.addEventListener("resize",C),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(C),this.terminalResizeObserver.observe(s),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const p=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const o=this._pendingInput,_=this.activeSessionId;this._pendingInput="",this._sendInputAsync(_,o)}};this.terminal.onData(o=>{if(!/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(o)&&(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(o)&&(_crashDiag.log("CJK regain-focus (onData swallowed input)"),u.focus());return}if(this.activeSessionId){if(window.CodemanTerminalInput?.shouldSuppressTerminalQueryResponse(o))return;typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.isCtrlArmed?.()&&!window.CodemanTerminalInput?.isTerminalFocusOrMouseReport(o)&&(o=KeyboardAccessoryBar.consumeCtrl(o)),this._lastTerminalData={data:o,time:performance.now()};const u=this._localEchoEnabled&&this._echoPassthroughSessions?.has(this.activeSessionId);if(u&&(o==="\r"||o==="")&&this._echoPassthroughSessions.delete(this.activeSessionId),this._localEchoEnabled&&!u){if(o==="\x7F"){const b=this._localEchoOverlay?.removeChar();if(b==="flushed"){const{count:S,text:I}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(S===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,S),this._flushedTexts?.set(this.activeSessionId,I))),this._pendingInput+=o,p()}else b===!1&&(this._pendingInput+=o,p());return}if(/^[\r\n]+$/.test(o)){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,p()),setTimeout(()=>{this._pendingInput+="\r",p()},80);return}if(o.length>1&&o.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(o);return}if(o.charCodeAt(0)<32){if(o.length>1&&o.charCodeAt(0)===27){if(o.startsWith(window.CodemanTerminalInput.BRACKETED_PASTE_START)){const S=!!this._localEchoOverlay?.pendingText;this._flushLocalEchoPending(),S?(p(),setTimeout(()=>{this._pendingInput+=o,p()},80)):(this._pendingInput+=o,p());return}if(window.CodemanTerminalInput.isComposerNavKey(o)){this._flushLocalEchoPending(),this._echoPassthroughSessions||(this._echoPassthroughSessions=new Set),this._echoPassthroughSessions.add(this.activeSessionId),this._pendingInput+=o,p();return}this._pendingInput+=o,p();return}if(this._restoringFlushedState){this._pendingInput+=o,p();return}if(o===" "){const S=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),S&&(this._pendingInput+=S),this._pendingInput+=o,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let I="";try{const E=this._localEchoOverlay?.findPrompt?.();if(E){const v=this.terminal.buffer.active,x=v.getLine(v.viewportY+E.row);x&&(I=x.translateToString(!0).slice(E.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=I,p(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const g=this;this._tabCompletionFallback=setTimeout(()=>{if(g._tabCompletionFallback=null,!g._tabCompletionSessionId||g._tabCompletionSessionId!==g.activeSessionId)return;const E=g._localEchoOverlay;!E||E.pendingText||g.terminal.write("",()=>{if(!g._tabCompletionSessionId)return;E.resetBufferDetection();const v=E.detectBufferText();v&&v!==g._tabCompletionBaseText&&(g._tabCompletionSessionId=null,g._tabCompletionRetries=0,g._tabCompletionBaseText=null,E.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+=o,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),p();return}if(o.length===1&&o.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(o);return}}if(this._predictHookOnData(o),this._pendingInput+=o,o.charCodeAt(0)<32||o.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),p();return}const w=performance.now();w-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=w,p()):(this._lastKeystrokeTime=w,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(p,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 n=e.terminal.buffer.active;if(!n.getLine(s-1)){i(void 0);return}const a=e.terminal.cols,l=E=>n.getLine(E-1),d=E=>{if(E<=1)return!1;if(l(E)?.isWrapped)return!0;const v=l(E-1);return!!v&&v.translateToString(!0).length>=a},m=12;let c=s;for(;c>1&&s-c<m&&d(c);)c--;let h=s;for(;h<n.length&&h-c<m&&d(h+1);)h++;const T=[];for(let E=c;E<=h;E++){const v=l(E);if(!v)break;T.push(v.translateToString(E===h))}const M=T.join(""),C=E=>{let v=E;for(let x=0;x<T.length-1;x++){if(v<T[x].length)return{x:v+1,y:c+x};v-=T[x].length}return{x:v+1,y:c+T.length-1}};if(!M||!M.includes("/")){i(void 0);return}const p=[],o=/https?:\/\/(?:[^\s"'<>|;&)\]\x00-\x1f]|&(?!&))+/g,_=(E,v)=>{const x=E.replace(/[.,;:!?)&]+$/,""),k=M.indexOf(x,v);if(k===-1)return;const R=C(k),A=C(k+x.length);p.some(y=>y.range.start.x===R.x&&y.range.start.y===R.y)||p.push({text:x,range:{start:R,end:A},decorations:{pointerCursor:!0,underline:!0},activate(y,f){window.open(f,"_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,w=/(\/(?: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,S=new Set(["png","jpg","jpeg","gif","webp","bmp","svg","pdf"]),I=(E,v)=>{const x=M.indexOf(E,v);if(x===-1)return;const k=C(x),R=C(x+E.length);p.some(A=>A.range.start.x===k.x&&A.range.start.y===k.y)||p.push({text:E,range:{start:k,end:R},decorations:{pointerCursor:!0,underline:!0},activate(A,y){const f=(y.split(".").pop()||"").toLowerCase();if(S.has(f)){e.openFilePreview(y,e.activeSessionId);return}e.openLogViewerWindow(y,e.activeSessionId)},hover(){e._linkHovered=!0},leave(){e._linkHovered=!1}})};let g;for(o.lastIndex=0;(g=o.exec(M))!==null;)_(g[0],g.index);for(u.lastIndex=0;(g=u.exec(M))!==null;)I(g[2],g.index);for(w.lastIndex=0;(g=w.exec(M))!==null;)I(g[1],g.index);for(b.lastIndex=0;(g=b.exec(M))!==null;)I(g[1],g.index);p.length>0&&console.debug("[LinkProvider] Found links:",p.map(E=>E.text)),i(p.length>0?p: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 r of s){const a=r.projectKey||r.workingDir;i.has(a)||i.set(a,[]),i.get(a).push(r)}const n=[];for(const[,r]of i)n.push(...r.slice(0,3));return n.sort((r,a)=>new Date(a.lastModified)-new Date(r.lastModified)),n},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||[]},_worktreeLabel(e){const t=e&&e.worktreeName;if(!t)return"";let s=e.gitBranch||"";return(s===t||s===`worktree-${t}`)&&(s=""),s.length>24&&(s=s.slice(0,23)+"\u2026"),"\u2442 "+[t,s].filter(Boolean).join(" \xB7 ")},_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 n=i.path.length;(!s||n>s.len)&&(s={name:i.name,suffix:e.slice(n),len:n})}}return s?`#${s.name}${s.suffix}`:e.split("/").pop()||e},_shortenHomePath(e){return(e||"").replace(/^\/(?:home|Users)\/[^/]+(?=\/|$)/,"~")},_buildHistoryItem(e,t,s){const i=s?.showViewAll!==!1,n=typeof e.sizeBytes=="number",r=n?e.sizeBytes<1024?`${e.sizeBytes}B`:e.sizeBytes<1048576?`${(e.sizeBytes/1024).toFixed(0)}K`:`${(e.sizeBytes/1048576).toFixed(1)}M`:"",a=typeof e.lastActivityAt=="number"?e.lastActivityAt:e.lastModified?Date.parse(e.lastModified):NaN;let l="";if(!Number.isNaN(a)){const f=new Date(a);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),m=this._resolveCaseLabel(e.workingDir,t),c=Array.isArray(e.sources)&&e.sources.includes("live"),h=e.pinned===!0,T=document.createElement("div");T.className="history-item"+(h?" is-pinned":""),T.title=e.workingDir||"";const M=document.createElement("div");M.className="history-item-main",M.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 C=document.createElement("div");C.className="history-item-text";const p=document.createElement("span");if(p.className="history-item-title",h){const f=document.createElement("span");f.className="history-item-pin",f.textContent="\u{1F4CC}",f.setAttribute("aria-label","Pinned"),f.title="Pinned",p.appendChild(f)}p.appendChild(document.createTextNode(this._historyRowLabel(e,d)));const o=document.createElement("div");if(o.className="history-item-badges",e.mode){const f=document.createElement("span");f.className="history-item-badge history-item-badge-mode",f.textContent=e.mode,o.appendChild(f)}const _=this._worktreeLabel(e);if(_){const f=document.createElement("span");f.className="history-item-badge history-item-badge-worktree",f.textContent=_,f.title=e.worktreeRepo?`worktree of ${e.worktreeRepo}`:_,o.appendChild(f)}if(c){const f=document.createElement("span");f.className="history-item-badge history-item-badge-live",f.textContent="LIVE",o.appendChild(f)}const u=document.createElement("span");u.className="history-item-subtitle",m.startsWith("#")&&u.classList.add("is-case"),u.textContent=m,C.append(p),o.childElementCount>0&&C.append(o),C.append(u);const w=document.createElement("span");w.className="history-item-meta",w.textContent=l;const b=document.createElement("button");b.className="history-item-expand",b.type="button",b.setAttribute("aria-haspopup","menu"),b.setAttribute("aria-label","Session actions"),b.setAttribute("aria-expanded","false"),b.textContent="\u22EF",M.append(C,w,b);const S=document.createElement("div");S.className="history-item-detail",S.hidden=!0;const I=document.createElement("div");I.className="history-detail-row";const g=document.createElement("span");g.className="history-detail-label",g.textContent="Prompt";const E=document.createElement("span");E.className="history-detail-value history-detail-prompt",E.textContent=e.firstPrompt||"(no prompt captured)",I.append(g,E);let v=null;if(e.lastPrompt&&e.lastPrompt!==e.firstPrompt){v=document.createElement("div"),v.className="history-detail-row";const f=document.createElement("span");f.className="history-detail-label",f.textContent="Last prompt";const L=document.createElement("span");L.className="history-detail-value history-detail-prompt",L.textContent=e.lastPrompt,v.append(f,L)}const x=document.createElement("div");x.className="history-detail-row";const k=document.createElement("span");k.className="history-detail-label",k.textContent="Path";const R=document.createElement("span");R.className="history-detail-value history-detail-path",R.textContent=d,x.append(k,R);const A=document.createElement("div");A.className="history-detail-row history-detail-meta";const y=[];if(l&&y.push(l),n&&y.push(r),y.push(e.sessionId.slice(0,8)),A.textContent=y.join(" \xB7 "),S.append(I),v&&S.append(v),S.append(x,A),i&&e.projectKey){const f=document.createElement("div");f.className="history-detail-row history-detail-actions";const L=document.createElement("button");L.type="button",L.className="history-view-all-btn",L.textContent="View all in this folder",L.addEventListener("click",P=>{P.stopPropagation(),this.openFolderHistoryModal(e.projectKey,e.workingDir,t)}),f.appendChild(L),S.appendChild(f)}return b.addEventListener("click",f=>{f.stopPropagation(),f.preventDefault(),this._openSessionRowMenu(f.currentTarget,e,t,T,S)}),T.append(M,S),T},_openSessionRowMenu(e,t,s,i,n){if(this._openRowMenuClose)try{this._openRowMenuClose()}catch{}const r=Array.isArray(t.sources)&&t.sources.includes("live")&&this.sessions.has(t.sessionId),a=document.createElement("div");a.className="session-row-menu",a.setAttribute("role","menu");let l=null,d=null,m=null;const c=()=>{document.removeEventListener("mousedown",l,!0),document.removeEventListener("keydown",d,!0),window.removeEventListener("scroll",m,!0),window.removeEventListener("resize",m,!0);try{a.remove()}catch{}this._openRowMenuEl===a&&(this._openRowMenuEl=null,this._openRowMenuClose=null)},h=(u,w,b)=>{const S=document.createElement("button");S.type="button",S.className="session-row-menu-item",S.setAttribute("role","menuitem");const I=document.createElement("span");if(I.className="session-row-menu-label",I.textContent=u,S.appendChild(I),b&&b.sublabel){const g=document.createElement("span");g.className="session-row-menu-sublabel",g.textContent=b.sublabel,S.appendChild(g)}S.addEventListener("click",async g=>{g.stopPropagation(),g.preventDefault(),await w()}),a.appendChild(S)};h(r?"Switch to session":"Resume session",()=>{r?this.selectSession(t.sessionId):this.resumeHistorySession(t.claudeSessionId||t.sessionId,t.workingDir||"",t.name),this.closeSessionManager?.(),c()});const T=t.pinned===!0;h(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()}),r&&h("Open folder",()=>{this.selectSession(t.sessionId),this.loadFileBrowser?.(t.sessionId),this.closeSessionManager?.(),c()}),t.workingDir&&h("Copy path",async()=>{const u=await this._copyText(t.workingDir);this.showToast(u?"Path copied":"Copy failed",u?"success":"error"),c()}),h("Show details",()=>{const u=i.classList.toggle("expanded");n.hidden=!u,e.setAttribute("aria-expanded",u?"true":"false"),c()}),document.body.appendChild(a);const M=e.getBoundingClientRect(),C=a.getBoundingClientRect(),p=4;let o=M.bottom+p;o+C.height>window.innerHeight&&M.top-p-C.height>=0&&(o=M.top-p-C.height);let _=M.right-C.width;_<p&&(_=p),_+C.width>window.innerWidth-p&&(_=Math.max(p,window.innerWidth-p-C.width)),a.style.top=`${Math.max(p,o)}px`,a.style.left=`${_}px`,l=u=>{a.contains(u.target)||e.contains(u.target)||c()},d=u=>{u.key==="Escape"&&(u.stopPropagation(),c())},m=()=>c(),document.addEventListener("mousedown",l,!0),document.addEventListener("keydown",d,!0),window.addEventListener("scroll",m,!0),window.addEventListener("resize",m,!0),this._openRowMenuEl=a,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:10,_HISTORY_FETCH_LIMIT:200,_HISTORY_SORT_KEY:"codeman:historySort",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(r=>r.ok?r.json():null).then(r=>r?.data||[]).catch(()=>[]),[i,n]=await Promise.all([this._fetchUnifiedSessions(this._HISTORY_FETCH_LIMIT),s]);if(i.length===0){e.style.display="none";return}this._historyAll=i,this._historyCases=n,this._wireHistoryControls(),this._renderHistoryList(),e.style.display=""}catch(s){console.error("[loadHistorySessions]",s),e.style.display="none"}},_wireHistoryControls(){if(this._historyControlsWired)return;const e=document.getElementById("historyFilter"),t=document.getElementById("historySort");if(!(!e&&!t)){if(this._historyControlsWired=!0,t)try{const s=localStorage.getItem(this._HISTORY_SORT_KEY);s&&Array.from(t.options).some(i=>i.value===s)&&(t.value=s)}catch{}e&&(e.addEventListener("input",()=>this._renderHistoryList()),e.addEventListener("keydown",s=>{s.key==="Escape"&&e.value&&(s.stopPropagation(),e.value="",this._renderHistoryList())})),t&&t.addEventListener("change",()=>{try{localStorage.setItem(this._HISTORY_SORT_KEY,t.value)}catch{}this._renderHistoryList()})}},_historyRowMatches(e,t,s){return[e.name,e.workingDir,this._resolveCaseLabel(e.workingDir,s),e.firstPrompt,e.lastPrompt,e.sessionId].some(n=>typeof n=="string"&&n.toLowerCase().includes(t))},_historyRowLabel(e,t){return e.name||e.firstPrompt||t||""},_sortHistoryRows(e,t){const n=t==="name"?l=>this._historyRowLabel(l,this._shortenHomePath(l.workingDir)).toLowerCase():l=>((l.workingDir||"").split("/").pop()||"").toLowerCase(),r=t==="recent"?e.slice():e.slice().sort((l,d)=>n(l).localeCompare(n(d),void 0,{sensitivity:"base",numeric:!0})),a=r.filter(l=>l.pinned);return a.length===0?r:a.concat(r.filter(l=>!l.pinned))},_renderHistoryList(){const e=document.getElementById("historyList");if(!e)return;const t=this._historyAll||[],s=this._historyCases||[],i=document.getElementById("historyCount"),n=(document.getElementById("historyFilter")?.value||"").trim().toLowerCase(),r=document.getElementById("historySort")?.value||"recent",a=n?t.filter(h=>this._historyRowMatches(h,n,s)):t,l=this._sortHistoryRows(a,r),d=!!this._historyExpanded||n.length>0,m=d?l:l.slice(0,this._HISTORY_INITIAL_COUNT);if(e.replaceChildren(),e.classList.toggle("expanded",d),l.length===0){const h=document.createElement("div");h.className="history-empty",h.textContent=`No conversations match "${n}"`,e.appendChild(h)}for(const h of m)e.appendChild(this._buildHistoryItem(h,s));const c=l.length-m.length;if(c>0){const h=document.createElement("button");h.className="history-show-more",h.textContent=`Show ${c} more`,h.addEventListener("click",()=>{this._historyExpanded=!0,this._renderHistoryList()}),e.appendChild(h)}else if(d&&!n&&l.length>this._HISTORY_INITIAL_COUNT){const h=document.createElement("button");h.className="history-show-more",h.textContent="Show less",h.addEventListener("click",()=>{this._historyExpanded=!1,this._renderHistoryList(),e.scrollTop=0}),e.appendChild(h)}i&&(i.textContent=n?`${l.length} of ${t.length}`:l.length>m.length?`${m.length} of ${l.length}`:String(l.length))},_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 n=document.createElement("div");n.className="modal-backdrop",n.addEventListener("click",()=>this._closeFolderHistoryModal());const r=document.createElement("div");r.className="modal-content modal-lg";const a=document.createElement("div");a.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 m=document.createElement("button");m.className="modal-close",m.setAttribute("aria-label","Close"),m.innerHTML="×",m.addEventListener("click",()=>this._closeFolderHistoryModal()),a.append(l,m);const c=document.createElement("div");c.className="modal-body";const h=document.createElement("div");h.className="folder-history-list",h.setAttribute("data-loading","true"),h.textContent="Loading...",c.append(d,h),r.append(a,c),i.append(n,r),document.body.appendChild(i),this._folderHistoryState={projectKey:e,workingDir:t,cases:s||[],offset:0,total:null,list:h},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,n=this._FOLDER_HISTORY_PAGE_SIZE,r=e.offset,a=i.querySelector(".folder-history-more");a&&a.remove(),r===0&&(i.replaceChildren(),i.removeAttribute("data-loading"));try{const l=`/api/history/sessions?projectKey=${encodeURIComponent(t)}&offset=${r}&limit=${n}`,m=await(await fetch(l)).json(),c=m.data?.sessions||[];if(e.total=typeof m.data?.total=="number"?m.data.total:c.length+r,r===0&&c.length===0){const h=document.createElement("div");h.className="folder-history-empty",h.textContent="No conversations found in this folder.",i.appendChild(h);return}for(const h of c)i.appendChild(this._buildHistoryItem(h,s,{showViewAll:!1}));if(e.offset=r+c.length,e.offset<e.total){const h=e.total-e.offset,T=document.createElement("button");T.className="history-show-more folder-history-more",T.textContent=`Show ${Math.min(n,h)} more (${h} 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[,n]of this.sessions){const r=n.name&&n.name.match(/^w(\d+)-/);if(r){const a=parseInt(r[1]);a>=i&&(i=a+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),r=(this.cases||[]).find(T=>T.path===t)?.name||t.split("/").pop()||"",a=this.loadAppSettingsFromStorage(),l=this.buildEnvOverrides(this.getCaseSettings(r),a),d=this.getEffortSetting(a),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 h=c.data.session.id;await fetch(`/api/sessions/${h}/interactive`,{method:"POST"}),this.terminal.writeln(`\x1B[90m Session ${i} ready\x1B[0m`),await this.selectSession(h),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 n=0;for(const r of i.split(`
|
|
2
|
-
`)){const a=r.endsWith("\r")?r.length-1:r.length;n+=a>s?Math.ceil(a/s):1}return n},_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,n=s>0?Math.max(1,Math.floor(i)):Math.min(-1,Math.ceil(i));this._smoothScrollPending=s-n,this.terminal.scrollLines(n),this._maybeLoadMoreHistoryOnScroll(n),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:r=>{try{const a=r.buffer.active,l=a.cursorY,d=a.getLine(a.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:r=>{try{const a=r.buffer.active;for(let l=r.rows-1;l>=0;l--){const d=a.getLine(a.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(r.rows-1,a.cursorY)),col:Math.max(0,Math.min(r.cols-1,a.cursorX))}}catch{return null}}}));let n="off";t&&s&&(t.mode==="codex"?n="predict":t.mode!=="shell"&&(n="buffer")),this._localEchoPolicy=n,n!=="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}typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.isCtrlArmed?.()&&(e=KeyboardAccessoryBar.consumeCtrl(e)),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 n=(this.activeSessionId&&this.sessions?this.sessions.get(this.activeSessionId):null)?.mode==="codex"?32768:65536;let r=!1;const a=this._hasRecentUserScrollUp()&&this.terminal.buffer?.active?this.terminal.buffer.active.viewportY:null;s<=n?this.terminal.write(t):(this.terminal.write(t.slice(0,n)),this.pendingWrites.push(t.slice(n)),r=!0,this._scheduleTerminalWriteFlush()),a!==null&&this.terminal.buffer?.active?.viewportY!==a&&typeof this.terminal.scrollToLine=="function"&&this.terminal.scrollToLine(a);const l=r?n:s,d=performance.now()-e;if((d>100||r)&&console.warn(`[CRASH-DIAG] flushPendingWrites: ${d.toFixed(0)}ms, ${(l/1024).toFixed(0)}KB written${r?", 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 m=this._localEchoOverlay,c=this;this.terminal.write("",()=>{if(!c._tabCompletionSessionId)return;m.resetBufferDetection();const h=m.detectBufferText();h?h===c._tabCompletionBaseText?(m.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),m.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 n=this._yieldQueue.shift();n&&n()}}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 n=Math.max(0,s);for(;i<n&&!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,n=this._beginBufferLoad(s);return new Promise(r=>{if(!e||e.length===0){this._finishBufferLoad(n),r();return}const a=e.replace(DEC_SYNC_STRIP_RE,""),l=()=>{this._chunkedWriteGen===i&&this._finishBufferLoad(n),r()};if(a.length<=t){this.terminal.write(a,l);return}let d=0;const m=performance.now();let c=0;const h=()=>{if(this._chunkedWriteGen!==i){r();return}if(d>=a.length){const p=performance.now()-m;console.log(`[CRASH-DIAG] chunkedTerminalWrite complete: ${a.length} bytes in ${c} chunks, ${p.toFixed(0)}ms total`),this._safeYield(l);return}const T=performance.now(),M=a.slice(d,d+t);this.terminal.write(M);const C=performance.now()-T;c++,C>50&&console.warn(`[CRASH-DIAG] chunk #${c} write took ${C.toFixed(0)}ms (${M.length} bytes at offset ${d})`),d+=t,this._safeYield(h)};this._safeYield(h)})},_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)+`
|
|
2
|
+
`)){const a=r.endsWith("\r")?r.length-1:r.length;n+=a>s?Math.ceil(a/s):1}return n},_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,n=s>0?Math.max(1,Math.floor(i)):Math.min(-1,Math.ceil(i));this._smoothScrollPending=s-n,this.terminal.scrollLines(n),this._maybeLoadMoreHistoryOnScroll(n),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:r=>{try{const a=r.buffer.active,l=a.cursorY,d=a.getLine(a.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:r=>{try{const a=r.buffer.active;for(let l=r.rows-1;l>=0;l--){const d=a.getLine(a.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(r.rows-1,a.cursorY)),col:Math.max(0,Math.min(r.cols-1,a.cursorX))}}catch{return null}}}));let n="off";t&&s&&(t.mode==="codex"?n="predict":t.mode!=="shell"&&(n="buffer")),this._localEchoPolicy=n,n!=="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}typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.isCtrlArmed?.()&&(e=KeyboardAccessoryBar.consumeCtrl(e)),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 n=(this.activeSessionId&&this.sessions?this.sessions.get(this.activeSessionId):null)?.mode==="codex"?32768:65536;let r=!1;const a=this.terminal.buffer?.active&&!this.isTerminalAtBottom()?this.terminal.buffer.active.viewportY:null;s<=n?this.terminal.write(t):(this.terminal.write(t.slice(0,n)),this.pendingWrites.push(t.slice(n)),r=!0,this._scheduleTerminalWriteFlush()),a!==null&&this.terminal.buffer?.active?.viewportY!==a&&typeof this.terminal.scrollToLine=="function"&&this.terminal.scrollToLine(a);const l=r?n:s,d=performance.now()-e;if((d>100||r)&&console.warn(`[CRASH-DIAG] flushPendingWrites: ${d.toFixed(0)}ms, ${(l/1024).toFixed(0)}KB written${r?", 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 m=this._localEchoOverlay,c=this;this.terminal.write("",()=>{if(!c._tabCompletionSessionId)return;m.resetBufferDetection();const h=m.detectBufferText();h?h===c._tabCompletionBaseText?(m.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),m.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 n=this._yieldQueue.shift();n&&n()}}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 n=Math.max(0,s);for(;i<n&&!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,n=this._beginBufferLoad(s);return new Promise(r=>{if(!e||e.length===0){this._finishBufferLoad(n),r();return}const a=e.replace(DEC_SYNC_STRIP_RE,""),l=()=>{this._chunkedWriteGen===i&&this._finishBufferLoad(n),r()};if(a.length<=t){this.terminal.write(a,l);return}let d=0;const m=performance.now();let c=0;const h=()=>{if(this._chunkedWriteGen!==i){r();return}if(d>=a.length){const p=performance.now()-m;console.log(`[CRASH-DIAG] chunkedTerminalWrite complete: ${a.length} bytes in ${c} chunks, ${p.toFixed(0)}ms total`),this._safeYield(l);return}const T=performance.now(),M=a.slice(d,d+t);this.terminal.write(M);const C=performance.now()-T;c++,C>50&&console.warn(`[CRASH-DIAG] chunk #${c} write took ${C.toFixed(0)}ms (${M.length} bytes at offset ${d})`),d+=t,this._safeYield(h)};this._safeYield(h)})},_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
3
|
`)}await navigator.clipboard.writeText(t.replace(/\n+$/,`
|
|
4
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(),n=s.getBoundingClientRect();if(!i.width&&!i.height)return;const r=Math.max(0,Math.round(i.left-n.left)),a=Math.max(0,Math.round(i.top-n.top));e.style.setProperty("--xterm-helper-left",`${r}px`),e.style.setProperty("--xterm-helper-top",`${a}px`)}catch{}},_isMobileTerminalInputFocused(){const e=document.activeElement;return e===this.terminal?.textarea||e?.classList?.contains("xterm-helper-textarea")||e?.id==="cjkInput"},_classifyMobileTerminalTap(e,t){if(!this._terminalViewportAtBottom())return"history";const s=this._clientPointToCell(e,t);if(!s||!this.terminal)return"input";const i=this.terminal.modes?.mouseTrackingMode;if(!(!!i&&i!=="none")&&!this._sessionUsesServerMouseStrip())return"input";const r=this.terminal.buffer?.active;if(!r?.getLine)return"input";const a=Math.max(1,this.terminal.rows||1),l=[],d=[];let m=!1;for(let u=0;u<a;u++){const w=r.getLine(r.viewportY+u),b=w?.translateToString?.(!0)||"";l.push(b),d.push(!!w?.isWrapped),b.trim()&&(m=!0)}if(!m)return"input";const c=Math.max(0,Math.min(a-1,r.cursorY||0)),h=this.sessions?.get(this.activeSessionId)?.mode||"claude";let T=-1,M=!1;if(h==="opencode")l[c]?.includes("\u2503")&&(T=c);else for(let u=a-1;u>=0;u--){const w=l[u].match(/^\s*[❯›]/);if(!w)continue;const b=l[u].slice(w[0].length).trim(),S=l.some((I,g)=>g!==u&&/^\s+\d+[.)]\s/.test(I));if(/^\d+[.)]\s/.test(b)&&S){M=!0;break}T=u;break}const C=s.row-1;let p=C;for(;p>0&&d[p];)p--;let o=C;for(;o+1<a&&d[o+1];)o++;const _=l.slice(p,o+1).join("");if(h==="claude"&&/\b(?:esc to interrupt|background)\b/i.test(_)||M)return"content";if(T>=0){const u=c>=T?c:T;if(C>=T&&C<=u)return"input"}else if(C===c||C>=Math.max(0,a-window.CodemanTerminalInput.TUI_PROMPT_DEFAULT_ROWS_FROM_BOTTOM))return"input";return"content"},_blurMobileTerminalInput(){const e=document.activeElement;(e===this.terminal?.textarea||e?.classList?.contains("xterm-helper-textarea")||e?.id==="cjkInput")&&e.blur?.()},_installMobileKeyboardDismiss(){if(this._mobileKeyboardDismissHandler)return;let e=0,t=0,s=!1;this._mobileKeyboardDismissStart=i=>{if(i.touches.length!==1){s=!0;return}e=i.touches[0].clientX,t=i.touches[0].clientY,s=!1},this._mobileKeyboardDismissMove=i=>{if(s||!i.touches.length)return;const n=i.touches[0].clientX-e,r=i.touches[0].clientY-t,a=window.CodemanTerminalInput.MOBILE_KEYBOARD_DISMISS_TAP_SLOP;(Math.abs(n)>a||Math.abs(r)>a)&&(s=!0)},this._mobileKeyboardDismissHandler=i=>{if(s||!this._isMobileTerminalInputFocused())return;const n=i.target;!n||typeof n.closest!="function"||n.closest("#terminalContainer")||n.closest(window.CodemanTerminalInput.MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR)||this._blurMobileTerminalInput()},document.addEventListener("touchstart",this._mobileKeyboardDismissStart,{passive:!0}),document.addEventListener("touchmove",this._mobileKeyboardDismissMove,{passive:!0}),document.addEventListener("touchend",this._mobileKeyboardDismissHandler,{passive:!0})},_isActionableMobileTerminalTap(e,t){const s=this._clientPointToCell(e,t),i=this.terminal?.buffer?.active;if(!s||!i?.getLine)return!1;const n=Math.max(1,this.terminal.rows||1),r=[],a=[];for(let o=0;o<n;o++){const _=i.getLine(i.viewportY+o);r.push(_?.translateToString?.(!0)||""),a.push(!!_?.isWrapped)}const l=s.row-1;let d=l;for(;d>0&&a[d];)d--;let m=l;for(;m+1<n&&a[m+1];)m++;const c=r.slice(d,m+1).join(""),h=/\b(?:ctrl\+\w+|shift\+\w+|esc|enter|tab|tap)\s+to\s+(?:expand|collapse|view|open|interrupt|see)\b/i,T=Math.max(0,d-1),M=Math.min(n-1,m+1);for(let o=T;o<=M;o++)if(h.test(r[o]))return!0;const C=r.some(o=>/^\s*[❯›]\s+\d+[.)]\s/.test(o)),p=r.some(o=>/^\s+\d+[.)]\s/.test(o));return C&&p&&/^\s*(?:[❯›]\s*)?\d+[.)]\s/.test(c)},_focusMobileTerminalInput(){this._syncMobileHelperTextareaToCursor();const e=document.getElementById("cjkInput");e?.classList.contains("cjk-input-visible")?e.focus():this.terminal?.focus()},_handleMobileTerminalTap(e,t,s=null){if(!e||!this.terminal)return null;const i=s??this._classifyMobileTerminalTap(e.clientX,e.clientY);if(i==="history")return this._focusMobileTerminalInput(),i;const n=this.terminal.modes?.mouseTrackingMode,r=!!n&&n!=="none",a=i==="content"||t;return a&&r?this._dispatchSyntheticTerminalClick(e.clientX,e.clientY):a&&this._sessionUsesServerMouseStrip()&&this._sendSyntheticSgrTap(e.clientX,e.clientY),i==="content"&&this._isActionableMobileTerminalTap(e.clientX,e.clientY)?this._blurMobileTerminalInput():i==="content"&&t?this._blurMobileTerminalInput():this._focusMobileTerminalInput(),i},_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 n=s.getBoundingClientRect(),r=Math.max(1,Math.min(this.terminal.cols,Math.floor((e-n.left)/i.width)+1)),a=Math.max(1,Math.min(this.terminal.rows,Math.floor((t-n.top)/i.height)+1));return{col:r,row:a}},_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(n=>!Number.isFinite(n)))return!1;const i=t.split(".").map(Number);for(let n=0;n<3;n++)if(s[n]!==i[n])return s[n]>i[n];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 n=s<0?64:65,r=Math.min(Math.abs(s),5);this._queueScrollBytes(`\x1B[<${n};${i.col};${i.row}M`.repeat(r))},_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)),n=(this._pageKeyPending||0)+t,r=Math.trunc(n/i);if(this._pageKeyPending=n-r*i,r){const a=r<0?s.KEY_PAGE_UP:s.KEY_PAGE_DOWN;this._queueScrollBytes(a.repeat(Math.min(Math.abs(r),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,n=this.terminal?.modes?.mouseTrackingMode||"none",r=this.terminal?.buffer?.active?.baseY??-1,a=`${e}|${s?.mode}|${s?.cliVersion}|${i}|${n}|${r>0}`;this._scrollRoutingLogged||(this._scrollRoutingLogged=new Map),this._scrollRoutingLogged.get(t)!==a&&(this._scrollRoutingLogged.set(t,a),console.log(`[scroll] ${t} \u2192 ${e} (mode=${s?.mode||"?"}, cliVersion=${s?.cliVersion||"unknown"}, localScrollbackOptOut=${i}, mouseTracking=${n}, localScrollbackRows=${r})`))},_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,n=!i||i.cols!==s.cols||i.rows!==s.rows;this._lastResizeDims={cols:s.cols,rows:s.rows};const r=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:r};return t.force&&(l.f=!0),this._ws.send(JSON.stringify(l)),n}catch{}const a={...s,viewportType:r};return t.force&&(a.force=!0),await fetch(`/api/sessions/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),n},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 n(r){if(!Number.isFinite(r))return"";const a=new Date(r);return a.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+a.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1})}e.CodemanSearch={SEARCH_DEBOUNCE_MS:250,SEARCH_LIMIT:60,SOURCE_LABELS:i,formatSearchTime:n}})(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",a=>{a.key==="Escape"&&e.value&&(a.stopPropagation(),this._clearSearch())}),t&&t.addEventListener("click",()=>this._clearSearch()),document.querySelectorAll("#searchFilters .search-filter-chip").forEach(a=>{a.addEventListener("click",()=>{const l=a.dataset.typeFilter;this._searchTypes.has(l)&&this._searchTypes.size===1||(this._searchTypes.has(l)?(this._searchTypes.delete(l),a.classList.remove("active")):(this._searchTypes.add(l),a.classList.add("active")),this._runSearch())})});const i=document.getElementById("searchCaseFilter"),n=document.getElementById("searchStatusFilter"),r=document.getElementById("searchDateFilter");i&&i.addEventListener("change",()=>{this._searchSecondary.caseLabel=i.value,this._renderSearch(this._searchLastData)}),n&&n.addEventListener("change",()=>{this._searchSecondary.status=n.value,this._renderSearch(this._searchLastData)}),r&&r.addEventListener("change",()=>{this._searchSecondary.days=r.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(r=>r&&r.name).filter(Boolean))).sort(),i=e.value;e.innerHTML="";const n=document.createElement("option");n.value="",n.textContent="All cases",e.appendChild(n);for(const r of s){const a=document.createElement("option");a.value=r,a.textContent="#"+r,e.appendChild(a)}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 n=++this._searchSeq,r=await this._apiJson("/api/search?"+i.toString());n===this._searchSeq&&(r?this._searchLastData=r: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 n=e;if(t){const r="#"+t;n=n.filter(a=>(a.sessionName||"").includes(r)||a.sessionName===t)}if(s){const r=new Set((this.sessionOrder||[]).concat(Object.keys(this.sessions||{})));n=n.filter(a=>{const l=r.has(a.sessionId);return s==="active"?l:!l})}if(i){const r=Date.now()-Number(i)*24*60*60*1e3;n=n.filter(a=>Number.isFinite(a.timestamp)&&a.timestamp>=r)}return n},_renderSearch(e){const t=document.getElementById("searchResults"),s=document.getElementById("historyHeader")||document.getElementById("historyTitle"),i=document.getElementById("historyList");if(!t)return;const n=!!e;if(s&&(s.style.display=n?"none":""),i&&(i.style.display=n?"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 r=(e.groups||[]).map(l=>({type:l.type,results:this._applySecondaryFilters(l.results||[])})).filter(l=>l.results.length>0);if(r.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 r){const d=document.createElement("div");d.className="search-group-header";const m=document.createElement("span");m.className="search-group-label",m.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(m,c),t.appendChild(d);for(const h of l.results)t.appendChild(this._buildSearchResultCard(h))}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=e.jumpTo&&e.jumpTo.kind==="resume-session",n=document.createElement("span");n.className="search-result-badge search-badge-"+e.type+(i?" search-badge-past":""),n.textContent=i?"Resume":(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(n,r,a);const l=document.createElement("div");l.className="search-result-snippet",l.textContent=e.snippet||"",t.append(s,l);const d=()=>this._jumpToSearchResult(e);return t.addEventListener("click",d),t.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),d())}),t},_jumpToSearchResult(e){const t=e&&e.jumpTo;if(t){if(t.kind==="resume-session"){this.resumeHistorySession(t.claudeSessionId||t.sessionId,t.workingDir||"",e.sessionName);return}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)}}}});
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-routes.d.ts","sourceRoot":"","sources":["../../../src/web/routes/file-routes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,eAAe,EAAqB,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"file-routes.d.ts","sourceRoot":"","sources":["../../../src/web/routes/file-routes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,eAAe,EAAqB,MAAM,SAAS,CAAC;AA2C7D,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AA+pB5E,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,WAAW,GAAG,SAAS,GAAG,UAAU,GAAG,IAAI,CAgkCxG"}
|
|
@@ -19,6 +19,7 @@ import { sanitizeAttachmentHistoryItem } from '../../session-attachment-history.
|
|
|
19
19
|
import { isBlockedAttachmentPath, loadAttachmentGuardConfig } from '../../config/attachment-guard.js';
|
|
20
20
|
import { isMultiUserMode, userSpacePath } from '../../config/multiuser.js';
|
|
21
21
|
import { CASES_DIR, canAccessOwned, findSessionOrFail, getAuthUser, parseBody, validateSessionFilePath, } from '../route-helpers.js';
|
|
22
|
+
import { parseByteRange } from '../http-range.js';
|
|
22
23
|
import { isSensitivePath } from '../sensitive-path.js';
|
|
23
24
|
import { SseEvent } from '../sse-events.js';
|
|
24
25
|
import { FilesystemBrowseQuerySchema, FilesystemPreviewQuerySchema, FileWriteSchema } from '../schemas.js';
|
|
@@ -46,7 +47,13 @@ function buildContentDisposition(disposition, fileName) {
|
|
|
46
47
|
}
|
|
47
48
|
function sendRawStream(reply, content) {
|
|
48
49
|
const headers = reply.getHeaders();
|
|
50
|
+
// hijack() answers on reply.raw, which keeps Fastify's own status handling out
|
|
51
|
+
// of the picture — so a 206 set with reply.code() has to be carried across by
|
|
52
|
+
// hand or a partial body would go out labelled 200 and the browser would treat
|
|
53
|
+
// it as the whole file.
|
|
54
|
+
const statusCode = reply.statusCode;
|
|
49
55
|
reply.hijack();
|
|
56
|
+
reply.raw.statusCode = statusCode;
|
|
50
57
|
for (const [name, value] of Object.entries(headers)) {
|
|
51
58
|
if (value !== undefined) {
|
|
52
59
|
reply.raw.setHeader(name, value);
|
|
@@ -62,7 +69,39 @@ function sendRawStream(reply, content) {
|
|
|
62
69
|
});
|
|
63
70
|
content.pipe(reply.raw);
|
|
64
71
|
}
|
|
65
|
-
|
|
72
|
+
/**
|
|
73
|
+
* Stream a file body, honoring a `Range` request header.
|
|
74
|
+
*
|
|
75
|
+
* Callers set Content-Type/Content-Disposition first; this adds the
|
|
76
|
+
* range-related headers and the body. Range support is what makes the file
|
|
77
|
+
* viewer's `<video>`/`<audio>` seekable: with a plain 200 and no
|
|
78
|
+
* `Accept-Ranges`, Chrome reports `video.seekable` as `[0, 0]`, the scrub bar
|
|
79
|
+
* does nothing and `currentTime = x` is silently reverted (measured against an
|
|
80
|
+
* 18MB mp4 before this existed). It also stops each seek from re-reading the
|
|
81
|
+
* whole file into memory.
|
|
82
|
+
*/
|
|
83
|
+
function sendFileBody(reply, resolvedPath, size, rangeHeader) {
|
|
84
|
+
reply.header('Accept-Ranges', 'bytes');
|
|
85
|
+
const range = parseByteRange(rangeHeader, size);
|
|
86
|
+
if (range.kind === 'unsatisfiable') {
|
|
87
|
+
reply
|
|
88
|
+
.code(416)
|
|
89
|
+
.header('Content-Range', `bytes */${size}`)
|
|
90
|
+
.type('application/json; charset=utf-8')
|
|
91
|
+
.send(createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Requested range not satisfiable'));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (range.kind === 'partial') {
|
|
95
|
+
reply.code(206);
|
|
96
|
+
reply.header('Content-Range', `bytes ${range.start}-${range.end}/${size}`);
|
|
97
|
+
reply.header('Content-Length', range.end - range.start + 1);
|
|
98
|
+
sendRawStream(reply, createReadStream(resolvedPath, { start: range.start, end: range.end }));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
reply.header('Content-Length', size);
|
|
102
|
+
sendRawStream(reply, createReadStream(resolvedPath));
|
|
103
|
+
}
|
|
104
|
+
async function serveRawFile(reply, resolvedPath, fileName, extension, download, rangeHeader) {
|
|
66
105
|
const stat = await fs.stat(resolvedPath);
|
|
67
106
|
const MAX_RAW_ATTACHMENT_SIZE = 50 * 1024 * 1024; // 50MB, matching file-raw / download
|
|
68
107
|
if (stat.size > MAX_RAW_ATTACHMENT_SIZE) {
|
|
@@ -71,20 +110,17 @@ async function serveRawFile(reply, resolvedPath, fileName, extension, download)
|
|
|
71
110
|
.send(createErrorResponse(ApiErrorCode.INVALID_INPUT, `File too large (${Math.round(stat.size / 1024 / 1024)}MB > ${MAX_RAW_ATTACHMENT_SIZE / 1024 / 1024}MB limit)`));
|
|
72
111
|
return;
|
|
73
112
|
}
|
|
74
|
-
const content = createReadStream(resolvedPath);
|
|
75
113
|
if (download || extension === 'svg') {
|
|
76
114
|
reply.header('Content-Type', extension === 'svg' ? 'application/octet-stream' : MIME_TYPES[extension] || 'application/octet-stream');
|
|
77
115
|
reply.header('Content-Disposition', buildContentDisposition('attachment', fileName));
|
|
78
|
-
reply.header('Content-Length', stat.size);
|
|
79
116
|
reply.header('X-Content-Type-Options', 'nosniff');
|
|
80
|
-
|
|
117
|
+
sendFileBody(reply, resolvedPath, stat.size, rangeHeader);
|
|
81
118
|
return;
|
|
82
119
|
}
|
|
83
120
|
reply.header('Content-Type', MIME_TYPES[extension] || 'application/octet-stream');
|
|
84
121
|
reply.header('Content-Disposition', buildContentDisposition('inline', fileName));
|
|
85
|
-
reply.header('Content-Length', stat.size);
|
|
86
122
|
reply.header('X-Content-Type-Options', 'nosniff');
|
|
87
|
-
|
|
123
|
+
sendFileBody(reply, resolvedPath, stat.size, rangeHeader);
|
|
88
124
|
}
|
|
89
125
|
function getAttachmentOr404(reply, sessionId, attachmentId) {
|
|
90
126
|
const record = attachmentRegistry.get(sessionId, attachmentId);
|
|
@@ -676,7 +712,7 @@ export function registerFileRoutes(app, ctx) {
|
|
|
676
712
|
await serveConvertedPreview(reply, resolvedPath, fileName, extension);
|
|
677
713
|
return;
|
|
678
714
|
}
|
|
679
|
-
await serveRawFile(reply, resolvedPath, fileName, extension);
|
|
715
|
+
await serveRawFile(reply, resolvedPath, fileName, extension, false, req.headers.range);
|
|
680
716
|
});
|
|
681
717
|
// File tree listing
|
|
682
718
|
app.get('/api/sessions/:id/files', async (req) => {
|
|
@@ -1119,24 +1155,21 @@ export function registerFileRoutes(app, ctx) {
|
|
|
1119
1155
|
pdf: 'application/pdf',
|
|
1120
1156
|
json: 'application/json',
|
|
1121
1157
|
};
|
|
1122
|
-
const content = await fs.readFile(resolvedPath);
|
|
1123
1158
|
const rawBasename = filePath.split('/').pop() || 'download';
|
|
1124
1159
|
// Sanitize filename for Content-Disposition header (prevent header injection)
|
|
1125
1160
|
const basename = rawBasename.replace(/["\\\r\n]/g, '_');
|
|
1126
1161
|
if (download === 'true' || ext === 'svg') {
|
|
1127
|
-
reply.
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
'Content-Length': content.length,
|
|
1132
|
-
'X-Content-Type-Options': 'nosniff',
|
|
1133
|
-
});
|
|
1134
|
-
reply.raw.end(content);
|
|
1162
|
+
reply.header('Content-Type', ext === 'svg' ? 'application/octet-stream' : mimeTypes[ext] || 'application/octet-stream');
|
|
1163
|
+
reply.header('Content-Disposition', `attachment; filename="${basename}"`);
|
|
1164
|
+
reply.header('X-Content-Type-Options', 'nosniff');
|
|
1165
|
+
sendFileBody(reply, resolvedPath, stat.size, req.headers.range);
|
|
1135
1166
|
return;
|
|
1136
1167
|
}
|
|
1137
1168
|
reply.header('Content-Type', mimeTypes[ext] || 'application/octet-stream');
|
|
1138
1169
|
reply.header('X-Content-Type-Options', 'nosniff');
|
|
1139
|
-
|
|
1170
|
+
// Streamed, range-aware: this is the <video>/<audio> source the file
|
|
1171
|
+
// viewer points at, and a 200-only response makes the media unseekable.
|
|
1172
|
+
sendFileBody(reply, resolvedPath, stat.size, req.headers.range);
|
|
1140
1173
|
}
|
|
1141
1174
|
catch (err) {
|
|
1142
1175
|
reply
|
|
@@ -1245,7 +1278,7 @@ export function registerFileRoutes(app, ctx) {
|
|
|
1245
1278
|
if (!servePath)
|
|
1246
1279
|
return;
|
|
1247
1280
|
try {
|
|
1248
|
-
await serveRawFile(reply, servePath, record.fileName, record.extension, download === 'true');
|
|
1281
|
+
await serveRawFile(reply, servePath, record.fileName, record.extension, download === 'true', req.headers.range);
|
|
1249
1282
|
}
|
|
1250
1283
|
catch (err) {
|
|
1251
1284
|
reply
|