claude-mpm 4.2.43__py3-none-any.whl → 4.2.51__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. claude_mpm/VERSION +1 -1
  2. claude_mpm/agents/BASE_PM.md +117 -12
  3. claude_mpm/agents/INSTRUCTIONS.md +154 -10
  4. claude_mpm/agents/WORKFLOW.md +46 -1
  5. claude_mpm/agents/frontmatter_validator.py +20 -12
  6. claude_mpm/agents/templates/nextjs_engineer.json +277 -0
  7. claude_mpm/agents/templates/python_engineer.json +289 -0
  8. claude_mpm/agents/templates/react_engineer.json +11 -3
  9. claude_mpm/agents/templates/security.json +50 -9
  10. claude_mpm/cli/commands/agents.py +2 -2
  11. claude_mpm/cli/commands/uninstall.py +1 -2
  12. claude_mpm/cli/interactive/agent_wizard.py +3 -3
  13. claude_mpm/cli/parsers/agent_manager_parser.py +3 -3
  14. claude_mpm/cli/parsers/agents_parser.py +1 -1
  15. claude_mpm/constants.py +1 -1
  16. claude_mpm/core/api_validator.py +330 -0
  17. claude_mpm/core/error_handler.py +2 -4
  18. claude_mpm/core/file_utils.py +4 -12
  19. claude_mpm/core/framework_loader.py +22 -0
  20. claude_mpm/core/log_manager.py +8 -5
  21. claude_mpm/core/logger.py +1 -1
  22. claude_mpm/core/logging_utils.py +6 -6
  23. claude_mpm/core/unified_agent_registry.py +18 -4
  24. claude_mpm/dashboard/react/components/DataInspector/DataInspector.module.css +188 -0
  25. claude_mpm/dashboard/react/components/EventViewer/EventViewer.module.css +156 -0
  26. claude_mpm/dashboard/react/components/shared/ConnectionStatus.module.css +38 -0
  27. claude_mpm/dashboard/react/components/shared/FilterBar.module.css +92 -0
  28. claude_mpm/dashboard/static/archive/activity_dashboard_fixed.html +248 -0
  29. claude_mpm/dashboard/static/archive/activity_dashboard_test.html +61 -0
  30. claude_mpm/dashboard/static/archive/test_activity_connection.html +179 -0
  31. claude_mpm/dashboard/static/archive/test_claude_tree_tab.html +68 -0
  32. claude_mpm/dashboard/static/archive/test_dashboard.html +409 -0
  33. claude_mpm/dashboard/static/archive/test_dashboard_fixed.html +519 -0
  34. claude_mpm/dashboard/static/archive/test_dashboard_verification.html +181 -0
  35. claude_mpm/dashboard/static/archive/test_file_data.html +315 -0
  36. claude_mpm/dashboard/static/archive/test_file_tree_empty_state.html +243 -0
  37. claude_mpm/dashboard/static/archive/test_file_tree_fix.html +234 -0
  38. claude_mpm/dashboard/static/archive/test_file_tree_rename.html +117 -0
  39. claude_mpm/dashboard/static/archive/test_file_tree_tab.html +115 -0
  40. claude_mpm/dashboard/static/archive/test_file_viewer.html +224 -0
  41. claude_mpm/dashboard/static/archive/test_final_activity.html +220 -0
  42. claude_mpm/dashboard/static/archive/test_tab_fix.html +139 -0
  43. claude_mpm/dashboard/static/built/assets/events.DjpNxWNo.css +1 -0
  44. claude_mpm/dashboard/static/built/components/activity-tree.js +1 -1
  45. claude_mpm/dashboard/static/built/components/agent-hierarchy.js +777 -0
  46. claude_mpm/dashboard/static/built/components/agent-inference.js +1 -1
  47. claude_mpm/dashboard/static/built/components/build-tracker.js +333 -0
  48. claude_mpm/dashboard/static/built/components/code-simple.js +857 -0
  49. claude_mpm/dashboard/static/built/components/code-tree/tree-breadcrumb.js +353 -0
  50. claude_mpm/dashboard/static/built/components/code-tree/tree-constants.js +235 -0
  51. claude_mpm/dashboard/static/built/components/code-tree/tree-search.js +409 -0
  52. claude_mpm/dashboard/static/built/components/code-tree/tree-utils.js +435 -0
  53. claude_mpm/dashboard/static/built/components/code-viewer.js +2 -1076
  54. claude_mpm/dashboard/static/built/components/connection-debug.js +654 -0
  55. claude_mpm/dashboard/static/built/components/diff-viewer.js +891 -0
  56. claude_mpm/dashboard/static/built/components/event-processor.js +1 -1
  57. claude_mpm/dashboard/static/built/components/event-viewer.js +1 -1
  58. claude_mpm/dashboard/static/built/components/export-manager.js +1 -1
  59. claude_mpm/dashboard/static/built/components/file-change-tracker.js +443 -0
  60. claude_mpm/dashboard/static/built/components/file-change-viewer.js +690 -0
  61. claude_mpm/dashboard/static/built/components/file-tool-tracker.js +1 -1
  62. claude_mpm/dashboard/static/built/components/module-viewer.js +1 -1
  63. claude_mpm/dashboard/static/built/components/nav-bar.js +145 -0
  64. claude_mpm/dashboard/static/built/components/page-structure.js +429 -0
  65. claude_mpm/dashboard/static/built/components/session-manager.js +1 -1
  66. claude_mpm/dashboard/static/built/components/ui-state-manager.js +2 -465
  67. claude_mpm/dashboard/static/built/components/working-directory.js +1 -1
  68. claude_mpm/dashboard/static/built/connection-manager.js +536 -0
  69. claude_mpm/dashboard/static/built/dashboard.js +1 -1
  70. claude_mpm/dashboard/static/built/extension-error-handler.js +164 -0
  71. claude_mpm/dashboard/static/built/react/events.js +30 -0
  72. claude_mpm/dashboard/static/built/shared/dom-helpers.js +396 -0
  73. claude_mpm/dashboard/static/built/shared/event-bus.js +330 -0
  74. claude_mpm/dashboard/static/built/shared/event-filter-service.js +540 -0
  75. claude_mpm/dashboard/static/built/shared/logger.js +385 -0
  76. claude_mpm/dashboard/static/built/shared/page-structure.js +251 -0
  77. claude_mpm/dashboard/static/built/shared/tooltip-service.js +253 -0
  78. claude_mpm/dashboard/static/built/socket-client.js +1 -1
  79. claude_mpm/dashboard/static/built/tab-isolation-fix.js +185 -0
  80. claude_mpm/dashboard/static/css/dashboard.css +28 -5
  81. claude_mpm/dashboard/static/dist/assets/events.DjpNxWNo.css +1 -0
  82. claude_mpm/dashboard/static/dist/components/activity-tree.js +1 -1
  83. claude_mpm/dashboard/static/dist/components/agent-inference.js +1 -1
  84. claude_mpm/dashboard/static/dist/components/code-viewer.js +2 -0
  85. claude_mpm/dashboard/static/dist/components/event-processor.js +1 -1
  86. claude_mpm/dashboard/static/dist/components/event-viewer.js +1 -1
  87. claude_mpm/dashboard/static/dist/components/export-manager.js +1 -1
  88. claude_mpm/dashboard/static/dist/components/file-tool-tracker.js +1 -1
  89. claude_mpm/dashboard/static/dist/components/module-viewer.js +1 -1
  90. claude_mpm/dashboard/static/dist/components/session-manager.js +1 -1
  91. claude_mpm/dashboard/static/dist/components/working-directory.js +1 -1
  92. claude_mpm/dashboard/static/dist/dashboard.js +1 -1
  93. claude_mpm/dashboard/static/dist/react/events.js +30 -0
  94. claude_mpm/dashboard/static/dist/socket-client.js +1 -1
  95. claude_mpm/dashboard/static/events.html +607 -0
  96. claude_mpm/dashboard/static/index.html +713 -0
  97. claude_mpm/dashboard/static/js/components/activity-tree.js +3 -17
  98. claude_mpm/dashboard/static/js/components/agent-hierarchy.js +4 -1
  99. claude_mpm/dashboard/static/js/components/agent-inference.js +3 -0
  100. claude_mpm/dashboard/static/js/components/build-tracker.js +8 -0
  101. claude_mpm/dashboard/static/js/components/code-viewer.js +387 -72
  102. claude_mpm/dashboard/static/js/components/event-processor.js +3 -0
  103. claude_mpm/dashboard/static/js/components/event-viewer.js +39 -2
  104. claude_mpm/dashboard/static/js/components/export-manager.js +3 -0
  105. claude_mpm/dashboard/static/js/components/file-tool-tracker.js +30 -10
  106. claude_mpm/dashboard/static/js/components/socket-manager.js +4 -0
  107. claude_mpm/dashboard/static/js/components/ui-state-manager.js +286 -108
  108. claude_mpm/dashboard/static/js/components/working-directory.js +3 -0
  109. claude_mpm/dashboard/static/js/dashboard.js +61 -49
  110. claude_mpm/dashboard/static/js/socket-client.js +12 -8
  111. claude_mpm/dashboard/static/js/stores/dashboard-store.js +562 -0
  112. claude_mpm/dashboard/static/js/tab-isolation-fix.js +185 -0
  113. claude_mpm/dashboard/static/legacy/activity.html +736 -0
  114. claude_mpm/dashboard/static/legacy/agents.html +786 -0
  115. claude_mpm/dashboard/static/legacy/files.html +747 -0
  116. claude_mpm/dashboard/static/legacy/tools.html +831 -0
  117. claude_mpm/dashboard/static/monitors-index.html +218 -0
  118. claude_mpm/dashboard/static/monitors.html +431 -0
  119. claude_mpm/dashboard/static/production/events.html +659 -0
  120. claude_mpm/dashboard/static/production/main.html +715 -0
  121. claude_mpm/dashboard/static/production/monitors.html +483 -0
  122. claude_mpm/dashboard/static/socket.io.min.js +7 -0
  123. claude_mpm/dashboard/static/socket.io.v4.8.1.backup.js +7 -0
  124. claude_mpm/dashboard/static/test-archive/dashboard.html +635 -0
  125. claude_mpm/dashboard/static/test-archive/debug-events.html +147 -0
  126. claude_mpm/dashboard/static/test-archive/test-navigation.html +256 -0
  127. claude_mpm/dashboard/static/test-archive/test-react-exports.html +180 -0
  128. claude_mpm/dashboard/templates/index.html +82 -38
  129. claude_mpm/hooks/claude_hooks/services/connection_manager_http.py +1 -1
  130. claude_mpm/services/agents/deployment/agent_discovery_service.py +3 -0
  131. claude_mpm/services/agents/deployment/agent_template_builder.py +25 -8
  132. claude_mpm/services/agents/deployment/agent_validator.py +3 -0
  133. claude_mpm/services/agents/deployment/validation/template_validator.py +13 -4
  134. claude_mpm/services/agents/local_template_manager.py +2 -6
  135. claude_mpm/services/monitor/daemon.py +1 -2
  136. claude_mpm/services/monitor/daemon_manager.py +2 -5
  137. claude_mpm/services/monitor/event_emitter.py +2 -2
  138. claude_mpm/services/monitor/handlers/code_analysis.py +4 -6
  139. claude_mpm/services/monitor/handlers/hooks.py +2 -4
  140. claude_mpm/services/monitor/server.py +23 -226
  141. claude_mpm/tools/code_tree_analyzer.py +2 -2
  142. {claude_mpm-4.2.43.dist-info → claude_mpm-4.2.51.dist-info}/METADATA +1 -1
  143. {claude_mpm-4.2.43.dist-info → claude_mpm-4.2.51.dist-info}/RECORD +148 -87
  144. claude_mpm/commands/mpm-browser-monitor.md +0 -370
  145. claude_mpm/commands/mpm-monitor.md +0 -177
  146. claude_mpm/dashboard/static/js/browser-console-monitor.js +0 -495
  147. claude_mpm/dashboard/static/js/components/browser-log-viewer.js +0 -763
  148. claude_mpm/dashboard/static/test-browser-monitor.html +0 -470
  149. claude_mpm/dashboard/static/test-simple.html +0 -97
  150. claude_mpm/services/monitor/handlers/browser.py +0 -451
  151. /claude_mpm/dashboard/static/{test_debug.html → test-archive/test_debug.html} +0 -0
  152. {claude_mpm-4.2.43.dist-info → claude_mpm-4.2.51.dist-info}/WHEEL +0 -0
  153. {claude_mpm-4.2.43.dist-info → claude_mpm-4.2.51.dist-info}/entry_points.txt +0 -0
  154. {claude_mpm-4.2.43.dist-info → claude_mpm-4.2.51.dist-info}/licenses/LICENSE +0 -0
  155. {claude_mpm-4.2.43.dist-info → claude_mpm-4.2.51.dist-info}/top_level.txt +0 -0
@@ -1,2 +1,2 @@
1
- const t=window.io;class e{constructor(){this.socket=null,this.port=null,this.connectionCallbacks={connect:[],disconnect:[],error:[],event:[]},this.eventSchema={required:["source","type","subtype","timestamp","data"],optional:["event","session_id"]},this.isConnected=!1,this.isConnecting=!1,this.lastConnectTime=null,this.disconnectTime=null,this.events=[],this.sessions=new Map,this.currentSessionId=null,this.eventQueue=[],this.maxQueueSize=100,this.retryAttempts=0,this.maxRetryAttempts=5,this.retryDelays=[1e3,2e3,3e3,4e3,5e3],this.pendingEmissions=new Map,this.lastPingTime=null,this.lastPongTime=null,this.pingTimeout=12e4,this.healthCheckInterval=null,this.startStatusCheckFallback(),this.startHealthMonitoring()}connect(t="8765"){this.port=t;const e=`http://localhost:${t}`;if(this.socket&&(this.socket.connected||this.socket.connecting))return console.log("Already connected or connecting, disconnecting first..."),this.socket.disconnect(),void setTimeout(()=>this.doConnect(e),100);this.doConnect(e)}doConnect(e){if(console.log(`Connecting to Socket.IO server at ${e}`),void 0===t)return console.error("Socket.IO library not loaded! Make sure socket.io.min.js is loaded before this script."),void this.notifyConnectionStatus("Socket.IO library not loaded","error");this.isConnecting=!0,this.notifyConnectionStatus("Connecting...","connecting"),this.socket=t(e,{autoConnect:!0,reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:1e4,reconnectionAttempts:10,timeout:3e4,forceNew:!0,transports:["websocket","polling"],pingInterval:3e4,pingTimeout:6e4}),this.setupSocketHandlers()}setupSocketHandlers(){this.socket.on("connect",()=>{console.log("Connected to Socket.IO server");const t=this.isConnected;if(this.isConnected=!0,this.isConnecting=!1,this.lastConnectTime=Date.now(),this.retryAttempts=0,this.disconnectTime&&!1===t){const t=(Date.now()-this.disconnectTime)/1e3;console.log(`Reconnected after ${t.toFixed(1)}s downtime`),this.flushEventQueue()}this.notifyConnectionStatus("Connected","connected"),window.socket=this.socket,console.log("SocketClient: Exposed socket globally as window.socket"),this.connectionCallbacks.connect.forEach(t=>t(this.socket.id)),this.requestStatus()}),this.socket.on("disconnect",t=>{const e={reason:t,timestamp:(new Date).toISOString(),wasConnected:this.isConnected,uptimeSeconds:this.lastConnectTime?((Date.now()-this.lastConnectTime)/1e3).toFixed(1):0,lastPing:this.lastPingTime?((Date.now()-this.lastPingTime)/1e3).toFixed(1)+"s ago":"never",lastPong:this.lastPongTime?((Date.now()-this.lastPongTime)/1e3).toFixed(1)+"s ago":"never"};console.log("Disconnected from server:",e),this.isConnected=!1,this.isConnecting=!1,this.disconnectTime=Date.now(),this.notifyConnectionStatus(`Disconnected: ${t}`,"disconnected"),this.connectionCallbacks.disconnect.forEach(e=>e(t));["transport close","ping timeout","transport error","io server disconnect"].includes(t)?(console.log(`Auto-reconnect triggered for reason: ${t}`),this.scheduleReconnect()):"io client disconnect"===t?console.log("Client-initiated disconnect, not auto-reconnecting"):(console.log(`Unknown disconnect reason: ${t}, attempting reconnect anyway`),this.scheduleReconnect())}),this.socket.on("connect_error",t=>{console.error("Connection error:",t),this.isConnecting=!1;const e=t.message||t.description||"Unknown error";this.notifyConnectionStatus(`Connection Error: ${e}`,"disconnected"),this.addEvent({type:"connection.error",timestamp:(new Date).toISOString(),data:{error:e,url:this.socket.io.uri,retry_attempt:this.retryAttempts}}),this.connectionCallbacks.error.forEach(t=>t(e)),this.scheduleReconnect()}),this.socket.on("claude_event",t=>{console.log("Received claude_event:",t);const e=this.validateEventSchema(t);if(!e)return void console.warn("Invalid event schema received:",t);e.type&&e.type.startsWith("code:")&&console.log("Code analysis event received via claude_event, adding to events list for troubleshooting:",e.type);const n=this.transformEvent(e);console.log("Transformed event:",n),this.addEvent(n)}),this.socket.on("ping",t=>{this.lastPingTime=Date.now(),this.socket.emit("pong",{timestamp:t.timestamp,client_time:Date.now()})}),this.socket.on("pong",t=>{this.lastPongTime=Date.now()}),this.socket.on("heartbeat",t=>{console.log("🫀 Received server heartbeat:",t),this.addEvent({type:"system",subtype:"heartbeat",timestamp:t.timestamp||(new Date).toISOString(),data:t}),this.lastPingTime=Date.now(),console.log(`Server heartbeat #${t.heartbeat_number}: ${t.server_uptime_formatted} uptime, ${t.connected_clients} clients connected`)}),this.socket.on("session.started",t=>{this.addEvent({type:"session",subtype:"started",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("session.ended",t=>{this.addEvent({type:"session",subtype:"ended",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("claude.request",t=>{this.addEvent({type:"claude",subtype:"request",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("claude.response",t=>{this.addEvent({type:"claude",subtype:"response",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("agent.loaded",t=>{this.addEvent({type:"agent",subtype:"loaded",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("agent.executed",t=>{this.addEvent({type:"agent",subtype:"executed",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("todo.updated",t=>{this.addEvent({type:"todo",subtype:"updated",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("memory.operation",t=>{this.addEvent({type:"memory",subtype:"operation",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("log.entry",t=>{this.addEvent({type:"log",subtype:"entry",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("code:analysis:queued",t=>{console.log("Code analysis queued event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"analysis:queued",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("code:analysis:accepted",t=>{console.log("Code analysis accepted event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"analysis:accepted",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("code:analysis:start",t=>{console.log("Code analysis start event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"analysis:start",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("code:analysis:complete",t=>{console.log("Code analysis complete event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"analysis:complete",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("code:analysis:error",t=>{console.log("Code analysis error event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"analysis:error",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("code:file:start",t=>{console.log("Code file start event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"file:start",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("code:node:found",t=>{console.log("Code node found event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"node:found",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("code:analysis:progress",t=>{console.log("Code analysis progress event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"analysis:progress",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("history",t=>{console.log("Received event history:",t),t&&Array.isArray(t.events)?(console.log(`Processing ${t.events.length} historical events (${t.count} sent, ${t.total_available} total available)`),t.events.forEach(t=>{const e=this.transformEvent(t);this.addEvent(e,!1)}),this.notifyEventUpdate(),console.log(`Event history loaded: ${t.events.length} events added to dashboard`)):Array.isArray(t)&&(console.log("Received legacy event history format:",t.length,"events"),t.forEach(t=>{const e=this.transformEvent(t);this.addEvent(e,!1)}),this.notifyEventUpdate())}),this.socket.on("system.status",t=>{console.log("Received system status:",t),t.sessions&&this.updateSessions(t.sessions),t.current_session&&(this.currentSessionId=t.current_session)})}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null),this.port=null,this.isConnected=!1,this.isConnecting=!1}emitWithRetry(t,e=null,n={}){const{maxRetries:s=3,retryDelays:o=[1e3,2e3,4e3],onSuccess:i=null,onFailure:a=null}=n,c=`${t}_${Date.now()}_${Math.random()}`,l=(n=0)=>{if(this.socket&&this.socket.connected)try{this.socket.emit(t,e),console.log(`Emitted ${t} successfully`),this.pendingEmissions.delete(c),i&&i()}catch(r){if(console.error(`Failed to emit ${t} (attempt ${n+1}):`,r),n<s-1){const s=o[n]||o[o.length-1];console.log(`Retrying ${t} in ${s}ms...`),this.pendingEmissions.set(c,{event:t,data:e,attemptNum:n+1,scheduledTime:Date.now()+s}),setTimeout(()=>l(n+1),s)}else console.error(`Failed to emit ${t} after ${s} attempts`),this.pendingEmissions.delete(c),a&&a("max_retries_exceeded")}else 0===n&&(this.queueEvent(t,e),console.log(`Queued ${t} for later emission (disconnected)`),a&&a("disconnected"))};l()}queueEvent(t,e){if(this.eventQueue.length>=this.maxQueueSize){const t=this.eventQueue.shift();console.warn(`Event queue full, dropped oldest event: ${t.event}`)}this.eventQueue.push({event:t,data:e,timestamp:Date.now()})}flushEventQueue(){if(0===this.eventQueue.length)return;console.log(`Flushing ${this.eventQueue.length} queued events...`);const t=[...this.eventQueue];this.eventQueue=[],t.forEach((t,e)=>{setTimeout(()=>{this.socket&&this.socket.connected&&(this.socket.emit(t.event,t.data),console.log(`Flushed queued event: ${t.event}`))},100*e)})}scheduleReconnect(){if(this.retryAttempts>=this.maxRetryAttempts)return console.log("Max reconnection attempts reached, stopping auto-reconnect"),void this.notifyConnectionStatus("Reconnection failed","disconnected");const t=this.retryDelays[this.retryAttempts]||this.retryDelays[this.retryDelays.length-1];this.retryAttempts++,console.log(`Scheduling reconnect attempt ${this.retryAttempts}/${this.maxRetryAttempts} in ${t}ms...`),this.notifyConnectionStatus(`Reconnecting in ${t/1e3}s...`,"connecting"),setTimeout(()=>{!this.isConnected&&this.port&&(console.log(`Attempting reconnection ${this.retryAttempts}/${this.maxRetryAttempts}...`),this.connect(this.port))},t)}requestStatus(){this.socket&&this.socket.connected&&(console.log("Requesting server status..."),this.emitWithRetry("request.status",null,{maxRetries:2,retryDelays:[500,1e3]}))}requestHistory(t={}){if(this.socket&&this.socket.connected){const e={limit:t.limit||50,event_types:t.event_types||[]};console.log("Requesting event history...",e),this.emitWithRetry("get_history",e,{maxRetries:3,retryDelays:[1e3,2e3,3e3],onFailure:t=>{console.error(`Failed to request history: ${t}`)}})}else console.warn("Cannot request history: not connected to server")}addEvent(t,e=!0){if(t.timestamp||(t.timestamp=(new Date).toISOString()),t.id||(t.id=Date.now()+Math.random()),this.events.push(t),t.data&&t.data.session_id){const e=t.data.session_id;this.sessions.has(e)||this.sessions.set(e,{id:e,startTime:t.timestamp,lastActivity:t.timestamp,eventCount:0,working_directory:null,git_branch:null});const n=this.sessions.get(e);n.lastActivity=t.timestamp,n.eventCount++;const s=[t.data.cwd,t.data.working_directory,t.data.working_dir,t.data.workingDirectory,t.data.instance_info?.working_dir,t.data.instance_info?.working_directory,t.data.instance_info?.cwd,t.cwd,t.working_directory,t.working_dir];for(const t of s)if(t&&"string"==typeof t&&t.trim()){n.working_directory=t,console.log(`[SOCKET-CLIENT] Found working directory for session ${e}:`,t);break}t.data.git_branch?n.git_branch=t.data.git_branch:t.data.instance_info&&t.data.instance_info.git_branch&&(n.git_branch=t.data.instance_info.git_branch)}e&&this.notifyEventUpdate()}updateSessions(t){Array.isArray(t)&&t.forEach(t=>{this.sessions.set(t.id,t)})}clearEvents(){this.events=[],this.sessions.clear(),this.notifyEventUpdate()}refreshHistory(t={}){this.clearEvents(),this.requestHistory(t)}getEventsBySession(t=null){return t?this.events.filter(e=>e.data&&e.data.session_id===t):this.events}onConnection(t,e){this.connectionCallbacks[t]&&this.connectionCallbacks[t].push(e)}onEventUpdate(t){this.connectionCallbacks.event.push(t)}on(t,e){if(this.socket)return this.socket.on(t,e);console.warn(`Cannot subscribe to '${t}': socket not initialized`)}off(t,e){if(this.socket)return this.socket.off(t,e);console.warn(`Cannot unsubscribe from '${t}': socket not initialized`)}notifyConnectionStatus(t,e){console.log(`SocketClient: Connection status changed to '${t}' (${e})`),this.updateConnectionStatusDOM(t,e),document.dispatchEvent(new CustomEvent("socketConnectionStatus",{detail:{status:t,type:e}}))}updateConnectionStatusDOM(t,e){const n=document.getElementById("connection-status");n?(n.innerHTML=`<span>●</span> ${t}`,n.className=`status-badge status-${e}`,console.log(`SocketClient: Direct DOM update - status: '${t}' (${e})`)):console.warn("SocketClient: Could not find connection-status element in DOM")}notifyEventUpdate(){this.connectionCallbacks.event.forEach(t=>t(this.events,this.sessions)),document.dispatchEvent(new CustomEvent("socketEventUpdate",{detail:{events:this.events,sessions:this.sessions}}))}getConnectionState(){return{isConnected:this.isConnected,isConnecting:this.isConnecting,socketId:this.socket?this.socket.id:null}}validateEventSchema(t){if(!t||"object"!=typeof t)return console.warn("Event data is not an object:",t),null;const e={...t};return e.source||(e.source="system"),e.type||(e.event?e.type=e.event:e.type="unknown"),e.subtype||(e.subtype="generic"),e.timestamp||(e.timestamp=(new Date).toISOString()),e.data||(e.data={}),e.data&&"object"!=typeof e.data&&(e.data={value:e.data}),console.log("Validated event:",e),e}transformEvent(t){if(!t)return t;let e={...t};if(t.type&&t.subtype&&!t.type.includes(".")&&!t.type.includes(":"))e.originalEventName||("generic"===t.subtype||t.type===t.subtype?e.originalEventName=t.type:e.originalEventName=`${t.type}.${t.subtype}`);else if(!t.type&&t.event){const n=t.event;"TestStart"===n||"TestEnd"===n?(e.type="test",e.subtype=n.toLowerCase().replace("test","")):"SubagentStart"===n||"SubagentStop"===n?(e.type="subagent",e.subtype=n.toLowerCase().replace("subagent","")):"ToolCall"===n?(e.type="tool",e.subtype="call"):"UserPrompt"===n?(e.type="hook",e.subtype="user_prompt"):(e.type="unknown",e.subtype=n.toLowerCase(),e.type===e.subtype&&(e.subtype="event")),delete e.event,e.originalEventName=n}else if(t.type){const n=t.type;if(n.startsWith("hook.")){const t=n.substring(5);e.type="hook",e.subtype=t,e.originalEventName=n}else if(n.startsWith("code:")){e.type="code";const t=n.substring(5);e.subtype=t.replace(/:/g,"_"),e.originalEventName=n}else if(n.includes(".")){const[t,...s]=n.split(".");e.type=t,e.subtype=s.join("."),e.originalEventName=n}else if(n.includes(":")){const t=n.split(":",2);e.type=t[0],e.subtype=t.length>1?t[1].replace(/:/g,"_"):"generic",e.originalEventName=n}else t.subtype||(e.subtype="generic",e.originalEventName=n)}else e.type="unknown",e.subtype="",e.originalEventName="unknown";if(t.data&&"object"==typeof t.data){const n=["type","subtype","timestamp","id","event","event_type","originalEventName"];Object.keys(t.data).forEach(s=>{n.includes(s)?"timestamp"!==s&&console.debug(`Protected field '${s}' in data object was not copied to top level to preserve event structure`):"tool_parameters"===s&&"object"==typeof t.data[s]?e[s]=JSON.parse(JSON.stringify(t.data[s])):e[s]=t.data[s]}),e.data=t.data}if("hook"===e.type?"pre_tool"===e.subtype?e.hook_event_name="PreToolUse":"post_tool"===e.subtype?e.hook_event_name="PostToolUse":"subagent_start"===e.subtype?e.hook_event_name="SubagentStart":"subagent_stop"===e.subtype?e.hook_event_name="SubagentStop":"todo_write"===e.subtype?e.hook_event_name="TodoWrite":"start"===e.subtype?e.hook_event_name="Start":"stop"===e.subtype&&(e.hook_event_name="Stop"):"subagent"===e.type?"start"===e.subtype?e.hook_event_name="SubagentStart":"stop"===e.subtype&&(e.hook_event_name="SubagentStop"):"todo"===e.type&&"updated"===e.subtype&&(e.hook_event_name="TodoWrite"),"hook"===e.type&&("pre_tool"===e.subtype||"post_tool"===e.subtype)){console.log("Transformed tool event:",{type:e.type,subtype:e.subtype,hook_event_name:e.hook_event_name,tool_name:e.tool_name,has_tool_parameters:!!e.tool_parameters,tool_parameters:e.tool_parameters,has_data:!!e.data,keys:Object.keys(e).filter(t=>"data"!==t)});["Read","Write","Edit","MultiEdit","NotebookEdit"].includes(e.tool_name)&&console.log("File tool event details:",{tool_name:e.tool_name,file_path:e.tool_parameters?.file_path,path:e.tool_parameters?.path,notebook_path:e.tool_parameters?.notebook_path,full_parameters:e.tool_parameters})}return e}getState(){return{events:this.events,sessions:this.sessions,currentSessionId:this.currentSessionId}}startHealthMonitoring(){this.healthCheckInterval=setInterval(()=>{if(this.isConnected&&this.lastPingTime){const t=Date.now()-this.lastPingTime;t>this.pingTimeout&&(console.warn(`No ping from server for ${t/1e3}s, connection may be stale`),this.socket&&(console.log("Forcing reconnection due to stale connection..."),this.socket.disconnect(),setTimeout(()=>{this.port&&this.connect(this.port)},1e3)))}},1e4)}stopHealthMonitoring(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null)}startStatusCheckFallback(){setInterval(()=>{this.checkAndUpdateStatus()},2e3),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{setTimeout(()=>this.checkAndUpdateStatus(),100)}):setTimeout(()=>this.checkAndUpdateStatus(),100)}checkAndUpdateStatus(){let t="Disconnected",e="disconnected";this.socket&&(this.socket.connected?(t="Connected",e="connected",this.isConnected=!0,this.isConnecting=!1):this.socket.connecting||this.isConnecting?(t="Connecting...",e="connecting",this.isConnected=!1):(t="Disconnected",e="disconnected",this.isConnected=!1,this.isConnecting=!1));const n=document.getElementById("connection-status");if(n){const s=n.textContent.replace("●","").trim(),o=n.className,i=`status-badge status-${e}`;s===t&&o===i||(console.log(`SocketClient: Fallback update - was '${s}' (${o}), now '${t}' (${i})`),this.updateConnectionStatusDOM(t,e))}}destroy(){this.stopHealthMonitoring(),this.socket&&(this.socket.disconnect(),this.socket=null),this.eventQueue=[],this.pendingEmissions.clear()}getConnectionMetrics(){return{isConnected:this.isConnected,uptime:this.lastConnectTime?(Date.now()-this.lastConnectTime)/1e3:0,lastPing:this.lastPingTime?(Date.now()-this.lastPingTime)/1e3:null,queuedEvents:this.eventQueue.length,pendingEmissions:this.pendingEmissions.size,retryAttempts:this.retryAttempts}}}window.SocketClient=e;class n{constructor(){this.socketClient=null,this.connectionCallbacks=new Set,this.eventUpdateCallbacks=new Set,this.socketClient=new e,window.socketClient=this.socketClient,this.setupSocketEventHandlers(),setTimeout(()=>{this.updateInitialConnectionStatus()},100),console.log("Socket manager initialized")}setupSocketEventHandlers(){document.addEventListener("socketConnectionStatus",t=>{console.log(`SocketManager: Processing connection status update: ${t.detail.status} (${t.detail.type})`),this.handleConnectionStatusChange(t.detail.status,t.detail.type),this.connectionCallbacks.forEach(e=>{try{e(t.detail.status,t.detail.type)}catch(n){console.error("Error in connection callback:",n)}})}),this.socketClient&&this.socketClient.onEventUpdate(t=>{this.eventUpdateCallbacks.forEach(e=>{try{e(t)}catch(n){console.error("Error in event update callback:",n)}})})}handleConnectionStatusChange(t,e){this.updateConnectionStatus(t,e),"connected"===e&&this.socketClient&&this.socketClient.socket&&(window.socket=this.socketClient.socket,console.log("SocketManager: Exposed socket globally as window.socket"),this.setupGitBranchListener())}updateInitialConnectionStatus(){console.log("SocketManager: Updating initial connection status"),this.socketClient&&"function"==typeof this.socketClient.checkAndUpdateStatus?(console.log("SocketManager: Using socket client checkAndUpdateStatus method"),this.socketClient.checkAndUpdateStatus()):this.socketClient&&this.socketClient.socket?(console.log("SocketManager: Checking socket state directly",{connected:this.socketClient.socket.connected,connecting:this.socketClient.socket.connecting,isConnecting:this.socketClient.isConnecting,isConnected:this.socketClient.isConnected}),this.socketClient.socket.connected?(console.log("SocketManager: Socket is already connected, updating status"),window.socket=this.socketClient.socket,console.log("SocketManager: Exposed socket globally as window.socket"),this.updateConnectionStatus("Connected","connected")):this.socketClient.isConnecting||this.socketClient.socket.connecting?(console.log("SocketManager: Socket is connecting, updating status"),this.updateConnectionStatus("Connecting...","connecting")):(console.log("SocketManager: Socket is disconnected, updating status"),this.updateConnectionStatus("Disconnected","disconnected"))):(console.log("SocketManager: No socket client or socket found, setting disconnected status"),this.updateConnectionStatus("Disconnected","disconnected")),setTimeout(()=>{console.log("SocketManager: Secondary status check after 1 second"),this.socketClient&&this.socketClient.socket&&this.socketClient.socket.connected&&(console.log("SocketManager: Socket connected in secondary check, updating status"),window.socket||(window.socket=this.socketClient.socket,console.log("SocketManager: Exposed socket globally as window.socket (secondary check)")),this.updateConnectionStatus("Connected","connected"))},1e3)}setupGitBranchListener(){this.socketClient.socket.off("git_branch_response"),this.socketClient.socket.on("git_branch_response",t=>{if(t.success){const e=document.getElementById("footer-git-branch");e&&(e.textContent=t.branch||"unknown"),e&&(e.style.display="inline")}else console.error("Git branch request failed:",t.error)})}updateConnectionStatus(t,e){const n=document.getElementById("connection-status");if(n){if(n.querySelector("span")){const e="●";n.innerHTML=`<span>${e}</span> ${t}`}else n.textContent=t;n.className=`status-badge status-${e}`,console.log(`SocketManager: UI updated - status: '${t}' (${e})`)}else console.error("SocketManager: Could not find connection-status element in DOM")}connect(t){this.socketClient&&this.socketClient.connect(t)}disconnect(){this.socketClient&&this.socketClient.disconnect()}isConnected(){return this.socketClient&&this.socketClient.isConnected}isConnecting(){return this.socketClient&&this.socketClient.isConnecting}getSocketClient(){return this.socketClient}getSocket(){return this.socketClient?this.socketClient.socket:null}onConnectionStatusChange(t){this.connectionCallbacks.add(t)}offConnectionStatusChange(t){this.connectionCallbacks.delete(t)}onEventUpdate(t){this.eventUpdateCallbacks.add(t)}offEventUpdate(t){this.eventUpdateCallbacks.delete(t)}toggleConnectionControls(){const t=document.getElementById("connection-controls-row"),e=document.getElementById("connection-toggle-btn");if(t&&e){t.classList.contains("show")?(t.classList.remove("show"),t.style.display="none",e.textContent="Connection Settings"):(t.classList.add("show"),t.style.display="block",e.textContent="Hide Settings")}}setupConnectionControls(){const t=document.getElementById("connect-btn"),e=document.getElementById("disconnect-btn"),n=document.getElementById("connection-toggle-btn");t&&t.addEventListener("click",()=>{const t=document.getElementById("port-input").value||8765;this.connect(t)}),e&&e.addEventListener("click",()=>{this.disconnect()}),n&&n.addEventListener("click",()=>{this.toggleConnectionControls()})}initializeFromURL(t){const e=t.get("port"),n=document.getElementById("port-input");let s=e;s||"http:"!==window.location.protocol||(s=window.location.port||"8765"),s||(s=n?.value||"8765"),n&&(n.value=s);!("false"!==t.get("connect"))||this.isConnected()||this.isConnecting()||(console.log(`SocketManager: Auto-connecting to port ${s}`),this.connect(s))}}class s{constructor(){this.currentTab="events",this.autoScroll=!0,this.selectedCard={tab:null,index:null,type:null,data:null},this.tabNavigation={events:{selectedIndex:-1,items:[]},agents:{selectedIndex:-1,items:[]},tools:{selectedIndex:-1,items:[]},files:{selectedIndex:-1,items:[]}},this.setupEventHandlers(),console.log("UI state manager initialized")}setupEventHandlers(){this.setupTabNavigation(),this.setupUnifiedKeyboardNavigation()}setupTabNavigation(){document.querySelectorAll(".tab-button").forEach(t=>{t.addEventListener("click",()=>{const e=this.getTabNameFromButton(t);this.switchTab(e)})})}setupUnifiedKeyboardNavigation(){document.addEventListener("keydown",t=>{document.activeElement&&["INPUT","TEXTAREA","SELECT"].includes(document.activeElement.tagName)||("ArrowUp"===t.key||"ArrowDown"===t.key?(t.preventDefault(),this.handleUnifiedArrowNavigation("ArrowDown"===t.key?1:-1)):"Enter"===t.key?(t.preventDefault(),this.handleUnifiedEnterKey()):"Escape"===t.key&&this.clearUnifiedSelection())})}getTabNameFromButton(t){const e=t.textContent.toLowerCase();return e.includes("events")?"events":e.includes("activity")?"activity":e.includes("agents")?"agents":e.includes("tools")?"tools":e.includes("files")?"files":e.includes("code")?"code":e.includes("sessions")?"sessions":e.includes("system")?"system":"events"}switchTab(t){console.log(`[DEBUG] switchTab called with tabName: ${t}`);const e=this.currentTab;this.currentTab=t,document.querySelectorAll(".tab-button").forEach(e=>{e.classList.remove("active"),this.getTabNameFromButton(e)===t&&e.classList.add("active")}),document.querySelectorAll(".tab-content").forEach(t=>{t.classList.remove("active")});const n=document.getElementById(`${t}-tab`);n&&n.classList.add("active"),this.clearUnifiedSelection(),document.dispatchEvent(new CustomEvent("tabChanged",{detail:{newTab:t,previousTab:e}})),setTimeout(()=>{this.autoScroll&&this.scrollCurrentTabToBottom()},100)}handleUnifiedArrowNavigation(t){const e=this.tabNavigation[this.currentTab];if(!e)return;let n=e.selectedIndex+t;0!==e.items.length&&(n<0?n=e.items.length-1:n>=e.items.length&&(n=0),this.selectCardByIndex(this.currentTab,n))}handleUnifiedEnterKey(){const t=this.tabNavigation[this.currentTab];if(!t||-1===t.selectedIndex)return;const e=t.items[t.selectedIndex];e&&e.onclick&&e.onclick()}clearUnifiedSelection(){Object.keys(this.tabNavigation).forEach(t=>{this.tabNavigation[t].selectedIndex=-1}),this.clearCardSelection()}updateTabNavigationItems(){const t=this.tabNavigation[this.currentTab];if(!t)return;let e;switch(this.currentTab){case"events":e="#events-list .event-item";break;case"agents":e="#agents-list .event-item";break;case"tools":e="#tools-list .event-item";break;case"files":e="#files-list .event-item"}e&&(t.items=Array.from(document.querySelectorAll(e)))}selectCardByIndex(t,e){const n=this.tabNavigation[t];if(!n||e<0||e>=n.items.length)return;n.selectedIndex=e,this.updateUnifiedSelectionUI();n.items[e]&&this.selectCard(t,e,this.getCardType(t),e),this.showCardDetails(t,e)}updateUnifiedSelectionUI(){document.querySelectorAll(".event-item.keyboard-selected").forEach(t=>{t.classList.remove("keyboard-selected")});const t=this.tabNavigation[this.currentTab];t&&-1!==t.selectedIndex&&t.items[t.selectedIndex]&&t.items[t.selectedIndex].classList.add("keyboard-selected")}showCardDetails(t,e){document.dispatchEvent(new CustomEvent("showCardDetails",{detail:{tabName:t,index:e}}))}selectCard(t,e,n,s){this.clearCardSelection(),this.selectedCard={tab:t,index:e,type:n,data:s},this.updateCardSelectionUI(),console.log("Card selected:",this.selectedCard)}clearCardSelection(){document.querySelectorAll(".event-item.selected, .file-item.selected").forEach(t=>{t.classList.remove("selected")}),this.selectedCard={tab:null,index:null,type:null,data:null}}updateCardSelectionUI(){if(!this.selectedCard.tab||null===this.selectedCard.index)return;let t;switch(this.selectedCard.tab){case"events":t=document.getElementById("events-list");break;case"agents":t=document.getElementById("agents-list");break;case"tools":t=document.getElementById("tools-list");break;case"files":t=document.getElementById("files-list")}if(t){const e=t.querySelectorAll(".event-item, .file-item");e[this.selectedCard.index]&&e[this.selectedCard.index].classList.add("selected")}}getCardType(t){switch(t){case"events":return"event";case"agents":return"agent";case"tools":return"tool";case"files":return"file";default:return"unknown"}}scrollCurrentTabToBottom(){const t=`${this.currentTab}-list`,e=document.getElementById(t);e&&this.autoScroll&&(e.scrollTop=e.scrollHeight)}clearSelection(){this.clearCardSelection(),this.clearUnifiedSelection()}getCurrentTab(){return this.currentTab}getSelectedCard(){return{...this.selectedCard}}getTabNavigation(){return{...this.tabNavigation}}setAutoScroll(t){this.autoScroll=t}getAutoScroll(){return this.autoScroll}}export{n as S,s as U};
1
+ const e=window.io;class t{constructor(){this.socket=null,this.port=null,this.connectionCallbacks={connect:[],disconnect:[],error:[],event:[]},this.eventSchema={required:["source","type","subtype","timestamp","data"],optional:["event","session_id"]},this.isConnected=!1,this.isConnecting=!1,this.lastConnectTime=null,this.disconnectTime=null,this.events=[],this.sessions=new Map,this.currentSessionId=null,this.eventQueue=[],this.maxQueueSize=100,this.retryAttempts=0,this.maxRetryAttempts=5,this.retryDelays=[1e3,2e3,3e3,4e3,5e3],this.pendingEmissions=new Map,this.lastPingTime=null,this.lastPongTime=null,this.pingTimeout=12e4,this.healthCheckInterval=null,this.startStatusCheckFallback(),this.startHealthMonitoring()}connect(e="8765"){this.port=e;const t=`http://localhost:${e}`;if(this.socket&&(this.socket.connected||this.socket.connecting))return console.log("Already connected or connecting, disconnecting first..."),this.socket.disconnect(),void setTimeout(()=>this.doConnect(t),100);this.doConnect(t)}doConnect(t){if(console.log(`Connecting to Socket.IO server at ${t}`),void 0===e)return console.error("Socket.IO library not loaded! Make sure socket.io.min.js is loaded before this script."),void this.notifyConnectionStatus("Socket.IO library not loaded","error");this.isConnecting=!0,this.notifyConnectionStatus("Connecting...","connecting"),this.socket=e(t,{autoConnect:!0,reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:1e4,reconnectionAttempts:10,timeout:3e4,forceNew:!0,transports:["websocket","polling"]}),this.setupSocketHandlers()}setupSocketHandlers(){this.socket.on("connect",()=>{console.log("Connected to Socket.IO server");const e=this.isConnected;if(this.isConnected=!0,this.isConnecting=!1,this.lastConnectTime=Date.now(),this.retryAttempts=0,this.disconnectTime&&!1===e){const e=(Date.now()-this.disconnectTime)/1e3;console.log(`Reconnected after ${e.toFixed(1)}s downtime`),this.flushEventQueue()}this.notifyConnectionStatus("Connected","connected"),window.socket=this.socket,console.log("SocketClient: Exposed socket globally as window.socket"),this.connectionCallbacks.connect.forEach(e=>e(this.socket.id)),this.requestStatus()}),this.socket.on("disconnect",e=>{const t={reason:e,timestamp:(new Date).toISOString(),wasConnected:this.isConnected,uptimeSeconds:this.lastConnectTime?((Date.now()-this.lastConnectTime)/1e3).toFixed(1):0,lastPing:this.lastPingTime?((Date.now()-this.lastPingTime)/1e3).toFixed(1)+"s ago":"never",lastPong:this.lastPongTime?((Date.now()-this.lastPongTime)/1e3).toFixed(1)+"s ago":"never"};console.log("Disconnected from server:",t),this.isConnected=!1,this.isConnecting=!1,this.disconnectTime=Date.now(),this.notifyConnectionStatus(`Disconnected: ${e}`,"disconnected"),this.connectionCallbacks.disconnect.forEach(t=>t(e));["transport close","ping timeout","transport error","io server disconnect"].includes(e)?(console.log(`Auto-reconnect triggered for reason: ${e}`),this.scheduleReconnect()):"io client disconnect"===e?console.log("Client-initiated disconnect, not auto-reconnecting"):(console.log(`Unknown disconnect reason: ${e}, attempting reconnect anyway`),this.scheduleReconnect())}),this.socket.on("connect_error",e=>{console.error("Connection error:",e),this.isConnecting=!1;const t=e.message||e.description||"Unknown error";this.notifyConnectionStatus(`Connection Error: ${t}`,"disconnected"),this.addEvent({type:"connection.error",timestamp:(new Date).toISOString(),data:{error:t,url:this.socket.io.uri,retry_attempt:this.retryAttempts}}),this.connectionCallbacks.error.forEach(e=>e(t)),this.scheduleReconnect()}),this.socket.on("claude_event",e=>{console.log("Received claude_event:",e);const t=this.validateEventSchema(e);if(!t)return void console.warn("Invalid event schema received:",e);t.type&&t.type.startsWith("code:")&&console.log("Code analysis event received via claude_event, adding to events list for troubleshooting:",t.type);const n=this.transformEvent(t);console.log("Transformed event:",n),this.addEvent(n)}),this.socket.on("ping",e=>{this.lastPingTime=Date.now(),this.socket.emit("pong",{timestamp:e.timestamp,client_time:Date.now()})}),this.socket.on("pong",e=>{this.lastPongTime=Date.now()}),this.socket.on("heartbeat",e=>{console.log("🫀 Received server heartbeat:",e),this.addEvent({type:"system",subtype:"heartbeat",timestamp:e.timestamp||(new Date).toISOString(),data:e}),this.lastPingTime=Date.now(),console.log(`Server heartbeat #${e.heartbeat_number}: ${e.server_uptime_formatted} uptime, ${e.connected_clients} clients connected`)}),this.socket.on("session.started",e=>{this.addEvent({type:"session",subtype:"started",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("session.ended",e=>{this.addEvent({type:"session",subtype:"ended",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("claude.request",e=>{this.addEvent({type:"claude",subtype:"request",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("claude.response",e=>{this.addEvent({type:"claude",subtype:"response",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("agent.loaded",e=>{this.addEvent({type:"agent",subtype:"loaded",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("agent.executed",e=>{this.addEvent({type:"agent",subtype:"executed",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("todo.updated",e=>{this.addEvent({type:"todo",subtype:"updated",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("memory.operation",e=>{this.addEvent({type:"memory",subtype:"operation",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("log.entry",e=>{this.addEvent({type:"log",subtype:"entry",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("code:analysis:queued",e=>{console.log("Code analysis queued event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"analysis:queued",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("code:analysis:accepted",e=>{console.log("Code analysis accepted event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"analysis:accepted",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("code:analysis:start",e=>{console.log("Code analysis start event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"analysis:start",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("code:analysis:complete",e=>{console.log("Code analysis complete event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"analysis:complete",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("code:analysis:error",e=>{console.log("Code analysis error event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"analysis:error",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("code:file:start",e=>{console.log("Code file start event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"file:start",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("code:node:found",e=>{console.log("Code node found event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"node:found",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("code:analysis:progress",e=>{console.log("Code analysis progress event received, adding to events list for troubleshooting"),this.addEvent({type:"code",subtype:"analysis:progress",timestamp:(new Date).toISOString(),data:e})}),this.socket.on("history",e=>{console.log("Received event history:",e),e&&Array.isArray(e.events)?(console.log(`Processing ${e.events.length} historical events (${e.count} sent, ${e.total_available} total available)`),e.events.forEach(e=>{const t=this.transformEvent(e);this.addEvent(t,!1)}),this.notifyEventUpdate(),console.log(`Event history loaded: ${e.events.length} events added to dashboard`)):Array.isArray(e)&&(console.log("Received legacy event history format:",e.length,"events"),e.forEach(e=>{const t=this.transformEvent(e);this.addEvent(t,!1)}),this.notifyEventUpdate())}),this.socket.on("system.status",e=>{console.log("Received system status:",e),e.sessions&&this.updateSessions(e.sessions),e.current_session&&(this.currentSessionId=e.current_session)})}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null),this.port=null,this.isConnected=!1,this.isConnecting=!1}emitWithRetry(e,t=null,n={}){const{maxRetries:o=3,retryDelays:s=[1e3,2e3,4e3],onSuccess:i=null,onFailure:a=null}=n,c=`${e}_${Date.now()}_${Math.random()}`,l=(n=0)=>{if(this.socket&&this.socket.connected)try{this.socket.emit(e,t),console.log(`Emitted ${e} successfully`),this.pendingEmissions.delete(c),i&&i()}catch(r){if(console.error(`Failed to emit ${e} (attempt ${n+1}):`,r),n<o-1){const o=s[n]||s[s.length-1];console.log(`Retrying ${e} in ${o}ms...`),this.pendingEmissions.set(c,{event:e,data:t,attemptNum:n+1,scheduledTime:Date.now()+o}),setTimeout(()=>l(n+1),o)}else console.error(`Failed to emit ${e} after ${o} attempts`),this.pendingEmissions.delete(c),a&&a("max_retries_exceeded")}else 0===n&&(this.queueEvent(e,t),console.log(`Queued ${e} for later emission (disconnected)`),a&&a("disconnected"))};l()}queueEvent(e,t){if(this.eventQueue.length>=this.maxQueueSize){const e=this.eventQueue.shift();console.warn(`Event queue full, dropped oldest event: ${e.event}`)}this.eventQueue.push({event:e,data:t,timestamp:Date.now()})}flushEventQueue(){if(0===this.eventQueue.length)return;console.log(`Flushing ${this.eventQueue.length} queued events...`);const e=[...this.eventQueue];this.eventQueue=[],e.forEach((e,t)=>{setTimeout(()=>{this.socket&&this.socket.connected&&(this.socket.emit(e.event,e.data),console.log(`Flushed queued event: ${e.event}`))},100*t)})}scheduleReconnect(){if(this.retryAttempts>=this.maxRetryAttempts)return console.log("Max reconnection attempts reached, stopping auto-reconnect"),void this.notifyConnectionStatus("Reconnection failed","disconnected");const e=this.retryDelays[this.retryAttempts]||this.retryDelays[this.retryDelays.length-1];this.retryAttempts++,console.log(`Scheduling reconnect attempt ${this.retryAttempts}/${this.maxRetryAttempts} in ${e}ms...`),this.notifyConnectionStatus(`Reconnecting in ${e/1e3}s...`,"connecting"),setTimeout(()=>{!this.isConnected&&this.port&&(console.log(`Attempting reconnection ${this.retryAttempts}/${this.maxRetryAttempts}...`),this.connect(this.port))},e)}requestStatus(){this.socket&&this.socket.connected&&(console.log("Requesting server status..."),this.emitWithRetry("request.status",null,{maxRetries:2,retryDelays:[500,1e3]}))}requestHistory(e={}){if(this.socket&&this.socket.connected){const t={limit:e.limit||50,event_types:e.event_types||[]};console.log("Requesting event history...",t),this.emitWithRetry("get_history",t,{maxRetries:3,retryDelays:[1e3,2e3,3e3],onFailure:e=>{console.error(`Failed to request history: ${e}`)}})}else console.warn("Cannot request history: not connected to server")}addEvent(e,t=!0){if(e.timestamp||(e.timestamp=(new Date).toISOString()),e.id||(e.id=Date.now()+Math.random()),this.events.push(e),e.data&&e.data.session_id){const t=e.data.session_id;this.sessions.has(t)||this.sessions.set(t,{id:t,startTime:e.timestamp,lastActivity:e.timestamp,eventCount:0,working_directory:null,git_branch:null});const n=this.sessions.get(t);n.lastActivity=e.timestamp,n.eventCount++;const o=[e.data.cwd,e.data.working_directory,e.data.working_dir,e.data.workingDirectory,e.data.instance_info?.working_dir,e.data.instance_info?.working_directory,e.data.instance_info?.cwd,e.cwd,e.working_directory,e.working_dir];for(const e of o)if(e&&"string"==typeof e&&e.trim()){n.working_directory=e,console.log(`[SOCKET-CLIENT] Found working directory for session ${t}:`,e);break}e.data.git_branch?n.git_branch=e.data.git_branch:e.data.instance_info&&e.data.instance_info.git_branch&&(n.git_branch=e.data.instance_info.git_branch)}t&&this.notifyEventUpdate()}updateSessions(e){Array.isArray(e)&&e.forEach(e=>{this.sessions.set(e.id,e)})}clearEvents(){this.events=[],this.sessions.clear(),this.notifyEventUpdate()}refreshHistory(e={}){this.clearEvents(),this.requestHistory(e)}getEventsBySession(e=null){return e?this.events.filter(t=>t.data&&t.data.session_id===e):this.events}onConnection(e,t){this.connectionCallbacks[e]&&this.connectionCallbacks[e].push(t)}onEventUpdate(e){this.connectionCallbacks.event.push(e)}on(e,t){if(this.socket)return this.socket.on(e,t);console.warn(`Cannot subscribe to '${e}': socket not initialized`)}off(e,t){if(this.socket)return this.socket.off(e,t);console.warn(`Cannot unsubscribe from '${e}': socket not initialized`)}notifyConnectionStatus(e,t){console.log(`SocketClient: Connection status changed to '${e}' (${t})`),this.updateConnectionStatusDOM(e,t),document.dispatchEvent(new CustomEvent("socketConnectionStatus",{detail:{status:e,type:t}}))}updateConnectionStatusDOM(e,t){const n=document.getElementById("connection-status");n?(n.innerHTML=`<span>●</span> ${e}`,n.className=`status-badge status-${t}`,console.log(`SocketClient: Direct DOM update - status: '${e}' (${t})`)):console.warn("SocketClient: Could not find connection-status element in DOM")}notifyEventUpdate(){this.connectionCallbacks.event.forEach(e=>e(this.events,this.sessions)),document.dispatchEvent(new CustomEvent("socketEventUpdate",{detail:{events:this.events,sessions:this.sessions}}))}getConnectionState(){return{isConnected:this.isConnected,isConnecting:this.isConnecting,socketId:this.socket?this.socket.id:null}}validateEventSchema(e){if(!e||"object"!=typeof e)return console.warn("Event data is not an object:",e),null;const t={...e};return t.source||(t.source="system"),t.type||(t.event?t.type=t.event:t.type="unknown"),t.subtype||(t.subtype="generic"),t.timestamp||(t.timestamp=(new Date).toISOString()),t.data||(t.data={}),t.data&&"object"!=typeof t.data&&(t.data={value:t.data}),console.log("Validated event:",t),t}transformEvent(e){if(!e)return e;let t={...e};if(e.type&&e.subtype&&!e.type.includes(".")&&!e.type.includes(":"))t.originalEventName||("generic"===e.subtype||e.type===e.subtype?t.originalEventName=e.type:t.originalEventName=`${e.type}.${e.subtype}`);else if(!e.type&&e.event){const n=e.event;"TestStart"===n||"TestEnd"===n?(t.type="test",t.subtype=n.toLowerCase().replace("test","")):"SubagentStart"===n||"SubagentStop"===n?(t.type="subagent",t.subtype=n.toLowerCase().replace("subagent","")):"ToolCall"===n?(t.type="tool",t.subtype="call"):"UserPrompt"===n?(t.type="hook",t.subtype="user_prompt"):(t.type="unknown",t.subtype=n.toLowerCase(),t.type===t.subtype&&(t.subtype="event")),delete t.event,t.originalEventName=n}else if(e.type){const n=e.type;if(n.startsWith("hook.")){const e=n.substring(5);t.type="hook",t.subtype=e,t.originalEventName=n}else if(n.startsWith("code:")){t.type="code";const e=n.substring(5);t.subtype=e.replace(/:/g,"_"),t.originalEventName=n}else if(n.includes(".")){const[e,...o]=n.split(".");t.type=e,t.subtype=o.join("."),t.originalEventName=n}else if(n.includes(":")){const e=n.split(":",2);t.type=e[0],t.subtype=e.length>1?e[1].replace(/:/g,"_"):"generic",t.originalEventName=n}else e.subtype||(t.subtype="generic",t.originalEventName=n)}else t.type="unknown",t.subtype="",t.originalEventName="unknown";if(e.data&&"object"==typeof e.data){const n=["type","subtype","timestamp","id","event","event_type","originalEventName"];Object.keys(e.data).forEach(o=>{n.includes(o)?"timestamp"!==o&&console.debug(`Protected field '${o}' in data object was not copied to top level to preserve event structure`):"tool_parameters"===o&&"object"==typeof e.data[o]?t[o]=JSON.parse(JSON.stringify(e.data[o])):t[o]=e.data[o]}),t.data=e.data}if("hook"===t.type?"pre_tool"===t.subtype?t.hook_event_name="PreToolUse":"post_tool"===t.subtype?t.hook_event_name="PostToolUse":"subagent_start"===t.subtype?t.hook_event_name="SubagentStart":"subagent_stop"===t.subtype?t.hook_event_name="SubagentStop":"todo_write"===t.subtype?t.hook_event_name="TodoWrite":"start"===t.subtype?t.hook_event_name="Start":"stop"===t.subtype&&(t.hook_event_name="Stop"):"subagent"===t.type?"start"===t.subtype?t.hook_event_name="SubagentStart":"stop"===t.subtype&&(t.hook_event_name="SubagentStop"):"todo"===t.type&&"updated"===t.subtype&&(t.hook_event_name="TodoWrite"),"hook"===t.type&&("pre_tool"===t.subtype||"post_tool"===t.subtype)){console.log("Transformed tool event:",{type:t.type,subtype:t.subtype,hook_event_name:t.hook_event_name,tool_name:t.tool_name,has_tool_parameters:!!t.tool_parameters,tool_parameters:t.tool_parameters,has_data:!!t.data,keys:Object.keys(t).filter(e=>"data"!==e)});["Read","Write","Edit","MultiEdit","NotebookEdit"].includes(t.tool_name)&&console.log("File tool event details:",{tool_name:t.tool_name,file_path:t.tool_parameters?.file_path,path:t.tool_parameters?.path,notebook_path:t.tool_parameters?.notebook_path,full_parameters:t.tool_parameters})}return t}getState(){return{events:this.events,sessions:this.sessions,currentSessionId:this.currentSessionId}}startHealthMonitoring(){this.healthCheckInterval=setInterval(()=>{if(this.isConnected&&this.lastPingTime){const e=Date.now()-this.lastPingTime;e>this.pingTimeout&&(console.warn(`No ping from server for ${e/1e3}s, connection may be stale`),this.socket&&(console.log("Forcing reconnection due to stale connection..."),this.socket.disconnect(),setTimeout(()=>{this.port&&this.connect(this.port)},1e3)))}},1e4)}stopHealthMonitoring(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null)}startStatusCheckFallback(){setInterval(()=>{this.checkAndUpdateStatus()},2e3),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{setTimeout(()=>this.checkAndUpdateStatus(),100)}):setTimeout(()=>this.checkAndUpdateStatus(),100)}checkAndUpdateStatus(){let e="Disconnected",t="disconnected";this.socket&&(this.socket.connected?(e="Connected",t="connected",this.isConnected=!0,this.isConnecting=!1):this.socket.connecting||this.isConnecting?(e="Connecting...",t="connecting",this.isConnected=!1):(e="Disconnected",t="disconnected",this.isConnected=!1,this.isConnecting=!1));const n=document.getElementById("connection-status");if(n){const o=n.textContent.replace("●","").trim(),s=n.className,i=`status-badge status-${t}`;o===e&&s===i||(console.log(`SocketClient: Fallback update - was '${o}' (${s}), now '${e}' (${i})`),this.updateConnectionStatusDOM(e,t))}}destroy(){this.stopHealthMonitoring(),this.socket&&(this.socket.disconnect(),this.socket=null),this.eventQueue=[],this.pendingEmissions.clear()}getConnectionMetrics(){return{isConnected:this.isConnected,uptime:this.lastConnectTime?(Date.now()-this.lastConnectTime)/1e3:0,lastPing:this.lastPingTime?(Date.now()-this.lastPingTime)/1e3:null,queuedEvents:this.eventQueue.length,pendingEmissions:this.pendingEmissions.size,retryAttempts:this.retryAttempts}}}window.SocketClient=t;class n{constructor(){this.socketClient=null,this.connectionCallbacks=new Set,this.eventUpdateCallbacks=new Set,this.socketClient=new t,window.socketClient=this.socketClient,this.setupSocketEventHandlers(),setTimeout(()=>{this.updateInitialConnectionStatus()},100),console.log("Socket manager initialized")}setupSocketEventHandlers(){document.addEventListener("socketConnectionStatus",e=>{console.log(`SocketManager: Processing connection status update: ${e.detail.status} (${e.detail.type})`),this.handleConnectionStatusChange(e.detail.status,e.detail.type),this.connectionCallbacks.forEach(t=>{try{t(e.detail.status,e.detail.type)}catch(n){console.error("Error in connection callback:",n)}})}),this.socketClient&&this.socketClient.onEventUpdate(e=>{this.eventUpdateCallbacks.forEach(t=>{try{t(e)}catch(n){console.error("Error in event update callback:",n)}})})}handleConnectionStatusChange(e,t){this.updateConnectionStatus(e,t),"connected"===t&&this.socketClient&&this.socketClient.socket&&(window.socket=this.socketClient.socket,console.log("SocketManager: Exposed socket globally as window.socket"),this.setupGitBranchListener())}updateInitialConnectionStatus(){console.log("SocketManager: Updating initial connection status"),this.socketClient&&"function"==typeof this.socketClient.checkAndUpdateStatus?(console.log("SocketManager: Using socket client checkAndUpdateStatus method"),this.socketClient.checkAndUpdateStatus()):this.socketClient&&this.socketClient.socket?(console.log("SocketManager: Checking socket state directly",{connected:this.socketClient.socket.connected,connecting:this.socketClient.socket.connecting,isConnecting:this.socketClient.isConnecting,isConnected:this.socketClient.isConnected}),this.socketClient.socket.connected?(console.log("SocketManager: Socket is already connected, updating status"),window.socket=this.socketClient.socket,console.log("SocketManager: Exposed socket globally as window.socket"),this.updateConnectionStatus("Connected","connected")):this.socketClient.isConnecting||this.socketClient.socket.connecting?(console.log("SocketManager: Socket is connecting, updating status"),this.updateConnectionStatus("Connecting...","connecting")):(console.log("SocketManager: Socket is disconnected, updating status"),this.updateConnectionStatus("Disconnected","disconnected"))):(console.log("SocketManager: No socket client or socket found, setting disconnected status"),this.updateConnectionStatus("Disconnected","disconnected")),setTimeout(()=>{console.log("SocketManager: Secondary status check after 1 second"),this.socketClient&&this.socketClient.socket&&this.socketClient.socket.connected&&(console.log("SocketManager: Socket connected in secondary check, updating status"),window.socket||(window.socket=this.socketClient.socket,console.log("SocketManager: Exposed socket globally as window.socket (secondary check)")),this.updateConnectionStatus("Connected","connected"))},1e3)}setupGitBranchListener(){this.socketClient.socket.off("git_branch_response"),this.socketClient.socket.on("git_branch_response",e=>{if(e.success){const t=document.getElementById("footer-git-branch");t&&(t.textContent=e.branch||"unknown"),t&&(t.style.display="inline")}else console.error("Git branch request failed:",e.error)})}updateConnectionStatus(e,t){const n=document.getElementById("connection-status");if(n){if(n.querySelector("span")){const t="●";n.innerHTML=`<span>${t}</span> ${e}`}else n.textContent=e;n.className=`status-badge status-${t}`,console.log(`SocketManager: UI updated - status: '${e}' (${t})`)}else console.error("SocketManager: Could not find connection-status element in DOM")}connect(e){this.socketClient&&this.socketClient.connect(e)}disconnect(){this.socketClient&&this.socketClient.disconnect()}isConnected(){return this.socketClient&&this.socketClient.isConnected}isConnecting(){return this.socketClient&&this.socketClient.isConnecting}getSocketClient(){return this.socketClient}getSocket(){return this.socketClient?this.socketClient.socket:null}onConnectionStatusChange(e){this.connectionCallbacks.add(e)}offConnectionStatusChange(e){this.connectionCallbacks.delete(e)}onEventUpdate(e){this.eventUpdateCallbacks.add(e)}offEventUpdate(e){this.eventUpdateCallbacks.delete(e)}toggleConnectionControls(){const e=document.getElementById("connection-controls-row"),t=document.getElementById("connection-toggle-btn");if(e&&t){e.classList.contains("show")?(e.classList.remove("show"),e.style.display="none",t.textContent="Connection Settings"):(e.classList.add("show"),e.style.display="block",t.textContent="Hide Settings")}}setupConnectionControls(){const e=document.getElementById("connect-btn"),t=document.getElementById("disconnect-btn"),n=document.getElementById("connection-toggle-btn");e&&e.addEventListener("click",()=>{const e=document.getElementById("port-input").value||8765;this.connect(e)}),t&&t.addEventListener("click",()=>{this.disconnect()}),n&&n.addEventListener("click",()=>{this.toggleConnectionControls()})}initializeFromURL(e){const t=e.get("port"),n=document.getElementById("port-input");let o=t;o||"http:"!==window.location.protocol||(o=window.location.port||"8765"),o||(o=n?.value||"8765"),n&&(n.value=o);!("false"!==e.get("connect"))||this.isConnected()||this.isConnecting()||(console.log(`SocketManager: Auto-connecting to port ${o}`),this.connect(o))}}window.SocketManager=n;class o{constructor(){this._switching=!1,this.hashToTab={"#events":"events","#agents":"agents","#tools":"tools","#files":"files","#activity":"activity","#file_tree":"claude-tree","":"events"},this.tabToHash={events:"#events",agents:"#agents",tools:"#tools",files:"#files",activity:"#activity","claude-tree":"#file_tree"},this.currentTab=this.getTabFromHash(),this.autoScroll=!0,this.selectedCard={tab:null,index:null,type:null,data:null},this.tabNavigation={events:{selectedIndex:-1,items:[]},agents:{selectedIndex:-1,items:[]},tools:{selectedIndex:-1,items:[]},files:{selectedIndex:-1,items:[]}},this.setupEventHandlers(),console.log("UI state manager initialized with hash navigation"),this.handleHashChange()}getTabFromHash(){const e=window.location.hash||"";return this.hashToTab[e]||"events"}setupEventHandlers(){this.setupHashNavigation(),this.setupTabClickHandlers(),this.setupUnifiedKeyboardNavigation()}setupHashNavigation(){window.addEventListener("hashchange",e=>{console.log("[Hash Navigation] Hash changed from",new URL(e.oldURL).hash,"to",window.location.hash),this.handleHashChange()}),document.addEventListener("DOMContentLoaded",()=>{console.log("[Hash Navigation] Initial hash:",window.location.hash),this.handleHashChange()})}handleHashChange(){const e=window.location.hash||"";console.log("[Hash Navigation] DETAILED DEBUG:"),console.log("[Hash Navigation] - Current hash:",e),console.log("[Hash Navigation] - hashToTab mapping:",this.hashToTab),console.log("[Hash Navigation] - Direct lookup result:",this.hashToTab[e]),console.log("[Hash Navigation] - Is hash in mapping?",e in this.hashToTab),console.log("[Hash Navigation] - Hash length:",e.length),console.log("[Hash Navigation] - Hash char codes:",e.split("").map(e=>e.charCodeAt(0)));const t=this.hashToTab[e]||"events";console.log("[Hash Navigation] Final resolved tab name:",t),"claude-tree"!==t&&"#file_tree"!==e||(console.log("[UIStateManager] FILE TREE TAB SELECTED via hash:",e),console.log("[UIStateManager] Tab name resolved to:",t)),this.switchTab(t,!1)}setupTabNavigation(){console.log("[Hash Navigation] setupTabNavigation is deprecated - using hash navigation instead")}setupTabClickHandlers(){document.querySelectorAll(".tab-button").forEach(e=>{e.addEventListener("click",e=>{console.log("[UIStateManager] Tab button clicked:",e.target);const t=this.getTabNameFromButton(e.target);console.log("[UIStateManager] Resolved tab name:",t),t&&setTimeout(()=>{const e=this.tabToHash[t];window.location.hash!==e&&e&&(console.log("[UIStateManager] Hash not updated, forcing update:",e),window.location.hash=e)},10)})}),console.log("[UIStateManager] Tab click handlers set up for",document.querySelectorAll(".tab-button").length,"buttons")}setupUnifiedKeyboardNavigation(){document.addEventListener("keydown",e=>{document.activeElement&&["INPUT","TEXTAREA","SELECT"].includes(document.activeElement.tagName)||("ArrowUp"===e.key||"ArrowDown"===e.key?(e.preventDefault(),this.handleUnifiedArrowNavigation("ArrowDown"===e.key?1:-1)):"Enter"===e.key?(e.preventDefault(),this.handleUnifiedEnterKey()):"Escape"===e.key&&this.clearUnifiedSelection())})}getTabNameFromButton(e){console.log("[getTabNameFromButton] DEBUG: button object:",e),console.log("[getTabNameFromButton] DEBUG: button.nodeType:",e.nodeType),console.log("[getTabNameFromButton] DEBUG: button.tagName:",e.tagName);let t=e;e&&e.closest&&e.closest(".tab-button")&&(t=e.closest(".tab-button"),console.log("[getTabNameFromButton] DEBUG: Used closest() to find actual button"));const n=t?t.getAttribute("data-tab"):null;if(console.log("[getTabNameFromButton] DEBUG: data-tab attribute:",n),console.log("[getTabNameFromButton] DEBUG: dataTab truthy:",!!n),"claude-tree"===n)return console.log("[getTabNameFromButton] DEBUG: Found claude-tree data-tab, returning it"),"claude-tree";if(n)return console.log("[getTabNameFromButton] DEBUG: Returning dataTab:",n),n;const o=t?t.textContent.toLowerCase():"";return console.log("[getTabNameFromButton] DEBUG: text content:",o),console.log("[getTabNameFromButton] DEBUG: text includes file tree:",o.includes("file tree")),console.log("[getTabNameFromButton] DEBUG: text includes events:",o.includes("events")),o.includes("file tree")||o.includes("📝")?(console.log("[getTabNameFromButton] DEBUG: Matched file tree, returning claude-tree"),"claude-tree"):o.includes("activity")||o.includes("🌳")?"activity":o.includes("agents")||o.includes("🤖")?"agents":o.includes("tools")||o.includes("🔧")?"tools":o.includes("files")||o.includes("📁")?"files":o.includes("code")?"code":o.includes("sessions")?"sessions":o.includes("system")?"system":(o.includes("events")||o.includes("📊")||console.log("[getTabNameFromButton] DEBUG: No match, falling back to events"),"events")}switchTab(e,t=!0){if(this._switching)return console.log(`[UIStateManager] Tab switch already in progress, queuing: ${e}`),void setTimeout(()=>this.switchTab(e,t),50);this._switching=!0,console.log(`[UIStateManager] BULLETPROOF switchTab: ${e}, updateHash: ${t}`);try{if("claude-tree"===e&&(console.log("[UIStateManager] SWITCHING TO FILE TREE TAB"),console.log("[UIStateManager] Current tab before switch:",this.currentTab)),t&&this.tabToHash[e]){const t=this.tabToHash[e];if(window.location.hash!==t)return console.log(`[UIStateManager] Updating hash to: ${t}`),this._switching=!1,void(window.location.hash=t)}const n=this.currentTab;this.currentTab=e,this._removeAllActiveStates(),this._setActiveTab(e),this._showTabContent(e),this._validateTabState(e),this.clearUnifiedSelection(),document.dispatchEvent(new CustomEvent("tabChanged",{detail:{newTab:e,previousTab:n}})),setTimeout(()=>{this.autoScroll&&this.scrollCurrentTabToBottom(),"claude-tree"===e&&window.CodeViewer&&(window.CodeViewer.renderContent?window.CodeViewer.renderContent():window.CodeViewer.show())},100)}finally{setTimeout(()=>{this._switching=!1},200)}}_removeAllActiveStates(){document.querySelectorAll(".tab-button").forEach(e=>{e.classList.remove("active"),e.style.removeProperty("border-bottom"),e.style.removeProperty("color")}),document.querySelectorAll(".tab-content").forEach(e=>{e.classList.remove("active"),e.style.removeProperty("display"),"events-tab"!==e.id&&this._cleanLeakedEventContent(e)}),console.log("[UIStateManager] NUCLEAR: All active states removed")}_setActiveTab(e){const t=document.querySelector(`[data-tab="${e}"]`);t?(t.classList.add("active"),console.log(`[UIStateManager] Set active: ${e}`)):console.error(`[UIStateManager] Could not find tab button for: ${e}`)}_showTabContent(e){const t=document.getElementById(`${e}-tab`);t?(t.classList.add("active"),console.log(`[UIStateManager] Showing content: ${e}-tab`),"claude-tree"===e&&this._prepareFileTreeContent(t)):console.error(`[UIStateManager] Could not find content for: ${e}`)}_cleanLeakedEventContent(e){const t=e.querySelectorAll(".event-item");t.length>0&&(console.warn(`[UIStateManager] Found ${t.length} leaked event items in ${e.id}, removing...`),t.forEach(e=>e.remove()));const n=e.querySelectorAll("#events-list, .events-list");n.length>0&&(console.warn(`[UIStateManager] Found leaked events-list in ${e.id}, removing...`),n.forEach(e=>e.remove()))}_prepareFileTreeContent(e){const t=document.getElementById("claude-tree-container");t&&(this._cleanLeakedEventContent(t),t.setAttribute("data-owner","code-viewer"),t.setAttribute("data-component","CodeViewer"),console.log("[UIStateManager] File Tree container prepared"))}_validateTabState(e){setTimeout(()=>{const t=document.querySelectorAll(".tab-button.active"),n=document.querySelectorAll(".tab-content.active");1!==t.length&&(console.error(`[UIStateManager] VALIDATION FAILED: Expected 1 active tab, found ${t.length}`),t.forEach((e,t)=>{console.error(` - Active tab ${t+1}: ${e.textContent.trim()} (${e.getAttribute("data-tab")})`)}),this._removeAllActiveStates(),this._setActiveTab(e)),1!==n.length&&(console.error(`[UIStateManager] VALIDATION FAILED: Expected 1 active content, found ${n.length}`),n.forEach((e,t)=>{console.error(` - Active content ${t+1}: ${e.id}`)}),this._removeAllActiveStates(),this._showTabContent(e)),console.log(`[UIStateManager] Tab state validated for: ${e}`)},50)}handleUnifiedArrowNavigation(e){const t=this.tabNavigation[this.currentTab];if(!t)return;let n=t.selectedIndex+e;0!==t.items.length&&(n<0?n=t.items.length-1:n>=t.items.length&&(n=0),this.selectCardByIndex(this.currentTab,n))}handleUnifiedEnterKey(){const e=this.tabNavigation[this.currentTab];if(!e||-1===e.selectedIndex)return;const t=e.items[e.selectedIndex];t&&t.onclick&&t.onclick()}clearUnifiedSelection(){Object.keys(this.tabNavigation).forEach(e=>{this.tabNavigation[e].selectedIndex=-1}),this.clearCardSelection()}updateTabNavigationItems(){const e=this.tabNavigation[this.currentTab];if(!e)return;let t;switch(this.currentTab){case"events":t="#events-list .event-item";break;case"agents":t="#agents-list .event-item";break;case"tools":t="#tools-list .event-item";break;case"files":t="#files-list .event-item"}t&&(e.items=Array.from(document.querySelectorAll(t)))}selectCardByIndex(e,t){const n=this.tabNavigation[e];if(!n||t<0||t>=n.items.length)return;n.selectedIndex=t,this.updateUnifiedSelectionUI();n.items[t]&&this.selectCard(e,t,this.getCardType(e),t),this.showCardDetails(e,t)}updateUnifiedSelectionUI(){document.querySelectorAll(".event-item.keyboard-selected").forEach(e=>{e.classList.remove("keyboard-selected")});const e=this.tabNavigation[this.currentTab];e&&-1!==e.selectedIndex&&e.items[e.selectedIndex]&&e.items[e.selectedIndex].classList.add("keyboard-selected")}showCardDetails(e,t){document.dispatchEvent(new CustomEvent("showCardDetails",{detail:{tabName:e,index:t}}))}selectCard(e,t,n,o){this.clearCardSelection(),this.selectedCard={tab:e,index:t,type:n,data:o},this.updateCardSelectionUI(),console.log("Card selected:",this.selectedCard)}clearCardSelection(){document.querySelectorAll(".event-item.selected, .file-item.selected").forEach(e=>{e.classList.remove("selected")}),this.selectedCard={tab:null,index:null,type:null,data:null}}updateCardSelectionUI(){if(!this.selectedCard.tab||null===this.selectedCard.index)return;let e;switch(this.selectedCard.tab){case"events":e=document.getElementById("events-list");break;case"agents":e=document.getElementById("agents-list");break;case"tools":e=document.getElementById("tools-list");break;case"files":e=document.getElementById("files-list")}if(e){const t=e.querySelectorAll(".event-item, .file-item");t[this.selectedCard.index]&&t[this.selectedCard.index].classList.add("selected")}}getCardType(e){switch(e){case"events":return"event";case"agents":return"agent";case"tools":return"tool";case"files":return"file";default:return"unknown"}}scrollCurrentTabToBottom(){const e=`${this.currentTab}-list`,t=document.getElementById(e);t&&this.autoScroll&&(t.scrollTop=t.scrollHeight)}clearSelection(){this.clearCardSelection(),this.clearUnifiedSelection()}getCurrentTab(){return this.currentTab}getSelectedCard(){return{...this.selectedCard}}getTabNavigation(){return{...this.tabNavigation}}setAutoScroll(e){this.autoScroll=e}getAutoScroll(){return this.autoScroll}}window.UIStateManager=o;export{n as S,o as U};
2
2
  //# sourceMappingURL=socket-client.js.map