aicodeman 0.3.5 → 0.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-checker-base.d.ts.map +1 -1
- package/dist/ai-checker-base.js +2 -2
- package/dist/ai-checker-base.js.map +1 -1
- package/dist/ai-idle-checker.d.ts.map +1 -1
- package/dist/ai-idle-checker.js +5 -5
- package/dist/ai-idle-checker.js.map +1 -1
- package/dist/ai-plan-checker.d.ts.map +1 -1
- package/dist/ai-plan-checker.js +5 -5
- package/dist/ai-plan-checker.js.map +1 -1
- package/dist/config/ai-defaults.d.ts +20 -4
- package/dist/config/ai-defaults.d.ts.map +1 -1
- package/dist/config/ai-defaults.js +32 -4
- package/dist/config/ai-defaults.js.map +1 -1
- package/dist/config/server-timing.d.ts +6 -0
- package/dist/config/server-timing.d.ts.map +1 -1
- package/dist/config/server-timing.js +9 -0
- package/dist/config/server-timing.js.map +1 -1
- package/dist/file-stream-manager.d.ts.map +1 -1
- package/dist/file-stream-manager.js +3 -2
- package/dist/file-stream-manager.js.map +1 -1
- package/dist/ralph-config.d.ts.map +1 -1
- package/dist/ralph-config.js +3 -4
- package/dist/ralph-config.js.map +1 -1
- package/dist/ralph-stall-detector.d.ts.map +1 -1
- package/dist/ralph-stall-detector.js +2 -1
- package/dist/ralph-stall-detector.js.map +1 -1
- package/dist/ralph-tracker.d.ts.map +1 -1
- package/dist/ralph-tracker.js +17 -22
- package/dist/ralph-tracker.js.map +1 -1
- package/dist/respawn-controller.d.ts.map +1 -1
- package/dist/respawn-controller.js +5 -5
- package/dist/respawn-controller.js.map +1 -1
- package/dist/run-summary.d.ts.map +1 -1
- package/dist/run-summary.js +2 -1
- package/dist/run-summary.js.map +1 -1
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +3 -6
- package/dist/session.js.map +1 -1
- package/dist/subagent-watcher.d.ts.map +1 -1
- package/dist/subagent-watcher.js +2 -1
- package/dist/subagent-watcher.js.map +1 -1
- package/dist/task-tracker.d.ts.map +1 -1
- package/dist/task-tracker.js +2 -1
- package/dist/task-tracker.js.map +1 -1
- package/dist/types/plan.d.ts +2 -4
- package/dist/types/plan.d.ts.map +1 -1
- package/dist/types/plan.js +1 -1
- package/dist/utils/index.d.ts +2 -2
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +2 -2
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/regex-patterns.d.ts +5 -0
- package/dist/utils/regex-patterns.d.ts.map +1 -1
- package/dist/utils/regex-patterns.js +11 -0
- package/dist/utils/regex-patterns.js.map +1 -1
- package/dist/utils/token-validation.d.ts +1 -27
- package/dist/utils/token-validation.d.ts.map +1 -1
- package/dist/utils/token-validation.js +1 -47
- package/dist/utils/token-validation.js.map +1 -1
- package/dist/web/public/api-client.js.gz +0 -0
- package/dist/web/public/app.js +26 -26
- package/dist/web/public/app.js.br +0 -0
- package/dist/web/public/app.js.gz +0 -0
- package/dist/web/public/constants.js +2 -2
- package/dist/web/public/constants.js.br +0 -0
- package/dist/web/public/constants.js.gz +0 -0
- package/dist/web/public/index.html.gz +0 -0
- package/dist/web/public/keyboard-accessory.js.gz +0 -0
- package/dist/web/public/mobile-handlers.js.gz +0 -0
- package/dist/web/public/mobile.css.gz +0 -0
- package/dist/web/public/notification-manager.js.gz +0 -0
- package/dist/web/public/ralph-wizard.js.gz +0 -0
- package/dist/web/public/styles.css.gz +0 -0
- package/dist/web/public/subagent-windows.js +118 -18
- package/dist/web/public/subagent-windows.js.br +0 -0
- package/dist/web/public/subagent-windows.js.gz +0 -0
- package/dist/web/public/sw.js.gz +0 -0
- package/dist/web/public/upload.html.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-zerolag-input.js.gz +0 -0
- package/dist/web/public/vendor/xterm.css.gz +0 -0
- package/dist/web/public/vendor/xterm.min.js.gz +0 -0
- package/dist/web/public/voice-input.js.gz +0 -0
- package/dist/web/routes/respawn-routes.d.ts.map +1 -1
- package/dist/web/routes/respawn-routes.js +5 -5
- package/dist/web/routes/respawn-routes.js.map +1 -1
- package/dist/web/server.d.ts +10 -0
- package/dist/web/server.d.ts.map +1 -1
- package/dist/web/server.js +66 -14
- package/dist/web/server.js.map +1 -1
- package/package.json +1 -1
package/dist/web/public/app.js
CHANGED
|
@@ -4,22 +4,22 @@
|
|
|
4
4
|
`)}))}catch{}},2e3),window.addEventListener("error",v=>{_crashDiag.log(`ERROR: ${v.message} at ${v.filename}:${v.lineno}`),console.error("[CRASH-DIAG] Uncaught error:",v.message,`
|
|
5
5
|
File:`,v.filename,":",v.lineno,":",v.colno,`
|
|
6
6
|
Stack:`,v.error?.stack)}),window.addEventListener("unhandledrejection",v=>{_crashDiag.log(`UNHANDLED: ${v.reason?.message||v.reason}`),console.error("[CRASH-DIAG] Unhandled promise rejection:",v.reason?.message||v.reason,`
|
|
7
|
-
Stack:`,v.reason?.stack)}),typeof PerformanceObserver<"u")try{new PerformanceObserver(e=>{for(const t of e.getEntries())t.duration>200&&(_crashDiag.log(`LONG_TASK: ${t.duration.toFixed(0)}ms`),console.warn(`[CRASH-DIAG] Long task: ${t.duration.toFixed(0)}ms (type: ${t.entryType}, name: ${t.name})`))}).observe({type:"longtask",buffered:!0})}catch{}const _origGetContext=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(v,...e){const t=_origGetContext.call(this,v,...e);return(v==="webgl2"||v==="webgl")&&(this.addEventListener("webglcontextlost",s=>{_crashDiag.log(`WEBGL_LOST: ${this.width}x${this.height}`),console.error("[CRASH-DIAG] WebGL context LOST on canvas",this.width,"x",this.height,"\u2014 prevented:",s.defaultPrevented)}),this.addEventListener("webglcontextrestored",()=>{_crashDiag.log("WEBGL_RESTORED"),console.warn("[CRASH-DIAG] WebGL context restored")})),t};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,new URLSearchParams(location.search).has("webgl")&&typeof WebglAddon<"u")try{this._webglAddon=new WebglAddon.WebglAddon,this._webglAddon.onContextLoss(()=>{console.error("[CRASH-DIAG] WebGL context LOST \u2014 falling back to canvas renderer"),this._webglAddon.dispose(),this._webglAddon=null}),this.terminal.loadAddon(this._webglAddon),console.log("[CRASH-DIAG] WebGL renderer enabled via ?webgl param")}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,console.debug("[LinkProvider] Checking line:",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&&console.debug("[LinkProvider] Found links:",a.map(m=>m.text)),n(a.length>0?a:void 0)}}),console.log("[LinkProvider] File path link provider registered")}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 t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,s=t?.flickerFilterEnabled??!1,i=!(t?.mode==="shell")&&/\x1b\[\d{1,2}A/.test(e);if(i||this.flickerFilterActive&&!s){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,i?(this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS)):this.flickerFilterTimeout||(this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS)),this.flickerFilterBuffer.length>256*1024&&(this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flushFlickerBuffer());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 o=this.pendingWrites.join(""),l=o.includes(DEC_SYNC_START),a=o.includes(DEC_SYNC_END);if(l&&!a){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}}}):t.mode==="shell"?(this._localEchoOverlay.clear(),this._localEchoEnabled=!1):this._localEchoOverlay.setPrompt({type:"character",char:"\u276F",offset:2}))}flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=performance.now(),t=this.pendingWrites.reduce((o,l)=>o+l.length,0);t>16384&&_crashDiag.log(`FLUSH: ${(t/1024).toFixed(0)}KB`);const s=this.pendingWrites.join("");this.pendingWrites=[];const n=extractSyncSegments(s);for(const o of n)if(o){const l=o.startsWith(DEC_SYNC_START)?o.slice(DEC_SYNC_START.length):o;l&&this.terminal.write(l)}const i=performance.now()-e;if(i>100&&console.warn(`[CRASH-DIAG] flushPendingWrites took ${i.toFixed(0)}ms (${t} bytes)`),this._wasAtBottomBeforeWrite&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const o=this._localEchoOverlay,l=this;this.terminal.write("",()=>{if(!l._tabCompletionSessionId)return;o.resetBufferDetection();const a=o.detectBufferText();a?a===l._tabCompletionBaseText?(o.undoDetection(),l._tabCompletionRetries=(l._tabCompletionRetries||0)+1,l._tabCompletionRetries>60&&(l._tabCompletionSessionId=null,l._tabCompletionRetries=0)):(l._tabCompletionSessionId=null,l._tabCompletionRetries=0,l._tabCompletionBaseText=null,l._tabCompletionFallback&&(clearTimeout(l._tabCompletionFallback),l._tabCompletionFallback=null),o.rerender()):(l._tabCompletionRetries=(l._tabCompletionRetries||0)+1,l._tabCompletionRetries>60&&(l._tabCompletionSessionId=null,l._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=performance.now();let a=0;const r=()=>{if(o>=n.length){const h=performance.now()-l;console.log(`[CRASH-DIAG] chunkedTerminalWrite complete: ${n.length} bytes in ${a} chunks, ${h.toFixed(0)}ms total`),requestAnimationFrame(i);return}const c=performance.now(),d=n.slice(o,o+t);this.terminal.write(d);const u=performance.now()-c;a++,u>50&&console.warn(`[CRASH-DIAG] chunk #${a} write took ${u.toFixed(0)}ms (${d.length} bytes at offset ${o})`),o+=t,requestAnimationFrame(r)};requestAnimationFrame(r)})}_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(l){console.error(`[SSE] Error handling ${s}:`,l)}})}}for(const[s]of _SSE_HANDLER_MAP)t(s,this._sseHandlerWrappers.get(s))}_onInit(e){_crashDiag.log(`INIT: ${e.sessions?.length||0} sessions`),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&&(e.data.length>32768&&_crashDiag.log(`TERMINAL: ${(e.data.length/1024).toFixed(0)}KB`),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(e){console.error("needsRefresh reload failed:",e)}}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(t){console.error("clearTerminal refresh failed:",t)}}_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){console.log("[Image Detected]",e),this.openImagePopup(e)}_onTunnelStarted(e){console.log("[Tunnel] Started:",e.url),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(){console.log("[Tunnel] Stopped"),this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this.closeTunnelQR()}_onTunnelProgress(e){console.log("[Tunnel] Progress:",e.message);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){console.warn("[Tunnel] Error:",e.message),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){console.log("[Plan Subagent]",e),this.handlePlanSubagentEvent(e)}_onPlanProgress(e){console.log("[Plan Progress]",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){console.log("[Plan Started]",e),this.activePlanOrchestratorId=e.orchestratorId,this.planGenerationStopped=!1,this.renderMonitorPlanAgents()}_onPlanCancelled(e){console.log("[Plan Cancelled]",e),this.activePlanOrchestratorId===e.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}_onPlanCompleted(e){console.log("[Plan Completed]",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(e){console.error("Failed to load state:",e)}}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 T=a.querySelector(".tab-name");T&&T.textContent!==d&&(T.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 b=a.querySelector(".tab-subagent-badge"),E=this.minimizedSubagents.get(o)?.size||0,C=b?parseInt(b.querySelector(".subagent-count")?.textContent||"0"):0;if(E!==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()||"",T=(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)}"`:""}>
|
|
7
|
+
Stack:`,v.reason?.stack)}),typeof PerformanceObserver<"u")try{new PerformanceObserver(e=>{for(const t of e.getEntries())t.duration>200&&(_crashDiag.log(`LONG_TASK: ${t.duration.toFixed(0)}ms`),console.warn(`[CRASH-DIAG] Long task: ${t.duration.toFixed(0)}ms (type: ${t.entryType}, name: ${t.name})`))}).observe({type:"longtask",buffered:!0})}catch{}const _origGetContext=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(v,...e){const t=_origGetContext.call(this,v,...e);return(v==="webgl2"||v==="webgl")&&(this.addEventListener("webglcontextlost",s=>{_crashDiag.log(`WEBGL_LOST: ${this.width}x${this.height}`),console.error("[CRASH-DIAG] WebGL context LOST on canvas",this.width,"x",this.height,"\u2014 prevented:",s.defaultPrevented)}),this.addEventListener("webglcontextrestored",()=>{_crashDiag.log("WEBGL_RESTORED"),console.warn("[CRASH-DIAG] WebGL context restored")})),t};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 c=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(c),this.terminal.unicode.activeVersion="11"}catch{}const t=document.getElementById("terminalContainer");if(this.terminal.open(t),this._webglAddon=null,!(MobileDetection.getDeviceType()!=="desktop")&&!new URLSearchParams(location.search).has("nowebgl")&&typeof WebglAddon<"u")try{this._webglAddon=new WebglAddon.WebglAddon,this._webglAddon.onContextLoss(()=>{console.error("[CRASH-DIAG] WebGL context LOST \u2014 falling back to canvas renderer"),this._webglAddon.dispose(),this._webglAddon=null}),this.terminal.loadAddon(this._webglAddon),console.log("[CRASH-DIAG] WebGL renderer enabled via ?webgl param")}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",c=>{c.preventDefault();const d=Math.round(c.deltaY/25)||(c.deltaY>0?1:-1);this.terminal.scrollLines(d)},{passive:!1}),!(MobileDetection.isTouchDevice()&&window.innerWidth<1024)){let c=0,d=0,u=0,h=0,m=null,p=!1;const g=t.querySelector(".xterm-viewport"),S=f=>{if(!g)return;const w=h?(f-h)/16.67:1;h=f,p?(d!==0&&(g.scrollTop+=d,d=0),m=requestAnimationFrame(S)):Math.abs(u)>.1?(g.scrollTop+=u*w,u*=.94,m=requestAnimationFrame(S)):(m=null,u=0)};t.addEventListener("touchstart",f=>{f.touches.length===1&&(c=f.touches[0].clientY,d=0,u=0,p=!0,h=0,m||(m=requestAnimationFrame(S)))},{passive:!0}),t.addEventListener("touchmove",f=>{if(f.touches.length===1&&p){const w=f.touches[0].clientY,E=c-w;d+=E,u=E*1.2,c=w}},{passive:!0}),t.addEventListener("touchend",()=>{p=!1},{passive:!0}),t.addEventListener("touchcancel",()=>{p=!1,u=0},{passive:!0})}this.showWelcome(),this._resizeTimeout=null,this._lastResizeDims=null;const o=40,l=10,a=()=>{this._resizeTimeout||(this._resizeTimeout=setTimeout(()=>{if(this._resizeTimeout=null,this.fitAddon){this.fitAddon.fit();const c=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;if(this.activeSessionId&&!c){const d=this.fitAddon.proposeDimensions(),u=d?Math.max(d.cols,o):o,h=d?Math.max(d.rows,l):l;(!this._lastResizeDims||u!==this._lastResizeDims.cols||h!==this._lastResizeDims.rows)&&(this._lastResizeDims={cols:u,rows:h},fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:u,rows:h})}).catch(()=>{}))}}this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},100))};window.addEventListener("resize",a),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(a),this.terminalResizeObserver.observe(t),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const r=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const c=this._pendingInput,d=this.activeSessionId;this._pendingInput="",this._sendInputAsync(d,c)}};this.terminal.onData(c=>{if(this.activeSessionId){if(/^\x1b\[[\?>=]?[\d;]*[cnR]$/.test(c))return;if(this._localEchoEnabled){if(c==="\x7F"){if(this._localEchoOverlay?.removeChar()==="flushed"){const{count:h,text:m}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(h===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,h),this._flushedTexts?.set(this.activeSessionId,m))),this._pendingInput+=c,r()}return}if(/^[\r\n]+$/.test(c)){const u=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),u&&(this._pendingInput+=u,r()),setTimeout(()=>{this._pendingInput+="\r",r()},80);return}if(c.length>1&&c.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(c);return}if(c.charCodeAt(0)<32){if(c.length>1&&c.charCodeAt(0)===27){this._pendingInput+=c,r();return}if(this._restoringFlushedState){this._pendingInput+=c,r();return}if(c===" "){const h=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),h&&(this._pendingInput+=h),this._pendingInput+=c,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let m="";try{const g=this._localEchoOverlay?.findPrompt?.();if(g){const S=this.terminal.buffer.active,f=S.getLine(S.viewportY+g.row);f&&(m=f.translateToString(!0).slice(g.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=m,r(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const p=this;this._tabCompletionFallback=setTimeout(()=>{if(p._tabCompletionFallback=null,!p._tabCompletionSessionId||p._tabCompletionSessionId!==p.activeSessionId)return;const g=p._localEchoOverlay;!g||g.pendingText||p.terminal.write("",()=>{if(!p._tabCompletionSessionId)return;g.resetBufferDetection();const S=g.detectBufferText();S&&S!==p._tabCompletionBaseText&&(p._tabCompletionSessionId=null,p._tabCompletionRetries=0,p._tabCompletionBaseText=null,g.rerender())})},300);return}const u=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),u&&(this._pendingInput+=u),this._pendingInput+=c,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),r();return}if(c.length===1&&c.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(c);return}}if(this._pendingInput+=c,c.charCodeAt(0)<32||c.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),r();return}const d=performance.now();d-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=d,r()):(this._lastKeystrokeTime=d,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(r,0)))}})}registerFilePathLinkProvider(){const e=this;let t=-1;this.terminal.registerLinkProvider({provideLinks(s,n){s!==t&&(t=s,console.debug("[LinkProvider] Checking line:",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(S=>S.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(S,f){e.openLogViewerWindow(f,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&&console.debug("[LinkProvider] Found links:",a.map(m=>m.text)),n(a.length>0?a:void 0)}}),console.log("[LinkProvider] File path link provider registered")}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 t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,s=t?.flickerFilterEnabled??!1,i=!(t?.mode==="shell")&&/\x1b\[\d{1,2}A/.test(e);if(i||this.flickerFilterActive&&!s){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,i?(this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS)):this.flickerFilterTimeout||(this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS)),this.flickerFilterBuffer.length>256*1024&&(this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flushFlickerBuffer());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 o=this.pendingWrites.join(""),l=o.includes(DEC_SYNC_START),a=o.includes(DEC_SYNC_END);if(l&&!a){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}}}):t.mode==="shell"?(this._localEchoOverlay.clear(),this._localEchoEnabled=!1):this._localEchoOverlay.setPrompt({type:"character",char:"\u276F",offset:2}))}flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=performance.now(),t=this.pendingWrites.reduce((r,c)=>r+c.length,0);t>16384&&_crashDiag.log(`FLUSH: ${(t/1024).toFixed(0)}KB`);const s=this.pendingWrites.join("");this.pendingWrites=[];const n=extractSyncSegments(s),i=65536;let o=0,l=!1;for(let r=0;r<n.length;r++){const c=n[r];if(!c)continue;const d=c.startsWith(DEC_SYNC_START)?c.slice(DEC_SYNC_START.length):c;if(d){if(o>0&&o+d.length>i){const u=n.slice(r).map(h=>h?h.startsWith(DEC_SYNC_START)?h.slice(DEC_SYNC_START.length):h:"").filter(Boolean).join("");u&&(this.pendingWrites.push(u),this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1}))),l=!0;break}this.terminal.write(d),o+=d.length}}const a=performance.now()-e;if((a>100||l)&&console.warn(`[CRASH-DIAG] flushPendingWrites: ${a.toFixed(0)}ms, ${(o/1024).toFixed(0)}KB written${l?", rest deferred":""} (total ${(t/1024).toFixed(0)}KB)`),this._wasAtBottomBeforeWrite&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const r=this._localEchoOverlay,c=this;this.terminal.write("",()=>{if(!c._tabCompletionSessionId)return;r.resetBufferDetection();const d=r.detectBufferText();d?d===c._tabCompletionBaseText?(r.undoDetection(),c._tabCompletionRetries=(c._tabCompletionRetries||0)+1,c._tabCompletionRetries>60&&(c._tabCompletionSessionId=null,c._tabCompletionRetries=0)):(c._tabCompletionSessionId=null,c._tabCompletionRetries=0,c._tabCompletionBaseText=null,c._tabCompletionFallback&&(clearTimeout(c._tabCompletionFallback),c._tabCompletionFallback=null),r.rerender()):(c._tabCompletionRetries=(c._tabCompletionRetries||0)+1,c._tabCompletionRetries>60&&(c._tabCompletionSessionId=null,c._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=performance.now();let a=0;const r=()=>{if(o>=n.length){const h=performance.now()-l;console.log(`[CRASH-DIAG] chunkedTerminalWrite complete: ${n.length} bytes in ${a} chunks, ${h.toFixed(0)}ms total`),requestAnimationFrame(i);return}const c=performance.now(),d=n.slice(o,o+t);this.terminal.write(d);const u=performance.now()-c;a++,u>50&&console.warn(`[CRASH-DIAG] chunk #${a} write took ${u.toFixed(0)}ms (${d.length} bytes at offset ${o})`),o+=t,requestAnimationFrame(r)};requestAnimationFrame(r)})}_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(l){console.error(`[SSE] Error handling ${s}:`,l)}})}}for(const[s]of _SSE_HANDLER_MAP)t(s,this._sseHandlerWrappers.get(s))}_onInit(e){_crashDiag.log(`INIT: ${e.sessions?.length||0} sessions`),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){if(e.id===this.activeSessionId){if(e.data.length>32768&&_crashDiag.log(`TERMINAL: ${(e.data.length/1024).toFixed(0)}KB`),(this.pendingWrites?.reduce((s,n)=>s+n.length,0)||0)+(this.flickerFilterBuffer?.length||0)>131072){this._clientDropRecoveryTimer||(this._clientDropRecoveryTimer=setTimeout(()=>{this._clientDropRecoveryTimer=null,this._onSessionNeedsRefresh()},2e3));return}this.batchTerminalWrite(e.data)}}async _onSessionNeedsRefresh(){if(!(!this.activeSessionId||!this.terminal))try{const t=await(await fetch(`/api/sessions/${this.activeSessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`)).json();t.terminalBuffer&&(this.terminal.clear(),this.terminal.reset(),await this.chunkedTerminalWrite(t.terminalBuffer),this.terminal.scrollToBottom(),this._localEchoOverlay?.rerender(),this.activeSessionId&&this.sendResize(this.activeSessionId))}catch(e){console.error("needsRefresh reload failed:",e)}}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(t){console.error("clearTerminal refresh failed:",t)}}_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){console.log("[Image Detected]",e),this.openImagePopup(e)}_onTunnelStarted(e){console.log("[Tunnel] Started:",e.url),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(){console.log("[Tunnel] Stopped"),this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this.closeTunnelQR()}_onTunnelProgress(e){console.log("[Tunnel] Progress:",e.message);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){console.warn("[Tunnel] Error:",e.message),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){console.log("[Plan Subagent]",e),this.handlePlanSubagentEvent(e)}_onPlanProgress(e){console.log("[Plan Progress]",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){console.log("[Plan Started]",e),this.activePlanOrchestratorId=e.orchestratorId,this.planGenerationStopped=!1,this.renderMonitorPlanAgents()}_onPlanCancelled(e){console.log("[Plan Cancelled]",e),this.activePlanOrchestratorId===e.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}_onPlanCompleted(e){console.log("[Plan Completed]",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(e){console.error("Failed to load state:",e)}}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",S=a.classList.contains("tab-alert-action"),f=a.classList.contains("tab-alert-idle");p&&!S?(a.classList.add("tab-alert-action"),a.classList.remove("tab-alert-idle")):g&&!f?(a.classList.add("tab-alert-idle"),a.classList.remove("tab-alert-action")):!m&&(S||f)&&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 E=a.querySelector(".tab-name");E&&E.textContent!==d&&(E.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 b=a.querySelector(".tab-subagent-badge"),I=this.minimizedSubagents.get(o),T=I?.size||0;if(T>0&&b){const C=b.querySelector(".subagent-label"),_=T===1?"AGENT":`AGENTS (${T})`;C&&C.textContent!==_&&(C.textContent=_);const k=b.querySelector(".subagent-dropdown");if(k){const x=this.renderSubagentTabBadge(o,I),B=document.createElement("div");B.innerHTML=x;const L=B.querySelector(".subagent-dropdown");L&&(k.innerHTML=L.innerHTML)}}else if(T>0&&!b){const C=this.renderSubagentTabBadge(o,I),_=a.querySelector(".tab-gear");_&&_.insertAdjacentHTML("beforebegin",C)}else T===0&&b&&b.remove()}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),S=(p?.size||0)>0?this.renderSubagentTabBadge(n,p):"",f=i.workingDir&&i.workingDir.split("/").pop()||"",E=(this._tallTabsEnabled??!1)&&i.name&&f&&f!==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)}"`:""}>
|
|
8
8
|
<span class="tab-status ${l}" aria-hidden="true"></span>
|
|
9
9
|
<span class="tab-info">
|
|
10
10
|
<span class="tab-name-row">
|
|
11
11
|
${r==="shell"?'<span class="tab-mode shell" aria-hidden="true">sh</span>':r==="opencode"?'<span class="tab-mode opencode" aria-hidden="true">oc</span>':""}
|
|
12
12
|
<span class="tab-name" data-session-id="${n}">${escapeHtml(a)}</span>
|
|
13
13
|
</span>
|
|
14
|
-
${
|
|
14
|
+
${E?`<span class="tab-folder">\u{1F4C1} ${escapeHtml(f)}</span>`:""}
|
|
15
15
|
</span>
|
|
16
16
|
${u?`<span class="tab-badge" onclick="event.stopPropagation(); app.toggleTaskPanel()" aria-label="${d.running} running tasks">${d.running}</span>`:""}
|
|
17
|
-
${
|
|
17
|
+
${S}
|
|
18
18
|
<span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions('${escapeHtml(n)}')" title="Session options" aria-label="Session options" tabindex="0">⚙</span>
|
|
19
19
|
<span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession('${escapeHtml(n)}')" title="Close session" aria-label="Close session" tabindex="0">×</span>
|
|
20
|
-
</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=performance.now(),s=this.sessions.get(e)?.name||e.slice(0,8);_crashDiag.log(`SELECT: ${s}`),console.log(`[CRASH-DIAG] selectSession START: ${e.slice(0,8)}`);const n=++this._selectGeneration;if(n!==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 l=this.terminal?._core?._compositionHelper;if(l?._isComposing){l._isComposing=!1;const a=this.terminal?.element?.querySelector(".xterm-helper-textarea");a&&a.dispatchEvent(new CompositionEvent("compositionend",{data:""}))}}catch{}if(this.activeSessionId){const l=this._localEchoOverlay?.pendingText||"",a=this._localEchoOverlay?.getFlushed()?.count||0,r=this._localEchoOverlay?.getFlushed()?.text||"";l&&this._sendInputAsync(this.activeSessionId,l);const c=a+l.length;c>0&&(this._flushedOffsets||(this._flushedOffsets=new Map),this._flushedTexts||(this._flushedTexts=new Map),this._flushedOffsets.set(this.activeSessionId,c),this._flushedTexts.set(this.activeSessionId,r+l))}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 i=document.querySelector(`.session-tab.active[data-id="${e}"]`);i&&(i.classList.add("tab-glow"),i.addEventListener("animationend",()=>i.classList.remove("tab-glow"),{once:!0}));const o=this.sessions.get(e);if(this.currentSessionWorkingDir=o?.workingDir||null,o&&o.pid===null&&o.status==="idle")try{await fetch(`/api/sessions/${e}/interactive`,{method:"POST"}),o.status="busy"}catch(l){console.error("Failed to attach to restored session:",l)}this._restoringFlushedState=!0,this._isLoadingBuffer=!0,this._loadBufferQueue=[];try{const l=this.terminalBufferCache.get(e);if(l){if(_crashDiag.log(`CACHE_WRITE: ${(l.length/1024).toFixed(0)}KB`),this.terminal.clear(),this.terminal.reset(),await this.chunkedTerminalWrite(l),n!==this._selectGeneration){this._isLoadingBuffer&&this._finishBufferLoad(),this._restoringFlushedState=!1;return}this.terminal.scrollToBottom(),_crashDiag.log("CACHE_DONE")}_crashDiag.log("FETCH_START");const a=
|
|
20
|
+
</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=performance.now(),s=this.sessions.get(e)?.name||e.slice(0,8);_crashDiag.log(`SELECT: ${s}`),console.log(`[CRASH-DIAG] selectSession START: ${e.slice(0,8)}`);const n=++this._selectGeneration;if(n!==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._clientDropRecoveryTimer&&(clearTimeout(this._clientDropRecoveryTimer),this._clientDropRecoveryTimer=null),this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.pendingWrites=[],this.writeFrameScheduled=!1,this._isLoadingBuffer=!1,this._loadBufferQueue=null;try{const l=this.terminal?._core?._compositionHelper;if(l?._isComposing){l._isComposing=!1;const a=this.terminal?.element?.querySelector(".xterm-helper-textarea");a&&a.dispatchEvent(new CompositionEvent("compositionend",{data:""}))}}catch{}if(this.activeSessionId){const l=this._localEchoOverlay?.pendingText||"",a=this._localEchoOverlay?.getFlushed()?.count||0,r=this._localEchoOverlay?.getFlushed()?.text||"";l&&this._sendInputAsync(this.activeSessionId,l);const c=a+l.length;c>0&&(this._flushedOffsets||(this._flushedOffsets=new Map),this._flushedTexts||(this._flushedTexts=new Map),this._flushedOffsets.set(this.activeSessionId,c),this._flushedTexts.set(this.activeSessionId,r+l))}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 i=document.querySelector(`.session-tab.active[data-id="${e}"]`);i&&(i.classList.add("tab-glow"),i.addEventListener("animationend",()=>i.classList.remove("tab-glow"),{once:!0}));const o=this.sessions.get(e);if(this.currentSessionWorkingDir=o?.workingDir||null,o&&o.pid===null&&o.status==="idle")try{await fetch(`/api/sessions/${e}/interactive`,{method:"POST"}),o.status="busy"}catch(l){console.error("Failed to attach to restored session:",l)}this._restoringFlushedState=!0,this._isLoadingBuffer=!0,this._loadBufferQueue=[];try{const l=this.terminalBufferCache.get(e);if(l){if(_crashDiag.log(`CACHE_WRITE: ${(l.length/1024).toFixed(0)}KB`),this.terminal.clear(),this.terminal.reset(),await this.chunkedTerminalWrite(l),n!==this._selectGeneration){this._isLoadingBuffer&&this._finishBufferLoad(),this._restoringFlushedState=!1;return}this.terminal.scrollToBottom(),_crashDiag.log("CACHE_DONE")}_crashDiag.log("FETCH_START");const a=await fetch(`/api/sessions/${e}/terminal?tail=${TERMINAL_TAIL_SIZE}`);if(n!==this._selectGeneration){this._isLoadingBuffer&&this._finishBufferLoad(),this._restoringFlushedState=!1;return}const r=await a.json();if(_crashDiag.log(`FETCH_DONE: ${r.terminalBuffer?(r.terminalBuffer.length/1024).toFixed(0)+"KB":"empty"} truncated=${r.truncated}`),r.terminalBuffer){if(r.terminalBuffer!==l){if(_crashDiag.log(`REWRITE: ${(r.terminalBuffer.length/1024).toFixed(0)}KB`),this.terminal.clear(),this.terminal.reset(),r.truncated&&this.terminal.write(`\x1B[90m... (earlier output truncated for performance) ...\x1B[0m\r
|
|
21
21
|
\r
|
|
22
|
-
`),await this.chunkedTerminalWrite(c.terminalBuffer),n!==this._selectGeneration){this._isLoadingBuffer&&this._finishBufferLoad(),this._restoringFlushedState=!1;return}this.terminal.scrollToBottom()}if(this.terminalBufferCache.set(e,c.terminalBuffer),this.terminalBufferCache.size>20){const h=this.terminalBufferCache.keys().next().value;this.terminalBufferCache.delete(h)}}else l||(this.terminal.clear(),this.terminal.reset());if(this._isLoadingBuffer&&this._finishBufferLoad(),this._restoringFlushedState=!1,this._flushedOffsets?.has(e)&&this._localEchoOverlay){this._localEchoOverlay.setFlushed(this._flushedOffsets.get(e),this._flushedTexts?.get(e)||"",!1);const u=this._localEchoOverlay;this.terminal.write("",()=>{u.hasPending&&u.rerender()})}this.sendResize(e),(typeof requestIdleCallback=="function"?requestIdleCallback:u=>setTimeout(u,16))(()=>{if(n!==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 u=document.getElementById("taskPanel");u&&u.classList.contains("open")&&this.renderTaskPanel();const h=this.sessions.get(e);if(h&&(h.ralphLoop||h.ralphTodos)&&this.updateRalphState(e,{loop:h.ralphLoop,todos:h.ralphTodos}),this.renderRalphStatePanel(),this.updateCliInfoDisplay(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this.loadAppSettingsFromStorage().showFileBrowser){const p=this.$("fileBrowserPanel");if(p&&(p.classList.add("visible"),this.loadFileBrowser(e),!this.fileBrowserDragListeners)){const g=p.querySelector(".file-browser-header");if(g){const f=()=>{if(!p.style.left){const S=p.getBoundingClientRect();p.style.left=`${S.left}px`,p.style.top=`${S.top}px`,p.style.right="auto"}};g.addEventListener("mousedown",f),g.addEventListener("touchstart",f,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(p,g),this.fileBrowserDragListeners._onFirstDrag=f}}}}),_crashDiag.log("FOCUS"),this.terminal.focus(),this.terminal.scrollToBottom(),_crashDiag.log(`SELECT_DONE: ${(performance.now()-t).toFixed(0)}ms`),console.log(`[CRASH-DIAG] selectSession DONE: ${e.slice(0,8)} in ${(performance.now()-t).toFixed(0)}ms`)}catch(l){this._isLoadingBuffer&&this._finishBufferLoad(),this._restoringFlushedState=!1,console.error("Failed to load session terminal:",l)}}_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,console.log("[loadQuickStartCases] Loaded cases:",i.map(d=>d.name),"lastUsedCase:",s);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,console.log("[loadQuickStartCases] Set options:",o.innerHTML.substring(0,200)),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(s){console.error("Failed to load cases:",s)}}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(t){console.error("Failed to save last used case:",t)}}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||"")}">
|
|
22
|
+
`),await this.chunkedTerminalWrite(r.terminalBuffer),n!==this._selectGeneration){this._isLoadingBuffer&&this._finishBufferLoad(),this._restoringFlushedState=!1;return}this.terminal.scrollToBottom()}if(this.terminalBufferCache.set(e,r.terminalBuffer),this.terminalBufferCache.size>20){const u=this.terminalBufferCache.keys().next().value;this.terminalBufferCache.delete(u)}}else l||(this.terminal.clear(),this.terminal.reset());if(this._isLoadingBuffer&&this._finishBufferLoad(),this._restoringFlushedState=!1,this._flushedOffsets?.has(e)&&this._localEchoOverlay){this._localEchoOverlay.setFlushed(this._flushedOffsets.get(e),this._flushedTexts?.get(e)||"",!1);const d=this._localEchoOverlay;this.terminal.write("",()=>{d.hasPending&&d.rerender()})}this.sendResize(e),(typeof requestIdleCallback=="function"?requestIdleCallback:d=>setTimeout(d,16))(()=>{if(n!==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 d=document.getElementById("taskPanel");d&&d.classList.contains("open")&&this.renderTaskPanel();const u=this.sessions.get(e);if(u&&(u.ralphLoop||u.ralphTodos)&&this.updateRalphState(e,{loop:u.ralphLoop,todos:u.ralphTodos}),this.renderRalphStatePanel(),this.updateCliInfoDisplay(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this.loadAppSettingsFromStorage().showFileBrowser){const m=this.$("fileBrowserPanel");if(m&&(m.classList.add("visible"),this.loadFileBrowser(e),!this.fileBrowserDragListeners)){const p=m.querySelector(".file-browser-header");if(p){const g=()=>{if(!m.style.left){const S=m.getBoundingClientRect();m.style.left=`${S.left}px`,m.style.top=`${S.top}px`,m.style.right="auto"}};p.addEventListener("mousedown",g),p.addEventListener("touchstart",g,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(m,p),this.fileBrowserDragListeners._onFirstDrag=g}}}}),_crashDiag.log("FOCUS"),this.terminal.focus(),this.terminal.scrollToBottom(),_crashDiag.log(`SELECT_DONE: ${(performance.now()-t).toFixed(0)}ms`),console.log(`[CRASH-DIAG] selectSession DONE: ${e.slice(0,8)} in ${(performance.now()-t).toFixed(0)}ms`)}catch(l){this._isLoadingBuffer&&this._finishBufferLoad(),this._restoringFlushedState=!1,console.error("Failed to load session terminal:",l)}}_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,console.log("[loadQuickStartCases] Loaded cases:",i.map(d=>d.name),"lastUsedCase:",s);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,console.log("[loadQuickStartCases] Set options:",o.innerHTML.substring(0,200)),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(s){console.error("Failed to load cases:",s)}}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(t){console.error("Failed to save last used case:",t)}}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 f=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!f.success)throw new Error(f.error||"Failed to create case");n=f.case}const i=n.path;if(!i)throw new Error("Case path not found");let o=null,l=1;for(const[,S]of this.sessions){const f=S.name&&S.name.match(/^w(\d+)-(.+)$/);if(f&&f[2]===e){const w=parseInt(f[1]);w>=l&&(l=w+1)}}const a=this.isRalphTrackerEnabledByDefault(),r=[];for(let S=0;S<t;S++)r.push(`w${l+S}-${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(S=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,name:S,...h?{envOverrides:u}:{}})}).then(f=>f.json())),p=await Promise.all(m),g=[];for(const S of p){if(!S.success)throw new Error(S.error);g.push(S.session.id)}o=g[0],await Promise.all(g.map(S=>fetch(`/api/sessions/${S}/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(S=>fetch(`/api/sessions/${S}/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||"")}">
|
|
23
23
|
<span class="timer-name">${escapeHtml(u)}</span>
|
|
24
24
|
<span class="timer-value">${c}s</span>
|
|
25
25
|
<div class="respawn-timer-bar">
|
|
@@ -69,7 +69,7 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
69
69
|
${i.details?`<div class="event-details">${escapeHtml(i.details)}</div>`:""}
|
|
70
70
|
</div>
|
|
71
71
|
</div>
|
|
72
|
-
`}).join("");t.innerHTML=n}getEventIcon(e,t){if(t==="error")return"❌";if(t==="warning")return"⚠";if(t==="success")return"✔";switch(e){case"session_started":return"🚀";case"session_stopped":return"🛑";case"respawn_cycle_started":return"🔄";case"respawn_cycle_completed":return"✅";case"respawn_state_change":return"➡";case"token_milestone":return"💰";case"idle_detected":return"💤";case"working_detected":return"💻";case"ai_check_result":return"🤖";case"hook_event":return"🔔";default:return"•"}}formatDuration(e){if(!e||e<0)return"0s";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=Math.floor(s/60);return n>0?`${n}h ${s%60}m`:s>0?`${s}m ${t%60}s`:`${t}s`}saveSessionOptions(){this.closeSessionOptions()}switchOptionsTab(e){document.querySelectorAll("#sessionOptionsModal .modal-tab-btn").forEach(t=>{t.classList.toggle("active",t.dataset.tab===e)}),document.getElementById("respawn-tab").classList.toggle("hidden",e!=="respawn"),document.getElementById("context-tab").classList.toggle("hidden",e!=="context"),document.getElementById("ralph-tab").classList.toggle("hidden",e!=="ralph"),document.getElementById("summary-tab").classList.toggle("hidden",e!=="summary"),e==="summary"&&this.editingSessionId&&this.loadRunSummary(this.editingSessionId)}getRalphConfig(){return{enabled:document.getElementById("modalRalphEnabled").checked,completionPhrase:document.getElementById("modalRalphPhrase").value.trim(),maxIterations:parseInt(document.getElementById("modalRalphMaxIterations").value)||0,maxTodos:parseInt(document.getElementById("modalRalphMaxTodos").value)||50,todoExpirationMinutes:parseInt(document.getElementById("modalRalphTodoExpiration").value)||60}}populateRalphForm(e){document.getElementById("modalRalphEnabled").checked=e?.enabled??!1,document.getElementById("modalRalphPhrase").value=e?.completionPhrase||"",document.getElementById("modalRalphMaxIterations").value=e?.maxIterations||0,document.getElementById("modalRalphMaxTodos").value=e?.maxTodos||50,document.getElementById("modalRalphTodoExpiration").value=e?.todoExpirationMinutes||60}async saveRalphConfig(){if(!this.editingSessionId){this.showToast("No session selected","warning");return}const e=this.getRalphConfig();e.enabled&&this.ralphClosedSessions.delete(this.editingSessionId);try{const s=await(await fetch(`/api/sessions/${this.editingSessionId}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(s.error)throw new Error(s.error);this.showToast("Ralph config saved","success")}catch(t){this.showToast("Failed to save Ralph config: "+t.message,"error")}}startInlineRename(e){const t=this.sessions.get(e);if(!t)return;const s=document.querySelector(`.tab-name[data-session-id="${e}"]`);if(!s)return;const n=this.getSessionName(t),i=document.createElement("input");i.type="text",i.value=t.name||"",i.placeholder=n,i.className="tab-rename-input",i.style.cssText="width: 80px; font-size: 0.75rem; padding: 2px 4px; background: var(--bg-input); border: 1px solid var(--accent); border-radius: 3px; color: var(--text); outline: none;";const o=s.textContent;s.textContent="",s.appendChild(i),i.focus(),i.select();const l=async()=>{const a=i.value.trim();if(s.textContent=a||o,a&&a!==t.name)try{await fetch(`/api/sessions/${e}/name`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a})})}catch{s.textContent=o,this.showToast("Failed to rename","error")}};i.addEventListener("blur",l),i.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),i.blur()):a.key==="Escape"&&(i.value="",i.blur())})}registerServiceWorker(){"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{this._swRegistration=e,navigator.serviceWorker.addEventListener("message",t=>{if(t.data?.type==="notification-click"){const{sessionId:s}=t.data;s&&this.sessions.has(s)&&this.selectSession(s),window.focus()}}),e.pushManager.getSubscription().then(t=>{t&&(this._pushSubscription=t,this._updatePushUI(!0))})}).catch(()=>{})}async subscribeToPush(){if(!this._swRegistration){this.showToast("Service worker not available. HTTPS or localhost required.","error");return}try{const e=await this._apiJson("/api/push/vapid-key");if(!e?.success)throw new Error("Failed to get VAPID key");const t=urlBase64ToUint8Array(e.data.publicKey),s=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),n=s.toJSON(),i=await this._apiJson("/api/push/subscribe",{method:"POST",body:{endpoint:n.endpoint,keys:n.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()}});if(!i?.success)throw new Error("Failed to register subscription");this._pushSubscription=s,this._pushSubscriptionId=i.data.id,localStorage.setItem("codeman-push-subscription-id",i.data.id),this._updatePushUI(!0),this.showToast("Push notifications enabled","success")}catch(e){this.showToast("Push subscription failed: "+(e.message||e),"error")}}async unsubscribeFromPush(){try{this._pushSubscription&&await this._pushSubscription.unsubscribe();const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");e&&await fetch(`/api/push/subscribe/${e}`,{method:"DELETE"}).catch(()=>{}),this._pushSubscription=null,this._pushSubscriptionId=null,localStorage.removeItem("codeman-push-subscription-id"),this._updatePushUI(!1),this.showToast("Push notifications disabled","success")}catch(e){this.showToast("Failed to unsubscribe: "+(e.message||e),"error")}}async togglePushSubscription(){this._pushSubscription?await this.unsubscribeFromPush():await this.subscribeToPush()}async _syncPushPreferences(){const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");if(e)try{await fetch(`/api/push/subscribe/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pushPreferences:this._buildPushPreferences()})})}catch{}}_buildPushPreferences(){const e={},t={"hook:permission_prompt":"eventPermissionPush","hook:elicitation_dialog":"eventQuestionPush","hook:idle_prompt":"eventIdlePush","hook:stop":"eventStopPush","respawn:blocked":"eventRespawnPush","session:ralphCompletionDetected":"eventRalphPush"};for(const[s,n]of Object.entries(t)){const i=document.getElementById(n);e[s]=i?i.checked:!0}return e["session:error"]=!0,e}_updatePushUI(e){const t=document.getElementById("pushSubscribeBtn"),s=document.getElementById("pushSubscriptionStatus");t&&(t.textContent=e?"Unsubscribe":"Subscribe"),s&&(s.textContent=e?"active":"off",s.classList.remove("granted","denied"),e&&s.classList.add("granted"))}openAppSettings(){const e=this.loadAppSettingsFromStorage();document.getElementById("appSettingsClaudeMdPath").value=e.defaultClaudeMdPath||"",document.getElementById("appSettingsDefaultDir").value=e.defaultWorkingDir||"";const t=this.getDefaultSettings();document.getElementById("appSettingsRalphEnabled").checked=e.ralphTrackerEnabled??t.ralphTrackerEnabled??!1,document.getElementById("appSettingsShowFontControls").checked=e.showFontControls??t.showFontControls??!1,document.getElementById("appSettingsShowSystemStats").checked=e.showSystemStats??t.showSystemStats??!0,document.getElementById("appSettingsShowTokenCount").checked=e.showTokenCount??t.showTokenCount??!0,document.getElementById("appSettingsShowCost").checked=e.showCost??t.showCost??!1,document.getElementById("appSettingsShowLifecycleLog").checked=e.showLifecycleLog??t.showLifecycleLog??!0,document.getElementById("appSettingsShowMonitor").checked=e.showMonitor??t.showMonitor??!0,document.getElementById("appSettingsShowProjectInsights").checked=e.showProjectInsights??t.showProjectInsights??!1,document.getElementById("appSettingsShowFileBrowser").checked=e.showFileBrowser??t.showFileBrowser??!1,document.getElementById("appSettingsShowSubagents").checked=e.showSubagents??t.showSubagents??!0,document.getElementById("appSettingsSubagentTracking").checked=e.subagentTrackingEnabled??t.subagentTrackingEnabled??!0,document.getElementById("appSettingsSubagentActiveTabOnly").checked=e.subagentActiveTabOnly??t.subagentActiveTabOnly??!0,document.getElementById("appSettingsImageWatcherEnabled").checked=e.imageWatcherEnabled??t.imageWatcherEnabled??!1,document.getElementById("appSettingsTunnelEnabled").checked=e.tunnelEnabled??!1,this.loadTunnelStatus(),document.getElementById("appSettingsLocalEcho").checked=e.localEchoEnabled??MobileDetection.isTouchDevice(),document.getElementById("appSettingsTabTwoRows").checked=e.tabTwoRows??t.tabTwoRows??!1;const s=document.getElementById("appSettingsClaudeMode"),n=document.getElementById("allowedToolsRow");s.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",n.style.display=s.value==="allowedTools"?"":"none",s.onchange=()=>{n.style.display=s.value==="allowedTools"?"":"none"},document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1;const i=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=i.enabled??!1,document.getElementById("appSettingsNiceValue").value=i.niceValue??10,this.loadModelConfigForSettings();const o=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=o.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=o.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=o.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((o.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!o.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!o.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!o.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const l=o.eventTypes||{},a=l.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=a.enabled??!0,document.getElementById("eventPermissionBrowser").checked=a.browser??!0,document.getElementById("eventPermissionPush").checked=a.push??!1,document.getElementById("eventPermissionAudio").checked=a.audio??!0;const r=l.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=r.enabled??!0,document.getElementById("eventQuestionBrowser").checked=r.browser??!0,document.getElementById("eventQuestionPush").checked=r.push??!1,document.getElementById("eventQuestionAudio").checked=r.audio??!0;const c=l.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=c.enabled??!0,document.getElementById("eventIdleBrowser").checked=c.browser??!0,document.getElementById("eventIdlePush").checked=c.push??!1,document.getElementById("eventIdleAudio").checked=c.audio??!1;const d=l.stop||{};document.getElementById("eventStopEnabled").checked=d.enabled??!0,document.getElementById("eventStopBrowser").checked=d.browser??!1,document.getElementById("eventStopPush").checked=d.push??!1,document.getElementById("eventStopAudio").checked=d.audio??!1;const u=l.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=u.enabled??!0,document.getElementById("eventRespawnBrowser").checked=u.browser??!1,document.getElementById("eventRespawnPush").checked=u.push??!1,document.getElementById("eventRespawnAudio").checked=u.audio??!1;const h=l.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=h.enabled??!0,document.getElementById("eventRalphBrowser").checked=h.browser??!0,document.getElementById("eventRalphPush").checked=h.push??!1,document.getElementById("eventRalphAudio").checked=h.audio??!0;const m=l.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=m.enabled??!1,document.getElementById("eventSubagentBrowser").checked=m.browser??!1,document.getElementById("eventSubagentPush").checked=m.push??!1,document.getElementById("eventSubagentAudio").checked=m.audio??!1;const p=document.getElementById("notifPermissionStatus");if(p&&typeof Notification<"u"){const y=Notification.permission;p.textContent=y==="granted"?"\u2713":y==="denied"?"\u2717":"?",p.classList.remove("granted","denied"),y==="granted"?p.classList.add("granted"):y==="denied"&&p.classList.add("denied")}const g=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=g.apiKey||"",document.getElementById("voiceLanguage").value=g.language||"en-US",document.getElementById("voiceKeyterms").value=g.keyterms||"refactor, endpoint, middleware, callback, async, regex, TypeScript, npm, API, deploy, config, linter, env, webhook, schema, CLI, JSON, CSS, DOM, SSE, backend, frontend, localhost, dependencies, repository, merge, rebase, diff, commit, com",document.getElementById("voiceInsertMode").value=g.insertMode||"direct";const f=document.getElementById("voiceDeepgramKey");f.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show";const S=VoiceInput.getActiveProviderName(),w=document.getElementById("voiceProviderStatus");w.textContent=S,w.className="voice-provider-status"+(S.startsWith("Deepgram")?" active":""),this.switchSettingsTab("settings-display");const T=document.getElementById("appSettingsModal");T.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(y=>{y.onclick=()=>this.switchSettingsTab(y.dataset.tab)}),T.classList.add("active"),this.activeFocusTrap=new FocusTrap(T),this.activeFocusTrap.activate()}switchSettingsTab(e){const t=document.getElementById("appSettingsModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(s=>{s.classList.toggle("active",s.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(s=>{s.classList.toggle("hidden",s.id!==e)})}closeAppSettings(){document.getElementById("appSettingsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)}async loadTunnelStatus(){try{const t=await(await fetch("/api/tunnel/status")).json(),s=t.running&&t.url;this._updateTunnelUrlDisplay(s?t.url:null),this._updateWelcomeTunnelBtn(!!s,s?t.url:null)}catch{this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1)}}_updateTunnelUrlDisplay(e){const t=document.getElementById("tunnelUrlRow"),s=document.getElementById("tunnelUrlDisplay");if(!t||!s)return;e?(t.style.display="",s.textContent=e,s.onclick=()=>{navigator.clipboard.writeText(e).then(()=>{this.showToast("Tunnel URL copied","success")})}):(t.style.display="none",s.textContent="",s.onclick=null);const n=document.getElementById("tunnelUploadUrlRow"),i=document.getElementById("tunnelUploadUrlDisplay");if(!(!n||!i))if(e){const o=e+"/upload.html";n.style.display="",i.textContent=o,i.onclick=()=>{navigator.clipboard.writeText(o).then(()=>{this.showToast("Upload URL copied","success")})}}else n.style.display="none",i.textContent="",i.onclick=null}showTunnelQR(){this.closeTunnelQR();const e=document.createElement("div");e.id="tunnelQrOverlay",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:5000;display:flex;align-items:center;justify-content:center;cursor:pointer",e.onclick=s=>{s.target===e&&this.closeTunnelQR()};const t=document.createElement("div");t.style.cssText="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;text-align:center;max-width:340px;width:90vw;box-shadow:var(--shadow-lg);cursor:default",t.innerHTML=`
|
|
72
|
+
`}).join("");t.innerHTML=n}getEventIcon(e,t){if(t==="error")return"❌";if(t==="warning")return"⚠";if(t==="success")return"✔";switch(e){case"session_started":return"🚀";case"session_stopped":return"🛑";case"respawn_cycle_started":return"🔄";case"respawn_cycle_completed":return"✅";case"respawn_state_change":return"➡";case"token_milestone":return"💰";case"idle_detected":return"💤";case"working_detected":return"💻";case"ai_check_result":return"🤖";case"hook_event":return"🔔";default:return"•"}}formatDuration(e){if(!e||e<0)return"0s";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=Math.floor(s/60);return n>0?`${n}h ${s%60}m`:s>0?`${s}m ${t%60}s`:`${t}s`}saveSessionOptions(){this.closeSessionOptions()}switchOptionsTab(e){document.querySelectorAll("#sessionOptionsModal .modal-tab-btn").forEach(t=>{t.classList.toggle("active",t.dataset.tab===e)}),document.getElementById("respawn-tab").classList.toggle("hidden",e!=="respawn"),document.getElementById("context-tab").classList.toggle("hidden",e!=="context"),document.getElementById("ralph-tab").classList.toggle("hidden",e!=="ralph"),document.getElementById("summary-tab").classList.toggle("hidden",e!=="summary"),e==="summary"&&this.editingSessionId&&this.loadRunSummary(this.editingSessionId)}getRalphConfig(){return{enabled:document.getElementById("modalRalphEnabled").checked,completionPhrase:document.getElementById("modalRalphPhrase").value.trim(),maxIterations:parseInt(document.getElementById("modalRalphMaxIterations").value)||0,maxTodos:parseInt(document.getElementById("modalRalphMaxTodos").value)||50,todoExpirationMinutes:parseInt(document.getElementById("modalRalphTodoExpiration").value)||60}}populateRalphForm(e){document.getElementById("modalRalphEnabled").checked=e?.enabled??!1,document.getElementById("modalRalphPhrase").value=e?.completionPhrase||"",document.getElementById("modalRalphMaxIterations").value=e?.maxIterations||0,document.getElementById("modalRalphMaxTodos").value=e?.maxTodos||50,document.getElementById("modalRalphTodoExpiration").value=e?.todoExpirationMinutes||60}async saveRalphConfig(){if(!this.editingSessionId){this.showToast("No session selected","warning");return}const e=this.getRalphConfig();e.enabled&&this.ralphClosedSessions.delete(this.editingSessionId);try{const s=await(await fetch(`/api/sessions/${this.editingSessionId}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(s.error)throw new Error(s.error);this.showToast("Ralph config saved","success")}catch(t){this.showToast("Failed to save Ralph config: "+t.message,"error")}}startInlineRename(e){const t=this.sessions.get(e);if(!t)return;const s=document.querySelector(`.tab-name[data-session-id="${e}"]`);if(!s)return;const n=this.getSessionName(t),i=document.createElement("input");i.type="text",i.value=t.name||"",i.placeholder=n,i.className="tab-rename-input",i.style.cssText="width: 80px; font-size: 0.75rem; padding: 2px 4px; background: var(--bg-input); border: 1px solid var(--accent); border-radius: 3px; color: var(--text); outline: none;";const o=s.textContent;s.textContent="",s.appendChild(i),i.focus(),i.select();const l=async()=>{const a=i.value.trim();if(s.textContent=a||o,a&&a!==t.name)try{await fetch(`/api/sessions/${e}/name`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a})})}catch{s.textContent=o,this.showToast("Failed to rename","error")}};i.addEventListener("blur",l),i.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),i.blur()):a.key==="Escape"&&(i.value="",i.blur())})}registerServiceWorker(){"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{this._swRegistration=e,navigator.serviceWorker.addEventListener("message",t=>{if(t.data?.type==="notification-click"){const{sessionId:s}=t.data;s&&this.sessions.has(s)&&this.selectSession(s),window.focus()}}),e.pushManager.getSubscription().then(t=>{t&&(this._pushSubscription=t,this._updatePushUI(!0))})}).catch(()=>{})}async subscribeToPush(){if(!this._swRegistration){this.showToast("Service worker not available. HTTPS or localhost required.","error");return}try{const e=await this._apiJson("/api/push/vapid-key");if(!e?.success)throw new Error("Failed to get VAPID key");const t=urlBase64ToUint8Array(e.data.publicKey),s=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),n=s.toJSON(),i=await this._apiJson("/api/push/subscribe",{method:"POST",body:{endpoint:n.endpoint,keys:n.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()}});if(!i?.success)throw new Error("Failed to register subscription");this._pushSubscription=s,this._pushSubscriptionId=i.data.id,localStorage.setItem("codeman-push-subscription-id",i.data.id),this._updatePushUI(!0),this.showToast("Push notifications enabled","success")}catch(e){this.showToast("Push subscription failed: "+(e.message||e),"error")}}async unsubscribeFromPush(){try{this._pushSubscription&&await this._pushSubscription.unsubscribe();const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");e&&await fetch(`/api/push/subscribe/${e}`,{method:"DELETE"}).catch(()=>{}),this._pushSubscription=null,this._pushSubscriptionId=null,localStorage.removeItem("codeman-push-subscription-id"),this._updatePushUI(!1),this.showToast("Push notifications disabled","success")}catch(e){this.showToast("Failed to unsubscribe: "+(e.message||e),"error")}}async togglePushSubscription(){this._pushSubscription?await this.unsubscribeFromPush():await this.subscribeToPush()}async _syncPushPreferences(){const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");if(e)try{await fetch(`/api/push/subscribe/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pushPreferences:this._buildPushPreferences()})})}catch{}}_buildPushPreferences(){const e={},t={"hook:permission_prompt":"eventPermissionPush","hook:elicitation_dialog":"eventQuestionPush","hook:idle_prompt":"eventIdlePush","hook:stop":"eventStopPush","respawn:blocked":"eventRespawnPush","session:ralphCompletionDetected":"eventRalphPush"};for(const[s,n]of Object.entries(t)){const i=document.getElementById(n);e[s]=i?i.checked:!0}return e["session:error"]=!0,e}_updatePushUI(e){const t=document.getElementById("pushSubscribeBtn"),s=document.getElementById("pushSubscriptionStatus");t&&(t.textContent=e?"Unsubscribe":"Subscribe"),s&&(s.textContent=e?"active":"off",s.classList.remove("granted","denied"),e&&s.classList.add("granted"))}openAppSettings(){const e=this.loadAppSettingsFromStorage();document.getElementById("appSettingsClaudeMdPath").value=e.defaultClaudeMdPath||"",document.getElementById("appSettingsDefaultDir").value=e.defaultWorkingDir||"";const t=this.getDefaultSettings();document.getElementById("appSettingsRalphEnabled").checked=e.ralphTrackerEnabled??t.ralphTrackerEnabled??!1,document.getElementById("appSettingsShowFontControls").checked=e.showFontControls??t.showFontControls??!1,document.getElementById("appSettingsShowSystemStats").checked=e.showSystemStats??t.showSystemStats??!0,document.getElementById("appSettingsShowTokenCount").checked=e.showTokenCount??t.showTokenCount??!0,document.getElementById("appSettingsShowCost").checked=e.showCost??t.showCost??!1,document.getElementById("appSettingsShowLifecycleLog").checked=e.showLifecycleLog??t.showLifecycleLog??!0,document.getElementById("appSettingsShowMonitor").checked=e.showMonitor??t.showMonitor??!0,document.getElementById("appSettingsShowProjectInsights").checked=e.showProjectInsights??t.showProjectInsights??!1,document.getElementById("appSettingsShowFileBrowser").checked=e.showFileBrowser??t.showFileBrowser??!1,document.getElementById("appSettingsShowSubagents").checked=e.showSubagents??t.showSubagents??!0,document.getElementById("appSettingsSubagentTracking").checked=e.subagentTrackingEnabled??t.subagentTrackingEnabled??!0,document.getElementById("appSettingsSubagentActiveTabOnly").checked=e.subagentActiveTabOnly??t.subagentActiveTabOnly??!0,document.getElementById("appSettingsImageWatcherEnabled").checked=e.imageWatcherEnabled??t.imageWatcherEnabled??!1,document.getElementById("appSettingsTunnelEnabled").checked=e.tunnelEnabled??!1,this.loadTunnelStatus(),document.getElementById("appSettingsLocalEcho").checked=e.localEchoEnabled??MobileDetection.isTouchDevice(),document.getElementById("appSettingsTabTwoRows").checked=e.tabTwoRows??t.tabTwoRows??!1;const s=document.getElementById("appSettingsClaudeMode"),n=document.getElementById("allowedToolsRow");s.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",n.style.display=s.value==="allowedTools"?"":"none",s.onchange=()=>{n.style.display=s.value==="allowedTools"?"":"none"},document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1;const i=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=i.enabled??!1,document.getElementById("appSettingsNiceValue").value=i.niceValue??10,this.loadModelConfigForSettings();const o=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=o.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=o.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=o.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((o.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!o.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!o.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!o.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const l=o.eventTypes||{},a=l.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=a.enabled??!0,document.getElementById("eventPermissionBrowser").checked=a.browser??!0,document.getElementById("eventPermissionPush").checked=a.push??!1,document.getElementById("eventPermissionAudio").checked=a.audio??!0;const r=l.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=r.enabled??!0,document.getElementById("eventQuestionBrowser").checked=r.browser??!0,document.getElementById("eventQuestionPush").checked=r.push??!1,document.getElementById("eventQuestionAudio").checked=r.audio??!0;const c=l.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=c.enabled??!0,document.getElementById("eventIdleBrowser").checked=c.browser??!0,document.getElementById("eventIdlePush").checked=c.push??!1,document.getElementById("eventIdleAudio").checked=c.audio??!1;const d=l.stop||{};document.getElementById("eventStopEnabled").checked=d.enabled??!0,document.getElementById("eventStopBrowser").checked=d.browser??!1,document.getElementById("eventStopPush").checked=d.push??!1,document.getElementById("eventStopAudio").checked=d.audio??!1;const u=l.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=u.enabled??!0,document.getElementById("eventRespawnBrowser").checked=u.browser??!1,document.getElementById("eventRespawnPush").checked=u.push??!1,document.getElementById("eventRespawnAudio").checked=u.audio??!1;const h=l.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=h.enabled??!0,document.getElementById("eventRalphBrowser").checked=h.browser??!0,document.getElementById("eventRalphPush").checked=h.push??!1,document.getElementById("eventRalphAudio").checked=h.audio??!0;const m=l.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=m.enabled??!1,document.getElementById("eventSubagentBrowser").checked=m.browser??!1,document.getElementById("eventSubagentPush").checked=m.push??!1,document.getElementById("eventSubagentAudio").checked=m.audio??!1;const p=document.getElementById("notifPermissionStatus");if(p&&typeof Notification<"u"){const y=Notification.permission;p.textContent=y==="granted"?"\u2713":y==="denied"?"\u2717":"?",p.classList.remove("granted","denied"),y==="granted"?p.classList.add("granted"):y==="denied"&&p.classList.add("denied")}const g=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=g.apiKey||"",document.getElementById("voiceLanguage").value=g.language||"en-US",document.getElementById("voiceKeyterms").value=g.keyterms||"refactor, endpoint, middleware, callback, async, regex, TypeScript, npm, API, deploy, config, linter, env, webhook, schema, CLI, JSON, CSS, DOM, SSE, backend, frontend, localhost, dependencies, repository, merge, rebase, diff, commit, com",document.getElementById("voiceInsertMode").value=g.insertMode||"direct";const S=document.getElementById("voiceDeepgramKey");S.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show";const f=VoiceInput.getActiveProviderName(),w=document.getElementById("voiceProviderStatus");w.textContent=f,w.className="voice-provider-status"+(f.startsWith("Deepgram")?" active":""),this.switchSettingsTab("settings-display");const E=document.getElementById("appSettingsModal");E.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(y=>{y.onclick=()=>this.switchSettingsTab(y.dataset.tab)}),E.classList.add("active"),this.activeFocusTrap=new FocusTrap(E),this.activeFocusTrap.activate()}switchSettingsTab(e){const t=document.getElementById("appSettingsModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(s=>{s.classList.toggle("active",s.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(s=>{s.classList.toggle("hidden",s.id!==e)})}closeAppSettings(){document.getElementById("appSettingsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)}async loadTunnelStatus(){try{const t=await(await fetch("/api/tunnel/status")).json(),s=t.running&&t.url;this._updateTunnelUrlDisplay(s?t.url:null),this._updateWelcomeTunnelBtn(!!s,s?t.url:null)}catch{this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1)}}_updateTunnelUrlDisplay(e){const t=document.getElementById("tunnelUrlRow"),s=document.getElementById("tunnelUrlDisplay");if(!t||!s)return;e?(t.style.display="",s.textContent=e,s.onclick=()=>{navigator.clipboard.writeText(e).then(()=>{this.showToast("Tunnel URL copied","success")})}):(t.style.display="none",s.textContent="",s.onclick=null);const n=document.getElementById("tunnelUploadUrlRow"),i=document.getElementById("tunnelUploadUrlDisplay");if(!(!n||!i))if(e){const o=e+"/upload.html";n.style.display="",i.textContent=o,i.onclick=()=>{navigator.clipboard.writeText(o).then(()=>{this.showToast("Upload URL copied","success")})}}else n.style.display="none",i.textContent="",i.onclick=null}showTunnelQR(){this.closeTunnelQR();const e=document.createElement("div");e.id="tunnelQrOverlay",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:5000;display:flex;align-items:center;justify-content:center;cursor:pointer",e.onclick=s=>{s.target===e&&this.closeTunnelQR()};const t=document.createElement("div");t.style.cssText="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;text-align:center;max-width:340px;width:90vw;box-shadow:var(--shadow-lg);cursor:default",t.innerHTML=`
|
|
73
73
|
<div style="font-size:14px;font-weight:600;color:var(--text-primary);margin-bottom:16px">Scan to connect</div>
|
|
74
74
|
<div id="tunnelQrContainer" style="background:#fff;border-radius:8px;padding:16px;display:inline-block">
|
|
75
75
|
<div style="color:#666;font-size:12px">Loading...</div>
|
|
@@ -104,14 +104,14 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
104
104
|
<span class="stat-card-value">${this.formatTokens(d+u)}</span>
|
|
105
105
|
<span class="stat-card-cost">~$${h.toFixed(2)}</span>
|
|
106
106
|
</div>
|
|
107
|
-
`;const p=document.getElementById("statsChart"),g=document.getElementById("statsChartDays"),
|
|
107
|
+
`;const p=document.getElementById("statsChart"),g=document.getElementById("statsChartDays"),S=[];for(let y=6;y>=0;y--){const b=new Date;b.setDate(b.getDate()-y);const I=b.toISOString().split("T")[0],T=t.find(C=>C.date===I);S.push({date:I,dayName:b.toLocaleDateString("en-US",{weekday:"short"}),tokens:T?T.inputTokens+T.outputTokens:0,cost:T?T.estimatedCost:0})}const f=Math.max(...S.map(y=>y.tokens),1);p.innerHTML=S.map(y=>{const b=Math.max(y.tokens/f*100,3),I=`${y.dayName}: ${this.formatTokens(y.tokens)} (~$${y.cost.toFixed(2)})`;return`<div class="bar" style="height: ${b}%" data-tooltip="${I}"></div>`}).join(""),g.innerHTML=S.map(y=>`<span>${y.dayName}</span>`).join("");const w=document.getElementById("statsTable"),E=t.slice(0,14);E.length===0?w.innerHTML='<div class="stats-no-data">No usage data recorded yet</div>':w.innerHTML=`
|
|
108
108
|
<div class="stats-table-header">
|
|
109
109
|
<span>Date</span>
|
|
110
110
|
<span>Input</span>
|
|
111
111
|
<span>Output</span>
|
|
112
112
|
<span>Cost</span>
|
|
113
113
|
</div>
|
|
114
|
-
${
|
|
114
|
+
${E.map(y=>`
|
|
115
115
|
<div class="stats-table-row">
|
|
116
116
|
<span class="cell cell-date">${new Date(y.date+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric"})}</span>
|
|
117
117
|
<span class="cell">${this.formatTokens(y.inputTokens)}</span>
|
|
@@ -119,7 +119,7 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
119
119
|
<span class="cell cell-cost">$${y.estimatedCost.toFixed(2)}</span>
|
|
120
120
|
</div>
|
|
121
121
|
`).join("")}
|
|
122
|
-
`}closeTokenStats(){const e=document.getElementById("tokenStatsModal");e&&e.classList.remove("active")}async toggleMonitorPanel(){const e=document.getElementById("monitorPanel"),t=document.getElementById("monitorToggleBtn");e.classList.toggle("open"),e.classList.contains("open")?(await this.loadMuxSessions(),await fetch("/api/mux-sessions/stats/start",{method:"POST"}),this.renderTaskPanel(),t&&(t.innerHTML="▼")):(await fetch("/api/mux-sessions/stats/stop",{method:"POST"}),t&&(t.innerHTML="▲"))}toggleTaskPanel(){this.toggleMonitorPanel()}toggleMonitorDetach(){const e=document.getElementById("monitorPanel"),t=document.getElementById("monitorDetachBtn");e.classList.contains("detached")?(e.classList.remove("detached"),e.style.top="",e.style.left="",e.style.width="",e.style.height="",t&&(t.innerHTML="⧉",t.title="Detach panel")):(e.classList.add("detached"),e.classList.add("open"),t&&(t.innerHTML="⊞",t.title="Attach panel"),this.setupMonitorDrag())}setupMonitorDrag(){const e=document.getElementById("monitorPanel"),t=document.getElementById("monitorPanelHeader");if(!e||!t)return;let s=!1,n,i,o,l;const a=d=>{if(d.target.closest("button")||!e.classList.contains("detached"))return;s=!0;const u=getEventCoords(d);n=u.clientX,i=u.clientY;const h=e.getBoundingClientRect();o=h.left,l=h.top,document.addEventListener("mousemove",r),document.addEventListener("mouseup",c),document.addEventListener("touchmove",r,{passive:!1}),document.addEventListener("touchend",c),d.preventDefault()},r=d=>{if(!s)return;const u=getEventCoords(d),h=u.clientX-n,m=u.clientY-i;let p=o+h,g=l+m;const
|
|
122
|
+
`}closeTokenStats(){const e=document.getElementById("tokenStatsModal");e&&e.classList.remove("active")}async toggleMonitorPanel(){const e=document.getElementById("monitorPanel"),t=document.getElementById("monitorToggleBtn");e.classList.toggle("open"),e.classList.contains("open")?(await this.loadMuxSessions(),await fetch("/api/mux-sessions/stats/start",{method:"POST"}),this.renderTaskPanel(),t&&(t.innerHTML="▼")):(await fetch("/api/mux-sessions/stats/stop",{method:"POST"}),t&&(t.innerHTML="▲"))}toggleTaskPanel(){this.toggleMonitorPanel()}toggleMonitorDetach(){const e=document.getElementById("monitorPanel"),t=document.getElementById("monitorDetachBtn");e.classList.contains("detached")?(e.classList.remove("detached"),e.style.top="",e.style.left="",e.style.width="",e.style.height="",t&&(t.innerHTML="⧉",t.title="Detach panel")):(e.classList.add("detached"),e.classList.add("open"),t&&(t.innerHTML="⊞",t.title="Attach panel"),this.setupMonitorDrag())}setupMonitorDrag(){const e=document.getElementById("monitorPanel"),t=document.getElementById("monitorPanelHeader");if(!e||!t)return;let s=!1,n,i,o,l;const a=d=>{if(d.target.closest("button")||!e.classList.contains("detached"))return;s=!0;const u=getEventCoords(d);n=u.clientX,i=u.clientY;const h=e.getBoundingClientRect();o=h.left,l=h.top,document.addEventListener("mousemove",r),document.addEventListener("mouseup",c),document.addEventListener("touchmove",r,{passive:!1}),document.addEventListener("touchend",c),d.preventDefault()},r=d=>{if(!s)return;const u=getEventCoords(d),h=u.clientX-n,m=u.clientY-i;let p=o+h,g=l+m;const S=e.getBoundingClientRect();p=Math.max(0,Math.min(window.innerWidth-S.width,p)),g=Math.max(0,Math.min(window.innerHeight-S.height,g)),e.style.left=p+"px",e.style.top=g+"px"},c=()=>{s=!1,document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",c),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",c)};t.removeEventListener("mousedown",t._dragHandler),t.removeEventListener("touchstart",t._touchDragHandler),t._dragHandler=a,t._touchDragHandler=a,t.addEventListener("mousedown",a),t.addEventListener("touchstart",a,{passive:!1})}toggleSubagentsDetach(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsDetachBtn");e.classList.contains("detached")?(e.classList.remove("detached"),e.style.top="",e.style.left="",e.style.width="",e.style.height="",t&&(t.innerHTML="⧉",t.title="Detach panel")):(e.classList.add("detached"),e.classList.add("open"),t&&(t.innerHTML="⊞",t.title="Attach panel"),this.setupSubagentsDrag())}setupSubagentsDrag(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsPanelHeader");if(!e||!t)return;let s=!1,n,i,o,l;const a=d=>{if(d.target.closest("button")||!e.classList.contains("detached"))return;s=!0;const u=getEventCoords(d);n=u.clientX,i=u.clientY;const h=e.getBoundingClientRect();o=h.left,l=h.top,document.addEventListener("mousemove",r),document.addEventListener("mouseup",c),document.addEventListener("touchmove",r,{passive:!1}),document.addEventListener("touchend",c),d.preventDefault()},r=d=>{if(!s)return;const u=getEventCoords(d),h=u.clientX-n,m=u.clientY-i;let p=o+h,g=l+m;const S=e.getBoundingClientRect();p=Math.max(0,Math.min(window.innerWidth-S.width,p)),g=Math.max(0,Math.min(window.innerHeight-S.height,g)),e.style.left=p+"px",e.style.top=g+"px"},c=()=>{s=!1,document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",c),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",c)};t.removeEventListener("mousedown",t._dragHandler),t.removeEventListener("touchstart",t._touchDragHandler),t._dragHandler=a,t._touchDragHandler=a,t.addEventListener("mousedown",a),t.addEventListener("touchstart",a,{passive:!1})}renderTaskPanel(){this.renderTaskPanelTimeout&&clearTimeout(this.renderTaskPanelTimeout),this.renderTaskPanelTimeout=setTimeout(()=>{this._renderTaskPanelImmediate()},100)}_renderTaskPanelImmediate(){const e=this.sessions.get(this.activeSessionId),t=document.getElementById("backgroundTasksBody"),s=document.getElementById("taskPanelStats"),n=document.getElementById("backgroundTasksSection");if(!e||!e.taskTree||e.taskTree.length===0){n&&(n.style.display="none"),t.innerHTML="",s.textContent="0 tasks";return}n&&(n.style.display="");const i=e.taskStats||{running:0,completed:0,failed:0,total:0};s.textContent=`${i.running} running, ${i.completed} done`;const o=(r,c)=>{const d=r.status==="running"?"":r.status==="completed"?"✓":"✗",u=r.endTime?`${((r.endTime-r.startTime)/1e3).toFixed(1)}s`:`${((Date.now()-r.startTime)/1e3).toFixed(0)}s...`;let h="";if(r.children&&r.children.length>0){h='<div class="task-children">';for(const m of r.children){const p=c.find(g=>g.id===m);p&&(h+=`<div class="task-node">${o(p,c)}</div>`)}h+="</div>"}return`
|
|
123
123
|
<div class="task-item">
|
|
124
124
|
<span class="task-status-icon ${r.status}">${d}</span>
|
|
125
125
|
<div class="task-info">
|
|
@@ -264,7 +264,7 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
264
264
|
`)}catch(t){console.error("Failed to load transcript:",t),alert("Failed to load transcript: "+t.message)}}findParentSessionForSubagent(e){if(this.subagentParentMap.has(e)){const s=this.subagentParentMap.get(e);if(this.sessions.has(s)){const n=this.subagents.get(e);if(n&&!n.parentSessionId){n.parentSessionId=s;const i=this.sessions.get(s);i&&(n.parentSessionName=this.getSessionName(i)),this.subagents.set(e,n),this.updateSubagentWindowParent(e)}return}this.subagentParentMap.delete(e)}const t=this.subagents.get(e);if(t){if(t.sessionId){for(const[s,n]of this.sessions)if(n.claudeSessionId===t.sessionId){this.setAgentParentSessionId(e,s),this.updateSubagentWindowParent(e),this.updateSubagentWindowVisibility(),this.updateConnectionLines();return}}if(this.activeSessionId&&this.sessions.has(this.activeSessionId)){this.setAgentParentSessionId(e,this.activeSessionId),this.updateSubagentWindowParent(e),this.updateSubagentWindowVisibility(),this.updateConnectionLines();return}if(this.sessions.size>0){const s=this.sessions.keys().next().value;this.setAgentParentSessionId(e,s),this.updateSubagentWindowParent(e),this.updateSubagentWindowVisibility(),this.updateConnectionLines()}}}recheckOrphanSubagents(){let e=!1;for(const[t,s]of this.subagents)if(!this.subagentParentMap.has(t))this.findParentSessionForSubagent(t),this.subagentParentMap.has(t)&&(e=!0);else if(s.sessionId){const n=this.subagentParentMap.get(t),i=this.sessions.get(n);if(i&&i.claudeSessionId!==s.sessionId){for(const[o,l]of this.sessions)if(l.claudeSessionId===s.sessionId){this.subagentParentMap.set(t,o),s.parentSessionId=o,s.parentSessionName=this.getSessionName(l),this.subagents.set(t,s),this.updateSubagentWindowParent(t),e=!0;break}}}e&&(this.saveSubagentParentMap(),this.updateConnectionLines())}updateSubagentParentNames(e){const t=this.sessions.get(e);if(!t)return;const s=this.getSessionName(t);if(this._parentNameCache?.get(e)!==s){this._parentNameCache||(this._parentNameCache=new Map),this._parentNameCache.set(e,s);for(const[i,o]of this.subagentParentMap)if(o===e){const l=this.subagents.get(i);if(l){l.parentSessionName=s,this.subagents.set(i,l);const a=this.subagentWindows.get(i);if(a){const r=a.element.querySelector(".subagent-window-parent .parent-name");r&&(r.textContent=s)}}}}}updateSubagentWindowParent(e){const t=this.subagentWindows.get(e);if(!t)return;const s=this.subagentParentMap.get(e);if(!s)return;const n=this.sessions.get(s),i=n?this.getSessionName(n):"Unknown",o=t.element,l=o.querySelector(".subagent-window-parent");if(l){l.dataset.parentSession=s;const r=l.querySelector(".parent-name");r&&(r.textContent=i,r.onclick=()=>this.selectSession(s));return}const a=o.querySelector(".subagent-window-header");if(a){const r=document.createElement("div");r.className="subagent-window-parent",r.dataset.parentSession=s,r.innerHTML=`
|
|
265
265
|
<span class="parent-label">from</span>
|
|
266
266
|
<span class="parent-name" onclick="app.selectSession('${escapeHtml(s)}')">${escapeHtml(i)}</span>
|
|
267
|
-
`,a.insertAdjacentElement("afterend",r)}}updateSubagentWindowVisibility(){const t=this.loadAppSettingsFromStorage().subagentActiveTabOnly??!0;for(const[s,n]of this.subagentWindows){const i=this.subagentParentMap.get(s),o=this.subagents.get(s),l=i||o?.parentSessionId;let a;t?a=!!!l||l===this.activeSessionId:a=!0,a?(n.minimized||(n.element.style.display="flex"),n.hidden=!1):(n.element.style.display="none",n.hidden=!0)}this.updateConnectionLines(),this.relayoutMobileSubagentWindows()}closeSessionSubagentWindows(e,t=!1){const s=[];for(const[n,i]of this.subagentWindows){const o=this.subagents.get(n),l=this.subagentParentMap.get(n);(o?.parentSessionId===e||l===e)&&s.push(n)}for(const n of s)this.forceCloseSubagentWindow(n),t&&(this.subagents.delete(n),this.subagentActivity.delete(n),this.subagentToolResults.delete(n),this.subagentParentMap.delete(n));this.minimizedSubagents.delete(e),this.renderSessionTabs()}forceCloseSubagentWindow(e){const t=this.subagentWindows.get(e);t&&(t.resizeObserver&&t.resizeObserver.disconnect(),t.dragListeners&&(document.removeEventListener("mousemove",t.dragListeners.move),document.removeEventListener("mouseup",t.dragListeners.up),t.dragListeners.touchMove&&(document.removeEventListener("touchmove",t.dragListeners.touchMove),document.removeEventListener("touchend",t.dragListeners.up),document.removeEventListener("touchcancel",t.dragListeners.up)),t.dragListeners.handle&&(t.dragListeners.handle.removeEventListener("mousedown",t.dragListeners.handleMouseDown),t.dragListeners.handle.removeEventListener("touchstart",t.dragListeners.handleTouchStart))),t.element.remove(),this.subagentWindows.delete(e));const s=this.teammateTerminals.get(e);if(s){if(s.resizeObserver&&s.resizeObserver.disconnect(),s.terminal)try{s.terminal.dispose()}catch{}this.teammateTerminals.delete(e)}}minimizeSubagentWindow(e){const t=this.subagentWindows.get(e);t&&(t.element.style.display="none",t.minimized=!0,this.updateConnectionLines())}scheduleSubagentWindowRender(e){this._subagentWindowRenderTimeouts||(this._subagentWindowRenderTimeouts=new Map),this._subagentWindowRenderTimeouts.has(e)&&clearTimeout(this._subagentWindowRenderTimeouts.get(e)),this._subagentWindowRenderTimeouts.set(e,setTimeout(()=>{this._subagentWindowRenderTimeouts.delete(e),scheduleBackground(()=>this.renderSubagentWindowContent(e))},100))}renderSubagentWindowContent(e){if(this.teammateTerminals.has(e))return;const
|
|
267
|
+
`,a.insertAdjacentElement("afterend",r)}}updateSubagentWindowVisibility(){const t=this.loadAppSettingsFromStorage().subagentActiveTabOnly??!0;for(const[s,n]of this.subagentWindows){const i=this.subagentParentMap.get(s),o=this.subagents.get(s),l=i||o?.parentSessionId;let a;t?a=!!!l||l===this.activeSessionId:a=!0,a?(n.minimized||(n.element.style.display="flex",n._lazyTerminal&&this._restoreTeammateTerminalFromLazy(s)),n.hidden=!1):(this._disposeTeammateTerminalForMinimize(s),n.element.style.display="none",n.hidden=!0)}this.updateConnectionLines(),this.relayoutMobileSubagentWindows()}closeSessionSubagentWindows(e,t=!1){const s=[];for(const[n,i]of this.subagentWindows){const o=this.subagents.get(n),l=this.subagentParentMap.get(n);(o?.parentSessionId===e||l===e)&&s.push(n)}for(const n of s)this.forceCloseSubagentWindow(n),t&&(this.subagents.delete(n),this.subagentActivity.delete(n),this.subagentToolResults.delete(n),this.subagentParentMap.delete(n));this.minimizedSubagents.delete(e),this.renderSessionTabs()}forceCloseSubagentWindow(e){const t=this.subagentWindows.get(e);t&&(t.resizeObserver&&t.resizeObserver.disconnect(),t.dragListeners&&(document.removeEventListener("mousemove",t.dragListeners.move),document.removeEventListener("mouseup",t.dragListeners.up),t.dragListeners.touchMove&&(document.removeEventListener("touchmove",t.dragListeners.touchMove),document.removeEventListener("touchend",t.dragListeners.up),document.removeEventListener("touchcancel",t.dragListeners.up)),t.dragListeners.handle&&(t.dragListeners.handle.removeEventListener("mousedown",t.dragListeners.handleMouseDown),t.dragListeners.handle.removeEventListener("touchstart",t.dragListeners.handleTouchStart))),t.element.remove(),this.subagentWindows.delete(e));const s=this.teammateTerminals.get(e);if(s){if(s.resizeObserver&&s.resizeObserver.disconnect(),s.terminal)try{s.terminal.dispose()}catch{}this.teammateTerminals.delete(e)}}minimizeSubagentWindow(e){const t=this.subagentWindows.get(e);t&&(this._disposeTeammateTerminalForMinimize(e),t.element.style.display="none",t.minimized=!0,this.updateConnectionLines())}scheduleSubagentWindowRender(e){this.subagentWindows.get(e)?.minimized||(this._subagentWindowRenderTimeouts||(this._subagentWindowRenderTimeouts=new Map),this._subagentWindowRenderTimeouts.has(e)&&clearTimeout(this._subagentWindowRenderTimeouts.get(e)),this._subagentWindowRenderTimeouts.set(e,setTimeout(()=>{this._subagentWindowRenderTimeouts.delete(e),scheduleBackground(()=>this.renderSubagentWindowContent(e))},100)))}renderSubagentWindowContent(e){if(this.teammateTerminals.has(e)||this.subagentWindows.get(e)?._lazyTerminal)return;const s=document.getElementById(`subagent-window-body-${e}`);if(!s)return;const n=this.subagentActivity.get(e)||[];if(n.length===0){s.innerHTML='<div class="subagent-empty">No activity yet</div>';return}const i=s.dataset.renderedCount?parseInt(s.dataset.renderedCount,10):0,o=100,l=n.slice(-o);if(i===0||i>l.length||s.children.length===0||s.children.length===1&&s.querySelector(".subagent-empty")){const a=l.map(r=>this._renderActivityItem(r)).join("");s.innerHTML=a,s.dataset.renderedCount=String(l.length)}else{const a=l.slice(i);if(a.length>0){const r=a.map(c=>this._renderActivityItem(c)).join("");for(s.insertAdjacentHTML("beforeend",r),s.dataset.renderedCount=String(l.length);s.children.length>o;)s.removeChild(s.firstChild)}}s.scrollTop=s.scrollHeight}_renderActivityItem(e){const t=new Date(e.timestamp).toLocaleTimeString("en-US",{hour12:!1});if(e.type==="tool")return`<div class="activity-line">
|
|
268
268
|
<span class="time">${t}</span>
|
|
269
269
|
<span class="tool-icon">${this.getToolIcon(e.tool)}</span>
|
|
270
270
|
<span class="tool-name">${e.tool}</span>
|
|
@@ -280,10 +280,10 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
280
280
|
<span class="tool-detail">${escapeHtml(i)}</span>
|
|
281
281
|
</div>`}else if(e.type==="message"){const s=e.text.length>150?e.text.substring(0,150)+"...":e.text;return`<div class="message-line">
|
|
282
282
|
<span class="time">${t}</span> \u{1F4AC} ${escapeHtml(s)}
|
|
283
|
-
</div>`}return""}updateSubagentWindows(){for(const e of this.subagentWindows.keys())this.renderSubagentWindowContent(e),this.updateSubagentWindowHeader(e)}updateSubagentWindowHeader(e){const t=this.subagents.get(e);if(!t)return;const s=document.getElementById(`subagent-window-${e}`);if(!s)return;const n=s.querySelector(".subagent-window-title .id");if(n){const c=this.getTeammateInfo(t),d=c?c.name:t.description||e.substring(0,7),u=d.length>50?d.substring(0,50)+"...":d;n.textContent=u}let i=s.querySelector(".teammate-badge");const o=this.getTeammateInfo(t);if(o&&!i){const c=s.querySelector(".subagent-window-title");if(c){const d=document.createElement("span");d.className=`teammate-badge teammate-color-${o.color}`,d.title=`Team: ${o.teamName}`,d.textContent=`@${o.name}`;const u=c.querySelector(".status");u&&u.insertAdjacentElement("beforebegin",d)}}const l=s.querySelector(".subagent-window-title");l&&(l.title=t.description||e);let a=s.querySelector(".subagent-window-title .subagent-model-badge");if(t.modelShort){if(!a){a=document.createElement("span"),a.className=`subagent-model-badge ${t.modelShort}`;const c=s.querySelector(".subagent-window-title .status");c&&c.insertAdjacentElement("beforebegin",a)}a.className=`subagent-model-badge ${t.modelShort}`,a.textContent=t.modelShort}const r=s.querySelector(".subagent-window-title .status");r&&(r.className=`status ${t.status}`,r.textContent=t.status)}openAllActiveSubagentWindows(){for(const[e,t]of this.subagents)t.status==="active"&&!this.subagentWindows.has(e)&&this.openSubagentWindow(e)}initTeammateTerminal(e,t,s){const n=s.querySelector(".subagent-window-body");if(!n)return;n.innerHTML="",n.classList.add("teammate-terminal-body"),s.classList.add("has-terminal");const i=t.sessionId,o=[];this.teammateTerminals.set(e,{terminal:null,fitAddon:null,paneTarget:t.paneTarget,sessionId:i,resizeObserver:null,pendingData:o}),requestAnimationFrame(()=>{if(!document.contains(n)){this.teammateTerminals.delete(e);return}const l=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:12,lineHeight:1.2,cursorBlink:!0,cursorStyle:"block",scrollback:5e3,allowTransparency:!0,allowProposedApi:!0}),a=new FitAddon.FitAddon;if(l.loadAddon(a),typeof Unicode11Addon<"u")try{const d=new Unicode11Addon.Unicode11Addon;l.loadAddon(d),l.unicode.activeVersion="11"}catch{}try{l.open(n)}catch(d){console.warn("[TeammateTerminal] Failed to open terminal:",d),this.teammateTerminals.delete(e);return}setTimeout(()=>{try{a.fit()}catch{}fetch(`/api/sessions/${i}/teammate-pane-buffer/${encodeURIComponent(t.paneTarget)}`).then(d=>d.json()).then(d=>{if(d.success&&d.data?.buffer)try{l.write(d.data.buffer)}catch{}}).catch(d=>console.error("[TeammateTerminal] Failed to fetch buffer:",d));for(const d of o)try{l.write(d)}catch{}o.length=0},100),l.onData(d=>{fetch(`/api/sessions/${i}/teammate-pane-input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paneTarget:t.paneTarget,input:d})}).catch(u=>console.error("[TeammateTerminal] Failed to send input:",u))});const r=new ResizeObserver(()=>{requestAnimationFrame(()=>{try{a.fit()}catch{}})});r.observe(n);const c=this.teammateTerminals.get(e);c&&(c.terminal=l,c.fitAddon=a,c.resizeObserver=r)})}openTeammateTerminalWindow(e){if(!this.sessions.has(e.sessionId))return;const t=`pane-${e.paneTarget}`;if(this.subagentWindows.has(t)){const
|
|
283
|
+
</div>`}return""}updateSubagentWindows(){for(const e of this.subagentWindows.keys())this.renderSubagentWindowContent(e),this.updateSubagentWindowHeader(e)}updateSubagentWindowHeader(e){const t=this.subagents.get(e);if(!t)return;const s=document.getElementById(`subagent-window-${e}`);if(!s)return;const n=s.querySelector(".subagent-window-title .id");if(n){const c=this.getTeammateInfo(t),d=c?c.name:t.description||e.substring(0,7),u=d.length>50?d.substring(0,50)+"...":d;n.textContent=u}let i=s.querySelector(".teammate-badge");const o=this.getTeammateInfo(t);if(o&&!i){const c=s.querySelector(".subagent-window-title");if(c){const d=document.createElement("span");d.className=`teammate-badge teammate-color-${o.color}`,d.title=`Team: ${o.teamName}`,d.textContent=`@${o.name}`;const u=c.querySelector(".status");u&&u.insertAdjacentElement("beforebegin",d)}}const l=s.querySelector(".subagent-window-title");l&&(l.title=t.description||e);let a=s.querySelector(".subagent-window-title .subagent-model-badge");if(t.modelShort){if(!a){a=document.createElement("span"),a.className=`subagent-model-badge ${t.modelShort}`;const c=s.querySelector(".subagent-window-title .status");c&&c.insertAdjacentElement("beforebegin",a)}a.className=`subagent-model-badge ${t.modelShort}`,a.textContent=t.modelShort}const r=s.querySelector(".subagent-window-title .status");r&&(r.className=`status ${t.status}`,r.textContent=t.status)}openAllActiveSubagentWindows(){for(const[e,t]of this.subagents)t.status==="active"&&!this.subagentWindows.has(e)&&this.openSubagentWindow(e)}initTeammateTerminal(e,t,s){const n=s.querySelector(".subagent-window-body");if(!n)return;n.innerHTML="",n.classList.add("teammate-terminal-body"),s.classList.add("has-terminal");const i=t.sessionId,o=[];this.teammateTerminals.set(e,{terminal:null,fitAddon:null,paneTarget:t.paneTarget,sessionId:i,resizeObserver:null,pendingData:o}),requestAnimationFrame(()=>{if(!document.contains(n)){this.teammateTerminals.delete(e);return}const l=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:12,lineHeight:1.2,cursorBlink:!0,cursorStyle:"block",scrollback:5e3,allowTransparency:!0,allowProposedApi:!0}),a=new FitAddon.FitAddon;if(l.loadAddon(a),typeof Unicode11Addon<"u")try{const d=new Unicode11Addon.Unicode11Addon;l.loadAddon(d),l.unicode.activeVersion="11"}catch{}try{l.open(n)}catch(d){console.warn("[TeammateTerminal] Failed to open terminal:",d),this.teammateTerminals.delete(e);return}setTimeout(()=>{try{a.fit()}catch{}fetch(`/api/sessions/${i}/teammate-pane-buffer/${encodeURIComponent(t.paneTarget)}`).then(d=>d.json()).then(d=>{if(d.success&&d.data?.buffer)try{l.write(d.data.buffer)}catch{}}).catch(d=>console.error("[TeammateTerminal] Failed to fetch buffer:",d));for(const d of o)try{l.write(d)}catch{}o.length=0},100),l.onData(d=>{fetch(`/api/sessions/${i}/teammate-pane-input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paneTarget:t.paneTarget,input:d})}).catch(u=>console.error("[TeammateTerminal] Failed to send input:",u))});const r=new ResizeObserver(()=>{requestAnimationFrame(()=>{try{a.fit()}catch{}})});r.observe(n);const c=this.teammateTerminals.get(e);c&&(c.terminal=l,c.fitAddon=a,c.resizeObserver=r)})}openTeammateTerminalWindow(e){if(!this.sessions.has(e.sessionId))return;const t=`pane-${e.paneTarget}`;if(this.subagentWindows.has(t)){const T=this.subagentWindows.get(t);T.hidden&&(T.element.style.display="flex",T.hidden=!1),T.element.style.zIndex=++this.subagentWindowZIndex,T.minimized&&this.restoreSubagentWindow(t);return}const s=this.subagentWindows.size,n=550,i=400,o=20,l=window.innerWidth,a=window.innerHeight,r=50,c=120,d=Math.floor((l-r-50)/(n+o))||1,u=Math.floor((a-c-50)/(i+o))||1,h=s%d,m=Math.floor(s/d)%u;let p=r+h*(n+o),g=c+m*(i+o);p=Math.max(10,Math.min(p,l-n-10)),g=Math.max(10,Math.min(g,a-i-10));const S=e.color||"blue",f=document.createElement("div");f.className="subagent-window has-terminal",f.id=`subagent-window-${t}`,f.style.zIndex=++this.subagentWindowZIndex,f.style.left=`${p}px`,f.style.top=`${g}px`,f.style.width=`${n}px`,f.style.height=`${i}px`,f.innerHTML=`
|
|
284
284
|
<div class="subagent-window-header">
|
|
285
285
|
<div class="subagent-window-title" title="Teammate terminal: ${escapeHtml(e.teammateName)} (pane ${e.paneTarget})">
|
|
286
|
-
<span class="icon" style="color: var(--team-color-${
|
|
286
|
+
<span class="icon" style="color: var(--team-color-${S}, #339af0)">\u2B24</span>
|
|
287
287
|
<span class="id">${escapeHtml(e.teammateName)}</span>
|
|
288
288
|
<span class="status running">terminal</span>
|
|
289
289
|
</div>
|
|
@@ -293,10 +293,10 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
293
293
|
</div>
|
|
294
294
|
<div class="subagent-window-body teammate-terminal-body" id="subagent-window-body-${t}">
|
|
295
295
|
</div>
|
|
296
|
-
`,document.body.appendChild(
|
|
296
|
+
`,document.body.appendChild(f);const w=this.makeWindowDraggable(f,f.querySelector(".subagent-window-header"));typeof this.makeWindowResizable=="function"&&this.makeWindowResizable(f);const b=(this.loadAppSettingsFromStorage().subagentActiveTabOnly??!0)&&e.sessionId!==this.activeSessionId;this.subagentWindows.set(t,{element:f,minimized:!1,hidden:b,dragListeners:w,description:`Teammate: ${e.teammateName}`}),this.subagentParentMap.set(t,e.sessionId),b&&(f.style.display="none"),f.addEventListener("mousedown",()=>{f.style.zIndex=++this.subagentWindowZIndex});const I=new ResizeObserver(()=>{this.updateConnectionLines()});if(I.observe(f),this.subagentWindows.get(t).resizeObserver=I,b){const T=this.subagentWindows.get(t);T&&(T._lazyTerminal=!0,T._lazyPaneTarget=e.paneTarget,T._lazySessionId=e.sessionId)}else this.initTeammateTerminal(t,e,f);requestAnimationFrame(()=>{f.style.transition="transform 0.3s ease, opacity 0.3s ease",f.style.transform="scale(1)",f.style.opacity="1"})}rebuildTeammateMap(){this.teammateMap.clear();for(const[e,t]of this.teams)for(const s of t.members)s.agentType!=="team-lead"&&this.teammateMap.set(s.name,{name:s.name,color:s.color||"blue",teamName:e,agentId:s.agentId})}getTeammateInfo(e){if(!e?.description)return null;const t=e.description.match(/<teammate-message\s+teammate_id="?([^">\s]+)/);if(!t)return null;const n=t[1].split("@")[0];return this.teammateMap.get(n)||{name:n,color:"blue",teamName:"unknown"}}getTeammateBadgeHtml(e){const t=this.getTeammateInfo(e);return t?`<span class="teammate-badge teammate-color-${t.color}" title="Team: ${escapeHtml(t.teamName)}">@${escapeHtml(t.name)}</span>`:""}renderTeamTasksPanel(){const e=document.getElementById("teamTasksPanel");if(!e)return;let t=null,s=null;if(this.activeSessionId){for(const[m,p]of this.teams)if(p.leadSessionId===this.activeSessionId){t=p,s=m;break}}if(!t){e.style.display="none";return}const n=e.style.display==="none";if(e.style.display="flex",n&&!this.teamTasksDragListeners){e.style.left=`${Math.max(10,window.innerWidth-360-20)}px`,e.style.top=`${Math.max(10,window.innerHeight-300-70)}px`;const g=e.querySelector(".team-tasks-header");g&&(this.teamTasksDragListeners=this.makeWindowDraggable(e,g))}const i=this.teamTasks.get(s)||[],o=i.filter(m=>m.status==="completed").length,l=i.length,a=l>0?Math.round(o/l*100):0,r=e.querySelector(".team-tasks-header-text");if(r){const m=t.members.filter(p=>p.agentType!=="team-lead").length;r.textContent=`Team Tasks (${m} teammates)`}const c=e.querySelector(".team-tasks-progress-fill");c&&(c.style.width=`${a}%`);const d=e.querySelector(".team-tasks-progress-text");d&&(d.textContent=`${o}/${l}`);const u=e.querySelector(".team-tasks-list");if(!u)return;if(i.length===0){u.innerHTML='<div class="team-task-empty">No tasks yet</div>';return}const h=i.map(m=>{const p=m.status==="completed"?"\u2713":m.status==="in_progress"?"\u25C9":"\u25CB",g=m.status.replace("_","-"),S=m.owner?`<span class="team-task-owner teammate-color-${this.getTeammateColor(m.owner)}">${escapeHtml(m.owner)}</span>`:"";return`<div class="team-task-item ${g}">
|
|
297
297
|
<span class="team-task-status">${p}</span>
|
|
298
298
|
<span class="team-task-subject">${escapeHtml(m.subject)}</span>
|
|
299
|
-
${
|
|
299
|
+
${S}
|
|
300
300
|
</div>`}).join("");u.innerHTML=h}hideTeamTasksPanel(){const e=document.getElementById("teamTasksPanel");e&&(e.style.display="none"),this.teamTasksDragListeners&&(document.removeEventListener("mousemove",this.teamTasksDragListeners.move),document.removeEventListener("mouseup",this.teamTasksDragListeners.up),this.teamTasksDragListeners.touchMove&&(document.removeEventListener("touchmove",this.teamTasksDragListeners.touchMove),document.removeEventListener("touchend",this.teamTasksDragListeners.up),document.removeEventListener("touchcancel",this.teamTasksDragListeners.up)),this.teamTasksDragListeners.handle&&(this.teamTasksDragListeners.handle.removeEventListener("mousedown",this.teamTasksDragListeners.handleMouseDown),this.teamTasksDragListeners.handle.removeEventListener("touchstart",this.teamTasksDragListeners.handleTouchStart)),this.teamTasksDragListeners=null)}getTeammateColor(e){return this.teammateMap.get(e)?.color||"blue"}normalizeFilePath(e,t){if(!e)return"";let s=e.trim();const n="/home/"+(window.USER||"user");s.startsWith("~/")?s=n+s.slice(1):s==="~"&&(s=n),!s.startsWith("/")&&t&&(s=t+"/"+s);const i=s.split("/"),o=[];for(const l of i)l===""||l==="."||(l===".."?o.length>1&&o.pop():o.push(l));return"/"+o.join("/")}getFilename(e){const t=e.split("/");return t[t.length-1]||""}isShallowRootPath(e){return e.startsWith("/")?e.split("/").filter(s=>s!=="").length===1:!1}isPathInWorkingDir(e,t){if(!t)return!1;const s=this.normalizeFilePath(e,t);return s.startsWith(t+"/")||s===t}pathsAreEquivalent(e,t,s){const n=this.normalizeFilePath(e,s),i=this.normalizeFilePath(t,s);if(n===i)return!0;const o=this.getFilename(n),l=this.getFilename(i);if(o!==l)return!1;const a=this.isShallowRootPath(e),r=this.isShallowRootPath(t),c=this.isPathInWorkingDir(n,s),d=this.isPathInWorkingDir(i,s);return!!(a&&d||r&&c)}pickBetterPath(e,t,s){if(s){const o=this.isPathInWorkingDir(e,s),l=this.isPathInWorkingDir(t,s);if(o&&!l)return e;if(l&&!o)return t}const n=e.startsWith("/"),i=t.startsWith("/");return n&&!i?e:i&&!n?t:e.length!==t.length?e.length>t.length?e:t:!e.includes("~")&&t.includes("~")?e:!t.includes("~")&&e.includes("~")?t:e}deduplicateProjectInsightPaths(e,t){const s=[];for(const o of e)for(const l of o.filePaths)s.push({rawPath:l,toolId:o.id});if(s.length<=1){const o=new Map;for(const l of s)o.set(this.normalizeFilePath(l.rawPath,t),l);return o}s.sort((o,l)=>{const a=this.isPathInWorkingDir(o.rawPath,t),r=this.isPathInWorkingDir(l.rawPath,t);return a&&!r?-1:r&&!a?1:l.rawPath.length-o.rawPath.length});const n=new Map,i=new Set;for(const{rawPath:o,toolId:l}of s){const a=this.normalizeFilePath(o,t);let r=!1;for(const[,c]of n)if(this.pathsAreEquivalent(o,c.rawPath,t)){r=!0;break}!r&&!i.has(a)&&(n.set(a,{rawPath:o,toolId:l}),i.add(a))}return n}handleBashToolStart(e,t){let s=this.projectInsights.get(e)||[];s=s.filter(n=>n.id!==t.id),s.push(t),this.projectInsights.set(e,s),this.renderProjectInsightsPanel()}handleBashToolEnd(e,t){const n=(this.projectInsights.get(e)||[]).find(i=>i.id===t.id);n&&(n.status="completed"),this.renderProjectInsightsPanel(),setTimeout(()=>{const i=this.projectInsights.get(e)||[];this.projectInsights.set(e,i.filter(o=>o.id!==t.id)),this.renderProjectInsightsPanel()},2e3)}handleBashToolsUpdate(e,t){this.projectInsights.set(e,t),this.renderProjectInsightsPanel()}renderProjectInsightsPanel(){const e=this.$("projectInsightsPanel"),t=this.$("projectInsightsList");if(!e||!t)return;if(!(this.loadAppSettingsFromStorage().showProjectInsights??!1)){e.classList.remove("visible"),this.projectInsightsPanelVisible=!1;return}const o=(this.projectInsights.get(this.activeSessionId)||[]).filter(u=>u.status==="running");if(o.length===0){e.classList.remove("visible"),this.projectInsightsPanelVisible=!1;return}e.classList.add("visible"),this.projectInsightsPanelVisible=!0;const a=this.sessions.get(this.activeSessionId)?.workingDir||this.currentSessionWorkingDir,r=this.deduplicateProjectInsightPaths(o,a),c=new Set(Array.from(r.values()).map(u=>u.rawPath)),d=[];for(const u of o){const h=u.filePaths.filter(p=>c.has(p));if(h.length===0)continue;const m=u.command.length>50?u.command.substring(0,50)+"...":u.command;d.push(`
|
|
301
301
|
<div class="project-insight-item" data-tool-id="${u.id}">
|
|
302
302
|
<div class="project-insight-command">
|
|
@@ -313,14 +313,14 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
313
313
|
`)}d.push(`
|
|
314
314
|
</div>
|
|
315
315
|
</div>
|
|
316
|
-
`)}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){console.error("Failed to load file browser:",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>`:"",
|
|
316
|
+
`)}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){console.error("Failed to load file browser:",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>`:"",S=a?"file-tree-name directory":"file-tree-name";if(s.push(`
|
|
317
317
|
<div class="file-tree-item${h}" data-path="${escapeHtml(o.path)}" data-type="${o.type}" data-depth="${l}">
|
|
318
318
|
${p}
|
|
319
319
|
<span class="file-tree-icon">${m}</span>
|
|
320
|
-
<span class="${
|
|
320
|
+
<span class="${S}">${escapeHtml(o.name)}</span>
|
|
321
321
|
${g}
|
|
322
322
|
</div>
|
|
323
|
-
`),a&&r&&o.children)for(const
|
|
323
|
+
`),a&&r&&o.children)for(const f of o.children)i(f,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){console.error("Failed to preview file:",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=`
|
|
324
324
|
<div class="log-viewer-window-header">
|
|
325
325
|
<div class="log-viewer-window-title" title="${escapeHtml(e)}">
|
|
326
326
|
<span class="icon">\u{1F4C4}</span>
|
|
@@ -334,25 +334,25 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
334
334
|
<div class="log-viewer-window-body" id="log-viewer-body-${s}">
|
|
335
335
|
<div class="log-info">Connecting to ${escapeHtml(e)}...</div>
|
|
336
336
|
</div>
|
|
337
|
-
`,document.body.appendChild(a);const r=this.makeWindowDraggable(a,a.querySelector(".log-viewer-window-header")),c=new EventSource(`/api/sessions/${t}/tail-file?path=${encodeURIComponent(e)}&lines=50`);c.onmessage=d=>{const u=JSON.parse(d.data),h=document.getElementById(`log-viewer-body-${s}`);if(h)switch(u.type){case"connected":h.innerHTML="";break;case"data":const m=h.scrollTop+h.clientHeight>=h.scrollHeight-10,p=escapeHtml(u.content);h.innerHTML+=p,m&&(h.scrollTop=h.scrollHeight),h.innerHTML.length>5e5&&(h.innerHTML=h.innerHTML.slice(-4e5));break;case"end":this.updateLogViewerStatus(s,"disconnected","ended");break;case"error":h.innerHTML+=`<div class="log-error">${escapeHtml(u.error)}</div>`,this.updateLogViewerStatus(s,"error","error");break}},c.onerror=()=>{this.updateLogViewerStatus(s,"disconnected","connection error")},this.logViewerWindows.set(s,{element:a,eventSource:c,filePath:e,sessionId:t,dragListeners:r})}updateLogViewerStatus(e,t,s){const n=document.querySelector(`#log-viewer-window-${e} .status`);n&&(n.className=`status ${t}`,n.textContent=s)}closeLogViewerWindow(e){const t=this.logViewerWindows.get(e);t&&(t.eventSource&&t.eventSource.close(),t.dragListeners&&(document.removeEventListener("mousemove",t.dragListeners.move),document.removeEventListener("mouseup",t.dragListeners.up),t.dragListeners.handle&&(t.dragListeners.handle.removeEventListener("mousedown",t.dragListeners.handleMouseDown),t.dragListeners.handle.removeEventListener("touchstart",t.dragListeners.handleTouchStart))),t.element.remove(),this.logViewerWindows.delete(e))}closeSessionLogViewerWindows(e){const t=[];for(const[s,n]of this.logViewerWindows)n.sessionId===e&&t.push(s);for(const s of t)this.closeLogViewerWindow(s)}openImagePopup(e){const{sessionId:t,filePath:s,relativePath:n,fileName:i,timestamp:o,size:l}=e,a=`${t}-${o}`;if(this.imagePopups.has(a)){const y=this.imagePopups.get(a);y.element.style.zIndex=++this.imagePopupZIndex;return}if(this.imagePopups.size>=20){const y=this.imagePopups.keys().next().value;y&&this.closeImagePopup(y)}const c=this.imagePopups.size,d=(window.innerWidth-600)/2,u=(window.innerHeight-500)/2,h=d+c%5*30,m=u+c%5*30,g=this.sessions.get(t)?.name||t.substring(0,8),
|
|
337
|
+
`,document.body.appendChild(a);const r=this.makeWindowDraggable(a,a.querySelector(".log-viewer-window-header")),c=new EventSource(`/api/sessions/${t}/tail-file?path=${encodeURIComponent(e)}&lines=50`);c.onmessage=d=>{const u=JSON.parse(d.data),h=document.getElementById(`log-viewer-body-${s}`);if(h)switch(u.type){case"connected":h.innerHTML="";break;case"data":const m=h.scrollTop+h.clientHeight>=h.scrollHeight-10,p=escapeHtml(u.content);h.innerHTML+=p,m&&(h.scrollTop=h.scrollHeight),h.innerHTML.length>5e5&&(h.innerHTML=h.innerHTML.slice(-4e5));break;case"end":this.updateLogViewerStatus(s,"disconnected","ended");break;case"error":h.innerHTML+=`<div class="log-error">${escapeHtml(u.error)}</div>`,this.updateLogViewerStatus(s,"error","error");break}},c.onerror=()=>{this.updateLogViewerStatus(s,"disconnected","connection error")},this.logViewerWindows.set(s,{element:a,eventSource:c,filePath:e,sessionId:t,dragListeners:r})}updateLogViewerStatus(e,t,s){const n=document.querySelector(`#log-viewer-window-${e} .status`);n&&(n.className=`status ${t}`,n.textContent=s)}closeLogViewerWindow(e){const t=this.logViewerWindows.get(e);t&&(t.eventSource&&t.eventSource.close(),t.dragListeners&&(document.removeEventListener("mousemove",t.dragListeners.move),document.removeEventListener("mouseup",t.dragListeners.up),t.dragListeners.handle&&(t.dragListeners.handle.removeEventListener("mousedown",t.dragListeners.handleMouseDown),t.dragListeners.handle.removeEventListener("touchstart",t.dragListeners.handleTouchStart))),t.element.remove(),this.logViewerWindows.delete(e))}closeSessionLogViewerWindows(e){const t=[];for(const[s,n]of this.logViewerWindows)n.sessionId===e&&t.push(s);for(const s of t)this.closeLogViewerWindow(s)}openImagePopup(e){const{sessionId:t,filePath:s,relativePath:n,fileName:i,timestamp:o,size:l}=e,a=`${t}-${o}`;if(this.imagePopups.has(a)){const y=this.imagePopups.get(a);y.element.style.zIndex=++this.imagePopupZIndex;return}if(this.imagePopups.size>=20){const y=this.imagePopups.keys().next().value;y&&this.closeImagePopup(y)}const c=this.imagePopups.size,d=(window.innerWidth-600)/2,u=(window.innerHeight-500)/2,h=d+c%5*30,m=u+c%5*30,g=this.sessions.get(t)?.name||t.substring(0,8),S=(l/1024).toFixed(1),f=`/api/sessions/${t}/file-raw?path=${encodeURIComponent(n||i)}`,w=document.createElement("div");w.className="image-popup-window",w.id=`image-popup-${a}`,w.style.left=`${h}px`,w.style.top=`${m}px`,w.style.zIndex=++this.imagePopupZIndex,w.innerHTML=`
|
|
338
338
|
<div class="image-popup-header">
|
|
339
339
|
<div class="image-popup-title" title="${escapeHtml(s)}">
|
|
340
340
|
<span class="icon">\u{1F5BC}\uFE0F</span>
|
|
341
341
|
<span class="filename">${escapeHtml(i)}</span>
|
|
342
342
|
<span class="session-badge">${escapeHtml(g)}</span>
|
|
343
|
-
<span class="size-badge">${
|
|
343
|
+
<span class="size-badge">${S} KB</span>
|
|
344
344
|
</div>
|
|
345
345
|
<div class="image-popup-actions">
|
|
346
|
-
<button onclick="app.openImageInNewTab('${escapeHtml(
|
|
346
|
+
<button onclick="app.openImageInNewTab('${escapeHtml(f)}')" title="Open in new tab">\u2197</button>
|
|
347
347
|
<button onclick="app.closeImagePopup('${escapeHtml(a)}')" title="Close">\xD7</button>
|
|
348
348
|
</div>
|
|
349
349
|
</div>
|
|
350
350
|
<div class="image-popup-body">
|
|
351
|
-
<img src="${
|
|
351
|
+
<img src="${f}" alt="${escapeHtml(i)}"
|
|
352
352
|
onerror="this.parentElement.innerHTML='<div class=\\'image-error\\'>Failed to load image</div>'"
|
|
353
|
-
onclick="app.openImageInNewTab('${escapeHtml(
|
|
353
|
+
onclick="app.openImageInNewTab('${escapeHtml(f)}')" />
|
|
354
354
|
</div>
|
|
355
|
-
`,document.body.appendChild(w);const
|
|
355
|
+
`,document.body.appendChild(w);const E=this.makeWindowDraggable(w,w.querySelector(".image-popup-header"));w.addEventListener("mousedown",()=>{w.style.zIndex=++this.imagePopupZIndex}),this.imagePopups.set(a,{element:w,sessionId:t,filePath:s,dragListeners:E})}closeImagePopup(e){const t=this.imagePopups.get(e);t&&(t.dragListeners&&(document.removeEventListener("mousemove",t.dragListeners.move),document.removeEventListener("mouseup",t.dragListeners.up),t.dragListeners.touchMove&&(document.removeEventListener("touchmove",t.dragListeners.touchMove),document.removeEventListener("touchend",t.dragListeners.up),document.removeEventListener("touchcancel",t.dragListeners.up)),t.dragListeners.handle&&(t.dragListeners.handle.removeEventListener("mousedown",t.dragListeners.handleMouseDown),t.dragListeners.handle.removeEventListener("touchstart",t.dragListeners.handleTouchStart))),t.element.remove(),this.imagePopups.delete(e))}openImageInNewTab(e){window.open(e,"_blank")}closeSessionImagePopups(e){const t=[];for(const[s,n]of this.imagePopups)n.sessionId===e&&t.push(s);for(const s of t)this.closeImagePopup(s)}async loadMuxSessions(){try{const t=await(await fetch("/api/mux-sessions")).json();this.muxSessions=t.sessions||[],this.renderMuxSessions()}catch(e){console.error("Failed to load mux sessions:",e)}}killAllMuxSessions(){const e=this.muxSessions?.length||0;if(e===0){alert("No sessions to kill");return}document.getElementById("killAllCount").textContent=e;const t=document.getElementById("killAllModal");t.classList.add("active"),this.activeFocusTrap=new FocusTrap(t),this.activeFocusTrap.activate()}closeKillAllModal(){document.getElementById("killAllModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)}async confirmKillAll(e){this.closeKillAllModal();try{if(e){if((await(await fetch("/api/sessions",{method:"DELETE"})).json()).success){this.sessions.clear(),this.muxSessions=[],this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.renderSessionTabs(),this.renderMuxSessions(),this.terminal.clear(),this.terminal.reset(),this.toast("All sessions and tmux killed","success")}}else{this.sessions.clear(),this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.renderSessionTabs(),this.terminal.clear(),this.terminal.reset(),this.toast("All tabs removed, tmux still running","info")}}catch(t){console.error("Failed to kill sessions:",t),this.toast("Failed to kill sessions: "+t.message,"error")}}toggleCaseSettings(){const e=document.getElementById("caseSettingsPopover");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeams").checked=s.agentTeams,e.classList.remove("hidden");const n=i=>{!e.contains(i.target)&&!i.target.classList.contains("btn-case-settings")&&(e.classList.add("hidden"),document.removeEventListener("click",n))};setTimeout(()=>document.addEventListener("click",n),0)}else e.classList.add("hidden")}getCaseSettings(e){try{const t=localStorage.getItem("caseSettings_"+e);if(t)return JSON.parse(t)}catch{}return{agentTeams:!1}}saveCaseSettings(e,t){localStorage.setItem("caseSettings_"+e,JSON.stringify(t))}onCaseSettingChanged(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeams").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeamsMobile");s&&(s.checked=t.agentTeams)}toggleCaseSettingsMobile(){const e=document.getElementById("caseSettingsPopoverMobile");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeamsMobile").checked=s.agentTeams,e.classList.remove("hidden");const n=i=>{!e.contains(i.target)&&!i.target.classList.contains("btn-case-settings-mobile")&&(e.classList.add("hidden"),document.removeEventListener("click",n))};setTimeout(()=>document.addEventListener("click",n),0)}else e.classList.add("hidden")}onCaseSettingChangedMobile(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeamsMobile").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeams");s&&(s.checked=t.agentTeams)}showCreateCaseModal(){document.getElementById("newCaseName").value="",document.getElementById("newCaseDescription").value="",document.getElementById("linkCaseName").value="",document.getElementById("linkCasePath").value="",this.caseModalTab="case-create",this.switchCaseModalTab("case-create");const e=document.getElementById("createCaseModal");e.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(t=>{t.onclick=()=>this.switchCaseModalTab(t.dataset.tab)}),e.querySelectorAll('input[type="text"]').forEach(t=>{t._mobileScrollWired||(t._mobileScrollWired=!0,t.addEventListener("focus",()=>{window.innerWidth<=430&&setTimeout(()=>t.scrollIntoView({behavior:"smooth",block:"center"}),300)}))}),e.classList.add("active"),document.getElementById("newCaseName").focus()}switchCaseModalTab(e){this.caseModalTab=e;const t=document.getElementById("createCaseModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(n=>{n.classList.toggle("active",n.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(n=>{n.classList.toggle("hidden",n.id!==e)});const s=document.getElementById("caseModalSubmit");s.textContent=e==="case-create"?"Create":"Link",e==="case-create"?document.getElementById("newCaseName").focus():document.getElementById("linkCaseName").focus()}closeCreateCaseModal(){document.getElementById("createCaseModal").classList.remove("active")}async submitCaseModal(){const e=document.getElementById("caseModalSubmit"),t=e.textContent;e.classList.add("loading"),e.textContent=this.caseModalTab==="case-create"?"Creating...":"Linking...";try{this.caseModalTab==="case-create"?await this.createCase():await this.linkCase()}finally{e.classList.remove("loading"),e.textContent=t}}async createCase(){const e=document.getElementById("newCaseName").value.trim(),t=document.getElementById("newCaseDescription").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}try{const n=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:t})})).json();n.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" created`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(n.error||"Failed to create case","error")}catch(s){console.error("Failed to create case:",s),this.showToast("Failed to create case: "+s.message,"error")}}async linkCase(){const e=document.getElementById("linkCaseName").value.trim(),t=document.getElementById("linkCasePath").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t){this.showToast("Please enter a folder path","error");return}try{const n=await(await fetch("/api/cases/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,path:t})})).json();n.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" linked to ${t}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(n.error||"Failed to link case","error")}catch(s){console.error("Failed to link case:",s),this.showToast("Failed to link case: "+s.message,"error")}}showMobileCasePicker(){const e=document.getElementById("mobileCasePickerModal"),t=document.getElementById("mobileCaseList"),n=document.getElementById("quickStartCase").value;let i="";const o=this.cases||[],a=o.some(r=>r.name==="testcase")?o:[{name:"testcase"},...o];for(const r of a){const c=r.name===n;i+=`
|
|
356
356
|
<button class="mobile-case-item ${c?"selected":""}"
|
|
357
357
|
onclick="app.selectMobileCase('${escapeHtml(r.name)}')">
|
|
358
358
|
<span class="mobile-case-item-icon">
|
|
@@ -367,14 +367,14 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
367
367
|
</svg>
|
|
368
368
|
</span>
|
|
369
369
|
</button>
|
|
370
|
-
`}t.innerHTML=i,e.classList.add("active")}closeMobileCasePicker(){document.getElementById("mobileCasePickerModal").classList.remove("active")}selectMobileCase(e){const t=document.getElementById("quickStartCase");t.value=e,this.updateMobileCaseLabel(e),this.updateDirDisplayForCase(e),this.saveLastUsedCase(e),this.closeMobileCasePicker(),this.showToast(`Selected: ${e}`,"success")}updateMobileCaseLabel(e){const t=document.getElementById("mobileCaseName");t&&(t.textContent=e)}showCreateCaseFromMobile(){this.closeMobileCasePicker(),this.showCreateCaseModal();const e=document.getElementById("createCaseModal");e.classList.add("from-mobile"),setTimeout(()=>e.classList.remove("from-mobile"),300)}renderMuxSessions(){this.renderMuxSessionsTimeout&&clearTimeout(this.renderMuxSessionsTimeout),this.renderMuxSessionsTimeout=setTimeout(()=>{this._renderMuxSessionsImmediate()},100)}_renderMuxSessionsImmediate(){const e=document.getElementById("muxSessionsBody");if(!this.muxSessions||this.muxSessions.length===0){e.innerHTML='<div class="monitor-empty">No mux sessions</div>';return}let t="";for(const s of this.muxSessions){const n=s.stats||{memoryMB:0,cpuPercent:0,childCount:0},i=this.sessions.get(s.sessionId),o=i?i.status:"unknown",l=i?i.isWorking:!1;let a,r;o==="idle"&&!l?(a="IDLE",r="status-idle"):o==="busy"||l?(a="WORKING",r="status-working"):o==="stopped"?(a="STOPPED",r="status-stopped"):(a=o.toUpperCase(),r="");const c=i&&i.tokens?i.tokens:null,d=i?i.totalCost:0,u=i&&i.cliModel||"",h=u.includes("opus")?"opus":u.includes("sonnet")?"sonnet":u.includes("haiku")?"haiku":"",m=i?i.ralphTodoStats:null;let p="";if(m&&m.total>0){const w=Math.round(m.completed/m.total*100);p=`<span class="process-stat todo-progress">${m.completed}/${m.total} (${w}%)</span>`}let g="";c&&c.total>0&&(g=`<span class="process-stat tokens">${(c.total/1e3).toFixed(1)}k tok</span>`);let
|
|
370
|
+
`}t.innerHTML=i,e.classList.add("active")}closeMobileCasePicker(){document.getElementById("mobileCasePickerModal").classList.remove("active")}selectMobileCase(e){const t=document.getElementById("quickStartCase");t.value=e,this.updateMobileCaseLabel(e),this.updateDirDisplayForCase(e),this.saveLastUsedCase(e),this.closeMobileCasePicker(),this.showToast(`Selected: ${e}`,"success")}updateMobileCaseLabel(e){const t=document.getElementById("mobileCaseName");t&&(t.textContent=e)}showCreateCaseFromMobile(){this.closeMobileCasePicker(),this.showCreateCaseModal();const e=document.getElementById("createCaseModal");e.classList.add("from-mobile"),setTimeout(()=>e.classList.remove("from-mobile"),300)}renderMuxSessions(){this.renderMuxSessionsTimeout&&clearTimeout(this.renderMuxSessionsTimeout),this.renderMuxSessionsTimeout=setTimeout(()=>{this._renderMuxSessionsImmediate()},100)}_renderMuxSessionsImmediate(){const e=document.getElementById("muxSessionsBody");if(!this.muxSessions||this.muxSessions.length===0){e.innerHTML='<div class="monitor-empty">No mux sessions</div>';return}let t="";for(const s of this.muxSessions){const n=s.stats||{memoryMB:0,cpuPercent:0,childCount:0},i=this.sessions.get(s.sessionId),o=i?i.status:"unknown",l=i?i.isWorking:!1;let a,r;o==="idle"&&!l?(a="IDLE",r="status-idle"):o==="busy"||l?(a="WORKING",r="status-working"):o==="stopped"?(a="STOPPED",r="status-stopped"):(a=o.toUpperCase(),r="");const c=i&&i.tokens?i.tokens:null,d=i?i.totalCost:0,u=i&&i.cliModel||"",h=u.includes("opus")?"opus":u.includes("sonnet")?"sonnet":u.includes("haiku")?"haiku":"",m=i?i.ralphTodoStats:null;let p="";if(m&&m.total>0){const w=Math.round(m.completed/m.total*100);p=`<span class="process-stat todo-progress">${m.completed}/${m.total} (${w}%)</span>`}let g="";c&&c.total>0&&(g=`<span class="process-stat tokens">${(c.total/1e3).toFixed(1)}k tok</span>`);let S="";d>0&&(S=`<span class="process-stat cost">$${d.toFixed(2)}</span>`);let f="";h&&(f=`<span class="monitor-model-badge ${h}">${h}</span>`),t+=`
|
|
371
371
|
<div class="process-item">
|
|
372
372
|
<span class="monitor-status-badge ${r}">${a}</span>
|
|
373
373
|
<div class="process-info">
|
|
374
|
-
<div class="process-name">${
|
|
374
|
+
<div class="process-name">${f} ${escapeHtml(s.name||s.muxName)}</div>
|
|
375
375
|
<div class="process-meta">
|
|
376
376
|
${g}
|
|
377
|
-
${
|
|
377
|
+
${S}
|
|
378
378
|
${p}
|
|
379
379
|
<span class="process-stat memory">${n.memoryMB}MB</span>
|
|
380
380
|
<span class="process-stat cpu">${n.cpuPercent}%</span>
|