aicodeman 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/web/public/api-client.js.gz +0 -0
- package/dist/web/public/app.js +2 -2
- package/dist/web/public/app.js.br +0 -0
- package/dist/web/public/app.js.gz +0 -0
- package/dist/web/public/constants.js +1 -1
- package/dist/web/public/constants.js.br +0 -0
- package/dist/web/public/constants.js.gz +0 -0
- package/dist/web/public/index.html +10 -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.gz +0 -0
- package/dist/web/public/mobile-handlers.js.gz +0 -0
- package/dist/web/public/mobile.css.gz +0 -0
- package/dist/web/public/notification-manager.js.gz +0 -0
- package/dist/web/public/ralph-wizard.js.gz +0 -0
- package/dist/web/public/styles.css.gz +0 -0
- package/dist/web/public/subagent-windows.js.gz +0 -0
- package/dist/web/public/sw.js.gz +0 -0
- package/dist/web/public/upload.html.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-zerolag-input.js +1 -1
- 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.gz +0 -0
- package/package.json +1 -1
|
Binary file
|
package/dist/web/public/app.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const _SSE_HANDLER_MAP=[[SSE_EVENTS.INIT,"_onInit"],[SSE_EVENTS.SESSION_CREATED,"_onSessionCreated"],[SSE_EVENTS.SESSION_UPDATED,"_onSessionUpdated"],[SSE_EVENTS.SESSION_DELETED,"_onSessionDeleted"],[SSE_EVENTS.SESSION_TERMINAL,"_onSessionTerminal"],[SSE_EVENTS.SESSION_NEEDS_REFRESH,"_onSessionNeedsRefresh"],[SSE_EVENTS.SESSION_CLEAR_TERMINAL,"_onSessionClearTerminal"],[SSE_EVENTS.SESSION_COMPLETION,"_onSessionCompletion"],[SSE_EVENTS.SESSION_ERROR,"_onSessionError"],[SSE_EVENTS.SESSION_EXIT,"_onSessionExit"],[SSE_EVENTS.SESSION_IDLE,"_onSessionIdle"],[SSE_EVENTS.SESSION_WORKING,"_onSessionWorking"],[SSE_EVENTS.SESSION_AUTO_CLEAR,"_onSessionAutoClear"],[SSE_EVENTS.SESSION_CLI_INFO,"_onSessionCliInfo"],[SSE_EVENTS.SCHEDULED_CREATED,"_onScheduledCreated"],[SSE_EVENTS.SCHEDULED_UPDATED,"_onScheduledUpdated"],[SSE_EVENTS.SCHEDULED_COMPLETED,"_onScheduledCompleted"],[SSE_EVENTS.SCHEDULED_STOPPED,"_onScheduledStopped"],[SSE_EVENTS.RESPAWN_STARTED,"_onRespawnStarted"],[SSE_EVENTS.RESPAWN_STOPPED,"_onRespawnStopped"],[SSE_EVENTS.RESPAWN_STATE_CHANGED,"_onRespawnStateChanged"],[SSE_EVENTS.RESPAWN_CYCLE_STARTED,"_onRespawnCycleStarted"],[SSE_EVENTS.RESPAWN_BLOCKED,"_onRespawnBlocked"],[SSE_EVENTS.RESPAWN_AUTO_ACCEPT_SENT,"_onRespawnAutoAcceptSent"],[SSE_EVENTS.RESPAWN_DETECTION_UPDATE,"_onRespawnDetectionUpdate"],[SSE_EVENTS.RESPAWN_TIMER_STARTED,"_onRespawnTimerStarted"],[SSE_EVENTS.RESPAWN_TIMER_CANCELLED,"_onRespawnTimerCancelled"],[SSE_EVENTS.RESPAWN_TIMER_COMPLETED,"_onRespawnTimerCompleted"],[SSE_EVENTS.RESPAWN_ERROR,"_onRespawnError"],[SSE_EVENTS.RESPAWN_ACTION_LOG,"_onRespawnActionLog"],[SSE_EVENTS.TASK_CREATED,"_onTaskCreated"],[SSE_EVENTS.TASK_COMPLETED,"_onTaskCompleted"],[SSE_EVENTS.TASK_FAILED,"_onTaskFailed"],[SSE_EVENTS.TASK_UPDATED,"_onTaskUpdated"],[SSE_EVENTS.MUX_CREATED,"_onMuxCreated"],[SSE_EVENTS.MUX_KILLED,"_onMuxKilled"],[SSE_EVENTS.MUX_DIED,"_onMuxDied"],[SSE_EVENTS.MUX_STATS_UPDATED,"_onMuxStatsUpdated"],[SSE_EVENTS.SESSION_RALPH_LOOP_UPDATE,"_onRalphLoopUpdate"],[SSE_EVENTS.SESSION_RALPH_TODO_UPDATE,"_onRalphTodoUpdate"],[SSE_EVENTS.SESSION_RALPH_COMPLETION_DETECTED,"_onRalphCompletionDetected"],[SSE_EVENTS.SESSION_RALPH_STATUS_UPDATE,"_onRalphStatusUpdate"],[SSE_EVENTS.SESSION_CIRCUIT_BREAKER_UPDATE,"_onCircuitBreakerUpdate"],[SSE_EVENTS.SESSION_EXIT_GATE_MET,"_onExitGateMet"],[SSE_EVENTS.SESSION_BASH_TOOL_START,"_onBashToolStart"],[SSE_EVENTS.SESSION_BASH_TOOL_END,"_onBashToolEnd"],[SSE_EVENTS.SESSION_BASH_TOOLS_UPDATE,"_onBashToolsUpdate"],[SSE_EVENTS.HOOK_IDLE_PROMPT,"_onHookIdlePrompt"],[SSE_EVENTS.HOOK_PERMISSION_PROMPT,"_onHookPermissionPrompt"],[SSE_EVENTS.HOOK_ELICITATION_DIALOG,"_onHookElicitationDialog"],[SSE_EVENTS.HOOK_STOP,"_onHookStop"],[SSE_EVENTS.HOOK_TEAMMATE_IDLE,"_onHookTeammateIdle"],[SSE_EVENTS.HOOK_TASK_COMPLETED,"_onHookTaskCompleted"],[SSE_EVENTS.SUBAGENT_DISCOVERED,"_onSubagentDiscovered"],[SSE_EVENTS.SUBAGENT_UPDATED,"_onSubagentUpdated"],[SSE_EVENTS.SUBAGENT_TOOL_CALL,"_onSubagentToolCall"],[SSE_EVENTS.SUBAGENT_PROGRESS,"_onSubagentProgress"],[SSE_EVENTS.SUBAGENT_MESSAGE,"_onSubagentMessage"],[SSE_EVENTS.SUBAGENT_TOOL_RESULT,"_onSubagentToolResult"],[SSE_EVENTS.SUBAGENT_COMPLETED,"_onSubagentCompleted"],[SSE_EVENTS.IMAGE_DETECTED,"_onImageDetected"],[SSE_EVENTS.TUNNEL_STARTED,"_onTunnelStarted"],[SSE_EVENTS.TUNNEL_STOPPED,"_onTunnelStopped"],[SSE_EVENTS.TUNNEL_PROGRESS,"_onTunnelProgress"],[SSE_EVENTS.TUNNEL_ERROR,"_onTunnelError"],[SSE_EVENTS.TUNNEL_QR_ROTATED,"_onTunnelQrRotated"],[SSE_EVENTS.TUNNEL_QR_REGENERATED,"_onTunnelQrRegenerated"],[SSE_EVENTS.TUNNEL_QR_AUTH_USED,"_onTunnelQrAuthUsed"],[SSE_EVENTS.PLAN_SUBAGENT,"_onPlanSubagent"],[SSE_EVENTS.PLAN_PROGRESS,"_onPlanProgress"],[SSE_EVENTS.PLAN_STARTED,"_onPlanStarted"],[SSE_EVENTS.PLAN_CANCELLED,"_onPlanCancelled"],[SSE_EVENTS.PLAN_COMPLETED,"_onPlanCompleted"]];class CodemanApp{constructor(){this.sessions=new Map,this._shortIdCache=new Map,this.sessionOrder=[],this.draggedTabId=null,this.cases=[],this.currentRun=null,this.totalTokens=0,this.globalStats=null,this.eventSource=null,this.terminal=null,this.fitAddon=null,this.activeSessionId=null,this._initGeneration=0,this._initFallbackTimer=null,this._selectGeneration=0,this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},this.timerCountdownInterval=null,this.terminalBuffers=new Map,this.editingSessionId=null,this.pendingCloseSessionId=null,this.muxSessions=[],this.ralphStates=new Map,this.subagents=new Map,this.subagentActivity=new Map,this.subagentToolResults=new Map,this.activeSubagentId=null,this.subagentPanelVisible=!1,this.subagentWindows=new Map,this.subagentWindowZIndex=ZINDEX_SUBAGENT_BASE,this.minimizedSubagents=new Map,this._subagentHideTimeout=null,this.subagentParentMap=new Map,this.teams=new Map,this.teamTasks=new Map,this.teammateMap=new Map,this.teammatePanesByName=new Map,this.teammateTerminals=new Map,this.terminalBufferCache=new Map,this.ralphStatePanelCollapsed=!0,this.ralphClosedSessions=new Set,this.planSubagents=new Map,this.planSubagentWindowZIndex=ZINDEX_PLAN_SUBAGENT_BASE,this.planGenerationStopped=!1,this.planAgentsMinimized=!1,this.wizardDragState=null,this.wizardDragListeners=null,this.wizardPosition=null,this.projectInsights=new Map,this.logViewerWindows=new Map,this.logViewerWindowZIndex=ZINDEX_LOG_VIEWER_BASE,this.projectInsightsPanelVisible=!1,this.currentSessionWorkingDir=null,this.imagePopups=new Map,this.imagePopupZIndex=ZINDEX_IMAGE_POPUP_BASE,this.tabAlerts=new Map,this.pendingHooks=new Map,this.pendingWrites=[],this.writeFrameScheduled=!1,this._wasAtBottomBeforeWrite=!0,this.syncWaitTimeout=null,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.flickerFilterTimeout=null,this.renderSessionTabsTimeout=null,this.renderRalphStatePanelTimeout=null,this.renderTaskPanelTimeout=null,this.renderMuxSessionsTimeout=null,this.systemStatsInterval=null,this.sseReconnectTimeout=null,this._sseListenerCleanup=null,this.reconnectAttempts=0,this.maxReconnectAttempts=10,this.isOnline=navigator.onLine,this._inputQueue=new Map,this._inputQueueMaxBytes=64*1024,this._connectionStatus="connected",this._inputSendChain=Promise.resolve(),this._localEchoOverlay=null,this._localEchoEnabled=!1,this._restoringFlushedState=!1,this.activeFocusTrap=null,this.notificationManager=new NotificationManager(this),this.idleTimers=new Map,this._elemCache={},this.init()}$(e){return this._elemCache[e]||(this._elemCache[e]=document.getElementById(e)),this._elemCache[e]}formatTokens(e){if(e>=1e6){const t=e/1e6;return t>=10?`${t.toFixed(1)}m`:`${t.toFixed(2)}m`}else if(e>=1e3){const t=e/1e3;return t>=100?`${t.toFixed(0)}k`:`${t.toFixed(1)}k`}return String(e)}estimateCost(e,t){const s=e/1e6*15,n=t/1e6*75;return s+n}setPendingHook(e,t){this.pendingHooks.has(e)||this.pendingHooks.set(e,new Set),this.pendingHooks.get(e).add(t),this.updateTabAlertFromHooks(e)}clearPendingHooks(e,t=null){const s=this.pendingHooks.get(e);s&&(t?s.delete(t):s.clear(),s.size===0&&this.pendingHooks.delete(e),this.updateTabAlertFromHooks(e))}updateTabAlertFromHooks(e){const t=this.pendingHooks.get(e);!t||t.size===0?this.tabAlerts.delete(e):t.has("permission_prompt")||t.has("elicitation_dialog")?this.tabAlerts.set(e,"action"):t.has("idle_prompt")&&this.tabAlerts.set(e,"idle"),this.renderSessionTabs()}init(){MobileDetection.init(),KeyboardHandler.init(),SwipeHandler.init(),VoiceInput.init(),KeyboardAccessoryBar.init(),this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility(),document.documentElement.classList.remove("mobile-init"),requestAnimationFrame(()=>{this.initTerminal(),this.loadFontSize(),this.connectSSE(),this._initFallbackTimer=setTimeout(()=>{this._initGeneration===0&&this.loadState()},3e3)}),this.registerServiceWorker();const e=fetch("/api/settings").then(t=>t.ok?t.json():null).catch(()=>null);if(this.loadQuickStartCases(null,e),this._initRunMode(),this.setupEventListeners(),MobileDetection.isTouchDevice()){const t=s=>{s&&s.addEventListener("touchstart",n=>{if(!KeyboardHandler.keyboardVisible)return;const i=n.target.closest("button");i&&(n.preventDefault(),i.click(),typeof app<"u"&&app.terminal&&app.terminal.focus())},{passive:!1})};t(document.querySelector(".toolbar")),t(document.querySelector(".welcome-overlay"))}this.setupOnlineDetection(),this.loadAppSettingsFromServer(e).then(()=>{this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility()}),document.body.classList.add("app-loaded")}initTerminal(){const e=parseInt(localStorage.getItem("codeman-scrollback"))||DEFAULT_SCROLLBACK;if(this.terminal=new Terminal({theme:{background:"#0d0d0d",foreground:"#e0e0e0",cursor:"#e0e0e0",cursorAccent:"#0d0d0d",selection:"rgba(255, 255, 255, 0.3)",black:"#0d0d0d",red:"#ff6b6b",green:"#51cf66",yellow:"#ffd43b",blue:"#339af0",magenta:"#cc5de8",cyan:"#22b8cf",white:"#e0e0e0",brightBlack:"#495057",brightRed:"#ff8787",brightGreen:"#69db7c",brightYellow:"#ffe066",brightBlue:"#5c7cfa",brightMagenta:"#da77f2",brightCyan:"#66d9e8",brightWhite:"#ffffff"},fontFamily:'"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, monospace',fontSize:MobileDetection.getDeviceType()==="mobile"?10:14,lineHeight:1.2,cursorBlink:!1,cursorStyle:"block",scrollback:e,allowTransparency:!0,allowProposedApi:!0}),this.fitAddon=new FitAddon.FitAddon,this.terminal.loadAddon(this.fitAddon),typeof Unicode11Addon<"u")try{const r=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(r),this.terminal.unicode.activeVersion="11"}catch{}const t=document.getElementById("terminalContainer");if(this.terminal.open(t),typeof WebglAddon<"u")try{const r=new WebglAddon.WebglAddon;r.onContextLoss(()=>{r.dispose()}),this.terminal.loadAddon(r)}catch{}if(this._localEchoOverlay=new LocalEchoOverlay(this.terminal),MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this.registerFilePathLinkProvider(),t.addEventListener("wheel",r=>{r.preventDefault();const c=Math.round(r.deltaY/25)||(r.deltaY>0?1:-1);this.terminal.scrollLines(c)},{passive:!1}),!(MobileDetection.isTouchDevice()&&window.innerWidth<1024)){let r=0,c=0,d=0,u=0,h=null,m=!1;const p=t.querySelector(".xterm-viewport"),g=f=>{if(!p)return;const S=u?(f-u)/16.67:1;u=f,m?(c!==0&&(p.scrollTop+=c,c=0),h=requestAnimationFrame(g)):Math.abs(d)>.1?(p.scrollTop+=d*S,d*=.94,h=requestAnimationFrame(g)):(h=null,d=0)};t.addEventListener("touchstart",f=>{f.touches.length===1&&(r=f.touches[0].clientY,c=0,d=0,m=!0,u=0,h||(h=requestAnimationFrame(g)))},{passive:!0}),t.addEventListener("touchmove",f=>{if(f.touches.length===1&&m){const S=f.touches[0].clientY,w=r-S;c+=w,d=w*1.2,r=S}},{passive:!0}),t.addEventListener("touchend",()=>{m=!1},{passive:!0}),t.addEventListener("touchcancel",()=>{m=!1,d=0},{passive:!0})}this.showWelcome(),this._resizeTimeout=null,this._lastResizeDims=null;const i=40,o=10,l=()=>{this._resizeTimeout||(this._resizeTimeout=setTimeout(()=>{if(this._resizeTimeout=null,this.fitAddon){this.fitAddon.fit();const r=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;if(this.activeSessionId&&!r){const c=this.fitAddon.proposeDimensions(),d=c?Math.max(c.cols,i):i,u=c?Math.max(c.rows,o):o;(!this._lastResizeDims||d!==this._lastResizeDims.cols||u!==this._lastResizeDims.rows)&&(this._lastResizeDims={cols:d,rows:u},fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:d,rows:u})}).catch(()=>{}))}}this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},100))};window.addEventListener("resize",l),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(l),this.terminalResizeObserver.observe(t),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const a=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const r=this._pendingInput,c=this.activeSessionId;this._pendingInput="",this._sendInputAsync(c,r)}};this.terminal.onData(r=>{if(this.activeSessionId){if(/^\x1b\[[\?>=]?[\d;]*[cnR]$/.test(r))return;if(this._localEchoEnabled){if(r==="\x7F"){if(this._localEchoOverlay?.removeChar()==="flushed"){const{count:u,text:h}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(u===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,u),this._flushedTexts?.set(this.activeSessionId,h))),this._pendingInput+=r,a()}return}if(/^[\r\n]+$/.test(r)){const d=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),d&&(this._pendingInput+=d,a()),setTimeout(()=>{this._pendingInput+="\r",a()},80);return}if(r.length>1&&r.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(r);return}if(r.charCodeAt(0)<32){if(r.length>1&&r.charCodeAt(0)===27){this._pendingInput+=r,a();return}if(this._restoringFlushedState){this._pendingInput+=r,a();return}if(r===" "){const u=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),u&&(this._pendingInput+=u),this._pendingInput+=r,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let h="";try{const p=this._localEchoOverlay?.findPrompt?.();if(p){const g=this.terminal.buffer.active,f=g.getLine(g.viewportY+p.row);f&&(h=f.translateToString(!0).slice(p.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=h,a(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const m=this;this._tabCompletionFallback=setTimeout(()=>{if(m._tabCompletionFallback=null,!m._tabCompletionSessionId||m._tabCompletionSessionId!==m.activeSessionId)return;const p=m._localEchoOverlay;!p||p.pendingText||m.terminal.write("",()=>{if(!m._tabCompletionSessionId)return;p.resetBufferDetection();const g=p.detectBufferText();g&&g!==m._tabCompletionBaseText&&(m._tabCompletionSessionId=null,m._tabCompletionRetries=0,m._tabCompletionBaseText=null,p.rerender())})},300);return}const d=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),d&&(this._pendingInput+=d),this._pendingInput+=r,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}if(r.length===1&&r.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(r);return}}if(this._pendingInput+=r,r.charCodeAt(0)<32||r.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}const c=performance.now();c-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=c,a()):(this._lastKeystrokeTime=c,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(a,0)))}})}registerFilePathLinkProvider(){const e=this;let t=-1;this.terminal.registerLinkProvider({provideLinks(s,n){s!==t&&(t=s);const o=e.terminal.buffer.active.getLine(s);if(!o){n(void 0);return}const l=o.translateToString(!0);if(!l||!l.includes("/")){n(void 0);return}const a=[],r=/(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]*\s+)*(\/[^\s"'<>|;&\n\x00-\x1f]+)/g,c=/(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\n\x00-\x1f]*\.(?:log|txt|json|md|yaml|yml|csv|xml|sh|py|ts|js))\b/g,d=/Bash\([^)]*?(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\)\n\x00-\x1f]+)/g,u=(m,p)=>{const g=l.indexOf(m,p);g!==-1&&(a.some(f=>f.range.start.x===g+1)||a.push({text:m,range:{start:{x:g+1,y:s},end:{x:g+m.length+1,y:s}},decorations:{pointerCursor:!0,underline:!0},activate(f,S){e.openLogViewerWindow(S,e.activeSessionId)}}))};let h;for(r.lastIndex=0;(h=r.exec(l))!==null;)u(h[2],h.index);for(c.lastIndex=0;(h=c.exec(l))!==null;)u(h[1],h.index);for(d.lastIndex=0;(h=d.exec(l))!==null;)u(h[1],h.index);a.length>0,n(a.length>0?a:void 0)}})}showWelcome(){const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus())}hideWelcome(){const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const t=document.getElementById("welcomeQr");t&&(clearTimeout(this._welcomeQrShrinkTimer),t.classList.remove("expanded"))}isTerminalAtBottom(){if(!this.terminal)return!0;const e=this.terminal.buffer.active;return e.viewportY>=e.baseY-2}batchTerminalWrite(e){if(this._isLoadingBuffer){this._loadBufferQueue&&this._loadBufferQueue.push(e);return}this.writeFrameScheduled||(this._wasAtBottomBeforeWrite=this.isTerminalAtBottom());const s=(this.activeSessionId?this.sessions.get(this.activeSessionId):null)?.flickerFilterEnabled??!1;if(/\x1b\[\d{1,2}A/.test(e)||this.flickerFilterActive&&!s){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(s){if(e.includes("\x1B[2J")||e.includes("\x1B[H\x1B[J")||e.includes("\x1B[H")&&e.includes("\x1B[?25l")){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(this.flickerFilterActive){this.flickerFilterBuffer+=e;return}}this.pendingWrites.push(e),this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{if(this.pendingWrites.length>0&&this.terminal){const i=this.pendingWrites.join(""),o=i.includes(DEC_SYNC_START),l=i.includes(DEC_SYNC_END);if(o&&!l){this.syncWaitTimeout||(this.syncWaitTimeout=setTimeout(()=>{this.syncWaitTimeout=null,this.flushPendingWrites()},50)),this.writeFrameScheduled=!1;return}this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.flushPendingWrites()}this.writeFrameScheduled=!1}))}flushFlickerBuffer(){this.flickerFilterBuffer&&(this.pendingWrites.push(this.flickerFilterBuffer),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1})))}_updateLocalEchoState(){const e=this.loadAppSettingsFromStorage(),t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,n=!!((e.localEchoEnabled??MobileDetection.isTouchDevice())&&t);this._localEchoEnabled&&!n&&this._localEchoOverlay?.clear(),this._localEchoEnabled=n,this._localEchoOverlay&&t&&(t.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:i=>{try{const o=i.buffer.active,l=o.cursorY,a=o.getLine(o.viewportY+l);if(!a)return null;const c=a.translateToString(!0).indexOf("\u2503");return c>=0?{row:l,col:c}:null}catch{return null}}}):this._localEchoOverlay.setPrompt({type:"character",char:"\u276F",offset:2}))}flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=extractSyncSegments(this.pendingWrites.join(""));this.pendingWrites=[];for(const t of e)if(t){const s=t.startsWith(DEC_SYNC_START)?t.slice(DEC_SYNC_START.length):t;s&&this.terminal.write(s)}if(this._wasAtBottomBeforeWrite&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const t=this._localEchoOverlay,s=this;this.terminal.write("",()=>{if(!s._tabCompletionSessionId)return;t.resetBufferDetection();const n=t.detectBufferText();n?n===s._tabCompletionBaseText?(t.undoDetection(),s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0)):(s._tabCompletionSessionId=null,s._tabCompletionRetries=0,s._tabCompletionBaseText=null,s._tabCompletionFallback&&(clearTimeout(s._tabCompletionFallback),s._tabCompletionFallback=null),t.rerender()):(s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0))})}}chunkedTerminalWrite(e,t=TERMINAL_CHUNK_SIZE){return new Promise(s=>{if(!e||e.length===0){this._finishBufferLoad(),s();return}this._isLoadingBuffer=!0,this._loadBufferQueue=[];const n=e.replace(DEC_SYNC_STRIP_RE,""),i=()=>{this._finishBufferLoad(),s()};if(n.length<=t){this.terminal.write(n),i();return}let o=0;const l=()=>{if(o>=n.length){requestAnimationFrame(i);return}const a=n.slice(o,o+t);this.terminal.write(a),o+=t,requestAnimationFrame(l)};requestAnimationFrame(l)})}_finishBufferLoad(){const e=this._loadBufferQueue;if(this._isLoadingBuffer=!1,this._loadBufferQueue=null,e&&e.length>0)for(const t of e)this.batchTerminalWrite(t)}setupEventListeners(){document.addEventListener("keydown",t=>{t.key==="Escape"&&(this.closeAllPanels(),this.closeHelp()),(t.ctrlKey||t.metaKey)&&(t.key==="?"||t.key==="/")&&(t.preventDefault(),this.showHelp()),(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.quickStart()),(t.ctrlKey||t.metaKey)&&t.key==="w"&&(t.preventDefault(),this.killActiveSession()),(t.ctrlKey||t.metaKey)&&t.key==="Tab"&&(t.preventDefault(),this.nextSession()),(t.ctrlKey||t.metaKey)&&t.key==="k"&&(t.preventDefault(),this.killAllSessions()),(t.ctrlKey||t.metaKey)&&t.key==="l"&&(t.preventDefault(),this.clearTerminal()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="R"&&(t.preventDefault(),this.restoreTerminalSize()),(t.ctrlKey||t.metaKey)&&(t.key==="="||t.key==="+")&&(t.preventDefault(),this.increaseFontSize()),(t.ctrlKey||t.metaKey)&&t.key==="-"&&(t.preventDefault(),this.decreaseFontSize()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="V"&&(t.preventDefault(),VoiceInput.toggle())},!0);const e=this.$("headerTokens");e&&!e._statsHandlerAttached&&(e.classList.add("clickable"),e._statsHandlerAttached=!0,e.addEventListener("click",()=>this.openTokenStats())),this.setupColorPicker()}connectSSE(){if(!navigator.onLine){this.setConnectionStatus("offline");return}this.sseReconnectTimeout&&(clearTimeout(this.sseReconnectTimeout),this.sseReconnectTimeout=null),this._sseListenerCleanup&&(this._sseListenerCleanup(),this._sseListenerCleanup=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.reconnectAttempts===0?this.setConnectionStatus("connecting"):this.setConnectionStatus("reconnecting"),this.eventSource=new EventSource("/api/events");const e=[],t=(s,n)=>{this.eventSource.addEventListener(s,n),e.push({event:s,handler:n})};if(this._sseListenerCleanup=()=>{for(const{event:s,handler:n}of e)this.eventSource&&this.eventSource.removeEventListener(s,n);e.length=0},this.eventSource.onopen=()=>{this.reconnectAttempts=0,this.setConnectionStatus("connected")},this.eventSource.onerror=()=>{this.reconnectAttempts++,this.reconnectAttempts>=this.maxReconnectAttempts?this.setConnectionStatus("disconnected"):this.setConnectionStatus("reconnecting"),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.sseReconnectTimeout&&clearTimeout(this.sseReconnectTimeout);const s=this.reconnectAttempts<=1?200:Math.min(500*Math.pow(2,this.reconnectAttempts-2),3e4);this.sseReconnectTimeout=setTimeout(()=>this.connectSSE(),s)},!this._sseHandlerWrappers){this._sseHandlerWrappers=new Map;for(const[s,n]of _SSE_HANDLER_MAP){const i=this[n];this._sseHandlerWrappers.set(s,o=>{try{i.call(this,o.data?JSON.parse(o.data):{})}catch{}})}}for(const[s]of _SSE_HANDLER_MAP)t(s,this._sseHandlerWrappers.get(s))}_onInit(e){this.handleInit(e)}_onSessionCreated(e){this.sessions.set(e.id,e),this.sessionOrder.includes(e.id)||(this.sessionOrder.push(e.id),this.saveSessionOrder()),this.renderSessionTabs(),this.updateCost(),this.sessions.size===1&&this.startSystemStatsPolling()}_onSessionUpdated(e){const t=e.session||e,s=this.sessions.get(t.id),n=t.claudeSessionId&&(!s||!s.claudeSessionId);this.sessions.set(t.id,t),this.renderSessionTabs(),this.updateCost(),t.id===this.activeSessionId&&t.tokens&&this.updateRespawnTokens(t.tokens),this.updateSubagentParentNames(t.id),n&&(this.recheckOrphanSubagents(),requestAnimationFrame(()=>{this.updateConnectionLines()}))}_onSessionDeleted(e){if(this._cleanupSessionData(e.id),this.activeSessionId===e.id){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome()}this.renderSessionTabs(),this.renderRalphStatePanel(),this.renderProjectInsightsPanel(),this.sessions.size===0&&this.stopSystemStatsPolling()}_onSessionTerminal(e){e.id===this.activeSessionId&&this.batchTerminalWrite(e.data)}async _onSessionNeedsRefresh(){if(!(!this.activeSessionId||!this.terminal))try{const s=await(await fetch(`/api/sessions/${this.activeSessionId}/terminal?tail=262144`)).json();s.terminalBuffer&&(this.terminal.clear(),this.terminal.reset(),await this.chunkedTerminalWrite(s.terminalBuffer),this.terminal.scrollToBottom(),this._localEchoOverlay?.rerender(),this.activeSessionId&&this.sendResize(this.activeSessionId))}catch{}}async _onSessionClearTerminal(e){if(e.id===this.activeSessionId)try{const s=await(await fetch(`/api/sessions/${e.id}/terminal`)).json();if(this.terminal.clear(),this.terminal.reset(),s.terminalBuffer){const n=s.terminalBuffer.replace(DEC_SYNC_STRIP_RE,"");await this.chunkedTerminalWrite(n)}this.sendResize(e.id),this._localEchoOverlay?.rerender()}catch{}}_onSessionCompletion(e){this.totalCost+=e.cost||0,this.updateCost(),e.id===this.activeSessionId&&(this.terminal.writeln(""),this.terminal.writeln(`\x1B[1;32m Done (Cost: $${(e.cost||0).toFixed(4)})\x1B[0m`))}_onSessionError(e){e.id===this.activeSessionId&&this.terminal.writeln(`\x1B[1;31m Error: ${e.error}\x1B[0m`);const t=this.sessions.get(e.id);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:e.id,sessionName:t?.name||this.getShortId(e.id),title:"Session Error",message:e.error||"Unknown error"})}_onSessionExit(e){const t=this.sessions.get(e.id);t&&(t.status="stopped",this.renderSessionTabs(),e.id===this.activeSessionId&&this._updateLocalEchoState()),e.code&&e.code!==0&&this.notificationManager?.notify({urgency:"critical",category:"session-crash",sessionId:e.id,sessionName:t?.name||this.getShortId(e.id),title:"Session Crashed",message:`Exited with code ${e.code}`})}_onSessionIdle(e){const t=this.sessions.get(e.id);if(t&&(t.status="idle",this.renderSessionTabs(),this.sendPendingCtrlL(e.id),e.id===this.activeSessionId&&this._updateLocalEchoState()),!this.respawnStatus[e.id]?.enabled){const s=this.notificationManager?.preferences?.stuckThresholdMs||6e5;clearTimeout(this.idleTimers.get(e.id)),this.idleTimers.set(e.id,setTimeout(()=>{const n=this.sessions.get(e.id);this.notificationManager?.notify({urgency:"warning",category:"session-stuck",sessionId:e.id,sessionName:n?.name||this.getShortId(e.id),title:"Session Idle",message:`Idle for ${Math.round(s/6e4)}+ minutes`}),this.idleTimers.delete(e.id)},s))}}_onSessionWorking(e){const t=this.sessions.get(e.id);t&&(t.status="busy",this.pendingHooks.has(e.id)||this.tabAlerts.delete(e.id),this.renderSessionTabs(),this.sendPendingCtrlL(e.id),e.id===this.activeSessionId&&this._updateLocalEchoState());const s=this.idleTimers.get(e.id);s&&(clearTimeout(s),this.idleTimers.delete(e.id))}_onSessionAutoClear(e){e.sessionId===this.activeSessionId&&(this.showToast(`Auto-cleared at ${e.tokens.toLocaleString()} tokens`,"info"),this.updateRespawnTokens(0));const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-clear",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Auto-Cleared",message:`Context reset at ${(e.tokens||0).toLocaleString()} tokens`})}_onSessionCliInfo(e){const t=this.sessions.get(e.sessionId);t&&(e.version&&(t.cliVersion=e.version),e.model&&(t.cliModel=e.model),e.accountType&&(t.cliAccountType=e.accountType),e.latestVersion&&(t.cliLatestVersion=e.latestVersion)),e.sessionId===this.activeSessionId&&this.updateCliInfoDisplay()}_onScheduledCreated(e){this.currentRun=e,this.showTimer()}_onScheduledUpdated(e){this.currentRun=e,this.updateTimer()}_onScheduledCompleted(e){this.currentRun=e,this.hideTimer(),this.showToast("Scheduled run completed!","success")}_onScheduledStopped(){this.currentRun=null,this.hideTimer()}_onRespawnStarted(e){this.respawnStatus[e.sessionId]=e.status,e.sessionId===this.activeSessionId&&this.showRespawnBanner()}_onRespawnStopped(e){delete this.respawnStatus[e.sessionId],e.sessionId===this.activeSessionId&&this.hideRespawnBanner()}_onRespawnStateChanged(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].state=e.state),e.sessionId===this.activeSessionId&&this.updateRespawnBanner(e.state)}_onRespawnCycleStarted(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].cycleCount=e.cycleNumber),e.sessionId===this.activeSessionId&&(document.getElementById("respawnCycleCount").textContent=e.cycleNumber)}_onRespawnBlocked(e){const t=this.sessions.get(e.sessionId),n={circuit_breaker_open:"Circuit Breaker Open",exit_signal:"Exit Signal Detected",status_blocked:"Claude Reported BLOCKED"}[e.reason]||"Respawn Blocked";if(this.notificationManager?.notify({urgency:"critical",category:"respawn-blocked",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:n,message:e.details}),e.sessionId===this.activeSessionId){const i=document.getElementById("respawnStateLabel");i&&(i.textContent=n,i.classList.add("respawn-blocked"))}}_onRespawnAutoAcceptSent(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-accept",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Plan Accepted",message:`Accepted plan mode for ${t?.name||"session"}`})}_onRespawnDetectionUpdate(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].detection=e.detection),e.sessionId===this.activeSessionId&&this.updateDetectionDisplay(e.detection)}_onRespawnTimerStarted(e){if(e.endAt&&(this.respawnTimers[e.sessionId]={endAt:e.endAt,startedAt:e.startedAt,durationMinutes:e.durationMinutes},e.sessionId===this.activeSessionId&&this.showRespawnTimer()),e.timer){const{sessionId:t,timer:s}=e;this.respawnCountdownTimers[t]||(this.respawnCountdownTimers[t]={}),this.respawnCountdownTimers[t][s.name]={endsAt:s.endsAt,totalMs:s.durationMs,reason:s.reason},t===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.startCountdownInterval())}}_onRespawnTimerCancelled(e){const{sessionId:t,timerName:s}=e;this.respawnCountdownTimers[t]&&delete this.respawnCountdownTimers[t][s],t===this.activeSessionId&&this.updateCountdownTimerDisplay()}_onRespawnTimerCompleted(e){const{sessionId:t,timerName:s}=e;this.respawnCountdownTimers[t]&&delete this.respawnCountdownTimers[t][s],t===this.activeSessionId&&this.updateCountdownTimerDisplay()}_onRespawnError(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Respawn Error",message:e.error||e.message||"Respawn encountered an error"})}_onRespawnActionLog(e){const{sessionId:t,action:s}=e;this.addActionLogEntry(t,s),t===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.updateActionLogDisplay())}_onTaskCreated(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskCompleted(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskFailed(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskUpdated(e){e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onMuxCreated(e){this.muxSessions.push(e),this.renderMuxSessions()}_onMuxKilled(e){this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e.sessionId),this.renderMuxSessions()}_onMuxDied(e){this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e.sessionId),this.renderMuxSessions(),this.showToast("Mux session died: "+this.getShortId(e.sessionId),"warning")}_onMuxStatsUpdated(e){this.muxSessions=e,document.getElementById("monitorPanel").classList.contains("open")&&this.renderMuxSessions()}_onRalphLoopUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{loop:e.state})}_onRalphTodoUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{todos:e.todos})}_onRalphCompletionDetected(e){if(this.ralphClosedSessions.has(e.sessionId))return;const t=`${e.sessionId}:${e.phrase}`;if(this._shownCompletions?.has(t))return;this._shownCompletions||(this._shownCompletions=new Set),this._shownCompletions.add(t),setTimeout(()=>this._shownCompletions?.delete(t),3e4);const s=this.ralphStates.get(e.sessionId)||{};s.loop&&(s.loop.active=!1,this.updateRalphState(e.sessionId,s));const n=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"ralph-complete",sessionId:e.sessionId,sessionName:n?.name||this.getShortId(e.sessionId),title:"Loop Complete",message:`Completion: ${e.phrase||"unknown"}`})}_onRalphStatusUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{statusBlock:e.block})}_onCircuitBreakerUpdate(e){if(!this.ralphClosedSessions.has(e.sessionId)&&(this.updateRalphState(e.sessionId,{circuitBreaker:e.status}),e.status.state==="OPEN")){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"critical",category:"circuit-breaker",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Circuit Breaker Open",message:e.status.reason||"Loop stuck - no progress detected"})}}_onExitGateMet(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"exit-gate",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Exit Gate Met",message:`Loop ready to exit (indicators: ${e.completionIndicators})`})}_onBashToolStart(e){this.handleBashToolStart(e.sessionId,e.tool)}_onBashToolEnd(e){this.handleBashToolEnd(e.sessionId,e.tool)}_onBashToolsUpdate(e){this.handleBashToolsUpdate(e.sessionId,e.tools)}_onHookIdlePrompt(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this.notificationManager?.notify({urgency:"warning",category:"hook-idle",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Waiting for Input",message:e.message||"Claude is idle and waiting for a prompt"})}_onHookPermissionPrompt(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const s=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this.notificationManager?.notify({urgency:"critical",category:"hook-permission",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Permission Required",message:s||"Claude needs tool approval to continue"})}_onHookElicitationDialog(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this.notificationManager?.notify({urgency:"critical",category:"hook-elicitation",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Question Asked",message:e.question||"Claude is asking a question and waiting for your answer"})}_onHookStop(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.clearPendingHooks(e.sessionId),this.notificationManager?.notify({urgency:"info",category:"hook-stop",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Response Complete",message:e.reason||"Claude has finished responding"})}_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"hook-teammate-idle",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Teammate Idle",message:`A teammate is idle in ${t?.name||e.sessionId}`})}_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"hook-task-completed",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Task Completed",message:`A team task completed in ${t?.name||e.sessionId}`})}_onSubagentDiscovered(e){if(this.subagents.set(e.agentId,e),this.subagentActivity.set(e.agentId,[]),this.subagentToolResults.delete(e.agentId),this.subagentWindows.has(e.agentId)&&this.forceCloseSubagentWindow(e.agentId),this.renderSubagentPanel(),this.findParentSessionForSubagent(e.agentId),e.status==="active"){const n=this.subagents.get(e.agentId);n?.sessionId&&Array.from(this.sessions.values()).some(o=>o.claudeSessionId===n.sessionId)&&this.openSubagentWindow(e.agentId)}requestAnimationFrame(()=>{this.updateConnectionLines()});const t=this.subagentParentMap.get(e.agentId),s=t?this.sessions.get(t):null;this.notificationManager?.notify({urgency:"info",category:"subagent-spawn",sessionId:t||e.sessionId,sessionName:s?.name||t||e.sessionId,title:"Subagent Spawned",message:e.description||"New background agent started"})}_onSubagentUpdated(e){const t=this.subagents.get(e.agentId);t?(Object.assign(t,e),this.subagents.set(e.agentId,t)):this.subagents.set(e.agentId,e),this.renderSubagentPanel(),this.subagentWindows.has(e.agentId)&&(this.renderSubagentWindowContent(e.agentId),this.updateSubagentWindowHeader(e.agentId))}_onSubagentToolCall(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"tool",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.renderSubagentPanel(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentProgress(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"progress",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentMessage(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"message",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentToolResult(e){this.subagentToolResults.has(e.agentId)||this.subagentToolResults.set(e.agentId,new Map);const t=this.subagentToolResults.get(e.agentId);if(t.set(e.toolUseId,e),t.size>50){const n=t.keys().next().value;t.delete(n)}const s=this.subagentActivity.get(e.agentId)||[];s.push({type:"tool_result",...e}),s.length>50&&s.shift(),this.subagentActivity.set(e.agentId,s),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}async _onSubagentCompleted(e){const t=this.subagents.get(e.agentId);if(t&&(t.status="completed",this.subagents.set(e.agentId,t)),this.renderSubagentPanel(),this.updateSubagentWindows(),this.subagentWindows.has(e.agentId)){const i=this.subagentWindows.get(e.agentId);i&&!i.minimized&&(await this.closeSubagentWindow(e.agentId),this.saveSubagentWindowStates())}const s=this.subagentParentMap.get(e.agentId),n=s?this.sessions.get(s):null;this.notificationManager?.notify({urgency:"info",category:"subagent-complete",sessionId:s||t?.sessionId||e.sessionId,sessionName:n?.name||s||e.sessionId,title:"Subagent Completed",message:t?.description||e.description||"Background agent finished"}),setTimeout(()=>{this.subagents.get(e.agentId)?.status==="completed"&&(this.subagentActivity.delete(e.agentId),this.subagentToolResults.delete(e.agentId))},300*1e3),setTimeout(()=>{this.subagents.get(e.agentId)?.status==="completed"&&!this.subagentWindows.has(e.agentId)&&(this.subagents.delete(e.agentId),this.subagentParentMap.delete(e.agentId))},1800*1e3)}_onImageDetected(e){this.openImagePopup(e)}_onTunnelStarted(e){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())}_onTunnelStopped(){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this.closeTunnelQR()}_onTunnelProgress(e){const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const s=document.getElementById("welcomeTunnelBtn");s?.classList.contains("connecting")&&(s.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)}_onTunnelError(e){this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))}_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()}_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()}_onTunnelQrAuthUsed(e){const s=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${s}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})}_onPlanSubagent(e){this.handlePlanSubagentEvent(e)}_onPlanProgress(e){this._planProgressHandler&&this._planProgressHandler({type:"plan:progress",data:e});const t=document.getElementById("planLoadingTitle"),s=document.getElementById("planLoadingHint");if(t&&e.phase){const n={"parallel-analysis":"Running parallel analysis...",subagent:e.detail||"Subagent working...",synthesis:"Synthesizing results...",verification:"Running verification..."};t.textContent=n[e.phase]||e.phase}s&&e.detail&&(s.textContent=e.detail)}_onPlanStarted(e){this.activePlanOrchestratorId=e.orchestratorId,this.planGenerationStopped=!1,this.renderMonitorPlanAgents()}_onPlanCancelled(e){this.activePlanOrchestratorId===e.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}_onPlanCompleted(e){this.activePlanOrchestratorId===e.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}setConnectionStatus(e){this._connectionStatus=e,this._updateConnectionIndicator(),e==="connected"&&this._inputQueue.size>0&&this._drainInputQueues()}_sendInputAsync(e,t){if(!this.isOnline||this._connectionStatus==="disconnected"){this._enqueueInput(e,t);return}this._inputSendChain=this._inputSendChain.then(()=>{fetch(`/api/sessions/${e}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:t}),keepalive:t.length<65536}).then(n=>{n.ok?this.clearPendingHooks(e):this._enqueueInput(e,t)}).catch(()=>{this._enqueueInput(e,t)})})}_enqueueInput(e,t){let n=(this._inputQueue.get(e)||"")+t;n.length>this._inputQueueMaxBytes&&(n=n.slice(n.length-this._inputQueueMaxBytes)),this._inputQueue.set(e,n),this._updateConnectionIndicator()}async _drainInputQueues(){if(this._inputQueue.size===0)return;const e=new Map(this._inputQueue);this._inputQueue.clear(),this._updateConnectionIndicator();for(const[t,s]of e)(await this._apiPost(`/api/sessions/${t}/input`,{input:s}))?.ok||this._enqueueInput(t,s);this._updateConnectionIndicator()}_updateConnectionIndicator(){const e=this.$("connectionIndicator"),t=this.$("connectionDot"),s=this.$("connectionText");if(!e||!t||!s)return;let n=0;for(const a of this._inputQueue.values())n+=a.length;const i=this._connectionStatus,o=n>0;if((i==="connected"||i==="connecting")&&!o){e.style.display="none";return}e.style.display="flex",t.className="connection-dot";const l=a=>a<1024?`${a}B`:`${(a/1024).toFixed(1)}KB`;i==="connected"&&o?(t.classList.add("draining"),s.textContent=`Sending ${l(n)}...`):i==="reconnecting"?(t.classList.add("reconnecting"),s.textContent=o?`Reconnecting (${l(n)} queued)`:"Reconnecting..."):(t.classList.add("offline"),s.textContent=o?`Offline (${l(n)} queued)`:"Offline")}setupOnlineDetection(){window.addEventListener("online",()=>{this.isOnline=!0,this.reconnectAttempts=0,this.connectSSE()}),window.addEventListener("offline",()=>{this.isOnline=!1,this.setConnectionStatus("offline")})}handleInit(e){this._initFallbackTimer&&(clearTimeout(this._initFallbackTimer),this._initFallbackTimer=null);const t=++this._initGeneration;if(e.version){const i=this.$("versionDisplay"),o=this.$("headerVersion");i&&(i.textContent=`v${e.version}`,i.title=`Codeman v${e.version}`),o&&(o.textContent=`v${e.version}`,o.title=`Codeman v${e.version}`)}VoiceInput.cleanup(),this.sessions.clear(),this.ralphStates.clear(),this.terminalBuffers.clear(),this.terminalBufferCache.clear(),this.projectInsights.clear(),this.teams.clear(),this.teamTasks.clear();for(const i of this.idleTimers.values())clearTimeout(i);if(this.idleTimers.clear(),this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.pendingWrites=[],this.writeFrameScheduled=!1,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._localEchoOverlay?.rerender(),this.pendingHooks.clear(),this._parentNameCache&&this._parentNameCache.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),MobileDetection.cleanup(),KeyboardHandler.cleanup(),MobileDetection.init(),KeyboardHandler.init(),this.tabAlerts.clear(),this._shownCompletions&&this._shownCompletions.clear(),this.notificationManager?.titleFlashInterval&&(clearInterval(this.notificationManager.titleFlashInterval),this.notificationManager.titleFlashInterval=null),this.notificationManager?.groupingMap){for(const{timeout:i}of this.notificationManager.groupingMap.values())clearTimeout(i);this.notificationManager.groupingMap.clear()}this.terminalResizeObserver&&(this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=null),this.planLoadingTimer&&(clearInterval(this.planLoadingTimer),this.planLoadingTimer=null),this.timerCountdownInterval&&(clearInterval(this.timerCountdownInterval),this.timerCountdownInterval=null),this.runSummaryAutoRefreshTimer&&(clearInterval(this.runSummaryAutoRefreshTimer),this.runSummaryAutoRefreshTimer=null),e.sessions.forEach(i=>{this.sessions.set(i.id,i),(i.ralphLoop||i.ralphTodos)&&!this.ralphClosedSessions.has(i.id)&&this.ralphStates.set(i.id,{loop:i.ralphLoop||null,todos:i.ralphTodos||[]})}),this.syncSessionOrder(),e.respawnStatus?this.respawnStatus=e.respawnStatus:this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},e.globalStats&&(this.globalStats=e.globalStats),this.totalCost=e.sessions.reduce((i,o)=>i+(o.totalCost||0),0),this.totalCost+=e.scheduledRuns.reduce((i,o)=>i+(o.totalCost||0),0);const s=e.scheduledRuns.find(i=>i.status==="running");if(s&&(this.currentRun=s,this.showTimer()),this.updateCost(),this.renderSessionTabs(),this.sessions.size>0?this.startSystemStatsPolling():this.stopSystemStatsPolling(),this.cleanupAllFloatingWindows(),e.subagents&&(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),e.subagents.forEach(i=>{this.subagents.set(i.agentId,i)}),this.renderSubagentPanel(),this.subagentParentMap.clear(),this.loadSubagentParentMap().then(()=>{for(const[i,o]of this.subagentParentMap){const l=this.subagents.get(i);if(l&&this.sessions.has(o)){l.parentSessionId=o;const a=this.sessions.get(o);a&&(l.parentSessionName=this.getSessionName(a)),this.subagents.set(i,l)}}for(const[i]of this.subagents)this.subagentParentMap.has(i)||this.findParentSessionForSubagent(i);this.restoreSubagentWindowStates()})),t!==this._initGeneration)return;const n=this.activeSessionId;if(this.activeSessionId=null,this.sessionOrder.length>0){let i=n;if(!i||!this.sessions.has(i))try{i=localStorage.getItem("codeman-active-session")}catch{}i&&this.sessions.has(i)?this.selectSession(i):this.selectSession(this.sessionOrder[0])}}async loadState(){try{const t=await(await fetch("/api/status")).json();this.handleInit(t)}catch{}}renderSessionTabs(){this.renderSessionTabsTimeout&&clearTimeout(this.renderSessionTabsTimeout),this.renderSessionTabsTimeout=setTimeout(()=>{this._renderSessionTabsImmediate()},100)}_updateActiveTabImmediate(e){const t=this.$("sessionTabs");if(!t)return;const s=t.querySelectorAll(".session-tab[data-id]");for(const n of s)n.dataset.id===e?n.classList.add("active"):n.classList.remove("active")}_renderSessionTabsImmediate(){const e=this.$("sessionTabs"),t=e.querySelectorAll(".session-tab[data-id]"),s=new Set([...t].map(o=>o.dataset.id)),n=new Set(this.sessions.keys());if(s.size===n.size&&[...s].every(o=>n.has(o)))for(const[o,l]of this.sessions){const a=e.querySelector(`.session-tab[data-id="${o}"]`);if(!a)continue;const r=o===this.activeSessionId,c=l.status||"idle",d=this.getSessionName(l),u=l.taskStats||{running:0,total:0},h=u.running>0;r&&!a.classList.contains("active")?a.classList.add("active"):!r&&a.classList.contains("active")&&a.classList.remove("active");const m=this.tabAlerts.get(o),p=m==="action",g=m==="idle",f=a.classList.contains("tab-alert-action"),S=a.classList.contains("tab-alert-idle");p&&!f?(a.classList.add("tab-alert-action"),a.classList.remove("tab-alert-idle")):g&&!S?(a.classList.add("tab-alert-idle"),a.classList.remove("tab-alert-action")):!m&&(f||S)&&a.classList.remove("tab-alert-action","tab-alert-idle");const w=a.querySelector(".tab-status");w&&!w.classList.contains(c)&&(w.className=`tab-status ${c}`);const b=a.querySelector(".tab-name");b&&b.textContent!==d&&(b.textContent=d);const y=a.querySelector(".tab-badge");if(h)if(y)y.textContent!==String(u.running)&&(y.textContent=u.running);else{this._fullRenderSessionTabs();return}else if(y){this._fullRenderSessionTabs();return}const v=a.querySelector(".tab-subagent-badge"),T=this.minimizedSubagents.get(o)?.size||0,C=v?parseInt(v.querySelector(".subagent-count")?.textContent||"0"):0;if(T!==C){this._fullRenderSessionTabs();return}}else this._fullRenderSessionTabs()}_fullRenderSessionTabs(){const e=this.$("sessionTabs");document.querySelectorAll("body > .subagent-dropdown").forEach(n=>n.remove()),this.cancelHideSubagentDropdown();const t=[];let s=this.sessionOrder;MobileDetection.getDeviceType()==="mobile"&&this.activeSessionId&&(s=[this.activeSessionId,...this.sessionOrder.filter(n=>n!==this.activeSessionId)]);for(const n of s){const i=this.sessions.get(n);if(!i)continue;const o=n===this.activeSessionId,l=i.status||"idle",a=this.getSessionName(i),r=i.mode||"claude",c=i.color||"default",d=i.taskStats||{running:0,total:0},u=d.running>0,h=this.tabAlerts.get(n),m=h==="action"?" tab-alert-action":h==="idle"?" tab-alert-idle":"",p=this.minimizedSubagents.get(n),f=(p?.size||0)>0?this.renderSubagentTabBadge(n,p):"",S=i.workingDir&&i.workingDir.split("/").pop()||"",b=(this._tallTabsEnabled??!1)&&i.name&&S&&S!==a;t.push(`<div class="session-tab ${o?"active":""}${m}" data-id="${n}" data-color="${c}" onclick="app.selectSession('${escapeHtml(n)}')" oncontextmenu="event.preventDefault(); app.startInlineRename('${escapeHtml(n)}')" tabindex="0" role="tab" aria-selected="${o?"true":"false"}" aria-label="${escapeHtml(a)} session" ${i.workingDir?`title="${escapeHtml(i.workingDir)}"`:""}>
|
|
1
|
+
"use strict";const _SSE_HANDLER_MAP=[[SSE_EVENTS.INIT,"_onInit"],[SSE_EVENTS.SESSION_CREATED,"_onSessionCreated"],[SSE_EVENTS.SESSION_UPDATED,"_onSessionUpdated"],[SSE_EVENTS.SESSION_DELETED,"_onSessionDeleted"],[SSE_EVENTS.SESSION_TERMINAL,"_onSessionTerminal"],[SSE_EVENTS.SESSION_NEEDS_REFRESH,"_onSessionNeedsRefresh"],[SSE_EVENTS.SESSION_CLEAR_TERMINAL,"_onSessionClearTerminal"],[SSE_EVENTS.SESSION_COMPLETION,"_onSessionCompletion"],[SSE_EVENTS.SESSION_ERROR,"_onSessionError"],[SSE_EVENTS.SESSION_EXIT,"_onSessionExit"],[SSE_EVENTS.SESSION_IDLE,"_onSessionIdle"],[SSE_EVENTS.SESSION_WORKING,"_onSessionWorking"],[SSE_EVENTS.SESSION_AUTO_CLEAR,"_onSessionAutoClear"],[SSE_EVENTS.SESSION_CLI_INFO,"_onSessionCliInfo"],[SSE_EVENTS.SCHEDULED_CREATED,"_onScheduledCreated"],[SSE_EVENTS.SCHEDULED_UPDATED,"_onScheduledUpdated"],[SSE_EVENTS.SCHEDULED_COMPLETED,"_onScheduledCompleted"],[SSE_EVENTS.SCHEDULED_STOPPED,"_onScheduledStopped"],[SSE_EVENTS.RESPAWN_STARTED,"_onRespawnStarted"],[SSE_EVENTS.RESPAWN_STOPPED,"_onRespawnStopped"],[SSE_EVENTS.RESPAWN_STATE_CHANGED,"_onRespawnStateChanged"],[SSE_EVENTS.RESPAWN_CYCLE_STARTED,"_onRespawnCycleStarted"],[SSE_EVENTS.RESPAWN_BLOCKED,"_onRespawnBlocked"],[SSE_EVENTS.RESPAWN_AUTO_ACCEPT_SENT,"_onRespawnAutoAcceptSent"],[SSE_EVENTS.RESPAWN_DETECTION_UPDATE,"_onRespawnDetectionUpdate"],[SSE_EVENTS.RESPAWN_TIMER_STARTED,"_onRespawnTimerStarted"],[SSE_EVENTS.RESPAWN_TIMER_CANCELLED,"_onRespawnTimerCancelled"],[SSE_EVENTS.RESPAWN_TIMER_COMPLETED,"_onRespawnTimerCompleted"],[SSE_EVENTS.RESPAWN_ERROR,"_onRespawnError"],[SSE_EVENTS.RESPAWN_ACTION_LOG,"_onRespawnActionLog"],[SSE_EVENTS.TASK_CREATED,"_onTaskCreated"],[SSE_EVENTS.TASK_COMPLETED,"_onTaskCompleted"],[SSE_EVENTS.TASK_FAILED,"_onTaskFailed"],[SSE_EVENTS.TASK_UPDATED,"_onTaskUpdated"],[SSE_EVENTS.MUX_CREATED,"_onMuxCreated"],[SSE_EVENTS.MUX_KILLED,"_onMuxKilled"],[SSE_EVENTS.MUX_DIED,"_onMuxDied"],[SSE_EVENTS.MUX_STATS_UPDATED,"_onMuxStatsUpdated"],[SSE_EVENTS.SESSION_RALPH_LOOP_UPDATE,"_onRalphLoopUpdate"],[SSE_EVENTS.SESSION_RALPH_TODO_UPDATE,"_onRalphTodoUpdate"],[SSE_EVENTS.SESSION_RALPH_COMPLETION_DETECTED,"_onRalphCompletionDetected"],[SSE_EVENTS.SESSION_RALPH_STATUS_UPDATE,"_onRalphStatusUpdate"],[SSE_EVENTS.SESSION_CIRCUIT_BREAKER_UPDATE,"_onCircuitBreakerUpdate"],[SSE_EVENTS.SESSION_EXIT_GATE_MET,"_onExitGateMet"],[SSE_EVENTS.SESSION_BASH_TOOL_START,"_onBashToolStart"],[SSE_EVENTS.SESSION_BASH_TOOL_END,"_onBashToolEnd"],[SSE_EVENTS.SESSION_BASH_TOOLS_UPDATE,"_onBashToolsUpdate"],[SSE_EVENTS.HOOK_IDLE_PROMPT,"_onHookIdlePrompt"],[SSE_EVENTS.HOOK_PERMISSION_PROMPT,"_onHookPermissionPrompt"],[SSE_EVENTS.HOOK_ELICITATION_DIALOG,"_onHookElicitationDialog"],[SSE_EVENTS.HOOK_STOP,"_onHookStop"],[SSE_EVENTS.HOOK_TEAMMATE_IDLE,"_onHookTeammateIdle"],[SSE_EVENTS.HOOK_TASK_COMPLETED,"_onHookTaskCompleted"],[SSE_EVENTS.SUBAGENT_DISCOVERED,"_onSubagentDiscovered"],[SSE_EVENTS.SUBAGENT_UPDATED,"_onSubagentUpdated"],[SSE_EVENTS.SUBAGENT_TOOL_CALL,"_onSubagentToolCall"],[SSE_EVENTS.SUBAGENT_PROGRESS,"_onSubagentProgress"],[SSE_EVENTS.SUBAGENT_MESSAGE,"_onSubagentMessage"],[SSE_EVENTS.SUBAGENT_TOOL_RESULT,"_onSubagentToolResult"],[SSE_EVENTS.SUBAGENT_COMPLETED,"_onSubagentCompleted"],[SSE_EVENTS.IMAGE_DETECTED,"_onImageDetected"],[SSE_EVENTS.TUNNEL_STARTED,"_onTunnelStarted"],[SSE_EVENTS.TUNNEL_STOPPED,"_onTunnelStopped"],[SSE_EVENTS.TUNNEL_PROGRESS,"_onTunnelProgress"],[SSE_EVENTS.TUNNEL_ERROR,"_onTunnelError"],[SSE_EVENTS.TUNNEL_QR_ROTATED,"_onTunnelQrRotated"],[SSE_EVENTS.TUNNEL_QR_REGENERATED,"_onTunnelQrRegenerated"],[SSE_EVENTS.TUNNEL_QR_AUTH_USED,"_onTunnelQrAuthUsed"],[SSE_EVENTS.PLAN_SUBAGENT,"_onPlanSubagent"],[SSE_EVENTS.PLAN_PROGRESS,"_onPlanProgress"],[SSE_EVENTS.PLAN_STARTED,"_onPlanStarted"],[SSE_EVENTS.PLAN_CANCELLED,"_onPlanCancelled"],[SSE_EVENTS.PLAN_COMPLETED,"_onPlanCompleted"]];class CodemanApp{constructor(){this.sessions=new Map,this._shortIdCache=new Map,this.sessionOrder=[],this.draggedTabId=null,this.cases=[],this.currentRun=null,this.totalTokens=0,this.globalStats=null,this.eventSource=null,this.terminal=null,this.fitAddon=null,this.activeSessionId=null,this._initGeneration=0,this._initFallbackTimer=null,this._selectGeneration=0,this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},this.timerCountdownInterval=null,this.terminalBuffers=new Map,this.editingSessionId=null,this.pendingCloseSessionId=null,this.muxSessions=[],this.ralphStates=new Map,this.subagents=new Map,this.subagentActivity=new Map,this.subagentToolResults=new Map,this.activeSubagentId=null,this.subagentPanelVisible=!1,this.subagentWindows=new Map,this.subagentWindowZIndex=ZINDEX_SUBAGENT_BASE,this.minimizedSubagents=new Map,this._subagentHideTimeout=null,this.subagentParentMap=new Map,this.teams=new Map,this.teamTasks=new Map,this.teammateMap=new Map,this.teammatePanesByName=new Map,this.teammateTerminals=new Map,this.terminalBufferCache=new Map,this.ralphStatePanelCollapsed=!0,this.ralphClosedSessions=new Set,this.planSubagents=new Map,this.planSubagentWindowZIndex=ZINDEX_PLAN_SUBAGENT_BASE,this.planGenerationStopped=!1,this.planAgentsMinimized=!1,this.wizardDragState=null,this.wizardDragListeners=null,this.wizardPosition=null,this.projectInsights=new Map,this.logViewerWindows=new Map,this.logViewerWindowZIndex=ZINDEX_LOG_VIEWER_BASE,this.projectInsightsPanelVisible=!1,this.currentSessionWorkingDir=null,this.imagePopups=new Map,this.imagePopupZIndex=ZINDEX_IMAGE_POPUP_BASE,this.tabAlerts=new Map,this.pendingHooks=new Map,this.pendingWrites=[],this.writeFrameScheduled=!1,this._wasAtBottomBeforeWrite=!0,this.syncWaitTimeout=null,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.flickerFilterTimeout=null,this.renderSessionTabsTimeout=null,this.renderRalphStatePanelTimeout=null,this.renderTaskPanelTimeout=null,this.renderMuxSessionsTimeout=null,this.systemStatsInterval=null,this.sseReconnectTimeout=null,this._sseListenerCleanup=null,this.reconnectAttempts=0,this.maxReconnectAttempts=10,this.isOnline=navigator.onLine,this._inputQueue=new Map,this._inputQueueMaxBytes=64*1024,this._connectionStatus="connected",this._inputSendChain=Promise.resolve(),this._localEchoOverlay=null,this._localEchoEnabled=!1,this._restoringFlushedState=!1,this.activeFocusTrap=null,this.notificationManager=new NotificationManager(this),this.idleTimers=new Map,this._elemCache={},this.init()}$(e){return this._elemCache[e]||(this._elemCache[e]=document.getElementById(e)),this._elemCache[e]}formatTokens(e){if(e>=1e6){const t=e/1e6;return t>=10?`${t.toFixed(1)}m`:`${t.toFixed(2)}m`}else if(e>=1e3){const t=e/1e3;return t>=100?`${t.toFixed(0)}k`:`${t.toFixed(1)}k`}return String(e)}estimateCost(e,t){const s=e/1e6*15,n=t/1e6*75;return s+n}setPendingHook(e,t){this.pendingHooks.has(e)||this.pendingHooks.set(e,new Set),this.pendingHooks.get(e).add(t),this.updateTabAlertFromHooks(e)}clearPendingHooks(e,t=null){const s=this.pendingHooks.get(e);s&&(t?s.delete(t):s.clear(),s.size===0&&this.pendingHooks.delete(e),this.updateTabAlertFromHooks(e))}updateTabAlertFromHooks(e){const t=this.pendingHooks.get(e);!t||t.size===0?this.tabAlerts.delete(e):t.has("permission_prompt")||t.has("elicitation_dialog")?this.tabAlerts.set(e,"action"):t.has("idle_prompt")&&this.tabAlerts.set(e,"idle"),this.renderSessionTabs()}init(){MobileDetection.init(),KeyboardHandler.init(),SwipeHandler.init(),VoiceInput.init(),KeyboardAccessoryBar.init(),this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility(),document.documentElement.classList.remove("mobile-init"),requestAnimationFrame(()=>{this.initTerminal(),this.loadFontSize(),this.connectSSE(),this._initFallbackTimer=setTimeout(()=>{this._initGeneration===0&&this.loadState()},3e3)}),this.registerServiceWorker();const e=fetch("/api/settings").then(t=>t.ok?t.json():null).catch(()=>null);if(this.loadQuickStartCases(null,e),this._initRunMode(),this.setupEventListeners(),MobileDetection.isTouchDevice()){const t=s=>{s&&s.addEventListener("touchstart",n=>{if(!KeyboardHandler.keyboardVisible)return;const i=n.target.closest("button");i&&(n.preventDefault(),i.click(),typeof app<"u"&&app.terminal&&app.terminal.focus())},{passive:!1})};t(document.querySelector(".toolbar")),t(document.querySelector(".welcome-overlay"))}this.setupOnlineDetection(),this.loadAppSettingsFromServer(e).then(()=>{this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility()}),document.body.classList.add("app-loaded")}initTerminal(){const e=parseInt(localStorage.getItem("codeman-scrollback"))||DEFAULT_SCROLLBACK;if(this.terminal=new Terminal({theme:{background:"#0d0d0d",foreground:"#e0e0e0",cursor:"#e0e0e0",cursorAccent:"#0d0d0d",selection:"rgba(255, 255, 255, 0.3)",black:"#0d0d0d",red:"#ff6b6b",green:"#51cf66",yellow:"#ffd43b",blue:"#339af0",magenta:"#cc5de8",cyan:"#22b8cf",white:"#e0e0e0",brightBlack:"#495057",brightRed:"#ff8787",brightGreen:"#69db7c",brightYellow:"#ffe066",brightBlue:"#5c7cfa",brightMagenta:"#da77f2",brightCyan:"#66d9e8",brightWhite:"#ffffff"},fontFamily:'"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, monospace',fontSize:MobileDetection.getDeviceType()==="mobile"?10:14,lineHeight:1.2,cursorBlink:!1,cursorStyle:"block",scrollback:e,allowTransparency:!0,allowProposedApi:!0}),this.fitAddon=new FitAddon.FitAddon,this.terminal.loadAddon(this.fitAddon),typeof Unicode11Addon<"u")try{const r=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(r),this.terminal.unicode.activeVersion="11"}catch{}const t=document.getElementById("terminalContainer");if(this.terminal.open(t),this._webglAddon=null,typeof WebglAddon<"u")try{this._webglAddon=new WebglAddon.WebglAddon,this._webglAddon.onContextLoss(()=>{this._webglAddon.dispose(),this._webglAddon=null}),this.terminal.loadAddon(this._webglAddon)}catch{}if(this._localEchoOverlay=new LocalEchoOverlay(this.terminal),MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this.registerFilePathLinkProvider(),t.addEventListener("wheel",r=>{r.preventDefault();const c=Math.round(r.deltaY/25)||(r.deltaY>0?1:-1);this.terminal.scrollLines(c)},{passive:!1}),!(MobileDetection.isTouchDevice()&&window.innerWidth<1024)){let r=0,c=0,d=0,u=0,h=null,m=!1;const p=t.querySelector(".xterm-viewport"),g=f=>{if(!p)return;const S=u?(f-u)/16.67:1;u=f,m?(c!==0&&(p.scrollTop+=c,c=0),h=requestAnimationFrame(g)):Math.abs(d)>.1?(p.scrollTop+=d*S,d*=.94,h=requestAnimationFrame(g)):(h=null,d=0)};t.addEventListener("touchstart",f=>{f.touches.length===1&&(r=f.touches[0].clientY,c=0,d=0,m=!0,u=0,h||(h=requestAnimationFrame(g)))},{passive:!0}),t.addEventListener("touchmove",f=>{if(f.touches.length===1&&m){const S=f.touches[0].clientY,w=r-S;c+=w,d=w*1.2,r=S}},{passive:!0}),t.addEventListener("touchend",()=>{m=!1},{passive:!0}),t.addEventListener("touchcancel",()=>{m=!1,d=0},{passive:!0})}this.showWelcome(),this._resizeTimeout=null,this._lastResizeDims=null;const i=40,o=10,l=()=>{this._resizeTimeout||(this._resizeTimeout=setTimeout(()=>{if(this._resizeTimeout=null,this.fitAddon){this.fitAddon.fit();const r=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;if(this.activeSessionId&&!r){const c=this.fitAddon.proposeDimensions(),d=c?Math.max(c.cols,i):i,u=c?Math.max(c.rows,o):o;(!this._lastResizeDims||d!==this._lastResizeDims.cols||u!==this._lastResizeDims.rows)&&(this._lastResizeDims={cols:d,rows:u},fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:d,rows:u})}).catch(()=>{}))}}this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},100))};window.addEventListener("resize",l),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(l),this.terminalResizeObserver.observe(t),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const a=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const r=this._pendingInput,c=this.activeSessionId;this._pendingInput="",this._sendInputAsync(c,r)}};this.terminal.onData(r=>{if(this.activeSessionId){if(/^\x1b\[[\?>=]?[\d;]*[cnR]$/.test(r))return;if(this._localEchoEnabled){if(r==="\x7F"){if(this._localEchoOverlay?.removeChar()==="flushed"){const{count:u,text:h}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(u===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,u),this._flushedTexts?.set(this.activeSessionId,h))),this._pendingInput+=r,a()}return}if(/^[\r\n]+$/.test(r)){const d=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),d&&(this._pendingInput+=d,a()),setTimeout(()=>{this._pendingInput+="\r",a()},80);return}if(r.length>1&&r.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(r);return}if(r.charCodeAt(0)<32){if(r.length>1&&r.charCodeAt(0)===27){this._pendingInput+=r,a();return}if(this._restoringFlushedState){this._pendingInput+=r,a();return}if(r===" "){const u=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),u&&(this._pendingInput+=u),this._pendingInput+=r,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let h="";try{const p=this._localEchoOverlay?.findPrompt?.();if(p){const g=this.terminal.buffer.active,f=g.getLine(g.viewportY+p.row);f&&(h=f.translateToString(!0).slice(p.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=h,a(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const m=this;this._tabCompletionFallback=setTimeout(()=>{if(m._tabCompletionFallback=null,!m._tabCompletionSessionId||m._tabCompletionSessionId!==m.activeSessionId)return;const p=m._localEchoOverlay;!p||p.pendingText||m.terminal.write("",()=>{if(!m._tabCompletionSessionId)return;p.resetBufferDetection();const g=p.detectBufferText();g&&g!==m._tabCompletionBaseText&&(m._tabCompletionSessionId=null,m._tabCompletionRetries=0,m._tabCompletionBaseText=null,p.rerender())})},300);return}const d=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),d&&(this._pendingInput+=d),this._pendingInput+=r,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}if(r.length===1&&r.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(r);return}}if(this._pendingInput+=r,r.charCodeAt(0)<32||r.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}const c=performance.now();c-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=c,a()):(this._lastKeystrokeTime=c,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(a,0)))}})}registerFilePathLinkProvider(){const e=this;let t=-1;this.terminal.registerLinkProvider({provideLinks(s,n){s!==t&&(t=s);const o=e.terminal.buffer.active.getLine(s);if(!o){n(void 0);return}const l=o.translateToString(!0);if(!l||!l.includes("/")){n(void 0);return}const a=[],r=/(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]*\s+)*(\/[^\s"'<>|;&\n\x00-\x1f]+)/g,c=/(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\n\x00-\x1f]*\.(?:log|txt|json|md|yaml|yml|csv|xml|sh|py|ts|js))\b/g,d=/Bash\([^)]*?(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\)\n\x00-\x1f]+)/g,u=(m,p)=>{const g=l.indexOf(m,p);g!==-1&&(a.some(f=>f.range.start.x===g+1)||a.push({text:m,range:{start:{x:g+1,y:s},end:{x:g+m.length+1,y:s}},decorations:{pointerCursor:!0,underline:!0},activate(f,S){e.openLogViewerWindow(S,e.activeSessionId)}}))};let h;for(r.lastIndex=0;(h=r.exec(l))!==null;)u(h[2],h.index);for(c.lastIndex=0;(h=c.exec(l))!==null;)u(h[1],h.index);for(d.lastIndex=0;(h=d.exec(l))!==null;)u(h[1],h.index);a.length>0,n(a.length>0?a:void 0)}})}showWelcome(){const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus())}hideWelcome(){const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const t=document.getElementById("welcomeQr");t&&(clearTimeout(this._welcomeQrShrinkTimer),t.classList.remove("expanded"))}isTerminalAtBottom(){if(!this.terminal)return!0;const e=this.terminal.buffer.active;return e.viewportY>=e.baseY-2}batchTerminalWrite(e){if(this._isLoadingBuffer){this._loadBufferQueue&&this._loadBufferQueue.push(e);return}this.writeFrameScheduled||(this._wasAtBottomBeforeWrite=this.isTerminalAtBottom());const s=(this.activeSessionId?this.sessions.get(this.activeSessionId):null)?.flickerFilterEnabled??!1;if(/\x1b\[\d{1,2}A/.test(e)||this.flickerFilterActive&&!s){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(s){if(e.includes("\x1B[2J")||e.includes("\x1B[H\x1B[J")||e.includes("\x1B[H")&&e.includes("\x1B[?25l")){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(this.flickerFilterActive){this.flickerFilterBuffer+=e;return}}this.pendingWrites.push(e),this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{if(this.pendingWrites.length>0&&this.terminal){const i=this.pendingWrites.join(""),o=i.includes(DEC_SYNC_START),l=i.includes(DEC_SYNC_END);if(o&&!l){this.syncWaitTimeout||(this.syncWaitTimeout=setTimeout(()=>{this.syncWaitTimeout=null,this.flushPendingWrites()},50)),this.writeFrameScheduled=!1;return}this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.flushPendingWrites()}this.writeFrameScheduled=!1}))}flushFlickerBuffer(){this.flickerFilterBuffer&&(this.pendingWrites.push(this.flickerFilterBuffer),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1})))}_updateLocalEchoState(){const e=this.loadAppSettingsFromStorage(),t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,n=!!((e.localEchoEnabled??MobileDetection.isTouchDevice())&&t);this._localEchoEnabled&&!n&&this._localEchoOverlay?.clear(),this._localEchoEnabled=n,this._localEchoOverlay&&t&&(t.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:i=>{try{const o=i.buffer.active,l=o.cursorY,a=o.getLine(o.viewportY+l);if(!a)return null;const c=a.translateToString(!0).indexOf("\u2503");return c>=0?{row:l,col:c}:null}catch{return null}}}):this._localEchoOverlay.setPrompt({type:"character",char:"\u276F",offset:2}))}flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=extractSyncSegments(this.pendingWrites.join(""));this.pendingWrites=[];for(const t of e)if(t){const s=t.startsWith(DEC_SYNC_START)?t.slice(DEC_SYNC_START.length):t;s&&this.terminal.write(s)}if(this._wasAtBottomBeforeWrite&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const t=this._localEchoOverlay,s=this;this.terminal.write("",()=>{if(!s._tabCompletionSessionId)return;t.resetBufferDetection();const n=t.detectBufferText();n?n===s._tabCompletionBaseText?(t.undoDetection(),s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0)):(s._tabCompletionSessionId=null,s._tabCompletionRetries=0,s._tabCompletionBaseText=null,s._tabCompletionFallback&&(clearTimeout(s._tabCompletionFallback),s._tabCompletionFallback=null),t.rerender()):(s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0))})}}chunkedTerminalWrite(e,t=TERMINAL_CHUNK_SIZE){return new Promise(s=>{if(!e||e.length===0){this._finishBufferLoad(),s();return}this._isLoadingBuffer=!0,this._loadBufferQueue=[];const n=e.replace(DEC_SYNC_STRIP_RE,""),i=()=>{this._finishBufferLoad(),s()};if(n.length<=t){this.terminal.write(n),i();return}let o=0;const l=()=>{if(o>=n.length){requestAnimationFrame(i);return}const a=n.slice(o,o+t);this.terminal.write(a),o+=t,requestAnimationFrame(l)};requestAnimationFrame(l)})}_finishBufferLoad(){const e=this._loadBufferQueue;if(this._isLoadingBuffer=!1,this._loadBufferQueue=null,e&&e.length>0)for(const t of e)this.batchTerminalWrite(t)}setupEventListeners(){document.addEventListener("keydown",t=>{t.key==="Escape"&&(this.closeAllPanels(),this.closeHelp()),(t.ctrlKey||t.metaKey)&&(t.key==="?"||t.key==="/")&&(t.preventDefault(),this.showHelp()),(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.quickStart()),(t.ctrlKey||t.metaKey)&&t.key==="w"&&(t.preventDefault(),this.killActiveSession()),(t.ctrlKey||t.metaKey)&&t.key==="Tab"&&(t.preventDefault(),this.nextSession()),(t.ctrlKey||t.metaKey)&&t.key==="k"&&(t.preventDefault(),this.killAllSessions()),(t.ctrlKey||t.metaKey)&&t.key==="l"&&(t.preventDefault(),this.clearTerminal()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="R"&&(t.preventDefault(),this.restoreTerminalSize()),(t.ctrlKey||t.metaKey)&&(t.key==="="||t.key==="+")&&(t.preventDefault(),this.increaseFontSize()),(t.ctrlKey||t.metaKey)&&t.key==="-"&&(t.preventDefault(),this.decreaseFontSize()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="V"&&(t.preventDefault(),VoiceInput.toggle())},!0);const e=this.$("headerTokens");e&&!e._statsHandlerAttached&&(e.classList.add("clickable"),e._statsHandlerAttached=!0,e.addEventListener("click",()=>this.openTokenStats())),this.setupColorPicker()}connectSSE(){if(!navigator.onLine){this.setConnectionStatus("offline");return}this.sseReconnectTimeout&&(clearTimeout(this.sseReconnectTimeout),this.sseReconnectTimeout=null),this._sseListenerCleanup&&(this._sseListenerCleanup(),this._sseListenerCleanup=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.reconnectAttempts===0?this.setConnectionStatus("connecting"):this.setConnectionStatus("reconnecting"),this.eventSource=new EventSource("/api/events");const e=[],t=(s,n)=>{this.eventSource.addEventListener(s,n),e.push({event:s,handler:n})};if(this._sseListenerCleanup=()=>{for(const{event:s,handler:n}of e)this.eventSource&&this.eventSource.removeEventListener(s,n);e.length=0},this.eventSource.onopen=()=>{this.reconnectAttempts=0,this.setConnectionStatus("connected")},this.eventSource.onerror=()=>{this.reconnectAttempts++,this.reconnectAttempts>=this.maxReconnectAttempts?this.setConnectionStatus("disconnected"):this.setConnectionStatus("reconnecting"),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.sseReconnectTimeout&&clearTimeout(this.sseReconnectTimeout);const s=this.reconnectAttempts<=1?200:Math.min(500*Math.pow(2,this.reconnectAttempts-2),3e4);this.sseReconnectTimeout=setTimeout(()=>this.connectSSE(),s)},!this._sseHandlerWrappers){this._sseHandlerWrappers=new Map;for(const[s,n]of _SSE_HANDLER_MAP){const i=this[n];this._sseHandlerWrappers.set(s,o=>{try{i.call(this,o.data?JSON.parse(o.data):{})}catch{}})}}for(const[s]of _SSE_HANDLER_MAP)t(s,this._sseHandlerWrappers.get(s))}_onInit(e){this.handleInit(e)}_onSessionCreated(e){this.sessions.set(e.id,e),this.sessionOrder.includes(e.id)||(this.sessionOrder.push(e.id),this.saveSessionOrder()),this.renderSessionTabs(),this.updateCost(),this.sessions.size===1&&this.startSystemStatsPolling()}_onSessionUpdated(e){const t=e.session||e,s=this.sessions.get(t.id),n=t.claudeSessionId&&(!s||!s.claudeSessionId);this.sessions.set(t.id,t),this.renderSessionTabs(),this.updateCost(),t.id===this.activeSessionId&&t.tokens&&this.updateRespawnTokens(t.tokens),this.updateSubagentParentNames(t.id),n&&(this.recheckOrphanSubagents(),requestAnimationFrame(()=>{this.updateConnectionLines()}))}_onSessionDeleted(e){if(this._cleanupSessionData(e.id),this.activeSessionId===e.id){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome()}this.renderSessionTabs(),this.renderRalphStatePanel(),this.renderProjectInsightsPanel(),this.sessions.size===0&&this.stopSystemStatsPolling()}_onSessionTerminal(e){e.id===this.activeSessionId&&this.batchTerminalWrite(e.data)}async _onSessionNeedsRefresh(){if(!(!this.activeSessionId||!this.terminal))try{const s=await(await fetch(`/api/sessions/${this.activeSessionId}/terminal?tail=262144`)).json();s.terminalBuffer&&(this.terminal.clear(),this.terminal.reset(),await this.chunkedTerminalWrite(s.terminalBuffer),this.terminal.scrollToBottom(),this._localEchoOverlay?.rerender(),this.activeSessionId&&this.sendResize(this.activeSessionId))}catch{}}async _onSessionClearTerminal(e){if(e.id===this.activeSessionId)try{const s=await(await fetch(`/api/sessions/${e.id}/terminal`)).json();if(this.terminal.clear(),this.terminal.reset(),s.terminalBuffer){const n=s.terminalBuffer.replace(DEC_SYNC_STRIP_RE,"");await this.chunkedTerminalWrite(n)}this.sendResize(e.id),this._localEchoOverlay?.rerender()}catch{}}_onSessionCompletion(e){this.totalCost+=e.cost||0,this.updateCost(),e.id===this.activeSessionId&&(this.terminal.writeln(""),this.terminal.writeln(`\x1B[1;32m Done (Cost: $${(e.cost||0).toFixed(4)})\x1B[0m`))}_onSessionError(e){e.id===this.activeSessionId&&this.terminal.writeln(`\x1B[1;31m Error: ${e.error}\x1B[0m`);const t=this.sessions.get(e.id);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:e.id,sessionName:t?.name||this.getShortId(e.id),title:"Session Error",message:e.error||"Unknown error"})}_onSessionExit(e){const t=this.sessions.get(e.id);t&&(t.status="stopped",this.renderSessionTabs(),e.id===this.activeSessionId&&this._updateLocalEchoState()),e.code&&e.code!==0&&this.notificationManager?.notify({urgency:"critical",category:"session-crash",sessionId:e.id,sessionName:t?.name||this.getShortId(e.id),title:"Session Crashed",message:`Exited with code ${e.code}`})}_onSessionIdle(e){const t=this.sessions.get(e.id);if(t&&(t.status="idle",this.renderSessionTabs(),this.sendPendingCtrlL(e.id),e.id===this.activeSessionId&&this._updateLocalEchoState()),!this.respawnStatus[e.id]?.enabled){const s=this.notificationManager?.preferences?.stuckThresholdMs||6e5;clearTimeout(this.idleTimers.get(e.id)),this.idleTimers.set(e.id,setTimeout(()=>{const n=this.sessions.get(e.id);this.notificationManager?.notify({urgency:"warning",category:"session-stuck",sessionId:e.id,sessionName:n?.name||this.getShortId(e.id),title:"Session Idle",message:`Idle for ${Math.round(s/6e4)}+ minutes`}),this.idleTimers.delete(e.id)},s))}}_onSessionWorking(e){const t=this.sessions.get(e.id);t&&(t.status="busy",this.pendingHooks.has(e.id)||this.tabAlerts.delete(e.id),this.renderSessionTabs(),this.sendPendingCtrlL(e.id),e.id===this.activeSessionId&&this._updateLocalEchoState());const s=this.idleTimers.get(e.id);s&&(clearTimeout(s),this.idleTimers.delete(e.id))}_onSessionAutoClear(e){e.sessionId===this.activeSessionId&&(this.showToast(`Auto-cleared at ${e.tokens.toLocaleString()} tokens`,"info"),this.updateRespawnTokens(0));const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-clear",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Auto-Cleared",message:`Context reset at ${(e.tokens||0).toLocaleString()} tokens`})}_onSessionCliInfo(e){const t=this.sessions.get(e.sessionId);t&&(e.version&&(t.cliVersion=e.version),e.model&&(t.cliModel=e.model),e.accountType&&(t.cliAccountType=e.accountType),e.latestVersion&&(t.cliLatestVersion=e.latestVersion)),e.sessionId===this.activeSessionId&&this.updateCliInfoDisplay()}_onScheduledCreated(e){this.currentRun=e,this.showTimer()}_onScheduledUpdated(e){this.currentRun=e,this.updateTimer()}_onScheduledCompleted(e){this.currentRun=e,this.hideTimer(),this.showToast("Scheduled run completed!","success")}_onScheduledStopped(){this.currentRun=null,this.hideTimer()}_onRespawnStarted(e){this.respawnStatus[e.sessionId]=e.status,e.sessionId===this.activeSessionId&&this.showRespawnBanner()}_onRespawnStopped(e){delete this.respawnStatus[e.sessionId],e.sessionId===this.activeSessionId&&this.hideRespawnBanner()}_onRespawnStateChanged(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].state=e.state),e.sessionId===this.activeSessionId&&this.updateRespawnBanner(e.state)}_onRespawnCycleStarted(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].cycleCount=e.cycleNumber),e.sessionId===this.activeSessionId&&(document.getElementById("respawnCycleCount").textContent=e.cycleNumber)}_onRespawnBlocked(e){const t=this.sessions.get(e.sessionId),n={circuit_breaker_open:"Circuit Breaker Open",exit_signal:"Exit Signal Detected",status_blocked:"Claude Reported BLOCKED"}[e.reason]||"Respawn Blocked";if(this.notificationManager?.notify({urgency:"critical",category:"respawn-blocked",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:n,message:e.details}),e.sessionId===this.activeSessionId){const i=document.getElementById("respawnStateLabel");i&&(i.textContent=n,i.classList.add("respawn-blocked"))}}_onRespawnAutoAcceptSent(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-accept",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Plan Accepted",message:`Accepted plan mode for ${t?.name||"session"}`})}_onRespawnDetectionUpdate(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].detection=e.detection),e.sessionId===this.activeSessionId&&this.updateDetectionDisplay(e.detection)}_onRespawnTimerStarted(e){if(e.endAt&&(this.respawnTimers[e.sessionId]={endAt:e.endAt,startedAt:e.startedAt,durationMinutes:e.durationMinutes},e.sessionId===this.activeSessionId&&this.showRespawnTimer()),e.timer){const{sessionId:t,timer:s}=e;this.respawnCountdownTimers[t]||(this.respawnCountdownTimers[t]={}),this.respawnCountdownTimers[t][s.name]={endsAt:s.endsAt,totalMs:s.durationMs,reason:s.reason},t===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.startCountdownInterval())}}_onRespawnTimerCancelled(e){const{sessionId:t,timerName:s}=e;this.respawnCountdownTimers[t]&&delete this.respawnCountdownTimers[t][s],t===this.activeSessionId&&this.updateCountdownTimerDisplay()}_onRespawnTimerCompleted(e){const{sessionId:t,timerName:s}=e;this.respawnCountdownTimers[t]&&delete this.respawnCountdownTimers[t][s],t===this.activeSessionId&&this.updateCountdownTimerDisplay()}_onRespawnError(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Respawn Error",message:e.error||e.message||"Respawn encountered an error"})}_onRespawnActionLog(e){const{sessionId:t,action:s}=e;this.addActionLogEntry(t,s),t===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.updateActionLogDisplay())}_onTaskCreated(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskCompleted(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskFailed(e){this.renderSessionTabs(),e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onTaskUpdated(e){e.sessionId===this.activeSessionId&&this.renderTaskPanel()}_onMuxCreated(e){this.muxSessions.push(e),this.renderMuxSessions()}_onMuxKilled(e){this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e.sessionId),this.renderMuxSessions()}_onMuxDied(e){this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e.sessionId),this.renderMuxSessions(),this.showToast("Mux session died: "+this.getShortId(e.sessionId),"warning")}_onMuxStatsUpdated(e){this.muxSessions=e,document.getElementById("monitorPanel").classList.contains("open")&&this.renderMuxSessions()}_onRalphLoopUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{loop:e.state})}_onRalphTodoUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{todos:e.todos})}_onRalphCompletionDetected(e){if(this.ralphClosedSessions.has(e.sessionId))return;const t=`${e.sessionId}:${e.phrase}`;if(this._shownCompletions?.has(t))return;this._shownCompletions||(this._shownCompletions=new Set),this._shownCompletions.add(t),setTimeout(()=>this._shownCompletions?.delete(t),3e4);const s=this.ralphStates.get(e.sessionId)||{};s.loop&&(s.loop.active=!1,this.updateRalphState(e.sessionId,s));const n=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"ralph-complete",sessionId:e.sessionId,sessionName:n?.name||this.getShortId(e.sessionId),title:"Loop Complete",message:`Completion: ${e.phrase||"unknown"}`})}_onRalphStatusUpdate(e){this.ralphClosedSessions.has(e.sessionId)||this.updateRalphState(e.sessionId,{statusBlock:e.block})}_onCircuitBreakerUpdate(e){if(!this.ralphClosedSessions.has(e.sessionId)&&(this.updateRalphState(e.sessionId,{circuitBreaker:e.status}),e.status.state==="OPEN")){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"critical",category:"circuit-breaker",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Circuit Breaker Open",message:e.status.reason||"Loop stuck - no progress detected"})}}_onExitGateMet(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"exit-gate",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Exit Gate Met",message:`Loop ready to exit (indicators: ${e.completionIndicators})`})}_onBashToolStart(e){this.handleBashToolStart(e.sessionId,e.tool)}_onBashToolEnd(e){this.handleBashToolEnd(e.sessionId,e.tool)}_onBashToolsUpdate(e){this.handleBashToolsUpdate(e.sessionId,e.tools)}_onHookIdlePrompt(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this.notificationManager?.notify({urgency:"warning",category:"hook-idle",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Waiting for Input",message:e.message||"Claude is idle and waiting for a prompt"})}_onHookPermissionPrompt(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const s=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this.notificationManager?.notify({urgency:"critical",category:"hook-permission",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Permission Required",message:s||"Claude needs tool approval to continue"})}_onHookElicitationDialog(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this.notificationManager?.notify({urgency:"critical",category:"hook-elicitation",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Question Asked",message:e.question||"Claude is asking a question and waiting for your answer"})}_onHookStop(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.clearPendingHooks(e.sessionId),this.notificationManager?.notify({urgency:"info",category:"hook-stop",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Response Complete",message:e.reason||"Claude has finished responding"})}_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"hook-teammate-idle",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Teammate Idle",message:`A teammate is idle in ${t?.name||e.sessionId}`})}_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"hook-task-completed",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Task Completed",message:`A team task completed in ${t?.name||e.sessionId}`})}_onSubagentDiscovered(e){if(this.subagents.set(e.agentId,e),this.subagentActivity.set(e.agentId,[]),this.subagentToolResults.delete(e.agentId),this.subagentWindows.has(e.agentId)&&this.forceCloseSubagentWindow(e.agentId),this.renderSubagentPanel(),this.findParentSessionForSubagent(e.agentId),e.status==="active"){const n=this.subagents.get(e.agentId);n?.sessionId&&Array.from(this.sessions.values()).some(o=>o.claudeSessionId===n.sessionId)&&this.openSubagentWindow(e.agentId)}requestAnimationFrame(()=>{this.updateConnectionLines()});const t=this.subagentParentMap.get(e.agentId),s=t?this.sessions.get(t):null;this.notificationManager?.notify({urgency:"info",category:"subagent-spawn",sessionId:t||e.sessionId,sessionName:s?.name||t||e.sessionId,title:"Subagent Spawned",message:e.description||"New background agent started"})}_onSubagentUpdated(e){const t=this.subagents.get(e.agentId);t?(Object.assign(t,e),this.subagents.set(e.agentId,t)):this.subagents.set(e.agentId,e),this.renderSubagentPanel(),this.subagentWindows.has(e.agentId)&&(this.renderSubagentWindowContent(e.agentId),this.updateSubagentWindowHeader(e.agentId))}_onSubagentToolCall(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"tool",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.renderSubagentPanel(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentProgress(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"progress",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentMessage(e){const t=this.subagentActivity.get(e.agentId)||[];t.push({type:"message",...e}),t.length>50&&t.shift(),this.subagentActivity.set(e.agentId,t),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}_onSubagentToolResult(e){this.subagentToolResults.has(e.agentId)||this.subagentToolResults.set(e.agentId,new Map);const t=this.subagentToolResults.get(e.agentId);if(t.set(e.toolUseId,e),t.size>50){const n=t.keys().next().value;t.delete(n)}const s=this.subagentActivity.get(e.agentId)||[];s.push({type:"tool_result",...e}),s.length>50&&s.shift(),this.subagentActivity.set(e.agentId,s),this.activeSubagentId===e.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(e.agentId)&&this.scheduleSubagentWindowRender(e.agentId)}async _onSubagentCompleted(e){const t=this.subagents.get(e.agentId);if(t&&(t.status="completed",this.subagents.set(e.agentId,t)),this.renderSubagentPanel(),this.updateSubagentWindows(),this.subagentWindows.has(e.agentId)){const i=this.subagentWindows.get(e.agentId);i&&!i.minimized&&(await this.closeSubagentWindow(e.agentId),this.saveSubagentWindowStates())}const s=this.subagentParentMap.get(e.agentId),n=s?this.sessions.get(s):null;this.notificationManager?.notify({urgency:"info",category:"subagent-complete",sessionId:s||t?.sessionId||e.sessionId,sessionName:n?.name||s||e.sessionId,title:"Subagent Completed",message:t?.description||e.description||"Background agent finished"}),setTimeout(()=>{this.subagents.get(e.agentId)?.status==="completed"&&(this.subagentActivity.delete(e.agentId),this.subagentToolResults.delete(e.agentId))},300*1e3),setTimeout(()=>{this.subagents.get(e.agentId)?.status==="completed"&&!this.subagentWindows.has(e.agentId)&&(this.subagents.delete(e.agentId),this.subagentParentMap.delete(e.agentId))},1800*1e3)}_onImageDetected(e){this.openImagePopup(e)}_onTunnelStarted(e){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())}_onTunnelStopped(){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this.closeTunnelQR()}_onTunnelProgress(e){const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const s=document.getElementById("welcomeTunnelBtn");s?.classList.contains("connecting")&&(s.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)}_onTunnelError(e){this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))}_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()}_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()}_onTunnelQrAuthUsed(e){const s=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${s}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})}_onPlanSubagent(e){this.handlePlanSubagentEvent(e)}_onPlanProgress(e){this._planProgressHandler&&this._planProgressHandler({type:"plan:progress",data:e});const t=document.getElementById("planLoadingTitle"),s=document.getElementById("planLoadingHint");if(t&&e.phase){const n={"parallel-analysis":"Running parallel analysis...",subagent:e.detail||"Subagent working...",synthesis:"Synthesizing results...",verification:"Running verification..."};t.textContent=n[e.phase]||e.phase}s&&e.detail&&(s.textContent=e.detail)}_onPlanStarted(e){this.activePlanOrchestratorId=e.orchestratorId,this.planGenerationStopped=!1,this.renderMonitorPlanAgents()}_onPlanCancelled(e){this.activePlanOrchestratorId===e.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}_onPlanCompleted(e){this.activePlanOrchestratorId===e.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}setConnectionStatus(e){this._connectionStatus=e,this._updateConnectionIndicator(),e==="connected"&&this._inputQueue.size>0&&this._drainInputQueues()}_sendInputAsync(e,t){if(!this.isOnline||this._connectionStatus==="disconnected"){this._enqueueInput(e,t);return}this._inputSendChain=this._inputSendChain.then(()=>{fetch(`/api/sessions/${e}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:t}),keepalive:t.length<65536}).then(n=>{n.ok?this.clearPendingHooks(e):this._enqueueInput(e,t)}).catch(()=>{this._enqueueInput(e,t)})})}_enqueueInput(e,t){let n=(this._inputQueue.get(e)||"")+t;n.length>this._inputQueueMaxBytes&&(n=n.slice(n.length-this._inputQueueMaxBytes)),this._inputQueue.set(e,n),this._updateConnectionIndicator()}async _drainInputQueues(){if(this._inputQueue.size===0)return;const e=new Map(this._inputQueue);this._inputQueue.clear(),this._updateConnectionIndicator();for(const[t,s]of e)(await this._apiPost(`/api/sessions/${t}/input`,{input:s}))?.ok||this._enqueueInput(t,s);this._updateConnectionIndicator()}_updateConnectionIndicator(){const e=this.$("connectionIndicator"),t=this.$("connectionDot"),s=this.$("connectionText");if(!e||!t||!s)return;let n=0;for(const a of this._inputQueue.values())n+=a.length;const i=this._connectionStatus,o=n>0;if((i==="connected"||i==="connecting")&&!o){e.style.display="none";return}e.style.display="flex",t.className="connection-dot";const l=a=>a<1024?`${a}B`:`${(a/1024).toFixed(1)}KB`;i==="connected"&&o?(t.classList.add("draining"),s.textContent=`Sending ${l(n)}...`):i==="reconnecting"?(t.classList.add("reconnecting"),s.textContent=o?`Reconnecting (${l(n)} queued)`:"Reconnecting..."):(t.classList.add("offline"),s.textContent=o?`Offline (${l(n)} queued)`:"Offline")}setupOnlineDetection(){window.addEventListener("online",()=>{this.isOnline=!0,this.reconnectAttempts=0,this.connectSSE()}),window.addEventListener("offline",()=>{this.isOnline=!1,this.setConnectionStatus("offline")})}handleInit(e){this._initFallbackTimer&&(clearTimeout(this._initFallbackTimer),this._initFallbackTimer=null);const t=++this._initGeneration;if(e.version){const i=this.$("versionDisplay"),o=this.$("headerVersion");i&&(i.textContent=`v${e.version}`,i.title=`Codeman v${e.version}`),o&&(o.textContent=`v${e.version}`,o.title=`Codeman v${e.version}`)}VoiceInput.cleanup(),this.sessions.clear(),this.ralphStates.clear(),this.terminalBuffers.clear(),this.terminalBufferCache.clear(),this.projectInsights.clear(),this.teams.clear(),this.teamTasks.clear();for(const i of this.idleTimers.values())clearTimeout(i);if(this.idleTimers.clear(),this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.pendingWrites=[],this.writeFrameScheduled=!1,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._localEchoOverlay?.rerender(),this.pendingHooks.clear(),this._parentNameCache&&this._parentNameCache.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),MobileDetection.cleanup(),KeyboardHandler.cleanup(),MobileDetection.init(),KeyboardHandler.init(),this.tabAlerts.clear(),this._shownCompletions&&this._shownCompletions.clear(),this.notificationManager?.titleFlashInterval&&(clearInterval(this.notificationManager.titleFlashInterval),this.notificationManager.titleFlashInterval=null),this.notificationManager?.groupingMap){for(const{timeout:i}of this.notificationManager.groupingMap.values())clearTimeout(i);this.notificationManager.groupingMap.clear()}this.terminalResizeObserver&&(this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=null),this.planLoadingTimer&&(clearInterval(this.planLoadingTimer),this.planLoadingTimer=null),this.timerCountdownInterval&&(clearInterval(this.timerCountdownInterval),this.timerCountdownInterval=null),this.runSummaryAutoRefreshTimer&&(clearInterval(this.runSummaryAutoRefreshTimer),this.runSummaryAutoRefreshTimer=null),e.sessions.forEach(i=>{this.sessions.set(i.id,i),(i.ralphLoop||i.ralphTodos)&&!this.ralphClosedSessions.has(i.id)&&this.ralphStates.set(i.id,{loop:i.ralphLoop||null,todos:i.ralphTodos||[]})}),this.syncSessionOrder(),e.respawnStatus?this.respawnStatus=e.respawnStatus:this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},e.globalStats&&(this.globalStats=e.globalStats),this.totalCost=e.sessions.reduce((i,o)=>i+(o.totalCost||0),0),this.totalCost+=e.scheduledRuns.reduce((i,o)=>i+(o.totalCost||0),0);const s=e.scheduledRuns.find(i=>i.status==="running");if(s&&(this.currentRun=s,this.showTimer()),this.updateCost(),this.renderSessionTabs(),this.sessions.size>0?this.startSystemStatsPolling():this.stopSystemStatsPolling(),this.cleanupAllFloatingWindows(),e.subagents&&(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),e.subagents.forEach(i=>{this.subagents.set(i.agentId,i)}),this.renderSubagentPanel(),this.subagentParentMap.clear(),this.loadSubagentParentMap().then(()=>{for(const[i,o]of this.subagentParentMap){const l=this.subagents.get(i);if(l&&this.sessions.has(o)){l.parentSessionId=o;const a=this.sessions.get(o);a&&(l.parentSessionName=this.getSessionName(a)),this.subagents.set(i,l)}}for(const[i]of this.subagents)this.subagentParentMap.has(i)||this.findParentSessionForSubagent(i);this.restoreSubagentWindowStates()})),t!==this._initGeneration)return;const n=this.activeSessionId;if(this.activeSessionId=null,this.sessionOrder.length>0){let i=n;if(!i||!this.sessions.has(i))try{i=localStorage.getItem("codeman-active-session")}catch{}i&&this.sessions.has(i)?this.selectSession(i):this.selectSession(this.sessionOrder[0])}}async loadState(){try{const t=await(await fetch("/api/status")).json();this.handleInit(t)}catch{}}renderSessionTabs(){this.renderSessionTabsTimeout&&clearTimeout(this.renderSessionTabsTimeout),this.renderSessionTabsTimeout=setTimeout(()=>{this._renderSessionTabsImmediate()},100)}_updateActiveTabImmediate(e){const t=this.$("sessionTabs");if(!t)return;const s=t.querySelectorAll(".session-tab[data-id]");for(const n of s)n.dataset.id===e?n.classList.add("active"):n.classList.remove("active")}_renderSessionTabsImmediate(){const e=this.$("sessionTabs"),t=e.querySelectorAll(".session-tab[data-id]"),s=new Set([...t].map(o=>o.dataset.id)),n=new Set(this.sessions.keys());if(s.size===n.size&&[...s].every(o=>n.has(o)))for(const[o,l]of this.sessions){const a=e.querySelector(`.session-tab[data-id="${o}"]`);if(!a)continue;const r=o===this.activeSessionId,c=l.status||"idle",d=this.getSessionName(l),u=l.taskStats||{running:0,total:0},h=u.running>0;r&&!a.classList.contains("active")?a.classList.add("active"):!r&&a.classList.contains("active")&&a.classList.remove("active");const m=this.tabAlerts.get(o),p=m==="action",g=m==="idle",f=a.classList.contains("tab-alert-action"),S=a.classList.contains("tab-alert-idle");p&&!f?(a.classList.add("tab-alert-action"),a.classList.remove("tab-alert-idle")):g&&!S?(a.classList.add("tab-alert-idle"),a.classList.remove("tab-alert-action")):!m&&(f||S)&&a.classList.remove("tab-alert-action","tab-alert-idle");const w=a.querySelector(".tab-status");w&&!w.classList.contains(c)&&(w.className=`tab-status ${c}`);const b=a.querySelector(".tab-name");b&&b.textContent!==d&&(b.textContent=d);const y=a.querySelector(".tab-badge");if(h)if(y)y.textContent!==String(u.running)&&(y.textContent=u.running);else{this._fullRenderSessionTabs();return}else if(y){this._fullRenderSessionTabs();return}const v=a.querySelector(".tab-subagent-badge"),T=this.minimizedSubagents.get(o)?.size||0,C=v?parseInt(v.querySelector(".subagent-count")?.textContent||"0"):0;if(T!==C){this._fullRenderSessionTabs();return}}else this._fullRenderSessionTabs()}_fullRenderSessionTabs(){const e=this.$("sessionTabs");document.querySelectorAll("body > .subagent-dropdown").forEach(n=>n.remove()),this.cancelHideSubagentDropdown();const t=[];let s=this.sessionOrder;MobileDetection.getDeviceType()==="mobile"&&this.activeSessionId&&(s=[this.activeSessionId,...this.sessionOrder.filter(n=>n!==this.activeSessionId)]);for(const n of s){const i=this.sessions.get(n);if(!i)continue;const o=n===this.activeSessionId,l=i.status||"idle",a=this.getSessionName(i),r=i.mode||"claude",c=i.color||"default",d=i.taskStats||{running:0,total:0},u=d.running>0,h=this.tabAlerts.get(n),m=h==="action"?" tab-alert-action":h==="idle"?" tab-alert-idle":"",p=this.minimizedSubagents.get(n),f=(p?.size||0)>0?this.renderSubagentTabBadge(n,p):"",S=i.workingDir&&i.workingDir.split("/").pop()||"",b=(this._tallTabsEnabled??!1)&&i.name&&S&&S!==a;t.push(`<div class="session-tab ${o?"active":""}${m}" data-id="${n}" data-color="${c}" onclick="app.selectSession('${escapeHtml(n)}')" oncontextmenu="event.preventDefault(); app.startInlineRename('${escapeHtml(n)}')" tabindex="0" role="tab" aria-selected="${o?"true":"false"}" aria-label="${escapeHtml(a)} session" ${i.workingDir?`title="${escapeHtml(i.workingDir)}"`:""}>
|
|
2
2
|
<span class="tab-status ${l}" aria-hidden="true"></span>
|
|
3
3
|
<span class="tab-info">
|
|
4
4
|
<span class="tab-name-row">
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
${f}
|
|
12
12
|
<span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions('${escapeHtml(n)}')" title="Session options" aria-label="Session options" tabindex="0">⚙</span>
|
|
13
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
|
|
14
|
+
</div>`)}e.innerHTML=t.join(""),this.setupTabDragHandlers(),this.setupTabKeyboardNavigation(e),this.updateConnectionLines()}setupTabKeyboardNavigation(e){this._tabKeydownHandler&&e.removeEventListener("keydown",this._tabKeydownHandler),this._tabKeydownHandler=t=>{if(!["ArrowLeft","ArrowRight","Home","End","Enter"," "].includes(t.key))return;const s=[...e.querySelectorAll(".session-tab")],n=s.indexOf(document.activeElement);if((t.key==="Enter"||t.key===" ")&&n>=0){t.preventDefault();const o=s[n].dataset.id;this.selectSession(o);return}if(n<0)return;let i;switch(t.key){case"ArrowLeft":i=n>0?n-1:s.length-1;break;case"ArrowRight":i=n<s.length-1?n+1:0;break;case"Home":i=0;break;case"End":i=s.length-1;break;default:return}t.preventDefault(),s[i]?.focus()},e.addEventListener("keydown",this._tabKeydownHandler)}syncSessionOrder(){const e=new Set(this.sessions.keys()),s=this.loadSessionOrder().filter(o=>e.has(o)),n=new Set(s),i=[...e].filter(o=>!n.has(o));this.sessionOrder=[...s,...i]}loadSessionOrder(){try{const e=localStorage.getItem("codeman-session-order");return e?JSON.parse(e):[]}catch{return[]}}saveSessionOrder(){try{localStorage.setItem("codeman-session-order",JSON.stringify(this.sessionOrder))}catch{}}setupTabDragHandlers(){const e=this.$("sessionTabs");e.querySelectorAll(".session-tab[data-id]").forEach(s=>{s.setAttribute("draggable","true"),s.addEventListener("dragstart",n=>{this.draggedTabId=s.dataset.id,s.classList.add("dragging"),n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",s.dataset.id)}),s.addEventListener("dragend",()=>{s.classList.remove("dragging"),this.draggedTabId=null,e.querySelectorAll(".session-tab").forEach(n=>{n.classList.remove("drag-over-left","drag-over-right")})}),s.addEventListener("dragover",n=>{if(n.preventDefault(),!this.draggedTabId||this.draggedTabId===s.dataset.id)return;n.dataTransfer.dropEffect="move";const i=s.getBoundingClientRect(),o=i.left+i.width/2,l=n.clientX<o;s.classList.toggle("drag-over-left",l),s.classList.toggle("drag-over-right",!l)}),s.addEventListener("dragleave",()=>{s.classList.remove("drag-over-left","drag-over-right")}),s.addEventListener("drop",n=>{if(n.preventDefault(),s.classList.remove("drag-over-left","drag-over-right"),!this.draggedTabId||this.draggedTabId===s.dataset.id)return;const i=s.dataset.id,o=this.draggedTabId,l=s.getBoundingClientRect(),a=l.left+l.width/2,r=n.clientX<a,c=this.sessionOrder.indexOf(o);let d=this.sessionOrder.indexOf(i);c===-1||d===-1||(this.sessionOrder.splice(c,1),d=this.sessionOrder.indexOf(i),d!==-1&&(r?this.sessionOrder.splice(d,0,o):this.sessionOrder.splice(d+1,0,o),this.saveSessionOrder(),this._fullRenderSessionTabs()))})})}getShortId(e){if(!e)return"";let t=this._shortIdCache.get(e);return t||(t=e.slice(0,8),this._shortIdCache.set(e,t)),t}getSessionName(e){return e.name?e.name:e.workingDir?e.workingDir.split("/").pop()||e.workingDir:this.getShortId(e.id)}async selectSession(e){if(this.activeSessionId===e)return;const t=++this._selectGeneration;if(t!==this._selectGeneration)return;this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this._tabCompletionSessionId=null,this._tabCompletionRetries=0,this._tabCompletionBaseText=null,this._tabCompletionFallback&&(clearTimeout(this._tabCompletionFallback),this._tabCompletionFallback=null),this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.pendingWrites=[],this.writeFrameScheduled=!1,this._isLoadingBuffer=!1,this._loadBufferQueue=null;try{const i=this.terminal?._core?._compositionHelper;if(i?._isComposing){i._isComposing=!1;const o=this.terminal?.element?.querySelector(".xterm-helper-textarea");o&&o.dispatchEvent(new CompositionEvent("compositionend",{data:""}))}}catch{}if(this.activeSessionId){const i=this._localEchoOverlay?.pendingText||"",o=this._localEchoOverlay?.getFlushed()?.count||0,l=this._localEchoOverlay?.getFlushed()?.text||"";i&&this._sendInputAsync(this.activeSessionId,i);const a=o+i.length;a>0&&(this._flushedOffsets||(this._flushedOffsets=new Map),this._flushedTexts||(this._flushedTexts=new Map),this._flushedOffsets.set(this.activeSessionId,a),this._flushedTexts.set(this.activeSessionId,l+i))}this._localEchoOverlay?.clear(),this._localEchoOverlay&&!this._flushedOffsets?.has(e)&&this._localEchoOverlay.suppressBufferDetection(),this.activeSessionId=e;try{localStorage.setItem("codeman-active-session",e)}catch{}this.hideWelcome(),this.clearPendingHooks(e,"idle_prompt"),this._updateActiveTabImmediate(e),this.renderSessionTabs(),this._updateLocalEchoState(),this._flushedOffsets?.has(e)&&this._localEchoOverlay&&this._localEchoOverlay.setFlushed(this._flushedOffsets.get(e),this._flushedTexts?.get(e)||"",!1);const s=document.querySelector(`.session-tab.active[data-id="${e}"]`);s&&(s.classList.add("tab-glow"),s.addEventListener("animationend",()=>s.classList.remove("tab-glow"),{once:!0}));const n=this.sessions.get(e);if(this.currentSessionWorkingDir=n?.workingDir||null,n&&n.pid===null&&n.status==="idle")try{await fetch(`/api/sessions/${e}/interactive`,{method:"POST"}),n.status="busy"}catch{}this._restoringFlushedState=!0;try{const i=this.terminalBufferCache.get(e);if(i){if(this.terminal.clear(),this.terminal.reset(),await this.chunkedTerminalWrite(i),t!==this._selectGeneration){this._restoringFlushedState=!1;return}this.terminal.scrollToBottom()}const o=256*1024,l=await fetch(`/api/sessions/${e}/terminal?tail=${o}`);if(t!==this._selectGeneration){this._restoringFlushedState=!1;return}const a=await l.json();if(a.terminalBuffer){if(a.terminalBuffer!==i){if(this.terminal.clear(),this.terminal.reset(),a.truncated&&this.terminal.write(`\x1B[90m... (earlier output truncated for performance) ...\x1B[0m\r
|
|
15
15
|
\r
|
|
16
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>
|
|
Binary file
|
|
Binary file
|
|
@@ -52,7 +52,7 @@ const TITLE_FLASH_INTERVAL_MS = 1500; // Title flash rate
|
|
|
52
52
|
const BROWSER_NOTIF_RATE_LIMIT_MS = 3000; // Rate limit for browser notifications
|
|
53
53
|
const AUTO_CLOSE_NOTIFICATION_MS = 8000; // Auto-close browser notifications
|
|
54
54
|
const THROTTLE_DELAY_MS = 100; // General UI throttle delay
|
|
55
|
-
const TERMINAL_CHUNK_SIZE =
|
|
55
|
+
const TERMINAL_CHUNK_SIZE = 32 * 1024; // 32KB chunks for terminal data (smaller to avoid WebGL GPU stalls)
|
|
56
56
|
const TERMINAL_TAIL_SIZE = 256 * 1024; // 256KB tail for initial load
|
|
57
57
|
const SYNC_WAIT_TIMEOUT_MS = 50; // Wait timeout for terminal sync
|
|
58
58
|
const STATS_POLLING_INTERVAL_MS = 2000; // System stats polling
|
|
Binary file
|
|
Binary file
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
<script defer src="vendor/xterm-addon-fit.min.js"></script>
|
|
21
21
|
<script defer src="vendor/xterm-addon-webgl.min.js"></script>
|
|
22
22
|
<script defer src="vendor/xterm-addon-unicode11.min.js"></script>
|
|
23
|
-
<script defer src="vendor/xterm-zerolag-input.js?v=0.3.
|
|
23
|
+
<script defer src="vendor/xterm-zerolag-input.js?v=0.3.2"></script>
|
|
24
24
|
<!-- Synchronous mobile detection — runs before first paint to prevent panel flash -->
|
|
25
25
|
<script>if(window.innerWidth<768||(('ontouchstart' in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024))document.documentElement.classList.add('mobile-init');</script>
|
|
26
26
|
<!-- Inline critical CSS for instant skeleton paint (before styles.css loads) -->
|
|
@@ -1674,14 +1674,14 @@
|
|
|
1674
1674
|
<!-- Lines drawn dynamically -->
|
|
1675
1675
|
</svg>
|
|
1676
1676
|
|
|
1677
|
-
<script defer src="constants.js?v=0.3.
|
|
1678
|
-
<script defer src="mobile-handlers.js?v=0.3.
|
|
1679
|
-
<script defer src="voice-input.js?v=0.3.
|
|
1680
|
-
<script defer src="notification-manager.js?v=0.3.
|
|
1681
|
-
<script defer src="keyboard-accessory.js?v=0.3.
|
|
1682
|
-
<script defer src="app.js?v=0.3.
|
|
1683
|
-
<script defer src="ralph-wizard.js?v=0.3.
|
|
1684
|
-
<script defer src="api-client.js?v=0.3.
|
|
1685
|
-
<script defer src="subagent-windows.js?v=0.3.
|
|
1677
|
+
<script defer src="constants.js?v=0.3.2"></script>
|
|
1678
|
+
<script defer src="mobile-handlers.js?v=0.3.2"></script>
|
|
1679
|
+
<script defer src="voice-input.js?v=0.3.2"></script>
|
|
1680
|
+
<script defer src="notification-manager.js?v=0.3.2"></script>
|
|
1681
|
+
<script defer src="keyboard-accessory.js?v=0.3.2"></script>
|
|
1682
|
+
<script defer src="app.js?v=0.3.2"></script>
|
|
1683
|
+
<script defer src="ralph-wizard.js?v=0.3.2"></script>
|
|
1684
|
+
<script defer src="api-client.js?v=0.3.2"></script>
|
|
1685
|
+
<script defer src="subagent-windows.js?v=0.3.2"></script>
|
|
1686
1686
|
</body>
|
|
1687
1687
|
</html>
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/dist/web/public/sw.js.gz
CHANGED
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var XtermZerolagInput=(()=>{var x=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var E=(r,t)=>{for(var s in t)x(r,s,{get:t[s],enumerable:!0})},H=(r,t,s,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of L(t))!R.call(r,i)&&i!==s&&x(r,i,{get:()=>t[i],enumerable:!(e=F(t,i))||e.enumerable});return r};var k=r=>H(x({},"__esModule",{value:!0}),r);var B={};E(B,{ZerolagInputAddon:()=>P});function w(r){let t=r,s=typeof devicePixelRatio=="number"&&devicePixelRatio>0?devicePixelRatio:1;if(t.dimensions?.css?.cell){let e=t.dimensions.css.cell.height;return{width:t.dimensions.css.cell.width,height:e,charTop:(t.dimensions?.device?.char?.top??0)/s,charHeight:(t.dimensions?.device?.char?.height??e*s)/s}}try{let e=t._core?._renderService?.dimensions;if(e?.css?.cell){let i=e.css.cell.height;return{width:e.css.cell.width,height:i,charTop:(e.device?.char?.top??0)/s,charHeight:(e.device?.char?.height??i*s)/s}}}catch{}return null}function C(r,t){try{let s=r.buffer.active,e=s.viewportY;switch(t.type){case"character":{for(let i=r.rows-1;i>=0;i--){let l=s.getLine(e+i);if(!l)continue;let p=l.translateToString(!0).lastIndexOf(t.char);if(p>=0)return{row:i,col:p}}return null}case"regex":{let i=t.pattern,l=i.global?new RegExp(i.source,i.flags.replace("g","")):i;for(let h=r.rows-1;h>=0;h--){let p=s.getLine(e+h);if(!p)continue;let o=p.translateToString(!0).match(l);if(o){let d=o.index??0;return{row:h,col:d}}}return null}case"custom":return t.find(r);default:return null}}catch{return null}}function T(r,t,s){try{let e=r.buffer.active,i=e.viewportY+t.row,l=e.getLine(i);return l?l.translateToString(!0).slice(t.col+s).trimEnd():""}catch{return""}}function O(r,t){let{lines:s,startCol:e,totalCols:i,cellW:l,cellH:h,charTop:p,charHeight:f,promptRow:o,font:d,showCursor:n,cursorColor:m}=t;r.style.left="0px",r.style.top=o*h+"px",r.innerHTML="";let g=i*l;for(let a=0;a<s.length;a++){let _=a===0?e*l:0,c=a===0?g-_:g,u=a*h,y=M(s[a],_,u,c,h,l,p,f,d);r.appendChild(y)}if(n){let a=s[s.length-1],c=(s.length===1?e:0)+a.length;if(c<i){let u=document.createElement("span");u.style.cssText="position:absolute;display:inline-block",u.style.left=c*l+"px",u.style.top=(s.length-1)*h+"px",u.style.width=l+"px",u.style.height=h+"px",u.style.backgroundColor=m,r.appendChild(u)}}r.style.display=""}function M(r,t,s,e,i,l,h,p,f){let o=document.createElement("div");o.style.cssText="position:absolute;pointer-events:none",o.style.backgroundColor=f.backgroundColor,o.style.left=t+"px",o.style.top=s+"px",o.style.width=e+"px",o.style.height=i+1+"px";for(let d=0;d<r.length;d++){let n=document.createElement("span");n.style.cssText="position:absolute;display:inline-block;text-align:center;pointer-events:none;font-feature-settings:'liga' 0,'calt' 0",n.style.left=d*l+"px",n.style.top="0px",n.style.width=l+"px",n.style.height=i+"px",n.style.lineHeight=i+"px",n.style.fontFamily=f.fontFamily,n.style.fontSize=f.fontSize,n.style.fontWeight=f.fontWeight,n.style.color=f.color,f.letterSpacing&&(n.style.letterSpacing=f.letterSpacing),n.textContent=r[d],o.appendChild(n)}return o}var v={type:"character",char:">",offset:2},I=7,X=50,D="#0d0d0d",S="#eeeeee",z="#e0e0e0",P=class{_terminal=null;_overlay=null;_options;_pendingText="";_flushedOffset=0;_flushedText="";_bufferDetectDone=!1;_lastRenderKey="";_lastPromptPos=null;_font={fontFamily:"monospace",fontSize:"14px",fontWeight:"normal",color:S,backgroundColor:D,letterSpacing:""};_scrollTimer=null;_scrollHandler=null;_scrollViewport=null;constructor(t){this._options={prompt:t?.prompt??v,zIndex:t?.zIndex??I,showCursor:t?.showCursor??!0,scrollDebounceMs:t?.scrollDebounceMs??X,backgroundColor:t?.backgroundColor,foregroundColor:t?.foregroundColor,cursorColor:t?.cursorColor}}activate(t){this._terminal=t,this._overlay=document.createElement("div"),this._overlay.style.cssText=`position:absolute;z-index:${this._options.zIndex};pointer-events:none;display:none`;let s=t.element?.querySelector(".xterm-screen");s&&s.appendChild(this._overlay),this._cacheFont(),this._scrollHandler=()=>{try{let i=this._terminal.buffer.active;i.viewportY!==i.baseY?(this._overlay.style.display="none",this._scrollTimer&&(clearTimeout(this._scrollTimer),this._scrollTimer=null)):(this._pendingText||this._flushedOffset>0)&&(this._scrollTimer&&clearTimeout(this._scrollTimer),this._scrollTimer=setTimeout(()=>{this._scrollTimer=null,this._lastRenderKey="",this._render()},this._options.scrollDebounceMs))}catch{}};let e=t.element?.querySelector(".xterm-viewport");e&&(e.addEventListener("scroll",this._scrollHandler,{passive:!0}),this._scrollViewport=e)}dispose(){this.clear(),this._scrollTimer&&(clearTimeout(this._scrollTimer),this._scrollTimer=null),this._scrollViewport&&this._scrollHandler&&this._scrollViewport.removeEventListener("scroll",this._scrollHandler),this._overlay?.remove(),this._overlay=null,this._scrollViewport=null,this._scrollHandler=null,this._terminal=null}addChar(t){!this._pendingText&&!this._flushedOffset&&this._detectBufferText(),this._pendingText+=t,this._render()}appendText(t){t&&(!this._pendingText&&!this._flushedOffset&&this._detectBufferText(),this._pendingText+=t,this._render())}removeChar(){return this._pendingText.length>0?(this._pendingText=this._pendingText.slice(0,-1),this._pendingText.length>0||this._flushedOffset>0?this._render():this._hide(),"pending"):this._flushedOffset>0?(this._flushedOffset--,this._flushedText=this._flushedText.slice(0,-1),this._flushedOffset>0?this._render():this._hide(),"flushed"):(this._detectBufferText(),this._flushedOffset>0?(this._flushedOffset--,this._flushedText=this._flushedText.slice(0,-1),this._flushedOffset>0?this._render():this._hide(),"flushed"):!1)}clear(){this._pendingText="",this._flushedOffset=0,this._flushedText="",this._bufferDetectDone=!1,this._lastRenderKey="",this._lastPromptPos=null,this._hide()}setFlushed(t,s,e=!0){this._flushedOffset=t,this._flushedText=s,e&&this._render()}getFlushed(){return{count:this._flushedOffset,text:this._flushedText}}clearFlushed(){this._flushedOffset=0,this._flushedText="",this._pendingText?this._render():this._hide()}rerender(){(this._pendingText||this._flushedOffset>0)&&(this._lastRenderKey="",this._render())}refreshFont(){this._cacheFont(),this._lastRenderKey="",(this._pendingText||this._flushedOffset>0)&&this._render()}detectBufferText(){return this._detectBufferText()}resetBufferDetection(){this._bufferDetectDone=!1}undoDetection(){this._flushedOffset=0,this._flushedText="",this._bufferDetectDone=!1}suppressBufferDetection(){this._bufferDetectDone=!0}setPrompt(t){this._options.prompt=t,this._lastPromptPos=null,this._lastRenderKey="",(this._pendingText||this._flushedOffset>0)&&this._render()}findPrompt(){return this._terminal?C(this._terminal,this._options.prompt??v):null}readPromptText(){if(!this._terminal)return null;let t=this.findPrompt();if(!t)return null;let s=this._getPromptOffset();return T(this._terminal,t,s)||null}get pendingText(){return this._pendingText}get hasPending(){return this._pendingText.length>0||this._flushedOffset>0}get state(){return{pendingText:this._pendingText,flushedLength:this._flushedOffset,flushedText:this._flushedText,visible:this._overlay!==null&&this._overlay.style.display!=="none",promptPosition:this._lastPromptPos?{...this._lastPromptPos}:null}}_getPromptOffset(){return(this._options.prompt??v).offset??2}_detectBufferText(){if(this._bufferDetectDone||!this._terminal)return null;try{let t=this.findPrompt();if(!t)return null;let s=this._getPromptOffset(),e=T(this._terminal,t,s);if(e.length>0)return this._flushedOffset=e.length,this._flushedText=e,this._lastPromptPos=t,this._bufferDetectDone=!0,e}catch{}return null}_cacheFont(){if(!this._terminal)return;let t=this._terminal;this._font.fontFamily=t.options.fontFamily||"monospace",this._font.fontSize=(t.options.fontSize||14)+"px",this._font.fontWeight=String(t.options.fontWeight||"normal"),this._font.backgroundColor=this._options.backgroundColor??t.options.theme?.background??D,this._font.color=this._options.foregroundColor??t.options.theme?.foreground??S,this._font.letterSpacing="";let s=t.element?.querySelector(".xterm-rows");if(s){let e=getComputedStyle(s);this._font.letterSpacing=e.letterSpacing,!this._options.foregroundColor&&e.color&&(this._font.color=e.color)}}_hide(){this._overlay&&(this._lastRenderKey="",this._lastPromptPos=null,this._overlay.innerHTML="",this._overlay.style.display="none")}_render(){if(!(!this._terminal||!this._overlay)){if(!this._pendingText&&!(this._flushedOffset>0)){this._overlay.style.display="none";return}try{let t=this._terminal.buffer.active;if(t.viewportY!==t.baseY){this._overlay.style.display="none";return}let s=this.findPrompt();if(s)this._lastPromptPos&&this._flushedOffset>0?this._lastPromptPos={row:s.row,col:this._lastPromptPos.col}:this._lastPromptPos=s;else if(!this._lastPromptPos){this._overlay.style.display="none";return}let e=this._lastPromptPos,i=w(this._terminal);if(!i){this._overlay.style.display="none";return}let{width:l,height:h,charTop:p,charHeight:f}=i,o=this._terminal.cols,d=this._getPromptOffset(),n=e.col+d,m=this._pendingText;if(this._flushedOffset>0)if(this._flushedText&&this._flushedText.length===this._flushedOffset)m=this._flushedText+this._pendingText;else{let y=t.viewportY+e.row,b=t.getLine(y);b&&(m=b.translateToString(!0).slice(n,n+this._flushedOffset)+this._pendingText)}let g=`${m}:${n}:${e.row}:${e.col}:${o}:${this._flushedOffset}`;if(g===this._lastRenderKey&&this._overlay.style.display!=="none")return;this._lastRenderKey=g;let a=Math.max(1,o-n),_=[],c=m;for(_.push(c.slice(0,a)),c=c.slice(a);c.length>0;)_.push(c.slice(0,o)),c=c.slice(o);let u=this._options.cursorColor??this._terminal.options.theme?.cursor??z;O(this._overlay,{lines:_,startCol:n,totalCols:o,cellW:l,cellH:h,charTop:p,charHeight:f,promptRow:e.row,font:this._font,showCursor:this._options.showCursor,cursorColor:u})}catch{this._overlay&&(this._overlay.innerHTML="",this._overlay.style.display="none")}}}};return k(B);})();
|
|
1
|
+
"use strict";var XtermZerolagInput=(()=>{var b=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var k=Object.prototype.hasOwnProperty;var X=(r,e)=>{for(var t in e)b(r,t,{get:e[t],enumerable:!0})},M=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of H(e))!k.call(r,i)&&i!==t&&b(r,i,{get:()=>e[i],enumerable:!(s=E(e,i))||s.enumerable});return r};var W=r=>M(b({},"__esModule",{value:!0}),r);var U={};X(U,{ZerolagInputAddon:()=>O});function D(r){let e=r,t=typeof devicePixelRatio=="number"&&devicePixelRatio>0?devicePixelRatio:1;if(e.dimensions?.css?.cell){let s=e.dimensions.css.cell.height;return{width:e.dimensions.css.cell.width,height:s,charTop:(e.dimensions?.device?.char?.top??0)/t,charHeight:(e.dimensions?.device?.char?.height??s*t)/t}}try{let s=e._core?._renderService?.dimensions;if(s?.css?.cell){let i=s.css.cell.height;return{width:s.css.cell.width,height:i,charTop:(s.device?.char?.top??0)/t,charHeight:(s.device?.char?.height??i*t)/t}}}catch{}return null}function S(r,e){try{let t=r.buffer.active,s=t.viewportY;switch(e.type){case"character":{for(let i=r.rows-1;i>=0;i--){let n=t.getLine(s+i);if(!n)continue;let p=n.translateToString(!0).lastIndexOf(e.char);if(p>=0)return{row:i,col:p}}return null}case"regex":{let i=e.pattern,n=i.global?new RegExp(i.source,i.flags.replace("g","")):i;for(let h=r.rows-1;h>=0;h--){let p=t.getLine(s+h);if(!p)continue;let u=p.translateToString(!0).match(n);if(u){let f=u.index??0;return{row:h,col:f}}}return null}case"custom":return e.find(r);default:return null}}catch{return null}}function w(r,e,t){try{let s=r.buffer.active,i=s.viewportY+e.row,n=s.getLine(i);return n?n.translateToString(!0).slice(e.col+t).trimEnd():""}catch{return""}}function P(r,e){if(r?.unicode?.getStringCellWidth)return r.unicode.getStringCellWidth(e);let t=e.codePointAt(0);return t!==void 0&&t>=4352&&(t<=4447||t>=11904&&t<=12350||t>=12352&&t<=13247||t>=13312&&t<=19903||t>=19968&&t<=42191||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65072&&t<=65135||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126976&&t<=130047||t>=131072&&t<=196607||t>=196608&&t<=262143)?2:1}function I(r,e){let t=0;for(let s of e)t+=P(r,s);return t}function F(r,e){let{lines:t,startCol:s,totalCols:i,cellW:n,cellH:h,charTop:p,charHeight:a,promptRow:u,font:f,showCursor:_,cursorColor:m,terminal:g}=e;r.style.left="0px",r.style.top=u*h+"px",r.innerHTML="";let o=i*n;for(let l=0;l<t.length;l++){let T=l===0?s*n:0,c=l===0?o-T:o,d=l*h,x=z(t[l],T,d,c,h,n,p,a,f,g);r.appendChild(x)}if(_){let l=t[t.length-1],c=(t.length===1?s:0)+I(g,l);if(c<i){let d=document.createElement("span");d.style.cssText="position:absolute;display:inline-block",d.style.left=c*n+"px",d.style.top=(t.length-1)*h+"px",d.style.width=n+"px",d.style.height=h+"px",d.style.backgroundColor=m,r.appendChild(d)}}r.style.display=""}function z(r,e,t,s,i,n,h,p,a,u){let f=document.createElement("div");f.style.cssText="position:absolute;pointer-events:none",f.style.backgroundColor=a.backgroundColor,f.style.left=e+"px",f.style.top=t+"px",f.style.width=s+"px",f.style.height=i+1+"px";let _=0;for(let m of r){let g=P(u,m),o=document.createElement("span");o.style.cssText="position:absolute;display:inline-block;text-align:center;pointer-events:none;font-feature-settings:'liga' 0,'calt' 0",o.style.left=_*n+"px",o.style.top="0px",o.style.width=g*n+"px",o.style.height=i+"px",o.style.lineHeight=i+"px",o.style.fontFamily=a.fontFamily,o.style.fontSize=a.fontSize,o.style.fontWeight=a.fontWeight,o.style.color=a.color,a.letterSpacing&&(o.style.letterSpacing=a.letterSpacing),o.textContent=m,f.appendChild(o),_+=g}return f}var C={type:"character",char:">",offset:2},A=7,B=50,L="#0d0d0d",R="#eeeeee",K="#e0e0e0",O=class{_terminal=null;_overlay=null;_options;_pendingText="";_flushedOffset=0;_flushedText="";_bufferDetectDone=!1;_lastRenderKey="";_lastPromptPos=null;_font={fontFamily:"monospace",fontSize:"14px",fontWeight:"normal",color:R,backgroundColor:L,letterSpacing:""};_scrollTimer=null;_scrollHandler=null;_scrollViewport=null;constructor(e){this._options={prompt:e?.prompt??C,zIndex:e?.zIndex??A,showCursor:e?.showCursor??!0,scrollDebounceMs:e?.scrollDebounceMs??B,backgroundColor:e?.backgroundColor,foregroundColor:e?.foregroundColor,cursorColor:e?.cursorColor}}activate(e){this._terminal=e,this._overlay=document.createElement("div"),this._overlay.style.cssText=`position:absolute;z-index:${this._options.zIndex};pointer-events:none;display:none`;let t=e.element?.querySelector(".xterm-screen");t&&t.appendChild(this._overlay),this._cacheFont(),this._scrollHandler=()=>{try{let i=this._terminal.buffer.active;i.viewportY!==i.baseY?(this._overlay.style.display="none",this._scrollTimer&&(clearTimeout(this._scrollTimer),this._scrollTimer=null)):(this._pendingText||this._flushedOffset>0)&&(this._scrollTimer&&clearTimeout(this._scrollTimer),this._scrollTimer=setTimeout(()=>{this._scrollTimer=null,this._lastRenderKey="",this._render()},this._options.scrollDebounceMs))}catch{}};let s=e.element?.querySelector(".xterm-viewport");s&&(s.addEventListener("scroll",this._scrollHandler,{passive:!0}),this._scrollViewport=s)}dispose(){this.clear(),this._scrollTimer&&(clearTimeout(this._scrollTimer),this._scrollTimer=null),this._scrollViewport&&this._scrollHandler&&this._scrollViewport.removeEventListener("scroll",this._scrollHandler),this._overlay?.remove(),this._overlay=null,this._scrollViewport=null,this._scrollHandler=null,this._terminal=null}addChar(e){!this._pendingText&&!this._flushedOffset&&this._detectBufferText(),this._pendingText+=e,this._render()}appendText(e){e&&(!this._pendingText&&!this._flushedOffset&&this._detectBufferText(),this._pendingText+=e,this._render())}removeChar(){return this._pendingText.length>0?(this._pendingText=this._pendingText.slice(0,-1),this._pendingText.length>0||this._flushedOffset>0?this._render():this._hide(),"pending"):this._flushedOffset>0?(this._flushedOffset--,this._flushedText=this._flushedText.slice(0,-1),this._flushedOffset>0?this._render():this._hide(),"flushed"):(this._detectBufferText(),this._flushedOffset>0?(this._flushedOffset--,this._flushedText=this._flushedText.slice(0,-1),this._flushedOffset>0?this._render():this._hide(),"flushed"):!1)}clear(){this._pendingText="",this._flushedOffset=0,this._flushedText="",this._bufferDetectDone=!1,this._lastRenderKey="",this._lastPromptPos=null,this._hide()}setFlushed(e,t,s=!0){this._flushedOffset=e,this._flushedText=t,s&&this._render()}getFlushed(){return{count:this._flushedOffset,text:this._flushedText}}clearFlushed(){this._flushedOffset=0,this._flushedText="",this._pendingText?this._render():this._hide()}rerender(){(this._pendingText||this._flushedOffset>0)&&(this._lastRenderKey="",this._render())}refreshFont(){this._cacheFont(),this._lastRenderKey="",(this._pendingText||this._flushedOffset>0)&&this._render()}detectBufferText(){return this._detectBufferText()}resetBufferDetection(){this._bufferDetectDone=!1}undoDetection(){this._flushedOffset=0,this._flushedText="",this._bufferDetectDone=!1}suppressBufferDetection(){this._bufferDetectDone=!0}setPrompt(e){this._options.prompt=e,this._lastPromptPos=null,this._lastRenderKey="",(this._pendingText||this._flushedOffset>0)&&this._render()}findPrompt(){return this._terminal?S(this._terminal,this._options.prompt??C):null}readPromptText(){if(!this._terminal)return null;let e=this.findPrompt();if(!e)return null;let t=this._getPromptOffset();return w(this._terminal,e,t)||null}get pendingText(){return this._pendingText}get hasPending(){return this._pendingText.length>0||this._flushedOffset>0}get state(){return{pendingText:this._pendingText,flushedLength:this._flushedOffset,flushedText:this._flushedText,visible:this._overlay!==null&&this._overlay.style.display!=="none",promptPosition:this._lastPromptPos?{...this._lastPromptPos}:null}}_getPromptOffset(){return(this._options.prompt??C).offset??2}_detectBufferText(){if(this._bufferDetectDone||!this._terminal)return null;try{let e=this.findPrompt();if(!e)return null;let t=this._getPromptOffset(),s=w(this._terminal,e,t);if(s.length>0)return this._flushedOffset=s.length,this._flushedText=s,this._lastPromptPos=e,this._bufferDetectDone=!0,s}catch{}return null}_cacheFont(){if(!this._terminal)return;let e=this._terminal;this._font.fontFamily=e.options.fontFamily||"monospace",this._font.fontSize=(e.options.fontSize||14)+"px",this._font.fontWeight=String(e.options.fontWeight||"normal"),this._font.backgroundColor=this._options.backgroundColor??e.options.theme?.background??L,this._font.color=this._options.foregroundColor??e.options.theme?.foreground??R,this._font.letterSpacing="";let t=e.element?.querySelector(".xterm-rows");if(t){let s=getComputedStyle(t);this._font.letterSpacing=s.letterSpacing,!this._options.foregroundColor&&s.color&&(this._font.color=s.color)}}_hide(){this._overlay&&(this._lastRenderKey="",this._lastPromptPos=null,this._overlay.innerHTML="",this._overlay.style.display="none")}_render(){if(!(!this._terminal||!this._overlay)){if(!this._pendingText&&!(this._flushedOffset>0)){this._overlay.style.display="none";return}try{let e=this._terminal.buffer.active;if(e.viewportY!==e.baseY){this._overlay.style.display="none";return}let t=this.findPrompt();if(t)this._lastPromptPos&&this._flushedOffset>0?this._lastPromptPos={row:t.row,col:this._lastPromptPos.col}:this._lastPromptPos=t;else if(!this._lastPromptPos){this._overlay.style.display="none";return}let s=this._lastPromptPos,i=D(this._terminal);if(!i){this._overlay.style.display="none";return}let{width:n,height:h,charTop:p,charHeight:a}=i,u=this._terminal.cols,f=this._getPromptOffset(),_=s.col+f,m=this._pendingText;if(this._flushedOffset>0)if(this._flushedText&&this._flushedText.length===this._flushedOffset)m=this._flushedText+this._pendingText;else{let x=e.viewportY+s.row,y=e.getLine(x);y&&(m=y.translateToString(!0).slice(_,_+this._flushedOffset)+this._pendingText)}let g=`${m}:${_}:${s.row}:${s.col}:${u}:${this._flushedOffset}`;if(g===this._lastRenderKey&&this._overlay.style.display!=="none")return;this._lastRenderKey=g;let o=Math.max(1,u-_),l=[...m],T=[],c=0;{let x="",y=0;for(;c<l.length;){let v=P(this._terminal,l[c]);if(y+v>o)break;x+=l[c],y+=v,c++}T.push(x)}for(;c<l.length;){let x="",y=0;for(;c<l.length;){let v=P(this._terminal,l[c]);if(y+v>u)break;x+=l[c],y+=v,c++}T.push(x)}let d=this._options.cursorColor??this._terminal.options.theme?.cursor??K;F(this._overlay,{lines:T,startCol:_,totalCols:u,cellW:n,cellH:h,charTop:p,charHeight:a,promptRow:s.row,font:this._font,showCursor:this._options.showCursor,cursorColor:d,terminal:this._terminal})}catch{this._overlay&&(this._overlay.innerHTML="",this._overlay.style.display="none")}}}};return W(U);})();
|
|
2
2
|
|
|
3
3
|
// Global aliases for browser usage
|
|
4
4
|
if(typeof window!=="undefined"){window.ZerolagInputAddon=XtermZerolagInput.ZerolagInputAddon;window.LocalEchoOverlay=class extends XtermZerolagInput.ZerolagInputAddon{constructor(terminal){super({prompt:{type:"character",char:"\u276f",offset:2}});this.activate(terminal);}};}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/package.json
CHANGED