aicodeman 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -4
- package/dist/config/server-timing.d.ts +8 -2
- package/dist/config/server-timing.d.ts.map +1 -1
- package/dist/config/server-timing.js +8 -2
- package/dist/config/server-timing.js.map +1 -1
- package/dist/hooks-config.d.ts +21 -6
- package/dist/hooks-config.d.ts.map +1 -1
- package/dist/hooks-config.js +21 -6
- package/dist/hooks-config.js.map +1 -1
- package/dist/prompts/planner.d.ts +7 -8
- package/dist/prompts/planner.d.ts.map +1 -1
- package/dist/prompts/planner.js +7 -8
- package/dist/prompts/planner.js.map +1 -1
- package/dist/prompts/research-agent.d.ts +6 -4
- package/dist/prompts/research-agent.d.ts.map +1 -1
- package/dist/prompts/research-agent.js +6 -4
- package/dist/prompts/research-agent.js.map +1 -1
- package/dist/ralph-loop.d.ts +14 -4
- package/dist/ralph-loop.d.ts.map +1 -1
- package/dist/ralph-loop.js +14 -4
- package/dist/ralph-loop.js.map +1 -1
- package/dist/ralph-tracker.d.ts +28 -11
- package/dist/ralph-tracker.d.ts.map +1 -1
- package/dist/ralph-tracker.js +43 -13
- package/dist/ralph-tracker.js.map +1 -1
- package/dist/respawn-controller.d.ts +23 -14
- package/dist/respawn-controller.d.ts.map +1 -1
- package/dist/respawn-controller.js +23 -14
- package/dist/respawn-controller.js.map +1 -1
- package/dist/session-manager.d.ts +17 -5
- package/dist/session-manager.d.ts.map +1 -1
- package/dist/session-manager.js +17 -5
- package/dist/session-manager.js.map +1 -1
- package/dist/session.d.ts +21 -8
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +21 -8
- package/dist/session.js.map +1 -1
- package/dist/state-store.d.ts +17 -7
- package/dist/state-store.d.ts.map +1 -1
- package/dist/state-store.js +17 -7
- package/dist/state-store.js.map +1 -1
- package/dist/subagent-watcher.d.ts +23 -3
- package/dist/subagent-watcher.d.ts.map +1 -1
- package/dist/subagent-watcher.js +23 -3
- package/dist/subagent-watcher.js.map +1 -1
- package/dist/tunnel-manager.d.ts.map +1 -1
- package/dist/tunnel-manager.js +1 -2
- package/dist/tunnel-manager.js.map +1 -1
- package/dist/types/api.d.ts +16 -1
- package/dist/types/api.d.ts.map +1 -1
- package/dist/types/api.js +16 -1
- package/dist/types/api.js.map +1 -1
- package/dist/types/app-state.d.ts +18 -1
- package/dist/types/app-state.d.ts.map +1 -1
- package/dist/types/app-state.js +18 -1
- package/dist/types/app-state.js.map +1 -1
- package/dist/types/common.d.ts +10 -1
- package/dist/types/common.d.ts.map +1 -1
- package/dist/types/common.js +10 -1
- package/dist/types/common.js.map +1 -1
- package/dist/types/index.d.ts +50 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +50 -2
- package/dist/types/index.js.map +1 -1
- package/dist/types/lifecycle.d.ts +12 -1
- package/dist/types/lifecycle.d.ts.map +1 -1
- package/dist/types/lifecycle.js +12 -1
- package/dist/types/lifecycle.js.map +1 -1
- package/dist/types/plan.d.ts +14 -1
- package/dist/types/plan.d.ts.map +1 -1
- package/dist/types/plan.js +14 -1
- package/dist/types/plan.js.map +1 -1
- package/dist/types/push.d.ts +14 -1
- package/dist/types/push.d.ts.map +1 -1
- package/dist/types/push.js +14 -1
- package/dist/types/push.js.map +1 -1
- package/dist/types/ralph.d.ts +22 -1
- package/dist/types/ralph.d.ts.map +1 -1
- package/dist/types/ralph.js +22 -1
- package/dist/types/ralph.js.map +1 -1
- package/dist/types/respawn.d.ts +22 -1
- package/dist/types/respawn.d.ts.map +1 -1
- package/dist/types/respawn.js +22 -1
- package/dist/types/respawn.js.map +1 -1
- package/dist/types/run-summary.d.ts +16 -1
- package/dist/types/run-summary.d.ts.map +1 -1
- package/dist/types/run-summary.js +16 -1
- package/dist/types/run-summary.js.map +1 -1
- package/dist/types/session.d.ts +23 -1
- package/dist/types/session.d.ts.map +1 -1
- package/dist/types/session.js +23 -1
- package/dist/types/session.js.map +1 -1
- package/dist/types/task.d.ts +15 -1
- package/dist/types/task.d.ts.map +1 -1
- package/dist/types/task.js +15 -1
- package/dist/types/task.js.map +1 -1
- package/dist/types/teams.d.ts +19 -1
- package/dist/types/teams.d.ts.map +1 -1
- package/dist/types/teams.js +19 -1
- package/dist/types/teams.js.map +1 -1
- package/dist/types/tools.d.ts +16 -1
- package/dist/types/tools.d.ts.map +1 -1
- package/dist/types/tools.js +16 -1
- package/dist/types/tools.js.map +1 -1
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +11 -0
- package/dist/types.js.map +1 -1
- package/dist/web/public/api-client.js +12 -0
- package/dist/web/public/api-client.js.br +0 -0
- package/dist/web/public/api-client.js.gz +0 -0
- package/dist/web/public/app.js +103 -103
- package/dist/web/public/app.js.br +0 -0
- package/dist/web/public/app.js.gz +0 -0
- package/dist/web/public/constants.js +133 -6
- package/dist/web/public/constants.js.br +0 -0
- package/dist/web/public/constants.js.gz +0 -0
- package/dist/web/public/index.html +14 -10
- package/dist/web/public/index.html.br +0 -0
- package/dist/web/public/index.html.gz +0 -0
- package/dist/web/public/keyboard-accessory.js +27 -4
- package/dist/web/public/keyboard-accessory.js.br +0 -0
- package/dist/web/public/keyboard-accessory.js.gz +0 -0
- package/dist/web/public/mobile-handlers.js +30 -6
- package/dist/web/public/mobile-handlers.js.br +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 +27 -0
- package/dist/web/public/notification-manager.js.br +0 -0
- package/dist/web/public/notification-manager.js.gz +0 -0
- package/dist/web/public/ralph-wizard.js +30 -6
- package/dist/web/public/ralph-wizard.js.br +0 -0
- package/dist/web/public/ralph-wizard.js.gz +0 -0
- package/dist/web/public/styles.css +1 -1
- package/dist/web/public/styles.css.br +0 -0
- package/dist/web/public/styles.css.gz +0 -0
- package/dist/web/public/subagent-windows.js +46 -12
- 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 +15 -0
- package/dist/web/public/sw.js.br +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 +4 -0
- package/dist/web/public/vendor/xterm-zerolag-input.js.br +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 +26 -2
- package/dist/web/public/voice-input.js.br +0 -0
- package/dist/web/public/voice-input.js.gz +0 -0
- package/dist/web/route-helpers.d.ts.map +1 -1
- package/dist/web/route-helpers.js +3 -2
- package/dist/web/route-helpers.js.map +1 -1
- package/dist/web/routes/case-routes.d.ts.map +1 -1
- package/dist/web/routes/case-routes.js +11 -4
- package/dist/web/routes/case-routes.js.map +1 -1
- package/dist/web/routes/plan-routes.d.ts.map +1 -1
- package/dist/web/routes/plan-routes.js +26 -22
- package/dist/web/routes/plan-routes.js.map +1 -1
- package/dist/web/routes/ralph-routes.d.ts.map +1 -1
- package/dist/web/routes/ralph-routes.js +16 -6
- package/dist/web/routes/ralph-routes.js.map +1 -1
- package/dist/web/routes/respawn-routes.d.ts.map +1 -1
- package/dist/web/routes/respawn-routes.js +25 -15
- package/dist/web/routes/respawn-routes.js.map +1 -1
- package/dist/web/routes/session-routes.d.ts.map +1 -1
- package/dist/web/routes/session-routes.js +40 -18
- package/dist/web/routes/session-routes.js.map +1 -1
- package/dist/web/routes/system-routes.d.ts.map +1 -1
- package/dist/web/routes/system-routes.js +26 -5
- package/dist/web/routes/system-routes.js.map +1 -1
- package/dist/web/server.d.ts +25 -6
- package/dist/web/server.d.ts.map +1 -1
- package/dist/web/server.js +237 -156
- package/dist/web/server.js.map +1 -1
- package/dist/web/sse-events.d.ts +361 -0
- package/dist/web/sse-events.d.ts.map +1 -0
- package/dist/web/sse-events.js +396 -0
- package/dist/web/sse-events.js.map +1 -0
- package/package.json +4 -1
- package/scripts/postinstall.js +58 -0
package/dist/web/public/app.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
|
-
"use strict";class CodemanApp{constructor(){this.sessions=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 n=e/1e6*15,s=t/1e6*75;return n+s}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 n=this.pendingHooks.get(e);n&&(t?n.delete(t):n.clear(),n.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=n=>{n&&n.addEventListener("touchstart",s=>{if(!KeyboardHandler.keyboardVisible)return;const i=s.target.closest("button");i&&(s.preventDefault(),i.click(),typeof app<"u"&&app.terminal&&app.terminal.focus())},{passive:!1})};t(document.querySelector(".toolbar")),t(document.querySelector(".welcome-overlay"))}this.setupOnlineDetection(),this.loadAppSettingsFromServer(e).then(()=>{this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility()}),document.body.classList.add("app-loaded")}initTerminal(){const e=parseInt(localStorage.getItem("codeman-scrollback"))||DEFAULT_SCROLLBACK;if(this.terminal=new Terminal({theme:{background:"#0d0d0d",foreground:"#e0e0e0",cursor:"#e0e0e0",cursorAccent:"#0d0d0d",selection:"rgba(255, 255, 255, 0.3)",black:"#0d0d0d",red:"#ff6b6b",green:"#51cf66",yellow:"#ffd43b",blue:"#339af0",magenta:"#cc5de8",cyan:"#22b8cf",white:"#e0e0e0",brightBlack:"#495057",brightRed:"#ff8787",brightGreen:"#69db7c",brightYellow:"#ffe066",brightBlue:"#5c7cfa",brightMagenta:"#da77f2",brightCyan:"#66d9e8",brightWhite:"#ffffff"},fontFamily:'"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, monospace',fontSize:MobileDetection.getDeviceType()==="mobile"?10:14,lineHeight:1.2,cursorBlink:!1,cursorStyle:"block",scrollback:e,allowTransparency:!0,allowProposedApi:!0}),this.fitAddon=new FitAddon.FitAddon,this.terminal.loadAddon(this.fitAddon),typeof Unicode11Addon<"u")try{const r=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(r),this.terminal.unicode.activeVersion="11"}catch{}const t=document.getElementById("terminalContainer");if(this.terminal.open(t),typeof WebglAddon<"u")try{const r=new WebglAddon.WebglAddon;r.onContextLoss(()=>{r.dispose()}),this.terminal.loadAddon(r)}catch{}if(this._localEchoOverlay=new LocalEchoOverlay(this.terminal),MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this.registerFilePathLinkProvider(),t.addEventListener("wheel",r=>{r.preventDefault();const c=Math.round(r.deltaY/25)||(r.deltaY>0?1:-1);this.terminal.scrollLines(c)},{passive:!1}),!(MobileDetection.isTouchDevice()&&window.innerWidth<1024)){let r=0,c=0,d=0,u=0,h=null,m=!1;const p=t.querySelector(".xterm-viewport"),g=f=>{if(!p)return;const y=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*y,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 y=f.touches[0].clientY,w=r-y;c+=w,d=w*1.2,r=y}},{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,a=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,a):a;(!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 o=()=>{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,o()}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,o()),setTimeout(()=>{this._pendingInput+="\r",o()},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,o();return}if(this._restoringFlushedState){this._pendingInput+=r,o();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,o(),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),o();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),o();return}const c=performance.now();c-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=c,o()):(this._lastKeystrokeTime=c,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(o,0)))}})}registerFilePathLinkProvider(){const e=this;let t=-1;this.terminal.registerLinkProvider({provideLinks(n,s){n!==t&&(t=n);const a=e.terminal.buffer.active.getLine(n);if(!a){s(void 0);return}const l=a.translateToString(!0);if(!l||!l.includes("/")){s(void 0);return}const o=[],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&&(o.some(f=>f.range.start.x===g+1)||o.push({text:m,range:{start:{x:g+1,y:n},end:{x:g+m.length+1,y:n}},decorations:{pointerCursor:!0,underline:!0},activate(f,y){e.openLogViewerWindow(y,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);o.length>0,s(o.length>0?o:void 0)}})}showWelcome(){const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus())}hideWelcome(){const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const t=document.getElementById("welcomeQr");t&&(clearTimeout(this._welcomeQrShrinkTimer),t.classList.remove("expanded"))}isTerminalAtBottom(){if(!this.terminal)return!0;const e=this.terminal.buffer.active;return e.viewportY>=e.baseY-2}batchTerminalWrite(e){if(this._isLoadingBuffer){this._loadBufferQueue&&this._loadBufferQueue.push(e);return}this.writeFrameScheduled||(this._wasAtBottomBeforeWrite=this.isTerminalAtBottom());const n=(this.activeSessionId?this.sessions.get(this.activeSessionId):null)?.flickerFilterEnabled??!1;if(/\x1b\[\d{1,2}A/.test(e)||this.flickerFilterActive&&!n){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(n){if(e.includes("\x1B[2J")||e.includes("\x1B[H\x1B[J")||e.includes("\x1B[H")&&e.includes("\x1B[?25l")){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(this.flickerFilterActive){this.flickerFilterBuffer+=e;return}}this.pendingWrites.push(e),this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{if(this.pendingWrites.length>0&&this.terminal){const i=this.pendingWrites.join(""),a=i.includes(DEC_SYNC_START),l=i.includes(DEC_SYNC_END);if(a&&!l){this.syncWaitTimeout||(this.syncWaitTimeout=setTimeout(()=>{this.syncWaitTimeout=null,this.flushPendingWrites()},50)),this.writeFrameScheduled=!1;return}this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.flushPendingWrites()}this.writeFrameScheduled=!1}))}flushFlickerBuffer(){this.flickerFilterBuffer&&(this.pendingWrites.push(this.flickerFilterBuffer),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1})))}_updateLocalEchoState(){const e=this.loadAppSettingsFromStorage(),t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,s=!!((e.localEchoEnabled??MobileDetection.isTouchDevice())&&t);this._localEchoEnabled&&!s&&this._localEchoOverlay?.clear(),this._localEchoEnabled=s,this._localEchoOverlay&&t&&(t.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:i=>{try{const a=i.buffer.active,l=a.cursorY,o=a.getLine(a.viewportY+l);if(!o)return null;const c=o.translateToString(!0).indexOf("\u2503");return c>=0?{row:l,col:c}:null}catch{return null}}}):this._localEchoOverlay.setPrompt({type:"character",char:"\u276F",offset:2}))}flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=extractSyncSegments(this.pendingWrites.join(""));this.pendingWrites=[];for(const t of e)if(t){const n=t.startsWith(DEC_SYNC_START)?t.slice(DEC_SYNC_START.length):t;n&&this.terminal.write(n)}if(this._wasAtBottomBeforeWrite&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const t=this._localEchoOverlay,n=this;this.terminal.write("",()=>{if(!n._tabCompletionSessionId)return;t.resetBufferDetection();const s=t.detectBufferText();s?s===n._tabCompletionBaseText?(t.undoDetection(),n._tabCompletionRetries=(n._tabCompletionRetries||0)+1,n._tabCompletionRetries>60&&(n._tabCompletionSessionId=null,n._tabCompletionRetries=0)):(n._tabCompletionSessionId=null,n._tabCompletionRetries=0,n._tabCompletionBaseText=null,n._tabCompletionFallback&&(clearTimeout(n._tabCompletionFallback),n._tabCompletionFallback=null),t.rerender()):(n._tabCompletionRetries=(n._tabCompletionRetries||0)+1,n._tabCompletionRetries>60&&(n._tabCompletionSessionId=null,n._tabCompletionRetries=0))})}}chunkedTerminalWrite(e,t=TERMINAL_CHUNK_SIZE){return new Promise(n=>{if(!e||e.length===0){this._finishBufferLoad(),n();return}this._isLoadingBuffer=!0,this._loadBufferQueue=[];const s=e.replace(DEC_SYNC_STRIP_RE,""),i=()=>{this._finishBufferLoad(),n()};if(s.length<=t){this.terminal.write(s),i();return}let a=0;const l=()=>{if(a>=s.length){requestAnimationFrame(i);return}const o=s.slice(a,a+t);this.terminal.write(o),a+=t,requestAnimationFrame(l)};requestAnimationFrame(l)})}_finishBufferLoad(){const e=this._loadBufferQueue;if(this._isLoadingBuffer=!1,this._loadBufferQueue=null,e&&e.length>0)for(const t of e)this.batchTerminalWrite(t)}setupEventListeners(){document.addEventListener("keydown",t=>{t.key==="Escape"&&(this.closeAllPanels(),this.closeHelp()),(t.ctrlKey||t.metaKey)&&(t.key==="?"||t.key==="/")&&(t.preventDefault(),this.showHelp()),(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.quickStart()),(t.ctrlKey||t.metaKey)&&t.key==="w"&&(t.preventDefault(),this.killActiveSession()),(t.ctrlKey||t.metaKey)&&t.key==="Tab"&&(t.preventDefault(),this.nextSession()),(t.ctrlKey||t.metaKey)&&t.key==="k"&&(t.preventDefault(),this.killAllSessions()),(t.ctrlKey||t.metaKey)&&t.key==="l"&&(t.preventDefault(),this.clearTerminal()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="R"&&(t.preventDefault(),this.restoreTerminalSize()),(t.ctrlKey||t.metaKey)&&(t.key==="="||t.key==="+")&&(t.preventDefault(),this.increaseFontSize()),(t.ctrlKey||t.metaKey)&&t.key==="-"&&(t.preventDefault(),this.decreaseFontSize()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="V"&&(t.preventDefault(),VoiceInput.toggle())},!0);const e=this.$("headerTokens");e&&!e._statsHandlerAttached&&(e.classList.add("clickable"),e._statsHandlerAttached=!0,e.addEventListener("click",()=>this.openTokenStats())),this.setupColorPicker()}connectSSE(){if(!navigator.onLine){this.setConnectionStatus("offline");return}this.sseReconnectTimeout&&(clearTimeout(this.sseReconnectTimeout),this.sseReconnectTimeout=null),this._sseListenerCleanup&&(this._sseListenerCleanup(),this._sseListenerCleanup=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.reconnectAttempts===0?this.setConnectionStatus("connecting"):this.setConnectionStatus("reconnecting"),this.eventSource=new EventSource("/api/events");const e=[],t=(n,s)=>{this.eventSource.addEventListener(n,s),e.push({event:n,handler:s})};this._sseListenerCleanup=()=>{for(const{event:n,handler:s}of e)this.eventSource&&this.eventSource.removeEventListener(n,s);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 n=this.reconnectAttempts<=1?200:Math.min(500*Math.pow(2,this.reconnectAttempts-2),3e4);this.sseReconnectTimeout=setTimeout(()=>this.connectSSE(),n)},t("init",n=>{try{this.handleInit(JSON.parse(n.data))}catch{}}),t("session:created",n=>{const s=JSON.parse(n.data);this.sessions.set(s.id,s),this.sessionOrder.includes(s.id)||(this.sessionOrder.push(s.id),this.saveSessionOrder()),this.renderSessionTabs(),this.updateCost(),this.sessions.size===1&&this.startSystemStatsPolling()}),t("session:updated",n=>{const s=JSON.parse(n.data),i=s.session||s,a=this.sessions.get(i.id),l=i.claudeSessionId&&(!a||!a.claudeSessionId);this.sessions.set(i.id,i),this.renderSessionTabs(),this.updateCost(),i.id===this.activeSessionId&&i.tokens&&this.updateRespawnTokens(i.tokens),this.updateSubagentParentNames(i.id),l&&(this.recheckOrphanSubagents(),requestAnimationFrame(()=>{this.updateConnectionLines()}))}),t("session:deleted",n=>{const s=JSON.parse(n.data);if(this._cleanupSessionData(s.id),this.activeSessionId===s.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()}),t("session:terminal",n=>{const s=JSON.parse(n.data);s.id===this.activeSessionId&&this.batchTerminalWrite(s.data)}),t("session:needsRefresh",async()=>{if(!(!this.activeSessionId||!this.terminal))try{const i=await(await fetch(`/api/sessions/${this.activeSessionId}/terminal?tail=262144`)).json();i.terminalBuffer&&(this.terminal.clear(),this.terminal.reset(),await this.chunkedTerminalWrite(i.terminalBuffer),this.terminal.scrollToBottom(),this._localEchoOverlay?.rerender(),this.activeSessionId&&this.sendResize(this.activeSessionId))}catch{}}),t("session:clearTerminal",async n=>{const s=JSON.parse(n.data);if(s.id===this.activeSessionId)try{const a=await(await fetch(`/api/sessions/${s.id}/terminal`)).json();if(this.terminal.clear(),this.terminal.reset(),a.terminalBuffer){const l=a.terminalBuffer.replace(DEC_SYNC_STRIP_RE,"");await this.chunkedTerminalWrite(l)}this.sendResize(s.id),this._localEchoOverlay?.rerender()}catch{}}),t("session:completion",n=>{const s=JSON.parse(n.data);this.totalCost+=s.cost||0,this.updateCost(),s.id===this.activeSessionId&&(this.terminal.writeln(""),this.terminal.writeln(`\x1B[1;32m Done (Cost: $${(s.cost||0).toFixed(4)})\x1B[0m`))}),t("session:error",n=>{const s=JSON.parse(n.data);s.id===this.activeSessionId&&this.terminal.writeln(`\x1B[1;31m Error: ${s.error}\x1B[0m`);const i=this.sessions.get(s.id);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:s.id,sessionName:i?.name||s.id?.slice(0,8),title:"Session Error",message:s.error||"Unknown error"})}),t("session:exit",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.id);i&&(i.status="stopped",this.renderSessionTabs(),s.id===this.activeSessionId&&this._updateLocalEchoState()),s.code&&s.code!==0&&this.notificationManager?.notify({urgency:"critical",category:"session-crash",sessionId:s.id,sessionName:i?.name||s.id?.slice(0,8),title:"Session Crashed",message:`Exited with code ${s.code}`})}),t("session:idle",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.id);if(i&&(i.status="idle",this.renderSessionTabs(),this.sendPendingCtrlL(s.id),s.id===this.activeSessionId&&this._updateLocalEchoState()),!this.respawnStatus[s.id]?.enabled){const a=this.notificationManager?.preferences?.stuckThresholdMs||6e5;clearTimeout(this.idleTimers.get(s.id)),this.idleTimers.set(s.id,setTimeout(()=>{const l=this.sessions.get(s.id);this.notificationManager?.notify({urgency:"warning",category:"session-stuck",sessionId:s.id,sessionName:l?.name||s.id?.slice(0,8),title:"Session Idle",message:`Idle for ${Math.round(a/6e4)}+ minutes`}),this.idleTimers.delete(s.id)},a))}}),t("session:working",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.id);i&&(i.status="busy",this.pendingHooks.has(s.id)||this.tabAlerts.delete(s.id),this.renderSessionTabs(),this.sendPendingCtrlL(s.id),s.id===this.activeSessionId&&this._updateLocalEchoState());const a=this.idleTimers.get(s.id);a&&(clearTimeout(a),this.idleTimers.delete(s.id))}),t("scheduled:created",n=>{this.currentRun=JSON.parse(n.data),this.showTimer()}),t("scheduled:updated",n=>{this.currentRun=JSON.parse(n.data),this.updateTimer()}),t("scheduled:completed",n=>{this.currentRun=JSON.parse(n.data),this.hideTimer(),this.showToast("Scheduled run completed!","success")}),t("scheduled:stopped",n=>{this.currentRun=null,this.hideTimer()}),t("respawn:started",n=>{const s=JSON.parse(n.data);this.respawnStatus[s.sessionId]=s.status,s.sessionId===this.activeSessionId&&this.showRespawnBanner()}),t("respawn:stopped",n=>{const s=JSON.parse(n.data);delete this.respawnStatus[s.sessionId],s.sessionId===this.activeSessionId&&this.hideRespawnBanner()}),t("respawn:stateChanged",n=>{const s=JSON.parse(n.data);this.respawnStatus[s.sessionId]&&(this.respawnStatus[s.sessionId].state=s.state),s.sessionId===this.activeSessionId&&this.updateRespawnBanner(s.state)}),t("respawn:cycleStarted",n=>{const s=JSON.parse(n.data);this.respawnStatus[s.sessionId]&&(this.respawnStatus[s.sessionId].cycleCount=s.cycleNumber),s.sessionId===this.activeSessionId&&(document.getElementById("respawnCycleCount").textContent=s.cycleNumber)}),t("respawn:blocked",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.sessionId),l={circuit_breaker_open:"Circuit Breaker Open",exit_signal:"Exit Signal Detected",status_blocked:"Claude Reported BLOCKED"}[s.reason]||"Respawn Blocked";if(this.notificationManager?.notify({urgency:"critical",category:"respawn-blocked",sessionId:s.sessionId,sessionName:i?.name||s.sessionId?.slice(0,8),title:l,message:s.details}),s.sessionId===this.activeSessionId){const o=document.getElementById("respawnStateLabel");o&&(o.textContent=l,o.classList.add("respawn-blocked"))}}),t("respawn:stepSent",n=>{}),t("respawn:autoAcceptSent",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-accept",sessionId:s.sessionId,sessionName:i?.name||s.sessionId?.slice(0,8),title:"Plan Accepted",message:`Accepted plan mode for ${i?.name||"session"}`})}),t("respawn:detectionUpdate",n=>{const s=JSON.parse(n.data);this.respawnStatus[s.sessionId]&&(this.respawnStatus[s.sessionId].detection=s.detection),s.sessionId===this.activeSessionId&&this.updateDetectionDisplay(s.detection)}),t("respawn:aiCheckStarted",n=>{}),t("respawn:aiCheckCompleted",n=>{}),t("respawn:aiCheckFailed",n=>{}),t("respawn:aiCheckCooldown",n=>{}),t("respawn:timerStarted",n=>{const s=JSON.parse(n.data);this.respawnTimers[s.sessionId]={endAt:s.endAt,startedAt:s.startedAt,durationMinutes:s.durationMinutes},s.sessionId===this.activeSessionId&&this.showRespawnTimer()}),t("respawn:timerStarted",n=>{const s=JSON.parse(n.data);if(s.timer){const{sessionId:i,timer:a}=s;this.respawnCountdownTimers[i]||(this.respawnCountdownTimers[i]={}),this.respawnCountdownTimers[i][a.name]={endsAt:a.endsAt,totalMs:a.durationMs,reason:a.reason},i===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.startCountdownInterval())}}),t("respawn:timerCancelled",n=>{const s=JSON.parse(n.data),{sessionId:i,timerName:a}=s;this.respawnCountdownTimers[i]&&delete this.respawnCountdownTimers[i][a],i===this.activeSessionId&&this.updateCountdownTimerDisplay()}),t("respawn:timerCompleted",n=>{const s=JSON.parse(n.data),{sessionId:i,timerName:a}=s;this.respawnCountdownTimers[i]&&delete this.respawnCountdownTimers[i][a],i===this.activeSessionId&&this.updateCountdownTimerDisplay()}),t("respawn:error",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.sessionId);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:s.sessionId,sessionName:i?.name||s.sessionId,title:"Respawn Error",message:s.error||s.message||"Respawn encountered an error"})}),t("respawn:actionLog",n=>{const s=JSON.parse(n.data),{sessionId:i,action:a}=s;this.addActionLogEntry(i,a),i===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.updateActionLogDisplay())}),t("session:autoClear",n=>{const s=JSON.parse(n.data);s.sessionId===this.activeSessionId&&(this.showToast(`Auto-cleared at ${s.tokens.toLocaleString()} tokens`,"info"),this.updateRespawnTokens(0));const i=this.sessions.get(s.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-clear",sessionId:s.sessionId,sessionName:i?.name||s.sessionId?.slice(0,8),title:"Auto-Cleared",message:`Context reset at ${(s.tokens||0).toLocaleString()} tokens`})}),t("session:cliInfo",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.sessionId);i&&(s.version&&(i.cliVersion=s.version),s.model&&(i.cliModel=s.model),s.accountType&&(i.cliAccountType=s.accountType),s.latestVersion&&(i.cliLatestVersion=s.latestVersion)),s.sessionId===this.activeSessionId&&this.updateCliInfoDisplay()}),t("task:created",n=>{const s=JSON.parse(n.data);this.renderSessionTabs(),s.sessionId===this.activeSessionId&&this.renderTaskPanel()}),t("task:completed",n=>{const s=JSON.parse(n.data);this.renderSessionTabs(),s.sessionId===this.activeSessionId&&this.renderTaskPanel()}),t("task:failed",n=>{const s=JSON.parse(n.data);this.renderSessionTabs(),s.sessionId===this.activeSessionId&&this.renderTaskPanel()}),t("task:updated",n=>{JSON.parse(n.data).sessionId===this.activeSessionId&&this.renderTaskPanel()}),t("mux:created",n=>{const s=JSON.parse(n.data);this.muxSessions.push(s),this.renderMuxSessions()}),t("mux:killed",n=>{const s=JSON.parse(n.data);this.muxSessions=this.muxSessions.filter(i=>i.sessionId!==s.sessionId),this.renderMuxSessions()}),t("mux:died",n=>{const s=JSON.parse(n.data);this.muxSessions=this.muxSessions.filter(i=>i.sessionId!==s.sessionId),this.renderMuxSessions(),this.showToast("Mux session died: "+s.sessionId.slice(0,8),"warning")}),t("mux:statsUpdated",n=>{this.muxSessions=JSON.parse(n.data),document.getElementById("monitorPanel").classList.contains("open")&&this.renderMuxSessions()}),t("session:ralphLoopUpdate",n=>{const s=JSON.parse(n.data);this.ralphClosedSessions.has(s.sessionId)||this.updateRalphState(s.sessionId,{loop:s.state})}),t("session:ralphTodoUpdate",n=>{const s=JSON.parse(n.data);this.ralphClosedSessions.has(s.sessionId)||this.updateRalphState(s.sessionId,{todos:s.todos})}),t("session:ralphCompletionDetected",n=>{const s=JSON.parse(n.data);if(this.ralphClosedSessions.has(s.sessionId))return;const i=`${s.sessionId}:${s.phrase}`;if(this._shownCompletions?.has(i))return;this._shownCompletions||(this._shownCompletions=new Set),this._shownCompletions.add(i),setTimeout(()=>this._shownCompletions?.delete(i),3e4);const a=this.ralphStates.get(s.sessionId)||{};a.loop&&(a.loop.active=!1,this.updateRalphState(s.sessionId,a));const l=this.sessions.get(s.sessionId);this.notificationManager?.notify({urgency:"warning",category:"ralph-complete",sessionId:s.sessionId,sessionName:l?.name||s.sessionId?.slice(0,8),title:"Loop Complete",message:`Completion: ${s.phrase||"unknown"}`})}),t("session:ralphStatusUpdate",n=>{const s=JSON.parse(n.data);this.ralphClosedSessions.has(s.sessionId)||this.updateRalphState(s.sessionId,{statusBlock:s.block})}),t("session:circuitBreakerUpdate",n=>{const s=JSON.parse(n.data);if(!this.ralphClosedSessions.has(s.sessionId)&&(this.updateRalphState(s.sessionId,{circuitBreaker:s.status}),s.status.state==="OPEN")){const i=this.sessions.get(s.sessionId);this.notificationManager?.notify({urgency:"critical",category:"circuit-breaker",sessionId:s.sessionId,sessionName:i?.name||s.sessionId?.slice(0,8),title:"Circuit Breaker Open",message:s.status.reason||"Loop stuck - no progress detected"})}}),t("session:exitGateMet",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.sessionId);this.notificationManager?.notify({urgency:"warning",category:"exit-gate",sessionId:s.sessionId,sessionName:i?.name||s.sessionId?.slice(0,8),title:"Exit Gate Met",message:`Loop ready to exit (indicators: ${s.completionIndicators})`})}),t("session:bashToolStart",n=>{const s=JSON.parse(n.data);this.handleBashToolStart(s.sessionId,s.tool)}),t("session:bashToolEnd",n=>{const s=JSON.parse(n.data);this.handleBashToolEnd(s.sessionId,s.tool)}),t("session:bashToolsUpdate",n=>{const s=JSON.parse(n.data);this.handleBashToolsUpdate(s.sessionId,s.tools)}),t("hook:idle_prompt",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.sessionId);s.sessionId&&this.setPendingHook(s.sessionId,"idle_prompt"),this.notificationManager?.notify({urgency:"warning",category:"hook-idle",sessionId:s.sessionId,sessionName:i?.name||s.sessionId,title:"Waiting for Input",message:s.message||"Claude is idle and waiting for a prompt"})}),t("hook:permission_prompt",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.sessionId);s.sessionId&&this.setPendingHook(s.sessionId,"permission_prompt");const a=s.tool?`${s.tool}${s.command?": "+s.command:s.file?": "+s.file:""}`:"";this.notificationManager?.notify({urgency:"critical",category:"hook-permission",sessionId:s.sessionId,sessionName:i?.name||s.sessionId,title:"Permission Required",message:a||"Claude needs tool approval to continue"})}),t("hook:elicitation_dialog",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.sessionId);s.sessionId&&this.setPendingHook(s.sessionId,"elicitation_dialog"),this.notificationManager?.notify({urgency:"critical",category:"hook-elicitation",sessionId:s.sessionId,sessionName:i?.name||s.sessionId,title:"Question Asked",message:s.question||"Claude is asking a question and waiting for your answer"})}),t("hook:stop",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.sessionId);s.sessionId&&this.clearPendingHooks(s.sessionId),this.notificationManager?.notify({urgency:"info",category:"hook-stop",sessionId:s.sessionId,sessionName:i?.name||s.sessionId,title:"Response Complete",message:s.reason||"Claude has finished responding"})}),t("hook:teammate_idle",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.sessionId);this.notificationManager?.notify({urgency:"warning",category:"hook-teammate-idle",sessionId:s.sessionId,sessionName:i?.name||s.sessionId,title:"Teammate Idle",message:`A teammate is idle in ${i?.name||s.sessionId}`})}),t("hook:task_completed",n=>{const s=JSON.parse(n.data),i=this.sessions.get(s.sessionId);this.notificationManager?.notify({urgency:"info",category:"hook-task-completed",sessionId:s.sessionId,sessionName:i?.name||s.sessionId,title:"Task Completed",message:`A team task completed in ${i?.name||s.sessionId}`})}),t("subagent:discovered",n=>{const s=JSON.parse(n.data);if(this.subagents.set(s.agentId,s),this.subagentActivity.set(s.agentId,[]),this.subagentToolResults.delete(s.agentId),this.subagentWindows.has(s.agentId)&&this.forceCloseSubagentWindow(s.agentId),this.renderSubagentPanel(),this.findParentSessionForSubagent(s.agentId),s.status==="active"){const l=this.subagents.get(s.agentId);l?.sessionId&&Array.from(this.sessions.values()).some(r=>r.claudeSessionId===l.sessionId)&&this.openSubagentWindow(s.agentId)}requestAnimationFrame(()=>{this.updateConnectionLines()});const i=this.subagentParentMap.get(s.agentId),a=i?this.sessions.get(i):null;this.notificationManager?.notify({urgency:"info",category:"subagent-spawn",sessionId:i||s.sessionId,sessionName:a?.name||i||s.sessionId,title:"Subagent Spawned",message:s.description||"New background agent started"})}),t("subagent:updated",n=>{const s=JSON.parse(n.data),i=this.subagents.get(s.agentId);i?(Object.assign(i,s),this.subagents.set(s.agentId,i)):this.subagents.set(s.agentId,s),this.renderSubagentPanel(),this.subagentWindows.has(s.agentId)&&(this.renderSubagentWindowContent(s.agentId),this.updateSubagentWindowHeader(s.agentId))}),t("subagent:tool_call",n=>{const s=JSON.parse(n.data),i=this.subagentActivity.get(s.agentId)||[];i.push({type:"tool",...s}),i.length>50&&i.shift(),this.subagentActivity.set(s.agentId,i),this.activeSubagentId===s.agentId&&this.renderSubagentDetail(),this.renderSubagentPanel(),this.subagentWindows.has(s.agentId)&&this.renderSubagentWindowContent(s.agentId)}),t("subagent:progress",n=>{const s=JSON.parse(n.data),i=this.subagentActivity.get(s.agentId)||[];i.push({type:"progress",...s}),i.length>50&&i.shift(),this.subagentActivity.set(s.agentId,i),this.activeSubagentId===s.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(s.agentId)&&this.renderSubagentWindowContent(s.agentId)}),t("subagent:message",n=>{const s=JSON.parse(n.data),i=this.subagentActivity.get(s.agentId)||[];i.push({type:"message",...s}),i.length>50&&i.shift(),this.subagentActivity.set(s.agentId,i),this.activeSubagentId===s.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(s.agentId)&&this.renderSubagentWindowContent(s.agentId)}),t("subagent:tool_result",n=>{const s=JSON.parse(n.data);this.subagentToolResults.has(s.agentId)||this.subagentToolResults.set(s.agentId,new Map);const i=this.subagentToolResults.get(s.agentId);if(i.set(s.toolUseId,s),i.size>50){const l=i.keys().next().value;i.delete(l)}const a=this.subagentActivity.get(s.agentId)||[];a.push({type:"tool_result",...s}),a.length>50&&a.shift(),this.subagentActivity.set(s.agentId,a),this.activeSubagentId===s.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(s.agentId)&&this.renderSubagentWindowContent(s.agentId)}),t("subagent:completed",async n=>{const s=JSON.parse(n.data),i=this.subagents.get(s.agentId);if(i&&(i.status="completed",this.subagents.set(s.agentId,i)),this.renderSubagentPanel(),this.updateSubagentWindows(),this.subagentWindows.has(s.agentId)){const o=this.subagentWindows.get(s.agentId);o&&!o.minimized&&(await this.closeSubagentWindow(s.agentId),this.saveSubagentWindowStates())}const a=this.subagentParentMap.get(s.agentId),l=a?this.sessions.get(a):null;this.notificationManager?.notify({urgency:"info",category:"subagent-complete",sessionId:a||i?.sessionId||s.sessionId,sessionName:l?.name||a||s.sessionId,title:"Subagent Completed",message:i?.description||s.description||"Background agent finished"}),setTimeout(()=>{this.subagents.get(s.agentId)?.status==="completed"&&(this.subagentActivity.delete(s.agentId),this.subagentToolResults.delete(s.agentId))},300*1e3),setTimeout(()=>{this.subagents.get(s.agentId)?.status==="completed"&&!this.subagentWindows.has(s.agentId)&&(this.subagents.delete(s.agentId),this.subagentParentMap.delete(s.agentId))},1800*1e3)}),t("image:detected",n=>{const s=JSON.parse(n.data);this.openImagePopup(s)}),t("tunnel:started",n=>{const s=JSON.parse(n.data);this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(s.url),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,s.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,s.url),this.showToast(`Tunnel active: ${s.url}`,"success"),this.showTunnelQR())}),t("tunnel:stopped",()=>{this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this.closeTunnelQR()}),t("tunnel:progress",n=>{const s=JSON.parse(n.data),i=document.getElementById("tunnelConnectingToast");i&&(i.innerHTML=`<span class="tunnel-spinner"></span> ${s.message}`);const a=document.getElementById("welcomeTunnelBtn");a?.classList.contains("connecting")&&(a.innerHTML=`<span class="tunnel-spinner"></span> ${s.message}`)}),t("tunnel:error",n=>{const s=JSON.parse(n.data);this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${s.message}`,"error");const i=document.getElementById("welcomeTunnelBtn");i&&(i.disabled=!1,i.classList.remove("connecting"))}),t("tunnel:qrRotated",n=>{const s=JSON.parse(n.data);if(s.svg){const i=document.getElementById("tunnelQrContainer");i&&(i.innerHTML=s.svg);const a=document.getElementById("welcomeQrInner");a&&(a.innerHTML=s.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()}),t("tunnel:qrRegenerated",n=>{const s=JSON.parse(n.data);if(s.svg){const i=document.getElementById("tunnelQrContainer");i&&(i.innerHTML=s.svg);const a=document.getElementById("welcomeQrInner");a&&(a.innerHTML=s.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()}),t("tunnel:qrAuthUsed",n=>{const s=JSON.parse(n.data),a=(s.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${a}, ${s.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"))}}})}),t("plan:subagent",n=>{const s=JSON.parse(n.data);this.handlePlanSubagentEvent(s)}),t("plan:progress",n=>{const s=JSON.parse(n.data);this._planProgressHandler&&this._planProgressHandler({type:"plan:progress",data:s});const i=document.getElementById("planLoadingTitle"),a=document.getElementById("planLoadingHint");if(i&&s.phase){const l={"parallel-analysis":"Running parallel analysis...",subagent:s.detail||"Subagent working...",synthesis:"Synthesizing results...",verification:"Running verification..."};i.textContent=l[s.phase]||s.phase}a&&s.detail&&(a.textContent=s.detail)}),t("plan:started",n=>{const s=JSON.parse(n.data);this.activePlanOrchestratorId=s.orchestratorId,this.planGenerationStopped=!1,this.renderMonitorPlanAgents()}),t("plan:cancelled",n=>{const s=JSON.parse(n.data);this.activePlanOrchestratorId===s.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}),t("plan:completed",n=>{const s=JSON.parse(n.data);this.activePlanOrchestratorId===s.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(s=>{s.ok?this.clearPendingHooks(e):this._enqueueInput(e,t)}).catch(()=>{this._enqueueInput(e,t)})})}_enqueueInput(e,t){let s=(this._inputQueue.get(e)||"")+t;s.length>this._inputQueueMaxBytes&&(s=s.slice(s.length-this._inputQueueMaxBytes)),this._inputQueue.set(e,s),this._updateConnectionIndicator()}async _drainInputQueues(){if(this._inputQueue.size===0)return;const e=new Map(this._inputQueue);this._inputQueue.clear(),this._updateConnectionIndicator();for(const[t,n]of e)(await this._apiPost(`/api/sessions/${t}/input`,{input:n}))?.ok||this._enqueueInput(t,n);this._updateConnectionIndicator()}_updateConnectionIndicator(){const e=this.$("connectionIndicator"),t=this.$("connectionDot"),n=this.$("connectionText");if(!e||!t||!n)return;let s=0;for(const o of this._inputQueue.values())s+=o.length;const i=this._connectionStatus,a=s>0;if((i==="connected"||i==="connecting")&&!a){e.style.display="none";return}e.style.display="flex",t.className="connection-dot";const l=o=>o<1024?`${o}B`:`${(o/1024).toFixed(1)}KB`;i==="connected"&&a?(t.classList.add("draining"),n.textContent=`Sending ${l(s)}...`):i==="reconnecting"?(t.classList.add("reconnecting"),n.textContent=a?`Reconnecting (${l(s)} queued)`:"Reconnecting..."):(t.classList.add("offline"),n.textContent=a?`Offline (${l(s)} 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"),a=this.$("headerVersion");i&&(i.textContent=`v${e.version}`,i.title=`Codeman v${e.version}`),a&&(a.textContent=`v${e.version}`,a.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,a)=>i+(a.totalCost||0),0),this.totalCost+=e.scheduledRuns.reduce((i,a)=>i+(a.totalCost||0),0);const n=e.scheduledRuns.find(i=>i.status==="running");if(n&&(this.currentRun=n,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,a]of this.subagentParentMap){const l=this.subagents.get(i);if(l&&this.sessions.has(a)){l.parentSessionId=a;const o=this.sessions.get(a);o&&(l.parentSessionName=this.getSessionName(o)),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 s=this.activeSessionId;if(this.activeSessionId=null,this.sessionOrder.length>0){let i=s;if(!i||!this.sessions.has(i))try{i=localStorage.getItem("codeman-active-session")}catch{}i&&this.sessions.has(i)?this.selectSession(i):this.selectSession(this.sessionOrder[0])}}async loadState(){try{const t=await(await fetch("/api/status")).json();this.handleInit(t)}catch{}}renderSessionTabs(){this.renderSessionTabsTimeout&&clearTimeout(this.renderSessionTabsTimeout),this.renderSessionTabsTimeout=setTimeout(()=>{this._renderSessionTabsImmediate()},100)}_updateActiveTabImmediate(e){const t=this.$("sessionTabs");if(!t)return;const n=t.querySelectorAll(".session-tab[data-id]");for(const s of n)s.dataset.id===e?s.classList.add("active"):s.classList.remove("active")}_renderSessionTabsImmediate(){const e=this.$("sessionTabs"),t=e.querySelectorAll(".session-tab[data-id]"),n=new Set([...t].map(a=>a.dataset.id)),s=new Set(this.sessions.keys());if(n.size===s.size&&[...n].every(a=>s.has(a)))for(const[a,l]of this.sessions){const o=e.querySelector(`.session-tab[data-id="${a}"]`);if(!o)continue;const r=a===this.activeSessionId,c=l.status||"idle",d=this.getSessionName(l),u=l.taskStats||{running:0,total:0},h=u.running>0;r&&!o.classList.contains("active")?o.classList.add("active"):!r&&o.classList.contains("active")&&o.classList.remove("active");const m=this.tabAlerts.get(a),p=m==="action",g=m==="idle",f=o.classList.contains("tab-alert-action"),y=o.classList.contains("tab-alert-idle");p&&!f?(o.classList.add("tab-alert-action"),o.classList.remove("tab-alert-idle")):g&&!y?(o.classList.add("tab-alert-idle"),o.classList.remove("tab-alert-action")):!m&&(f||y)&&o.classList.remove("tab-alert-action","tab-alert-idle");const w=o.querySelector(".tab-status");w&&!w.classList.contains(c)&&(w.className=`tab-status ${c}`);const b=o.querySelector(".tab-name");b&&b.textContent!==d&&(b.textContent=d);const S=o.querySelector(".tab-badge");if(h)if(S)S.textContent!==String(u.running)&&(S.textContent=u.running);else{this._fullRenderSessionTabs();return}else if(S){this._fullRenderSessionTabs();return}const v=o.querySelector(".tab-subagent-badge"),T=this.minimizedSubagents.get(a)?.size||0,E=v?parseInt(v.querySelector(".subagent-count")?.textContent||"0"):0;if(T!==E){this._fullRenderSessionTabs();return}}else this._fullRenderSessionTabs()}_fullRenderSessionTabs(){const e=this.$("sessionTabs");document.querySelectorAll("body > .subagent-dropdown").forEach(s=>s.remove()),this.cancelHideSubagentDropdown();const t=[];let n=this.sessionOrder;MobileDetection.getDeviceType()==="mobile"&&this.activeSessionId&&(n=[this.activeSessionId,...this.sessionOrder.filter(s=>s!==this.activeSessionId)]);for(const s of n){const i=this.sessions.get(s);if(!i)continue;const a=s===this.activeSessionId,l=i.status||"idle",o=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(s),m=h==="action"?" tab-alert-action":h==="idle"?" tab-alert-idle":"",p=this.minimizedSubagents.get(s),f=(p?.size||0)>0?this.renderSubagentTabBadge(s,p):"",y=i.workingDir&&i.workingDir.split("/").pop()||"",b=(this._tallTabsEnabled??!1)&&i.name&&y&&y!==o;t.push(`<div class="session-tab ${a?"active":""}${m}" data-id="${s}" data-color="${c}" onclick="app.selectSession('${escapeHtml(s)}')" oncontextmenu="event.preventDefault(); app.startInlineRename('${escapeHtml(s)}')" tabindex="0" role="tab" aria-selected="${a?"true":"false"}" aria-label="${escapeHtml(o)} session" ${i.workingDir?`title="${escapeHtml(i.workingDir)}"`:""}>
|
|
1
|
+
"use strict";const _SSE_HANDLER_MAP=[[SSE_EVENTS.INIT,"_onInit"],[SSE_EVENTS.SESSION_CREATED,"_onSessionCreated"],[SSE_EVENTS.SESSION_UPDATED,"_onSessionUpdated"],[SSE_EVENTS.SESSION_DELETED,"_onSessionDeleted"],[SSE_EVENTS.SESSION_TERMINAL,"_onSessionTerminal"],[SSE_EVENTS.SESSION_NEEDS_REFRESH,"_onSessionNeedsRefresh"],[SSE_EVENTS.SESSION_CLEAR_TERMINAL,"_onSessionClearTerminal"],[SSE_EVENTS.SESSION_COMPLETION,"_onSessionCompletion"],[SSE_EVENTS.SESSION_ERROR,"_onSessionError"],[SSE_EVENTS.SESSION_EXIT,"_onSessionExit"],[SSE_EVENTS.SESSION_IDLE,"_onSessionIdle"],[SSE_EVENTS.SESSION_WORKING,"_onSessionWorking"],[SSE_EVENTS.SESSION_AUTO_CLEAR,"_onSessionAutoClear"],[SSE_EVENTS.SESSION_CLI_INFO,"_onSessionCliInfo"],[SSE_EVENTS.SCHEDULED_CREATED,"_onScheduledCreated"],[SSE_EVENTS.SCHEDULED_UPDATED,"_onScheduledUpdated"],[SSE_EVENTS.SCHEDULED_COMPLETED,"_onScheduledCompleted"],[SSE_EVENTS.SCHEDULED_STOPPED,"_onScheduledStopped"],[SSE_EVENTS.RESPAWN_STARTED,"_onRespawnStarted"],[SSE_EVENTS.RESPAWN_STOPPED,"_onRespawnStopped"],[SSE_EVENTS.RESPAWN_STATE_CHANGED,"_onRespawnStateChanged"],[SSE_EVENTS.RESPAWN_CYCLE_STARTED,"_onRespawnCycleStarted"],[SSE_EVENTS.RESPAWN_BLOCKED,"_onRespawnBlocked"],[SSE_EVENTS.RESPAWN_AUTO_ACCEPT_SENT,"_onRespawnAutoAcceptSent"],[SSE_EVENTS.RESPAWN_DETECTION_UPDATE,"_onRespawnDetectionUpdate"],[SSE_EVENTS.RESPAWN_TIMER_STARTED,"_onRespawnTimerStarted"],[SSE_EVENTS.RESPAWN_TIMER_CANCELLED,"_onRespawnTimerCancelled"],[SSE_EVENTS.RESPAWN_TIMER_COMPLETED,"_onRespawnTimerCompleted"],[SSE_EVENTS.RESPAWN_ERROR,"_onRespawnError"],[SSE_EVENTS.RESPAWN_ACTION_LOG,"_onRespawnActionLog"],[SSE_EVENTS.TASK_CREATED,"_onTaskCreated"],[SSE_EVENTS.TASK_COMPLETED,"_onTaskCompleted"],[SSE_EVENTS.TASK_FAILED,"_onTaskFailed"],[SSE_EVENTS.TASK_UPDATED,"_onTaskUpdated"],[SSE_EVENTS.MUX_CREATED,"_onMuxCreated"],[SSE_EVENTS.MUX_KILLED,"_onMuxKilled"],[SSE_EVENTS.MUX_DIED,"_onMuxDied"],[SSE_EVENTS.MUX_STATS_UPDATED,"_onMuxStatsUpdated"],[SSE_EVENTS.SESSION_RALPH_LOOP_UPDATE,"_onRalphLoopUpdate"],[SSE_EVENTS.SESSION_RALPH_TODO_UPDATE,"_onRalphTodoUpdate"],[SSE_EVENTS.SESSION_RALPH_COMPLETION_DETECTED,"_onRalphCompletionDetected"],[SSE_EVENTS.SESSION_RALPH_STATUS_UPDATE,"_onRalphStatusUpdate"],[SSE_EVENTS.SESSION_CIRCUIT_BREAKER_UPDATE,"_onCircuitBreakerUpdate"],[SSE_EVENTS.SESSION_EXIT_GATE_MET,"_onExitGateMet"],[SSE_EVENTS.SESSION_BASH_TOOL_START,"_onBashToolStart"],[SSE_EVENTS.SESSION_BASH_TOOL_END,"_onBashToolEnd"],[SSE_EVENTS.SESSION_BASH_TOOLS_UPDATE,"_onBashToolsUpdate"],[SSE_EVENTS.HOOK_IDLE_PROMPT,"_onHookIdlePrompt"],[SSE_EVENTS.HOOK_PERMISSION_PROMPT,"_onHookPermissionPrompt"],[SSE_EVENTS.HOOK_ELICITATION_DIALOG,"_onHookElicitationDialog"],[SSE_EVENTS.HOOK_STOP,"_onHookStop"],[SSE_EVENTS.HOOK_TEAMMATE_IDLE,"_onHookTeammateIdle"],[SSE_EVENTS.HOOK_TASK_COMPLETED,"_onHookTaskCompleted"],[SSE_EVENTS.SUBAGENT_DISCOVERED,"_onSubagentDiscovered"],[SSE_EVENTS.SUBAGENT_UPDATED,"_onSubagentUpdated"],[SSE_EVENTS.SUBAGENT_TOOL_CALL,"_onSubagentToolCall"],[SSE_EVENTS.SUBAGENT_PROGRESS,"_onSubagentProgress"],[SSE_EVENTS.SUBAGENT_MESSAGE,"_onSubagentMessage"],[SSE_EVENTS.SUBAGENT_TOOL_RESULT,"_onSubagentToolResult"],[SSE_EVENTS.SUBAGENT_COMPLETED,"_onSubagentCompleted"],[SSE_EVENTS.IMAGE_DETECTED,"_onImageDetected"],[SSE_EVENTS.TUNNEL_STARTED,"_onTunnelStarted"],[SSE_EVENTS.TUNNEL_STOPPED,"_onTunnelStopped"],[SSE_EVENTS.TUNNEL_PROGRESS,"_onTunnelProgress"],[SSE_EVENTS.TUNNEL_ERROR,"_onTunnelError"],[SSE_EVENTS.TUNNEL_QR_ROTATED,"_onTunnelQrRotated"],[SSE_EVENTS.TUNNEL_QR_REGENERATED,"_onTunnelQrRegenerated"],[SSE_EVENTS.TUNNEL_QR_AUTH_USED,"_onTunnelQrAuthUsed"],[SSE_EVENTS.PLAN_SUBAGENT,"_onPlanSubagent"],[SSE_EVENTS.PLAN_PROGRESS,"_onPlanProgress"],[SSE_EVENTS.PLAN_STARTED,"_onPlanStarted"],[SSE_EVENTS.PLAN_CANCELLED,"_onPlanCancelled"],[SSE_EVENTS.PLAN_COMPLETED,"_onPlanCompleted"]];class CodemanApp{constructor(){this.sessions=new Map,this._shortIdCache=new Map,this.sessionOrder=[],this.draggedTabId=null,this.cases=[],this.currentRun=null,this.totalTokens=0,this.globalStats=null,this.eventSource=null,this.terminal=null,this.fitAddon=null,this.activeSessionId=null,this._initGeneration=0,this._initFallbackTimer=null,this._selectGeneration=0,this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},this.timerCountdownInterval=null,this.terminalBuffers=new Map,this.editingSessionId=null,this.pendingCloseSessionId=null,this.muxSessions=[],this.ralphStates=new Map,this.subagents=new Map,this.subagentActivity=new Map,this.subagentToolResults=new Map,this.activeSubagentId=null,this.subagentPanelVisible=!1,this.subagentWindows=new Map,this.subagentWindowZIndex=ZINDEX_SUBAGENT_BASE,this.minimizedSubagents=new Map,this._subagentHideTimeout=null,this.subagentParentMap=new Map,this.teams=new Map,this.teamTasks=new Map,this.teammateMap=new Map,this.teammatePanesByName=new Map,this.teammateTerminals=new Map,this.terminalBufferCache=new Map,this.ralphStatePanelCollapsed=!0,this.ralphClosedSessions=new Set,this.planSubagents=new Map,this.planSubagentWindowZIndex=ZINDEX_PLAN_SUBAGENT_BASE,this.planGenerationStopped=!1,this.planAgentsMinimized=!1,this.wizardDragState=null,this.wizardDragListeners=null,this.wizardPosition=null,this.projectInsights=new Map,this.logViewerWindows=new Map,this.logViewerWindowZIndex=ZINDEX_LOG_VIEWER_BASE,this.projectInsightsPanelVisible=!1,this.currentSessionWorkingDir=null,this.imagePopups=new Map,this.imagePopupZIndex=ZINDEX_IMAGE_POPUP_BASE,this.tabAlerts=new Map,this.pendingHooks=new Map,this.pendingWrites=[],this.writeFrameScheduled=!1,this._wasAtBottomBeforeWrite=!0,this.syncWaitTimeout=null,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.flickerFilterTimeout=null,this.renderSessionTabsTimeout=null,this.renderRalphStatePanelTimeout=null,this.renderTaskPanelTimeout=null,this.renderMuxSessionsTimeout=null,this.systemStatsInterval=null,this.sseReconnectTimeout=null,this._sseListenerCleanup=null,this.reconnectAttempts=0,this.maxReconnectAttempts=10,this.isOnline=navigator.onLine,this._inputQueue=new Map,this._inputQueueMaxBytes=64*1024,this._connectionStatus="connected",this._inputSendChain=Promise.resolve(),this._localEchoOverlay=null,this._localEchoEnabled=!1,this._restoringFlushedState=!1,this.activeFocusTrap=null,this.notificationManager=new NotificationManager(this),this.idleTimers=new Map,this._elemCache={},this.init()}$(e){return this._elemCache[e]||(this._elemCache[e]=document.getElementById(e)),this._elemCache[e]}formatTokens(e){if(e>=1e6){const t=e/1e6;return t>=10?`${t.toFixed(1)}m`:`${t.toFixed(2)}m`}else if(e>=1e3){const t=e/1e3;return t>=100?`${t.toFixed(0)}k`:`${t.toFixed(1)}k`}return String(e)}estimateCost(e,t){const s=e/1e6*15,n=t/1e6*75;return s+n}setPendingHook(e,t){this.pendingHooks.has(e)||this.pendingHooks.set(e,new Set),this.pendingHooks.get(e).add(t),this.updateTabAlertFromHooks(e)}clearPendingHooks(e,t=null){const s=this.pendingHooks.get(e);s&&(t?s.delete(t):s.clear(),s.size===0&&this.pendingHooks.delete(e),this.updateTabAlertFromHooks(e))}updateTabAlertFromHooks(e){const t=this.pendingHooks.get(e);!t||t.size===0?this.tabAlerts.delete(e):t.has("permission_prompt")||t.has("elicitation_dialog")?this.tabAlerts.set(e,"action"):t.has("idle_prompt")&&this.tabAlerts.set(e,"idle"),this.renderSessionTabs()}init(){MobileDetection.init(),KeyboardHandler.init(),SwipeHandler.init(),VoiceInput.init(),KeyboardAccessoryBar.init(),this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility(),document.documentElement.classList.remove("mobile-init"),requestAnimationFrame(()=>{this.initTerminal(),this.loadFontSize(),this.connectSSE(),this._initFallbackTimer=setTimeout(()=>{this._initGeneration===0&&this.loadState()},3e3)}),this.registerServiceWorker();const e=fetch("/api/settings").then(t=>t.ok?t.json():null).catch(()=>null);if(this.loadQuickStartCases(null,e),this._initRunMode(),this.setupEventListeners(),MobileDetection.isTouchDevice()){const t=s=>{s&&s.addEventListener("touchstart",n=>{if(!KeyboardHandler.keyboardVisible)return;const i=n.target.closest("button");i&&(n.preventDefault(),i.click(),typeof app<"u"&&app.terminal&&app.terminal.focus())},{passive:!1})};t(document.querySelector(".toolbar")),t(document.querySelector(".welcome-overlay"))}this.setupOnlineDetection(),this.loadAppSettingsFromServer(e).then(()=>{this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility()}),document.body.classList.add("app-loaded")}initTerminal(){const e=parseInt(localStorage.getItem("codeman-scrollback"))||DEFAULT_SCROLLBACK;if(this.terminal=new Terminal({theme:{background:"#0d0d0d",foreground:"#e0e0e0",cursor:"#e0e0e0",cursorAccent:"#0d0d0d",selection:"rgba(255, 255, 255, 0.3)",black:"#0d0d0d",red:"#ff6b6b",green:"#51cf66",yellow:"#ffd43b",blue:"#339af0",magenta:"#cc5de8",cyan:"#22b8cf",white:"#e0e0e0",brightBlack:"#495057",brightRed:"#ff8787",brightGreen:"#69db7c",brightYellow:"#ffe066",brightBlue:"#5c7cfa",brightMagenta:"#da77f2",brightCyan:"#66d9e8",brightWhite:"#ffffff"},fontFamily:'"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, monospace',fontSize:MobileDetection.getDeviceType()==="mobile"?10:14,lineHeight:1.2,cursorBlink:!1,cursorStyle:"block",scrollback:e,allowTransparency:!0,allowProposedApi:!0}),this.fitAddon=new FitAddon.FitAddon,this.terminal.loadAddon(this.fitAddon),typeof Unicode11Addon<"u")try{const r=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(r),this.terminal.unicode.activeVersion="11"}catch{}const t=document.getElementById("terminalContainer");if(this.terminal.open(t),typeof WebglAddon<"u")try{const r=new WebglAddon.WebglAddon;r.onContextLoss(()=>{r.dispose()}),this.terminal.loadAddon(r)}catch{}if(this._localEchoOverlay=new LocalEchoOverlay(this.terminal),MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this.registerFilePathLinkProvider(),t.addEventListener("wheel",r=>{r.preventDefault();const c=Math.round(r.deltaY/25)||(r.deltaY>0?1:-1);this.terminal.scrollLines(c)},{passive:!1}),!(MobileDetection.isTouchDevice()&&window.innerWidth<1024)){let r=0,c=0,d=0,u=0,h=null,m=!1;const p=t.querySelector(".xterm-viewport"),g=f=>{if(!p)return;const S=u?(f-u)/16.67:1;u=f,m?(c!==0&&(p.scrollTop+=c,c=0),h=requestAnimationFrame(g)):Math.abs(d)>.1?(p.scrollTop+=d*S,d*=.94,h=requestAnimationFrame(g)):(h=null,d=0)};t.addEventListener("touchstart",f=>{f.touches.length===1&&(r=f.touches[0].clientY,c=0,d=0,m=!0,u=0,h||(h=requestAnimationFrame(g)))},{passive:!0}),t.addEventListener("touchmove",f=>{if(f.touches.length===1&&m){const S=f.touches[0].clientY,w=r-S;c+=w,d=w*1.2,r=S}},{passive:!0}),t.addEventListener("touchend",()=>{m=!1},{passive:!0}),t.addEventListener("touchcancel",()=>{m=!1,d=0},{passive:!0})}this.showWelcome(),this._resizeTimeout=null,this._lastResizeDims=null;const i=40,o=10,l=()=>{this._resizeTimeout||(this._resizeTimeout=setTimeout(()=>{if(this._resizeTimeout=null,this.fitAddon){this.fitAddon.fit();const r=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;if(this.activeSessionId&&!r){const c=this.fitAddon.proposeDimensions(),d=c?Math.max(c.cols,i):i,u=c?Math.max(c.rows,o):o;(!this._lastResizeDims||d!==this._lastResizeDims.cols||u!==this._lastResizeDims.rows)&&(this._lastResizeDims={cols:d,rows:u},fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:d,rows:u})}).catch(()=>{}))}}this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},100))};window.addEventListener("resize",l),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(l),this.terminalResizeObserver.observe(t),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const a=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const r=this._pendingInput,c=this.activeSessionId;this._pendingInput="",this._sendInputAsync(c,r)}};this.terminal.onData(r=>{if(this.activeSessionId){if(/^\x1b\[[\?>=]?[\d;]*[cnR]$/.test(r))return;if(this._localEchoEnabled){if(r==="\x7F"){if(this._localEchoOverlay?.removeChar()==="flushed"){const{count:u,text:h}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(u===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,u),this._flushedTexts?.set(this.activeSessionId,h))),this._pendingInput+=r,a()}return}if(/^[\r\n]+$/.test(r)){const d=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),d&&(this._pendingInput+=d,a()),setTimeout(()=>{this._pendingInput+="\r",a()},80);return}if(r.length>1&&r.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(r);return}if(r.charCodeAt(0)<32){if(r.length>1&&r.charCodeAt(0)===27){this._pendingInput+=r,a();return}if(this._restoringFlushedState){this._pendingInput+=r,a();return}if(r===" "){const u=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),u&&(this._pendingInput+=u),this._pendingInput+=r,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let h="";try{const p=this._localEchoOverlay?.findPrompt?.();if(p){const g=this.terminal.buffer.active,f=g.getLine(g.viewportY+p.row);f&&(h=f.translateToString(!0).slice(p.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=h,a(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const m=this;this._tabCompletionFallback=setTimeout(()=>{if(m._tabCompletionFallback=null,!m._tabCompletionSessionId||m._tabCompletionSessionId!==m.activeSessionId)return;const p=m._localEchoOverlay;!p||p.pendingText||m.terminal.write("",()=>{if(!m._tabCompletionSessionId)return;p.resetBufferDetection();const g=p.detectBufferText();g&&g!==m._tabCompletionBaseText&&(m._tabCompletionSessionId=null,m._tabCompletionRetries=0,m._tabCompletionBaseText=null,p.rerender())})},300);return}const d=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),d&&(this._pendingInput+=d),this._pendingInput+=r,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}if(r.length===1&&r.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(r);return}}if(this._pendingInput+=r,r.charCodeAt(0)<32||r.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}const c=performance.now();c-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=c,a()):(this._lastKeystrokeTime=c,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(a,0)))}})}registerFilePathLinkProvider(){const e=this;let t=-1;this.terminal.registerLinkProvider({provideLinks(s,n){s!==t&&(t=s);const o=e.terminal.buffer.active.getLine(s);if(!o){n(void 0);return}const l=o.translateToString(!0);if(!l||!l.includes("/")){n(void 0);return}const a=[],r=/(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]*\s+)*(\/[^\s"'<>|;&\n\x00-\x1f]+)/g,c=/(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\n\x00-\x1f]*\.(?:log|txt|json|md|yaml|yml|csv|xml|sh|py|ts|js))\b/g,d=/Bash\([^)]*?(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\)\n\x00-\x1f]+)/g,u=(m,p)=>{const g=l.indexOf(m,p);g!==-1&&(a.some(f=>f.range.start.x===g+1)||a.push({text:m,range:{start:{x:g+1,y:s},end:{x:g+m.length+1,y:s}},decorations:{pointerCursor:!0,underline:!0},activate(f,S){e.openLogViewerWindow(S,e.activeSessionId)}}))};let h;for(r.lastIndex=0;(h=r.exec(l))!==null;)u(h[2],h.index);for(c.lastIndex=0;(h=c.exec(l))!==null;)u(h[1],h.index);for(d.lastIndex=0;(h=d.exec(l))!==null;)u(h[1],h.index);a.length>0,n(a.length>0?a:void 0)}})}showWelcome(){const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus())}hideWelcome(){const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const t=document.getElementById("welcomeQr");t&&(clearTimeout(this._welcomeQrShrinkTimer),t.classList.remove("expanded"))}isTerminalAtBottom(){if(!this.terminal)return!0;const e=this.terminal.buffer.active;return e.viewportY>=e.baseY-2}batchTerminalWrite(e){if(this._isLoadingBuffer){this._loadBufferQueue&&this._loadBufferQueue.push(e);return}this.writeFrameScheduled||(this._wasAtBottomBeforeWrite=this.isTerminalAtBottom());const s=(this.activeSessionId?this.sessions.get(this.activeSessionId):null)?.flickerFilterEnabled??!1;if(/\x1b\[\d{1,2}A/.test(e)||this.flickerFilterActive&&!s){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(s){if(e.includes("\x1B[2J")||e.includes("\x1B[H\x1B[J")||e.includes("\x1B[H")&&e.includes("\x1B[?25l")){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(this.flickerFilterActive){this.flickerFilterBuffer+=e;return}}this.pendingWrites.push(e),this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{if(this.pendingWrites.length>0&&this.terminal){const i=this.pendingWrites.join(""),o=i.includes(DEC_SYNC_START),l=i.includes(DEC_SYNC_END);if(o&&!l){this.syncWaitTimeout||(this.syncWaitTimeout=setTimeout(()=>{this.syncWaitTimeout=null,this.flushPendingWrites()},50)),this.writeFrameScheduled=!1;return}this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.flushPendingWrites()}this.writeFrameScheduled=!1}))}flushFlickerBuffer(){this.flickerFilterBuffer&&(this.pendingWrites.push(this.flickerFilterBuffer),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1})))}_updateLocalEchoState(){const e=this.loadAppSettingsFromStorage(),t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,n=!!((e.localEchoEnabled??MobileDetection.isTouchDevice())&&t);this._localEchoEnabled&&!n&&this._localEchoOverlay?.clear(),this._localEchoEnabled=n,this._localEchoOverlay&&t&&(t.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:i=>{try{const o=i.buffer.active,l=o.cursorY,a=o.getLine(o.viewportY+l);if(!a)return null;const c=a.translateToString(!0).indexOf("\u2503");return c>=0?{row:l,col:c}:null}catch{return null}}}):this._localEchoOverlay.setPrompt({type:"character",char:"\u276F",offset:2}))}flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=extractSyncSegments(this.pendingWrites.join(""));this.pendingWrites=[];for(const t of e)if(t){const s=t.startsWith(DEC_SYNC_START)?t.slice(DEC_SYNC_START.length):t;s&&this.terminal.write(s)}if(this._wasAtBottomBeforeWrite&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const t=this._localEchoOverlay,s=this;this.terminal.write("",()=>{if(!s._tabCompletionSessionId)return;t.resetBufferDetection();const n=t.detectBufferText();n?n===s._tabCompletionBaseText?(t.undoDetection(),s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0)):(s._tabCompletionSessionId=null,s._tabCompletionRetries=0,s._tabCompletionBaseText=null,s._tabCompletionFallback&&(clearTimeout(s._tabCompletionFallback),s._tabCompletionFallback=null),t.rerender()):(s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0))})}}chunkedTerminalWrite(e,t=TERMINAL_CHUNK_SIZE){return new Promise(s=>{if(!e||e.length===0){this._finishBufferLoad(),s();return}this._isLoadingBuffer=!0,this._loadBufferQueue=[];const n=e.replace(DEC_SYNC_STRIP_RE,""),i=()=>{this._finishBufferLoad(),s()};if(n.length<=t){this.terminal.write(n),i();return}let o=0;const l=()=>{if(o>=n.length){requestAnimationFrame(i);return}const a=n.slice(o,o+t);this.terminal.write(a),o+=t,requestAnimationFrame(l)};requestAnimationFrame(l)})}_finishBufferLoad(){const e=this._loadBufferQueue;if(this._isLoadingBuffer=!1,this._loadBufferQueue=null,e&&e.length>0)for(const t of e)this.batchTerminalWrite(t)}setupEventListeners(){document.addEventListener("keydown",t=>{t.key==="Escape"&&(this.closeAllPanels(),this.closeHelp()),(t.ctrlKey||t.metaKey)&&(t.key==="?"||t.key==="/")&&(t.preventDefault(),this.showHelp()),(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.quickStart()),(t.ctrlKey||t.metaKey)&&t.key==="w"&&(t.preventDefault(),this.killActiveSession()),(t.ctrlKey||t.metaKey)&&t.key==="Tab"&&(t.preventDefault(),this.nextSession()),(t.ctrlKey||t.metaKey)&&t.key==="k"&&(t.preventDefault(),this.killAllSessions()),(t.ctrlKey||t.metaKey)&&t.key==="l"&&(t.preventDefault(),this.clearTerminal()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="R"&&(t.preventDefault(),this.restoreTerminalSize()),(t.ctrlKey||t.metaKey)&&(t.key==="="||t.key==="+")&&(t.preventDefault(),this.increaseFontSize()),(t.ctrlKey||t.metaKey)&&t.key==="-"&&(t.preventDefault(),this.decreaseFontSize()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="V"&&(t.preventDefault(),VoiceInput.toggle())},!0);const e=this.$("headerTokens");e&&!e._statsHandlerAttached&&(e.classList.add("clickable"),e._statsHandlerAttached=!0,e.addEventListener("click",()=>this.openTokenStats())),this.setupColorPicker()}connectSSE(){if(!navigator.onLine){this.setConnectionStatus("offline");return}this.sseReconnectTimeout&&(clearTimeout(this.sseReconnectTimeout),this.sseReconnectTimeout=null),this._sseListenerCleanup&&(this._sseListenerCleanup(),this._sseListenerCleanup=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.reconnectAttempts===0?this.setConnectionStatus("connecting"):this.setConnectionStatus("reconnecting"),this.eventSource=new EventSource("/api/events");const e=[],t=(s,n)=>{this.eventSource.addEventListener(s,n),e.push({event:s,handler:n})};if(this._sseListenerCleanup=()=>{for(const{event:s,handler:n}of e)this.eventSource&&this.eventSource.removeEventListener(s,n);e.length=0},this.eventSource.onopen=()=>{this.reconnectAttempts=0,this.setConnectionStatus("connected")},this.eventSource.onerror=()=>{this.reconnectAttempts++,this.reconnectAttempts>=this.maxReconnectAttempts?this.setConnectionStatus("disconnected"):this.setConnectionStatus("reconnecting"),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.sseReconnectTimeout&&clearTimeout(this.sseReconnectTimeout);const s=this.reconnectAttempts<=1?200:Math.min(500*Math.pow(2,this.reconnectAttempts-2),3e4);this.sseReconnectTimeout=setTimeout(()=>this.connectSSE(),s)},!this._sseHandlerWrappers){this._sseHandlerWrappers=new Map;for(const[s,n]of _SSE_HANDLER_MAP){const i=this[n];this._sseHandlerWrappers.set(s,o=>{try{i.call(this,o.data?JSON.parse(o.data):{})}catch{}})}}for(const[s]of _SSE_HANDLER_MAP)t(s,this._sseHandlerWrappers.get(s))}_onInit(e){this.handleInit(e)}_onSessionCreated(e){this.sessions.set(e.id,e),this.sessionOrder.includes(e.id)||(this.sessionOrder.push(e.id),this.saveSessionOrder()),this.renderSessionTabs(),this.updateCost(),this.sessions.size===1&&this.startSystemStatsPolling()}_onSessionUpdated(e){const t=e.session||e,s=this.sessions.get(t.id),n=t.claudeSessionId&&(!s||!s.claudeSessionId);this.sessions.set(t.id,t),this.renderSessionTabs(),this.updateCost(),t.id===this.activeSessionId&&t.tokens&&this.updateRespawnTokens(t.tokens),this.updateSubagentParentNames(t.id),n&&(this.recheckOrphanSubagents(),requestAnimationFrame(()=>{this.updateConnectionLines()}))}_onSessionDeleted(e){if(this._cleanupSessionData(e.id),this.activeSessionId===e.id){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome()}this.renderSessionTabs(),this.renderRalphStatePanel(),this.renderProjectInsightsPanel(),this.sessions.size===0&&this.stopSystemStatsPolling()}_onSessionTerminal(e){e.id===this.activeSessionId&&this.batchTerminalWrite(e.data)}async _onSessionNeedsRefresh(){if(!(!this.activeSessionId||!this.terminal))try{const s=await(await fetch(`/api/sessions/${this.activeSessionId}/terminal?tail=262144`)).json();s.terminalBuffer&&(this.terminal.clear(),this.terminal.reset(),await this.chunkedTerminalWrite(s.terminalBuffer),this.terminal.scrollToBottom(),this._localEchoOverlay?.rerender(),this.activeSessionId&&this.sendResize(this.activeSessionId))}catch{}}async _onSessionClearTerminal(e){if(e.id===this.activeSessionId)try{const s=await(await fetch(`/api/sessions/${e.id}/terminal`)).json();if(this.terminal.clear(),this.terminal.reset(),s.terminalBuffer){const n=s.terminalBuffer.replace(DEC_SYNC_STRIP_RE,"");await this.chunkedTerminalWrite(n)}this.sendResize(e.id),this._localEchoOverlay?.rerender()}catch{}}_onSessionCompletion(e){this.totalCost+=e.cost||0,this.updateCost(),e.id===this.activeSessionId&&(this.terminal.writeln(""),this.terminal.writeln(`\x1B[1;32m Done (Cost: $${(e.cost||0).toFixed(4)})\x1B[0m`))}_onSessionError(e){e.id===this.activeSessionId&&this.terminal.writeln(`\x1B[1;31m Error: ${e.error}\x1B[0m`);const t=this.sessions.get(e.id);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:e.id,sessionName:t?.name||this.getShortId(e.id),title:"Session Error",message:e.error||"Unknown error"})}_onSessionExit(e){const t=this.sessions.get(e.id);t&&(t.status="stopped",this.renderSessionTabs(),e.id===this.activeSessionId&&this._updateLocalEchoState()),e.code&&e.code!==0&&this.notificationManager?.notify({urgency:"critical",category:"session-crash",sessionId:e.id,sessionName:t?.name||this.getShortId(e.id),title:"Session Crashed",message:`Exited with code ${e.code}`})}_onSessionIdle(e){const t=this.sessions.get(e.id);if(t&&(t.status="idle",this.renderSessionTabs(),this.sendPendingCtrlL(e.id),e.id===this.activeSessionId&&this._updateLocalEchoState()),!this.respawnStatus[e.id]?.enabled){const s=this.notificationManager?.preferences?.stuckThresholdMs||6e5;clearTimeout(this.idleTimers.get(e.id)),this.idleTimers.set(e.id,setTimeout(()=>{const n=this.sessions.get(e.id);this.notificationManager?.notify({urgency:"warning",category:"session-stuck",sessionId:e.id,sessionName:n?.name||this.getShortId(e.id),title:"Session Idle",message:`Idle for ${Math.round(s/6e4)}+ minutes`}),this.idleTimers.delete(e.id)},s))}}_onSessionWorking(e){const t=this.sessions.get(e.id);t&&(t.status="busy",this.pendingHooks.has(e.id)||this.tabAlerts.delete(e.id),this.renderSessionTabs(),this.sendPendingCtrlL(e.id),e.id===this.activeSessionId&&this._updateLocalEchoState());const s=this.idleTimers.get(e.id);s&&(clearTimeout(s),this.idleTimers.delete(e.id))}_onSessionAutoClear(e){e.sessionId===this.activeSessionId&&(this.showToast(`Auto-cleared at ${e.tokens.toLocaleString()} tokens`,"info"),this.updateRespawnTokens(0));const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-clear",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Auto-Cleared",message:`Context reset at ${(e.tokens||0).toLocaleString()} tokens`})}_onSessionCliInfo(e){const t=this.sessions.get(e.sessionId);t&&(e.version&&(t.cliVersion=e.version),e.model&&(t.cliModel=e.model),e.accountType&&(t.cliAccountType=e.accountType),e.latestVersion&&(t.cliLatestVersion=e.latestVersion)),e.sessionId===this.activeSessionId&&this.updateCliInfoDisplay()}_onScheduledCreated(e){this.currentRun=e,this.showTimer()}_onScheduledUpdated(e){this.currentRun=e,this.updateTimer()}_onScheduledCompleted(e){this.currentRun=e,this.hideTimer(),this.showToast("Scheduled run completed!","success")}_onScheduledStopped(){this.currentRun=null,this.hideTimer()}_onRespawnStarted(e){this.respawnStatus[e.sessionId]=e.status,e.sessionId===this.activeSessionId&&this.showRespawnBanner()}_onRespawnStopped(e){delete this.respawnStatus[e.sessionId],e.sessionId===this.activeSessionId&&this.hideRespawnBanner()}_onRespawnStateChanged(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].state=e.state),e.sessionId===this.activeSessionId&&this.updateRespawnBanner(e.state)}_onRespawnCycleStarted(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].cycleCount=e.cycleNumber),e.sessionId===this.activeSessionId&&(document.getElementById("respawnCycleCount").textContent=e.cycleNumber)}_onRespawnBlocked(e){const t=this.sessions.get(e.sessionId),n={circuit_breaker_open:"Circuit Breaker Open",exit_signal:"Exit Signal Detected",status_blocked:"Claude Reported BLOCKED"}[e.reason]||"Respawn Blocked";if(this.notificationManager?.notify({urgency:"critical",category:"respawn-blocked",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:n,message:e.details}),e.sessionId===this.activeSessionId){const i=document.getElementById("respawnStateLabel");i&&(i.textContent=n,i.classList.add("respawn-blocked"))}}_onRespawnAutoAcceptSent(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-accept",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Plan Accepted",message:`Accepted plan mode for ${t?.name||"session"}`})}_onRespawnDetectionUpdate(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].detection=e.detection),e.sessionId===this.activeSessionId&&this.updateDetectionDisplay(e.detection)}_onRespawnTimerStarted(e){if(e.endAt&&(this.respawnTimers[e.sessionId]={endAt:e.endAt,startedAt:e.startedAt,durationMinutes:e.durationMinutes},e.sessionId===this.activeSessionId&&this.showRespawnTimer()),e.timer){const{sessionId:t,timer:s}=e;this.respawnCountdownTimers[t]||(this.respawnCountdownTimers[t]={}),this.respawnCountdownTimers[t][s.name]={endsAt:s.endsAt,totalMs:s.durationMs,reason:s.reason},t===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.startCountdownInterval())}}_onRespawnTimerCancelled(e){const{sessionId:t,timerName:s}=e;this.respawnCountdownTimers[t]&&delete this.respawnCountdownTimers[t][s],t===this.activeSessionId&&this.updateCountdownTimerDisplay()}_onRespawnTimerCompleted(e){const{sessionId:t,timerName:s}=e;this.respawnCountdownTimers[t]&&delete this.respawnCountdownTimers[t][s],t===this.activeSessionId&&this.updateCountdownTimerDisplay()}_onRespawnError(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Respawn Error",message:e.error||e.message||"Respawn encountered an error"})}_onRespawnActionLog(e){const{sessionId:t,action:s}=e;this.addActionLogEntry(t,s),t===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.updateActionLogDisplay())}_onTaskCreated(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskCompleted(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskFailed(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskUpdated(e){e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onMuxCreated(e){this.muxSessions.push(e),this.renderMuxSessions()}_onMuxKilled(e){this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e.sessionId),this.renderMuxSessions()}_onMuxDied(e){this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e.sessionId),this.renderMuxSessions(),this.showToast("Mux session died: "+this.getShortId(e.sessionId),"warning")}_onMuxStatsUpdated(e){this.muxSessions=e,document.getElementById("monitorPanel").classList.contains("open")&&this.renderMuxSessions()}_onRalphLoopUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{loop:e.state})}_onRalphTodoUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{todos:e.todos})}_onRalphCompletionDetected(e){if(this.ralphClosedSessions.has(e.sessionId))return;const t=`${e.sessionId}:${e.phrase}`;if(this._shownCompletions?.has(t))return;this._shownCompletions||(this._shownCompletions=new Set),this._shownCompletions.add(t),setTimeout(()=>this._shownCompletions?.delete(t),3e4);const s=this.ralphStates.get(e.sessionId)||{};s.loop&&(s.loop.active=!1,this.updateRalphState(e.sessionId,s));const n=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"ralph-complete",sessionId:e.sessionId,sessionName:n?.name||this.getShortId(e.sessionId),title:"Loop Complete",message:`Completion: ${e.phrase||"unknown"}`})}_onRalphStatusUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{statusBlock:e.block})}_onCircuitBreakerUpdate(e){if(!this.ralphClosedSessions.has(e.sessionId)&&(this.updateRalphState(e.sessionId,{circuitBreaker:e.status}),e.status.state==="OPEN")){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"critical",category:"circuit-breaker",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Circuit Breaker Open",message:e.status.reason||"Loop stuck - no progress detected"})}}_onExitGateMet(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"exit-gate",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Exit Gate Met",message:`Loop ready to exit (indicators: ${e.completionIndicators})`})}_onBashToolStart(e){this.handleBashToolStart(e.sessionId,e.tool)}_onBashToolEnd(e){this.handleBashToolEnd(e.sessionId,e.tool)}_onBashToolsUpdate(e){this.handleBashToolsUpdate(e.sessionId,e.tools)}_onHookIdlePrompt(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this.notificationManager?.notify({urgency:"warning",category:"hook-idle",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Waiting for Input",message:e.message||"Claude is idle and waiting for a prompt"})}_onHookPermissionPrompt(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const s=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this.notificationManager?.notify({urgency:"critical",category:"hook-permission",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Permission Required",message:s||"Claude needs tool approval to continue"})}_onHookElicitationDialog(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this.notificationManager?.notify({urgency:"critical",category:"hook-elicitation",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Question Asked",message:e.question||"Claude is asking a question and waiting for your answer"})}_onHookStop(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.clearPendingHooks(e.sessionId),this.notificationManager?.notify({urgency:"info",category:"hook-stop",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Response Complete",message:e.reason||"Claude has finished responding"})}_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"hook-teammate-idle",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Teammate Idle",message:`A teammate is idle in ${t?.name||e.sessionId}`})}_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"hook-task-completed",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Task Completed",message:`A team task completed in ${t?.name||e.sessionId}`})}_onSubagentDiscovered(e){if(this.subagents.set(e.agentId,e),this.subagentActivity.set(e.agentId,[]),this.subagentToolResults.delete(e.agentId),this.subagentWindows.has(e.agentId)&&this.forceCloseSubagentWindow(e.agentId),this.renderSubagentPanel(),this.findParentSessionForSubagent(e.agentId),e.status==="active"){const n=this.subagents.get(e.agentId);n?.sessionId&&Array.from(this.sessions.values()).some(o=>o.claudeSessionId===n.sessionId)&&this.openSubagentWindow(e.agentId)}requestAnimationFrame(()=>{this.updateConnectionLines()});const t=this.subagentParentMap.get(e.agentId),s=t?this.sessions.get(t):null;this.notificationManager?.notify({urgency:"info",category:"subagent-spawn",sessionId:t||e.sessionId,sessionName:s?.name||t||e.sessionId,title:"Subagent Spawned",message:e.description||"New background agent started"})}_onSubagentUpdated(e){const t=this.subagents.get(e.agentId);t?(Object.assign(t,e),this.subagents.set(e.agentId,t)):this.subagents.set(e.agentId,e),this.renderSubagentPanel(),this.subagentWindows.has(e.agentId)&&(this.renderSubagentWindowContent(e.agentId),this.updateSubagentWindowHeader(e.agentId))}_onSubagentToolCall(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"tool",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.renderSubagentPanel(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentProgress(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"progress",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentMessage(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"message",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentToolResult(e){this.subagentToolResults.has(e.agentId)||this.subagentToolResults.set(e.agentId,new Map);const t=this.subagentToolResults.get(e.agentId);if(t.set(e.toolUseId,e),t.size>50){const n=t.keys().next().value;t.delete(n)}const s=this.subagentActivity.get(e.agentId)||[];s.push({type:"tool_result",...e}),s.length>50&&s.shift(),this.subagentActivity.set(e.agentId,s),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}async _onSubagentCompleted(e){const t=this.subagents.get(e.agentId);if(t&&(t.status="completed",this.subagents.set(e.agentId,t)),this.renderSubagentPanel(),this.updateSubagentWindows(),this.subagentWindows.has(e.agentId)){const i=this.subagentWindows.get(e.agentId);i&&!i.minimized&&(await this.closeSubagentWindow(e.agentId),this.saveSubagentWindowStates())}const s=this.subagentParentMap.get(e.agentId),n=s?this.sessions.get(s):null;this.notificationManager?.notify({urgency:"info",category:"subagent-complete",sessionId:s||t?.sessionId||e.sessionId,sessionName:n?.name||s||e.sessionId,title:"Subagent Completed",message:t?.description||e.description||"Background agent finished"}),setTimeout(()=>{this.subagents.get(e.agentId)?.status==="completed"&&(this.subagentActivity.delete(e.agentId),this.subagentToolResults.delete(e.agentId))},300*1e3),setTimeout(()=>{this.subagents.get(e.agentId)?.status==="completed"&&!this.subagentWindows.has(e.agentId)&&(this.subagents.delete(e.agentId),this.subagentParentMap.delete(e.agentId))},1800*1e3)}_onImageDetected(e){this.openImagePopup(e)}_onTunnelStarted(e){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())}_onTunnelStopped(){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this.closeTunnelQR()}_onTunnelProgress(e){const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const s=document.getElementById("welcomeTunnelBtn");s?.classList.contains("connecting")&&(s.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)}_onTunnelError(e){this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))}_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()}_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()}_onTunnelQrAuthUsed(e){const s=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${s}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})}_onPlanSubagent(e){this.handlePlanSubagentEvent(e)}_onPlanProgress(e){this._planProgressHandler&&this._planProgressHandler({type:"plan:progress",data:e});const t=document.getElementById("planLoadingTitle"),s=document.getElementById("planLoadingHint");if(t&&e.phase){const n={"parallel-analysis":"Running parallel analysis...",subagent:e.detail||"Subagent working...",synthesis:"Synthesizing results...",verification:"Running verification..."};t.textContent=n[e.phase]||e.phase}s&&e.detail&&(s.textContent=e.detail)}_onPlanStarted(e){this.activePlanOrchestratorId=e.orchestratorId,this.planGenerationStopped=!1,this.renderMonitorPlanAgents()}_onPlanCancelled(e){this.activePlanOrchestratorId===e.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}_onPlanCompleted(e){this.activePlanOrchestratorId===e.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}setConnectionStatus(e){this._connectionStatus=e,this._updateConnectionIndicator(),e==="connected"&&this._inputQueue.size>0&&this._drainInputQueues()}_sendInputAsync(e,t){if(!this.isOnline||this._connectionStatus==="disconnected"){this._enqueueInput(e,t);return}this._inputSendChain=this._inputSendChain.then(()=>{fetch(`/api/sessions/${e}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:t}),keepalive:t.length<65536}).then(n=>{n.ok?this.clearPendingHooks(e):this._enqueueInput(e,t)}).catch(()=>{this._enqueueInput(e,t)})})}_enqueueInput(e,t){let n=(this._inputQueue.get(e)||"")+t;n.length>this._inputQueueMaxBytes&&(n=n.slice(n.length-this._inputQueueMaxBytes)),this._inputQueue.set(e,n),this._updateConnectionIndicator()}async _drainInputQueues(){if(this._inputQueue.size===0)return;const e=new Map(this._inputQueue);this._inputQueue.clear(),this._updateConnectionIndicator();for(const[t,s]of e)(await this._apiPost(`/api/sessions/${t}/input`,{input:s}))?.ok||this._enqueueInput(t,s);this._updateConnectionIndicator()}_updateConnectionIndicator(){const e=this.$("connectionIndicator"),t=this.$("connectionDot"),s=this.$("connectionText");if(!e||!t||!s)return;let n=0;for(const a of this._inputQueue.values())n+=a.length;const i=this._connectionStatus,o=n>0;if((i==="connected"||i==="connecting")&&!o){e.style.display="none";return}e.style.display="flex",t.className="connection-dot";const l=a=>a<1024?`${a}B`:`${(a/1024).toFixed(1)}KB`;i==="connected"&&o?(t.classList.add("draining"),s.textContent=`Sending ${l(n)}...`):i==="reconnecting"?(t.classList.add("reconnecting"),s.textContent=o?`Reconnecting (${l(n)} queued)`:"Reconnecting..."):(t.classList.add("offline"),s.textContent=o?`Offline (${l(n)} queued)`:"Offline")}setupOnlineDetection(){window.addEventListener("online",()=>{this.isOnline=!0,this.reconnectAttempts=0,this.connectSSE()}),window.addEventListener("offline",()=>{this.isOnline=!1,this.setConnectionStatus("offline")})}handleInit(e){this._initFallbackTimer&&(clearTimeout(this._initFallbackTimer),this._initFallbackTimer=null);const t=++this._initGeneration;if(e.version){const i=this.$("versionDisplay"),o=this.$("headerVersion");i&&(i.textContent=`v${e.version}`,i.title=`Codeman v${e.version}`),o&&(o.textContent=`v${e.version}`,o.title=`Codeman v${e.version}`)}VoiceInput.cleanup(),this.sessions.clear(),this.ralphStates.clear(),this.terminalBuffers.clear(),this.terminalBufferCache.clear(),this.projectInsights.clear(),this.teams.clear(),this.teamTasks.clear();for(const i of this.idleTimers.values())clearTimeout(i);if(this.idleTimers.clear(),this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.pendingWrites=[],this.writeFrameScheduled=!1,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._localEchoOverlay?.rerender(),this.pendingHooks.clear(),this._parentNameCache&&this._parentNameCache.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),MobileDetection.cleanup(),KeyboardHandler.cleanup(),MobileDetection.init(),KeyboardHandler.init(),this.tabAlerts.clear(),this._shownCompletions&&this._shownCompletions.clear(),this.notificationManager?.titleFlashInterval&&(clearInterval(this.notificationManager.titleFlashInterval),this.notificationManager.titleFlashInterval=null),this.notificationManager?.groupingMap){for(const{timeout:i}of this.notificationManager.groupingMap.values())clearTimeout(i);this.notificationManager.groupingMap.clear()}this.terminalResizeObserver&&(this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=null),this.planLoadingTimer&&(clearInterval(this.planLoadingTimer),this.planLoadingTimer=null),this.timerCountdownInterval&&(clearInterval(this.timerCountdownInterval),this.timerCountdownInterval=null),this.runSummaryAutoRefreshTimer&&(clearInterval(this.runSummaryAutoRefreshTimer),this.runSummaryAutoRefreshTimer=null),e.sessions.forEach(i=>{this.sessions.set(i.id,i),(i.ralphLoop||i.ralphTodos)&&!this.ralphClosedSessions.has(i.id)&&this.ralphStates.set(i.id,{loop:i.ralphLoop||null,todos:i.ralphTodos||[]})}),this.syncSessionOrder(),e.respawnStatus?this.respawnStatus=e.respawnStatus:this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},e.globalStats&&(this.globalStats=e.globalStats),this.totalCost=e.sessions.reduce((i,o)=>i+(o.totalCost||0),0),this.totalCost+=e.scheduledRuns.reduce((i,o)=>i+(o.totalCost||0),0);const s=e.scheduledRuns.find(i=>i.status==="running");if(s&&(this.currentRun=s,this.showTimer()),this.updateCost(),this.renderSessionTabs(),this.sessions.size>0?this.startSystemStatsPolling():this.stopSystemStatsPolling(),this.cleanupAllFloatingWindows(),e.subagents&&(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),e.subagents.forEach(i=>{this.subagents.set(i.agentId,i)}),this.renderSubagentPanel(),this.subagentParentMap.clear(),this.loadSubagentParentMap().then(()=>{for(const[i,o]of this.subagentParentMap){const l=this.subagents.get(i);if(l&&this.sessions.has(o)){l.parentSessionId=o;const a=this.sessions.get(o);a&&(l.parentSessionName=this.getSessionName(a)),this.subagents.set(i,l)}}for(const[i]of this.subagents)this.subagentParentMap.has(i)||this.findParentSessionForSubagent(i);this.restoreSubagentWindowStates()})),t!==this._initGeneration)return;const n=this.activeSessionId;if(this.activeSessionId=null,this.sessionOrder.length>0){let i=n;if(!i||!this.sessions.has(i))try{i=localStorage.getItem("codeman-active-session")}catch{}i&&this.sessions.has(i)?this.selectSession(i):this.selectSession(this.sessionOrder[0])}}async loadState(){try{const t=await(await fetch("/api/status")).json();this.handleInit(t)}catch{}}renderSessionTabs(){this.renderSessionTabsTimeout&&clearTimeout(this.renderSessionTabsTimeout),this.renderSessionTabsTimeout=setTimeout(()=>{this._renderSessionTabsImmediate()},100)}_updateActiveTabImmediate(e){const t=this.$("sessionTabs");if(!t)return;const s=t.querySelectorAll(".session-tab[data-id]");for(const n of s)n.dataset.id===e?n.classList.add("active"):n.classList.remove("active")}_renderSessionTabsImmediate(){const e=this.$("sessionTabs"),t=e.querySelectorAll(".session-tab[data-id]"),s=new Set([...t].map(o=>o.dataset.id)),n=new Set(this.sessions.keys());if(s.size===n.size&&[...s].every(o=>n.has(o)))for(const[o,l]of this.sessions){const a=e.querySelector(`.session-tab[data-id="${o}"]`);if(!a)continue;const r=o===this.activeSessionId,c=l.status||"idle",d=this.getSessionName(l),u=l.taskStats||{running:0,total:0},h=u.running>0;r&&!a.classList.contains("active")?a.classList.add("active"):!r&&a.classList.contains("active")&&a.classList.remove("active");const m=this.tabAlerts.get(o),p=m==="action",g=m==="idle",f=a.classList.contains("tab-alert-action"),S=a.classList.contains("tab-alert-idle");p&&!f?(a.classList.add("tab-alert-action"),a.classList.remove("tab-alert-idle")):g&&!S?(a.classList.add("tab-alert-idle"),a.classList.remove("tab-alert-action")):!m&&(f||S)&&a.classList.remove("tab-alert-action","tab-alert-idle");const w=a.querySelector(".tab-status");w&&!w.classList.contains(c)&&(w.className=`tab-status ${c}`);const b=a.querySelector(".tab-name");b&&b.textContent!==d&&(b.textContent=d);const y=a.querySelector(".tab-badge");if(h)if(y)y.textContent!==String(u.running)&&(y.textContent=u.running);else{this._fullRenderSessionTabs();return}else if(y){this._fullRenderSessionTabs();return}const v=a.querySelector(".tab-subagent-badge"),T=this.minimizedSubagents.get(o)?.size||0,C=v?parseInt(v.querySelector(".subagent-count")?.textContent||"0"):0;if(T!==C){this._fullRenderSessionTabs();return}}else this._fullRenderSessionTabs()}_fullRenderSessionTabs(){const e=this.$("sessionTabs");document.querySelectorAll("body > .subagent-dropdown").forEach(n=>n.remove()),this.cancelHideSubagentDropdown();const t=[];let s=this.sessionOrder;MobileDetection.getDeviceType()==="mobile"&&this.activeSessionId&&(s=[this.activeSessionId,...this.sessionOrder.filter(n=>n!==this.activeSessionId)]);for(const n of s){const i=this.sessions.get(n);if(!i)continue;const o=n===this.activeSessionId,l=i.status||"idle",a=this.getSessionName(i),r=i.mode||"claude",c=i.color||"default",d=i.taskStats||{running:0,total:0},u=d.running>0,h=this.tabAlerts.get(n),m=h==="action"?" tab-alert-action":h==="idle"?" tab-alert-idle":"",p=this.minimizedSubagents.get(n),f=(p?.size||0)>0?this.renderSubagentTabBadge(n,p):"",S=i.workingDir&&i.workingDir.split("/").pop()||"",b=(this._tallTabsEnabled??!1)&&i.name&&S&&S!==a;t.push(`<div class="session-tab ${o?"active":""}${m}" data-id="${n}" data-color="${c}" onclick="app.selectSession('${escapeHtml(n)}')" oncontextmenu="event.preventDefault(); app.startInlineRename('${escapeHtml(n)}')" tabindex="0" role="tab" aria-selected="${o?"true":"false"}" aria-label="${escapeHtml(a)} session" ${i.workingDir?`title="${escapeHtml(i.workingDir)}"`:""}>
|
|
2
2
|
<span class="tab-status ${l}" aria-hidden="true"></span>
|
|
3
3
|
<span class="tab-info">
|
|
4
4
|
<span class="tab-name-row">
|
|
5
5
|
${r==="shell"?'<span class="tab-mode shell" aria-hidden="true">sh</span>':r==="opencode"?'<span class="tab-mode opencode" aria-hidden="true">oc</span>':""}
|
|
6
|
-
<span class="tab-name" data-session-id="${
|
|
6
|
+
<span class="tab-name" data-session-id="${n}">${escapeHtml(a)}</span>
|
|
7
7
|
</span>
|
|
8
|
-
${b?`<span class="tab-folder">\u{1F4C1} ${escapeHtml(
|
|
8
|
+
${b?`<span class="tab-folder">\u{1F4C1} ${escapeHtml(S)}</span>`:""}
|
|
9
9
|
</span>
|
|
10
10
|
${u?`<span class="tab-badge" onclick="event.stopPropagation(); app.toggleTaskPanel()" aria-label="${d.running} running tasks">${d.running}</span>`:""}
|
|
11
11
|
${f}
|
|
12
|
-
<span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions('${escapeHtml(
|
|
13
|
-
<span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession('${escapeHtml(
|
|
14
|
-
</div>`)}e.innerHTML=t.join(""),this.setupTabDragHandlers(),this.setupTabKeyboardNavigation(e),this.updateConnectionLines()}setupTabKeyboardNavigation(e){this._tabKeydownHandler&&e.removeEventListener("keydown",this._tabKeydownHandler),this._tabKeydownHandler=t=>{if(!["ArrowLeft","ArrowRight","Home","End","Enter"," "].includes(t.key))return;const
|
|
12
|
+
<span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions('${escapeHtml(n)}')" title="Session options" aria-label="Session options" tabindex="0">⚙</span>
|
|
13
|
+
<span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession('${escapeHtml(n)}')" title="Close session" aria-label="Close session" tabindex="0">×</span>
|
|
14
|
+
</div>`)}e.innerHTML=t.join(""),this.setupTabDragHandlers(),this.setupTabKeyboardNavigation(e),this.updateConnectionLines()}setupTabKeyboardNavigation(e){this._tabKeydownHandler&&e.removeEventListener("keydown",this._tabKeydownHandler),this._tabKeydownHandler=t=>{if(!["ArrowLeft","ArrowRight","Home","End","Enter"," "].includes(t.key))return;const s=[...e.querySelectorAll(".session-tab")],n=s.indexOf(document.activeElement);if((t.key==="Enter"||t.key===" ")&&n>=0){t.preventDefault();const o=s[n].dataset.id;this.selectSession(o);return}if(n<0)return;let i;switch(t.key){case"ArrowLeft":i=n>0?n-1:s.length-1;break;case"ArrowRight":i=n<s.length-1?n+1:0;break;case"Home":i=0;break;case"End":i=s.length-1;break;default:return}t.preventDefault(),s[i]?.focus()},e.addEventListener("keydown",this._tabKeydownHandler)}syncSessionOrder(){const e=new Set(this.sessions.keys()),s=this.loadSessionOrder().filter(o=>e.has(o)),n=new Set(s),i=[...e].filter(o=>!n.has(o));this.sessionOrder=[...s,...i]}loadSessionOrder(){try{const e=localStorage.getItem("codeman-session-order");return e?JSON.parse(e):[]}catch{return[]}}saveSessionOrder(){try{localStorage.setItem("codeman-session-order",JSON.stringify(this.sessionOrder))}catch{}}setupTabDragHandlers(){const e=this.$("sessionTabs");e.querySelectorAll(".session-tab[data-id]").forEach(s=>{s.setAttribute("draggable","true"),s.addEventListener("dragstart",n=>{this.draggedTabId=s.dataset.id,s.classList.add("dragging"),n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",s.dataset.id)}),s.addEventListener("dragend",()=>{s.classList.remove("dragging"),this.draggedTabId=null,e.querySelectorAll(".session-tab").forEach(n=>{n.classList.remove("drag-over-left","drag-over-right")})}),s.addEventListener("dragover",n=>{if(n.preventDefault(),!this.draggedTabId||this.draggedTabId===s.dataset.id)return;n.dataTransfer.dropEffect="move";const i=s.getBoundingClientRect(),o=i.left+i.width/2,l=n.clientX<o;s.classList.toggle("drag-over-left",l),s.classList.toggle("drag-over-right",!l)}),s.addEventListener("dragleave",()=>{s.classList.remove("drag-over-left","drag-over-right")}),s.addEventListener("drop",n=>{if(n.preventDefault(),s.classList.remove("drag-over-left","drag-over-right"),!this.draggedTabId||this.draggedTabId===s.dataset.id)return;const i=s.dataset.id,o=this.draggedTabId,l=s.getBoundingClientRect(),a=l.left+l.width/2,r=n.clientX<a,c=this.sessionOrder.indexOf(o);let d=this.sessionOrder.indexOf(i);c===-1||d===-1||(this.sessionOrder.splice(c,1),d=this.sessionOrder.indexOf(i),d!==-1&&(r?this.sessionOrder.splice(d,0,o):this.sessionOrder.splice(d+1,0,o),this.saveSessionOrder(),this._fullRenderSessionTabs()))})})}getShortId(e){if(!e)return"";let t=this._shortIdCache.get(e);return t||(t=e.slice(0,8),this._shortIdCache.set(e,t)),t}getSessionName(e){return e.name?e.name:e.workingDir?e.workingDir.split("/").pop()||e.workingDir:this.getShortId(e.id)}async selectSession(e){if(this.activeSessionId===e)return;const t=++this._selectGeneration;if(t!==this._selectGeneration)return;this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this._tabCompletionSessionId=null,this._tabCompletionRetries=0,this._tabCompletionBaseText=null,this._tabCompletionFallback&&(clearTimeout(this._tabCompletionFallback),this._tabCompletionFallback=null),this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.pendingWrites=[],this.writeFrameScheduled=!1,this._isLoadingBuffer=!1,this._loadBufferQueue=null;try{const i=this.terminal?._core?._compositionHelper;if(i?._isComposing){i._isComposing=!1;const o=this.terminal?.element?.querySelector(".xterm-helper-textarea");o&&o.dispatchEvent(new CompositionEvent("compositionend",{data:""}))}}catch{}if(this.activeSessionId){const i=this._localEchoOverlay?.pendingText||"",o=this._localEchoOverlay?.getFlushed()?.count||0,l=this._localEchoOverlay?.getFlushed()?.text||"";i&&this._sendInputAsync(this.activeSessionId,i);const a=o+i.length;a>0&&(this._flushedOffsets||(this._flushedOffsets=new Map),this._flushedTexts||(this._flushedTexts=new Map),this._flushedOffsets.set(this.activeSessionId,a),this._flushedTexts.set(this.activeSessionId,l+i))}this._localEchoOverlay?.clear(),this._localEchoOverlay&&!this._flushedOffsets?.has(e)&&this._localEchoOverlay.suppressBufferDetection(),this.activeSessionId=e;try{localStorage.setItem("codeman-active-session",e)}catch{}this.hideWelcome(),this.clearPendingHooks(e,"idle_prompt"),this._updateActiveTabImmediate(e),this.renderSessionTabs(),this._updateLocalEchoState(),this._flushedOffsets?.has(e)&&this._localEchoOverlay&&this._localEchoOverlay.setFlushed(this._flushedOffsets.get(e),this._flushedTexts?.get(e)||"",!1);const s=document.querySelector(`.session-tab.active[data-id="${e}"]`);s&&(s.classList.add("tab-glow"),s.addEventListener("animationend",()=>s.classList.remove("tab-glow"),{once:!0}));const n=this.sessions.get(e);if(this.currentSessionWorkingDir=n?.workingDir||null,n&&n.pid===null&&n.status==="idle")try{await fetch(`/api/sessions/${e}/interactive`,{method:"POST"}),n.status="busy"}catch{}this._restoringFlushedState=!0;try{const i=this.terminalBufferCache.get(e);i&&(this.terminal.clear(),this.terminal.reset(),this.terminal.write(i),this.terminal.scrollToBottom());const o=256*1024,l=await fetch(`/api/sessions/${e}/terminal?tail=${o}`);if(t!==this._selectGeneration){this._restoringFlushedState=!1;return}const a=await l.json();if(a.terminalBuffer){if(a.terminalBuffer!==i){if(this.terminal.clear(),this.terminal.reset(),a.truncated&&this.terminal.write(`\x1B[90m... (earlier output truncated for performance) ...\x1B[0m\r
|
|
15
15
|
\r
|
|
16
|
-
`),await this.chunkedTerminalWrite(o.terminalBuffer),t!==this._selectGeneration){this._restoringFlushedState=!1;return}this.terminal.scrollToBottom()}if(this.terminalBufferCache.set(e,o.terminalBuffer),this.terminalBufferCache.size>20){const d=this.terminalBufferCache.keys().next().value;this.terminalBufferCache.delete(d)}}else i||(this.terminal.clear(),this.terminal.reset());if(this._restoringFlushedState=!1,this._flushedOffsets?.has(e)&&this._localEchoOverlay){this._localEchoOverlay.setFlushed(this._flushedOffsets.get(e),this._flushedTexts?.get(e)||"",!1);const c=this._localEchoOverlay;this.terminal.write("",()=>{c.hasPending&&c.rerender()})}this.sendResize(e),(typeof requestIdleCallback=="function"?requestIdleCallback:c=>setTimeout(c,16))(()=>{if(t!==this._selectGeneration)return;this.respawnStatus[e]?(this.showRespawnBanner(),this.updateRespawnBanner(this.respawnStatus[e].state),document.getElementById("respawnCycleCount").textContent=this.respawnStatus[e].cycleCount||0,this.updateCountdownTimerDisplay(),this.updateActionLogDisplay(),Object.keys(this.respawnCountdownTimers[e]||{}).length>0&&this.startCountdownInterval()):(this.hideRespawnBanner(),this.stopCountdownInterval());const c=document.getElementById("taskPanel");c&&c.classList.contains("open")&&this.renderTaskPanel();const d=this.sessions.get(e);if(d&&(d.ralphLoop||d.ralphTodos)&&this.updateRalphState(e,{loop:d.ralphLoop,todos:d.ralphTodos}),this.renderRalphStatePanel(),this.updateCliInfoDisplay(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this.loadAppSettingsFromStorage().showFileBrowser){const h=this.$("fileBrowserPanel");h&&(h.classList.add("visible"),this.loadFileBrowser(e))}}),this.terminal.focus(),this.terminal.scrollToBottom()}catch{this._restoringFlushedState=!1}}_cleanupSessionData(e){this.sessions.delete(e);const t=this.sessionOrder.indexOf(e);t!==-1&&(this.sessionOrder.splice(t,1),this.saveSessionOrder()),this.terminalBuffers.delete(e),this.terminalBufferCache.delete(e),this._flushedOffsets?.delete(e),this._flushedTexts?.delete(e),this._inputQueue.delete(e),this.ralphStates.delete(e),this.ralphClosedSessions.delete(e),this.projectInsights.delete(e),this.pendingHooks.delete(e),this.tabAlerts.delete(e),this.clearCountdownTimers(e),this.closeSessionLogViewerWindows(e),this.closeSessionImagePopups(e),this.closeSessionSubagentWindows(e,!0);const n=this.idleTimers.get(e);n&&(clearTimeout(n),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 n=this.sessionOrder[0];this.selectSession(n)}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 n=this.getSessionName(t),s=document.getElementById("closeConfirmSessionName");s.textContent=n;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 n=null;try{const d=t?await t:await fetch("/api/settings").then(u=>u.ok?u.json():null);d&&(n=d.lastUsedCase||null)}catch{}const i=await(await fetch("/api/cases")).json();this.cases=i;const a=document.getElementById("quickStartCase");let l="";const o=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>`}),o||(l='<option value="testcase">testcase</option>'+l),a.innerHTML=l,e)a.value=e,this.updateDirDisplayForCase(e),this.updateMobileCaseLabel(e);else if(n&&i.some(d=>d.name===n))a.value=n,this.updateDirDisplayForCase(n),this.updateMobileCaseLabel(n);else if(i.length>0){const d=i.find(u=>u.name==="testcase")||i[0];a.value=d.name,this.updateDirDisplayForCase(d.name),this.updateMobileCaseLabel(d.name)}else a.value="testcase",document.getElementById("dirDisplay").textContent="~/codeman-cases/testcase",this.updateMobileCaseLabel("testcase");a.dataset.listenerAdded||(a.addEventListener("change",()=>{this.updateDirDisplayForCase(a.value),this.saveLastUsedCase(a.value),this.updateMobileCaseLabel(a.value)}),a.dataset.listenerAdded="true")}catch{}}async updateDirDisplayForCase(e){try{const n=await(await fetch(`/api/cases/${e}`)).json();n.path&&(document.getElementById("dirDisplay").textContent=n.path,document.getElementById("dirInput").value=n.path)}catch{document.getElementById("dirDisplay").textContent=e}}async saveLastUsedCase(e){try{const t=await fetch("/api/settings"),n=t.ok?await t.json():{};n.lastUsedCase=e,await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}catch{}}async quickStart(){return this.run()}async run(){return(this._runMode||"claude")==="opencode"?this.runOpenCode():this.runClaude()}get runMode(){return this._runMode||"claude"}setRunMode(e){this._runMode=e;try{localStorage.setItem("codeman_runMode",e)}catch{}this._applyRunMode(),document.getElementById("runModeMenu")?.classList.remove("active")}toggleRunModeMenu(e){e?.stopPropagation();const t=document.getElementById("runModeMenu");if(t&&(t.classList.toggle("active"),t.querySelectorAll(".run-mode-option").forEach(n=>{n.classList.toggle("selected",n.dataset.mode===this.runMode)}),t.classList.contains("active"))){const n=s=>{t.contains(s.target)||(t.classList.remove("active"),document.removeEventListener("click",n))};setTimeout(()=>document.addEventListener("click",n),0)}}_applyRunMode(){const e=this.runMode,t=document.getElementById("runBtn"),n=t?.nextElementSibling,s=document.getElementById("runBtnLabel");t&&(t.className=`btn-toolbar btn-run mode-${e}`),n&&(n.className=`btn-toolbar btn-run-gear mode-${e}`),s&&(s.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 s=await(await fetch(`/api/cases/${e}`)).json();if(!s.path){const y=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!y.success)throw new Error(y.error||"Failed to create case");s=y.case}const i=s.path;if(!i)throw new Error("Case path not found");let a=null,l=1;for(const[,f]of this.sessions){const y=f.name&&f.name.match(/^w(\d+)-(.+)$/);if(y&&y[2]===e){const w=parseInt(y[1]);w>=l&&(l=w+1)}}const o=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(y=>y.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)}a=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:o,disableAutoEnable:!o})}))),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`),a&&(await this.selectSession(a),this.loadQuickStartCases()),this.terminal.focus()}catch(n){this.terminal.writeln(`\x1B[1;31m Error: ${n.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 a=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>=a&&(a=m+1)}}const l=[];for(let u=0;u<t;u++)l.push(`s${a+u}-${e}`);const o=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(o),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(n){this.terminal.writeln(`\x1B[1;31m Error: ${n.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 n=t.value.trim();document.getElementById("dirDisplay").textContent=n||"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"),n=this.$("detectionWaiting"),s=this.$("detectionConfidence"),i=document.getElementById("detectionAiCheck"),a=document.getElementById("detectionHook");if(a)if(e.stopHookReceived||e.idlePromptReceived){const r=e.idlePromptReceived?"idle":"stop";a.textContent=`\u{1F3AF} ${r} hook`,a.className="detection-hook hook-active",a.style.display=""}else a.style.display="none";e.statusText&&e.statusText!=="Watching..."?(t.textContent=e.statusText,t.style.display=""):t.style.display="none",n.style.display="none";const l=e.confidenceLevel||0;if(l>0?(s.textContent=`${l}%`,s.style.display="",s.className="detection-confidence",e.stopHookReceived||e.idlePromptReceived?s.classList.add("hook-confirmed"):l>=60?s.classList.add("high"):l>=30&&s.classList.add("medium")):s.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 o=this.$("respawnStatusRow2");if(o){const r=a&&a.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;o.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(),n=Math.max(0,e.endAt-t);if(n<=0){this.$("respawnTimer").textContent="Time up",delete this.respawnTimers[this.activeSessionId],this.hideRespawnTimer();return}this.$("respawnTimer").textContent=this.formatTime(n)}updateRespawnTokens(e){const t=e&&typeof e=="object",n=t?e.total:e;if(n===this._lastRespawnTokenTotal)return;this._lastRespawnTokenTotal=n;const s=this.$("respawnTokens"),i=t?e.input||0:Math.round(n*.6),a=t?e.output||0:Math.round(n*.4);if(n>0){s.style.display="";const l=this.formatTokens(n);if(this.loadAppSettingsFromStorage().showCost??!1){const c=this.estimateCost(i,a);s.textContent=`${l} tokens \xB7 $${c.toFixed(2)}`}else s.textContent=`${l} tokens`}else s.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 n=[];if(t.tokens){const s=typeof t.tokens=="object"?t.tokens.total:t.tokens;s>0&&n.push(`${this.formatTokens(s)} tokens`)}if(t.cliModel){let s=t.cliModel;s.includes("opus")?s="Opus":s.includes("sonnet")?s="Sonnet":s.includes("haiku")&&(s="Haiku"),n.push(s)}if(t.cliVersion){let s=`v${t.cliVersion}`;t.cliLatestVersion&&t.cliLatestVersion!==t.cliVersion&&(s+=" \u2191"),n.push(s)}n.length>0?(e.textContent=n.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 n=this.respawnCountdownTimers[this.activeSessionId];if(!(n&&Object.keys(n).length>0)){if(e.innerHTML="",t){const l=document.getElementById("detectionHook"),o=document.getElementById("detectionAiCheck"),r=this.$("detectionStatus"),c=l&&l.style.display!=="none"||o&&o.style.display!=="none"||r&&r.style.display!=="none";t.style.display=c?"":"none"}return}t&&(t.style.display="");const i=Date.now();let a="";for(const[l,o]of Object.entries(n)){const r=Math.max(0,o.endsAt-i),c=(r/1e3).toFixed(1),d=Math.max(0,Math.min(100,r/o.totalMs*100)),u=l.replace(/-/g," ").replace(/^\w/,h=>h.toUpperCase());a+=`<div class="respawn-countdown-timer" title="${escapeHtml(o.reason||"")}">
|
|
16
|
+
`),await this.chunkedTerminalWrite(a.terminalBuffer),t!==this._selectGeneration){this._restoringFlushedState=!1;return}this.terminal.scrollToBottom()}if(this.terminalBufferCache.set(e,a.terminalBuffer),this.terminalBufferCache.size>20){const d=this.terminalBufferCache.keys().next().value;this.terminalBufferCache.delete(d)}}else i||(this.terminal.clear(),this.terminal.reset());if(this._restoringFlushedState=!1,this._flushedOffsets?.has(e)&&this._localEchoOverlay){this._localEchoOverlay.setFlushed(this._flushedOffsets.get(e),this._flushedTexts?.get(e)||"",!1);const c=this._localEchoOverlay;this.terminal.write("",()=>{c.hasPending&&c.rerender()})}this.sendResize(e),(typeof requestIdleCallback=="function"?requestIdleCallback:c=>setTimeout(c,16))(()=>{if(t!==this._selectGeneration)return;this.respawnStatus[e]?(this.showRespawnBanner(),this.updateRespawnBanner(this.respawnStatus[e].state),document.getElementById("respawnCycleCount").textContent=this.respawnStatus[e].cycleCount||0,this.updateCountdownTimerDisplay(),this.updateActionLogDisplay(),Object.keys(this.respawnCountdownTimers[e]||{}).length>0&&this.startCountdownInterval()):(this.hideRespawnBanner(),this.stopCountdownInterval());const c=document.getElementById("taskPanel");c&&c.classList.contains("open")&&this.renderTaskPanel();const d=this.sessions.get(e);if(d&&(d.ralphLoop||d.ralphTodos)&&this.updateRalphState(e,{loop:d.ralphLoop,todos:d.ralphTodos}),this.renderRalphStatePanel(),this.updateCliInfoDisplay(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this.loadAppSettingsFromStorage().showFileBrowser){const h=this.$("fileBrowserPanel");if(h&&(h.classList.add("visible"),this.loadFileBrowser(e),!this.fileBrowserDragListeners)){const m=h.querySelector(".file-browser-header");if(m){const p=()=>{if(!h.style.left){const g=h.getBoundingClientRect();h.style.left=`${g.left}px`,h.style.top=`${g.top}px`,h.style.right="auto"}};m.addEventListener("mousedown",p),m.addEventListener("touchstart",p,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(h,m),this.fileBrowserDragListeners._onFirstDrag=p}}}}),this.terminal.focus(),this.terminal.scrollToBottom()}catch{this._restoringFlushedState=!1}}_cleanupSessionData(e){this.sessions.delete(e);const t=this.sessionOrder.indexOf(e);t!==-1&&(this.sessionOrder.splice(t,1),this.saveSessionOrder()),this.terminalBuffers.delete(e),this.terminalBufferCache.delete(e),this._flushedOffsets?.delete(e),this._flushedTexts?.delete(e),this._inputQueue.delete(e),this.ralphStates.delete(e),this.ralphClosedSessions.delete(e),this.projectInsights.delete(e),this.pendingHooks.delete(e),this.tabAlerts.delete(e),this.clearCountdownTimers(e),this.closeSessionLogViewerWindows(e),this.closeSessionImagePopups(e),this.closeSessionSubagentWindows(e,!0);const s=this.idleTimers.get(e);s&&(clearTimeout(s),this.idleTimers.delete(e)),delete this.respawnStatus[e],delete this.respawnTimers[e],delete this.respawnCountdownTimers[e],delete this.respawnActionLogs[e]}async closeSession(e,t=!0){try{if(await this._apiDelete(`/api/sessions/${e}?killMux=${t}`),this._cleanupSessionData(e),this.activeSessionId===e){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}if(this.sessionOrder.length>0&&this.sessions.size>0){const s=this.sessionOrder[0];this.selectSession(s)}else this.terminal.clear(),this.showWelcome(),this.renderRalphStatePanel()}this.renderSessionTabs(),t?this.showToast("Session closed and tmux killed","success"):this.showToast("Tab hidden, tmux still running","info")}catch{this.showToast("Failed to close session","error")}}requestCloseSession(e){const t=this.sessions.get(e);if(!t)return;this.pendingCloseSessionId=e;const s=this.getSessionName(t),n=document.getElementById("closeConfirmSessionName");n.textContent=s;const i=document.getElementById("closeConfirmKillTitle");i&&(i.textContent=t.mode==="opencode"?"Kill Tmux & OpenCode":"Kill Tmux & Claude Code"),document.getElementById("closeConfirmModal").classList.add("active")}cancelCloseSession(){this.pendingCloseSessionId=null,document.getElementById("closeConfirmModal").classList.remove("active")}async confirmCloseSession(e=!0){const t=this.pendingCloseSessionId;this.cancelCloseSession(),t&&await this.closeSession(t,e)}nextSession(){if(this.sessionOrder.length<=1)return;const t=(this.sessionOrder.indexOf(this.activeSessionId)+1)%this.sessionOrder.length;this.selectSession(this.sessionOrder[t])}prevSession(){if(this.sessionOrder.length<=1)return;const t=(this.sessionOrder.indexOf(this.activeSessionId)-1+this.sessionOrder.length)%this.sessionOrder.length;this.selectSession(this.sessionOrder[t])}goHome(){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome(),this.renderSessionTabs(),this.renderRalphStatePanel()}ralphWizardStep=1;ralphWizardConfig={taskDescription:"",completionPhrase:"COMPLETE",maxIterations:10,caseName:"testcase",enableRespawn:!1,generatedPlan:null,planGenerated:!1,skipPlanGeneration:!1,planDetailLevel:"detailed",existingPlan:null,useExistingPlan:!1};planLoadingTimer=null;planLoadingStartTime=null;async loadQuickStartCases(e=null,t=null){try{let s=null;try{const d=t?await t:await fetch("/api/settings").then(u=>u.ok?u.json():null);d&&(s=d.lastUsedCase||null)}catch{}const i=await(await fetch("/api/cases")).json();this.cases=i;const o=document.getElementById("quickStartCase");let l="";const a=i.some(d=>d.name==="testcase"),c=MobileDetection.getDeviceType()==="mobile"?8:20;if(i.forEach(d=>{const u=d.name.length>c?d.name.substring(0,c)+"\u2026":d.name;l+=`<option value="${escapeHtml(d.name)}">${escapeHtml(u)}</option>`}),a||(l='<option value="testcase">testcase</option>'+l),o.innerHTML=l,e)o.value=e,this.updateDirDisplayForCase(e),this.updateMobileCaseLabel(e);else if(s&&i.some(d=>d.name===s))o.value=s,this.updateDirDisplayForCase(s),this.updateMobileCaseLabel(s);else if(i.length>0){const d=i.find(u=>u.name==="testcase")||i[0];o.value=d.name,this.updateDirDisplayForCase(d.name),this.updateMobileCaseLabel(d.name)}else o.value="testcase",document.getElementById("dirDisplay").textContent="~/codeman-cases/testcase",this.updateMobileCaseLabel("testcase");o.dataset.listenerAdded||(o.addEventListener("change",()=>{this.updateDirDisplayForCase(o.value),this.saveLastUsedCase(o.value),this.updateMobileCaseLabel(o.value)}),o.dataset.listenerAdded="true")}catch{}}async updateDirDisplayForCase(e){try{const s=await(await fetch(`/api/cases/${e}`)).json();s.path&&(document.getElementById("dirDisplay").textContent=s.path,document.getElementById("dirInput").value=s.path)}catch{document.getElementById("dirDisplay").textContent=e}}async saveLastUsedCase(e){try{const t=await fetch("/api/settings"),s=t.ok?await t.json():{};s.lastUsedCase=e,await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})}catch{}}async quickStart(){return this.run()}async run(){return(this._runMode||"claude")==="opencode"?this.runOpenCode():this.runClaude()}get runMode(){return this._runMode||"claude"}setRunMode(e){this._runMode=e;try{localStorage.setItem("codeman_runMode",e)}catch{}this._applyRunMode(),document.getElementById("runModeMenu")?.classList.remove("active")}toggleRunModeMenu(e){e?.stopPropagation();const t=document.getElementById("runModeMenu");if(t&&(t.classList.toggle("active"),t.querySelectorAll(".run-mode-option").forEach(s=>{s.classList.toggle("selected",s.dataset.mode===this.runMode)}),t.classList.contains("active"))){const s=n=>{t.contains(n.target)||(t.classList.remove("active"),document.removeEventListener("click",s))};setTimeout(()=>document.addEventListener("click",s),0)}}_applyRunMode(){const e=this.runMode,t=document.getElementById("runBtn"),s=t?.nextElementSibling,n=document.getElementById("runBtnLabel");t&&(t.className=`btn-toolbar btn-run mode-${e}`),s&&(s.className=`btn-toolbar btn-run-gear mode-${e}`),n&&(n.textContent=e==="opencode"?"Run OC":"Run")}_initRunMode(){try{this._runMode=localStorage.getItem("codeman_runMode")||"claude"}catch{this._runMode="claude"}this._applyRunMode()}incrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)}decrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)}incrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)}decrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)}async runClaude(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("tabCount").value)||1));this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting ${t} Claude session(s) in ${e}...\x1B[0m`),this.terminal.writeln("");try{let n=await(await fetch(`/api/cases/${e}`)).json();if(!n.path){const S=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!S.success)throw new Error(S.error||"Failed to create case");n=S.case}const i=n.path;if(!i)throw new Error("Case path not found");let o=null,l=1;for(const[,f]of this.sessions){const S=f.name&&f.name.match(/^w(\d+)-(.+)$/);if(S&&S[2]===e){const w=parseInt(S[1]);w>=l&&(l=w+1)}}const a=this.isRalphTrackerEnabledByDefault(),r=[];for(let f=0;f<t;f++)r.push(`w${l+f}-${e}`);const c=this.getCaseSettings(e),d=this.loadAppSettingsFromStorage(),u={};(c.agentTeams||d.agentTeamsEnabled)&&(u.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS="1");const h=Object.keys(u).length>0;this.terminal.writeln(`\x1B[90m Creating ${t} session(s)...\x1B[0m`);const m=r.map(f=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,name:f,...h?{envOverrides:u}:{}})}).then(S=>S.json())),p=await Promise.all(m),g=[];for(const f of p){if(!f.success)throw new Error(f.error);g.push(f.session.id)}o=g[0],await Promise.all(g.map(f=>fetch(`/api/sessions/${f}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:a,disableAutoEnable:!a})}))),this.terminal.writeln(`\x1B[90m Starting ${t} session(s) in parallel...\x1B[0m`),await Promise.all(g.map(f=>fetch(`/api/sessions/${f}/interactive`,{method:"POST"}))),this.terminal.writeln(`\x1B[90m All ${t} sessions ready\x1B[0m`),o&&(await this.selectSession(o),this.loadQuickStartCases()),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}}stopClaude(){if(!this.activeSessionId)return;const e=document.querySelector(".btn-toolbar.btn-stop");e&&(this._stopConfirmTimer?(clearTimeout(this._stopConfirmTimer),this._stopConfirmTimer=null,e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml,e.classList.remove("confirming"),fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:""})})):(e.dataset.origHtml=e.innerHTML,e.textContent="Tap again",e.classList.add("confirming"),this._stopConfirmTimer=setTimeout(()=>{this._stopConfirmTimer=null,e.dataset.origHtml&&(e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml),e.classList.remove("confirming")},2e3)))}async runShell(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("shellCount").value)||1));this.terminal.clear(),this.terminal.writeln(`\x1B[1;33m Starting ${t} Shell session(s) in ${e}...\x1B[0m`),this.terminal.writeln("");try{const i=(await(await fetch(`/api/cases/${e}`)).json()).path;if(!i)throw new Error("Case path not found");let o=1;for(const[,u]of this.sessions){const h=u.name&&u.name.match(/^s(\d+)-(.+)$/);if(h&&h[2]===e){const m=parseInt(h[1]);m>=o&&(o=m+1)}}const l=[];for(let u=0;u<t;u++)l.push(`s${o+u}-${e}`);const a=l.map(u=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,mode:"shell",name:u})}).then(h=>h.json())),r=await Promise.all(a),c=[];for(const u of r){if(!u.success)throw new Error(u.error);c.push(u.session.id)}await Promise.all(c.map(u=>fetch(`/api/sessions/${u}/shell`,{method:"POST"})));const d=this.getTerminalDimensions();d&&await Promise.all(c.map(u=>fetch(`/api/sessions/${u}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}))),c.length>0&&(this.activeSessionId=c[0],await this.selectSession(c[0])),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}}async runOpenCode(){const e=document.getElementById("quickStartCase").value||"testcase";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting OpenCode session in ${e}...\x1B[0m`),this.terminal.writeln("");try{if(!(await(await fetch("/api/opencode/status")).json()).available){this.terminal.writeln("\x1B[1;31m OpenCode CLI not found.\x1B[0m"),this.terminal.writeln("\x1B[90m Install with: curl -fsSL https://opencode.ai/install | bash\x1B[0m");return}const i=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"opencode",openCodeConfig:{autoAllowTools:!0}})})).json();if(!i.success)throw new Error(i.error||"Failed to start OpenCode");i.sessionId&&await this.selectSession(i.sessionId),this.terminal.focus()}catch(t){this.terminal.writeln(`\x1B[1;31m Error: ${t.message}\x1B[0m`)}}toggleDirInput(){const e=document.querySelector("#dirDisplay").parentElement,t=document.getElementById("dirInput");t.classList.contains("hidden")&&(t.classList.remove("hidden"),e.style.display="none",t.focus())}hideDirInput(){const e=document.querySelector("#dirDisplay").parentElement,t=document.getElementById("dirInput");setTimeout(()=>{t.classList.add("hidden"),e.style.display="";const s=t.value.trim();document.getElementById("dirDisplay").textContent=s||"No directory"},100)}showRespawnBanner(){this.$("respawnBanner").style.display="flex",this.activeSessionId&&this.respawnTimers[this.activeSessionId]&&this.showRespawnTimer();const e=this.sessions.get(this.activeSessionId);e&&e.tokens&&this.updateRespawnTokens(e.tokens)}hideRespawnBanner(){this.$("respawnBanner").style.display="none",this.hideRespawnTimer()}getStateLabel(e){return{stopped:"Stopped",watching:"Watching",confirming_idle:"Confirming idle",ai_checking:"AI checking",sending_update:"Sending prompt",waiting_update:"Running prompt",sending_clear:"Clearing context",waiting_clear:"Clearing...",sending_init:"Initializing",waiting_init:"Initializing...",monitoring_init:"Waiting for work",sending_kickstart:"Kickstarting",waiting_kickstart:"Kickstarting..."}[e]||e.replace(/_/g," ")}updateRespawnBanner(e){const t=this.$("respawnState");t.textContent=this.getStateLabel(e),t.classList.remove("respawn-blocked")}updateDetectionDisplay(e){if(!e)return;const t=this.$("detectionStatus"),s=this.$("detectionWaiting"),n=this.$("detectionConfidence"),i=document.getElementById("detectionAiCheck"),o=document.getElementById("detectionHook");if(o)if(e.stopHookReceived||e.idlePromptReceived){const r=e.idlePromptReceived?"idle":"stop";o.textContent=`\u{1F3AF} ${r} hook`,o.className="detection-hook hook-active",o.style.display=""}else o.style.display="none";e.statusText&&e.statusText!=="Watching..."?(t.textContent=e.statusText,t.style.display=""):t.style.display="none",s.style.display="none";const l=e.confidenceLevel||0;if(l>0?(n.textContent=`${l}%`,n.style.display="",n.className="detection-confidence",e.stopHookReceived||e.idlePromptReceived?n.classList.add("hook-confirmed"):l>=60?n.classList.add("high"):l>=30&&n.classList.add("medium")):n.style.display="none",i&&e.aiCheck){const r=e.aiCheck;let c="",d="detection-ai-check";if(r.status==="checking")c="\u{1F50D} AI checking...",d+=" ai-checking";else if(r.status==="cooldown"&&r.cooldownEndsAt){const u=Math.ceil((r.cooldownEndsAt-Date.now())/1e3);u>0&&(r.lastVerdict==="WORKING"?(c=`\u23F3 Working, retry ${u}s`,d+=" ai-working"):(c=`\u2713 Idle, wait ${u}s`,d+=" ai-idle"))}else if(r.status==="disabled")c="\u26A0 AI disabled",d+=" ai-disabled";else if(r.lastVerdict&&r.lastCheckTime){const u=Math.round((Date.now()-r.lastCheckTime)/1e3);u<120&&(c=r.lastVerdict==="IDLE"?`\u2713 Idle (${u}s)`:`\u23F3 Working (${u}s)`,d+=r.lastVerdict==="IDLE"?" ai-idle":" ai-working")}i.textContent=c,i.className=d,i.style.display=c?"":"none"}else i&&(i.style.display="none");const a=this.$("respawnStatusRow2");if(a){const r=o&&o.style.display!=="none"||i&&i.style.display!=="none"||t&&t.style.display!=="none"||this.respawnCountdownTimers[this.activeSessionId]&&Object.keys(this.respawnCountdownTimers[this.activeSessionId]).length>0;a.style.display=r?"":"none"}}showRespawnTimer(){const e=this.$("respawnTimer");e.style.display="",this.updateRespawnTimer(),this.respawnTimerInterval&&clearInterval(this.respawnTimerInterval),this.respawnTimerInterval=setInterval(()=>this.updateRespawnTimer(),1e3)}hideRespawnTimer(){this.$("respawnTimer").style.display="none",this.respawnTimerInterval&&(clearInterval(this.respawnTimerInterval),this.respawnTimerInterval=null)}updateRespawnTimer(){if(!this.activeSessionId||!this.respawnTimers[this.activeSessionId]){this.hideRespawnTimer();return}const e=this.respawnTimers[this.activeSessionId];if(!e.endAt||isNaN(e.endAt)){this.hideRespawnTimer();return}const t=Date.now(),s=Math.max(0,e.endAt-t);if(s<=0){this.$("respawnTimer").textContent="Time up",delete this.respawnTimers[this.activeSessionId],this.hideRespawnTimer();return}this.$("respawnTimer").textContent=this.formatTime(s)}updateRespawnTokens(e){const t=e&&typeof e=="object",s=t?e.total:e;if(s===this._lastRespawnTokenTotal)return;this._lastRespawnTokenTotal=s;const n=this.$("respawnTokens"),i=t?e.input||0:Math.round(s*.6),o=t?e.output||0:Math.round(s*.4);if(s>0){n.style.display="";const l=this.formatTokens(s);if(this.loadAppSettingsFromStorage().showCost??!1){const c=this.estimateCost(i,o);n.textContent=`${l} tokens \xB7 $${c.toFixed(2)}`}else n.textContent=`${l} tokens`}else n.style.display="none";this.updateCliInfoDisplay()}updateCliInfoDisplay(){const e=this.$("cliInfoBar");if(!e)return;const t=this.sessions.get(this.activeSessionId);if(!t){e.style.display="none";return}let s=[];if(t.tokens){const n=typeof t.tokens=="object"?t.tokens.total:t.tokens;n>0&&s.push(`${this.formatTokens(n)} tokens`)}if(t.cliModel){let n=t.cliModel;n.includes("opus")?n="Opus":n.includes("sonnet")?n="Sonnet":n.includes("haiku")&&(n="Haiku"),s.push(n)}if(t.cliVersion){let n=`v${t.cliVersion}`;t.cliLatestVersion&&t.cliLatestVersion!==t.cliVersion&&(n+=" \u2191"),s.push(n)}s.length>0?(e.textContent=s.join(" \xB7 "),e.style.display=""):e.style.display="none"}addActionLogEntry(e,t){if(!["command","hook"].includes(t.type)){if(t.type==="ai-check"){if(t.detail.includes("Spawning"))return}else if(t.type==="plan-check"){if(t.detail.includes("Spawning"))return}else if(t.type!=="transcript")return}this.respawnActionLogs[e]||(this.respawnActionLogs[e]=[]),this.respawnActionLogs[e].unshift(t),this.respawnActionLogs[e].length>30&&this.respawnActionLogs[e].pop()}startCountdownInterval(){this.timerCountdownInterval||(this.timerCountdownInterval=setInterval(()=>{this.activeSessionId&&this.respawnCountdownTimers[this.activeSessionId]&&this.updateCountdownTimerDisplay()},100))}stopCountdownInterval(){this.timerCountdownInterval&&(clearInterval(this.timerCountdownInterval),this.timerCountdownInterval=null)}updateCountdownTimerDisplay(){const e=this.$("respawnCountdownTimers"),t=this.$("respawnStatusRow2");if(!e)return;const s=this.respawnCountdownTimers[this.activeSessionId];if(!(s&&Object.keys(s).length>0)){if(e.innerHTML="",t){const l=document.getElementById("detectionHook"),a=document.getElementById("detectionAiCheck"),r=this.$("detectionStatus"),c=l&&l.style.display!=="none"||a&&a.style.display!=="none"||r&&r.style.display!=="none";t.style.display=c?"":"none"}return}t&&(t.style.display="");const i=Date.now();let o="";for(const[l,a]of Object.entries(s)){const r=Math.max(0,a.endsAt-i),c=(r/1e3).toFixed(1),d=Math.max(0,Math.min(100,r/a.totalMs*100)),u=l.replace(/-/g," ").replace(/^\w/,h=>h.toUpperCase());o+=`<div class="respawn-countdown-timer" title="${escapeHtml(a.reason||"")}">
|
|
17
17
|
<span class="timer-name">${escapeHtml(u)}</span>
|
|
18
18
|
<span class="timer-value">${c}s</span>
|
|
19
19
|
<div class="respawn-timer-bar">
|
|
20
20
|
<div class="respawn-timer-progress" style="width: ${d}%"></div>
|
|
21
21
|
</div>
|
|
22
|
-
</div>`}e.innerHTML=
|
|
22
|
+
</div>`}e.innerHTML=o}updateActionLogDisplay(){const e=this.$("respawnActionLog");if(!e)return;const t=this.respawnActionLogs[this.activeSessionId];if(!t||t.length===0){e.innerHTML="";return}let s="";for(const n of t.slice(0,5)){const i=new Date(n.timestamp).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"}),l=n.type==="command"?" action-command":"";s+=`<div class="respawn-action-entry${l}">
|
|
23
23
|
<span class="action-time">${i}</span>
|
|
24
|
-
<span class="action-type">[${
|
|
25
|
-
<span class="action-detail">${escapeHtml(
|
|
26
|
-
</div>`}e.innerHTML=
|
|
24
|
+
<span class="action-type">[${n.type}]</span>
|
|
25
|
+
<span class="action-detail">${escapeHtml(n.detail)}</span>
|
|
26
|
+
</div>`}e.innerHTML=s}clearCountdownTimers(e){delete this.respawnCountdownTimers[e],delete this.respawnActionLogs[e],e===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.updateActionLogDisplay())}async stopRespawn(){if(this.activeSessionId)try{await this._apiPost(`/api/sessions/${this.activeSessionId}/respawn/stop`,{}),delete this.respawnTimers[this.activeSessionId],this.clearCountdownTimers(this.activeSessionId)}catch{this.showToast("Failed to stop respawn","error")}}async killActiveSession(){if(!this.activeSessionId){this.showToast("No active session","warning");return}await this.closeSession(this.activeSessionId)}async killAllSessions(){if(this.sessions.size!==0&&confirm(`Kill all ${this.sessions.size} session(s)?`))try{await this._apiDelete("/api/sessions"),this.sessions.clear(),this.terminalBuffers.clear(),this.terminalBufferCache.clear(),this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.respawnStatus={},this.respawnCountdownTimers={},this.respawnActionLogs={},this.stopCountdownInterval(),this.hideRespawnBanner(),this.renderSessionTabs(),this.terminal.clear(),this.showWelcome(),this.showToast("All sessions killed","success")}catch{this.showToast("Failed to kill sessions","error")}}clearTerminal(){this.terminal.clear()}async restoreTerminalSize(){if(!this.activeSessionId){this.showToast("No active session","warning");return}const e=this.getTerminalDimensions();if(!e){this.showToast("Could not determine terminal size","error");return}try{await this.sendResize(this.activeSessionId),await fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:"\f"})}),this.showToast(`Terminal restored to ${e.cols}x${e.rows}`,"success")}catch{this.showToast("Failed to restore terminal size","error")}}sendPendingCtrlL(e){!this.pendingCtrlL||!this.pendingCtrlL.has(e)||(this.pendingCtrlL.delete(e),e===this.activeSessionId&&this.sendResize(e).then(()=>{fetch(`/api/sessions/${e}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:"\f"})})}))}async copyTerminal(){try{const e=this.terminal.buffer.active;let t="";for(let s=0;s<e.length;s++){const n=e.getLine(s);n&&(t+=n.translateToString(!0)+`
|
|
27
27
|
`)}await navigator.clipboard.writeText(t.replace(/\n+$/,`
|
|
28
|
-
`)),this.showToast("Copied to clipboard","success")}catch{this.showToast("Failed to copy","error")}}increaseFontSize(){const e=this.terminal.options.fontSize||14;this.setFontSize(Math.min(e+2,24))}decreaseFontSize(){const e=this.terminal.options.fontSize||14;this.setFontSize(Math.max(e-2,10))}setFontSize(e){this.terminal.options.fontSize=e,document.getElementById("fontSizeDisplay").textContent=e,this.fitAddon.fit(),localStorage.setItem("codeman-font-size",e),this._localEchoOverlay?.refreshFont()}loadFontSize(){const e=localStorage.getItem("codeman-font-size");if(e){const t=parseInt(e,10);t>=10&&t<=24&&(this.terminal.options.fontSize=t,document.getElementById("fontSizeDisplay").textContent=t)}}getTerminalDimensions(){const
|
|
29
|
-
Estimated cost based on Claude Opus pricing`:""}`:`Token usage across active sessions${
|
|
30
|
-
Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t=this.sessions.get(e);if(!t)return;this.editingSessionId=e,this.switchOptionsTab(t.mode==="opencode"?"summary":"respawn");const n=document.getElementById("sessionRespawnStatus"),s=document.getElementById("modalEnableRespawnBtn"),i=document.getElementById("modalStopRespawnBtn");this.respawnStatus[e]?(n.classList.add("active"),n.querySelector(".respawn-status-text").textContent=this.respawnStatus[e].state||"Active",s.style.display="none",i.style.display=""):(n.classList.remove("active"),n.querySelector(".respawn-status-text").textContent="Not active",s.style.display="",i.style.display="none");const a=document.getElementById("sessionRespawnSection");t.mode==="claude"&&t.pid?a.style.display="":a.style.display="none";const l=t.mode==="opencode";document.querySelectorAll("[data-claude-only]").forEach(m=>{m.style.display=l?"none":""}),this.selectDurationPreset(""),this.loadSavedRespawnConfig(e),document.getElementById("modalAutoCompactEnabled").checked=t.autoCompactEnabled??!1,document.getElementById("modalAutoCompactThreshold").value=t.autoCompactThreshold??11e4,document.getElementById("modalAutoCompactPrompt").value=t.autoCompactPrompt??"",document.getElementById("modalAutoClearEnabled").checked=t.autoClearEnabled??!1,document.getElementById("modalAutoClearThreshold").value=t.autoClearThreshold??14e4,document.getElementById("modalImageWatcherEnabled").checked=t.imageWatcherEnabled??!0,document.getElementById("modalFlickerFilterEnabled").checked=t.flickerFilterEnabled??!1,document.getElementById("modalSessionName").value=t.name||"";const r=t.color||"default";document.getElementById("sessionColorPicker")?.querySelectorAll(".color-swatch").forEach(m=>{m.classList.toggle("selected",m.dataset.color===r)}),this.renderPresetDropdown(),document.getElementById("respawnPresetSelect").value="",document.getElementById("presetDescriptionHint").textContent="";const d=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="ralph"]'),u=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="respawn"]');if(l?(d&&(d.style.display="none"),u&&(u.style.display="none"),this.switchOptionsTab("context")):(d&&(d.style.display=""),u&&(u.style.display="")),!l){const m=this.ralphStates.get(e);this.populateRalphForm({enabled:m?.loop?.enabled??t.ralphLoop?.enabled??!1,completionPhrase:m?.loop?.completionPhrase||t.ralphLoop?.completionPhrase||"",maxIterations:m?.loop?.maxIterations||t.ralphLoop?.maxIterations||0})}const h=document.getElementById("sessionOptionsModal");h.classList.add("active"),this.activeFocusTrap=new FocusTrap(h),this.activeFocusTrap.activate()}async saveSessionName(){if(!this.editingSessionId)return;const e=document.getElementById("modalSessionName").value.trim();try{await this._apiPut(`/api/sessions/${this.editingSessionId}/name`,{name:e})}catch(t){this.showToast("Failed to save session name: "+t.message,"error")}}async autoSaveAutoCompact(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-compact`,{enabled:document.getElementById("modalAutoCompactEnabled").checked,threshold:parseInt(document.getElementById("modalAutoCompactThreshold").value)||11e4,prompt:document.getElementById("modalAutoCompactPrompt").value.trim()||void 0})}catch{}}async autoSaveAutoClear(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-clear`,{enabled:document.getElementById("modalAutoClearEnabled").checked,threshold:parseInt(document.getElementById("modalAutoClearThreshold").value)||14e4})}catch{}}async toggleSessionImageWatcher(){if(!this.editingSessionId)return;const e=document.getElementById("modalImageWatcherEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/image-watcher`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.imageWatcherEnabled=e),this.showToast(`Image watcher ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle image watcher","error")}}async toggleFlickerFilter(){if(!this.editingSessionId)return;const e=document.getElementById("modalFlickerFilterEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/flicker-filter`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.flickerFilterEnabled=e),this.showToast(`Flicker filter ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle flicker filter","error")}}async autoSaveRespawnConfig(){if(!this.editingSessionId)return;const e={updatePrompt:document.getElementById("modalRespawnPrompt").value,sendClear:document.getElementById("modalRespawnSendClear").checked,sendInit:document.getElementById("modalRespawnSendInit").checked,kickstartPrompt:document.getElementById("modalRespawnKickstart").value.trim()||void 0,autoAcceptPrompts:document.getElementById("modalRespawnAutoAccept").checked};try{await this._apiPut(`/api/sessions/${this.editingSessionId}/respawn/config`,e)}catch{}}async loadSavedRespawnConfig(e){try{const n=await(await fetch(`/api/sessions/${e}/respawn/config`)).json();if(n.success&&n.config){const s=n.config;document.getElementById("modalRespawnPrompt").value=s.updatePrompt||"update all the docs and CLAUDE.md",document.getElementById("modalRespawnSendClear").checked=s.sendClear??!0,document.getElementById("modalRespawnSendInit").checked=s.sendInit??!0,document.getElementById("modalRespawnKickstart").value=s.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=s.autoAcceptPrompts??!0,s.durationMinutes&&(document.querySelector(`.duration-preset-btn[data-minutes="${s.durationMinutes}"]`)?this.selectDurationPreset(String(s.durationMinutes)):(this.selectDurationPreset("custom"),document.getElementById("modalRespawnDuration").value=s.durationMinutes))}}catch{}}selectDurationPreset(e){document.querySelectorAll(".duration-preset-btn").forEach(i=>i.classList.remove("active"));const t=document.querySelector(`.duration-preset-btn[data-minutes="${e}"]`);t&&t.classList.add("active");const n=document.querySelector(".duration-custom-input"),s=document.getElementById("modalRespawnDuration");e==="custom"?(n.classList.add("visible"),s.focus()):(n.classList.remove("visible"),s.value="")}getSelectedDuration(){const e=document.querySelector(".duration-custom-input"),t=document.getElementById("modalRespawnDuration");if(e.classList.contains("visible"))return t.value?parseInt(t.value):null;{const s=document.querySelector(".duration-preset-btn.active")?.dataset.minutes;return s?parseInt(s):null}}loadRespawnPresets(){const e=localStorage.getItem("codeman-respawn-presets"),t=e?JSON.parse(e):[];return[...BUILTIN_RESPAWN_PRESETS,...t]}saveRespawnPresets(e){const t=e.filter(n=>!n.builtIn);localStorage.setItem("codeman-respawn-presets",JSON.stringify(t))}renderPresetDropdown(){const e=this.loadRespawnPresets(),t=document.getElementById("builtinPresetsGroup"),n=document.getElementById("customPresetsGroup");!t||!n||(t.innerHTML="",n.innerHTML="",e.forEach(s=>{const i=document.createElement("option");i.value=s.id,i.textContent=s.name,s.builtIn?t.appendChild(i):n.appendChild(i)}))}updatePresetDescription(){const e=document.getElementById("respawnPresetSelect"),t=document.getElementById("presetDescriptionHint");if(!e||!t)return;const n=e.value;if(!n){t.textContent="";return}const i=this.loadRespawnPresets().find(a=>a.id===n);t.textContent=i?.description||""}loadRespawnPreset(){const e=document.getElementById("respawnPresetSelect"),t=e?.value;if(!t){this.showToast("Please select a preset first","warning");return}const s=this.loadRespawnPresets().find(i=>i.id===t);s&&(document.getElementById("modalRespawnPrompt").value=s.config.updatePrompt||"",document.getElementById("modalRespawnSendClear").checked=s.config.sendClear??!1,document.getElementById("modalRespawnSendInit").checked=s.config.sendInit??!1,document.getElementById("modalRespawnKickstart").value=s.config.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=s.config.autoAcceptPrompts??!0,s.durationMinutes&&this.selectDurationPreset(String(s.durationMinutes)),e.value="",document.getElementById("presetDescriptionHint").textContent="",this.showToast(`Loaded preset: ${s.name}`,"info"))}saveCurrentAsPreset(){document.getElementById("savePresetModal").classList.add("active"),document.getElementById("presetNameInput").value="",document.getElementById("presetDescriptionInput").value="",document.getElementById("presetNameInput").focus()}closeSavePresetModal(){document.getElementById("savePresetModal").classList.remove("active")}confirmSavePreset(){const e=document.getElementById("presetNameInput").value.trim();if(!e){this.showToast("Please enter a preset name","error");return}const t=document.getElementById("modalRespawnPrompt").value,n=document.getElementById("modalRespawnSendClear").checked,s=document.getElementById("modalRespawnSendInit").checked,i=document.getElementById("modalRespawnKickstart").value.trim()||void 0,a=this.getSelectedDuration(),l={id:"custom-"+Date.now(),name:e,description:document.getElementById("presetDescriptionInput").value.trim()||void 0,config:{idleTimeoutMs:5e3,updatePrompt:t,interStepDelayMs:3e3,sendClear:n,sendInit:s,kickstartPrompt:i},durationMinutes:a||void 0,builtIn:!1,createdAt:Date.now()},o=this.loadRespawnPresets();o.push(l),this.saveRespawnPresets(o),this.renderPresetDropdown(),this.closeSavePresetModal(),this.showToast(`Saved preset: ${e}`,"success")}deletePreset(e){const t=this.loadRespawnPresets(),n=t.find(i=>i.id===e);if(!n||n.builtIn){this.showToast("Cannot delete built-in presets","warning");return}const s=t.filter(i=>i.id!==e);this.saveRespawnPresets(s),this.renderPresetDropdown(),this.showToast(`Deleted preset: ${n.name}`,"success")}getModalRespawnConfig(){const e=document.getElementById("modalRespawnPrompt").value,t=document.getElementById("modalRespawnSendClear").checked,n=document.getElementById("modalRespawnSendInit").checked,s=document.getElementById("modalRespawnKickstart").value.trim()||void 0,i=document.getElementById("modalRespawnAutoAccept").checked,a=this.getSelectedDuration(),l=document.getElementById("modalAutoCompactEnabled").checked,o=parseInt(document.getElementById("modalAutoCompactThreshold").value)||11e4,r=document.getElementById("modalAutoCompactPrompt").value.trim()||void 0,c=document.getElementById("modalAutoClearEnabled").checked,d=parseInt(document.getElementById("modalAutoClearThreshold").value)||14e4;return{respawnConfig:{enabled:!0,updatePrompt:e,sendClear:t,sendInit:n,kickstartPrompt:s,autoAcceptPrompts:i},durationMinutes:a,autoCompactEnabled:l,autoCompactThreshold:o,autoCompactPrompt:r,autoClearEnabled:c,autoClearThreshold:d}}async enableRespawnFromModal(){if(!this.editingSessionId){this.showToast("No session selected","warning");return}const{respawnConfig:e,durationMinutes:t,autoCompactEnabled:n,autoCompactThreshold:s,autoCompactPrompt:i,autoClearEnabled:a,autoClearThreshold:l}=this.getModalRespawnConfig();try{const r=await(await fetch(`/api/sessions/${this.editingSessionId}/respawn/enable`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({config:e,durationMinutes:t})})).json();if(r.error)throw new Error(r.error);n&&await fetch(`/api/sessions/${this.editingSessionId}/auto-compact`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!0,threshold:s,prompt:i})}),a&&await fetch(`/api/sessions/${this.editingSessionId}/auto-clear`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!0,threshold:l})});const c=document.getElementById("sessionRespawnStatus");c.classList.add("active"),c.querySelector(".respawn-status-text").textContent="WATCHING",document.getElementById("modalEnableRespawnBtn").style.display="none",document.getElementById("modalStopRespawnBtn").style.display="",this.showToast("Respawn enabled","success")}catch(o){this.showToast("Failed to enable respawn: "+o.message,"error")}}async stopRespawnFromModal(){if(this.editingSessionId)try{await fetch(`/api/sessions/${this.editingSessionId}/respawn/stop`,{method:"POST"}),delete this.respawnTimers[this.editingSessionId];const e=document.getElementById("sessionRespawnStatus");e.classList.remove("active"),e.querySelector(".respawn-status-text").textContent="Not active",document.getElementById("modalEnableRespawnBtn").style.display="",document.getElementById("modalStopRespawnBtn").style.display="none",this.showToast("Respawn stopped","success")}catch{this.showToast("Failed to stop respawn","error")}}closeSessionOptions(){this.editingSessionId=null,this.stopRunSummaryAutoRefresh(),document.getElementById("sessionOptionsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)}setupColorPicker(){const e=document.getElementById("sessionColorPicker");e&&e.addEventListener("click",t=>{const n=t.target.closest(".color-swatch");if(!n||!this.editingSessionId)return;const s=n.dataset.color;this.setSessionColor(this.editingSessionId,s)})}async setSessionColor(e,t){try{if((await fetch(`/api/sessions/${e}/color`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({color:t})})).ok){const s=this.sessions.get(e);s&&(s.color=t,this.renderSessionTabs());const i=document.getElementById("sessionColorPicker");i&&i.querySelectorAll(".color-swatch").forEach(a=>{a.classList.toggle("selected",a.dataset.color===t)})}else this.showToast("Failed to set session color","error")}catch{this.showToast("Failed to set session color","error")}}async openRunSummary(e){this.openSessionOptions(e),this.switchOptionsTab("summary"),this.runSummarySessionId=e,this.runSummaryFilter="all",document.querySelectorAll(".run-summary-filters .filter-btn").forEach(t=>{t.classList.toggle("active",t.dataset.filter==="all")}),await this.loadRunSummary(e)}closeRunSummary(){this.runSummarySessionId=null,this.stopRunSummaryAutoRefresh(),this.closeSessionOptions()}async refreshRunSummary(){const e=this.runSummarySessionId||this.editingSessionId;e&&await this.loadRunSummary(e)}toggleRunSummaryAutoRefresh(){document.getElementById("runSummaryAutoRefresh").checked?this.startRunSummaryAutoRefresh():this.stopRunSummaryAutoRefresh()}startRunSummaryAutoRefresh(){this.runSummaryAutoRefreshTimer||(this.runSummaryAutoRefreshTimer=setInterval(()=>{this.runSummarySessionId&&this.loadRunSummary(this.runSummarySessionId)},5e3))}stopRunSummaryAutoRefresh(){this.runSummaryAutoRefreshTimer&&(clearInterval(this.runSummaryAutoRefreshTimer),this.runSummaryAutoRefreshTimer=null);const e=document.getElementById("runSummaryAutoRefresh");e&&(e.checked=!1)}exportRunSummary(e){if(!this.runSummaryData){this.showToast("No summary data to export","error");return}const{stats:t,events:n,sessionName:s,startedAt:i,lastUpdatedAt:a}=this.runSummaryData,l=new Date().toISOString().slice(0,19).replace(/:/g,"-"),o=`run-summary-${s||"session"}-${l}`;if(e==="json"){const r=JSON.stringify(this.runSummaryData,null,2);this.downloadFile(`${o}.json`,r,"application/json")}else if(e==="md"){const r=a-i;let c=`# Run Summary: ${s||"Session"}
|
|
28
|
+
`)),this.showToast("Copied to clipboard","success")}catch{this.showToast("Failed to copy","error")}}increaseFontSize(){const e=this.terminal.options.fontSize||14;this.setFontSize(Math.min(e+2,24))}decreaseFontSize(){const e=this.terminal.options.fontSize||14;this.setFontSize(Math.max(e-2,10))}setFontSize(e){this.terminal.options.fontSize=e,document.getElementById("fontSizeDisplay").textContent=e,this.fitAddon.fit(),localStorage.setItem("codeman-font-size",e),this._localEchoOverlay?.refreshFont()}loadFontSize(){const e=localStorage.getItem("codeman-font-size");if(e){const t=parseInt(e,10);t>=10&&t<=24&&(this.terminal.options.fontSize=t,document.getElementById("fontSizeDisplay").textContent=t)}}getTerminalDimensions(){const s=this.fitAddon?.proposeDimensions();return s?{cols:Math.max(s.cols,40),rows:Math.max(s.rows,10)}:null}async sendResize(e){const t=this.getTerminalDimensions();t&&await fetch(`/api/sessions/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async sendInput(e){this.activeSessionId&&await fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:e,useMux:!0})})}showTimer(){document.getElementById("timerBanner").style.display="flex",this.updateTimer(),this.timerInterval=setInterval(()=>this.updateTimer(),1e3)}hideTimer(){document.getElementById("timerBanner").style.display="none",this.timerInterval&&(clearInterval(this.timerInterval),this.timerInterval=null)}updateTimer(){if(!this.currentRun||this.currentRun.status!=="running")return;const e=Date.now(),t=Math.max(0,this.currentRun.endAt-e),s=this.currentRun.endAt-this.currentRun.startedAt,n=e-this.currentRun.startedAt,i=Math.min(100,n/s*100);document.getElementById("timerValue").textContent=this.formatTime(t),document.getElementById("timerProgress").style.width=`${i}%`,document.getElementById("timerMeta").textContent=`${this.currentRun.completedTasks} tasks | $${this.currentRun.totalCost.toFixed(2)}`}async stopCurrentRun(){if(this.currentRun)try{await fetch(`/api/scheduled/${this.currentRun.id}`,{method:"DELETE"})}catch{this.showToast("Failed to stop run","error")}}formatTime(e){const t=Math.floor(e/1e3),s=Math.floor(t/3600),n=Math.floor(t%3600/60),i=t%60;return`${s.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`}updateCost(){this.updateTokens()}updateTokens(){this._updateTokensTimeout&&clearTimeout(this._updateTokensTimeout),this._updateTokensTimeout=setTimeout(()=>{this._updateTokensTimeout=null,this._updateTokensImmediate()},200)}_updateTokensImmediate(){let e=0,t=0;this.globalStats?(e=this.globalStats.totalInputTokens||0,t=this.globalStats.totalOutputTokens||0):this.sessions.forEach(l=>{l.tokens&&(e+=l.tokens.input||0,t+=l.tokens.output||0)});const s=e+t;this.totalTokens=s;const n=this.formatTokens(s),i=this.estimateCost(e,t),o=this.$("headerTokens");if(o){const a=this.loadAppSettingsFromStorage().showCost??!1;o.textContent=s>0?a?`${n} tokens \xB7 $${i.toFixed(2)}`:`${n} tokens`:"0 tokens",o.title=this.globalStats?`Lifetime: ${this.globalStats.totalSessionsCreated} sessions created${a?`
|
|
29
|
+
Estimated cost based on Claude Opus pricing`:""}`:`Token usage across active sessions${a?`
|
|
30
|
+
Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t=this.sessions.get(e);if(!t)return;this.editingSessionId=e,this.switchOptionsTab(t.mode==="opencode"?"summary":"respawn");const s=document.getElementById("sessionRespawnStatus"),n=document.getElementById("modalEnableRespawnBtn"),i=document.getElementById("modalStopRespawnBtn");this.respawnStatus[e]?(s.classList.add("active"),s.querySelector(".respawn-status-text").textContent=this.respawnStatus[e].state||"Active",n.style.display="none",i.style.display=""):(s.classList.remove("active"),s.querySelector(".respawn-status-text").textContent="Not active",n.style.display="",i.style.display="none");const o=document.getElementById("sessionRespawnSection");t.mode==="claude"&&t.pid?o.style.display="":o.style.display="none";const l=t.mode==="opencode";document.querySelectorAll("[data-claude-only]").forEach(m=>{m.style.display=l?"none":""}),this.selectDurationPreset(""),this.loadSavedRespawnConfig(e),document.getElementById("modalAutoCompactEnabled").checked=t.autoCompactEnabled??!1,document.getElementById("modalAutoCompactThreshold").value=t.autoCompactThreshold??11e4,document.getElementById("modalAutoCompactPrompt").value=t.autoCompactPrompt??"",document.getElementById("modalAutoClearEnabled").checked=t.autoClearEnabled??!1,document.getElementById("modalAutoClearThreshold").value=t.autoClearThreshold??14e4,document.getElementById("modalImageWatcherEnabled").checked=t.imageWatcherEnabled??!0,document.getElementById("modalFlickerFilterEnabled").checked=t.flickerFilterEnabled??!1,document.getElementById("modalSessionName").value=t.name||"";const r=t.color||"default";document.getElementById("sessionColorPicker")?.querySelectorAll(".color-swatch").forEach(m=>{m.classList.toggle("selected",m.dataset.color===r)}),this.renderPresetDropdown(),document.getElementById("respawnPresetSelect").value="",document.getElementById("presetDescriptionHint").textContent="";const d=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="ralph"]'),u=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="respawn"]');if(l?(d&&(d.style.display="none"),u&&(u.style.display="none"),this.switchOptionsTab("context")):(d&&(d.style.display=""),u&&(u.style.display="")),!l){const m=this.ralphStates.get(e);this.populateRalphForm({enabled:m?.loop?.enabled??t.ralphLoop?.enabled??!1,completionPhrase:m?.loop?.completionPhrase||t.ralphLoop?.completionPhrase||"",maxIterations:m?.loop?.maxIterations||t.ralphLoop?.maxIterations||0})}const h=document.getElementById("sessionOptionsModal");h.classList.add("active"),this.activeFocusTrap=new FocusTrap(h),this.activeFocusTrap.activate()}async saveSessionName(){if(!this.editingSessionId)return;const e=document.getElementById("modalSessionName").value.trim();try{await this._apiPut(`/api/sessions/${this.editingSessionId}/name`,{name:e})}catch(t){this.showToast("Failed to save session name: "+t.message,"error")}}async autoSaveAutoCompact(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-compact`,{enabled:document.getElementById("modalAutoCompactEnabled").checked,threshold:parseInt(document.getElementById("modalAutoCompactThreshold").value)||11e4,prompt:document.getElementById("modalAutoCompactPrompt").value.trim()||void 0})}catch{}}async autoSaveAutoClear(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-clear`,{enabled:document.getElementById("modalAutoClearEnabled").checked,threshold:parseInt(document.getElementById("modalAutoClearThreshold").value)||14e4})}catch{}}async toggleSessionImageWatcher(){if(!this.editingSessionId)return;const e=document.getElementById("modalImageWatcherEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/image-watcher`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.imageWatcherEnabled=e),this.showToast(`Image watcher ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle image watcher","error")}}async toggleFlickerFilter(){if(!this.editingSessionId)return;const e=document.getElementById("modalFlickerFilterEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/flicker-filter`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.flickerFilterEnabled=e),this.showToast(`Flicker filter ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle flicker filter","error")}}async autoSaveRespawnConfig(){if(!this.editingSessionId)return;const e={updatePrompt:document.getElementById("modalRespawnPrompt").value,sendClear:document.getElementById("modalRespawnSendClear").checked,sendInit:document.getElementById("modalRespawnSendInit").checked,kickstartPrompt:document.getElementById("modalRespawnKickstart").value.trim()||void 0,autoAcceptPrompts:document.getElementById("modalRespawnAutoAccept").checked};try{await this._apiPut(`/api/sessions/${this.editingSessionId}/respawn/config`,e)}catch{}}async loadSavedRespawnConfig(e){try{const s=await(await fetch(`/api/sessions/${e}/respawn/config`)).json();if(s.success&&s.config){const n=s.config;document.getElementById("modalRespawnPrompt").value=n.updatePrompt||"update all the docs and CLAUDE.md",document.getElementById("modalRespawnSendClear").checked=n.sendClear??!0,document.getElementById("modalRespawnSendInit").checked=n.sendInit??!0,document.getElementById("modalRespawnKickstart").value=n.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=n.autoAcceptPrompts??!0,n.durationMinutes&&(document.querySelector(`.duration-preset-btn[data-minutes="${n.durationMinutes}"]`)?this.selectDurationPreset(String(n.durationMinutes)):(this.selectDurationPreset("custom"),document.getElementById("modalRespawnDuration").value=n.durationMinutes))}}catch{}}selectDurationPreset(e){document.querySelectorAll(".duration-preset-btn").forEach(i=>i.classList.remove("active"));const t=document.querySelector(`.duration-preset-btn[data-minutes="${e}"]`);t&&t.classList.add("active");const s=document.querySelector(".duration-custom-input"),n=document.getElementById("modalRespawnDuration");e==="custom"?(s.classList.add("visible"),n.focus()):(s.classList.remove("visible"),n.value="")}getSelectedDuration(){const e=document.querySelector(".duration-custom-input"),t=document.getElementById("modalRespawnDuration");if(e.classList.contains("visible"))return t.value?parseInt(t.value):null;{const n=document.querySelector(".duration-preset-btn.active")?.dataset.minutes;return n?parseInt(n):null}}loadRespawnPresets(){const e=localStorage.getItem("codeman-respawn-presets"),t=e?JSON.parse(e):[];return[...BUILTIN_RESPAWN_PRESETS,...t]}saveRespawnPresets(e){const t=e.filter(s=>!s.builtIn);localStorage.setItem("codeman-respawn-presets",JSON.stringify(t))}renderPresetDropdown(){const e=this.loadRespawnPresets(),t=document.getElementById("builtinPresetsGroup"),s=document.getElementById("customPresetsGroup");!t||!s||(t.innerHTML="",s.innerHTML="",e.forEach(n=>{const i=document.createElement("option");i.value=n.id,i.textContent=n.name,n.builtIn?t.appendChild(i):s.appendChild(i)}))}updatePresetDescription(){const e=document.getElementById("respawnPresetSelect"),t=document.getElementById("presetDescriptionHint");if(!e||!t)return;const s=e.value;if(!s){t.textContent="";return}const i=this.loadRespawnPresets().find(o=>o.id===s);t.textContent=i?.description||""}loadRespawnPreset(){const e=document.getElementById("respawnPresetSelect"),t=e?.value;if(!t){this.showToast("Please select a preset first","warning");return}const n=this.loadRespawnPresets().find(i=>i.id===t);n&&(document.getElementById("modalRespawnPrompt").value=n.config.updatePrompt||"",document.getElementById("modalRespawnSendClear").checked=n.config.sendClear??!1,document.getElementById("modalRespawnSendInit").checked=n.config.sendInit??!1,document.getElementById("modalRespawnKickstart").value=n.config.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=n.config.autoAcceptPrompts??!0,n.durationMinutes&&this.selectDurationPreset(String(n.durationMinutes)),e.value="",document.getElementById("presetDescriptionHint").textContent="",this.showToast(`Loaded preset: ${n.name}`,"info"))}saveCurrentAsPreset(){document.getElementById("savePresetModal").classList.add("active"),document.getElementById("presetNameInput").value="",document.getElementById("presetDescriptionInput").value="",document.getElementById("presetNameInput").focus()}closeSavePresetModal(){document.getElementById("savePresetModal").classList.remove("active")}confirmSavePreset(){const e=document.getElementById("presetNameInput").value.trim();if(!e){this.showToast("Please enter a preset name","error");return}const t=document.getElementById("modalRespawnPrompt").value,s=document.getElementById("modalRespawnSendClear").checked,n=document.getElementById("modalRespawnSendInit").checked,i=document.getElementById("modalRespawnKickstart").value.trim()||void 0,o=this.getSelectedDuration(),l={id:"custom-"+Date.now(),name:e,description:document.getElementById("presetDescriptionInput").value.trim()||void 0,config:{idleTimeoutMs:5e3,updatePrompt:t,interStepDelayMs:3e3,sendClear:s,sendInit:n,kickstartPrompt:i},durationMinutes:o||void 0,builtIn:!1,createdAt:Date.now()},a=this.loadRespawnPresets();a.push(l),this.saveRespawnPresets(a),this.renderPresetDropdown(),this.closeSavePresetModal(),this.showToast(`Saved preset: ${e}`,"success")}deletePreset(e){const t=this.loadRespawnPresets(),s=t.find(i=>i.id===e);if(!s||s.builtIn){this.showToast("Cannot delete built-in presets","warning");return}const n=t.filter(i=>i.id!==e);this.saveRespawnPresets(n),this.renderPresetDropdown(),this.showToast(`Deleted preset: ${s.name}`,"success")}getModalRespawnConfig(){const e=document.getElementById("modalRespawnPrompt").value,t=document.getElementById("modalRespawnSendClear").checked,s=document.getElementById("modalRespawnSendInit").checked,n=document.getElementById("modalRespawnKickstart").value.trim()||void 0,i=document.getElementById("modalRespawnAutoAccept").checked,o=this.getSelectedDuration(),l=document.getElementById("modalAutoCompactEnabled").checked,a=parseInt(document.getElementById("modalAutoCompactThreshold").value)||11e4,r=document.getElementById("modalAutoCompactPrompt").value.trim()||void 0,c=document.getElementById("modalAutoClearEnabled").checked,d=parseInt(document.getElementById("modalAutoClearThreshold").value)||14e4;return{respawnConfig:{enabled:!0,updatePrompt:e,sendClear:t,sendInit:s,kickstartPrompt:n,autoAcceptPrompts:i},durationMinutes:o,autoCompactEnabled:l,autoCompactThreshold:a,autoCompactPrompt:r,autoClearEnabled:c,autoClearThreshold:d}}async enableRespawnFromModal(){if(!this.editingSessionId){this.showToast("No session selected","warning");return}const{respawnConfig:e,durationMinutes:t,autoCompactEnabled:s,autoCompactThreshold:n,autoCompactPrompt:i,autoClearEnabled:o,autoClearThreshold:l}=this.getModalRespawnConfig();try{const r=await(await fetch(`/api/sessions/${this.editingSessionId}/respawn/enable`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({config:e,durationMinutes:t})})).json();if(r.error)throw new Error(r.error);s&&await fetch(`/api/sessions/${this.editingSessionId}/auto-compact`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!0,threshold:n,prompt:i})}),o&&await fetch(`/api/sessions/${this.editingSessionId}/auto-clear`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!0,threshold:l})});const c=document.getElementById("sessionRespawnStatus");c.classList.add("active"),c.querySelector(".respawn-status-text").textContent="WATCHING",document.getElementById("modalEnableRespawnBtn").style.display="none",document.getElementById("modalStopRespawnBtn").style.display="",this.showToast("Respawn enabled","success")}catch(a){this.showToast("Failed to enable respawn: "+a.message,"error")}}async stopRespawnFromModal(){if(this.editingSessionId)try{await fetch(`/api/sessions/${this.editingSessionId}/respawn/stop`,{method:"POST"}),delete this.respawnTimers[this.editingSessionId];const e=document.getElementById("sessionRespawnStatus");e.classList.remove("active"),e.querySelector(".respawn-status-text").textContent="Not active",document.getElementById("modalEnableRespawnBtn").style.display="",document.getElementById("modalStopRespawnBtn").style.display="none",this.showToast("Respawn stopped","success")}catch{this.showToast("Failed to stop respawn","error")}}closeSessionOptions(){this.editingSessionId=null,this.stopRunSummaryAutoRefresh(),document.getElementById("sessionOptionsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)}setupColorPicker(){const e=document.getElementById("sessionColorPicker");e&&e.addEventListener("click",t=>{const s=t.target.closest(".color-swatch");if(!s||!this.editingSessionId)return;const n=s.dataset.color;this.setSessionColor(this.editingSessionId,n)})}async setSessionColor(e,t){try{if((await fetch(`/api/sessions/${e}/color`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({color:t})})).ok){const n=this.sessions.get(e);n&&(n.color=t,this.renderSessionTabs());const i=document.getElementById("sessionColorPicker");i&&i.querySelectorAll(".color-swatch").forEach(o=>{o.classList.toggle("selected",o.dataset.color===t)})}else this.showToast("Failed to set session color","error")}catch{this.showToast("Failed to set session color","error")}}async openRunSummary(e){this.openSessionOptions(e),this.switchOptionsTab("summary"),this.runSummarySessionId=e,this.runSummaryFilter="all",document.querySelectorAll(".run-summary-filters .filter-btn").forEach(t=>{t.classList.toggle("active",t.dataset.filter==="all")}),await this.loadRunSummary(e)}closeRunSummary(){this.runSummarySessionId=null,this.stopRunSummaryAutoRefresh(),this.closeSessionOptions()}async refreshRunSummary(){const e=this.runSummarySessionId||this.editingSessionId;e&&await this.loadRunSummary(e)}toggleRunSummaryAutoRefresh(){document.getElementById("runSummaryAutoRefresh").checked?this.startRunSummaryAutoRefresh():this.stopRunSummaryAutoRefresh()}startRunSummaryAutoRefresh(){this.runSummaryAutoRefreshTimer||(this.runSummaryAutoRefreshTimer=setInterval(()=>{this.runSummarySessionId&&this.loadRunSummary(this.runSummarySessionId)},5e3))}stopRunSummaryAutoRefresh(){this.runSummaryAutoRefreshTimer&&(clearInterval(this.runSummaryAutoRefreshTimer),this.runSummaryAutoRefreshTimer=null);const e=document.getElementById("runSummaryAutoRefresh");e&&(e.checked=!1)}exportRunSummary(e){if(!this.runSummaryData){this.showToast("No summary data to export","error");return}const{stats:t,events:s,sessionName:n,startedAt:i,lastUpdatedAt:o}=this.runSummaryData,l=new Date().toISOString().slice(0,19).replace(/:/g,"-"),a=`run-summary-${n||"session"}-${l}`;if(e==="json"){const r=JSON.stringify(this.runSummaryData,null,2);this.downloadFile(`${a}.json`,r,"application/json")}else if(e==="md"){const r=o-i;let c=`# Run Summary: ${n||"Session"}
|
|
31
31
|
|
|
32
32
|
`;if(c+=`**Duration**: ${this.formatDuration(r)}
|
|
33
33
|
`,c+=`**Started**: ${new Date(i).toLocaleString()}
|
|
34
|
-
`,c+=`**Last Update**: ${new Date(
|
|
34
|
+
`,c+=`**Last Update**: ${new Date(o).toLocaleString()}
|
|
35
35
|
|
|
36
36
|
`,c+=`## Statistics
|
|
37
37
|
|
|
@@ -48,41 +48,41 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
48
48
|
|
|
49
49
|
`,c+=`## Event Timeline
|
|
50
50
|
|
|
51
|
-
`,
|
|
51
|
+
`,s.length===0)c+=`No events recorded.
|
|
52
52
|
`;else{c+=`| Time | Type | Severity | Title | Details |
|
|
53
53
|
`,c+=`|------|------|----------|-------|----------|
|
|
54
|
-
`;for(const d of
|
|
55
|
-
`}}this.downloadFile(`${
|
|
54
|
+
`;for(const d of s){const u=new Date(d.timestamp).toLocaleTimeString("en-US",{hour12:!1}),h=d.details?d.details.replace(/\|/g,"\\|"):"-";c+=`| ${u} | ${d.type} | ${d.severity} | ${d.title} | ${h} |
|
|
55
|
+
`}}this.downloadFile(`${a}.md`,c,"text/markdown")}this.showToast(`Exported as ${e.toUpperCase()}`,"success")}downloadFile(e,t,s){const n=new Blob([t],{type:s}),i=URL.createObjectURL(n),o=document.createElement("a");o.href=i,o.download=e,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(i)}async loadRunSummary(e){const t=document.getElementById("runSummaryTimeline");t.innerHTML='<p class="empty-message">Loading summary...</p>';try{const n=await(await fetch(`/api/sessions/${e}/run-summary`)).json();if(!n.success){t.innerHTML=`<p class="empty-message">Failed to load summary: ${escapeHtml(n.error)}</p>`;return}this.runSummaryData=n.summary,this.renderRunSummary()}catch{t.innerHTML='<p class="empty-message">Failed to load summary</p>'}}renderRunSummary(){if(!this.runSummaryData)return;const{stats:e,events:t,sessionName:s,startedAt:n,lastUpdatedAt:i}=this.runSummaryData,o=i-n;document.getElementById("runSummarySessionInfo").textContent=`${s||"Session"} - ${this.formatDuration(o)} total`;const l=this.filterRunSummaryEvents(t);this.renderRunSummaryTimeline(l)}filterRunSummaryEvents(e){return this.runSummaryFilter==="all"?e:e.filter(t=>{switch(this.runSummaryFilter){case"errors":return t.severity==="error";case"warnings":return t.severity==="warning"||t.severity==="error";case"respawn":return t.type.startsWith("respawn_")||t.type==="state_stuck";case"idle":return t.type==="idle_detected"||t.type==="working_detected";default:return!0}})}filterRunSummary(e){this.runSummaryFilter=e,document.querySelectorAll(".run-summary-filters .filter-btn").forEach(t=>{t.classList.toggle("active",t.dataset.filter===e)}),this.renderRunSummary()}renderRunSummaryTimeline(e){const t=document.getElementById("runSummaryTimeline");if(!e||e.length===0){t.innerHTML='<p class="empty-message">No events recorded yet</p>';return}const n=[...e].reverse().map(i=>{const o=new Date(i.timestamp).toLocaleTimeString("en-US",{hour12:!1}),l=`event-${i.severity}`,a=this.getEventIcon(i.type,i.severity);return`
|
|
56
56
|
<div class="timeline-event ${l}">
|
|
57
|
-
<div class="event-icon">${
|
|
57
|
+
<div class="event-icon">${a}</div>
|
|
58
58
|
<div class="event-content">
|
|
59
59
|
<div class="event-header">
|
|
60
60
|
<span class="event-title">${escapeHtml(i.title)}</span>
|
|
61
|
-
<span class="event-time">${
|
|
61
|
+
<span class="event-time">${o}</span>
|
|
62
62
|
</div>
|
|
63
63
|
${i.details?`<div class="event-details">${escapeHtml(i.details)}</div>`:""}
|
|
64
64
|
</div>
|
|
65
65
|
</div>
|
|
66
|
-
`}).join("");t.innerHTML=s}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),n=Math.floor(t/60),s=Math.floor(n/60);return s>0?`${s}h ${n%60}m`:n>0?`${n}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 n=await(await fetch(`/api/sessions/${this.editingSessionId}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(n.error)throw new Error(n.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 n=document.querySelector(`.tab-name[data-session-id="${e}"]`);if(!n)return;const s=this.getSessionName(t),i=document.createElement("input");i.type="text",i.value=t.name||"",i.placeholder=s,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 a=n.textContent;n.textContent="",n.appendChild(i),i.focus(),i.select();const l=async()=>{const o=i.value.trim();if(n.textContent=o||a,o&&o!==t.name)try{await fetch(`/api/sessions/${e}/name`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:o})})}catch{n.textContent=a,this.showToast("Failed to rename","error")}};i.addEventListener("blur",l),i.addEventListener("keydown",o=>{o.key==="Enter"?(o.preventDefault(),i.blur()):o.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:n}=t.data;n&&this.sessions.has(n)&&this.selectSession(n),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),n=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),s=n.toJSON(),i=await this._apiJson("/api/push/subscribe",{method:"POST",body:{endpoint:s.endpoint,keys:s.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()}});if(!i?.success)throw new Error("Failed to register subscription");this._pushSubscription=n,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[n,s]of Object.entries(t)){const i=document.getElementById(s);e[n]=i?i.checked:!0}return e["session:error"]=!0,e}_updatePushUI(e){const t=document.getElementById("pushSubscribeBtn"),n=document.getElementById("pushSubscriptionStatus");t&&(t.textContent=e?"Unsubscribe":"Subscribe"),n&&(n.textContent=e?"active":"off",n.classList.remove("granted","denied"),e&&n.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 n=document.getElementById("appSettingsClaudeMode"),s=document.getElementById("allowedToolsRow");n.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",s.style.display=n.value==="allowedTools"?"":"none",n.onchange=()=>{s.style.display=n.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 a=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=a.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=a.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=a.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((a.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!a.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!a.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!a.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const l=a.eventTypes||{},o=l.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=o.enabled??!0,document.getElementById("eventPermissionBrowser").checked=o.browser??!0,document.getElementById("eventPermissionPush").checked=o.push??!1,document.getElementById("eventPermissionAudio").checked=o.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 S=Notification.permission;p.textContent=S==="granted"?"\u2713":S==="denied"?"\u2717":"?",p.classList.remove("granted","denied"),S==="granted"?p.classList.add("granted"):S==="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 y=VoiceInput.getActiveProviderName(),w=document.getElementById("voiceProviderStatus");w.textContent=y,w.className="voice-provider-status"+(y.startsWith("Deepgram")?" active":""),this.switchSettingsTab("settings-display");const b=document.getElementById("appSettingsModal");b.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(S=>{S.onclick=()=>this.switchSettingsTab(S.dataset.tab)}),b.classList.add("active"),this.activeFocusTrap=new FocusTrap(b),this.activeFocusTrap.activate()}switchSettingsTab(e){const t=document.getElementById("appSettingsModal");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)})}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(),n=t.running&&t.url;this._updateTunnelUrlDisplay(n?t.url:null),this._updateWelcomeTunnelBtn(!!n,n?t.url:null)}catch{this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1)}}_updateTunnelUrlDisplay(e){const t=document.getElementById("tunnelUrlRow"),n=document.getElementById("tunnelUrlDisplay");!t||!n||(e?(t.style.display="",n.textContent=e,n.onclick=()=>{navigator.clipboard.writeText(e).then(()=>{this.showToast("Tunnel URL copied","success")})}):(t.style.display="none",n.textContent="",n.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=n=>{n.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=`
|
|
66
|
+
`}).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 b=document.getElementById("appSettingsModal");b.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(y=>{y.onclick=()=>this.switchSettingsTab(y.dataset.tab)}),b.classList.add("active"),this.activeFocusTrap=new FocusTrap(b),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=`
|
|
67
67
|
<div style="font-size:14px;font-weight:600;color:var(--text-primary);margin-bottom:16px">Scan to connect</div>
|
|
68
68
|
<div id="tunnelQrContainer" style="background:#fff;border-radius:8px;padding:16px;display:inline-block">
|
|
69
69
|
<div style="color:#666;font-size:12px">Loading...</div>
|
|
70
70
|
</div>
|
|
71
71
|
<div id="tunnelQrUrl" style="margin-top:12px;font-family:monospace;font-size:11px;color:var(--text-muted);word-break:break-all;cursor:pointer" title="Click to copy"></div>
|
|
72
72
|
<button onclick="app.closeTunnelQR()" style="margin-top:16px;padding:6px 20px;background:var(--bg-elevated);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);cursor:pointer;font-size:13px">Close</button>
|
|
73
|
-
`,e.appendChild(t),document.body.appendChild(e),fetch("/api/tunnel/qr").then(
|
|
73
|
+
`,e.appendChild(t),document.body.appendChild(e),fetch("/api/tunnel/qr").then(s=>{if(!s.ok)throw new Error("Tunnel not running");return s.json()}).then(s=>{const n=document.getElementById("tunnelQrContainer");if(n&&s.svg&&(n.innerHTML=s.svg),s.authEnabled){const i=document.createElement("div");i.id="tunnelQrBadge",i.style.cssText="margin-top:8px;font-size:11px;color:var(--text-muted)",i.textContent="Single-use auth \xB7 expires in 60s";const o=document.createElement("button");o.textContent="Regenerate QR",o.style.cssText="margin-top:8px;padding:4px 12px;background:var(--bg-elevated);border:1px solid var(--border);border-radius:4px;color:var(--text-secondary);cursor:pointer;font-size:11px",o.onclick=()=>{fetch("/api/tunnel/qr/regenerate",{method:"POST"}).then(()=>this.showToast("QR code regenerated","success")).catch(()=>this.showToast("Failed to regenerate QR","error"))};const l=n.parentElement;l&&(l.appendChild(i),l.appendChild(o)),this._resetQrCountdown()}}).catch(()=>{const s=document.getElementById("tunnelQrContainer");s&&(s.innerHTML='<div style="color:#c00;font-size:12px;padding:20px">Tunnel not active</div>')}),fetch("/api/tunnel/status").then(s=>s.json()).then(s=>{const n=document.getElementById("tunnelQrUrl");n&&s.url&&(n.textContent=s.url,n.onclick=()=>{navigator.clipboard.writeText(s.url).then(()=>{this.showToast("Tunnel URL copied","success")})})}).catch(()=>{}),this._tunnelQrEscHandler=s=>{s.key==="Escape"&&this.closeTunnelQR()},document.addEventListener("keydown",this._tunnelQrEscHandler)}closeTunnelQR(){const e=document.getElementById("tunnelQrOverlay");e&&e.remove(),this._tunnelQrEscHandler&&(document.removeEventListener("keydown",this._tunnelQrEscHandler),this._tunnelQrEscHandler=null),this._clearQrCountdown()}_refreshTunnelQrFromApi(){fetch("/api/tunnel/qr").then(e=>e.ok?e.json():null).then(e=>{if(!e?.svg)return;const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=e.svg)}).catch(()=>{})}_resetQrCountdown(){this._clearQrCountdown(),this._qrCountdownSec=60,this._updateQrCountdownText(),this._qrCountdownTimer=setInterval(()=>{if(this._qrCountdownSec--,this._qrCountdownSec<=0){this._clearQrCountdown();return}this._updateQrCountdownText()},1e3)}_updateQrCountdownText(){const e=document.getElementById("tunnelQrBadge");e&&(e.textContent=`Single-use auth \xB7 expires in ${this._qrCountdownSec}s`)}_clearQrCountdown(){this._qrCountdownTimer&&(clearInterval(this._qrCountdownTimer),this._qrCountdownTimer=null)}async toggleTunnelFromWelcome(){const e=document.getElementById("welcomeTunnelBtn");if(!e)return;const t=e.classList.contains("active");e.disabled=!0;try{const s=!t;await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:s})}),s?(this._showTunnelConnecting(),this._pollTunnelStatus()):(this._dismissTunnelConnecting(),this.showToast("Tunnel stopped","info"),this._updateWelcomeTunnelBtn(!1),e.disabled=!1)}catch{this._dismissTunnelConnecting(),this.showToast("Failed to toggle tunnel","error"),e.disabled=!1}}_showTunnelConnecting(){const e=document.getElementById("tunnelConnectingToast");e&&e.remove();const t=document.getElementById("welcomeTunnelBtn");t&&(t.classList.add("connecting"),t.innerHTML=`
|
|
74
74
|
<span class="tunnel-spinner"></span>
|
|
75
|
-
Connecting...`);const
|
|
75
|
+
Connecting...`);const s=document.createElement("div");s.className="toast toast-info show",s.id="tunnelConnectingToast",s.innerHTML='<span class="tunnel-spinner"></span> Cloudflare Tunnel connecting...',s.style.pointerEvents="auto",this._toastContainer||(this._toastContainer=document.querySelector(".toast-container"),this._toastContainer||(this._toastContainer=document.createElement("div"),this._toastContainer.className="toast-container",document.body.appendChild(this._toastContainer))),this._toastContainer.appendChild(s)}_dismissTunnelConnecting(){clearTimeout(this._tunnelPollTimer),this._tunnelPollTimer=null;const e=document.getElementById("tunnelConnectingToast");e&&(e.classList.remove("show"),setTimeout(()=>e.remove(),200));const t=document.getElementById("welcomeTunnelBtn");t&&t.classList.remove("connecting")}_pollTunnelStatus(e=0){e>15||(this._tunnelPollTimer=setTimeout(async()=>{try{const s=await(await fetch("/api/tunnel/status")).json();if(s.running&&s.url){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(s.url),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,s.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,s.url),this.showToast(`Tunnel active: ${s.url}`,"success"),this.showTunnelQR());return}}catch{}this._pollTunnelStatus(e+1)},2e3))}_updateWelcomeTunnelBtn(e,t,s=!1){const n=document.getElementById("welcomeTunnelBtn");n&&(n.disabled=!1,e?(n.classList.remove("connecting"),n.classList.add("active"),n.innerHTML=`
|
|
76
76
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
|
|
77
|
-
Tunnel Active`):(
|
|
77
|
+
Tunnel Active`):(n.classList.remove("active","connecting"),n.innerHTML=`
|
|
78
78
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
|
|
79
|
-
Cloudflare Tunnel`));const i=document.getElementById("welcomeQr"),
|
|
79
|
+
Cloudflare Tunnel`));const i=document.getElementById("welcomeQr"),o=document.getElementById("welcomeQrInner"),l=document.getElementById("welcomeQrUrl");!i||!o||(e?(i.classList.add("visible"),s&&(i.classList.add("expanded"),clearTimeout(this._welcomeQrShrinkTimer),this._welcomeQrShrinkTimer=setTimeout(()=>{i.classList.remove("expanded")},8e3)),t&&(l.textContent=t,l.title="Click QR to enlarge"),fetch("/api/tunnel/qr").then(a=>{if(!a.ok)throw new Error;return a.json()}).then(a=>{a.svg&&(o.innerHTML=a.svg)}).catch(()=>{o.innerHTML='<div style="color:#999;font-size:11px;padding:20px">QR unavailable</div>'})):(clearTimeout(this._welcomeQrShrinkTimer),i.classList.remove("visible","expanded"),o.innerHTML="",l&&(l.textContent="")))}toggleWelcomeQrSize(){const e=document.getElementById("welcomeQr");e&&(clearTimeout(this._welcomeQrShrinkTimer),e.classList.toggle("expanded"))}toggleDeepgramKeyVisibility(){const e=document.getElementById("voiceDeepgramKey"),t=document.getElementById("voiceKeyToggleBtn");e.type==="password"?(e.type="text",t.textContent="Hide"):(e.type="password",t.textContent="Show")}openLifecycleLog(){const e=document.getElementById("lifecycleWindow");e.style.display="block",e._dragInitialized||(e.style.left="50%",e.style.transform="translateX(-50%)",this._initLifecycleDrag(e),e._dragInitialized=!0),this.loadLifecycleLog()}closeLifecycleLog(){document.getElementById("lifecycleWindow").style.display="none"}_initLifecycleDrag(e){const t=document.getElementById("lifecycleWindowHeader");let s=!1,n,i,o,l;t.addEventListener("mousedown",a=>{if(a.target.tagName==="SELECT"||a.target.tagName==="INPUT"||a.target.tagName==="BUTTON")return;s=!0;const r=e.getBoundingClientRect();e.style.transform="none",e.style.left=r.left+"px",e.style.top=r.top+"px",n=a.clientX,i=a.clientY,o=r.left,l=r.top,a.preventDefault()}),document.addEventListener("mousemove",a=>{s&&(e.style.left=o+a.clientX-n+"px",e.style.top=l+a.clientY-i+"px")}),document.addEventListener("mouseup",()=>{s=!1})}async loadLifecycleLog(){const e=document.getElementById("lifecycleFilterEvent").value,t=document.getElementById("lifecycleFilterSession").value.trim(),s=new URLSearchParams;e&&s.set("event",e),t&&s.set("sessionId",t),s.set("limit","300");try{const i=await(await fetch(`/api/session-lifecycle?${s}`)).json(),o=document.getElementById("lifecycleTableBody"),l=document.getElementById("lifecycleEmpty");if(!i.entries||i.entries.length===0){o.innerHTML="",l.style.display="";return}l.style.display="none";const a={created:"#4ade80",started:"#4ade80",recovered:"#4ade80",exit:"#fbbf24",mux_died:"#f87171",deleted:"#f87171",stale_cleaned:"#f87171",server_started:"#666",server_stopped:"#666"};o.innerHTML=i.entries.map(r=>{const c=new Date(r.ts).toLocaleString(),d=a[r.event]||"#888",u=r.name||(r.sessionId==="*"?"\u2014":this.getShortId(r.sessionId)),h=[];return r.exitCode!==void 0&&r.exitCode!==null&&h.push(`code=${r.exitCode}`),r.mode&&h.push(r.mode),`<tr style="border-bottom:1px solid #1a1a2e">
|
|
80
80
|
<td style="padding:3px 8px;color:#888;white-space:nowrap">${c}</td>
|
|
81
81
|
<td style="padding:3px 8px;color:${d};font-weight:600">${r.event}</td>
|
|
82
82
|
<td style="padding:3px 8px;color:#e0e0e0" title="${r.sessionId}">${u}</td>
|
|
83
83
|
<td style="padding:3px 8px;color:#aaa">${r.reason||""}</td>
|
|
84
84
|
<td style="padding:3px 8px;color:#666">${h.join(", ")}</td>
|
|
85
|
-
</tr>`}).join("")}catch{}}async saveAppSettings(){const e={defaultClaudeMdPath:document.getElementById("appSettingsClaudeMdPath").value.trim(),defaultWorkingDir:document.getElementById("appSettingsDefaultDir").value.trim(),ralphTrackerEnabled:document.getElementById("appSettingsRalphEnabled").checked,showFontControls:document.getElementById("appSettingsShowFontControls").checked,showSystemStats:document.getElementById("appSettingsShowSystemStats").checked,showTokenCount:document.getElementById("appSettingsShowTokenCount").checked,showCost:document.getElementById("appSettingsShowCost").checked,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").checked,subagentTrackingEnabled:document.getElementById("appSettingsSubagentTracking").checked,subagentActiveTabOnly:document.getElementById("appSettingsSubagentActiveTabOnly").checked,imageWatcherEnabled:document.getElementById("appSettingsImageWatcherEnabled").checked,tunnelEnabled:document.getElementById("appSettingsTunnelEnabled").checked,localEchoEnabled:document.getElementById("appSettingsLocalEcho").checked,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};this.saveAppSettingsToStorage(e),this._updateLocalEchoState();const t={apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(t);const n={enabled:document.getElementById("appSettingsNotifEnabled").checked,browserNotifications:document.getElementById("appSettingsNotifBrowser").checked,audioAlerts:document.getElementById("appSettingsNotifAudio").checked,stuckThresholdMs:(parseInt(document.getElementById("appSettingsNotifStuckMins").value)||10)*6e4,muteCritical:!document.getElementById("appSettingsNotifCritical").checked,muteWarning:!document.getElementById("appSettingsNotifWarning").checked,muteInfo:!document.getElementById("appSettingsNotifInfo").checked,eventTypes:{permission_prompt:{enabled:document.getElementById("eventPermissionEnabled").checked,browser:document.getElementById("eventPermissionBrowser").checked,push:document.getElementById("eventPermissionPush").checked,audio:document.getElementById("eventPermissionAudio").checked},elicitation_dialog:{enabled:document.getElementById("eventQuestionEnabled").checked,browser:document.getElementById("eventQuestionBrowser").checked,push:document.getElementById("eventQuestionPush").checked,audio:document.getElementById("eventQuestionAudio").checked},idle_prompt:{enabled:document.getElementById("eventIdleEnabled").checked,browser:document.getElementById("eventIdleBrowser").checked,push:document.getElementById("eventIdlePush").checked,audio:document.getElementById("eventIdleAudio").checked},stop:{enabled:document.getElementById("eventStopEnabled").checked,browser:document.getElementById("eventStopBrowser").checked,push:document.getElementById("eventStopPush").checked,audio:document.getElementById("eventStopAudio").checked},session_error:{enabled:!0,browser:this.notificationManager?.preferences?.eventTypes?.session_error?.browser??!0,push:this.notificationManager?.preferences?.eventTypes?.session_error?.push??!1,audio:!1},respawn_cycle:{enabled:document.getElementById("eventRespawnEnabled").checked,browser:document.getElementById("eventRespawnBrowser").checked,push:document.getElementById("eventRespawnPush").checked,audio:document.getElementById("eventRespawnAudio").checked},token_milestone:{enabled:!0,browser:!1,push:!1,audio:!1},ralph_complete:{enabled:document.getElementById("eventRalphEnabled").checked,browser:document.getElementById("eventRalphBrowser").checked,push:document.getElementById("eventRalphPush").checked,audio:document.getElementById("eventRalphAudio").checked},subagent_spawn:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked},subagent_complete:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked}},_version:4};this.notificationManager&&(this.notificationManager.preferences=n,this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility();const{localEchoEnabled:s,...i}=e;try{await this._apiPut("/api/settings",{...i,notificationPreferences:n,voiceSettings:t}),await this.saveModelConfigFromSettings(),this.showToast("Settings saved","success"),e.tunnelEnabled&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}this.closeAppSettings()}async loadModelConfigForSettings(){try{const t=await(await fetch("/api/execution/model-config")).json();if(t.success&&t.data){const n=t.data,s=document.getElementById("appSettingsDefaultModel");s&&(s.value=n.defaultModel||"opus");const i=document.getElementById("appSettingsShowModelRecommendations");i&&(i.checked=n.showRecommendations??!0);const a=n.agentTypeOverrides||{},l=document.getElementById("appSettingsModelExplore"),o=document.getElementById("appSettingsModelImplement"),r=document.getElementById("appSettingsModelTest"),c=document.getElementById("appSettingsModelReview");l&&(l.value=a.explore||""),o&&(o.value=a.implement||""),r&&(r.value=a.test||""),c&&(c.value=a.review||"")}}catch{}}async saveModelConfigFromSettings(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),n=document.getElementById("appSettingsModelExplore"),s=document.getElementById("appSettingsModelImplement"),i=document.getElementById("appSettingsModelTest"),a=document.getElementById("appSettingsModelReview"),l={};n?.value&&(l.explore=n.value),s?.value&&(l.implement=s.value),i?.value&&(l.test=i.value),a?.value&&(l.review=a.value);const o={defaultModel:e?.value||"opus",showRecommendations:t?.checked??!0,agentTypeOverrides:l};try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})}catch{}}isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1}getSettingsStorageKey(){return MobileDetection.getDeviceType()==="mobile"?"codeman-app-settings-mobile":"codeman-app-settings"}getDefaultSettings(){return MobileDetection.getDeviceType()==="mobile"?{showFontControls:!1,showSystemStats:!1,showTokenCount:!1,showCost:!1,showMonitor:!1,showProjectInsights:!1,showFileBrowser:!1,showSubagents:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1}:{}}loadAppSettingsFromStorage(){if(this._cachedAppSettings)return this._cachedAppSettings;try{const e=this.getSettingsStorageKey(),t=localStorage.getItem(e);if(t)return this._cachedAppSettings=JSON.parse(t),this._cachedAppSettings}catch{}return this._cachedAppSettings=this.getDefaultSettings(),this._cachedAppSettings}saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch{}}applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showFontControls??t.showFontControls??!1,s=e.showSystemStats??t.showSystemStats??!0,i=e.showTokenCount??t.showTokenCount??!0,a=document.querySelector(".header-font-controls"),l=document.getElementById("headerSystemStats"),o=document.getElementById("headerTokens");a&&(a.style.display=n?"":"none"),l&&(l.style.display=s?"":"none"),o&&(o.style.display=i?"":"none");const r=e.showLifecycleLog??t.showLifecycleLog??!0,c=document.querySelector(".btn-lifecycle-log");c&&(c.style.display=r?"":"none");const d=this.notificationManager?.preferences?.enabled??!0,u=document.querySelector(".btn-notifications");if(u&&(u.style.display=d?"":"none"),!d){const h=document.getElementById("notifDrawer");h&&h.classList.remove("open")}}applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=MobileDetection.getDeviceType()==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,i=this._tallTabsEnabled;this._tallTabsEnabled=s;const a=document.getElementById("sessionTabs");a&&(a.classList.toggle("tabs-two-rows",s),a.classList.toggle("tabs-show-folder",s)),i!==void 0&&i!==s&&this._fullRenderSessionTabs()}applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showMonitor??t.showMonitor??!0,s=e.showSubagents??t.showSubagents??!0,i=e.showFileBrowser??t.showFileBrowser??!1,a=document.getElementById("monitorPanel");a&&(a.style.display=n?"":"none",n?a.classList.add("open"):a.classList.remove("open"));const l=document.getElementById("subagentsPanel");l&&(s?l.classList.remove("hidden"):l.classList.add("hidden"));const o=document.getElementById("fileBrowserPanel");o&&(i&&this.activeSessionId?(o.classList.add("visible"),this.loadFileBrowser(this.activeSessionId)):o.classList.remove("visible"))}closeMonitor(){const e=document.getElementById("monitorPanel");e&&(e.classList.remove("open"),e.style.display="none");const t=this.loadAppSettingsFromStorage();t.showMonitor=!1,this.saveAppSettingsToStorage(t)}closeSubagentsPanel(){const e=document.getElementById("subagentsPanel");e&&(e.classList.remove("open"),e.classList.add("hidden")),this.subagentPanelVisible=!1;const t=this.loadAppSettingsFromStorage();t.showSubagents=!1,this.saveAppSettingsToStorage(t)}async clearAllSubagents(){const e=this.subagents.size;if(e===0){this.showToast("No subagents to clear","info");return}if(confirm(`Clear all ${e} tracked subagent(s)? This removes them from the UI but does not affect running processes.`))try{const n=await(await fetch("/api/subagents",{method:"DELETE"})).json();n.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${n.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+n.error,"error")}catch{this.showToast("Failed to clear subagents","error")}}toggleSubagentsPanel(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsToggleBtn");if(e){if(e.classList.contains("hidden")){e.classList.remove("hidden");const n=this.loadAppSettingsFromStorage();n.showSubagents=!0,this.saveAppSettingsToStorage(n)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"▼":"▲"),this.subagentPanelVisible&&this.renderSubagentPanel()}}async loadAppSettingsFromServer(e=null){try{const t=e?await e:await fetch("/api/settings").then(n=>n.ok?n.json():null);if(t){const{notificationPreferences:n,voiceSettings:s,...i}=t,a=new Set(["showFontControls","showSystemStats","showTokenCount","showCost","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","localEchoEnabled"]),l=this.loadAppSettingsFromStorage(),o={...l};for(const[r,c]of Object.entries(i))a.has(r)&&r in l||(o[r]=c);if(this.saveAppSettingsToStorage(o),n&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=n,this.notificationManager.savePreferences())),s){const r=localStorage.getItem("codeman-voice-settings");(!r||!JSON.parse(r).apiKey)&&VoiceInput._saveDeepgramConfig(s)}return o}}catch{}return this.loadAppSettingsFromStorage()}async loadSubagentWindowStates(){let e=null;try{const t=await fetch("/api/subagent-window-states");t.ok&&(e=await t.json(),localStorage.setItem("codeman-subagent-window-states",JSON.stringify(e)))}catch{}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch{}return e||{minimized:{},open:[]}}async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch{}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{}}async loadSubagentParentMap(){let e=null;try{const t=await fetch("/api/subagent-parents");t.ok&&(e=await t.json(),localStorage.setItem("codeman-subagent-parents",JSON.stringify(e)))}catch{}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch{}if(e&&typeof e=="object")for(const[t,n]of Object.entries(e))this.sessions.has(n)&&this.subagents.has(t)&&this.subagentParentMap.set(t,n)}getAgentParentSessionId(e){return this.subagentParentMap.get(e)||null}setAgentParentSessionId(e,t){if(!e||!t||this.subagentParentMap.has(e))return;this.subagentParentMap.set(e,t),this.saveSubagentParentMap();const n=this.subagents.get(e);if(n){n.parentSessionId=t;const s=this.sessions.get(t);s&&(n.parentSessionName=this.getSessionName(s)),this.subagents.set(e,n)}}showHelp(){const e=document.getElementById("helpModal");e.classList.add("active"),this.activeFocusTrap=new FocusTrap(e),this.activeFocusTrap.activate()}closeHelp(){document.getElementById("helpModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)}closeAllPanels(){this.closeSessionOptions(),this.closeAppSettings(),this.cancelCloseSession(),this.closeTokenStats(),document.getElementById("monitorPanel").classList.remove("open");const e=document.getElementById("subagentsPanel");e&&e.classList.remove("open"),this.subagentPanelVisible=!1}async openTokenStats(){try{const t=await(await fetch("/api/token-stats")).json();t.success?(this.renderTokenStats(t),document.getElementById("tokenStatsModal").classList.add("active")):this.showToast("Failed to load token stats","error")}catch{this.showToast("Failed to load token stats","error")}}renderTokenStats(e){const{daily:t,totals:n}=e,s=new Date().toISOString().split("T")[0],i=t.find(S=>S.date===s)||{inputTokens:0,outputTokens:0,estimatedCost:0},a=new Date;a.setDate(a.getDate()-7);const l=t.filter(S=>new Date(S.date)>=a),o=l.reduce((S,v)=>S+v.inputTokens,0),r=l.reduce((S,v)=>S+v.outputTokens,0),c=this.estimateCost(o,r),d=n.totalInputTokens,u=n.totalOutputTokens,h=this.estimateCost(d,u),m=document.getElementById("statsSummary");m.innerHTML=`
|
|
85
|
+
</tr>`}).join("")}catch{}}async saveAppSettings(){const e={defaultClaudeMdPath:document.getElementById("appSettingsClaudeMdPath").value.trim(),defaultWorkingDir:document.getElementById("appSettingsDefaultDir").value.trim(),ralphTrackerEnabled:document.getElementById("appSettingsRalphEnabled").checked,showFontControls:document.getElementById("appSettingsShowFontControls").checked,showSystemStats:document.getElementById("appSettingsShowSystemStats").checked,showTokenCount:document.getElementById("appSettingsShowTokenCount").checked,showCost:document.getElementById("appSettingsShowCost").checked,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").checked,subagentTrackingEnabled:document.getElementById("appSettingsSubagentTracking").checked,subagentActiveTabOnly:document.getElementById("appSettingsSubagentActiveTabOnly").checked,imageWatcherEnabled:document.getElementById("appSettingsImageWatcherEnabled").checked,tunnelEnabled:document.getElementById("appSettingsTunnelEnabled").checked,localEchoEnabled:document.getElementById("appSettingsLocalEcho").checked,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};this.saveAppSettingsToStorage(e),this._updateLocalEchoState();const t={apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(t);const s={enabled:document.getElementById("appSettingsNotifEnabled").checked,browserNotifications:document.getElementById("appSettingsNotifBrowser").checked,audioAlerts:document.getElementById("appSettingsNotifAudio").checked,stuckThresholdMs:(parseInt(document.getElementById("appSettingsNotifStuckMins").value)||10)*6e4,muteCritical:!document.getElementById("appSettingsNotifCritical").checked,muteWarning:!document.getElementById("appSettingsNotifWarning").checked,muteInfo:!document.getElementById("appSettingsNotifInfo").checked,eventTypes:{permission_prompt:{enabled:document.getElementById("eventPermissionEnabled").checked,browser:document.getElementById("eventPermissionBrowser").checked,push:document.getElementById("eventPermissionPush").checked,audio:document.getElementById("eventPermissionAudio").checked},elicitation_dialog:{enabled:document.getElementById("eventQuestionEnabled").checked,browser:document.getElementById("eventQuestionBrowser").checked,push:document.getElementById("eventQuestionPush").checked,audio:document.getElementById("eventQuestionAudio").checked},idle_prompt:{enabled:document.getElementById("eventIdleEnabled").checked,browser:document.getElementById("eventIdleBrowser").checked,push:document.getElementById("eventIdlePush").checked,audio:document.getElementById("eventIdleAudio").checked},stop:{enabled:document.getElementById("eventStopEnabled").checked,browser:document.getElementById("eventStopBrowser").checked,push:document.getElementById("eventStopPush").checked,audio:document.getElementById("eventStopAudio").checked},session_error:{enabled:!0,browser:this.notificationManager?.preferences?.eventTypes?.session_error?.browser??!0,push:this.notificationManager?.preferences?.eventTypes?.session_error?.push??!1,audio:!1},respawn_cycle:{enabled:document.getElementById("eventRespawnEnabled").checked,browser:document.getElementById("eventRespawnBrowser").checked,push:document.getElementById("eventRespawnPush").checked,audio:document.getElementById("eventRespawnAudio").checked},token_milestone:{enabled:!0,browser:!1,push:!1,audio:!1},ralph_complete:{enabled:document.getElementById("eventRalphEnabled").checked,browser:document.getElementById("eventRalphBrowser").checked,push:document.getElementById("eventRalphPush").checked,audio:document.getElementById("eventRalphAudio").checked},subagent_spawn:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked},subagent_complete:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked}},_version:4};this.notificationManager&&(this.notificationManager.preferences=s,this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility();const{localEchoEnabled:n,...i}=e;try{await this._apiPut("/api/settings",{...i,notificationPreferences:s,voiceSettings:t}),await this.saveModelConfigFromSettings(),this.showToast("Settings saved","success"),e.tunnelEnabled&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}this.closeAppSettings()}async loadModelConfigForSettings(){try{const t=await(await fetch("/api/execution/model-config")).json();if(t.success&&t.data){const s=t.data,n=document.getElementById("appSettingsDefaultModel");n&&(n.value=s.defaultModel||"opus");const i=document.getElementById("appSettingsShowModelRecommendations");i&&(i.checked=s.showRecommendations??!0);const o=s.agentTypeOverrides||{},l=document.getElementById("appSettingsModelExplore"),a=document.getElementById("appSettingsModelImplement"),r=document.getElementById("appSettingsModelTest"),c=document.getElementById("appSettingsModelReview");l&&(l.value=o.explore||""),a&&(a.value=o.implement||""),r&&(r.value=o.test||""),c&&(c.value=o.review||"")}}catch{}}async saveModelConfigFromSettings(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),s=document.getElementById("appSettingsModelExplore"),n=document.getElementById("appSettingsModelImplement"),i=document.getElementById("appSettingsModelTest"),o=document.getElementById("appSettingsModelReview"),l={};s?.value&&(l.explore=s.value),n?.value&&(l.implement=n.value),i?.value&&(l.test=i.value),o?.value&&(l.review=o.value);const a={defaultModel:e?.value||"opus",showRecommendations:t?.checked??!0,agentTypeOverrides:l};try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})}catch{}}isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1}getSettingsStorageKey(){return MobileDetection.getDeviceType()==="mobile"?"codeman-app-settings-mobile":"codeman-app-settings"}getDefaultSettings(){return MobileDetection.getDeviceType()==="mobile"?{showFontControls:!1,showSystemStats:!1,showTokenCount:!1,showCost:!1,showMonitor:!1,showProjectInsights:!1,showFileBrowser:!1,showSubagents:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1}:{}}loadAppSettingsFromStorage(){if(this._cachedAppSettings)return this._cachedAppSettings;try{const e=this.getSettingsStorageKey(),t=localStorage.getItem(e);if(t)return this._cachedAppSettings=JSON.parse(t),this._cachedAppSettings}catch{}return this._cachedAppSettings=this.getDefaultSettings(),this._cachedAppSettings}saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch{}}applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=e.showFontControls??t.showFontControls??!1,n=e.showSystemStats??t.showSystemStats??!0,i=e.showTokenCount??t.showTokenCount??!0,o=document.querySelector(".header-font-controls"),l=document.getElementById("headerSystemStats"),a=document.getElementById("headerTokens");o&&(o.style.display=s?"":"none"),l&&(l.style.display=n?"":"none"),a&&(a.style.display=i?"":"none");const r=e.showLifecycleLog??t.showLifecycleLog??!0,c=document.querySelector(".btn-lifecycle-log");c&&(c.style.display=r?"":"none");const d=this.notificationManager?.preferences?.enabled??!0,u=document.querySelector(".btn-notifications");if(u&&(u.style.display=d?"":"none"),!d){const h=document.getElementById("notifDrawer");h&&h.classList.remove("open")}}applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=MobileDetection.getDeviceType()==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,i=this._tallTabsEnabled;this._tallTabsEnabled=n;const o=document.getElementById("sessionTabs");o&&(o.classList.toggle("tabs-two-rows",n),o.classList.toggle("tabs-show-folder",n)),i!==void 0&&i!==n&&this._fullRenderSessionTabs()}applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=e.showMonitor??t.showMonitor??!0,n=e.showSubagents??t.showSubagents??!0,i=e.showFileBrowser??t.showFileBrowser??!1,o=document.getElementById("monitorPanel");o&&(o.style.display=s?"":"none",s?o.classList.add("open"):o.classList.remove("open"));const l=document.getElementById("subagentsPanel");l&&(n?l.classList.remove("hidden"):l.classList.add("hidden"));const a=document.getElementById("fileBrowserPanel");if(a)if(i&&this.activeSessionId){if(a.classList.add("visible"),this.loadFileBrowser(this.activeSessionId),!this.fileBrowserDragListeners){const r=a.querySelector(".file-browser-header");if(r){const c=()=>{if(!a.style.left){const d=a.getBoundingClientRect();a.style.left=`${d.left}px`,a.style.top=`${d.top}px`,a.style.right="auto"}};r.addEventListener("mousedown",c),r.addEventListener("touchstart",c,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(a,r),this.fileBrowserDragListeners._onFirstDrag=c}}}else a.classList.remove("visible")}closeMonitor(){const e=document.getElementById("monitorPanel");e&&(e.classList.remove("open"),e.style.display="none");const t=this.loadAppSettingsFromStorage();t.showMonitor=!1,this.saveAppSettingsToStorage(t)}closeSubagentsPanel(){const e=document.getElementById("subagentsPanel");e&&(e.classList.remove("open"),e.classList.add("hidden")),this.subagentPanelVisible=!1;const t=this.loadAppSettingsFromStorage();t.showSubagents=!1,this.saveAppSettingsToStorage(t)}async clearAllSubagents(){const e=this.subagents.size;if(e===0){this.showToast("No subagents to clear","info");return}if(confirm(`Clear all ${e} tracked subagent(s)? This removes them from the UI but does not affect running processes.`))try{const s=await(await fetch("/api/subagents",{method:"DELETE"})).json();s.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${s.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+s.error,"error")}catch{this.showToast("Failed to clear subagents","error")}}toggleSubagentsPanel(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsToggleBtn");if(e){if(e.classList.contains("hidden")){e.classList.remove("hidden");const s=this.loadAppSettingsFromStorage();s.showSubagents=!0,this.saveAppSettingsToStorage(s)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"▼":"▲"),this.subagentPanelVisible&&this.renderSubagentPanel()}}async loadAppSettingsFromServer(e=null){try{const t=e?await e:await fetch("/api/settings").then(s=>s.ok?s.json():null);if(t){const{notificationPreferences:s,voiceSettings:n,...i}=t,o=new Set(["showFontControls","showSystemStats","showTokenCount","showCost","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","localEchoEnabled"]),l=this.loadAppSettingsFromStorage(),a={...l};for(const[r,c]of Object.entries(i))o.has(r)&&r in l||(a[r]=c);if(this.saveAppSettingsToStorage(a),s&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=s,this.notificationManager.savePreferences())),n){const r=localStorage.getItem("codeman-voice-settings");(!r||!JSON.parse(r).apiKey)&&VoiceInput._saveDeepgramConfig(n)}return a}}catch{}return this.loadAppSettingsFromStorage()}async loadSubagentWindowStates(){let e=null;try{const t=await fetch("/api/subagent-window-states");t.ok&&(e=await t.json(),localStorage.setItem("codeman-subagent-window-states",JSON.stringify(e)))}catch{}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch{}return e||{minimized:{},open:[]}}async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch{}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{}}async loadSubagentParentMap(){let e=null;try{const t=await fetch("/api/subagent-parents");t.ok&&(e=await t.json(),localStorage.setItem("codeman-subagent-parents",JSON.stringify(e)))}catch{}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch{}if(e&&typeof e=="object")for(const[t,s]of Object.entries(e))this.sessions.has(s)&&this.subagents.has(t)&&this.subagentParentMap.set(t,s)}getAgentParentSessionId(e){return this.subagentParentMap.get(e)||null}setAgentParentSessionId(e,t){if(!e||!t||this.subagentParentMap.has(e))return;this.subagentParentMap.set(e,t),this.saveSubagentParentMap();const s=this.subagents.get(e);if(s){s.parentSessionId=t;const n=this.sessions.get(t);n&&(s.parentSessionName=this.getSessionName(n)),this.subagents.set(e,s)}}showHelp(){const e=document.getElementById("helpModal");e.classList.add("active"),this.activeFocusTrap=new FocusTrap(e),this.activeFocusTrap.activate()}closeHelp(){document.getElementById("helpModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)}closeAllPanels(){this.closeSessionOptions(),this.closeAppSettings(),this.cancelCloseSession(),this.closeTokenStats(),document.getElementById("monitorPanel").classList.remove("open");const e=document.getElementById("subagentsPanel");e&&e.classList.remove("open"),this.subagentPanelVisible=!1}async openTokenStats(){try{const t=await(await fetch("/api/token-stats")).json();t.success?(this.renderTokenStats(t),document.getElementById("tokenStatsModal").classList.add("active")):this.showToast("Failed to load token stats","error")}catch{this.showToast("Failed to load token stats","error")}}renderTokenStats(e){const{daily:t,totals:s}=e,n=new Date().toISOString().split("T")[0],i=t.find(y=>y.date===n)||{inputTokens:0,outputTokens:0,estimatedCost:0},o=new Date;o.setDate(o.getDate()-7);const l=t.filter(y=>new Date(y.date)>=o),a=l.reduce((y,v)=>y+v.inputTokens,0),r=l.reduce((y,v)=>y+v.outputTokens,0),c=this.estimateCost(a,r),d=s.totalInputTokens,u=s.totalOutputTokens,h=this.estimateCost(d,u),m=document.getElementById("statsSummary");m.innerHTML=`
|
|
86
86
|
<div class="stat-card">
|
|
87
87
|
<span class="stat-card-label">Today</span>
|
|
88
88
|
<span class="stat-card-value">${this.formatTokens(i.inputTokens+i.outputTokens)}</span>
|
|
@@ -90,7 +90,7 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
90
90
|
</div>
|
|
91
91
|
<div class="stat-card">
|
|
92
92
|
<span class="stat-card-label">7 Days</span>
|
|
93
|
-
<span class="stat-card-value">${this.formatTokens(
|
|
93
|
+
<span class="stat-card-value">${this.formatTokens(a+r)}</span>
|
|
94
94
|
<span class="stat-card-cost">~$${c.toFixed(2)}</span>
|
|
95
95
|
</div>
|
|
96
96
|
<div class="stat-card">
|
|
@@ -98,22 +98,22 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
98
98
|
<span class="stat-card-value">${this.formatTokens(d+u)}</span>
|
|
99
99
|
<span class="stat-card-cost">~$${h.toFixed(2)}</span>
|
|
100
100
|
</div>
|
|
101
|
-
`;const p=document.getElementById("statsChart"),g=document.getElementById("statsChartDays"),f=[];for(let
|
|
101
|
+
`;const p=document.getElementById("statsChart"),g=document.getElementById("statsChartDays"),f=[];for(let y=6;y>=0;y--){const v=new Date;v.setDate(v.getDate()-y);const E=v.toISOString().split("T")[0],T=t.find(C=>C.date===E);f.push({date:E,dayName:v.toLocaleDateString("en-US",{weekday:"short"}),tokens:T?T.inputTokens+T.outputTokens:0,cost:T?T.estimatedCost:0})}const S=Math.max(...f.map(y=>y.tokens),1);p.innerHTML=f.map(y=>{const v=Math.max(y.tokens/S*100,3),E=`${y.dayName}: ${this.formatTokens(y.tokens)} (~$${y.cost.toFixed(2)})`;return`<div class="bar" style="height: ${v}%" data-tooltip="${E}"></div>`}).join(""),g.innerHTML=f.map(y=>`<span>${y.dayName}</span>`).join("");const w=document.getElementById("statsTable"),b=t.slice(0,14);b.length===0?w.innerHTML='<div class="stats-no-data">No usage data recorded yet</div>':w.innerHTML=`
|
|
102
102
|
<div class="stats-table-header">
|
|
103
103
|
<span>Date</span>
|
|
104
104
|
<span>Input</span>
|
|
105
105
|
<span>Output</span>
|
|
106
106
|
<span>Cost</span>
|
|
107
107
|
</div>
|
|
108
|
-
${b.map(
|
|
108
|
+
${b.map(y=>`
|
|
109
109
|
<div class="stats-table-row">
|
|
110
|
-
<span class="cell cell-date">${new Date(
|
|
111
|
-
<span class="cell">${this.formatTokens(
|
|
112
|
-
<span class="cell">${this.formatTokens(
|
|
113
|
-
<span class="cell cell-cost">$${
|
|
110
|
+
<span class="cell cell-date">${new Date(y.date+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric"})}</span>
|
|
111
|
+
<span class="cell">${this.formatTokens(y.inputTokens)}</span>
|
|
112
|
+
<span class="cell">${this.formatTokens(y.outputTokens)}</span>
|
|
113
|
+
<span class="cell cell-cost">$${y.estimatedCost.toFixed(2)}</span>
|
|
114
114
|
</div>
|
|
115
115
|
`).join("")}
|
|
116
|
-
`}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
|
|
116
|
+
`}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 f=e.getBoundingClientRect();p=Math.max(0,Math.min(window.innerWidth-f.width,p)),g=Math.max(0,Math.min(window.innerHeight-f.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 f=e.getBoundingClientRect();p=Math.max(0,Math.min(window.innerWidth-f.width,p)),g=Math.max(0,Math.min(window.innerHeight-f.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`
|
|
117
117
|
<div class="task-item">
|
|
118
118
|
<span class="task-status-icon ${r.status}">${d}</span>
|
|
119
119
|
<div class="task-info">
|
|
@@ -125,7 +125,7 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
125
125
|
</div>
|
|
126
126
|
</div>
|
|
127
127
|
${h}
|
|
128
|
-
`},l=this.flattenTaskTree(e.taskTree);let
|
|
128
|
+
`},l=this.flattenTaskTree(e.taskTree);let a='<div class="task-tree">';for(const r of e.taskTree)a+=`<div class="task-node">${o(r,l)}</div>`;a+="</div>",t.innerHTML=a}flattenTaskTree(e,t=[]){for(const s of e)t.push(s);return t}updateRalphState(e,t){const n={...this.ralphStates.get(e)||{loop:null,todos:[]},...t};this.ralphStates.set(e,n),e===this.activeSessionId&&this.renderRalphStatePanel()}toggleRalphStatePanel(){const e=this.terminal?.element?.querySelector(".xterm-viewport"),t=e?.scrollTop;this.ralphStatePanelCollapsed=!this.ralphStatePanelCollapsed,this.renderRalphStatePanel(),requestAnimationFrame(()=>{e&&t!==void 0&&(e.scrollTop=t),this.terminal&&this.fitAddon&&this.fitAddon.fit()})}async closeRalphTracker(){this.activeSessionId&&(this.ralphClosedSessions.add(this.activeSessionId),await this._apiPost(`/api/sessions/${this.activeSessionId}/ralph-config`,{enabled:!1}),this.ralphStates.delete(this.activeSessionId),this.renderRalphStatePanel())}toggleRalphMenu(){const e=document.getElementById("ralphDropdown");e&&e.classList.toggle("show")}closeRalphMenu(){const e=document.getElementById("ralphDropdown");e&&e.classList.remove("show")}async resetCircuitBreaker(){if(this.activeSessionId)try{(await(await this._apiPost(`/api/sessions/${this.activeSessionId}/ralph-circuit-breaker/reset`,{}))?.json())?.success&&this.notificationManager?.notify({urgency:"info",category:"circuit-breaker",title:"Reset",message:"Circuit breaker reset to CLOSED"})}catch{}}async showFixPlan(){if(this.activeSessionId)try{const t=await(await fetch(`/api/sessions/${this.activeSessionId}/fix-plan`)).json();if(!t.success){this.notificationManager?.notify({urgency:"error",category:"fix-plan",title:"Error",message:t.error||"Failed to generate fix plan"});return}this.showFixPlanModal(t.data.content,t.data.todoCount)}catch{}}showFixPlanModal(e,t){let s=document.getElementById("fixPlanModal");s||(s=document.createElement("div"),s.id="fixPlanModal",s.className="modal",s.innerHTML=`
|
|
129
129
|
<div class="modal-content fix-plan-modal">
|
|
130
130
|
<div class="modal-header">
|
|
131
131
|
<h3>@fix_plan.md</h3>
|
|
@@ -141,19 +141,19 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
141
141
|
<button class="btn btn-secondary" onclick="app.closeFixPlanModal()">Close</button>
|
|
142
142
|
</div>
|
|
143
143
|
</div>
|
|
144
|
-
`,document.body.appendChild(
|
|
144
|
+
`,document.body.appendChild(s)),document.getElementById("fixPlanContent").value=e,document.getElementById("fixPlanStats").textContent=`${t} tasks`,s.classList.add("show")}closeFixPlanModal(){const e=document.getElementById("fixPlanModal");e&&e.classList.remove("show")}async copyFixPlan(){const e=document.getElementById("fixPlanContent")?.value;e&&(await navigator.clipboard.writeText(e),this.notificationManager?.notify({urgency:"info",category:"fix-plan",title:"Copied",message:"Fix plan copied to clipboard"}))}async writeFixPlanToFile(){if(this.activeSessionId)try{const t=await(await fetch(`/api/sessions/${this.activeSessionId}/fix-plan/write`,{method:"POST"})).json();t.success?(this.notificationManager?.notify({urgency:"info",category:"fix-plan",title:"Written",message:`@fix_plan.md written to ${t.data.filePath}`}),this.closeFixPlanModal()):this.notificationManager?.notify({urgency:"error",category:"fix-plan",title:"Error",message:t.error||"Failed to write file"})}catch{}}async importFixPlanFromFile(){if(this.activeSessionId)try{const t=await(await fetch(`/api/sessions/${this.activeSessionId}/fix-plan/read`,{method:"POST"})).json();t.success?(this.notificationManager?.notify({urgency:"info",category:"fix-plan",title:"Imported",message:`Imported ${t.data.importedCount} tasks from @fix_plan.md`}),this.updateRalphState(this.activeSessionId,{todos:t.data.todos})):this.notificationManager?.notify({urgency:"warning",category:"fix-plan",title:"Not Found",message:t.error||"@fix_plan.md not found"})}catch{}}toggleRalphDetach(){const e=this.$("ralphStatePanel"),t=this.$("ralphDetachBtn");e&&(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"),this.ralphStatePanelCollapsed=!1,e.classList.remove("collapsed"),t&&(t.innerHTML="⊞",t.title="Attach panel"),this.setupRalphDrag()),this.renderRalphStatePanel())}setupRalphDrag(){const e=this.$("ralphStatePanel"),t=this.$("ralphSummary");if(!e||!t)return;let s=!1,n,i,o,l;const a=d=>{if(d.target.closest("button")||d.target.closest(".ralph-toggle")||!e.classList.contains("detached"))return;s=!0,n=d.clientX,i=d.clientY;const u=e.getBoundingClientRect();o=u.left,l=u.top,document.addEventListener("mousemove",r),document.addEventListener("mouseup",c),d.preventDefault()},r=d=>{if(!s)return;const u=d.clientX-n,h=d.clientY-i;let m=o+u,p=l+h;const g=e.getBoundingClientRect();m=Math.max(0,Math.min(window.innerWidth-g.width,m)),p=Math.max(0,Math.min(window.innerHeight-g.height,p)),e.style.left=m+"px",e.style.top=p+"px"},c=()=>{s=!1,document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",c)};t.removeEventListener("mousedown",t._ralphDragHandler),t._ralphDragHandler=a,t.addEventListener("mousedown",a)}renderRalphStatePanel(){this.renderRalphStatePanelTimeout&&clearTimeout(this.renderRalphStatePanelTimeout),this.renderRalphStatePanelTimeout=setTimeout(()=>{this._renderRalphStatePanelImmediate()},50)}_renderRalphStatePanelImmediate(){const e=this.$("ralphStatePanel"),t=this.$("ralphToggle");if(!e)return;if(this.ralphClosedSessions.has(this.activeSessionId)){e.style.display="none";return}const s=this.ralphStates.get(this.activeSessionId),n=s?.loop?.enabled===!0,i=s?.loop?.active||s?.loop?.completionPhrase,o=s?.todos?.length>0,l=s?.circuitBreaker&&s.circuitBreaker.state!=="CLOSED",a=s?.statusBlock!==void 0;if(!n&&!i&&!o&&!l&&!a){e.style.display="none";return}e.style.display="";const r=s?.todos||[],c=r.filter(h=>h.status==="completed").length,d=r.length,u=d>0?Math.round(c/d*100):0;this.updateRalphRing(u),this.updateRalphStatus(s?.loop,c,d),this.updateRalphStats(s?.loop,c,d),this.updateCircuitBreakerBadge(s?.circuitBreaker),this.ralphStatePanelCollapsed?(e.classList.add("collapsed"),t&&(t.innerHTML="▼")):(e.classList.remove("collapsed"),t&&(t.innerHTML="▲"),this.updateRalphExpandedView(s))}updateRalphRing(e){const t=Math.max(0,Math.min(100,Number(e)||0)),s=this.$("ralphRingMiniProgress"),n=this.$("ralphRingMiniText");if(s){const l=100-t;s.style.strokeDashoffset=l}n&&(n.textContent=`${t}%`);const i=this.$("ralphRingProgress"),o=this.$("ralphRingPercent");if(i){const l=264-264*t/100;i.style.strokeDashoffset=l}o&&(o.textContent=`${t}%`)}updateRalphStatus(e,t=0,s=0){const n=this.$("ralphStatusBadge"),i=n?.querySelector(".ralph-status-text");!n||!i||(n.classList.remove("active","completed","tracking"),e?.active?(n.classList.add("active"),i.textContent="Running"):s>0&&t===s?(n.classList.add("completed"),i.textContent="Complete"):e?.enabled||s>0?(n.classList.add("tracking"),i.textContent="Tracking"):i.textContent="Idle")}updateCircuitBreakerBadge(e){let t=this.$("ralphCircuitBreakerBadge");if(!t){const s=this.$("ralphSummary");if(!s)return;if(t=s.querySelector(".ralph-circuit-breaker"),!t){t=document.createElement("div"),t.id="ralphCircuitBreakerBadge",t.className="ralph-circuit-breaker";const n=this.$("ralphStatusBadge");n&&n.nextSibling?n.parentNode.insertBefore(t,n.nextSibling):s.appendChild(t)}}if(!e||e.state==="CLOSED"){t.style.display="none";return}t.style.display="",t.classList.remove("half-open","open"),e.state==="HALF_OPEN"?(t.classList.add("half-open"),t.innerHTML='<span class="cb-icon">\u26A0</span><span class="cb-text">Warning</span>',t.title=e.reason||"Circuit breaker warning"):e.state==="OPEN"&&(t.classList.add("open"),t.innerHTML='<span class="cb-icon">\u{1F6D1}</span><span class="cb-text">Stuck</span>',t.title=e.reason||"Loop appears stuck"),t.onclick=()=>this.resetCircuitBreaker()}updateRalphStats(e,t,s){const n=this.$("ralphStatTime");if(n)if(e?.elapsedHours!==null&&e?.elapsedHours!==void 0)n.textContent=this.formatRalphTime(e.elapsedHours);else if(e?.startedAt){const l=(Date.now()-e.startedAt)/36e5;n.textContent=this.formatRalphTime(l)}else n.textContent="0m";const i=this.$("ralphStatCycles");i&&(e?.maxIterations?i.textContent=`${e.cycleCount||0}/${e.maxIterations}`:i.textContent=String(e?.cycleCount||0));const o=this.$("ralphStatTasks");o&&(o.textContent=`${t}/${s}`)}formatRalphTime(e){if(e<.0167)return"0m";if(e<1)return`${Math.round(e*60)}m`;const t=Math.floor(e),s=Math.round((e-t)*60);return s===0?`${t}h`:`${t}h ${s}m`}updateRalphExpandedView(e){const t=this.$("ralphPhrase");t&&(t.textContent=e?.loop?.completionPhrase||"--");const s=this.$("ralphElapsed");if(s)if(e?.loop?.elapsedHours!==null&&e?.loop?.elapsedHours!==void 0)s.textContent=this.formatRalphTime(e.loop.elapsedHours);else if(e?.loop?.startedAt){const a=(Date.now()-e.loop.startedAt)/36e5;s.textContent=this.formatRalphTime(a)}else s.textContent="0m";const n=this.$("ralphIterations");n&&(e?.loop?.maxIterations?n.textContent=`${e.loop.cycleCount||0} / ${e.loop.maxIterations}`:n.textContent=String(e?.loop?.cycleCount||0));const i=e?.todos||[],o=i.filter(a=>a.status==="completed").length,l=this.$("ralphTasksCount");l&&(l.textContent=`${o}/${i.length}`),e?.loop?.planVersion?this.updatePlanVersionDisplay(e.loop.planVersion,e.loop.planHistoryLength||1):this.updatePlanVersionDisplay(null,0),this.renderRalphTasks(i),this.renderRalphStatusBlock(e?.statusBlock)}renderRalphStatusBlock(e){let t=this.$("ralphStatusBlockDisplay");const s=this.$("ralphExpandedContent");if(!e){t&&t.remove();return}if(!t&&s&&(t=document.createElement("div"),t.id="ralphStatusBlockDisplay",t.className="ralph-status-block",s.insertBefore(t,s.firstChild)),!t)return;const n=e.status==="IN_PROGRESS"?"in-progress":e.status==="COMPLETE"?"complete":e.status==="BLOCKED"?"blocked":"",i=e.testsStatus==="PASSING"?"\u2705":e.testsStatus==="FAILING"?"\u274C":"\u23F8",o=e.workType==="IMPLEMENTATION"?"\u{1F527}":e.workType==="TESTING"?"\u{1F9EA}":e.workType==="DOCUMENTATION"?"\u{1F4DD}":e.workType==="REFACTORING"?"\u267B\uFE0F":"\u{1F4CB}";let l=`
|
|
145
145
|
<div class="ralph-status-block-header">
|
|
146
146
|
<span>RALPH_STATUS</span>
|
|
147
|
-
<span class="ralph-status-block-status ${
|
|
147
|
+
<span class="ralph-status-block-status ${n}">${escapeHtml(e.status)}</span>
|
|
148
148
|
${e.exitSignal?'<span style="color: #4caf50;">\u{1F6AA} EXIT</span>':""}
|
|
149
149
|
</div>
|
|
150
150
|
<div class="ralph-status-block-stats">
|
|
151
|
-
<span>${
|
|
151
|
+
<span>${o} ${escapeHtml(e.workType)}</span>
|
|
152
152
|
<span>\u{1F4C1} ${e.filesModified} files</span>
|
|
153
153
|
<span>\u2713 ${escapeHtml(String(e.tasksCompletedThisLoop))} tasks</span>
|
|
154
154
|
<span>${i} Tests: ${escapeHtml(e.testsStatus)}</span>
|
|
155
155
|
</div>
|
|
156
|
-
`;e.recommendation&&(l+=`<div class="ralph-status-block-recommendation">${escapeHtml(e.recommendation)}</div>`),t.innerHTML=l}renderRalphTasks(e){const t=this.$("ralphTasksGrid");if(!t)return;if(e.length===0){(t.children.length!==1||!t.querySelector(".ralph-state-empty"))&&(t.innerHTML='<div class="ralph-state-empty">No tasks detected</div>');return}const
|
|
156
|
+
`;e.recommendation&&(l+=`<div class="ralph-status-block-recommendation">${escapeHtml(e.recommendation)}</div>`),t.innerHTML=l}renderRalphTasks(e){const t=this.$("ralphTasksGrid");if(!t)return;if(e.length===0){(t.children.length!==1||!t.querySelector(".ralph-state-empty"))&&(t.innerHTML='<div class="ralph-state-empty">No tasks detected</div>');return}const s={P0:0,P1:1,P2:2,null:3},n={in_progress:0,pending:1,completed:2},i=[...e].sort((l,a)=>{const r=s[l.priority]??3,c=s[a.priority]??3;return r!==c?r-c:(n[l.status]||1)-(n[a.status]||1)}),o=document.createDocumentFragment();i.forEach((l,a)=>{const r=this.createRalphTaskCard(l,a);o.appendChild(r)}),t.innerHTML="",t.appendChild(o)}createRalphTaskCard(e,t){const s=document.createElement("div"),n=`task-${e.status.replace("_","-")}`,i=e.priority?`task-priority-${e.priority.toLowerCase()}`:"";s.className=`ralph-task-card ${n} ${i}`.trim(),s.dataset.taskId=e.id||t;const o=document.createElement("span");if(o.className="ralph-task-icon",o.textContent=this.getRalphTaskIcon(e.status),s.appendChild(o),e.priority){const r=document.createElement("span");r.className=`ralph-task-priority priority-${e.priority.toLowerCase()}`,r.textContent=e.priority,s.appendChild(r)}const l=document.createElement("span");if(l.className="ralph-task-content",l.textContent=e.content,s.appendChild(l),e.attempts&&e.attempts>0){const r=document.createElement("span");r.className="ralph-task-attempts",e.lastError&&(r.classList.add("has-errors"),r.title=`Last error: ${e.lastError}`),r.textContent=`#${e.attempts}`,s.appendChild(r)}if(e.verificationCriteria){const r=document.createElement("span");r.className="ralph-task-verify-badge",r.title=`Verify: ${e.verificationCriteria}`,r.textContent="\u2713",s.appendChild(r)}if(e.dependencies&&e.dependencies.length>0){const r=document.createElement("span");r.className="ralph-task-deps-indicator",r.title=`Depends on: ${e.dependencies.join(", ")}`,r.textContent=`\u2197${e.dependencies.length}`,s.appendChild(r)}const a=document.createElement("div");if(a.className="ralph-task-actions",e.status!=="completed"){const r=document.createElement("button");r.className="ralph-task-action-btn",r.textContent="\u2713",r.title="Mark complete",r.onclick=c=>{c.stopPropagation(),this.updateRalphTaskStatus(e.id,"completed")},a.appendChild(r)}if(e.status==="completed"){const r=document.createElement("button");r.className="ralph-task-action-btn",r.textContent="\u21BA",r.title="Reopen",r.onclick=c=>{c.stopPropagation(),this.updateRalphTaskStatus(e.id,"pending")},a.appendChild(r)}if(e.lastError){const r=document.createElement("button");r.className="ralph-task-action-btn",r.textContent="\u21BB",r.title="Retry (clear error)",r.onclick=c=>{c.stopPropagation(),this.retryRalphTask(e.id)},a.appendChild(r)}return s.appendChild(a),s}async updateRalphTaskStatus(e,t){if(this.activeSessionId)try{const s=await fetch(`/api/sessions/${this.activeSessionId}/plan/task/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t})});if(!s.ok){const n=await s.json();throw new Error(n.error||"Failed to update task")}this.showToast(`Task ${t==="completed"?"completed":"reopened"}`,"success")}catch(s){this.showToast("Failed to update task: "+s.message,"error")}}async retryRalphTask(e){if(this.activeSessionId)try{const t=await fetch(`/api/sessions/${this.activeSessionId}/plan/task/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({attempts:0,lastError:null,status:"pending"})});if(!t.ok){const s=await t.json();throw new Error(s.error||"Failed to retry task")}this.showToast("Task reset for retry","success")}catch(t){this.showToast("Failed to retry task: "+t.message,"error")}}getRalphTaskIcon(e){switch(e){case"completed":return"\u2713";case"in_progress":return"\u25D0";default:return"\u25CB"}}getTodoIcon(e){return this.getRalphTaskIcon(e)}updatePlanVersionDisplay(e,t){const s=this.$("ralphVersionRow"),n=this.$("ralphPlanVersion"),i=this.$("ralphRollbackBtn");s&&(e&&e>0?(s.style.display="",n&&(n.textContent=`v${e}`),i&&(i.style.display=t>1?"":"none")):s.style.display="none")}async showPlanHistory(){if(this.activeSessionId)try{const t=await(await fetch(`/api/sessions/${this.activeSessionId}/plan/history`)).json();if(t.error){this.showToast("Failed to load plan history: "+t.error,"error");return}const s=t.history||[];if(s.length===0){this.showToast("No plan history available","info");return}this.showPlanHistoryModal(s,t.currentVersion)}catch(e){this.showToast("Failed to load plan history: "+e.message,"error")}}showPlanHistoryModal(e,t){const s=document.getElementById("planHistoryModal");s&&s.remove();const n=document.createElement("div");n.id="planHistoryModal",n.className="modal active",n.innerHTML=`
|
|
157
157
|
<div class="modal-backdrop" onclick="app.closePlanHistoryModal()"></div>
|
|
158
158
|
<div class="modal-content modal-sm">
|
|
159
159
|
<div class="modal-header">
|
|
@@ -181,51 +181,51 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
181
181
|
<button class="btn-toolbar" onclick="app.closePlanHistoryModal()">Close</button>
|
|
182
182
|
</div>
|
|
183
183
|
</div>
|
|
184
|
-
`,document.body.appendChild(
|
|
185
|
-
<div class="subagent-item ${
|
|
186
|
-
onclick="app.selectSubagent('${escapeHtml(
|
|
187
|
-
ondblclick="app.openSubagentWindow('${escapeHtml(
|
|
184
|
+
`,document.body.appendChild(n)}closePlanHistoryModal(){const e=document.getElementById("planHistoryModal");e&&e.remove()}async rollbackToPlanVersion(e){if(this.activeSessionId&&confirm(`Rollback to plan version ${e}? Current changes will be preserved in history.`))try{const s=await(await fetch(`/api/sessions/${this.activeSessionId}/plan/rollback/${e}`,{method:"POST"})).json();if(s.error){this.showToast("Failed to rollback: "+s.error,"error");return}this.showToast(`Rolled back to plan v${e}`,"success"),this.closePlanHistoryModal(),this.renderRalphStatePanel()}catch(t){this.showToast("Failed to rollback: "+t.message,"error")}}formatRelativeTime(e){if(!e)return"";const s=Date.now()-e,n=Math.floor(s/6e4),i=Math.floor(s/36e5),o=Math.floor(s/864e5);return n<1?"just now":n<60?`${n}m ago`:i<24?`${i}h ago`:`${o}d ago`}toggleSubagentPanel(){this.toggleSubagentsPanel()}updateSubagentBadge(){const e=this.$("subagentCountBadge"),t=Array.from(this.subagents.values()).filter(s=>s.status==="active"||s.status==="idle").length;e&&(e.textContent=t>0?t:"")}renderSubagentPanel(){this._subagentPanelRenderTimeout&&clearTimeout(this._subagentPanelRenderTimeout),this._subagentPanelRenderTimeout=setTimeout(()=>{scheduleBackground(()=>this._renderSubagentPanelImmediate())},150)}_renderSubagentPanelImmediate(){const e=this.$("subagentList");if(!e||(this.updateSubagentBadge(),this.renderMonitorSubagents(),!this.subagentPanelVisible))return;if(this.subagents.size===0){e.innerHTML='<div class="subagent-empty">No background agents detected</div>';return}const t=[],s=Array.from(this.subagents.values()).sort((n,i)=>n.status==="active"&&i.status!=="active"?-1:i.status==="active"&&n.status!=="active"?1:(i.lastActivityAt||0)-(n.lastActivityAt||0));for(const n of s){const i=this.activeSubagentId===n.agentId,o=n.status==="active"?"active":n.status==="idle"?"idle":"completed",l=this.subagentActivity.get(n.agentId)||[],a=l[l.length-1],r=a?.type==="tool"?a.tool:null,c=this.subagentWindows.has(n.agentId),d=n.status==="active"||n.status==="idle",u=n.modelShort?`<span class="subagent-model-badge ${escapeHtml(n.modelShort)}">${escapeHtml(n.modelShort)}</span>`:"",h=this.getTeammateInfo(n),m=h?h.name:n.description||n.agentId.substring(0,7),p=this.getTeammateBadgeHtml(n),g=h?`<span class="subagent-icon teammate-dot teammate-color-${h.color}">\u25CF</span>`:'<span class="subagent-icon">\u{1F916}</span>';t.push(`
|
|
185
|
+
<div class="subagent-item ${o} ${i?"selected":""}${h?" is-teammate":""}"
|
|
186
|
+
onclick="app.selectSubagent('${escapeHtml(n.agentId)}')"
|
|
187
|
+
ondblclick="app.openSubagentWindow('${escapeHtml(n.agentId)}')"
|
|
188
188
|
title="Double-click to open tracking window">
|
|
189
189
|
<div class="subagent-header">
|
|
190
190
|
${g}
|
|
191
|
-
<span class="subagent-id" title="${escapeHtml(
|
|
191
|
+
<span class="subagent-id" title="${escapeHtml(n.description||n.agentId)}">${escapeHtml(m.length>40?m.substring(0,40)+"...":m)}</span>
|
|
192
192
|
${p}
|
|
193
193
|
${u}
|
|
194
|
-
<span class="subagent-status ${
|
|
195
|
-
${d?`<button class="subagent-kill-btn" onclick="event.stopPropagation(); app.killSubagent('${escapeHtml(
|
|
196
|
-
<button class="subagent-window-btn" onclick="event.stopPropagation(); app.${c?"closeSubagentWindow":"openSubagentWindow"}('${escapeHtml(
|
|
194
|
+
<span class="subagent-status ${o}">${n.status}</span>
|
|
195
|
+
${d?`<button class="subagent-kill-btn" onclick="event.stopPropagation(); app.killSubagent('${escapeHtml(n.agentId)}')" title="Kill agent">✕</button>`:""}
|
|
196
|
+
<button class="subagent-window-btn" onclick="event.stopPropagation(); app.${c?"closeSubagentWindow":"openSubagentWindow"}('${escapeHtml(n.agentId)}')" title="${c?"Close window":"Open in window"}">
|
|
197
197
|
${c?"\u2715":"\u29C9"}
|
|
198
198
|
</button>
|
|
199
199
|
</div>
|
|
200
200
|
<div class="subagent-meta">
|
|
201
|
-
<span class="subagent-tools">${
|
|
201
|
+
<span class="subagent-tools">${n.toolCallCount} tools</span>
|
|
202
202
|
${r?`<span class="subagent-last-tool">${this.getToolIcon(r)} ${r}</span>`:""}
|
|
203
203
|
</div>
|
|
204
204
|
</div>
|
|
205
|
-
`)}e.innerHTML=t.join("")}selectSubagent(e){this.activeSubagentId=e,this.renderSubagentPanel(),this.renderSubagentDetail()}renderSubagentDetail(){const e=this.$("subagentDetail");if(!e)return;if(!this.activeSubagentId){e.innerHTML='<div class="subagent-empty">Select an agent to view details</div>';return}const t=this.subagents.get(this.activeSubagentId),
|
|
205
|
+
`)}e.innerHTML=t.join("")}selectSubagent(e){this.activeSubagentId=e,this.renderSubagentPanel(),this.renderSubagentDetail()}renderSubagentDetail(){const e=this.$("subagentDetail");if(!e)return;if(!this.activeSubagentId){e.innerHTML='<div class="subagent-empty">Select an agent to view details</div>';return}const t=this.subagents.get(this.activeSubagentId),s=this.subagentActivity.get(this.activeSubagentId)||[];if(!t){e.innerHTML='<div class="subagent-empty">Agent not found</div>';return}const n=s.slice(-30).map(a=>{const r=new Date(a.timestamp).toLocaleTimeString("en-US",{hour12:!1});if(a.type==="tool"){const c=this.getToolDetailExpanded(a.tool,a.input,a.fullInput,a.toolUseId);return`<div class="subagent-activity tool" data-tool-use-id="${a.toolUseId||""}">
|
|
206
206
|
<span class="time">${r}</span>
|
|
207
|
-
<span class="icon">${this.getToolIcon(
|
|
208
|
-
<span class="name">${
|
|
207
|
+
<span class="icon">${this.getToolIcon(a.tool)}</span>
|
|
208
|
+
<span class="name">${a.tool}</span>
|
|
209
209
|
<span class="detail">${c.primary}</span>
|
|
210
|
-
${c.hasMore?`<button class="tool-expand-btn" onclick="app.toggleToolParams('${escapeHtml(
|
|
211
|
-
${c.hasMore?`<div class="tool-params-expanded" id="tool-params-${
|
|
212
|
-
</div>`}else if(
|
|
210
|
+
${c.hasMore?`<button class="tool-expand-btn" onclick="app.toggleToolParams('${escapeHtml(a.toolUseId)}')">\u25B6</button>`:""}
|
|
211
|
+
${c.hasMore?`<div class="tool-params-expanded" id="tool-params-${a.toolUseId}" style="display:none;"><pre>${escapeHtml(JSON.stringify(a.fullInput||a.input,null,2))}</pre></div>`:""}
|
|
212
|
+
</div>`}else if(a.type==="tool_result"){const c=a.isError?"\u274C":"\u{1F4C4}",d=a.isError?"error":"",u=a.contentLength>500?` (${this.formatBytes(a.contentLength)})`:"",h=a.preview.length>80?a.preview.substring(0,80)+"...":a.preview;return`<div class="subagent-activity tool-result ${d}">
|
|
213
213
|
<span class="time">${r}</span>
|
|
214
214
|
<span class="icon">${c}</span>
|
|
215
|
-
<span class="name">${
|
|
215
|
+
<span class="name">${a.tool||"result"}</span>
|
|
216
216
|
<span class="detail">${escapeHtml(h)}${u}</span>
|
|
217
|
-
</div>`}else if(
|
|
217
|
+
</div>`}else if(a.type==="progress"){const c=a.hookEvent||a.hookName,d=c?"\u{1FA9D}":a.progressType==="query_update"?"\u27F3":"\u2713",u=c?" hook":"",h=c?a.hookName||a.hookEvent:a.query||a.progressType;return`<div class="subagent-activity progress${u}">
|
|
218
218
|
<span class="time">${r}</span>
|
|
219
219
|
<span class="icon">${d}</span>
|
|
220
220
|
<span class="detail">${h}</span>
|
|
221
|
-
</div>`}else if(
|
|
221
|
+
</div>`}else if(a.type==="message"){const c=a.text.length>100?a.text.substring(0,100)+"...":a.text;return`<div class="subagent-activity message">
|
|
222
222
|
<span class="time">${r}</span>
|
|
223
223
|
<span class="icon">\u{1F4AC}</span>
|
|
224
224
|
<span class="detail">${escapeHtml(c)}</span>
|
|
225
|
-
</div>`}return""}).join(""),i=t.description||`Agent ${t.agentId}`,
|
|
225
|
+
</div>`}return""}).join(""),i=t.description||`Agent ${t.agentId}`,o=t.modelShort?`<span class="subagent-model-badge ${escapeHtml(t.modelShort)}">${escapeHtml(t.modelShort)}</span>`:"",l=t.totalInputTokens||t.totalOutputTokens?`<span>Tokens: ${this.formatTokenCount(t.totalInputTokens||0)}\u2193 ${this.formatTokenCount(t.totalOutputTokens||0)}\u2191</span>`:"";e.innerHTML=`
|
|
226
226
|
<div class="subagent-detail-header">
|
|
227
227
|
<span class="subagent-id" title="${escapeHtml(t.description||t.agentId)}">${escapeHtml(i.length>60?i.substring(0,60)+"...":i)}</span>
|
|
228
|
-
${
|
|
228
|
+
${o}
|
|
229
229
|
<span class="subagent-status ${t.status}">${t.status}</span>
|
|
230
230
|
<button class="subagent-transcript-btn" onclick="app.viewSubagentTranscript('${escapeHtml(t.agentId)}')">
|
|
231
231
|
View Full Transcript
|
|
@@ -238,9 +238,9 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
238
238
|
${l}
|
|
239
239
|
</div>
|
|
240
240
|
<div class="subagent-activity-log">
|
|
241
|
-
${
|
|
241
|
+
${n||'<div class="subagent-empty">No activity yet</div>'}
|
|
242
242
|
</div>
|
|
243
|
-
`}toggleToolParams(e){const t=document.getElementById(`tool-params-${e}`);if(!t)return;const
|
|
243
|
+
`}toggleToolParams(e){const t=document.getElementById(`tool-params-${e}`);if(!t)return;const s=t.previousElementSibling;t.style.display==="none"?(t.style.display="block",s&&(s.textContent="\u25BC")):(t.style.display="none",s&&(s.textContent="\u25B6"))}formatTokenCount(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"k":e.toString()}formatBytes(e){return e>=1024*1024?(e/(1024*1024)).toFixed(1)+"MB":e>=1024?(e/1024).toFixed(1)+"KB":e+"B"}getToolIcon(e){return{WebSearch:"\u{1F50D}",WebFetch:"\u{1F310}",Read:"\u{1F4D6}",Write:"\u{1F4DD}",Edit:"\u270F\uFE0F",Bash:"\u{1F4BB}",Glob:"\u{1F4C1}",Grep:"\u{1F50E}",Task:"\u{1F916}"}[e]||"\u{1F527}"}getToolDetail(e,t){if(!t)return"";if(e==="WebSearch"&&t.query)return`"${t.query}"`;if(e==="WebFetch"&&t.url)return t.url;if(e==="Read"&&t.file_path||(e==="Write"||e==="Edit")&&t.file_path)return t.file_path;if(e==="Bash"&&t.command){const s=t.command;return s.length>40?s.substring(0,40)+"...":s}return e==="Glob"&&t.pattern||e==="Grep"&&t.pattern?t.pattern:""}getToolDetailExpanded(e,t,s,n){const i=this.getToolDetail(e,t),o=["query","url","file_path","command","pattern"],r=Object.keys(s||t||{}).filter(c=>!o.includes(c)).length>0||s&&JSON.stringify(s).length>100;return{primary:i,hasMore:r,fullInput:s||t}}async killSubagent(e){try{const s=await(await this._apiDelete(`/api/subagents/${e}`))?.json();if(s?.success){const n=this.subagents.get(e);n&&(n.status="completed",this.subagents.set(e,n)),this.renderSubagentPanel(),this.renderSubagentDetail(),this.updateSubagentWindows(),this.showToast(`Subagent ${e.substring(0,7)} killed`,"success")}else this.showToast(s.error||"Failed to kill subagent","error")}catch(t){this.showToast("Failed to kill subagent: "+t.message,"error")}}async viewSubagentTranscript(e){try{const s=await(await fetch(`/api/subagents/${e}/transcript?format=formatted`)).json();if(!s.success){alert("Failed to load transcript");return}const n=s.data.formatted.join(`
|
|
244
244
|
`);window.open("","_blank","width=800,height=600").document.write(`
|
|
245
245
|
<html>
|
|
246
246
|
<head>
|
|
@@ -251,30 +251,30 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
251
251
|
</style>
|
|
252
252
|
</head>
|
|
253
253
|
<body>
|
|
254
|
-
<h2>Subagent ${escapeHtml(e)} Transcript (${
|
|
255
|
-
<pre>${escapeHtml(
|
|
254
|
+
<h2>Subagent ${escapeHtml(e)} Transcript (${s.data.entryCount} entries)</h2>
|
|
255
|
+
<pre>${escapeHtml(n)}</pre>
|
|
256
256
|
</body>
|
|
257
257
|
</html>
|
|
258
|
-
`)}catch(t){alert("Failed to load transcript: "+t.message)}}findParentSessionForSubagent(e){if(this.subagentParentMap.has(e)){const
|
|
258
|
+
`)}catch(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=`
|
|
259
259
|
<span class="parent-label">from</span>
|
|
260
|
-
<span class="parent-name" onclick="app.selectSession('${escapeHtml(
|
|
261
|
-
`,
|
|
260
|
+
<span class="parent-name" onclick="app.selectSession('${escapeHtml(s)}')">${escapeHtml(i)}</span>
|
|
261
|
+
`,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 t=document.getElementById(`subagent-window-body-${e}`);if(!t)return;const s=this.subagentActivity.get(e)||[];if(s.length===0){t.innerHTML='<div class="subagent-empty">No activity yet</div>';return}const n=t.dataset.renderedCount?parseInt(t.dataset.renderedCount,10):0,i=100,o=s.slice(-i);if(n===0||n>o.length||t.children.length===0||t.children.length===1&&t.querySelector(".subagent-empty")){const l=o.map(a=>this._renderActivityItem(a)).join("");t.innerHTML=l,t.dataset.renderedCount=String(o.length)}else{const l=o.slice(n);if(l.length>0){const a=l.map(r=>this._renderActivityItem(r)).join("");for(t.insertAdjacentHTML("beforeend",a),t.dataset.renderedCount=String(o.length);t.children.length>i;)t.removeChild(t.firstChild)}}t.scrollTop=t.scrollHeight}_renderActivityItem(e){const t=new Date(e.timestamp).toLocaleTimeString("en-US",{hour12:!1});if(e.type==="tool")return`<div class="activity-line">
|
|
262
262
|
<span class="time">${t}</span>
|
|
263
263
|
<span class="tool-icon">${this.getToolIcon(e.tool)}</span>
|
|
264
264
|
<span class="tool-name">${e.tool}</span>
|
|
265
265
|
<span class="tool-detail">${escapeHtml(this.getToolDetail(e.tool,e.input))}</span>
|
|
266
|
-
</div>`;if(e.type==="tool_result"){const
|
|
266
|
+
</div>`;if(e.type==="tool_result"){const s=e.isError?"\u274C":"\u{1F4C4}",n=e.isError?" error":"",i=e.contentLength>500?` (${this.formatBytes(e.contentLength)})`:"",o=e.preview.length>60?e.preview.substring(0,60)+"...":e.preview;return`<div class="activity-line result-line${n}">
|
|
267
267
|
<span class="time">${t}</span>
|
|
268
|
-
<span class="tool-icon">${
|
|
268
|
+
<span class="tool-icon">${s}</span>
|
|
269
269
|
<span class="tool-name">${e.tool||"\u2192"}</span>
|
|
270
|
-
<span class="tool-detail">${escapeHtml(
|
|
271
|
-
</div>`}else if(e.type==="progress"){const
|
|
270
|
+
<span class="tool-detail">${escapeHtml(o)}${i}</span>
|
|
271
|
+
</div>`}else if(e.type==="progress"){const s=e.hookEvent||e.hookName,n=s?"\u{1FA9D}":e.progressType==="query_update"?"\u27F3":"\u2713",i=s?e.hookName||e.hookEvent:e.query||e.progressType;return`<div class="activity-line progress-line${s?" hook-line":""}">
|
|
272
272
|
<span class="time">${t}</span>
|
|
273
|
-
<span class="tool-icon">${
|
|
273
|
+
<span class="tool-icon">${n}</span>
|
|
274
274
|
<span class="tool-detail">${escapeHtml(i)}</span>
|
|
275
|
-
</div>`}else if(e.type==="message"){const
|
|
276
|
-
<span class="time">${t}</span> \u{1F4AC} ${escapeHtml(
|
|
277
|
-
</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
|
|
275
|
+
</div>`}else if(e.type==="message"){const s=e.text.length>150?e.text.substring(0,150)+"...":e.text;return`<div class="message-line">
|
|
276
|
+
<span class="time">${t}</span> \u{1F4AC} ${escapeHtml(s)}
|
|
277
|
+
</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{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=>{});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=>{})});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 f=e.color||"blue",S=document.createElement("div");S.className="subagent-window has-terminal",S.id=`subagent-window-${t}`,S.style.zIndex=++this.subagentWindowZIndex,S.style.left=`${p}px`,S.style.top=`${g}px`,S.style.width=`${n}px`,S.style.height=`${i}px`,S.innerHTML=`
|
|
278
278
|
<div class="subagent-window-header">
|
|
279
279
|
<div class="subagent-window-title" title="Teammate terminal: ${escapeHtml(e.teammateName)} (pane ${e.paneTarget})">
|
|
280
280
|
<span class="icon" style="color: var(--team-color-${f}, #339af0)">\u2B24</span>
|
|
@@ -287,11 +287,11 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
287
287
|
</div>
|
|
288
288
|
<div class="subagent-window-body teammate-terminal-body" id="subagent-window-body-${t}">
|
|
289
289
|
</div>
|
|
290
|
-
`,document.body.appendChild(
|
|
290
|
+
`,document.body.appendChild(S);const w=this.makeWindowDraggable(S,S.querySelector(".subagent-window-header"));typeof this.makeWindowResizable=="function"&&this.makeWindowResizable(S);const v=(this.loadAppSettingsFromStorage().subagentActiveTabOnly??!0)&&e.sessionId!==this.activeSessionId;this.subagentWindows.set(t,{element:S,minimized:!1,hidden:v,dragListeners:w,description:`Teammate: ${e.teammateName}`}),this.subagentParentMap.set(t,e.sessionId),v&&(S.style.display="none"),S.addEventListener("mousedown",()=>{S.style.zIndex=++this.subagentWindowZIndex});const E=new ResizeObserver(()=>{this.updateConnectionLines()});E.observe(S),this.subagentWindows.get(t).resizeObserver=E,this.initTeammateTerminal(t,e,S),requestAnimationFrame(()=>{S.style.transition="transform 0.3s ease, opacity 0.3s ease",S.style.transform="scale(1)",S.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("_","-"),f=m.owner?`<span class="team-task-owner teammate-color-${this.getTeammateColor(m.owner)}">${escapeHtml(m.owner)}</span>`:"";return`<div class="team-task-item ${g}">
|
|
291
291
|
<span class="team-task-status">${p}</span>
|
|
292
292
|
<span class="team-task-subject">${escapeHtml(m.subject)}</span>
|
|
293
293
|
${f}
|
|
294
|
-
</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=null)}getTeammateColor(e){return this.teammateMap.get(e)?.color||"blue"}normalizeFilePath(e,t){if(!e)return"";let
|
|
294
|
+
</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(`
|
|
295
295
|
<div class="project-insight-item" data-tool-id="${u.id}">
|
|
296
296
|
<div class="project-insight-command">
|
|
297
297
|
<span class="icon">\u{1F4BB}</span>
|
|
@@ -307,14 +307,14 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
307
307
|
`)}d.push(`
|
|
308
308
|
</div>
|
|
309
309
|
</div>
|
|
310
|
-
`)}t.innerHTML=d.join("")}closeProjectInsightsPanel(){const e=this.$("projectInsightsPanel");e&&(e.classList.remove("visible"),this.projectInsightsPanelVisible=!1)}fileBrowserData=null;fileBrowserExpandedDirs=new Set;fileBrowserFilter="";fileBrowserAllExpanded=!1;filePreviewContent="";async loadFileBrowser(e){if(!e)return;const t=this.$("fileBrowserTree"),
|
|
311
|
-
<div class="file-tree-item${h}" data-path="${escapeHtml(
|
|
310
|
+
`)}t.innerHTML=d.join("")}closeProjectInsightsPanel(){const e=this.$("projectInsightsPanel");e&&(e.classList.remove("visible"),this.projectInsightsPanelVisible=!1)}fileBrowserData=null;fileBrowserExpandedDirs=new Set;fileBrowserFilter="";fileBrowserAllExpanded=!1;fileBrowserDragListeners=null;filePreviewContent="";async loadFileBrowser(e){if(!e)return;const t=this.$("fileBrowserTree"),s=this.$("fileBrowserStatus");if(t){t.innerHTML='<div class="file-browser-loading">Loading files...</div>';try{const n=await fetch(`/api/sessions/${e}/files?depth=5&showHidden=false`);if(!n.ok)throw new Error("Failed to load files");const i=await n.json();if(!i.success)throw new Error(i.error||"Failed to load files");if(this.fileBrowserData=i.data,this.renderFileBrowserTree(),s){const{totalFiles:o,totalDirectories:l,truncated:a}=i.data;s.textContent=`${o} files, ${l} dirs${a?" (truncated)":""}`}}catch(n){t.innerHTML=`<div class="file-browser-empty">Failed to load files: ${escapeHtml(n.message)}</div>`}}}renderFileBrowserTree(){const e=this.$("fileBrowserTree");if(!e||!this.fileBrowserData)return;const{tree:t}=this.fileBrowserData;if(!t||t.length===0){e.innerHTML='<div class="file-browser-empty">No files found</div>';return}const s=[],n=this.fileBrowserFilter.toLowerCase(),i=(o,l)=>{const a=o.type==="directory",r=this.fileBrowserExpandedDirs.has(o.path),c=!n||o.name.toLowerCase().includes(n);let d=!1;a&&n&&o.children&&(d=this.hasMatchingChild(o,n));const h=!(c||d)&&n?" hidden-by-filter":"",m=a?r?"\u{1F4C2}":"\u{1F4C1}":this.getFileIcon(o.extension),p=a?`<span class="file-tree-expand${r?" expanded":""}">\u25B6</span>`:'<span class="file-tree-expand"></span>',g=!a&&o.size!==void 0?`<span class="file-tree-size">${this.formatFileSize(o.size)}</span>`:"",f=a?"file-tree-name directory":"file-tree-name";if(s.push(`
|
|
311
|
+
<div class="file-tree-item${h}" data-path="${escapeHtml(o.path)}" data-type="${o.type}" data-depth="${l}">
|
|
312
312
|
${p}
|
|
313
313
|
<span class="file-tree-icon">${m}</span>
|
|
314
|
-
<span class="${f}">${escapeHtml(
|
|
314
|
+
<span class="${f}">${escapeHtml(o.name)}</span>
|
|
315
315
|
${g}
|
|
316
316
|
</div>
|
|
317
|
-
`),
|
|
317
|
+
`),a&&r&&o.children)for(const S of o.children)i(S,l+1)};for(const o of t)i(o,0);e.innerHTML=s.join(""),e.querySelectorAll(".file-tree-item").forEach(o=>{o.addEventListener("click",()=>{const l=o.dataset.path;o.dataset.type==="directory"?this.toggleFileBrowserFolder(l):this.openFilePreview(l)})})}hasMatchingChild(e,t){if(!e.children)return!1;for(const s of e.children)if(s.name.toLowerCase().includes(t)||s.type==="directory"&&this.hasMatchingChild(s,t))return!0;return!1}toggleFileBrowserFolder(e){this.fileBrowserExpandedDirs.has(e)?this.fileBrowserExpandedDirs.delete(e):this.fileBrowserExpandedDirs.add(e),this.renderFileBrowserTree()}filterFileBrowser(e){this.fileBrowserFilter=e,e&&this.expandAllDirectories(this.fileBrowserData?.tree||[]),this.renderFileBrowserTree()}expandAllDirectories(e){for(const t of e)t.type==="directory"&&(this.fileBrowserExpandedDirs.add(t.path),t.children&&this.expandAllDirectories(t.children))}collapseAllDirectories(){this.fileBrowserExpandedDirs.clear()}toggleFileBrowserExpand(){this.fileBrowserAllExpanded=!this.fileBrowserAllExpanded;const e=this.$("fileBrowserExpandBtn");this.fileBrowserAllExpanded?(this.expandAllDirectories(this.fileBrowserData?.tree||[]),e&&(e.innerHTML="\u229F")):(this.collapseAllDirectories(),e&&(e.innerHTML="\u229E")),this.renderFileBrowserTree()}refreshFileBrowser(){if(this.activeSessionId){this.fileBrowserExpandedDirs.clear(),this.fileBrowserFilter="",this.fileBrowserAllExpanded=!1;const e=this.$("fileBrowserSearch");e&&(e.value=""),this.loadFileBrowser(this.activeSessionId)}}closeFileBrowserPanel(){const e=this.$("fileBrowserPanel");if(e&&(e.classList.remove("visible"),e.style.left="",e.style.top="",e.style.bottom="",e.style.right=""),this.fileBrowserDragListeners){const s=this.fileBrowserDragListeners;document.removeEventListener("mousemove",s.move),document.removeEventListener("mouseup",s.up),document.removeEventListener("touchmove",s.touchMove),document.removeEventListener("touchend",s.up),document.removeEventListener("touchcancel",s.up),s.handle&&(s.handle.removeEventListener("mousedown",s.handleMouseDown),s.handle.removeEventListener("touchstart",s.handleTouchStart),s._onFirstDrag&&(s.handle.removeEventListener("mousedown",s._onFirstDrag),s.handle.removeEventListener("touchstart",s._onFirstDrag))),this.fileBrowserDragListeners=null}const t=this.loadAppSettingsFromStorage();t.showFileBrowser=!1,this.saveAppSettingsToStorage(t)}async openFilePreview(e){if(!this.activeSessionId||!e)return;const t=this.$("filePreviewOverlay"),s=this.$("filePreviewTitle"),n=this.$("filePreviewBody"),i=this.$("filePreviewFooter");if(!(!t||!n)){t.classList.add("visible"),s.textContent=e,n.innerHTML='<div class="binary-message">Loading...</div>',i.textContent="";try{const o=await fetch(`/api/sessions/${this.activeSessionId}/file-content?path=${encodeURIComponent(e)}&lines=500`);if(!o.ok)throw new Error("Failed to load file");const l=await o.json();if(!l.success)throw new Error(l.error||"Failed to load file");const a=l.data;if(a.type==="image")n.innerHTML=`<img src="${a.url}" alt="${escapeHtml(e)}">`,i.textContent=`${this.formatFileSize(a.size)} \u2022 ${a.extension}`;else if(a.type==="video")n.innerHTML=`<video src="${a.url}" controls autoplay></video>`,i.textContent=`${this.formatFileSize(a.size)} \u2022 ${a.extension}`;else if(a.type==="binary")n.innerHTML=`<div class="binary-message">Binary file (${this.formatFileSize(a.size)})<br>Cannot preview</div>`,i.textContent=a.extension||"binary";else{this.filePreviewContent=a.content,n.innerHTML=`<pre><code>${escapeHtml(a.content)}</code></pre>`;const r=a.truncated?` (showing 500/${a.totalLines} lines)`:"";i.textContent=`${a.totalLines} lines \u2022 ${this.formatFileSize(a.size)}${r}`}}catch(o){n.innerHTML=`<div class="binary-message">Error: ${escapeHtml(o.message)}</div>`}}}closeFilePreview(){const e=this.$("filePreviewOverlay");e&&e.classList.remove("visible"),this.filePreviewContent=""}copyFilePreviewContent(){this.filePreviewContent&&navigator.clipboard.writeText(this.filePreviewContent).then(()=>{this.showToast("Copied to clipboard","success")}).catch(()=>{this.showToast("Failed to copy","error")})}getFileIcon(e){return e&&{ts:"\u{1F4D8}",tsx:"\u{1F4D8}",js:"\u{1F4D2}",jsx:"\u{1F4D2}",mjs:"\u{1F4D2}",cjs:"\u{1F4D2}",py:"\u{1F40D}",pyx:"\u{1F40D}",pyw:"\u{1F40D}",rs:"\u{1F980}",go:"\u{1F439}",c:"\u2699\uFE0F",cpp:"\u2699\uFE0F",h:"\u2699\uFE0F",hpp:"\u2699\uFE0F",html:"\u{1F310}",htm:"\u{1F310}",css:"\u{1F3A8}",scss:"\u{1F3A8}",sass:"\u{1F3A8}",less:"\u{1F3A8}",json:"\u{1F4CB}",yaml:"\u{1F4CB}",yml:"\u{1F4CB}",xml:"\u{1F4CB}",toml:"\u{1F4CB}",csv:"\u{1F4CB}",md:"\u{1F4DD}",markdown:"\u{1F4DD}",txt:"\u{1F4DD}",rst:"\u{1F4DD}",png:"\u{1F5BC}\uFE0F",jpg:"\u{1F5BC}\uFE0F",jpeg:"\u{1F5BC}\uFE0F",gif:"\u{1F5BC}\uFE0F",svg:"\u{1F5BC}\uFE0F",webp:"\u{1F5BC}\uFE0F",ico:"\u{1F5BC}\uFE0F",bmp:"\u{1F5BC}\uFE0F",mp4:"\u{1F3AC}",webm:"\u{1F3AC}",mov:"\u{1F3AC}",mp3:"\u{1F3B5}",wav:"\u{1F3B5}",ogg:"\u{1F3B5}",sh:"\u{1F4BB}",bash:"\u{1F4BB}",zsh:"\u{1F4BB}",env:"\u{1F510}",gitignore:"\u{1F6AB}",dockerfile:"\u{1F433}",lock:"\u{1F512}"}[e.toLowerCase()]||"\u{1F4C4}"}formatFileSize(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}openLogViewerWindow(e,t){if(t=t||this.activeSessionId,!t)return;const s=`${t}-${e.replace(/[^a-zA-Z0-9]/g,"_")}`;if(this.logViewerWindows.has(s)){const d=this.logViewerWindows.get(s);d.element.style.zIndex=++this.logViewerWindowZIndex;return}const n=this.logViewerWindows.size,i=100+n%5*30,o=100+n%5*30,l=e.split("/").pop(),a=document.createElement("div");a.className="log-viewer-window",a.id=`log-viewer-window-${s}`,a.style.left=`${i}px`,a.style.top=`${o}px`,a.style.zIndex=++this.logViewerWindowZIndex,a.innerHTML=`
|
|
318
318
|
<div class="log-viewer-window-header">
|
|
319
319
|
<div class="log-viewer-window-title" title="${escapeHtml(e)}">
|
|
320
320
|
<span class="icon">\u{1F4C4}</span>
|
|
@@ -322,31 +322,31 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
322
322
|
<span class="status streaming">streaming</span>
|
|
323
323
|
</div>
|
|
324
324
|
<div class="log-viewer-window-actions">
|
|
325
|
-
<button onclick="app.closeLogViewerWindow('${escapeHtml(
|
|
325
|
+
<button onclick="app.closeLogViewerWindow('${escapeHtml(s)}')" title="Close">\xD7</button>
|
|
326
326
|
</div>
|
|
327
327
|
</div>
|
|
328
|
-
<div class="log-viewer-window-body" id="log-viewer-body-${
|
|
328
|
+
<div class="log-viewer-window-body" id="log-viewer-body-${s}">
|
|
329
329
|
<div class="log-info">Connecting to ${escapeHtml(e)}...</div>
|
|
330
330
|
</div>
|
|
331
|
-
`,document.body.appendChild(
|
|
331
|
+
`,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),f=(l/1024).toFixed(1),S=`/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=`
|
|
332
332
|
<div class="image-popup-header">
|
|
333
|
-
<div class="image-popup-title" title="${escapeHtml(
|
|
333
|
+
<div class="image-popup-title" title="${escapeHtml(s)}">
|
|
334
334
|
<span class="icon">\u{1F5BC}\uFE0F</span>
|
|
335
335
|
<span class="filename">${escapeHtml(i)}</span>
|
|
336
336
|
<span class="session-badge">${escapeHtml(g)}</span>
|
|
337
337
|
<span class="size-badge">${f} KB</span>
|
|
338
338
|
</div>
|
|
339
339
|
<div class="image-popup-actions">
|
|
340
|
-
<button onclick="app.openImageInNewTab('${escapeHtml(
|
|
341
|
-
<button onclick="app.closeImagePopup('${escapeHtml(
|
|
340
|
+
<button onclick="app.openImageInNewTab('${escapeHtml(S)}')" title="Open in new tab">\u2197</button>
|
|
341
|
+
<button onclick="app.closeImagePopup('${escapeHtml(a)}')" title="Close">\xD7</button>
|
|
342
342
|
</div>
|
|
343
343
|
</div>
|
|
344
344
|
<div class="image-popup-body">
|
|
345
|
-
<img src="${
|
|
345
|
+
<img src="${S}" alt="${escapeHtml(i)}"
|
|
346
346
|
onerror="this.parentElement.innerHTML='<div class=\\'image-error\\'>Failed to load image</div>'"
|
|
347
|
-
onclick="app.openImageInNewTab('${escapeHtml(
|
|
347
|
+
onclick="app.openImageInNewTab('${escapeHtml(S)}')" />
|
|
348
348
|
</div>
|
|
349
|
-
`,document.body.appendChild(w);const b=this.makeWindowDraggable(w,w.querySelector(".image-popup-header"));w.addEventListener("mousedown",()=>{w.style.zIndex=++this.imagePopupZIndex}),this.imagePopups.set(
|
|
349
|
+
`,document.body.appendChild(w);const b=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:b})}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{}}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){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){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){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+=`
|
|
350
350
|
<button class="mobile-case-item ${c?"selected":""}"
|
|
351
351
|
onclick="app.selectMobileCase('${escapeHtml(r.name)}')">
|
|
352
352
|
<span class="mobile-case-item-icon">
|
|
@@ -361,38 +361,38 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
361
361
|
</svg>
|
|
362
362
|
</span>
|
|
363
363
|
</button>
|
|
364
|
-
`}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
|
|
364
|
+
`}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 f="";d>0&&(f=`<span class="process-stat cost">$${d.toFixed(2)}</span>`);let S="";h&&(S=`<span class="monitor-model-badge ${h}">${h}</span>`),t+=`
|
|
365
365
|
<div class="process-item">
|
|
366
|
-
<span class="monitor-status-badge ${r}">${
|
|
366
|
+
<span class="monitor-status-badge ${r}">${a}</span>
|
|
367
367
|
<div class="process-info">
|
|
368
|
-
<div class="process-name">${
|
|
368
|
+
<div class="process-name">${S} ${escapeHtml(s.name||s.muxName)}</div>
|
|
369
369
|
<div class="process-meta">
|
|
370
370
|
${g}
|
|
371
371
|
${f}
|
|
372
372
|
${p}
|
|
373
|
-
<span class="process-stat memory">${
|
|
374
|
-
<span class="process-stat cpu">${
|
|
373
|
+
<span class="process-stat memory">${n.memoryMB}MB</span>
|
|
374
|
+
<span class="process-stat cpu">${n.cpuPercent}%</span>
|
|
375
375
|
</div>
|
|
376
376
|
</div>
|
|
377
377
|
<div class="process-actions">
|
|
378
|
-
<button class="btn-toolbar btn-sm btn-danger" onclick="app.killMuxSession('${escapeHtml(
|
|
378
|
+
<button class="btn-toolbar btn-sm btn-danger" onclick="app.killMuxSession('${escapeHtml(s.sessionId)}')" title="Kill session">Kill</button>
|
|
379
379
|
</div>
|
|
380
380
|
</div>
|
|
381
|
-
`}e.innerHTML=t}renderMonitorSubagents(){const e=document.getElementById("monitorSubagentsBody"),t=document.getElementById("monitorSubagentStats");if(!e)return;const
|
|
381
|
+
`}e.innerHTML=t}renderMonitorSubagents(){const e=document.getElementById("monitorSubagentsBody"),t=document.getElementById("monitorSubagentStats");if(!e)return;const s=Array.from(this.subagents.values()),n=s.filter(o=>o.status==="active"||o.status==="idle").length;if(t&&(t.textContent=`${s.length} tracked`+(n>0?`, ${n} active`:"")),s.length===0){e.innerHTML='<div class="monitor-empty">No background agents</div>';return}let i="";for(const o of s){const l=o.status==="active"?"active":o.status==="idle"?"idle":"completed",a=o.modelShort?`<span class="model-badge ${o.modelShort}">${o.modelShort}</span>`:"",r=o.description?escapeHtml(o.description.substring(0,40)):o.agentId;i+=`
|
|
382
382
|
<div class="process-item">
|
|
383
|
-
<span class="process-mode ${l}">${
|
|
383
|
+
<span class="process-mode ${l}">${o.status}</span>
|
|
384
384
|
<div class="process-info">
|
|
385
|
-
<div class="process-name">${
|
|
385
|
+
<div class="process-name">${a} ${r}</div>
|
|
386
386
|
<div class="process-meta">
|
|
387
|
-
<span>ID: ${
|
|
388
|
-
<span>${
|
|
387
|
+
<span>ID: ${o.agentId}</span>
|
|
388
|
+
<span>${o.toolCallCount||0} tools</span>
|
|
389
389
|
</div>
|
|
390
390
|
</div>
|
|
391
391
|
<div class="process-actions">
|
|
392
|
-
${
|
|
392
|
+
${o.status!=="completed"?`<button class="btn-toolbar btn-sm btn-danger" onclick="app.killSubagent('${escapeHtml(o.agentId)}')" title="Kill agent">Kill</button>`:""}
|
|
393
393
|
</div>
|
|
394
394
|
</div>
|
|
395
|
-
`}e.innerHTML=i}async killMuxSession(e){if(confirm("Kill this mux session?")){try{await this.closeSession(e,!0)}catch{try{await fetch(`/api/mux-sessions/${e}`,{method:"DELETE"})}catch{}this.showToast("Tmux session killed","success")}this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e),this.renderMuxSessions()}}async reconcileMuxSessions(){try{const t=await(await fetch("/api/mux-sessions/reconcile",{method:"POST"})).json();t.dead&&t.dead.length>0?(this.showToast(`Found ${t.dead.length} dead mux session(s)`,"warning"),await this.loadMuxSessions()):this.showToast("All mux sessions are alive","success")}catch{this.showToast("Failed to reconcile mux sessions","error")}}renderMonitorPlanAgents(){const e=document.getElementById("monitorPlanAgentsSection"),t=document.getElementById("monitorPlanAgentsBody"),
|
|
395
|
+
`}e.innerHTML=i}async killMuxSession(e){if(confirm("Kill this mux session?")){try{await this.closeSession(e,!0)}catch{try{await fetch(`/api/mux-sessions/${e}`,{method:"DELETE"})}catch{}this.showToast("Tmux session killed","success")}this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e),this.renderMuxSessions()}}async reconcileMuxSessions(){try{const t=await(await fetch("/api/mux-sessions/reconcile",{method:"POST"})).json();t.dead&&t.dead.length>0?(this.showToast(`Found ${t.dead.length} dead mux session(s)`,"warning"),await this.loadMuxSessions()):this.showToast("All mux sessions are alive","success")}catch{this.showToast("Failed to reconcile mux sessions","error")}}renderMonitorPlanAgents(){const e=document.getElementById("monitorPlanAgentsSection"),t=document.getElementById("monitorPlanAgentsBody"),s=document.getElementById("monitorPlanAgentStats");if(!e||!t)return;const n=Array.from(this.planSubagents?.values()||[]),i=!!this.activePlanOrchestratorId;if(n.length===0&&!i){e.style.display="none";return}e.style.display="";const o=n.filter(r=>r.status==="running").length,l=n.filter(r=>r.status==="completed"||r.status==="failed").length;if(s&&(i?s.textContent=`${o} running, ${l} done`:s.textContent=`${n.length} total`),n.length===0){t.innerHTML=`<div class="monitor-empty">${i?"Plan generation starting...":"No plan agents"}</div>`;return}let a="";for(const r of n){const c=r.status==="running"?"active":r.status==="completed"?"completed":"error",d=r.agentType||r.agentId,u=r.model?'<span class="model-badge opus">opus</span>':"",h=r.detail?escapeHtml(r.detail.substring(0,50)):"",m=r.durationMs?`${(r.durationMs/1e3).toFixed(1)}s`:"",p=r.itemCount?`${r.itemCount} items`:"";a+=`
|
|
396
396
|
<div class="process-item">
|
|
397
397
|
<span class="process-mode ${c}">${r.status||"pending"}</span>
|
|
398
398
|
<div class="process-info">
|
|
@@ -404,4 +404,4 @@ Estimated cost based on Claude Opus pricing`:""}`}}openSessionOptions(e){const t
|
|
|
404
404
|
</div>
|
|
405
405
|
</div>
|
|
406
406
|
</div>
|
|
407
|
-
`}t.innerHTML=
|
|
407
|
+
`}t.innerHTML=a}async cancelPlanFromMonitor(){if(!this.activePlanOrchestratorId&&this.planSubagents?.size===0){this.showToast("No active plan generation","info");return}if(!confirm("Cancel plan generation and close all plan agent windows?"))return;await this.cancelPlanGeneration(),document.getElementById("ralphWizardModal")?.classList.contains("active")&&this.closeRalphWizard(),this.renderMonitorPlanAgents(),this.showToast("Plan generation cancelled","success")}_toastContainer=null;toggleNotifications(){this.notificationManager?.toggleDrawer()}toast(e,t="info"){return this.showToast(e,t)}showToast(e,t="info",s={}){const{duration:n=3e3,action:i}=s,o=document.createElement("div");o.className=`toast toast-${t}`;const l=document.createElement("span");if(l.textContent=e,o.appendChild(l),i){const a=document.createElement("button");a.textContent=i.label,a.style.cssText="margin-left:12px;padding:2px 10px;background:rgba(255,255,255,0.15);border:1px solid rgba(255,255,255,0.3);border-radius:3px;color:inherit;cursor:pointer;font-size:12px",a.onclick=r=>{r.stopPropagation(),i.onClick(),o.remove()},o.appendChild(a)}this._toastContainer||(this._toastContainer=document.querySelector(".toast-container"),this._toastContainer||(this._toastContainer=document.createElement("div"),this._toastContainer.className="toast-container",document.body.appendChild(this._toastContainer))),this._toastContainer.appendChild(o),requestAnimationFrame(()=>o.classList.add("show")),setTimeout(()=>{o.classList.remove("show"),setTimeout(()=>o.remove(),200)},n)}startSystemStatsPolling(){this.stopSystemStatsPolling(),this.fetchSystemStats(),this.systemStatsInterval=setInterval(()=>{this.fetchSystemStats()},2e3)}stopSystemStatsPolling(){this.systemStatsInterval&&(clearInterval(this.systemStatsInterval),this.systemStatsInterval=null)}async fetchSystemStats(){const e=document.getElementById("headerSystemStats");if(!(!e||e.style.display==="none"))try{const s=await(await fetch("/api/system/stats")).json();this.updateSystemStatsDisplay(s)}catch{}}updateSystemStatsDisplay(e){const t=this.$("statCpu"),s=this.$("statCpuBar"),n=this.$("statMem"),i=this.$("statMemBar");if(t&&s&&(t.textContent=`${e.cpu}%`,s.style.width=`${Math.min(100,e.cpu)}%`,s.classList.remove("medium","high"),t.classList.remove("high"),e.cpu>80?(s.classList.add("high"),t.classList.add("high")):e.cpu>50&&s.classList.add("medium")),n&&i){const o=(e.memory.usedMB/1024).toFixed(1);n.textContent=`${o}G`,i.style.width=`${Math.min(100,e.memory.percent)}%`,i.classList.remove("medium","high"),n.classList.remove("high"),e.memory.percent>80?(i.classList.add("high"),n.classList.add("high")):e.memory.percent>50&&i.classList.add("medium")}}}try{for(let I=0;I<localStorage.length;I++){const e=localStorage.key(I);if(e&&(e.startsWith("claudeman-")||e.startsWith("claudeman_"))){const t=e.replace(/^claudeman[-_]/,s=>"codeman"+s.charAt(s.length-1));localStorage.getItem(t)===null&&localStorage.setItem(t,localStorage.getItem(e))}}}catch{}const app=new CodemanApp;window.app=app,window.MobileDetection=MobileDetection;
|