claude-mpm 4.0.28__py3-none-any.whl → 4.0.29__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 (38) hide show
  1. claude_mpm/agents/templates/agent-manager.json +24 -0
  2. claude_mpm/agents/templates/agent-manager.md +304 -0
  3. claude_mpm/cli/__init__.py +2 -0
  4. claude_mpm/cli/commands/__init__.py +2 -0
  5. claude_mpm/cli/commands/agent_manager.py +517 -0
  6. claude_mpm/cli/commands/memory.py +1 -1
  7. claude_mpm/cli/parsers/agent_manager_parser.py +247 -0
  8. claude_mpm/cli/parsers/base_parser.py +7 -0
  9. claude_mpm/cli/shared/__init__.py +1 -1
  10. claude_mpm/constants.py +1 -0
  11. claude_mpm/core/claude_runner.py +3 -2
  12. claude_mpm/core/constants.py +2 -2
  13. claude_mpm/core/socketio_pool.py +2 -2
  14. claude_mpm/dashboard/static/built/components/event-viewer.js +1 -1
  15. claude_mpm/dashboard/static/built/components/module-viewer.js +1 -1
  16. claude_mpm/dashboard/static/built/dashboard.js +1 -1
  17. claude_mpm/dashboard/static/built/socket-client.js +1 -1
  18. claude_mpm/dashboard/static/css/dashboard.css +170 -0
  19. claude_mpm/dashboard/static/dist/components/module-viewer.js +1 -1
  20. claude_mpm/dashboard/static/dist/dashboard.js +1 -1
  21. claude_mpm/dashboard/static/dist/socket-client.js +1 -1
  22. claude_mpm/dashboard/static/js/components/file-tool-tracker.js +21 -3
  23. claude_mpm/dashboard/static/js/components/module-viewer.js +129 -1
  24. claude_mpm/dashboard/static/js/dashboard.js +116 -0
  25. claude_mpm/dashboard/static/js/socket-client.js +0 -1
  26. claude_mpm/hooks/claude_hooks/connection_pool.py +1 -1
  27. claude_mpm/hooks/claude_hooks/hook_handler.py +1 -1
  28. claude_mpm/services/agents/agent_builder.py +455 -0
  29. claude_mpm/services/agents/deployment/agent_template_builder.py +10 -3
  30. claude_mpm/services/memory/__init__.py +2 -0
  31. claude_mpm/services/socketio/handlers/connection.py +27 -33
  32. {claude_mpm-4.0.28.dist-info → claude_mpm-4.0.29.dist-info}/METADATA +1 -1
  33. {claude_mpm-4.0.28.dist-info → claude_mpm-4.0.29.dist-info}/RECORD +38 -33
  34. /claude_mpm/cli/shared/{command_base.py → base_command.py} +0 -0
  35. {claude_mpm-4.0.28.dist-info → claude_mpm-4.0.29.dist-info}/WHEEL +0 -0
  36. {claude_mpm-4.0.28.dist-info → claude_mpm-4.0.29.dist-info}/entry_points.txt +0 -0
  37. {claude_mpm-4.0.28.dist-info → claude_mpm-4.0.29.dist-info}/licenses/LICENSE +0 -0
  38. {claude_mpm-4.0.28.dist-info → claude_mpm-4.0.29.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.isConnected=!1,this.isConnecting=!1,this.events=[],this.sessions=new Map,this.currentSessionId=null,this.startStatusCheckFallback()}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,maxReconnectionAttempts:10,timeout:1e4,forceNew:!0,transports:["websocket","polling"]}),this.setupSocketHandlers()}setupSocketHandlers(){this.socket.on("connect",()=>{console.log("Connected to Socket.IO server"),this.isConnected=!0,this.isConnecting=!1,this.notifyConnectionStatus("Connected","connected"),this.connectionCallbacks.connect.forEach(t=>t(this.socket.id)),this.requestStatus()}),this.socket.on("disconnect",t=>{console.log("Disconnected from server:",t),this.isConnected=!1,this.isConnecting=!1,this.notifyConnectionStatus(`Disconnected: ${t}`,"disconnected"),this.connectionCallbacks.disconnect.forEach(e=>e(t))}),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}}),this.connectionCallbacks.error.forEach(t=>t(e))}),this.socket.on("claude_event",t=>{const e=this.transformEvent(t);this.addEvent(e)}),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("hook.pre",t=>{this.addEvent({type:"hook",subtype:"pre",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("hook.post",t=>{this.addEvent({type:"hook",subtype:"post",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("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}requestStatus(){this.socket&&this.socket.connected&&(console.log("Requesting server status..."),this.socket.emit("request.status"))}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.socket.emit("get_history",e)}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});const n=this.sessions.get(e);n.lastActivity=t.timestamp,n.eventCount++}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)}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}}transformEvent(t){if(!t)return t;let e={...t};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="system",e.subtype=n.toLowerCase()),delete e.event}else if(t.type){const n=t.type;if(n.startsWith("hook.")){const t=n.substring(5);e.type="hook",e.subtype=t}else if(n.includes(".")){const[t,...s]=n.split(".");e.type=t,e.subtype=s.join(".")}}else e.type="unknown",e.subtype="";if(!t.type&&t.event?e.originalEventName=t.event:t.type&&(e.originalEventName=t.type),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)?console.warn(`Protected field '${s}' in data object was not copied to top level to preserve event structure`):e[s]=t.data[s]}),e.data=t.data}return"hook"!==e.type||"pre_tool"!==e.subtype&&"post_tool"!==e.subtype||console.log("Transformed tool event:",{type:e.type,subtype:e.subtype,tool_name:e.tool_name,has_data:!!e.data,keys:Object.keys(e).filter(t=>"data"!==t)}),e}getState(){return{events:this.events,sessions:this.sessions,currentSessionId:this.currentSessionId}}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))}}}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&&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"),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"),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()||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("agents")?"agents":e.includes("tools")?"tools":e.includes("files")?"files":"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 t=window.io;class e{constructor(){this.socket=null,this.port=null,this.connectionCallbacks={connect:[],disconnect:[],error:[],event:[]},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=3,this.retryDelays=[1e3,2e3,4e3],this.pendingEmissions=new Map,this.lastPingTime=null,this.lastPongTime=null,this.pingTimeout=4e4,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,maxReconnectionAttempts:10,timeout:1e4,forceNew:!0,transports:["websocket","polling"]}),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"),this.connectionCallbacks.connect.forEach(t=>t(this.socket.id)),this.requestStatus()}),this.socket.on("disconnect",t=>{if(console.log("Disconnected from server:",t),this.isConnected=!1,this.isConnecting=!1,this.disconnectTime=Date.now(),this.lastConnectTime){const t=(Date.now()-this.lastConnectTime)/1e3;console.log(`Connection uptime was ${t.toFixed(1)}s`)}this.notifyConnectionStatus(`Disconnected: ${t}`,"disconnected"),this.connectionCallbacks.disconnect.forEach(e=>e(t)),"transport close"!==t&&"ping timeout"!==t||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=>{const e=this.transformEvent(t);this.addEvent(e)}),this.socket.on("ping",t=>{this.lastPingTime=Date.now(),this.socket.emit("pong",{timestamp:t.timestamp,client_time:Date.now()})}),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("hook.pre",t=>{this.addEvent({type:"hook",subtype:"pre",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("hook.post",t=>{this.addEvent({type:"hook",subtype:"post",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("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:c=null}=n,a=`${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(a),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(a,{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(a),c&&c("max_retries_exceeded")}else 0===n&&(this.queueEvent(t,e),console.log(`Queued ${t} for later emission (disconnected)`),c&&c("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});const n=this.sessions.get(e);n.lastActivity=t.timestamp,n.eventCount++}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)}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}}transformEvent(t){if(!t)return t;let e={...t};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}else if(t.type){const n=t.type;if(n.startsWith("hook.")){const t=n.substring(5);e.type="hook",e.subtype=t}else if(n.includes(".")){const[t,...s]=n.split(".");e.type=t,e.subtype=s.join(".")}}else e.type="unknown",e.subtype="";if(!t.type&&t.event?e.originalEventName=t.event:t.type&&(e.originalEventName=t.type),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)?console.warn(`Protected field '${s}' in data object was not copied to top level to preserve event structure`):e[s]=t.data[s]}),e.data=t.data}return"hook"!==e.type||"pre_tool"!==e.subtype&&"post_tool"!==e.subtype||console.log("Transformed tool event:",{type:e.type,subtype:e.subtype,tool_name:e.tool_name,has_data:!!e.data,keys:Object.keys(e).filter(t=>"data"!==t)}),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&&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"),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"),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()||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("agents")?"agents":e.includes("tools")?"tools":e.includes("files")?"files":"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};
2
2
  //# sourceMappingURL=socket-client.js.map
@@ -2104,6 +2104,176 @@ button:disabled:hover {
2104
2104
  font-weight: 600;
2105
2105
  }
2106
2106
 
2107
+ /* Search Viewer Modal Styles */
2108
+ .search-viewer-modal {
2109
+ z-index: 1001; /* Higher than regular modals */
2110
+ }
2111
+
2112
+ .modal-content.search-viewer-content {
2113
+ width: 80vw;
2114
+ height: 80vh;
2115
+ max-width: 1200px;
2116
+ max-height: 800px;
2117
+ margin: 10vh auto;
2118
+ padding: 0;
2119
+ display: flex;
2120
+ flex-direction: column;
2121
+ background: #ffffff;
2122
+ border-radius: 8px;
2123
+ overflow: hidden;
2124
+ }
2125
+
2126
+ .search-viewer-header {
2127
+ display: flex;
2128
+ align-items: center;
2129
+ justify-content: space-between;
2130
+ padding: 20px 24px;
2131
+ border-bottom: 1px solid #e2e8f0;
2132
+ background: #f8fafc;
2133
+ border-radius: 8px 8px 0 0;
2134
+ min-height: 60px;
2135
+ flex-shrink: 0;
2136
+ }
2137
+
2138
+ .search-viewer-title {
2139
+ display: flex;
2140
+ align-items: center;
2141
+ gap: 12px;
2142
+ margin: 0;
2143
+ font-size: 20px;
2144
+ font-weight: 600;
2145
+ color: #2d3748;
2146
+ }
2147
+
2148
+ .search-viewer-icon {
2149
+ font-size: 24px;
2150
+ }
2151
+
2152
+ .search-viewer-close {
2153
+ background: none;
2154
+ border: none;
2155
+ font-size: 24px;
2156
+ cursor: pointer;
2157
+ color: #a0aec0;
2158
+ padding: 8px;
2159
+ border-radius: 4px;
2160
+ transition: all 0.2s ease;
2161
+ display: flex;
2162
+ align-items: center;
2163
+ justify-content: center;
2164
+ }
2165
+
2166
+ .search-viewer-close:hover {
2167
+ background: #fed7d7;
2168
+ color: #e53e3e;
2169
+ }
2170
+
2171
+ .search-viewer-body {
2172
+ flex: 1;
2173
+ display: flex;
2174
+ flex-direction: column;
2175
+ overflow-y: auto;
2176
+ padding: 20px;
2177
+ gap: 20px;
2178
+ }
2179
+
2180
+ .search-params-section,
2181
+ .search-results-section {
2182
+ background: #f8fafc;
2183
+ border: 1px solid #e2e8f0;
2184
+ border-radius: 6px;
2185
+ padding: 16px;
2186
+ }
2187
+
2188
+ .search-params-section h3,
2189
+ .search-results-section h3 {
2190
+ margin: 0 0 12px 0;
2191
+ font-size: 16px;
2192
+ font-weight: 600;
2193
+ color: #2d3748;
2194
+ }
2195
+
2196
+ .search-params-display {
2197
+ background: #1a202c;
2198
+ color: #e2e8f0;
2199
+ padding: 12px;
2200
+ border-radius: 4px;
2201
+ font-family: 'Monaco', 'Consolas', monospace;
2202
+ font-size: 13px;
2203
+ overflow-x: auto;
2204
+ white-space: pre;
2205
+ }
2206
+
2207
+ .search-results-display {
2208
+ max-height: 400px;
2209
+ overflow-y: auto;
2210
+ }
2211
+
2212
+ .search-results-text,
2213
+ .search-results-json {
2214
+ background: #1a202c;
2215
+ color: #e2e8f0;
2216
+ padding: 12px;
2217
+ border-radius: 4px;
2218
+ font-family: 'Monaco', 'Consolas', monospace;
2219
+ font-size: 13px;
2220
+ overflow-x: auto;
2221
+ white-space: pre-wrap;
2222
+ word-break: break-word;
2223
+ }
2224
+
2225
+ .search-results-list {
2226
+ list-style: none;
2227
+ padding: 0;
2228
+ margin: 0;
2229
+ }
2230
+
2231
+ .search-results-list li {
2232
+ background: white;
2233
+ border: 1px solid #e2e8f0;
2234
+ border-radius: 4px;
2235
+ padding: 8px 12px;
2236
+ margin-bottom: 8px;
2237
+ }
2238
+
2239
+ .search-results-list li pre {
2240
+ margin: 0;
2241
+ background: #1a202c;
2242
+ color: #e2e8f0;
2243
+ padding: 8px;
2244
+ border-radius: 4px;
2245
+ font-family: 'Monaco', 'Consolas', monospace;
2246
+ font-size: 12px;
2247
+ overflow-x: auto;
2248
+ }
2249
+
2250
+ /* Button for viewing search details */
2251
+ .btn-view-search {
2252
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
2253
+ color: white;
2254
+ border: none;
2255
+ padding: 10px 20px;
2256
+ border-radius: 6px;
2257
+ font-size: 14px;
2258
+ font-weight: 500;
2259
+ cursor: pointer;
2260
+ transition: all 0.3s ease;
2261
+ display: inline-flex;
2262
+ align-items: center;
2263
+ gap: 8px;
2264
+ }
2265
+
2266
+ .btn-view-search:hover {
2267
+ transform: translateY(-2px);
2268
+ box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
2269
+ }
2270
+
2271
+ .search-view-action {
2272
+ margin-top: 20px;
2273
+ display: flex;
2274
+ justify-content: center;
2275
+ }
2276
+
2107
2277
  .file-content-code .comment {
2108
2278
  color: #6272a4;
2109
2279
  font-style: italic;
@@ -1,2 +1,2 @@
1
- class t{constructor(t){this.container=document.getElementById(t),this.dataContainer=null,this.jsonContainer=null,this.currentEvent=null,this.eventsByClass=new Map,this.globalJsonExpanded="true"===localStorage.getItem("dashboard-json-expanded"),this.keyboardListenerAdded=!1,this.init()}init(){this.setupContainers(),this.setupEventHandlers(),this.showEmptyState()}setupContainers(){this.dataContainer=document.getElementById("module-data-content"),this.jsonContainer=null,this.dataContainer||console.error("Module viewer data container not found")}setupEventHandlers(){document.addEventListener("eventSelected",t=>{this.showEventDetails(t.detail.event)}),document.addEventListener("eventSelectionCleared",()=>{this.showEmptyState()}),document.addEventListener("socketEventUpdate",t=>{this.updateEventsByClass(t.detail.events)})}showEmptyState(){this.dataContainer&&(this.dataContainer.innerHTML='\n <div class="module-empty">\n <p>Click on an event to view structured data</p>\n <p class="module-hint">Data is organized by event type</p>\n </div>\n '),this.currentEvent=null}showEventDetails(t){this.currentEvent=t,this.renderStructuredData(t),this.renderJsonData(t)}renderStructuredData(t){if(!this.dataContainer)return;const e=this.createContextualHeader(t),n=this.createEventStructuredView(t),o=this.createCollapsibleJsonSection(t);this.dataContainer.innerHTML=e+n+o,this.initializeJsonToggle()}renderJsonData(t){}ingest(t){Array.isArray(t)?t.length>0?this.showEventDetails(t[0]):this.showEmptyState():t&&"object"==typeof t?this.showEventDetails(t):this.showEmptyState()}updateEventsByClass(t){this.eventsByClass.clear(),t.forEach(t=>{const e=this.getEventClass(t);this.eventsByClass.has(e)||this.eventsByClass.set(e,[]),this.eventsByClass.get(e).push(t)})}getEventClass(t){if(!t.type)return"unknown";switch(t.type){case"session":return"Session Management";case"claude":return"Claude Interactions";case"agent":return"Agent Operations";case"hook":return"Hook System";case"todo":return"Task Management";case"memory":return"Memory Operations";case"log":return"System Logs";case"connection":return"Connection Events";default:return"Other Events"}}createContextualHeader(t){const e=this.formatTimestamp(t.timestamp),n=t.data||{};let o="";switch(t.type){case"hook":const s=this.extractToolName(n),i=this.extractAgent(t)||"Unknown";if(s)o=`${s}: ${i} ${e}`;else{o=`${this.getHookDisplayName(t,n)}: ${i} ${e}`}break;case"agent":o=`Agent: ${n.agent_type||n.name||"Unknown"} ${e}`;break;case"todo":o=`TodoWrite: ${this.extractAgent(t)||"PM"} ${e}`;break;case"memory":o=`Memory: ${n.operation||"Unknown"} ${e}`;break;case"session":case"claude":case"log":case"connection":o=`Event: ${t.type}.${t.subtype||"default"} ${e}`;break;default:const a=this.extractFileName(n);if(a)o=`File: ${a} ${e}`;else{o=`Event: ${t.type||"Unknown"}.${t.subtype||"default"} ${e}`}}return`\n <div class="contextual-header">\n <h3 class="contextual-header-text">${o}</h3>\n </div>\n `}createEventStructuredView(t){const e=this.getEventClass(t),n=(this.eventsByClass.get(e)||[]).length;let o=`\n <div class="structured-view-section">\n ${this.createEventDetailCard(t.type,t,n)}\n </div>\n `;switch(t.type){case"agent":o+=this.createAgentStructuredView(t);break;case"hook":"Task"===t.data?.tool_name&&t.data?.tool_parameters?.subagent_type?o+=this.createAgentStructuredView(t):o+=this.createHookStructuredView(t);break;case"todo":o+=this.createTodoStructuredView(t);break;case"memory":o+=this.createMemoryStructuredView(t);break;case"claude":o+=this.createClaudeStructuredView(t);break;case"session":o+=this.createSessionStructuredView(t);break;default:o+=this.createGenericStructuredView(t)}return o}createEventDetailCard(t,e,n){const o=new Date(e.timestamp).toLocaleString();return`\n <div class="event-detail-card">\n <div class="event-detail-header">\n <div class="event-detail-title">\n ${this.getEventIcon(t)} ${t||"Unknown"}.${e.subtype||"default"}\n </div>\n <div class="event-detail-time">${o}</div>\n </div>\n <div class="event-detail-content">\n ${this.createProperty("Event ID",e.id||"N/A")}\n ${this.createProperty("Type",`${t}.${e.subtype||"default"}`)}\n ${this.createProperty("Class Events",n)}\n ${e.data&&e.data.session_id?this.createProperty("Session",e.data.session_id):""}\n </div>\n </div>\n `}createAgentStructuredView(t){const e=t.data||{};if("hook"===t.type&&"Task"===e.tool_name&&e.tool_parameters?.subagent_type){const n=e.tool_parameters;return`\n <div class="structured-view-section">\n <div class="structured-data">\n ${this.createProperty("Agent Type",n.subagent_type)}\n ${this.createProperty("Task Type","Subagent Delegation")}\n ${this.createProperty("Phase",t.subtype||"pre_tool")}\n ${n.description?this.createProperty("Description",n.description):""}\n ${n.prompt?this.createProperty("Prompt Preview",this.truncateText(n.prompt,200)):""}\n ${e.session_id?this.createProperty("Session ID",e.session_id):""}\n ${e.working_directory?this.createProperty("Working Directory",e.working_directory):""}\n </div>\n ${n.prompt?`\n <div class="prompt-section">\n <div class="contextual-header">\n <h3 class="contextual-header-text">📝 Task Prompt</h3>\n </div>\n <div class="structured-data">\n <div class="task-prompt" style="white-space: pre-wrap; max-height: 300px; overflow-y: auto; padding: 10px; background: #f8fafc; border-radius: 6px; font-family: monospace; font-size: 12px; line-height: 1.4;">\n ${n.prompt}\n </div>\n </div>\n </div>\n `:""}\n </div>\n `}return`\n <div class="structured-view-section">\n <div class="structured-data">\n ${this.createProperty("Agent Type",e.agent_type||e.subagent_type||"Unknown")}\n ${this.createProperty("Name",e.name||"N/A")}\n ${this.createProperty("Phase",t.subtype||"N/A")}\n ${e.config?this.createProperty("Config","object"==typeof e.config?Object.keys(e.config).join(", "):String(e.config)):""}\n ${e.capabilities?this.createProperty("Capabilities",e.capabilities.join(", ")):""}\n ${e.result?this.createProperty("Result","object"==typeof e.result?"[Object]":String(e.result)):""}\n </div>\n </div>\n `}createHookStructuredView(t){const e=t.data||{},n=this.extractFilePathFromHook(e),o=this.extractToolInfoFromHook(e),s=this.createInlineToolResultContent(e,t);return`\n <div class="structured-view-section">\n <div class="structured-data">\n ${this.createProperty("Hook Name",this.getHookDisplayName(t,e))}\n ${this.createProperty("Event Type",e.event_type||t.subtype||"N/A")}\n ${n?this.createProperty("File Path",n):""}\n ${o.tool_name?this.createProperty("Tool",o.tool_name):""}\n ${o.operation_type?this.createProperty("Operation",o.operation_type):""}\n ${e.session_id?this.createProperty("Session ID",e.session_id):""}\n ${e.working_directory?this.createProperty("Working Directory",e.working_directory):""}\n ${e.duration_ms?this.createProperty("Duration",`${e.duration_ms}ms`):""}\n ${s}\n </div>\n </div>\n `}createInlineToolResultContent(t,e=null){const n=t.result_summary,o=e?.subtype||t.event_type||t.phase,s="post_tool"===o||o?.includes("post");if(window.DEBUG_TOOL_RESULTS&&console.log("🔧 createInlineToolResultContent debug:",{hasResultSummary:!!n,eventPhase:o,isPostTool:s,eventSubtype:e?.subtype,dataEventType:t.event_type,dataPhase:t.phase,toolName:t.tool_name,resultSummaryKeys:n?Object.keys(n):[]}),!n)return"";if("pre_tool"===o||o?.includes("pre")&&!o?.includes("post"))return"";let i="";if(n.has_output&&n.output_preview&&(i+=`\n ${this.createProperty("Output",this.truncateText(n.output_preview,200))}\n ${n.output_lines?this.createProperty("Output Lines",n.output_lines):""}\n `),n.has_error&&n.error_preview&&(i+=`\n ${this.createProperty("Error",this.truncateText(n.error_preview,200))}\n `),!n.has_output&&!n.has_error&&Object.keys(n).length>3){i+=Object.entries(n).filter(([t,e])=>!["has_output","has_error","exit_code"].includes(t)&&void 0!==e).map(([t,e])=>this.createProperty(this.formatFieldName(t),String(e))).join("")}return i}createToolResultSection(t,e=null){const n=t.result_summary,o=e?.subtype||t.event_type||t.phase,s="post_tool"===o||o?.includes("post");if(window.DEBUG_TOOL_RESULTS&&console.log("🔧 createToolResultSection debug:",{hasResultSummary:!!n,eventPhase:o,isPostTool:s,eventSubtype:e?.subtype,dataEventType:t.event_type,dataPhase:t.phase,toolName:t.tool_name,resultSummaryKeys:n?Object.keys(n):[]}),!n)return"";if("pre_tool"===o||o?.includes("pre")&&!o?.includes("post"))return"";let i="⏳",a="tool-running",r="Unknown";!0===t.success?(i="✅",a="tool-success",r="Success"):!1===t.success?(i="❌",a="tool-failure",r="Failed"):0===t.exit_code?(i="✅",a="tool-success",r="Completed"):2===t.exit_code?(i="⚠️",a="tool-blocked",r="Blocked"):void 0!==t.exit_code&&0!==t.exit_code&&(i="❌",a="tool-failure",r="Error");let l="";if(l+=`\n <div class="tool-result-status ${a}">\n <span class="tool-result-icon">${i}</span>\n <span class="tool-result-text">${r}</span>\n ${void 0!==t.exit_code?`<span class="tool-exit-code">Exit Code: ${t.exit_code}</span>`:""}\n </div>\n `,n.has_output&&n.output_preview&&(l+=`\n <div class="tool-result-output">\n <div class="tool-result-label">📄 Output:</div>\n <div class="tool-result-preview">\n <pre>${this.escapeHtml(n.output_preview)}</pre>\n </div>\n ${n.output_lines?`<div class="tool-result-meta">Lines: ${n.output_lines}</div>`:""}\n </div>\n `),n.has_error&&n.error_preview&&(l+=`\n <div class="tool-result-error">\n <div class="tool-result-label">⚠️ Error:</div>\n <div class="tool-result-preview error-preview">\n <pre>${this.escapeHtml(n.error_preview)}</pre>\n </div>\n </div>\n `),!n.has_output&&!n.has_error&&Object.keys(n).length>3){const t=Object.entries(n).filter(([t,e])=>!["has_output","has_error","exit_code"].includes(t)&&void 0!==e).map(([t,e])=>this.createProperty(this.formatFieldName(t),String(e))).join("");t&&(l+=`\n <div class="tool-result-other">\n <div class="tool-result-label">📊 Result Details:</div>\n <div class="structured-data">\n ${t}\n </div>\n </div>\n `)}return l.trim()?`\n <div class="tool-result-section">\n <div class="contextual-header">\n <h3 class="contextual-header-text">🔧 Tool Result</h3>\n </div>\n <div class="tool-result-content">\n ${l}\n </div>\n </div>\n `:""}isWriteOperation(t,e){if(["Write","Edit","MultiEdit","NotebookEdit"].includes(t))return!0;if(e.tool_parameters){const t=e.tool_parameters;if(t.content||t.new_string||t.edits)return!0;if(t.edit_mode&&"read"!==t.edit_mode)return!0}return!("post_tool"!==e.event_type&&"pre_tool"!==e.event_type||!t||!(t.toLowerCase().includes("write")||t.toLowerCase().includes("edit")||t.toLowerCase().includes("modify")))}isReadOnlyOperation(t){if(!t)return!0;const e=t.toLowerCase();return!!["read"].includes(e)||!["write","edit","multiedit","create","delete","move","copy"].includes(e)}createTodoStructuredView(t){const e=t.data||{};let n="";return e.todos&&Array.isArray(e.todos)&&(n+=`\n <div class="todo-checklist">\n ${e.todos.map(t=>`\n <div class="todo-item todo-${t.status||"pending"}">\n <span class="todo-status">${this.getTodoStatusIcon(t.status)}</span>\n <span class="todo-content">${t.content||"No content"}</span>\n <span class="todo-priority priority-${t.priority||"medium"}">${this.getTodoPriorityIcon(t.priority)}</span>\n </div>\n `).join("")}\n </div>\n `),n}createMemoryStructuredView(t){const e=t.data||{};return`\n <div class="structured-view-section">\n <div class="structured-data">\n ${this.createProperty("Operation",e.operation||"Unknown")}\n ${this.createProperty("Key",e.key||"N/A")}\n ${e.value?this.createProperty("Value","object"==typeof e.value?"[Object]":String(e.value)):""}\n ${e.namespace?this.createProperty("Namespace",e.namespace):""}\n ${e.metadata?this.createProperty("Metadata","object"==typeof e.metadata?"[Object]":String(e.metadata)):""}\n </div>\n </div>\n `}createClaudeStructuredView(t){const e=t.data||{};return`\n <div class="structured-view-section">\n <div class="structured-data">\n ${this.createProperty("Type",t.subtype||"N/A")}\n ${e.prompt?this.createProperty("Prompt",this.truncateText(e.prompt,200)):""}\n ${e.message?this.createProperty("Message",this.truncateText(e.message,200)):""}\n ${e.response?this.createProperty("Response",this.truncateText(e.response,200)):""}\n ${e.content?this.createProperty("Content",this.truncateText(e.content,200)):""}\n ${e.tokens?this.createProperty("Tokens",e.tokens):""}\n ${e.model?this.createProperty("Model",e.model):""}\n </div>\n </div>\n `}createSessionStructuredView(t){const e=t.data||{};return`\n <div class="structured-view-section">\n <div class="structured-data">\n ${this.createProperty("Action",t.subtype||"N/A")}\n ${this.createProperty("Session ID",e.session_id||"N/A")}\n ${e.working_directory?this.createProperty("Working Dir",e.working_directory):""}\n ${e.git_branch?this.createProperty("Git Branch",e.git_branch):""}\n ${e.agent_type?this.createProperty("Agent Type",e.agent_type):""}\n </div>\n </div>\n `}createGenericStructuredView(t){const e=t.data||{},n=Object.keys(e);return 0===n.length?"":`\n <div class="structured-view-section">\n <div class="structured-data">\n ${n.map(t=>this.createProperty(t,"object"==typeof e[t]?"[Object]":String(e[t]))).join("")}\n </div>\n </div>\n `}createCollapsibleJsonSection(t){const e="json-section-"+Math.random().toString(36).substr(2,9),n=this.formatJSON(t),o=this.globalJsonExpanded;return`\n <div class="collapsible-json-section" id="${e}">\n <div class="json-toggle-header"\n onclick="window.moduleViewer.toggleJsonSection()"\n role="button"\n tabindex="0"\n aria-expanded="${o?"true":"false"}"\n onkeydown="if(event.key==='Enter'||event.key===' '){window.moduleViewer.toggleJsonSection();event.preventDefault();}">\n <span class="json-toggle-text">Raw JSON</span>\n <span class="json-toggle-arrow">${o?"▲":"▼"}</span>\n </div>\n <div class="json-content-collapsible" style="display: ${o?"block":"none"};" aria-hidden="${!o}">\n <div class="json-display" onclick="window.moduleViewer.copyJsonToClipboard(event)">\n <pre>${n}</pre>\n </div>\n </div>\n </div>\n `}async copyJsonToClipboard(t){const e=t.currentTarget.getBoundingClientRect(),n=t.clientX-e.left,o=t.clientY-e.top;if(n>e.width-50&&o<30){const e=t.currentTarget.querySelector("pre");if(e)try{await navigator.clipboard.writeText(e.textContent),this.showNotification("JSON copied to clipboard","success")}catch(s){console.error("Failed to copy JSON:",s),this.showNotification("Failed to copy JSON","error")}t.stopPropagation()}}initializeJsonToggle(){window.moduleViewer=this,this.globalJsonExpanded&&setTimeout(()=>{this.updateAllJsonSections()},0),this.keyboardListenerAdded||(this.keyboardListenerAdded=!0,document.addEventListener("keydown",t=>{t.target.classList.contains("json-toggle-header")&&("Enter"!==t.key&&" "!==t.key||(this.toggleJsonSection(),t.preventDefault()))}))}toggleJsonSection(){this.globalJsonExpanded=!this.globalJsonExpanded,localStorage.setItem("dashboard-json-expanded",this.globalJsonExpanded.toString()),this.updateAllJsonSections(),document.dispatchEvent(new CustomEvent("jsonToggleChanged",{detail:{expanded:this.globalJsonExpanded}}))}updateAllJsonSections(){const t=document.querySelectorAll(".json-content-collapsible"),e=document.querySelectorAll(".json-toggle-arrow"),n=document.querySelectorAll(".json-toggle-header");t.forEach((t,o)=>{this.globalJsonExpanded?(t.style.display="block",t.setAttribute("aria-hidden","false"),e[o]&&(e[o].textContent="▲"),n[o]&&n[o].setAttribute("aria-expanded","true")):(t.style.display="none",t.setAttribute("aria-hidden","true"),e[o]&&(e[o].textContent="▼"),n[o]&&n[o].setAttribute("aria-expanded","false"))}),this.globalJsonExpanded&&t.length>0&&setTimeout(()=>{const e=t[0];e&&e.scrollIntoView({behavior:"smooth",block:"nearest"})},100)}createProperty(t,e){const n=this.truncateText(String(e),300);return this.isFilePathProperty(t,e)?`\n <div class="event-property">\n <span class="event-property-key">${t}:</span>\n <span class="event-property-value">\n ${this.createClickableFilePath(e)}\n </span>\n </div>\n `:`\n <div class="event-property">\n <span class="event-property-key">${t}:</span>\n <span class="event-property-value">${n}</span>\n </div>\n `}isFilePathProperty(t,e){if(["File Path","file_path","notebook_path","Full Path","Working Directory","working_directory"].some(e=>t.toLowerCase().includes(e.toLowerCase()))){const t=String(e);return t.length>0&&(t.includes("/")||t.includes("\\"))&&t.length<500}return!1}createClickableFilePath(t){const e=this.truncateText(String(t),300);return`\n <span class="clickable-file-path"\n onclick="showFileViewerModal('${t.replace(/'/g,"\\'")}')"\n title="Click to view file contents with syntax highlighting&#10;Path: ${t}">\n ${e}\n </span>\n `}getEventIcon(t){const e={session:"📱",claude:"🤖",agent:"🎯",hook:"🔗",todo:"✅",memory:"🧠",log:"📝",connection:"🔌",unknown:"❓"};return e[t]||e.unknown}getTodoStatusIcon(t){const e={completed:"✅",in_progress:"🔄",pending:"⏳",cancelled:"❌"};return e[t]||e.pending}getTodoPriorityIcon(t){const e={high:"🔴",medium:"🟡",low:"🟢"};return e[t]||e.medium}getHookDisplayName(t,e){if(e.hook_name)return e.hook_name;if(e.name)return e.name;const n=t.subtype||e.event_type,o={user_prompt:"User Prompt",pre_tool:"Tool Execution (Pre)",post_tool:"Tool Execution (Post)",notification:"Notification",stop:"Session Stop",subagent_stop:"Subagent Stop"};if(o[n])return o[n];if("string"==typeof t.type&&t.type.startsWith("hook.")){const e=t.type.replace("hook.","");if(o[e])return o[e]}return n?n.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "):"Unknown Hook"}extractFilePathFromHook(t){return t.tool_parameters&&t.tool_parameters.file_path?t.tool_parameters.file_path:t.file_path?t.file_path:t.tool_input&&t.tool_input.file_path?t.tool_input.file_path:t.tool_parameters&&t.tool_parameters.notebook_path?t.tool_parameters.notebook_path:null}extractToolInfoFromHook(t){return{tool_name:t.tool_name||t.tool_parameters&&t.tool_parameters.tool_name,operation_type:t.operation_type||t.tool_parameters&&t.tool_parameters.operation_type}}truncateText(t,e){return!t||t.length<=e?t:t.substring(0,e)+"..."}formatJSON(t){try{return JSON.stringify(t,null,2)}catch(e){return String(t)}}formatTimestamp(t){if(!t)return"Unknown time";try{return new Date(t).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",second:"2-digit",hour12:!0})}catch(e){return"Invalid time"}}escapeHtml(t){if(!t)return"";const e=document.createElement("div");return e.textContent=t,e.innerHTML}formatFieldName(t){return t.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}extractToolName(t){if(t.tool_name)return t.tool_name;if(t.tool_parameters&&t.tool_parameters.tool_name)return t.tool_parameters.tool_name;if(t.tool_input&&t.tool_input.tool_name)return t.tool_input.tool_name;if(t.tool_parameters){if(t.tool_parameters.file_path||t.tool_parameters.notebook_path)return"FileOperation";if(t.tool_parameters.pattern)return"Search";if(t.tool_parameters.command)return"Bash";if(t.tool_parameters.todos)return"TodoWrite"}return null}extractAgent(t){if(t._agentName&&"Unknown Agent"!==t._agentName)return t._agentName;if(t._inference&&t._inference.agentName&&"Unknown"!==t._inference.agentName)return t._inference.agentName;if(t.agent)return t.agent;if(t.agent_type)return t.agent_type;if(t.agent_name)return t.agent_name;if(t.session_id&&"string"==typeof t.session_id){const e=t.session_id.split("_");if(e.length>1)return e[0].toUpperCase()}return t.todos||"TodoWrite"===t.tool_name?"PM":null}extractFileName(t){const e=this.extractFilePathFromHook(t);if(e){const t=e.split("/");return t[t.length-1]}return t.filename?t.filename:t.file?t.file:null}clear(){this.showEmptyState()}showToolCall(t,e){if(!t)return void this.showEmptyState();const n=t.tool_name||"Unknown Tool",o=t.agent_type||"PM",s=this.formatTimestamp(t.timestamp),i=t.pre_event,a=t.post_event,r=i?.tool_parameters||{},l=i?this.extractToolTarget(n,r):"Unknown target",c=t.duration_ms?`${t.duration_ms}ms`:"-",d=void 0!==t.success?t.success:null;void 0!==t.exit_code&&t.exit_code;let p=t.result_summary||"No summary available";if("object"==typeof p&&null!==p){const t=[];void 0!==p.exit_code&&t.push(`Exit Code: ${p.exit_code}`),void 0!==p.has_output&&t.push("Has Output: "+(p.has_output?"Yes":"No")),void 0!==p.has_error&&t.push("Has Error: "+(p.has_error?"Yes":"No")),void 0!==p.output_lines&&t.push(`Output Lines: ${p.output_lines}`),p.output_preview&&t.push(`Output Preview: ${p.output_preview}`),p.error_preview&&t.push(`Error Preview: ${p.error_preview}`)}let u="⏳",h="Running...",m="tool-running";a&&(!0===d?(u="✅",h="Success",m="tool-success"):!1===d?(u="❌",h="Failed",m="tool-failure"):(u="⏳",h="Completed",m="tool-completed"));const g=`\n <div class="contextual-header">\n <h3 class="contextual-header-text">${n}: ${o} ${s}</h3>\n </div>\n `;if("TodoWrite"===n&&r.todos){const e=`\n <div class="todo-checklist">\n ${r.todos.map(t=>{const e=this.getTodoStatusIcon(t.status),n=this.getTodoPriorityIcon(t.priority);return`\n <div class="todo-item todo-${t.status||"pending"}">\n <span class="todo-status">${e}</span>\n <span class="todo-content">${t.content||"No content"}</span>\n <span class="todo-priority priority-${t.priority||"medium"}">${n}</span>\n </div>\n `}).join("")}\n </div>\n `,n={toolCall:t,preEvent:i,postEvent:a},o=this.createCollapsibleJsonSection(n);this.dataContainer&&(this.dataContainer.innerHTML=g+e+o),this.initializeJsonToggle()}else{const e=`\n <div class="structured-view-section">\n <div class="tool-call-details">\n <div class="tool-call-info ${m}">\n <div class="structured-field">\n <strong>Tool Name:</strong> ${n}\n </div>\n <div class="structured-field">\n <strong>Agent:</strong> ${o}\n </div>\n <div class="structured-field">\n <strong>Status:</strong> ${u} ${h}\n </div>\n <div class="structured-field">\n <strong>Target:</strong> ${l}\n </div>\n <div class="structured-field">\n <strong>Started:</strong> ${new Date(t.timestamp).toLocaleString()}\n </div>\n ${c&&"-"!==c?`\n <div class="structured-field">\n <strong>Duration:</strong> ${c}\n </div>\n `:""}\n ${t.session_id?`\n <div class="structured-field">\n <strong>Session ID:</strong> ${t.session_id}\n </div>\n `:""}\n </div>\n\n ${this.createToolResultFromToolCall(t)}\n </div>\n </div>\n `,s={toolCall:t,preEvent:i,postEvent:a},r=this.createCollapsibleJsonSection(s);this.dataContainer&&(this.dataContainer.innerHTML=g+e+r),this.initializeJsonToggle()}}showFileOperations(t,e){if(!t||!e)return void this.showEmptyState();const n=e.split("/").pop()||e,o=t.operations||[],s=o[o.length-1],i=`\n <div class="contextual-header">\n <h3 class="contextual-header-text">File: ${n} ${s?this.formatTimestamp(s.timestamp):""}</h3>\n </div>\n `,a=`\n <div class="structured-view-section">\n <div class="file-details">\n <div class="file-path-display">\n <strong>Full Path:</strong> ${this.createClickableFilePath(e)}\n <div id="git-track-status-${e.replace(/[^a-zA-Z0-9]/g,"-")}" class="git-track-status" style="margin-top: 8px;">\n \x3c!-- Git tracking status will be populated here --\x3e\n </div>\n </div>\n <div class="operations-list">\n ${o.map(t=>`\n <div class="operation-item">\n <div class="operation-header">\n <span class="operation-icon">${this.getOperationIcon(t.operation)}</span>\n <span class="operation-type">${t.operation}</span>\n <span class="operation-timestamp">${new Date(t.timestamp).toLocaleString()}</span>\n ${this.isReadOnlyOperation(t.operation)?`\n \x3c!-- Read-only operation: show only file viewer --\x3e\n <span class="file-viewer-icon"\n onclick="showFileViewerModal('${e}')"\n title="View file contents with syntax highlighting"\n style="margin-left: 8px; cursor: pointer; font-size: 16px;">\n 👁️\n </span>\n `:`\n \x3c!-- Edit operation: show both file viewer and git diff --\x3e\n <span class="file-viewer-icon"\n onclick="showFileViewerModal('${e}')"\n title="View file contents with syntax highlighting"\n style="margin-left: 8px; cursor: pointer; font-size: 16px;">\n 👁️\n </span>\n <span class="git-diff-icon"\n onclick="showGitDiffModal('${e}', '${t.timestamp}')"\n title="View git diff for this file operation"\n style="margin-left: 8px; cursor: pointer; font-size: 16px; display: none;"\n data-file-path="${e}"\n data-operation-timestamp="${t.timestamp}">\n 📋\n </span>\n `}\n </div>\n <div class="operation-details">\n <strong>Agent:</strong> ${t.agent}<br>\n <strong>Session:</strong> ${t.sessionId?t.sessionId.substring(0,8)+"...":"Unknown"}\n ${t.details?`<br><strong>Details:</strong> ${t.details}`:""}\n </div>\n </div>\n `).join("")}\n </div>\n </div>\n </div>\n `;this.checkAndShowTrackControl(e),this.checkAndShowGitDiffIcons(e);const r=this.createCollapsibleJsonSection(t);this.dataContainer&&(this.dataContainer.innerHTML=i+a+r),this.initializeJsonToggle()}showErrorMessage(t,e){const n=`\n <div class="module-error">\n <div class="error-header">\n <h3>❌ ${t}</h3>\n </div>\n <div class="error-message">\n <p>${e}</p>\n </div>\n </div>\n `,o={title:t,message:e},s=this.createCollapsibleJsonSection(o);this.dataContainer&&(this.dataContainer.innerHTML=n+s),this.initializeJsonToggle()}showAgentEvent(t,e){this.showAgentSpecificDetails(t,e)}showAgentSpecificDetails(t,e){if(!t)return void this.showEmptyState();const n=window.dashboard?.agentInference,o=window.dashboard?.eventViewer;if(!n||!o)return console.warn("AgentInference or EventViewer not available, falling back to single event view"),void this.showEventDetails(t);const s=n.getInferredAgentForEvent(t),i=s?.agentName||this.extractAgent(t)||"Unknown",a=o.events||[],r=this.getAgentSpecificEvents(a,i,n);console.log(`Showing details for agent: ${i}, found ${r.length} related events`);const l=this.extractAgentSpecificData(i,r);this.renderAgentSpecificView(i,l,t)}getAgentSpecificEvents(t,e,n){return t.filter(t=>{const o=n.getInferredAgentForEvent(t);return(o?.agentName||this.extractAgent(t)||"Unknown").toLowerCase()===e.toLowerCase()})}extractAgentSpecificData(t,e){const n={agentName:t,totalEvents:e.length,prompt:null,todos:[],toolsCalled:[],sessions:new Set,firstSeen:null,lastSeen:null,eventTypes:new Set};return e.forEach(e=>{const o=e.data||{},s=new Date(e.timestamp);(!n.firstSeen||s<n.firstSeen)&&(n.firstSeen=s),(!n.lastSeen||s>n.lastSeen)&&(n.lastSeen=s),(e.session_id||o.session_id)&&n.sessions.add(e.session_id||o.session_id);const i=e.hook_event_name||e.type||"unknown";if(n.eventTypes.add(i),"hook"===e.type&&"Task"===o.tool_name&&o.tool_parameters){const e=o.tool_parameters;e.prompt&&!n.prompt&&(n.prompt=e.prompt),e.description&&!n.description&&(n.description=e.description),e.subagent_type===t&&e.prompt&&(n.prompt=e.prompt)}if(!o.prompt||o.agent_type!==t&&o.subagent_type!==t||(n.prompt=o.prompt),"todo"===e.type||"hook"===e.type&&"TodoWrite"===o.tool_name){const t=o.todos||o.tool_parameters?.todos;t&&Array.isArray(t)&&t.forEach(t=>{const e=n.todos.findIndex(e=>e.id===t.id||e.content===t.content);e>=0?n.todos[e]={...n.todos[e],...t,timestamp:s}:n.todos.push({...t,timestamp:s})})}if("hook"===e.type&&o.tool_name){const t=e.subtype||o.event_type,i=this.generateToolCallId(o.tool_name,o.tool_parameters,s);"pre_tool"===t?(n._preToolEvents||(n._preToolEvents=new Map),n._preToolEvents.set(i,{toolName:o.tool_name,timestamp:s,target:this.extractToolTarget(o.tool_name,o.tool_parameters,null),parameters:o.tool_parameters})):"post_tool"===t&&(n._postToolEvents||(n._postToolEvents=new Map),n._postToolEvents.set(i,{toolName:o.tool_name,timestamp:s,success:o.success,duration:o.duration_ms,resultSummary:o.result_summary,exitCode:o.exit_code}))}}),n.todos.sort((t,e)=>(e.timestamp||0)-(t.timestamp||0)),n.toolsCalled=this.consolidateToolCalls(n._preToolEvents,n._postToolEvents),delete n._preToolEvents,delete n._postToolEvents,n.toolsCalled.sort((t,e)=>e.timestamp-t.timestamp),n}generateToolCallId(t,e,n){const o=Math.floor(n.getTime()/5e3);let s="";if(e){const t=[];e.file_path&&t.push(e.file_path),e.command&&t.push(e.command.substring(0,50)),e.pattern&&t.push(e.pattern),e.subagent_type&&t.push(e.subagent_type),e.notebook_path&&t.push(e.notebook_path),e.url&&t.push(e.url),e.prompt&&t.push(e.prompt.substring(0,30)),s=t.join("|")}return s||(s="default"),`${t}:${o}:${s}`}consolidateToolCalls(t,e){const n=[],o=new Set;t||(t=new Map),e||(e=new Map);for(const[s,i]of t){if(o.has(s))continue;const t=e.get(s),a={toolName:i.toolName,timestamp:i.timestamp,target:i.target,parameters:i.parameters,status:this.determineToolCallStatus(i,t),statusIcon:this.getToolCallStatusIcon(i,t),phase:t?"completed":"running"};t&&(a.success=t.success,a.duration=t.duration,a.resultSummary=t.resultSummary,a.exitCode=t.exitCode,a.completedAt=t.timestamp),n.push(a),o.add(s)}for(const[s,i]of e){if(o.has(s))continue;const t={toolName:i.toolName,timestamp:i.timestamp,target:"Unknown target",parameters:null,status:this.determineToolCallStatus(null,i),statusIcon:this.getToolCallStatusIcon(null,i),phase:"completed",success:i.success,duration:i.duration,resultSummary:i.resultSummary,exitCode:i.exitCode,completedAt:i.timestamp};n.push(t),o.add(s)}return n}determineToolCallStatus(t,e){return e?!0===e.success?"Success":!1===e.success?"Failed":0===e.exitCode?"Completed":2===e.exitCode?"Blocked":void 0!==e.exitCode&&0!==e.exitCode?"Error":"Completed":"Running..."}getToolCallStatusIcon(t,e){return e?!0===e.success?"✅":!1===e.success?"❌":0===e.exitCode?"✅":2===e.exitCode?"⚠️":void 0!==e.exitCode&&0!==e.exitCode?"❌":"✅":"⏳"}estimateTokenCount(t){if(!t||"string"!=typeof t)return 0;const e=t.trim().split(/\s+/).length,n=Math.ceil(t.length/4);return Math.max(1.3*e,n)}trimPromptWhitespace(t){return t&&"string"==typeof t?t=(t=(t=t.trim()).replace(/\n\s*\n\s*\n+/g,"\n\n")).split("\n").map(t=>t.replace(/\s+$/,"")).join("\n"):""}renderAgentSpecificView(t,e,n){const o=this.formatTimestamp(n.timestamp),s=`\n <div class="contextual-header">\n <h3 class="contextual-header-text">🤖 ${t} Agent Details ${o}</h3>\n </div>\n `;let i=`\n <div class="agent-overview-section">\n <div class="structured-data">\n ${this.createProperty("Agent Name",t)}\n ${this.createProperty("Total Events",e.totalEvents)}\n ${this.createProperty("Active Sessions",e.sessions.size)}\n ${this.createProperty("Event Types",Array.from(e.eventTypes).join(", "))}\n ${e.firstSeen?this.createProperty("First Seen",e.firstSeen.toLocaleString()):""}\n ${e.lastSeen?this.createProperty("Last Seen",e.lastSeen.toLocaleString()):""}\n </div>\n </div>\n `;if(e.prompt){const t=this.trimPromptWhitespace(e.prompt);i+=`\n <div class="agent-prompt-section">\n <div class="contextual-header">\n <h3 class="contextual-header-text">📝 Agent Task Prompt</h3>\n <div class="prompt-stats" style="font-size: 11px; color: #64748b; margin-top: 4px;">\n ~${Math.round(this.estimateTokenCount(t))} tokens • ${t.trim().split(/\s+/).length} words • ${t.length} characters\n </div>\n </div>\n <div class="structured-data">\n <div class="agent-prompt" style="white-space: pre-wrap; max-height: 300px; overflow-y: auto; padding: 10px; background: #f8fafc; border-radius: 6px; font-family: monospace; font-size: 12px; line-height: 1.4; border: 1px solid #e2e8f0;">\n ${this.escapeHtml(t)}\n </div>\n </div>\n </div>\n `}e.todos.length>0&&(i+=`\n <div class="agent-todos-section">\n <div class="contextual-header">\n <h3 class="contextual-header-text">✅ Agent Todo List (${e.todos.length} items)</h3>\n </div>\n <div class="todo-checklist">\n ${e.todos.map(t=>`\n <div class="todo-item todo-${t.status||"pending"}">\n <span class="todo-status">${this.getTodoStatusIcon(t.status)}</span>\n <span class="todo-content">${t.content||"No content"}</span>\n <span class="todo-priority priority-${t.priority||"medium"}">${this.getTodoPriorityIcon(t.priority)}</span>\n ${t.timestamp?`<span class="todo-timestamp">${new Date(t.timestamp).toLocaleTimeString()}</span>`:""}\n </div>\n `).join("")}\n </div>\n </div>\n `),e.toolsCalled.length>0&&(i+=`\n <div class="agent-tools-section">\n <div class="contextual-header">\n <h3 class="contextual-header-text">🔧 Tools Called by Agent (${e.toolsCalled.length} calls)</h3>\n </div>\n <div class="tools-list">\n ${e.toolsCalled.map(e=>{let n="";return"✅"===e.statusIcon?n="status-success":"❌"===e.statusIcon?n="status-failed":"⚠️"===e.statusIcon?n="status-blocked":"⏳"===e.statusIcon&&(n="status-running"),`\n <div class="tool-call-item">\n <div class="tool-call-header">\n <div style="display: flex; align-items: center; gap: 12px; flex: 1;">\n <span class="tool-name">🔧 ${e.toolName}</span>\n <span class="tool-agent">${t}</span>\n <span class="tool-status-indicator ${n}">${e.statusIcon} ${e.status}</span>\n </div>\n <span class="tool-timestamp" style="margin-left: auto;">${e.timestamp.toLocaleTimeString()}</span>\n </div>\n <div class="tool-call-details">\n ${e.target?`<span class="tool-target">Target: ${e.target}</span>`:""}\n ${e.duration?`<span class="tool-duration">Duration: ${e.duration}ms</span>`:""}\n ${e.completedAt&&e.completedAt!==e.timestamp?`<span class="tool-completed">Completed: ${e.completedAt.toLocaleTimeString()}</span>`:""}\n </div>\n </div>\n `}).join("")}\n </div>\n </div>\n `);const a={agentName:t,agentData:e,originalEvent:n},r=this.createCollapsibleJsonSection(a);this.dataContainer&&(this.dataContainer.innerHTML=s+i+r),this.initializeJsonToggle()}createToolResultFromToolCall(t){if(!t.result_summary)return"";const e={event_type:"post_tool",result_summary:t.result_summary,success:t.success,exit_code:t.exit_code},n=this.createInlineToolResultContent(e,{subtype:"post_tool"});return n.trim()?`\n <div class="tool-result-inline">\n <div class="structured-data">\n ${n}\n </div>\n </div>\n `:""}extractToolTarget(t,e,n){const o=e||n||{};switch(t?.toLowerCase()){case"write":case"read":case"edit":case"multiedit":return o.file_path||"Unknown file";case"bash":return o.command?`${o.command.substring(0,50)}${o.command.length>50?"...":""}`:"Unknown command";case"grep":return o.pattern?`Pattern: ${o.pattern}`:"Unknown pattern";case"glob":return o.pattern?`Pattern: ${o.pattern}`:"Unknown glob";case"todowrite":return`${o.todos?.length||0} todos`;case"task":return o.subagent_type||o.agent_type||"Subagent delegation";default:return o.file_path?o.file_path:o.pattern?`Pattern: ${o.pattern}`:o.command?`Command: ${o.command.substring(0,30)}...`:o.path?o.path:"Unknown target"}}getOperationIcon(t){return{read:"👁️",write:"✏️",edit:"📝",multiedit:"📝",create:"🆕",delete:"🗑️",move:"📦",copy:"📋"}[t?.toLowerCase()]||"📄"}getCurrentEvent(){return this.currentEvent}async checkAndShowTrackControl(t){if(t)try{const e=window.socket||window.dashboard?.socketClient?.socket;if(!e)return void console.warn("No socket connection available for git tracking check");let n=window.dashboard?.currentWorkingDir;if(!n||"Unknown"===n||""===n.trim()){const t=document.getElementById("footer-working-dir");n=t?.textContent?.trim()&&"Unknown"!==t.textContent.trim()?t.textContent.trim():".",console.log("[MODULE-VIEWER-DEBUG] Working directory fallback used:",n)}const o=new Promise((n,o)=>{const s=o=>{o.file_path===t&&(e.off("file_tracked_response",s),n(o))};e.on("file_tracked_response",s),setTimeout(()=>{e.off("file_tracked_response",s),o(new Error("Request timeout"))},5e3)});e.emit("check_file_tracked",{file_path:t,working_dir:n});const s=await o;this.displayTrackingStatus(t,s)}catch(e){console.error("Error checking file tracking status:",e),this.displayTrackingStatus(t,{success:!1,error:e.message,file_path:t})}}displayTrackingStatus(t,e){const n=`git-track-status-${t.replace(/[^a-zA-Z0-9]/g,"-")}`,o=document.getElementById(n);o&&(e.success&&!1===e.is_tracked?o.innerHTML=`\n <div class="untracked-file-notice">\n <span class="untracked-icon">⚠️</span>\n <span class="untracked-text">This file is not tracked by git</span>\n <button class="track-file-button"\n onclick="window.moduleViewer.trackFile('${t}')"\n title="Add this file to git tracking">\n <span class="git-icon">📁</span> Track File\n </button>\n </div>\n `:e.success&&!0===e.is_tracked?o.innerHTML='\n <div class="tracked-file-notice">\n <span class="tracked-icon">✅</span>\n <span class="tracked-text">This file is tracked by git</span>\n </div>\n ':e.success||(o.innerHTML=`\n <div class="tracking-error-notice">\n <span class="error-icon">❌</span>\n <span class="error-text">Could not check git status: ${e.error||"Unknown error"}</span>\n </div>\n `))}async trackFile(t){if(t)try{const e=window.socket||window.dashboard?.socketClient?.socket;if(!e)return void console.warn("No socket connection available for git add");let n=window.dashboard?.currentWorkingDir;if(!n||"Unknown"===n||""===n.trim()){const t=document.getElementById("footer-working-dir");n=t?.textContent?.trim()&&"Unknown"!==t.textContent.trim()?t.textContent.trim():".",console.log("[MODULE-VIEWER-DEBUG] Working directory fallback used:",n)}const o=`git-track-status-${t.replace(/[^a-zA-Z0-9]/g,"-")}`,s=document.getElementById(o);s&&(s.innerHTML='\n <div class="tracking-file-notice">\n <span class="loading-icon">⏳</span>\n <span class="loading-text">Adding file to git tracking...</span>\n </div>\n ');const i=new Promise((n,o)=>{const s=o=>{o.file_path===t&&(e.off("git_add_response",s),n(o))};e.on("git_add_response",s),setTimeout(()=>{e.off("git_add_response",s),o(new Error("Request timeout"))},1e4)});e.emit("git_add_file",{file_path:t,working_dir:n}),console.log("📁 Git add request sent:",{filePath:t,workingDir:n});const a=await i;console.log("📦 Git add result:",a),a.success?(s&&(s.innerHTML='\n <div class="tracked-file-notice">\n <span class="tracked-icon">✅</span>\n <span class="tracked-text">File successfully added to git tracking</span>\n </div>\n '),this.showNotification("File tracked successfully","success")):(s&&(s.innerHTML=`\n <div class="tracking-error-notice">\n <span class="error-icon">❌</span>\n <span class="error-text">Failed to track file: ${a.error||"Unknown error"}</span>\n <button class="track-file-button"\n onclick="window.moduleViewer.trackFile('${t}')"\n title="Try again">\n <span class="git-icon">📁</span> Retry\n </button>\n </div>\n `),this.showNotification(`Failed to track file: ${a.error}`,"error"))}catch(e){console.error("❌ Failed to track file:",e);const n=`git-track-status-${t.replace(/[^a-zA-Z0-9]/g,"-")}`,o=document.getElementById(n);o&&(o.innerHTML=`\n <div class="tracking-error-notice">\n <span class="error-icon">❌</span>\n <span class="error-text">Error: ${e.message}</span>\n <button class="track-file-button"\n onclick="window.moduleViewer.trackFile('${t}')"\n title="Try again">\n <span class="git-icon">📁</span> Retry\n </button>\n </div>\n `),this.showNotification(`Error tracking file: ${e.message}`,"error")}}async checkAndShowGitDiffIcons(t){if(t){console.debug("[GIT-DIFF-ICONS] Checking git diff icons for file:",t);try{const e=window.socket||window.dashboard?.socketClient?.socket;if(!e)return void console.warn("[GIT-DIFF-ICONS] No socket connection available for git status check");console.debug("[GIT-DIFF-ICONS] Socket connection available, proceeding");let n=window.dashboard?.currentWorkingDir;if(n&&"Unknown"!==n&&""!==n.trim())console.debug("[GIT-DIFF-ICONS] Using working directory:",n);else{const t=document.getElementById("footer-working-dir");n=t?.textContent?.trim()&&"Unknown"!==t.textContent.trim()?t.textContent.trim():".",console.log("[GIT-DIFF-ICONS] Working directory fallback used:",n)}const o=new Promise((n,o)=>{const s=o=>{console.debug("[GIT-DIFF-ICONS] Received git status response:",o),o.file_path===t?(e.off("git_status_response",s),n(o)):console.debug("[GIT-DIFF-ICONS] Response for different file, ignoring:",o.file_path)};e.on("git_status_response",s),setTimeout(()=>{e.off("git_status_response",s),console.warn("[GIT-DIFF-ICONS] Timeout waiting for git status response"),o(new Error("Request timeout"))},3e3)});console.debug("[GIT-DIFF-ICONS] Sending check_git_status event"),e.emit("check_git_status",{file_path:t,working_dir:n});const s=await o;console.debug("[GIT-DIFF-ICONS] Git status check result:",s),s.success?(console.debug("[GIT-DIFF-ICONS] Git status check successful, showing icons for:",t),this.showGitDiffIconsForFile(t)):console.debug("[GIT-DIFF-ICONS] Git status check failed, icons will remain hidden:",s.error)}catch(e){console.warn("[GIT-DIFF-ICONS] Git status check failed, hiding git diff icons:",e.message)}}else console.debug("[GIT-DIFF-ICONS] No filePath provided, skipping git diff icon check")}showGitDiffIconsForFile(t){console.debug("[GIT-DIFF-ICONS] Showing git diff icons for file:",t);const e=document.querySelectorAll(`[data-file-path="${t}"]`);console.debug("[GIT-DIFF-ICONS] Found",e.length,"elements with matching file path");let n=0;e.forEach((t,e)=>{console.debug("[GIT-DIFF-ICONS] Processing element",e,":",t),console.debug("[GIT-DIFF-ICONS] Element classes:",t.classList.toString()),t.classList.contains("git-diff-icon")?(console.debug("[GIT-DIFF-ICONS] Setting display to inline for git-diff-icon"),t.style.display="inline",n++):console.debug("[GIT-DIFF-ICONS] Element is not a git-diff-icon, skipping")}),console.debug("[GIT-DIFF-ICONS] Showed",n,"git diff icons for file:",t)}showNotification(t,e="info"){const n=document.createElement("div");n.className=`notification notification-${e}`,n.innerHTML=`\n <span class="notification-icon">${"success"===e?"✅":"error"===e?"❌":"ℹ️"}</span>\n <span class="notification-message">${t}</span>\n `,n.style.cssText=`\n position: fixed;\n top: 20px;\n right: 20px;\n background: ${"success"===e?"#d4edda":"error"===e?"#f8d7da":"#d1ecf1"};\n color: ${"success"===e?"#155724":"error"===e?"#721c24":"#0c5460"};\n border: 1px solid ${"success"===e?"#c3e6cb":"error"===e?"#f5c6cb":"#bee5eb"};\n border-radius: 6px;\n padding: 12px 16px;\n font-size: 14px;\n font-weight: 500;\n z-index: 2000;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n display: flex;\n align-items: center;\n gap: 8px;\n max-width: 400px;\n animation: slideIn 0.3s ease-out;\n `;const o=document.createElement("style");o.textContent="\n @keyframes slideIn {\n from { transform: translateX(100%); opacity: 0; }\n to { transform: translateX(0); opacity: 1; }\n }\n @keyframes slideOut {\n from { transform: translateX(0); opacity: 1; }\n to { transform: translateX(100%); opacity: 0; }\n }\n ",document.head.appendChild(o),document.body.appendChild(n),setTimeout(()=>{n.style.animation="slideOut 0.3s ease-in",setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),o.parentNode&&o.parentNode.removeChild(o)},300)},5e3)}showAgentInstance(t){if(!t)return void this.showEmptyState();const e={type:"pm_delegation",subtype:t.agentName,agent_type:t.agentName,timestamp:t.timestamp,session_id:t.sessionId,metadata:{delegation_type:"explicit",event_count:t.agentEvents.length,pm_call:t.pmCall||null,agent_events:t.agentEvents}};console.log("Showing PM delegation details:",t),this.showAgentSpecificDetails(e,0)}showImpliedAgent(t){if(!t)return void this.showEmptyState();const e={type:"implied_delegation",subtype:t.agentName,agent_type:t.agentName,timestamp:t.timestamp,session_id:t.sessionId,metadata:{delegation_type:"implied",event_count:t.eventCount,pm_call:null,note:"No explicit PM call found - inferred from agent activity"}};console.log("Showing implied agent details:",t),this.showAgentSpecificDetails(e,0)}}window.ModuleViewer=t,window.enableToolResultDebugging=function(){window.DEBUG_TOOL_RESULTS=!0,console.log("🔧 Tool result debugging enabled. Click on tool events to see debug info.")},window.disableToolResultDebugging=function(){window.DEBUG_TOOL_RESULTS=!1,console.log("🔧 Tool result debugging disabled.")};export{t as M};
1
+ class t{constructor(t){this.container=document.getElementById(t),this.dataContainer=null,this.jsonContainer=null,this.currentEvent=null,this.eventsByClass=new Map,this.globalJsonExpanded="true"===localStorage.getItem("dashboard-json-expanded"),this.keyboardListenerAdded=!1,this.init()}init(){this.setupContainers(),this.setupEventHandlers(),this.showEmptyState()}setupContainers(){this.dataContainer=document.getElementById("module-data-content"),this.jsonContainer=null,this.dataContainer||console.error("Module viewer data container not found")}setupEventHandlers(){document.addEventListener("eventSelected",t=>{this.showEventDetails(t.detail.event)}),document.addEventListener("eventSelectionCleared",()=>{this.showEmptyState()}),document.addEventListener("socketEventUpdate",t=>{this.updateEventsByClass(t.detail.events)})}showEmptyState(){this.dataContainer&&(this.dataContainer.innerHTML='\n <div class="module-empty">\n <p>Click on an event to view structured data</p>\n <p class="module-hint">Data is organized by event type</p>\n </div>\n '),this.currentEvent=null}showEventDetails(t){this.currentEvent=t,this.renderStructuredData(t),this.renderJsonData(t)}renderStructuredData(t){if(!this.dataContainer)return;const e=this.createContextualHeader(t),n=this.createEventStructuredView(t),s=this.createCollapsibleJsonSection(t);this.dataContainer.innerHTML=e+n+s,this.initializeJsonToggle()}renderJsonData(t){}ingest(t){Array.isArray(t)?t.length>0?this.showEventDetails(t[0]):this.showEmptyState():t&&"object"==typeof t?this.showEventDetails(t):this.showEmptyState()}updateEventsByClass(t){this.eventsByClass.clear(),t.forEach(t=>{const e=this.getEventClass(t);this.eventsByClass.has(e)||this.eventsByClass.set(e,[]),this.eventsByClass.get(e).push(t)})}getEventClass(t){if(!t.type)return"unknown";switch(t.type){case"session":return"Session Management";case"claude":return"Claude Interactions";case"agent":return"Agent Operations";case"hook":return"Hook System";case"todo":return"Task Management";case"memory":return"Memory Operations";case"log":return"System Logs";case"connection":return"Connection Events";default:return"Other Events"}}createContextualHeader(t){const e=this.formatTimestamp(t.timestamp),n=t.data||{};let s="";switch(t.type){case"hook":const o=this.extractToolName(n),i=this.extractAgent(t)||"Unknown";if(o)s=`${o}: ${i} ${e}`;else{s=`${this.getHookDisplayName(t,n)}: ${i} ${e}`}break;case"agent":s=`Agent: ${n.agent_type||n.name||"Unknown"} ${e}`;break;case"todo":s=`TodoWrite: ${this.extractAgent(t)||"PM"} ${e}`;break;case"memory":s=`Memory: ${n.operation||"Unknown"} ${e}`;break;case"session":case"claude":case"log":case"connection":s=`Event: ${t.type}.${t.subtype||"default"} ${e}`;break;default:const a=this.extractFileName(n);if(a)s=`File: ${a} ${e}`;else{s=`Event: ${t.type||"Unknown"}.${t.subtype||"default"} ${e}`}}return`\n <div class="contextual-header">\n <h3 class="contextual-header-text">${s}</h3>\n </div>\n `}createEventStructuredView(t){const e=this.getEventClass(t),n=(this.eventsByClass.get(e)||[]).length;let s=`\n <div class="structured-view-section">\n ${this.createEventDetailCard(t.type,t,n)}\n </div>\n `;switch(t.type){case"agent":s+=this.createAgentStructuredView(t);break;case"hook":"Task"===t.data?.tool_name&&t.data?.tool_parameters?.subagent_type?s+=this.createAgentStructuredView(t):s+=this.createHookStructuredView(t);break;case"todo":s+=this.createTodoStructuredView(t);break;case"memory":s+=this.createMemoryStructuredView(t);break;case"claude":s+=this.createClaudeStructuredView(t);break;case"session":s+=this.createSessionStructuredView(t);break;default:s+=this.createGenericStructuredView(t)}return s}createEventDetailCard(t,e,n){const s=new Date(e.timestamp).toLocaleString();return`\n <div class="event-detail-card">\n <div class="event-detail-header">\n <div class="event-detail-title">\n ${this.getEventIcon(t)} ${t||"Unknown"}.${e.subtype||"default"}\n </div>\n <div class="event-detail-time">${s}</div>\n </div>\n <div class="event-detail-content">\n ${this.createProperty("Event ID",e.id||"N/A")}\n ${this.createProperty("Type",`${t}.${e.subtype||"default"}`)}\n ${this.createProperty("Class Events",n)}\n ${e.data&&e.data.session_id?this.createProperty("Session",e.data.session_id):""}\n </div>\n </div>\n `}createAgentStructuredView(t){const e=t.data||{};if("hook"===t.type&&"Task"===e.tool_name&&e.tool_parameters?.subagent_type){const n=e.tool_parameters;return`\n <div class="structured-view-section">\n <div class="structured-data">\n ${this.createProperty("Agent Type",n.subagent_type)}\n ${this.createProperty("Task Type","Subagent Delegation")}\n ${this.createProperty("Phase",t.subtype||"pre_tool")}\n ${n.description?this.createProperty("Description",n.description):""}\n ${n.prompt?this.createProperty("Prompt Preview",this.truncateText(n.prompt,200)):""}\n ${e.session_id?this.createProperty("Session ID",e.session_id):""}\n ${e.working_directory?this.createProperty("Working Directory",e.working_directory):""}\n </div>\n ${n.prompt?`\n <div class="prompt-section">\n <div class="contextual-header">\n <h3 class="contextual-header-text">📝 Task Prompt</h3>\n </div>\n <div class="structured-data">\n <div class="task-prompt" style="white-space: pre-wrap; max-height: 300px; overflow-y: auto; padding: 10px; background: #f8fafc; border-radius: 6px; font-family: monospace; font-size: 12px; line-height: 1.4;">\n ${n.prompt}\n </div>\n </div>\n </div>\n `:""}\n </div>\n `}return`\n <div class="structured-view-section">\n <div class="structured-data">\n ${this.createProperty("Agent Type",e.agent_type||e.subagent_type||"Unknown")}\n ${this.createProperty("Name",e.name||"N/A")}\n ${this.createProperty("Phase",t.subtype||"N/A")}\n ${e.config?this.createProperty("Config","object"==typeof e.config?Object.keys(e.config).join(", "):String(e.config)):""}\n ${e.capabilities?this.createProperty("Capabilities",e.capabilities.join(", ")):""}\n ${e.result?this.createProperty("Result","object"==typeof e.result?"[Object]":String(e.result)):""}\n </div>\n </div>\n `}createHookStructuredView(t){const e=t.data||{},n=this.extractFilePathFromHook(e),s=this.extractToolInfoFromHook(e),o=this.createInlineToolResultContent(e,t);return`\n <div class="structured-view-section">\n <div class="structured-data">\n ${this.createProperty("Hook Name",this.getHookDisplayName(t,e))}\n ${this.createProperty("Event Type",e.event_type||t.subtype||"N/A")}\n ${n?this.createProperty("File Path",n):""}\n ${s.tool_name?this.createProperty("Tool",s.tool_name):""}\n ${s.operation_type?this.createProperty("Operation",s.operation_type):""}\n ${e.session_id?this.createProperty("Session ID",e.session_id):""}\n ${e.working_directory?this.createProperty("Working Directory",e.working_directory):""}\n ${e.duration_ms?this.createProperty("Duration",`${e.duration_ms}ms`):""}\n ${o}\n </div>\n </div>\n `}createInlineToolResultContent(t,e=null){const n=t.result_summary,s=e?.subtype||t.event_type||t.phase,o="post_tool"===s||s?.includes("post");if(window.DEBUG_TOOL_RESULTS&&console.log("🔧 createInlineToolResultContent debug:",{hasResultSummary:!!n,eventPhase:s,isPostTool:o,eventSubtype:e?.subtype,dataEventType:t.event_type,dataPhase:t.phase,toolName:t.tool_name,resultSummaryKeys:n?Object.keys(n):[]}),!n)return"";if("pre_tool"===s||s?.includes("pre")&&!s?.includes("post"))return"";let i="";if(n.has_output&&n.output_preview&&(i+=`\n ${this.createProperty("Output",this.truncateText(n.output_preview,200))}\n ${n.output_lines?this.createProperty("Output Lines",n.output_lines):""}\n `),n.has_error&&n.error_preview&&(i+=`\n ${this.createProperty("Error",this.truncateText(n.error_preview,200))}\n `),!n.has_output&&!n.has_error&&Object.keys(n).length>3){i+=Object.entries(n).filter(([t,e])=>!["has_output","has_error","exit_code"].includes(t)&&void 0!==e).map(([t,e])=>this.createProperty(this.formatFieldName(t),String(e))).join("")}return i}createToolResultSection(t,e=null){const n=t.result_summary,s=e?.subtype||t.event_type||t.phase,o="post_tool"===s||s?.includes("post");if(window.DEBUG_TOOL_RESULTS&&console.log("🔧 createToolResultSection debug:",{hasResultSummary:!!n,eventPhase:s,isPostTool:o,eventSubtype:e?.subtype,dataEventType:t.event_type,dataPhase:t.phase,toolName:t.tool_name,resultSummaryKeys:n?Object.keys(n):[]}),!n)return"";if("pre_tool"===s||s?.includes("pre")&&!s?.includes("post"))return"";let i="⏳",a="tool-running",r="Unknown";!0===t.success?(i="✅",a="tool-success",r="Success"):!1===t.success?(i="❌",a="tool-failure",r="Failed"):0===t.exit_code?(i="✅",a="tool-success",r="Completed"):2===t.exit_code?(i="⚠️",a="tool-blocked",r="Blocked"):void 0!==t.exit_code&&0!==t.exit_code&&(i="❌",a="tool-failure",r="Error");let l="";if(l+=`\n <div class="tool-result-status ${a}">\n <span class="tool-result-icon">${i}</span>\n <span class="tool-result-text">${r}</span>\n ${void 0!==t.exit_code?`<span class="tool-exit-code">Exit Code: ${t.exit_code}</span>`:""}\n </div>\n `,n.has_output&&n.output_preview&&(l+=`\n <div class="tool-result-output">\n <div class="tool-result-label">📄 Output:</div>\n <div class="tool-result-preview">\n <pre>${this.escapeHtml(n.output_preview)}</pre>\n </div>\n ${n.output_lines?`<div class="tool-result-meta">Lines: ${n.output_lines}</div>`:""}\n </div>\n `),n.has_error&&n.error_preview&&(l+=`\n <div class="tool-result-error">\n <div class="tool-result-label">⚠️ Error:</div>\n <div class="tool-result-preview error-preview">\n <pre>${this.escapeHtml(n.error_preview)}</pre>\n </div>\n </div>\n `),!n.has_output&&!n.has_error&&Object.keys(n).length>3){const t=Object.entries(n).filter(([t,e])=>!["has_output","has_error","exit_code"].includes(t)&&void 0!==e).map(([t,e])=>this.createProperty(this.formatFieldName(t),String(e))).join("");t&&(l+=`\n <div class="tool-result-other">\n <div class="tool-result-label">📊 Result Details:</div>\n <div class="structured-data">\n ${t}\n </div>\n </div>\n `)}return l.trim()?`\n <div class="tool-result-section">\n <div class="contextual-header">\n <h3 class="contextual-header-text">🔧 Tool Result</h3>\n </div>\n <div class="tool-result-content">\n ${l}\n </div>\n </div>\n `:""}isWriteOperation(t,e){if(["Write","Edit","MultiEdit","NotebookEdit"].includes(t))return!0;if(e.tool_parameters){const t=e.tool_parameters;if(t.content||t.new_string||t.edits)return!0;if(t.edit_mode&&"read"!==t.edit_mode)return!0}return!("post_tool"!==e.event_type&&"pre_tool"!==e.event_type||!t||!(t.toLowerCase().includes("write")||t.toLowerCase().includes("edit")||t.toLowerCase().includes("modify")))}isReadOnlyOperation(t){if(!t)return!0;const e=t.toLowerCase();return!!["read"].includes(e)||!["write","edit","multiedit","create","delete","move","copy"].includes(e)}createTodoStructuredView(t){const e=t.data||{};let n="";return e.todos&&Array.isArray(e.todos)&&(n+=`\n <div class="todo-checklist">\n ${e.todos.map(t=>`\n <div class="todo-item todo-${t.status||"pending"}">\n <span class="todo-status">${this.getTodoStatusIcon(t.status)}</span>\n <span class="todo-content">${t.content||"No content"}</span>\n <span class="todo-priority priority-${t.priority||"medium"}">${this.getTodoPriorityIcon(t.priority)}</span>\n </div>\n `).join("")}\n </div>\n `),n}createMemoryStructuredView(t){const e=t.data||{};return`\n <div class="structured-view-section">\n <div class="structured-data">\n ${this.createProperty("Operation",e.operation||"Unknown")}\n ${this.createProperty("Key",e.key||"N/A")}\n ${e.value?this.createProperty("Value","object"==typeof e.value?"[Object]":String(e.value)):""}\n ${e.namespace?this.createProperty("Namespace",e.namespace):""}\n ${e.metadata?this.createProperty("Metadata","object"==typeof e.metadata?"[Object]":String(e.metadata)):""}\n </div>\n </div>\n `}createClaudeStructuredView(t){const e=t.data||{};return`\n <div class="structured-view-section">\n <div class="structured-data">\n ${this.createProperty("Type",t.subtype||"N/A")}\n ${e.prompt?this.createProperty("Prompt",this.truncateText(e.prompt,200)):""}\n ${e.message?this.createProperty("Message",this.truncateText(e.message,200)):""}\n ${e.response?this.createProperty("Response",this.truncateText(e.response,200)):""}\n ${e.content?this.createProperty("Content",this.truncateText(e.content,200)):""}\n ${e.tokens?this.createProperty("Tokens",e.tokens):""}\n ${e.model?this.createProperty("Model",e.model):""}\n </div>\n </div>\n `}createSessionStructuredView(t){const e=t.data||{};return`\n <div class="structured-view-section">\n <div class="structured-data">\n ${this.createProperty("Action",t.subtype||"N/A")}\n ${this.createProperty("Session ID",e.session_id||"N/A")}\n ${e.working_directory?this.createProperty("Working Dir",e.working_directory):""}\n ${e.git_branch?this.createProperty("Git Branch",e.git_branch):""}\n ${e.agent_type?this.createProperty("Agent Type",e.agent_type):""}\n </div>\n </div>\n `}createGenericStructuredView(t){const e=t.data||{},n=Object.keys(e);return 0===n.length?"":`\n <div class="structured-view-section">\n <div class="structured-data">\n ${n.map(t=>this.createProperty(t,"object"==typeof e[t]?"[Object]":String(e[t]))).join("")}\n </div>\n </div>\n `}createCollapsibleJsonSection(t){const e="json-section-"+Math.random().toString(36).substr(2,9),n=this.formatJSON(t),s=this.globalJsonExpanded;return`\n <div class="collapsible-json-section" id="${e}">\n <div class="json-toggle-header"\n onclick="window.moduleViewer.toggleJsonSection()"\n role="button"\n tabindex="0"\n aria-expanded="${s?"true":"false"}"\n onkeydown="if(event.key==='Enter'||event.key===' '){window.moduleViewer.toggleJsonSection();event.preventDefault();}">\n <span class="json-toggle-text">Raw JSON</span>\n <span class="json-toggle-arrow">${s?"▲":"▼"}</span>\n </div>\n <div class="json-content-collapsible" style="display: ${s?"block":"none"};" aria-hidden="${!s}">\n <div class="json-display" onclick="window.moduleViewer.copyJsonToClipboard(event)">\n <pre>${n}</pre>\n </div>\n </div>\n </div>\n `}async copyJsonToClipboard(t){const e=t.currentTarget.getBoundingClientRect(),n=t.clientX-e.left,s=t.clientY-e.top;if(n>e.width-50&&s<30){const e=t.currentTarget.querySelector("pre");if(e)try{await navigator.clipboard.writeText(e.textContent),this.showNotification("JSON copied to clipboard","success")}catch(o){console.error("Failed to copy JSON:",o),this.showNotification("Failed to copy JSON","error")}t.stopPropagation()}}initializeJsonToggle(){window.moduleViewer=this,this.globalJsonExpanded&&setTimeout(()=>{this.updateAllJsonSections()},0),this.keyboardListenerAdded||(this.keyboardListenerAdded=!0,document.addEventListener("keydown",t=>{t.target.classList.contains("json-toggle-header")&&("Enter"!==t.key&&" "!==t.key||(this.toggleJsonSection(),t.preventDefault()))}))}toggleJsonSection(){this.globalJsonExpanded=!this.globalJsonExpanded,localStorage.setItem("dashboard-json-expanded",this.globalJsonExpanded.toString()),this.updateAllJsonSections(),document.dispatchEvent(new CustomEvent("jsonToggleChanged",{detail:{expanded:this.globalJsonExpanded}}))}updateAllJsonSections(){const t=document.querySelectorAll(".json-content-collapsible"),e=document.querySelectorAll(".json-toggle-arrow"),n=document.querySelectorAll(".json-toggle-header");t.forEach((t,s)=>{this.globalJsonExpanded?(t.style.display="block",t.setAttribute("aria-hidden","false"),e[s]&&(e[s].textContent="▲"),n[s]&&n[s].setAttribute("aria-expanded","true")):(t.style.display="none",t.setAttribute("aria-hidden","true"),e[s]&&(e[s].textContent="▼"),n[s]&&n[s].setAttribute("aria-expanded","false"))}),this.globalJsonExpanded&&t.length>0&&setTimeout(()=>{const e=t[0];e&&e.scrollIntoView({behavior:"smooth",block:"nearest"})},100)}createProperty(t,e){const n=this.truncateText(String(e),300);return this.isFilePathProperty(t,e)?`\n <div class="event-property">\n <span class="event-property-key">${t}:</span>\n <span class="event-property-value">\n ${this.createClickableFilePath(e)}\n </span>\n </div>\n `:`\n <div class="event-property">\n <span class="event-property-key">${t}:</span>\n <span class="event-property-value">${n}</span>\n </div>\n `}isFilePathProperty(t,e){if(["File Path","file_path","notebook_path","Full Path","Working Directory","working_directory"].some(e=>t.toLowerCase().includes(e.toLowerCase()))){const t=String(e);return t.length>0&&(t.includes("/")||t.includes("\\"))&&t.length<500}return!1}createClickableFilePath(t){const e=this.truncateText(String(t),300);return`\n <span class="clickable-file-path"\n onclick="showFileViewerModal('${t.replace(/'/g,"\\'")}')"\n title="Click to view file contents with syntax highlighting&#10;Path: ${t}">\n ${e}\n </span>\n `}getEventIcon(t){const e={session:"📱",claude:"🤖",agent:"🎯",hook:"🔗",todo:"✅",memory:"🧠",log:"📝",connection:"🔌",unknown:"❓"};return e[t]||e.unknown}getTodoStatusIcon(t){const e={completed:"✅",in_progress:"🔄",pending:"⏳",cancelled:"❌"};return e[t]||e.pending}getTodoPriorityIcon(t){const e={high:"🔴",medium:"🟡",low:"🟢"};return e[t]||e.medium}getHookDisplayName(t,e){if(e.hook_name)return e.hook_name;if(e.name)return e.name;const n=t.subtype||e.event_type,s={user_prompt:"User Prompt",pre_tool:"Tool Execution (Pre)",post_tool:"Tool Execution (Post)",notification:"Notification",stop:"Session Stop",subagent_stop:"Subagent Stop"};if(s[n])return s[n];if("string"==typeof t.type&&t.type.startsWith("hook.")){const e=t.type.replace("hook.","");if(s[e])return s[e]}return n?n.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "):"Unknown Hook"}extractFilePathFromHook(t){return t.tool_parameters&&t.tool_parameters.file_path?t.tool_parameters.file_path:t.file_path?t.file_path:t.tool_input&&t.tool_input.file_path?t.tool_input.file_path:t.tool_parameters&&t.tool_parameters.notebook_path?t.tool_parameters.notebook_path:null}extractToolInfoFromHook(t){return{tool_name:t.tool_name||t.tool_parameters&&t.tool_parameters.tool_name,operation_type:t.operation_type||t.tool_parameters&&t.tool_parameters.operation_type}}truncateText(t,e){return!t||t.length<=e?t:t.substring(0,e)+"..."}formatJSON(t){try{return JSON.stringify(t,null,2)}catch(e){return String(t)}}formatTimestamp(t){if(!t)return"Unknown time";try{return new Date(t).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",second:"2-digit",hour12:!0})}catch(e){return"Invalid time"}}escapeHtml(t){if(!t)return"";const e=document.createElement("div");return e.textContent=t,e.innerHTML}formatFieldName(t){return t.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}extractToolName(t){if(t.tool_name)return t.tool_name;if(t.tool_parameters&&t.tool_parameters.tool_name)return t.tool_parameters.tool_name;if(t.tool_input&&t.tool_input.tool_name)return t.tool_input.tool_name;if(t.tool_parameters){if(t.tool_parameters.file_path||t.tool_parameters.notebook_path)return"FileOperation";if(t.tool_parameters.pattern)return"Search";if(t.tool_parameters.command)return"Bash";if(t.tool_parameters.todos)return"TodoWrite"}return null}extractAgent(t){if(t._agentName&&"Unknown Agent"!==t._agentName)return t._agentName;if(t._inference&&t._inference.agentName&&"Unknown"!==t._inference.agentName)return t._inference.agentName;if(t.agent)return t.agent;if(t.agent_type)return t.agent_type;if(t.agent_name)return t.agent_name;if(t.session_id&&"string"==typeof t.session_id){const e=t.session_id.split("_");if(e.length>1)return e[0].toUpperCase()}return t.todos||"TodoWrite"===t.tool_name?"PM":null}extractFileName(t){const e=this.extractFilePathFromHook(t);if(e){const t=e.split("/");return t[t.length-1]}return t.filename?t.filename:t.file?t.file:null}clear(){this.showEmptyState()}showToolCall(t,e){if(!t)return void this.showEmptyState();const n=t.tool_name||"Unknown Tool",s=t.agent_type||"PM",o=this.formatTimestamp(t.timestamp),i=t.pre_event,a=t.post_event,r=i?.tool_parameters||{},l=i?this.extractToolTarget(n,r):"Unknown target",c=t.duration_ms?`${t.duration_ms}ms`:"-",d=void 0!==t.success?t.success:null;void 0!==t.exit_code&&t.exit_code;let p=t.result_summary||"No summary available";if("object"==typeof p&&null!==p){const t=[];void 0!==p.exit_code&&t.push(`Exit Code: ${p.exit_code}`),void 0!==p.has_output&&t.push("Has Output: "+(p.has_output?"Yes":"No")),void 0!==p.has_error&&t.push("Has Error: "+(p.has_error?"Yes":"No")),void 0!==p.output_lines&&t.push(`Output Lines: ${p.output_lines}`),p.output_preview&&t.push(`Output Preview: ${p.output_preview}`),p.error_preview&&t.push(`Error Preview: ${p.error_preview}`)}let u="⏳",h="Running...",m="tool-running";a&&(!0===d?(u="✅",h="Success",m="tool-success"):!1===d?(u="❌",h="Failed",m="tool-failure"):(u="⏳",h="Completed",m="tool-completed"));const g=`\n <div class="contextual-header">\n <h3 class="contextual-header-text">${n}: ${s} ${o}</h3>\n </div>\n `;if("TodoWrite"===n&&r.todos){const e=`\n <div class="todo-checklist">\n ${r.todos.map(t=>{const e=this.getTodoStatusIcon(t.status),n=this.getTodoPriorityIcon(t.priority);return`\n <div class="todo-item todo-${t.status||"pending"}">\n <span class="todo-status">${e}</span>\n <span class="todo-content">${t.content||"No content"}</span>\n <span class="todo-priority priority-${t.priority||"medium"}">${n}</span>\n </div>\n `}).join("")}\n </div>\n `,n={toolCall:t,preEvent:i,postEvent:a},s=this.createCollapsibleJsonSection(n);this.dataContainer&&(this.dataContainer.innerHTML=g+e+s),this.initializeJsonToggle()}else if("Grep"===n||"Search"===n||r&&r.pattern&&!r.file_path){const e=r.pattern||"No pattern specified",o=r.path||r.directory||".",l=r.type||r.glob||"all files";let d="";t.result_summary&&(d="string"==typeof t.result_summary?t.result_summary:t.result_summary.output_preview?t.result_summary.output_preview:JSON.stringify(t.result_summary,null,2));const p=`\n <div class="structured-view-section">\n <div class="tool-call-details">\n <div class="tool-call-info ${m}">\n <div class="structured-field">\n <strong>Tool Name:</strong> ${n}\n </div>\n <div class="structured-field">\n <strong>Agent:</strong> ${s}\n </div>\n <div class="structured-field">\n <strong>Status:</strong> ${u} ${h}\n </div>\n <div class="structured-field">\n <strong>Search Pattern:</strong> <code>${e}</code>\n </div>\n <div class="structured-field">\n <strong>Search Path:</strong> ${o}\n </div>\n <div class="structured-field">\n <strong>File Type:</strong> ${l}\n </div>\n <div class="structured-field">\n <strong>Started:</strong> ${new Date(t.timestamp).toLocaleString()}\n </div>\n ${c&&"-"!==c?`\n <div class="structured-field">\n <strong>Duration:</strong> ${c}\n </div>\n `:""}\n </div>\n\n <div class="search-view-action" style="margin-top: 20px;">\n <button class="btn-view-search" data-search-params='${JSON.stringify(r)}' data-search-results='${JSON.stringify(d).replace(/'/g,"&#39;")}' onclick="window.showSearchViewerModal(JSON.parse(this.getAttribute('data-search-params')), JSON.parse(this.getAttribute('data-search-results')))">\n 🔍 View Search Details\n </button>\n </div>\n\n ${this.createToolResultFromToolCall(t)}\n </div>\n </div>\n `,v={toolCall:t,preEvent:i,postEvent:a},f=this.createCollapsibleJsonSection(v);this.dataContainer&&(this.dataContainer.innerHTML=g+p+f),this.initializeJsonToggle()}else{const e=`\n <div class="structured-view-section">\n <div class="tool-call-details">\n <div class="tool-call-info ${m}">\n <div class="structured-field">\n <strong>Tool Name:</strong> ${n}\n </div>\n <div class="structured-field">\n <strong>Agent:</strong> ${s}\n </div>\n <div class="structured-field">\n <strong>Status:</strong> ${u} ${h}\n </div>\n <div class="structured-field">\n <strong>Target:</strong> ${l}\n </div>\n <div class="structured-field">\n <strong>Started:</strong> ${new Date(t.timestamp).toLocaleString()}\n </div>\n ${c&&"-"!==c?`\n <div class="structured-field">\n <strong>Duration:</strong> ${c}\n </div>\n `:""}\n ${t.session_id?`\n <div class="structured-field">\n <strong>Session ID:</strong> ${t.session_id}\n </div>\n `:""}\n </div>\n\n ${this.createToolResultFromToolCall(t)}\n </div>\n </div>\n `,o={toolCall:t,preEvent:i,postEvent:a},r=this.createCollapsibleJsonSection(o);this.dataContainer&&(this.dataContainer.innerHTML=g+e+r),this.initializeJsonToggle()}}showFileOperations(t,e){if(!t||!e)return void this.showEmptyState();const n=e.split("/").pop()||e,s=t.operations||[],o=s[s.length-1],i=`\n <div class="contextual-header">\n <h3 class="contextual-header-text">File: ${n} ${o?this.formatTimestamp(o.timestamp):""}</h3>\n </div>\n `,a=`\n <div class="structured-view-section">\n <div class="file-details">\n <div class="file-path-display">\n <strong>Full Path:</strong> ${this.createClickableFilePath(e)}\n <div id="git-track-status-${e.replace(/[^a-zA-Z0-9]/g,"-")}" class="git-track-status" style="margin-top: 8px;">\n \x3c!-- Git tracking status will be populated here --\x3e\n </div>\n </div>\n <div class="operations-list">\n ${s.map(t=>`\n <div class="operation-item">\n <div class="operation-header">\n <span class="operation-icon">${this.getOperationIcon(t.operation)}</span>\n <span class="operation-type">${t.operation}</span>\n <span class="operation-timestamp">${new Date(t.timestamp).toLocaleString()}</span>\n ${this.isReadOnlyOperation(t.operation)?`\n \x3c!-- Read-only operation: show only file viewer --\x3e\n <span class="file-viewer-icon"\n onclick="showFileViewerModal('${e}')"\n title="View file contents with syntax highlighting"\n style="margin-left: 8px; cursor: pointer; font-size: 16px;">\n 👁️\n </span>\n `:`\n \x3c!-- Edit operation: show both file viewer and git diff --\x3e\n <span class="file-viewer-icon"\n onclick="showFileViewerModal('${e}')"\n title="View file contents with syntax highlighting"\n style="margin-left: 8px; cursor: pointer; font-size: 16px;">\n 👁️\n </span>\n <span class="git-diff-icon"\n onclick="showGitDiffModal('${e}', '${t.timestamp}')"\n title="View git diff for this file operation"\n style="margin-left: 8px; cursor: pointer; font-size: 16px; display: none;"\n data-file-path="${e}"\n data-operation-timestamp="${t.timestamp}">\n 📋\n </span>\n `}\n </div>\n <div class="operation-details">\n <strong>Agent:</strong> ${t.agent}<br>\n <strong>Session:</strong> ${t.sessionId?t.sessionId.substring(0,8)+"...":"Unknown"}\n ${t.details?`<br><strong>Details:</strong> ${t.details}`:""}\n </div>\n </div>\n `).join("")}\n </div>\n </div>\n </div>\n `;this.checkAndShowTrackControl(e),this.checkAndShowGitDiffIcons(e);const r=this.createCollapsibleJsonSection(t);this.dataContainer&&(this.dataContainer.innerHTML=i+a+r),this.initializeJsonToggle()}showErrorMessage(t,e){const n=`\n <div class="module-error">\n <div class="error-header">\n <h3>❌ ${t}</h3>\n </div>\n <div class="error-message">\n <p>${e}</p>\n </div>\n </div>\n `,s={title:t,message:e},o=this.createCollapsibleJsonSection(s);this.dataContainer&&(this.dataContainer.innerHTML=n+o),this.initializeJsonToggle()}showAgentEvent(t,e){this.showAgentSpecificDetails(t,e)}showAgentSpecificDetails(t,e){if(!t)return void this.showEmptyState();const n=window.dashboard?.agentInference,s=window.dashboard?.eventViewer;if(!n||!s)return console.warn("AgentInference or EventViewer not available, falling back to single event view"),void this.showEventDetails(t);const o=n.getInferredAgentForEvent(t),i=o?.agentName||this.extractAgent(t)||"Unknown",a=s.events||[],r=this.getAgentSpecificEvents(a,i,n);console.log(`Showing details for agent: ${i}, found ${r.length} related events`);const l=this.extractAgentSpecificData(i,r);this.renderAgentSpecificView(i,l,t)}getAgentSpecificEvents(t,e,n){return t.filter(t=>{const s=n.getInferredAgentForEvent(t);return(s?.agentName||this.extractAgent(t)||"Unknown").toLowerCase()===e.toLowerCase()})}extractAgentSpecificData(t,e){const n={agentName:t,totalEvents:e.length,prompt:null,todos:[],toolsCalled:[],sessions:new Set,firstSeen:null,lastSeen:null,eventTypes:new Set};return e.forEach(e=>{const s=e.data||{},o=new Date(e.timestamp);(!n.firstSeen||o<n.firstSeen)&&(n.firstSeen=o),(!n.lastSeen||o>n.lastSeen)&&(n.lastSeen=o),(e.session_id||s.session_id)&&n.sessions.add(e.session_id||s.session_id);const i=e.hook_event_name||e.type||"unknown";if(n.eventTypes.add(i),"hook"===e.type&&"Task"===s.tool_name&&s.tool_parameters){const e=s.tool_parameters;e.prompt&&!n.prompt&&(n.prompt=e.prompt),e.description&&!n.description&&(n.description=e.description),e.subagent_type===t&&e.prompt&&(n.prompt=e.prompt)}if(!s.prompt||s.agent_type!==t&&s.subagent_type!==t||(n.prompt=s.prompt),"todo"===e.type||"hook"===e.type&&"TodoWrite"===s.tool_name){const t=s.todos||s.tool_parameters?.todos;t&&Array.isArray(t)&&t.forEach(t=>{const e=n.todos.findIndex(e=>e.id===t.id||e.content===t.content);e>=0?n.todos[e]={...n.todos[e],...t,timestamp:o}:n.todos.push({...t,timestamp:o})})}if("hook"===e.type&&s.tool_name){const t=e.subtype||s.event_type,i=this.generateToolCallId(s.tool_name,s.tool_parameters,o);"pre_tool"===t?(n._preToolEvents||(n._preToolEvents=new Map),n._preToolEvents.set(i,{toolName:s.tool_name,timestamp:o,target:this.extractToolTarget(s.tool_name,s.tool_parameters,null),parameters:s.tool_parameters})):"post_tool"===t&&(n._postToolEvents||(n._postToolEvents=new Map),n._postToolEvents.set(i,{toolName:s.tool_name,timestamp:o,success:s.success,duration:s.duration_ms,resultSummary:s.result_summary,exitCode:s.exit_code}))}}),n.todos.sort((t,e)=>(e.timestamp||0)-(t.timestamp||0)),n.toolsCalled=this.consolidateToolCalls(n._preToolEvents,n._postToolEvents),delete n._preToolEvents,delete n._postToolEvents,n.toolsCalled.sort((t,e)=>e.timestamp-t.timestamp),n}generateToolCallId(t,e,n){const s=Math.floor(n.getTime()/5e3);let o="";if(e){const t=[];e.file_path&&t.push(e.file_path),e.command&&t.push(e.command.substring(0,50)),e.pattern&&t.push(e.pattern),e.subagent_type&&t.push(e.subagent_type),e.notebook_path&&t.push(e.notebook_path),e.url&&t.push(e.url),e.prompt&&t.push(e.prompt.substring(0,30)),o=t.join("|")}return o||(o="default"),`${t}:${s}:${o}`}consolidateToolCalls(t,e){const n=[],s=new Set;t||(t=new Map),e||(e=new Map);for(const[o,i]of t){if(s.has(o))continue;const t=e.get(o),a={toolName:i.toolName,timestamp:i.timestamp,target:i.target,parameters:i.parameters,status:this.determineToolCallStatus(i,t),statusIcon:this.getToolCallStatusIcon(i,t),phase:t?"completed":"running"};t&&(a.success=t.success,a.duration=t.duration,a.resultSummary=t.resultSummary,a.exitCode=t.exitCode,a.completedAt=t.timestamp),n.push(a),s.add(o)}for(const[o,i]of e){if(s.has(o))continue;const t={toolName:i.toolName,timestamp:i.timestamp,target:"Unknown target",parameters:null,status:this.determineToolCallStatus(null,i),statusIcon:this.getToolCallStatusIcon(null,i),phase:"completed",success:i.success,duration:i.duration,resultSummary:i.resultSummary,exitCode:i.exitCode,completedAt:i.timestamp};n.push(t),s.add(o)}return n}determineToolCallStatus(t,e){return e?!0===e.success?"Success":!1===e.success?"Failed":0===e.exitCode?"Completed":2===e.exitCode?"Blocked":void 0!==e.exitCode&&0!==e.exitCode?"Error":"Completed":"Running..."}getToolCallStatusIcon(t,e){return e?!0===e.success?"✅":!1===e.success?"❌":0===e.exitCode?"✅":2===e.exitCode?"⚠️":void 0!==e.exitCode&&0!==e.exitCode?"❌":"✅":"⏳"}estimateTokenCount(t){if(!t||"string"!=typeof t)return 0;const e=t.trim().split(/\s+/).length,n=Math.ceil(t.length/4);return Math.max(1.3*e,n)}trimPromptWhitespace(t){return t&&"string"==typeof t?t=(t=(t=t.trim()).replace(/\n\s*\n\s*\n+/g,"\n\n")).split("\n").map(t=>t.replace(/\s+$/,"")).join("\n"):""}renderAgentSpecificView(t,e,n){const s=this.formatTimestamp(n.timestamp),o=`\n <div class="contextual-header">\n <h3 class="contextual-header-text">🤖 ${t} Agent Details ${s}</h3>\n </div>\n `;let i=`\n <div class="agent-overview-section">\n <div class="structured-data">\n ${this.createProperty("Agent Name",t)}\n ${this.createProperty("Total Events",e.totalEvents)}\n ${this.createProperty("Active Sessions",e.sessions.size)}\n ${this.createProperty("Event Types",Array.from(e.eventTypes).join(", "))}\n ${e.firstSeen?this.createProperty("First Seen",e.firstSeen.toLocaleString()):""}\n ${e.lastSeen?this.createProperty("Last Seen",e.lastSeen.toLocaleString()):""}\n </div>\n </div>\n `;if(e.prompt){const t=this.trimPromptWhitespace(e.prompt);i+=`\n <div class="agent-prompt-section">\n <div class="contextual-header">\n <h3 class="contextual-header-text">📝 Agent Task Prompt</h3>\n <div class="prompt-stats" style="font-size: 11px; color: #64748b; margin-top: 4px;">\n ~${Math.round(this.estimateTokenCount(t))} tokens • ${t.trim().split(/\s+/).length} words • ${t.length} characters\n </div>\n </div>\n <div class="structured-data">\n <div class="agent-prompt" style="white-space: pre-wrap; max-height: 300px; overflow-y: auto; padding: 10px; background: #f8fafc; border-radius: 6px; font-family: monospace; font-size: 12px; line-height: 1.4; border: 1px solid #e2e8f0;">\n ${this.escapeHtml(t)}\n </div>\n </div>\n </div>\n `}e.todos.length>0&&(i+=`\n <div class="agent-todos-section">\n <div class="contextual-header">\n <h3 class="contextual-header-text">✅ Agent Todo List (${e.todos.length} items)</h3>\n </div>\n <div class="todo-checklist">\n ${e.todos.map(t=>`\n <div class="todo-item todo-${t.status||"pending"}">\n <span class="todo-status">${this.getTodoStatusIcon(t.status)}</span>\n <span class="todo-content">${t.content||"No content"}</span>\n <span class="todo-priority priority-${t.priority||"medium"}">${this.getTodoPriorityIcon(t.priority)}</span>\n ${t.timestamp?`<span class="todo-timestamp">${new Date(t.timestamp).toLocaleTimeString()}</span>`:""}\n </div>\n `).join("")}\n </div>\n </div>\n `),e.toolsCalled.length>0&&(i+=`\n <div class="agent-tools-section">\n <div class="contextual-header">\n <h3 class="contextual-header-text">🔧 Tools Called by Agent (${e.toolsCalled.length} calls)</h3>\n </div>\n <div class="tools-list">\n ${e.toolsCalled.map(e=>{let n="";return"✅"===e.statusIcon?n="status-success":"❌"===e.statusIcon?n="status-failed":"⚠️"===e.statusIcon?n="status-blocked":"⏳"===e.statusIcon&&(n="status-running"),`\n <div class="tool-call-item">\n <div class="tool-call-header">\n <div style="display: flex; align-items: center; gap: 12px; flex: 1;">\n <span class="tool-name">🔧 ${e.toolName}</span>\n <span class="tool-agent">${t}</span>\n <span class="tool-status-indicator ${n}">${e.statusIcon} ${e.status}</span>\n </div>\n <span class="tool-timestamp" style="margin-left: auto;">${e.timestamp.toLocaleTimeString()}</span>\n </div>\n <div class="tool-call-details">\n ${e.target?`<span class="tool-target">Target: ${e.target}</span>`:""}\n ${e.duration?`<span class="tool-duration">Duration: ${e.duration}ms</span>`:""}\n ${e.completedAt&&e.completedAt!==e.timestamp?`<span class="tool-completed">Completed: ${e.completedAt.toLocaleTimeString()}</span>`:""}\n </div>\n </div>\n `}).join("")}\n </div>\n </div>\n `);const a={agentName:t,agentData:e,originalEvent:n},r=this.createCollapsibleJsonSection(a);this.dataContainer&&(this.dataContainer.innerHTML=o+i+r),this.initializeJsonToggle()}createToolResultFromToolCall(t){if(!t.result_summary)return"";const e={event_type:"post_tool",result_summary:t.result_summary,success:t.success,exit_code:t.exit_code},n=this.createInlineToolResultContent(e,{subtype:"post_tool"});return n.trim()?`\n <div class="tool-result-inline">\n <div class="structured-data">\n ${n}\n </div>\n </div>\n `:""}extractToolTarget(t,e,n){const s=e||n||{};switch(t?.toLowerCase()){case"write":case"read":case"edit":case"multiedit":return s.file_path||"Unknown file";case"bash":return s.command?`${s.command.substring(0,50)}${s.command.length>50?"...":""}`:"Unknown command";case"grep":return s.pattern?`Pattern: ${s.pattern}`:"Unknown pattern";case"glob":return s.pattern?`Pattern: ${s.pattern}`:"Unknown glob";case"todowrite":return`${s.todos?.length||0} todos`;case"task":return s.subagent_type||s.agent_type||"Subagent delegation";default:return s.file_path?s.file_path:s.pattern?`Pattern: ${s.pattern}`:s.command?`Command: ${s.command.substring(0,30)}...`:s.path?s.path:"Unknown target"}}getOperationIcon(t){return{read:"👁️",write:"✏️",edit:"📝",multiedit:"📝",create:"🆕",delete:"🗑️",move:"📦",copy:"📋"}[t?.toLowerCase()]||"📄"}getCurrentEvent(){return this.currentEvent}async checkAndShowTrackControl(t){if(t)try{const e=window.socket||window.dashboard?.socketClient?.socket;if(!e)return void console.warn("No socket connection available for git tracking check");let n=window.dashboard?.currentWorkingDir;if(!n||"Unknown"===n||""===n.trim()){const t=document.getElementById("footer-working-dir");n=t?.textContent?.trim()&&"Unknown"!==t.textContent.trim()?t.textContent.trim():".",console.log("[MODULE-VIEWER-DEBUG] Working directory fallback used:",n)}const s=new Promise((n,s)=>{const o=s=>{s.file_path===t&&(e.off("file_tracked_response",o),n(s))};e.on("file_tracked_response",o),setTimeout(()=>{e.off("file_tracked_response",o),s(new Error("Request timeout"))},5e3)});e.emit("check_file_tracked",{file_path:t,working_dir:n});const o=await s;this.displayTrackingStatus(t,o)}catch(e){console.error("Error checking file tracking status:",e),this.displayTrackingStatus(t,{success:!1,error:e.message,file_path:t})}}displayTrackingStatus(t,e){const n=`git-track-status-${t.replace(/[^a-zA-Z0-9]/g,"-")}`,s=document.getElementById(n);s&&(e.success&&!1===e.is_tracked?s.innerHTML=`\n <div class="untracked-file-notice">\n <span class="untracked-icon">⚠️</span>\n <span class="untracked-text">This file is not tracked by git</span>\n <button class="track-file-button"\n onclick="window.moduleViewer.trackFile('${t}')"\n title="Add this file to git tracking">\n <span class="git-icon">📁</span> Track File\n </button>\n </div>\n `:e.success&&!0===e.is_tracked?s.innerHTML='\n <div class="tracked-file-notice">\n <span class="tracked-icon">✅</span>\n <span class="tracked-text">This file is tracked by git</span>\n </div>\n ':e.success||(s.innerHTML=`\n <div class="tracking-error-notice">\n <span class="error-icon">❌</span>\n <span class="error-text">Could not check git status: ${e.error||"Unknown error"}</span>\n </div>\n `))}async trackFile(t){if(t)try{const e=window.socket||window.dashboard?.socketClient?.socket;if(!e)return void console.warn("No socket connection available for git add");let n=window.dashboard?.currentWorkingDir;if(!n||"Unknown"===n||""===n.trim()){const t=document.getElementById("footer-working-dir");n=t?.textContent?.trim()&&"Unknown"!==t.textContent.trim()?t.textContent.trim():".",console.log("[MODULE-VIEWER-DEBUG] Working directory fallback used:",n)}const s=`git-track-status-${t.replace(/[^a-zA-Z0-9]/g,"-")}`,o=document.getElementById(s);o&&(o.innerHTML='\n <div class="tracking-file-notice">\n <span class="loading-icon">⏳</span>\n <span class="loading-text">Adding file to git tracking...</span>\n </div>\n ');const i=new Promise((n,s)=>{const o=s=>{s.file_path===t&&(e.off("git_add_response",o),n(s))};e.on("git_add_response",o),setTimeout(()=>{e.off("git_add_response",o),s(new Error("Request timeout"))},1e4)});e.emit("git_add_file",{file_path:t,working_dir:n}),console.log("📁 Git add request sent:",{filePath:t,workingDir:n});const a=await i;console.log("📦 Git add result:",a),a.success?(o&&(o.innerHTML='\n <div class="tracked-file-notice">\n <span class="tracked-icon">✅</span>\n <span class="tracked-text">File successfully added to git tracking</span>\n </div>\n '),this.showNotification("File tracked successfully","success")):(o&&(o.innerHTML=`\n <div class="tracking-error-notice">\n <span class="error-icon">❌</span>\n <span class="error-text">Failed to track file: ${a.error||"Unknown error"}</span>\n <button class="track-file-button"\n onclick="window.moduleViewer.trackFile('${t}')"\n title="Try again">\n <span class="git-icon">📁</span> Retry\n </button>\n </div>\n `),this.showNotification(`Failed to track file: ${a.error}`,"error"))}catch(e){console.error("❌ Failed to track file:",e);const n=`git-track-status-${t.replace(/[^a-zA-Z0-9]/g,"-")}`,s=document.getElementById(n);s&&(s.innerHTML=`\n <div class="tracking-error-notice">\n <span class="error-icon">❌</span>\n <span class="error-text">Error: ${e.message}</span>\n <button class="track-file-button"\n onclick="window.moduleViewer.trackFile('${t}')"\n title="Try again">\n <span class="git-icon">📁</span> Retry\n </button>\n </div>\n `),this.showNotification(`Error tracking file: ${e.message}`,"error")}}async checkAndShowGitDiffIcons(t){if(t){console.debug("[GIT-DIFF-ICONS] Checking git diff icons for file:",t);try{const e=window.socket||window.dashboard?.socketClient?.socket;if(!e)return void console.warn("[GIT-DIFF-ICONS] No socket connection available for git status check");console.debug("[GIT-DIFF-ICONS] Socket connection available, proceeding");let n=window.dashboard?.currentWorkingDir;if(n&&"Unknown"!==n&&""!==n.trim())console.debug("[GIT-DIFF-ICONS] Using working directory:",n);else{const t=document.getElementById("footer-working-dir");n=t?.textContent?.trim()&&"Unknown"!==t.textContent.trim()?t.textContent.trim():".",console.log("[GIT-DIFF-ICONS] Working directory fallback used:",n)}const s=new Promise((n,s)=>{const o=s=>{console.debug("[GIT-DIFF-ICONS] Received git status response:",s),s.file_path===t?(e.off("git_status_response",o),n(s)):console.debug("[GIT-DIFF-ICONS] Response for different file, ignoring:",s.file_path)};e.on("git_status_response",o),setTimeout(()=>{e.off("git_status_response",o),console.warn("[GIT-DIFF-ICONS] Timeout waiting for git status response"),s(new Error("Request timeout"))},3e3)});console.debug("[GIT-DIFF-ICONS] Sending check_git_status event"),e.emit("check_git_status",{file_path:t,working_dir:n});const o=await s;console.debug("[GIT-DIFF-ICONS] Git status check result:",o),o.success?(console.debug("[GIT-DIFF-ICONS] Git status check successful, showing icons for:",t),this.showGitDiffIconsForFile(t)):console.debug("[GIT-DIFF-ICONS] Git status check failed, icons will remain hidden:",o.error)}catch(e){console.warn("[GIT-DIFF-ICONS] Git status check failed, hiding git diff icons:",e.message)}}else console.debug("[GIT-DIFF-ICONS] No filePath provided, skipping git diff icon check")}showGitDiffIconsForFile(t){console.debug("[GIT-DIFF-ICONS] Showing git diff icons for file:",t);const e=document.querySelectorAll(`[data-file-path="${t}"]`);console.debug("[GIT-DIFF-ICONS] Found",e.length,"elements with matching file path");let n=0;e.forEach((t,e)=>{console.debug("[GIT-DIFF-ICONS] Processing element",e,":",t),console.debug("[GIT-DIFF-ICONS] Element classes:",t.classList.toString()),t.classList.contains("git-diff-icon")?(console.debug("[GIT-DIFF-ICONS] Setting display to inline for git-diff-icon"),t.style.display="inline",n++):console.debug("[GIT-DIFF-ICONS] Element is not a git-diff-icon, skipping")}),console.debug("[GIT-DIFF-ICONS] Showed",n,"git diff icons for file:",t)}showNotification(t,e="info"){const n=document.createElement("div");n.className=`notification notification-${e}`,n.innerHTML=`\n <span class="notification-icon">${"success"===e?"✅":"error"===e?"❌":"ℹ️"}</span>\n <span class="notification-message">${t}</span>\n `,n.style.cssText=`\n position: fixed;\n top: 20px;\n right: 20px;\n background: ${"success"===e?"#d4edda":"error"===e?"#f8d7da":"#d1ecf1"};\n color: ${"success"===e?"#155724":"error"===e?"#721c24":"#0c5460"};\n border: 1px solid ${"success"===e?"#c3e6cb":"error"===e?"#f5c6cb":"#bee5eb"};\n border-radius: 6px;\n padding: 12px 16px;\n font-size: 14px;\n font-weight: 500;\n z-index: 2000;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n display: flex;\n align-items: center;\n gap: 8px;\n max-width: 400px;\n animation: slideIn 0.3s ease-out;\n `;const s=document.createElement("style");s.textContent="\n @keyframes slideIn {\n from { transform: translateX(100%); opacity: 0; }\n to { transform: translateX(0); opacity: 1; }\n }\n @keyframes slideOut {\n from { transform: translateX(0); opacity: 1; }\n to { transform: translateX(100%); opacity: 0; }\n }\n ",document.head.appendChild(s),document.body.appendChild(n),setTimeout(()=>{n.style.animation="slideOut 0.3s ease-in",setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),s.parentNode&&s.parentNode.removeChild(s)},300)},5e3)}showAgentInstance(t){if(!t)return void this.showEmptyState();const e={type:"pm_delegation",subtype:t.agentName,agent_type:t.agentName,timestamp:t.timestamp,session_id:t.sessionId,metadata:{delegation_type:"explicit",event_count:t.agentEvents.length,pm_call:t.pmCall||null,agent_events:t.agentEvents}};console.log("Showing PM delegation details:",t),this.showAgentSpecificDetails(e,0)}showImpliedAgent(t){if(!t)return void this.showEmptyState();const e={type:"implied_delegation",subtype:t.agentName,agent_type:t.agentName,timestamp:t.timestamp,session_id:t.sessionId,metadata:{delegation_type:"implied",event_count:t.eventCount,pm_call:null,note:"No explicit PM call found - inferred from agent activity"}};console.log("Showing implied agent details:",t),this.showAgentSpecificDetails(e,0)}}window.ModuleViewer=t,window.enableToolResultDebugging=function(){window.DEBUG_TOOL_RESULTS=!0,console.log("🔧 Tool result debugging enabled. Click on tool events to see debug info.")},window.disableToolResultDebugging=function(){window.DEBUG_TOOL_RESULTS=!1,console.log("🔧 Tool result debugging disabled.")};export{t as M};
2
2
  //# sourceMappingURL=module-viewer.js.map