aicodeman 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/web/public/api-client.js.gz +0 -0
  2. package/dist/web/public/app.js +6 -6
  3. package/dist/web/public/app.js.br +0 -0
  4. package/dist/web/public/app.js.gz +0 -0
  5. package/dist/web/public/constants.js +1 -1
  6. package/dist/web/public/constants.js.br +0 -0
  7. package/dist/web/public/constants.js.gz +0 -0
  8. package/dist/web/public/index.html +10 -10
  9. package/dist/web/public/index.html.br +0 -0
  10. package/dist/web/public/index.html.gz +0 -0
  11. package/dist/web/public/keyboard-accessory.js.gz +0 -0
  12. package/dist/web/public/mobile-handlers.js.gz +0 -0
  13. package/dist/web/public/mobile.css.gz +0 -0
  14. package/dist/web/public/notification-manager.js.gz +0 -0
  15. package/dist/web/public/ralph-wizard.js.gz +0 -0
  16. package/dist/web/public/styles.css +1 -1
  17. package/dist/web/public/styles.css.br +0 -0
  18. package/dist/web/public/styles.css.gz +0 -0
  19. package/dist/web/public/subagent-windows.js.gz +0 -0
  20. package/dist/web/public/sw.js.gz +0 -0
  21. package/dist/web/public/upload.html.gz +0 -0
  22. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  23. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  24. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  25. package/dist/web/public/vendor/xterm-zerolag-input.js +1 -1
  26. package/dist/web/public/vendor/xterm-zerolag-input.js.br +0 -0
  27. package/dist/web/public/vendor/xterm-zerolag-input.js.gz +0 -0
  28. package/dist/web/public/vendor/xterm.css.gz +0 -0
  29. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  30. package/dist/web/public/voice-input.js.gz +0 -0
  31. package/package.json +3 -1
Binary file
@@ -1,4 +1,4 @@
1
- "use strict";const _SSE_HANDLER_MAP=[[SSE_EVENTS.INIT,"_onInit"],[SSE_EVENTS.SESSION_CREATED,"_onSessionCreated"],[SSE_EVENTS.SESSION_UPDATED,"_onSessionUpdated"],[SSE_EVENTS.SESSION_DELETED,"_onSessionDeleted"],[SSE_EVENTS.SESSION_TERMINAL,"_onSessionTerminal"],[SSE_EVENTS.SESSION_NEEDS_REFRESH,"_onSessionNeedsRefresh"],[SSE_EVENTS.SESSION_CLEAR_TERMINAL,"_onSessionClearTerminal"],[SSE_EVENTS.SESSION_COMPLETION,"_onSessionCompletion"],[SSE_EVENTS.SESSION_ERROR,"_onSessionError"],[SSE_EVENTS.SESSION_EXIT,"_onSessionExit"],[SSE_EVENTS.SESSION_IDLE,"_onSessionIdle"],[SSE_EVENTS.SESSION_WORKING,"_onSessionWorking"],[SSE_EVENTS.SESSION_AUTO_CLEAR,"_onSessionAutoClear"],[SSE_EVENTS.SESSION_CLI_INFO,"_onSessionCliInfo"],[SSE_EVENTS.SCHEDULED_CREATED,"_onScheduledCreated"],[SSE_EVENTS.SCHEDULED_UPDATED,"_onScheduledUpdated"],[SSE_EVENTS.SCHEDULED_COMPLETED,"_onScheduledCompleted"],[SSE_EVENTS.SCHEDULED_STOPPED,"_onScheduledStopped"],[SSE_EVENTS.RESPAWN_STARTED,"_onRespawnStarted"],[SSE_EVENTS.RESPAWN_STOPPED,"_onRespawnStopped"],[SSE_EVENTS.RESPAWN_STATE_CHANGED,"_onRespawnStateChanged"],[SSE_EVENTS.RESPAWN_CYCLE_STARTED,"_onRespawnCycleStarted"],[SSE_EVENTS.RESPAWN_BLOCKED,"_onRespawnBlocked"],[SSE_EVENTS.RESPAWN_AUTO_ACCEPT_SENT,"_onRespawnAutoAcceptSent"],[SSE_EVENTS.RESPAWN_DETECTION_UPDATE,"_onRespawnDetectionUpdate"],[SSE_EVENTS.RESPAWN_TIMER_STARTED,"_onRespawnTimerStarted"],[SSE_EVENTS.RESPAWN_TIMER_CANCELLED,"_onRespawnTimerCancelled"],[SSE_EVENTS.RESPAWN_TIMER_COMPLETED,"_onRespawnTimerCompleted"],[SSE_EVENTS.RESPAWN_ERROR,"_onRespawnError"],[SSE_EVENTS.RESPAWN_ACTION_LOG,"_onRespawnActionLog"],[SSE_EVENTS.TASK_CREATED,"_onTaskCreated"],[SSE_EVENTS.TASK_COMPLETED,"_onTaskCompleted"],[SSE_EVENTS.TASK_FAILED,"_onTaskFailed"],[SSE_EVENTS.TASK_UPDATED,"_onTaskUpdated"],[SSE_EVENTS.MUX_CREATED,"_onMuxCreated"],[SSE_EVENTS.MUX_KILLED,"_onMuxKilled"],[SSE_EVENTS.MUX_DIED,"_onMuxDied"],[SSE_EVENTS.MUX_STATS_UPDATED,"_onMuxStatsUpdated"],[SSE_EVENTS.SESSION_RALPH_LOOP_UPDATE,"_onRalphLoopUpdate"],[SSE_EVENTS.SESSION_RALPH_TODO_UPDATE,"_onRalphTodoUpdate"],[SSE_EVENTS.SESSION_RALPH_COMPLETION_DETECTED,"_onRalphCompletionDetected"],[SSE_EVENTS.SESSION_RALPH_STATUS_UPDATE,"_onRalphStatusUpdate"],[SSE_EVENTS.SESSION_CIRCUIT_BREAKER_UPDATE,"_onCircuitBreakerUpdate"],[SSE_EVENTS.SESSION_EXIT_GATE_MET,"_onExitGateMet"],[SSE_EVENTS.SESSION_BASH_TOOL_START,"_onBashToolStart"],[SSE_EVENTS.SESSION_BASH_TOOL_END,"_onBashToolEnd"],[SSE_EVENTS.SESSION_BASH_TOOLS_UPDATE,"_onBashToolsUpdate"],[SSE_EVENTS.HOOK_IDLE_PROMPT,"_onHookIdlePrompt"],[SSE_EVENTS.HOOK_PERMISSION_PROMPT,"_onHookPermissionPrompt"],[SSE_EVENTS.HOOK_ELICITATION_DIALOG,"_onHookElicitationDialog"],[SSE_EVENTS.HOOK_STOP,"_onHookStop"],[SSE_EVENTS.HOOK_TEAMMATE_IDLE,"_onHookTeammateIdle"],[SSE_EVENTS.HOOK_TASK_COMPLETED,"_onHookTaskCompleted"],[SSE_EVENTS.SUBAGENT_DISCOVERED,"_onSubagentDiscovered"],[SSE_EVENTS.SUBAGENT_UPDATED,"_onSubagentUpdated"],[SSE_EVENTS.SUBAGENT_TOOL_CALL,"_onSubagentToolCall"],[SSE_EVENTS.SUBAGENT_PROGRESS,"_onSubagentProgress"],[SSE_EVENTS.SUBAGENT_MESSAGE,"_onSubagentMessage"],[SSE_EVENTS.SUBAGENT_TOOL_RESULT,"_onSubagentToolResult"],[SSE_EVENTS.SUBAGENT_COMPLETED,"_onSubagentCompleted"],[SSE_EVENTS.IMAGE_DETECTED,"_onImageDetected"],[SSE_EVENTS.TUNNEL_STARTED,"_onTunnelStarted"],[SSE_EVENTS.TUNNEL_STOPPED,"_onTunnelStopped"],[SSE_EVENTS.TUNNEL_PROGRESS,"_onTunnelProgress"],[SSE_EVENTS.TUNNEL_ERROR,"_onTunnelError"],[SSE_EVENTS.TUNNEL_QR_ROTATED,"_onTunnelQrRotated"],[SSE_EVENTS.TUNNEL_QR_REGENERATED,"_onTunnelQrRegenerated"],[SSE_EVENTS.TUNNEL_QR_AUTH_USED,"_onTunnelQrAuthUsed"],[SSE_EVENTS.PLAN_SUBAGENT,"_onPlanSubagent"],[SSE_EVENTS.PLAN_PROGRESS,"_onPlanProgress"],[SSE_EVENTS.PLAN_STARTED,"_onPlanStarted"],[SSE_EVENTS.PLAN_CANCELLED,"_onPlanCancelled"],[SSE_EVENTS.PLAN_COMPLETED,"_onPlanCompleted"]];class CodemanApp{constructor(){this.sessions=new Map,this._shortIdCache=new Map,this.sessionOrder=[],this.draggedTabId=null,this.cases=[],this.currentRun=null,this.totalTokens=0,this.globalStats=null,this.eventSource=null,this.terminal=null,this.fitAddon=null,this.activeSessionId=null,this._initGeneration=0,this._initFallbackTimer=null,this._selectGeneration=0,this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},this.timerCountdownInterval=null,this.terminalBuffers=new Map,this.editingSessionId=null,this.pendingCloseSessionId=null,this.muxSessions=[],this.ralphStates=new Map,this.subagents=new Map,this.subagentActivity=new Map,this.subagentToolResults=new Map,this.activeSubagentId=null,this.subagentPanelVisible=!1,this.subagentWindows=new Map,this.subagentWindowZIndex=ZINDEX_SUBAGENT_BASE,this.minimizedSubagents=new Map,this._subagentHideTimeout=null,this.subagentParentMap=new Map,this.teams=new Map,this.teamTasks=new Map,this.teammateMap=new Map,this.teammatePanesByName=new Map,this.teammateTerminals=new Map,this.terminalBufferCache=new Map,this.ralphStatePanelCollapsed=!0,this.ralphClosedSessions=new Set,this.planSubagents=new Map,this.planSubagentWindowZIndex=ZINDEX_PLAN_SUBAGENT_BASE,this.planGenerationStopped=!1,this.planAgentsMinimized=!1,this.wizardDragState=null,this.wizardDragListeners=null,this.wizardPosition=null,this.projectInsights=new Map,this.logViewerWindows=new Map,this.logViewerWindowZIndex=ZINDEX_LOG_VIEWER_BASE,this.projectInsightsPanelVisible=!1,this.currentSessionWorkingDir=null,this.imagePopups=new Map,this.imagePopupZIndex=ZINDEX_IMAGE_POPUP_BASE,this.tabAlerts=new Map,this.pendingHooks=new Map,this.pendingWrites=[],this.writeFrameScheduled=!1,this._wasAtBottomBeforeWrite=!0,this.syncWaitTimeout=null,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.flickerFilterTimeout=null,this.renderSessionTabsTimeout=null,this.renderRalphStatePanelTimeout=null,this.renderTaskPanelTimeout=null,this.renderMuxSessionsTimeout=null,this.systemStatsInterval=null,this.sseReconnectTimeout=null,this._sseListenerCleanup=null,this.reconnectAttempts=0,this.maxReconnectAttempts=10,this.isOnline=navigator.onLine,this._inputQueue=new Map,this._inputQueueMaxBytes=64*1024,this._connectionStatus="connected",this._inputSendChain=Promise.resolve(),this._localEchoOverlay=null,this._localEchoEnabled=!1,this._restoringFlushedState=!1,this.activeFocusTrap=null,this.notificationManager=new NotificationManager(this),this.idleTimers=new Map,this._elemCache={},this.init()}$(e){return this._elemCache[e]||(this._elemCache[e]=document.getElementById(e)),this._elemCache[e]}formatTokens(e){if(e>=1e6){const t=e/1e6;return t>=10?`${t.toFixed(1)}m`:`${t.toFixed(2)}m`}else if(e>=1e3){const t=e/1e3;return t>=100?`${t.toFixed(0)}k`:`${t.toFixed(1)}k`}return String(e)}estimateCost(e,t){const s=e/1e6*15,n=t/1e6*75;return s+n}setPendingHook(e,t){this.pendingHooks.has(e)||this.pendingHooks.set(e,new Set),this.pendingHooks.get(e).add(t),this.updateTabAlertFromHooks(e)}clearPendingHooks(e,t=null){const s=this.pendingHooks.get(e);s&&(t?s.delete(t):s.clear(),s.size===0&&this.pendingHooks.delete(e),this.updateTabAlertFromHooks(e))}updateTabAlertFromHooks(e){const t=this.pendingHooks.get(e);!t||t.size===0?this.tabAlerts.delete(e):t.has("permission_prompt")||t.has("elicitation_dialog")?this.tabAlerts.set(e,"action"):t.has("idle_prompt")&&this.tabAlerts.set(e,"idle"),this.renderSessionTabs()}init(){MobileDetection.init(),KeyboardHandler.init(),SwipeHandler.init(),VoiceInput.init(),KeyboardAccessoryBar.init(),this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility(),document.documentElement.classList.remove("mobile-init"),requestAnimationFrame(()=>{this.initTerminal(),this.loadFontSize(),this.connectSSE(),this._initFallbackTimer=setTimeout(()=>{this._initGeneration===0&&this.loadState()},3e3)}),this.registerServiceWorker();const e=fetch("/api/settings").then(t=>t.ok?t.json():null).catch(()=>null);if(this.loadQuickStartCases(null,e),this._initRunMode(),this.setupEventListeners(),MobileDetection.isTouchDevice()){const t=s=>{s&&s.addEventListener("touchstart",n=>{if(!KeyboardHandler.keyboardVisible)return;const i=n.target.closest("button");i&&(n.preventDefault(),i.click(),typeof app<"u"&&app.terminal&&app.terminal.focus())},{passive:!1})};t(document.querySelector(".toolbar")),t(document.querySelector(".welcome-overlay"))}this.setupOnlineDetection(),this.loadAppSettingsFromServer(e).then(()=>{this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility()}),document.body.classList.add("app-loaded")}initTerminal(){const e=parseInt(localStorage.getItem("codeman-scrollback"))||DEFAULT_SCROLLBACK;if(this.terminal=new Terminal({theme:{background:"#0d0d0d",foreground:"#e0e0e0",cursor:"#e0e0e0",cursorAccent:"#0d0d0d",selection:"rgba(255, 255, 255, 0.3)",black:"#0d0d0d",red:"#ff6b6b",green:"#51cf66",yellow:"#ffd43b",blue:"#339af0",magenta:"#cc5de8",cyan:"#22b8cf",white:"#e0e0e0",brightBlack:"#495057",brightRed:"#ff8787",brightGreen:"#69db7c",brightYellow:"#ffe066",brightBlue:"#5c7cfa",brightMagenta:"#da77f2",brightCyan:"#66d9e8",brightWhite:"#ffffff"},fontFamily:'"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, monospace',fontSize:MobileDetection.getDeviceType()==="mobile"?10:14,lineHeight:1.2,cursorBlink:!1,cursorStyle:"block",scrollback:e,allowTransparency:!0,allowProposedApi:!0}),this.fitAddon=new FitAddon.FitAddon,this.terminal.loadAddon(this.fitAddon),typeof Unicode11Addon<"u")try{const r=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(r),this.terminal.unicode.activeVersion="11"}catch{}const t=document.getElementById("terminalContainer");if(this.terminal.open(t),typeof WebglAddon<"u")try{const r=new WebglAddon.WebglAddon;r.onContextLoss(()=>{r.dispose()}),this.terminal.loadAddon(r)}catch{}if(this._localEchoOverlay=new LocalEchoOverlay(this.terminal),MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this.registerFilePathLinkProvider(),t.addEventListener("wheel",r=>{r.preventDefault();const c=Math.round(r.deltaY/25)||(r.deltaY>0?1:-1);this.terminal.scrollLines(c)},{passive:!1}),!(MobileDetection.isTouchDevice()&&window.innerWidth<1024)){let r=0,c=0,d=0,u=0,h=null,m=!1;const p=t.querySelector(".xterm-viewport"),g=f=>{if(!p)return;const S=u?(f-u)/16.67:1;u=f,m?(c!==0&&(p.scrollTop+=c,c=0),h=requestAnimationFrame(g)):Math.abs(d)>.1?(p.scrollTop+=d*S,d*=.94,h=requestAnimationFrame(g)):(h=null,d=0)};t.addEventListener("touchstart",f=>{f.touches.length===1&&(r=f.touches[0].clientY,c=0,d=0,m=!0,u=0,h||(h=requestAnimationFrame(g)))},{passive:!0}),t.addEventListener("touchmove",f=>{if(f.touches.length===1&&m){const S=f.touches[0].clientY,w=r-S;c+=w,d=w*1.2,r=S}},{passive:!0}),t.addEventListener("touchend",()=>{m=!1},{passive:!0}),t.addEventListener("touchcancel",()=>{m=!1,d=0},{passive:!0})}this.showWelcome(),this._resizeTimeout=null,this._lastResizeDims=null;const i=40,o=10,l=()=>{this._resizeTimeout||(this._resizeTimeout=setTimeout(()=>{if(this._resizeTimeout=null,this.fitAddon){this.fitAddon.fit();const r=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;if(this.activeSessionId&&!r){const c=this.fitAddon.proposeDimensions(),d=c?Math.max(c.cols,i):i,u=c?Math.max(c.rows,o):o;(!this._lastResizeDims||d!==this._lastResizeDims.cols||u!==this._lastResizeDims.rows)&&(this._lastResizeDims={cols:d,rows:u},fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:d,rows:u})}).catch(()=>{}))}}this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},100))};window.addEventListener("resize",l),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(l),this.terminalResizeObserver.observe(t),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const a=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const r=this._pendingInput,c=this.activeSessionId;this._pendingInput="",this._sendInputAsync(c,r)}};this.terminal.onData(r=>{if(this.activeSessionId){if(/^\x1b\[[\?>=]?[\d;]*[cnR]$/.test(r))return;if(this._localEchoEnabled){if(r==="\x7F"){if(this._localEchoOverlay?.removeChar()==="flushed"){const{count:u,text:h}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(u===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,u),this._flushedTexts?.set(this.activeSessionId,h))),this._pendingInput+=r,a()}return}if(/^[\r\n]+$/.test(r)){const d=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),d&&(this._pendingInput+=d,a()),setTimeout(()=>{this._pendingInput+="\r",a()},80);return}if(r.length>1&&r.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(r);return}if(r.charCodeAt(0)<32){if(r.length>1&&r.charCodeAt(0)===27){this._pendingInput+=r,a();return}if(this._restoringFlushedState){this._pendingInput+=r,a();return}if(r===" "){const u=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),u&&(this._pendingInput+=u),this._pendingInput+=r,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let h="";try{const p=this._localEchoOverlay?.findPrompt?.();if(p){const g=this.terminal.buffer.active,f=g.getLine(g.viewportY+p.row);f&&(h=f.translateToString(!0).slice(p.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=h,a(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const m=this;this._tabCompletionFallback=setTimeout(()=>{if(m._tabCompletionFallback=null,!m._tabCompletionSessionId||m._tabCompletionSessionId!==m.activeSessionId)return;const p=m._localEchoOverlay;!p||p.pendingText||m.terminal.write("",()=>{if(!m._tabCompletionSessionId)return;p.resetBufferDetection();const g=p.detectBufferText();g&&g!==m._tabCompletionBaseText&&(m._tabCompletionSessionId=null,m._tabCompletionRetries=0,m._tabCompletionBaseText=null,p.rerender())})},300);return}const d=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),d&&(this._pendingInput+=d),this._pendingInput+=r,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}if(r.length===1&&r.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(r);return}}if(this._pendingInput+=r,r.charCodeAt(0)<32||r.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}const c=performance.now();c-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=c,a()):(this._lastKeystrokeTime=c,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(a,0)))}})}registerFilePathLinkProvider(){const e=this;let t=-1;this.terminal.registerLinkProvider({provideLinks(s,n){s!==t&&(t=s);const o=e.terminal.buffer.active.getLine(s);if(!o){n(void 0);return}const l=o.translateToString(!0);if(!l||!l.includes("/")){n(void 0);return}const a=[],r=/(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]*\s+)*(\/[^\s"'<>|;&\n\x00-\x1f]+)/g,c=/(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\n\x00-\x1f]*\.(?:log|txt|json|md|yaml|yml|csv|xml|sh|py|ts|js))\b/g,d=/Bash\([^)]*?(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\)\n\x00-\x1f]+)/g,u=(m,p)=>{const g=l.indexOf(m,p);g!==-1&&(a.some(f=>f.range.start.x===g+1)||a.push({text:m,range:{start:{x:g+1,y:s},end:{x:g+m.length+1,y:s}},decorations:{pointerCursor:!0,underline:!0},activate(f,S){e.openLogViewerWindow(S,e.activeSessionId)}}))};let h;for(r.lastIndex=0;(h=r.exec(l))!==null;)u(h[2],h.index);for(c.lastIndex=0;(h=c.exec(l))!==null;)u(h[1],h.index);for(d.lastIndex=0;(h=d.exec(l))!==null;)u(h[1],h.index);a.length>0,n(a.length>0?a:void 0)}})}showWelcome(){const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus())}hideWelcome(){const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const t=document.getElementById("welcomeQr");t&&(clearTimeout(this._welcomeQrShrinkTimer),t.classList.remove("expanded"))}isTerminalAtBottom(){if(!this.terminal)return!0;const e=this.terminal.buffer.active;return e.viewportY>=e.baseY-2}batchTerminalWrite(e){if(this._isLoadingBuffer){this._loadBufferQueue&&this._loadBufferQueue.push(e);return}this.writeFrameScheduled||(this._wasAtBottomBeforeWrite=this.isTerminalAtBottom());const s=(this.activeSessionId?this.sessions.get(this.activeSessionId):null)?.flickerFilterEnabled??!1;if(/\x1b\[\d{1,2}A/.test(e)||this.flickerFilterActive&&!s){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(s){if(e.includes("\x1B[2J")||e.includes("\x1B[H\x1B[J")||e.includes("\x1B[H")&&e.includes("\x1B[?25l")){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(this.flickerFilterActive){this.flickerFilterBuffer+=e;return}}this.pendingWrites.push(e),this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{if(this.pendingWrites.length>0&&this.terminal){const i=this.pendingWrites.join(""),o=i.includes(DEC_SYNC_START),l=i.includes(DEC_SYNC_END);if(o&&!l){this.syncWaitTimeout||(this.syncWaitTimeout=setTimeout(()=>{this.syncWaitTimeout=null,this.flushPendingWrites()},50)),this.writeFrameScheduled=!1;return}this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.flushPendingWrites()}this.writeFrameScheduled=!1}))}flushFlickerBuffer(){this.flickerFilterBuffer&&(this.pendingWrites.push(this.flickerFilterBuffer),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1})))}_updateLocalEchoState(){const e=this.loadAppSettingsFromStorage(),t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,n=!!((e.localEchoEnabled??MobileDetection.isTouchDevice())&&t);this._localEchoEnabled&&!n&&this._localEchoOverlay?.clear(),this._localEchoEnabled=n,this._localEchoOverlay&&t&&(t.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:i=>{try{const o=i.buffer.active,l=o.cursorY,a=o.getLine(o.viewportY+l);if(!a)return null;const c=a.translateToString(!0).indexOf("\u2503");return c>=0?{row:l,col:c}:null}catch{return null}}}):this._localEchoOverlay.setPrompt({type:"character",char:"\u276F",offset:2}))}flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=extractSyncSegments(this.pendingWrites.join(""));this.pendingWrites=[];for(const t of e)if(t){const s=t.startsWith(DEC_SYNC_START)?t.slice(DEC_SYNC_START.length):t;s&&this.terminal.write(s)}if(this._wasAtBottomBeforeWrite&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const t=this._localEchoOverlay,s=this;this.terminal.write("",()=>{if(!s._tabCompletionSessionId)return;t.resetBufferDetection();const n=t.detectBufferText();n?n===s._tabCompletionBaseText?(t.undoDetection(),s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0)):(s._tabCompletionSessionId=null,s._tabCompletionRetries=0,s._tabCompletionBaseText=null,s._tabCompletionFallback&&(clearTimeout(s._tabCompletionFallback),s._tabCompletionFallback=null),t.rerender()):(s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0))})}}chunkedTerminalWrite(e,t=TERMINAL_CHUNK_SIZE){return new Promise(s=>{if(!e||e.length===0){this._finishBufferLoad(),s();return}this._isLoadingBuffer=!0,this._loadBufferQueue=[];const n=e.replace(DEC_SYNC_STRIP_RE,""),i=()=>{this._finishBufferLoad(),s()};if(n.length<=t){this.terminal.write(n),i();return}let o=0;const l=()=>{if(o>=n.length){requestAnimationFrame(i);return}const a=n.slice(o,o+t);this.terminal.write(a),o+=t,requestAnimationFrame(l)};requestAnimationFrame(l)})}_finishBufferLoad(){const e=this._loadBufferQueue;if(this._isLoadingBuffer=!1,this._loadBufferQueue=null,e&&e.length>0)for(const t of e)this.batchTerminalWrite(t)}setupEventListeners(){document.addEventListener("keydown",t=>{t.key==="Escape"&&(this.closeAllPanels(),this.closeHelp()),(t.ctrlKey||t.metaKey)&&(t.key==="?"||t.key==="/")&&(t.preventDefault(),this.showHelp()),(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.quickStart()),(t.ctrlKey||t.metaKey)&&t.key==="w"&&(t.preventDefault(),this.killActiveSession()),(t.ctrlKey||t.metaKey)&&t.key==="Tab"&&(t.preventDefault(),this.nextSession()),(t.ctrlKey||t.metaKey)&&t.key==="k"&&(t.preventDefault(),this.killAllSessions()),(t.ctrlKey||t.metaKey)&&t.key==="l"&&(t.preventDefault(),this.clearTerminal()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="R"&&(t.preventDefault(),this.restoreTerminalSize()),(t.ctrlKey||t.metaKey)&&(t.key==="="||t.key==="+")&&(t.preventDefault(),this.increaseFontSize()),(t.ctrlKey||t.metaKey)&&t.key==="-"&&(t.preventDefault(),this.decreaseFontSize()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="V"&&(t.preventDefault(),VoiceInput.toggle())},!0);const e=this.$("headerTokens");e&&!e._statsHandlerAttached&&(e.classList.add("clickable"),e._statsHandlerAttached=!0,e.addEventListener("click",()=>this.openTokenStats())),this.setupColorPicker()}connectSSE(){if(!navigator.onLine){this.setConnectionStatus("offline");return}this.sseReconnectTimeout&&(clearTimeout(this.sseReconnectTimeout),this.sseReconnectTimeout=null),this._sseListenerCleanup&&(this._sseListenerCleanup(),this._sseListenerCleanup=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.reconnectAttempts===0?this.setConnectionStatus("connecting"):this.setConnectionStatus("reconnecting"),this.eventSource=new EventSource("/api/events");const e=[],t=(s,n)=>{this.eventSource.addEventListener(s,n),e.push({event:s,handler:n})};if(this._sseListenerCleanup=()=>{for(const{event:s,handler:n}of e)this.eventSource&&this.eventSource.removeEventListener(s,n);e.length=0},this.eventSource.onopen=()=>{this.reconnectAttempts=0,this.setConnectionStatus("connected")},this.eventSource.onerror=()=>{this.reconnectAttempts++,this.reconnectAttempts>=this.maxReconnectAttempts?this.setConnectionStatus("disconnected"):this.setConnectionStatus("reconnecting"),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.sseReconnectTimeout&&clearTimeout(this.sseReconnectTimeout);const s=this.reconnectAttempts<=1?200:Math.min(500*Math.pow(2,this.reconnectAttempts-2),3e4);this.sseReconnectTimeout=setTimeout(()=>this.connectSSE(),s)},!this._sseHandlerWrappers){this._sseHandlerWrappers=new Map;for(const[s,n]of _SSE_HANDLER_MAP){const i=this[n];this._sseHandlerWrappers.set(s,o=>{try{i.call(this,o.data?JSON.parse(o.data):{})}catch{}})}}for(const[s]of _SSE_HANDLER_MAP)t(s,this._sseHandlerWrappers.get(s))}_onInit(e){this.handleInit(e)}_onSessionCreated(e){this.sessions.set(e.id,e),this.sessionOrder.includes(e.id)||(this.sessionOrder.push(e.id),this.saveSessionOrder()),this.renderSessionTabs(),this.updateCost(),this.sessions.size===1&&this.startSystemStatsPolling()}_onSessionUpdated(e){const t=e.session||e,s=this.sessions.get(t.id),n=t.claudeSessionId&&(!s||!s.claudeSessionId);this.sessions.set(t.id,t),this.renderSessionTabs(),this.updateCost(),t.id===this.activeSessionId&&t.tokens&&this.updateRespawnTokens(t.tokens),this.updateSubagentParentNames(t.id),n&&(this.recheckOrphanSubagents(),requestAnimationFrame(()=>{this.updateConnectionLines()}))}_onSessionDeleted(e){if(this._cleanupSessionData(e.id),this.activeSessionId===e.id){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome()}this.renderSessionTabs(),this.renderRalphStatePanel(),this.renderProjectInsightsPanel(),this.sessions.size===0&&this.stopSystemStatsPolling()}_onSessionTerminal(e){e.id===this.activeSessionId&&this.batchTerminalWrite(e.data)}async _onSessionNeedsRefresh(){if(!(!this.activeSessionId||!this.terminal))try{const s=await(await fetch(`/api/sessions/${this.activeSessionId}/terminal?tail=262144`)).json();s.terminalBuffer&&(this.terminal.clear(),this.terminal.reset(),await this.chunkedTerminalWrite(s.terminalBuffer),this.terminal.scrollToBottom(),this._localEchoOverlay?.rerender(),this.activeSessionId&&this.sendResize(this.activeSessionId))}catch{}}async _onSessionClearTerminal(e){if(e.id===this.activeSessionId)try{const s=await(await fetch(`/api/sessions/${e.id}/terminal`)).json();if(this.terminal.clear(),this.terminal.reset(),s.terminalBuffer){const n=s.terminalBuffer.replace(DEC_SYNC_STRIP_RE,"");await this.chunkedTerminalWrite(n)}this.sendResize(e.id),this._localEchoOverlay?.rerender()}catch{}}_onSessionCompletion(e){this.totalCost+=e.cost||0,this.updateCost(),e.id===this.activeSessionId&&(this.terminal.writeln(""),this.terminal.writeln(`\x1B[1;32m Done (Cost: $${(e.cost||0).toFixed(4)})\x1B[0m`))}_onSessionError(e){e.id===this.activeSessionId&&this.terminal.writeln(`\x1B[1;31m Error: ${e.error}\x1B[0m`);const t=this.sessions.get(e.id);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:e.id,sessionName:t?.name||this.getShortId(e.id),title:"Session Error",message:e.error||"Unknown error"})}_onSessionExit(e){const t=this.sessions.get(e.id);t&&(t.status="stopped",this.renderSessionTabs(),e.id===this.activeSessionId&&this._updateLocalEchoState()),e.code&&e.code!==0&&this.notificationManager?.notify({urgency:"critical",category:"session-crash",sessionId:e.id,sessionName:t?.name||this.getShortId(e.id),title:"Session Crashed",message:`Exited with code ${e.code}`})}_onSessionIdle(e){const t=this.sessions.get(e.id);if(t&&(t.status="idle",this.renderSessionTabs(),this.sendPendingCtrlL(e.id),e.id===this.activeSessionId&&this._updateLocalEchoState()),!this.respawnStatus[e.id]?.enabled){const s=this.notificationManager?.preferences?.stuckThresholdMs||6e5;clearTimeout(this.idleTimers.get(e.id)),this.idleTimers.set(e.id,setTimeout(()=>{const n=this.sessions.get(e.id);this.notificationManager?.notify({urgency:"warning",category:"session-stuck",sessionId:e.id,sessionName:n?.name||this.getShortId(e.id),title:"Session Idle",message:`Idle for ${Math.round(s/6e4)}+ minutes`}),this.idleTimers.delete(e.id)},s))}}_onSessionWorking(e){const t=this.sessions.get(e.id);t&&(t.status="busy",this.pendingHooks.has(e.id)||this.tabAlerts.delete(e.id),this.renderSessionTabs(),this.sendPendingCtrlL(e.id),e.id===this.activeSessionId&&this._updateLocalEchoState());const s=this.idleTimers.get(e.id);s&&(clearTimeout(s),this.idleTimers.delete(e.id))}_onSessionAutoClear(e){e.sessionId===this.activeSessionId&&(this.showToast(`Auto-cleared at ${e.tokens.toLocaleString()} tokens`,"info"),this.updateRespawnTokens(0));const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-clear",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Auto-Cleared",message:`Context reset at ${(e.tokens||0).toLocaleString()} tokens`})}_onSessionCliInfo(e){const t=this.sessions.get(e.sessionId);t&&(e.version&&(t.cliVersion=e.version),e.model&&(t.cliModel=e.model),e.accountType&&(t.cliAccountType=e.accountType),e.latestVersion&&(t.cliLatestVersion=e.latestVersion)),e.sessionId===this.activeSessionId&&this.updateCliInfoDisplay()}_onScheduledCreated(e){this.currentRun=e,this.showTimer()}_onScheduledUpdated(e){this.currentRun=e,this.updateTimer()}_onScheduledCompleted(e){this.currentRun=e,this.hideTimer(),this.showToast("Scheduled run completed!","success")}_onScheduledStopped(){this.currentRun=null,this.hideTimer()}_onRespawnStarted(e){this.respawnStatus[e.sessionId]=e.status,e.sessionId===this.activeSessionId&&this.showRespawnBanner()}_onRespawnStopped(e){delete this.respawnStatus[e.sessionId],e.sessionId===this.activeSessionId&&this.hideRespawnBanner()}_onRespawnStateChanged(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].state=e.state),e.sessionId===this.activeSessionId&&this.updateRespawnBanner(e.state)}_onRespawnCycleStarted(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].cycleCount=e.cycleNumber),e.sessionId===this.activeSessionId&&(document.getElementById("respawnCycleCount").textContent=e.cycleNumber)}_onRespawnBlocked(e){const t=this.sessions.get(e.sessionId),n={circuit_breaker_open:"Circuit Breaker Open",exit_signal:"Exit Signal Detected",status_blocked:"Claude Reported BLOCKED"}[e.reason]||"Respawn Blocked";if(this.notificationManager?.notify({urgency:"critical",category:"respawn-blocked",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:n,message:e.details}),e.sessionId===this.activeSessionId){const i=document.getElementById("respawnStateLabel");i&&(i.textContent=n,i.classList.add("respawn-blocked"))}}_onRespawnAutoAcceptSent(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-accept",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Plan Accepted",message:`Accepted plan mode for ${t?.name||"session"}`})}_onRespawnDetectionUpdate(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].detection=e.detection),e.sessionId===this.activeSessionId&&this.updateDetectionDisplay(e.detection)}_onRespawnTimerStarted(e){if(e.endAt&&(this.respawnTimers[e.sessionId]={endAt:e.endAt,startedAt:e.startedAt,durationMinutes:e.durationMinutes},e.sessionId===this.activeSessionId&&this.showRespawnTimer()),e.timer){const{sessionId:t,timer:s}=e;this.respawnCountdownTimers[t]||(this.respawnCountdownTimers[t]={}),this.respawnCountdownTimers[t][s.name]={endsAt:s.endsAt,totalMs:s.durationMs,reason:s.reason},t===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.startCountdownInterval())}}_onRespawnTimerCancelled(e){const{sessionId:t,timerName:s}=e;this.respawnCountdownTimers[t]&&delete this.respawnCountdownTimers[t][s],t===this.activeSessionId&&this.updateCountdownTimerDisplay()}_onRespawnTimerCompleted(e){const{sessionId:t,timerName:s}=e;this.respawnCountdownTimers[t]&&delete this.respawnCountdownTimers[t][s],t===this.activeSessionId&&this.updateCountdownTimerDisplay()}_onRespawnError(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Respawn Error",message:e.error||e.message||"Respawn encountered an error"})}_onRespawnActionLog(e){const{sessionId:t,action:s}=e;this.addActionLogEntry(t,s),t===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.updateActionLogDisplay())}_onTaskCreated(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskCompleted(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskFailed(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskUpdated(e){e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onMuxCreated(e){this.muxSessions.push(e),this.renderMuxSessions()}_onMuxKilled(e){this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e.sessionId),this.renderMuxSessions()}_onMuxDied(e){this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e.sessionId),this.renderMuxSessions(),this.showToast("Mux session died: "+this.getShortId(e.sessionId),"warning")}_onMuxStatsUpdated(e){this.muxSessions=e,document.getElementById("monitorPanel").classList.contains("open")&&this.renderMuxSessions()}_onRalphLoopUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{loop:e.state})}_onRalphTodoUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{todos:e.todos})}_onRalphCompletionDetected(e){if(this.ralphClosedSessions.has(e.sessionId))return;const t=`${e.sessionId}:${e.phrase}`;if(this._shownCompletions?.has(t))return;this._shownCompletions||(this._shownCompletions=new Set),this._shownCompletions.add(t),setTimeout(()=>this._shownCompletions?.delete(t),3e4);const s=this.ralphStates.get(e.sessionId)||{};s.loop&&(s.loop.active=!1,this.updateRalphState(e.sessionId,s));const n=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"ralph-complete",sessionId:e.sessionId,sessionName:n?.name||this.getShortId(e.sessionId),title:"Loop Complete",message:`Completion: ${e.phrase||"unknown"}`})}_onRalphStatusUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{statusBlock:e.block})}_onCircuitBreakerUpdate(e){if(!this.ralphClosedSessions.has(e.sessionId)&&(this.updateRalphState(e.sessionId,{circuitBreaker:e.status}),e.status.state==="OPEN")){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"critical",category:"circuit-breaker",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Circuit Breaker Open",message:e.status.reason||"Loop stuck - no progress detected"})}}_onExitGateMet(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"exit-gate",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Exit Gate Met",message:`Loop ready to exit (indicators: ${e.completionIndicators})`})}_onBashToolStart(e){this.handleBashToolStart(e.sessionId,e.tool)}_onBashToolEnd(e){this.handleBashToolEnd(e.sessionId,e.tool)}_onBashToolsUpdate(e){this.handleBashToolsUpdate(e.sessionId,e.tools)}_onHookIdlePrompt(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this.notificationManager?.notify({urgency:"warning",category:"hook-idle",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Waiting for Input",message:e.message||"Claude is idle and waiting for a prompt"})}_onHookPermissionPrompt(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const s=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this.notificationManager?.notify({urgency:"critical",category:"hook-permission",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Permission Required",message:s||"Claude needs tool approval to continue"})}_onHookElicitationDialog(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this.notificationManager?.notify({urgency:"critical",category:"hook-elicitation",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Question Asked",message:e.question||"Claude is asking a question and waiting for your answer"})}_onHookStop(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.clearPendingHooks(e.sessionId),this.notificationManager?.notify({urgency:"info",category:"hook-stop",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Response Complete",message:e.reason||"Claude has finished responding"})}_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"hook-teammate-idle",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Teammate Idle",message:`A teammate is idle in ${t?.name||e.sessionId}`})}_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"hook-task-completed",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Task Completed",message:`A team task completed in ${t?.name||e.sessionId}`})}_onSubagentDiscovered(e){if(this.subagents.set(e.agentId,e),this.subagentActivity.set(e.agentId,[]),this.subagentToolResults.delete(e.agentId),this.subagentWindows.has(e.agentId)&&this.forceCloseSubagentWindow(e.agentId),this.renderSubagentPanel(),this.findParentSessionForSubagent(e.agentId),e.status==="active"){const n=this.subagents.get(e.agentId);n?.sessionId&&Array.from(this.sessions.values()).some(o=>o.claudeSessionId===n.sessionId)&&this.openSubagentWindow(e.agentId)}requestAnimationFrame(()=>{this.updateConnectionLines()});const t=this.subagentParentMap.get(e.agentId),s=t?this.sessions.get(t):null;this.notificationManager?.notify({urgency:"info",category:"subagent-spawn",sessionId:t||e.sessionId,sessionName:s?.name||t||e.sessionId,title:"Subagent Spawned",message:e.description||"New background agent started"})}_onSubagentUpdated(e){const t=this.subagents.get(e.agentId);t?(Object.assign(t,e),this.subagents.set(e.agentId,t)):this.subagents.set(e.agentId,e),this.renderSubagentPanel(),this.subagentWindows.has(e.agentId)&&(this.renderSubagentWindowContent(e.agentId),this.updateSubagentWindowHeader(e.agentId))}_onSubagentToolCall(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"tool",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.renderSubagentPanel(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentProgress(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"progress",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentMessage(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"message",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentToolResult(e){this.subagentToolResults.has(e.agentId)||this.subagentToolResults.set(e.agentId,new Map);const t=this.subagentToolResults.get(e.agentId);if(t.set(e.toolUseId,e),t.size>50){const n=t.keys().next().value;t.delete(n)}const s=this.subagentActivity.get(e.agentId)||[];s.push({type:"tool_result",...e}),s.length>50&&s.shift(),this.subagentActivity.set(e.agentId,s),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}async _onSubagentCompleted(e){const t=this.subagents.get(e.agentId);if(t&&(t.status="completed",this.subagents.set(e.agentId,t)),this.renderSubagentPanel(),this.updateSubagentWindows(),this.subagentWindows.has(e.agentId)){const i=this.subagentWindows.get(e.agentId);i&&!i.minimized&&(await this.closeSubagentWindow(e.agentId),this.saveSubagentWindowStates())}const s=this.subagentParentMap.get(e.agentId),n=s?this.sessions.get(s):null;this.notificationManager?.notify({urgency:"info",category:"subagent-complete",sessionId:s||t?.sessionId||e.sessionId,sessionName:n?.name||s||e.sessionId,title:"Subagent Completed",message:t?.description||e.description||"Background agent finished"}),setTimeout(()=>{this.subagents.get(e.agentId)?.status==="completed"&&(this.subagentActivity.delete(e.agentId),this.subagentToolResults.delete(e.agentId))},300*1e3),setTimeout(()=>{this.subagents.get(e.agentId)?.status==="completed"&&!this.subagentWindows.has(e.agentId)&&(this.subagents.delete(e.agentId),this.subagentParentMap.delete(e.agentId))},1800*1e3)}_onImageDetected(e){this.openImagePopup(e)}_onTunnelStarted(e){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())}_onTunnelStopped(){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this.closeTunnelQR()}_onTunnelProgress(e){const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const s=document.getElementById("welcomeTunnelBtn");s?.classList.contains("connecting")&&(s.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)}_onTunnelError(e){this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))}_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()}_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()}_onTunnelQrAuthUsed(e){const s=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${s}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})}_onPlanSubagent(e){this.handlePlanSubagentEvent(e)}_onPlanProgress(e){this._planProgressHandler&&this._planProgressHandler({type:"plan:progress",data:e});const t=document.getElementById("planLoadingTitle"),s=document.getElementById("planLoadingHint");if(t&&e.phase){const n={"parallel-analysis":"Running parallel analysis...",subagent:e.detail||"Subagent working...",synthesis:"Synthesizing results...",verification:"Running verification..."};t.textContent=n[e.phase]||e.phase}s&&e.detail&&(s.textContent=e.detail)}_onPlanStarted(e){this.activePlanOrchestratorId=e.orchestratorId,this.planGenerationStopped=!1,this.renderMonitorPlanAgents()}_onPlanCancelled(e){this.activePlanOrchestratorId===e.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}_onPlanCompleted(e){this.activePlanOrchestratorId===e.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}setConnectionStatus(e){this._connectionStatus=e,this._updateConnectionIndicator(),e==="connected"&&this._inputQueue.size>0&&this._drainInputQueues()}_sendInputAsync(e,t){if(!this.isOnline||this._connectionStatus==="disconnected"){this._enqueueInput(e,t);return}this._inputSendChain=this._inputSendChain.then(()=>{fetch(`/api/sessions/${e}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:t}),keepalive:t.length<65536}).then(n=>{n.ok?this.clearPendingHooks(e):this._enqueueInput(e,t)}).catch(()=>{this._enqueueInput(e,t)})})}_enqueueInput(e,t){let n=(this._inputQueue.get(e)||"")+t;n.length>this._inputQueueMaxBytes&&(n=n.slice(n.length-this._inputQueueMaxBytes)),this._inputQueue.set(e,n),this._updateConnectionIndicator()}async _drainInputQueues(){if(this._inputQueue.size===0)return;const e=new Map(this._inputQueue);this._inputQueue.clear(),this._updateConnectionIndicator();for(const[t,s]of e)(await this._apiPost(`/api/sessions/${t}/input`,{input:s}))?.ok||this._enqueueInput(t,s);this._updateConnectionIndicator()}_updateConnectionIndicator(){const e=this.$("connectionIndicator"),t=this.$("connectionDot"),s=this.$("connectionText");if(!e||!t||!s)return;let n=0;for(const a of this._inputQueue.values())n+=a.length;const i=this._connectionStatus,o=n>0;if((i==="connected"||i==="connecting")&&!o){e.style.display="none";return}e.style.display="flex",t.className="connection-dot";const l=a=>a<1024?`${a}B`:`${(a/1024).toFixed(1)}KB`;i==="connected"&&o?(t.classList.add("draining"),s.textContent=`Sending ${l(n)}...`):i==="reconnecting"?(t.classList.add("reconnecting"),s.textContent=o?`Reconnecting (${l(n)} queued)`:"Reconnecting..."):(t.classList.add("offline"),s.textContent=o?`Offline (${l(n)} queued)`:"Offline")}setupOnlineDetection(){window.addEventListener("online",()=>{this.isOnline=!0,this.reconnectAttempts=0,this.connectSSE()}),window.addEventListener("offline",()=>{this.isOnline=!1,this.setConnectionStatus("offline")})}handleInit(e){this._initFallbackTimer&&(clearTimeout(this._initFallbackTimer),this._initFallbackTimer=null);const t=++this._initGeneration;if(e.version){const i=this.$("versionDisplay"),o=this.$("headerVersion");i&&(i.textContent=`v${e.version}`,i.title=`Codeman v${e.version}`),o&&(o.textContent=`v${e.version}`,o.title=`Codeman v${e.version}`)}VoiceInput.cleanup(),this.sessions.clear(),this.ralphStates.clear(),this.terminalBuffers.clear(),this.terminalBufferCache.clear(),this.projectInsights.clear(),this.teams.clear(),this.teamTasks.clear();for(const i of this.idleTimers.values())clearTimeout(i);if(this.idleTimers.clear(),this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.pendingWrites=[],this.writeFrameScheduled=!1,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._localEchoOverlay?.rerender(),this.pendingHooks.clear(),this._parentNameCache&&this._parentNameCache.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),MobileDetection.cleanup(),KeyboardHandler.cleanup(),MobileDetection.init(),KeyboardHandler.init(),this.tabAlerts.clear(),this._shownCompletions&&this._shownCompletions.clear(),this.notificationManager?.titleFlashInterval&&(clearInterval(this.notificationManager.titleFlashInterval),this.notificationManager.titleFlashInterval=null),this.notificationManager?.groupingMap){for(const{timeout:i}of this.notificationManager.groupingMap.values())clearTimeout(i);this.notificationManager.groupingMap.clear()}this.terminalResizeObserver&&(this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=null),this.planLoadingTimer&&(clearInterval(this.planLoadingTimer),this.planLoadingTimer=null),this.timerCountdownInterval&&(clearInterval(this.timerCountdownInterval),this.timerCountdownInterval=null),this.runSummaryAutoRefreshTimer&&(clearInterval(this.runSummaryAutoRefreshTimer),this.runSummaryAutoRefreshTimer=null),e.sessions.forEach(i=>{this.sessions.set(i.id,i),(i.ralphLoop||i.ralphTodos)&&!this.ralphClosedSessions.has(i.id)&&this.ralphStates.set(i.id,{loop:i.ralphLoop||null,todos:i.ralphTodos||[]})}),this.syncSessionOrder(),e.respawnStatus?this.respawnStatus=e.respawnStatus:this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},e.globalStats&&(this.globalStats=e.globalStats),this.totalCost=e.sessions.reduce((i,o)=>i+(o.totalCost||0),0),this.totalCost+=e.scheduledRuns.reduce((i,o)=>i+(o.totalCost||0),0);const s=e.scheduledRuns.find(i=>i.status==="running");if(s&&(this.currentRun=s,this.showTimer()),this.updateCost(),this.renderSessionTabs(),this.sessions.size>0?this.startSystemStatsPolling():this.stopSystemStatsPolling(),this.cleanupAllFloatingWindows(),e.subagents&&(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),e.subagents.forEach(i=>{this.subagents.set(i.agentId,i)}),this.renderSubagentPanel(),this.subagentParentMap.clear(),this.loadSubagentParentMap().then(()=>{for(const[i,o]of this.subagentParentMap){const l=this.subagents.get(i);if(l&&this.sessions.has(o)){l.parentSessionId=o;const a=this.sessions.get(o);a&&(l.parentSessionName=this.getSessionName(a)),this.subagents.set(i,l)}}for(const[i]of this.subagents)this.subagentParentMap.has(i)||this.findParentSessionForSubagent(i);this.restoreSubagentWindowStates()})),t!==this._initGeneration)return;const n=this.activeSessionId;if(this.activeSessionId=null,this.sessionOrder.length>0){let i=n;if(!i||!this.sessions.has(i))try{i=localStorage.getItem("codeman-active-session")}catch{}i&&this.sessions.has(i)?this.selectSession(i):this.selectSession(this.sessionOrder[0])}}async loadState(){try{const t=await(await fetch("/api/status")).json();this.handleInit(t)}catch{}}renderSessionTabs(){this.renderSessionTabsTimeout&&clearTimeout(this.renderSessionTabsTimeout),this.renderSessionTabsTimeout=setTimeout(()=>{this._renderSessionTabsImmediate()},100)}_updateActiveTabImmediate(e){const t=this.$("sessionTabs");if(!t)return;const s=t.querySelectorAll(".session-tab[data-id]");for(const n of s)n.dataset.id===e?n.classList.add("active"):n.classList.remove("active")}_renderSessionTabsImmediate(){const e=this.$("sessionTabs"),t=e.querySelectorAll(".session-tab[data-id]"),s=new Set([...t].map(o=>o.dataset.id)),n=new Set(this.sessions.keys());if(s.size===n.size&&[...s].every(o=>n.has(o)))for(const[o,l]of this.sessions){const a=e.querySelector(`.session-tab[data-id="${o}"]`);if(!a)continue;const r=o===this.activeSessionId,c=l.status||"idle",d=this.getSessionName(l),u=l.taskStats||{running:0,total:0},h=u.running>0;r&&!a.classList.contains("active")?a.classList.add("active"):!r&&a.classList.contains("active")&&a.classList.remove("active");const m=this.tabAlerts.get(o),p=m==="action",g=m==="idle",f=a.classList.contains("tab-alert-action"),S=a.classList.contains("tab-alert-idle");p&&!f?(a.classList.add("tab-alert-action"),a.classList.remove("tab-alert-idle")):g&&!S?(a.classList.add("tab-alert-idle"),a.classList.remove("tab-alert-action")):!m&&(f||S)&&a.classList.remove("tab-alert-action","tab-alert-idle");const w=a.querySelector(".tab-status");w&&!w.classList.contains(c)&&(w.className=`tab-status ${c}`);const b=a.querySelector(".tab-name");b&&b.textContent!==d&&(b.textContent=d);const y=a.querySelector(".tab-badge");if(h)if(y)y.textContent!==String(u.running)&&(y.textContent=u.running);else{this._fullRenderSessionTabs();return}else if(y){this._fullRenderSessionTabs();return}const v=a.querySelector(".tab-subagent-badge"),T=this.minimizedSubagents.get(o)?.size||0,C=v?parseInt(v.querySelector(".subagent-count")?.textContent||"0"):0;if(T!==C){this._fullRenderSessionTabs();return}}else this._fullRenderSessionTabs()}_fullRenderSessionTabs(){const e=this.$("sessionTabs");document.querySelectorAll("body > .subagent-dropdown").forEach(n=>n.remove()),this.cancelHideSubagentDropdown();const t=[];let s=this.sessionOrder;MobileDetection.getDeviceType()==="mobile"&&this.activeSessionId&&(s=[this.activeSessionId,...this.sessionOrder.filter(n=>n!==this.activeSessionId)]);for(const n of s){const i=this.sessions.get(n);if(!i)continue;const o=n===this.activeSessionId,l=i.status||"idle",a=this.getSessionName(i),r=i.mode||"claude",c=i.color||"default",d=i.taskStats||{running:0,total:0},u=d.running>0,h=this.tabAlerts.get(n),m=h==="action"?" tab-alert-action":h==="idle"?" tab-alert-idle":"",p=this.minimizedSubagents.get(n),f=(p?.size||0)>0?this.renderSubagentTabBadge(n,p):"",S=i.workingDir&&i.workingDir.split("/").pop()||"",b=(this._tallTabsEnabled??!1)&&i.name&&S&&S!==a;t.push(`<div class="session-tab ${o?"active":""}${m}" data-id="${n}" data-color="${c}" onclick="app.selectSession('${escapeHtml(n)}')" oncontextmenu="event.preventDefault(); app.startInlineRename('${escapeHtml(n)}')" tabindex="0" role="tab" aria-selected="${o?"true":"false"}" aria-label="${escapeHtml(a)} session" ${i.workingDir?`title="${escapeHtml(i.workingDir)}"`:""}>
1
+ "use strict";const _SSE_HANDLER_MAP=[[SSE_EVENTS.INIT,"_onInit"],[SSE_EVENTS.SESSION_CREATED,"_onSessionCreated"],[SSE_EVENTS.SESSION_UPDATED,"_onSessionUpdated"],[SSE_EVENTS.SESSION_DELETED,"_onSessionDeleted"],[SSE_EVENTS.SESSION_TERMINAL,"_onSessionTerminal"],[SSE_EVENTS.SESSION_NEEDS_REFRESH,"_onSessionNeedsRefresh"],[SSE_EVENTS.SESSION_CLEAR_TERMINAL,"_onSessionClearTerminal"],[SSE_EVENTS.SESSION_COMPLETION,"_onSessionCompletion"],[SSE_EVENTS.SESSION_ERROR,"_onSessionError"],[SSE_EVENTS.SESSION_EXIT,"_onSessionExit"],[SSE_EVENTS.SESSION_IDLE,"_onSessionIdle"],[SSE_EVENTS.SESSION_WORKING,"_onSessionWorking"],[SSE_EVENTS.SESSION_AUTO_CLEAR,"_onSessionAutoClear"],[SSE_EVENTS.SESSION_CLI_INFO,"_onSessionCliInfo"],[SSE_EVENTS.SCHEDULED_CREATED,"_onScheduledCreated"],[SSE_EVENTS.SCHEDULED_UPDATED,"_onScheduledUpdated"],[SSE_EVENTS.SCHEDULED_COMPLETED,"_onScheduledCompleted"],[SSE_EVENTS.SCHEDULED_STOPPED,"_onScheduledStopped"],[SSE_EVENTS.RESPAWN_STARTED,"_onRespawnStarted"],[SSE_EVENTS.RESPAWN_STOPPED,"_onRespawnStopped"],[SSE_EVENTS.RESPAWN_STATE_CHANGED,"_onRespawnStateChanged"],[SSE_EVENTS.RESPAWN_CYCLE_STARTED,"_onRespawnCycleStarted"],[SSE_EVENTS.RESPAWN_BLOCKED,"_onRespawnBlocked"],[SSE_EVENTS.RESPAWN_AUTO_ACCEPT_SENT,"_onRespawnAutoAcceptSent"],[SSE_EVENTS.RESPAWN_DETECTION_UPDATE,"_onRespawnDetectionUpdate"],[SSE_EVENTS.RESPAWN_TIMER_STARTED,"_onRespawnTimerStarted"],[SSE_EVENTS.RESPAWN_TIMER_CANCELLED,"_onRespawnTimerCancelled"],[SSE_EVENTS.RESPAWN_TIMER_COMPLETED,"_onRespawnTimerCompleted"],[SSE_EVENTS.RESPAWN_ERROR,"_onRespawnError"],[SSE_EVENTS.RESPAWN_ACTION_LOG,"_onRespawnActionLog"],[SSE_EVENTS.TASK_CREATED,"_onTaskCreated"],[SSE_EVENTS.TASK_COMPLETED,"_onTaskCompleted"],[SSE_EVENTS.TASK_FAILED,"_onTaskFailed"],[SSE_EVENTS.TASK_UPDATED,"_onTaskUpdated"],[SSE_EVENTS.MUX_CREATED,"_onMuxCreated"],[SSE_EVENTS.MUX_KILLED,"_onMuxKilled"],[SSE_EVENTS.MUX_DIED,"_onMuxDied"],[SSE_EVENTS.MUX_STATS_UPDATED,"_onMuxStatsUpdated"],[SSE_EVENTS.SESSION_RALPH_LOOP_UPDATE,"_onRalphLoopUpdate"],[SSE_EVENTS.SESSION_RALPH_TODO_UPDATE,"_onRalphTodoUpdate"],[SSE_EVENTS.SESSION_RALPH_COMPLETION_DETECTED,"_onRalphCompletionDetected"],[SSE_EVENTS.SESSION_RALPH_STATUS_UPDATE,"_onRalphStatusUpdate"],[SSE_EVENTS.SESSION_CIRCUIT_BREAKER_UPDATE,"_onCircuitBreakerUpdate"],[SSE_EVENTS.SESSION_EXIT_GATE_MET,"_onExitGateMet"],[SSE_EVENTS.SESSION_BASH_TOOL_START,"_onBashToolStart"],[SSE_EVENTS.SESSION_BASH_TOOL_END,"_onBashToolEnd"],[SSE_EVENTS.SESSION_BASH_TOOLS_UPDATE,"_onBashToolsUpdate"],[SSE_EVENTS.HOOK_IDLE_PROMPT,"_onHookIdlePrompt"],[SSE_EVENTS.HOOK_PERMISSION_PROMPT,"_onHookPermissionPrompt"],[SSE_EVENTS.HOOK_ELICITATION_DIALOG,"_onHookElicitationDialog"],[SSE_EVENTS.HOOK_STOP,"_onHookStop"],[SSE_EVENTS.HOOK_TEAMMATE_IDLE,"_onHookTeammateIdle"],[SSE_EVENTS.HOOK_TASK_COMPLETED,"_onHookTaskCompleted"],[SSE_EVENTS.SUBAGENT_DISCOVERED,"_onSubagentDiscovered"],[SSE_EVENTS.SUBAGENT_UPDATED,"_onSubagentUpdated"],[SSE_EVENTS.SUBAGENT_TOOL_CALL,"_onSubagentToolCall"],[SSE_EVENTS.SUBAGENT_PROGRESS,"_onSubagentProgress"],[SSE_EVENTS.SUBAGENT_MESSAGE,"_onSubagentMessage"],[SSE_EVENTS.SUBAGENT_TOOL_RESULT,"_onSubagentToolResult"],[SSE_EVENTS.SUBAGENT_COMPLETED,"_onSubagentCompleted"],[SSE_EVENTS.IMAGE_DETECTED,"_onImageDetected"],[SSE_EVENTS.TUNNEL_STARTED,"_onTunnelStarted"],[SSE_EVENTS.TUNNEL_STOPPED,"_onTunnelStopped"],[SSE_EVENTS.TUNNEL_PROGRESS,"_onTunnelProgress"],[SSE_EVENTS.TUNNEL_ERROR,"_onTunnelError"],[SSE_EVENTS.TUNNEL_QR_ROTATED,"_onTunnelQrRotated"],[SSE_EVENTS.TUNNEL_QR_REGENERATED,"_onTunnelQrRegenerated"],[SSE_EVENTS.TUNNEL_QR_AUTH_USED,"_onTunnelQrAuthUsed"],[SSE_EVENTS.PLAN_SUBAGENT,"_onPlanSubagent"],[SSE_EVENTS.PLAN_PROGRESS,"_onPlanProgress"],[SSE_EVENTS.PLAN_STARTED,"_onPlanStarted"],[SSE_EVENTS.PLAN_CANCELLED,"_onPlanCancelled"],[SSE_EVENTS.PLAN_COMPLETED,"_onPlanCompleted"]];class CodemanApp{constructor(){this.sessions=new Map,this._shortIdCache=new Map,this.sessionOrder=[],this.draggedTabId=null,this.cases=[],this.currentRun=null,this.totalTokens=0,this.globalStats=null,this.eventSource=null,this.terminal=null,this.fitAddon=null,this.activeSessionId=null,this._initGeneration=0,this._initFallbackTimer=null,this._selectGeneration=0,this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},this.timerCountdownInterval=null,this.terminalBuffers=new Map,this.editingSessionId=null,this.pendingCloseSessionId=null,this.muxSessions=[],this.ralphStates=new Map,this.subagents=new Map,this.subagentActivity=new Map,this.subagentToolResults=new Map,this.activeSubagentId=null,this.subagentPanelVisible=!1,this.subagentWindows=new Map,this.subagentWindowZIndex=ZINDEX_SUBAGENT_BASE,this.minimizedSubagents=new Map,this._subagentHideTimeout=null,this.subagentParentMap=new Map,this.teams=new Map,this.teamTasks=new Map,this.teammateMap=new Map,this.teammatePanesByName=new Map,this.teammateTerminals=new Map,this.terminalBufferCache=new Map,this.ralphStatePanelCollapsed=!0,this.ralphClosedSessions=new Set,this.planSubagents=new Map,this.planSubagentWindowZIndex=ZINDEX_PLAN_SUBAGENT_BASE,this.planGenerationStopped=!1,this.planAgentsMinimized=!1,this.wizardDragState=null,this.wizardDragListeners=null,this.wizardPosition=null,this.projectInsights=new Map,this.logViewerWindows=new Map,this.logViewerWindowZIndex=ZINDEX_LOG_VIEWER_BASE,this.projectInsightsPanelVisible=!1,this.currentSessionWorkingDir=null,this.imagePopups=new Map,this.imagePopupZIndex=ZINDEX_IMAGE_POPUP_BASE,this.tabAlerts=new Map,this.pendingHooks=new Map,this.pendingWrites=[],this.writeFrameScheduled=!1,this._wasAtBottomBeforeWrite=!0,this.syncWaitTimeout=null,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.flickerFilterTimeout=null,this.renderSessionTabsTimeout=null,this.renderRalphStatePanelTimeout=null,this.renderTaskPanelTimeout=null,this.renderMuxSessionsTimeout=null,this.systemStatsInterval=null,this.sseReconnectTimeout=null,this._sseListenerCleanup=null,this.reconnectAttempts=0,this.maxReconnectAttempts=10,this.isOnline=navigator.onLine,this._inputQueue=new Map,this._inputQueueMaxBytes=64*1024,this._connectionStatus="connected",this._inputSendChain=Promise.resolve(),this._localEchoOverlay=null,this._localEchoEnabled=!1,this._restoringFlushedState=!1,this.activeFocusTrap=null,this.notificationManager=new NotificationManager(this),this.idleTimers=new Map,this._elemCache={},this.init()}$(e){return this._elemCache[e]||(this._elemCache[e]=document.getElementById(e)),this._elemCache[e]}formatTokens(e){if(e>=1e6){const t=e/1e6;return t>=10?`${t.toFixed(1)}m`:`${t.toFixed(2)}m`}else if(e>=1e3){const t=e/1e3;return t>=100?`${t.toFixed(0)}k`:`${t.toFixed(1)}k`}return String(e)}estimateCost(e,t){const s=e/1e6*15,n=t/1e6*75;return s+n}setPendingHook(e,t){this.pendingHooks.has(e)||this.pendingHooks.set(e,new Set),this.pendingHooks.get(e).add(t),this.updateTabAlertFromHooks(e)}clearPendingHooks(e,t=null){const s=this.pendingHooks.get(e);s&&(t?s.delete(t):s.clear(),s.size===0&&this.pendingHooks.delete(e),this.updateTabAlertFromHooks(e))}updateTabAlertFromHooks(e){const t=this.pendingHooks.get(e);!t||t.size===0?this.tabAlerts.delete(e):t.has("permission_prompt")||t.has("elicitation_dialog")?this.tabAlerts.set(e,"action"):t.has("idle_prompt")&&this.tabAlerts.set(e,"idle"),this.renderSessionTabs()}init(){MobileDetection.init(),KeyboardHandler.init(),SwipeHandler.init(),VoiceInput.init(),KeyboardAccessoryBar.init(),this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility(),document.documentElement.classList.remove("mobile-init"),requestAnimationFrame(()=>{this.initTerminal(),this.loadFontSize(),this.connectSSE(),this._initFallbackTimer=setTimeout(()=>{this._initGeneration===0&&this.loadState()},3e3)}),this.registerServiceWorker();const e=fetch("/api/settings").then(t=>t.ok?t.json():null).catch(()=>null);if(this.loadQuickStartCases(null,e),this._initRunMode(),this.setupEventListeners(),MobileDetection.isTouchDevice()){const t=s=>{s&&s.addEventListener("touchstart",n=>{if(!KeyboardHandler.keyboardVisible)return;const i=n.target.closest("button");i&&(n.preventDefault(),i.click(),typeof app<"u"&&app.terminal&&app.terminal.focus())},{passive:!1})};t(document.querySelector(".toolbar")),t(document.querySelector(".welcome-overlay"))}this.setupOnlineDetection(),this.loadAppSettingsFromServer(e).then(()=>{this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility()}),document.body.classList.add("app-loaded")}initTerminal(){const e=parseInt(localStorage.getItem("codeman-scrollback"))||DEFAULT_SCROLLBACK;if(this.terminal=new Terminal({theme:{background:"#0d0d0d",foreground:"#e0e0e0",cursor:"#e0e0e0",cursorAccent:"#0d0d0d",selection:"rgba(255, 255, 255, 0.3)",black:"#0d0d0d",red:"#ff6b6b",green:"#51cf66",yellow:"#ffd43b",blue:"#339af0",magenta:"#cc5de8",cyan:"#22b8cf",white:"#e0e0e0",brightBlack:"#495057",brightRed:"#ff8787",brightGreen:"#69db7c",brightYellow:"#ffe066",brightBlue:"#5c7cfa",brightMagenta:"#da77f2",brightCyan:"#66d9e8",brightWhite:"#ffffff"},fontFamily:'"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, monospace',fontSize:MobileDetection.getDeviceType()==="mobile"?10:14,lineHeight:1.2,cursorBlink:!1,cursorStyle:"block",scrollback:e,allowTransparency:!0,allowProposedApi:!0}),this.fitAddon=new FitAddon.FitAddon,this.terminal.loadAddon(this.fitAddon),typeof Unicode11Addon<"u")try{const r=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(r),this.terminal.unicode.activeVersion="11"}catch{}const t=document.getElementById("terminalContainer");if(this.terminal.open(t),this._webglAddon=null,typeof WebglAddon<"u")try{this._webglAddon=new WebglAddon.WebglAddon,this._webglAddon.onContextLoss(()=>{this._webglAddon.dispose(),this._webglAddon=null}),this.terminal.loadAddon(this._webglAddon)}catch{}if(this._localEchoOverlay=new LocalEchoOverlay(this.terminal),MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this.registerFilePathLinkProvider(),t.addEventListener("wheel",r=>{r.preventDefault();const c=Math.round(r.deltaY/25)||(r.deltaY>0?1:-1);this.terminal.scrollLines(c)},{passive:!1}),!(MobileDetection.isTouchDevice()&&window.innerWidth<1024)){let r=0,c=0,d=0,u=0,h=null,m=!1;const p=t.querySelector(".xterm-viewport"),g=f=>{if(!p)return;const S=u?(f-u)/16.67:1;u=f,m?(c!==0&&(p.scrollTop+=c,c=0),h=requestAnimationFrame(g)):Math.abs(d)>.1?(p.scrollTop+=d*S,d*=.94,h=requestAnimationFrame(g)):(h=null,d=0)};t.addEventListener("touchstart",f=>{f.touches.length===1&&(r=f.touches[0].clientY,c=0,d=0,m=!0,u=0,h||(h=requestAnimationFrame(g)))},{passive:!0}),t.addEventListener("touchmove",f=>{if(f.touches.length===1&&m){const S=f.touches[0].clientY,w=r-S;c+=w,d=w*1.2,r=S}},{passive:!0}),t.addEventListener("touchend",()=>{m=!1},{passive:!0}),t.addEventListener("touchcancel",()=>{m=!1,d=0},{passive:!0})}this.showWelcome(),this._resizeTimeout=null,this._lastResizeDims=null;const i=40,o=10,l=()=>{this._resizeTimeout||(this._resizeTimeout=setTimeout(()=>{if(this._resizeTimeout=null,this.fitAddon){this.fitAddon.fit();const r=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;if(this.activeSessionId&&!r){const c=this.fitAddon.proposeDimensions(),d=c?Math.max(c.cols,i):i,u=c?Math.max(c.rows,o):o;(!this._lastResizeDims||d!==this._lastResizeDims.cols||u!==this._lastResizeDims.rows)&&(this._lastResizeDims={cols:d,rows:u},fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:d,rows:u})}).catch(()=>{}))}}this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},100))};window.addEventListener("resize",l),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(l),this.terminalResizeObserver.observe(t),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const a=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const r=this._pendingInput,c=this.activeSessionId;this._pendingInput="",this._sendInputAsync(c,r)}};this.terminal.onData(r=>{if(this.activeSessionId){if(/^\x1b\[[\?>=]?[\d;]*[cnR]$/.test(r))return;if(this._localEchoEnabled){if(r==="\x7F"){if(this._localEchoOverlay?.removeChar()==="flushed"){const{count:u,text:h}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(u===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,u),this._flushedTexts?.set(this.activeSessionId,h))),this._pendingInput+=r,a()}return}if(/^[\r\n]+$/.test(r)){const d=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),d&&(this._pendingInput+=d,a()),setTimeout(()=>{this._pendingInput+="\r",a()},80);return}if(r.length>1&&r.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(r);return}if(r.charCodeAt(0)<32){if(r.length>1&&r.charCodeAt(0)===27){this._pendingInput+=r,a();return}if(this._restoringFlushedState){this._pendingInput+=r,a();return}if(r===" "){const u=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),u&&(this._pendingInput+=u),this._pendingInput+=r,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let h="";try{const p=this._localEchoOverlay?.findPrompt?.();if(p){const g=this.terminal.buffer.active,f=g.getLine(g.viewportY+p.row);f&&(h=f.translateToString(!0).slice(p.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=h,a(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const m=this;this._tabCompletionFallback=setTimeout(()=>{if(m._tabCompletionFallback=null,!m._tabCompletionSessionId||m._tabCompletionSessionId!==m.activeSessionId)return;const p=m._localEchoOverlay;!p||p.pendingText||m.terminal.write("",()=>{if(!m._tabCompletionSessionId)return;p.resetBufferDetection();const g=p.detectBufferText();g&&g!==m._tabCompletionBaseText&&(m._tabCompletionSessionId=null,m._tabCompletionRetries=0,m._tabCompletionBaseText=null,p.rerender())})},300);return}const d=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),d&&(this._pendingInput+=d),this._pendingInput+=r,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}if(r.length===1&&r.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(r);return}}if(this._pendingInput+=r,r.charCodeAt(0)<32||r.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}const c=performance.now();c-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=c,a()):(this._lastKeystrokeTime=c,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(a,0)))}})}registerFilePathLinkProvider(){const e=this;let t=-1;this.terminal.registerLinkProvider({provideLinks(s,n){s!==t&&(t=s);const o=e.terminal.buffer.active.getLine(s);if(!o){n(void 0);return}const l=o.translateToString(!0);if(!l||!l.includes("/")){n(void 0);return}const a=[],r=/(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]*\s+)*(\/[^\s"'<>|;&\n\x00-\x1f]+)/g,c=/(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\n\x00-\x1f]*\.(?:log|txt|json|md|yaml|yml|csv|xml|sh|py|ts|js))\b/g,d=/Bash\([^)]*?(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\)\n\x00-\x1f]+)/g,u=(m,p)=>{const g=l.indexOf(m,p);g!==-1&&(a.some(f=>f.range.start.x===g+1)||a.push({text:m,range:{start:{x:g+1,y:s},end:{x:g+m.length+1,y:s}},decorations:{pointerCursor:!0,underline:!0},activate(f,S){e.openLogViewerWindow(S,e.activeSessionId)}}))};let h;for(r.lastIndex=0;(h=r.exec(l))!==null;)u(h[2],h.index);for(c.lastIndex=0;(h=c.exec(l))!==null;)u(h[1],h.index);for(d.lastIndex=0;(h=d.exec(l))!==null;)u(h[1],h.index);a.length>0,n(a.length>0?a:void 0)}})}showWelcome(){const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus())}hideWelcome(){const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const t=document.getElementById("welcomeQr");t&&(clearTimeout(this._welcomeQrShrinkTimer),t.classList.remove("expanded"))}isTerminalAtBottom(){if(!this.terminal)return!0;const e=this.terminal.buffer.active;return e.viewportY>=e.baseY-2}batchTerminalWrite(e){if(this._isLoadingBuffer){this._loadBufferQueue&&this._loadBufferQueue.push(e);return}this.writeFrameScheduled||(this._wasAtBottomBeforeWrite=this.isTerminalAtBottom());const s=(this.activeSessionId?this.sessions.get(this.activeSessionId):null)?.flickerFilterEnabled??!1;if(/\x1b\[\d{1,2}A/.test(e)||this.flickerFilterActive&&!s){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(s){if(e.includes("\x1B[2J")||e.includes("\x1B[H\x1B[J")||e.includes("\x1B[H")&&e.includes("\x1B[?25l")){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(this.flickerFilterActive){this.flickerFilterBuffer+=e;return}}this.pendingWrites.push(e),this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{if(this.pendingWrites.length>0&&this.terminal){const i=this.pendingWrites.join(""),o=i.includes(DEC_SYNC_START),l=i.includes(DEC_SYNC_END);if(o&&!l){this.syncWaitTimeout||(this.syncWaitTimeout=setTimeout(()=>{this.syncWaitTimeout=null,this.flushPendingWrites()},50)),this.writeFrameScheduled=!1;return}this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.flushPendingWrites()}this.writeFrameScheduled=!1}))}flushFlickerBuffer(){this.flickerFilterBuffer&&(this.pendingWrites.push(this.flickerFilterBuffer),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1})))}_updateLocalEchoState(){const e=this.loadAppSettingsFromStorage(),t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,n=!!((e.localEchoEnabled??MobileDetection.isTouchDevice())&&t);this._localEchoEnabled&&!n&&this._localEchoOverlay?.clear(),this._localEchoEnabled=n,this._localEchoOverlay&&t&&(t.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:i=>{try{const o=i.buffer.active,l=o.cursorY,a=o.getLine(o.viewportY+l);if(!a)return null;const c=a.translateToString(!0).indexOf("\u2503");return c>=0?{row:l,col:c}:null}catch{return null}}}):this._localEchoOverlay.setPrompt({type:"character",char:"\u276F",offset:2}))}flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=extractSyncSegments(this.pendingWrites.join(""));this.pendingWrites=[];for(const t of e)if(t){const s=t.startsWith(DEC_SYNC_START)?t.slice(DEC_SYNC_START.length):t;s&&this.terminal.write(s)}if(this._wasAtBottomBeforeWrite&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const t=this._localEchoOverlay,s=this;this.terminal.write("",()=>{if(!s._tabCompletionSessionId)return;t.resetBufferDetection();const n=t.detectBufferText();n?n===s._tabCompletionBaseText?(t.undoDetection(),s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0)):(s._tabCompletionSessionId=null,s._tabCompletionRetries=0,s._tabCompletionBaseText=null,s._tabCompletionFallback&&(clearTimeout(s._tabCompletionFallback),s._tabCompletionFallback=null),t.rerender()):(s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0))})}}chunkedTerminalWrite(e,t=TERMINAL_CHUNK_SIZE){return new Promise(s=>{if(!e||e.length===0){this._finishBufferLoad(),s();return}this._isLoadingBuffer=!0,this._loadBufferQueue=[];const n=e.replace(DEC_SYNC_STRIP_RE,""),i=()=>{this._finishBufferLoad(),s()};if(n.length<=t){this.terminal.write(n),i();return}let o=0;const l=()=>{if(o>=n.length){requestAnimationFrame(i);return}const a=n.slice(o,o+t);this.terminal.write(a),o+=t,requestAnimationFrame(l)};requestAnimationFrame(l)})}_finishBufferLoad(){const e=this._loadBufferQueue;if(this._isLoadingBuffer=!1,this._loadBufferQueue=null,e&&e.length>0)for(const t of e)this.batchTerminalWrite(t)}setupEventListeners(){document.addEventListener("keydown",t=>{t.key==="Escape"&&(this.closeAllPanels(),this.closeHelp()),(t.ctrlKey||t.metaKey)&&(t.key==="?"||t.key==="/")&&(t.preventDefault(),this.showHelp()),(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.quickStart()),(t.ctrlKey||t.metaKey)&&t.key==="w"&&(t.preventDefault(),this.killActiveSession()),(t.ctrlKey||t.metaKey)&&t.key==="Tab"&&(t.preventDefault(),this.nextSession()),(t.ctrlKey||t.metaKey)&&t.key==="k"&&(t.preventDefault(),this.killAllSessions()),(t.ctrlKey||t.metaKey)&&t.key==="l"&&(t.preventDefault(),this.clearTerminal()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="R"&&(t.preventDefault(),this.restoreTerminalSize()),(t.ctrlKey||t.metaKey)&&(t.key==="="||t.key==="+")&&(t.preventDefault(),this.increaseFontSize()),(t.ctrlKey||t.metaKey)&&t.key==="-"&&(t.preventDefault(),this.decreaseFontSize()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="V"&&(t.preventDefault(),VoiceInput.toggle())},!0);const e=this.$("headerTokens");e&&!e._statsHandlerAttached&&(e.classList.add("clickable"),e._statsHandlerAttached=!0,e.addEventListener("click",()=>this.openTokenStats())),this.setupColorPicker()}connectSSE(){if(!navigator.onLine){this.setConnectionStatus("offline");return}this.sseReconnectTimeout&&(clearTimeout(this.sseReconnectTimeout),this.sseReconnectTimeout=null),this._sseListenerCleanup&&(this._sseListenerCleanup(),this._sseListenerCleanup=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.reconnectAttempts===0?this.setConnectionStatus("connecting"):this.setConnectionStatus("reconnecting"),this.eventSource=new EventSource("/api/events");const e=[],t=(s,n)=>{this.eventSource.addEventListener(s,n),e.push({event:s,handler:n})};if(this._sseListenerCleanup=()=>{for(const{event:s,handler:n}of e)this.eventSource&&this.eventSource.removeEventListener(s,n);e.length=0},this.eventSource.onopen=()=>{this.reconnectAttempts=0,this.setConnectionStatus("connected")},this.eventSource.onerror=()=>{this.reconnectAttempts++,this.reconnectAttempts>=this.maxReconnectAttempts?this.setConnectionStatus("disconnected"):this.setConnectionStatus("reconnecting"),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.sseReconnectTimeout&&clearTimeout(this.sseReconnectTimeout);const s=this.reconnectAttempts<=1?200:Math.min(500*Math.pow(2,this.reconnectAttempts-2),3e4);this.sseReconnectTimeout=setTimeout(()=>this.connectSSE(),s)},!this._sseHandlerWrappers){this._sseHandlerWrappers=new Map;for(const[s,n]of _SSE_HANDLER_MAP){const i=this[n];this._sseHandlerWrappers.set(s,o=>{try{i.call(this,o.data?JSON.parse(o.data):{})}catch{}})}}for(const[s]of _SSE_HANDLER_MAP)t(s,this._sseHandlerWrappers.get(s))}_onInit(e){this.handleInit(e)}_onSessionCreated(e){this.sessions.set(e.id,e),this.sessionOrder.includes(e.id)||(this.sessionOrder.push(e.id),this.saveSessionOrder()),this.renderSessionTabs(),this.updateCost(),this.sessions.size===1&&this.startSystemStatsPolling()}_onSessionUpdated(e){const t=e.session||e,s=this.sessions.get(t.id),n=t.claudeSessionId&&(!s||!s.claudeSessionId);this.sessions.set(t.id,t),this.renderSessionTabs(),this.updateCost(),t.id===this.activeSessionId&&t.tokens&&this.updateRespawnTokens(t.tokens),this.updateSubagentParentNames(t.id),n&&(this.recheckOrphanSubagents(),requestAnimationFrame(()=>{this.updateConnectionLines()}))}_onSessionDeleted(e){if(this._cleanupSessionData(e.id),this.activeSessionId===e.id){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome()}this.renderSessionTabs(),this.renderRalphStatePanel(),this.renderProjectInsightsPanel(),this.sessions.size===0&&this.stopSystemStatsPolling()}_onSessionTerminal(e){e.id===this.activeSessionId&&this.batchTerminalWrite(e.data)}async _onSessionNeedsRefresh(){if(!(!this.activeSessionId||!this.terminal))try{const s=await(await fetch(`/api/sessions/${this.activeSessionId}/terminal?tail=262144`)).json();s.terminalBuffer&&(this.terminal.clear(),this.terminal.reset(),await this.chunkedTerminalWrite(s.terminalBuffer),this.terminal.scrollToBottom(),this._localEchoOverlay?.rerender(),this.activeSessionId&&this.sendResize(this.activeSessionId))}catch{}}async _onSessionClearTerminal(e){if(e.id===this.activeSessionId)try{const s=await(await fetch(`/api/sessions/${e.id}/terminal`)).json();if(this.terminal.clear(),this.terminal.reset(),s.terminalBuffer){const n=s.terminalBuffer.replace(DEC_SYNC_STRIP_RE,"");await this.chunkedTerminalWrite(n)}this.sendResize(e.id),this._localEchoOverlay?.rerender()}catch{}}_onSessionCompletion(e){this.totalCost+=e.cost||0,this.updateCost(),e.id===this.activeSessionId&&(this.terminal.writeln(""),this.terminal.writeln(`\x1B[1;32m Done (Cost: $${(e.cost||0).toFixed(4)})\x1B[0m`))}_onSessionError(e){e.id===this.activeSessionId&&this.terminal.writeln(`\x1B[1;31m Error: ${e.error}\x1B[0m`);const t=this.sessions.get(e.id);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:e.id,sessionName:t?.name||this.getShortId(e.id),title:"Session Error",message:e.error||"Unknown error"})}_onSessionExit(e){const t=this.sessions.get(e.id);t&&(t.status="stopped",this.renderSessionTabs(),e.id===this.activeSessionId&&this._updateLocalEchoState()),e.code&&e.code!==0&&this.notificationManager?.notify({urgency:"critical",category:"session-crash",sessionId:e.id,sessionName:t?.name||this.getShortId(e.id),title:"Session Crashed",message:`Exited with code ${e.code}`})}_onSessionIdle(e){const t=this.sessions.get(e.id);if(t&&(t.status="idle",this.renderSessionTabs(),this.sendPendingCtrlL(e.id),e.id===this.activeSessionId&&this._updateLocalEchoState()),!this.respawnStatus[e.id]?.enabled){const s=this.notificationManager?.preferences?.stuckThresholdMs||6e5;clearTimeout(this.idleTimers.get(e.id)),this.idleTimers.set(e.id,setTimeout(()=>{const n=this.sessions.get(e.id);this.notificationManager?.notify({urgency:"warning",category:"session-stuck",sessionId:e.id,sessionName:n?.name||this.getShortId(e.id),title:"Session Idle",message:`Idle for ${Math.round(s/6e4)}+ minutes`}),this.idleTimers.delete(e.id)},s))}}_onSessionWorking(e){const t=this.sessions.get(e.id);t&&(t.status="busy",this.pendingHooks.has(e.id)||this.tabAlerts.delete(e.id),this.renderSessionTabs(),this.sendPendingCtrlL(e.id),e.id===this.activeSessionId&&this._updateLocalEchoState());const s=this.idleTimers.get(e.id);s&&(clearTimeout(s),this.idleTimers.delete(e.id))}_onSessionAutoClear(e){e.sessionId===this.activeSessionId&&(this.showToast(`Auto-cleared at ${e.tokens.toLocaleString()} tokens`,"info"),this.updateRespawnTokens(0));const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-clear",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Auto-Cleared",message:`Context reset at ${(e.tokens||0).toLocaleString()} tokens`})}_onSessionCliInfo(e){const t=this.sessions.get(e.sessionId);t&&(e.version&&(t.cliVersion=e.version),e.model&&(t.cliModel=e.model),e.accountType&&(t.cliAccountType=e.accountType),e.latestVersion&&(t.cliLatestVersion=e.latestVersion)),e.sessionId===this.activeSessionId&&this.updateCliInfoDisplay()}_onScheduledCreated(e){this.currentRun=e,this.showTimer()}_onScheduledUpdated(e){this.currentRun=e,this.updateTimer()}_onScheduledCompleted(e){this.currentRun=e,this.hideTimer(),this.showToast("Scheduled run completed!","success")}_onScheduledStopped(){this.currentRun=null,this.hideTimer()}_onRespawnStarted(e){this.respawnStatus[e.sessionId]=e.status,e.sessionId===this.activeSessionId&&this.showRespawnBanner()}_onRespawnStopped(e){delete this.respawnStatus[e.sessionId],e.sessionId===this.activeSessionId&&this.hideRespawnBanner()}_onRespawnStateChanged(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].state=e.state),e.sessionId===this.activeSessionId&&this.updateRespawnBanner(e.state)}_onRespawnCycleStarted(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].cycleCount=e.cycleNumber),e.sessionId===this.activeSessionId&&(document.getElementById("respawnCycleCount").textContent=e.cycleNumber)}_onRespawnBlocked(e){const t=this.sessions.get(e.sessionId),n={circuit_breaker_open:"Circuit Breaker Open",exit_signal:"Exit Signal Detected",status_blocked:"Claude Reported BLOCKED"}[e.reason]||"Respawn Blocked";if(this.notificationManager?.notify({urgency:"critical",category:"respawn-blocked",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:n,message:e.details}),e.sessionId===this.activeSessionId){const i=document.getElementById("respawnStateLabel");i&&(i.textContent=n,i.classList.add("respawn-blocked"))}}_onRespawnAutoAcceptSent(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-accept",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Plan Accepted",message:`Accepted plan mode for ${t?.name||"session"}`})}_onRespawnDetectionUpdate(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].detection=e.detection),e.sessionId===this.activeSessionId&&this.updateDetectionDisplay(e.detection)}_onRespawnTimerStarted(e){if(e.endAt&&(this.respawnTimers[e.sessionId]={endAt:e.endAt,startedAt:e.startedAt,durationMinutes:e.durationMinutes},e.sessionId===this.activeSessionId&&this.showRespawnTimer()),e.timer){const{sessionId:t,timer:s}=e;this.respawnCountdownTimers[t]||(this.respawnCountdownTimers[t]={}),this.respawnCountdownTimers[t][s.name]={endsAt:s.endsAt,totalMs:s.durationMs,reason:s.reason},t===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.startCountdownInterval())}}_onRespawnTimerCancelled(e){const{sessionId:t,timerName:s}=e;this.respawnCountdownTimers[t]&&delete this.respawnCountdownTimers[t][s],t===this.activeSessionId&&this.updateCountdownTimerDisplay()}_onRespawnTimerCompleted(e){const{sessionId:t,timerName:s}=e;this.respawnCountdownTimers[t]&&delete this.respawnCountdownTimers[t][s],t===this.activeSessionId&&this.updateCountdownTimerDisplay()}_onRespawnError(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Respawn Error",message:e.error||e.message||"Respawn encountered an error"})}_onRespawnActionLog(e){const{sessionId:t,action:s}=e;this.addActionLogEntry(t,s),t===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.updateActionLogDisplay())}_onTaskCreated(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskCompleted(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskFailed(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskUpdated(e){e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onMuxCreated(e){this.muxSessions.push(e),this.renderMuxSessions()}_onMuxKilled(e){this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e.sessionId),this.renderMuxSessions()}_onMuxDied(e){this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e.sessionId),this.renderMuxSessions(),this.showToast("Mux session died: "+this.getShortId(e.sessionId),"warning")}_onMuxStatsUpdated(e){this.muxSessions=e,document.getElementById("monitorPanel").classList.contains("open")&&this.renderMuxSessions()}_onRalphLoopUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{loop:e.state})}_onRalphTodoUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{todos:e.todos})}_onRalphCompletionDetected(e){if(this.ralphClosedSessions.has(e.sessionId))return;const t=`${e.sessionId}:${e.phrase}`;if(this._shownCompletions?.has(t))return;this._shownCompletions||(this._shownCompletions=new Set),this._shownCompletions.add(t),setTimeout(()=>this._shownCompletions?.delete(t),3e4);const s=this.ralphStates.get(e.sessionId)||{};s.loop&&(s.loop.active=!1,this.updateRalphState(e.sessionId,s));const n=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"ralph-complete",sessionId:e.sessionId,sessionName:n?.name||this.getShortId(e.sessionId),title:"Loop Complete",message:`Completion: ${e.phrase||"unknown"}`})}_onRalphStatusUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{statusBlock:e.block})}_onCircuitBreakerUpdate(e){if(!this.ralphClosedSessions.has(e.sessionId)&&(this.updateRalphState(e.sessionId,{circuitBreaker:e.status}),e.status.state==="OPEN")){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"critical",category:"circuit-breaker",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Circuit Breaker Open",message:e.status.reason||"Loop stuck - no progress detected"})}}_onExitGateMet(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"exit-gate",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Exit Gate Met",message:`Loop ready to exit (indicators: ${e.completionIndicators})`})}_onBashToolStart(e){this.handleBashToolStart(e.sessionId,e.tool)}_onBashToolEnd(e){this.handleBashToolEnd(e.sessionId,e.tool)}_onBashToolsUpdate(e){this.handleBashToolsUpdate(e.sessionId,e.tools)}_onHookIdlePrompt(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this.notificationManager?.notify({urgency:"warning",category:"hook-idle",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Waiting for Input",message:e.message||"Claude is idle and waiting for a prompt"})}_onHookPermissionPrompt(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const s=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this.notificationManager?.notify({urgency:"critical",category:"hook-permission",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Permission Required",message:s||"Claude needs tool approval to continue"})}_onHookElicitationDialog(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this.notificationManager?.notify({urgency:"critical",category:"hook-elicitation",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Question Asked",message:e.question||"Claude is asking a question and waiting for your answer"})}_onHookStop(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.clearPendingHooks(e.sessionId),this.notificationManager?.notify({urgency:"info",category:"hook-stop",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Response Complete",message:e.reason||"Claude has finished responding"})}_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"hook-teammate-idle",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Teammate Idle",message:`A teammate is idle in ${t?.name||e.sessionId}`})}_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"hook-task-completed",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Task Completed",message:`A team task completed in ${t?.name||e.sessionId}`})}_onSubagentDiscovered(e){if(this.subagents.set(e.agentId,e),this.subagentActivity.set(e.agentId,[]),this.subagentToolResults.delete(e.agentId),this.subagentWindows.has(e.agentId)&&this.forceCloseSubagentWindow(e.agentId),this.renderSubagentPanel(),this.findParentSessionForSubagent(e.agentId),e.status==="active"){const n=this.subagents.get(e.agentId);n?.sessionId&&Array.from(this.sessions.values()).some(o=>o.claudeSessionId===n.sessionId)&&this.openSubagentWindow(e.agentId)}requestAnimationFrame(()=>{this.updateConnectionLines()});const t=this.subagentParentMap.get(e.agentId),s=t?this.sessions.get(t):null;this.notificationManager?.notify({urgency:"info",category:"subagent-spawn",sessionId:t||e.sessionId,sessionName:s?.name||t||e.sessionId,title:"Subagent Spawned",message:e.description||"New background agent started"})}_onSubagentUpdated(e){const t=this.subagents.get(e.agentId);t?(Object.assign(t,e),this.subagents.set(e.agentId,t)):this.subagents.set(e.agentId,e),this.renderSubagentPanel(),this.subagentWindows.has(e.agentId)&&(this.renderSubagentWindowContent(e.agentId),this.updateSubagentWindowHeader(e.agentId))}_onSubagentToolCall(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"tool",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.renderSubagentPanel(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentProgress(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"progress",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentMessage(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"message",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentToolResult(e){this.subagentToolResults.has(e.agentId)||this.subagentToolResults.set(e.agentId,new Map);const t=this.subagentToolResults.get(e.agentId);if(t.set(e.toolUseId,e),t.size>50){const n=t.keys().next().value;t.delete(n)}const s=this.subagentActivity.get(e.agentId)||[];s.push({type:"tool_result",...e}),s.length>50&&s.shift(),this.subagentActivity.set(e.agentId,s),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}async _onSubagentCompleted(e){const t=this.subagents.get(e.agentId);if(t&&(t.status="completed",this.subagents.set(e.agentId,t)),this.renderSubagentPanel(),this.updateSubagentWindows(),this.subagentWindows.has(e.agentId)){const i=this.subagentWindows.get(e.agentId);i&&!i.minimized&&(await this.closeSubagentWindow(e.agentId),this.saveSubagentWindowStates())}const s=this.subagentParentMap.get(e.agentId),n=s?this.sessions.get(s):null;this.notificationManager?.notify({urgency:"info",category:"subagent-complete",sessionId:s||t?.sessionId||e.sessionId,sessionName:n?.name||s||e.sessionId,title:"Subagent Completed",message:t?.description||e.description||"Background agent finished"}),setTimeout(()=>{this.subagents.get(e.agentId)?.status==="completed"&&(this.subagentActivity.delete(e.agentId),this.subagentToolResults.delete(e.agentId))},300*1e3),setTimeout(()=>{this.subagents.get(e.agentId)?.status==="completed"&&!this.subagentWindows.has(e.agentId)&&(this.subagents.delete(e.agentId),this.subagentParentMap.delete(e.agentId))},1800*1e3)}_onImageDetected(e){this.openImagePopup(e)}_onTunnelStarted(e){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())}_onTunnelStopped(){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this.closeTunnelQR()}_onTunnelProgress(e){const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const s=document.getElementById("welcomeTunnelBtn");s?.classList.contains("connecting")&&(s.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)}_onTunnelError(e){this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))}_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()}_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()}_onTunnelQrAuthUsed(e){const s=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${s}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})}_onPlanSubagent(e){this.handlePlanSubagentEvent(e)}_onPlanProgress(e){this._planProgressHandler&&this._planProgressHandler({type:"plan:progress",data:e});const t=document.getElementById("planLoadingTitle"),s=document.getElementById("planLoadingHint");if(t&&e.phase){const n={"parallel-analysis":"Running parallel analysis...",subagent:e.detail||"Subagent working...",synthesis:"Synthesizing results...",verification:"Running verification..."};t.textContent=n[e.phase]||e.phase}s&&e.detail&&(s.textContent=e.detail)}_onPlanStarted(e){this.activePlanOrchestratorId=e.orchestratorId,this.planGenerationStopped=!1,this.renderMonitorPlanAgents()}_onPlanCancelled(e){this.activePlanOrchestratorId===e.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}_onPlanCompleted(e){this.activePlanOrchestratorId===e.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}setConnectionStatus(e){this._connectionStatus=e,this._updateConnectionIndicator(),e==="connected"&&this._inputQueue.size>0&&this._drainInputQueues()}_sendInputAsync(e,t){if(!this.isOnline||this._connectionStatus==="disconnected"){this._enqueueInput(e,t);return}this._inputSendChain=this._inputSendChain.then(()=>{fetch(`/api/sessions/${e}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:t}),keepalive:t.length<65536}).then(n=>{n.ok?this.clearPendingHooks(e):this._enqueueInput(e,t)}).catch(()=>{this._enqueueInput(e,t)})})}_enqueueInput(e,t){let n=(this._inputQueue.get(e)||"")+t;n.length>this._inputQueueMaxBytes&&(n=n.slice(n.length-this._inputQueueMaxBytes)),this._inputQueue.set(e,n),this._updateConnectionIndicator()}async _drainInputQueues(){if(this._inputQueue.size===0)return;const e=new Map(this._inputQueue);this._inputQueue.clear(),this._updateConnectionIndicator();for(const[t,s]of e)(await this._apiPost(`/api/sessions/${t}/input`,{input:s}))?.ok||this._enqueueInput(t,s);this._updateConnectionIndicator()}_updateConnectionIndicator(){const e=this.$("connectionIndicator"),t=this.$("connectionDot"),s=this.$("connectionText");if(!e||!t||!s)return;let n=0;for(const a of this._inputQueue.values())n+=a.length;const i=this._connectionStatus,o=n>0;if((i==="connected"||i==="connecting")&&!o){e.style.display="none";return}e.style.display="flex",t.className="connection-dot";const l=a=>a<1024?`${a}B`:`${(a/1024).toFixed(1)}KB`;i==="connected"&&o?(t.classList.add("draining"),s.textContent=`Sending ${l(n)}...`):i==="reconnecting"?(t.classList.add("reconnecting"),s.textContent=o?`Reconnecting (${l(n)} queued)`:"Reconnecting..."):(t.classList.add("offline"),s.textContent=o?`Offline (${l(n)} queued)`:"Offline")}setupOnlineDetection(){window.addEventListener("online",()=>{this.isOnline=!0,this.reconnectAttempts=0,this.connectSSE()}),window.addEventListener("offline",()=>{this.isOnline=!1,this.setConnectionStatus("offline")})}handleInit(e){this._initFallbackTimer&&(clearTimeout(this._initFallbackTimer),this._initFallbackTimer=null);const t=++this._initGeneration;if(e.version){const i=this.$("versionDisplay"),o=this.$("headerVersion");i&&(i.textContent=`v${e.version}`,i.title=`Codeman v${e.version}`),o&&(o.textContent=`v${e.version}`,o.title=`Codeman v${e.version}`)}VoiceInput.cleanup(),this.sessions.clear(),this.ralphStates.clear(),this.terminalBuffers.clear(),this.terminalBufferCache.clear(),this.projectInsights.clear(),this.teams.clear(),this.teamTasks.clear();for(const i of this.idleTimers.values())clearTimeout(i);if(this.idleTimers.clear(),this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.pendingWrites=[],this.writeFrameScheduled=!1,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._localEchoOverlay?.rerender(),this.pendingHooks.clear(),this._parentNameCache&&this._parentNameCache.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),MobileDetection.cleanup(),KeyboardHandler.cleanup(),MobileDetection.init(),KeyboardHandler.init(),this.tabAlerts.clear(),this._shownCompletions&&this._shownCompletions.clear(),this.notificationManager?.titleFlashInterval&&(clearInterval(this.notificationManager.titleFlashInterval),this.notificationManager.titleFlashInterval=null),this.notificationManager?.groupingMap){for(const{timeout:i}of this.notificationManager.groupingMap.values())clearTimeout(i);this.notificationManager.groupingMap.clear()}this.terminalResizeObserver&&(this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=null),this.planLoadingTimer&&(clearInterval(this.planLoadingTimer),this.planLoadingTimer=null),this.timerCountdownInterval&&(clearInterval(this.timerCountdownInterval),this.timerCountdownInterval=null),this.runSummaryAutoRefreshTimer&&(clearInterval(this.runSummaryAutoRefreshTimer),this.runSummaryAutoRefreshTimer=null),e.sessions.forEach(i=>{this.sessions.set(i.id,i),(i.ralphLoop||i.ralphTodos)&&!this.ralphClosedSessions.has(i.id)&&this.ralphStates.set(i.id,{loop:i.ralphLoop||null,todos:i.ralphTodos||[]})}),this.syncSessionOrder(),e.respawnStatus?this.respawnStatus=e.respawnStatus:this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},e.globalStats&&(this.globalStats=e.globalStats),this.totalCost=e.sessions.reduce((i,o)=>i+(o.totalCost||0),0),this.totalCost+=e.scheduledRuns.reduce((i,o)=>i+(o.totalCost||0),0);const s=e.scheduledRuns.find(i=>i.status==="running");if(s&&(this.currentRun=s,this.showTimer()),this.updateCost(),this.renderSessionTabs(),this.sessions.size>0?this.startSystemStatsPolling():this.stopSystemStatsPolling(),this.cleanupAllFloatingWindows(),e.subagents&&(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),e.subagents.forEach(i=>{this.subagents.set(i.agentId,i)}),this.renderSubagentPanel(),this.subagentParentMap.clear(),this.loadSubagentParentMap().then(()=>{for(const[i,o]of this.subagentParentMap){const l=this.subagents.get(i);if(l&&this.sessions.has(o)){l.parentSessionId=o;const a=this.sessions.get(o);a&&(l.parentSessionName=this.getSessionName(a)),this.subagents.set(i,l)}}for(const[i]of this.subagents)this.subagentParentMap.has(i)||this.findParentSessionForSubagent(i);this.restoreSubagentWindowStates()})),t!==this._initGeneration)return;const n=this.activeSessionId;if(this.activeSessionId=null,this.sessionOrder.length>0){let i=n;if(!i||!this.sessions.has(i))try{i=localStorage.getItem("codeman-active-session")}catch{}i&&this.sessions.has(i)?this.selectSession(i):this.selectSession(this.sessionOrder[0])}}async loadState(){try{const t=await(await fetch("/api/status")).json();this.handleInit(t)}catch{}}renderSessionTabs(){this.renderSessionTabsTimeout&&clearTimeout(this.renderSessionTabsTimeout),this.renderSessionTabsTimeout=setTimeout(()=>{this._renderSessionTabsImmediate()},100)}_updateActiveTabImmediate(e){const t=this.$("sessionTabs");if(!t)return;const s=t.querySelectorAll(".session-tab[data-id]");for(const n of s)n.dataset.id===e?n.classList.add("active"):n.classList.remove("active")}_renderSessionTabsImmediate(){const e=this.$("sessionTabs"),t=e.querySelectorAll(".session-tab[data-id]"),s=new Set([...t].map(o=>o.dataset.id)),n=new Set(this.sessions.keys());if(s.size===n.size&&[...s].every(o=>n.has(o)))for(const[o,l]of this.sessions){const a=e.querySelector(`.session-tab[data-id="${o}"]`);if(!a)continue;const r=o===this.activeSessionId,c=l.status||"idle",d=this.getSessionName(l),u=l.taskStats||{running:0,total:0},h=u.running>0;r&&!a.classList.contains("active")?a.classList.add("active"):!r&&a.classList.contains("active")&&a.classList.remove("active");const m=this.tabAlerts.get(o),p=m==="action",g=m==="idle",f=a.classList.contains("tab-alert-action"),S=a.classList.contains("tab-alert-idle");p&&!f?(a.classList.add("tab-alert-action"),a.classList.remove("tab-alert-idle")):g&&!S?(a.classList.add("tab-alert-idle"),a.classList.remove("tab-alert-action")):!m&&(f||S)&&a.classList.remove("tab-alert-action","tab-alert-idle");const w=a.querySelector(".tab-status");w&&!w.classList.contains(c)&&(w.className=`tab-status ${c}`);const b=a.querySelector(".tab-name");b&&b.textContent!==d&&(b.textContent=d);const y=a.querySelector(".tab-badge");if(h)if(y)y.textContent!==String(u.running)&&(y.textContent=u.running);else{this._fullRenderSessionTabs();return}else if(y){this._fullRenderSessionTabs();return}const v=a.querySelector(".tab-subagent-badge"),T=this.minimizedSubagents.get(o)?.size||0,C=v?parseInt(v.querySelector(".subagent-count")?.textContent||"0"):0;if(T!==C){this._fullRenderSessionTabs();return}}else this._fullRenderSessionTabs()}_fullRenderSessionTabs(){const e=this.$("sessionTabs");document.querySelectorAll("body > .subagent-dropdown").forEach(n=>n.remove()),this.cancelHideSubagentDropdown();const t=[];let s=this.sessionOrder;MobileDetection.getDeviceType()==="mobile"&&this.activeSessionId&&(s=[this.activeSessionId,...this.sessionOrder.filter(n=>n!==this.activeSessionId)]);for(const n of s){const i=this.sessions.get(n);if(!i)continue;const o=n===this.activeSessionId,l=i.status||"idle",a=this.getSessionName(i),r=i.mode||"claude",c=i.color||"default",d=i.taskStats||{running:0,total:0},u=d.running>0,h=this.tabAlerts.get(n),m=h==="action"?" tab-alert-action":h==="idle"?" tab-alert-idle":"",p=this.minimizedSubagents.get(n),f=(p?.size||0)>0?this.renderSubagentTabBadge(n,p):"",S=i.workingDir&&i.workingDir.split("/").pop()||"",b=(this._tallTabsEnabled??!1)&&i.name&&S&&S!==a;t.push(`<div class="session-tab ${o?"active":""}${m}" data-id="${n}" data-color="${c}" onclick="app.selectSession('${escapeHtml(n)}')" oncontextmenu="event.preventDefault(); app.startInlineRename('${escapeHtml(n)}')" tabindex="0" role="tab" aria-selected="${o?"true":"false"}" aria-label="${escapeHtml(a)} session" ${i.workingDir?`title="${escapeHtml(i.workingDir)}"`:""}>
2
2
  <span class="tab-status ${l}" aria-hidden="true"></span>
3
3
  <span class="tab-info">
4
4
  <span class="tab-name-row">
@@ -11,9 +11,9 @@
11
11
  ${f}
12
12
  <span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions('${escapeHtml(n)}')" title="Session options" aria-label="Session options" tabindex="0">&#x2699;</span>
13
13
  <span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession('${escapeHtml(n)}')" title="Close session" aria-label="Close session" tabindex="0">&times;</span>
14
- </div>`)}e.innerHTML=t.join(""),this.setupTabDragHandlers(),this.setupTabKeyboardNavigation(e),this.updateConnectionLines()}setupTabKeyboardNavigation(e){this._tabKeydownHandler&&e.removeEventListener("keydown",this._tabKeydownHandler),this._tabKeydownHandler=t=>{if(!["ArrowLeft","ArrowRight","Home","End","Enter"," "].includes(t.key))return;const s=[...e.querySelectorAll(".session-tab")],n=s.indexOf(document.activeElement);if((t.key==="Enter"||t.key===" ")&&n>=0){t.preventDefault();const o=s[n].dataset.id;this.selectSession(o);return}if(n<0)return;let i;switch(t.key){case"ArrowLeft":i=n>0?n-1:s.length-1;break;case"ArrowRight":i=n<s.length-1?n+1:0;break;case"Home":i=0;break;case"End":i=s.length-1;break;default:return}t.preventDefault(),s[i]?.focus()},e.addEventListener("keydown",this._tabKeydownHandler)}syncSessionOrder(){const e=new Set(this.sessions.keys()),s=this.loadSessionOrder().filter(o=>e.has(o)),n=new Set(s),i=[...e].filter(o=>!n.has(o));this.sessionOrder=[...s,...i]}loadSessionOrder(){try{const e=localStorage.getItem("codeman-session-order");return e?JSON.parse(e):[]}catch{return[]}}saveSessionOrder(){try{localStorage.setItem("codeman-session-order",JSON.stringify(this.sessionOrder))}catch{}}setupTabDragHandlers(){const e=this.$("sessionTabs");e.querySelectorAll(".session-tab[data-id]").forEach(s=>{s.setAttribute("draggable","true"),s.addEventListener("dragstart",n=>{this.draggedTabId=s.dataset.id,s.classList.add("dragging"),n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",s.dataset.id)}),s.addEventListener("dragend",()=>{s.classList.remove("dragging"),this.draggedTabId=null,e.querySelectorAll(".session-tab").forEach(n=>{n.classList.remove("drag-over-left","drag-over-right")})}),s.addEventListener("dragover",n=>{if(n.preventDefault(),!this.draggedTabId||this.draggedTabId===s.dataset.id)return;n.dataTransfer.dropEffect="move";const i=s.getBoundingClientRect(),o=i.left+i.width/2,l=n.clientX<o;s.classList.toggle("drag-over-left",l),s.classList.toggle("drag-over-right",!l)}),s.addEventListener("dragleave",()=>{s.classList.remove("drag-over-left","drag-over-right")}),s.addEventListener("drop",n=>{if(n.preventDefault(),s.classList.remove("drag-over-left","drag-over-right"),!this.draggedTabId||this.draggedTabId===s.dataset.id)return;const i=s.dataset.id,o=this.draggedTabId,l=s.getBoundingClientRect(),a=l.left+l.width/2,r=n.clientX<a,c=this.sessionOrder.indexOf(o);let d=this.sessionOrder.indexOf(i);c===-1||d===-1||(this.sessionOrder.splice(c,1),d=this.sessionOrder.indexOf(i),d!==-1&&(r?this.sessionOrder.splice(d,0,o):this.sessionOrder.splice(d+1,0,o),this.saveSessionOrder(),this._fullRenderSessionTabs()))})})}getShortId(e){if(!e)return"";let t=this._shortIdCache.get(e);return t||(t=e.slice(0,8),this._shortIdCache.set(e,t)),t}getSessionName(e){return e.name?e.name:e.workingDir?e.workingDir.split("/").pop()||e.workingDir:this.getShortId(e.id)}async selectSession(e){if(this.activeSessionId===e)return;const t=++this._selectGeneration;if(t!==this._selectGeneration)return;this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this._tabCompletionSessionId=null,this._tabCompletionRetries=0,this._tabCompletionBaseText=null,this._tabCompletionFallback&&(clearTimeout(this._tabCompletionFallback),this._tabCompletionFallback=null),this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.pendingWrites=[],this.writeFrameScheduled=!1,this._isLoadingBuffer=!1,this._loadBufferQueue=null;try{const i=this.terminal?._core?._compositionHelper;if(i?._isComposing){i._isComposing=!1;const o=this.terminal?.element?.querySelector(".xterm-helper-textarea");o&&o.dispatchEvent(new CompositionEvent("compositionend",{data:""}))}}catch{}if(this.activeSessionId){const i=this._localEchoOverlay?.pendingText||"",o=this._localEchoOverlay?.getFlushed()?.count||0,l=this._localEchoOverlay?.getFlushed()?.text||"";i&&this._sendInputAsync(this.activeSessionId,i);const a=o+i.length;a>0&&(this._flushedOffsets||(this._flushedOffsets=new Map),this._flushedTexts||(this._flushedTexts=new Map),this._flushedOffsets.set(this.activeSessionId,a),this._flushedTexts.set(this.activeSessionId,l+i))}this._localEchoOverlay?.clear(),this._localEchoOverlay&&!this._flushedOffsets?.has(e)&&this._localEchoOverlay.suppressBufferDetection(),this.activeSessionId=e;try{localStorage.setItem("codeman-active-session",e)}catch{}this.hideWelcome(),this.clearPendingHooks(e,"idle_prompt"),this._updateActiveTabImmediate(e),this.renderSessionTabs(),this._updateLocalEchoState(),this._flushedOffsets?.has(e)&&this._localEchoOverlay&&this._localEchoOverlay.setFlushed(this._flushedOffsets.get(e),this._flushedTexts?.get(e)||"",!1);const s=document.querySelector(`.session-tab.active[data-id="${e}"]`);s&&(s.classList.add("tab-glow"),s.addEventListener("animationend",()=>s.classList.remove("tab-glow"),{once:!0}));const n=this.sessions.get(e);if(this.currentSessionWorkingDir=n?.workingDir||null,n&&n.pid===null&&n.status==="idle")try{await fetch(`/api/sessions/${e}/interactive`,{method:"POST"}),n.status="busy"}catch{}this._restoringFlushedState=!0;try{const i=this.terminalBufferCache.get(e);i&&(this.terminal.clear(),this.terminal.reset(),this.terminal.write(i),this.terminal.scrollToBottom());const o=256*1024,l=await fetch(`/api/sessions/${e}/terminal?tail=${o}`);if(t!==this._selectGeneration){this._restoringFlushedState=!1;return}const a=await l.json();if(a.terminalBuffer){if(a.terminalBuffer!==i){if(this.terminal.clear(),this.terminal.reset(),a.truncated&&this.terminal.write(`\x1B[90m... (earlier output truncated for performance) ...\x1B[0m\r
14
+ </div>`)}e.innerHTML=t.join(""),this.setupTabDragHandlers(),this.setupTabKeyboardNavigation(e),this.updateConnectionLines()}setupTabKeyboardNavigation(e){this._tabKeydownHandler&&e.removeEventListener("keydown",this._tabKeydownHandler),this._tabKeydownHandler=t=>{if(!["ArrowLeft","ArrowRight","Home","End","Enter"," "].includes(t.key))return;const s=[...e.querySelectorAll(".session-tab")],n=s.indexOf(document.activeElement);if((t.key==="Enter"||t.key===" ")&&n>=0){t.preventDefault();const o=s[n].dataset.id;this.selectSession(o);return}if(n<0)return;let i;switch(t.key){case"ArrowLeft":i=n>0?n-1:s.length-1;break;case"ArrowRight":i=n<s.length-1?n+1:0;break;case"Home":i=0;break;case"End":i=s.length-1;break;default:return}t.preventDefault(),s[i]?.focus()},e.addEventListener("keydown",this._tabKeydownHandler)}syncSessionOrder(){const e=new Set(this.sessions.keys()),s=this.loadSessionOrder().filter(o=>e.has(o)),n=new Set(s),i=[...e].filter(o=>!n.has(o));this.sessionOrder=[...s,...i]}loadSessionOrder(){try{const e=localStorage.getItem("codeman-session-order");return e?JSON.parse(e):[]}catch{return[]}}saveSessionOrder(){try{localStorage.setItem("codeman-session-order",JSON.stringify(this.sessionOrder))}catch{}}setupTabDragHandlers(){const e=this.$("sessionTabs");e.querySelectorAll(".session-tab[data-id]").forEach(s=>{s.setAttribute("draggable","true"),s.addEventListener("dragstart",n=>{this.draggedTabId=s.dataset.id,s.classList.add("dragging"),n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",s.dataset.id)}),s.addEventListener("dragend",()=>{s.classList.remove("dragging"),this.draggedTabId=null,e.querySelectorAll(".session-tab").forEach(n=>{n.classList.remove("drag-over-left","drag-over-right")})}),s.addEventListener("dragover",n=>{if(n.preventDefault(),!this.draggedTabId||this.draggedTabId===s.dataset.id)return;n.dataTransfer.dropEffect="move";const i=s.getBoundingClientRect(),o=i.left+i.width/2,l=n.clientX<o;s.classList.toggle("drag-over-left",l),s.classList.toggle("drag-over-right",!l)}),s.addEventListener("dragleave",()=>{s.classList.remove("drag-over-left","drag-over-right")}),s.addEventListener("drop",n=>{if(n.preventDefault(),s.classList.remove("drag-over-left","drag-over-right"),!this.draggedTabId||this.draggedTabId===s.dataset.id)return;const i=s.dataset.id,o=this.draggedTabId,l=s.getBoundingClientRect(),a=l.left+l.width/2,r=n.clientX<a,c=this.sessionOrder.indexOf(o);let d=this.sessionOrder.indexOf(i);c===-1||d===-1||(this.sessionOrder.splice(c,1),d=this.sessionOrder.indexOf(i),d!==-1&&(r?this.sessionOrder.splice(d,0,o):this.sessionOrder.splice(d+1,0,o),this.saveSessionOrder(),this._fullRenderSessionTabs()))})})}getShortId(e){if(!e)return"";let t=this._shortIdCache.get(e);return t||(t=e.slice(0,8),this._shortIdCache.set(e,t)),t}getSessionName(e){return e.name?e.name:e.workingDir?e.workingDir.split("/").pop()||e.workingDir:this.getShortId(e.id)}async selectSession(e){if(this.activeSessionId===e)return;const t=++this._selectGeneration;if(t!==this._selectGeneration)return;this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this._tabCompletionSessionId=null,this._tabCompletionRetries=0,this._tabCompletionBaseText=null,this._tabCompletionFallback&&(clearTimeout(this._tabCompletionFallback),this._tabCompletionFallback=null),this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.pendingWrites=[],this.writeFrameScheduled=!1,this._isLoadingBuffer=!1,this._loadBufferQueue=null;try{const i=this.terminal?._core?._compositionHelper;if(i?._isComposing){i._isComposing=!1;const o=this.terminal?.element?.querySelector(".xterm-helper-textarea");o&&o.dispatchEvent(new CompositionEvent("compositionend",{data:""}))}}catch{}if(this.activeSessionId){const i=this._localEchoOverlay?.pendingText||"",o=this._localEchoOverlay?.getFlushed()?.count||0,l=this._localEchoOverlay?.getFlushed()?.text||"";i&&this._sendInputAsync(this.activeSessionId,i);const a=o+i.length;a>0&&(this._flushedOffsets||(this._flushedOffsets=new Map),this._flushedTexts||(this._flushedTexts=new Map),this._flushedOffsets.set(this.activeSessionId,a),this._flushedTexts.set(this.activeSessionId,l+i))}this._localEchoOverlay?.clear(),this._localEchoOverlay&&!this._flushedOffsets?.has(e)&&this._localEchoOverlay.suppressBufferDetection(),this.activeSessionId=e;try{localStorage.setItem("codeman-active-session",e)}catch{}this.hideWelcome(),this.clearPendingHooks(e,"idle_prompt"),this._updateActiveTabImmediate(e),this.renderSessionTabs(),this._updateLocalEchoState(),this._flushedOffsets?.has(e)&&this._localEchoOverlay&&this._localEchoOverlay.setFlushed(this._flushedOffsets.get(e),this._flushedTexts?.get(e)||"",!1);const s=document.querySelector(`.session-tab.active[data-id="${e}"]`);s&&(s.classList.add("tab-glow"),s.addEventListener("animationend",()=>s.classList.remove("tab-glow"),{once:!0}));const n=this.sessions.get(e);if(this.currentSessionWorkingDir=n?.workingDir||null,n&&n.pid===null&&n.status==="idle")try{await fetch(`/api/sessions/${e}/interactive`,{method:"POST"}),n.status="busy"}catch{}this._restoringFlushedState=!0;try{const i=this.terminalBufferCache.get(e);if(i){if(this.terminal.clear(),this.terminal.reset(),await this.chunkedTerminalWrite(i),t!==this._selectGeneration){this._restoringFlushedState=!1;return}this.terminal.scrollToBottom()}const o=256*1024,l=await fetch(`/api/sessions/${e}/terminal?tail=${o}`);if(t!==this._selectGeneration){this._restoringFlushedState=!1;return}const a=await l.json();if(a.terminalBuffer){if(a.terminalBuffer!==i){if(this.terminal.clear(),this.terminal.reset(),a.truncated&&this.terminal.write(`\x1B[90m... (earlier output truncated for performance) ...\x1B[0m\r
15
15
  \r
16
- `),await this.chunkedTerminalWrite(a.terminalBuffer),t!==this._selectGeneration){this._restoringFlushedState=!1;return}this.terminal.scrollToBottom()}if(this.terminalBufferCache.set(e,a.terminalBuffer),this.terminalBufferCache.size>20){const d=this.terminalBufferCache.keys().next().value;this.terminalBufferCache.delete(d)}}else i||(this.terminal.clear(),this.terminal.reset());if(this._restoringFlushedState=!1,this._flushedOffsets?.has(e)&&this._localEchoOverlay){this._localEchoOverlay.setFlushed(this._flushedOffsets.get(e),this._flushedTexts?.get(e)||"",!1);const c=this._localEchoOverlay;this.terminal.write("",()=>{c.hasPending&&c.rerender()})}this.sendResize(e),(typeof requestIdleCallback=="function"?requestIdleCallback:c=>setTimeout(c,16))(()=>{if(t!==this._selectGeneration)return;this.respawnStatus[e]?(this.showRespawnBanner(),this.updateRespawnBanner(this.respawnStatus[e].state),document.getElementById("respawnCycleCount").textContent=this.respawnStatus[e].cycleCount||0,this.updateCountdownTimerDisplay(),this.updateActionLogDisplay(),Object.keys(this.respawnCountdownTimers[e]||{}).length>0&&this.startCountdownInterval()):(this.hideRespawnBanner(),this.stopCountdownInterval());const c=document.getElementById("taskPanel");c&&c.classList.contains("open")&&this.renderTaskPanel();const d=this.sessions.get(e);if(d&&(d.ralphLoop||d.ralphTodos)&&this.updateRalphState(e,{loop:d.ralphLoop,todos:d.ralphTodos}),this.renderRalphStatePanel(),this.updateCliInfoDisplay(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this.loadAppSettingsFromStorage().showFileBrowser){const h=this.$("fileBrowserPanel");h&&(h.classList.add("visible"),this.loadFileBrowser(e))}}),this.terminal.focus(),this.terminal.scrollToBottom()}catch{this._restoringFlushedState=!1}}_cleanupSessionData(e){this.sessions.delete(e);const t=this.sessionOrder.indexOf(e);t!==-1&&(this.sessionOrder.splice(t,1),this.saveSessionOrder()),this.terminalBuffers.delete(e),this.terminalBufferCache.delete(e),this._flushedOffsets?.delete(e),this._flushedTexts?.delete(e),this._inputQueue.delete(e),this.ralphStates.delete(e),this.ralphClosedSessions.delete(e),this.projectInsights.delete(e),this.pendingHooks.delete(e),this.tabAlerts.delete(e),this.clearCountdownTimers(e),this.closeSessionLogViewerWindows(e),this.closeSessionImagePopups(e),this.closeSessionSubagentWindows(e,!0);const s=this.idleTimers.get(e);s&&(clearTimeout(s),this.idleTimers.delete(e)),delete this.respawnStatus[e],delete this.respawnTimers[e],delete this.respawnCountdownTimers[e],delete this.respawnActionLogs[e]}async closeSession(e,t=!0){try{if(await this._apiDelete(`/api/sessions/${e}?killMux=${t}`),this._cleanupSessionData(e),this.activeSessionId===e){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}if(this.sessionOrder.length>0&&this.sessions.size>0){const s=this.sessionOrder[0];this.selectSession(s)}else this.terminal.clear(),this.showWelcome(),this.renderRalphStatePanel()}this.renderSessionTabs(),t?this.showToast("Session closed and tmux killed","success"):this.showToast("Tab hidden, tmux still running","info")}catch{this.showToast("Failed to close session","error")}}requestCloseSession(e){const t=this.sessions.get(e);if(!t)return;this.pendingCloseSessionId=e;const s=this.getSessionName(t),n=document.getElementById("closeConfirmSessionName");n.textContent=s;const i=document.getElementById("closeConfirmKillTitle");i&&(i.textContent=t.mode==="opencode"?"Kill Tmux & OpenCode":"Kill Tmux & Claude Code"),document.getElementById("closeConfirmModal").classList.add("active")}cancelCloseSession(){this.pendingCloseSessionId=null,document.getElementById("closeConfirmModal").classList.remove("active")}async confirmCloseSession(e=!0){const t=this.pendingCloseSessionId;this.cancelCloseSession(),t&&await this.closeSession(t,e)}nextSession(){if(this.sessionOrder.length<=1)return;const t=(this.sessionOrder.indexOf(this.activeSessionId)+1)%this.sessionOrder.length;this.selectSession(this.sessionOrder[t])}prevSession(){if(this.sessionOrder.length<=1)return;const t=(this.sessionOrder.indexOf(this.activeSessionId)-1+this.sessionOrder.length)%this.sessionOrder.length;this.selectSession(this.sessionOrder[t])}goHome(){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome(),this.renderSessionTabs(),this.renderRalphStatePanel()}ralphWizardStep=1;ralphWizardConfig={taskDescription:"",completionPhrase:"COMPLETE",maxIterations:10,caseName:"testcase",enableRespawn:!1,generatedPlan:null,planGenerated:!1,skipPlanGeneration:!1,planDetailLevel:"detailed",existingPlan:null,useExistingPlan:!1};planLoadingTimer=null;planLoadingStartTime=null;async loadQuickStartCases(e=null,t=null){try{let s=null;try{const d=t?await t:await fetch("/api/settings").then(u=>u.ok?u.json():null);d&&(s=d.lastUsedCase||null)}catch{}const i=await(await fetch("/api/cases")).json();this.cases=i;const o=document.getElementById("quickStartCase");let l="";const a=i.some(d=>d.name==="testcase"),c=MobileDetection.getDeviceType()==="mobile"?8:20;if(i.forEach(d=>{const u=d.name.length>c?d.name.substring(0,c)+"\u2026":d.name;l+=`<option value="${escapeHtml(d.name)}">${escapeHtml(u)}</option>`}),a||(l='<option value="testcase">testcase</option>'+l),o.innerHTML=l,e)o.value=e,this.updateDirDisplayForCase(e),this.updateMobileCaseLabel(e);else if(s&&i.some(d=>d.name===s))o.value=s,this.updateDirDisplayForCase(s),this.updateMobileCaseLabel(s);else if(i.length>0){const d=i.find(u=>u.name==="testcase")||i[0];o.value=d.name,this.updateDirDisplayForCase(d.name),this.updateMobileCaseLabel(d.name)}else o.value="testcase",document.getElementById("dirDisplay").textContent="~/codeman-cases/testcase",this.updateMobileCaseLabel("testcase");o.dataset.listenerAdded||(o.addEventListener("change",()=>{this.updateDirDisplayForCase(o.value),this.saveLastUsedCase(o.value),this.updateMobileCaseLabel(o.value)}),o.dataset.listenerAdded="true")}catch{}}async updateDirDisplayForCase(e){try{const s=await(await fetch(`/api/cases/${e}`)).json();s.path&&(document.getElementById("dirDisplay").textContent=s.path,document.getElementById("dirInput").value=s.path)}catch{document.getElementById("dirDisplay").textContent=e}}async saveLastUsedCase(e){try{const t=await fetch("/api/settings"),s=t.ok?await t.json():{};s.lastUsedCase=e,await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})}catch{}}async quickStart(){return this.run()}async run(){return(this._runMode||"claude")==="opencode"?this.runOpenCode():this.runClaude()}get runMode(){return this._runMode||"claude"}setRunMode(e){this._runMode=e;try{localStorage.setItem("codeman_runMode",e)}catch{}this._applyRunMode(),document.getElementById("runModeMenu")?.classList.remove("active")}toggleRunModeMenu(e){e?.stopPropagation();const t=document.getElementById("runModeMenu");if(t&&(t.classList.toggle("active"),t.querySelectorAll(".run-mode-option").forEach(s=>{s.classList.toggle("selected",s.dataset.mode===this.runMode)}),t.classList.contains("active"))){const s=n=>{t.contains(n.target)||(t.classList.remove("active"),document.removeEventListener("click",s))};setTimeout(()=>document.addEventListener("click",s),0)}}_applyRunMode(){const e=this.runMode,t=document.getElementById("runBtn"),s=t?.nextElementSibling,n=document.getElementById("runBtnLabel");t&&(t.className=`btn-toolbar btn-run mode-${e}`),s&&(s.className=`btn-toolbar btn-run-gear mode-${e}`),n&&(n.textContent=e==="opencode"?"Run OC":"Run")}_initRunMode(){try{this._runMode=localStorage.getItem("codeman_runMode")||"claude"}catch{this._runMode="claude"}this._applyRunMode()}incrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)}decrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)}incrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)}decrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)}async runClaude(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("tabCount").value)||1));this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting ${t} Claude session(s) in ${e}...\x1B[0m`),this.terminal.writeln("");try{let n=await(await fetch(`/api/cases/${e}`)).json();if(!n.path){const S=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!S.success)throw new Error(S.error||"Failed to create case");n=S.case}const i=n.path;if(!i)throw new Error("Case path not found");let o=null,l=1;for(const[,f]of this.sessions){const S=f.name&&f.name.match(/^w(\d+)-(.+)$/);if(S&&S[2]===e){const w=parseInt(S[1]);w>=l&&(l=w+1)}}const a=this.isRalphTrackerEnabledByDefault(),r=[];for(let f=0;f<t;f++)r.push(`w${l+f}-${e}`);const c=this.getCaseSettings(e),d=this.loadAppSettingsFromStorage(),u={};(c.agentTeams||d.agentTeamsEnabled)&&(u.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS="1");const h=Object.keys(u).length>0;this.terminal.writeln(`\x1B[90m Creating ${t} session(s)...\x1B[0m`);const m=r.map(f=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,name:f,...h?{envOverrides:u}:{}})}).then(S=>S.json())),p=await Promise.all(m),g=[];for(const f of p){if(!f.success)throw new Error(f.error);g.push(f.session.id)}o=g[0],await Promise.all(g.map(f=>fetch(`/api/sessions/${f}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:a,disableAutoEnable:!a})}))),this.terminal.writeln(`\x1B[90m Starting ${t} session(s) in parallel...\x1B[0m`),await Promise.all(g.map(f=>fetch(`/api/sessions/${f}/interactive`,{method:"POST"}))),this.terminal.writeln(`\x1B[90m All ${t} sessions ready\x1B[0m`),o&&(await this.selectSession(o),this.loadQuickStartCases()),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}}stopClaude(){if(!this.activeSessionId)return;const e=document.querySelector(".btn-toolbar.btn-stop");e&&(this._stopConfirmTimer?(clearTimeout(this._stopConfirmTimer),this._stopConfirmTimer=null,e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml,e.classList.remove("confirming"),fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:""})})):(e.dataset.origHtml=e.innerHTML,e.textContent="Tap again",e.classList.add("confirming"),this._stopConfirmTimer=setTimeout(()=>{this._stopConfirmTimer=null,e.dataset.origHtml&&(e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml),e.classList.remove("confirming")},2e3)))}async runShell(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("shellCount").value)||1));this.terminal.clear(),this.terminal.writeln(`\x1B[1;33m Starting ${t} Shell session(s) in ${e}...\x1B[0m`),this.terminal.writeln("");try{const i=(await(await fetch(`/api/cases/${e}`)).json()).path;if(!i)throw new Error("Case path not found");let o=1;for(const[,u]of this.sessions){const h=u.name&&u.name.match(/^s(\d+)-(.+)$/);if(h&&h[2]===e){const m=parseInt(h[1]);m>=o&&(o=m+1)}}const l=[];for(let u=0;u<t;u++)l.push(`s${o+u}-${e}`);const a=l.map(u=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,mode:"shell",name:u})}).then(h=>h.json())),r=await Promise.all(a),c=[];for(const u of r){if(!u.success)throw new Error(u.error);c.push(u.session.id)}await Promise.all(c.map(u=>fetch(`/api/sessions/${u}/shell`,{method:"POST"})));const d=this.getTerminalDimensions();d&&await Promise.all(c.map(u=>fetch(`/api/sessions/${u}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}))),c.length>0&&(this.activeSessionId=c[0],await this.selectSession(c[0])),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}}async runOpenCode(){const e=document.getElementById("quickStartCase").value||"testcase";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting OpenCode session in ${e}...\x1B[0m`),this.terminal.writeln("");try{if(!(await(await fetch("/api/opencode/status")).json()).available){this.terminal.writeln("\x1B[1;31m OpenCode CLI not found.\x1B[0m"),this.terminal.writeln("\x1B[90m Install with: curl -fsSL https://opencode.ai/install | bash\x1B[0m");return}const i=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"opencode",openCodeConfig:{autoAllowTools:!0}})})).json();if(!i.success)throw new Error(i.error||"Failed to start OpenCode");i.sessionId&&await this.selectSession(i.sessionId),this.terminal.focus()}catch(t){this.terminal.writeln(`\x1B[1;31m Error: ${t.message}\x1B[0m`)}}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)}showRespawnBanner(){this.$("respawnBanner").style.display="flex",this.activeSessionId&&this.respawnTimers[this.activeSessionId]&&this.showRespawnTimer();const e=this.sessions.get(this.activeSessionId);e&&e.tokens&&this.updateRespawnTokens(e.tokens)}hideRespawnBanner(){this.$("respawnBanner").style.display="none",this.hideRespawnTimer()}getStateLabel(e){return{stopped:"Stopped",watching:"Watching",confirming_idle:"Confirming idle",ai_checking:"AI checking",sending_update:"Sending prompt",waiting_update:"Running prompt",sending_clear:"Clearing context",waiting_clear:"Clearing...",sending_init:"Initializing",waiting_init:"Initializing...",monitoring_init:"Waiting for work",sending_kickstart:"Kickstarting",waiting_kickstart:"Kickstarting..."}[e]||e.replace(/_/g," ")}updateRespawnBanner(e){const t=this.$("respawnState");t.textContent=this.getStateLabel(e),t.classList.remove("respawn-blocked")}updateDetectionDisplay(e){if(!e)return;const t=this.$("detectionStatus"),s=this.$("detectionWaiting"),n=this.$("detectionConfidence"),i=document.getElementById("detectionAiCheck"),o=document.getElementById("detectionHook");if(o)if(e.stopHookReceived||e.idlePromptReceived){const r=e.idlePromptReceived?"idle":"stop";o.textContent=`\u{1F3AF} ${r} hook`,o.className="detection-hook hook-active",o.style.display=""}else o.style.display="none";e.statusText&&e.statusText!=="Watching..."?(t.textContent=e.statusText,t.style.display=""):t.style.display="none",s.style.display="none";const l=e.confidenceLevel||0;if(l>0?(n.textContent=`${l}%`,n.style.display="",n.className="detection-confidence",e.stopHookReceived||e.idlePromptReceived?n.classList.add("hook-confirmed"):l>=60?n.classList.add("high"):l>=30&&n.classList.add("medium")):n.style.display="none",i&&e.aiCheck){const r=e.aiCheck;let c="",d="detection-ai-check";if(r.status==="checking")c="\u{1F50D} AI checking...",d+=" ai-checking";else if(r.status==="cooldown"&&r.cooldownEndsAt){const u=Math.ceil((r.cooldownEndsAt-Date.now())/1e3);u>0&&(r.lastVerdict==="WORKING"?(c=`\u23F3 Working, retry ${u}s`,d+=" ai-working"):(c=`\u2713 Idle, wait ${u}s`,d+=" ai-idle"))}else if(r.status==="disabled")c="\u26A0 AI disabled",d+=" ai-disabled";else if(r.lastVerdict&&r.lastCheckTime){const u=Math.round((Date.now()-r.lastCheckTime)/1e3);u<120&&(c=r.lastVerdict==="IDLE"?`\u2713 Idle (${u}s)`:`\u23F3 Working (${u}s)`,d+=r.lastVerdict==="IDLE"?" ai-idle":" ai-working")}i.textContent=c,i.className=d,i.style.display=c?"":"none"}else i&&(i.style.display="none");const a=this.$("respawnStatusRow2");if(a){const r=o&&o.style.display!=="none"||i&&i.style.display!=="none"||t&&t.style.display!=="none"||this.respawnCountdownTimers[this.activeSessionId]&&Object.keys(this.respawnCountdownTimers[this.activeSessionId]).length>0;a.style.display=r?"":"none"}}showRespawnTimer(){const e=this.$("respawnTimer");e.style.display="",this.updateRespawnTimer(),this.respawnTimerInterval&&clearInterval(this.respawnTimerInterval),this.respawnTimerInterval=setInterval(()=>this.updateRespawnTimer(),1e3)}hideRespawnTimer(){this.$("respawnTimer").style.display="none",this.respawnTimerInterval&&(clearInterval(this.respawnTimerInterval),this.respawnTimerInterval=null)}updateRespawnTimer(){if(!this.activeSessionId||!this.respawnTimers[this.activeSessionId]){this.hideRespawnTimer();return}const e=this.respawnTimers[this.activeSessionId];if(!e.endAt||isNaN(e.endAt)){this.hideRespawnTimer();return}const t=Date.now(),s=Math.max(0,e.endAt-t);if(s<=0){this.$("respawnTimer").textContent="Time up",delete this.respawnTimers[this.activeSessionId],this.hideRespawnTimer();return}this.$("respawnTimer").textContent=this.formatTime(s)}updateRespawnTokens(e){const t=e&&typeof e=="object",s=t?e.total:e;if(s===this._lastRespawnTokenTotal)return;this._lastRespawnTokenTotal=s;const n=this.$("respawnTokens"),i=t?e.input||0:Math.round(s*.6),o=t?e.output||0:Math.round(s*.4);if(s>0){n.style.display="";const l=this.formatTokens(s);if(this.loadAppSettingsFromStorage().showCost??!1){const c=this.estimateCost(i,o);n.textContent=`${l} tokens \xB7 $${c.toFixed(2)}`}else n.textContent=`${l} tokens`}else n.style.display="none";this.updateCliInfoDisplay()}updateCliInfoDisplay(){const e=this.$("cliInfoBar");if(!e)return;const t=this.sessions.get(this.activeSessionId);if(!t){e.style.display="none";return}let s=[];if(t.tokens){const n=typeof t.tokens=="object"?t.tokens.total:t.tokens;n>0&&s.push(`${this.formatTokens(n)} tokens`)}if(t.cliModel){let n=t.cliModel;n.includes("opus")?n="Opus":n.includes("sonnet")?n="Sonnet":n.includes("haiku")&&(n="Haiku"),s.push(n)}if(t.cliVersion){let n=`v${t.cliVersion}`;t.cliLatestVersion&&t.cliLatestVersion!==t.cliVersion&&(n+=" \u2191"),s.push(n)}s.length>0?(e.textContent=s.join(" \xB7 "),e.style.display=""):e.style.display="none"}addActionLogEntry(e,t){if(!["command","hook"].includes(t.type)){if(t.type==="ai-check"){if(t.detail.includes("Spawning"))return}else if(t.type==="plan-check"){if(t.detail.includes("Spawning"))return}else if(t.type!=="transcript")return}this.respawnActionLogs[e]||(this.respawnActionLogs[e]=[]),this.respawnActionLogs[e].unshift(t),this.respawnActionLogs[e].length>30&&this.respawnActionLogs[e].pop()}startCountdownInterval(){this.timerCountdownInterval||(this.timerCountdownInterval=setInterval(()=>{this.activeSessionId&&this.respawnCountdownTimers[this.activeSessionId]&&this.updateCountdownTimerDisplay()},100))}stopCountdownInterval(){this.timerCountdownInterval&&(clearInterval(this.timerCountdownInterval),this.timerCountdownInterval=null)}updateCountdownTimerDisplay(){const e=this.$("respawnCountdownTimers"),t=this.$("respawnStatusRow2");if(!e)return;const s=this.respawnCountdownTimers[this.activeSessionId];if(!(s&&Object.keys(s).length>0)){if(e.innerHTML="",t){const l=document.getElementById("detectionHook"),a=document.getElementById("detectionAiCheck"),r=this.$("detectionStatus"),c=l&&l.style.display!=="none"||a&&a.style.display!=="none"||r&&r.style.display!=="none";t.style.display=c?"":"none"}return}t&&(t.style.display="");const i=Date.now();let o="";for(const[l,a]of Object.entries(s)){const r=Math.max(0,a.endsAt-i),c=(r/1e3).toFixed(1),d=Math.max(0,Math.min(100,r/a.totalMs*100)),u=l.replace(/-/g," ").replace(/^\w/,h=>h.toUpperCase());o+=`<div class="respawn-countdown-timer" title="${escapeHtml(a.reason||"")}">
16
+ `),await this.chunkedTerminalWrite(a.terminalBuffer),t!==this._selectGeneration){this._restoringFlushedState=!1;return}this.terminal.scrollToBottom()}if(this.terminalBufferCache.set(e,a.terminalBuffer),this.terminalBufferCache.size>20){const d=this.terminalBufferCache.keys().next().value;this.terminalBufferCache.delete(d)}}else i||(this.terminal.clear(),this.terminal.reset());if(this._restoringFlushedState=!1,this._flushedOffsets?.has(e)&&this._localEchoOverlay){this._localEchoOverlay.setFlushed(this._flushedOffsets.get(e),this._flushedTexts?.get(e)||"",!1);const c=this._localEchoOverlay;this.terminal.write("",()=>{c.hasPending&&c.rerender()})}this.sendResize(e),(typeof requestIdleCallback=="function"?requestIdleCallback:c=>setTimeout(c,16))(()=>{if(t!==this._selectGeneration)return;this.respawnStatus[e]?(this.showRespawnBanner(),this.updateRespawnBanner(this.respawnStatus[e].state),document.getElementById("respawnCycleCount").textContent=this.respawnStatus[e].cycleCount||0,this.updateCountdownTimerDisplay(),this.updateActionLogDisplay(),Object.keys(this.respawnCountdownTimers[e]||{}).length>0&&this.startCountdownInterval()):(this.hideRespawnBanner(),this.stopCountdownInterval());const c=document.getElementById("taskPanel");c&&c.classList.contains("open")&&this.renderTaskPanel();const d=this.sessions.get(e);if(d&&(d.ralphLoop||d.ralphTodos)&&this.updateRalphState(e,{loop:d.ralphLoop,todos:d.ralphTodos}),this.renderRalphStatePanel(),this.updateCliInfoDisplay(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this.loadAppSettingsFromStorage().showFileBrowser){const h=this.$("fileBrowserPanel");if(h&&(h.classList.add("visible"),this.loadFileBrowser(e),!this.fileBrowserDragListeners)){const m=h.querySelector(".file-browser-header");if(m){const p=()=>{if(!h.style.left){const g=h.getBoundingClientRect();h.style.left=`${g.left}px`,h.style.top=`${g.top}px`,h.style.right="auto"}};m.addEventListener("mousedown",p),m.addEventListener("touchstart",p,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(h,m),this.fileBrowserDragListeners._onFirstDrag=p}}}}),this.terminal.focus(),this.terminal.scrollToBottom()}catch{this._restoringFlushedState=!1}}_cleanupSessionData(e){this.sessions.delete(e);const t=this.sessionOrder.indexOf(e);t!==-1&&(this.sessionOrder.splice(t,1),this.saveSessionOrder()),this.terminalBuffers.delete(e),this.terminalBufferCache.delete(e),this._flushedOffsets?.delete(e),this._flushedTexts?.delete(e),this._inputQueue.delete(e),this.ralphStates.delete(e),this.ralphClosedSessions.delete(e),this.projectInsights.delete(e),this.pendingHooks.delete(e),this.tabAlerts.delete(e),this.clearCountdownTimers(e),this.closeSessionLogViewerWindows(e),this.closeSessionImagePopups(e),this.closeSessionSubagentWindows(e,!0);const s=this.idleTimers.get(e);s&&(clearTimeout(s),this.idleTimers.delete(e)),delete this.respawnStatus[e],delete this.respawnTimers[e],delete this.respawnCountdownTimers[e],delete this.respawnActionLogs[e]}async closeSession(e,t=!0){try{if(await this._apiDelete(`/api/sessions/${e}?killMux=${t}`),this._cleanupSessionData(e),this.activeSessionId===e){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}if(this.sessionOrder.length>0&&this.sessions.size>0){const s=this.sessionOrder[0];this.selectSession(s)}else this.terminal.clear(),this.showWelcome(),this.renderRalphStatePanel()}this.renderSessionTabs(),t?this.showToast("Session closed and tmux killed","success"):this.showToast("Tab hidden, tmux still running","info")}catch{this.showToast("Failed to close session","error")}}requestCloseSession(e){const t=this.sessions.get(e);if(!t)return;this.pendingCloseSessionId=e;const s=this.getSessionName(t),n=document.getElementById("closeConfirmSessionName");n.textContent=s;const i=document.getElementById("closeConfirmKillTitle");i&&(i.textContent=t.mode==="opencode"?"Kill Tmux & OpenCode":"Kill Tmux & Claude Code"),document.getElementById("closeConfirmModal").classList.add("active")}cancelCloseSession(){this.pendingCloseSessionId=null,document.getElementById("closeConfirmModal").classList.remove("active")}async confirmCloseSession(e=!0){const t=this.pendingCloseSessionId;this.cancelCloseSession(),t&&await this.closeSession(t,e)}nextSession(){if(this.sessionOrder.length<=1)return;const t=(this.sessionOrder.indexOf(this.activeSessionId)+1)%this.sessionOrder.length;this.selectSession(this.sessionOrder[t])}prevSession(){if(this.sessionOrder.length<=1)return;const t=(this.sessionOrder.indexOf(this.activeSessionId)-1+this.sessionOrder.length)%this.sessionOrder.length;this.selectSession(this.sessionOrder[t])}goHome(){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome(),this.renderSessionTabs(),this.renderRalphStatePanel()}ralphWizardStep=1;ralphWizardConfig={taskDescription:"",completionPhrase:"COMPLETE",maxIterations:10,caseName:"testcase",enableRespawn:!1,generatedPlan:null,planGenerated:!1,skipPlanGeneration:!1,planDetailLevel:"detailed",existingPlan:null,useExistingPlan:!1};planLoadingTimer=null;planLoadingStartTime=null;async loadQuickStartCases(e=null,t=null){try{let s=null;try{const d=t?await t:await fetch("/api/settings").then(u=>u.ok?u.json():null);d&&(s=d.lastUsedCase||null)}catch{}const i=await(await fetch("/api/cases")).json();this.cases=i;const o=document.getElementById("quickStartCase");let l="";const a=i.some(d=>d.name==="testcase"),c=MobileDetection.getDeviceType()==="mobile"?8:20;if(i.forEach(d=>{const u=d.name.length>c?d.name.substring(0,c)+"\u2026":d.name;l+=`<option value="${escapeHtml(d.name)}">${escapeHtml(u)}</option>`}),a||(l='<option value="testcase">testcase</option>'+l),o.innerHTML=l,e)o.value=e,this.updateDirDisplayForCase(e),this.updateMobileCaseLabel(e);else if(s&&i.some(d=>d.name===s))o.value=s,this.updateDirDisplayForCase(s),this.updateMobileCaseLabel(s);else if(i.length>0){const d=i.find(u=>u.name==="testcase")||i[0];o.value=d.name,this.updateDirDisplayForCase(d.name),this.updateMobileCaseLabel(d.name)}else o.value="testcase",document.getElementById("dirDisplay").textContent="~/codeman-cases/testcase",this.updateMobileCaseLabel("testcase");o.dataset.listenerAdded||(o.addEventListener("change",()=>{this.updateDirDisplayForCase(o.value),this.saveLastUsedCase(o.value),this.updateMobileCaseLabel(o.value)}),o.dataset.listenerAdded="true")}catch{}}async updateDirDisplayForCase(e){try{const s=await(await fetch(`/api/cases/${e}`)).json();s.path&&(document.getElementById("dirDisplay").textContent=s.path,document.getElementById("dirInput").value=s.path)}catch{document.getElementById("dirDisplay").textContent=e}}async saveLastUsedCase(e){try{const t=await fetch("/api/settings"),s=t.ok?await t.json():{};s.lastUsedCase=e,await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})}catch{}}async quickStart(){return this.run()}async run(){return(this._runMode||"claude")==="opencode"?this.runOpenCode():this.runClaude()}get runMode(){return this._runMode||"claude"}setRunMode(e){this._runMode=e;try{localStorage.setItem("codeman_runMode",e)}catch{}this._applyRunMode(),document.getElementById("runModeMenu")?.classList.remove("active")}toggleRunModeMenu(e){e?.stopPropagation();const t=document.getElementById("runModeMenu");if(t&&(t.classList.toggle("active"),t.querySelectorAll(".run-mode-option").forEach(s=>{s.classList.toggle("selected",s.dataset.mode===this.runMode)}),t.classList.contains("active"))){const s=n=>{t.contains(n.target)||(t.classList.remove("active"),document.removeEventListener("click",s))};setTimeout(()=>document.addEventListener("click",s),0)}}_applyRunMode(){const e=this.runMode,t=document.getElementById("runBtn"),s=t?.nextElementSibling,n=document.getElementById("runBtnLabel");t&&(t.className=`btn-toolbar btn-run mode-${e}`),s&&(s.className=`btn-toolbar btn-run-gear mode-${e}`),n&&(n.textContent=e==="opencode"?"Run OC":"Run")}_initRunMode(){try{this._runMode=localStorage.getItem("codeman_runMode")||"claude"}catch{this._runMode="claude"}this._applyRunMode()}incrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)}decrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)}incrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)}decrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)}async runClaude(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("tabCount").value)||1));this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting ${t} Claude session(s) in ${e}...\x1B[0m`),this.terminal.writeln("");try{let n=await(await fetch(`/api/cases/${e}`)).json();if(!n.path){const S=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!S.success)throw new Error(S.error||"Failed to create case");n=S.case}const i=n.path;if(!i)throw new Error("Case path not found");let o=null,l=1;for(const[,f]of this.sessions){const S=f.name&&f.name.match(/^w(\d+)-(.+)$/);if(S&&S[2]===e){const w=parseInt(S[1]);w>=l&&(l=w+1)}}const a=this.isRalphTrackerEnabledByDefault(),r=[];for(let f=0;f<t;f++)r.push(`w${l+f}-${e}`);const c=this.getCaseSettings(e),d=this.loadAppSettingsFromStorage(),u={};(c.agentTeams||d.agentTeamsEnabled)&&(u.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS="1");const h=Object.keys(u).length>0;this.terminal.writeln(`\x1B[90m Creating ${t} session(s)...\x1B[0m`);const m=r.map(f=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,name:f,...h?{envOverrides:u}:{}})}).then(S=>S.json())),p=await Promise.all(m),g=[];for(const f of p){if(!f.success)throw new Error(f.error);g.push(f.session.id)}o=g[0],await Promise.all(g.map(f=>fetch(`/api/sessions/${f}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:a,disableAutoEnable:!a})}))),this.terminal.writeln(`\x1B[90m Starting ${t} session(s) in parallel...\x1B[0m`),await Promise.all(g.map(f=>fetch(`/api/sessions/${f}/interactive`,{method:"POST"}))),this.terminal.writeln(`\x1B[90m All ${t} sessions ready\x1B[0m`),o&&(await this.selectSession(o),this.loadQuickStartCases()),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}}stopClaude(){if(!this.activeSessionId)return;const e=document.querySelector(".btn-toolbar.btn-stop");e&&(this._stopConfirmTimer?(clearTimeout(this._stopConfirmTimer),this._stopConfirmTimer=null,e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml,e.classList.remove("confirming"),fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:""})})):(e.dataset.origHtml=e.innerHTML,e.textContent="Tap again",e.classList.add("confirming"),this._stopConfirmTimer=setTimeout(()=>{this._stopConfirmTimer=null,e.dataset.origHtml&&(e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml),e.classList.remove("confirming")},2e3)))}async runShell(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("shellCount").value)||1));this.terminal.clear(),this.terminal.writeln(`\x1B[1;33m Starting ${t} Shell session(s) in ${e}...\x1B[0m`),this.terminal.writeln("");try{const i=(await(await fetch(`/api/cases/${e}`)).json()).path;if(!i)throw new Error("Case path not found");let o=1;for(const[,u]of this.sessions){const h=u.name&&u.name.match(/^s(\d+)-(.+)$/);if(h&&h[2]===e){const m=parseInt(h[1]);m>=o&&(o=m+1)}}const l=[];for(let u=0;u<t;u++)l.push(`s${o+u}-${e}`);const a=l.map(u=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,mode:"shell",name:u})}).then(h=>h.json())),r=await Promise.all(a),c=[];for(const u of r){if(!u.success)throw new Error(u.error);c.push(u.session.id)}await Promise.all(c.map(u=>fetch(`/api/sessions/${u}/shell`,{method:"POST"})));const d=this.getTerminalDimensions();d&&await Promise.all(c.map(u=>fetch(`/api/sessions/${u}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}))),c.length>0&&(this.activeSessionId=c[0],await this.selectSession(c[0])),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}}async runOpenCode(){const e=document.getElementById("quickStartCase").value||"testcase";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting OpenCode session in ${e}...\x1B[0m`),this.terminal.writeln("");try{if(!(await(await fetch("/api/opencode/status")).json()).available){this.terminal.writeln("\x1B[1;31m OpenCode CLI not found.\x1B[0m"),this.terminal.writeln("\x1B[90m Install with: curl -fsSL https://opencode.ai/install | bash\x1B[0m");return}const i=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"opencode",openCodeConfig:{autoAllowTools:!0}})})).json();if(!i.success)throw new Error(i.error||"Failed to start OpenCode");i.sessionId&&await this.selectSession(i.sessionId),this.terminal.focus()}catch(t){this.terminal.writeln(`\x1B[1;31m Error: ${t.message}\x1B[0m`)}}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)}showRespawnBanner(){this.$("respawnBanner").style.display="flex",this.activeSessionId&&this.respawnTimers[this.activeSessionId]&&this.showRespawnTimer();const e=this.sessions.get(this.activeSessionId);e&&e.tokens&&this.updateRespawnTokens(e.tokens)}hideRespawnBanner(){this.$("respawnBanner").style.display="none",this.hideRespawnTimer()}getStateLabel(e){return{stopped:"Stopped",watching:"Watching",confirming_idle:"Confirming idle",ai_checking:"AI checking",sending_update:"Sending prompt",waiting_update:"Running prompt",sending_clear:"Clearing context",waiting_clear:"Clearing...",sending_init:"Initializing",waiting_init:"Initializing...",monitoring_init:"Waiting for work",sending_kickstart:"Kickstarting",waiting_kickstart:"Kickstarting..."}[e]||e.replace(/_/g," ")}updateRespawnBanner(e){const t=this.$("respawnState");t.textContent=this.getStateLabel(e),t.classList.remove("respawn-blocked")}updateDetectionDisplay(e){if(!e)return;const t=this.$("detectionStatus"),s=this.$("detectionWaiting"),n=this.$("detectionConfidence"),i=document.getElementById("detectionAiCheck"),o=document.getElementById("detectionHook");if(o)if(e.stopHookReceived||e.idlePromptReceived){const r=e.idlePromptReceived?"idle":"stop";o.textContent=`\u{1F3AF} ${r} hook`,o.className="detection-hook hook-active",o.style.display=""}else o.style.display="none";e.statusText&&e.statusText!=="Watching..."?(t.textContent=e.statusText,t.style.display=""):t.style.display="none",s.style.display="none";const l=e.confidenceLevel||0;if(l>0?(n.textContent=`${l}%`,n.style.display="",n.className="detection-confidence",e.stopHookReceived||e.idlePromptReceived?n.classList.add("hook-confirmed"):l>=60?n.classList.add("high"):l>=30&&n.classList.add("medium")):n.style.display="none",i&&e.aiCheck){const r=e.aiCheck;let c="",d="detection-ai-check";if(r.status==="checking")c="\u{1F50D} AI checking...",d+=" ai-checking";else if(r.status==="cooldown"&&r.cooldownEndsAt){const u=Math.ceil((r.cooldownEndsAt-Date.now())/1e3);u>0&&(r.lastVerdict==="WORKING"?(c=`\u23F3 Working, retry ${u}s`,d+=" ai-working"):(c=`\u2713 Idle, wait ${u}s`,d+=" ai-idle"))}else if(r.status==="disabled")c="\u26A0 AI disabled",d+=" ai-disabled";else if(r.lastVerdict&&r.lastCheckTime){const u=Math.round((Date.now()-r.lastCheckTime)/1e3);u<120&&(c=r.lastVerdict==="IDLE"?`\u2713 Idle (${u}s)`:`\u23F3 Working (${u}s)`,d+=r.lastVerdict==="IDLE"?" ai-idle":" ai-working")}i.textContent=c,i.className=d,i.style.display=c?"":"none"}else i&&(i.style.display="none");const a=this.$("respawnStatusRow2");if(a){const r=o&&o.style.display!=="none"||i&&i.style.display!=="none"||t&&t.style.display!=="none"||this.respawnCountdownTimers[this.activeSessionId]&&Object.keys(this.respawnCountdownTimers[this.activeSessionId]).length>0;a.style.display=r?"":"none"}}showRespawnTimer(){const e=this.$("respawnTimer");e.style.display="",this.updateRespawnTimer(),this.respawnTimerInterval&&clearInterval(this.respawnTimerInterval),this.respawnTimerInterval=setInterval(()=>this.updateRespawnTimer(),1e3)}hideRespawnTimer(){this.$("respawnTimer").style.display="none",this.respawnTimerInterval&&(clearInterval(this.respawnTimerInterval),this.respawnTimerInterval=null)}updateRespawnTimer(){if(!this.activeSessionId||!this.respawnTimers[this.activeSessionId]){this.hideRespawnTimer();return}const e=this.respawnTimers[this.activeSessionId];if(!e.endAt||isNaN(e.endAt)){this.hideRespawnTimer();return}const t=Date.now(),s=Math.max(0,e.endAt-t);if(s<=0){this.$("respawnTimer").textContent="Time up",delete this.respawnTimers[this.activeSessionId],this.hideRespawnTimer();return}this.$("respawnTimer").textContent=this.formatTime(s)}updateRespawnTokens(e){const t=e&&typeof e=="object",s=t?e.total:e;if(s===this._lastRespawnTokenTotal)return;this._lastRespawnTokenTotal=s;const n=this.$("respawnTokens"),i=t?e.input||0:Math.round(s*.6),o=t?e.output||0:Math.round(s*.4);if(s>0){n.style.display="";const l=this.formatTokens(s);if(this.loadAppSettingsFromStorage().showCost??!1){const c=this.estimateCost(i,o);n.textContent=`${l} tokens \xB7 $${c.toFixed(2)}`}else n.textContent=`${l} tokens`}else n.style.display="none";this.updateCliInfoDisplay()}updateCliInfoDisplay(){const e=this.$("cliInfoBar");if(!e)return;const t=this.sessions.get(this.activeSessionId);if(!t){e.style.display="none";return}let s=[];if(t.tokens){const n=typeof t.tokens=="object"?t.tokens.total:t.tokens;n>0&&s.push(`${this.formatTokens(n)} tokens`)}if(t.cliModel){let n=t.cliModel;n.includes("opus")?n="Opus":n.includes("sonnet")?n="Sonnet":n.includes("haiku")&&(n="Haiku"),s.push(n)}if(t.cliVersion){let n=`v${t.cliVersion}`;t.cliLatestVersion&&t.cliLatestVersion!==t.cliVersion&&(n+=" \u2191"),s.push(n)}s.length>0?(e.textContent=s.join(" \xB7 "),e.style.display=""):e.style.display="none"}addActionLogEntry(e,t){if(!["command","hook"].includes(t.type)){if(t.type==="ai-check"){if(t.detail.includes("Spawning"))return}else if(t.type==="plan-check"){if(t.detail.includes("Spawning"))return}else if(t.type!=="transcript")return}this.respawnActionLogs[e]||(this.respawnActionLogs[e]=[]),this.respawnActionLogs[e].unshift(t),this.respawnActionLogs[e].length>30&&this.respawnActionLogs[e].pop()}startCountdownInterval(){this.timerCountdownInterval||(this.timerCountdownInterval=setInterval(()=>{this.activeSessionId&&this.respawnCountdownTimers[this.activeSessionId]&&this.updateCountdownTimerDisplay()},100))}stopCountdownInterval(){this.timerCountdownInterval&&(clearInterval(this.timerCountdownInterval),this.timerCountdownInterval=null)}updateCountdownTimerDisplay(){const e=this.$("respawnCountdownTimers"),t=this.$("respawnStatusRow2");if(!e)return;const s=this.respawnCountdownTimers[this.activeSessionId];if(!(s&&Object.keys(s).length>0)){if(e.innerHTML="",t){const l=document.getElementById("detectionHook"),a=document.getElementById("detectionAiCheck"),r=this.$("detectionStatus"),c=l&&l.style.display!=="none"||a&&a.style.display!=="none"||r&&r.style.display!=="none";t.style.display=c?"":"none"}return}t&&(t.style.display="");const i=Date.now();let o="";for(const[l,a]of Object.entries(s)){const r=Math.max(0,a.endsAt-i),c=(r/1e3).toFixed(1),d=Math.max(0,Math.min(100,r/a.totalMs*100)),u=l.replace(/-/g," ").replace(/^\w/,h=>h.toUpperCase());o+=`<div class="respawn-countdown-timer" title="${escapeHtml(a.reason||"")}">
17
17
  <span class="timer-name">${escapeHtml(u)}</span>
18
18
  <span class="timer-value">${c}s</span>
19
19
  <div class="respawn-timer-bar">
@@ -82,7 +82,7 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
82
82
  <td style="padding:3px 8px;color:#e0e0e0" title="${r.sessionId}">${u}</td>
83
83
  <td style="padding:3px 8px;color:#aaa">${r.reason||""}</td>
84
84
  <td style="padding:3px 8px;color:#666">${h.join(", ")}</td>
85
- </tr>`}).join("")}catch{}}async saveAppSettings(){const e={defaultClaudeMdPath:document.getElementById("appSettingsClaudeMdPath").value.trim(),defaultWorkingDir:document.getElementById("appSettingsDefaultDir").value.trim(),ralphTrackerEnabled:document.getElementById("appSettingsRalphEnabled").checked,showFontControls:document.getElementById("appSettingsShowFontControls").checked,showSystemStats:document.getElementById("appSettingsShowSystemStats").checked,showTokenCount:document.getElementById("appSettingsShowTokenCount").checked,showCost:document.getElementById("appSettingsShowCost").checked,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").checked,subagentTrackingEnabled:document.getElementById("appSettingsSubagentTracking").checked,subagentActiveTabOnly:document.getElementById("appSettingsSubagentActiveTabOnly").checked,imageWatcherEnabled:document.getElementById("appSettingsImageWatcherEnabled").checked,tunnelEnabled:document.getElementById("appSettingsTunnelEnabled").checked,localEchoEnabled:document.getElementById("appSettingsLocalEcho").checked,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};this.saveAppSettingsToStorage(e),this._updateLocalEchoState();const t={apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(t);const s={enabled:document.getElementById("appSettingsNotifEnabled").checked,browserNotifications:document.getElementById("appSettingsNotifBrowser").checked,audioAlerts:document.getElementById("appSettingsNotifAudio").checked,stuckThresholdMs:(parseInt(document.getElementById("appSettingsNotifStuckMins").value)||10)*6e4,muteCritical:!document.getElementById("appSettingsNotifCritical").checked,muteWarning:!document.getElementById("appSettingsNotifWarning").checked,muteInfo:!document.getElementById("appSettingsNotifInfo").checked,eventTypes:{permission_prompt:{enabled:document.getElementById("eventPermissionEnabled").checked,browser:document.getElementById("eventPermissionBrowser").checked,push:document.getElementById("eventPermissionPush").checked,audio:document.getElementById("eventPermissionAudio").checked},elicitation_dialog:{enabled:document.getElementById("eventQuestionEnabled").checked,browser:document.getElementById("eventQuestionBrowser").checked,push:document.getElementById("eventQuestionPush").checked,audio:document.getElementById("eventQuestionAudio").checked},idle_prompt:{enabled:document.getElementById("eventIdleEnabled").checked,browser:document.getElementById("eventIdleBrowser").checked,push:document.getElementById("eventIdlePush").checked,audio:document.getElementById("eventIdleAudio").checked},stop:{enabled:document.getElementById("eventStopEnabled").checked,browser:document.getElementById("eventStopBrowser").checked,push:document.getElementById("eventStopPush").checked,audio:document.getElementById("eventStopAudio").checked},session_error:{enabled:!0,browser:this.notificationManager?.preferences?.eventTypes?.session_error?.browser??!0,push:this.notificationManager?.preferences?.eventTypes?.session_error?.push??!1,audio:!1},respawn_cycle:{enabled:document.getElementById("eventRespawnEnabled").checked,browser:document.getElementById("eventRespawnBrowser").checked,push:document.getElementById("eventRespawnPush").checked,audio:document.getElementById("eventRespawnAudio").checked},token_milestone:{enabled:!0,browser:!1,push:!1,audio:!1},ralph_complete:{enabled:document.getElementById("eventRalphEnabled").checked,browser:document.getElementById("eventRalphBrowser").checked,push:document.getElementById("eventRalphPush").checked,audio:document.getElementById("eventRalphAudio").checked},subagent_spawn:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked},subagent_complete:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked}},_version:4};this.notificationManager&&(this.notificationManager.preferences=s,this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility();const{localEchoEnabled:n,...i}=e;try{await this._apiPut("/api/settings",{...i,notificationPreferences:s,voiceSettings:t}),await this.saveModelConfigFromSettings(),this.showToast("Settings saved","success"),e.tunnelEnabled&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}this.closeAppSettings()}async loadModelConfigForSettings(){try{const t=await(await fetch("/api/execution/model-config")).json();if(t.success&&t.data){const s=t.data,n=document.getElementById("appSettingsDefaultModel");n&&(n.value=s.defaultModel||"opus");const i=document.getElementById("appSettingsShowModelRecommendations");i&&(i.checked=s.showRecommendations??!0);const o=s.agentTypeOverrides||{},l=document.getElementById("appSettingsModelExplore"),a=document.getElementById("appSettingsModelImplement"),r=document.getElementById("appSettingsModelTest"),c=document.getElementById("appSettingsModelReview");l&&(l.value=o.explore||""),a&&(a.value=o.implement||""),r&&(r.value=o.test||""),c&&(c.value=o.review||"")}}catch{}}async saveModelConfigFromSettings(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),s=document.getElementById("appSettingsModelExplore"),n=document.getElementById("appSettingsModelImplement"),i=document.getElementById("appSettingsModelTest"),o=document.getElementById("appSettingsModelReview"),l={};s?.value&&(l.explore=s.value),n?.value&&(l.implement=n.value),i?.value&&(l.test=i.value),o?.value&&(l.review=o.value);const a={defaultModel:e?.value||"opus",showRecommendations:t?.checked??!0,agentTypeOverrides:l};try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})}catch{}}isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1}getSettingsStorageKey(){return MobileDetection.getDeviceType()==="mobile"?"codeman-app-settings-mobile":"codeman-app-settings"}getDefaultSettings(){return MobileDetection.getDeviceType()==="mobile"?{showFontControls:!1,showSystemStats:!1,showTokenCount:!1,showCost:!1,showMonitor:!1,showProjectInsights:!1,showFileBrowser:!1,showSubagents:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1}:{}}loadAppSettingsFromStorage(){if(this._cachedAppSettings)return this._cachedAppSettings;try{const e=this.getSettingsStorageKey(),t=localStorage.getItem(e);if(t)return this._cachedAppSettings=JSON.parse(t),this._cachedAppSettings}catch{}return this._cachedAppSettings=this.getDefaultSettings(),this._cachedAppSettings}saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch{}}applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=e.showFontControls??t.showFontControls??!1,n=e.showSystemStats??t.showSystemStats??!0,i=e.showTokenCount??t.showTokenCount??!0,o=document.querySelector(".header-font-controls"),l=document.getElementById("headerSystemStats"),a=document.getElementById("headerTokens");o&&(o.style.display=s?"":"none"),l&&(l.style.display=n?"":"none"),a&&(a.style.display=i?"":"none");const r=e.showLifecycleLog??t.showLifecycleLog??!0,c=document.querySelector(".btn-lifecycle-log");c&&(c.style.display=r?"":"none");const d=this.notificationManager?.preferences?.enabled??!0,u=document.querySelector(".btn-notifications");if(u&&(u.style.display=d?"":"none"),!d){const h=document.getElementById("notifDrawer");h&&h.classList.remove("open")}}applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=MobileDetection.getDeviceType()==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,i=this._tallTabsEnabled;this._tallTabsEnabled=n;const o=document.getElementById("sessionTabs");o&&(o.classList.toggle("tabs-two-rows",n),o.classList.toggle("tabs-show-folder",n)),i!==void 0&&i!==n&&this._fullRenderSessionTabs()}applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=e.showMonitor??t.showMonitor??!0,n=e.showSubagents??t.showSubagents??!0,i=e.showFileBrowser??t.showFileBrowser??!1,o=document.getElementById("monitorPanel");o&&(o.style.display=s?"":"none",s?o.classList.add("open"):o.classList.remove("open"));const l=document.getElementById("subagentsPanel");l&&(n?l.classList.remove("hidden"):l.classList.add("hidden"));const a=document.getElementById("fileBrowserPanel");a&&(i&&this.activeSessionId?(a.classList.add("visible"),this.loadFileBrowser(this.activeSessionId)):a.classList.remove("visible"))}closeMonitor(){const e=document.getElementById("monitorPanel");e&&(e.classList.remove("open"),e.style.display="none");const t=this.loadAppSettingsFromStorage();t.showMonitor=!1,this.saveAppSettingsToStorage(t)}closeSubagentsPanel(){const e=document.getElementById("subagentsPanel");e&&(e.classList.remove("open"),e.classList.add("hidden")),this.subagentPanelVisible=!1;const t=this.loadAppSettingsFromStorage();t.showSubagents=!1,this.saveAppSettingsToStorage(t)}async clearAllSubagents(){const e=this.subagents.size;if(e===0){this.showToast("No subagents to clear","info");return}if(confirm(`Clear all ${e} tracked subagent(s)? This removes them from the UI but does not affect running processes.`))try{const s=await(await fetch("/api/subagents",{method:"DELETE"})).json();s.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${s.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+s.error,"error")}catch{this.showToast("Failed to clear subagents","error")}}toggleSubagentsPanel(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsToggleBtn");if(e){if(e.classList.contains("hidden")){e.classList.remove("hidden");const s=this.loadAppSettingsFromStorage();s.showSubagents=!0,this.saveAppSettingsToStorage(s)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"&#x25BC;":"&#x25B2;"),this.subagentPanelVisible&&this.renderSubagentPanel()}}async loadAppSettingsFromServer(e=null){try{const t=e?await e:await fetch("/api/settings").then(s=>s.ok?s.json():null);if(t){const{notificationPreferences:s,voiceSettings:n,...i}=t,o=new Set(["showFontControls","showSystemStats","showTokenCount","showCost","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","localEchoEnabled"]),l=this.loadAppSettingsFromStorage(),a={...l};for(const[r,c]of Object.entries(i))o.has(r)&&r in l||(a[r]=c);if(this.saveAppSettingsToStorage(a),s&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=s,this.notificationManager.savePreferences())),n){const r=localStorage.getItem("codeman-voice-settings");(!r||!JSON.parse(r).apiKey)&&VoiceInput._saveDeepgramConfig(n)}return a}}catch{}return this.loadAppSettingsFromStorage()}async loadSubagentWindowStates(){let e=null;try{const t=await fetch("/api/subagent-window-states");t.ok&&(e=await t.json(),localStorage.setItem("codeman-subagent-window-states",JSON.stringify(e)))}catch{}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch{}return e||{minimized:{},open:[]}}async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch{}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{}}async loadSubagentParentMap(){let e=null;try{const t=await fetch("/api/subagent-parents");t.ok&&(e=await t.json(),localStorage.setItem("codeman-subagent-parents",JSON.stringify(e)))}catch{}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch{}if(e&&typeof e=="object")for(const[t,s]of Object.entries(e))this.sessions.has(s)&&this.subagents.has(t)&&this.subagentParentMap.set(t,s)}getAgentParentSessionId(e){return this.subagentParentMap.get(e)||null}setAgentParentSessionId(e,t){if(!e||!t||this.subagentParentMap.has(e))return;this.subagentParentMap.set(e,t),this.saveSubagentParentMap();const s=this.subagents.get(e);if(s){s.parentSessionId=t;const n=this.sessions.get(t);n&&(s.parentSessionName=this.getSessionName(n)),this.subagents.set(e,s)}}showHelp(){const e=document.getElementById("helpModal");e.classList.add("active"),this.activeFocusTrap=new FocusTrap(e),this.activeFocusTrap.activate()}closeHelp(){document.getElementById("helpModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)}closeAllPanels(){this.closeSessionOptions(),this.closeAppSettings(),this.cancelCloseSession(),this.closeTokenStats(),document.getElementById("monitorPanel").classList.remove("open");const e=document.getElementById("subagentsPanel");e&&e.classList.remove("open"),this.subagentPanelVisible=!1}async openTokenStats(){try{const t=await(await fetch("/api/token-stats")).json();t.success?(this.renderTokenStats(t),document.getElementById("tokenStatsModal").classList.add("active")):this.showToast("Failed to load token stats","error")}catch{this.showToast("Failed to load token stats","error")}}renderTokenStats(e){const{daily:t,totals:s}=e,n=new Date().toISOString().split("T")[0],i=t.find(y=>y.date===n)||{inputTokens:0,outputTokens:0,estimatedCost:0},o=new Date;o.setDate(o.getDate()-7);const l=t.filter(y=>new Date(y.date)>=o),a=l.reduce((y,v)=>y+v.inputTokens,0),r=l.reduce((y,v)=>y+v.outputTokens,0),c=this.estimateCost(a,r),d=s.totalInputTokens,u=s.totalOutputTokens,h=this.estimateCost(d,u),m=document.getElementById("statsSummary");m.innerHTML=`
85
+ </tr>`}).join("")}catch{}}async saveAppSettings(){const e={defaultClaudeMdPath:document.getElementById("appSettingsClaudeMdPath").value.trim(),defaultWorkingDir:document.getElementById("appSettingsDefaultDir").value.trim(),ralphTrackerEnabled:document.getElementById("appSettingsRalphEnabled").checked,showFontControls:document.getElementById("appSettingsShowFontControls").checked,showSystemStats:document.getElementById("appSettingsShowSystemStats").checked,showTokenCount:document.getElementById("appSettingsShowTokenCount").checked,showCost:document.getElementById("appSettingsShowCost").checked,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").checked,subagentTrackingEnabled:document.getElementById("appSettingsSubagentTracking").checked,subagentActiveTabOnly:document.getElementById("appSettingsSubagentActiveTabOnly").checked,imageWatcherEnabled:document.getElementById("appSettingsImageWatcherEnabled").checked,tunnelEnabled:document.getElementById("appSettingsTunnelEnabled").checked,localEchoEnabled:document.getElementById("appSettingsLocalEcho").checked,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};this.saveAppSettingsToStorage(e),this._updateLocalEchoState();const t={apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(t);const s={enabled:document.getElementById("appSettingsNotifEnabled").checked,browserNotifications:document.getElementById("appSettingsNotifBrowser").checked,audioAlerts:document.getElementById("appSettingsNotifAudio").checked,stuckThresholdMs:(parseInt(document.getElementById("appSettingsNotifStuckMins").value)||10)*6e4,muteCritical:!document.getElementById("appSettingsNotifCritical").checked,muteWarning:!document.getElementById("appSettingsNotifWarning").checked,muteInfo:!document.getElementById("appSettingsNotifInfo").checked,eventTypes:{permission_prompt:{enabled:document.getElementById("eventPermissionEnabled").checked,browser:document.getElementById("eventPermissionBrowser").checked,push:document.getElementById("eventPermissionPush").checked,audio:document.getElementById("eventPermissionAudio").checked},elicitation_dialog:{enabled:document.getElementById("eventQuestionEnabled").checked,browser:document.getElementById("eventQuestionBrowser").checked,push:document.getElementById("eventQuestionPush").checked,audio:document.getElementById("eventQuestionAudio").checked},idle_prompt:{enabled:document.getElementById("eventIdleEnabled").checked,browser:document.getElementById("eventIdleBrowser").checked,push:document.getElementById("eventIdlePush").checked,audio:document.getElementById("eventIdleAudio").checked},stop:{enabled:document.getElementById("eventStopEnabled").checked,browser:document.getElementById("eventStopBrowser").checked,push:document.getElementById("eventStopPush").checked,audio:document.getElementById("eventStopAudio").checked},session_error:{enabled:!0,browser:this.notificationManager?.preferences?.eventTypes?.session_error?.browser??!0,push:this.notificationManager?.preferences?.eventTypes?.session_error?.push??!1,audio:!1},respawn_cycle:{enabled:document.getElementById("eventRespawnEnabled").checked,browser:document.getElementById("eventRespawnBrowser").checked,push:document.getElementById("eventRespawnPush").checked,audio:document.getElementById("eventRespawnAudio").checked},token_milestone:{enabled:!0,browser:!1,push:!1,audio:!1},ralph_complete:{enabled:document.getElementById("eventRalphEnabled").checked,browser:document.getElementById("eventRalphBrowser").checked,push:document.getElementById("eventRalphPush").checked,audio:document.getElementById("eventRalphAudio").checked},subagent_spawn:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked},subagent_complete:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked}},_version:4};this.notificationManager&&(this.notificationManager.preferences=s,this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility();const{localEchoEnabled:n,...i}=e;try{await this._apiPut("/api/settings",{...i,notificationPreferences:s,voiceSettings:t}),await this.saveModelConfigFromSettings(),this.showToast("Settings saved","success"),e.tunnelEnabled&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}this.closeAppSettings()}async loadModelConfigForSettings(){try{const t=await(await fetch("/api/execution/model-config")).json();if(t.success&&t.data){const s=t.data,n=document.getElementById("appSettingsDefaultModel");n&&(n.value=s.defaultModel||"opus");const i=document.getElementById("appSettingsShowModelRecommendations");i&&(i.checked=s.showRecommendations??!0);const o=s.agentTypeOverrides||{},l=document.getElementById("appSettingsModelExplore"),a=document.getElementById("appSettingsModelImplement"),r=document.getElementById("appSettingsModelTest"),c=document.getElementById("appSettingsModelReview");l&&(l.value=o.explore||""),a&&(a.value=o.implement||""),r&&(r.value=o.test||""),c&&(c.value=o.review||"")}}catch{}}async saveModelConfigFromSettings(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),s=document.getElementById("appSettingsModelExplore"),n=document.getElementById("appSettingsModelImplement"),i=document.getElementById("appSettingsModelTest"),o=document.getElementById("appSettingsModelReview"),l={};s?.value&&(l.explore=s.value),n?.value&&(l.implement=n.value),i?.value&&(l.test=i.value),o?.value&&(l.review=o.value);const a={defaultModel:e?.value||"opus",showRecommendations:t?.checked??!0,agentTypeOverrides:l};try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})}catch{}}isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1}getSettingsStorageKey(){return MobileDetection.getDeviceType()==="mobile"?"codeman-app-settings-mobile":"codeman-app-settings"}getDefaultSettings(){return MobileDetection.getDeviceType()==="mobile"?{showFontControls:!1,showSystemStats:!1,showTokenCount:!1,showCost:!1,showMonitor:!1,showProjectInsights:!1,showFileBrowser:!1,showSubagents:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1}:{}}loadAppSettingsFromStorage(){if(this._cachedAppSettings)return this._cachedAppSettings;try{const e=this.getSettingsStorageKey(),t=localStorage.getItem(e);if(t)return this._cachedAppSettings=JSON.parse(t),this._cachedAppSettings}catch{}return this._cachedAppSettings=this.getDefaultSettings(),this._cachedAppSettings}saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch{}}applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=e.showFontControls??t.showFontControls??!1,n=e.showSystemStats??t.showSystemStats??!0,i=e.showTokenCount??t.showTokenCount??!0,o=document.querySelector(".header-font-controls"),l=document.getElementById("headerSystemStats"),a=document.getElementById("headerTokens");o&&(o.style.display=s?"":"none"),l&&(l.style.display=n?"":"none"),a&&(a.style.display=i?"":"none");const r=e.showLifecycleLog??t.showLifecycleLog??!0,c=document.querySelector(".btn-lifecycle-log");c&&(c.style.display=r?"":"none");const d=this.notificationManager?.preferences?.enabled??!0,u=document.querySelector(".btn-notifications");if(u&&(u.style.display=d?"":"none"),!d){const h=document.getElementById("notifDrawer");h&&h.classList.remove("open")}}applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=MobileDetection.getDeviceType()==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,i=this._tallTabsEnabled;this._tallTabsEnabled=n;const o=document.getElementById("sessionTabs");o&&(o.classList.toggle("tabs-two-rows",n),o.classList.toggle("tabs-show-folder",n)),i!==void 0&&i!==n&&this._fullRenderSessionTabs()}applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=e.showMonitor??t.showMonitor??!0,n=e.showSubagents??t.showSubagents??!0,i=e.showFileBrowser??t.showFileBrowser??!1,o=document.getElementById("monitorPanel");o&&(o.style.display=s?"":"none",s?o.classList.add("open"):o.classList.remove("open"));const l=document.getElementById("subagentsPanel");l&&(n?l.classList.remove("hidden"):l.classList.add("hidden"));const a=document.getElementById("fileBrowserPanel");if(a)if(i&&this.activeSessionId){if(a.classList.add("visible"),this.loadFileBrowser(this.activeSessionId),!this.fileBrowserDragListeners){const r=a.querySelector(".file-browser-header");if(r){const c=()=>{if(!a.style.left){const d=a.getBoundingClientRect();a.style.left=`${d.left}px`,a.style.top=`${d.top}px`,a.style.right="auto"}};r.addEventListener("mousedown",c),r.addEventListener("touchstart",c,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(a,r),this.fileBrowserDragListeners._onFirstDrag=c}}}else a.classList.remove("visible")}closeMonitor(){const e=document.getElementById("monitorPanel");e&&(e.classList.remove("open"),e.style.display="none");const t=this.loadAppSettingsFromStorage();t.showMonitor=!1,this.saveAppSettingsToStorage(t)}closeSubagentsPanel(){const e=document.getElementById("subagentsPanel");e&&(e.classList.remove("open"),e.classList.add("hidden")),this.subagentPanelVisible=!1;const t=this.loadAppSettingsFromStorage();t.showSubagents=!1,this.saveAppSettingsToStorage(t)}async clearAllSubagents(){const e=this.subagents.size;if(e===0){this.showToast("No subagents to clear","info");return}if(confirm(`Clear all ${e} tracked subagent(s)? This removes them from the UI but does not affect running processes.`))try{const s=await(await fetch("/api/subagents",{method:"DELETE"})).json();s.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${s.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+s.error,"error")}catch{this.showToast("Failed to clear subagents","error")}}toggleSubagentsPanel(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsToggleBtn");if(e){if(e.classList.contains("hidden")){e.classList.remove("hidden");const s=this.loadAppSettingsFromStorage();s.showSubagents=!0,this.saveAppSettingsToStorage(s)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"&#x25BC;":"&#x25B2;"),this.subagentPanelVisible&&this.renderSubagentPanel()}}async loadAppSettingsFromServer(e=null){try{const t=e?await e:await fetch("/api/settings").then(s=>s.ok?s.json():null);if(t){const{notificationPreferences:s,voiceSettings:n,...i}=t,o=new Set(["showFontControls","showSystemStats","showTokenCount","showCost","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","localEchoEnabled"]),l=this.loadAppSettingsFromStorage(),a={...l};for(const[r,c]of Object.entries(i))o.has(r)&&r in l||(a[r]=c);if(this.saveAppSettingsToStorage(a),s&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=s,this.notificationManager.savePreferences())),n){const r=localStorage.getItem("codeman-voice-settings");(!r||!JSON.parse(r).apiKey)&&VoiceInput._saveDeepgramConfig(n)}return a}}catch{}return this.loadAppSettingsFromStorage()}async loadSubagentWindowStates(){let e=null;try{const t=await fetch("/api/subagent-window-states");t.ok&&(e=await t.json(),localStorage.setItem("codeman-subagent-window-states",JSON.stringify(e)))}catch{}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch{}return e||{minimized:{},open:[]}}async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch{}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{}}async loadSubagentParentMap(){let e=null;try{const t=await fetch("/api/subagent-parents");t.ok&&(e=await t.json(),localStorage.setItem("codeman-subagent-parents",JSON.stringify(e)))}catch{}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch{}if(e&&typeof e=="object")for(const[t,s]of Object.entries(e))this.sessions.has(s)&&this.subagents.has(t)&&this.subagentParentMap.set(t,s)}getAgentParentSessionId(e){return this.subagentParentMap.get(e)||null}setAgentParentSessionId(e,t){if(!e||!t||this.subagentParentMap.has(e))return;this.subagentParentMap.set(e,t),this.saveSubagentParentMap();const s=this.subagents.get(e);if(s){s.parentSessionId=t;const n=this.sessions.get(t);n&&(s.parentSessionName=this.getSessionName(n)),this.subagents.set(e,s)}}showHelp(){const e=document.getElementById("helpModal");e.classList.add("active"),this.activeFocusTrap=new FocusTrap(e),this.activeFocusTrap.activate()}closeHelp(){document.getElementById("helpModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)}closeAllPanels(){this.closeSessionOptions(),this.closeAppSettings(),this.cancelCloseSession(),this.closeTokenStats(),document.getElementById("monitorPanel").classList.remove("open");const e=document.getElementById("subagentsPanel");e&&e.classList.remove("open"),this.subagentPanelVisible=!1}async openTokenStats(){try{const t=await(await fetch("/api/token-stats")).json();t.success?(this.renderTokenStats(t),document.getElementById("tokenStatsModal").classList.add("active")):this.showToast("Failed to load token stats","error")}catch{this.showToast("Failed to load token stats","error")}}renderTokenStats(e){const{daily:t,totals:s}=e,n=new Date().toISOString().split("T")[0],i=t.find(y=>y.date===n)||{inputTokens:0,outputTokens:0,estimatedCost:0},o=new Date;o.setDate(o.getDate()-7);const l=t.filter(y=>new Date(y.date)>=o),a=l.reduce((y,v)=>y+v.inputTokens,0),r=l.reduce((y,v)=>y+v.outputTokens,0),c=this.estimateCost(a,r),d=s.totalInputTokens,u=s.totalOutputTokens,h=this.estimateCost(d,u),m=document.getElementById("statsSummary");m.innerHTML=`
86
86
  <div class="stat-card">
87
87
  <span class="stat-card-label">Today</span>
88
88
  <span class="stat-card-value">${this.formatTokens(i.inputTokens+i.outputTokens)}</span>
@@ -307,14 +307,14 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
307
307
  `)}d.push(`
308
308
  </div>
309
309
  </div>
310
- `)}t.innerHTML=d.join("")}closeProjectInsightsPanel(){const e=this.$("projectInsightsPanel");e&&(e.classList.remove("visible"),this.projectInsightsPanelVisible=!1)}fileBrowserData=null;fileBrowserExpandedDirs=new Set;fileBrowserFilter="";fileBrowserAllExpanded=!1;filePreviewContent="";async loadFileBrowser(e){if(!e)return;const t=this.$("fileBrowserTree"),s=this.$("fileBrowserStatus");if(t){t.innerHTML='<div class="file-browser-loading">Loading files...</div>';try{const n=await fetch(`/api/sessions/${e}/files?depth=5&showHidden=false`);if(!n.ok)throw new Error("Failed to load files");const i=await n.json();if(!i.success)throw new Error(i.error||"Failed to load files");if(this.fileBrowserData=i.data,this.renderFileBrowserTree(),s){const{totalFiles:o,totalDirectories:l,truncated:a}=i.data;s.textContent=`${o} files, ${l} dirs${a?" (truncated)":""}`}}catch(n){t.innerHTML=`<div class="file-browser-empty">Failed to load files: ${escapeHtml(n.message)}</div>`}}}renderFileBrowserTree(){const e=this.$("fileBrowserTree");if(!e||!this.fileBrowserData)return;const{tree:t}=this.fileBrowserData;if(!t||t.length===0){e.innerHTML='<div class="file-browser-empty">No files found</div>';return}const s=[],n=this.fileBrowserFilter.toLowerCase(),i=(o,l)=>{const a=o.type==="directory",r=this.fileBrowserExpandedDirs.has(o.path),c=!n||o.name.toLowerCase().includes(n);let d=!1;a&&n&&o.children&&(d=this.hasMatchingChild(o,n));const h=!(c||d)&&n?" hidden-by-filter":"",m=a?r?"\u{1F4C2}":"\u{1F4C1}":this.getFileIcon(o.extension),p=a?`<span class="file-tree-expand${r?" expanded":""}">\u25B6</span>`:'<span class="file-tree-expand"></span>',g=!a&&o.size!==void 0?`<span class="file-tree-size">${this.formatFileSize(o.size)}</span>`:"",f=a?"file-tree-name directory":"file-tree-name";if(s.push(`
310
+ `)}t.innerHTML=d.join("")}closeProjectInsightsPanel(){const e=this.$("projectInsightsPanel");e&&(e.classList.remove("visible"),this.projectInsightsPanelVisible=!1)}fileBrowserData=null;fileBrowserExpandedDirs=new Set;fileBrowserFilter="";fileBrowserAllExpanded=!1;fileBrowserDragListeners=null;filePreviewContent="";async loadFileBrowser(e){if(!e)return;const t=this.$("fileBrowserTree"),s=this.$("fileBrowserStatus");if(t){t.innerHTML='<div class="file-browser-loading">Loading files...</div>';try{const n=await fetch(`/api/sessions/${e}/files?depth=5&showHidden=false`);if(!n.ok)throw new Error("Failed to load files");const i=await n.json();if(!i.success)throw new Error(i.error||"Failed to load files");if(this.fileBrowserData=i.data,this.renderFileBrowserTree(),s){const{totalFiles:o,totalDirectories:l,truncated:a}=i.data;s.textContent=`${o} files, ${l} dirs${a?" (truncated)":""}`}}catch(n){t.innerHTML=`<div class="file-browser-empty">Failed to load files: ${escapeHtml(n.message)}</div>`}}}renderFileBrowserTree(){const e=this.$("fileBrowserTree");if(!e||!this.fileBrowserData)return;const{tree:t}=this.fileBrowserData;if(!t||t.length===0){e.innerHTML='<div class="file-browser-empty">No files found</div>';return}const s=[],n=this.fileBrowserFilter.toLowerCase(),i=(o,l)=>{const a=o.type==="directory",r=this.fileBrowserExpandedDirs.has(o.path),c=!n||o.name.toLowerCase().includes(n);let d=!1;a&&n&&o.children&&(d=this.hasMatchingChild(o,n));const h=!(c||d)&&n?" hidden-by-filter":"",m=a?r?"\u{1F4C2}":"\u{1F4C1}":this.getFileIcon(o.extension),p=a?`<span class="file-tree-expand${r?" expanded":""}">\u25B6</span>`:'<span class="file-tree-expand"></span>',g=!a&&o.size!==void 0?`<span class="file-tree-size">${this.formatFileSize(o.size)}</span>`:"",f=a?"file-tree-name directory":"file-tree-name";if(s.push(`
311
311
  <div class="file-tree-item${h}" data-path="${escapeHtml(o.path)}" data-type="${o.type}" data-depth="${l}">
312
312
  ${p}
313
313
  <span class="file-tree-icon">${m}</span>
314
314
  <span class="${f}">${escapeHtml(o.name)}</span>
315
315
  ${g}
316
316
  </div>
317
- `),a&&r&&o.children)for(const S of o.children)i(S,l+1)};for(const o of t)i(o,0);e.innerHTML=s.join(""),e.querySelectorAll(".file-tree-item").forEach(o=>{o.addEventListener("click",()=>{const l=o.dataset.path;o.dataset.type==="directory"?this.toggleFileBrowserFolder(l):this.openFilePreview(l)})})}hasMatchingChild(e,t){if(!e.children)return!1;for(const s of e.children)if(s.name.toLowerCase().includes(t)||s.type==="directory"&&this.hasMatchingChild(s,t))return!0;return!1}toggleFileBrowserFolder(e){this.fileBrowserExpandedDirs.has(e)?this.fileBrowserExpandedDirs.delete(e):this.fileBrowserExpandedDirs.add(e),this.renderFileBrowserTree()}filterFileBrowser(e){this.fileBrowserFilter=e,e&&this.expandAllDirectories(this.fileBrowserData?.tree||[]),this.renderFileBrowserTree()}expandAllDirectories(e){for(const t of e)t.type==="directory"&&(this.fileBrowserExpandedDirs.add(t.path),t.children&&this.expandAllDirectories(t.children))}collapseAllDirectories(){this.fileBrowserExpandedDirs.clear()}toggleFileBrowserExpand(){this.fileBrowserAllExpanded=!this.fileBrowserAllExpanded;const e=this.$("fileBrowserExpandBtn");this.fileBrowserAllExpanded?(this.expandAllDirectories(this.fileBrowserData?.tree||[]),e&&(e.innerHTML="\u229F")):(this.collapseAllDirectories(),e&&(e.innerHTML="\u229E")),this.renderFileBrowserTree()}refreshFileBrowser(){if(this.activeSessionId){this.fileBrowserExpandedDirs.clear(),this.fileBrowserFilter="",this.fileBrowserAllExpanded=!1;const e=this.$("fileBrowserSearch");e&&(e.value=""),this.loadFileBrowser(this.activeSessionId)}}closeFileBrowserPanel(){const e=this.$("fileBrowserPanel");e&&e.classList.remove("visible");const t=this.loadAppSettingsFromStorage();t.showFileBrowser=!1,this.saveAppSettingsToStorage(t)}async openFilePreview(e){if(!this.activeSessionId||!e)return;const t=this.$("filePreviewOverlay"),s=this.$("filePreviewTitle"),n=this.$("filePreviewBody"),i=this.$("filePreviewFooter");if(!(!t||!n)){t.classList.add("visible"),s.textContent=e,n.innerHTML='<div class="binary-message">Loading...</div>',i.textContent="";try{const o=await fetch(`/api/sessions/${this.activeSessionId}/file-content?path=${encodeURIComponent(e)}&lines=500`);if(!o.ok)throw new Error("Failed to load file");const l=await o.json();if(!l.success)throw new Error(l.error||"Failed to load file");const a=l.data;if(a.type==="image")n.innerHTML=`<img src="${a.url}" alt="${escapeHtml(e)}">`,i.textContent=`${this.formatFileSize(a.size)} \u2022 ${a.extension}`;else if(a.type==="video")n.innerHTML=`<video src="${a.url}" controls autoplay></video>`,i.textContent=`${this.formatFileSize(a.size)} \u2022 ${a.extension}`;else if(a.type==="binary")n.innerHTML=`<div class="binary-message">Binary file (${this.formatFileSize(a.size)})<br>Cannot preview</div>`,i.textContent=a.extension||"binary";else{this.filePreviewContent=a.content,n.innerHTML=`<pre><code>${escapeHtml(a.content)}</code></pre>`;const r=a.truncated?` (showing 500/${a.totalLines} lines)`:"";i.textContent=`${a.totalLines} lines \u2022 ${this.formatFileSize(a.size)}${r}`}}catch(o){n.innerHTML=`<div class="binary-message">Error: ${escapeHtml(o.message)}</div>`}}}closeFilePreview(){const e=this.$("filePreviewOverlay");e&&e.classList.remove("visible"),this.filePreviewContent=""}copyFilePreviewContent(){this.filePreviewContent&&navigator.clipboard.writeText(this.filePreviewContent).then(()=>{this.showToast("Copied to clipboard","success")}).catch(()=>{this.showToast("Failed to copy","error")})}getFileIcon(e){return e&&{ts:"\u{1F4D8}",tsx:"\u{1F4D8}",js:"\u{1F4D2}",jsx:"\u{1F4D2}",mjs:"\u{1F4D2}",cjs:"\u{1F4D2}",py:"\u{1F40D}",pyx:"\u{1F40D}",pyw:"\u{1F40D}",rs:"\u{1F980}",go:"\u{1F439}",c:"\u2699\uFE0F",cpp:"\u2699\uFE0F",h:"\u2699\uFE0F",hpp:"\u2699\uFE0F",html:"\u{1F310}",htm:"\u{1F310}",css:"\u{1F3A8}",scss:"\u{1F3A8}",sass:"\u{1F3A8}",less:"\u{1F3A8}",json:"\u{1F4CB}",yaml:"\u{1F4CB}",yml:"\u{1F4CB}",xml:"\u{1F4CB}",toml:"\u{1F4CB}",csv:"\u{1F4CB}",md:"\u{1F4DD}",markdown:"\u{1F4DD}",txt:"\u{1F4DD}",rst:"\u{1F4DD}",png:"\u{1F5BC}\uFE0F",jpg:"\u{1F5BC}\uFE0F",jpeg:"\u{1F5BC}\uFE0F",gif:"\u{1F5BC}\uFE0F",svg:"\u{1F5BC}\uFE0F",webp:"\u{1F5BC}\uFE0F",ico:"\u{1F5BC}\uFE0F",bmp:"\u{1F5BC}\uFE0F",mp4:"\u{1F3AC}",webm:"\u{1F3AC}",mov:"\u{1F3AC}",mp3:"\u{1F3B5}",wav:"\u{1F3B5}",ogg:"\u{1F3B5}",sh:"\u{1F4BB}",bash:"\u{1F4BB}",zsh:"\u{1F4BB}",env:"\u{1F510}",gitignore:"\u{1F6AB}",dockerfile:"\u{1F433}",lock:"\u{1F512}"}[e.toLowerCase()]||"\u{1F4C4}"}formatFileSize(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}openLogViewerWindow(e,t){if(t=t||this.activeSessionId,!t)return;const s=`${t}-${e.replace(/[^a-zA-Z0-9]/g,"_")}`;if(this.logViewerWindows.has(s)){const d=this.logViewerWindows.get(s);d.element.style.zIndex=++this.logViewerWindowZIndex;return}const n=this.logViewerWindows.size,i=100+n%5*30,o=100+n%5*30,l=e.split("/").pop(),a=document.createElement("div");a.className="log-viewer-window",a.id=`log-viewer-window-${s}`,a.style.left=`${i}px`,a.style.top=`${o}px`,a.style.zIndex=++this.logViewerWindowZIndex,a.innerHTML=`
317
+ `),a&&r&&o.children)for(const S of o.children)i(S,l+1)};for(const o of t)i(o,0);e.innerHTML=s.join(""),e.querySelectorAll(".file-tree-item").forEach(o=>{o.addEventListener("click",()=>{const l=o.dataset.path;o.dataset.type==="directory"?this.toggleFileBrowserFolder(l):this.openFilePreview(l)})})}hasMatchingChild(e,t){if(!e.children)return!1;for(const s of e.children)if(s.name.toLowerCase().includes(t)||s.type==="directory"&&this.hasMatchingChild(s,t))return!0;return!1}toggleFileBrowserFolder(e){this.fileBrowserExpandedDirs.has(e)?this.fileBrowserExpandedDirs.delete(e):this.fileBrowserExpandedDirs.add(e),this.renderFileBrowserTree()}filterFileBrowser(e){this.fileBrowserFilter=e,e&&this.expandAllDirectories(this.fileBrowserData?.tree||[]),this.renderFileBrowserTree()}expandAllDirectories(e){for(const t of e)t.type==="directory"&&(this.fileBrowserExpandedDirs.add(t.path),t.children&&this.expandAllDirectories(t.children))}collapseAllDirectories(){this.fileBrowserExpandedDirs.clear()}toggleFileBrowserExpand(){this.fileBrowserAllExpanded=!this.fileBrowserAllExpanded;const e=this.$("fileBrowserExpandBtn");this.fileBrowserAllExpanded?(this.expandAllDirectories(this.fileBrowserData?.tree||[]),e&&(e.innerHTML="\u229F")):(this.collapseAllDirectories(),e&&(e.innerHTML="\u229E")),this.renderFileBrowserTree()}refreshFileBrowser(){if(this.activeSessionId){this.fileBrowserExpandedDirs.clear(),this.fileBrowserFilter="",this.fileBrowserAllExpanded=!1;const e=this.$("fileBrowserSearch");e&&(e.value=""),this.loadFileBrowser(this.activeSessionId)}}closeFileBrowserPanel(){const e=this.$("fileBrowserPanel");if(e&&(e.classList.remove("visible"),e.style.left="",e.style.top="",e.style.bottom="",e.style.right=""),this.fileBrowserDragListeners){const s=this.fileBrowserDragListeners;document.removeEventListener("mousemove",s.move),document.removeEventListener("mouseup",s.up),document.removeEventListener("touchmove",s.touchMove),document.removeEventListener("touchend",s.up),document.removeEventListener("touchcancel",s.up),s.handle&&(s.handle.removeEventListener("mousedown",s.handleMouseDown),s.handle.removeEventListener("touchstart",s.handleTouchStart),s._onFirstDrag&&(s.handle.removeEventListener("mousedown",s._onFirstDrag),s.handle.removeEventListener("touchstart",s._onFirstDrag))),this.fileBrowserDragListeners=null}const t=this.loadAppSettingsFromStorage();t.showFileBrowser=!1,this.saveAppSettingsToStorage(t)}async openFilePreview(e){if(!this.activeSessionId||!e)return;const t=this.$("filePreviewOverlay"),s=this.$("filePreviewTitle"),n=this.$("filePreviewBody"),i=this.$("filePreviewFooter");if(!(!t||!n)){t.classList.add("visible"),s.textContent=e,n.innerHTML='<div class="binary-message">Loading...</div>',i.textContent="";try{const o=await fetch(`/api/sessions/${this.activeSessionId}/file-content?path=${encodeURIComponent(e)}&lines=500`);if(!o.ok)throw new Error("Failed to load file");const l=await o.json();if(!l.success)throw new Error(l.error||"Failed to load file");const a=l.data;if(a.type==="image")n.innerHTML=`<img src="${a.url}" alt="${escapeHtml(e)}">`,i.textContent=`${this.formatFileSize(a.size)} \u2022 ${a.extension}`;else if(a.type==="video")n.innerHTML=`<video src="${a.url}" controls autoplay></video>`,i.textContent=`${this.formatFileSize(a.size)} \u2022 ${a.extension}`;else if(a.type==="binary")n.innerHTML=`<div class="binary-message">Binary file (${this.formatFileSize(a.size)})<br>Cannot preview</div>`,i.textContent=a.extension||"binary";else{this.filePreviewContent=a.content,n.innerHTML=`<pre><code>${escapeHtml(a.content)}</code></pre>`;const r=a.truncated?` (showing 500/${a.totalLines} lines)`:"";i.textContent=`${a.totalLines} lines \u2022 ${this.formatFileSize(a.size)}${r}`}}catch(o){n.innerHTML=`<div class="binary-message">Error: ${escapeHtml(o.message)}</div>`}}}closeFilePreview(){const e=this.$("filePreviewOverlay");e&&e.classList.remove("visible"),this.filePreviewContent=""}copyFilePreviewContent(){this.filePreviewContent&&navigator.clipboard.writeText(this.filePreviewContent).then(()=>{this.showToast("Copied to clipboard","success")}).catch(()=>{this.showToast("Failed to copy","error")})}getFileIcon(e){return e&&{ts:"\u{1F4D8}",tsx:"\u{1F4D8}",js:"\u{1F4D2}",jsx:"\u{1F4D2}",mjs:"\u{1F4D2}",cjs:"\u{1F4D2}",py:"\u{1F40D}",pyx:"\u{1F40D}",pyw:"\u{1F40D}",rs:"\u{1F980}",go:"\u{1F439}",c:"\u2699\uFE0F",cpp:"\u2699\uFE0F",h:"\u2699\uFE0F",hpp:"\u2699\uFE0F",html:"\u{1F310}",htm:"\u{1F310}",css:"\u{1F3A8}",scss:"\u{1F3A8}",sass:"\u{1F3A8}",less:"\u{1F3A8}",json:"\u{1F4CB}",yaml:"\u{1F4CB}",yml:"\u{1F4CB}",xml:"\u{1F4CB}",toml:"\u{1F4CB}",csv:"\u{1F4CB}",md:"\u{1F4DD}",markdown:"\u{1F4DD}",txt:"\u{1F4DD}",rst:"\u{1F4DD}",png:"\u{1F5BC}\uFE0F",jpg:"\u{1F5BC}\uFE0F",jpeg:"\u{1F5BC}\uFE0F",gif:"\u{1F5BC}\uFE0F",svg:"\u{1F5BC}\uFE0F",webp:"\u{1F5BC}\uFE0F",ico:"\u{1F5BC}\uFE0F",bmp:"\u{1F5BC}\uFE0F",mp4:"\u{1F3AC}",webm:"\u{1F3AC}",mov:"\u{1F3AC}",mp3:"\u{1F3B5}",wav:"\u{1F3B5}",ogg:"\u{1F3B5}",sh:"\u{1F4BB}",bash:"\u{1F4BB}",zsh:"\u{1F4BB}",env:"\u{1F510}",gitignore:"\u{1F6AB}",dockerfile:"\u{1F433}",lock:"\u{1F512}"}[e.toLowerCase()]||"\u{1F4C4}"}formatFileSize(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}openLogViewerWindow(e,t){if(t=t||this.activeSessionId,!t)return;const s=`${t}-${e.replace(/[^a-zA-Z0-9]/g,"_")}`;if(this.logViewerWindows.has(s)){const d=this.logViewerWindows.get(s);d.element.style.zIndex=++this.logViewerWindowZIndex;return}const n=this.logViewerWindows.size,i=100+n%5*30,o=100+n%5*30,l=e.split("/").pop(),a=document.createElement("div");a.className="log-viewer-window",a.id=`log-viewer-window-${s}`,a.style.left=`${i}px`,a.style.top=`${o}px`,a.style.zIndex=++this.logViewerWindowZIndex,a.innerHTML=`
318
318
  <div class="log-viewer-window-header">
319
319
  <div class="log-viewer-window-title" title="${escapeHtml(e)}">
320
320
  <span class="icon">\u{1F4C4}</span>
Binary file
Binary file
@@ -52,7 +52,7 @@ const TITLE_FLASH_INTERVAL_MS = 1500; // Title flash rate
52
52
  const BROWSER_NOTIF_RATE_LIMIT_MS = 3000; // Rate limit for browser notifications
53
53
  const AUTO_CLOSE_NOTIFICATION_MS = 8000; // Auto-close browser notifications
54
54
  const THROTTLE_DELAY_MS = 100; // General UI throttle delay
55
- const TERMINAL_CHUNK_SIZE = 128 * 1024; // 128KB chunks for terminal data
55
+ const TERMINAL_CHUNK_SIZE = 32 * 1024; // 32KB chunks for terminal data (smaller to avoid WebGL GPU stalls)
56
56
  const TERMINAL_TAIL_SIZE = 256 * 1024; // 256KB tail for initial load
57
57
  const SYNC_WAIT_TIMEOUT_MS = 50; // Wait timeout for terminal sync
58
58
  const STATS_POLLING_INTERVAL_MS = 2000; // System stats polling
Binary file