claude-mpm 4.0.3__py3-none-any.whl → 4.0.8__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.
- claude_mpm/VERSION +1 -1
- claude_mpm/agents/templates/ticketing.json +1 -1
- claude_mpm/cli/commands/monitor.py +131 -9
- claude_mpm/cli/commands/tickets.py +61 -26
- claude_mpm/cli/parsers/monitor_parser.py +22 -2
- claude_mpm/constants.py +4 -1
- claude_mpm/core/framework_loader.py +102 -14
- claude_mpm/dashboard/static/built/components/agent-inference.js +2 -0
- claude_mpm/dashboard/static/built/components/event-processor.js +2 -0
- claude_mpm/dashboard/static/built/components/event-viewer.js +2 -0
- claude_mpm/dashboard/static/built/components/export-manager.js +2 -0
- claude_mpm/dashboard/static/built/components/file-tool-tracker.js +2 -0
- claude_mpm/dashboard/static/built/components/hud-library-loader.js +2 -0
- claude_mpm/dashboard/static/built/components/hud-manager.js +2 -0
- claude_mpm/dashboard/static/built/components/hud-visualizer.js +2 -0
- claude_mpm/dashboard/static/built/components/module-viewer.js +2 -0
- claude_mpm/dashboard/static/built/components/session-manager.js +2 -0
- claude_mpm/dashboard/static/built/components/socket-manager.js +2 -0
- claude_mpm/dashboard/static/built/components/ui-state-manager.js +2 -0
- claude_mpm/dashboard/static/built/components/working-directory.js +2 -0
- claude_mpm/dashboard/static/built/dashboard.js +2 -0
- claude_mpm/dashboard/static/built/socket-client.js +2 -0
- claude_mpm/dashboard/static/dist/components/event-viewer.js +1 -1
- claude_mpm/dashboard/static/dist/components/file-tool-tracker.js +1 -1
- claude_mpm/dashboard/static/dist/socket-client.js +1 -1
- claude_mpm/dashboard/static/js/components/event-viewer.js +24 -3
- claude_mpm/dashboard/static/js/components/file-tool-tracker.js +5 -5
- claude_mpm/dashboard/static/js/socket-client.js +25 -5
- claude_mpm/hooks/claude_hooks/connection_pool.py +75 -12
- claude_mpm/hooks/claude_hooks/hook_handler.py +63 -12
- claude_mpm/services/port_manager.py +370 -18
- claude_mpm/services/socketio/handlers/connection.py +41 -19
- claude_mpm/services/socketio/handlers/hook.py +23 -8
- claude_mpm/services/system_instructions_service.py +22 -7
- {claude_mpm-4.0.3.dist-info → claude_mpm-4.0.8.dist-info}/METADATA +64 -22
- {claude_mpm-4.0.3.dist-info → claude_mpm-4.0.8.dist-info}/RECORD +40 -25
- {claude_mpm-4.0.3.dist-info → claude_mpm-4.0.8.dist-info}/WHEEL +0 -0
- {claude_mpm-4.0.3.dist-info → claude_mpm-4.0.8.dist-info}/entry_points.txt +0 -0
- {claude_mpm-4.0.3.dist-info → claude_mpm-4.0.8.dist-info}/licenses/LICENSE +0 -0
- {claude_mpm-4.0.3.dist-info → claude_mpm-4.0.8.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
class e{constructor(e){this.socketManager=e,this.currentWorkingDir=null,this.footerDirObserver=null,this._updatingFooter=!1,this.setupEventHandlers(),this.initialize(),console.log("Working directory manager initialized")}initialize(){this.initializeWorkingDirectory(),this.watchFooterDirectory()}setupEventHandlers(){const e=document.getElementById("change-dir-btn"),t=document.getElementById("working-dir-path");if(e&&e.addEventListener("click",()=>{this.showChangeDirDialog()}),t&&t.addEventListener("click",e=>{e.shiftKey?this.showChangeDirDialog():this.showWorkingDirectoryViewer()}),document.addEventListener("sessionChanged",e=>{const t=e.detail.sessionId;console.log("[WORKING-DIR-DEBUG] sessionChanged event received, sessionId:",this.repr(t)),t&&this.loadWorkingDirectoryForSession(t)}),this.socketManager&&this.socketManager.getSocket){const e=this.socketManager.getSocket();e&&(console.log("[WORKING-DIR-DEBUG] Setting up git_branch_response listener"),e.on("git_branch_response",e=>{console.log("[GIT-BRANCH-DEBUG] Received git_branch_response:",e),this.handleGitBranchResponse(e)}))}}initializeWorkingDirectory(){const e=document.getElementById("working-dir-path");e&&!e.textContent.trim()&&(e.textContent="Loading...");const t=document.getElementById("session-select");t&&t.value&&"all"!==t.value?this.loadWorkingDirectoryForSession(t.value):this.setWorkingDirectory(this.getDefaultWorkingDir())}watchFooterDirectory(){const e=document.getElementById("footer-working-dir");e&&(this.footerDirObserver=new MutationObserver(t=>{this._updatingFooter||t.forEach(t=>{if("childList"===t.type||"characterData"===t.type){const t=e.textContent.trim();console.log("Footer directory changed to:",t),t&&t!==this.currentWorkingDir&&(console.log("Syncing working directory from footer change"),this.setWorkingDirectory(t))}})}),this.footerDirObserver.observe(e,{childList:!0,characterData:!0,subtree:!0}),console.log("Started watching footer directory for changes"))}loadWorkingDirectoryForSession(e){if(console.log("[WORKING-DIR-DEBUG] loadWorkingDirectoryForSession called with sessionId:",this.repr(e)),!e||"all"===e){console.log('[WORKING-DIR-DEBUG] No sessionId or sessionId is "all", using default working dir');const e=this.getDefaultWorkingDir();return console.log("[WORKING-DIR-DEBUG] Default working dir:",this.repr(e)),void this.setWorkingDirectory(e)}const t=JSON.parse(localStorage.getItem("sessionWorkingDirs")||"{}");console.log("[WORKING-DIR-DEBUG] Session directories from localStorage:",t);const r=t[e],o=this.getDefaultWorkingDir(),i=r||o;console.log("[WORKING-DIR-DEBUG] Directory selection:",{sessionId:e,sessionDir:this.repr(r),defaultDir:this.repr(o),finalDir:this.repr(i)}),this.setWorkingDirectory(i)}setWorkingDirectory(e){console.log("[WORKING-DIR-DEBUG] setWorkingDirectory called with:",this.repr(e)),this.currentWorkingDir=e;const t=document.getElementById("working-dir-path");t?(console.log("[WORKING-DIR-DEBUG] Updating UI path element to:",e),t.textContent=e):console.warn("[WORKING-DIR-DEBUG] working-dir-path element not found");const r=document.getElementById("footer-working-dir");if(r){const t=r.textContent;console.log("[WORKING-DIR-DEBUG] Footer directory current text:",this.repr(t),"new text:",this.repr(e)),t!==e?(this._updatingFooter=!0,r.textContent=e,console.log("[WORKING-DIR-DEBUG] Updated footer directory to:",e),setTimeout(()=>{this._updatingFooter=!1,console.log("[WORKING-DIR-DEBUG] Cleared _updatingFooter flag")},100)):console.log("[WORKING-DIR-DEBUG] Footer directory already has correct text")}else console.warn("[WORKING-DIR-DEBUG] footer-working-dir element not found");const o=document.getElementById("session-select");if(o&&o.value&&"all"!==o.value){const t=o.value,r=JSON.parse(localStorage.getItem("sessionWorkingDirs")||"{}");r[t]=e,localStorage.setItem("sessionWorkingDirs",JSON.stringify(r)),console.log(`[WORKING-DIR-DEBUG] Saved working directory for session ${t}:`,e)}else console.log('[WORKING-DIR-DEBUG] No session selected or session is "all", not saving to localStorage');console.log("[WORKING-DIR-DEBUG] About to call updateGitBranch with:",this.repr(e)),this.validateDirectoryPath(e)?this.updateGitBranch(e):console.log("[WORKING-DIR-DEBUG] Skipping git branch update for invalid directory:",this.repr(e)),document.dispatchEvent(new CustomEvent("workingDirectoryChanged",{detail:{directory:e}})),console.log("[WORKING-DIR-DEBUG] Working directory set to:",e)}updateGitBranch(e){if(console.log("[GIT-BRANCH-DEBUG] updateGitBranch called with dir:",this.repr(e),"type:",typeof e),!this.socketManager||!this.socketManager.isConnected()){console.log("[GIT-BRANCH-DEBUG] Not connected to socket server");const e=document.getElementById("footer-git-branch");return void(e&&(e.textContent="Not Connected",e.style.display="inline"))}const t=this.validateDirectoryPath(e),r="Loading..."===e||"Loading"===e,o="Unknown"===e,i=!e||"string"==typeof e&&""===e.trim();if(console.log("[GIT-BRANCH-DEBUG] Validation results:",{dir:e,isValidPath:t,isLoadingState:r,isUnknown:o,isEmptyOrWhitespace:i,shouldReject:!t||r||o||i}),!t||r||o||i){console.warn("[GIT-BRANCH-DEBUG] Invalid working directory for git branch request:",e);const t=document.getElementById("footer-git-branch");return void(t&&(t.textContent=r?"Loading...":o||i?"No Directory":"Invalid Directory",t.style.display="inline"))}const n=this.socketManager.getSocket();n?(console.log("[GIT-BRANCH-DEBUG] Requesting git branch for directory:",e),console.log("[GIT-BRANCH-DEBUG] Socket state:",{connected:n.connected,id:n.id}),n.emit("get_git_branch",e)):console.error("[GIT-BRANCH-DEBUG] No socket available for git branch request")}getDefaultWorkingDir(){console.log("[WORKING-DIR-DEBUG] getDefaultWorkingDir called");const e=document.getElementById("footer-working-dir");if(e?.textContent?.trim()){const t=e.textContent.trim();console.log("[WORKING-DIR-DEBUG] Footer path found:",this.repr(t));const r="Unknown"===t,o=this.validateDirectoryPath(t);if(console.log("[WORKING-DIR-DEBUG] Footer path validation:",{footerPath:this.repr(t),isUnknown:r,isValid:o,shouldUse:!r&&o}),!r&&o)return console.log("[WORKING-DIR-DEBUG] Using footer path as default:",t),t}else console.log("[WORKING-DIR-DEBUG] No footer directory element or no text content");if(window.location.pathname.includes("claude-mpm")){const e="/Users/masa/Projects/claude-mpm";return console.log("[WORKING-DIR-DEBUG] Using inferred project path as fallback:",e),e}const t=document.getElementById("working-dir-path");if(t?.textContent?.trim()){const e=t.textContent.trim();if(console.log("[WORKING-DIR-DEBUG] Found working-dir-path element text:",this.repr(e)),"Unknown"!==e&&this.validateDirectoryPath(e))return console.log("[WORKING-DIR-DEBUG] Using working-dir-path as fallback:",e),e}const r=process?.cwd?.()||"/Users/masa/Projects/claude-mpm";return console.log("[WORKING-DIR-DEBUG] Using hard-coded fallback directory:",this.repr(r)),r}showChangeDirDialog(){const e=prompt("Enter new working directory:",this.currentWorkingDir||"");e&&""!==e.trim()&&this.setWorkingDirectory(e.trim())}showWorkingDirectoryViewer(){this.createDirectoryViewerOverlay()}createDirectoryViewerOverlay(){this.removeDirectoryViewerOverlay();const e=document.querySelector(".working-dir-display");if(!e)return;const t=document.createElement("div");t.id="directory-viewer-overlay",t.className="directory-viewer-overlay",t.innerHTML=`\n <div class="directory-viewer-content">\n <div class="directory-viewer-header">\n <h3 class="directory-viewer-title">\n 📁 ${this.currentWorkingDir||"Working Directory"}\n </h3>\n <button class="close-btn" onclick="workingDirectoryManager.removeDirectoryViewerOverlay()">✕</button>\n </div>\n <div class="directory-viewer-body">\n <div class="loading-indicator">Loading directory contents...</div>\n </div>\n <div class="directory-viewer-footer">\n <span class="directory-hint">Click file to view • Shift+Click directory path to change</span>\n </div>\n </div>\n `;const r=e.getBoundingClientRect();t.style.cssText=`\n position: fixed;\n top: ${r.bottom+5}px;\n left: ${r.left}px;\n min-width: 400px;\n max-width: 600px;\n max-height: 400px;\n z-index: 1001;\n background: white;\n border-radius: 8px;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);\n border: 1px solid #e2e8f0;\n `,document.body.appendChild(t),this.loadDirectoryContents(),setTimeout(()=>{document.addEventListener("click",this.handleOutsideClick.bind(this),!0)},100)}removeDirectoryViewerOverlay(){const e=document.getElementById("directory-viewer-overlay");e&&(e.remove(),document.removeEventListener("click",this.handleOutsideClick.bind(this),!0))}handleOutsideClick(e){const t=document.getElementById("directory-viewer-overlay"),r=document.getElementById("working-dir-path");t&&!t.contains(e.target)&&e.target!==r&&this.removeDirectoryViewerOverlay()}loadDirectoryContents(){if(!this.socketManager||!this.socketManager.isConnected())return void this.showDirectoryError("Not connected to server");const e=this.socketManager.getSocket();if(!e)return void this.showDirectoryError("No socket connection available");e.emit("get_directory_listing",{directory:this.currentWorkingDir,limit:50});const t=r=>{e.off("directory_listing_response",t),this.handleDirectoryListingResponse(r)};e.on("directory_listing_response",t),setTimeout(()=>{e.off("directory_listing_response",t);const r=document.getElementById("directory-viewer-overlay");r&&r.querySelector(".loading-indicator")&&this.showDirectoryError("Request timeout")},5e3)}handleDirectoryListingResponse(e){const t=document.querySelector(".directory-viewer-body");if(!t)return;if(!e.success)return void this.showDirectoryError(e.error||"Failed to load directory");const r=e.files||[],o=e.directories||[];let i="";if(this.currentWorkingDir&&"/"!==this.currentWorkingDir){const e=this.currentWorkingDir.split("/").slice(0,-1).join("/")||"/";i+=`\n <div class="file-item directory-item" onclick="workingDirectoryManager.setWorkingDirectory('${e}')">\n <span class="file-icon">📁</span>\n <span class="file-name">..</span>\n <span class="file-type">parent directory</span>\n </div>\n `}o.forEach(e=>{const t=`${this.currentWorkingDir}/${e}`.replace(/\/+/g,"/");i+=`\n <div class="file-item directory-item" onclick="workingDirectoryManager.setWorkingDirectory('${t}')">\n <span class="file-icon">📁</span>\n <span class="file-name">${e}</span>\n <span class="file-type">directory</span>\n </div>\n `}),r.forEach(e=>{const t=`${this.currentWorkingDir}/${e}`.replace(/\/+/g,"/"),r=e.split(".").pop().toLowerCase(),o=this.getFileIcon(r);i+=`\n <div class="file-item" onclick="workingDirectoryManager.viewFile('${t}')">\n <span class="file-icon">${o}</span>\n <span class="file-name">${e}</span>\n <span class="file-type">${r}</span>\n </div>\n `}),""===i&&(i='<div class="no-files">Empty directory</div>'),t.innerHTML=i}showDirectoryError(e){const t=document.querySelector(".directory-viewer-body");t&&(t.innerHTML=`\n <div class="directory-error">\n <span class="error-icon">⚠️</span>\n <span class="error-message">${e}</span>\n </div>\n `)}getFileIcon(e){return{js:"📄",py:"🐍",html:"🌐",css:"🎨",json:"📋",md:"📝",txt:"📝",yml:"⚙️",yaml:"⚙️",xml:"📄",pdf:"📕",png:"🖼️",jpg:"🖼️",jpeg:"🖼️",gif:"🖼️",svg:"🖼️",zip:"📦",tar:"📦",gz:"📦",sh:"🔧",bat:"🔧",exe:"⚙️",dll:"⚙️"}[e]||"📄"}viewFile(e){this.removeDirectoryViewerOverlay(),window.showFileViewerModal?window.showFileViewerModal(e):console.warn("File viewer modal function not available")}getCurrentWorkingDir(){return this.currentWorkingDir}getSessionDirectories(){return JSON.parse(localStorage.getItem("sessionWorkingDirs")||"{}")}setSessionDirectory(e,t){const r=this.getSessionDirectories();r[e]=t,localStorage.setItem("sessionWorkingDirs",JSON.stringify(r));const o=document.getElementById("session-select");o&&o.value===e&&this.setWorkingDirectory(t)}removeSessionDirectory(e){const t=this.getSessionDirectories();delete t[e],localStorage.setItem("sessionWorkingDirs",JSON.stringify(t))}clearAllSessionDirectories(){localStorage.removeItem("sessionWorkingDirs")}extractWorkingDirectoryFromPair(e){return e.pre?.working_dir?e.pre.working_dir:e.post?.working_dir?e.post.working_dir:e.pre?.data?.working_dir?e.pre.data.working_dir:e.post?.data?.working_dir?e.post.data.working_dir:this.currentWorkingDir||this.getDefaultWorkingDir()}validateDirectoryPath(e){if(!e||"string"!=typeof e)return!1;const t=e.trim();if(0===t.length)return!1;if(t.includes("\0"))return!1;return!["Loading...","Loading","Unknown","undefined","null","Not Connected","Invalid Directory","No Directory"].includes(t)&&(!(!t.startsWith("/")&&!/^[A-Za-z]:/.test(t))||!!(t.startsWith("./")||t.startsWith("../")||/^[a-zA-Z0-9._-]+/.test(t)))}handleGitBranchResponse(e){console.log("[GIT-BRANCH-DEBUG] handleGitBranchResponse called with:",e);const t=document.getElementById("footer-git-branch");if(t){if(e.success)console.log("[GIT-BRANCH-DEBUG] Git branch request successful, branch:",e.branch),t.textContent=e.branch,t.style.display="inline",t.classList.remove("git-error"),t.classList.add("git-success");else{let r="Git Error";const o=e.error||"Unknown error";r=o.includes("Directory not found")||o.includes("does not exist")?"Dir Not Found":o.includes("Not a directory")?"Invalid Path":o.includes("Not a git repository")?"No Git Repo":o.includes("git")?"Git Error":"Unknown",console.log("[GIT-BRANCH-DEBUG] Git branch request failed:",o,"- showing as:",r),t.textContent=r,t.style.display="inline",t.classList.remove("git-success"),t.classList.add("git-error")}e.original_working_dir&&console.log("[GIT-BRANCH-DEBUG] Server received original working_dir:",this.repr(e.original_working_dir)),e.working_dir&&console.log("[GIT-BRANCH-DEBUG] Server used working_dir:",this.repr(e.working_dir)),e.git_error&&console.log("[GIT-BRANCH-DEBUG] Git command stderr:",e.git_error)}else console.warn("[GIT-BRANCH-DEBUG] footer-git-branch element not found")}isWorkingDirectoryReady(){const e=this.getCurrentWorkingDir();return this.validateDirectoryPath(e)&&"Loading..."!==e&&"Unknown"!==e}whenDirectoryReady(e,t=5e3){const r=Date.now(),o=()=>{this.isWorkingDirectoryReady()?e():Date.now()-r<t?setTimeout(o,100):console.warn("[WORKING-DIR-DEBUG] Timeout waiting for directory to be ready")};o()}repr(e){return null===e?"null":void 0===e?"undefined":"string"==typeof e?`"${e}"`:String(e)}cleanup(){this.footerDirObserver&&(this.footerDirObserver.disconnect(),this.footerDirObserver=null),console.log("Working directory manager cleaned up")}}export{e as W};
|
|
2
|
+
//# sourceMappingURL=working-directory.js.map
|
|
@@ -0,0 +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 o}from"./components/module-viewer.js";import{S as s}from"./components/session-manager.js";import{A as r}from"./components/agent-inference.js";import{E as a}from"./components/export-manager.js";import{W as l}from"./components/working-directory.js";import{F as c}from"./components/file-tool-tracker.js";class d{constructor(){this.eventViewer=null,this.moduleViewer=null,this.sessionManager=null,this.socketManager=null,this.agentInference=null,this.uiStateManager=null,this.eventProcessor=null,this.exportManager=null,this.workingDirectoryManager=null,this.fileToolTracker=null,this.init()}init(){console.log("Initializing refactored Claude MPM Dashboard..."),this.initializeSocketManager(),this.initializeCoreComponents(),this.initializeAgentInference(),this.initializeUIStateManager(),this.initializeWorkingDirectoryManager(),this.initializeFileToolTracker(),this.initializeEventProcessor(),this.initializeExportManager(),this.setupModuleInteractions(),this.initializeFromURL(),console.log("Claude MPM Dashboard initialized successfully")}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 o,this.sessionManager=new s(this.socketClient),window.eventViewer=this.eventViewer,window.moduleViewer=this.moduleViewer,window.sessionManager=this.sessionManager}initializeAgentInference(){this.agentInference=new r(this.eventViewer),this.agentInference.initialize()}initializeUIStateManager(){this.uiStateManager=new t,this.setupTabFilters()}initializeWorkingDirectoryManager(){this.workingDirectoryManager=new l(this.socketManager)}initializeFileToolTracker(){this.fileToolTracker=new c(this.agentInference,this.workingDirectoryManager)}initializeEventProcessor(){this.eventProcessor=new i(this.eventViewer,this.agentInference)}initializeExportManager(){this.exportManager=new a(this.eventViewer)}setupModuleInteractions(){this.socketManager.onEventUpdate(e=>{this.fileToolTracker.updateFileOperations(e),this.fileToolTracker.updateToolCalls(e),this.agentInference.processAgentInference(),"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 o=document.getElementById("files-search-input"),s=document.getElementById("files-type-filter");o&&o.addEventListener("input",()=>{"files"===this.uiStateManager.getCurrentTab()&&this.renderCurrentTab()}),s&&s.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"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;this.agentInference.processAgentInference();const t=this.eventProcessor.getFilteredEventsForTab("agents"),n=this.eventProcessor.generateAgentHTML(t);e.innerHTML=n,this.exportManager.scrollListToBottom("agents-list");const i=this.agentInference.getUniqueAgentInstances();this.updateAgentsFilterDropdowns(i)}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),o=this.eventProcessor.generateToolHTML(i);e.innerHTML=o,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),o=this.eventProcessor.generateFileHTML(i);e.innerHTML=o,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 o=i.value,s=t.sort((e,t)=>e.localeCompare(t));i.innerHTML=`<option value="">${n}</option>`,s.forEach(e=>{const t=document.createElement("option");t.value=e,t.textContent=e,i.appendChild(t)}),o&&s.includes(o)&&(i.value=o)}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 g(){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>×</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 f(e,t,n){const i=e.querySelector(".file-viewer-file-path"),o=e.querySelector(".file-viewer-file-size");i.textContent=t,o.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 o=new Promise((e,n)=>{const o=s=>{s.file_path===t&&(i.off("file_content_response",o),s.success?e(s):n(new Error(s.error||"Failed to read file")))};i.on("file_content_response",o),setTimeout(()=>{i.off("file_content_response",o),n(new Error("Request timeout"))},1e4)});i.emit("read_file",{file_path:t,working_dir:n}),console.log("📄 File viewer request sent:",{filePath:t,workingDir:n});const s=await o;console.log("📦 File content received:",s),e.querySelector(".file-viewer-loading").style.display="none",function(e,t){console.log("📝 displayFileContent called with:",t);const n=e.querySelector(".file-viewer-content-area"),i=e.querySelector(".file-extension"),o=e.querySelector(".file-encoding"),s=e.querySelector(".file-viewer-file-size"),r=e.querySelector(".file-content-code");i&&(i.textContent=`Type: ${t.extension||"unknown"}`);o&&(o.textContent=`Encoding: ${t.encoding||"unknown"}`);s&&(s.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(r&&t.content){console.log("💡 Setting file content, length:",t.content.length),r.innerHTML=function(e,t){const n=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");switch(t){case".js":case".jsx":case".ts":case".tsx":return function(e){return p(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 p(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 p(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 p(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 p(e.replace(/(<\/?[\w-]+)/g,'<span class="tag">$1</span>').replace(/([\w-]+)=(['"][^'"]*['"])/g,'<span class="attribute">$1</span>=<span class="string">$2</span>').replace(/(<!--[\s\S]*?-->)/g,'<span class="comment">$1</span>'))}(n);case".md":case".markdown":return function(e){return p(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 p(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"),o=e.querySelector(".file-viewer-toolbar"),s=t?.offsetHeight||0,r=i?.offsetHeight||0,a=o?.offsetHeight||0,l=s-r-a-40;console.log("🎯 Setting file viewer scroll height:",{modalHeight:s,headerHeight:r,toolbarHeight:a,availableHeight:l}),n.style.maxHeight=`${l}px`,n.style.overflowY="auto"},50)}else console.warn("⚠️ Missing codeElement or file content");n&&(n.style.display="block",console.log("✅ File content area displayed"))}(e,s)}catch(s){console.error("❌ Failed to fetch file content:",s),e.querySelector(".file-viewer-loading").style.display="none";let i=s.message||"Unknown error occurred",o=[];s.message.includes("No socket connection")?(i="Failed to connect to the monitoring server",o=["Check if the monitoring server is running","Verify the socket connection in the dashboard","Try refreshing the page and reconnecting"]):s.message.includes("timeout")?(i="Request timed out",o=["The file may be too large to load quickly","Check your network connection","Try again in a few moments"]):s.message.includes("File does not exist")?(i="File not found",o=["The file may have been moved or deleted","Check the file path spelling","Refresh the file list to see current files"]):s.message.includes("Access denied")&&(i="Access denied",o=["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"),o=e.querySelector(".error-suggestions");let s=t.error||"Unknown error occurred";i.innerHTML=`\n <div class="error-main">${s}</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?o.innerHTML=`\n <h4>Suggestions:</h4>\n <ul>\n ${t.suggestions.map(e=>`<li>${e}</li>`).join("")}\n </ul>\n `:o.innerHTML="";console.log("📋 Displaying file viewer error:",{originalError:t.error,processedMessage:s,suggestions:t.suggestions}),n.style.display="block"}(e,{error:i,file_path:t,working_dir:n,suggestions:o})}}function p(e){return e.split("\n").map((e,t)=>`<span class="line-number">${String(t+1).padStart(3," ")}</span> ${e||" "}`).join("\n")}function h(e,t){const n=e.querySelector(".git-diff-error"),i=e.querySelector(".error-message"),o=e.querySelector(".error-suggestions");let s=t.error||"Unknown error occurred",r=!1;if(s.includes("not tracked by git")?(s="📝 This file is not tracked by git yet",r=!0):s.includes("No git history found")&&(s="📋 No git history available for this file"),i.innerHTML=`\n <div class="error-main">${s}</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=r?"How to track this file:":"Suggestions:";o.innerHTML=`\n <h4>${e}</h4>\n <ul>\n ${t.suggestions.map(e=>`<li>${e}</li>`).join("")}\n </ul>\n `}else o.innerHTML="";console.log("📋 Displaying git diff error:",{originalError:t.error,processedMessage:s,isUntracked:r,suggestions:t.suggestions}),n.style.display="block"}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=g(),document.body.appendChild(n)),f(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"),o=i.textContent;i.textContent="✅ Copied!",setTimeout(()=>{i.textContent=o},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>×</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 o=e.querySelector(".git-diff-file-path"),s=e.querySelector(".git-diff-timestamp");o.textContent=t,s.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 o=8765;if(window.dashboard&&window.dashboard.socketClient&&window.dashboard.socketClient.port)o=window.dashboard.socketClient.port;else{const e=document.getElementById("port-input");e&&e.value&&(o=e.value)}const s=new URLSearchParams({file:t});n&&s.append("timestamp",n),i&&s.append("working_dir",i);const a=`http://localhost:${o}/api/git-diff?${s}`;console.log("🌐 Making git diff request to:",a),console.log("📋 Git diff request parameters:",{filePath:t,timestamp:n,workingDir:i,urlParams:s.toString()});try{const e=await fetch(`http://localhost:${o}/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}`);console.log("✅ Server health check passed")}catch(r){throw new Error(`Cannot reach server at localhost:${o}. Health check failed: ${r.message}`)}const l=await fetch(a,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json"},mode:"cors"});if(!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);const c=await l.json();console.log("📦 Git diff response:",c),e.querySelector(".git-diff-loading").style.display="none",c.success?(console.log("📊 Displaying successful git diff"),function(e,t){console.log("📝 displayGitDiff called with:",t);const n=e.querySelector(".git-diff-content-area"),i=e.querySelector(".commit-hash"),o=e.querySelector(".diff-method"),s=e.querySelector(".git-diff-code");console.log("🔍 Elements found:",{contentArea:!!n,commitHashElement:!!i,methodElement:!!o,codeElement:!!s}),i&&(i.textContent=`Commit: ${t.commit_hash}`);o&&(o.textContent=`Method: ${t.method}`);if(s&&t.diff){console.log("💡 Setting diff content, length:",t.diff.length),s.innerHTML=t.diff.split("\n").map(e=>{const t=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");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"),o=e.querySelector(".git-diff-toolbar"),s=t?.offsetHeight||0,r=i?.offsetHeight||0,a=o?.offsetHeight||0,l=s-r-a-40;console.log("🎯 Setting explicit scroll height:",{modalHeight:s,headerHeight:r,toolbarHeight:a,availableHeight:l}),n.style.maxHeight=`${l}px`,n.style.overflowY="auto"},50)}else console.warn("⚠️ Missing codeElement or diff data");n&&(n.style.display="block",console.log("✅ Content area displayed"))}(e,c)):(console.log("⚠️ Displaying git diff error:",c),h(e,c))}catch(a){console.error("❌ Failed to fetch git diff:",a),console.error("Error details:",{name:a.name,message:a.message,stack:a.stack,filePath:t,timestamp:n,workingDir:i}),e.querySelector(".git-diff-loading").style.display="none";let o=`Network error: ${a.message}`,s=[];a.message.includes("Failed to fetch")?(o="Failed to connect to the monitoring server",s=["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"]):a.message.includes("health check failed")?(o=a.message,s=["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"]):a.message.includes("HTTP")&&(o=`Server error: ${a.message}`,s=["The server encountered an internal error","Check the server logs for more details","Try with a different file or working directory"]),h(e,{error:o,file_path:t,working_dir:i,suggestions:s,debug_info:{error_type:a.name,original_message:a.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"),o=i.textContent;i.textContent="✅ Copied!",setTimeout(()=>{i.textContent=o},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=g(),document.body.appendChild(n)),f(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"),o=i.textContent;i.textContent="✅ Copied!",setTimeout(()=>{i.textContent=o},2e3)}},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(){window.dashboard=new d,console.log("Dashboard loaded and initialized")});
|
|
2
|
+
//# sourceMappingURL=dashboard.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const t=window.io;class e{constructor(){this.socket=null,this.port=null,this.connectionCallbacks={connect:[],disconnect:[],error:[],event:[]},this.isConnected=!1,this.isConnecting=!1,this.events=[],this.sessions=new Map,this.currentSessionId=null,this.startStatusCheckFallback()}connect(t="8765"){this.port=t;const e=`http://localhost:${t}`;if(this.socket&&(this.socket.connected||this.socket.connecting))return console.log("Already connected or connecting, disconnecting first..."),this.socket.disconnect(),void setTimeout(()=>this.doConnect(e),100);this.doConnect(e)}doConnect(e){if(console.log(`Connecting to Socket.IO server at ${e}`),void 0===t)return console.error("Socket.IO library not loaded! Make sure socket.io.min.js is loaded before this script."),void this.notifyConnectionStatus("Socket.IO library not loaded","error");this.isConnecting=!0,this.notifyConnectionStatus("Connecting...","connecting"),this.socket=t(e,{autoConnect:!0,reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:1e4,maxReconnectionAttempts:10,timeout:1e4,forceNew:!0,transports:["websocket","polling"]}),this.setupSocketHandlers()}setupSocketHandlers(){this.socket.on("connect",()=>{console.log("Connected to Socket.IO server"),this.isConnected=!0,this.isConnecting=!1,this.notifyConnectionStatus("Connected","connected"),this.connectionCallbacks.connect.forEach(t=>t(this.socket.id)),this.requestStatus()}),this.socket.on("disconnect",t=>{console.log("Disconnected from server:",t),this.isConnected=!1,this.isConnecting=!1,this.notifyConnectionStatus(`Disconnected: ${t}`,"disconnected"),this.connectionCallbacks.disconnect.forEach(e=>e(t))}),this.socket.on("connect_error",t=>{console.error("Connection error:",t),this.isConnecting=!1;const e=t.message||t.description||"Unknown error";this.notifyConnectionStatus(`Connection Error: ${e}`,"disconnected"),this.addEvent({type:"connection.error",timestamp:(new Date).toISOString(),data:{error:e,url:this.socket.io.uri}}),this.connectionCallbacks.error.forEach(t=>t(e))}),this.socket.on("claude_event",t=>{const e=this.transformEvent(t);this.addEvent(e)}),this.socket.on("session.started",t=>{this.addEvent({type:"session",subtype:"started",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("session.ended",t=>{this.addEvent({type:"session",subtype:"ended",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("claude.request",t=>{this.addEvent({type:"claude",subtype:"request",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("claude.response",t=>{this.addEvent({type:"claude",subtype:"response",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("agent.loaded",t=>{this.addEvent({type:"agent",subtype:"loaded",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("agent.executed",t=>{this.addEvent({type:"agent",subtype:"executed",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("hook.pre",t=>{this.addEvent({type:"hook",subtype:"pre",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("hook.post",t=>{this.addEvent({type:"hook",subtype:"post",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("todo.updated",t=>{this.addEvent({type:"todo",subtype:"updated",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("memory.operation",t=>{this.addEvent({type:"memory",subtype:"operation",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("log.entry",t=>{this.addEvent({type:"log",subtype:"entry",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("history",t=>{console.log("Received event history:",t),t&&Array.isArray(t.events)?(console.log(`Processing ${t.events.length} historical events (${t.count} sent, ${t.total_available} total available)`),t.events.forEach(t=>{const e=this.transformEvent(t);this.addEvent(e,!1)}),this.notifyEventUpdate(),console.log(`Event history loaded: ${t.events.length} events added to dashboard`)):Array.isArray(t)&&(console.log("Received legacy event history format:",t.length,"events"),t.forEach(t=>{const e=this.transformEvent(t);this.addEvent(e,!1)}),this.notifyEventUpdate())}),this.socket.on("system.status",t=>{console.log("Received system status:",t),t.sessions&&this.updateSessions(t.sessions),t.current_session&&(this.currentSessionId=t.current_session)})}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null),this.port=null,this.isConnected=!1,this.isConnecting=!1}requestStatus(){this.socket&&this.socket.connected&&(console.log("Requesting server status..."),this.socket.emit("request.status"))}requestHistory(t={}){if(this.socket&&this.socket.connected){const e={limit:t.limit||50,event_types:t.event_types||[]};console.log("Requesting event history...",e),this.socket.emit("get_history",e)}else console.warn("Cannot request history: not connected to server")}addEvent(t,e=!0){if(t.timestamp||(t.timestamp=(new Date).toISOString()),t.id||(t.id=Date.now()+Math.random()),this.events.push(t),t.data&&t.data.session_id){const e=t.data.session_id;this.sessions.has(e)||this.sessions.set(e,{id:e,startTime:t.timestamp,lastActivity:t.timestamp,eventCount:0});const n=this.sessions.get(e);n.lastActivity=t.timestamp,n.eventCount++}e&&this.notifyEventUpdate()}updateSessions(t){Array.isArray(t)&&t.forEach(t=>{this.sessions.set(t.id,t)})}clearEvents(){this.events=[],this.sessions.clear(),this.notifyEventUpdate()}refreshHistory(t={}){this.clearEvents(),this.requestHistory(t)}getEventsBySession(t=null){return t?this.events.filter(e=>e.data&&e.data.session_id===t):this.events}onConnection(t,e){this.connectionCallbacks[t]&&this.connectionCallbacks[t].push(e)}onEventUpdate(t){this.connectionCallbacks.event.push(t)}notifyConnectionStatus(t,e){console.log(`SocketClient: Connection status changed to '${t}' (${e})`),this.updateConnectionStatusDOM(t,e),document.dispatchEvent(new CustomEvent("socketConnectionStatus",{detail:{status:t,type:e}}))}updateConnectionStatusDOM(t,e){const n=document.getElementById("connection-status");n?(n.innerHTML=`<span>●</span> ${t}`,n.className=`status-badge status-${e}`,console.log(`SocketClient: Direct DOM update - status: '${t}' (${e})`)):console.warn("SocketClient: Could not find connection-status element in DOM")}notifyEventUpdate(){this.connectionCallbacks.event.forEach(t=>t(this.events,this.sessions)),document.dispatchEvent(new CustomEvent("socketEventUpdate",{detail:{events:this.events,sessions:this.sessions}}))}getConnectionState(){return{isConnected:this.isConnected,isConnecting:this.isConnecting,socketId:this.socket?this.socket.id:null}}transformEvent(t){if(!t)return t;let e={...t};if(!t.type&&t.event){const n=t.event;"TestStart"===n||"TestEnd"===n?(e.type="test",e.subtype=n.toLowerCase().replace("test","")):"SubagentStart"===n||"SubagentStop"===n?(e.type="subagent",e.subtype=n.toLowerCase().replace("subagent","")):"ToolCall"===n?(e.type="tool",e.subtype="call"):"UserPrompt"===n?(e.type="hook",e.subtype="user_prompt"):(e.type="system",e.subtype=n.toLowerCase()),delete e.event}else if(t.type){const n=t.type;if(n.startsWith("hook.")){const t=n.substring(5);e.type="hook",e.subtype=t}else if(n.includes(".")){const[t,...s]=n.split(".");e.type=t,e.subtype=s.join(".")}}else e.type="unknown",e.subtype="";if(!t.type&&t.event?e.originalEventName=t.event:t.type&&(e.originalEventName=t.type),t.data&&"object"==typeof t.data){const n=["type","subtype","timestamp","id","event","event_type","originalEventName"];Object.keys(t.data).forEach(s=>{n.includes(s)?console.warn(`Protected field '${s}' in data object was not copied to top level to preserve event structure`):e[s]=t.data[s]}),e.data=t.data}return"hook"!==e.type||"pre_tool"!==e.subtype&&"post_tool"!==e.subtype||console.log("Transformed tool event:",{type:e.type,subtype:e.subtype,tool_name:e.tool_name,has_data:!!e.data,keys:Object.keys(e).filter(t=>"data"!==t)}),e}getState(){return{events:this.events,sessions:this.sessions,currentSessionId:this.currentSessionId}}startStatusCheckFallback(){setInterval(()=>{this.checkAndUpdateStatus()},2e3),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{setTimeout(()=>this.checkAndUpdateStatus(),100)}):setTimeout(()=>this.checkAndUpdateStatus(),100)}checkAndUpdateStatus(){let t="Disconnected",e="disconnected";this.socket&&(this.socket.connected?(t="Connected",e="connected",this.isConnected=!0,this.isConnecting=!1):this.socket.connecting||this.isConnecting?(t="Connecting...",e="connecting",this.isConnected=!1):(t="Disconnected",e="disconnected",this.isConnected=!1,this.isConnecting=!1));const n=document.getElementById("connection-status");if(n){const s=n.textContent.replace("●","").trim(),o=n.className,i=`status-badge status-${e}`;s===t&&o===i||(console.log(`SocketClient: Fallback update - was '${s}' (${o}), now '${t}' (${i})`),this.updateConnectionStatusDOM(t,e))}}}window.SocketClient=e;class n{constructor(){this.socketClient=null,this.connectionCallbacks=new Set,this.eventUpdateCallbacks=new Set,this.socketClient=new e,window.socketClient=this.socketClient,this.setupSocketEventHandlers(),setTimeout(()=>{this.updateInitialConnectionStatus()},100),console.log("Socket manager initialized")}setupSocketEventHandlers(){document.addEventListener("socketConnectionStatus",t=>{console.log(`SocketManager: Processing connection status update: ${t.detail.status} (${t.detail.type})`),this.handleConnectionStatusChange(t.detail.status,t.detail.type),this.connectionCallbacks.forEach(e=>{try{e(t.detail.status,t.detail.type)}catch(n){console.error("Error in connection callback:",n)}})}),this.socketClient&&this.socketClient.onEventUpdate(t=>{this.eventUpdateCallbacks.forEach(e=>{try{e(t)}catch(n){console.error("Error in event update callback:",n)}})})}handleConnectionStatusChange(t,e){this.updateConnectionStatus(t,e),"connected"===e&&this.socketClient&&this.socketClient.socket&&this.setupGitBranchListener()}updateInitialConnectionStatus(){console.log("SocketManager: Updating initial connection status"),this.socketClient&&"function"==typeof this.socketClient.checkAndUpdateStatus?(console.log("SocketManager: Using socket client checkAndUpdateStatus method"),this.socketClient.checkAndUpdateStatus()):this.socketClient&&this.socketClient.socket?(console.log("SocketManager: Checking socket state directly",{connected:this.socketClient.socket.connected,connecting:this.socketClient.socket.connecting,isConnecting:this.socketClient.isConnecting,isConnected:this.socketClient.isConnected}),this.socketClient.socket.connected?(console.log("SocketManager: Socket is already connected, updating status"),this.updateConnectionStatus("Connected","connected")):this.socketClient.isConnecting||this.socketClient.socket.connecting?(console.log("SocketManager: Socket is connecting, updating status"),this.updateConnectionStatus("Connecting...","connecting")):(console.log("SocketManager: Socket is disconnected, updating status"),this.updateConnectionStatus("Disconnected","disconnected"))):(console.log("SocketManager: No socket client or socket found, setting disconnected status"),this.updateConnectionStatus("Disconnected","disconnected")),setTimeout(()=>{console.log("SocketManager: Secondary status check after 1 second"),this.socketClient&&this.socketClient.socket&&this.socketClient.socket.connected&&(console.log("SocketManager: Socket connected in secondary check, updating status"),this.updateConnectionStatus("Connected","connected"))},1e3)}setupGitBranchListener(){this.socketClient.socket.off("git_branch_response"),this.socketClient.socket.on("git_branch_response",t=>{if(t.success){const e=document.getElementById("footer-git-branch");e&&(e.textContent=t.branch||"unknown"),e&&(e.style.display="inline")}else console.error("Git branch request failed:",t.error)})}updateConnectionStatus(t,e){const n=document.getElementById("connection-status");if(n){if(n.querySelector("span")){const e="●";n.innerHTML=`<span>${e}</span> ${t}`}else n.textContent=t;n.className=`status-badge status-${e}`,console.log(`SocketManager: UI updated - status: '${t}' (${e})`)}else console.error("SocketManager: Could not find connection-status element in DOM")}connect(t){this.socketClient&&this.socketClient.connect(t)}disconnect(){this.socketClient&&this.socketClient.disconnect()}isConnected(){return this.socketClient&&this.socketClient.isConnected}isConnecting(){return this.socketClient&&this.socketClient.isConnecting}getSocketClient(){return this.socketClient}getSocket(){return this.socketClient?this.socketClient.socket:null}onConnectionStatusChange(t){this.connectionCallbacks.add(t)}offConnectionStatusChange(t){this.connectionCallbacks.delete(t)}onEventUpdate(t){this.eventUpdateCallbacks.add(t)}offEventUpdate(t){this.eventUpdateCallbacks.delete(t)}toggleConnectionControls(){const t=document.getElementById("connection-controls-row"),e=document.getElementById("connection-toggle-btn");if(t&&e){t.classList.contains("show")?(t.classList.remove("show"),t.style.display="none",e.textContent="Connection Settings"):(t.classList.add("show"),t.style.display="block",e.textContent="Hide Settings")}}setupConnectionControls(){const t=document.getElementById("connect-btn"),e=document.getElementById("disconnect-btn"),n=document.getElementById("connection-toggle-btn");t&&t.addEventListener("click",()=>{const t=document.getElementById("port-input").value||8765;this.connect(t)}),e&&e.addEventListener("click",()=>{this.disconnect()}),n&&n.addEventListener("click",()=>{this.toggleConnectionControls()})}initializeFromURL(t){const e=t.get("port"),n=document.getElementById("port-input");let s=e;s||"http:"!==window.location.protocol||(s=window.location.port||"8765"),s||(s=n?.value||"8765"),n&&(n.value=s);!("false"!==t.get("connect"))||this.isConnected()||this.isConnecting()||this.connect(s)}}class s{constructor(){this.currentTab="events",this.autoScroll=!0,this.selectedCard={tab:null,index:null,type:null,data:null},this.tabNavigation={events:{selectedIndex:-1,items:[]},agents:{selectedIndex:-1,items:[]},tools:{selectedIndex:-1,items:[]},files:{selectedIndex:-1,items:[]}},this.setupEventHandlers(),console.log("UI state manager initialized")}setupEventHandlers(){this.setupTabNavigation(),this.setupUnifiedKeyboardNavigation()}setupTabNavigation(){document.querySelectorAll(".tab-button").forEach(t=>{t.addEventListener("click",()=>{const e=this.getTabNameFromButton(t);this.switchTab(e)})})}setupUnifiedKeyboardNavigation(){document.addEventListener("keydown",t=>{document.activeElement&&["INPUT","TEXTAREA","SELECT"].includes(document.activeElement.tagName)||("ArrowUp"===t.key||"ArrowDown"===t.key?(t.preventDefault(),this.handleUnifiedArrowNavigation("ArrowDown"===t.key?1:-1)):"Enter"===t.key?(t.preventDefault(),this.handleUnifiedEnterKey()):"Escape"===t.key&&this.clearUnifiedSelection())})}getTabNameFromButton(t){const e=t.textContent.toLowerCase();return e.includes("events")?"events":e.includes("agents")?"agents":e.includes("tools")?"tools":e.includes("files")?"files":"events"}switchTab(t){console.log(`[DEBUG] switchTab called with tabName: ${t}`);const e=this.currentTab;this.currentTab=t,document.querySelectorAll(".tab-button").forEach(e=>{e.classList.remove("active"),this.getTabNameFromButton(e)===t&&e.classList.add("active")}),document.querySelectorAll(".tab-content").forEach(t=>{t.classList.remove("active")});const n=document.getElementById(`${t}-tab`);n&&n.classList.add("active"),this.clearUnifiedSelection(),document.dispatchEvent(new CustomEvent("tabChanged",{detail:{newTab:t,previousTab:e}})),setTimeout(()=>{this.autoScroll&&this.scrollCurrentTabToBottom()},100)}handleUnifiedArrowNavigation(t){const e=this.tabNavigation[this.currentTab];if(!e)return;let n=e.selectedIndex+t;0!==e.items.length&&(n<0?n=e.items.length-1:n>=e.items.length&&(n=0),this.selectCardByIndex(this.currentTab,n))}handleUnifiedEnterKey(){const t=this.tabNavigation[this.currentTab];if(!t||-1===t.selectedIndex)return;const e=t.items[t.selectedIndex];e&&e.onclick&&e.onclick()}clearUnifiedSelection(){Object.keys(this.tabNavigation).forEach(t=>{this.tabNavigation[t].selectedIndex=-1}),this.clearCardSelection()}updateTabNavigationItems(){const t=this.tabNavigation[this.currentTab];if(!t)return;let e;switch(this.currentTab){case"events":e="#events-list .event-item";break;case"agents":e="#agents-list .event-item";break;case"tools":e="#tools-list .event-item";break;case"files":e="#files-list .event-item"}e&&(t.items=Array.from(document.querySelectorAll(e)))}selectCardByIndex(t,e){const n=this.tabNavigation[t];if(!n||e<0||e>=n.items.length)return;n.selectedIndex=e,this.updateUnifiedSelectionUI();n.items[e]&&this.selectCard(t,e,this.getCardType(t),e),this.showCardDetails(t,e)}updateUnifiedSelectionUI(){document.querySelectorAll(".event-item.keyboard-selected").forEach(t=>{t.classList.remove("keyboard-selected")});const t=this.tabNavigation[this.currentTab];t&&-1!==t.selectedIndex&&t.items[t.selectedIndex]&&t.items[t.selectedIndex].classList.add("keyboard-selected")}showCardDetails(t,e){document.dispatchEvent(new CustomEvent("showCardDetails",{detail:{tabName:t,index:e}}))}selectCard(t,e,n,s){this.clearCardSelection(),this.selectedCard={tab:t,index:e,type:n,data:s},this.updateCardSelectionUI(),console.log("Card selected:",this.selectedCard)}clearCardSelection(){document.querySelectorAll(".event-item.selected, .file-item.selected").forEach(t=>{t.classList.remove("selected")}),this.selectedCard={tab:null,index:null,type:null,data:null}}updateCardSelectionUI(){if(!this.selectedCard.tab||null===this.selectedCard.index)return;let t;switch(this.selectedCard.tab){case"events":t=document.getElementById("events-list");break;case"agents":t=document.getElementById("agents-list");break;case"tools":t=document.getElementById("tools-list");break;case"files":t=document.getElementById("files-list")}if(t){const e=t.querySelectorAll(".event-item, .file-item");e[this.selectedCard.index]&&e[this.selectedCard.index].classList.add("selected")}}getCardType(t){switch(t){case"events":return"event";case"agents":return"agent";case"tools":return"tool";case"files":return"file";default:return"unknown"}}scrollCurrentTabToBottom(){const t=`${this.currentTab}-list`,e=document.getElementById(t);e&&this.autoScroll&&(e.scrollTop=e.scrollHeight)}clearSelection(){this.clearCardSelection(),this.clearUnifiedSelection()}getCurrentTab(){return this.currentTab}getSelectedCard(){return{...this.selectedCard}}getTabNavigation(){return{...this.tabNavigation}}setAutoScroll(t){this.autoScroll=t}getAutoScroll(){return this.autoScroll}}export{n as S,s as U};
|
|
2
|
+
//# sourceMappingURL=socket-client.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
class e{constructor(e,t){this.container=document.getElementById(e),this.socketClient=t,this.events=[],this.filteredEvents=[],this.selectedEventIndex=-1,this.filteredEventElements=[],this.autoScroll=!0,this.searchFilter="",this.typeFilter="",this.sessionFilter="",this.eventTypeCount={},this.availableEventTypes=new Set,this.errorCount=0,this.eventsThisMinute=0,this.lastMinute=(new Date).getMinutes(),this.init()}init(){this.setupEventHandlers(),this.setupKeyboardNavigation(),this.socketClient.onEventUpdate((e,t)=>{this.events=Array.isArray(e)?e:[],this.updateDisplay()})}setupEventHandlers(){const e=document.getElementById("events-search-input");e&&e.addEventListener("input",e=>{this.searchFilter=e.target.value.toLowerCase(),this.applyFilters()});const t=document.getElementById("events-type-filter");t&&t.addEventListener("change",e=>{this.typeFilter=e.target.value,this.applyFilters()})}setupKeyboardNavigation(){console.log("EventViewer: Keyboard navigation handled by unified Dashboard system")}handleArrowNavigation(e){if(0===this.filteredEventElements.length)return;let t=this.selectedEventIndex+e;t>=this.filteredEventElements.length?t=0:t<0&&(t=this.filteredEventElements.length-1),this.showEventDetails(t)}applyFilters(){this.events&&Array.isArray(this.events)||(console.warn("EventViewer: events array is not initialized, using empty array"),this.events=[]),this.filteredEvents=this.events.filter(e=>{if(this.searchFilter){if(![e.type||"",e.subtype||"",JSON.stringify(e.data||{})].join(" ").toLowerCase().includes(this.searchFilter))return!1}if(this.typeFilter){const t=e.type&&""!==e.type.trim()?e.type:"";if((e.subtype&&t?`${t}.${e.subtype}`:t)!==this.typeFilter)return!1}return!(this.sessionFilter&&""!==this.sessionFilter&&(!e.data||e.data.session_id!==this.sessionFilter))}),this.renderEvents(),this.updateMetrics()}updateEventTypeDropdown(){const e=document.getElementById("events-type-filter");if(!e)return;const t=new Set;this.events&&Array.isArray(this.events)||(console.warn("EventViewer: events array is not initialized in updateEventTypeDropdown"),this.events=[]),this.events.forEach(e=>{if(e.type&&""!==e.type.trim()){const n=e.subtype?`${e.type}.${e.subtype}`:e.type;t.add(n)}});const n=Array.from(t).sort(),s=Array.from(this.availableEventTypes).sort();if(JSON.stringify(n)===JSON.stringify(s))return;this.availableEventTypes=t;const i=e.value;e.innerHTML='<option value="">All Events</option>';Array.from(t).sort().forEach(t=>{const n=document.createElement("option");n.value=t,n.textContent=t,e.appendChild(n)}),i&&t.has(i)?e.value=i:i&&!t.has(i)&&(e.value="",this.typeFilter="")}updateDisplay(){this.updateEventTypeDropdown(),this.applyFilters()}renderEvents(){const e=document.getElementById("events-list");if(!e)return;if(0===this.filteredEvents.length)return e.innerHTML=`\n <div class="no-events">\n ${0===this.events.length?"Connect to Socket.IO server to see events...":"No events match current filters..."}\n </div>\n `,void(this.filteredEventElements=[]);const t=this.filteredEvents.map((e,t)=>{const n=new Date(e.timestamp).toLocaleTimeString();return`\n <div class="event-item single-row ${e.type?`event-${e.type}`:"event-default"} ${t===this.selectedEventIndex?"selected":""}"\n onclick="eventViewer.showEventDetails(${t})"\n data-index="${t}">\n <span class="event-single-row-content">\n <span class="event-content-main">${this.formatSingleRowEventContent(e)}</span>\n <span class="event-timestamp">${n}</span>\n </span>\n ${this.createInlineEditDiffViewer(e,t)}\n </div>\n `}).join("");e.innerHTML=t,this.filteredEventElements=Array.from(e.querySelectorAll(".event-item")),window.dashboard&&"events"===window.dashboard.currentTab&&window.dashboard.tabNavigation&&window.dashboard.tabNavigation.events&&(window.dashboard.tabNavigation.events.items=this.filteredEventElements),this.autoScroll&&this.filteredEvents.length>0&&(e.scrollTop=e.scrollHeight)}formatEventType(e){return e.subtype?`${e.type}.${e.subtype}`:e.type||"unknown"}formatEventData(e){if(!e.data)return"No data";switch(e.type){case"session":return this.formatSessionEvent(e);case"claude":return this.formatClaudeEvent(e);case"agent":return this.formatAgentEvent(e);case"hook":return this.formatHookEvent(e);case"todo":return this.formatTodoEvent(e);case"memory":return this.formatMemoryEvent(e);case"log":return this.formatLogEvent(e);default:return this.formatGenericEvent(e)}}formatSessionEvent(e){const t=e.data;return"started"===e.subtype?`<strong>Session started:</strong> ${t.session_id||"Unknown"}`:"ended"===e.subtype?`<strong>Session ended:</strong> ${t.session_id||"Unknown"}`:`<strong>Session:</strong> ${JSON.stringify(t)}`}formatClaudeEvent(e){const t=e.data;if("request"===e.subtype){const e=t.prompt||t.message||"";return`<strong>Request:</strong> ${e.length>100?e.substring(0,100)+"...":e}`}if("response"===e.subtype){const e=t.response||t.content||"";return`<strong>Response:</strong> ${e.length>100?e.substring(0,100)+"...":e}`}return`<strong>Claude:</strong> ${JSON.stringify(t)}`}formatAgentEvent(e){const t=e.data;return"loaded"===e.subtype?`<strong>Agent loaded:</strong> ${t.agent_type||t.name||"Unknown"}`:"executed"===e.subtype?`<strong>Agent executed:</strong> ${t.agent_type||t.name||"Unknown"}`:`<strong>Agent:</strong> ${JSON.stringify(t)}`}formatHookEvent(e){const t=e.data,n=t.event_type||e.subtype||"unknown";switch(n){case"user_prompt":const s=t.prompt_text||t.prompt_preview||"";return`<strong>User Prompt:</strong> ${(s.length>80?s.substring(0,80)+"...":s)||"No prompt text"}`;case"pre_tool":const i=t.tool_name||"Unknown tool";return`<strong>Pre-Tool (${t.operation_type||"operation"}):</strong> ${i}`;case"post_tool":const o=t.tool_name||"Unknown tool";return`<strong>Post-Tool (${t.success?"success":t.status||"failed"}):</strong> ${o}${t.duration_ms?` (${t.duration_ms}ms)`:""}`;case"notification":return`<strong>Notification (${t.notification_type||"notification"}):</strong> ${t.message_preview||t.message||"No message"}`;case"stop":const r=t.reason||"unknown";return`<strong>Stop (${t.stop_type||"normal"}):</strong> ${r}`;case"subagent_stop":return`<strong>Subagent Stop (${t.agent_type||"unknown agent"}):</strong> ${t.reason||"unknown"}`;default:const a=t.hook_name||t.name||t.event_type||"Unknown";return`<strong>Hook ${e.subtype||n}:</strong> ${a}`}}formatTodoEvent(e){const t=e.data;if(t.todos&&Array.isArray(t.todos)){const e=t.todos.length;return`<strong>Todo updated:</strong> ${e} item${1!==e?"s":""}`}return`<strong>Todo:</strong> ${JSON.stringify(t)}`}formatMemoryEvent(e){const t=e.data;return`<strong>Memory ${t.operation||"unknown"}:</strong> ${t.key||"Unknown key"}`}formatLogEvent(e){const t=e.data,n=t.level||"info",s=t.message||"",i=s.length>80?s.substring(0,80)+"...":s;return`<strong>[${n.toUpperCase()}]</strong> ${i}`}formatGenericEvent(e){const t=e.data;return"string"==typeof t?t.length>100?t.substring(0,100)+"...":t:JSON.stringify(t)}formatSingleRowEventContent(e){const t=this.formatEventType(e),n=e.data||{};let s="",i="";switch(e.type){case"hook":const t=e.tool_name||n.tool_name||"Unknown",o=e.subtype||"Unknown",r=this.getHookDisplayName(o,n);i=this.getEventCategory(e),s=`${r} (${i}): ${t}`;break;case"agent":i="agent_operations",s=`${e.subagent_type||n.subagent_type||"PM"} ${e.subtype||"action"}`;break;case"todo":i="task_management",s=`TodoWrite (${n.todos?n.todos.length:0} items)`;break;case"memory":i="memory_operations",s=`${n.operation||"unknown"} ${n.key||"unknown"}`;break;case"session":i="session_management",s=`Session ${e.subtype||"unknown"}`;break;case"claude":i="claude_interactions",s=`Claude ${e.subtype||"interaction"}`;break;default:i="general",s=e.type||"Unknown Event"}return`${t} ${s}`}getHookDisplayName(e,t){return{pre_tool:"Pre-Tool",post_tool:"Post-Tool",user_prompt:"User-Prompt",stop:"Stop",subagent_stop:"Subagent-Stop",notification:"Notification"}[e]||e.replace("_","-")}getEventCategory(e){const t=e.data||{},n=e.tool_name||t.tool_name||"";return["Read","Write","Edit","MultiEdit"].includes(n)?"file_operations":["Bash","grep","Glob"].includes(n)?"system_operations":"TodoWrite"===n?"task_management":"Task"===n?"agent_delegation":"stop"===e.subtype||"subagent_stop"===e.subtype?"session_control":"general"}showEventDetails(e){if(!this.filteredEvents||!Array.isArray(this.filteredEvents))return void console.warn("EventViewer: filteredEvents array is not initialized");if(e<0||e>=this.filteredEvents.length)return;this.selectedEventIndex=e;const t=this.filteredEvents[e];window.dashboard&&(window.dashboard.tabNavigation&&window.dashboard.tabNavigation.events&&(window.dashboard.tabNavigation.events.selectedIndex=e),window.dashboard.selectCard&&window.dashboard.selectCard("events",e,"event",t)),this.filteredEventElements.forEach((t,n)=>{t.classList.toggle("selected",n===e)}),document.dispatchEvent(new CustomEvent("eventSelected",{detail:{event:t,index:e}}));const n=this.filteredEventElements[e];n&&n.scrollIntoView({behavior:"smooth",block:"nearest"})}clearSelection(){this.selectedEventIndex=-1,this.filteredEventElements.forEach(e=>{e.classList.remove("selected")}),window.dashboard&&(window.dashboard.tabNavigation&&window.dashboard.tabNavigation.events&&(window.dashboard.tabNavigation.events.selectedIndex=-1),window.dashboard.clearCardSelection&&window.dashboard.clearCardSelection()),document.dispatchEvent(new CustomEvent("eventSelectionCleared"))}updateMetrics(){this.eventTypeCount={},this.errorCount=0,this.events&&Array.isArray(this.events)||(console.warn("EventViewer: events array is not initialized in updateMetrics"),this.events=[]),this.events.forEach(e=>{const t=e.type||"unknown";this.eventTypeCount[t]=(this.eventTypeCount[t]||0)+1,"log"===e.type&&e.data&&["error","critical"].includes(e.data.level)&&this.errorCount++});const e=(new Date).getMinutes();e!==this.lastMinute&&(this.lastMinute=e,this.eventsThisMinute=0);const t=new Date(Date.now()-6e4);this.eventsThisMinute=this.events.filter(e=>new Date(e.timestamp)>t).length,this.updateMetricsUI()}updateMetricsUI(){const e=document.getElementById("total-events"),t=document.getElementById("events-per-minute"),n=document.getElementById("unique-types"),s=document.getElementById("error-count");e&&(e.textContent=this.events.length),t&&(t.textContent=this.eventsThisMinute),n&&(n.textContent=Object.keys(this.eventTypeCount).length),s&&(s.textContent=this.errorCount)}exportEvents(){const e=JSON.stringify(this.filteredEvents,null,2),t=new Blob([e],{type:"application/json"}),n=URL.createObjectURL(t),s=document.createElement("a");s.href=n,s.download=`claude-mpm-events-${(new Date).toISOString().split("T")[0]}.json`,s.click(),URL.revokeObjectURL(n)}clearEvents(){this.socketClient.clearEvents(),this.selectedEventIndex=-1,this.updateDisplay()}setSessionFilter(e){this.sessionFilter=e,this.applyFilters()}getFilters(){return{search:this.searchFilter,type:this.typeFilter,session:this.sessionFilter}}getFilteredEvents(){return this.filteredEvents}getAllEvents(){return this.events}createInlineEditDiffViewer(e,t){const n=e.data||{},s=e.tool_name||n.tool_name||"";if(!["Edit","MultiEdit"].includes(s))return"";let i=[];if("Edit"===s){const t=e.tool_parameters||n.tool_parameters||{};t.old_string&&t.new_string&&i.push({old_string:t.old_string,new_string:t.new_string,file_path:t.file_path||"unknown"})}else if("MultiEdit"===s){const t=e.tool_parameters||n.tool_parameters||{};t.edits&&Array.isArray(t.edits)&&(i=t.edits.map(e=>({...e,file_path:t.file_path||"unknown"})))}if(0===i.length)return"";const o=`edit-diff-${t}`,r=i.length>1;let a="";return i.forEach((e,t)=>{const n=this.createDiffHtml(e.old_string,e.new_string);a+=`\n <div class="edit-diff-section">\n ${r?`<div class="edit-diff-header">Edit ${t+1}</div>`:""}\n <div class="diff-content">${n}</div>\n </div>\n `}),`\n <div class="inline-edit-diff-viewer">\n <div class="diff-toggle-header" onclick="eventViewer.toggleEditDiff('${o}', event)">\n <span class="diff-toggle-icon">📋</span>\n <span class="diff-toggle-text">Show ${r?i.length+" edits":"edit"}</span>\n <span class="diff-toggle-arrow">▼</span>\n </div>\n <div id="${o}" class="diff-content-container" style="display: none;">\n ${a}\n </div>\n </div>\n `}createDiffHtml(e,t){const n=e.split("\n"),s=t.split("\n");let i="",o=0,r=0;for(;o<n.length||r<s.length;){const e=o<n.length?n[o]:null,t=r<s.length?s[r]:null;null===e?(i+=`<div class="diff-line diff-added">+ ${this.escapeHtml(t)}</div>`,r++):null===t?(i+=`<div class="diff-line diff-removed">- ${this.escapeHtml(e)}</div>`,o++):e===t?(i+=`<div class="diff-line diff-unchanged"> ${this.escapeHtml(e)}</div>`,o++,r++):(i+=`<div class="diff-line diff-removed">- ${this.escapeHtml(e)}</div>`,i+=`<div class="diff-line diff-added">+ ${this.escapeHtml(t)}</div>`,o++,r++)}return`<div class="diff-container">${i}</div>`}toggleEditDiff(e,t){t.stopPropagation();const n=document.getElementById(e),s=t.currentTarget.querySelector(".diff-toggle-arrow");if(n){const e="none"!==n.style.display;n.style.display=e?"none":"block",s&&(s.textContent=e?"▼":"▲")}}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}window.EventViewer=e;class t{constructor(e,t){this.eventViewer=e,this.agentInference=t,this.agentEvents=[],this.filteredAgentEvents=[],this.filteredToolEvents=[],this.filteredFileEvents=[],this.selectedSessionId=null,this.fileTrackingCache=new Map,this.trackingCheckTimeout=3e4,console.log("Event processor initialized")}getFilteredEventsForTab(e){const t=this.eventViewer.events;console.log(`getFilteredEventsForTab(${e}) - using RAW events: ${t.length} total`);const n=window.sessionManager;if(n&&n.selectedSessionId){const e=n.getEventsForSession(n.selectedSessionId);return console.log(`Filtering by session ${n.selectedSessionId}: ${e.length} events`),e}return t}applyAgentsFilters(e){const t=document.getElementById("agents-search-input"),n=document.getElementById("agents-type-filter"),s=t?t.value.toLowerCase():"",i=n?n.value:"";return e.filter(e=>{if(s){if(![e.agentName||"",e.type||"",e.isImplied?"implied":"explicit"].join(" ").toLowerCase().includes(s))return!1}if(i){if(!(e.agentName||"unknown").toLowerCase().includes(i.toLowerCase()))return!1}return!0})}applyToolsFilters(e){const t=document.getElementById("tools-search-input"),n=document.getElementById("tools-type-filter"),s=t?t.value.toLowerCase():"",i=n?n.value:"";return e.filter(e=>{if(s){if(![e.tool_name||"",e.agent_type||"",e.type||"",e.subtype||""].join(" ").toLowerCase().includes(s))return!1}if(i){if((e.tool_name||"")!==i)return!1}return!0})}applyToolCallFilters(e){const t=document.getElementById("tools-search-input"),n=document.getElementById("tools-type-filter"),s=t?t.value.toLowerCase():"",i=n?n.value:"";return e.filter(([e,t])=>{if(s){if(![t.tool_name||"",t.agent_type||"","tool_call"].join(" ").toLowerCase().includes(s))return!1}if(i){if((t.tool_name||"")!==i)return!1}return!0})}applyFilesFilters(e){const t=document.getElementById("files-search-input"),n=document.getElementById("files-type-filter"),s=t?t.value.toLowerCase():"",i=n?n.value:"";return e.filter(([e,t])=>{if(this.selectedSessionId){const e=t.operations.filter(e=>e.sessionId===this.selectedSessionId);if(0===e.length)return!1;t={...t,operations:e,lastOperation:e[e.length-1]?.timestamp||t.lastOperation}}if(s){if(![e,...t.operations.map(e=>e.operation),...t.operations.map(e=>e.agent)].join(" ").toLowerCase().includes(s))return!1}if(i){if(!t.operations.map(e=>e.operation).includes(i))return!1}return!0})}extractOperation(e){if(!e)return"unknown";const t=e.toLowerCase();return t.includes("read")?"read":t.includes("write")?"write":t.includes("edit")?"edit":t.includes("create")?"create":t.includes("delete")?"delete":t.includes("move")||t.includes("rename")?"move":"other"}extractToolFromHook(e){if(!e)return"";const t=e.match(/^(?:Pre|Post)(.+)Use$/);return t?t[1]:""}extractToolFromSubtype(e){if(!e)return"";if(e.includes("_")){return e.split("_")[0]||""}return e}extractToolTarget(e,t,n){const s=t||n||{};switch(e?.toLowerCase()){case"read":case"write":case"edit":return s.file_path||s.path||"";case"bash":return s.command||"";case"grep":return s.pattern||"";case"task":return s.subagent_type||s.agent_type||"";default:const e=Object.keys(s),t=["path","file_path","command","pattern","query","target"];for(const n of t)if(s[n])return s[n];return e.length>0?`${e[0]}: ${s[e[0]]}`:""}}generateAgentHTML(e){const t=this.agentInference.getUniqueAgentInstances();return this.applyAgentsFilters(t).map((e,t)=>{const n=e.agentName,s=this.formatTimestamp(e.firstTimestamp||e.timestamp),i=e.isImplied?"implied":"explicit",o=e.totalEventCount||e.eventCount||0;return`\n <div class="event-item single-row event-agent" onclick="${`dashboard.selectCard('agents', ${t}, 'agent_instance', '${e.id}'); dashboard.showAgentInstanceDetails('${e.id}');`}">\n <span class="event-single-row-content">\n <span class="event-content-main">${`${n} (${i}, ${o} events)`}</span>\n <span class="event-timestamp">${s}</span>\n </span>\n </div>\n `}).join("")}generateToolHTML(e){return this.applyToolCallFilters(e).map(([e,t],n)=>{const s=t.tool_name||"Unknown",i=t.agent_type||"Unknown",o=this.formatTimestamp(t.timestamp);return`\n <div class="event-item single-row event-tool ${"completed"===(t.post_event?"completed":"pending")?"status-success":"status-pending"}" onclick="dashboard.selectCard('tools', ${n}, 'toolCall', '${e}'); dashboard.showToolCallDetails('${e}')">\n <span class="event-single-row-content">\n <span class="event-content-main">${`${s} (${"pm"===i.toLowerCase()?"pm":i})`}</span>\n <span class="event-timestamp">${o}</span>\n </span>\n </div>\n `}).join("")}generateFileHTML(e){return this.applyFilesFilters(e).map(([e,t],n)=>{const s=t.operations.map(e=>e.operation),i=this.formatTimestamp(t.lastOperation),o={};s.forEach(e=>{o[e]=(o[e]||0)+1});const r=Object.entries(o).map(([e,t])=>`${e}(${t})`).join(", "),a=[...new Set(t.operations.map(e=>e.agent))],l=a.length>1?`by ${a.length} agents`:`by ${a[0]||"unknown"}`;return`\n <div class="event-item single-row file-item" onclick="dashboard.selectCard('files', ${n}, 'file', '${e}'); dashboard.showFileDetails('${e}')">\n <span class="event-single-row-content">\n <span class="event-content-main">${`${this.getRelativeFilePath(e)} ${r} ${l}`}</span>\n <span class="event-timestamp">${i}</span>\n </span>\n </div>\n `}).join("")}getFileOperationIcon(e){return e.includes("write")||e.includes("create")?"📝":e.includes("edit")?"✏️":e.includes("read")?"👁️":e.includes("delete")?"🗑️":e.includes("move")?"📦":"📄"}getRelativeFilePath(e){if(!e)return"";const t=e.split("/");return t.length>3?".../"+t.slice(-2).join("/"):e}formatTimestamp(e){if(!e)return"";return new Date(e).toLocaleTimeString()}setSelectedSessionId(e){this.selectedSessionId=e}getSelectedSessionId(){return this.selectedSessionId}getUniqueToolInstances(e){return this.applyToolCallFilters(e)}getUniqueFileInstances(e){return this.applyFilesFilters(e)}async isFileTracked(e,t){const n=`${t}:${e}`,s=Date.now(),i=this.fileTrackingCache.get(n);if(i&&s-i.timestamp<this.trackingCheckTimeout)return i.is_tracked;try{const i=window.socket;return i?new Promise(o=>{const r=t=>{if(t.file_path===e){const e=t.success&&t.is_tracked;this.fileTrackingCache.set(n,{is_tracked:e,timestamp:s}),i.off("file_tracked_response",r),o(e)}};i.on("file_tracked_response",r),i.emit("check_file_tracked",{file_path:e,working_dir:t}),setTimeout(()=>{i.off("file_tracked_response",r),o(!1)},5e3)}):(console.warn("No socket connection available for git tracking check"),!1)}catch(o){return console.error("Error checking file tracking status:",o),!1}}generateGitDiffIcon(e,t,n){const s=`git-icon-${e.replace(/[^a-zA-Z0-9]/g,"-")}-${t}`,i=`\n <span id="${s}" class="git-diff-icon"\n onclick="event.stopPropagation(); showGitDiffModal('${e}', '${t}')"\n title="View git diff for this file operation"\n style="margin-left: 8px; cursor: pointer; font-size: 16px;">\n 📋\n </span>\n `;return this.isFileTracked(e,n).then(e=>{const t=document.getElementById(s);t&&(e?(t.innerHTML="📋",t.title="View git diff for this file operation",t.classList.add("tracked-file")):(t.innerHTML="📋❌",t.title="File not tracked by git - click to see details",t.classList.add("untracked-file")))}).catch(e=>{console.error("Error updating git diff icon:",e)}),i}showAgentInstanceDetails(e){const t=this.agentInference.getPMDelegations().get(e);if(!t)return void console.error("Agent instance not found:",e);console.log("Showing agent instance details for:",e,t);const n=`\n <div class="agent-instance-details">\n <h3>Agent Instance: ${t.agentName}</h3>\n <p><strong>Type:</strong> ${t.isImplied?"Implied PM Delegation":"Explicit PM Delegation"}</p>\n <p><strong>Start Time:</strong> ${this.formatTimestamp(t.timestamp)}</p>\n <p><strong>Event Count:</strong> ${t.agentEvents.length}</p>\n <p><strong>Session:</strong> ${t.sessionId}</p>\n ${t.pmCall?`<p><strong>PM Call:</strong> Task delegation to ${t.agentName}</p>`:"<p><strong>Note:</strong> Implied delegation (no explicit PM call found)</p>"}\n </div>\n `;console.log("Agent instance details HTML:",n)}}export{e as E,t as a};
|
|
1
|
+
class e{constructor(e,t){this.container=document.getElementById(e),this.socketClient=t,this.events=[],this.filteredEvents=[],this.selectedEventIndex=-1,this.filteredEventElements=[],this.autoScroll=!0,this.searchFilter="",this.typeFilter="",this.sessionFilter="",this.eventTypeCount={},this.availableEventTypes=new Set,this.errorCount=0,this.eventsThisMinute=0,this.lastMinute=(new Date).getMinutes(),this.init()}init(){this.setupEventHandlers(),this.setupKeyboardNavigation(),this.socketClient.onEventUpdate((e,t)=>{this.events=Array.isArray(e)?e:[],this.updateDisplay()})}setupEventHandlers(){const e=document.getElementById("events-search-input");e&&e.addEventListener("input",e=>{this.searchFilter=e.target.value.toLowerCase(),this.applyFilters()});const t=document.getElementById("events-type-filter");t&&t.addEventListener("change",e=>{this.typeFilter=e.target.value,this.applyFilters()})}setupKeyboardNavigation(){console.log("EventViewer: Keyboard navigation handled by unified Dashboard system")}handleArrowNavigation(e){if(0===this.filteredEventElements.length)return;let t=this.selectedEventIndex+e;t>=this.filteredEventElements.length?t=0:t<0&&(t=this.filteredEventElements.length-1),this.showEventDetails(t)}applyFilters(){this.events&&Array.isArray(this.events)||(console.warn("EventViewer: events array is not initialized, using empty array"),this.events=[]),this.filteredEvents=this.events.filter(e=>{if(this.searchFilter){if(![e.type||"",e.subtype||"",JSON.stringify(e.data||{})].join(" ").toLowerCase().includes(this.searchFilter))return!1}if(this.typeFilter){const t=e.type&&""!==e.type.trim()?e.type:"";if((e.subtype&&t?`${t}.${e.subtype}`:t)!==this.typeFilter)return!1}return!(this.sessionFilter&&""!==this.sessionFilter&&(!e.data||e.data.session_id!==this.sessionFilter))}),this.renderEvents(),this.updateMetrics()}updateEventTypeDropdown(){const e=document.getElementById("events-type-filter");if(!e)return;const t=new Set;this.events&&Array.isArray(this.events)||(console.warn("EventViewer: events array is not initialized in updateEventTypeDropdown"),this.events=[]),this.events.forEach(e=>{if(e.type&&""!==e.type.trim()){const n=e.subtype?`${e.type}.${e.subtype}`:e.type;t.add(n)}});const n=Array.from(t).sort(),s=Array.from(this.availableEventTypes).sort();if(JSON.stringify(n)===JSON.stringify(s))return;this.availableEventTypes=t;const i=e.value;e.innerHTML='<option value="">All Events</option>';Array.from(t).sort().forEach(t=>{const n=document.createElement("option");n.value=t,n.textContent=t,e.appendChild(n)}),i&&t.has(i)?e.value=i:i&&!t.has(i)&&(e.value="",this.typeFilter="")}updateDisplay(){this.updateEventTypeDropdown(),this.applyFilters()}renderEvents(){const e=document.getElementById("events-list");if(!e)return;if(0===this.filteredEvents.length)return e.innerHTML=`\n <div class="no-events">\n ${0===this.events.length?"Connect to Socket.IO server to see events...":"No events match current filters..."}\n </div>\n `,void(this.filteredEventElements=[]);const t=this.filteredEvents.map((e,t)=>{const n=new Date(e.timestamp).toLocaleTimeString();return`\n <div class="event-item single-row ${e.type?`event-${e.type}`:"event-default"} ${t===this.selectedEventIndex?"selected":""}"\n onclick="eventViewer.showEventDetails(${t})"\n data-index="${t}">\n <span class="event-single-row-content">\n <span class="event-content-main">${this.formatSingleRowEventContent(e)}</span>\n <span class="event-timestamp">${n}</span>\n </span>\n ${this.createInlineEditDiffViewer(e,t)}\n </div>\n `}).join("");e.innerHTML=t,this.filteredEventElements=Array.from(e.querySelectorAll(".event-item")),window.dashboard&&"events"===window.dashboard.currentTab&&window.dashboard.tabNavigation&&window.dashboard.tabNavigation.events&&(window.dashboard.tabNavigation.events.items=this.filteredEventElements),this.autoScroll&&this.filteredEvents.length>0&&(e.scrollTop=e.scrollHeight)}formatEventType(e){return e.type&&e.subtype?e.type===e.subtype?e.type:`${e.type}.${e.subtype}`:e.type?e.type:e.originalEventName?e.originalEventName:"unknown"}formatEventData(e){if(!e.data)return"No data";switch(e.type){case"session":return this.formatSessionEvent(e);case"claude":return this.formatClaudeEvent(e);case"agent":return this.formatAgentEvent(e);case"hook":return this.formatHookEvent(e);case"todo":return this.formatTodoEvent(e);case"memory":return this.formatMemoryEvent(e);case"log":return this.formatLogEvent(e);default:return this.formatGenericEvent(e)}}formatSessionEvent(e){const t=e.data;return"started"===e.subtype?`<strong>Session started:</strong> ${t.session_id||"Unknown"}`:"ended"===e.subtype?`<strong>Session ended:</strong> ${t.session_id||"Unknown"}`:`<strong>Session:</strong> ${JSON.stringify(t)}`}formatClaudeEvent(e){const t=e.data;if("request"===e.subtype){const e=t.prompt||t.message||"";return`<strong>Request:</strong> ${e.length>100?e.substring(0,100)+"...":e}`}if("response"===e.subtype){const e=t.response||t.content||"";return`<strong>Response:</strong> ${e.length>100?e.substring(0,100)+"...":e}`}return`<strong>Claude:</strong> ${JSON.stringify(t)}`}formatAgentEvent(e){const t=e.data;return"loaded"===e.subtype?`<strong>Agent loaded:</strong> ${t.agent_type||t.name||"Unknown"}`:"executed"===e.subtype?`<strong>Agent executed:</strong> ${t.agent_type||t.name||"Unknown"}`:`<strong>Agent:</strong> ${JSON.stringify(t)}`}formatHookEvent(e){const t=e.data,n=t.event_type||e.subtype||"unknown";switch(n){case"user_prompt":const s=t.prompt_text||t.prompt_preview||"";return`<strong>User Prompt:</strong> ${(s.length>80?s.substring(0,80)+"...":s)||"No prompt text"}`;case"pre_tool":const i=t.tool_name||"Unknown tool";return`<strong>Pre-Tool (${t.operation_type||"operation"}):</strong> ${i}`;case"post_tool":const o=t.tool_name||"Unknown tool";return`<strong>Post-Tool (${t.success?"success":t.status||"failed"}):</strong> ${o}${t.duration_ms?` (${t.duration_ms}ms)`:""}`;case"notification":return`<strong>Notification (${t.notification_type||"notification"}):</strong> ${t.message_preview||t.message||"No message"}`;case"stop":const r=t.reason||"unknown";return`<strong>Stop (${t.stop_type||"normal"}):</strong> ${r}`;case"subagent_stop":return`<strong>Subagent Stop (${t.agent_type||"unknown agent"}):</strong> ${t.reason||"unknown"}`;default:const a=t.hook_name||t.name||t.event_type||"Unknown";return`<strong>Hook ${e.subtype||n}:</strong> ${a}`}}formatTodoEvent(e){const t=e.data;if(t.todos&&Array.isArray(t.todos)){const e=t.todos.length;return`<strong>Todo updated:</strong> ${e} item${1!==e?"s":""}`}return`<strong>Todo:</strong> ${JSON.stringify(t)}`}formatMemoryEvent(e){const t=e.data;return`<strong>Memory ${t.operation||"unknown"}:</strong> ${t.key||"Unknown key"}`}formatLogEvent(e){const t=e.data,n=t.level||"info",s=t.message||"",i=s.length>80?s.substring(0,80)+"...":s;return`<strong>[${n.toUpperCase()}]</strong> ${i}`}formatGenericEvent(e){const t=e.data;return"string"==typeof t?t.length>100?t.substring(0,100)+"...":t:JSON.stringify(t)}formatSingleRowEventContent(e){const t=this.formatEventType(e),n=e.data||{};let s="",i="";switch(e.type){case"hook":const t=e.tool_name||n.tool_name||"Unknown",o=e.subtype||"Unknown",r=this.getHookDisplayName(o,n);i=this.getEventCategory(e),s=`${r} (${i}): ${t}`;break;case"agent":i="agent_operations",s=`${e.subagent_type||n.subagent_type||"PM"} ${e.subtype||"action"}`;break;case"todo":i="task_management",s=`TodoWrite (${n.todos?n.todos.length:0} items)`;break;case"memory":i="memory_operations",s=`${n.operation||"unknown"} ${n.key||"unknown"}`;break;case"session":i="session_management",s=`Session ${e.subtype||"unknown"}`;break;case"claude":i="claude_interactions",s=`Claude ${e.subtype||"interaction"}`;break;default:i="general",s=e.type||"Unknown Event"}return`${t} ${s}`}getHookDisplayName(e,t){const n={pre_tool:"Pre-Tool",post_tool:"Post-Tool",user_prompt:"User-Prompt",stop:"Stop",subagent_stop:"Subagent-Stop",notification:"Notification"};if(n[e])return n[e];return String(e||"unknown").replace(/_/g," ")}getEventCategory(e){const t=e.data||{},n=e.tool_name||t.tool_name||"";return["Read","Write","Edit","MultiEdit"].includes(n)?"file_operations":["Bash","grep","Glob"].includes(n)?"system_operations":"TodoWrite"===n?"task_management":"Task"===n?"agent_delegation":"stop"===e.subtype||"subagent_stop"===e.subtype?"session_control":"general"}showEventDetails(e){if(!this.filteredEvents||!Array.isArray(this.filteredEvents))return void console.warn("EventViewer: filteredEvents array is not initialized");if(e<0||e>=this.filteredEvents.length)return;this.selectedEventIndex=e;const t=this.filteredEvents[e];window.dashboard&&(window.dashboard.tabNavigation&&window.dashboard.tabNavigation.events&&(window.dashboard.tabNavigation.events.selectedIndex=e),window.dashboard.selectCard&&window.dashboard.selectCard("events",e,"event",t)),this.filteredEventElements.forEach((t,n)=>{t.classList.toggle("selected",n===e)}),document.dispatchEvent(new CustomEvent("eventSelected",{detail:{event:t,index:e}}));const n=this.filteredEventElements[e];n&&n.scrollIntoView({behavior:"smooth",block:"nearest"})}clearSelection(){this.selectedEventIndex=-1,this.filteredEventElements.forEach(e=>{e.classList.remove("selected")}),window.dashboard&&(window.dashboard.tabNavigation&&window.dashboard.tabNavigation.events&&(window.dashboard.tabNavigation.events.selectedIndex=-1),window.dashboard.clearCardSelection&&window.dashboard.clearCardSelection()),document.dispatchEvent(new CustomEvent("eventSelectionCleared"))}updateMetrics(){this.eventTypeCount={},this.errorCount=0,this.events&&Array.isArray(this.events)||(console.warn("EventViewer: events array is not initialized in updateMetrics"),this.events=[]),this.events.forEach(e=>{const t=e.type||"unknown";this.eventTypeCount[t]=(this.eventTypeCount[t]||0)+1,"log"===e.type&&e.data&&["error","critical"].includes(e.data.level)&&this.errorCount++});const e=(new Date).getMinutes();e!==this.lastMinute&&(this.lastMinute=e,this.eventsThisMinute=0);const t=new Date(Date.now()-6e4);this.eventsThisMinute=this.events.filter(e=>new Date(e.timestamp)>t).length,this.updateMetricsUI()}updateMetricsUI(){const e=document.getElementById("total-events"),t=document.getElementById("events-per-minute"),n=document.getElementById("unique-types"),s=document.getElementById("error-count");e&&(e.textContent=this.events.length),t&&(t.textContent=this.eventsThisMinute),n&&(n.textContent=Object.keys(this.eventTypeCount).length),s&&(s.textContent=this.errorCount)}exportEvents(){const e=JSON.stringify(this.filteredEvents,null,2),t=new Blob([e],{type:"application/json"}),n=URL.createObjectURL(t),s=document.createElement("a");s.href=n,s.download=`claude-mpm-events-${(new Date).toISOString().split("T")[0]}.json`,s.click(),URL.revokeObjectURL(n)}clearEvents(){this.socketClient.clearEvents(),this.selectedEventIndex=-1,this.updateDisplay()}setSessionFilter(e){this.sessionFilter=e,this.applyFilters()}getFilters(){return{search:this.searchFilter,type:this.typeFilter,session:this.sessionFilter}}getFilteredEvents(){return this.filteredEvents}getAllEvents(){return this.events}createInlineEditDiffViewer(e,t){const n=e.data||{},s=e.tool_name||n.tool_name||"";if(!["Edit","MultiEdit"].includes(s))return"";let i=[];if("Edit"===s){const t=e.tool_parameters||n.tool_parameters||{};t.old_string&&t.new_string&&i.push({old_string:t.old_string,new_string:t.new_string,file_path:t.file_path||"unknown"})}else if("MultiEdit"===s){const t=e.tool_parameters||n.tool_parameters||{};t.edits&&Array.isArray(t.edits)&&(i=t.edits.map(e=>({...e,file_path:t.file_path||"unknown"})))}if(0===i.length)return"";const o=`edit-diff-${t}`,r=i.length>1;let a="";return i.forEach((e,t)=>{const n=this.createDiffHtml(e.old_string,e.new_string);a+=`\n <div class="edit-diff-section">\n ${r?`<div class="edit-diff-header">Edit ${t+1}</div>`:""}\n <div class="diff-content">${n}</div>\n </div>\n `}),`\n <div class="inline-edit-diff-viewer">\n <div class="diff-toggle-header" onclick="eventViewer.toggleEditDiff('${o}', event)">\n <span class="diff-toggle-icon">📋</span>\n <span class="diff-toggle-text">Show ${r?i.length+" edits":"edit"}</span>\n <span class="diff-toggle-arrow">▼</span>\n </div>\n <div id="${o}" class="diff-content-container" style="display: none;">\n ${a}\n </div>\n </div>\n `}createDiffHtml(e,t){const n=e.split("\n"),s=t.split("\n");let i="",o=0,r=0;for(;o<n.length||r<s.length;){const e=o<n.length?n[o]:null,t=r<s.length?s[r]:null;null===e?(i+=`<div class="diff-line diff-added">+ ${this.escapeHtml(t)}</div>`,r++):null===t?(i+=`<div class="diff-line diff-removed">- ${this.escapeHtml(e)}</div>`,o++):e===t?(i+=`<div class="diff-line diff-unchanged"> ${this.escapeHtml(e)}</div>`,o++,r++):(i+=`<div class="diff-line diff-removed">- ${this.escapeHtml(e)}</div>`,i+=`<div class="diff-line diff-added">+ ${this.escapeHtml(t)}</div>`,o++,r++)}return`<div class="diff-container">${i}</div>`}toggleEditDiff(e,t){t.stopPropagation();const n=document.getElementById(e),s=t.currentTarget.querySelector(".diff-toggle-arrow");if(n){const e="none"!==n.style.display;n.style.display=e?"none":"block",s&&(s.textContent=e?"▼":"▲")}}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}window.EventViewer=e;class t{constructor(e,t){this.eventViewer=e,this.agentInference=t,this.agentEvents=[],this.filteredAgentEvents=[],this.filteredToolEvents=[],this.filteredFileEvents=[],this.selectedSessionId=null,this.fileTrackingCache=new Map,this.trackingCheckTimeout=3e4,console.log("Event processor initialized")}getFilteredEventsForTab(e){const t=this.eventViewer.events;console.log(`getFilteredEventsForTab(${e}) - using RAW events: ${t.length} total`);const n=window.sessionManager;if(n&&n.selectedSessionId){const e=n.getEventsForSession(n.selectedSessionId);return console.log(`Filtering by session ${n.selectedSessionId}: ${e.length} events`),e}return t}applyAgentsFilters(e){const t=document.getElementById("agents-search-input"),n=document.getElementById("agents-type-filter"),s=t?t.value.toLowerCase():"",i=n?n.value:"";return e.filter(e=>{if(s){if(![e.agentName||"",e.type||"",e.isImplied?"implied":"explicit"].join(" ").toLowerCase().includes(s))return!1}if(i){if(!(e.agentName||"unknown").toLowerCase().includes(i.toLowerCase()))return!1}return!0})}applyToolsFilters(e){const t=document.getElementById("tools-search-input"),n=document.getElementById("tools-type-filter"),s=t?t.value.toLowerCase():"",i=n?n.value:"";return e.filter(e=>{if(s){if(![e.tool_name||"",e.agent_type||"",e.type||"",e.subtype||""].join(" ").toLowerCase().includes(s))return!1}if(i){if((e.tool_name||"")!==i)return!1}return!0})}applyToolCallFilters(e){const t=document.getElementById("tools-search-input"),n=document.getElementById("tools-type-filter"),s=t?t.value.toLowerCase():"",i=n?n.value:"";return e.filter(([e,t])=>{if(s){if(![t.tool_name||"",t.agent_type||"","tool_call"].join(" ").toLowerCase().includes(s))return!1}if(i){if((t.tool_name||"")!==i)return!1}return!0})}applyFilesFilters(e){const t=document.getElementById("files-search-input"),n=document.getElementById("files-type-filter"),s=t?t.value.toLowerCase():"",i=n?n.value:"";return e.filter(([e,t])=>{if(this.selectedSessionId){const e=t.operations.filter(e=>e.sessionId===this.selectedSessionId);if(0===e.length)return!1;t={...t,operations:e,lastOperation:e[e.length-1]?.timestamp||t.lastOperation}}if(s){if(![e,...t.operations.map(e=>e.operation),...t.operations.map(e=>e.agent)].join(" ").toLowerCase().includes(s))return!1}if(i){if(!t.operations.map(e=>e.operation).includes(i))return!1}return!0})}extractOperation(e){if(!e)return"unknown";const t=e.toLowerCase();return t.includes("read")?"read":t.includes("write")?"write":t.includes("edit")?"edit":t.includes("create")?"create":t.includes("delete")?"delete":t.includes("move")||t.includes("rename")?"move":"other"}extractToolFromHook(e){if(!e)return"";const t=e.match(/^(?:Pre|Post)(.+)Use$/);return t?t[1]:""}extractToolFromSubtype(e){if(!e)return"";if(e.includes("_")){return e.split("_")[0]||""}return e}extractToolTarget(e,t,n){const s=t||n||{};switch(e?.toLowerCase()){case"read":case"write":case"edit":return s.file_path||s.path||"";case"bash":return s.command||"";case"grep":return s.pattern||"";case"task":return s.subagent_type||s.agent_type||"";default:const e=Object.keys(s),t=["path","file_path","command","pattern","query","target"];for(const n of t)if(s[n])return s[n];return e.length>0?`${e[0]}: ${s[e[0]]}`:""}}generateAgentHTML(e){const t=this.agentInference.getUniqueAgentInstances();return this.applyAgentsFilters(t).map((e,t)=>{const n=e.agentName,s=this.formatTimestamp(e.firstTimestamp||e.timestamp),i=e.isImplied?"implied":"explicit",o=e.totalEventCount||e.eventCount||0;return`\n <div class="event-item single-row event-agent" onclick="${`dashboard.selectCard('agents', ${t}, 'agent_instance', '${e.id}'); dashboard.showAgentInstanceDetails('${e.id}');`}">\n <span class="event-single-row-content">\n <span class="event-content-main">${`${n} (${i}, ${o} events)`}</span>\n <span class="event-timestamp">${s}</span>\n </span>\n </div>\n `}).join("")}generateToolHTML(e){return this.applyToolCallFilters(e).map(([e,t],n)=>{const s=t.tool_name||"Unknown",i=t.agent_type||"Unknown",o=this.formatTimestamp(t.timestamp);return`\n <div class="event-item single-row event-tool ${"completed"===(t.post_event?"completed":"pending")?"status-success":"status-pending"}" onclick="dashboard.selectCard('tools', ${n}, 'toolCall', '${e}'); dashboard.showToolCallDetails('${e}')">\n <span class="event-single-row-content">\n <span class="event-content-main">${`${s} (${"pm"===i.toLowerCase()?"pm":i})`}</span>\n <span class="event-timestamp">${o}</span>\n </span>\n </div>\n `}).join("")}generateFileHTML(e){return this.applyFilesFilters(e).map(([e,t],n)=>{const s=t.operations.map(e=>e.operation),i=this.formatTimestamp(t.lastOperation),o={};s.forEach(e=>{o[e]=(o[e]||0)+1});const r=Object.entries(o).map(([e,t])=>`${e}(${t})`).join(", "),a=[...new Set(t.operations.map(e=>e.agent))],l=a.length>1?`by ${a.length} agents`:`by ${a[0]||"unknown"}`;return`\n <div class="event-item single-row file-item" onclick="dashboard.selectCard('files', ${n}, 'file', '${e}'); dashboard.showFileDetails('${e}')">\n <span class="event-single-row-content">\n <span class="event-content-main">${`${this.getRelativeFilePath(e)} ${r} ${l}`}</span>\n <span class="event-timestamp">${i}</span>\n </span>\n </div>\n `}).join("")}getFileOperationIcon(e){return e.includes("write")||e.includes("create")?"📝":e.includes("edit")?"✏️":e.includes("read")?"👁️":e.includes("delete")?"🗑️":e.includes("move")?"📦":"📄"}getRelativeFilePath(e){if(!e)return"";const t=e.split("/");return t.length>3?".../"+t.slice(-2).join("/"):e}formatTimestamp(e){if(!e)return"";return new Date(e).toLocaleTimeString()}setSelectedSessionId(e){this.selectedSessionId=e}getSelectedSessionId(){return this.selectedSessionId}getUniqueToolInstances(e){return this.applyToolCallFilters(e)}getUniqueFileInstances(e){return this.applyFilesFilters(e)}async isFileTracked(e,t){const n=`${t}:${e}`,s=Date.now(),i=this.fileTrackingCache.get(n);if(i&&s-i.timestamp<this.trackingCheckTimeout)return i.is_tracked;try{const i=window.socket;return i?new Promise(o=>{const r=t=>{if(t.file_path===e){const e=t.success&&t.is_tracked;this.fileTrackingCache.set(n,{is_tracked:e,timestamp:s}),i.off("file_tracked_response",r),o(e)}};i.on("file_tracked_response",r),i.emit("check_file_tracked",{file_path:e,working_dir:t}),setTimeout(()=>{i.off("file_tracked_response",r),o(!1)},5e3)}):(console.warn("No socket connection available for git tracking check"),!1)}catch(o){return console.error("Error checking file tracking status:",o),!1}}generateGitDiffIcon(e,t,n){const s=`git-icon-${e.replace(/[^a-zA-Z0-9]/g,"-")}-${t}`,i=`\n <span id="${s}" class="git-diff-icon"\n onclick="event.stopPropagation(); showGitDiffModal('${e}', '${t}')"\n title="View git diff for this file operation"\n style="margin-left: 8px; cursor: pointer; font-size: 16px;">\n 📋\n </span>\n `;return this.isFileTracked(e,n).then(e=>{const t=document.getElementById(s);t&&(e?(t.innerHTML="📋",t.title="View git diff for this file operation",t.classList.add("tracked-file")):(t.innerHTML="📋❌",t.title="File not tracked by git - click to see details",t.classList.add("untracked-file")))}).catch(e=>{console.error("Error updating git diff icon:",e)}),i}showAgentInstanceDetails(e){const t=this.agentInference.getPMDelegations().get(e);if(!t)return void console.error("Agent instance not found:",e);console.log("Showing agent instance details for:",e,t);const n=`\n <div class="agent-instance-details">\n <h3>Agent Instance: ${t.agentName}</h3>\n <p><strong>Type:</strong> ${t.isImplied?"Implied PM Delegation":"Explicit PM Delegation"}</p>\n <p><strong>Start Time:</strong> ${this.formatTimestamp(t.timestamp)}</p>\n <p><strong>Event Count:</strong> ${t.agentEvents.length}</p>\n <p><strong>Session:</strong> ${t.sessionId}</p>\n ${t.pmCall?`<p><strong>PM Call:</strong> Task delegation to ${t.agentName}</p>`:"<p><strong>Note:</strong> Implied delegation (no explicit PM call found)</p>"}\n </div>\n `;console.log("Agent instance details HTML:",n)}}export{e as E,t as a};
|
|
2
2
|
//# sourceMappingURL=event-viewer.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
class e{constructor(e,t){this.agentInference=e,this.workingDirectoryManager=t,this.fileOperations=new Map,this.toolCalls=new Map,console.log("File-tool tracker initialized")}updateFileOperations(e){this.fileOperations.clear(),console.log("updateFileOperations - processing",e.length,"events");const t=new Map;let o=0;e.forEach((e,a)=>{const n=this.isFileOperation(e);if(n&&o++,a<5&&console.log(`Event ${a}:`,{type:e.type,subtype:e.subtype,tool_name:e.tool_name,tool_parameters:e.tool_parameters,isFileOp:n}),n){const o=e.tool_name||e.data&&e.data.tool_name,a=e.session_id||e.data&&e.data.session_id||"unknown",n=`${a}_${o}_${Math.floor(new Date(e.timestamp).getTime()/1e3)}`;t.has(n)||t.set(n,{pre_event:null,post_event:null,tool_name:o,session_id:a});const s=t.get(n);"pre_tool"===e.subtype||"hook"===e.type&&!e.subtype.includes("post")?s.pre_event=e:("post_tool"===e.subtype||e.subtype.includes("post")||(s.pre_event=e),s.post_event=e)}}),console.log("updateFileOperations - found",o,"file operations in",t.size,"event pairs"),t.forEach((e,t)=>{const o=this.extractFilePathFromPair(e);if(o){console.log("File operation detected for:",o,"from pair:",t),this.fileOperations.has(o)||this.fileOperations.set(o,{path:o,operations:[],lastOperation:null});const a=this.fileOperations.get(o),n=this.getFileOperationFromPair(e),s=e.post_event?.timestamp||e.pre_event?.timestamp,r=this.extractAgentFromPair(e),i=this.workingDirectoryManager.extractWorkingDirectoryFromPair(e);a.operations.push({operation:n,timestamp:s,agent:r.name,confidence:r.confidence,sessionId:e.session_id,details:this.getFileOperationDetailsFromPair(e),workingDirectory:i}),a.lastOperation=s}else console.log("No file path found for pair:",t,e)}),console.log("updateFileOperations - final result:",this.fileOperations.size,"file operations"),this.fileOperations.size>0&&console.log("File operations map:",Array.from(this.fileOperations.entries()))}updateToolCalls(e){this.toolCalls.clear(),console.log("updateToolCalls - processing",e.length,"events");const t=[],o=[];let a=0;e.forEach((e,n)=>{const s=this.isToolOperation(e);s&&a++,n<5&&console.log(`Tool Event ${n}:`,{type:e.type,subtype:e.subtype,tool_name:e.tool_name,tool_parameters:e.tool_parameters,isToolOp:s}),s&&("pre_tool"===e.subtype||"hook"===e.type&&!e.subtype.includes("post")?t.push(e):("post_tool"===e.subtype||e.subtype.includes("post")||t.push(e),o.push(e)))}),console.log("updateToolCalls - found",a,"tool operations:",t.length,"pre_tool,",o.length,"post_tool");const n=new Map,s=new Set;t.forEach((e,t)=>{const a=e.tool_name||e.data&&e.data.tool_name,r=e.session_id||e.data&&e.data.session_id||"unknown",i=new Date(e.timestamp).getTime(),l=`${r}_${a}_${t}_${i}`,p={pre_event:e,post_event:null,tool_name:a,session_id:r,operation_type:e.operation_type||"tool_execution",timestamp:e.timestamp,duration_ms:null,success:null,exit_code:null,result_summary:null,agent_type:null,agent_confidence:null},c=this.extractAgentFromEvent(e);p.agent_type=c.name,p.agent_confidence=c.confidence;let _=-1,m=-1;if(o.forEach((t,o)=>{if(s.has(o))return;const n=t.tool_name||t.data&&t.data.tool_name,l=t.session_id||t.data&&t.data.session_id||"unknown";if(n!==a||l!==r)return;const p=new Date(t.timestamp).getTime(),c=Math.abs(p-i);let u=0;p>=i-1e3&&c<=3e5&&(u=1e3-c/1e3,this.compareToolParameters(e,t)&&(u+=500),e.working_directory&&t.working_directory&&e.working_directory===t.working_directory&&(u+=100)),u>m&&(m=u,_=o)}),_>=0&&m>0){const t=o[_];p.post_event=t,p.duration_ms=t.duration_ms,p.success=t.success,p.exit_code=t.exit_code,p.result_summary=t.result_summary,s.add(_),console.log(`Paired pre_tool ${a} at ${e.timestamp} with post_tool at ${t.timestamp} (score: ${m})`)}else console.log(`No matching post_tool found for ${a} at ${e.timestamp} (still running or orphaned)`);n.set(l,p)}),o.forEach((e,t)=>{if(s.has(t))return;const o=e.tool_name||e.data&&e.data.tool_name;console.log("Orphaned post_tool event found:",o,"at",e.timestamp);const a=e.session_id||e.data&&e.data.session_id||"unknown",r=`orphaned_${a}_${o}_${t}_${new Date(e.timestamp).getTime()}`,i={pre_event:null,post_event:e,tool_name:o,session_id:a,operation_type:"tool_execution",timestamp:e.timestamp,duration_ms:e.duration_ms,success:e.success,exit_code:e.exit_code,result_summary:e.result_summary,agent_type:null,agent_confidence:null},l=this.extractAgentFromEvent(e);i.agent_type=l.name,i.agent_confidence=l.confidence,n.set(r,i)}),this.toolCalls=n,console.log("updateToolCalls - final result:",this.toolCalls.size,"tool calls"),this.toolCalls.size>0&&console.log("Tool calls map keys:",Array.from(this.toolCalls.keys()))}isToolOperation(e){const t=e.tool_name||e.data&&e.data.tool_name,o="hook"===e.type,a="pre_tool"===e.subtype||"post_tool"===e.subtype||e.subtype&&e.subtype.includes("tool");return t&&o&&a}isFileOperation(e){let t=e.tool_name||e.data&&e.data.tool_name||"";t=t.toLowerCase();const o=e.tool_parameters||e.data&&e.data.tool_parameters;if("bash"===t&&o){if((o.command||"").match(/\b(cat|less|more|head|tail|touch|mv|cp|rm|mkdir|ls|find)\b/))return!0}return t&&["read","write","edit","grep","multiedit","glob","ls","bash","notebookedit"].includes(t)}extractFilePath(e){if(e.tool_parameters?.file_path)return e.tool_parameters.file_path;if(e.tool_parameters?.path)return e.tool_parameters.path;if(e.tool_parameters?.notebook_path)return e.tool_parameters.notebook_path;if(e.data?.tool_parameters?.file_path)return e.data.tool_parameters.file_path;if(e.data?.tool_parameters?.path)return e.data.tool_parameters.path;if(e.data?.tool_parameters?.notebook_path)return e.data.tool_parameters.notebook_path;if(e.file_path)return e.file_path;if(e.path)return e.path;if("glob"===e.tool_name?.toLowerCase()&&e.tool_parameters?.pattern)return`[glob] ${e.tool_parameters.pattern}`;if("bash"===e.tool_name?.toLowerCase()&&e.tool_parameters?.command){const t=e.tool_parameters.command.match(/(?:cat|less|more|head|tail|touch|mv|cp|rm|mkdir|ls|find|echo.*>|sed|awk|grep)\s+([^\s;|&]+)/);if(t&&t[1])return t[1]}return null}extractFilePathFromPair(e){let t=null;return e.pre_event&&(t=this.extractFilePath(e.pre_event)),!t&&e.post_event&&(t=this.extractFilePath(e.post_event)),t}getFileOperation(e){if(!e.tool_name)return"unknown";const t=e.tool_name.toLowerCase();switch(t){case"read":return"read";case"write":return"write";case"edit":case"multiedit":case"notebookedit":return"edit";case"grep":case"glob":return"search";case"ls":return"list";case"bash":const o=e.tool_parameters?.command||"";return o.match(/\b(cat|less|more|head|tail)\b/)?"read":o.match(/\b(touch|echo.*>|tee)\b/)?"write":o.match(/\b(sed|awk)\b/)?"edit":o.match(/\b(grep|find)\b/)?"search":o.match(/\b(ls|dir)\b/)?"list":o.match(/\b(mv|cp)\b/)?"copy/move":o.match(/\b(rm|rmdir)\b/)?"delete":o.match(/\b(mkdir)\b/)?"create":"bash";default:return t}}getFileOperationFromPair(e){return e.pre_event?this.getFileOperation(e.pre_event):e.post_event?this.getFileOperation(e.post_event):"unknown"}extractAgentFromPair(e){const t=e.pre_event||e.post_event;if(t&&this.agentInference){const e=this.agentInference.getInferredAgentForEvent(t);if(e)return{name:e.agentName||"Unknown",confidence:e.confidence||"unknown"}}return{name:t?.agent_type||t?.subagent_type||e.pre_event?.agent_type||e.post_event?.agent_type||"PM",confidence:"direct"}}getFileOperationDetailsFromPair(e){const t={};if(e.pre_event){const o=e.pre_event.tool_parameters||e.pre_event.data?.tool_parameters||{};t.parameters=o,t.tool_input=e.pre_event.tool_input}return e.post_event&&(t.result=e.post_event.result,t.success=e.post_event.success,t.error=e.post_event.error,t.exit_code=e.post_event.exit_code,t.duration_ms=e.post_event.duration_ms),t}getFileOperations(){return this.fileOperations}getToolCalls(){return this.toolCalls}getToolCallsArray(){return Array.from(this.toolCalls.entries())}getFileOperationsForFile(e){return this.fileOperations.get(e)||null}getToolCall(e){return this.toolCalls.get(e)||null}clear(){this.fileOperations.clear(),this.toolCalls.clear(),console.log("File-tool tracker cleared")}getStatistics(){return{fileOperations:this.fileOperations.size,toolCalls:this.toolCalls.size,uniqueFiles:this.fileOperations.size,totalFileOperations:Array.from(this.fileOperations.values()).reduce((e,t)=>e+t.operations.length,0)}}compareToolParameters(e,t){const o=e.tool_parameters||e.data?.tool_parameters||{},a=t.tool_parameters||t.data?.tool_parameters||{};if(0===Object.keys(o).length&&0===Object.keys(a).length)return!1;let n=0,s=0;if(["file_path","path","pattern","command","notebook_path"].forEach(e=>{const t=o[e],r=a[e];void 0===t&&void 0===r||(s++,t===r&&n++)}),s>0)return n/s>=.8;const r=Object.keys(o).sort(),i=Object.keys(a).sort();if(0===r.length&&0===i.length)return!1;if(r.length===i.length){return r.filter(e=>i.includes(e)).length>=Math.max(1,.5*r.length)}return!1}extractAgentFromEvent(e){if(this.agentInference){const t=this.agentInference.getInferredAgentForEvent(e);if(t)return{name:t.agentName||"Unknown",confidence:t.confidence||"unknown"}}return{name:e.agent_type||e.subagent_type||e.data?.agent_type||e.data?.subagent_type||"PM",confidence:"direct"}}}export{e as F};
|
|
1
|
+
class e{constructor(e,t){this.agentInference=e,this.workingDirectoryManager=t,this.fileOperations=new Map,this.toolCalls=new Map,console.log("File-tool tracker initialized")}updateFileOperations(e){this.fileOperations.clear(),console.log("updateFileOperations - processing",e.length,"events");const t=new Map;let o=0;e.forEach((e,a)=>{const n=this.isFileOperation(e);if(n&&o++,a<5&&console.log(`Event ${a}:`,{type:e.type,subtype:e.subtype,tool_name:e.tool_name,tool_parameters:e.tool_parameters,isFileOp:n}),n){const o=e.tool_name||e.data&&e.data.tool_name,a=e.session_id||e.data&&e.data.session_id||"unknown",n=`${a}_${o}_${Math.floor(new Date(e.timestamp).getTime()/1e3)}`;t.has(n)||t.set(n,{pre_event:null,post_event:null,tool_name:o,session_id:a});const s=t.get(n);"pre_tool"===e.subtype||"hook"===e.type&&e.subtype&&!e.subtype.includes("post")?s.pre_event=e:("post_tool"===e.subtype||e.subtype&&e.subtype.includes("post")||(s.pre_event=e),s.post_event=e)}}),console.log("updateFileOperations - found",o,"file operations in",t.size,"event pairs"),t.forEach((e,t)=>{const o=this.extractFilePathFromPair(e);if(o){console.log("File operation detected for:",o,"from pair:",t),this.fileOperations.has(o)||this.fileOperations.set(o,{path:o,operations:[],lastOperation:null});const a=this.fileOperations.get(o),n=this.getFileOperationFromPair(e),s=e.post_event?.timestamp||e.pre_event?.timestamp,r=this.extractAgentFromPair(e),i=this.workingDirectoryManager.extractWorkingDirectoryFromPair(e);a.operations.push({operation:n,timestamp:s,agent:r.name,confidence:r.confidence,sessionId:e.session_id,details:this.getFileOperationDetailsFromPair(e),workingDirectory:i}),a.lastOperation=s}else console.log("No file path found for pair:",t,e)}),console.log("updateFileOperations - final result:",this.fileOperations.size,"file operations"),this.fileOperations.size>0&&console.log("File operations map:",Array.from(this.fileOperations.entries()))}updateToolCalls(e){this.toolCalls.clear(),console.log("updateToolCalls - processing",e.length,"events");const t=[],o=[];let a=0;e.forEach((e,n)=>{const s=this.isToolOperation(e);s&&a++,n<5&&console.log(`Tool Event ${n}:`,{type:e.type,subtype:e.subtype,tool_name:e.tool_name,tool_parameters:e.tool_parameters,isToolOp:s}),s&&("pre_tool"===e.subtype||"hook"===e.type&&e.subtype&&!e.subtype.includes("post")?t.push(e):("post_tool"===e.subtype||e.subtype&&e.subtype.includes("post")||t.push(e),o.push(e)))}),console.log("updateToolCalls - found",a,"tool operations:",t.length,"pre_tool,",o.length,"post_tool");const n=new Map,s=new Set;t.forEach((e,t)=>{const a=e.tool_name||e.data&&e.data.tool_name,r=e.session_id||e.data&&e.data.session_id||"unknown",i=new Date(e.timestamp).getTime(),l=`${r}_${a}_${t}_${i}`,p={pre_event:e,post_event:null,tool_name:a,session_id:r,operation_type:e.operation_type||"tool_execution",timestamp:e.timestamp,duration_ms:null,success:null,exit_code:null,result_summary:null,agent_type:null,agent_confidence:null},c=this.extractAgentFromEvent(e);p.agent_type=c.name,p.agent_confidence=c.confidence;let _=-1,m=-1;if(o.forEach((t,o)=>{if(s.has(o))return;const n=t.tool_name||t.data&&t.data.tool_name,l=t.session_id||t.data&&t.data.session_id||"unknown";if(n!==a||l!==r)return;const p=new Date(t.timestamp).getTime(),c=Math.abs(p-i);let u=0;p>=i-1e3&&c<=3e5&&(u=1e3-c/1e3,this.compareToolParameters(e,t)&&(u+=500),e.working_directory&&t.working_directory&&e.working_directory===t.working_directory&&(u+=100)),u>m&&(m=u,_=o)}),_>=0&&m>0){const t=o[_];p.post_event=t,p.duration_ms=t.duration_ms,p.success=t.success,p.exit_code=t.exit_code,p.result_summary=t.result_summary,s.add(_),console.log(`Paired pre_tool ${a} at ${e.timestamp} with post_tool at ${t.timestamp} (score: ${m})`)}else console.log(`No matching post_tool found for ${a} at ${e.timestamp} (still running or orphaned)`);n.set(l,p)}),o.forEach((e,t)=>{if(s.has(t))return;const o=e.tool_name||e.data&&e.data.tool_name;console.log("Orphaned post_tool event found:",o,"at",e.timestamp);const a=e.session_id||e.data&&e.data.session_id||"unknown",r=`orphaned_${a}_${o}_${t}_${new Date(e.timestamp).getTime()}`,i={pre_event:null,post_event:e,tool_name:o,session_id:a,operation_type:"tool_execution",timestamp:e.timestamp,duration_ms:e.duration_ms,success:e.success,exit_code:e.exit_code,result_summary:e.result_summary,agent_type:null,agent_confidence:null},l=this.extractAgentFromEvent(e);i.agent_type=l.name,i.agent_confidence=l.confidence,n.set(r,i)}),this.toolCalls=n,console.log("updateToolCalls - final result:",this.toolCalls.size,"tool calls"),this.toolCalls.size>0&&console.log("Tool calls map keys:",Array.from(this.toolCalls.keys()))}isToolOperation(e){const t=e.tool_name||e.data&&e.data.tool_name,o="hook"===e.type,a="pre_tool"===e.subtype||"post_tool"===e.subtype||e.subtype&&"string"==typeof e.subtype&&e.subtype.includes("tool");return t&&o&&a}isFileOperation(e){let t=e.tool_name||e.data&&e.data.tool_name||"";t=t.toLowerCase();const o=e.tool_parameters||e.data&&e.data.tool_parameters;if("bash"===t&&o){if((o.command||"").match(/\b(cat|less|more|head|tail|touch|mv|cp|rm|mkdir|ls|find)\b/))return!0}return t&&["read","write","edit","grep","multiedit","glob","ls","bash","notebookedit"].includes(t)}extractFilePath(e){if(e.tool_parameters?.file_path)return e.tool_parameters.file_path;if(e.tool_parameters?.path)return e.tool_parameters.path;if(e.tool_parameters?.notebook_path)return e.tool_parameters.notebook_path;if(e.data?.tool_parameters?.file_path)return e.data.tool_parameters.file_path;if(e.data?.tool_parameters?.path)return e.data.tool_parameters.path;if(e.data?.tool_parameters?.notebook_path)return e.data.tool_parameters.notebook_path;if(e.file_path)return e.file_path;if(e.path)return e.path;if("glob"===e.tool_name?.toLowerCase()&&e.tool_parameters?.pattern)return`[glob] ${e.tool_parameters.pattern}`;if("bash"===e.tool_name?.toLowerCase()&&e.tool_parameters?.command){const t=e.tool_parameters.command.match(/(?:cat|less|more|head|tail|touch|mv|cp|rm|mkdir|ls|find|echo.*>|sed|awk|grep)\s+([^\s;|&]+)/);if(t&&t[1])return t[1]}return null}extractFilePathFromPair(e){let t=null;return e.pre_event&&(t=this.extractFilePath(e.pre_event)),!t&&e.post_event&&(t=this.extractFilePath(e.post_event)),t}getFileOperation(e){if(!e.tool_name)return"unknown";const t=e.tool_name.toLowerCase();switch(t){case"read":return"read";case"write":return"write";case"edit":case"multiedit":case"notebookedit":return"edit";case"grep":case"glob":return"search";case"ls":return"list";case"bash":const o=e.tool_parameters?.command||"";return o.match(/\b(cat|less|more|head|tail)\b/)?"read":o.match(/\b(touch|echo.*>|tee)\b/)?"write":o.match(/\b(sed|awk)\b/)?"edit":o.match(/\b(grep|find)\b/)?"search":o.match(/\b(ls|dir)\b/)?"list":o.match(/\b(mv|cp)\b/)?"copy/move":o.match(/\b(rm|rmdir)\b/)?"delete":o.match(/\b(mkdir)\b/)?"create":"bash";default:return t}}getFileOperationFromPair(e){return e.pre_event?this.getFileOperation(e.pre_event):e.post_event?this.getFileOperation(e.post_event):"unknown"}extractAgentFromPair(e){const t=e.pre_event||e.post_event;if(t&&this.agentInference){const e=this.agentInference.getInferredAgentForEvent(t);if(e)return{name:e.agentName||"Unknown",confidence:e.confidence||"unknown"}}return{name:t?.agent_type||t?.subagent_type||e.pre_event?.agent_type||e.post_event?.agent_type||"PM",confidence:"direct"}}getFileOperationDetailsFromPair(e){const t={};if(e.pre_event){const o=e.pre_event.tool_parameters||e.pre_event.data?.tool_parameters||{};t.parameters=o,t.tool_input=e.pre_event.tool_input}return e.post_event&&(t.result=e.post_event.result,t.success=e.post_event.success,t.error=e.post_event.error,t.exit_code=e.post_event.exit_code,t.duration_ms=e.post_event.duration_ms),t}getFileOperations(){return this.fileOperations}getToolCalls(){return this.toolCalls}getToolCallsArray(){return Array.from(this.toolCalls.entries())}getFileOperationsForFile(e){return this.fileOperations.get(e)||null}getToolCall(e){return this.toolCalls.get(e)||null}clear(){this.fileOperations.clear(),this.toolCalls.clear(),console.log("File-tool tracker cleared")}getStatistics(){return{fileOperations:this.fileOperations.size,toolCalls:this.toolCalls.size,uniqueFiles:this.fileOperations.size,totalFileOperations:Array.from(this.fileOperations.values()).reduce((e,t)=>e+t.operations.length,0)}}compareToolParameters(e,t){const o=e.tool_parameters||e.data?.tool_parameters||{},a=t.tool_parameters||t.data?.tool_parameters||{};if(0===Object.keys(o).length&&0===Object.keys(a).length)return!1;let n=0,s=0;if(["file_path","path","pattern","command","notebook_path"].forEach(e=>{const t=o[e],r=a[e];void 0===t&&void 0===r||(s++,t===r&&n++)}),s>0)return n/s>=.8;const r=Object.keys(o).sort(),i=Object.keys(a).sort();if(0===r.length&&0===i.length)return!1;if(r.length===i.length){return r.filter(e=>i.includes(e)).length>=Math.max(1,.5*r.length)}return!1}extractAgentFromEvent(e){if(this.agentInference){const t=this.agentInference.getInferredAgentForEvent(e);if(t)return{name:t.agentName||"Unknown",confidence:t.confidence||"unknown"}}return{name:e.agent_type||e.subagent_type||e.data?.agent_type||e.data?.subagent_type||"PM",confidence:"direct"}}}export{e as F};
|
|
2
2
|
//# sourceMappingURL=file-tool-tracker.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const t=window.io;class e{constructor(){this.socket=null,this.port=null,this.connectionCallbacks={connect:[],disconnect:[],error:[],event:[]},this.isConnected=!1,this.isConnecting=!1,this.events=[],this.sessions=new Map,this.currentSessionId=null,this.startStatusCheckFallback()}connect(t="8765"){this.port=t;const e=`http://localhost:${t}`;if(this.socket&&(this.socket.connected||this.socket.connecting))return console.log("Already connected or connecting, disconnecting first..."),this.socket.disconnect(),void setTimeout(()=>this.doConnect(e),100);this.doConnect(e)}doConnect(e){if(console.log(`Connecting to Socket.IO server at ${e}`),void 0===t)return console.error("Socket.IO library not loaded! Make sure socket.io.min.js is loaded before this script."),void this.notifyConnectionStatus("Socket.IO library not loaded","error");this.isConnecting=!0,this.notifyConnectionStatus("Connecting...","connecting"),this.socket=t(e,{autoConnect:!0,reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:1e4,maxReconnectionAttempts:10,timeout:1e4,forceNew:!0,transports:["websocket","polling"]}),this.setupSocketHandlers()}setupSocketHandlers(){this.socket.on("connect",()=>{console.log("Connected to Socket.IO server"),this.isConnected=!0,this.isConnecting=!1,this.notifyConnectionStatus("Connected","connected"),this.connectionCallbacks.connect.forEach(t=>t(this.socket.id)),this.requestStatus()}),this.socket.on("disconnect",t=>{console.log("Disconnected from server:",t),this.isConnected=!1,this.isConnecting=!1,this.notifyConnectionStatus(`Disconnected: ${t}`,"disconnected"),this.connectionCallbacks.disconnect.forEach(e=>e(t))}),this.socket.on("connect_error",t=>{console.error("Connection error:",t),this.isConnecting=!1;const e=t.message||t.description||"Unknown error";this.notifyConnectionStatus(`Connection Error: ${e}`,"disconnected"),this.addEvent({type:"connection.error",timestamp:(new Date).toISOString(),data:{error:e,url:this.socket.io.uri}}),this.connectionCallbacks.error.forEach(t=>t(e))}),this.socket.on("claude_event",t=>{const e=this.transformEvent(t);this.addEvent(e)}),this.socket.on("session.started",t=>{this.addEvent({type:"session",subtype:"started",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("session.ended",t=>{this.addEvent({type:"session",subtype:"ended",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("claude.request",t=>{this.addEvent({type:"claude",subtype:"request",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("claude.response",t=>{this.addEvent({type:"claude",subtype:"response",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("agent.loaded",t=>{this.addEvent({type:"agent",subtype:"loaded",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("agent.executed",t=>{this.addEvent({type:"agent",subtype:"executed",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("hook.pre",t=>{this.addEvent({type:"hook",subtype:"pre",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("hook.post",t=>{this.addEvent({type:"hook",subtype:"post",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("todo.updated",t=>{this.addEvent({type:"todo",subtype:"updated",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("memory.operation",t=>{this.addEvent({type:"memory",subtype:"operation",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("log.entry",t=>{this.addEvent({type:"log",subtype:"entry",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("history",t=>{console.log("Received event history:",t),t&&Array.isArray(t.events)?(console.log(`Processing ${t.events.length} historical events (${t.count} sent, ${t.total_available} total available)`),t.events.forEach(t=>{const e=this.transformEvent(t);this.addEvent(e,!1)}),this.notifyEventUpdate(),console.log(`Event history loaded: ${t.events.length} events added to dashboard`)):Array.isArray(t)&&(console.log("Received legacy event history format:",t.length,"events"),t.forEach(t=>{const e=this.transformEvent(t);this.addEvent(e,!1)}),this.notifyEventUpdate())}),this.socket.on("system.status",t=>{console.log("Received system status:",t),t.sessions&&this.updateSessions(t.sessions),t.current_session&&(this.currentSessionId=t.current_session)})}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null),this.port=null,this.isConnected=!1,this.isConnecting=!1}requestStatus(){this.socket&&this.socket.connected&&(console.log("Requesting server status..."),this.socket.emit("request.status"))}requestHistory(t={}){if(this.socket&&this.socket.connected){const e={limit:t.limit||50,event_types:t.event_types||[]};console.log("Requesting event history...",e),this.socket.emit("get_history",e)}else console.warn("Cannot request history: not connected to server")}addEvent(t,e=!0){if(t.timestamp||(t.timestamp=(new Date).toISOString()),t.id||(t.id=Date.now()+Math.random()),this.events.push(t),t.data&&t.data.session_id){const e=t.data.session_id;this.sessions.has(e)||this.sessions.set(e,{id:e,startTime:t.timestamp,lastActivity:t.timestamp,eventCount:0});const n=this.sessions.get(e);n.lastActivity=t.timestamp,n.eventCount++}e&&this.notifyEventUpdate()}updateSessions(t){Array.isArray(t)&&t.forEach(t=>{this.sessions.set(t.id,t)})}clearEvents(){this.events=[],this.sessions.clear(),this.notifyEventUpdate()}refreshHistory(t={}){this.clearEvents(),this.requestHistory(t)}getEventsBySession(t=null){return t?this.events.filter(e=>e.data&&e.data.session_id===t):this.events}onConnection(t,e){this.connectionCallbacks[t]&&this.connectionCallbacks[t].push(e)}onEventUpdate(t){this.connectionCallbacks.event.push(t)}notifyConnectionStatus(t,e){console.log(`SocketClient: Connection status changed to '${t}' (${e})`),this.updateConnectionStatusDOM(t,e),document.dispatchEvent(new CustomEvent("socketConnectionStatus",{detail:{status:t,type:e}}))}updateConnectionStatusDOM(t,e){const n=document.getElementById("connection-status");n?(n.innerHTML=`<span>●</span> ${t}`,n.className=`status-badge status-${e}`,console.log(`SocketClient: Direct DOM update - status: '${t}' (${e})`)):console.warn("SocketClient: Could not find connection-status element in DOM")}notifyEventUpdate(){this.connectionCallbacks.event.forEach(t=>t(this.events,this.sessions)),document.dispatchEvent(new CustomEvent("socketEventUpdate",{detail:{events:this.events,sessions:this.sessions}}))}getConnectionState(){return{isConnected:this.isConnected,isConnecting:this.isConnecting,socketId:this.socket?this.socket.id:null}}transformEvent(t){if(!t)return t;let e={...t};if(!t.type&&t.event){const n=t.event;"TestStart"===n||"TestEnd"===n?(e.type="test",e.subtype=n.toLowerCase().replace("test","")):"SubagentStart"===n||"SubagentStop"===n?(e.type="subagent",e.subtype=n.toLowerCase().replace("subagent","")):"ToolCall"===n?(e.type="tool",e.subtype="call"):"UserPrompt"===n?(e.type="hook",e.subtype="user_prompt"):(e.type="system",e.subtype=n.toLowerCase()),delete e.event}else if(t.type){const n=t.type;if(n.startsWith("hook.")){const t=n.substring(5);e.type="hook",e.subtype=t}else if(n.includes(".")){const[t,...s]=n.split(".");e.type=t,e.subtype=s.join(".")}}else e.type="unknown",e.subtype="";return t.data&&"object"==typeof t.data&&(Object.keys(t.data).forEach(n=>{e[n]=t.data[n]}),e.data=t.data),"hook"!==e.type||"pre_tool"!==e.subtype&&"post_tool"!==e.subtype||console.log("Transformed tool event:",{type:e.type,subtype:e.subtype,tool_name:e.tool_name,has_data:!!e.data,keys:Object.keys(e).filter(t=>"data"!==t)}),e}getState(){return{events:this.events,sessions:this.sessions,currentSessionId:this.currentSessionId}}startStatusCheckFallback(){setInterval(()=>{this.checkAndUpdateStatus()},2e3),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{setTimeout(()=>this.checkAndUpdateStatus(),100)}):setTimeout(()=>this.checkAndUpdateStatus(),100)}checkAndUpdateStatus(){let t="Disconnected",e="disconnected";this.socket&&(this.socket.connected?(t="Connected",e="connected",this.isConnected=!0,this.isConnecting=!1):this.socket.connecting||this.isConnecting?(t="Connecting...",e="connecting",this.isConnected=!1):(t="Disconnected",e="disconnected",this.isConnected=!1,this.isConnecting=!1));const n=document.getElementById("connection-status");if(n){const s=n.textContent.replace("●","").trim(),o=n.className,i=`status-badge status-${e}`;s===t&&o===i||(console.log(`SocketClient: Fallback update - was '${s}' (${o}), now '${t}' (${i})`),this.updateConnectionStatusDOM(t,e))}}}window.SocketClient=e;class n{constructor(){this.socketClient=null,this.connectionCallbacks=new Set,this.eventUpdateCallbacks=new Set,this.socketClient=new e,window.socketClient=this.socketClient,this.setupSocketEventHandlers(),setTimeout(()=>{this.updateInitialConnectionStatus()},100),console.log("Socket manager initialized")}setupSocketEventHandlers(){document.addEventListener("socketConnectionStatus",t=>{console.log(`SocketManager: Processing connection status update: ${t.detail.status} (${t.detail.type})`),this.handleConnectionStatusChange(t.detail.status,t.detail.type),this.connectionCallbacks.forEach(e=>{try{e(t.detail.status,t.detail.type)}catch(n){console.error("Error in connection callback:",n)}})}),this.socketClient&&this.socketClient.onEventUpdate(t=>{this.eventUpdateCallbacks.forEach(e=>{try{e(t)}catch(n){console.error("Error in event update callback:",n)}})})}handleConnectionStatusChange(t,e){this.updateConnectionStatus(t,e),"connected"===e&&this.socketClient&&this.socketClient.socket&&this.setupGitBranchListener()}updateInitialConnectionStatus(){console.log("SocketManager: Updating initial connection status"),this.socketClient&&"function"==typeof this.socketClient.checkAndUpdateStatus?(console.log("SocketManager: Using socket client checkAndUpdateStatus method"),this.socketClient.checkAndUpdateStatus()):this.socketClient&&this.socketClient.socket?(console.log("SocketManager: Checking socket state directly",{connected:this.socketClient.socket.connected,connecting:this.socketClient.socket.connecting,isConnecting:this.socketClient.isConnecting,isConnected:this.socketClient.isConnected}),this.socketClient.socket.connected?(console.log("SocketManager: Socket is already connected, updating status"),this.updateConnectionStatus("Connected","connected")):this.socketClient.isConnecting||this.socketClient.socket.connecting?(console.log("SocketManager: Socket is connecting, updating status"),this.updateConnectionStatus("Connecting...","connecting")):(console.log("SocketManager: Socket is disconnected, updating status"),this.updateConnectionStatus("Disconnected","disconnected"))):(console.log("SocketManager: No socket client or socket found, setting disconnected status"),this.updateConnectionStatus("Disconnected","disconnected")),setTimeout(()=>{console.log("SocketManager: Secondary status check after 1 second"),this.socketClient&&this.socketClient.socket&&this.socketClient.socket.connected&&(console.log("SocketManager: Socket connected in secondary check, updating status"),this.updateConnectionStatus("Connected","connected"))},1e3)}setupGitBranchListener(){this.socketClient.socket.off("git_branch_response"),this.socketClient.socket.on("git_branch_response",t=>{if(t.success){const e=document.getElementById("footer-git-branch");e&&(e.textContent=t.branch||"unknown"),e&&(e.style.display="inline")}else console.error("Git branch request failed:",t.error)})}updateConnectionStatus(t,e){const n=document.getElementById("connection-status");if(n){if(n.querySelector("span")){const e="●";n.innerHTML=`<span>${e}</span> ${t}`}else n.textContent=t;n.className=`status-badge status-${e}`,console.log(`SocketManager: UI updated - status: '${t}' (${e})`)}else console.error("SocketManager: Could not find connection-status element in DOM")}connect(t){this.socketClient&&this.socketClient.connect(t)}disconnect(){this.socketClient&&this.socketClient.disconnect()}isConnected(){return this.socketClient&&this.socketClient.isConnected}isConnecting(){return this.socketClient&&this.socketClient.isConnecting}getSocketClient(){return this.socketClient}getSocket(){return this.socketClient?this.socketClient.socket:null}onConnectionStatusChange(t){this.connectionCallbacks.add(t)}offConnectionStatusChange(t){this.connectionCallbacks.delete(t)}onEventUpdate(t){this.eventUpdateCallbacks.add(t)}offEventUpdate(t){this.eventUpdateCallbacks.delete(t)}toggleConnectionControls(){const t=document.getElementById("connection-controls-row"),e=document.getElementById("connection-toggle-btn");if(t&&e){t.classList.contains("show")?(t.classList.remove("show"),t.style.display="none",e.textContent="Connection Settings"):(t.classList.add("show"),t.style.display="block",e.textContent="Hide Settings")}}setupConnectionControls(){const t=document.getElementById("connect-btn"),e=document.getElementById("disconnect-btn"),n=document.getElementById("connection-toggle-btn");t&&t.addEventListener("click",()=>{const t=document.getElementById("port-input").value||8765;this.connect(t)}),e&&e.addEventListener("click",()=>{this.disconnect()}),n&&n.addEventListener("click",()=>{this.toggleConnectionControls()})}initializeFromURL(t){const e=t.get("port"),n=document.getElementById("port-input");let s=e;s||"http:"!==window.location.protocol||(s=window.location.port||"8765"),s||(s=n?.value||"8765"),n&&(n.value=s);!("false"!==t.get("connect"))||this.isConnected()||this.isConnecting()||this.connect(s)}}class s{constructor(){this.currentTab="events",this.autoScroll=!0,this.selectedCard={tab:null,index:null,type:null,data:null},this.tabNavigation={events:{selectedIndex:-1,items:[]},agents:{selectedIndex:-1,items:[]},tools:{selectedIndex:-1,items:[]},files:{selectedIndex:-1,items:[]}},this.setupEventHandlers(),console.log("UI state manager initialized")}setupEventHandlers(){this.setupTabNavigation(),this.setupUnifiedKeyboardNavigation()}setupTabNavigation(){document.querySelectorAll(".tab-button").forEach(t=>{t.addEventListener("click",()=>{const e=this.getTabNameFromButton(t);this.switchTab(e)})})}setupUnifiedKeyboardNavigation(){document.addEventListener("keydown",t=>{document.activeElement&&["INPUT","TEXTAREA","SELECT"].includes(document.activeElement.tagName)||("ArrowUp"===t.key||"ArrowDown"===t.key?(t.preventDefault(),this.handleUnifiedArrowNavigation("ArrowDown"===t.key?1:-1)):"Enter"===t.key?(t.preventDefault(),this.handleUnifiedEnterKey()):"Escape"===t.key&&this.clearUnifiedSelection())})}getTabNameFromButton(t){const e=t.textContent.toLowerCase();return e.includes("events")?"events":e.includes("agents")?"agents":e.includes("tools")?"tools":e.includes("files")?"files":"events"}switchTab(t){console.log(`[DEBUG] switchTab called with tabName: ${t}`);const e=this.currentTab;this.currentTab=t,document.querySelectorAll(".tab-button").forEach(e=>{e.classList.remove("active"),this.getTabNameFromButton(e)===t&&e.classList.add("active")}),document.querySelectorAll(".tab-content").forEach(t=>{t.classList.remove("active")});const n=document.getElementById(`${t}-tab`);n&&n.classList.add("active"),this.clearUnifiedSelection(),document.dispatchEvent(new CustomEvent("tabChanged",{detail:{newTab:t,previousTab:e}})),setTimeout(()=>{this.autoScroll&&this.scrollCurrentTabToBottom()},100)}handleUnifiedArrowNavigation(t){const e=this.tabNavigation[this.currentTab];if(!e)return;let n=e.selectedIndex+t;0!==e.items.length&&(n<0?n=e.items.length-1:n>=e.items.length&&(n=0),this.selectCardByIndex(this.currentTab,n))}handleUnifiedEnterKey(){const t=this.tabNavigation[this.currentTab];if(!t||-1===t.selectedIndex)return;const e=t.items[t.selectedIndex];e&&e.onclick&&e.onclick()}clearUnifiedSelection(){Object.keys(this.tabNavigation).forEach(t=>{this.tabNavigation[t].selectedIndex=-1}),this.clearCardSelection()}updateTabNavigationItems(){const t=this.tabNavigation[this.currentTab];if(!t)return;let e;switch(this.currentTab){case"events":e="#events-list .event-item";break;case"agents":e="#agents-list .event-item";break;case"tools":e="#tools-list .event-item";break;case"files":e="#files-list .event-item"}e&&(t.items=Array.from(document.querySelectorAll(e)))}selectCardByIndex(t,e){const n=this.tabNavigation[t];if(!n||e<0||e>=n.items.length)return;n.selectedIndex=e,this.updateUnifiedSelectionUI();n.items[e]&&this.selectCard(t,e,this.getCardType(t),e),this.showCardDetails(t,e)}updateUnifiedSelectionUI(){document.querySelectorAll(".event-item.keyboard-selected").forEach(t=>{t.classList.remove("keyboard-selected")});const t=this.tabNavigation[this.currentTab];t&&-1!==t.selectedIndex&&t.items[t.selectedIndex]&&t.items[t.selectedIndex].classList.add("keyboard-selected")}showCardDetails(t,e){document.dispatchEvent(new CustomEvent("showCardDetails",{detail:{tabName:t,index:e}}))}selectCard(t,e,n,s){this.clearCardSelection(),this.selectedCard={tab:t,index:e,type:n,data:s},this.updateCardSelectionUI(),console.log("Card selected:",this.selectedCard)}clearCardSelection(){document.querySelectorAll(".event-item.selected, .file-item.selected").forEach(t=>{t.classList.remove("selected")}),this.selectedCard={tab:null,index:null,type:null,data:null}}updateCardSelectionUI(){if(!this.selectedCard.tab||null===this.selectedCard.index)return;let t;switch(this.selectedCard.tab){case"events":t=document.getElementById("events-list");break;case"agents":t=document.getElementById("agents-list");break;case"tools":t=document.getElementById("tools-list");break;case"files":t=document.getElementById("files-list")}if(t){const e=t.querySelectorAll(".event-item, .file-item");e[this.selectedCard.index]&&e[this.selectedCard.index].classList.add("selected")}}getCardType(t){switch(t){case"events":return"event";case"agents":return"agent";case"tools":return"tool";case"files":return"file";default:return"unknown"}}scrollCurrentTabToBottom(){const t=`${this.currentTab}-list`,e=document.getElementById(t);e&&this.autoScroll&&(e.scrollTop=e.scrollHeight)}clearSelection(){this.clearCardSelection(),this.clearUnifiedSelection()}getCurrentTab(){return this.currentTab}getSelectedCard(){return{...this.selectedCard}}getTabNavigation(){return{...this.tabNavigation}}setAutoScroll(t){this.autoScroll=t}getAutoScroll(){return this.autoScroll}}export{n as S,s as U};
|
|
1
|
+
const t=window.io;class e{constructor(){this.socket=null,this.port=null,this.connectionCallbacks={connect:[],disconnect:[],error:[],event:[]},this.isConnected=!1,this.isConnecting=!1,this.events=[],this.sessions=new Map,this.currentSessionId=null,this.startStatusCheckFallback()}connect(t="8765"){this.port=t;const e=`http://localhost:${t}`;if(this.socket&&(this.socket.connected||this.socket.connecting))return console.log("Already connected or connecting, disconnecting first..."),this.socket.disconnect(),void setTimeout(()=>this.doConnect(e),100);this.doConnect(e)}doConnect(e){if(console.log(`Connecting to Socket.IO server at ${e}`),void 0===t)return console.error("Socket.IO library not loaded! Make sure socket.io.min.js is loaded before this script."),void this.notifyConnectionStatus("Socket.IO library not loaded","error");this.isConnecting=!0,this.notifyConnectionStatus("Connecting...","connecting"),this.socket=t(e,{autoConnect:!0,reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:1e4,maxReconnectionAttempts:10,timeout:1e4,forceNew:!0,transports:["websocket","polling"]}),this.setupSocketHandlers()}setupSocketHandlers(){this.socket.on("connect",()=>{console.log("Connected to Socket.IO server"),this.isConnected=!0,this.isConnecting=!1,this.notifyConnectionStatus("Connected","connected"),this.connectionCallbacks.connect.forEach(t=>t(this.socket.id)),this.requestStatus()}),this.socket.on("disconnect",t=>{console.log("Disconnected from server:",t),this.isConnected=!1,this.isConnecting=!1,this.notifyConnectionStatus(`Disconnected: ${t}`,"disconnected"),this.connectionCallbacks.disconnect.forEach(e=>e(t))}),this.socket.on("connect_error",t=>{console.error("Connection error:",t),this.isConnecting=!1;const e=t.message||t.description||"Unknown error";this.notifyConnectionStatus(`Connection Error: ${e}`,"disconnected"),this.addEvent({type:"connection.error",timestamp:(new Date).toISOString(),data:{error:e,url:this.socket.io.uri}}),this.connectionCallbacks.error.forEach(t=>t(e))}),this.socket.on("claude_event",t=>{const e=this.transformEvent(t);this.addEvent(e)}),this.socket.on("session.started",t=>{this.addEvent({type:"session",subtype:"started",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("session.ended",t=>{this.addEvent({type:"session",subtype:"ended",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("claude.request",t=>{this.addEvent({type:"claude",subtype:"request",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("claude.response",t=>{this.addEvent({type:"claude",subtype:"response",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("agent.loaded",t=>{this.addEvent({type:"agent",subtype:"loaded",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("agent.executed",t=>{this.addEvent({type:"agent",subtype:"executed",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("hook.pre",t=>{this.addEvent({type:"hook",subtype:"pre",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("hook.post",t=>{this.addEvent({type:"hook",subtype:"post",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("todo.updated",t=>{this.addEvent({type:"todo",subtype:"updated",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("memory.operation",t=>{this.addEvent({type:"memory",subtype:"operation",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("log.entry",t=>{this.addEvent({type:"log",subtype:"entry",timestamp:(new Date).toISOString(),data:t})}),this.socket.on("history",t=>{console.log("Received event history:",t),t&&Array.isArray(t.events)?(console.log(`Processing ${t.events.length} historical events (${t.count} sent, ${t.total_available} total available)`),t.events.forEach(t=>{const e=this.transformEvent(t);this.addEvent(e,!1)}),this.notifyEventUpdate(),console.log(`Event history loaded: ${t.events.length} events added to dashboard`)):Array.isArray(t)&&(console.log("Received legacy event history format:",t.length,"events"),t.forEach(t=>{const e=this.transformEvent(t);this.addEvent(e,!1)}),this.notifyEventUpdate())}),this.socket.on("system.status",t=>{console.log("Received system status:",t),t.sessions&&this.updateSessions(t.sessions),t.current_session&&(this.currentSessionId=t.current_session)})}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null),this.port=null,this.isConnected=!1,this.isConnecting=!1}requestStatus(){this.socket&&this.socket.connected&&(console.log("Requesting server status..."),this.socket.emit("request.status"))}requestHistory(t={}){if(this.socket&&this.socket.connected){const e={limit:t.limit||50,event_types:t.event_types||[]};console.log("Requesting event history...",e),this.socket.emit("get_history",e)}else console.warn("Cannot request history: not connected to server")}addEvent(t,e=!0){if(t.timestamp||(t.timestamp=(new Date).toISOString()),t.id||(t.id=Date.now()+Math.random()),this.events.push(t),t.data&&t.data.session_id){const e=t.data.session_id;this.sessions.has(e)||this.sessions.set(e,{id:e,startTime:t.timestamp,lastActivity:t.timestamp,eventCount:0});const n=this.sessions.get(e);n.lastActivity=t.timestamp,n.eventCount++}e&&this.notifyEventUpdate()}updateSessions(t){Array.isArray(t)&&t.forEach(t=>{this.sessions.set(t.id,t)})}clearEvents(){this.events=[],this.sessions.clear(),this.notifyEventUpdate()}refreshHistory(t={}){this.clearEvents(),this.requestHistory(t)}getEventsBySession(t=null){return t?this.events.filter(e=>e.data&&e.data.session_id===t):this.events}onConnection(t,e){this.connectionCallbacks[t]&&this.connectionCallbacks[t].push(e)}onEventUpdate(t){this.connectionCallbacks.event.push(t)}notifyConnectionStatus(t,e){console.log(`SocketClient: Connection status changed to '${t}' (${e})`),this.updateConnectionStatusDOM(t,e),document.dispatchEvent(new CustomEvent("socketConnectionStatus",{detail:{status:t,type:e}}))}updateConnectionStatusDOM(t,e){const n=document.getElementById("connection-status");n?(n.innerHTML=`<span>●</span> ${t}`,n.className=`status-badge status-${e}`,console.log(`SocketClient: Direct DOM update - status: '${t}' (${e})`)):console.warn("SocketClient: Could not find connection-status element in DOM")}notifyEventUpdate(){this.connectionCallbacks.event.forEach(t=>t(this.events,this.sessions)),document.dispatchEvent(new CustomEvent("socketEventUpdate",{detail:{events:this.events,sessions:this.sessions}}))}getConnectionState(){return{isConnected:this.isConnected,isConnecting:this.isConnecting,socketId:this.socket?this.socket.id:null}}transformEvent(t){if(!t)return t;let e={...t};if(!t.type&&t.event){const n=t.event;"TestStart"===n||"TestEnd"===n?(e.type="test",e.subtype=n.toLowerCase().replace("test","")):"SubagentStart"===n||"SubagentStop"===n?(e.type="subagent",e.subtype=n.toLowerCase().replace("subagent","")):"ToolCall"===n?(e.type="tool",e.subtype="call"):"UserPrompt"===n?(e.type="hook",e.subtype="user_prompt"):(e.type="unknown",e.subtype=n.toLowerCase(),e.type===e.subtype&&(e.subtype="event")),delete e.event}else if(t.type){const n=t.type;if(n.startsWith("hook.")){const t=n.substring(5);e.type="hook",e.subtype=t}else if(n.includes(".")){const[t,...s]=n.split(".");e.type=t,e.subtype=s.join(".")}}else e.type="unknown",e.subtype="";if(!t.type&&t.event?e.originalEventName=t.event:t.type&&(e.originalEventName=t.type),t.data&&"object"==typeof t.data){const n=["type","subtype","timestamp","id","event","event_type","originalEventName"];Object.keys(t.data).forEach(s=>{n.includes(s)?console.warn(`Protected field '${s}' in data object was not copied to top level to preserve event structure`):e[s]=t.data[s]}),e.data=t.data}return"hook"!==e.type||"pre_tool"!==e.subtype&&"post_tool"!==e.subtype||console.log("Transformed tool event:",{type:e.type,subtype:e.subtype,tool_name:e.tool_name,has_data:!!e.data,keys:Object.keys(e).filter(t=>"data"!==t)}),e}getState(){return{events:this.events,sessions:this.sessions,currentSessionId:this.currentSessionId}}startStatusCheckFallback(){setInterval(()=>{this.checkAndUpdateStatus()},2e3),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{setTimeout(()=>this.checkAndUpdateStatus(),100)}):setTimeout(()=>this.checkAndUpdateStatus(),100)}checkAndUpdateStatus(){let t="Disconnected",e="disconnected";this.socket&&(this.socket.connected?(t="Connected",e="connected",this.isConnected=!0,this.isConnecting=!1):this.socket.connecting||this.isConnecting?(t="Connecting...",e="connecting",this.isConnected=!1):(t="Disconnected",e="disconnected",this.isConnected=!1,this.isConnecting=!1));const n=document.getElementById("connection-status");if(n){const s=n.textContent.replace("●","").trim(),o=n.className,i=`status-badge status-${e}`;s===t&&o===i||(console.log(`SocketClient: Fallback update - was '${s}' (${o}), now '${t}' (${i})`),this.updateConnectionStatusDOM(t,e))}}}window.SocketClient=e;class n{constructor(){this.socketClient=null,this.connectionCallbacks=new Set,this.eventUpdateCallbacks=new Set,this.socketClient=new e,window.socketClient=this.socketClient,this.setupSocketEventHandlers(),setTimeout(()=>{this.updateInitialConnectionStatus()},100),console.log("Socket manager initialized")}setupSocketEventHandlers(){document.addEventListener("socketConnectionStatus",t=>{console.log(`SocketManager: Processing connection status update: ${t.detail.status} (${t.detail.type})`),this.handleConnectionStatusChange(t.detail.status,t.detail.type),this.connectionCallbacks.forEach(e=>{try{e(t.detail.status,t.detail.type)}catch(n){console.error("Error in connection callback:",n)}})}),this.socketClient&&this.socketClient.onEventUpdate(t=>{this.eventUpdateCallbacks.forEach(e=>{try{e(t)}catch(n){console.error("Error in event update callback:",n)}})})}handleConnectionStatusChange(t,e){this.updateConnectionStatus(t,e),"connected"===e&&this.socketClient&&this.socketClient.socket&&this.setupGitBranchListener()}updateInitialConnectionStatus(){console.log("SocketManager: Updating initial connection status"),this.socketClient&&"function"==typeof this.socketClient.checkAndUpdateStatus?(console.log("SocketManager: Using socket client checkAndUpdateStatus method"),this.socketClient.checkAndUpdateStatus()):this.socketClient&&this.socketClient.socket?(console.log("SocketManager: Checking socket state directly",{connected:this.socketClient.socket.connected,connecting:this.socketClient.socket.connecting,isConnecting:this.socketClient.isConnecting,isConnected:this.socketClient.isConnected}),this.socketClient.socket.connected?(console.log("SocketManager: Socket is already connected, updating status"),this.updateConnectionStatus("Connected","connected")):this.socketClient.isConnecting||this.socketClient.socket.connecting?(console.log("SocketManager: Socket is connecting, updating status"),this.updateConnectionStatus("Connecting...","connecting")):(console.log("SocketManager: Socket is disconnected, updating status"),this.updateConnectionStatus("Disconnected","disconnected"))):(console.log("SocketManager: No socket client or socket found, setting disconnected status"),this.updateConnectionStatus("Disconnected","disconnected")),setTimeout(()=>{console.log("SocketManager: Secondary status check after 1 second"),this.socketClient&&this.socketClient.socket&&this.socketClient.socket.connected&&(console.log("SocketManager: Socket connected in secondary check, updating status"),this.updateConnectionStatus("Connected","connected"))},1e3)}setupGitBranchListener(){this.socketClient.socket.off("git_branch_response"),this.socketClient.socket.on("git_branch_response",t=>{if(t.success){const e=document.getElementById("footer-git-branch");e&&(e.textContent=t.branch||"unknown"),e&&(e.style.display="inline")}else console.error("Git branch request failed:",t.error)})}updateConnectionStatus(t,e){const n=document.getElementById("connection-status");if(n){if(n.querySelector("span")){const e="●";n.innerHTML=`<span>${e}</span> ${t}`}else n.textContent=t;n.className=`status-badge status-${e}`,console.log(`SocketManager: UI updated - status: '${t}' (${e})`)}else console.error("SocketManager: Could not find connection-status element in DOM")}connect(t){this.socketClient&&this.socketClient.connect(t)}disconnect(){this.socketClient&&this.socketClient.disconnect()}isConnected(){return this.socketClient&&this.socketClient.isConnected}isConnecting(){return this.socketClient&&this.socketClient.isConnecting}getSocketClient(){return this.socketClient}getSocket(){return this.socketClient?this.socketClient.socket:null}onConnectionStatusChange(t){this.connectionCallbacks.add(t)}offConnectionStatusChange(t){this.connectionCallbacks.delete(t)}onEventUpdate(t){this.eventUpdateCallbacks.add(t)}offEventUpdate(t){this.eventUpdateCallbacks.delete(t)}toggleConnectionControls(){const t=document.getElementById("connection-controls-row"),e=document.getElementById("connection-toggle-btn");if(t&&e){t.classList.contains("show")?(t.classList.remove("show"),t.style.display="none",e.textContent="Connection Settings"):(t.classList.add("show"),t.style.display="block",e.textContent="Hide Settings")}}setupConnectionControls(){const t=document.getElementById("connect-btn"),e=document.getElementById("disconnect-btn"),n=document.getElementById("connection-toggle-btn");t&&t.addEventListener("click",()=>{const t=document.getElementById("port-input").value||8765;this.connect(t)}),e&&e.addEventListener("click",()=>{this.disconnect()}),n&&n.addEventListener("click",()=>{this.toggleConnectionControls()})}initializeFromURL(t){const e=t.get("port"),n=document.getElementById("port-input");let s=e;s||"http:"!==window.location.protocol||(s=window.location.port||"8765"),s||(s=n?.value||"8765"),n&&(n.value=s);!("false"!==t.get("connect"))||this.isConnected()||this.isConnecting()||this.connect(s)}}class s{constructor(){this.currentTab="events",this.autoScroll=!0,this.selectedCard={tab:null,index:null,type:null,data:null},this.tabNavigation={events:{selectedIndex:-1,items:[]},agents:{selectedIndex:-1,items:[]},tools:{selectedIndex:-1,items:[]},files:{selectedIndex:-1,items:[]}},this.setupEventHandlers(),console.log("UI state manager initialized")}setupEventHandlers(){this.setupTabNavigation(),this.setupUnifiedKeyboardNavigation()}setupTabNavigation(){document.querySelectorAll(".tab-button").forEach(t=>{t.addEventListener("click",()=>{const e=this.getTabNameFromButton(t);this.switchTab(e)})})}setupUnifiedKeyboardNavigation(){document.addEventListener("keydown",t=>{document.activeElement&&["INPUT","TEXTAREA","SELECT"].includes(document.activeElement.tagName)||("ArrowUp"===t.key||"ArrowDown"===t.key?(t.preventDefault(),this.handleUnifiedArrowNavigation("ArrowDown"===t.key?1:-1)):"Enter"===t.key?(t.preventDefault(),this.handleUnifiedEnterKey()):"Escape"===t.key&&this.clearUnifiedSelection())})}getTabNameFromButton(t){const e=t.textContent.toLowerCase();return e.includes("events")?"events":e.includes("agents")?"agents":e.includes("tools")?"tools":e.includes("files")?"files":"events"}switchTab(t){console.log(`[DEBUG] switchTab called with tabName: ${t}`);const e=this.currentTab;this.currentTab=t,document.querySelectorAll(".tab-button").forEach(e=>{e.classList.remove("active"),this.getTabNameFromButton(e)===t&&e.classList.add("active")}),document.querySelectorAll(".tab-content").forEach(t=>{t.classList.remove("active")});const n=document.getElementById(`${t}-tab`);n&&n.classList.add("active"),this.clearUnifiedSelection(),document.dispatchEvent(new CustomEvent("tabChanged",{detail:{newTab:t,previousTab:e}})),setTimeout(()=>{this.autoScroll&&this.scrollCurrentTabToBottom()},100)}handleUnifiedArrowNavigation(t){const e=this.tabNavigation[this.currentTab];if(!e)return;let n=e.selectedIndex+t;0!==e.items.length&&(n<0?n=e.items.length-1:n>=e.items.length&&(n=0),this.selectCardByIndex(this.currentTab,n))}handleUnifiedEnterKey(){const t=this.tabNavigation[this.currentTab];if(!t||-1===t.selectedIndex)return;const e=t.items[t.selectedIndex];e&&e.onclick&&e.onclick()}clearUnifiedSelection(){Object.keys(this.tabNavigation).forEach(t=>{this.tabNavigation[t].selectedIndex=-1}),this.clearCardSelection()}updateTabNavigationItems(){const t=this.tabNavigation[this.currentTab];if(!t)return;let e;switch(this.currentTab){case"events":e="#events-list .event-item";break;case"agents":e="#agents-list .event-item";break;case"tools":e="#tools-list .event-item";break;case"files":e="#files-list .event-item"}e&&(t.items=Array.from(document.querySelectorAll(e)))}selectCardByIndex(t,e){const n=this.tabNavigation[t];if(!n||e<0||e>=n.items.length)return;n.selectedIndex=e,this.updateUnifiedSelectionUI();n.items[e]&&this.selectCard(t,e,this.getCardType(t),e),this.showCardDetails(t,e)}updateUnifiedSelectionUI(){document.querySelectorAll(".event-item.keyboard-selected").forEach(t=>{t.classList.remove("keyboard-selected")});const t=this.tabNavigation[this.currentTab];t&&-1!==t.selectedIndex&&t.items[t.selectedIndex]&&t.items[t.selectedIndex].classList.add("keyboard-selected")}showCardDetails(t,e){document.dispatchEvent(new CustomEvent("showCardDetails",{detail:{tabName:t,index:e}}))}selectCard(t,e,n,s){this.clearCardSelection(),this.selectedCard={tab:t,index:e,type:n,data:s},this.updateCardSelectionUI(),console.log("Card selected:",this.selectedCard)}clearCardSelection(){document.querySelectorAll(".event-item.selected, .file-item.selected").forEach(t=>{t.classList.remove("selected")}),this.selectedCard={tab:null,index:null,type:null,data:null}}updateCardSelectionUI(){if(!this.selectedCard.tab||null===this.selectedCard.index)return;let t;switch(this.selectedCard.tab){case"events":t=document.getElementById("events-list");break;case"agents":t=document.getElementById("agents-list");break;case"tools":t=document.getElementById("tools-list");break;case"files":t=document.getElementById("files-list")}if(t){const e=t.querySelectorAll(".event-item, .file-item");e[this.selectedCard.index]&&e[this.selectedCard.index].classList.add("selected")}}getCardType(t){switch(t){case"events":return"event";case"agents":return"agent";case"tools":return"tool";case"files":return"file";default:return"unknown"}}scrollCurrentTabToBottom(){const t=`${this.currentTab}-list`,e=document.getElementById(t);e&&this.autoScroll&&(e.scrollTop=e.scrollHeight)}clearSelection(){this.clearCardSelection(),this.clearUnifiedSelection()}getCurrentTab(){return this.currentTab}getSelectedCard(){return{...this.selectedCard}}getTabNavigation(){return{...this.tabNavigation}}setAutoScroll(t){this.autoScroll=t}getAutoScroll(){return this.autoScroll}}export{n as S,s as U};
|
|
2
2
|
//# sourceMappingURL=socket-client.js.map
|
|
@@ -280,10 +280,24 @@ class EventViewer {
|
|
|
280
280
|
* @returns {string} Formatted event type
|
|
281
281
|
*/
|
|
282
282
|
formatEventType(event) {
|
|
283
|
-
|
|
283
|
+
// If we have type and subtype, use them
|
|
284
|
+
if (event.type && event.subtype) {
|
|
285
|
+
// Check if type and subtype are identical to prevent "type.type" display
|
|
286
|
+
if (event.type === event.subtype) {
|
|
287
|
+
return event.type;
|
|
288
|
+
}
|
|
284
289
|
return `${event.type}.${event.subtype}`;
|
|
285
290
|
}
|
|
286
|
-
|
|
291
|
+
// If we have just type, use it
|
|
292
|
+
if (event.type) {
|
|
293
|
+
return event.type;
|
|
294
|
+
}
|
|
295
|
+
// If we have originalEventName (from transformation), use it as fallback
|
|
296
|
+
if (event.originalEventName) {
|
|
297
|
+
return event.originalEventName;
|
|
298
|
+
}
|
|
299
|
+
// Last resort fallback
|
|
300
|
+
return 'unknown';
|
|
287
301
|
}
|
|
288
302
|
|
|
289
303
|
/**
|
|
@@ -538,7 +552,14 @@ class EventViewer {
|
|
|
538
552
|
'notification': 'Notification'
|
|
539
553
|
};
|
|
540
554
|
|
|
541
|
-
|
|
555
|
+
// Handle non-string hookType safely
|
|
556
|
+
if (hookNames[hookType]) {
|
|
557
|
+
return hookNames[hookType];
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// Convert to string and handle null/undefined
|
|
561
|
+
const typeStr = String(hookType || 'unknown');
|
|
562
|
+
return typeStr.replace(/_/g, ' ');
|
|
542
563
|
}
|
|
543
564
|
|
|
544
565
|
/**
|
|
@@ -74,9 +74,9 @@ class FileToolTracker {
|
|
|
74
74
|
}
|
|
75
75
|
|
|
76
76
|
const pair = eventPairs.get(eventKey);
|
|
77
|
-
if (event.subtype === 'pre_tool' || event.type === 'hook' && !event.subtype.includes('post')) {
|
|
77
|
+
if (event.subtype === 'pre_tool' || (event.type === 'hook' && event.subtype && !event.subtype.includes('post'))) {
|
|
78
78
|
pair.pre_event = event;
|
|
79
|
-
} else if (event.subtype === 'post_tool' || event.subtype.includes('post')) {
|
|
79
|
+
} else if (event.subtype === 'post_tool' || (event.subtype && event.subtype.includes('post'))) {
|
|
80
80
|
pair.post_event = event;
|
|
81
81
|
} else {
|
|
82
82
|
// For events without clear pre/post distinction, treat as both
|
|
@@ -162,9 +162,9 @@ class FileToolTracker {
|
|
|
162
162
|
}
|
|
163
163
|
|
|
164
164
|
if (isToolOp) {
|
|
165
|
-
if (event.subtype === 'pre_tool' || (event.type === 'hook' && !event.subtype.includes('post'))) {
|
|
165
|
+
if (event.subtype === 'pre_tool' || (event.type === 'hook' && event.subtype && !event.subtype.includes('post'))) {
|
|
166
166
|
preToolEvents.push(event);
|
|
167
|
-
} else if (event.subtype === 'post_tool' || event.subtype.includes('post')) {
|
|
167
|
+
} else if (event.subtype === 'post_tool' || (event.subtype && event.subtype.includes('post'))) {
|
|
168
168
|
postToolEvents.push(event);
|
|
169
169
|
} else {
|
|
170
170
|
// For events without clear pre/post distinction, treat as standalone
|
|
@@ -321,7 +321,7 @@ class FileToolTracker {
|
|
|
321
321
|
const hasToolName = event.tool_name || (event.data && event.data.tool_name);
|
|
322
322
|
const isHookEvent = event.type === 'hook';
|
|
323
323
|
const isToolSubtype = event.subtype === 'pre_tool' || event.subtype === 'post_tool' ||
|
|
324
|
-
(event.subtype && event.subtype.includes('tool'));
|
|
324
|
+
(event.subtype && typeof event.subtype === 'string' && event.subtype.includes('tool'));
|
|
325
325
|
|
|
326
326
|
return hasToolName && isHookEvent && isToolSubtype;
|
|
327
327
|
}
|