claude-mpm 4.1.22__py3-none-any.whl → 4.1.24__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.
@@ -1,2 +1,2 @@
1
- import{S as e,U as t}from"./socket-client.js";import{E as n,a as i}from"./components/event-viewer.js";import{M as s}from"./components/module-viewer.js";import{S as o}from"./components/session-manager.js";import{A as a}from"./components/agent-inference.js";import{E as r}from"./components/export-manager.js";import{W as l}from"./components/working-directory.js";import{F as d}from"./components/file-tool-tracker.js";class c{constructor(e,t){this.agentInference=e,this.eventViewer=t,this.state={hierarchyTree:null,nodeMap:new Map,expandedNodes:new Set,selectedNode:null},this.expandAll=!0,this.setupEventListeners(),console.log("Agent hierarchy component initialized")}setupEventListeners(){document.addEventListener("click",e=>{const t=e.target.closest("[data-toggle-node]");if(t&&window.dashboard&&window.dashboard.agentHierarchy){const e=t.dataset.toggleNode;window.dashboard.agentHierarchy.toggleNode(e)}})}buildHierarchy(){this.agentInference.processAgentInference();const e=this.agentInference.getPMDelegations(),t=this.eventViewer.events,n=this.agentInference.getEventAgentMap(),i={id:"pm_main",type:"pm",name:"PM (Main Session)",children:[],events:[],eventCount:0,status:"active",startTime:null,endTime:null,expanded:!0},s=new Map;this.state.nodeMap.clear(),this.state.nodeMap.set(i.id,i);const o=new Set;for(const[h,u]of e){const e={id:h,type:"subagent",name:u.agentName,delegationContext:this.extractDelegationContext(u.pmCall),children:[],events:u.agentEvents,eventCount:u.agentEvents.length,status:u.endIndex?"completed":"active",startTime:u.timestamp,endTime:u.endIndex?t[u.endIndex]?.timestamp:null,startIndex:u.startIndex,endIndex:u.endIndex,expanded:this.expandAll||this.state.expandedNodes.has(h)};if(i.children.push(e),this.state.nodeMap.set(h,e),o.add(u.agentName),i.eventCount++,(!i.startTime||new Date(u.timestamp)<new Date(i.startTime))&&(i.startTime=u.timestamp),u.endIndex&&t[u.endIndex]){const e=t[u.endIndex].timestamp;(!i.endTime||new Date(e)>new Date(i.endTime))&&(i.endTime=e)}}const a=this.agentInference.getOrphanGroups();let r=1;for(const[h,u]of a){const i={id:`pm_implied_${h}`,type:"pm",name:`PM (Implied #${r})`,children:[],events:[],eventCount:0,status:"inferred",startTime:null,endTime:null,expanded:!0,isImplied:!0,tooltip:"Inferred PM - Subagents started without explicit PM delegation"};s.set(h,i),this.state.nodeMap.set(i.id,i),r++;const o=new Map;for(const s of u){const i=[];t.forEach((t,o)=>{const a=n.get(o);if(a&&a.agentName===s.agentName){let n=!0;for(const[t,i]of e)if(i.agentEvents.some(e=>e.eventIndex===o)){n=!1;break}n&&i.push({eventIndex:o,event:t,inference:a})}}),i.length>0&&(o.has(s.agentName)||o.set(s.agentName,[]),o.get(s.agentName).push(...i))}for(const[e,t]of o){if(0===t.length)continue;const n=t[0].event,s=t[t.length-1].event,o={id:`implied_agent_${h}_${e}`,type:"subagent",name:e,delegationContext:"Orphan agent - no explicit PM delegation found",children:[],events:t,eventCount:t.length,status:"inferred",startTime:n.timestamp,endTime:s.timestamp,startIndex:t[0].eventIndex,endIndex:t[t.length-1].eventIndex,expanded:this.expandAll,isImplied:!0,tooltip:"This agent was spawned without an explicit PM Task delegation"};i.children.push(o),this.state.nodeMap.set(o.id,o),i.eventCount+=t.length,(!i.startTime||new Date(n.timestamp)<new Date(i.startTime))&&(i.startTime=n.timestamp),(!i.endTime||new Date(s.timestamp)>new Date(i.endTime))&&(i.endTime=s.timestamp)}}const l=[];if(t.forEach((t,i)=>{const o=n.get(i);if(o&&"subagent"===o.type){let n=!0;for(const[t,s]of e)if(s.agentEvents.some(e=>e.eventIndex===i)){n=!1;break}if(n)for(const[e,t]of s){for(const e of t.children)if(e.events.some(e=>e.eventIndex===i)){n=!1;break}if(!n)break}n&&l.push({eventIndex:i,event:t,inference:o})}}),l.length>0){const e={id:"pm_implied_generic",type:"pm",name:"PM (Implied - Uncategorized)",children:[],events:[],eventCount:0,status:"inferred",startTime:null,endTime:null,expanded:!0,isImplied:!0,tooltip:"Orphan agents without clear grouping"},t=new Map;for(const n of l){const e=n.inference.agentName;t.has(e)||t.set(e,[]),t.get(e).push(n)}for(const[n,i]of t){const t=i[0].event,s=i[i.length-1].event,o={id:`implied_generic_${n}`,type:"subagent",name:n,delegationContext:"Uncategorized orphan agent",children:[],events:i,eventCount:i.length,status:"inferred",startTime:t.timestamp,endTime:s.timestamp,startIndex:i[0].eventIndex,endIndex:i[i.length-1].eventIndex,expanded:this.expandAll,isImplied:!0};e.children.push(o),this.state.nodeMap.set(o.id,o),e.eventCount+=i.length,(!e.startTime||new Date(t.timestamp)<new Date(e.startTime))&&(e.startTime=t.timestamp),(!e.endTime||new Date(s.timestamp)>new Date(e.endTime))&&(e.endTime=s.timestamp)}e.children.length>0&&(s.set("generic",e),this.state.nodeMap.set(e.id,e))}let d=0;if(t.forEach((e,t)=>{const s=n.get(t);s&&"main_agent"===s.type&&(d++,i.events.push({eventIndex:t,event:e,inference:s}))}),i.eventCount+=d,i.children.length>0){const e=i.children.some(e=>"active"===e.status);i.status=e?"active":"completed"}const c={roots:[]};(i.eventCount>0||i.children.length>0)&&c.roots.push(i);for(const[h,u]of s)u.children.length>0&&c.roots.push(u);return this.state.hierarchyTree=c,console.log("Hierarchy built:",{mainPM:{children:i.children.length,events:i.eventCount,ownEvents:d},impliedPMGroups:s.size,totalImpliedAgents:Array.from(s.values()).reduce((e,t)=>e+t.children.length,0)}),c}extractDelegationContext(e){if(!e)return"Unknown delegation";const t=e.tool_parameters||e.data?.tool_parameters||{},n=t.task||t.request||t.description;if(n){const e=100;return n.length>e?n.substring(0,e)+"...":n}const i=e.tool_input||e.data?.tool_input;if(i&&"string"==typeof i){const e=100;return i.length>e?i.substring(0,e)+"...":i}return"Task delegation"}render(e={}){const t=this.state.hierarchyTree||this.buildHierarchy();if(!t.roots||0===t.roots.length)return'<div class="agent-hierarchy-empty">No agent activity detected</div>';return`<div class="agent-hierarchy">${this.applyFilters(t,e).roots.map(e=>this.renderNode(e,0)).join("")}</div>`}renderNode(e,t){const n=e.expanded||this.state.expandedNodes.has(e.id),i=e.children&&e.children.length>0,s=this.state.selectedNode===e.id,o=this.getNodeIcon(e),a=i?n?"▼":"▶":"&nbsp;&nbsp;",r=this.getStatusClass(e.status),l=e.isImplied?"agent-node-implied":"",d=e.tooltip?`title="${this.escapeHtml(e.tooltip)}"`:"";let c=`\n <div class="agent-node agent-node-level-${t} ${s?"agent-node-selected":""} ${l}" \n data-node-id="${e.id}" ${d}>\n <div class="agent-node-header ${r}" \n data-toggle-node="${e.id}" style="cursor: pointer">\n <span class="agent-node-expand">${a}</span>\n <span class="agent-node-icon">${o}</span>\n <span class="agent-node-name">${this.escapeHtml(e.name)}</span>\n <span class="agent-node-stats">\n <span class="agent-event-count">${e.eventCount} events</span>\n ${e.status?`<span class="agent-status">${e.status}</span>`:""}\n </span>\n </div>\n `;if(n&&(e.delegationContext||e.startTime)){if(c+='<div class="agent-node-details">',e.delegationContext&&"Unknown delegation"!==e.delegationContext&&(c+=`\n <div class="agent-delegation-context">\n <strong>Task:</strong> ${this.escapeHtml(e.delegationContext)}\n </div>\n `),e.startTime){const t=this.calculateDuration(e.startTime,e.endTime);c+=`\n <div class="agent-timing">\n <span class="agent-time-start">${this.formatTime(e.startTime)}</span>\n ${t?`<span class="agent-duration">(${t})</span>`:""}\n </div>\n `}c+="</div>"}return n&&i&&(c+='<div class="agent-node-children">',c+=e.children.map(e=>this.renderNode(e,t+1)).join(""),c+="</div>"),c+="</div>",c}getNodeIcon(e){if("pm"===e.type)return e.isImplied?"🔍":"👔";return{"Engineer Agent":"🔧","Research Agent":"🔍","QA Agent":"✅","Documentation Agent":"📝","Security Agent":"🔒","Ops Agent":"⚙️","Version Control Agent":"📦","Data Engineer Agent":"💾","Test Integration Agent":"🧪"}[e.name]||"🤖"}getStatusClass(e){switch(e){case"active":return"agent-status-active";case"completed":return"agent-status-completed";case"pending":return"agent-status-pending";case"inferred":return"agent-status-inferred";default:return"agent-status-unknown"}}toggleNode(e){const t=this.state.nodeMap.get(e);t&&(this.state.expandedNodes.has(e)?(this.state.expandedNodes.delete(e),t.expanded=!1):(this.state.expandedNodes.add(e),t.expanded=!0),window.dashboard&&window.dashboard.renderCurrentTab())}selectNode(e){this.state.selectedNode=e;const t=this.state.nodeMap.get(e);if(t){const e=new CustomEvent("agentNodeSelected",{detail:{node:t}});document.dispatchEvent(e)}}applyFilters(e,t){if(!t||0===Object.keys(t).length)return e;const n={roots:[]};for(const i of e.roots){const e=this.filterNode(i,t);e&&n.roots.push(e)}return n}filterNode(e,t){let n=!0;if(t.searchText){const i=t.searchText.toLowerCase();n=n&&(e.name.toLowerCase().includes(i)||e.delegationContext&&e.delegationContext.toLowerCase().includes(i))}t.agentType&&(n=n&&e.name.includes(t.agentType)),t.status&&(n=n&&e.status===t.status);let i=[];if(e.children)for(const s of e.children){const e=this.filterNode(s,t);e&&i.push(e)}return n||i.length>0?{...e,children:i}:null}formatTime(e){if(!e)return"";return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}calculateDuration(e,t){if(!e||!t)return"";const n=new Date(e).getTime(),i=new Date(t).getTime()-n;if(i<1e3)return`${i}ms`;if(i<6e4)return`${(i/1e3).toFixed(1)}s`;return`${Math.floor(i/6e4)}m ${Math.floor(i%6e4/1e3)}s`}escapeHtml(e){if(!e)return"";const t=document.createElement("div");return t.textContent=e,t.innerHTML}updateWithNewEvents(e){this.buildHierarchy()}clear(){this.state.hierarchyTree=null,this.state.nodeMap.clear(),this.state.expandedNodes.clear(),this.state.selectedNode=null}expandAllNodes(){for(const[e,t]of this.state.nodeMap)this.state.expandedNodes.add(e),t.expanded=!0;this.expandAll=!0}collapseAllNodes(){this.state.expandedNodes.clear();for(const[e,t]of this.state.nodeMap)t.expanded=!1;this.expandAll=!1}}class h{constructor(){this.element=null,this.buildInfo={monitor:{version:"1.0.0",build:1,formatted_build:"0001",full_version:"v1.0.0-0001"},mpm:{version:"unknown",build:"unknown",full_version:"v0.0.0"}},this.socketClient=null,this.init()}async init(){await this.loadDashboardVersion(),this.createElements(),this.setupEventListeners()}async loadDashboardVersion(){try{const e=await fetch("/version.json");if(e.ok){const t=await e.json();this.buildInfo.monitor={version:t.version||"1.0.0",build:t.build||1,formatted_build:t.formatted_build||"0001",full_version:t.full_version||"v1.0.0-0001"}}}catch(e){}}createElements(){this.element=document.createElement("div"),this.element.className="version-display",this.element.id="version-display";const e=document.createElement("span");e.className="version-item mpm-version",e.id="mpm-version",e.innerHTML='\n <span class="version-label">MPM</span>\n <span class="version-value">v0.0.0</span>\n ';const t=document.createElement("span");t.className="version-separator",t.textContent="|";const n=document.createElement("span");n.className="version-item monitor-version",n.id="monitor-version",n.innerHTML='\n <span class="version-label">Monitor</span>\n <span class="version-value">v1.0.0-0001</span>\n ',this.element.appendChild(e),this.element.appendChild(t),this.element.appendChild(n),this.element.title="Click for detailed version information"}setSocketClient(e){this.socketClient=e,this.socketClient&&this.socketClient.socket&&(this.socketClient.socket.on("welcome",e=>{const t=e.build_info||e.data&&e.data.build_info;t&&this.updateBuildInfo(t)}),this.socketClient.socket.on("status",e=>{const t=e.build_info||e.data&&e.data.build_info;t&&this.updateBuildInfo(t)}),this.socketClient.socket.on("build_info",e=>{this.updateBuildInfo(e)}))}updateBuildInfo(e){this.buildInfo=e,this.updateDisplay()}updateDisplay(){const e=this.element.querySelector(".mpm-version .version-value");if(e&&this.buildInfo.mpm){const t=this.buildInfo.mpm.full_version||`v${this.buildInfo.mpm.version}`;e.textContent=t,this.buildInfo.mpm.build&&"unknown"!==this.buildInfo.mpm.build&&(e.parentElement.title=`MPM Build: ${this.buildInfo.mpm.build}`)}const t=this.element.querySelector(".monitor-version .version-value");if(t&&this.buildInfo.monitor){const e=this.buildInfo.monitor.full_version||`v${this.buildInfo.monitor.version}-${this.buildInfo.monitor.formatted_build}`;if(t.textContent=e,this.buildInfo.monitor.last_updated){const e=new Date(this.buildInfo.monitor.last_updated).toLocaleString();t.parentElement.title=`Monitor Build: ${this.buildInfo.monitor.formatted_build}\nLast Updated: ${e}`}}}setupEventListeners(){this.element.addEventListener("click",()=>{this.showDetailedInfo()})}showDetailedInfo(){const e=[];if(this.buildInfo.mpm&&(e.push("=== MPM Framework ==="),e.push(`Version: ${this.buildInfo.mpm.version}`),this.buildInfo.mpm.build&&"unknown"!==this.buildInfo.mpm.build&&e.push(`Build: ${this.buildInfo.mpm.build}`),e.push(`Full: ${this.buildInfo.mpm.full_version}`)),e.push(""),this.buildInfo.monitor&&(e.push("=== Monitor UI ==="),e.push(`Version: ${this.buildInfo.monitor.version}`),e.push(`Build: ${this.buildInfo.monitor.formatted_build} (${this.buildInfo.monitor.build})`),e.push(`Full: ${this.buildInfo.monitor.full_version}`),this.buildInfo.monitor.last_updated)){const t=new Date(this.buildInfo.monitor.last_updated).toLocaleString();e.push(`Updated: ${t}`)}const t=document.createElement("div");t.className="version-modal",t.innerHTML=`\n <div class="version-modal-content">\n <h3>Version Information</h3>\n <pre>${e.join("\n")}</pre>\n <button onclick="this.parentElement.parentElement.remove()">Close</button>\n </div>\n `,document.body.appendChild(t),setTimeout(()=>{t.remove()},1e4)}mount(e){const t="string"==typeof e?document.querySelector(e):e;this.element&&t&&this.element.parentNode!==t&&t.appendChild(this.element)}getElement(){return this.element}destroy(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.socketClient&&this.socketClient.socket&&(this.socketClient.socket.off("welcome"),this.socketClient.socket.off("status"),this.socketClient.socket.off("build_info")),this.element=null,this.socketClient=null}}class u{constructor(){this.eventViewer=null,this.moduleViewer=null,this.sessionManager=null,this.socketManager=null,this.agentInference=null,this.agentHierarchy=null,this.uiStateManager=null,this.eventProcessor=null,this.exportManager=null,this.workingDirectoryManager=null,this.fileToolTracker=null,this.buildTracker=null,this.init()}init(){console.log("Initializing refactored Claude MPM Dashboard...");try{this.initializeSocketManager(),this.initializeCoreComponents(),this.initializeBuildTracker(),this.initializeAgentInference(),this.initializeAgentHierarchy(),this.initializeUIStateManager(),this.initializeWorkingDirectoryManager(),this.initializeFileToolTracker(),this.initializeEventProcessor(),this.initializeExportManager(),this.setupModuleInteractions(),this.initializeFromURL(),console.log("Claude MPM Dashboard initialized successfully")}catch(e){throw console.error("Error during dashboard initialization:",e),e}}validateInitialization(){const e=[{name:"socketManager",component:this.socketManager},{name:"eventViewer",component:this.eventViewer},{name:"agentHierarchy",component:this.agentHierarchy}].filter(e=>!e.component);e.length>0?console.warn("Missing critical components:",e.map(e=>e.name)):console.log("All critical components initialized")}postInit(){try{this.agentHierarchy&&(window.dashboard.agentHierarchy=this.agentHierarchy,console.log("Agent hierarchy global reference set")),this.validateInitialization()}catch(e){console.error("Error in dashboard postInit:",e)}}initializeSocketManager(){this.socketManager=new e,this.socketManager.setupConnectionControls(),this.socketClient=this.socketManager.getSocketClient(),window.socketClient=this.socketClient}initializeCoreComponents(){this.eventViewer=new n("events-list",this.socketClient),this.moduleViewer=new s,this.sessionManager=new o(this.socketClient),window.eventViewer=this.eventViewer,window.moduleViewer=this.moduleViewer,window.sessionManager=this.sessionManager}initializeBuildTracker(){this.buildTracker=new h,this.buildTracker.setSocketClient(this.socketClient);const e=()=>{const t=document.querySelector(".header-title");t?(this.buildTracker.mount(t),console.log("BuildTracker mounted successfully")):(console.warn("Header-title element not found for build tracker, will retry"),setTimeout(e,100))};e(),window.buildTracker=this.buildTracker}initializeAgentInference(){this.agentInference=new a(this.eventViewer),this.agentInference.initialize()}initializeAgentHierarchy(){try{this.agentHierarchy=new c(this.agentInference,this.eventViewer),console.log("Agent hierarchy component created")}catch(e){console.error("Failed to initialize agent hierarchy:",e),this.agentHierarchy={render:()=>'<div class="error">Agent hierarchy unavailable</div>',expandAllNodes:()=>{},collapseAllNodes:()=>{},updateWithNewEvents:()=>{}}}}initializeUIStateManager(){this.uiStateManager=new t,this.setupTabFilters()}initializeWorkingDirectoryManager(){this.workingDirectoryManager=new l(this.socketManager)}initializeFileToolTracker(){this.fileToolTracker=new d(this.agentInference,this.workingDirectoryManager)}initializeEventProcessor(){this.eventProcessor=new i(this.eventViewer,this.agentInference)}initializeExportManager(){this.exportManager=new r(this.eventViewer)}setupModuleInteractions(){this.socketManager.onEventUpdate(e=>{this.fileToolTracker.updateFileOperations(e),this.fileToolTracker.updateToolCalls(e),this.agentInference.processAgentInference(),this.agentHierarchy.updateWithNewEvents(e),"events"===this.uiStateManager.getCurrentTab()&&this.exportManager.scrollListToBottom("events-list"),this.renderCurrentTab()}),this.socketManager.onConnectionStatusChange((e,t)=>{"connected"===t&&this.workingDirectoryManager.updateGitBranch(this.workingDirectoryManager.getCurrentWorkingDir())}),document.addEventListener("tabChanged",e=>{this.renderCurrentTab(),this.uiStateManager.updateTabNavigationItems()}),document.addEventListener("eventsClearing",()=>{this.fileToolTracker.clear(),this.agentInference.initialize()}),document.addEventListener("showCardDetails",e=>{this.showCardDetails(e.detail.tabName,e.detail.index)}),document.addEventListener("sessionFilterChanged",e=>{console.log("Session filter changed, re-rendering current tab:",this.uiStateManager.getCurrentTab()),this.renderCurrentTab()})}setupTabFilters(){const e=document.getElementById("agents-search-input"),t=document.getElementById("agents-type-filter");e&&e.addEventListener("input",()=>{"agents"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()}),t&&t.addEventListener("change",()=>{"agents"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()});const n=document.getElementById("tools-search-input"),i=document.getElementById("tools-type-filter");n&&n.addEventListener("input",()=>{"tools"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()}),i&&i.addEventListener("change",()=>{"tools"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()});const s=document.getElementById("files-search-input"),o=document.getElementById("files-type-filter");s&&s.addEventListener("input",()=>{"files"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()}),o&&o.addEventListener("change",()=>{"files"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()})}initializeFromURL(){const e=new URLSearchParams(window.location.search);this.socketManager.initializeFromURL(e)}renderCurrentTab(){const e=this.uiStateManager.getCurrentTab();switch(e){case"events":break;case"activity":if(window.ActivityTree&&"function"==typeof window.ActivityTree)window.activityTreeInstance||(console.log("Creating new ActivityTree instance..."),window.activityTreeInstance=new window.ActivityTree),window.activityTreeInstance&&(window.activityTreeInstance.initialized||(console.log("Initializing ActivityTree..."),window.activityTreeInstance.initialize()),"function"==typeof window.activityTreeInstance.renderWhenVisible&&(console.log("Dashboard triggering activity tree render..."),window.activityTreeInstance.renderWhenVisible()),"function"==typeof window.activityTreeInstance.forceShow&&(console.log("Dashboard forcing activity tree to show..."),window.activityTreeInstance.forceShow()));else if(window.activityTree&&"function"==typeof window.activityTree){const e=window.activityTree();e&&("function"==typeof e.renderWhenVisible&&(console.log("Dashboard triggering activity tree render (legacy)..."),e.renderWhenVisible()),"function"==typeof e.forceShow&&(console.log("Dashboard forcing activity tree to show (legacy)..."),e.forceShow()))}else console.warn("Activity tree component not available, retrying in 100ms..."),setTimeout(()=>{"activity"===this.currentTab&&this.renderCurrentTab()},100);break;case"agents":this.renderAgents();break;case"tools":this.renderTools();break;case"files":this.renderFiles()}this.uiStateManager.getSelectedCard().tab===e&&this.uiStateManager.updateCardSelectionUI(),this.uiStateManager.updateUnifiedSelectionUI()}renderAgents(){const e=document.getElementById("agents-list");if(!e)return;const t=document.getElementById("agents-search-input")?.value||"",n=document.getElementById("agents-type-filter")?.value||"",i=this.renderAgentsFlat(t,n);e.innerHTML=i,this.removeHierarchyControls();const s=this.agentInference.getUniqueAgentInstances();this.updateAgentsFilterDropdowns(s)}removeHierarchyControls(){const e=document.getElementById("hierarchy-controls");e&&e.remove()}renderAgentsFlat(e,t){const n=this.eventViewer.events;if(!n||0===n.length)return'<div class="no-events">No agent events found...</div>';this.agentInference.processAgentInference();const i=this.agentInference.getEventAgentMap(),s=[];if(n.forEach((n,o)=>{const a=i.get(o);if(a&&("subagent"===a.type||"main_agent"===a.type)){let i=!0;if(e){const t=e.toLowerCase();i=i&&(a.agentName.toLowerCase().includes(t)||n.tool_name&&n.tool_name.toLowerCase().includes(t)||n.data&&JSON.stringify(n.data).toLowerCase().includes(t))}t&&(i=i&&a.agentName.includes(t)),i&&s.push({event:n,inference:a,index:o,timestamp:new Date(n.timestamp)})}}),0===s.length)return'<div class="no-events">No agent events match the current filters...</div>';return`<div class="agent-events-flat">${s.map((e,t)=>{const{event:n,inference:i,index:s,timestamp:o}=e;let a="Activity",r="📋",l="";if("SubagentStart"===n.event_type)a="Started",r="🟢",l="Agent session began";else if("SubagentStop"===n.event_type)a="Stopped",r="🔴",l="Agent session ended";else if(n.tool_name&&(a=`Tool: ${n.tool_name}`,r=this.getToolIcon(n.tool_name),n.data&&n.data.tool_parameters)){const e=n.data.tool_parameters;e.file_path?l=e.file_path:e.command?l=e.command.substring(0,50)+(e.command.length>50?"...":""):e.pattern?l=`pattern="${e.pattern}"`:e.query&&(l=`query="${e.query}"`)}let d="completed";return"SubagentStart"===n.event_type?d="active":n.data&&n.data.error&&(d="error"),`\n <div class="agent-event-item" data-index="${t}" onclick="window.dashboard.showCardDetails('agents', ${s})">\n <div class="agent-event-header">\n <div class="agent-event-time">${this.formatTimestamp(o)}</div>\n <div class="agent-event-agent">\n ${this.getAgentIcon(i.agentName)} ${i.agentName}\n </div>\n <div class="agent-event-action">\n ${r} ${a}\n </div>\n <div class="agent-event-status status-${d}">\n ${this.getStatusIcon(d)}\n </div>\n </div>\n ${l?`<div class="agent-event-details">${this.escapeHtml(l)}</div>`:""}\n </div>\n `}).join("")}</div>`}getAgentIcon(e){return{PM:"🎯","Engineer Agent":"🔧","Research Agent":"🔍","QA Agent":"✅","Documentation Agent":"📝","Security Agent":"🔒","Ops Agent":"⚙️","Version Control Agent":"📦","Data Engineer Agent":"💾","Test Integration Agent":"🧪"}[e]||"🤖"}getToolIcon(e){return{Read:"📖",Write:"✏️",Edit:"📝",Bash:"💻",Grep:"🔍",Glob:"📂",LS:"📁",Task:"📋"}[e]||"🔧"}getStatusIcon(e){return{active:"🟢",completed:"✅",error:"❌",pending:"🟡"}[e]||"❓"}formatTimestamp(e){return e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}escapeHtml(e){if(!e)return"";const t=document.createElement("div");return t.textContent=e,t.innerHTML}renderTools(){const e=document.getElementById("tools-list");if(!e)return;const t=this.fileToolTracker.getToolCalls(),n=Array.from(t.entries()),i=this.eventProcessor.getUniqueToolInstances(n),s=this.eventProcessor.generateToolHTML(i);e.innerHTML=s,this.exportManager.scrollListToBottom("tools-list"),this.updateToolsFilterDropdowns(i)}renderFiles(){const e=document.getElementById("files-list");if(!e)return;const t=this.fileToolTracker.getFileOperations(),n=Array.from(t.entries()),i=this.eventProcessor.getUniqueFileInstances(n),s=this.eventProcessor.generateFileHTML(i);e.innerHTML=s,this.exportManager.scrollListToBottom("files-list"),this.updateFilesFilterDropdowns(n)}updateAgentsFilterDropdowns(e){const t=new Set;e.forEach(e=>{e.agentName&&"Unknown"!==e.agentName&&t.add(e.agentName)});const n=Array.from(t).filter(e=>e&&""!==e.trim());this.populateFilterDropdown("agents-type-filter",n,"All Agent Types"),n.length>0?console.log("Agent types found for filter:",n):console.log("No agent types found for filter. Instances:",e.length)}updateToolsFilterDropdowns(e){const t=[...new Set(e.map(([e,t])=>t.tool_name))].filter(e=>e);this.populateFilterDropdown("tools-type-filter",t,"All Tools")}updateFilesFilterDropdowns(e){const t=[...new Set(e.flatMap(([e,t])=>t.operations.map(e=>e.operation)))].filter(e=>e);this.populateFilterDropdown("files-type-filter",t,"All Operations")}populateFilterDropdown(e,t,n="All"){const i=document.getElementById(e);if(!i)return;const s=i.value,o=t.sort((e,t)=>e.localeCompare(t));i.innerHTML=`<option value="">${n}</option>`,o.forEach(e=>{const t=document.createElement("option");t.value=e,t.textContent=e,i.appendChild(t)}),s&&o.includes(s)&&(i.value=s)}showCardDetails(e,t){switch(e){case"events":this.eventViewer&&this.eventViewer.showEventDetails(t);break;case"agents":this.showAgentDetailsByIndex(t);break;case"tools":this.showToolDetailsByIndex(t);break;case"files":this.showFileDetailsByIndex(t)}}showAgentDetailsByIndex(e){const t=this.eventProcessor.getFilteredEventsForTab("agents");if(!t||!Array.isArray(t)||e<0||e>=t.length)return void console.warn("Dashboard: Invalid agent index or events array");const n=this.eventProcessor.applyAgentsFilters([t[e]]);if(n.length>0&&this.moduleViewer&&"function"==typeof this.moduleViewer.showAgentEvent){const t=n[0];this.moduleViewer.showAgentEvent(t,e)}}showAgentInstanceDetails(e){const t=this.agentInference.getPMDelegations().get(e);if(!t){const t=this.agentInference.getUniqueAgentInstances().find(t=>t.id===e);return t?void this.showImpliedAgentDetails(t):void console.error("Agent instance not found:",e)}this.moduleViewer&&"function"==typeof this.moduleViewer.showAgentInstance?this.moduleViewer.showAgentInstance(t):console.log("Agent Instance Details:",{id:e,agentName:t.agentName,type:"PM Delegation",eventCount:t.agentEvents.length,startTime:t.timestamp,pmCall:t.pmCall})}showImpliedAgentDetails(e){this.moduleViewer&&"function"==typeof this.moduleViewer.showImpliedAgent?this.moduleViewer.showImpliedAgent(e):console.log("Implied Agent Details:",{id:e.id,agentName:e.agentName,type:"Implied PM Delegation",eventCount:e.eventCount,startTime:e.timestamp,note:"No explicit PM call found - inferred from agent activity"})}showToolDetailsByIndex(e){const t=this.fileToolTracker.getToolCalls(),n=Array.from(t.entries()),i=this.eventProcessor.applyToolCallFilters(n);if(e>=0&&e<i.length){const[t]=i[e];this.showToolCallDetails(t)}}showFileDetailsByIndex(e){const t=this.fileToolTracker.getFileOperations();let n=Array.from(t.entries());if(n=this.eventProcessor.applyFilesFilters(n),e>=0&&e<n.length){const[t]=n[e];this.showFileDetails(t)}}showToolCallDetails(e){const t=this.fileToolTracker.getToolCall(e);t&&this.moduleViewer&&this.moduleViewer.showToolCall(t,e)}showFileDetails(e){const t=this.fileToolTracker.getFileOperationsForFile(e);t&&this.moduleViewer&&this.moduleViewer.showFileOperations(t,e)}switchTab(e){this.uiStateManager.switchTab(e)}selectCard(e,t,n,i){this.uiStateManager.selectCard(e,t,n,i)}clearEvents(){this.exportManager.clearEvents()}exportEvents(){this.exportManager.exportEvents()}clearSelection(){this.uiStateManager.clearSelection(),this.eventViewer&&this.eventViewer.clearSelection(),this.moduleViewer&&this.moduleViewer.clear()}get currentWorkingDir(){return this.workingDirectoryManager.getCurrentWorkingDir()}set currentWorkingDir(e){this.workingDirectoryManager.setWorkingDirectory(e)}get currentTab(){return this.uiStateManager.getCurrentTab()}get selectedCard(){return this.uiStateManager.getSelectedCard()}get fileOperations(){return this.fileToolTracker.getFileOperations()}get toolCalls(){return this.fileToolTracker.getToolCalls()}get tabNavigation(){return this.uiStateManager?this.uiStateManager.tabNavigation:null}}function p(){const e=document.createElement("div");return e.id="file-viewer-modal",e.className="modal file-viewer-modal",e.innerHTML='\n <div class="modal-content file-viewer-content">\n <div class="file-viewer-header">\n <h2 class="file-viewer-title">\n <span class="file-viewer-icon">📄</span>\n <span class="file-viewer-title-text">File Viewer</span>\n </h2>\n <div class="file-viewer-meta">\n <span class="file-viewer-file-path"></span>\n <span class="file-viewer-file-size"></span>\n </div>\n <button class="file-viewer-close" onclick="hideFileViewerModal()">\n <span>&times;</span>\n </button>\n </div>\n <div class="file-viewer-body">\n <div class="file-viewer-loading">\n <div class="loading-spinner"></div>\n <span>Loading file content...</span>\n </div>\n <div class="file-viewer-error" style="display: none;">\n <div class="error-icon">⚠️</div>\n <div class="error-message"></div>\n <div class="error-suggestions"></div>\n </div>\n <div class="file-viewer-content-area" style="display: none;">\n <div class="file-viewer-toolbar">\n <div class="file-viewer-info">\n <span class="file-extension"></span>\n <span class="file-encoding"></span>\n </div>\n <div class="file-viewer-actions">\n <button class="file-content-copy" onclick="copyFileContent()">\n 📋 Copy\n </button>\n </div>\n </div>\n <div class="file-viewer-scroll-wrapper">\n <pre class="file-content-display"><code class="file-content-code"></code></pre>\n </div>\n </div>\n </div>\n </div>\n ',e.addEventListener("click",t=>{t.target===e&&hideFileViewerModal()}),document.addEventListener("keydown",t=>{"Escape"===t.key&&"flex"===e.style.display&&hideFileViewerModal()}),e}async function g(e,t,n){const i=e.querySelector(".file-viewer-file-path"),s=e.querySelector(".file-viewer-file-size");i.textContent=t,s.textContent="",e.querySelector(".file-viewer-loading").style.display="flex",e.querySelector(".file-viewer-error").style.display="none",e.querySelector(".file-viewer-content-area").style.display="none";try{const i=window.socket||window.dashboard?.socketClient?.socket;if(!i)throw new Error("No socket connection available");const s=new Promise((e,n)=>{const s=o=>{o.file_path===t&&(i.off("file_content_response",s),o.success?e(o):n(new Error(o.error||"Failed to read file")))};i.on("file_content_response",s),setTimeout(()=>{i.off("file_content_response",s),n(new Error("Request timeout"))},1e4)});i.emit("read_file",{file_path:t,working_dir:n});const o=await s;e.querySelector(".file-viewer-loading").style.display="none",function(e,t){const n=e.querySelector(".file-viewer-content-area"),i=e.querySelector(".file-extension"),s=e.querySelector(".file-encoding"),o=e.querySelector(".file-viewer-file-size"),a=e.querySelector(".file-content-code");i&&(i.textContent=`Type: ${t.extension||"unknown"}`);s&&(s.textContent=`Encoding: ${t.encoding||"unknown"}`);o&&(o.textContent=`Size: ${function(e){if(!e)return"0 B";const t=1024,n=["B","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,i)).toFixed(2))+" "+n[i]}(t.file_size)}`);if(a&&t.content){a.innerHTML=function(e,t){const n=e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");switch(t){case".js":case".jsx":case".ts":case".tsx":return function(e){return m(e.replace(/\b(function|const|let|var|if|else|for|while|return|import|export|class|extends)\b/g,'<span class="keyword">$1</span>').replace(/(\/\*[\s\S]*?\*\/|\/\/.*)/g,'<span class="comment">$1</span>').replace(/('[^']*'|"[^"]*"|`[^`]*`)/g,'<span class="string">$1</span>').replace(/\b(\d+)\b/g,'<span class="number">$1</span>'))}(n);case".py":return function(e){return m(e.replace(/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|with)\b/g,'<span class="keyword">$1</span>').replace(/(#.*)/g,'<span class="comment">$1</span>').replace(/('[^']*'|"[^"]*"|"""[\s\S]*?""")/g,'<span class="string">$1</span>').replace(/\b(\d+)\b/g,'<span class="number">$1</span>'))}(n);case".json":return function(e){return m(e.replace(/("[\w\s]*")\s*:/g,'<span class="property">$1</span>:').replace(/:\s*(".*?")/g,': <span class="string">$1</span>').replace(/:\s*(\d+)/g,': <span class="number">$1</span>').replace(/:\s*(true|false|null)/g,': <span class="keyword">$1</span>'))}(n);case".css":return function(e){return m(e.replace(/([.#]?[\w-]+)\s*\{/g,'<span class="selector">$1</span> {').replace(/([\w-]+)\s*:/g,'<span class="property">$1</span>:').replace(/:\s*([^;]+);/g,': <span class="value">$1</span>;').replace(/(\/\*[\s\S]*?\*\/)/g,'<span class="comment">$1</span>'))}(n);case".html":case".htm":return function(e){return m(e.replace(/(&lt;\/?[\w-]+)/g,'<span class="tag">$1</span>').replace(/([\w-]+)=(['"][^'"]*['"])/g,'<span class="attribute">$1</span>=<span class="string">$2</span>').replace(/(&lt;!--[\s\S]*?--&gt;)/g,'<span class="comment">$1</span>'))}(n);case".md":case".markdown":return function(e){return m(e.replace(/^(#{1,6})\s+(.*)$/gm,'<span class="header">$1</span> <span class="header-text">$2</span>').replace(/\*\*(.*?)\*\*/g,'<span class="bold">**$1**</span>').replace(/\*(.*?)\*/g,'<span class="italic">*$1*</span>').replace(/`([^`]+)`/g,'<span class="code">`$1`</span>').replace(/^\s*[-*+]\s+(.*)$/gm,'<span class="list-marker">•</span> $1'))}(n);default:return m(n)}}(t.content,t.extension);const n=e.querySelector(".file-viewer-scroll-wrapper");n&&setTimeout(()=>{const t=e.querySelector(".modal-content"),i=e.querySelector(".file-viewer-header"),s=e.querySelector(".file-viewer-toolbar"),o=(t?.offsetHeight||0)-(i?.offsetHeight||0)-(s?.offsetHeight||0)-40;n.style.maxHeight=`${o}px`,n.style.overflowY="auto"},50)}else console.warn("⚠️ Missing codeElement or file content");n&&(n.style.display="block")}(e,o)}catch(o){console.error("❌ Failed to fetch file content:",o),e.querySelector(".file-viewer-loading").style.display="none";let i=o.message||"Unknown error occurred",s=[];o.message.includes("No socket connection")?(i="Failed to connect to the monitoring server",s=["Check if the monitoring server is running","Verify the socket connection in the dashboard","Try refreshing the page and reconnecting"]):o.message.includes("timeout")?(i="Request timed out",s=["The file may be too large to load quickly","Check your network connection","Try again in a few moments"]):o.message.includes("File does not exist")?(i="File not found",s=["The file may have been moved or deleted","Check the file path spelling","Refresh the file list to see current files"]):o.message.includes("Access denied")&&(i="Access denied",s=["The file is outside the allowed directories","File access is restricted for security reasons"]),function(e,t){const n=e.querySelector(".file-viewer-error"),i=e.querySelector(".error-message"),s=e.querySelector(".error-suggestions");let o=t.error||"Unknown error occurred";i.innerHTML=`\n <div class="error-main">${o}</div>\n ${t.file_path?`<div class="error-file">File: ${t.file_path}</div>`:""}\n ${t.working_dir?`<div class="error-dir">Working directory: ${t.working_dir}</div>`:""}\n `,t.suggestions&&t.suggestions.length>0?s.innerHTML=`\n <h4>Suggestions:</h4>\n <ul>\n ${t.suggestions.map(e=>`<li>${e}</li>`).join("")}\n </ul>\n `:s.innerHTML="";console.log("📋 Displaying file viewer error:",{originalError:t.error,processedMessage:o,suggestions:t.suggestions}),n.style.display="block"}(e,{error:i,file_path:t,working_dir:n,suggestions:s})}}function m(e){return e.split("\n").map((e,t)=>`<span class="line-number">${String(t+1).padStart(3," ")}</span> ${e||" "}`).join("\n")}function f(e,t){const n=e.querySelector(".git-diff-error"),i=e.querySelector(".error-message"),s=e.querySelector(".error-suggestions");let o=t.error||"Unknown error occurred",a=!1;if(o.includes("not tracked by git")?(o="📝 This file is not tracked by git yet",a=!0):o.includes("No git history found")&&(o="📋 No git history available for this file"),i.innerHTML=`\n <div class="error-main">${o}</div>\n ${t.file_path?`<div class="error-file">File: ${t.file_path}</div>`:""}\n ${t.working_dir?`<div class="error-dir">Working directory: ${t.working_dir}</div>`:""}\n `,t.suggestions&&t.suggestions.length>0){const e=a?"How to track this file:":"Suggestions:";s.innerHTML=`\n <h4>${e}</h4>\n <ul>\n ${t.suggestions.map(e=>`<li>${e}</li>`).join("")}\n </ul>\n `}else s.innerHTML="";console.log("📋 Displaying git diff error:",{originalError:t.error,processedMessage:o,isUntracked:a,suggestions:t.suggestions}),n.style.display="block"}function v(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}window.clearEvents=function(){window.dashboard&&window.dashboard.clearEvents()},window.exportEvents=function(){window.dashboard&&window.dashboard.exportEvents()},window.clearSelection=function(){window.dashboard&&window.dashboard.clearSelection()},window.switchTab=function(e){window.dashboard&&window.dashboard.switchTab(e)},window.showFileViewerModal=function(e,t){!t&&window.dashboard&&window.dashboard.currentWorkingDir&&(t=window.dashboard.currentWorkingDir);let n=document.getElementById("file-viewer-modal");n||(n=p(),document.body.appendChild(n)),g(n,e,t),n.style.display="flex",document.body.style.overflow="hidden"},window.hideFileViewerModal=function(){const e=document.getElementById("file-viewer-modal");e&&(e.style.display="none",document.body.style.overflow="")},window.copyFileContent=function(){const e=document.getElementById("file-viewer-modal");if(!e)return;const t=e.querySelector(".file-content-code");if(!t)return;const n=t.textContent;if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(n).then(()=>{const t=e.querySelector(".file-content-copy"),n=t.textContent;t.textContent="✅ Copied!",setTimeout(()=>{t.textContent=n},2e3)}).catch(e=>{console.error("Failed to copy text:",e)});else{const t=document.createElement("textarea");t.value=n,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t);const i=e.querySelector(".file-content-copy"),s=i.textContent;i.textContent="✅ Copied!",setTimeout(()=>{i.textContent=s},2e3)}},window.showGitDiffModal=function(e,t,n){!n&&window.dashboard&&window.dashboard.currentWorkingDir&&(n=window.dashboard.currentWorkingDir);let i=document.getElementById("git-diff-modal");i||(i=function(){const e=document.createElement("div");return e.id="git-diff-modal",e.className="modal git-diff-modal",e.innerHTML='\n <div class="modal-content git-diff-content">\n <div class="git-diff-header">\n <h2 class="git-diff-title">\n <span class="git-diff-icon">📋</span>\n <span class="git-diff-title-text">Git Diff</span>\n </h2>\n <div class="git-diff-meta">\n <span class="git-diff-file-path"></span>\n <span class="git-diff-timestamp"></span>\n </div>\n <button class="git-diff-close" onclick="hideGitDiffModal()">\n <span>&times;</span>\n </button>\n </div>\n <div class="git-diff-body">\n <div class="git-diff-loading">\n <div class="loading-spinner"></div>\n <span>Loading git diff...</span>\n </div>\n <div class="git-diff-error" style="display: none;">\n <div class="error-icon">⚠️</div>\n <div class="error-message"></div>\n <div class="error-suggestions"></div>\n </div>\n <div class="git-diff-content-area" style="display: none;">\n <div class="git-diff-toolbar">\n <div class="git-diff-info">\n <span class="commit-hash"></span>\n <span class="diff-method"></span>\n </div>\n <div class="git-diff-actions">\n <button class="git-diff-copy" onclick="copyGitDiff()">\n 📋 Copy\n </button>\n </div>\n </div>\n <div class="git-diff-scroll-wrapper">\n <pre class="git-diff-display"><code class="git-diff-code"></code></pre>\n </div>\n </div>\n </div>\n </div>\n ',e.addEventListener("click",t=>{t.target===e&&hideGitDiffModal()}),document.addEventListener("keydown",t=>{"Escape"===t.key&&"flex"===e.style.display&&hideGitDiffModal()}),e}(),document.body.appendChild(i)),async function(e,t,n,i){const s=e.querySelector(".git-diff-file-path"),o=e.querySelector(".git-diff-timestamp");s.textContent=t,o.textContent=n?new Date(n).toLocaleString():"Latest",e.querySelector(".git-diff-loading").style.display="flex",e.querySelector(".git-diff-error").style.display="none",e.querySelector(".git-diff-content-area").style.display="none";try{let s=8765;if(window.dashboard&&window.dashboard.socketClient&&window.dashboard.socketClient.port)s=window.dashboard.socketClient.port;else{const e=document.getElementById("port-input");e&&e.value&&(s=e.value)}const o=new URLSearchParams({file:t});n&&o.append("timestamp",n),i&&o.append("working_dir",i);const r=`http://localhost:${s}/api/git-diff?${o}`;console.log("🌐 Making git diff request to:",r),console.log("📋 Git diff request parameters:",{filePath:t,timestamp:n,workingDir:i,urlParams:o.toString()});try{const e=await fetch(`http://localhost:${s}/health`,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json"},mode:"cors"});if(!e.ok)throw new Error(`Server health check failed: ${e.status} ${e.statusText}`)}catch(a){throw new Error(`Cannot reach server at localhost:${s}. Health check failed: ${a.message}`)}const l=await fetch(r,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json"},mode:"cors"});if(!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);const d=await l.json();e.querySelector(".git-diff-loading").style.display="none",d.success?function(e,t){const n=e.querySelector(".git-diff-content-area"),i=e.querySelector(".commit-hash"),s=e.querySelector(".diff-method"),o=e.querySelector(".git-diff-code");i&&(i.textContent=`Commit: ${t.commit_hash}`);s&&(s.textContent=`Method: ${t.method}`);if(o&&t.diff){o.innerHTML=t.diff.split("\n").map(e=>{const t=e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return e.startsWith("+++")||e.startsWith("---")?`<span class="diff-header">${t}</span>`:e.startsWith("@@")?`<span class="diff-meta">${t}</span>`:e.startsWith("+")?`<span class="diff-addition">${t}</span>`:e.startsWith("-")?`<span class="diff-deletion">${t}</span>`:e.startsWith("commit ")||e.startsWith("Author:")||e.startsWith("Date:")?`<span class="diff-header">${t}</span>`:`<span class="diff-context">${t}</span>`}).join("\n");const n=e.querySelector(".git-diff-scroll-wrapper");n&&setTimeout(()=>{const t=e.querySelector(".modal-content"),i=e.querySelector(".git-diff-header"),s=e.querySelector(".git-diff-toolbar"),o=(t?.offsetHeight||0)-(i?.offsetHeight||0)-(s?.offsetHeight||0)-40;n.style.maxHeight=`${o}px`,n.style.overflowY="auto"},50)}else console.warn("⚠️ Missing codeElement or diff data");n&&(n.style.display="block")}(e,d):f(e,d)}catch(r){console.error("❌ Failed to fetch git diff:",r),console.error("Error details:",{name:r.name,message:r.message,stack:r.stack,filePath:t,timestamp:n,workingDir:i}),e.querySelector(".git-diff-loading").style.display="none";let s=`Network error: ${r.message}`,o=[];r.message.includes("Failed to fetch")?(s="Failed to connect to the monitoring server",o=["Check if the monitoring server is running on port 8765","Verify the port configuration in the dashboard","Check browser console for CORS or network errors","Try refreshing the page and reconnecting"]):r.message.includes("health check failed")?(s=r.message,o=["The server may be starting up - try again in a few seconds","Check if another process is using port 8765","Restart the claude-mpm monitoring server"]):r.message.includes("HTTP")&&(s=`Server error: ${r.message}`,o=["The server encountered an internal error","Check the server logs for more details","Try with a different file or working directory"]),f(e,{error:s,file_path:t,working_dir:i,suggestions:o,debug_info:{error_type:r.name,original_message:r.message,port:window.dashboard?.socketClient?.port||document.getElementById("port-input")?.value||"8765",timestamp:(new Date).toISOString()}})}}(i,e,t,n),i.style.display="flex",document.body.style.overflow="hidden"},window.hideGitDiffModal=function(){const e=document.getElementById("git-diff-modal");e&&(e.style.display="none",document.body.style.overflow="")},window.copyGitDiff=function(){const e=document.getElementById("git-diff-modal");if(!e)return;const t=e.querySelector(".git-diff-code");if(!t)return;const n=t.textContent;if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(n).then(()=>{const t=e.querySelector(".git-diff-copy"),n=t.textContent;t.textContent="✅ Copied!",setTimeout(()=>{t.textContent=n},2e3)}).catch(e=>{console.error("Failed to copy text:",e)});else{const t=document.createElement("textarea");t.value=n,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t);const i=e.querySelector(".git-diff-copy"),s=i.textContent;i.textContent="✅ Copied!",setTimeout(()=>{i.textContent=s},2e3)}},window.showFileViewerModal=function(e){let t="";window.dashboard&&window.dashboard.currentWorkingDir&&(t=window.dashboard.currentWorkingDir);let n=document.getElementById("file-viewer-modal");n||(n=p(),document.body.appendChild(n)),g(n,e,t),n.style.display="flex",document.body.style.overflow="hidden"},window.hideFileViewerModal=function(){const e=document.getElementById("file-viewer-modal");e&&(e.style.display="none",document.body.style.overflow="")},window.copyFileContent=function(){const e=document.getElementById("file-viewer-modal");if(!e)return;const t=e.querySelector(".file-content-code");if(!t)return;const n=t.textContent;if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(n).then(()=>{const t=e.querySelector(".file-content-copy"),n=t.textContent;t.textContent="✅ Copied!",setTimeout(()=>{t.textContent=n},2e3)}).catch(e=>{console.error("Failed to copy text:",e)});else{const t=document.createElement("textarea");t.value=n,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t);const i=e.querySelector(".file-content-copy"),s=i.textContent;i.textContent="✅ Copied!",setTimeout(()=>{i.textContent=s},2e3)}},window.showSearchViewerModal=function(e,t){let n=document.getElementById("search-viewer-modal");n||(n=function(){const e=document.createElement("div");return e.id="search-viewer-modal",e.className="modal search-viewer-modal",e.innerHTML='\n <div class="modal-content search-viewer-content">\n <div class="search-viewer-header">\n <h2 class="search-viewer-title">\n <span class="search-viewer-icon">🔍</span>\n <span class="search-viewer-title-text">Search Results</span>\n </h2>\n <button class="search-viewer-close" onclick="hideSearchViewerModal()">\n <span>&times;</span>\n </button>\n </div>\n <div class="search-viewer-body">\n <div class="search-params-section">\n <h3>Search Parameters</h3>\n <pre class="search-params-display"></pre>\n </div>\n <div class="search-results-section">\n <h3>Search Results</h3>\n <div class="search-results-display"></div>\n </div>\n </div>\n </div>\n ',e.addEventListener("click",t=>{t.target===e&&hideSearchViewerModal()}),document.addEventListener("keydown",t=>{"Escape"===t.key&&"flex"===e.style.display&&hideSearchViewerModal()}),e}(),document.body.appendChild(n)),function(e,t,n){const i=e.querySelector(".search-params-display"),s=e.querySelector(".search-results-display");i&&t&&(i.textContent=JSON.stringify(t,null,2));if(s&&n){let e="";"string"==typeof n?e=`<pre class="search-results-text">${v(n)}</pre>`:Array.isArray(n)?(e='<ul class="search-results-list">',n.forEach(t=>{e+="object"==typeof t?`<li><pre>${JSON.stringify(t,null,2)}</pre></li>`:`<li>${v(String(t))}</li>`}),e+="</ul>"):e="object"==typeof n?`<pre class="search-results-json">${JSON.stringify(n,null,2)}</pre>`:`<div class="search-results-text">${v(String(n))}</div>`,s.innerHTML=e}}(n,e,t),n.style.display="flex",document.body.style.overflow="hidden"},window.hideSearchViewerModal=function(){const e=document.getElementById("search-viewer-modal");e&&(e.style.display="none",document.body.style.overflow="")},window.showAgentInstanceDetails=function(e){window.dashboard&&"function"==typeof window.dashboard.showAgentInstanceDetails?window.dashboard.showAgentInstanceDetails(e):console.error("Dashboard not available or method not found")},document.addEventListener("DOMContentLoaded",function(){try{window.dashboard=new u,window.dashboard&&"function"==typeof window.dashboard.postInit&&window.dashboard.postInit(),console.log("Dashboard loaded and initialized successfully"),document.dispatchEvent(new CustomEvent("dashboardReady",{detail:{dashboard:window.dashboard}}))}catch(e){console.error("Failed to initialize dashboard:",e),document.body.innerHTML=`\n <div style="padding: 20px; font-family: sans-serif;">\n <h1>Dashboard Initialization Error</h1>\n <p>The dashboard failed to load properly. Please refresh the page or check the console for details.</p>\n <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px;">${e.message}</pre>\n </div>\n `}});
1
+ import{S as e,U as t}from"./socket-client.js";import{E as n,a as i}from"./components/event-viewer.js";import{M as s}from"./components/module-viewer.js";import{S as o}from"./components/session-manager.js";import{A as a}from"./components/agent-inference.js";import{E as r}from"./components/export-manager.js";import{W as l}from"./components/working-directory.js";import{F as d}from"./components/file-tool-tracker.js";import"./chunks/unified-data-viewer.B7wmm2bD.js";class c{constructor(e,t){this.agentInference=e,this.eventViewer=t,this.state={hierarchyTree:null,nodeMap:new Map,expandedNodes:new Set,selectedNode:null},this.expandAll=!0,this.setupEventListeners(),console.log("Agent hierarchy component initialized")}setupEventListeners(){document.addEventListener("click",e=>{const t=e.target.closest("[data-toggle-node]");if(t&&window.dashboard&&window.dashboard.agentHierarchy){const e=t.dataset.toggleNode;window.dashboard.agentHierarchy.toggleNode(e)}})}buildHierarchy(){this.agentInference.processAgentInference();const e=this.agentInference.getPMDelegations(),t=this.eventViewer.events,n=this.agentInference.getEventAgentMap(),i={id:"pm_main",type:"pm",name:"PM (Main Session)",children:[],events:[],eventCount:0,status:"active",startTime:null,endTime:null,expanded:!0},s=new Map;this.state.nodeMap.clear(),this.state.nodeMap.set(i.id,i);const o=new Set;for(const[h,u]of e){const e={id:h,type:"subagent",name:u.agentName,delegationContext:this.extractDelegationContext(u.pmCall),children:[],events:u.agentEvents,eventCount:u.agentEvents.length,status:u.endIndex?"completed":"active",startTime:u.timestamp,endTime:u.endIndex?t[u.endIndex]?.timestamp:null,startIndex:u.startIndex,endIndex:u.endIndex,expanded:this.expandAll||this.state.expandedNodes.has(h)};if(i.children.push(e),this.state.nodeMap.set(h,e),o.add(u.agentName),i.eventCount++,(!i.startTime||new Date(u.timestamp)<new Date(i.startTime))&&(i.startTime=u.timestamp),u.endIndex&&t[u.endIndex]){const e=t[u.endIndex].timestamp;(!i.endTime||new Date(e)>new Date(i.endTime))&&(i.endTime=e)}}const a=this.agentInference.getOrphanGroups();let r=1;for(const[h,u]of a){const i={id:`pm_implied_${h}`,type:"pm",name:`PM (Implied #${r})`,children:[],events:[],eventCount:0,status:"inferred",startTime:null,endTime:null,expanded:!0,isImplied:!0,tooltip:"Inferred PM - Subagents started without explicit PM delegation"};s.set(h,i),this.state.nodeMap.set(i.id,i),r++;const o=new Map;for(const s of u){const i=[];t.forEach((t,o)=>{const a=n.get(o);if(a&&a.agentName===s.agentName){let n=!0;for(const[t,i]of e)if(i.agentEvents.some(e=>e.eventIndex===o)){n=!1;break}n&&i.push({eventIndex:o,event:t,inference:a})}}),i.length>0&&(o.has(s.agentName)||o.set(s.agentName,[]),o.get(s.agentName).push(...i))}for(const[e,t]of o){if(0===t.length)continue;const n=t[0].event,s=t[t.length-1].event,o={id:`implied_agent_${h}_${e}`,type:"subagent",name:e,delegationContext:"Orphan agent - no explicit PM delegation found",children:[],events:t,eventCount:t.length,status:"inferred",startTime:n.timestamp,endTime:s.timestamp,startIndex:t[0].eventIndex,endIndex:t[t.length-1].eventIndex,expanded:this.expandAll,isImplied:!0,tooltip:"This agent was spawned without an explicit PM Task delegation"};i.children.push(o),this.state.nodeMap.set(o.id,o),i.eventCount+=t.length,(!i.startTime||new Date(n.timestamp)<new Date(i.startTime))&&(i.startTime=n.timestamp),(!i.endTime||new Date(s.timestamp)>new Date(i.endTime))&&(i.endTime=s.timestamp)}}const l=[];if(t.forEach((t,i)=>{const o=n.get(i);if(o&&"subagent"===o.type){let n=!0;for(const[t,s]of e)if(s.agentEvents.some(e=>e.eventIndex===i)){n=!1;break}if(n)for(const[e,t]of s){for(const e of t.children)if(e.events.some(e=>e.eventIndex===i)){n=!1;break}if(!n)break}n&&l.push({eventIndex:i,event:t,inference:o})}}),l.length>0){const e={id:"pm_implied_generic",type:"pm",name:"PM (Implied - Uncategorized)",children:[],events:[],eventCount:0,status:"inferred",startTime:null,endTime:null,expanded:!0,isImplied:!0,tooltip:"Orphan agents without clear grouping"},t=new Map;for(const n of l){const e=n.inference.agentName;t.has(e)||t.set(e,[]),t.get(e).push(n)}for(const[n,i]of t){const t=i[0].event,s=i[i.length-1].event,o={id:`implied_generic_${n}`,type:"subagent",name:n,delegationContext:"Uncategorized orphan agent",children:[],events:i,eventCount:i.length,status:"inferred",startTime:t.timestamp,endTime:s.timestamp,startIndex:i[0].eventIndex,endIndex:i[i.length-1].eventIndex,expanded:this.expandAll,isImplied:!0};e.children.push(o),this.state.nodeMap.set(o.id,o),e.eventCount+=i.length,(!e.startTime||new Date(t.timestamp)<new Date(e.startTime))&&(e.startTime=t.timestamp),(!e.endTime||new Date(s.timestamp)>new Date(e.endTime))&&(e.endTime=s.timestamp)}e.children.length>0&&(s.set("generic",e),this.state.nodeMap.set(e.id,e))}let d=0;if(t.forEach((e,t)=>{const s=n.get(t);s&&"main_agent"===s.type&&(d++,i.events.push({eventIndex:t,event:e,inference:s}))}),i.eventCount+=d,i.children.length>0){const e=i.children.some(e=>"active"===e.status);i.status=e?"active":"completed"}const c={roots:[]};(i.eventCount>0||i.children.length>0)&&c.roots.push(i);for(const[h,u]of s)u.children.length>0&&c.roots.push(u);return this.state.hierarchyTree=c,console.log("Hierarchy built:",{mainPM:{children:i.children.length,events:i.eventCount,ownEvents:d},impliedPMGroups:s.size,totalImpliedAgents:Array.from(s.values()).reduce((e,t)=>e+t.children.length,0)}),c}extractDelegationContext(e){if(!e)return"Unknown delegation";const t=e.tool_parameters||e.data?.tool_parameters||{},n=t.task||t.request||t.description;if(n){const e=100;return n.length>e?n.substring(0,e)+"...":n}const i=e.tool_input||e.data?.tool_input;if(i&&"string"==typeof i){const e=100;return i.length>e?i.substring(0,e)+"...":i}return"Task delegation"}render(e={}){const t=this.state.hierarchyTree||this.buildHierarchy();if(!t.roots||0===t.roots.length)return'<div class="agent-hierarchy-empty">No agent activity detected</div>';return`<div class="agent-hierarchy">${this.applyFilters(t,e).roots.map(e=>this.renderNode(e,0)).join("")}</div>`}renderNode(e,t){const n=e.expanded||this.state.expandedNodes.has(e.id),i=e.children&&e.children.length>0,s=this.state.selectedNode===e.id,o=this.getNodeIcon(e),a=i?n?"▼":"▶":"&nbsp;&nbsp;",r=this.getStatusClass(e.status),l=e.isImplied?"agent-node-implied":"",d=e.tooltip?`title="${this.escapeHtml(e.tooltip)}"`:"";let c=`\n <div class="agent-node agent-node-level-${t} ${s?"agent-node-selected":""} ${l}" \n data-node-id="${e.id}" ${d}>\n <div class="agent-node-header ${r}" \n data-toggle-node="${e.id}" style="cursor: pointer">\n <span class="agent-node-expand">${a}</span>\n <span class="agent-node-icon">${o}</span>\n <span class="agent-node-name">${this.escapeHtml(e.name)}</span>\n <span class="agent-node-stats">\n <span class="agent-event-count">${e.eventCount} events</span>\n ${e.status?`<span class="agent-status">${e.status}</span>`:""}\n </span>\n </div>\n `;if(n&&(e.delegationContext||e.startTime)){if(c+='<div class="agent-node-details">',e.delegationContext&&"Unknown delegation"!==e.delegationContext&&(c+=`\n <div class="agent-delegation-context">\n <strong>Task:</strong> ${this.escapeHtml(e.delegationContext)}\n </div>\n `),e.startTime){const t=this.calculateDuration(e.startTime,e.endTime);c+=`\n <div class="agent-timing">\n <span class="agent-time-start">${this.formatTime(e.startTime)}</span>\n ${t?`<span class="agent-duration">(${t})</span>`:""}\n </div>\n `}c+="</div>"}return n&&i&&(c+='<div class="agent-node-children">',c+=e.children.map(e=>this.renderNode(e,t+1)).join(""),c+="</div>"),c+="</div>",c}getNodeIcon(e){if("pm"===e.type)return e.isImplied?"🔍":"👔";return{"Engineer Agent":"🔧","Research Agent":"🔍","QA Agent":"✅","Documentation Agent":"📝","Security Agent":"🔒","Ops Agent":"⚙️","Version Control Agent":"📦","Data Engineer Agent":"💾","Test Integration Agent":"🧪"}[e.name]||"🤖"}getStatusClass(e){switch(e){case"active":return"agent-status-active";case"completed":return"agent-status-completed";case"pending":return"agent-status-pending";case"inferred":return"agent-status-inferred";default:return"agent-status-unknown"}}toggleNode(e){const t=this.state.nodeMap.get(e);t&&(this.state.expandedNodes.has(e)?(this.state.expandedNodes.delete(e),t.expanded=!1):(this.state.expandedNodes.add(e),t.expanded=!0),window.dashboard&&window.dashboard.renderCurrentTab())}selectNode(e){this.state.selectedNode=e;const t=this.state.nodeMap.get(e);if(t){const e=new CustomEvent("agentNodeSelected",{detail:{node:t}});document.dispatchEvent(e)}}applyFilters(e,t){if(!t||0===Object.keys(t).length)return e;const n={roots:[]};for(const i of e.roots){const e=this.filterNode(i,t);e&&n.roots.push(e)}return n}filterNode(e,t){let n=!0;if(t.searchText){const i=t.searchText.toLowerCase();n=n&&(e.name.toLowerCase().includes(i)||e.delegationContext&&e.delegationContext.toLowerCase().includes(i))}t.agentType&&(n=n&&e.name.includes(t.agentType)),t.status&&(n=n&&e.status===t.status);let i=[];if(e.children)for(const s of e.children){const e=this.filterNode(s,t);e&&i.push(e)}return n||i.length>0?{...e,children:i}:null}formatTime(e){if(!e)return"";return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}calculateDuration(e,t){if(!e||!t)return"";const n=new Date(e).getTime(),i=new Date(t).getTime()-n;if(i<1e3)return`${i}ms`;if(i<6e4)return`${(i/1e3).toFixed(1)}s`;return`${Math.floor(i/6e4)}m ${Math.floor(i%6e4/1e3)}s`}escapeHtml(e){if(!e)return"";const t=document.createElement("div");return t.textContent=e,t.innerHTML}updateWithNewEvents(e){this.buildHierarchy()}clear(){this.state.hierarchyTree=null,this.state.nodeMap.clear(),this.state.expandedNodes.clear(),this.state.selectedNode=null}expandAllNodes(){for(const[e,t]of this.state.nodeMap)this.state.expandedNodes.add(e),t.expanded=!0;this.expandAll=!0}collapseAllNodes(){this.state.expandedNodes.clear();for(const[e,t]of this.state.nodeMap)t.expanded=!1;this.expandAll=!1}}class h{constructor(){this.element=null,this.buildInfo={monitor:{version:"1.0.0",build:1,formatted_build:"0001",full_version:"v1.0.0-0001"},mpm:{version:"unknown",build:"unknown",full_version:"v0.0.0"}},this.socketClient=null,this.init()}async init(){await this.loadDashboardVersion(),this.createElements(),this.setupEventListeners()}async loadDashboardVersion(){try{const e=await fetch("/version.json");if(e.ok){const t=await e.json();this.buildInfo.monitor={version:t.version||"1.0.0",build:t.build||1,formatted_build:t.formatted_build||"0001",full_version:t.full_version||"v1.0.0-0001"}}}catch(e){}}createElements(){this.element=document.createElement("div"),this.element.className="version-display",this.element.id="version-display";const e=document.createElement("span");e.className="version-item mpm-version",e.id="mpm-version",e.innerHTML='\n <span class="version-label">MPM</span>\n <span class="version-value">v0.0.0</span>\n ';const t=document.createElement("span");t.className="version-separator",t.textContent="|";const n=document.createElement("span");n.className="version-item monitor-version",n.id="monitor-version",n.innerHTML='\n <span class="version-label">Monitor</span>\n <span class="version-value">v1.0.0-0001</span>\n ',this.element.appendChild(e),this.element.appendChild(t),this.element.appendChild(n),this.element.title="Click for detailed version information"}setSocketClient(e){this.socketClient=e,this.socketClient&&this.socketClient.socket&&(this.socketClient.socket.on("welcome",e=>{const t=e.build_info||e.data&&e.data.build_info;t&&this.updateBuildInfo(t)}),this.socketClient.socket.on("status",e=>{const t=e.build_info||e.data&&e.data.build_info;t&&this.updateBuildInfo(t)}),this.socketClient.socket.on("build_info",e=>{this.updateBuildInfo(e)}))}updateBuildInfo(e){this.buildInfo=e,this.updateDisplay()}updateDisplay(){const e=this.element.querySelector(".mpm-version .version-value");if(e&&this.buildInfo.mpm){const t=this.buildInfo.mpm.full_version||`v${this.buildInfo.mpm.version}`;e.textContent=t,this.buildInfo.mpm.build&&"unknown"!==this.buildInfo.mpm.build&&(e.parentElement.title=`MPM Build: ${this.buildInfo.mpm.build}`)}const t=this.element.querySelector(".monitor-version .version-value");if(t&&this.buildInfo.monitor){const e=this.buildInfo.monitor.full_version||`v${this.buildInfo.monitor.version}-${this.buildInfo.monitor.formatted_build}`;if(t.textContent=e,this.buildInfo.monitor.last_updated){const e=new Date(this.buildInfo.monitor.last_updated).toLocaleString();t.parentElement.title=`Monitor Build: ${this.buildInfo.monitor.formatted_build}\nLast Updated: ${e}`}}}setupEventListeners(){this.element.addEventListener("click",()=>{this.showDetailedInfo()})}showDetailedInfo(){const e=[];if(this.buildInfo.mpm&&(e.push("=== MPM Framework ==="),e.push(`Version: ${this.buildInfo.mpm.version}`),this.buildInfo.mpm.build&&"unknown"!==this.buildInfo.mpm.build&&e.push(`Build: ${this.buildInfo.mpm.build}`),e.push(`Full: ${this.buildInfo.mpm.full_version}`)),e.push(""),this.buildInfo.monitor&&(e.push("=== Monitor UI ==="),e.push(`Version: ${this.buildInfo.monitor.version}`),e.push(`Build: ${this.buildInfo.monitor.formatted_build} (${this.buildInfo.monitor.build})`),e.push(`Full: ${this.buildInfo.monitor.full_version}`),this.buildInfo.monitor.last_updated)){const t=new Date(this.buildInfo.monitor.last_updated).toLocaleString();e.push(`Updated: ${t}`)}const t=document.createElement("div");t.className="version-modal",t.innerHTML=`\n <div class="version-modal-content">\n <h3>Version Information</h3>\n <pre>${e.join("\n")}</pre>\n <button onclick="this.parentElement.parentElement.remove()">Close</button>\n </div>\n `,document.body.appendChild(t),setTimeout(()=>{t.remove()},1e4)}mount(e){const t="string"==typeof e?document.querySelector(e):e;this.element&&t&&this.element.parentNode!==t&&t.appendChild(this.element)}getElement(){return this.element}destroy(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.socketClient&&this.socketClient.socket&&(this.socketClient.socket.off("welcome"),this.socketClient.socket.off("status"),this.socketClient.socket.off("build_info")),this.element=null,this.socketClient=null}}class u{constructor(){this.eventViewer=null,this.moduleViewer=null,this.sessionManager=null,this.socketManager=null,this.agentInference=null,this.agentHierarchy=null,this.uiStateManager=null,this.eventProcessor=null,this.exportManager=null,this.workingDirectoryManager=null,this.fileToolTracker=null,this.buildTracker=null,this.init()}init(){console.log("Initializing refactored Claude MPM Dashboard...");try{this.initializeSocketManager(),this.initializeCoreComponents(),this.initializeBuildTracker(),this.initializeAgentInference(),this.initializeAgentHierarchy(),this.initializeUIStateManager(),this.initializeWorkingDirectoryManager(),this.initializeFileToolTracker(),this.initializeEventProcessor(),this.initializeExportManager(),this.setupModuleInteractions(),this.initializeFromURL(),console.log("Claude MPM Dashboard initialized successfully")}catch(e){throw console.error("Error during dashboard initialization:",e),e}}validateInitialization(){const e=[{name:"socketManager",component:this.socketManager},{name:"eventViewer",component:this.eventViewer},{name:"agentHierarchy",component:this.agentHierarchy}].filter(e=>!e.component);e.length>0?console.warn("Missing critical components:",e.map(e=>e.name)):console.log("All critical components initialized")}postInit(){try{this.agentHierarchy&&(window.dashboard.agentHierarchy=this.agentHierarchy,console.log("Agent hierarchy global reference set")),this.validateInitialization()}catch(e){console.error("Error in dashboard postInit:",e)}}initializeSocketManager(){this.socketManager=new e,this.socketManager.setupConnectionControls(),this.socketClient=this.socketManager.getSocketClient(),window.socketClient=this.socketClient}initializeCoreComponents(){this.eventViewer=new n("events-list",this.socketClient),this.moduleViewer=new s,this.sessionManager=new o(this.socketClient),window.eventViewer=this.eventViewer,window.moduleViewer=this.moduleViewer,window.sessionManager=this.sessionManager}initializeBuildTracker(){this.buildTracker=new h,this.buildTracker.setSocketClient(this.socketClient);const e=()=>{const t=document.querySelector(".header-title");t?(this.buildTracker.mount(t),console.log("BuildTracker mounted successfully")):(console.warn("Header-title element not found for build tracker, will retry"),setTimeout(e,100))};e(),window.buildTracker=this.buildTracker}initializeAgentInference(){this.agentInference=new a(this.eventViewer),this.agentInference.initialize()}initializeAgentHierarchy(){try{this.agentHierarchy=new c(this.agentInference,this.eventViewer),console.log("Agent hierarchy component created")}catch(e){console.error("Failed to initialize agent hierarchy:",e),this.agentHierarchy={render:()=>'<div class="error">Agent hierarchy unavailable</div>',expandAllNodes:()=>{},collapseAllNodes:()=>{},updateWithNewEvents:()=>{}}}}initializeUIStateManager(){this.uiStateManager=new t,this.setupTabFilters()}initializeWorkingDirectoryManager(){this.workingDirectoryManager=new l(this.socketManager)}initializeFileToolTracker(){this.fileToolTracker=new d(this.agentInference,this.workingDirectoryManager)}initializeEventProcessor(){this.eventProcessor=new i(this.eventViewer,this.agentInference)}initializeExportManager(){this.exportManager=new r(this.eventViewer)}setupModuleInteractions(){this.socketManager.onEventUpdate(e=>{this.fileToolTracker.updateFileOperations(e),this.fileToolTracker.updateToolCalls(e),this.agentInference.processAgentInference(),this.agentHierarchy.updateWithNewEvents(e),"events"===this.uiStateManager.getCurrentTab()&&this.exportManager.scrollListToBottom("events-list"),this.renderCurrentTab()}),this.socketManager.onConnectionStatusChange((e,t)=>{"connected"===t&&this.workingDirectoryManager.updateGitBranch(this.workingDirectoryManager.getCurrentWorkingDir())}),document.addEventListener("tabChanged",e=>{this.renderCurrentTab(),this.uiStateManager.updateTabNavigationItems()}),document.addEventListener("eventsClearing",()=>{this.fileToolTracker.clear(),this.agentInference.initialize()}),document.addEventListener("showCardDetails",e=>{this.showCardDetails(e.detail.tabName,e.detail.index)}),document.addEventListener("sessionFilterChanged",e=>{console.log("Session filter changed, re-rendering current tab:",this.uiStateManager.getCurrentTab()),this.renderCurrentTab()})}setupTabFilters(){const e=document.getElementById("agents-search-input"),t=document.getElementById("agents-type-filter");e&&e.addEventListener("input",()=>{"agents"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()}),t&&t.addEventListener("change",()=>{"agents"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()});const n=document.getElementById("tools-search-input"),i=document.getElementById("tools-type-filter");n&&n.addEventListener("input",()=>{"tools"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()}),i&&i.addEventListener("change",()=>{"tools"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()});const s=document.getElementById("files-search-input"),o=document.getElementById("files-type-filter");s&&s.addEventListener("input",()=>{"files"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()}),o&&o.addEventListener("change",()=>{"files"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()})}initializeFromURL(){const e=new URLSearchParams(window.location.search);this.socketManager.initializeFromURL(e)}renderCurrentTab(){const e=this.uiStateManager.getCurrentTab();switch(e){case"events":break;case"activity":if(window.ActivityTree&&"function"==typeof window.ActivityTree)window.activityTreeInstance||(console.log("Creating new ActivityTree instance..."),window.activityTreeInstance=new window.ActivityTree),window.activityTreeInstance&&(window.activityTreeInstance.initialized||(console.log("Initializing ActivityTree..."),window.activityTreeInstance.initialize()),"function"==typeof window.activityTreeInstance.renderWhenVisible&&(console.log("Dashboard triggering activity tree render..."),window.activityTreeInstance.renderWhenVisible()),"function"==typeof window.activityTreeInstance.forceShow&&(console.log("Dashboard forcing activity tree to show..."),window.activityTreeInstance.forceShow()));else if(window.activityTree&&"function"==typeof window.activityTree){const e=window.activityTree();e&&("function"==typeof e.renderWhenVisible&&(console.log("Dashboard triggering activity tree render (legacy)..."),e.renderWhenVisible()),"function"==typeof e.forceShow&&(console.log("Dashboard forcing activity tree to show (legacy)..."),e.forceShow()))}else console.warn("Activity tree component not available, retrying in 100ms..."),setTimeout(()=>{"activity"===this.currentTab&&this.renderCurrentTab()},100);break;case"agents":this.renderAgents();break;case"tools":this.renderTools();break;case"files":this.renderFiles()}this.uiStateManager.getSelectedCard().tab===e&&this.uiStateManager.updateCardSelectionUI(),this.uiStateManager.updateUnifiedSelectionUI()}renderAgents(){const e=document.getElementById("agents-list");if(!e)return;const t=document.getElementById("agents-search-input")?.value||"",n=document.getElementById("agents-type-filter")?.value||"",i=this.renderAgentsFlat(t,n);e.innerHTML=i,this.removeHierarchyControls();const s=this.agentInference.getUniqueAgentInstances();this.updateAgentsFilterDropdowns(s)}removeHierarchyControls(){const e=document.getElementById("hierarchy-controls");e&&e.remove()}renderAgentsFlat(e,t){const n=this.eventViewer.events;if(!n||0===n.length)return'<div class="no-events">No agent events found...</div>';this.agentInference.processAgentInference();const i=this.agentInference.getEventAgentMap(),s=[];if(n.forEach((n,o)=>{const a=i.get(o);if(a&&("subagent"===a.type||"main_agent"===a.type)){let i=!0;if(e){const t=e.toLowerCase();i=i&&(a.agentName.toLowerCase().includes(t)||n.tool_name&&n.tool_name.toLowerCase().includes(t)||n.data&&JSON.stringify(n.data).toLowerCase().includes(t))}t&&(i=i&&a.agentName.includes(t)),i&&s.push({event:n,inference:a,index:o,timestamp:new Date(n.timestamp)})}}),0===s.length)return'<div class="no-events">No agent events match the current filters...</div>';return`<div class="agent-events-flat">${s.map((e,t)=>{const{event:n,inference:i,index:s,timestamp:o}=e;let a="Activity",r="📋",l="";if("SubagentStart"===n.event_type)a="Started",r="🟢",l="Agent session began";else if("SubagentStop"===n.event_type)a="Stopped",r="🔴",l="Agent session ended";else if(n.tool_name&&(a=`Tool: ${n.tool_name}`,r=this.getToolIcon(n.tool_name),n.data&&n.data.tool_parameters)){const e=n.data.tool_parameters;e.file_path?l=e.file_path:e.command?l=e.command.substring(0,50)+(e.command.length>50?"...":""):e.pattern?l=`pattern="${e.pattern}"`:e.query&&(l=`query="${e.query}"`)}let d="completed";return"SubagentStart"===n.event_type?d="active":n.data&&n.data.error&&(d="error"),`\n <div class="agent-event-item" data-index="${t}" onclick="window.dashboard.showCardDetails('agents', ${s})">\n <div class="agent-event-header">\n <div class="agent-event-time">${this.formatTimestamp(o)}</div>\n <div class="agent-event-agent">\n ${this.getAgentIcon(i.agentName)} ${i.agentName}\n </div>\n <div class="agent-event-action">\n ${r} ${a}\n </div>\n <div class="agent-event-status status-${d}">\n ${this.getStatusIcon(d)}\n </div>\n </div>\n ${l?`<div class="agent-event-details">${this.escapeHtml(l)}</div>`:""}\n </div>\n `}).join("")}</div>`}getAgentIcon(e){return{PM:"🎯","Engineer Agent":"🔧","Research Agent":"🔍","QA Agent":"✅","Documentation Agent":"📝","Security Agent":"🔒","Ops Agent":"⚙️","Version Control Agent":"📦","Data Engineer Agent":"💾","Test Integration Agent":"🧪"}[e]||"🤖"}getToolIcon(e){return{Read:"📖",Write:"✏️",Edit:"📝",Bash:"💻",Grep:"🔍",Glob:"📂",LS:"📁",Task:"📋"}[e]||"🔧"}getStatusIcon(e){return{active:"🟢",completed:"✅",error:"❌",pending:"🟡"}[e]||"❓"}formatTimestamp(e){return e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}escapeHtml(e){if(!e)return"";const t=document.createElement("div");return t.textContent=e,t.innerHTML}renderTools(){const e=document.getElementById("tools-list");if(!e)return;const t=this.fileToolTracker.getToolCalls(),n=Array.from(t.entries()),i=this.eventProcessor.getUniqueToolInstances(n),s=this.eventProcessor.generateToolHTML(i);e.innerHTML=s,this.exportManager.scrollListToBottom("tools-list"),this.updateToolsFilterDropdowns(i)}renderFiles(){const e=document.getElementById("files-list");if(!e)return;const t=this.fileToolTracker.getFileOperations(),n=Array.from(t.entries()),i=this.eventProcessor.getUniqueFileInstances(n),s=this.eventProcessor.generateFileHTML(i);e.innerHTML=s,this.exportManager.scrollListToBottom("files-list"),this.updateFilesFilterDropdowns(n)}updateAgentsFilterDropdowns(e){const t=new Set;e.forEach(e=>{e.agentName&&"Unknown"!==e.agentName&&t.add(e.agentName)});const n=Array.from(t).filter(e=>e&&""!==e.trim());this.populateFilterDropdown("agents-type-filter",n,"All Agent Types"),n.length>0?console.log("Agent types found for filter:",n):console.log("No agent types found for filter. Instances:",e.length)}updateToolsFilterDropdowns(e){const t=[...new Set(e.map(([e,t])=>t.tool_name))].filter(e=>e);this.populateFilterDropdown("tools-type-filter",t,"All Tools")}updateFilesFilterDropdowns(e){const t=[...new Set(e.flatMap(([e,t])=>t.operations.map(e=>e.operation)))].filter(e=>e);this.populateFilterDropdown("files-type-filter",t,"All Operations")}populateFilterDropdown(e,t,n="All"){const i=document.getElementById(e);if(!i)return;const s=i.value,o=t.sort((e,t)=>e.localeCompare(t));i.innerHTML=`<option value="">${n}</option>`,o.forEach(e=>{const t=document.createElement("option");t.value=e,t.textContent=e,i.appendChild(t)}),s&&o.includes(s)&&(i.value=s)}showCardDetails(e,t){switch(e){case"events":this.eventViewer&&this.eventViewer.showEventDetails(t);break;case"agents":this.showAgentDetailsByIndex(t);break;case"tools":this.showToolDetailsByIndex(t);break;case"files":this.showFileDetailsByIndex(t)}}showAgentDetailsByIndex(e){const t=this.eventProcessor.getFilteredEventsForTab("agents");if(!t||!Array.isArray(t)||e<0||e>=t.length)return void console.warn("Dashboard: Invalid agent index or events array");const n=this.eventProcessor.applyAgentsFilters([t[e]]);if(n.length>0&&this.moduleViewer&&"function"==typeof this.moduleViewer.showAgentEvent){const t=n[0];this.moduleViewer.showAgentEvent(t,e)}}showAgentInstanceDetails(e){const t=this.agentInference.getPMDelegations().get(e);if(!t){const t=this.agentInference.getUniqueAgentInstances().find(t=>t.id===e);return t?void this.showImpliedAgentDetails(t):void console.error("Agent instance not found:",e)}this.moduleViewer&&"function"==typeof this.moduleViewer.showAgentInstance?this.moduleViewer.showAgentInstance(t):console.log("Agent Instance Details:",{id:e,agentName:t.agentName,type:"PM Delegation",eventCount:t.agentEvents.length,startTime:t.timestamp,pmCall:t.pmCall})}showImpliedAgentDetails(e){this.moduleViewer&&"function"==typeof this.moduleViewer.showImpliedAgent?this.moduleViewer.showImpliedAgent(e):console.log("Implied Agent Details:",{id:e.id,agentName:e.agentName,type:"Implied PM Delegation",eventCount:e.eventCount,startTime:e.timestamp,note:"No explicit PM call found - inferred from agent activity"})}showToolDetailsByIndex(e){const t=this.fileToolTracker.getToolCalls(),n=Array.from(t.entries()),i=this.eventProcessor.applyToolCallFilters(n);if(e>=0&&e<i.length){const[t]=i[e];this.showToolCallDetails(t)}}showFileDetailsByIndex(e){const t=this.fileToolTracker.getFileOperations();let n=Array.from(t.entries());if(n=this.eventProcessor.applyFilesFilters(n),e>=0&&e<n.length){const[t]=n[e];this.showFileDetails(t)}}showToolCallDetails(e){const t=this.fileToolTracker.getToolCall(e);t&&this.moduleViewer&&this.moduleViewer.showToolCall(t,e)}showFileDetails(e){const t=this.fileToolTracker.getFileOperationsForFile(e);t&&this.moduleViewer&&this.moduleViewer.showFileOperations(t,e)}switchTab(e){this.uiStateManager.switchTab(e)}selectCard(e,t,n,i){this.uiStateManager.selectCard(e,t,n,i)}clearEvents(){this.exportManager.clearEvents()}exportEvents(){this.exportManager.exportEvents()}clearSelection(){this.uiStateManager.clearSelection(),this.eventViewer&&this.eventViewer.clearSelection(),this.moduleViewer&&this.moduleViewer.clear()}get currentWorkingDir(){return this.workingDirectoryManager.getCurrentWorkingDir()}set currentWorkingDir(e){this.workingDirectoryManager.setWorkingDirectory(e)}get currentTab(){return this.uiStateManager.getCurrentTab()}get selectedCard(){return this.uiStateManager.getSelectedCard()}get fileOperations(){return this.fileToolTracker.getFileOperations()}get toolCalls(){return this.fileToolTracker.getToolCalls()}get tabNavigation(){return this.uiStateManager?this.uiStateManager.tabNavigation:null}}function p(){const e=document.createElement("div");return e.id="file-viewer-modal",e.className="modal file-viewer-modal",e.innerHTML='\n <div class="modal-content file-viewer-content">\n <div class="file-viewer-header">\n <h2 class="file-viewer-title">\n <span class="file-viewer-icon">📄</span>\n <span class="file-viewer-title-text">File Viewer</span>\n </h2>\n <div class="file-viewer-meta">\n <span class="file-viewer-file-path"></span>\n <span class="file-viewer-file-size"></span>\n </div>\n <button class="file-viewer-close" onclick="hideFileViewerModal()">\n <span>&times;</span>\n </button>\n </div>\n <div class="file-viewer-body">\n <div class="file-viewer-loading">\n <div class="loading-spinner"></div>\n <span>Loading file content...</span>\n </div>\n <div class="file-viewer-error" style="display: none;">\n <div class="error-icon">⚠️</div>\n <div class="error-message"></div>\n <div class="error-suggestions"></div>\n </div>\n <div class="file-viewer-content-area" style="display: none;">\n <div class="file-viewer-toolbar">\n <div class="file-viewer-info">\n <span class="file-extension"></span>\n <span class="file-encoding"></span>\n </div>\n <div class="file-viewer-actions">\n <button class="file-content-copy" onclick="copyFileContent()">\n 📋 Copy\n </button>\n </div>\n </div>\n <div class="file-viewer-scroll-wrapper">\n <pre class="file-content-display"><code class="file-content-code"></code></pre>\n </div>\n </div>\n </div>\n </div>\n ',e.addEventListener("click",t=>{t.target===e&&hideFileViewerModal()}),document.addEventListener("keydown",t=>{"Escape"===t.key&&"flex"===e.style.display&&hideFileViewerModal()}),e}async function g(e,t,n){const i=e.querySelector(".file-viewer-file-path"),s=e.querySelector(".file-viewer-file-size");i.textContent=t,s.textContent="",e.querySelector(".file-viewer-loading").style.display="flex",e.querySelector(".file-viewer-error").style.display="none",e.querySelector(".file-viewer-content-area").style.display="none";try{const i=window.socket||window.dashboard?.socketClient?.socket;if(!i)throw new Error("No socket connection available");const s=new Promise((e,n)=>{const s=o=>{o.file_path===t&&(i.off("file_content_response",s),o.success?e(o):n(new Error(o.error||"Failed to read file")))};i.on("file_content_response",s),setTimeout(()=>{i.off("file_content_response",s),n(new Error("Request timeout"))},1e4)});i.emit("read_file",{file_path:t,working_dir:n});const o=await s;e.querySelector(".file-viewer-loading").style.display="none",function(e,t){const n=e.querySelector(".file-viewer-content-area"),i=e.querySelector(".file-extension"),s=e.querySelector(".file-encoding"),o=e.querySelector(".file-viewer-file-size"),a=e.querySelector(".file-content-code");i&&(i.textContent=`Type: ${t.extension||"unknown"}`);s&&(s.textContent=`Encoding: ${t.encoding||"unknown"}`);o&&(o.textContent=`Size: ${function(e){if(!e)return"0 B";const t=1024,n=["B","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,i)).toFixed(2))+" "+n[i]}(t.file_size)}`);if(a&&t.content){a.innerHTML=function(e,t){const n=e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");switch(t){case".js":case".jsx":case".ts":case".tsx":return function(e){return m(e.replace(/\b(function|const|let|var|if|else|for|while|return|import|export|class|extends)\b/g,'<span class="keyword">$1</span>').replace(/(\/\*[\s\S]*?\*\/|\/\/.*)/g,'<span class="comment">$1</span>').replace(/('[^']*'|"[^"]*"|`[^`]*`)/g,'<span class="string">$1</span>').replace(/\b(\d+)\b/g,'<span class="number">$1</span>'))}(n);case".py":return function(e){return m(e.replace(/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|with)\b/g,'<span class="keyword">$1</span>').replace(/(#.*)/g,'<span class="comment">$1</span>').replace(/('[^']*'|"[^"]*"|"""[\s\S]*?""")/g,'<span class="string">$1</span>').replace(/\b(\d+)\b/g,'<span class="number">$1</span>'))}(n);case".json":return function(e){return m(e.replace(/("[\w\s]*")\s*:/g,'<span class="property">$1</span>:').replace(/:\s*(".*?")/g,': <span class="string">$1</span>').replace(/:\s*(\d+)/g,': <span class="number">$1</span>').replace(/:\s*(true|false|null)/g,': <span class="keyword">$1</span>'))}(n);case".css":return function(e){return m(e.replace(/([.#]?[\w-]+)\s*\{/g,'<span class="selector">$1</span> {').replace(/([\w-]+)\s*:/g,'<span class="property">$1</span>:').replace(/:\s*([^;]+);/g,': <span class="value">$1</span>;').replace(/(\/\*[\s\S]*?\*\/)/g,'<span class="comment">$1</span>'))}(n);case".html":case".htm":return function(e){return m(e.replace(/(&lt;\/?[\w-]+)/g,'<span class="tag">$1</span>').replace(/([\w-]+)=(['"][^'"]*['"])/g,'<span class="attribute">$1</span>=<span class="string">$2</span>').replace(/(&lt;!--[\s\S]*?--&gt;)/g,'<span class="comment">$1</span>'))}(n);case".md":case".markdown":return function(e){return m(e.replace(/^(#{1,6})\s+(.*)$/gm,'<span class="header">$1</span> <span class="header-text">$2</span>').replace(/\*\*(.*?)\*\*/g,'<span class="bold">**$1**</span>').replace(/\*(.*?)\*/g,'<span class="italic">*$1*</span>').replace(/`([^`]+)`/g,'<span class="code">`$1`</span>').replace(/^\s*[-*+]\s+(.*)$/gm,'<span class="list-marker">•</span> $1'))}(n);default:return m(n)}}(t.content,t.extension);const n=e.querySelector(".file-viewer-scroll-wrapper");n&&setTimeout(()=>{const t=e.querySelector(".modal-content"),i=e.querySelector(".file-viewer-header"),s=e.querySelector(".file-viewer-toolbar"),o=(t?.offsetHeight||0)-(i?.offsetHeight||0)-(s?.offsetHeight||0)-40;n.style.maxHeight=`${o}px`,n.style.overflowY="auto"},50)}else console.warn("⚠️ Missing codeElement or file content");n&&(n.style.display="block")}(e,o)}catch(o){console.error("❌ Failed to fetch file content:",o),e.querySelector(".file-viewer-loading").style.display="none";let i=o.message||"Unknown error occurred",s=[];o.message.includes("No socket connection")?(i="Failed to connect to the monitoring server",s=["Check if the monitoring server is running","Verify the socket connection in the dashboard","Try refreshing the page and reconnecting"]):o.message.includes("timeout")?(i="Request timed out",s=["The file may be too large to load quickly","Check your network connection","Try again in a few moments"]):o.message.includes("File does not exist")?(i="File not found",s=["The file may have been moved or deleted","Check the file path spelling","Refresh the file list to see current files"]):o.message.includes("Access denied")&&(i="Access denied",s=["The file is outside the allowed directories","File access is restricted for security reasons"]),function(e,t){const n=e.querySelector(".file-viewer-error"),i=e.querySelector(".error-message"),s=e.querySelector(".error-suggestions");let o=t.error||"Unknown error occurred";i.innerHTML=`\n <div class="error-main">${o}</div>\n ${t.file_path?`<div class="error-file">File: ${t.file_path}</div>`:""}\n ${t.working_dir?`<div class="error-dir">Working directory: ${t.working_dir}</div>`:""}\n `,t.suggestions&&t.suggestions.length>0?s.innerHTML=`\n <h4>Suggestions:</h4>\n <ul>\n ${t.suggestions.map(e=>`<li>${e}</li>`).join("")}\n </ul>\n `:s.innerHTML="";console.log("📋 Displaying file viewer error:",{originalError:t.error,processedMessage:o,suggestions:t.suggestions}),n.style.display="block"}(e,{error:i,file_path:t,working_dir:n,suggestions:s})}}function m(e){return e.split("\n").map((e,t)=>`<span class="line-number">${String(t+1).padStart(3," ")}</span> ${e||" "}`).join("\n")}function f(e,t){const n=e.querySelector(".git-diff-error"),i=e.querySelector(".error-message"),s=e.querySelector(".error-suggestions");let o=t.error||"Unknown error occurred",a=!1;if(o.includes("not tracked by git")?(o="📝 This file is not tracked by git yet",a=!0):o.includes("No git history found")&&(o="📋 No git history available for this file"),i.innerHTML=`\n <div class="error-main">${o}</div>\n ${t.file_path?`<div class="error-file">File: ${t.file_path}</div>`:""}\n ${t.working_dir?`<div class="error-dir">Working directory: ${t.working_dir}</div>`:""}\n `,t.suggestions&&t.suggestions.length>0){const e=a?"How to track this file:":"Suggestions:";s.innerHTML=`\n <h4>${e}</h4>\n <ul>\n ${t.suggestions.map(e=>`<li>${e}</li>`).join("")}\n </ul>\n `}else s.innerHTML="";console.log("📋 Displaying git diff error:",{originalError:t.error,processedMessage:o,isUntracked:a,suggestions:t.suggestions}),n.style.display="block"}function v(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}window.clearEvents=function(){window.dashboard&&window.dashboard.clearEvents()},window.exportEvents=function(){window.dashboard&&window.dashboard.exportEvents()},window.clearSelection=function(){window.dashboard&&window.dashboard.clearSelection()},window.switchTab=function(e){window.dashboard&&window.dashboard.switchTab(e)},window.showFileViewerModal=function(e,t){!t&&window.dashboard&&window.dashboard.currentWorkingDir&&(t=window.dashboard.currentWorkingDir);let n=document.getElementById("file-viewer-modal");n||(n=p(),document.body.appendChild(n)),g(n,e,t),n.style.display="flex",document.body.style.overflow="hidden"},window.hideFileViewerModal=function(){const e=document.getElementById("file-viewer-modal");e&&(e.style.display="none",document.body.style.overflow="")},window.copyFileContent=function(){const e=document.getElementById("file-viewer-modal");if(!e)return;const t=e.querySelector(".file-content-code");if(!t)return;const n=t.textContent;if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(n).then(()=>{const t=e.querySelector(".file-content-copy"),n=t.textContent;t.textContent="✅ Copied!",setTimeout(()=>{t.textContent=n},2e3)}).catch(e=>{console.error("Failed to copy text:",e)});else{const t=document.createElement("textarea");t.value=n,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t);const i=e.querySelector(".file-content-copy"),s=i.textContent;i.textContent="✅ Copied!",setTimeout(()=>{i.textContent=s},2e3)}},window.showGitDiffModal=function(e,t,n){!n&&window.dashboard&&window.dashboard.currentWorkingDir&&(n=window.dashboard.currentWorkingDir);let i=document.getElementById("git-diff-modal");i||(i=function(){const e=document.createElement("div");return e.id="git-diff-modal",e.className="modal git-diff-modal",e.innerHTML='\n <div class="modal-content git-diff-content">\n <div class="git-diff-header">\n <h2 class="git-diff-title">\n <span class="git-diff-icon">📋</span>\n <span class="git-diff-title-text">Git Diff</span>\n </h2>\n <div class="git-diff-meta">\n <span class="git-diff-file-path"></span>\n <span class="git-diff-timestamp"></span>\n </div>\n <button class="git-diff-close" onclick="hideGitDiffModal()">\n <span>&times;</span>\n </button>\n </div>\n <div class="git-diff-body">\n <div class="git-diff-loading">\n <div class="loading-spinner"></div>\n <span>Loading git diff...</span>\n </div>\n <div class="git-diff-error" style="display: none;">\n <div class="error-icon">⚠️</div>\n <div class="error-message"></div>\n <div class="error-suggestions"></div>\n </div>\n <div class="git-diff-content-area" style="display: none;">\n <div class="git-diff-toolbar">\n <div class="git-diff-info">\n <span class="commit-hash"></span>\n <span class="diff-method"></span>\n </div>\n <div class="git-diff-actions">\n <button class="git-diff-copy" onclick="copyGitDiff()">\n 📋 Copy\n </button>\n </div>\n </div>\n <div class="git-diff-scroll-wrapper">\n <pre class="git-diff-display"><code class="git-diff-code"></code></pre>\n </div>\n </div>\n </div>\n </div>\n ',e.addEventListener("click",t=>{t.target===e&&hideGitDiffModal()}),document.addEventListener("keydown",t=>{"Escape"===t.key&&"flex"===e.style.display&&hideGitDiffModal()}),e}(),document.body.appendChild(i)),async function(e,t,n,i){const s=e.querySelector(".git-diff-file-path"),o=e.querySelector(".git-diff-timestamp");s.textContent=t,o.textContent=n?new Date(n).toLocaleString():"Latest",e.querySelector(".git-diff-loading").style.display="flex",e.querySelector(".git-diff-error").style.display="none",e.querySelector(".git-diff-content-area").style.display="none";try{let s=8765;if(window.dashboard&&window.dashboard.socketClient&&window.dashboard.socketClient.port)s=window.dashboard.socketClient.port;else{const e=document.getElementById("port-input");e&&e.value&&(s=e.value)}const o=new URLSearchParams({file:t});n&&o.append("timestamp",n),i&&o.append("working_dir",i);const r=`http://localhost:${s}/api/git-diff?${o}`;console.log("🌐 Making git diff request to:",r),console.log("📋 Git diff request parameters:",{filePath:t,timestamp:n,workingDir:i,urlParams:o.toString()});try{const e=await fetch(`http://localhost:${s}/health`,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json"},mode:"cors"});if(!e.ok)throw new Error(`Server health check failed: ${e.status} ${e.statusText}`)}catch(a){throw new Error(`Cannot reach server at localhost:${s}. Health check failed: ${a.message}`)}const l=await fetch(r,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json"},mode:"cors"});if(!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);const d=await l.json();e.querySelector(".git-diff-loading").style.display="none",d.success?function(e,t){const n=e.querySelector(".git-diff-content-area"),i=e.querySelector(".commit-hash"),s=e.querySelector(".diff-method"),o=e.querySelector(".git-diff-code");i&&(i.textContent=`Commit: ${t.commit_hash}`);s&&(s.textContent=`Method: ${t.method}`);if(o&&t.diff){o.innerHTML=t.diff.split("\n").map(e=>{const t=e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return e.startsWith("+++")||e.startsWith("---")?`<span class="diff-header">${t}</span>`:e.startsWith("@@")?`<span class="diff-meta">${t}</span>`:e.startsWith("+")?`<span class="diff-addition">${t}</span>`:e.startsWith("-")?`<span class="diff-deletion">${t}</span>`:e.startsWith("commit ")||e.startsWith("Author:")||e.startsWith("Date:")?`<span class="diff-header">${t}</span>`:`<span class="diff-context">${t}</span>`}).join("\n");const n=e.querySelector(".git-diff-scroll-wrapper");n&&setTimeout(()=>{const t=e.querySelector(".modal-content"),i=e.querySelector(".git-diff-header"),s=e.querySelector(".git-diff-toolbar"),o=(t?.offsetHeight||0)-(i?.offsetHeight||0)-(s?.offsetHeight||0)-40;n.style.maxHeight=`${o}px`,n.style.overflowY="auto"},50)}else console.warn("⚠️ Missing codeElement or diff data");n&&(n.style.display="block")}(e,d):f(e,d)}catch(r){console.error("❌ Failed to fetch git diff:",r),console.error("Error details:",{name:r.name,message:r.message,stack:r.stack,filePath:t,timestamp:n,workingDir:i}),e.querySelector(".git-diff-loading").style.display="none";let s=`Network error: ${r.message}`,o=[];r.message.includes("Failed to fetch")?(s="Failed to connect to the monitoring server",o=["Check if the monitoring server is running on port 8765","Verify the port configuration in the dashboard","Check browser console for CORS or network errors","Try refreshing the page and reconnecting"]):r.message.includes("health check failed")?(s=r.message,o=["The server may be starting up - try again in a few seconds","Check if another process is using port 8765","Restart the claude-mpm monitoring server"]):r.message.includes("HTTP")&&(s=`Server error: ${r.message}`,o=["The server encountered an internal error","Check the server logs for more details","Try with a different file or working directory"]),f(e,{error:s,file_path:t,working_dir:i,suggestions:o,debug_info:{error_type:r.name,original_message:r.message,port:window.dashboard?.socketClient?.port||document.getElementById("port-input")?.value||"8765",timestamp:(new Date).toISOString()}})}}(i,e,t,n),i.style.display="flex",document.body.style.overflow="hidden"},window.hideGitDiffModal=function(){const e=document.getElementById("git-diff-modal");e&&(e.style.display="none",document.body.style.overflow="")},window.copyGitDiff=function(){const e=document.getElementById("git-diff-modal");if(!e)return;const t=e.querySelector(".git-diff-code");if(!t)return;const n=t.textContent;if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(n).then(()=>{const t=e.querySelector(".git-diff-copy"),n=t.textContent;t.textContent="✅ Copied!",setTimeout(()=>{t.textContent=n},2e3)}).catch(e=>{console.error("Failed to copy text:",e)});else{const t=document.createElement("textarea");t.value=n,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t);const i=e.querySelector(".git-diff-copy"),s=i.textContent;i.textContent="✅ Copied!",setTimeout(()=>{i.textContent=s},2e3)}},window.showFileViewerModal=function(e){let t="";window.dashboard&&window.dashboard.currentWorkingDir&&(t=window.dashboard.currentWorkingDir);let n=document.getElementById("file-viewer-modal");n||(n=p(),document.body.appendChild(n)),g(n,e,t),n.style.display="flex",document.body.style.overflow="hidden"},window.hideFileViewerModal=function(){const e=document.getElementById("file-viewer-modal");e&&(e.style.display="none",document.body.style.overflow="")},window.copyFileContent=function(){const e=document.getElementById("file-viewer-modal");if(!e)return;const t=e.querySelector(".file-content-code");if(!t)return;const n=t.textContent;if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(n).then(()=>{const t=e.querySelector(".file-content-copy"),n=t.textContent;t.textContent="✅ Copied!",setTimeout(()=>{t.textContent=n},2e3)}).catch(e=>{console.error("Failed to copy text:",e)});else{const t=document.createElement("textarea");t.value=n,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t);const i=e.querySelector(".file-content-copy"),s=i.textContent;i.textContent="✅ Copied!",setTimeout(()=>{i.textContent=s},2e3)}},window.showSearchViewerModal=function(e,t){let n=document.getElementById("search-viewer-modal");n||(n=function(){const e=document.createElement("div");return e.id="search-viewer-modal",e.className="modal search-viewer-modal",e.innerHTML='\n <div class="modal-content search-viewer-content">\n <div class="search-viewer-header">\n <h2 class="search-viewer-title">\n <span class="search-viewer-icon">🔍</span>\n <span class="search-viewer-title-text">Search Results</span>\n </h2>\n <button class="search-viewer-close" onclick="hideSearchViewerModal()">\n <span>&times;</span>\n </button>\n </div>\n <div class="search-viewer-body">\n <div class="search-params-section">\n <h3>Search Parameters</h3>\n <pre class="search-params-display"></pre>\n </div>\n <div class="search-results-section">\n <h3>Search Results</h3>\n <div class="search-results-display"></div>\n </div>\n </div>\n </div>\n ',e.addEventListener("click",t=>{t.target===e&&hideSearchViewerModal()}),document.addEventListener("keydown",t=>{"Escape"===t.key&&"flex"===e.style.display&&hideSearchViewerModal()}),e}(),document.body.appendChild(n)),function(e,t,n){const i=e.querySelector(".search-params-display"),s=e.querySelector(".search-results-display");i&&t&&(i.textContent=JSON.stringify(t,null,2));if(s&&n){let e="";"string"==typeof n?e=`<pre class="search-results-text">${v(n)}</pre>`:Array.isArray(n)?(e='<ul class="search-results-list">',n.forEach(t=>{e+="object"==typeof t?`<li><pre>${JSON.stringify(t,null,2)}</pre></li>`:`<li>${v(String(t))}</li>`}),e+="</ul>"):e="object"==typeof n?`<pre class="search-results-json">${JSON.stringify(n,null,2)}</pre>`:`<div class="search-results-text">${v(String(n))}</div>`,s.innerHTML=e}}(n,e,t),n.style.display="flex",document.body.style.overflow="hidden"},window.hideSearchViewerModal=function(){const e=document.getElementById("search-viewer-modal");e&&(e.style.display="none",document.body.style.overflow="")},window.showAgentInstanceDetails=function(e){window.dashboard&&"function"==typeof window.dashboard.showAgentInstanceDetails?window.dashboard.showAgentInstanceDetails(e):console.error("Dashboard not available or method not found")},document.addEventListener("DOMContentLoaded",function(){try{window.dashboard=new u,window.dashboard&&"function"==typeof window.dashboard.postInit&&window.dashboard.postInit(),console.log("Dashboard loaded and initialized successfully"),document.dispatchEvent(new CustomEvent("dashboardReady",{detail:{dashboard:window.dashboard}}))}catch(e){console.error("Failed to initialize dashboard:",e),document.body.innerHTML=`\n <div style="padding: 20px; font-family: sans-serif;">\n <h1>Dashboard Initialization Error</h1>\n <p>The dashboard failed to load properly. Please refresh the page or check the console for details.</p>\n <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px;">${e.message}</pre>\n </div>\n `}});
2
2
  //# sourceMappingURL=dashboard.js.map