mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-24 14:16:34 +09:00
🏁 Session end checkpoint: session-20250926-175950
This commit is contained in:
1 parent
51bf28fb93
commit
2f2fb4e99b
127 files changed
+4230
-58868
No files matched your search
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"startTime": 1758909300011,
|
||||
"startTime": 1758909566305,
|
||||
"totalTasks": 1,
|
||||
"successfulTasks": 1,
|
||||
"failedTasks": 0,
|
||||
|
||||
+3584
-3404
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,10 @@
|
||||
[
|
||||
{
|
||||
"id": "cmd-hooks-1758909300111",
|
||||
"id": "cmd-hooks-1758909566410",
|
||||
"type": "hooks",
|
||||
"success": true,
|
||||
"duration": 35.59752699999996,
|
||||
"timestamp": 1758909300147,
|
||||
"duration": 9.132583000000011,
|
||||
"timestamp": 1758909566419,
|
||||
"metadata": {}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
{"branch": "checkpoint/pre-edit-20250926-175740", "file": "/workspaces/claude-code-flow/package.json", "timestamp": "2025-09-26T17:57:40Z", "type": "pre-edit", "original_branch": "alpha-125"}
|
||||
@@ -0,0 +1 @@
|
||||
{"tag": "checkpoint-20250926-175741", "file": "/workspaces/claude-code-flow/package.json", "timestamp": "2025-09-26T17:57:41Z", "type": "post-edit", "branch": "alpha-125", "diff_summary": " .claude-flow/metrics/performance.json | 2 +- .claude-flow/metrics/system-metrics.json | 48 + .claude-flow/metrics/task-metrics.json | 6 +- .claude/checkpoints/task-1758909345.json | 1 + claude-flow-wiki | 0 dist-cjs/src/cli/help-formatter.js | 5 - dist-cjs/src/cli/simple-cli.js | 353 ++-- dist-cjs/src/cli/simple-cli.js.map | 2 +- dist-cjs/src/cli/simple-commands/hive-mind.js | 8 + dist-cjs/src/cli/simple-commands/hive-mind.js.map | 2 +- .../cli/simple-commands/inject-memory-protocol.js | 200 +++ .../simple-commands/inject-memory-protocol.js.map | 1 + dist-cjs/src/cli/simple-commands/swarm.js | 8 + dist-cjs/src/cli/simple-commands/swarm.js.map | 2 +- dist-cjs/src/ui/console/js/analysis-tools.js | 941 ---------- dist-cjs/src/ui/console/js/analysis-tools.js.map | 1 - dist-cjs/src/ui/console/js/command-handler.js | 667 -------- dist-cjs/src/ui/console/js/command-handler.js.map | 1 - dist-cjs/src/ui/console/js/console.js | 410 ----- dist-cjs/src/ui/console/js/console.js.map | 1 - dist-cjs/src/ui/console/js/daa-tools.js | 891 ---------- dist-cjs/src/ui/console/js/daa-tools.js.map | 1 - dist-cjs/src/ui/console/js/memory-interface.js | 792 --------- dist-cjs/src/ui/console/js/memory-interface.js.map | 1 - dist-cjs/src/ui/console/js/memory-test.js | 178 -- dist-cjs/src/ui/console/js/memory-test.js.map | 1 - dist-cjs/src/ui/console/js/memory-tools.js | 1270 -------------- dist-cjs/src/ui/console/js/memory-tools.js.map | 1 - dist-cjs/src/ui/console/js/real-time-dashboard.js | 548 ------ .../src/ui/console/js/real-time-dashboard.js.map | 1 - dist-cjs/src/ui/console/js/settings.js | 406 ----- dist-cjs/src/ui/console/js/settings.js.map | 1 - dist-cjs/src/ui/console/js/swarm-integration.js | 359 ---- .../src/ui/console/js/swarm-integration.js.map | 1 - dist-cjs/src/ui/console/js/swarm-visualizer.js | 661 ------- dist-cjs/src/ui/console/js/swarm-visualizer.js.map | 1 - dist-cjs/src/ui/console/js/terminal-emulator.js | 444 ----- .../src/ui/console/js/terminal-emulator.js.map | 1 - dist-cjs/src/ui/console/js/websocket-client.js | 360 ---- dist-cjs/src/ui/console/js/websocket-client.js.map | 1 - dist-cjs/src/ui/console/js/workflow-designer.js | 1577 ----------------- .../src/ui/console/js/workflow-designer.js.map | 1 - dist-cjs/src/ui/console/test-neural-networks.js | 220 --- .../src/ui/console/test-neural-networks.js.map | 1 - dist-cjs/src/ui/hive-dashboard.js | 240 --- dist-cjs/src/ui/hive-dashboard.js.map | 1 - dist-cjs/src/ui/web-ui/EnhancedProcessUI.js | 1775 ------------------- dist-cjs/src/ui/web-ui/EnhancedProcessUI.js.map | 1 - dist-cjs/src/ui/web-ui/EnhancedWebUI.js | 420 ----- dist-cjs/src/ui/web-ui/EnhancedWebUI.js.map | 1 - .../src/ui/web-ui/components/ComponentLibrary.js | 872 ---------- .../ui/web-ui/components/ComponentLibrary.js.map | 1 - dist-cjs/src/ui/web-ui/core/EventBus.js | 359 ---- dist-cjs/src/ui/web-ui/core/EventBus.js.map | 1 - dist-cjs/src/ui/web-ui/core/MCPIntegrationLayer.js | 948 ---------- .../src/ui/web-ui/core/MCPIntegrationLayer.js.map | 1 - dist-cjs/src/ui/web-ui/core/StateManager.js | 356 ---- dist-cjs/src/ui/web-ui/core/StateManager.js.map | 1 - dist-cjs/src/ui/web-ui/core/UIManager.js | 419 ----- dist-cjs/src/ui/web-ui/core/UIManager.js.map | 1 - dist-cjs/src/ui/web-ui/core/ViewManager.js | 449 ----- dist-cjs/src/ui/web-ui/core/ViewManager.js.map | 1 - dist-cjs/src/ui/web-ui/index.js | 242 --- dist-cjs/src/ui/web-ui/index.js.map | 1 - dist-cjs/src/ui/web-ui/neural-panel-test.js | 326 ---- dist-cjs/src/ui/web-ui/neural-panel-test.js.map | 1 - dist-cjs/src/ui/web-ui/test-github-view.js | 64 - dist-cjs/src/ui/web-ui/test-github-view.js.map | 1 - dist-cjs/src/ui/web-ui/views/DAAView.js | 1593 ----------------- dist-cjs/src/ui/web-ui/views/DAAView.js.map | 1 - .../src/ui/web-ui/views/GitHubIntegrationTest.js | 182 -- .../ui/web-ui/views/GitHubIntegrationTest.js.map | 1 - .../src/ui/web-ui/views/GitHubIntegrationView.js | 1356 --------------- .../ui/web-ui/views/GitHubIntegrationView.js.map | 1 - dist-cjs/src/ui/web-ui/views/NeuralNetworkView.js | 795 --------- .../src/ui/web-ui/views/NeuralNeLine truncated
|
||||
@@ -0,0 +1,396 @@
|
||||
# Session Summary - 2025-09-26 17:59:50
|
||||
|
||||
## Checkpoints Created
|
||||
1758899542.json
|
||||
1758899543.json
|
||||
1758899689.json
|
||||
1758899690.json
|
||||
1758899920.json
|
||||
1758899921.json
|
||||
1758899927.json
|
||||
1758899929.json
|
||||
1758899935.json
|
||||
1758899936.json
|
||||
1758900019.json
|
||||
1758900020.json
|
||||
1758900085.json
|
||||
1758900087.json
|
||||
1758900094.json
|
||||
1758900095.json
|
||||
1758900254.json
|
||||
1758900256.json
|
||||
1758900262.json
|
||||
1758900264.json
|
||||
1758900279.json
|
||||
1758900281.json
|
||||
1758900322.json
|
||||
1758900324.json
|
||||
1758900339.json
|
||||
1758900340.json
|
||||
1758900477.json
|
||||
1758900479.json
|
||||
1758900652.json
|
||||
1758900653.json
|
||||
1758900668.json
|
||||
1758900670.json
|
||||
1758900676.json
|
||||
1758900677.json
|
||||
1758901378.json
|
||||
1758901379.json
|
||||
1758901397.json
|
||||
1758901398.json
|
||||
1758906498.json
|
||||
1758906500.json
|
||||
1758906541.json
|
||||
1758906542.json
|
||||
1758906566.json
|
||||
1758906568.json
|
||||
1758906576.json
|
||||
1758906577.json
|
||||
1758906592.json
|
||||
1758906594.json
|
||||
1758906672.json
|
||||
1758906673.json
|
||||
1758907923.json
|
||||
1758907924.json
|
||||
1758907948.json
|
||||
1758907949.json
|
||||
1758907963.json
|
||||
1758907965.json
|
||||
1758908014.json
|
||||
1758908015.json
|
||||
1758908060.json
|
||||
1758908062.json
|
||||
1758908110.json
|
||||
1758908112.json
|
||||
1758908164.json
|
||||
1758908166.json
|
||||
1758908191.json
|
||||
1758908192.json
|
||||
1758908244.json
|
||||
1758908246.json
|
||||
1758908298.json
|
||||
1758908300.json
|
||||
1758908507.json
|
||||
1758908508.json
|
||||
1758908542.json
|
||||
1758908543.json
|
||||
1758908614.json
|
||||
1758908650.json
|
||||
1758908688.json
|
||||
1758908690.json
|
||||
1758908711.json
|
||||
1758908713.json
|
||||
1758908734.json
|
||||
1758908735.json
|
||||
1758908976.json
|
||||
1758908978.json
|
||||
1758909003.json
|
||||
1758909004.json
|
||||
1758909040.json
|
||||
1758909042.json
|
||||
1758909059.json
|
||||
1758909061.json
|
||||
1758909079.json
|
||||
1758909080.json
|
||||
1758909460.json
|
||||
1758909461.json
|
||||
task-1758897441.json
|
||||
task-1758897633.json
|
||||
task-1758897700.json
|
||||
task-1758897778.json
|
||||
task-1758897849.json
|
||||
task-1758898177.json
|
||||
task-1758898262.json
|
||||
task-1758898292.json
|
||||
task-1758898768.json
|
||||
task-1758898901.json
|
||||
task-1758899153.json
|
||||
task-1758899343.json
|
||||
task-1758899432.json
|
||||
task-1758899657.json
|
||||
task-1758900179.json
|
||||
task-1758900466.json
|
||||
task-1758900887.json
|
||||
task-1758901024.json
|
||||
task-1758901161.json
|
||||
task-1758901317.json
|
||||
task-1758901716.json
|
||||
task-1758905291.json
|
||||
task-1758906389.json
|
||||
task-1758906470.json
|
||||
task-1758907797.json
|
||||
task-1758908385.json
|
||||
task-1758908593.json
|
||||
task-1758908830.json
|
||||
task-1758909193.json
|
||||
task-1758909345.json
|
||||
|
||||
## Files Modified
|
||||
.claude-flow/metrics/performance.json
|
||||
.claude-flow/metrics/system-metrics.json
|
||||
.claude-flow/metrics/task-metrics.json
|
||||
.claude/agents/MIGRATION_SUMMARY.md
|
||||
.claude/agents/README.md
|
||||
.claude/agents/consensus/README.md
|
||||
.claude/agents/core/coder.md
|
||||
.claude/agents/core/planner.md
|
||||
.claude/agents/core/researcher.md
|
||||
.claude/agents/core/reviewer.md
|
||||
.claude/agents/core/tester.md
|
||||
.claude/agents/hive-mind/collective-intelligence-coordinator.md
|
||||
.claude/agents/hive-mind/queen-coordinator.md
|
||||
.claude/agents/hive-mind/scout-explorer.md
|
||||
.claude/agents/hive-mind/swarm-memory-manager.md
|
||||
.claude/agents/hive-mind/worker-specialist.md
|
||||
.claude/agents/optimization/README.md
|
||||
.claude/agents/swarm/README.md
|
||||
.claude/agents/swarm/hierarchical-coordinator.md
|
||||
.claude/agents/templates/coordinator-swarm-init.md
|
||||
.claude/checkpoints/1758906498.json
|
||||
.claude/checkpoints/1758906500.json
|
||||
.claude/checkpoints/1758906541.json
|
||||
.claude/checkpoints/1758906542.json
|
||||
.claude/checkpoints/1758906566.json
|
||||
.claude/checkpoints/1758906568.json
|
||||
.claude/checkpoints/1758906576.json
|
||||
.claude/checkpoints/1758906577.json
|
||||
.claude/checkpoints/1758906592.json
|
||||
.claude/checkpoints/1758906594.json
|
||||
.claude/checkpoints/1758906672.json
|
||||
.claude/checkpoints/1758906673.json
|
||||
.claude/checkpoints/1758907923.json
|
||||
.claude/checkpoints/1758907924.json
|
||||
.claude/checkpoints/1758907948.json
|
||||
.claude/checkpoints/1758907949.json
|
||||
.claude/checkpoints/1758907963.json
|
||||
.claude/checkpoints/1758907965.json
|
||||
.claude/checkpoints/1758908014.json
|
||||
.claude/checkpoints/1758908015.json
|
||||
.claude/checkpoints/1758908060.json
|
||||
.claude/checkpoints/1758908062.json
|
||||
.claude/checkpoints/1758908110.json
|
||||
.claude/checkpoints/1758908112.json
|
||||
.claude/checkpoints/1758908164.json
|
||||
.claude/checkpoints/1758908166.json
|
||||
.claude/checkpoints/1758908191.json
|
||||
.claude/checkpoints/1758908192.json
|
||||
.claude/checkpoints/1758908244.json
|
||||
.claude/checkpoints/1758908246.json
|
||||
.claude/checkpoints/1758908298.json
|
||||
.claude/checkpoints/1758908300.json
|
||||
.claude/checkpoints/1758908507.json
|
||||
.claude/checkpoints/1758908508.json
|
||||
.claude/checkpoints/1758908542.json
|
||||
.claude/checkpoints/1758908543.json
|
||||
.claude/checkpoints/1758908614.json
|
||||
.claude/checkpoints/1758908650.json
|
||||
.claude/checkpoints/1758908688.json
|
||||
.claude/checkpoints/1758908690.json
|
||||
.claude/checkpoints/1758908711.json
|
||||
.claude/checkpoints/1758908713.json
|
||||
.claude/checkpoints/1758908734.json
|
||||
.claude/checkpoints/1758908735.json
|
||||
.claude/checkpoints/1758908976.json
|
||||
.claude/checkpoints/1758908978.json
|
||||
.claude/checkpoints/1758909003.json
|
||||
.claude/checkpoints/1758909004.json
|
||||
.claude/checkpoints/1758909040.json
|
||||
.claude/checkpoints/1758909042.json
|
||||
.claude/checkpoints/1758909059.json
|
||||
.claude/checkpoints/1758909061.json
|
||||
.claude/checkpoints/1758909079.json
|
||||
.claude/checkpoints/1758909080.json
|
||||
.claude/checkpoints/summary-session-20250926-170658.md
|
||||
.claude/checkpoints/summary-session-20250926-171226.md
|
||||
.claude/checkpoints/summary-session-20250926-173942.md
|
||||
.claude/checkpoints/summary-session-20250926-174627.md
|
||||
.claude/checkpoints/summary-session-20250926-175225.md
|
||||
.claude/checkpoints/summary-session-20250926-175458.md
|
||||
.claude/checkpoints/task-1758906389.json
|
||||
.claude/checkpoints/task-1758906470.json
|
||||
.claude/checkpoints/task-1758907797.json
|
||||
.claude/checkpoints/task-1758908385.json
|
||||
.claude/checkpoints/task-1758908593.json
|
||||
.claude/checkpoints/task-1758908830.json
|
||||
.claude/checkpoints/task-1758909193.json
|
||||
.claude/checkpoints/task-1758909345.json
|
||||
.claude/commands/agents/README.md
|
||||
.claude/commands/agents/agent-spawning.md
|
||||
.claude/commands/analysis/README.md
|
||||
.claude/commands/automation/README.md
|
||||
.claude/commands/automation/smart-spawn.md
|
||||
.claude/commands/coordination/README.md
|
||||
.claude/commands/coordination/task-orchestrate.md
|
||||
.claude/commands/github/README.md
|
||||
.claude/commands/hive-mind/README.md
|
||||
.claude/commands/hive-mind/hive-mind-spawn.md
|
||||
.claude/commands/hooks/README.md
|
||||
.claude/commands/hooks/overview.md
|
||||
.claude/commands/memory/README.md
|
||||
.claude/commands/memory/memory-usage.md
|
||||
.claude/commands/monitoring/README.md
|
||||
.claude/commands/optimization/README.md
|
||||
.claude/commands/pair/README.md
|
||||
.claude/commands/swarm/README.md
|
||||
.claude/commands/training/README.md
|
||||
.claude/commands/workflows/README.md
|
||||
.gitignore
|
||||
CLAUDE.md
|
||||
claude-flow-wiki
|
||||
dist-cjs/src/cli/simple-cli.js
|
||||
dist-cjs/src/cli/simple-cli.js.map
|
||||
dist-cjs/src/cli/simple-commands/hive-mind.js
|
||||
dist-cjs/src/cli/simple-commands/hive-mind.js.map
|
||||
dist-cjs/src/cli/simple-commands/inject-memory-protocol.js
|
||||
dist-cjs/src/cli/simple-commands/inject-memory-protocol.js.map
|
||||
dist-cjs/src/cli/simple-commands/swarm.js
|
||||
dist-cjs/src/cli/simple-commands/swarm.js.map
|
||||
dist-cjs/src/ui/console/js/analysis-tools.js
|
||||
dist-cjs/src/ui/console/js/analysis-tools.js.map
|
||||
dist-cjs/src/ui/console/js/command-handler.js
|
||||
dist-cjs/src/ui/console/js/command-handler.js.map
|
||||
dist-cjs/src/ui/console/js/console.js
|
||||
dist-cjs/src/ui/console/js/console.js.map
|
||||
dist-cjs/src/ui/console/js/daa-tools.js
|
||||
dist-cjs/src/ui/console/js/daa-tools.js.map
|
||||
dist-cjs/src/ui/console/js/memory-interface.js
|
||||
dist-cjs/src/ui/console/js/memory-interface.js.map
|
||||
dist-cjs/src/ui/console/js/memory-test.js
|
||||
dist-cjs/src/ui/console/js/memory-test.js.map
|
||||
dist-cjs/src/ui/console/js/memory-tools.js
|
||||
dist-cjs/src/ui/console/js/memory-tools.js.map
|
||||
dist-cjs/src/ui/console/js/real-time-dashboard.js
|
||||
dist-cjs/src/ui/console/js/real-time-dashboard.js.map
|
||||
dist-cjs/src/ui/console/js/settings.js
|
||||
dist-cjs/src/ui/console/js/settings.js.map
|
||||
dist-cjs/src/ui/console/js/swarm-integration.js
|
||||
dist-cjs/src/ui/console/js/swarm-integration.js.map
|
||||
dist-cjs/src/ui/console/js/swarm-visualizer.js
|
||||
dist-cjs/src/ui/console/js/swarm-visualizer.js.map
|
||||
dist-cjs/src/ui/console/js/terminal-emulator.js
|
||||
dist-cjs/src/ui/console/js/terminal-emulator.js.map
|
||||
dist-cjs/src/ui/console/js/websocket-client.js
|
||||
dist-cjs/src/ui/console/js/websocket-client.js.map
|
||||
dist-cjs/src/ui/console/js/workflow-designer.js
|
||||
dist-cjs/src/ui/console/js/workflow-designer.js.map
|
||||
dist-cjs/src/ui/console/test-neural-networks.js
|
||||
dist-cjs/src/ui/console/test-neural-networks.js.map
|
||||
dist-cjs/src/ui/hive-dashboard.js
|
||||
dist-cjs/src/ui/hive-dashboard.js.map
|
||||
dist-cjs/src/ui/web-ui/EnhancedProcessUI.js
|
||||
dist-cjs/src/ui/web-ui/EnhancedProcessUI.js.map
|
||||
dist-cjs/src/ui/web-ui/EnhancedWebUI.js
|
||||
dist-cjs/src/ui/web-ui/EnhancedWebUI.js.map
|
||||
dist-cjs/src/ui/web-ui/components/ComponentLibrary.js
|
||||
dist-cjs/src/ui/web-ui/components/ComponentLibrary.js.map
|
||||
dist-cjs/src/ui/web-ui/core/EventBus.js
|
||||
dist-cjs/src/ui/web-ui/core/EventBus.js.map
|
||||
dist-cjs/src/ui/web-ui/core/MCPIntegrationLayer.js
|
||||
dist-cjs/src/ui/web-ui/core/MCPIntegrationLayer.js.map
|
||||
dist-cjs/src/ui/web-ui/core/StateManager.js
|
||||
dist-cjs/src/ui/web-ui/core/StateManager.js.map
|
||||
dist-cjs/src/ui/web-ui/core/UIManager.js
|
||||
dist-cjs/src/ui/web-ui/core/UIManager.js.map
|
||||
dist-cjs/src/ui/web-ui/core/ViewManager.js
|
||||
dist-cjs/src/ui/web-ui/core/ViewManager.js.map
|
||||
dist-cjs/src/ui/web-ui/index.js
|
||||
dist-cjs/src/ui/web-ui/index.js.map
|
||||
dist-cjs/src/ui/web-ui/neural-panel-test.js
|
||||
dist-cjs/src/ui/web-ui/neural-panel-test.js.map
|
||||
dist-cjs/src/ui/web-ui/test-github-view.js
|
||||
dist-cjs/src/ui/web-ui/test-github-view.js.map
|
||||
dist-cjs/src/ui/web-ui/views/DAAView.js
|
||||
dist-cjs/src/ui/web-ui/views/DAAView.js.map
|
||||
dist-cjs/src/ui/web-ui/views/GitHubIntegrationTest.js
|
||||
dist-cjs/src/ui/web-ui/views/GitHubIntegrationTest.js.map
|
||||
dist-cjs/src/ui/web-ui/views/GitHubIntegrationView.js
|
||||
dist-cjs/src/ui/web-ui/views/GitHubIntegrationView.js.map
|
||||
dist-cjs/src/ui/web-ui/views/NeuralNetworkView.js
|
||||
dist-cjs/src/ui/web-ui/views/NeuralNetworkView.js.map
|
||||
dist-cjs/src/ui/web-ui/views/WorkflowAutomationView.js
|
||||
dist-cjs/src/ui/web-ui/views/WorkflowAutomationView.js.map
|
||||
dist-cjs/src/utils/metrics-reader.js
|
||||
examples/memory-coordination-example.md
|
||||
package.json
|
||||
src/cli/simple-commands/hive-mind.js
|
||||
src/cli/simple-commands/inject-memory-protocol.js
|
||||
src/cli/simple-commands/swarm.js
|
||||
src/ui/console/README-analysis-tools.md
|
||||
src/ui/console/README.md
|
||||
src/ui/console/WORKFLOW_DESIGNER_README.md
|
||||
src/ui/console/analysis-tools.html
|
||||
src/ui/console/analytics.html
|
||||
src/ui/console/index.html
|
||||
src/ui/console/js/analysis-tools.js
|
||||
src/ui/console/js/command-handler.js
|
||||
src/ui/console/js/console.js
|
||||
src/ui/console/js/daa-tools.js
|
||||
src/ui/console/js/memory-interface.js
|
||||
src/ui/console/js/memory-test.js
|
||||
src/ui/console/js/memory-tools.js
|
||||
src/ui/console/js/real-time-dashboard.js
|
||||
src/ui/console/js/settings.js
|
||||
src/ui/console/js/swarm-integration.js
|
||||
src/ui/console/js/swarm-visualizer.js
|
||||
src/ui/console/js/terminal-emulator.js
|
||||
src/ui/console/js/websocket-client.js
|
||||
src/ui/console/js/workflow-designer.js
|
||||
src/ui/console/neural-networks-demo.md
|
||||
src/ui/console/styles/analysis-tools.css
|
||||
src/ui/console/styles/console.css
|
||||
src/ui/console/styles/daa-tools.css
|
||||
src/ui/console/styles/responsive.css
|
||||
src/ui/console/styles/settings.css
|
||||
src/ui/console/styles/swarm-visualizer.css
|
||||
src/ui/console/styles/workflow-designer.css
|
||||
src/ui/console/test-neural-networks.js
|
||||
src/ui/console/test-neural.html
|
||||
src/ui/console/workflow-designer-demo.html
|
||||
src/ui/hive-dashboard.ts
|
||||
src/ui/web-ui/EnhancedProcessUI.js
|
||||
src/ui/web-ui/EnhancedWebUI.js
|
||||
src/ui/web-ui/README.md
|
||||
src/ui/web-ui/components/ComponentLibrary.js
|
||||
src/ui/web-ui/core/EventBus.js
|
||||
src/ui/web-ui/core/MCPIntegrationLayer.js
|
||||
src/ui/web-ui/core/StateManager.js
|
||||
src/ui/web-ui/core/UIManager.js
|
||||
src/ui/web-ui/core/ViewManager.js
|
||||
src/ui/web-ui/index.js
|
||||
src/ui/web-ui/neural-panel-test.js
|
||||
src/ui/web-ui/test-github-view.js
|
||||
src/ui/web-ui/test-neural-panel.html
|
||||
src/ui/web-ui/views/DAAView.js
|
||||
src/ui/web-ui/views/GitHubIntegrationTest.js
|
||||
src/ui/web-ui/views/GitHubIntegrationView.js
|
||||
src/ui/web-ui/views/NeuralNetworkView.js
|
||||
src/ui/web-ui/views/WorkflowAutomationView.js
|
||||
|
||||
## Recent Commits
|
||||
a4bae50e2 🔖 Checkpoint: Edit /workspaces/claude-code-flow/package.json
|
||||
adfebf94a 🔖 Checkpoint: Edit /workspaces/claude-code-flow/.claude/agents/core/reviewer.md
|
||||
a218853e0 🔖 Checkpoint: Edit /workspaces/claude-code-flow/.claude/agents/core/planner.md
|
||||
07d35ca83 🔖 Checkpoint: Edit /workspaces/claude-code-flow/.claude/agents/core/researcher.md
|
||||
4e9d15391 🔖 Checkpoint: Edit /workspaces/claude-code-flow/.claude/agents/core/tester.md
|
||||
1bce8f7a8 🔖 Checkpoint: Edit /workspaces/claude-code-flow/.claude/agents/core/coder.md
|
||||
a52ca8e54 🔖 Checkpoint: Edit /workspaces/claude-code-flow/.claude/commands/hooks/overview.md
|
||||
18db98ab2 🔖 Checkpoint: Edit /workspaces/claude-code-flow/.claude/commands/hooks/overview.md
|
||||
cd341c287 🔖 Checkpoint: Edit /workspaces/claude-code-flow/.claude/commands/automation/smart-spawn.md
|
||||
40624db73 🔖 Checkpoint: Edit /workspaces/claude-code-flow/.claude/commands/agents/agent-spawning.md
|
||||
|
||||
## GitHub Releases Created
|
||||
No GitHub releases
|
||||
|
||||
## Rollback Instructions
|
||||
To rollback to a specific checkpoint:
|
||||
```bash
|
||||
# List all checkpoints
|
||||
git tag -l checkpoint-* | sort -r
|
||||
|
||||
# List GitHub releases
|
||||
gh release list
|
||||
|
||||
# Rollback to a checkpoint
|
||||
git checkout checkpoint-YYYYMMDD-HHMMSS
|
||||
```
|
||||
+188
-165
@@ -1,47 +1,13 @@
|
||||
#!/usr/bin/env node
|
||||
#!/usr/bin/env -S deno run --allow-all
|
||||
import { promises as fs } from 'node:fs';
|
||||
import { executeCommand, hasCommand, showCommandHelp, listCommands } from './command-registry.js';
|
||||
import { parseFlags } from './utils.js';
|
||||
import { args, cwd, isMainModule, exit, readTextFile, writeTextFile, mkdirAsync, errors } from './node-compat.js';
|
||||
import { spawn } from 'child_process';
|
||||
import process from 'process';
|
||||
import readline from 'readline';
|
||||
import { getMainHelp, getCommandHelp, getStandardizedCommandHelp } from './help-text.js';
|
||||
import { VERSION } from '../core/version.js';
|
||||
const LEGACY_AGENT_MAPPING = {
|
||||
analyst: 'code-analyzer',
|
||||
coordinator: 'task-orchestrator',
|
||||
optimizer: 'perf-analyzer',
|
||||
documenter: 'api-docs',
|
||||
monitor: 'performance-benchmarker',
|
||||
specialist: 'system-architect',
|
||||
architect: 'system-architect'
|
||||
};
|
||||
function resolveLegacyAgentType(legacyType) {
|
||||
return LEGACY_AGENT_MAPPING[legacyType] || legacyType;
|
||||
}
|
||||
function printHelp(plain = false) {
|
||||
console.log(getMainHelp(plain));
|
||||
}
|
||||
function printCommandHelp(command) {
|
||||
const standardCommands = [
|
||||
'agent',
|
||||
'sparc',
|
||||
'memory'
|
||||
];
|
||||
if (standardCommands.includes(command)) {
|
||||
const help = getStandardizedCommandHelp(command);
|
||||
console.log(help);
|
||||
} else {
|
||||
const help = getCommandHelp(command);
|
||||
console.log(help);
|
||||
}
|
||||
}
|
||||
function printLegacyHelp() {
|
||||
function printHelp() {
|
||||
console.log(`
|
||||
🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform
|
||||
|
||||
🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 90+ MCP tools, neural networking, and production-ready infrastructure
|
||||
⚡ ALPHA 85: Advanced automation capabilities & stream-JSON chaining for multi-agent pipelines
|
||||
🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 27 MCP tools, neural networking, and production-ready infrastructure
|
||||
|
||||
USAGE:
|
||||
claude-flow <command> [options]
|
||||
@@ -175,8 +141,8 @@ function printSuccess(message) {
|
||||
function printWarning(message) {
|
||||
console.warn(`⚠️ Warning: ${message}`);
|
||||
}
|
||||
function showHelpWithCommands(plain = false) {
|
||||
printHelp(plain);
|
||||
function showHelpWithCommands() {
|
||||
printHelp();
|
||||
console.log('\nRegistered Commands:');
|
||||
const commands = listCommands();
|
||||
for (const command of commands){
|
||||
@@ -185,58 +151,14 @@ function showHelpWithCommands(plain = false) {
|
||||
console.log('\nUse "claude-flow help <command>" for detailed usage information');
|
||||
}
|
||||
async function main() {
|
||||
const args = Deno.args;
|
||||
if (args.length === 0) {
|
||||
printHelp(usePlainHelp);
|
||||
printHelp();
|
||||
return;
|
||||
}
|
||||
const command = args[0];
|
||||
const { flags, args: parsedArgs } = parseFlags(args.slice(1));
|
||||
const usePlainHelp = args.includes('--plain');
|
||||
let enhancedFlags = flags;
|
||||
try {
|
||||
const { detectExecutionEnvironment, applySmartDefaults } = await import('./utils/environment-detector.js');
|
||||
enhancedFlags = applySmartDefaults(flags);
|
||||
enhancedFlags._environment = detectExecutionEnvironment({
|
||||
skipWarnings: true
|
||||
});
|
||||
} catch (e) {
|
||||
enhancedFlags = flags;
|
||||
}
|
||||
if (command !== 'help' && command !== '--help' && command !== '-h' && (enhancedFlags.help || enhancedFlags.h)) {
|
||||
const detailedHelp = getCommandHelp(command);
|
||||
if (detailedHelp && !detailedHelp.includes('Help not available')) {
|
||||
printCommandHelp(command);
|
||||
} else if (hasCommand(command)) {
|
||||
showCommandHelp(command);
|
||||
} else {
|
||||
printError(`Unknown command: ${command}`);
|
||||
console.log('\nRun "claude-flow --help" to see available commands.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
switch(command){
|
||||
case 'env-check':
|
||||
case 'environment':
|
||||
if (enhancedFlags._environment) {
|
||||
const env = enhancedFlags._environment;
|
||||
console.log(`\n🖥️ Environment Detection Results:`);
|
||||
console.log(` Terminal: ${env.terminalType}`);
|
||||
console.log(` Interactive: ${env.isInteractive ? 'Yes' : 'No'}`);
|
||||
console.log(` TTY Support: ${env.supportsRawMode ? 'Yes' : 'No'}`);
|
||||
console.log(` Detected: ${env.isVSCode ? 'VS Code' : env.isCI ? 'CI/CD' : env.isDocker ? 'Docker' : env.isSSH ? 'SSH' : 'Standard Terminal'}`);
|
||||
if (env.recommendedFlags.length > 0) {
|
||||
console.log(`\n💡 Recommended flags:`);
|
||||
console.log(` ${env.recommendedFlags.join(' ')}`);
|
||||
}
|
||||
if (enhancedFlags.appliedDefaults && enhancedFlags.appliedDefaults.length > 0) {
|
||||
console.log(`\n✅ Auto-applied:`);
|
||||
console.log(` ${enhancedFlags.appliedDefaults.join(' ')}`);
|
||||
}
|
||||
console.log();
|
||||
} else {
|
||||
console.log('Environment detection not available');
|
||||
}
|
||||
return;
|
||||
case 'version':
|
||||
case '--version':
|
||||
case '-v':
|
||||
@@ -246,14 +168,9 @@ async function main() {
|
||||
case '--help':
|
||||
case '-h':
|
||||
if (parsedArgs.length > 0) {
|
||||
const detailedHelp = getCommandHelp(parsedArgs[0]);
|
||||
if (detailedHelp && !detailedHelp.includes('Help not available')) {
|
||||
printCommandHelp(parsedArgs[0]);
|
||||
} else {
|
||||
showCommandHelp(parsedArgs[0]);
|
||||
}
|
||||
showCommandHelp(parsedArgs[0]);
|
||||
} else {
|
||||
printHelp(usePlainHelp);
|
||||
showHelpWithCommands();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -263,7 +180,6 @@ async function main() {
|
||||
return;
|
||||
} catch (err) {
|
||||
printError(err.message);
|
||||
console.log(`\nRun "claude-flow ${command} --help" for usage information.`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -283,12 +199,11 @@ async function main() {
|
||||
console.log('📊 Real-time monitoring would display here');
|
||||
break;
|
||||
case 'spawn':
|
||||
const rawSpawnType = subArgs[0] || 'general';
|
||||
const spawnType = resolveLegacyAgentType(rawSpawnType);
|
||||
const spawnType = subArgs[0] || 'general';
|
||||
const spawnName = flags.name || `agent-${Date.now()}`;
|
||||
printSuccess(`Spawning ${spawnType} agent: ${spawnName}`);
|
||||
console.log('🤖 Agent would be created with the following configuration:');
|
||||
console.log(` Type: ${spawnType}${rawSpawnType !== spawnType ? ` (resolved from: ${rawSpawnType})` : ''}`);
|
||||
console.log(` Type: ${spawnType}`);
|
||||
console.log(` Name: ${spawnName}`);
|
||||
console.log(' Capabilities: Research, Analysis, Code Generation');
|
||||
console.log(' Status: Ready');
|
||||
@@ -313,7 +228,7 @@ async function main() {
|
||||
console.log(' • Max Pool Size: 10');
|
||||
console.log(' • Idle Timeout: 5 minutes');
|
||||
console.log(' • Shell: /bin/bash');
|
||||
console.log(' • Working Directory: ' + cwd());
|
||||
console.log(' • Working Directory: ' + process.cwd());
|
||||
console.log(' Performance:');
|
||||
console.log(' • Average Response Time: N/A');
|
||||
console.log(' • Terminal Creation Time: N/A');
|
||||
@@ -362,7 +277,7 @@ async function main() {
|
||||
const terminalConfig = {
|
||||
name: nameIndex >= 0 ? subArgs[nameIndex + 1] : 'terminal-' + Date.now(),
|
||||
shell: shellIndex >= 0 ? subArgs[shellIndex + 1] : 'bash',
|
||||
workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : cwd(),
|
||||
workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : process.cwd(),
|
||||
env: envIndex >= 0 ? subArgs[envIndex + 1] : '',
|
||||
persistent: persistentIndex >= 0
|
||||
};
|
||||
@@ -1319,9 +1234,10 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all
|
||||
console.log('Debug - Executing command:');
|
||||
console.log(`claude ${claudeArgs.map((arg)=>arg.includes(' ') || arg.includes('\n') ? `"${arg}"` : arg).join(' ')}`);
|
||||
}
|
||||
const child = spawn('claude', claudeArgs, {
|
||||
const command = new Deno.Command('claude', {
|
||||
args: claudeArgs,
|
||||
env: {
|
||||
...process.env,
|
||||
...Deno.env.toObject(),
|
||||
CLAUDE_INSTANCE_ID: instanceId,
|
||||
CLAUDE_FLOW_MODE: flags1.mode || 'full',
|
||||
CLAUDE_FLOW_COVERAGE: (flags1.coverage || 80).toString(),
|
||||
@@ -1331,18 +1247,17 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all
|
||||
CLAUDE_FLOW_COORDINATION_ENABLED: flags1.parallel ? 'true' : 'false',
|
||||
CLAUDE_FLOW_FEATURES: 'memory,coordination,swarm'
|
||||
},
|
||||
stdio: 'inherit'
|
||||
});
|
||||
await new Promise((resolve)=>{
|
||||
child.on('exit', (code)=>{
|
||||
if (code === 0) {
|
||||
printSuccess(`Claude instance ${instanceId} completed successfully`);
|
||||
} else {
|
||||
printError(`Claude instance ${instanceId} exited with code ${code}`);
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
stdin: 'inherit',
|
||||
stdout: 'inherit',
|
||||
stderr: 'inherit'
|
||||
});
|
||||
const child = command.spawn();
|
||||
const status = await child.status;
|
||||
if (status.success) {
|
||||
printSuccess(`Claude instance ${instanceId} completed successfully`);
|
||||
} else {
|
||||
printError(`Claude instance ${instanceId} exited with code ${status.code}`);
|
||||
}
|
||||
} catch (err) {
|
||||
printError(`Failed to spawn Claude: ${err.message}`);
|
||||
console.log('Make sure you have the Claude CLI installed.');
|
||||
@@ -1895,7 +1810,7 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all
|
||||
console.log('\nDid you mean:');
|
||||
suggestions.forEach((cmd)=>console.log(` claude-flow ${cmd}`));
|
||||
}
|
||||
exit(1);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
async function startRepl() {
|
||||
@@ -1973,7 +1888,7 @@ Shortcuts:
|
||||
},
|
||||
config: async (key)=>{
|
||||
try {
|
||||
const config = JSON.parse(await readTextFile('claude-flow.config.json'));
|
||||
const config = JSON.parse(await fs.readFile('claude-flow.config.json', 'utf-8'));
|
||||
if (key) {
|
||||
const keys = key.split('.');
|
||||
let value = config;
|
||||
@@ -2001,25 +1916,21 @@ Shortcuts:
|
||||
if (trimmed.startsWith('!')) {
|
||||
const shellCmd = trimmed.substring(1);
|
||||
try {
|
||||
await new Promise((resolve)=>{
|
||||
const proc = spawn('sh', [
|
||||
const command = new Deno.Command('sh', {
|
||||
args: [
|
||||
'-c',
|
||||
shellCmd
|
||||
], {
|
||||
stdio: [
|
||||
'inherit',
|
||||
'pipe',
|
||||
'pipe'
|
||||
]
|
||||
});
|
||||
proc.stdout.on('data', (data)=>{
|
||||
console.log(data.toString());
|
||||
});
|
||||
proc.stderr.on('data', (data)=>{
|
||||
console.error(data.toString());
|
||||
});
|
||||
proc.on('exit', resolve);
|
||||
],
|
||||
stdout: 'piped',
|
||||
stderr: 'piped'
|
||||
});
|
||||
const { stdout, stderr } = await command.output();
|
||||
if (stdout.length > 0) {
|
||||
console.log(new TextDecoder().decode(stdout));
|
||||
}
|
||||
if (stderr.length > 0) {
|
||||
console.error(new TextDecoder().decode(stderr));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Shell error: ${err.message}`);
|
||||
}
|
||||
@@ -2039,7 +1950,7 @@ Shortcuts:
|
||||
const parts = trimmed.split(' ');
|
||||
const command = parts[0];
|
||||
const args = parts.slice(1);
|
||||
if (replCommands[command]) {
|
||||
if (command in replCommands) {
|
||||
await replCommands[command](...args);
|
||||
return true;
|
||||
}
|
||||
@@ -2060,8 +1971,7 @@ Shortcuts:
|
||||
const subCmd = args[0];
|
||||
switch(subCmd){
|
||||
case 'spawn':
|
||||
const rawType = args[1] || 'researcher';
|
||||
const type = resolveLegacyAgentType(rawType);
|
||||
const type = args[1] || 'researcher';
|
||||
const name = args[2] || `agent-${Date.now()}`;
|
||||
const agent = {
|
||||
id: `agent-${Date.now()}`,
|
||||
@@ -2266,33 +2176,18 @@ Shortcuts:
|
||||
console.log('Terminal commands: create, list, exec, attach, detach');
|
||||
}
|
||||
}
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
});
|
||||
function updatePrompt() {
|
||||
rl.setPrompt(replState.currentSession ? `claude-flow:${replState.currentSession}> ` : 'claude-flow> ');
|
||||
}
|
||||
updatePrompt();
|
||||
rl.prompt();
|
||||
rl.on('line', async (input)=>{
|
||||
input = input.trim();
|
||||
const decoder = new TextDecoder();
|
||||
const encoder = new TextEncoder();
|
||||
while(true){
|
||||
const prompt = replState.currentSession ? `claude-flow:${replState.currentSession}> ` : 'claude-flow> ';
|
||||
await Deno.stdout.write(encoder.encode(prompt));
|
||||
const buf = new Uint8Array(1024);
|
||||
const n = await Deno.stdin.read(buf);
|
||||
if (n === null) break;
|
||||
const input = decoder.decode(buf.subarray(0, n)).trim();
|
||||
const shouldContinue = await processReplCommand(input);
|
||||
if (!shouldContinue) {
|
||||
rl.close();
|
||||
} else {
|
||||
updatePrompt();
|
||||
rl.prompt();
|
||||
}
|
||||
});
|
||||
rl.on('SIGINT', ()=>{
|
||||
console.log('\nExiting Claude-Flow...');
|
||||
rl.close();
|
||||
process.exit(0);
|
||||
});
|
||||
return new Promise((resolve)=>{
|
||||
rl.on('close', resolve);
|
||||
});
|
||||
if (!shouldContinue) break;
|
||||
}
|
||||
}
|
||||
function createMinimalClaudeMd() {
|
||||
return `# Claude Code Integration
|
||||
@@ -2609,30 +2504,30 @@ async function createSparcStructureManually() {
|
||||
];
|
||||
for (const dir of rooDirectories){
|
||||
try {
|
||||
await mkdirAsync(dir, {
|
||||
await Deno.mkdir(dir, {
|
||||
recursive: true
|
||||
});
|
||||
console.log(` ✓ Created ${dir}/`);
|
||||
} catch (err) {
|
||||
if (!(err instanceof errors.AlreadyExists)) {
|
||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
let roomodesContent;
|
||||
try {
|
||||
roomodesContent = await readTextFile('.roomodes');
|
||||
roomodesContent = await fs.readFile('.roomodes');
|
||||
console.log(' ✓ Using existing .roomodes configuration');
|
||||
} catch {
|
||||
roomodesContent = createBasicRoomodesConfig();
|
||||
await writeTextFile('.roomodes', roomodesContent);
|
||||
await fs.writeFile('.roomodes', roomodesContent);
|
||||
console.log(' ✓ Created .roomodes configuration');
|
||||
}
|
||||
const basicWorkflow = createBasicSparcWorkflow();
|
||||
await writeTextFile('.roo/workflows/basic-tdd.json', basicWorkflow);
|
||||
await fs.writeFile('.roo/workflows/basic-tdd.json', basicWorkflow);
|
||||
console.log(' ✓ Created .roo/workflows/basic-tdd.json');
|
||||
const rooReadme = createRooReadme();
|
||||
await writeTextFile('.roo/README.md', rooReadme);
|
||||
await fs.writeFile('.roo/README.md', rooReadme);
|
||||
console.log(' ✓ Created .roo/README.md');
|
||||
console.log(' ✅ Basic SPARC structure created successfully');
|
||||
} catch (err) {
|
||||
@@ -3060,6 +2955,134 @@ This SPARC-enabled project follows a systematic development approach:
|
||||
- Document architectural decisions in memory for future reference
|
||||
- Regular security reviews for any authentication or data handling code
|
||||
|
||||
For more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md
|
||||
`;
|
||||
}
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
await main();
|
||||
}
|
||||
|
||||
//# sourceMappingURL=simple-cli.js.mapsign choices"
|
||||
|
||||
# Store test results and coverage
|
||||
npx claude-flow memory store test_coverage "Authentication module: 95% coverage, all tests passing"
|
||||
|
||||
# Query previous work
|
||||
npx claude-flow memory query auth_implementation
|
||||
|
||||
# Export project memory
|
||||
npx claude-flow memory export project_backup.json
|
||||
\`\`\`
|
||||
|
||||
### Memory Namespaces
|
||||
- **\`spec\`**: Requirements and specifications
|
||||
- **\`arch\`**: Architecture and design decisions
|
||||
- **\`impl\`**: Implementation notes and code patterns
|
||||
- **\`test\`**: Test results and coverage reports
|
||||
- **\`debug\`**: Bug reports and resolution notes
|
||||
|
||||
## Workflow Examples
|
||||
|
||||
### Feature Development Workflow
|
||||
\`\`\`bash
|
||||
# 1. Start with specification
|
||||
npx claude-flow sparc run spec-pseudocode "User profile management feature"
|
||||
|
||||
# 2. Design architecture
|
||||
npx claude-flow sparc run architect "Profile service architecture with data validation"
|
||||
|
||||
# 3. Implement with TDD
|
||||
npx claude-flow sparc tdd "user profile CRUD operations"
|
||||
|
||||
# 4. Security review
|
||||
npx claude-flow sparc run security-review "profile data access and validation"
|
||||
|
||||
# 5. Integration testing
|
||||
npx claude-flow sparc run integration "profile service with authentication system"
|
||||
|
||||
# 6. Documentation
|
||||
npx claude-flow sparc run docs-writer "profile service API documentation"
|
||||
\`\`\`
|
||||
|
||||
### Bug Fix Workflow
|
||||
\`\`\`bash
|
||||
# 1. Debug and analyze
|
||||
npx claude-flow sparc run debug "authentication token expiration issue"
|
||||
|
||||
# 2. Write regression tests
|
||||
npx claude-flow sparc run tdd "token refresh mechanism tests"
|
||||
|
||||
# 3. Implement fix
|
||||
npx claude-flow sparc run code "fix token refresh in authentication service"
|
||||
|
||||
# 4. Security review
|
||||
npx claude-flow sparc run security-review "token handling security implications"
|
||||
\`\`\`
|
||||
|
||||
## Configuration Files
|
||||
|
||||
### SPARC Configuration
|
||||
- **\`.roomodes\`**: SPARC mode definitions and configurations
|
||||
- **\`.roo/\`**: Templates, workflows, and mode-specific rules
|
||||
|
||||
### Claude-Flow Configuration
|
||||
- **\`memory/\`**: Persistent memory and session data
|
||||
- **\`coordination/\`**: Multi-agent coordination settings
|
||||
|
||||
## Git Workflow Integration
|
||||
|
||||
### Commit Strategy with SPARC
|
||||
- **Specification commits**: After completing requirements analysis
|
||||
- **Architecture commits**: After design phase completion
|
||||
- **TDD commits**: After each Red-Green-Refactor cycle
|
||||
- **Integration commits**: After successful component integration
|
||||
- **Documentation commits**: After completing documentation updates
|
||||
|
||||
### Branch Strategy
|
||||
- **\`feature/sparc-<feature-name>\`**: Feature development with SPARC methodology
|
||||
- **\`hotfix/sparc-<issue>\`**: Bug fixes using SPARC debugging workflow
|
||||
- **\`refactor/sparc-<component>\`**: Refactoring using optimization mode
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common SPARC Issues
|
||||
- **Mode not found**: Check \`.roomodes\` file exists and is valid JSON
|
||||
- **Memory persistence**: Ensure \`memory/\` directory has write permissions
|
||||
- **Tool access**: Verify required tools are available for the selected mode
|
||||
- **Namespace conflicts**: Use unique memory namespaces for different features
|
||||
|
||||
### Debug Commands
|
||||
\`\`\`bash
|
||||
# Check SPARC configuration
|
||||
npx claude-flow sparc modes
|
||||
|
||||
# Verify memory system
|
||||
npx claude-flow memory stats
|
||||
|
||||
# Check system status
|
||||
npx claude-flow status
|
||||
|
||||
# View detailed mode information
|
||||
npx claude-flow sparc info <mode-name>
|
||||
\`\`\`
|
||||
|
||||
## Project Architecture
|
||||
|
||||
This SPARC-enabled project follows a systematic development approach:
|
||||
- **Clear separation of concerns** through modular design
|
||||
- **Test-driven development** ensuring reliability and maintainability
|
||||
- **Iterative refinement** for continuous improvement
|
||||
- **Comprehensive documentation** for team collaboration
|
||||
- **AI-assisted development** through specialized SPARC modes
|
||||
|
||||
## Important Notes
|
||||
|
||||
- Always run tests before committing (\`npm run test\`)
|
||||
- Use SPARC memory system to maintain context across sessions
|
||||
- Follow the Red-Green-Refactor cycle during TDD phases
|
||||
- Document architectural decisions in memory for future reference
|
||||
- Regular security reviews for any authentication or data handling code
|
||||
|
||||
For more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/cli/simple-cli.js"],"sourcesContent":["#!/usr/bin/env node\n/**\n * Simple CLI wrapper for Claude-Flow (JavaScript version)\n * This version avoids TypeScript issues in node_modules\n */\n\nimport {\n executeCommand,\n hasCommand,\n showCommandHelp,\n showAllCommands,\n listCommands,\n} from './command-registry.js';\nimport { parseFlags } from './utils.js';\nimport {\n args,\n cwd,\n isMainModule,\n exit,\n readTextFile,\n writeTextFile,\n mkdirAsync,\n errors,\n} from './node-compat.js';\nimport { spawn } from 'child_process';\nimport process from 'process';\nimport readline from 'readline';\nimport { getMainHelp, getCommandHelp, getStandardizedCommandHelp } from './help-text.js';\nimport { VERSION } from '../core/version.js';\n\n// Legacy agent type mapping for backward compatibility\nconst LEGACY_AGENT_MAPPING = {\n analyst: 'code-analyzer',\n coordinator: 'task-orchestrator', \n optimizer: 'perf-analyzer',\n documenter: 'api-docs',\n monitor: 'performance-benchmarker',\n specialist: 'system-architect',\n architect: 'system-architect',\n};\n\n// Resolve legacy agent types to current equivalents\nfunction resolveLegacyAgentType(legacyType) {\n return LEGACY_AGENT_MAPPING[legacyType] || legacyType;\n}\n\nfunction printHelp(plain = false) {\n console.log(getMainHelp(plain));\n}\n\nfunction printCommandHelp(command) {\n // Try standardized help first\n const standardCommands = ['agent', 'sparc', 'memory'];\n if (standardCommands.includes(command)) {\n const help = getStandardizedCommandHelp(command);\n console.log(help);\n } else {\n const help = getCommandHelp(command);\n console.log(help);\n }\n}\n\n// Legacy help function for backward compatibility\nfunction printLegacyHelp() {\n console.log(`\n🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform\n\n🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 90+ MCP tools, neural networking, and production-ready infrastructure\n⚡ ALPHA 85: Advanced automation capabilities & stream-JSON chaining for multi-agent pipelines\n\nUSAGE:\n claude-flow <command> [options]\n\n🚀 INSTALLATION & ENTERPRISE SETUP:\n npx claude-flow@2.0.0 init --sparc # Enterprise SPARC + ruv-swarm integration\n \n The --sparc flag creates:\n • Complete ruv-swarm integration with 27 MCP tools\n • Neural network processing with WASM optimization\n • Multi-agent coordination (hierarchical, mesh, ring, star topologies)\n • Cross-session memory and persistent learning\n • GitHub workflow automation (6 specialized modes)\n • Production-ready Docker infrastructure\n • Enterprise security and compliance features\n\n🧠 SWARM INTELLIGENCE COMMANDS (v2.0.0):\n swarm \"objective\" [--strategy] [--mode] [--max-agents N] [--parallel] [--monitor]\n --strategy: research, development, analysis, testing, optimization, maintenance\n --mode: centralized, distributed, hierarchical, mesh, hybrid\n --parallel: Enable parallel execution (2.8-4.4x speed improvement)\n --monitor: Real-time swarm monitoring and performance tracking\n\n🐙 GITHUB WORKFLOW AUTOMATION (v2.0.0):\n github gh-coordinator # GitHub workflow orchestration and coordination\n github pr-manager # Pull request management with multi-reviewer coordination\n github issue-tracker # Issue management and project coordination\n github release-manager # Release coordination and deployment pipelines\n github repo-architect # Repository structure optimization\n github sync-coordinator # Multi-package synchronization and version alignment\n\n🏗️ CORE ENTERPRISE COMMANDS:\n init [--sparc] # Initialize with enterprise environment + ruv-swarm\n start [--ui] [--swarm] # Start orchestration with swarm intelligence\n spawn <type> [--name] # Create AI agent with swarm coordination\n agent <subcommand> # Advanced agent management with neural patterns\n sparc <subcommand> # 17 SPARC modes with neural enhancement\n memory <subcommand> # Cross-session persistent memory with neural learning\n status # Comprehensive system status with performance metrics\n\n🤖 NEURAL AGENT TYPES (ruv-swarm Integration):\n researcher # Research with web access and data analysis\n coder # Code development with neural patterns\n analyst # Performance analysis and optimization\n architect # System design with enterprise patterns\n tester # Comprehensive testing with automation\n coordinator # Multi-agent orchestration and workflow management\n reviewer # Code review with security and quality checks\n optimizer # Performance optimization and bottleneck analysis\n\n🎮 ENTERPRISE QUICK START:\n # Initialize enterprise environment\n npx claude-flow@2.0.0 init --sparc\n \n # Start enterprise orchestration with swarm intelligence\n ./claude-flow start Line truncated
|
||||
{"version":3,"sources":["../../../src/cli/simple-cli.ts"],"sourcesContent":["#!/usr/bin/env -S deno run --allow-all\n/**\n * Simple CLI wrapper for Claude-Flow (JavaScript version)\n * This version avoids TypeScript issues in node_modules\n */\n\nimport { promises as fs } from 'node:fs';\nimport {\n executeCommand,\n hasCommand,\n showCommandHelp,\n showAllCommands,\n listCommands,\n} from './command-registry.js';\nimport { parseFlags } from './utils.js';\nimport { VERSION } from '../core/version.js';\n\nfunction printHelp() {\n console.log(`\n🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform\n\n🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 27 MCP tools, neural networking, and production-ready infrastructure\n\nUSAGE:\n claude-flow <command> [options]\n\n🚀 INSTALLATION & ENTERPRISE SETUP:\n npx claude-flow@2.0.0 init --sparc # Enterprise SPARC + ruv-swarm integration\n \n The --sparc flag creates:\n • Complete ruv-swarm integration with 27 MCP tools\n • Neural network processing with WASM optimization\n • Multi-agent coordination (hierarchical, mesh, ring, star topologies)\n • Cross-session memory and persistent learning\n • GitHub workflow automation (6 specialized modes)\n • Production-ready Docker infrastructure\n • Enterprise security and compliance features\n\n🧠 SWARM INTELLIGENCE COMMANDS (v2.0.0):\n swarm \"objective\" [--strategy] [--mode] [--max-agents N] [--parallel] [--monitor]\n --strategy: research, development, analysis, testing, optimization, maintenance\n --mode: centralized, distributed, hierarchical, mesh, hybrid\n --parallel: Enable parallel execution (2.8-4.4x speed improvement)\n --monitor: Real-time swarm monitoring and performance tracking\n\n🐙 GITHUB WORKFLOW AUTOMATION (v2.0.0):\n github gh-coordinator # GitHub workflow orchestration and coordination\n github pr-manager # Pull request management with multi-reviewer coordination\n github issue-tracker # Issue management and project coordination\n github release-manager # Release coordination and deployment pipelines\n github repo-architect # Repository structure optimization\n github sync-coordinator # Multi-package synchronization and version alignment\n\n🏗️ CORE ENTERPRISE COMMANDS:\n init [--sparc] # Initialize with enterprise environment + ruv-swarm\n start [--ui] [--swarm] # Start orchestration with swarm intelligence\n spawn <type> [--name] # Create AI agent with swarm coordination\n agent <subcommand> # Advanced agent management with neural patterns\n sparc <subcommand> # 17 SPARC modes with neural enhancement\n memory <subcommand> # Cross-session persistent memory with neural learning\n status # Comprehensive system status with performance metrics\n\n🤖 NEURAL AGENT TYPES (ruv-swarm Integration):\n researcher # Research with web access and data analysis\n coder # Code development with neural patterns\n analyst # Performance analysis and optimization\n architect # System design with enterprise patterns\n tester # Comprehensive testing with automation\n coordinator # Multi-agent orchestration and workflow management\n reviewer # Code review with security and quality checks\n optimizer # Performance optimization and bottleneck analysis\n\n🎮 ENTERPRISE QUICK START:\n # Initialize enterprise environment\n npx claude-flow@2.0.0 init --sparc\n \n # Start enterprise orchestration with swarm intelligence\n ./claude-flow start --ui --swarm\n \n # Deploy intelligent multi-agent development workflow\n ./claude-flow swarm \"build enterprise API\" --strategy development --parallel --monitor\n \n # GitHub workflow automation\n ./claude-flow github pr-manager \"coordinate release with automated testing\"\n \n # Neural memory management\n ./claude-flow memory store \"architecture\" \"microservices with API gateway pattern\"\n \n # Real-time system monitoring\n ./claude-flow status --verbose\n\n🏢 ENTERPRISE COMMAND CATEGORIES:\n Core Intelligence: swarm, agent, sparc, memory, neural\n GitHub Automation: github (6 specialized modes)\n Development: init, start, status, config, workflow\n Infrastructure: mcp, terminal, session, docker\n Enterprise: project, deploy, cloud, security, analytics, audit\n\n🧠 NEURAL NETWORK FEATURES (v2.0.0):\n • WASM-powered cognitive patterns with SIMD optimization\n • 27 MCP tools for comprehensive workflow automation\n • Cross-session learning and adaptation\n • Real-time performance monitoring (sub-10ms response times)\n • 32.3% token usage reduction through intelligent coordination\n • Self-healing workflows with automatic error recovery\n\n📊 ENTERPRISE PERFORMANCE METRICS:\n • 84.8% SWE-Bench solve rate through coordinated intelligence\n • 2.8-Line truncated
|
||||
@@ -1669,6 +1669,14 @@ async function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers,
|
||||
console.log(chalk.gray('\nFalling back to displaying instructions...'));
|
||||
}
|
||||
if (claudeAvailable && !flags.dryRun) {
|
||||
try {
|
||||
const { injectMemoryProtocol, enhanceHiveMindPrompt } = await import('./inject-memory-protocol.js');
|
||||
await injectMemoryProtocol();
|
||||
hiveMindPrompt = enhanceHiveMindPrompt(hiveMindPrompt, workers);
|
||||
console.log(chalk.green('📝 Memory coordination protocol injected into CLAUDE.md'));
|
||||
} catch (err) {
|
||||
console.log(chalk.yellow('⚠️ Memory protocol injection not available, using standard prompt'));
|
||||
}
|
||||
const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;
|
||||
const claudeArgs = [];
|
||||
if (isNonInteractive) {
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../../src/cli/simple-commands/hive-mind.js"],"sourcesContent":["/**\n * Hive Mind command for Claude-Flow v2.0.0\n * Advanced swarm intelligence with collective decision-making\n */\n\nimport { spawn } from 'child_process';\nimport { existsSync, mkdirSync } from 'fs';\nimport { writeFile, readFile } from 'fs/promises';\nimport path from 'path';\nimport readline from 'readline';\nimport inquirer from 'inquirer';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { args, cwd, exit, writeTextFile, readTextFile, mkdirAsync } from '../node-compat.js';\nimport {\n isInteractive,\n isRawModeSupported,\n warnNonInteractive,\n checkNonInteractiveAuth,\n} from '../utils/interactive-detector.js';\nimport {\n safeInteractive,\n nonInteractiveProgress,\n nonInteractiveSelect,\n} from '../utils/safe-interactive.js';\n\n// Import SQLite for persistence\nimport Database from 'better-sqlite3';\n\n// Import help formatter\nimport { HelpFormatter } from '../help-formatter.js';\n\n// Import MCP tool wrappers\nimport { MCPToolWrapper } from './hive-mind/mcp-wrapper.js';\nimport { HiveMindCore } from './hive-mind/core.js';\nimport { QueenCoordinator } from './hive-mind/queen.js';\nimport { CollectiveMemory } from './hive-mind/memory.js';\nimport { SwarmCommunication } from './hive-mind/communication.js';\nimport { HiveMindSessionManager } from './hive-mind/session-manager.js';\nimport { createAutoSaveMiddleware } from './hive-mind/auto-save-middleware.js';\nimport { HiveMindMetricsReader } from './hive-mind/metrics-reader.js';\n\nfunction showHiveMindHelp() {\n console.log(`\n${chalk.yellow('🧠 Claude Flow Hive Mind System')}\n\n${chalk.bold('USAGE:')}\n claude-flow hive-mind [subcommand] [options]\n\n${chalk.bold('SUBCOMMANDS:')}\n ${chalk.green('init')} Initialize hive mind system\n ${chalk.green('spawn')} Spawn hive mind swarm for a task\n ${chalk.green('status')} Show hive mind status\n ${chalk.green('resume')} Resume a paused hive mind session\n ${chalk.green('stop')} Stop a running hive mind session\n ${chalk.green('sessions')} List all hive mind sessions\n ${chalk.green('consensus')} View consensus decisions\n ${chalk.green('memory')} Manage collective memory\n ${chalk.green('metrics')} View performance metrics\n ${chalk.green('wizard')} Interactive hive mind wizard with Claude Code spawning\n\n${chalk.bold('EXAMPLES:')}\n ${chalk.gray('# Initialize hive mind')}\n claude-flow hive-mind init\n\n ${chalk.gray('# Spawn swarm with interactive wizard')}\n claude-flow hive-mind spawn\n\n ${chalk.gray('# Quick spawn with objective')}\n claude-flow hive-mind spawn \"Build microservices architecture\"\n\n ${chalk.gray('# View current status')}\n claude-flow hive-mind status\n\n ${chalk.gray('# Interactive wizard with Claude Code spawning')}\n claude-flow hive-mind wizard\n\n ${chalk.gray('# Spawn with Claude Code coordination')}\n claude-flow hive-mind spawn \"Build REST API\" --claude\n\n ${chalk.gray('# Auto-spawn coordinated Claude Code instances')}\n claude-flow hive-mind spawn \"Research AI trends\" --auto-spawn --verbose\n\n ${chalk.gray('# List all sessions')}\n claude-flow hive-mind sessions\n\n ${chalk.gray('# Resume a paused session')}\n claude-flow hive-mind resume session-1234567890-abc123\n\n${chalk.bold('KEY FEATURES:')}\n ${chalk.cyan('🐝')} Queen-led coordination with worker specialization\n ${chalk.cyan('🧠')} Collective memory and knowledge sharing\n ${chalk.cyan('🤝')} Consensus building for critical decisions\n ${chalk.cyan('⚡')} Parallel task execution with auto-scaling\n ${chalk.cyan('🔄')} Work stealing and load balancing\n ${chalk.cyan('📊')} Real-time metrics and performance tracking\n ${chalk.cyan('🛡️')} Fault tolerance and self-healing\n ${chalk.cyan('🔒')} Secure communication between agents\n\n${chalk.bold('OPTIONS:')}\n --queen-type <type> Queen coordinator type (strategic, tactical, adaptive)\n --max-workers <n> Maximum worker agents (default: 8)\n --consensus <type> Consensus algorithm (majority, weighted, byzantine)\n --memory-size <mb> Collective memory size in MB (default: 100)\n --auto-scale Enable auto-scaling based on workload\n --encryption Enable encrypted communication\n --monitor Real-time monitoring dashboard\n --verbose Detailed logging\n --claude Generate Claude Code spawn commands with coordination\n --spawn Alias for --claude\n --auto-spawn Automatically spawn Claude Code instances\n --execute Execute Claude Code spawn commands immediately\n\n${chalk.bold('For more information:')}\n${chalk.blue('https://github.com/ruvnet/claude-flow/tree/main/docs/hive-mind')}\n`);\n}\n\n/**\n * Initialize hive mind system\n */\nasync function initHiveMind(flags) {\n const spinner = ora('Initializing Hive Mind sysLine truncated
|
||||
{"version":3,"sources":["../../../../src/cli/simple-commands/hive-mind.js"],"sourcesContent":["/**\n * Hive Mind command for Claude-Flow v2.0.0\n * Advanced swarm intelligence with collective decision-making\n */\n\nimport { spawn } from 'child_process';\nimport { existsSync, mkdirSync } from 'fs';\nimport { writeFile, readFile } from 'fs/promises';\nimport path from 'path';\nimport readline from 'readline';\nimport inquirer from 'inquirer';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { args, cwd, exit, writeTextFile, readTextFile, mkdirAsync } from '../node-compat.js';\nimport {\n isInteractive,\n isRawModeSupported,\n warnNonInteractive,\n checkNonInteractiveAuth,\n} from '../utils/interactive-detector.js';\nimport {\n safeInteractive,\n nonInteractiveProgress,\n nonInteractiveSelect,\n} from '../utils/safe-interactive.js';\n\n// Import SQLite for persistence\nimport Database from 'better-sqlite3';\n\n// Import help formatter\nimport { HelpFormatter } from '../help-formatter.js';\n\n// Import MCP tool wrappers\nimport { MCPToolWrapper } from './hive-mind/mcp-wrapper.js';\nimport { HiveMindCore } from './hive-mind/core.js';\nimport { QueenCoordinator } from './hive-mind/queen.js';\nimport { CollectiveMemory } from './hive-mind/memory.js';\nimport { SwarmCommunication } from './hive-mind/communication.js';\nimport { HiveMindSessionManager } from './hive-mind/session-manager.js';\nimport { createAutoSaveMiddleware } from './hive-mind/auto-save-middleware.js';\nimport { HiveMindMetricsReader } from './hive-mind/metrics-reader.js';\n\nfunction showHiveMindHelp() {\n console.log(`\n${chalk.yellow('🧠 Claude Flow Hive Mind System')}\n\n${chalk.bold('USAGE:')}\n claude-flow hive-mind [subcommand] [options]\n\n${chalk.bold('SUBCOMMANDS:')}\n ${chalk.green('init')} Initialize hive mind system\n ${chalk.green('spawn')} Spawn hive mind swarm for a task\n ${chalk.green('status')} Show hive mind status\n ${chalk.green('resume')} Resume a paused hive mind session\n ${chalk.green('stop')} Stop a running hive mind session\n ${chalk.green('sessions')} List all hive mind sessions\n ${chalk.green('consensus')} View consensus decisions\n ${chalk.green('memory')} Manage collective memory\n ${chalk.green('metrics')} View performance metrics\n ${chalk.green('wizard')} Interactive hive mind wizard with Claude Code spawning\n\n${chalk.bold('EXAMPLES:')}\n ${chalk.gray('# Initialize hive mind')}\n claude-flow hive-mind init\n\n ${chalk.gray('# Spawn swarm with interactive wizard')}\n claude-flow hive-mind spawn\n\n ${chalk.gray('# Quick spawn with objective')}\n claude-flow hive-mind spawn \"Build microservices architecture\"\n\n ${chalk.gray('# View current status')}\n claude-flow hive-mind status\n\n ${chalk.gray('# Interactive wizard with Claude Code spawning')}\n claude-flow hive-mind wizard\n\n ${chalk.gray('# Spawn with Claude Code coordination')}\n claude-flow hive-mind spawn \"Build REST API\" --claude\n\n ${chalk.gray('# Auto-spawn coordinated Claude Code instances')}\n claude-flow hive-mind spawn \"Research AI trends\" --auto-spawn --verbose\n\n ${chalk.gray('# List all sessions')}\n claude-flow hive-mind sessions\n\n ${chalk.gray('# Resume a paused session')}\n claude-flow hive-mind resume session-1234567890-abc123\n\n${chalk.bold('KEY FEATURES:')}\n ${chalk.cyan('🐝')} Queen-led coordination with worker specialization\n ${chalk.cyan('🧠')} Collective memory and knowledge sharing\n ${chalk.cyan('🤝')} Consensus building for critical decisions\n ${chalk.cyan('⚡')} Parallel task execution with auto-scaling\n ${chalk.cyan('🔄')} Work stealing and load balancing\n ${chalk.cyan('📊')} Real-time metrics and performance tracking\n ${chalk.cyan('🛡️')} Fault tolerance and self-healing\n ${chalk.cyan('🔒')} Secure communication between agents\n\n${chalk.bold('OPTIONS:')}\n --queen-type <type> Queen coordinator type (strategic, tactical, adaptive)\n --max-workers <n> Maximum worker agents (default: 8)\n --consensus <type> Consensus algorithm (majority, weighted, byzantine)\n --memory-size <mb> Collective memory size in MB (default: 100)\n --auto-scale Enable auto-scaling based on workload\n --encryption Enable encrypted communication\n --monitor Real-time monitoring dashboard\n --verbose Detailed logging\n --claude Generate Claude Code spawn commands with coordination\n --spawn Alias for --claude\n --auto-spawn Automatically spawn Claude Code instances\n --execute Execute Claude Code spawn commands immediately\n\n${chalk.bold('For more information:')}\n${chalk.blue('https://github.com/ruvnet/claude-flow/tree/main/docs/hive-mind')}\n`);\n}\n\n/**\n * Initialize hive mind system\n */\nasync function initHiveMind(flags) {\n const spinner = ora('Initializing Hive Mind sysLine truncated
|
||||
@@ -706,12 +706,20 @@ Start by spawning a coordinator agent and creating the initial task structure. U
|
||||
|
||||
The swarm should be self-documenting - use memory_store to save all important information, decisions, and results throughout the execution.`;
|
||||
if (flags && flags.claude) {
|
||||
try {
|
||||
const { injectMemoryProtocol, enhanceSwarmPrompt } = await import('./inject-memory-protocol.js');
|
||||
await injectMemoryProtocol();
|
||||
swarmPrompt = enhanceSwarmPrompt(swarmPrompt, maxAgents);
|
||||
} catch (err) {
|
||||
console.log('⚠️ Memory protocol injection not available, using standard prompt');
|
||||
}
|
||||
console.log('🐝 Launching Claude Flow Swarm System...');
|
||||
console.log(`📋 Objective: ${objective}`);
|
||||
console.log(`🎯 Strategy: ${strategy}`);
|
||||
console.log(`🏗️ Mode: ${mode}`);
|
||||
console.log(`🤖 Max Agents: ${maxAgents}\n`);
|
||||
console.log('🚀 Launching Claude Code with Swarm Coordination');
|
||||
console.log('📝 Memory protocol injected into CLAUDE.md');
|
||||
console.log('─'.repeat(60));
|
||||
const claudeArgs = [];
|
||||
if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../../src/cli/simple-commands/swarm.js"],"sourcesContent":["/**\n * Swarm command wrapper for simple CLI\n */\n\nimport { args, mkdirAsync, writeTextFile, exit, cwd } from '../node-compat.js';\nimport { spawn, execSync } from 'child_process';\nimport { existsSync, chmodSync, statSync, readFileSync } from 'fs';\nimport { open } from 'fs/promises';\nimport process from 'process';\nimport path from 'path';\n\n/**\n * Detects if the environment is headless (non-interactive)\n */\nfunction isHeadlessEnvironment() {\n // Check for common CI environment variables\n const ciEnvironments = [\n 'CI',\n 'GITHUB_ACTIONS',\n 'GITLAB_CI',\n 'JENKINS_URL',\n 'CIRCLECI',\n 'TRAVIS',\n 'BUILDKITE',\n 'DRONE',\n 'DOCKER_CONTAINER',\n ];\n \n const isCI = ciEnvironments.some(env => process.env[env]);\n \n // Check if running in Docker\n let isDocker = existsSync('/.dockerenv');\n \n // Additional Docker check for cgroup\n if (!isDocker && existsSync('/proc/1/cgroup')) {\n try {\n const cgroupContent = readFileSync('/proc/1/cgroup', 'utf8');\n isDocker = cgroupContent.includes('docker');\n } catch {\n // Ignore read errors\n }\n }\n \n // Check TTY availability\n const hasTTY = process.stdin.isTTY && process.stdout.isTTY;\n \n return isCI || isDocker || !hasTTY;\n}\n\n/**\n * Basic swarm implementation for fallback scenarios\n */\nasync function basicSwarmNew(args, flags) {\n const objective = (args || []).join(' ').trim();\n \n if (!objective) {\n console.error('❌ Usage: swarm <objective>');\n showSwarmHelp();\n return;\n }\n\n const isHeadless = isHeadlessEnvironment();\n \n // Configure for headless mode\n if (isHeadless) {\n console.log('🤖 Headless environment detected - running in non-interactive mode');\n flags = {\n ...flags,\n 'non-interactive': true,\n 'output-format': flags['output-format'] || 'stream-json', // Use stream-json for Claude compatibility\n 'no-auto-permissions': false,\n };\n }\n\n // Set up graceful shutdown handlers\n const cleanup = () => {\n console.log('\\n🛑 Shutting down swarm gracefully...');\n process.exit(0);\n };\n\n process.on('SIGTERM', cleanup);\n process.on('SIGINT', cleanup);\n\n try {\n // Try to use the swarm executor\n const { executeSwarm } = await import('./swarm-executor.js');\n \n console.log(`🐝 Starting basic swarm execution...`);\n console.log(`📋 Objective: ${objective}`);\n console.log(`🎯 Strategy: ${flags.strategy || 'auto'}`);\n console.log(`🏗️ Mode: ${flags.mode || 'centralized'}`);\n console.log(`🤖 Max Agents: ${flags['max-agents'] || 5}`);\n \n if (isHeadless) {\n console.log(`🖥️ Headless Mode: Enabled`);\n console.log(`📄 Output Format: ${flags['output-format']}`);\n }\n\n const result = await executeSwarm(objective, flags);\n\n // Handle output based on format\n if (flags['output-format'] === 'json') {\n // In JSON mode, output clean JSON\n const output = {\n success: result.success,\n swarmId: result.summary?.swarmId,\n objective: objective,\n duration: result.summary?.duration,\n agents: result.summary?.totalAgents,\n tasks: result.summary?.totalTasks,\n timestamp: new Date().toISOString(),\n };\n \n if (flags['output-file']) {\n const fs = await import('fs/promises');\n await fs.writeFile(flags['output-file'], JSON.stringify(output, null, 2));\n console.log(`✅ Output saved to: ${flags['output-file']}`);\n } else {\n console.log(JSON.stringify(output, null, 2));\n }\n } else {\n // Text mode output\n if (result.success) {\n console.log(`\\n✅ Swarm execution completed successfully!`);\n if (result.summary) {\n console.log(` Duration: ${result.summary.duration}`);\n console.log(` Agents: ${result.summary.totalAgents}`);\n console.log(` Tasks: ${result.summary.totalTasks}`);\n }\n } else {\n console.error(`\\n❌ Swarm execution failed: ${result.error}`);\n }\n }\n\n return result;\n } catch (error) {\n console.error(`❌ Basic swarm execution error: ${error.message}`);\n \n // In headless mode, ensure we output JSON error\n if (flags['output-format'] === 'json') {\n const errorOutput = {\n success: false,\n error: error.message,\n timestamp: new Date().toISOString(),\n };\n console.log(JSON.stringify(errorOutput, null, 2));\n }\n \n throw error;\n }\n}\n\nfunction showSwarmHelp() {\n console.log(`\n🐝 Claude Flow Advanced Swarm System\n\nUSAGE:\n claude-flow swarm <objective> [options]\n\nEXAMPLES:\n claude-flow swarm \"Build a REST API with authentication\"\n claude-flow swarm \"Research cloud architecture patterns\" --strategy research\n claude-flow swarm \"AnalyLine truncated
|
||||
{"version":3,"sources":["../../../../src/cli/simple-commands/swarm.js"],"sourcesContent":["/**\n * Swarm command wrapper for simple CLI\n */\n\nimport { args, mkdirAsync, writeTextFile, exit, cwd } from '../node-compat.js';\nimport { spawn, execSync } from 'child_process';\nimport { existsSync, chmodSync, statSync, readFileSync } from 'fs';\nimport { open } from 'fs/promises';\nimport process from 'process';\nimport path from 'path';\n\n/**\n * Detects if the environment is headless (non-interactive)\n */\nfunction isHeadlessEnvironment() {\n // Check for common CI environment variables\n const ciEnvironments = [\n 'CI',\n 'GITHUB_ACTIONS',\n 'GITLAB_CI',\n 'JENKINS_URL',\n 'CIRCLECI',\n 'TRAVIS',\n 'BUILDKITE',\n 'DRONE',\n 'DOCKER_CONTAINER',\n ];\n \n const isCI = ciEnvironments.some(env => process.env[env]);\n \n // Check if running in Docker\n let isDocker = existsSync('/.dockerenv');\n \n // Additional Docker check for cgroup\n if (!isDocker && existsSync('/proc/1/cgroup')) {\n try {\n const cgroupContent = readFileSync('/proc/1/cgroup', 'utf8');\n isDocker = cgroupContent.includes('docker');\n } catch {\n // Ignore read errors\n }\n }\n \n // Check TTY availability\n const hasTTY = process.stdin.isTTY && process.stdout.isTTY;\n \n return isCI || isDocker || !hasTTY;\n}\n\n/**\n * Basic swarm implementation for fallback scenarios\n */\nasync function basicSwarmNew(args, flags) {\n const objective = (args || []).join(' ').trim();\n \n if (!objective) {\n console.error('❌ Usage: swarm <objective>');\n showSwarmHelp();\n return;\n }\n\n const isHeadless = isHeadlessEnvironment();\n \n // Configure for headless mode\n if (isHeadless) {\n console.log('🤖 Headless environment detected - running in non-interactive mode');\n flags = {\n ...flags,\n 'non-interactive': true,\n 'output-format': flags['output-format'] || 'stream-json', // Use stream-json for Claude compatibility\n 'no-auto-permissions': false,\n };\n }\n\n // Set up graceful shutdown handlers\n const cleanup = () => {\n console.log('\\n🛑 Shutting down swarm gracefully...');\n process.exit(0);\n };\n\n process.on('SIGTERM', cleanup);\n process.on('SIGINT', cleanup);\n\n try {\n // Try to use the swarm executor\n const { executeSwarm } = await import('./swarm-executor.js');\n \n console.log(`🐝 Starting basic swarm execution...`);\n console.log(`📋 Objective: ${objective}`);\n console.log(`🎯 Strategy: ${flags.strategy || 'auto'}`);\n console.log(`🏗️ Mode: ${flags.mode || 'centralized'}`);\n console.log(`🤖 Max Agents: ${flags['max-agents'] || 5}`);\n \n if (isHeadless) {\n console.log(`🖥️ Headless Mode: Enabled`);\n console.log(`📄 Output Format: ${flags['output-format']}`);\n }\n\n const result = await executeSwarm(objective, flags);\n\n // Handle output based on format\n if (flags['output-format'] === 'json') {\n // In JSON mode, output clean JSON\n const output = {\n success: result.success,\n swarmId: result.summary?.swarmId,\n objective: objective,\n duration: result.summary?.duration,\n agents: result.summary?.totalAgents,\n tasks: result.summary?.totalTasks,\n timestamp: new Date().toISOString(),\n };\n \n if (flags['output-file']) {\n const fs = await import('fs/promises');\n await fs.writeFile(flags['output-file'], JSON.stringify(output, null, 2));\n console.log(`✅ Output saved to: ${flags['output-file']}`);\n } else {\n console.log(JSON.stringify(output, null, 2));\n }\n } else {\n // Text mode output\n if (result.success) {\n console.log(`\\n✅ Swarm execution completed successfully!`);\n if (result.summary) {\n console.log(` Duration: ${result.summary.duration}`);\n console.log(` Agents: ${result.summary.totalAgents}`);\n console.log(` Tasks: ${result.summary.totalTasks}`);\n }\n } else {\n console.error(`\\n❌ Swarm execution failed: ${result.error}`);\n }\n }\n\n return result;\n } catch (error) {\n console.error(`❌ Basic swarm execution error: ${error.message}`);\n \n // In headless mode, ensure we output JSON error\n if (flags['output-format'] === 'json') {\n const errorOutput = {\n success: false,\n error: error.message,\n timestamp: new Date().toISOString(),\n };\n console.log(JSON.stringify(errorOutput, null, 2));\n }\n \n throw error;\n }\n}\n\nfunction showSwarmHelp() {\n console.log(`\n🐝 Claude Flow Advanced Swarm System\n\nUSAGE:\n claude-flow swarm <objective> [options]\n\nEXAMPLES:\n claude-flow swarm \"Build a REST API with authentication\"\n claude-flow swarm \"Research cloud architecture patterns\" --strategy research\n claude-flow swarm \"AnalyLine truncated
|
||||
@@ -1,941 +0,0 @@
|
||||
let AnalysisTools = class AnalysisTools {
|
||||
constructor(){
|
||||
this.ws = null;
|
||||
this.charts = {};
|
||||
this.currentTab = 'metrics';
|
||||
this.isConnected = false;
|
||||
this.metricsCache = new Map();
|
||||
this.updateInterval = null;
|
||||
this.init();
|
||||
}
|
||||
init() {
|
||||
this.setupWebSocket();
|
||||
this.setupEventListeners();
|
||||
this.initializeCharts();
|
||||
this.startRealTimeUpdates();
|
||||
}
|
||||
setupWebSocket() {
|
||||
try {
|
||||
this.ws = new WebSocket('ws://localhost:3000/analysis');
|
||||
this.ws.onopen = ()=>{
|
||||
this.isConnected = true;
|
||||
console.log('Analysis WebSocket connected');
|
||||
this.updateConnectionStatus('connected');
|
||||
};
|
||||
this.ws.onmessage = (event)=>{
|
||||
const data = JSON.parse(event.data);
|
||||
this.handleWebSocketData(data);
|
||||
};
|
||||
this.ws.onclose = ()=>{
|
||||
this.isConnected = false;
|
||||
console.log('Analysis WebSocket disconnected');
|
||||
this.updateConnectionStatus('disconnected');
|
||||
setTimeout(()=>this.setupWebSocket(), 5000);
|
||||
};
|
||||
this.ws.onerror = (error)=>{
|
||||
console.error('Analysis WebSocket error:', error);
|
||||
this.updateConnectionStatus('error');
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Failed to setup WebSocket:', error);
|
||||
this.updateConnectionStatus('error');
|
||||
}
|
||||
}
|
||||
setupEventListeners() {
|
||||
document.querySelectorAll('.analysis-tab').forEach((tab)=>{
|
||||
tab.addEventListener('click', (e)=>{
|
||||
this.switchTab(e.target.dataset.tab);
|
||||
});
|
||||
});
|
||||
document.querySelectorAll('.export-btn').forEach((btn)=>{
|
||||
btn.addEventListener('click', (e)=>{
|
||||
const format = e.target.dataset.format;
|
||||
const type = e.target.dataset.type;
|
||||
this.exportData(type, format);
|
||||
});
|
||||
});
|
||||
document.querySelectorAll('.tool-btn').forEach((btn)=>{
|
||||
btn.addEventListener('click', (e)=>{
|
||||
const tool = e.target.dataset.tool;
|
||||
this.executeTool(tool);
|
||||
});
|
||||
});
|
||||
document.querySelectorAll('.refresh-btn').forEach((btn)=>{
|
||||
btn.addEventListener('click', (e)=>{
|
||||
const section = e.target.dataset.section;
|
||||
this.refreshSection(section);
|
||||
});
|
||||
});
|
||||
}
|
||||
initializeCharts() {
|
||||
this.charts.performance = new Chart(document.getElementById('performance-chart'), {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: [],
|
||||
datasets: [
|
||||
{
|
||||
label: 'Response Time (ms)',
|
||||
data: [],
|
||||
borderColor: '#3b82f6',
|
||||
backgroundColor: 'rgba(59, 130, 246, 0.1)',
|
||||
tension: 0.4
|
||||
},
|
||||
{
|
||||
label: 'Throughput (req/s)',
|
||||
data: [],
|
||||
borderColor: '#10b981',
|
||||
backgroundColor: 'rgba(16, 185, 129, 0.1)',
|
||||
tension: 0.4
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
position: 'top'
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
display: true,
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Time'
|
||||
}
|
||||
},
|
||||
y: {
|
||||
display: true,
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Value'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
this.charts.tokenUsage = new Chart(document.getElementById('token-usage-chart'), {
|
||||
type: 'doughnut',
|
||||
data: {
|
||||
labels: [
|
||||
'Input Tokens',
|
||||
'Output Tokens',
|
||||
'Cached Tokens'
|
||||
],
|
||||
datasets: [
|
||||
{
|
||||
data: [
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
backgroundColor: [
|
||||
'#3b82f6',
|
||||
'#10b981',
|
||||
'#f59e0b'
|
||||
],
|
||||
borderWidth: 2
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
position: 'bottom'
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
this.charts.systemHealth = new Chart(document.getElementById('system-health-chart'), {
|
||||
type: 'radar',
|
||||
data: {
|
||||
labels: [
|
||||
'CPU',
|
||||
'Memory',
|
||||
'Disk',
|
||||
'Network',
|
||||
'API',
|
||||
'Database'
|
||||
],
|
||||
datasets: [
|
||||
{
|
||||
label: 'Health Score',
|
||||
data: [
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100,
|
||||
100
|
||||
],
|
||||
borderColor: '#10b981',
|
||||
backgroundColor: 'rgba(16, 185, 129, 0.2)',
|
||||
pointBackgroundColor: '#10b981',
|
||||
pointBorderColor: '#fff',
|
||||
pointHoverBackgroundColor: '#fff',
|
||||
pointHoverBorderColor: '#10b981'
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
scales: {
|
||||
r: {
|
||||
beginAtZero: true,
|
||||
max: 100
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
this.charts.loadMonitor = new Chart(document.getElementById('load-monitor-chart'), {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: [
|
||||
'1m',
|
||||
'5m',
|
||||
'15m',
|
||||
'30m',
|
||||
'1h',
|
||||
'24h'
|
||||
],
|
||||
datasets: [
|
||||
{
|
||||
label: 'Average Load',
|
||||
data: [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
backgroundColor: 'rgba(59, 130, 246, 0.7)',
|
||||
borderColor: '#3b82f6',
|
||||
borderWidth: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
position: 'top'
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
y: {
|
||||
beginAtZero: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
startRealTimeUpdates() {
|
||||
this.updateInterval = setInterval(()=>{
|
||||
if (this.isConnected) {
|
||||
this.requestMetricsUpdate();
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
requestMetricsUpdate() {
|
||||
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify({
|
||||
type: 'request_metrics',
|
||||
timestamp: Date.now()
|
||||
}));
|
||||
}
|
||||
}
|
||||
handleWebSocketData(data) {
|
||||
switch(data.type){
|
||||
case 'metrics_update':
|
||||
this.updateMetrics(data.payload);
|
||||
break;
|
||||
case 'alert':
|
||||
this.handleAlert(data.payload);
|
||||
break;
|
||||
case 'health_status':
|
||||
this.updateHealthStatus(data.payload);
|
||||
break;
|
||||
default:
|
||||
console.log('Unknown WebSocket message type:', data.type);
|
||||
}
|
||||
}
|
||||
updateMetrics(metrics) {
|
||||
this.metricsCache.set('latest', metrics);
|
||||
if (this.charts.performance && metrics.performance) {
|
||||
const chart = this.charts.performance;
|
||||
const now = new Date().toLocaleTimeString();
|
||||
chart.data.labels.push(now);
|
||||
chart.data.datasets[0].data.push(metrics.performance.responseTime);
|
||||
chart.data.datasets[1].data.push(metrics.performance.throughput);
|
||||
if (chart.data.labels.length > 20) {
|
||||
chart.data.labels.shift();
|
||||
chart.data.datasets[0].data.shift();
|
||||
chart.data.datasets[1].data.shift();
|
||||
}
|
||||
chart.update('none');
|
||||
}
|
||||
if (this.charts.tokenUsage && metrics.tokens) {
|
||||
const chart = this.charts.tokenUsage;
|
||||
chart.data.datasets[0].data = [
|
||||
metrics.tokens.input,
|
||||
metrics.tokens.output,
|
||||
metrics.tokens.cached
|
||||
];
|
||||
chart.update('none');
|
||||
}
|
||||
if (this.charts.systemHealth && metrics.health) {
|
||||
const chart = this.charts.systemHealth;
|
||||
chart.data.datasets[0].data = [
|
||||
metrics.health.cpu,
|
||||
metrics.health.memory,
|
||||
metrics.health.disk,
|
||||
metrics.health.network,
|
||||
metrics.health.api,
|
||||
metrics.health.database
|
||||
];
|
||||
chart.update('none');
|
||||
}
|
||||
if (this.charts.loadMonitor && metrics.load) {
|
||||
const chart = this.charts.loadMonitor;
|
||||
chart.data.datasets[0].data = [
|
||||
metrics.load.oneMin,
|
||||
metrics.load.fiveMin,
|
||||
metrics.load.fifteenMin,
|
||||
metrics.load.thirtyMin,
|
||||
metrics.load.oneHour,
|
||||
metrics.load.twentyFourHour
|
||||
];
|
||||
chart.update('none');
|
||||
}
|
||||
this.updateMetricDisplays(metrics);
|
||||
}
|
||||
updateMetricDisplays(metrics) {
|
||||
const perfSection = document.getElementById('performance-metrics');
|
||||
if (perfSection && metrics.performance) {
|
||||
perfSection.innerHTML = `
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Response Time</div>
|
||||
<div class="metric-value">${metrics.performance.responseTime}ms</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Throughput</div>
|
||||
<div class="metric-value">${metrics.performance.throughput} req/s</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Error Rate</div>
|
||||
<div class="metric-value">${metrics.performance.errorRate}%</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Uptime</div>
|
||||
<div class="metric-value">${metrics.performance.uptime}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
const tokenSection = document.getElementById('token-metrics');
|
||||
if (tokenSection && metrics.tokens) {
|
||||
const total = metrics.tokens.input + metrics.tokens.output + metrics.tokens.cached;
|
||||
tokenSection.innerHTML = `
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Total Tokens</div>
|
||||
<div class="metric-value">${total.toLocaleString()}</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Input Tokens</div>
|
||||
<div class="metric-value">${metrics.tokens.input.toLocaleString()}</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Output Tokens</div>
|
||||
<div class="metric-value">${metrics.tokens.output.toLocaleString()}</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Cache Hit Rate</div>
|
||||
<div class="metric-value">${(metrics.tokens.cached / total * 100).toFixed(1)}%</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
const healthSection = document.getElementById('health-status');
|
||||
if (healthSection && metrics.health) {
|
||||
const overallHealth = Math.round((metrics.health.cpu + metrics.health.memory + metrics.health.disk + metrics.health.network + metrics.health.api + metrics.health.database) / 6);
|
||||
healthSection.innerHTML = `
|
||||
<div class="health-overview">
|
||||
<div class="health-score ${this.getHealthClass(overallHealth)}">
|
||||
${overallHealth}%
|
||||
</div>
|
||||
<div class="health-label">Overall Health</div>
|
||||
</div>
|
||||
<div class="health-components">
|
||||
<div class="health-component">
|
||||
<span class="component-name">CPU</span>
|
||||
<span class="component-value ${this.getHealthClass(metrics.health.cpu)}">${metrics.health.cpu}%</span>
|
||||
</div>
|
||||
<div class="health-component">
|
||||
<span class="component-name">Memory</span>
|
||||
<span class="component-value ${this.getHealthClass(metrics.health.memory)}">${metrics.health.memory}%</span>
|
||||
</div>
|
||||
<div class="health-component">
|
||||
<span class="component-name">Disk</span>
|
||||
<span class="component-value ${this.getHealthClass(metrics.health.disk)}">${metrics.health.disk}%</span>
|
||||
</div>
|
||||
<div class="health-component">
|
||||
<span class="component-name">Network</span>
|
||||
<span class="component-value ${this.getHealthClass(metrics.health.network)}">${metrics.health.network}%</span>
|
||||
</div>
|
||||
<div class="health-component">
|
||||
<span class="component-name">API</span>
|
||||
<span class="component-value ${this.getHealthClass(metrics.health.api)}">${metrics.health.api}%</span>
|
||||
</div>
|
||||
<div class="health-component">
|
||||
<span class="component-name">Database</span>
|
||||
<span class="component-value ${this.getHealthClass(metrics.health.database)}">${metrics.health.database}%</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
getHealthClass(score) {
|
||||
if (score >= 90) return 'health-excellent';
|
||||
if (score >= 70) return 'health-good';
|
||||
if (score >= 50) return 'health-warning';
|
||||
return 'health-critical';
|
||||
}
|
||||
handleAlert(alert) {
|
||||
const alertsContainer = document.getElementById('alerts-container');
|
||||
if (alertsContainer) {
|
||||
const alertElement = document.createElement('div');
|
||||
alertElement.className = `alert alert-${alert.severity}`;
|
||||
alertElement.innerHTML = `
|
||||
<div class="alert-header">
|
||||
<span class="alert-title">${alert.title}</span>
|
||||
<span class="alert-timestamp">${new Date(alert.timestamp).toLocaleTimeString()}</span>
|
||||
</div>
|
||||
<div class="alert-message">${alert.message}</div>
|
||||
<button class="alert-dismiss" onclick="this.parentElement.remove()">×</button>
|
||||
`;
|
||||
alertsContainer.insertBefore(alertElement, alertsContainer.firstChild);
|
||||
if (alert.severity === 'info') {
|
||||
setTimeout(()=>{
|
||||
if (alertElement.parentElement) {
|
||||
alertElement.remove();
|
||||
}
|
||||
}, 10000);
|
||||
}
|
||||
}
|
||||
}
|
||||
switchTab(tabName) {
|
||||
this.currentTab = tabName;
|
||||
document.querySelectorAll('.analysis-tab').forEach((tab)=>{
|
||||
tab.classList.remove('active');
|
||||
});
|
||||
document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
|
||||
document.querySelectorAll('.analysis-panel').forEach((panel)=>{
|
||||
panel.classList.remove('active');
|
||||
});
|
||||
document.getElementById(`${tabName}-panel`).classList.add('active');
|
||||
setTimeout(()=>{
|
||||
Object.values(this.charts).forEach((chart)=>{
|
||||
if (chart && chart.resize) {
|
||||
chart.resize();
|
||||
}
|
||||
});
|
||||
}, 100);
|
||||
}
|
||||
async executeTool(toolName) {
|
||||
const button = document.querySelector(`[data-tool="${toolName}"]`);
|
||||
if (button) {
|
||||
button.classList.add('loading');
|
||||
button.disabled = true;
|
||||
}
|
||||
try {
|
||||
switch(toolName){
|
||||
case 'performance_report':
|
||||
await this.performanceReport();
|
||||
break;
|
||||
case 'bottleneck_analyze':
|
||||
await this.bottleneckAnalyze();
|
||||
break;
|
||||
case 'token_usage':
|
||||
await this.tokenUsage();
|
||||
break;
|
||||
case 'benchmark_run':
|
||||
await this.benchmarkRun();
|
||||
break;
|
||||
case 'metrics_collect':
|
||||
await this.metricsCollect();
|
||||
break;
|
||||
case 'trend_analysis':
|
||||
await this.trendAnalysis();
|
||||
break;
|
||||
case 'cost_analysis':
|
||||
await this.costAnalysis();
|
||||
break;
|
||||
case 'quality_assess':
|
||||
await this.qualityAssess();
|
||||
break;
|
||||
case 'error_analysis':
|
||||
await this.errorAnalysis();
|
||||
break;
|
||||
case 'usage_stats':
|
||||
await this.usageStats();
|
||||
break;
|
||||
case 'health_check':
|
||||
await this.healthCheck();
|
||||
break;
|
||||
case 'load_monitor':
|
||||
await this.loadMonitor();
|
||||
break;
|
||||
case 'capacity_plan':
|
||||
await this.capacityPlan();
|
||||
break;
|
||||
default:
|
||||
console.warn('Unknown tool:', toolName);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error executing tool ${toolName}:`, error);
|
||||
this.showError(`Failed to execute ${toolName}: ${error.message}`);
|
||||
} finally{
|
||||
if (button) {
|
||||
button.classList.remove('loading');
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
async performanceReport() {
|
||||
try {
|
||||
const report = await this.fetchAnalysisData('/api/analysis/performance-report');
|
||||
this.displayReport('performance-report-output', report);
|
||||
await this.notifyToolCompletion('performance_report');
|
||||
} catch (error) {
|
||||
this.displayError('performance-report-output', 'Unable to fetch performance report. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async bottleneckAnalyze() {
|
||||
try {
|
||||
const analysis = await this.fetchAnalysisData('/api/analysis/bottleneck-analyze');
|
||||
this.displayAnalysis('bottleneck-analysis-output', analysis);
|
||||
await this.notifyToolCompletion('bottleneck_analyze');
|
||||
} catch (error) {
|
||||
this.displayError('bottleneck-analysis-output', 'Unable to fetch bottleneck analysis. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async tokenUsage() {
|
||||
try {
|
||||
const usage = await this.fetchAnalysisData('/api/analysis/token-usage');
|
||||
this.displayUsage('token-usage-output', usage);
|
||||
await this.notifyToolCompletion('token_usage');
|
||||
} catch (error) {
|
||||
this.displayError('token-usage-output', 'Unable to fetch token usage data. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async benchmarkRun() {
|
||||
try {
|
||||
const benchmark = await this.fetchAnalysisData('/api/analysis/benchmark-run');
|
||||
this.displayBenchmark('benchmark-output', benchmark);
|
||||
await this.notifyToolCompletion('benchmark_run');
|
||||
} catch (error) {
|
||||
this.displayError('benchmark-output', 'Unable to run benchmark. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async metricsCollect() {
|
||||
try {
|
||||
const metrics = await this.fetchAnalysisData('/api/analysis/metrics-collect');
|
||||
this.displayMetrics('metrics-output', metrics);
|
||||
await this.notifyToolCompletion('metrics_collect');
|
||||
} catch (error) {
|
||||
this.displayError('metrics-output', 'Unable to collect metrics. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async trendAnalysis() {
|
||||
try {
|
||||
const trends = await this.fetchAnalysisData('/api/analysis/trend-analysis');
|
||||
this.displayTrends('trends-output', trends);
|
||||
await this.notifyToolCompletion('trend_analysis');
|
||||
} catch (error) {
|
||||
this.displayError('trends-output', 'Unable to fetch trend analysis. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async costAnalysis() {
|
||||
try {
|
||||
const costs = await this.fetchAnalysisData('/api/analysis/cost-analysis');
|
||||
this.displayCosts('costs-output', costs);
|
||||
await this.notifyToolCompletion('cost_analysis');
|
||||
} catch (error) {
|
||||
this.displayError('costs-output', 'Unable to fetch cost analysis. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async qualityAssess() {
|
||||
try {
|
||||
const quality = await this.fetchAnalysisData('/api/analysis/quality-assess');
|
||||
this.displayQuality('quality-output', quality);
|
||||
await this.notifyToolCompletion('quality_assess');
|
||||
} catch (error) {
|
||||
this.displayError('quality-output', 'Unable to assess quality. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async errorAnalysis() {
|
||||
try {
|
||||
const errors = await this.fetchAnalysisData('/api/analysis/error-analysis');
|
||||
this.displayErrors('errors-output', errors);
|
||||
await this.notifyToolCompletion('error_analysis');
|
||||
} catch (error) {
|
||||
this.displayError('errors-output', 'Unable to fetch error analysis. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async usageStats() {
|
||||
try {
|
||||
const stats = await this.fetchAnalysisData('/api/analysis/usage-stats');
|
||||
this.displayStats('stats-output', stats);
|
||||
await this.notifyToolCompletion('usage_stats');
|
||||
} catch (error) {
|
||||
this.displayError('stats-output', 'Unable to fetch usage statistics. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async healthCheck() {
|
||||
try {
|
||||
const health = await this.fetchAnalysisData('/api/analysis/health-check');
|
||||
this.displayHealth('health-output', health);
|
||||
await this.notifyToolCompletion('health_check');
|
||||
} catch (error) {
|
||||
this.displayError('health-output', 'Unable to perform health check. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async loadMonitor() {
|
||||
try {
|
||||
const load = await this.fetchAnalysisData('/api/analysis/load-monitor');
|
||||
this.displayLoad('load-output', load);
|
||||
await this.notifyToolCompletion('load_monitor');
|
||||
} catch (error) {
|
||||
this.displayError('load-output', 'Unable to monitor load. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async capacityPlan() {
|
||||
try {
|
||||
const capacity = await this.fetchAnalysisData('/api/analysis/capacity-plan');
|
||||
this.displayCapacity('capacity-output', capacity);
|
||||
await this.notifyToolCompletion('capacity_plan');
|
||||
} catch (error) {
|
||||
this.displayError('capacity-output', 'Unable to fetch capacity plan. Please ensure the analysis service is running.');
|
||||
}
|
||||
}
|
||||
async fetchAnalysisData(endpoint) {
|
||||
try {
|
||||
const response = await fetch(endpoint);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('Fetch error:', error);
|
||||
this.showError(`Failed to fetch data from ${endpoint}: ${error.message}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
getMockData(endpoint) {
|
||||
const mockData = {
|
||||
'/api/analysis/performance-report': {
|
||||
summary: 'System performance is within acceptable ranges',
|
||||
metrics: {
|
||||
averageResponseTime: 245,
|
||||
throughput: 1250,
|
||||
errorRate: 0.02,
|
||||
uptime: '99.8%'
|
||||
},
|
||||
recommendations: [
|
||||
'Consider caching frequently accessed data',
|
||||
'Optimize database queries for better performance',
|
||||
'Monitor memory usage during peak hours'
|
||||
]
|
||||
},
|
||||
'/api/analysis/bottleneck-analyze': {
|
||||
bottlenecks: [
|
||||
{
|
||||
component: 'Database',
|
||||
severity: 'medium',
|
||||
impact: 'Response time +15%'
|
||||
},
|
||||
{
|
||||
component: 'API Gateway',
|
||||
severity: 'low',
|
||||
impact: 'Throughput -5%'
|
||||
}
|
||||
],
|
||||
recommendations: [
|
||||
'Add database read replicas',
|
||||
'Implement connection pooling',
|
||||
'Optimize slow queries'
|
||||
]
|
||||
},
|
||||
'/api/analysis/token-usage': {
|
||||
totalTokens: 2450000,
|
||||
inputTokens: 1200000,
|
||||
outputTokens: 950000,
|
||||
cachedTokens: 300000,
|
||||
cost: 245.5,
|
||||
efficiency: 85.2
|
||||
}
|
||||
};
|
||||
return mockData[endpoint] || {
|
||||
message: 'No data available'
|
||||
};
|
||||
}
|
||||
displayReport(containerId, report) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
container.innerHTML = `
|
||||
<div class="report-summary">
|
||||
<h3>Performance Report</h3>
|
||||
<p>${report.summary}</p>
|
||||
</div>
|
||||
<div class="report-metrics">
|
||||
<div class="metric-grid">
|
||||
<div class="metric-item">
|
||||
<label>Average Response Time</label>
|
||||
<span>${report.metrics.averageResponseTime}ms</span>
|
||||
</div>
|
||||
<div class="metric-item">
|
||||
<label>Throughput</label>
|
||||
<span>${report.metrics.throughput} req/s</span>
|
||||
</div>
|
||||
<div class="metric-item">
|
||||
<label>Error Rate</label>
|
||||
<span>${(report.metrics.errorRate * 100).toFixed(2)}%</span>
|
||||
</div>
|
||||
<div class="metric-item">
|
||||
<label>Uptime</label>
|
||||
<span>${report.metrics.uptime}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="report-recommendations">
|
||||
<h4>Recommendations</h4>
|
||||
<ul>
|
||||
${report.recommendations.map((rec)=>`<li>${rec}</li>`).join('')}
|
||||
</ul>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
displayAnalysis(containerId, analysis) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
container.innerHTML = `
|
||||
<div class="analysis-results">
|
||||
<h3>Bottleneck Analysis</h3>
|
||||
<div class="bottleneck-list">
|
||||
${analysis.bottlenecks.map((bottleneck)=>`
|
||||
<div class="bottleneck-item severity-${bottleneck.severity}">
|
||||
<div class="bottleneck-component">${bottleneck.component}</div>
|
||||
<div class="bottleneck-severity">${bottleneck.severity}</div>
|
||||
<div class="bottleneck-impact">${bottleneck.impact}</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
<div class="analysis-recommendations">
|
||||
<h4>Recommendations</h4>
|
||||
<ul>
|
||||
${analysis.recommendations.map((rec)=>`<li>${rec}</li>`).join('')}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
displayUsage(containerId, usage) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
container.innerHTML = `
|
||||
<div class="usage-overview">
|
||||
<h3>Token Usage Analysis</h3>
|
||||
<div class="usage-stats">
|
||||
<div class="usage-stat">
|
||||
<label>Total Tokens</label>
|
||||
<span>${usage.totalTokens.toLocaleString()}</span>
|
||||
</div>
|
||||
<div class="usage-stat">
|
||||
<label>Input Tokens</label>
|
||||
<span>${usage.inputTokens.toLocaleString()}</span>
|
||||
</div>
|
||||
<div class="usage-stat">
|
||||
<label>Output Tokens</label>
|
||||
<span>${usage.outputTokens.toLocaleString()}</span>
|
||||
</div>
|
||||
<div class="usage-stat">
|
||||
<label>Cached Tokens</label>
|
||||
<span>${usage.cachedTokens.toLocaleString()}</span>
|
||||
</div>
|
||||
<div class="usage-stat">
|
||||
<label>Total Cost</label>
|
||||
<span>$${usage.cost.toFixed(2)}</span>
|
||||
</div>
|
||||
<div class="usage-stat">
|
||||
<label>Efficiency</label>
|
||||
<span>${usage.efficiency.toFixed(1)}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
exportData(type, format) {
|
||||
const data = this.metricsCache.get('latest') || {};
|
||||
const timestamp = new Date().toISOString().split('T')[0];
|
||||
const filename = `${type}_${timestamp}.${format}`;
|
||||
if (format === 'json') {
|
||||
this.downloadJSON(data, filename);
|
||||
} else if (format === 'csv') {
|
||||
this.downloadCSV(data, filename);
|
||||
}
|
||||
}
|
||||
downloadJSON(data, filename) {
|
||||
const blob = new Blob([
|
||||
JSON.stringify(data, null, 2)
|
||||
], {
|
||||
type: 'application/json'
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
downloadCSV(data, filename) {
|
||||
const csv = this.jsonToCSV(data);
|
||||
const blob = new Blob([
|
||||
csv
|
||||
], {
|
||||
type: 'text/csv'
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
jsonToCSV(json) {
|
||||
const flatten = (obj, prefix = '')=>{
|
||||
const flattened = {};
|
||||
for(const key in obj){
|
||||
if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
|
||||
Object.assign(flattened, flatten(obj[key], prefix + key + '.'));
|
||||
} else {
|
||||
flattened[prefix + key] = Array.isArray(obj[key]) ? JSON.stringify(obj[key]) : obj[key];
|
||||
}
|
||||
}
|
||||
return flattened;
|
||||
};
|
||||
const flattened = flatten(json);
|
||||
const headers = Object.keys(flattened);
|
||||
const valueRow = headers.map((header)=>{
|
||||
const value = flattened[header];
|
||||
if (value === null || value === undefined) {
|
||||
return '';
|
||||
}
|
||||
let strValue = String(value);
|
||||
if (strValue.includes(',') || strValue.includes('"') || strValue.includes('\n')) {
|
||||
strValue = '"' + strValue.replace(/"/g, '""') + '"';
|
||||
}
|
||||
return strValue;
|
||||
}).join(',');
|
||||
return [
|
||||
headers.join(','),
|
||||
valueRow
|
||||
].join('\n');
|
||||
}
|
||||
refreshSection(section) {
|
||||
switch(section){
|
||||
case 'metrics':
|
||||
this.requestMetricsUpdate();
|
||||
break;
|
||||
case 'charts':
|
||||
Object.values(this.charts).forEach((chart)=>{
|
||||
if (chart && chart.update) {
|
||||
chart.update();
|
||||
}
|
||||
});
|
||||
break;
|
||||
case 'alerts':
|
||||
document.getElementById('alerts-container').innerHTML = '';
|
||||
break;
|
||||
default:
|
||||
console.warn('Unknown section:', section);
|
||||
}
|
||||
}
|
||||
updateConnectionStatus(status) {
|
||||
const statusElement = document.getElementById('connection-status');
|
||||
if (statusElement) {
|
||||
statusElement.className = `connection-status ${status}`;
|
||||
statusElement.textContent = status.charAt(0).toUpperCase() + status.slice(1);
|
||||
}
|
||||
}
|
||||
showError(message) {
|
||||
const errorElement = document.createElement('div');
|
||||
errorElement.className = 'error-message';
|
||||
errorElement.textContent = message;
|
||||
document.body.appendChild(errorElement);
|
||||
setTimeout(()=>{
|
||||
errorElement.remove();
|
||||
}, 5000);
|
||||
}
|
||||
displayError(containerId, message) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
container.innerHTML = `
|
||||
<div class="error-container">
|
||||
<div class="error-icon">❌</div>
|
||||
<div class="error-message">
|
||||
<h4>Error</h4>
|
||||
<p>${message}</p>
|
||||
</div>
|
||||
<div class="error-actions">
|
||||
<button class="retry-btn" onclick="location.reload()">Retry</button>
|
||||
<button class="dismiss-btn" onclick="this.parentElement.parentElement.remove()">Dismiss</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
async notifyToolCompletion(toolName) {
|
||||
try {
|
||||
const response = await fetch('/api/swarm/notify', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
message: `${toolName} completed`,
|
||||
timestamp: Date.now(),
|
||||
agent: 'analysis-tools'
|
||||
})
|
||||
});
|
||||
if (!response.ok) {
|
||||
console.warn('Failed to notify swarm');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error notifying swarm:', error);
|
||||
}
|
||||
}
|
||||
destroy() {
|
||||
if (this.updateInterval) {
|
||||
clearInterval(this.updateInterval);
|
||||
}
|
||||
if (this.ws) {
|
||||
this.ws.close();
|
||||
}
|
||||
Object.values(this.charts).forEach((chart)=>{
|
||||
if (chart && chart.destroy) {
|
||||
chart.destroy();
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
document.addEventListener('DOMContentLoaded', ()=>{
|
||||
window.analysisTools = new AnalysisTools();
|
||||
});
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = AnalysisTools;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=analysis-tools.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/analysis-tools.js"],"sourcesContent":["/**\n * Analysis & Monitoring Tools for Claude Flow Web UI\n * Agent 2 - Analysis & Monitoring Tools Developer\n *\n * Features:\n * - 13 analysis and monitoring tools\n * - Real-time dashboards and visualizations\n * - WebSocket integration for live data\n * - Export functionality for reports\n * - 4 main tabs: Metrics, Reports, Analysis, Health\n */\n\nclass AnalysisTools {\n constructor() {\n this.ws = null;\n this.charts = {};\n this.currentTab = 'metrics';\n this.isConnected = false;\n this.metricsCache = new Map();\n this.updateInterval = null;\n this.init();\n }\n\n init() {\n this.setupWebSocket();\n this.setupEventListeners();\n this.initializeCharts();\n this.startRealTimeUpdates();\n }\n\n setupWebSocket() {\n try {\n this.ws = new WebSocket('ws://localhost:3000/analysis');\n\n this.ws.onopen = () => {\n this.isConnected = true;\n console.log('Analysis WebSocket connected');\n this.updateConnectionStatus('connected');\n };\n\n this.ws.onmessage = (event) => {\n const data = JSON.parse(event.data);\n this.handleWebSocketData(data);\n };\n\n this.ws.onclose = () => {\n this.isConnected = false;\n console.log('Analysis WebSocket disconnected');\n this.updateConnectionStatus('disconnected');\n setTimeout(() => this.setupWebSocket(), 5000);\n };\n\n this.ws.onerror = (error) => {\n console.error('Analysis WebSocket error:', error);\n this.updateConnectionStatus('error');\n };\n } catch (error) {\n console.error('Failed to setup WebSocket:', error);\n this.updateConnectionStatus('error');\n }\n }\n\n setupEventListeners() {\n // Tab switching\n document.querySelectorAll('.analysis-tab').forEach((tab) => {\n tab.addEventListener('click', (e) => {\n this.switchTab(e.target.dataset.tab);\n });\n });\n\n // Export buttons\n document.querySelectorAll('.export-btn').forEach((btn) => {\n btn.addEventListener('click', (e) => {\n const format = e.target.dataset.format;\n const type = e.target.dataset.type;\n this.exportData(type, format);\n });\n });\n\n // Tool buttons\n document.querySelectorAll('.tool-btn').forEach((btn) => {\n btn.addEventListener('click', (e) => {\n const tool = e.target.dataset.tool;\n this.executeTool(tool);\n });\n });\n\n // Refresh buttons\n document.querySelectorAll('.refresh-btn').forEach((btn) => {\n btn.addEventListener('click', (e) => {\n const section = e.target.dataset.section;\n this.refreshSection(section);\n });\n });\n }\n\n initializeCharts() {\n // Performance metrics chart\n this.charts.performance = new Chart(document.getElementById('performance-chart'), {\n type: 'line',\n data: {\n labels: [],\n datasets: [\n {\n label: 'Response Time (ms)',\n data: [],\n borderColor: '#3b82f6',\n backgroundColor: 'rgba(59, 130, 246, 0.1)',\n tension: 0.4,\n },\n {\n label: 'Throughput (req/s)',\n data: [],\n borderColor: '#10b981',\n backgroundColor: 'rgba(16, 185, 129, 0.1)',\n tension: 0.4,\n },\n ],\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n plugins: {\n legend: {\n position: 'top',\n },\n },\n scales: {\n x: {\n display: true,\n title: {\n display: true,\n text: 'Time',\n },\n },\n y: {\n display: true,\n title: {\n display: true,\n text: 'Value',\n },\n },\n },\n },\n });\n\n // Token usage chart\n this.charts.tokenUsage = new Chart(document.getElementById('token-usage-chart'), {\n type: 'doughnut',\n data: {\n labels: ['Input Tokens', 'Output Tokens', 'Cached Tokens'],\n datasets: [\n {\n data: [0, 0, 0],\n backgroundColor: ['#3b82f6', '#10b981', '#f59e0b'],\n borderWidth: 2,\n },\n ],\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n plugins: {\n legend: {\n position: 'bottom',\n },\n },\n },\n });\n\n // System health chart\n this.charts.systemHealth = new Chart(document.getElementById('system-health-chart'), {\n type: 'radar',\n data: {\n labels: ['CPU', 'Memory', 'Disk', 'Network', 'API', 'Database'],\n datasets: [\n {\n label: 'Health Score',\n data: [100, 100, 100, 100, 100, 100],\n Line truncated
|
||||
@@ -1,667 +0,0 @@
|
||||
export class CommandHandler {
|
||||
constructor(terminal, wsClient){
|
||||
this.terminal = terminal;
|
||||
this.wsClient = wsClient;
|
||||
this.isProcessing = false;
|
||||
this.builtinCommands = {
|
||||
help: this.showHelp.bind(this),
|
||||
clear: this.clearConsole.bind(this),
|
||||
status: this.showStatus.bind(this),
|
||||
connect: this.connectToServer.bind(this),
|
||||
disconnect: this.disconnectFromServer.bind(this),
|
||||
tools: this.listTools.bind(this),
|
||||
health: this.checkHealth.bind(this),
|
||||
history: this.showHistory.bind(this),
|
||||
export: this.exportSession.bind(this),
|
||||
theme: this.changeTheme.bind(this),
|
||||
version: this.showVersion.bind(this)
|
||||
};
|
||||
this.claudeFlowCommands = {
|
||||
'claude-flow': this.executeClaudeFlow.bind(this),
|
||||
swarm: this.executeSwarm.bind(this),
|
||||
init: this.initializeProject.bind(this),
|
||||
config: this.manageConfig.bind(this),
|
||||
memory: this.manageMemory.bind(this),
|
||||
agents: this.manageAgents.bind(this),
|
||||
benchmark: this.runBenchmark.bind(this),
|
||||
sparc: this.executeSparc.bind(this)
|
||||
};
|
||||
this.sparcModeCommands = {
|
||||
coder: this.executeSparcMode.bind(this, 'coder'),
|
||||
architect: this.executeSparcMode.bind(this, 'architect'),
|
||||
analyst: this.executeSparcMode.bind(this, 'analyst'),
|
||||
researcher: this.executeSparcMode.bind(this, 'researcher'),
|
||||
reviewer: this.executeSparcMode.bind(this, 'reviewer'),
|
||||
tester: this.executeSparcMode.bind(this, 'tester'),
|
||||
debugger: this.executeSparcMode.bind(this, 'debugger'),
|
||||
documenter: this.executeSparcMode.bind(this, 'documenter'),
|
||||
optimizer: this.executeSparcMode.bind(this, 'optimizer'),
|
||||
designer: this.executeSparcMode.bind(this, 'designer')
|
||||
};
|
||||
this.allCommands = {
|
||||
...this.builtinCommands,
|
||||
...this.claudeFlowCommands,
|
||||
...this.sparcModeCommands
|
||||
};
|
||||
}
|
||||
async processCommand(command) {
|
||||
if (this.isProcessing) {
|
||||
this.terminal.writeWarning('Another command is still processing. Please wait...');
|
||||
return;
|
||||
}
|
||||
this.isProcessing = true;
|
||||
this.terminal.setLocked(true);
|
||||
try {
|
||||
const { cmd, args } = this.parseCommand(command);
|
||||
if (this.allCommands[cmd]) {
|
||||
await this.allCommands[cmd](args);
|
||||
} else {
|
||||
await this.executeRemoteCommand(cmd, args);
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(error.message);
|
||||
console.error('Command execution error:', error);
|
||||
} finally{
|
||||
this.isProcessing = false;
|
||||
this.terminal.setLocked(false);
|
||||
}
|
||||
}
|
||||
parseCommand(commandString) {
|
||||
const parts = commandString.trim().split(/\s+/);
|
||||
const cmd = parts[0].toLowerCase();
|
||||
const args = parts.slice(1);
|
||||
return {
|
||||
cmd,
|
||||
args
|
||||
};
|
||||
}
|
||||
async showHelp(args) {
|
||||
if (args.length > 0) {
|
||||
const command = args[0].toLowerCase();
|
||||
if (this.allCommands[command]) {
|
||||
this.showCommandHelp(command);
|
||||
} else {
|
||||
this.terminal.writeError(`Unknown command: ${command}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.terminal.writeInfo('Claude Flow Console Commands:');
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Built-in Commands:');
|
||||
Object.keys(this.builtinCommands).forEach((cmd)=>{
|
||||
this.terminal.writeLine(` ${cmd.padEnd(12)} - ${this.getCommandDescription(cmd)}`);
|
||||
});
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Claude Flow Commands:');
|
||||
Object.keys(this.claudeFlowCommands).forEach((cmd)=>{
|
||||
this.terminal.writeLine(` ${cmd.padEnd(12)} - ${this.getCommandDescription(cmd)}`);
|
||||
});
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Tool Commands (from tools list):');
|
||||
this.terminal.writeLine(' system/health - Get system health status');
|
||||
this.terminal.writeLine(' memory/manage - Manage memory (list, store <key> <value>, retrieve <key>)');
|
||||
this.terminal.writeLine(' agents/manage - Manage agents (list, create <type>, status <id>)');
|
||||
this.terminal.writeLine(' swarm/orchestrate - Swarm operations (status, create, start, stop)');
|
||||
this.terminal.writeLine(' sparc/execute - Execute SPARC modes (coder, architect, etc.)');
|
||||
this.terminal.writeLine(' benchmark/run - Run benchmarks (default, memory, cpu, network)');
|
||||
this.terminal.writeLine(' claude-flow/execute - Execute Claude Flow commands');
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Use "help <command>" for detailed information about a specific command.');
|
||||
this.terminal.writeInfo('Use Ctrl+L to clear console, Ctrl+C to interrupt, Tab for autocomplete.');
|
||||
}
|
||||
getCommandDescription(command) {
|
||||
const descriptions = {
|
||||
help: 'Show help information',
|
||||
clear: 'Clear console output',
|
||||
status: 'Show connection and system status',
|
||||
connect: 'Connect to Claude Code server',
|
||||
disconnect: 'Disconnect from server',
|
||||
tools: 'List available tools',
|
||||
health: 'Check server health',
|
||||
history: 'Show command history',
|
||||
export: 'Export session data',
|
||||
theme: 'Change console theme',
|
||||
version: 'Show version information',
|
||||
'claude-flow': 'Execute Claude Flow commands',
|
||||
swarm: 'Manage and execute swarms',
|
||||
init: 'Initialize new project',
|
||||
config: 'Manage configuration',
|
||||
memory: 'Manage memory and data',
|
||||
agents: 'Manage agents',
|
||||
benchmark: 'Run benchmarks',
|
||||
sparc: 'Execute SPARC mode commands'
|
||||
};
|
||||
return descriptions[command] || "No description available";
|
||||
}
|
||||
showCommandHelp(command) {
|
||||
const helpText = {
|
||||
help: `
|
||||
Usage: help [command]
|
||||
Show help information for all commands or a specific command.
|
||||
|
||||
Examples:
|
||||
help - Show all commands
|
||||
help claude-flow - Show help for claude-flow command`,
|
||||
clear: `
|
||||
Usage: clear
|
||||
Clear the console output. You can also use Ctrl+L.`,
|
||||
connect: `
|
||||
Usage: connect [url] [token]
|
||||
Connect to Claude Code server.
|
||||
|
||||
Arguments:
|
||||
url - WebSocket URL (default: ws://localhost:3000/ws)
|
||||
token - Authentication token (optional)
|
||||
|
||||
Examples:
|
||||
connect
|
||||
connect ws://localhost:3000/ws
|
||||
connect ws://localhost:3000/ws my-auth-token`,
|
||||
'claude-flow': `
|
||||
Usage: claude-flow <subcommand> [options]
|
||||
Execute Claude Flow commands.
|
||||
|
||||
Subcommands:
|
||||
start [mode] - Start Claude Flow in specified mode
|
||||
stop - Stop Claude Flow
|
||||
status - Show Claude Flow status
|
||||
modes - List available SPARC modes
|
||||
|
||||
Examples:
|
||||
claude-flow start coder
|
||||
claude-flow status
|
||||
claude-flow modes`,
|
||||
swarm: `
|
||||
Usage: swarm <action> [options]
|
||||
Manage and execute swarms.
|
||||
|
||||
Actions:
|
||||
create <name> - Create new swarm
|
||||
start <name> - Start existing swarm
|
||||
stop <name> - Stop running swarm
|
||||
list - List all swarms
|
||||
status <name> - Show swarm status
|
||||
|
||||
Examples:
|
||||
swarm create my-swarm
|
||||
swarm start my-swarm
|
||||
swarm list`
|
||||
};
|
||||
if (helpText[command]) {
|
||||
this.terminal.writeInfo(helpText[command].trim());
|
||||
} else {
|
||||
this.terminal.writeInfo(`No detailed help available for: ${command}`);
|
||||
}
|
||||
}
|
||||
async clearConsole() {
|
||||
this.terminal.clear();
|
||||
this.terminal.writeSuccess('Console cleared');
|
||||
}
|
||||
async showStatus() {
|
||||
const wsStatus = this.wsClient.getStatus();
|
||||
const terminalStats = this.terminal.getStats();
|
||||
this.terminal.writeInfo('System Status:');
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Connection:');
|
||||
this.terminal.writeLine(` Status: ${wsStatus.connected ? 'Connected' : 'Disconnected'}`);
|
||||
this.terminal.writeLine(` URL: ${wsStatus.url || 'Not set'}`);
|
||||
this.terminal.writeLine(` Reconnect attempts: ${wsStatus.reconnectAttempts}`);
|
||||
this.terminal.writeLine(` Queued messages: ${wsStatus.queuedMessages}`);
|
||||
this.terminal.writeLine(` Pending requests: ${wsStatus.pendingRequests}`);
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Terminal:');
|
||||
this.terminal.writeLine(` Total lines: ${terminalStats.totalLines}`);
|
||||
this.terminal.writeLine(` History size: ${terminalStats.historySize}`);
|
||||
this.terminal.writeLine(` Input locked: ${terminalStats.isLocked}`);
|
||||
this.terminal.writeLine(` Current prompt: ${terminalStats.currentPrompt}`);
|
||||
if (wsStatus.connected) {
|
||||
try {
|
||||
const healthStatus = await this.wsClient.getHealthStatus();
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Server Health:');
|
||||
this.terminal.writeLine(` Status: ${healthStatus.healthy ? 'Healthy' : 'Unhealthy'}`);
|
||||
if (healthStatus.metrics) {
|
||||
Object.entries(healthStatus.metrics).forEach(([key, value])=>{
|
||||
this.terminal.writeLine(` ${key}: ${value}`);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeWarning('Failed to get server health status');
|
||||
}
|
||||
}
|
||||
}
|
||||
async connectToServer(args) {
|
||||
const url = args[0] || 'ws://localhost:3000/ws';
|
||||
const token = args[1] || '';
|
||||
this.terminal.writeInfo(`Connecting to ${url}...`);
|
||||
try {
|
||||
await this.wsClient.connect(url, token);
|
||||
await this.wsClient.initializeSession();
|
||||
this.terminal.writeSuccess('Connected successfully');
|
||||
this.terminal.setPrompt('claude-flow>');
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Connection failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
async disconnectFromServer() {
|
||||
this.wsClient.disconnect();
|
||||
this.terminal.writeSuccess('Disconnected from server');
|
||||
this.terminal.setPrompt('offline>');
|
||||
}
|
||||
async listTools() {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const tools = await this.wsClient.getAvailableTools();
|
||||
this.terminal.writeInfo('Available Tools:');
|
||||
this.terminal.writeLine('');
|
||||
if (tools && tools.length > 0) {
|
||||
tools.forEach((tool)=>{
|
||||
this.terminal.writeLine(` ${tool.name.padEnd(20)} - ${tool.description || "No description"}`);
|
||||
});
|
||||
} else {
|
||||
this.terminal.writeWarning('No tools available');
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Failed to list tools: ${error.message}`);
|
||||
}
|
||||
}
|
||||
async checkHealth() {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const health = await this.wsClient.getHealthStatus();
|
||||
if (health.healthy) {
|
||||
this.terminal.writeSuccess('Server is healthy');
|
||||
} else {
|
||||
this.terminal.writeError(`Server is unhealthy: ${health.error || 'Unknown error'}`);
|
||||
}
|
||||
if (health.metrics) {
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Metrics:');
|
||||
Object.entries(health.metrics).forEach(([key, value])=>{
|
||||
this.terminal.writeLine(` ${key}: ${value}`);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Health check failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
async showHistory() {
|
||||
const history = this.terminal.history;
|
||||
if (history.length === 0) {
|
||||
this.terminal.writeInfo('No command history');
|
||||
return;
|
||||
}
|
||||
this.terminal.writeInfo('Command History:');
|
||||
history.forEach((cmd, index)=>{
|
||||
this.terminal.writeLine(` ${(index + 1).toString().padStart(3)}: ${cmd}`);
|
||||
});
|
||||
}
|
||||
async exportSession(args) {
|
||||
const format = args[0] || 'json';
|
||||
const sessionData = {
|
||||
timestamp: new Date().toISOString(),
|
||||
terminal: this.terminal.exportHistory(),
|
||||
history: this.terminal.history,
|
||||
status: this.wsClient.getStatus()
|
||||
};
|
||||
if (format === 'json') {
|
||||
const blob = new Blob([
|
||||
JSON.stringify(sessionData, null, 2)
|
||||
], {
|
||||
type: 'application/json'
|
||||
});
|
||||
this.downloadFile(blob, `console-session-${Date.now()}.json`);
|
||||
this.terminal.writeSuccess('Session exported as JSON');
|
||||
} else {
|
||||
this.terminal.writeError(`Unsupported export format: ${format}`);
|
||||
}
|
||||
}
|
||||
async changeTheme(args) {
|
||||
const theme = args[0];
|
||||
const validThemes = [
|
||||
'dark',
|
||||
'light',
|
||||
'classic',
|
||||
'matrix'
|
||||
];
|
||||
if (!theme) {
|
||||
this.terminal.writeInfo(`Available themes: ${validThemes.join(', ')}`);
|
||||
return;
|
||||
}
|
||||
if (!validThemes.includes(theme)) {
|
||||
this.terminal.writeError(`Invalid theme: ${theme}`);
|
||||
return;
|
||||
}
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
localStorage.setItem('console_theme', theme);
|
||||
this.terminal.writeSuccess(`Theme changed to: ${theme}`);
|
||||
}
|
||||
async showVersion() {
|
||||
this.terminal.writeInfo('🌊 Claude Flow v2.0.0');
|
||||
this.terminal.writeLine('Advanced swarm orchestration platform');
|
||||
this.terminal.writeLine('Built with modern web technologies');
|
||||
}
|
||||
async executeClaudeFlow(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
if (args.length === 0) {
|
||||
this.terminal.writeError('Usage: claude-flow <subcommand> [options]');
|
||||
return;
|
||||
}
|
||||
const subcommand = args[0];
|
||||
const subArgs = args.slice(1);
|
||||
try {
|
||||
const result = await this.wsClient.executeCommand('claude-flow', {
|
||||
subcommand,
|
||||
args: subArgs
|
||||
});
|
||||
this.terminal.writeSuccess(`Claude Flow ${subcommand} executed successfully`);
|
||||
if (result && result.output) {
|
||||
this.terminal.writeLine(result.output);
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Claude Flow command failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
async executeSwarm(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const action = args[0] || 'status';
|
||||
this.terminal.writeInfo(`Executing swarm ${action}...`);
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: 'swarm/status',
|
||||
arguments: {
|
||||
action,
|
||||
args: args.slice(1)
|
||||
}
|
||||
});
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess('Swarm command executed successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Swarm command failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
async initializeProject(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
this.terminal.writeWarning('Project initialization not yet implemented in web console');
|
||||
}
|
||||
async manageConfig(args) {
|
||||
this.terminal.writeInfo('Use the Settings panel (⚙️ button) to manage configuration');
|
||||
}
|
||||
async manageMemory(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const operation = args[0] || 'list';
|
||||
const key = args[1];
|
||||
const value = args.slice(2).join(' ');
|
||||
this.terminal.writeInfo(`Executing memory ${operation}...`);
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: 'memory/manage',
|
||||
arguments: {
|
||||
operation,
|
||||
key,
|
||||
value
|
||||
}
|
||||
});
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess('Memory operation completed successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Memory command failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
async manageAgents(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const action = args[0] || 'list';
|
||||
const agentType = args[1];
|
||||
const agentId = args[1];
|
||||
this.terminal.writeInfo(`Executing agents ${action}...`);
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: 'agents/manage',
|
||||
arguments: {
|
||||
action,
|
||||
agentType,
|
||||
agentId
|
||||
}
|
||||
});
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess('Agent operation completed successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Agent command failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
async runBenchmark(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const suite = args[0] || 'default';
|
||||
const iterations = parseInt(args[1]) || 10;
|
||||
this.terminal.writeInfo(`Running benchmark suite: ${suite}...`);
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: 'benchmark/run',
|
||||
arguments: {
|
||||
suite,
|
||||
iterations
|
||||
}
|
||||
});
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess('Benchmark completed successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Benchmark failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
async executeSparc(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
if (args.length === 0) {
|
||||
this.terminal.writeInfo('Available SPARC modes:');
|
||||
const modes = [
|
||||
'coder',
|
||||
'architect',
|
||||
'analyst',
|
||||
'researcher',
|
||||
'reviewer',
|
||||
'tester',
|
||||
'debugger',
|
||||
'documenter',
|
||||
'optimizer',
|
||||
'designer'
|
||||
];
|
||||
modes.forEach((mode)=>{
|
||||
this.terminal.writeLine(` ${mode}`);
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const mode = args[0];
|
||||
const task = args.slice(1).join(' ') || 'General task execution';
|
||||
const options = {};
|
||||
this.terminal.writeInfo(`Executing SPARC mode: ${mode}...`);
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: 'sparc/execute',
|
||||
arguments: {
|
||||
mode,
|
||||
task,
|
||||
options
|
||||
}
|
||||
});
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess(`SPARC ${mode} mode executed successfully`);
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`SPARC execution failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
async executeSparcMode(mode, args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const task = args.join(' ') || `Execute ${mode} mode tasks`;
|
||||
const options = {};
|
||||
this.terminal.writeInfo(`Executing SPARC ${mode} mode...`);
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: 'sparc/execute',
|
||||
arguments: {
|
||||
mode,
|
||||
task,
|
||||
options
|
||||
}
|
||||
});
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess(`SPARC ${mode} mode executed successfully`);
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`SPARC ${mode} execution failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
async executeRemoteCommand(command, args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server. Use "connect" command first.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (command.includes('/')) {
|
||||
return await this.executeToolDirect(command, args);
|
||||
}
|
||||
this.terminal.writeInfo(`Executing remote command: ${command}`);
|
||||
const result = await this.wsClient.executeCommand(command, {
|
||||
args
|
||||
});
|
||||
if (result && result.output) {
|
||||
this.terminal.writeLine(result.output);
|
||||
} else {
|
||||
this.terminal.writeSuccess('Command executed successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Remote command failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
async executeToolDirect(toolName, args) {
|
||||
try {
|
||||
this.terminal.writeInfo(`Executing tool: ${toolName}...`);
|
||||
let toolArgs = {};
|
||||
switch(toolName){
|
||||
case 'system/health':
|
||||
toolArgs = {
|
||||
detailed: args.includes('--detailed')
|
||||
};
|
||||
break;
|
||||
case 'memory/manage':
|
||||
toolArgs = {
|
||||
operation: args[0] || 'list',
|
||||
key: args[1],
|
||||
value: args.slice(2).join(' ')
|
||||
};
|
||||
break;
|
||||
case 'agents/manage':
|
||||
toolArgs = {
|
||||
action: args[0] || 'list',
|
||||
agentType: args[1],
|
||||
agentId: args[1]
|
||||
};
|
||||
break;
|
||||
case 'swarm/orchestrate':
|
||||
toolArgs = {
|
||||
action: args[0] || 'status',
|
||||
args: args.slice(1)
|
||||
};
|
||||
break;
|
||||
case 'sparc/execute':
|
||||
toolArgs = {
|
||||
mode: args[0] || 'coder',
|
||||
task: args.slice(1).join(' ') || 'General task execution',
|
||||
options: {}
|
||||
};
|
||||
break;
|
||||
case 'benchmark/run':
|
||||
toolArgs = {
|
||||
suite: args[0] || 'default',
|
||||
iterations: parseInt(args[1]) || 10
|
||||
};
|
||||
break;
|
||||
case 'claude-flow/execute':
|
||||
toolArgs = {
|
||||
command: args[0] || 'status',
|
||||
args: args.slice(1)
|
||||
};
|
||||
break;
|
||||
default:
|
||||
toolArgs = {
|
||||
args
|
||||
};
|
||||
}
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: toolName,
|
||||
arguments: toolArgs
|
||||
});
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess(`Tool ${toolName} executed successfully`);
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Tool execution failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
downloadFile(blob, filename) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
getCommandSuggestions(input) {
|
||||
const allCommands = Object.keys(this.allCommands);
|
||||
return allCommands.filter((cmd)=>cmd.startsWith(input.toLowerCase()));
|
||||
}
|
||||
hasCommand(command) {
|
||||
return this.allCommands.hasOwnProperty(command.toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=command-handler.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/command-handler.js"],"sourcesContent":["/**\n * Command Handler for Claude Code Console\n * Processes and executes console commands\n */\n\nexport class CommandHandler {\n constructor(terminal, wsClient) {\n this.terminal = terminal;\n this.wsClient = wsClient;\n this.isProcessing = false;\n\n // Built-in commands\n this.builtinCommands = {\n help: this.showHelp.bind(this),\n clear: this.clearConsole.bind(this),\n status: this.showStatus.bind(this),\n connect: this.connectToServer.bind(this),\n disconnect: this.disconnectFromServer.bind(this),\n tools: this.listTools.bind(this),\n health: this.checkHealth.bind(this),\n history: this.showHistory.bind(this),\n export: this.exportSession.bind(this),\n theme: this.changeTheme.bind(this),\n version: this.showVersion.bind(this),\n };\n\n // Claude Flow commands\n this.claudeFlowCommands = {\n 'claude-flow': this.executeClaudeFlow.bind(this),\n swarm: this.executeSwarm.bind(this),\n init: this.initializeProject.bind(this),\n config: this.manageConfig.bind(this),\n memory: this.manageMemory.bind(this),\n agents: this.manageAgents.bind(this),\n benchmark: this.runBenchmark.bind(this),\n sparc: this.executeSparc.bind(this),\n };\n\n // Direct SPARC mode commands\n this.sparcModeCommands = {\n coder: this.executeSparcMode.bind(this, 'coder'),\n architect: this.executeSparcMode.bind(this, 'architect'),\n analyst: this.executeSparcMode.bind(this, 'analyst'),\n researcher: this.executeSparcMode.bind(this, 'researcher'),\n reviewer: this.executeSparcMode.bind(this, 'reviewer'),\n tester: this.executeSparcMode.bind(this, 'tester'),\n debugger: this.executeSparcMode.bind(this, 'debugger'),\n documenter: this.executeSparcMode.bind(this, 'documenter'),\n optimizer: this.executeSparcMode.bind(this, 'optimizer'),\n designer: this.executeSparcMode.bind(this, 'designer'),\n };\n\n this.allCommands = {\n ...this.builtinCommands,\n ...this.claudeFlowCommands,\n ...this.sparcModeCommands,\n };\n }\n\n /**\n * Process a command\n */\n async processCommand(command) {\n if (this.isProcessing) {\n this.terminal.writeWarning('Another command is still processing. Please wait...');\n return;\n }\n\n this.isProcessing = true;\n this.terminal.setLocked(true);\n\n try {\n const { cmd, args } = this.parseCommand(command);\n\n if (this.allCommands[cmd]) {\n await this.allCommands[cmd](args);\n } else {\n await this.executeRemoteCommand(cmd, args);\n }\n } catch (error) {\n this.terminal.writeError(error.message);\n console.error('Command execution error:', error);\n } finally {\n this.isProcessing = false;\n this.terminal.setLocked(false);\n }\n }\n\n /**\n * Parse command string into command and arguments\n */\n parseCommand(commandString) {\n const parts = commandString.trim().split(/\\s+/);\n const cmd = parts[0].toLowerCase();\n const args = parts.slice(1);\n\n return { cmd, args };\n }\n\n /**\n * Show help information\n */\n async showHelp(args) {\n if (args.length > 0) {\n const command = args[0].toLowerCase();\n if (this.allCommands[command]) {\n this.showCommandHelp(command);\n } else {\n this.terminal.writeError(`Unknown command: ${command}`);\n }\n return;\n }\n\n this.terminal.writeInfo('Claude Flow Console Commands:');\n this.terminal.writeLine('');\n\n this.terminal.writeInfo('Built-in Commands:');\n Object.keys(this.builtinCommands).forEach((cmd) => {\n this.terminal.writeLine(` ${cmd.padEnd(12)} - ${this.getCommandDescription(cmd)}`);\n });\n\n this.terminal.writeLine('');\n this.terminal.writeInfo('Claude Flow Commands:');\n Object.keys(this.claudeFlowCommands).forEach((cmd) => {\n this.terminal.writeLine(` ${cmd.padEnd(12)} - ${this.getCommandDescription(cmd)}`);\n });\n\n this.terminal.writeLine('');\n this.terminal.writeInfo('Tool Commands (from tools list):');\n this.terminal.writeLine(' system/health - Get system health status');\n this.terminal.writeLine(\n ' memory/manage - Manage memory (list, store <key> <value>, retrieve <key>)',\n );\n this.terminal.writeLine(\n ' agents/manage - Manage agents (list, create <type>, status <id>)',\n );\n this.terminal.writeLine(\n ' swarm/orchestrate - Swarm operations (status, create, start, stop)',\n );\n this.terminal.writeLine(\n ' sparc/execute - Execute SPARC modes (coder, architect, etc.)',\n );\n this.terminal.writeLine(\n ' benchmark/run - Run benchmarks (default, memory, cpu, network)',\n );\n this.terminal.writeLine(' claude-flow/execute - Execute Claude Line truncated
|
||||
@@ -1,410 +0,0 @@
|
||||
import { WebSocketClient } from './websocket-client.js';
|
||||
import { TerminalEmulator } from './terminal-emulator.js';
|
||||
import { CommandHandler } from './command-handler.js';
|
||||
import { SettingsManager } from './settings.js';
|
||||
let ClaudeCodeConsole = class ClaudeCodeConsole {
|
||||
constructor(){
|
||||
this.wsClient = new WebSocketClient();
|
||||
this.terminal = null;
|
||||
this.commandHandler = null;
|
||||
this.settings = new SettingsManager();
|
||||
this.isInitialized = false;
|
||||
this.startTime = Date.now();
|
||||
this.messageCount = 0;
|
||||
this.activeAgents = 0;
|
||||
this.elements = {};
|
||||
this.statusInterval = null;
|
||||
this.uptimeInterval = null;
|
||||
this.setupEventListeners();
|
||||
}
|
||||
async init() {
|
||||
if (this.isInitialized) return;
|
||||
try {
|
||||
this.showLoading('Initializing Claude Code Console...');
|
||||
this.getDOMElements();
|
||||
this.terminal = new TerminalEmulator(this.elements.consoleOutput, this.elements.consoleInput);
|
||||
this.commandHandler = new CommandHandler(this.terminal, this.wsClient);
|
||||
this.settings.init();
|
||||
this.setupComponentInteractions();
|
||||
this.setupUIEventHandlers();
|
||||
this.applyInitialSettings();
|
||||
this.startStatusUpdates();
|
||||
this.hideLoading();
|
||||
this.showWelcomeMessage();
|
||||
if (this.settings.get('autoConnect')) {
|
||||
await this.autoConnect();
|
||||
}
|
||||
this.isInitialized = true;
|
||||
console.log('Claude Code Console initialized successfully');
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize console:', error);
|
||||
this.showError('Failed to initialize console: ' + error.message);
|
||||
}
|
||||
}
|
||||
getDOMElements() {
|
||||
this.elements = {
|
||||
consoleOutput: document.getElementById('consoleOutput'),
|
||||
consoleInput: document.getElementById('consoleInput'),
|
||||
settingsPanel: document.getElementById('settingsPanel'),
|
||||
loadingOverlay: document.getElementById('loadingOverlay'),
|
||||
connectionStatus: document.getElementById('connectionStatus'),
|
||||
statusIndicator: document.getElementById('statusIndicator'),
|
||||
statusText: document.getElementById('statusText'),
|
||||
currentMode: document.getElementById('currentMode'),
|
||||
activeAgents: document.getElementById('activeAgents'),
|
||||
uptime: document.getElementById('uptime'),
|
||||
memoryUsage: document.getElementById('memoryUsage'),
|
||||
messageCount: document.getElementById('messageCount'),
|
||||
timestamp: document.getElementById('timestamp'),
|
||||
clearConsole: document.getElementById('clearConsole'),
|
||||
fullscreenToggle: document.getElementById('fullscreenToggle')
|
||||
};
|
||||
const required = [
|
||||
'consoleOutput',
|
||||
'consoleInput',
|
||||
'loadingOverlay'
|
||||
];
|
||||
for (const elementId of required){
|
||||
if (!this.elements[elementId]) {
|
||||
throw new Error(`Required element not found: ${elementId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
setupComponentInteractions() {
|
||||
this.terminal.on('command', (command)=>{
|
||||
this.commandHandler.processCommand(command);
|
||||
});
|
||||
this.terminal.on('interrupt', ()=>{
|
||||
this.handleInterrupt();
|
||||
});
|
||||
this.wsClient.on('connected', ()=>{
|
||||
this.updateConnectionStatus(true, false);
|
||||
this.terminal.writeSuccess('Connected to Claude Code server');
|
||||
this.terminal.setPrompt('claude-flow>');
|
||||
});
|
||||
this.wsClient.on('disconnected', (info)=>{
|
||||
this.updateConnectionStatus(false, false);
|
||||
this.terminal.writeWarning('Disconnected from server');
|
||||
this.terminal.setPrompt('offline>');
|
||||
if (info && info.code !== 1000) {
|
||||
this.terminal.writeError(`Connection lost: ${info.reason || 'Unknown reason'}`);
|
||||
}
|
||||
});
|
||||
this.wsClient.on('reconnecting', (info)=>{
|
||||
this.updateConnectionStatus(false, true);
|
||||
this.terminal.writeInfo(`Reconnecting... (${info.attempt}/${this.wsClient.maxReconnectAttempts})`);
|
||||
});
|
||||
this.wsClient.on('error', (error)=>{
|
||||
this.terminal.writeError(`WebSocket error: ${error.message || 'Unknown error'}`);
|
||||
});
|
||||
this.wsClient.on('message_received', (message)=>{
|
||||
this.messageCount++;
|
||||
this.handleIncomingMessage(message);
|
||||
});
|
||||
this.wsClient.on('notification', (notification)=>{
|
||||
this.handleNotification(notification);
|
||||
});
|
||||
this.settings.on('connect_requested', async (config)=>{
|
||||
await this.connect(config.url, config.token);
|
||||
});
|
||||
this.settings.on('disconnect_requested', ()=>{
|
||||
this.disconnect();
|
||||
});
|
||||
this.settings.on('max_lines_changed', (maxLines)=>{
|
||||
this.terminal.setMaxLines(maxLines);
|
||||
});
|
||||
this.settings.on('setting_changed', ({ key, value })=>{
|
||||
this.handleSettingChange(key, value);
|
||||
});
|
||||
}
|
||||
setupUIEventHandlers() {
|
||||
if (this.elements.clearConsole) {
|
||||
this.elements.clearConsole.addEventListener('click', ()=>{
|
||||
this.terminal.clear();
|
||||
});
|
||||
}
|
||||
if (this.elements.fullscreenToggle) {
|
||||
this.elements.fullscreenToggle.addEventListener('click', ()=>{
|
||||
this.toggleFullscreen();
|
||||
});
|
||||
}
|
||||
if (this.elements.consoleOutput) {
|
||||
this.elements.consoleOutput.addEventListener('click', ()=>{
|
||||
this.terminal.focus();
|
||||
});
|
||||
}
|
||||
window.addEventListener('focus', ()=>{
|
||||
this.terminal.focus();
|
||||
});
|
||||
document.addEventListener('visibilitychange', ()=>{
|
||||
if (!document.hidden) {
|
||||
this.updateTimestamp();
|
||||
}
|
||||
});
|
||||
window.addEventListener('beforeunload', ()=>{
|
||||
this.cleanup();
|
||||
});
|
||||
}
|
||||
applyInitialSettings() {
|
||||
const maxLines = this.settings.get('maxLines');
|
||||
if (maxLines) {
|
||||
this.terminal.setMaxLines(maxLines);
|
||||
}
|
||||
this.settings.updateConnectionStatus(this.wsClient.getStatus());
|
||||
}
|
||||
showWelcomeMessage() {
|
||||
this.terminal.showWelcomeMessage();
|
||||
this.terminal.writeInfo('Console ready. Type "help" for available commands.');
|
||||
const config = this.settings.getConnectionConfig();
|
||||
if (config.url && !config.autoConnect) {
|
||||
this.terminal.writeInfo(`Use "connect" to connect to ${config.url}`);
|
||||
}
|
||||
}
|
||||
async autoConnect() {
|
||||
const config = this.settings.getConnectionConfig();
|
||||
if (config.url) {
|
||||
this.terminal.writeInfo(`Auto-connecting to ${config.url}...`);
|
||||
await this.connect(config.url, config.token);
|
||||
}
|
||||
}
|
||||
async connect(url, token = '') {
|
||||
try {
|
||||
this.updateConnectionStatus(false, true);
|
||||
await this.wsClient.connect(url, token);
|
||||
await this.wsClient.initializeSession();
|
||||
this.settings.set('serverUrl', url);
|
||||
if (token) {
|
||||
this.settings.set('authToken', token);
|
||||
}
|
||||
} catch (error) {
|
||||
this.updateConnectionStatus(false, false);
|
||||
this.terminal.writeError(`Connection failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
disconnect() {
|
||||
this.wsClient.disconnect();
|
||||
this.updateConnectionStatus(false, false);
|
||||
}
|
||||
updateConnectionStatus(connected, connecting) {
|
||||
const status = this.wsClient.getStatus();
|
||||
if (this.elements.statusIndicator) {
|
||||
this.elements.statusIndicator.className = 'status-indicator ' + (connected ? 'connected' : connecting ? 'connecting' : '');
|
||||
}
|
||||
if (this.elements.statusText) {
|
||||
this.elements.statusText.textContent = connected ? 'Connected' : connecting ? 'Connecting...' : 'Disconnected';
|
||||
}
|
||||
this.settings.updateConnectionStatus(status);
|
||||
}
|
||||
handleIncomingMessage(message) {
|
||||
if (message.method === 'output/stream') {
|
||||
this.handleStreamingOutput(message.params);
|
||||
}
|
||||
if (message.method && message.method.startsWith('claude-flow/')) {
|
||||
this.handleClaudeFlowNotification(message);
|
||||
}
|
||||
}
|
||||
handleNotification(notification) {
|
||||
const { method, params } = notification;
|
||||
switch(method){
|
||||
case 'agent/status':
|
||||
this.handleAgentStatus(params);
|
||||
break;
|
||||
case 'swarm/update':
|
||||
this.handleSwarmUpdate(params);
|
||||
break;
|
||||
case 'memory/update':
|
||||
this.handleMemoryUpdate(params);
|
||||
break;
|
||||
case 'log/message':
|
||||
this.handleLogMessage(params);
|
||||
break;
|
||||
case 'connection/established':
|
||||
this.handleConnectionEstablished(params);
|
||||
break;
|
||||
default:
|
||||
console.log('Unhandled notification:', method, params);
|
||||
}
|
||||
}
|
||||
handleStreamingOutput(params) {
|
||||
if (params && params.content) {
|
||||
const type = params.type || 'output';
|
||||
if (params.streaming) {
|
||||
this.terminal.streamText(params.content, 10);
|
||||
} else {
|
||||
this.terminal.write(params.content, type);
|
||||
}
|
||||
}
|
||||
}
|
||||
handleClaudeFlowNotification(message) {
|
||||
const { method, params } = message;
|
||||
switch(method){
|
||||
case 'claude-flow/started':
|
||||
this.terminal.writeSuccess(`Claude Flow started in ${params.mode} mode`);
|
||||
break;
|
||||
case 'claude-flow/stopped':
|
||||
this.terminal.writeInfo('Claude Flow stopped');
|
||||
break;
|
||||
case 'claude-flow/error':
|
||||
this.terminal.writeError(`Claude Flow error: ${params.message}`);
|
||||
break;
|
||||
default:
|
||||
this.terminal.writeInfo(`Claude Flow: ${method} - ${JSON.stringify(params)}`);
|
||||
}
|
||||
}
|
||||
handleAgentStatus(params) {
|
||||
if (params.active !== undefined) {
|
||||
this.activeAgents = params.active;
|
||||
}
|
||||
if (params.message) {
|
||||
this.terminal.writeInfo(`Agent: ${params.message}`);
|
||||
}
|
||||
}
|
||||
handleSwarmUpdate(params) {
|
||||
if (params.message) {
|
||||
this.terminal.writeInfo(`Swarm: ${params.message}`);
|
||||
}
|
||||
}
|
||||
handleMemoryUpdate(params) {
|
||||
if (params.message) {
|
||||
this.terminal.writeInfo(`Memory: ${params.message}`);
|
||||
}
|
||||
}
|
||||
handleLogMessage(params) {
|
||||
if (params.level && params.message) {
|
||||
const type = params.level === 'error' ? 'error' : params.level === 'warn' ? 'warning' : 'info';
|
||||
this.terminal.write(`[${params.level.toUpperCase()}] ${params.message}`, type);
|
||||
}
|
||||
}
|
||||
handleConnectionEstablished(params) {
|
||||
console.log('Connection established:', params);
|
||||
}
|
||||
handleInterrupt() {
|
||||
this.terminal.writeWarning('Interrupt signal sent');
|
||||
}
|
||||
handleSettingChange(key, value) {
|
||||
switch(key){
|
||||
case 'theme':
|
||||
document.documentElement.setAttribute('data-theme', value);
|
||||
break;
|
||||
case 'fontSize':
|
||||
document.documentElement.style.setProperty('--font-size-base', `${value}px`);
|
||||
break;
|
||||
case 'lineHeight':
|
||||
document.documentElement.style.setProperty('--line-height', value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
startStatusUpdates() {
|
||||
this.statusInterval = setInterval(()=>{
|
||||
this.updateStatus();
|
||||
}, 5000);
|
||||
this.uptimeInterval = setInterval(()=>{
|
||||
this.updateUptime();
|
||||
this.updateTimestamp();
|
||||
}, 1000);
|
||||
this.updateStatus();
|
||||
this.updateUptime();
|
||||
this.updateTimestamp();
|
||||
}
|
||||
updateStatus() {
|
||||
if (this.elements.activeAgents) {
|
||||
this.elements.activeAgents.textContent = `Agents: ${this.activeAgents}`;
|
||||
}
|
||||
if (this.elements.messageCount) {
|
||||
this.elements.messageCount.textContent = `Messages: ${this.messageCount}`;
|
||||
}
|
||||
if (this.elements.memoryUsage && performance.memory) {
|
||||
const used = Math.round(performance.memory.usedJSHeapSize / 1024 / 1024);
|
||||
this.elements.memoryUsage.textContent = `Memory: ${used}MB`;
|
||||
}
|
||||
}
|
||||
updateUptime() {
|
||||
if (this.elements.uptime) {
|
||||
const uptime = Date.now() - this.startTime;
|
||||
const hours = Math.floor(uptime / (1000 * 60 * 60));
|
||||
const minutes = Math.floor(uptime % (1000 * 60 * 60) / (1000 * 60));
|
||||
const seconds = Math.floor(uptime % (1000 * 60) / 1000);
|
||||
this.elements.uptime.textContent = `Uptime: ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
||||
}
|
||||
}
|
||||
updateTimestamp() {
|
||||
if (this.elements.timestamp) {
|
||||
this.elements.timestamp.textContent = new Date().toLocaleTimeString();
|
||||
}
|
||||
}
|
||||
toggleFullscreen() {
|
||||
if (!document.fullscreenElement) {
|
||||
document.documentElement.requestFullscreen().catch((err)=>{
|
||||
console.error('Error attempting to enable fullscreen:', err);
|
||||
});
|
||||
} else {
|
||||
document.exitFullscreen();
|
||||
}
|
||||
}
|
||||
showLoading(message = 'Loading...') {
|
||||
if (this.elements.loadingOverlay) {
|
||||
const loadingText = this.elements.loadingOverlay.querySelector('.loading-text');
|
||||
if (loadingText) {
|
||||
loadingText.textContent = message;
|
||||
}
|
||||
this.elements.loadingOverlay.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
hideLoading() {
|
||||
if (this.elements.loadingOverlay) {
|
||||
this.elements.loadingOverlay.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
showError(message) {
|
||||
this.hideLoading();
|
||||
if (this.terminal) {
|
||||
this.terminal.writeError(message);
|
||||
} else {
|
||||
console.error(message);
|
||||
alert(message);
|
||||
}
|
||||
}
|
||||
setupEventListeners() {
|
||||
window.addEventListener('unhandledrejection', (event)=>{
|
||||
console.error('Unhandled promise rejection:', event.reason);
|
||||
if (this.terminal) {
|
||||
this.terminal.writeError(`Unhandled error: ${event.reason.message || event.reason}`);
|
||||
}
|
||||
});
|
||||
window.addEventListener('error', (event)=>{
|
||||
console.error('Global error:', event.error);
|
||||
if (this.terminal) {
|
||||
this.terminal.writeError(`Application error: ${event.error.message || event.error}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
cleanup() {
|
||||
if (this.statusInterval) {
|
||||
clearInterval(this.statusInterval);
|
||||
}
|
||||
if (this.uptimeInterval) {
|
||||
clearInterval(this.uptimeInterval);
|
||||
}
|
||||
if (this.wsClient) {
|
||||
this.wsClient.disconnect();
|
||||
}
|
||||
}
|
||||
getStats() {
|
||||
return {
|
||||
initialized: this.isInitialized,
|
||||
uptime: Date.now() - this.startTime,
|
||||
messageCount: this.messageCount,
|
||||
activeAgents: this.activeAgents,
|
||||
connection: this.wsClient.getStatus(),
|
||||
terminal: this.terminal ? this.terminal.getStats() : null
|
||||
};
|
||||
}
|
||||
};
|
||||
document.addEventListener('DOMContentLoaded', async ()=>{
|
||||
const console1 = new ClaudeCodeConsole();
|
||||
window.claudeConsole = console1;
|
||||
await console1.init();
|
||||
});
|
||||
export { ClaudeCodeConsole };
|
||||
|
||||
//# sourceMappingURL=console.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/console.js"],"sourcesContent":["/**\n * Main Console Application\n * Coordinates all components of the Claude Code Console\n */\n\nimport { WebSocketClient } from './websocket-client.js';\nimport { TerminalEmulator } from './terminal-emulator.js';\nimport { CommandHandler } from './command-handler.js';\nimport { SettingsManager } from './settings.js';\n\nclass ClaudeCodeConsole {\n constructor() {\n // Initialize components\n this.wsClient = new WebSocketClient();\n this.terminal = null;\n this.commandHandler = null;\n this.settings = new SettingsManager();\n\n // State management\n this.isInitialized = false;\n this.startTime = Date.now();\n this.messageCount = 0;\n this.activeAgents = 0;\n\n // DOM elements\n this.elements = {};\n\n // Status update intervals\n this.statusInterval = null;\n this.uptimeInterval = null;\n\n this.setupEventListeners();\n }\n\n /**\n * Initialize the console application\n */\n async init() {\n if (this.isInitialized) return;\n\n try {\n // Show loading overlay\n this.showLoading('Initializing Claude Code Console...');\n\n // Get DOM elements\n this.getDOMElements();\n\n // Initialize terminal emulator\n this.terminal = new TerminalEmulator(this.elements.consoleOutput, this.elements.consoleInput);\n\n // Initialize command handler\n this.commandHandler = new CommandHandler(this.terminal, this.wsClient);\n\n // Initialize settings\n this.settings.init();\n\n // Setup component interactions\n this.setupComponentInteractions();\n\n // Setup UI event handlers\n this.setupUIEventHandlers();\n\n // Apply initial settings\n this.applyInitialSettings();\n\n // Start status updates\n this.startStatusUpdates();\n\n // Hide loading overlay\n this.hideLoading();\n\n // Show welcome message\n this.showWelcomeMessage();\n\n // Auto-connect if enabled\n if (this.settings.get('autoConnect')) {\n await this.autoConnect();\n }\n\n this.isInitialized = true;\n console.log('Claude Code Console initialized successfully');\n } catch (error) {\n console.error('Failed to initialize console:', error);\n this.showError('Failed to initialize console: ' + error.message);\n }\n }\n\n /**\n * Get DOM elements\n */\n getDOMElements() {\n this.elements = {\n consoleOutput: document.getElementById('consoleOutput'),\n consoleInput: document.getElementById('consoleInput'),\n settingsPanel: document.getElementById('settingsPanel'),\n loadingOverlay: document.getElementById('loadingOverlay'),\n connectionStatus: document.getElementById('connectionStatus'),\n statusIndicator: document.getElementById('statusIndicator'),\n statusText: document.getElementById('statusText'),\n currentMode: document.getElementById('currentMode'),\n activeAgents: document.getElementById('activeAgents'),\n uptime: document.getElementById('uptime'),\n memoryUsage: document.getElementById('memoryUsage'),\n messageCount: document.getElementById('messageCount'),\n timestamp: document.getElementById('timestamp'),\n clearConsole: document.getElementById('clearConsole'),\n fullscreenToggle: document.getElementById('fullscreenToggle'),\n };\n\n // Validate required elements\n const required = ['consoleOutput', 'consoleInput', 'loadingOverlay'];\n for (const elementId of required) {\n if (!this.elements[elementId]) {\n throw new Error(`Required element not found: ${elementId}`);\n }\n }\n }\n\n /**\n * Setup component interactions\n */\n setupComponentInteractions() {\n // Terminal -> Command Handler\n this.terminal.on('command', (command) => {\n this.commandHandler.processCommand(command);\n });\n\n this.terminal.on('interrupt', () => {\n this.handleInterrupt();\n });\n\n // WebSocket -> Terminal\n this.wsClient.on('connected', () => {\n this.updateConnectionStatus(true, false);\n this.terminal.writeSuccess('Connected to Claude Code server');\n this.terminal.setPrompt('claude-flow>');\n });\n\n this.wsClient.on('disconnected', (info) => {\n this.updateConnectionStatus(false, false);\n this.terminal.writeWarning('Disconnected from server');\n this.terminal.setPrompt('offline>');\n\n if (info && info.code !== 1000) {\n this.terminal.writeError(`Connection lost: ${info.reason || 'Unknown reason'}`);\n }\n });\n\n this.wsClient.on('reconnecting', (info) => {\n this.updateConnectionStatus(false, true);\n this.terminal.writeInfo(\n `Reconnecting... (${info.attempt}/${this.wsClient.maxReconnectAttempts})`,\n );\n });\n\n this.wsClient.on('error', (error) => {\n this.terminal.writeError(`WebSocket error: ${error.message || 'Unknown errorLine truncated
|
||||
@@ -1,891 +0,0 @@
|
||||
let DAATools = class DAATools {
|
||||
constructor(){
|
||||
this.agents = new Map();
|
||||
this.resources = new Map();
|
||||
this.communications = new Map();
|
||||
this.consensus = new Map();
|
||||
this.isInitialized = false;
|
||||
this.currentTab = 'agents';
|
||||
this.metrics = {
|
||||
totalAgents: 0,
|
||||
activeAgents: 0,
|
||||
resourceUtilization: 0,
|
||||
communicationLatency: 0,
|
||||
consensusTime: 0,
|
||||
faultCount: 0
|
||||
};
|
||||
this.init();
|
||||
}
|
||||
init() {
|
||||
if (this.isInitialized) return;
|
||||
this.createDAAPanel();
|
||||
this.setupEventListeners();
|
||||
this.initializeMonitoring();
|
||||
this.isInitialized = true;
|
||||
console.log('DAA Tools initialized');
|
||||
}
|
||||
daa_agent_create(config) {
|
||||
const agentId = this.generateAgentId();
|
||||
const agent = {
|
||||
id: agentId,
|
||||
type: config.type || 'generic',
|
||||
capabilities: config.capabilities || [],
|
||||
resources: config.resources || {},
|
||||
status: 'initializing',
|
||||
created: Date.now(),
|
||||
lastActivity: Date.now(),
|
||||
tasks: [],
|
||||
metadata: config.metadata || {}
|
||||
};
|
||||
this.agents.set(agentId, agent);
|
||||
this.metrics.totalAgents++;
|
||||
this.metrics.activeAgents++;
|
||||
this.initializeAgent(agent);
|
||||
this.updateAgentsList();
|
||||
this.updateMetrics();
|
||||
return {
|
||||
success: true,
|
||||
agentId: agentId,
|
||||
agent: agent
|
||||
};
|
||||
}
|
||||
daa_capability_match(requirements) {
|
||||
const matches = [];
|
||||
for (const [agentId, agent] of this.agents){
|
||||
if (agent.status !== 'active') continue;
|
||||
const score = this.calculateCapabilityScore(agent.capabilities, requirements);
|
||||
if (score > 0) {
|
||||
matches.push({
|
||||
agentId,
|
||||
agent,
|
||||
score,
|
||||
availableCapabilities: agent.capabilities.filter((cap)=>requirements.some((req)=>this.matchCapability(cap, req)))
|
||||
});
|
||||
}
|
||||
}
|
||||
matches.sort((a, b)=>b.score - a.score);
|
||||
this.updateCapabilityMatches(matches);
|
||||
return {
|
||||
success: true,
|
||||
matches: matches,
|
||||
totalCandidates: matches.length
|
||||
};
|
||||
}
|
||||
daa_resource_alloc(allocation) {
|
||||
const resourceId = this.generateResourceId();
|
||||
const resource = {
|
||||
id: resourceId,
|
||||
type: allocation.type,
|
||||
capacity: allocation.capacity,
|
||||
allocated: 0,
|
||||
assignments: new Map(),
|
||||
priority: allocation.priority || 'medium',
|
||||
created: Date.now(),
|
||||
metadata: allocation.metadata || {}
|
||||
};
|
||||
this.resources.set(resourceId, resource);
|
||||
const allocationResult = this.allocateResource(resource, allocation);
|
||||
this.updateResourceGraphs();
|
||||
this.updateMetrics();
|
||||
return {
|
||||
success: allocationResult.success,
|
||||
resourceId: resourceId,
|
||||
allocation: allocationResult,
|
||||
utilization: this.calculateResourceUtilization()
|
||||
};
|
||||
}
|
||||
daa_lifecycle_manage(agentId, action, params = {}) {
|
||||
const agent = this.agents.get(agentId);
|
||||
if (!agent) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Agent not found'
|
||||
};
|
||||
}
|
||||
let result;
|
||||
switch(action){
|
||||
case 'start':
|
||||
result = this.startAgent(agent, params);
|
||||
break;
|
||||
case 'pause':
|
||||
result = this.pauseAgent(agent, params);
|
||||
break;
|
||||
case 'resume':
|
||||
result = this.resumeAgent(agent, params);
|
||||
break;
|
||||
case 'stop':
|
||||
result = this.stopAgent(agent, params);
|
||||
break;
|
||||
case 'restart':
|
||||
result = this.restartAgent(agent, params);
|
||||
break;
|
||||
case 'destroy':
|
||||
result = this.destroyAgent(agent, params);
|
||||
break;
|
||||
default:
|
||||
return {
|
||||
success: false,
|
||||
error: 'Unknown action'
|
||||
};
|
||||
}
|
||||
this.updateLifecycleVisualization();
|
||||
this.updateMetrics();
|
||||
return result;
|
||||
}
|
||||
daa_communication(fromAgent, toAgent, message, options = {}) {
|
||||
const commId = this.generateCommId();
|
||||
const communication = {
|
||||
id: commId,
|
||||
from: fromAgent,
|
||||
to: toAgent,
|
||||
message: message,
|
||||
timestamp: Date.now(),
|
||||
type: options.type || 'direct',
|
||||
priority: options.priority || 'normal',
|
||||
status: 'pending',
|
||||
latency: 0,
|
||||
metadata: options.metadata || {}
|
||||
};
|
||||
this.communications.set(commId, communication);
|
||||
const result = this.processCommunication(communication);
|
||||
this.updateCommunicationFlow();
|
||||
return {
|
||||
success: result.success,
|
||||
commId: commId,
|
||||
latency: result.latency,
|
||||
status: result.status
|
||||
};
|
||||
}
|
||||
daa_consensus(proposal, agents, options = {}) {
|
||||
const consensusId = this.generateConsensusId();
|
||||
const consensus = {
|
||||
id: consensusId,
|
||||
proposal: proposal,
|
||||
participants: agents,
|
||||
votes: new Map(),
|
||||
status: 'voting',
|
||||
algorithm: options.algorithm || 'majority',
|
||||
threshold: options.threshold || 0.5,
|
||||
timeout: options.timeout || 30000,
|
||||
started: Date.now(),
|
||||
completed: null,
|
||||
result: null
|
||||
};
|
||||
this.consensus.set(consensusId, consensus);
|
||||
const result = this.startConsensusProcess(consensus);
|
||||
this.updateConsensusInterface();
|
||||
return {
|
||||
success: result.success,
|
||||
consensusId: consensusId,
|
||||
expectedCompletion: result.expectedCompletion
|
||||
};
|
||||
}
|
||||
daa_fault_tolerance(faultType, affectedAgents, recoveryOptions = {}) {
|
||||
const faultId = this.generateFaultId();
|
||||
const fault = {
|
||||
id: faultId,
|
||||
type: faultType,
|
||||
affected: affectedAgents,
|
||||
detected: Date.now(),
|
||||
severity: recoveryOptions.severity || 'medium',
|
||||
status: 'detected',
|
||||
recoveryPlan: null,
|
||||
recovered: null
|
||||
};
|
||||
this.metrics.faultCount++;
|
||||
const recoveryPlan = this.createRecoveryPlan(fault, recoveryOptions);
|
||||
fault.recoveryPlan = recoveryPlan;
|
||||
const recoveryResult = this.executeRecovery(fault);
|
||||
this.updateFaultDashboard();
|
||||
return {
|
||||
success: recoveryResult.success,
|
||||
faultId: faultId,
|
||||
recoveryPlan: recoveryPlan,
|
||||
estimatedRecoveryTime: recoveryResult.estimatedTime
|
||||
};
|
||||
}
|
||||
daa_optimization(target, options = {}) {
|
||||
const optimizationId = this.generateOptimizationId();
|
||||
const optimization = {
|
||||
id: optimizationId,
|
||||
target: target,
|
||||
baseline: this.capturePerformanceBaseline(),
|
||||
options: options,
|
||||
started: Date.now(),
|
||||
status: 'running',
|
||||
improvements: [],
|
||||
completed: null
|
||||
};
|
||||
const result = this.performOptimization(optimization);
|
||||
this.updateOptimizationDashboard();
|
||||
return {
|
||||
success: result.success,
|
||||
optimizationId: optimizationId,
|
||||
improvements: result.improvements,
|
||||
performanceGain: result.performanceGain
|
||||
};
|
||||
}
|
||||
createDAAPanel() {
|
||||
const panel = document.createElement('div');
|
||||
panel.id = 'daa-tools-panel';
|
||||
panel.className = 'daa-panel';
|
||||
panel.innerHTML = `
|
||||
<div class="daa-header">
|
||||
<h3>DAA Control Center</h3>
|
||||
<div class="daa-metrics">
|
||||
<div class="metric">
|
||||
<span class="metric-label">Agents</span>
|
||||
<span class="metric-value" id="daa-agents-count">0</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="metric-label">Resources</span>
|
||||
<span class="metric-value" id="daa-resources-util">0%</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="metric-label">Latency</span>
|
||||
<span class="metric-value" id="daa-latency">0ms</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="metric-label">Faults</span>
|
||||
<span class="metric-value" id="daa-faults">0</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="daa-tabs">
|
||||
<button class="daa-tab active" data-tab="agents">Agents</button>
|
||||
<button class="daa-tab" data-tab="resources">Resources</button>
|
||||
<button class="daa-tab" data-tab="communication">Communication</button>
|
||||
<button class="daa-tab" data-tab="monitoring">Monitoring</button>
|
||||
</div>
|
||||
|
||||
<div class="daa-content">
|
||||
${this.createAgentsTab()}
|
||||
${this.createResourcesTab()}
|
||||
${this.createCommunicationTab()}
|
||||
${this.createMonitoringTab()}
|
||||
</div>
|
||||
`;
|
||||
const consoleContainer = document.querySelector('.console-container') || document.body;
|
||||
consoleContainer.appendChild(panel);
|
||||
}
|
||||
createAgentsTab() {
|
||||
return `
|
||||
<div class="daa-tab-content active" id="daa-agents-tab">
|
||||
<div class="daa-section">
|
||||
<h4>Agent Creation</h4>
|
||||
<div class="daa-form">
|
||||
<select id="daa-agent-type">
|
||||
<option value="researcher">Researcher</option>
|
||||
<option value="coder">Coder</option>
|
||||
<option value="analyst">Analyst</option>
|
||||
<option value="coordinator">Coordinator</option>
|
||||
<option value="tester">Tester</option>
|
||||
</select>
|
||||
<input type="text" id="daa-agent-capabilities" placeholder="Capabilities (comma-separated)">
|
||||
<button id="daa-create-agent">Create Agent</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="daa-section">
|
||||
<h4>Agent Lifecycle</h4>
|
||||
<div id="daa-lifecycle-visualization" class="daa-visualization">
|
||||
<!-- Lifecycle visualization will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="daa-section">
|
||||
<h4>Active Agents</h4>
|
||||
<div id="daa-agents-list" class="daa-agents-grid">
|
||||
<!-- Agents will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
createResourcesTab() {
|
||||
return `
|
||||
<div class="daa-tab-content" id="daa-resources-tab">
|
||||
<div class="daa-section">
|
||||
<h4>Resource Allocation</h4>
|
||||
<div class="daa-form">
|
||||
<select id="daa-resource-type">
|
||||
<option value="cpu">CPU</option>
|
||||
<option value="memory">Memory</option>
|
||||
<option value="storage">Storage</option>
|
||||
<option value="network">Network</option>
|
||||
</select>
|
||||
<input type="number" id="daa-resource-capacity" placeholder="Capacity">
|
||||
<select id="daa-resource-priority">
|
||||
<option value="low">Low</option>
|
||||
<option value="medium">Medium</option>
|
||||
<option value="high">High</option>
|
||||
</select>
|
||||
<button id="daa-allocate-resource">Allocate Resource</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="daa-section">
|
||||
<h4>Resource Graphs</h4>
|
||||
<div id="daa-resource-graphs" class="daa-visualization">
|
||||
<canvas id="daa-resource-chart" width="600" height="300"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="daa-section">
|
||||
<h4>Resource Status</h4>
|
||||
<div id="daa-resource-status" class="daa-status-grid">
|
||||
<!-- Resource status will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
createCommunicationTab() {
|
||||
return `
|
||||
<div class="daa-tab-content" id="daa-communication-tab">
|
||||
<div class="daa-section">
|
||||
<h4>Communication Flow</h4>
|
||||
<div id="daa-communication-flow" class="daa-visualization">
|
||||
<svg id="daa-comm-diagram" width="600" height="400"></svg>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="daa-section">
|
||||
<h4>Consensus Voting</h4>
|
||||
<div class="daa-form">
|
||||
<textarea id="daa-consensus-proposal" placeholder="Enter proposal..."></textarea>
|
||||
<select id="daa-consensus-algorithm">
|
||||
<option value="majority">Majority</option>
|
||||
<option value="unanimous">Unanimous</option>
|
||||
<option value="weighted">Weighted</option>
|
||||
</select>
|
||||
<button id="daa-start-consensus">Start Consensus</button>
|
||||
</div>
|
||||
<div id="daa-consensus-status" class="daa-consensus-grid">
|
||||
<!-- Consensus status will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
createMonitoringTab() {
|
||||
return `
|
||||
<div class="daa-tab-content" id="daa-monitoring-tab">
|
||||
<div class="daa-section">
|
||||
<h4>Real-time Dashboard</h4>
|
||||
<div id="daa-monitoring-dashboard" class="daa-dashboard">
|
||||
<div class="daa-dashboard-grid">
|
||||
<div class="daa-dashboard-item">
|
||||
<h5>Performance Metrics</h5>
|
||||
<canvas id="daa-performance-chart" width="300" height="200"></canvas>
|
||||
</div>
|
||||
<div class="daa-dashboard-item">
|
||||
<h5>System Health</h5>
|
||||
<div id="daa-health-indicators" class="daa-health-grid">
|
||||
<!-- Health indicators will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
<div class="daa-dashboard-item">
|
||||
<h5>Fault Tolerance</h5>
|
||||
<div id="daa-fault-status" class="daa-fault-grid">
|
||||
<!-- Fault status will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
<div class="daa-dashboard-item">
|
||||
<h5>Optimization</h5>
|
||||
<div id="daa-optimization-status" class="daa-optimization-grid">
|
||||
<!-- Optimization status will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
generateAgentId() {
|
||||
return `agent-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
generateResourceId() {
|
||||
return `resource-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
generateCommId() {
|
||||
return `comm-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
generateConsensusId() {
|
||||
return `consensus-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
generateFaultId() {
|
||||
return `fault-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
generateOptimizationId() {
|
||||
return `opt-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
calculateCapabilityScore(agentCapabilities, requirements) {
|
||||
let score = 0;
|
||||
for (const requirement of requirements){
|
||||
for (const capability of agentCapabilities){
|
||||
if (this.matchCapability(capability, requirement)) {
|
||||
score += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return score;
|
||||
}
|
||||
matchCapability(capability, requirement) {
|
||||
return capability.toLowerCase().includes(requirement.toLowerCase());
|
||||
}
|
||||
calculateResourceUtilization() {
|
||||
let totalCapacity = 0;
|
||||
let totalAllocated = 0;
|
||||
for (const [_, resource] of this.resources){
|
||||
totalCapacity += resource.capacity;
|
||||
totalAllocated += resource.allocated;
|
||||
}
|
||||
return totalCapacity > 0 ? Math.round(totalAllocated / totalCapacity * 100) : 0;
|
||||
}
|
||||
initializeAgent(agent) {
|
||||
agent.status = 'active';
|
||||
agent.lastActivity = Date.now();
|
||||
}
|
||||
startAgent(agent, params) {
|
||||
agent.status = 'active';
|
||||
agent.lastActivity = Date.now();
|
||||
return {
|
||||
success: true,
|
||||
status: 'active'
|
||||
};
|
||||
}
|
||||
pauseAgent(agent, params) {
|
||||
agent.status = 'paused';
|
||||
return {
|
||||
success: true,
|
||||
status: 'paused'
|
||||
};
|
||||
}
|
||||
resumeAgent(agent, params) {
|
||||
agent.status = 'active';
|
||||
agent.lastActivity = Date.now();
|
||||
return {
|
||||
success: true,
|
||||
status: 'active'
|
||||
};
|
||||
}
|
||||
stopAgent(agent, params) {
|
||||
agent.status = 'stopped';
|
||||
this.metrics.activeAgents--;
|
||||
return {
|
||||
success: true,
|
||||
status: 'stopped'
|
||||
};
|
||||
}
|
||||
restartAgent(agent, params) {
|
||||
agent.status = 'active';
|
||||
agent.lastActivity = Date.now();
|
||||
return {
|
||||
success: true,
|
||||
status: 'active'
|
||||
};
|
||||
}
|
||||
destroyAgent(agent, params) {
|
||||
this.agents.delete(agent.id);
|
||||
this.metrics.totalAgents--;
|
||||
this.metrics.activeAgents--;
|
||||
return {
|
||||
success: true,
|
||||
status: 'destroyed'
|
||||
};
|
||||
}
|
||||
allocateResource(resource, allocation) {
|
||||
const requested = allocation.amount || 0;
|
||||
const available = resource.capacity - resource.allocated;
|
||||
if (requested <= available) {
|
||||
resource.allocated += requested;
|
||||
return {
|
||||
success: true,
|
||||
allocated: requested,
|
||||
remaining: available - requested
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Insufficient resources',
|
||||
available: available
|
||||
};
|
||||
}
|
||||
}
|
||||
processCommunication(communication) {
|
||||
const latency = Math.random() * 100;
|
||||
communication.latency = latency;
|
||||
communication.status = 'completed';
|
||||
this.metrics.communicationLatency = (this.metrics.communicationLatency + latency) / 2;
|
||||
return {
|
||||
success: true,
|
||||
latency: latency,
|
||||
status: 'completed'
|
||||
};
|
||||
}
|
||||
startConsensusProcess(consensus) {
|
||||
const expectedTime = consensus.timeout || 30000;
|
||||
setTimeout(()=>{
|
||||
this.completeConsensus(consensus);
|
||||
}, expectedTime);
|
||||
return {
|
||||
success: true,
|
||||
expectedCompletion: Date.now() + expectedTime
|
||||
};
|
||||
}
|
||||
completeConsensus(consensus) {
|
||||
consensus.status = 'completed';
|
||||
consensus.completed = Date.now();
|
||||
consensus.result = 'approved';
|
||||
this.metrics.consensusTime = consensus.completed - consensus.started;
|
||||
this.updateConsensusInterface();
|
||||
}
|
||||
createRecoveryPlan(fault, options) {
|
||||
return {
|
||||
steps: [
|
||||
'Isolate affected agents',
|
||||
'Backup current state',
|
||||
'Restart affected components',
|
||||
'Verify system integrity',
|
||||
'Resume normal operations'
|
||||
],
|
||||
estimatedTime: 60000,
|
||||
priority: fault.severity
|
||||
};
|
||||
}
|
||||
executeRecovery(fault) {
|
||||
fault.status = 'recovering';
|
||||
setTimeout(()=>{
|
||||
fault.status = 'recovered';
|
||||
fault.recovered = Date.now();
|
||||
this.updateFaultDashboard();
|
||||
}, fault.recoveryPlan.estimatedTime);
|
||||
return {
|
||||
success: true,
|
||||
estimatedTime: fault.recoveryPlan.estimatedTime
|
||||
};
|
||||
}
|
||||
capturePerformanceBaseline() {
|
||||
return {
|
||||
timestamp: Date.now(),
|
||||
metrics: {
|
||||
...this.metrics
|
||||
},
|
||||
agentCount: this.agents.size,
|
||||
resourceCount: this.resources.size
|
||||
};
|
||||
}
|
||||
performOptimization(optimization) {
|
||||
const improvements = [
|
||||
{
|
||||
type: 'agent_efficiency',
|
||||
improvement: 15
|
||||
},
|
||||
{
|
||||
type: 'resource_allocation',
|
||||
improvement: 12
|
||||
},
|
||||
{
|
||||
type: 'communication_latency',
|
||||
improvement: 8
|
||||
}
|
||||
];
|
||||
optimization.improvements = improvements;
|
||||
optimization.status = 'completed';
|
||||
optimization.completed = Date.now();
|
||||
const totalGain = improvements.reduce((sum, imp)=>sum + imp.improvement, 0) / improvements.length;
|
||||
return {
|
||||
success: true,
|
||||
improvements: improvements,
|
||||
performanceGain: totalGain
|
||||
};
|
||||
}
|
||||
updateAgentsList() {
|
||||
const agentsList = document.getElementById('daa-agents-list');
|
||||
if (!agentsList) return;
|
||||
agentsList.innerHTML = '';
|
||||
for (const [agentId, agent] of this.agents){
|
||||
const agentElement = document.createElement('div');
|
||||
agentElement.className = 'daa-agent-card';
|
||||
agentElement.innerHTML = `
|
||||
<div class="agent-header">
|
||||
<span class="agent-id">${agentId}</span>
|
||||
<span class="agent-status status-${agent.status}">${agent.status}</span>
|
||||
</div>
|
||||
<div class="agent-details">
|
||||
<div class="agent-type">${agent.type}</div>
|
||||
<div class="agent-capabilities">${agent.capabilities.join(', ')}</div>
|
||||
</div>
|
||||
<div class="agent-actions">
|
||||
<button onclick="daaTools.daa_lifecycle_manage('${agentId}', 'pause')">Pause</button>
|
||||
<button onclick="daaTools.daa_lifecycle_manage('${agentId}', 'stop')">Stop</button>
|
||||
<button onclick="daaTools.daa_lifecycle_manage('${agentId}', 'destroy')">Destroy</button>
|
||||
</div>
|
||||
`;
|
||||
agentsList.appendChild(agentElement);
|
||||
}
|
||||
}
|
||||
updateMetrics() {
|
||||
const elements = {
|
||||
'daa-agents-count': this.metrics.activeAgents,
|
||||
'daa-resources-util': `${this.metrics.resourceUtilization}%`,
|
||||
'daa-latency': `${Math.round(this.metrics.communicationLatency)}ms`,
|
||||
'daa-faults': this.metrics.faultCount
|
||||
};
|
||||
for (const [id, value] of Object.entries(elements)){
|
||||
const element = document.getElementById(id);
|
||||
if (element) {
|
||||
element.textContent = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
updateCapabilityMatches(matches) {
|
||||
console.log('Capability matches:', matches);
|
||||
}
|
||||
updateResourceGraphs() {
|
||||
const canvas = document.getElementById('daa-resource-chart');
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
const resources = Array.from(this.resources.values());
|
||||
const barWidth = canvas.width / Math.max(resources.length, 1);
|
||||
resources.forEach((resource, index)=>{
|
||||
const utilization = resource.capacity > 0 ? resource.allocated / resource.capacity : 0;
|
||||
const barHeight = utilization * canvas.height;
|
||||
ctx.fillStyle = utilization > 0.8 ? '#ff4444' : utilization > 0.5 ? '#ffaa00' : '#44ff44';
|
||||
ctx.fillRect(index * barWidth, canvas.height - barHeight, barWidth - 2, barHeight);
|
||||
ctx.fillStyle = '#000';
|
||||
ctx.font = '12px Arial';
|
||||
ctx.fillText(resource.type, index * barWidth + 5, canvas.height - 5);
|
||||
});
|
||||
}
|
||||
updateLifecycleVisualization() {
|
||||
const visualization = document.getElementById('daa-lifecycle-visualization');
|
||||
if (!visualization) return;
|
||||
const statusCounts = {};
|
||||
for (const [_, agent] of this.agents){
|
||||
statusCounts[agent.status] = (statusCounts[agent.status] || 0) + 1;
|
||||
}
|
||||
visualization.innerHTML = Object.entries(statusCounts).map(([status, count])=>`<div class="lifecycle-item">
|
||||
<span class="status-badge status-${status}">${status}</span>
|
||||
<span class="status-count">${count}</span>
|
||||
</div>`).join('');
|
||||
}
|
||||
updateCommunicationFlow() {
|
||||
const svg = document.getElementById('daa-comm-diagram');
|
||||
if (!svg) return;
|
||||
svg.innerHTML = '';
|
||||
const agents = Array.from(this.agents.values());
|
||||
const centerX = 300;
|
||||
const centerY = 200;
|
||||
const radius = 150;
|
||||
agents.forEach((agent, index)=>{
|
||||
const angle = index * 2 * Math.PI / agents.length;
|
||||
const x = centerX + radius * Math.cos(angle);
|
||||
const y = centerY + radius * Math.sin(angle);
|
||||
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
|
||||
circle.setAttribute('cx', x);
|
||||
circle.setAttribute('cy', y);
|
||||
circle.setAttribute('r', 20);
|
||||
circle.setAttribute('fill', '#4CAF50');
|
||||
circle.setAttribute('stroke', '#333');
|
||||
circle.setAttribute('stroke-width', '2');
|
||||
svg.appendChild(circle);
|
||||
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
|
||||
text.setAttribute('x', x);
|
||||
text.setAttribute('y', y + 5);
|
||||
text.setAttribute('text-anchor', 'middle');
|
||||
text.setAttribute('font-size', '12');
|
||||
text.setAttribute('fill', '#fff');
|
||||
text.textContent = agent.id.split('-')[0];
|
||||
svg.appendChild(text);
|
||||
});
|
||||
}
|
||||
updateConsensusInterface() {
|
||||
const consensusStatus = document.getElementById('daa-consensus-status');
|
||||
if (!consensusStatus) return;
|
||||
consensusStatus.innerHTML = Array.from(this.consensus.values()).map((consensus)=>`<div class="consensus-item">
|
||||
<div class="consensus-proposal">${consensus.proposal}</div>
|
||||
<div class="consensus-status">${consensus.status}</div>
|
||||
<div class="consensus-progress">
|
||||
<div class="progress-bar" style="width: ${consensus.status === 'completed' ? '100%' : '50%'}"></div>
|
||||
</div>
|
||||
</div>`).join('');
|
||||
}
|
||||
updateFaultDashboard() {
|
||||
const faultStatus = document.getElementById('daa-fault-status');
|
||||
if (!faultStatus) return;
|
||||
faultStatus.innerHTML = `
|
||||
<div class="fault-item">
|
||||
<span class="fault-label">Total Faults</span>
|
||||
<span class="fault-value">${this.metrics.faultCount}</span>
|
||||
</div>
|
||||
<div class="fault-item">
|
||||
<span class="fault-label">Recovery Rate</span>
|
||||
<span class="fault-value">95%</span>
|
||||
</div>
|
||||
<div class="fault-item">
|
||||
<span class="fault-label">MTTR</span>
|
||||
<span class="fault-value">2.3min</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
updateOptimizationDashboard() {
|
||||
const optimizationStatus = document.getElementById('daa-optimization-status');
|
||||
if (!optimizationStatus) return;
|
||||
optimizationStatus.innerHTML = `
|
||||
<div class="optimization-item">
|
||||
<span class="opt-label">Performance Gain</span>
|
||||
<span class="opt-value">+15%</span>
|
||||
</div>
|
||||
<div class="optimization-item">
|
||||
<span class="opt-label">Resource Efficiency</span>
|
||||
<span class="opt-value">+12%</span>
|
||||
</div>
|
||||
<div class="optimization-item">
|
||||
<span class="opt-label">Latency Reduction</span>
|
||||
<span class="opt-value">-8%</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
setupEventListeners() {
|
||||
document.addEventListener('click', (e)=>{
|
||||
if (e.target.classList.contains('daa-tab')) {
|
||||
this.switchTab(e.target.dataset.tab);
|
||||
}
|
||||
});
|
||||
document.addEventListener('click', (e)=>{
|
||||
if (e.target.id === 'daa-create-agent') {
|
||||
this.handleCreateAgent();
|
||||
}
|
||||
});
|
||||
document.addEventListener('click', (e)=>{
|
||||
if (e.target.id === 'daa-allocate-resource') {
|
||||
this.handleAllocateResource();
|
||||
}
|
||||
});
|
||||
document.addEventListener('click', (e)=>{
|
||||
if (e.target.id === 'daa-start-consensus') {
|
||||
this.handleStartConsensus();
|
||||
}
|
||||
});
|
||||
}
|
||||
switchTab(tabName) {
|
||||
document.querySelectorAll('.daa-tab-content').forEach((tab)=>{
|
||||
tab.classList.remove('active');
|
||||
});
|
||||
document.querySelectorAll('.daa-tab').forEach((tab)=>{
|
||||
tab.classList.remove('active');
|
||||
});
|
||||
document.getElementById(`daa-${tabName}-tab`).classList.add('active');
|
||||
document.querySelector(`.daa-tab[data-tab="${tabName}"]`).classList.add('active');
|
||||
this.currentTab = tabName;
|
||||
}
|
||||
handleCreateAgent() {
|
||||
const type = document.getElementById('daa-agent-type').value;
|
||||
const capabilities = document.getElementById('daa-agent-capabilities').value.split(',').map((s)=>s.trim());
|
||||
const result = this.daa_agent_create({
|
||||
type: type,
|
||||
capabilities: capabilities,
|
||||
resources: {
|
||||
cpu: 1,
|
||||
memory: 512
|
||||
}
|
||||
});
|
||||
if (result.success) {
|
||||
console.log('Agent created:', result.agentId);
|
||||
}
|
||||
}
|
||||
handleAllocateResource() {
|
||||
const type = document.getElementById('daa-resource-type').value;
|
||||
const capacity = parseInt(document.getElementById('daa-resource-capacity').value) || 100;
|
||||
const priority = document.getElementById('daa-resource-priority').value;
|
||||
const result = this.daa_resource_alloc({
|
||||
type: type,
|
||||
capacity: capacity,
|
||||
priority: priority,
|
||||
amount: capacity * 0.5
|
||||
});
|
||||
if (result.success) {
|
||||
console.log('Resource allocated:', result.resourceId);
|
||||
}
|
||||
}
|
||||
handleStartConsensus() {
|
||||
const proposal = document.getElementById('daa-consensus-proposal').value;
|
||||
const algorithm = document.getElementById('daa-consensus-algorithm').value;
|
||||
if (!proposal.trim()) {
|
||||
alert('Please enter a proposal');
|
||||
return;
|
||||
}
|
||||
const agents = Array.from(this.agents.keys());
|
||||
const result = this.daa_consensus(proposal, agents, {
|
||||
algorithm: algorithm,
|
||||
timeout: 30000
|
||||
});
|
||||
if (result.success) {
|
||||
console.log('Consensus started:', result.consensusId);
|
||||
}
|
||||
}
|
||||
initializeMonitoring() {
|
||||
setInterval(()=>{
|
||||
this.updateMetrics();
|
||||
this.updateResourceGraphs();
|
||||
this.updateLifecycleVisualization();
|
||||
}, 5000);
|
||||
this.createSampleData();
|
||||
}
|
||||
createSampleData() {
|
||||
this.daa_agent_create({
|
||||
type: 'researcher',
|
||||
capabilities: [
|
||||
'data_analysis',
|
||||
'research',
|
||||
'documentation'
|
||||
],
|
||||
resources: {
|
||||
cpu: 2,
|
||||
memory: 1024
|
||||
}
|
||||
});
|
||||
this.daa_agent_create({
|
||||
type: 'coder',
|
||||
capabilities: [
|
||||
"javascript",
|
||||
'python',
|
||||
'testing'
|
||||
],
|
||||
resources: {
|
||||
cpu: 4,
|
||||
memory: 2048
|
||||
}
|
||||
});
|
||||
this.daa_resource_alloc({
|
||||
type: 'cpu',
|
||||
capacity: 100,
|
||||
priority: 'high',
|
||||
amount: 30
|
||||
});
|
||||
this.daa_resource_alloc({
|
||||
type: 'memory',
|
||||
capacity: 8192,
|
||||
priority: 'medium',
|
||||
amount: 2048
|
||||
});
|
||||
}
|
||||
};
|
||||
let daaTools;
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', ()=>{
|
||||
daaTools = new DAATools();
|
||||
});
|
||||
} else {
|
||||
daaTools = new DAATools();
|
||||
}
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = DAATools;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=daa-tools.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/daa-tools.js"],"sourcesContent":["/**\n * Dynamic Agent Architecture (DAA) Tools\n * Implementation of 8 core DAA tools for Claude Flow\n */\n\nclass DAATools {\n constructor() {\n this.agents = new Map();\n this.resources = new Map();\n this.communications = new Map();\n this.consensus = new Map();\n this.isInitialized = false;\n this.currentTab = 'agents';\n\n // Performance metrics\n this.metrics = {\n totalAgents: 0,\n activeAgents: 0,\n resourceUtilization: 0,\n communicationLatency: 0,\n consensusTime: 0,\n faultCount: 0,\n };\n\n this.init();\n }\n\n init() {\n if (this.isInitialized) return;\n\n this.createDAAPanel();\n this.setupEventListeners();\n this.initializeMonitoring();\n this.isInitialized = true;\n\n console.log('DAA Tools initialized');\n }\n\n // Tool 1: Dynamic Agent Creation\n daa_agent_create(config) {\n const agentId = this.generateAgentId();\n const agent = {\n id: agentId,\n type: config.type || 'generic',\n capabilities: config.capabilities || [],\n resources: config.resources || {},\n status: 'initializing',\n created: Date.now(),\n lastActivity: Date.now(),\n tasks: [],\n metadata: config.metadata || {},\n };\n\n this.agents.set(agentId, agent);\n this.metrics.totalAgents++;\n this.metrics.activeAgents++;\n\n // Lifecycle management\n this.initializeAgent(agent);\n\n // Update UI\n this.updateAgentsList();\n this.updateMetrics();\n\n return {\n success: true,\n agentId: agentId,\n agent: agent,\n };\n }\n\n // Tool 2: Capability Matching System\n daa_capability_match(requirements) {\n const matches = [];\n\n for (const [agentId, agent] of this.agents) {\n if (agent.status !== 'active') continue;\n\n const score = this.calculateCapabilityScore(agent.capabilities, requirements);\n if (score > 0) {\n matches.push({\n agentId,\n agent,\n score,\n availableCapabilities: agent.capabilities.filter((cap) =>\n requirements.some((req) => this.matchCapability(cap, req)),\n ),\n });\n }\n }\n\n // Sort by score descending\n matches.sort((a, b) => b.score - a.score);\n\n this.updateCapabilityMatches(matches);\n\n return {\n success: true,\n matches: matches,\n totalCandidates: matches.length,\n };\n }\n\n // Tool 3: Resource Allocation Management\n daa_resource_alloc(allocation) {\n const resourceId = this.generateResourceId();\n const resource = {\n id: resourceId,\n type: allocation.type,\n capacity: allocation.capacity,\n allocated: 0,\n assignments: new Map(),\n priority: allocation.priority || 'medium',\n created: Date.now(),\n metadata: allocation.metadata || {},\n };\n\n this.resources.set(resourceId, resource);\n\n // Perform allocation\n const allocationResult = this.allocateResource(resource, allocation);\n\n // Update visualizations\n this.updateResourceGraphs();\n this.updateMetrics();\n\n return {\n success: allocationResult.success,\n resourceId: resourceId,\n allocation: allocationResult,\n utilization: this.calculateResourceUtilization(),\n };\n }\n\n // Tool 4: Agent Lifecycle Management\n daa_lifecycle_manage(agentId, action, params = {}) {\n const agent = this.agents.get(agentId);\n if (!agent) {\n return { success: false, error: 'Agent not found' };\n }\n\n let result;\n\n switch (action) {\n case 'start':\n result = this.startAgent(agent, params);\n break;\n case 'pause':\n result = this.pauseAgent(agent, params);\n break;\n case 'resume':\n result = this.resumeAgent(agent, params);\n break;\n case 'stop':\n result = this.stopAgent(agent, params);\n break;\n case 'restart':\n result = this.restartAgent(agent, params);\n break;\n case 'destroy':\n result = this.destroyAgent(agent, params);\n break;\n default:\n return { success: false, error: 'Unknown action' };\n }\n\n // Update lifecycle visualization\n this.updateLifecycleVisualization();\n this.updateMetrics();\n\n return result;\n }\n\n // Tool 5: Inter-agent Communication\n daa_communication(fromAgent, toAgent, message, options = {}) {\n const commId = this.generateCommId();\n const communication = {\n id: commId,\n from: fromAgent,\n to: toAgent,\n message: message,\n timestamp: Date.now(),\n type: options.type || 'direct',\n priority: options.priority || 'normal',\n status: 'pending',\n latency: 0,\n metadata: options.metadata || {},\n };\n\n this.communications.set(commId, communication);\n\n // Process communication\n coLine truncated
|
||||
@@ -1,792 +0,0 @@
|
||||
let MemoryInterface = class MemoryInterface {
|
||||
constructor(){
|
||||
this.container = null;
|
||||
this.currentNamespace = 'global';
|
||||
this.memoryData = new Map();
|
||||
this.searchFilters = {};
|
||||
this.analytics = {
|
||||
usage: new Map(),
|
||||
history: [],
|
||||
patterns: new Map()
|
||||
};
|
||||
this.backupManager = new BackupManager();
|
||||
this.syncManager = new SyncManager();
|
||||
this.compressionManager = new CompressionManager();
|
||||
this.visualizer = new MemoryVisualizer();
|
||||
this.init();
|
||||
}
|
||||
init() {
|
||||
this.createInterface();
|
||||
this.setupEventListeners();
|
||||
this.startMonitoring();
|
||||
this.loadMemoryData();
|
||||
}
|
||||
createInterface() {
|
||||
this.container = document.createElement('div');
|
||||
this.container.className = 'memory-interface';
|
||||
this.container.innerHTML = `
|
||||
<div class="memory-header">
|
||||
<h2>Memory Management Interface</h2>
|
||||
<div class="memory-controls">
|
||||
<button class="btn-refresh" title="Refresh Data">
|
||||
<i class="icon-refresh"></i>
|
||||
</button>
|
||||
<button class="btn-backup" title="Create Backup">
|
||||
<i class="icon-backup"></i>
|
||||
</button>
|
||||
<button class="btn-compress" title="Optimize Memory">
|
||||
<i class="icon-compress"></i>
|
||||
</button>
|
||||
<button class="btn-sync" title="Sync Status">
|
||||
<i class="icon-sync"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="memory-layout">
|
||||
<!-- Namespace Browser -->
|
||||
<div class="namespace-panel">
|
||||
<div class="panel-header">
|
||||
<h3>Namespace Browser</h3>
|
||||
<button class="btn-add-namespace" title="Add Namespace">+</button>
|
||||
</div>
|
||||
<div class="namespace-tree">
|
||||
<div class="namespace-search">
|
||||
<input type="text" placeholder="Search namespaces..."
|
||||
class="namespace-search-input">
|
||||
</div>
|
||||
<div class="namespace-tree-container">
|
||||
<!-- Namespace tree will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Key-Value Editor -->
|
||||
<div class="editor-panel">
|
||||
<div class="panel-header">
|
||||
<h3>Key-Value Editor</h3>
|
||||
<div class="editor-controls">
|
||||
<button class="btn-add-key" title="Add Key">+</button>
|
||||
<button class="btn-bulk-edit" title="Bulk Edit">Bulk</button>
|
||||
<button class="btn-export" title="Export">Export</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="editor-content">
|
||||
<div class="editor-search">
|
||||
<input type="text" placeholder="Search keys..."
|
||||
class="key-search-input">
|
||||
<select class="type-filter">
|
||||
<option value="">All Types</option>
|
||||
<option value="string">String</option>
|
||||
<option value="number">Number</option>
|
||||
<option value="boolean">Boolean</option>
|
||||
<option value="object">Object</option>
|
||||
<option value="array">Array</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="key-value-list">
|
||||
<!-- Key-value pairs will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Analytics Dashboard -->
|
||||
<div class="analytics-panel">
|
||||
<div class="panel-header">
|
||||
<h3>Memory Analytics</h3>
|
||||
<select class="analytics-timeframe">
|
||||
<option value="1h">Last Hour</option>
|
||||
<option value="24h">Last 24 Hours</option>
|
||||
<option value="7d">Last 7 Days</option>
|
||||
<option value="30d">Last 30 Days</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="analytics-content">
|
||||
<div class="analytics-stats">
|
||||
<div class="stat-card">
|
||||
<h4>Total Keys</h4>
|
||||
<span class="stat-value" id="total-keys">0</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<h4>Memory Usage</h4>
|
||||
<span class="stat-value" id="memory-usage">0 KB</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<h4>Compression Rate</h4>
|
||||
<span class="stat-value" id="compression-rate">0%</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<h4>Access Frequency</h4>
|
||||
<span class="stat-value" id="access-frequency">0/min</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="analytics-charts">
|
||||
<div class="chart-container">
|
||||
<canvas id="usage-chart"></canvas>
|
||||
</div>
|
||||
<div class="chart-container">
|
||||
<canvas id="pattern-chart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Search Interface -->
|
||||
<div class="search-panel">
|
||||
<div class="panel-header">
|
||||
<h3>Advanced Search</h3>
|
||||
<button class="btn-saved-searches" title="Saved Searches">
|
||||
<i class="icon-bookmark"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="search-content">
|
||||
<div class="search-builder">
|
||||
<div class="search-row">
|
||||
<select class="search-field">
|
||||
<option value="key">Key</option>
|
||||
<option value="value">Value</option>
|
||||
<option value="type">Type</option>
|
||||
<option value="namespace">Namespace</option>
|
||||
<option value="created">Created Date</option>
|
||||
<option value="modified">Modified Date</option>
|
||||
</select>
|
||||
<select class="search-operator">
|
||||
<option value="contains">Contains</option>
|
||||
<option value="equals">Equals</option>
|
||||
<option value="startsWith">Starts With</option>
|
||||
<option value="endsWith">Ends With</option>
|
||||
<option value="regex">Regex</option>
|
||||
</select>
|
||||
<input type="text" class="search-value" placeholder="Search value...">
|
||||
<button class="btn-add-filter">+</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="search-filters">
|
||||
<!-- Active filters will be shown here -->
|
||||
</div>
|
||||
<div class="search-results">
|
||||
<!-- Search results will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Backup/Restore Panel -->
|
||||
<div class="backup-panel">
|
||||
<div class="panel-header">
|
||||
<h3>Backup & Restore</h3>
|
||||
<button class="btn-schedule-backup" title="Schedule Backup">
|
||||
<i class="icon-schedule"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="backup-content">
|
||||
<div class="backup-controls">
|
||||
<button class="btn-create-backup">Create Backup</button>
|
||||
<button class="btn-restore-backup">Restore Backup</button>
|
||||
<button class="btn-import-backup">Import Backup</button>
|
||||
</div>
|
||||
<div class="backup-list">
|
||||
<!-- Backup list will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modals -->
|
||||
<div class="modal-overlay" id="modal-overlay">
|
||||
<div class="modal" id="key-editor-modal">
|
||||
<div class="modal-header">
|
||||
<h3>Edit Key-Value Pair</h3>
|
||||
<button class="btn-close-modal">×</button>
|
||||
</div>
|
||||
<div class="modal-content">
|
||||
<form id="key-editor-form">
|
||||
<div class="form-group">
|
||||
<label>Key:</label>
|
||||
<input type="text" id="edit-key" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Type:</label>
|
||||
<select id="edit-type">
|
||||
<option value="string">String</option>
|
||||
<option value="number">Number</option>
|
||||
<option value="boolean">Boolean</option>
|
||||
<option value="object">Object</option>
|
||||
<option value="array">Array</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Value:</label>
|
||||
<textarea id="edit-value" rows="10"></textarea>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Namespace:</label>
|
||||
<select id="edit-namespace">
|
||||
<!-- Namespaces will be populated here -->
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn-save">Save</button>
|
||||
<button type="button" class="btn-cancel">Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
setupEventListeners() {
|
||||
this.container.querySelector('.btn-refresh').addEventListener('click', ()=>this.refresh());
|
||||
this.container.querySelector('.btn-backup').addEventListener('click', ()=>this.createBackup());
|
||||
this.container.querySelector('.btn-compress').addEventListener('click', ()=>this.optimizeMemory());
|
||||
this.container.querySelector('.btn-sync').addEventListener('click', ()=>this.showSyncStatus());
|
||||
this.container.querySelector('.btn-add-namespace').addEventListener('click', ()=>this.addNamespace());
|
||||
this.container.querySelector('.namespace-search-input').addEventListener('input', (e)=>this.searchNamespaces(e.target.value));
|
||||
this.container.querySelector('.btn-add-key').addEventListener('click', ()=>this.addKey());
|
||||
this.container.querySelector('.btn-bulk-edit').addEventListener('click', ()=>this.bulkEdit());
|
||||
this.container.querySelector('.btn-export').addEventListener('click', ()=>this.exportMemory());
|
||||
this.container.querySelector('.key-search-input').addEventListener('input', (e)=>this.searchKeys(e.target.value));
|
||||
this.container.querySelector('.type-filter').addEventListener('change', (e)=>this.filterByType(e.target.value));
|
||||
this.container.querySelector('.analytics-timeframe').addEventListener('change', (e)=>this.updateAnalytics(e.target.value));
|
||||
this.container.querySelector('.btn-add-filter').addEventListener('click', ()=>this.addSearchFilter());
|
||||
this.container.querySelector('.btn-saved-searches').addEventListener('click', ()=>this.showSavedSearches());
|
||||
this.container.querySelector('.btn-create-backup').addEventListener('click', ()=>this.createBackup());
|
||||
this.container.querySelector('.btn-restore-backup').addEventListener('click', ()=>this.restoreBackup());
|
||||
this.container.querySelector('.btn-import-backup').addEventListener('click', ()=>this.importBackup());
|
||||
this.container.querySelector('.btn-close-modal').addEventListener('click', ()=>this.closeModal());
|
||||
this.container.querySelector('.modal-overlay').addEventListener('click', (e)=>{
|
||||
if (e.target === this.container.querySelector('.modal-overlay')) {
|
||||
this.closeModal();
|
||||
}
|
||||
});
|
||||
this.container.querySelector('#key-editor-form').addEventListener('submit', (e)=>this.saveKeyValue(e));
|
||||
}
|
||||
async loadMemoryData() {
|
||||
try {
|
||||
const response = await fetch('/api/memory/list');
|
||||
const data = await response.json();
|
||||
this.memoryData = new Map(Object.entries(data));
|
||||
this.updateNamespaceTree();
|
||||
this.updateKeyValueList();
|
||||
this.updateAnalytics();
|
||||
} catch (error) {
|
||||
console.error('Failed to load memory data:', error);
|
||||
this.showError('Failed to load memory data');
|
||||
}
|
||||
}
|
||||
updateNamespaceTree() {
|
||||
const container = this.container.querySelector('.namespace-tree-container');
|
||||
const namespaces = this.getNamespaces();
|
||||
container.innerHTML = this.renderNamespaceTree(namespaces);
|
||||
container.querySelectorAll('.namespace-item').forEach((item)=>{
|
||||
item.addEventListener('click', (e)=>{
|
||||
e.stopPropagation();
|
||||
this.selectNamespace(item.dataset.namespace);
|
||||
});
|
||||
});
|
||||
}
|
||||
renderNamespaceTree(namespaces, parent = '', level = 0) {
|
||||
let html = '';
|
||||
for (const [namespace, data] of namespaces){
|
||||
const fullPath = parent ? `${parent}.${namespace}` : namespace;
|
||||
const hasChildren = data.children && data.children.size > 0;
|
||||
html += `
|
||||
<div class="namespace-item ${this.currentNamespace === fullPath ? 'active' : ''}"
|
||||
data-namespace="${fullPath}"
|
||||
style="padding-left: ${level * 20}px">
|
||||
<div class="namespace-content">
|
||||
${hasChildren ? '<i class="icon-folder"></i>' : '<i class="icon-file"></i>'}
|
||||
<span class="namespace-name">${namespace}</span>
|
||||
<span class="namespace-count">(${data.count})</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
if (hasChildren) {
|
||||
html += this.renderNamespaceTree(data.children, fullPath, level + 1);
|
||||
}
|
||||
}
|
||||
return html;
|
||||
}
|
||||
updateKeyValueList() {
|
||||
const container = this.container.querySelector('.key-value-list');
|
||||
const keys = this.getKeysForNamespace(this.currentNamespace);
|
||||
container.innerHTML = keys.map((key)=>this.renderKeyValueItem(key)).join('');
|
||||
container.querySelectorAll('.key-value-item').forEach((item)=>{
|
||||
item.querySelector('.btn-edit').addEventListener('click', ()=>this.editKey(item.dataset.key));
|
||||
item.querySelector('.btn-delete').addEventListener('click', ()=>this.deleteKey(item.dataset.key));
|
||||
item.querySelector('.btn-copy').addEventListener('click', ()=>this.copyKey(item.dataset.key));
|
||||
});
|
||||
}
|
||||
renderKeyValueItem(key) {
|
||||
const value = this.memoryData.get(key);
|
||||
const type = this.getValueType(value);
|
||||
const displayValue = this.formatValueForDisplay(value, type);
|
||||
return `
|
||||
<div class="key-value-item" data-key="${key}">
|
||||
<div class="key-info">
|
||||
<span class="key-name">${key}</span>
|
||||
<span class="key-type">${type}</span>
|
||||
</div>
|
||||
<div class="value-preview">
|
||||
<span class="value-content">${displayValue}</span>
|
||||
</div>
|
||||
<div class="item-actions">
|
||||
<button class="btn-edit" title="Edit">
|
||||
<i class="icon-edit"></i>
|
||||
</button>
|
||||
<button class="btn-copy" title="Copy">
|
||||
<i class="icon-copy"></i>
|
||||
</button>
|
||||
<button class="btn-delete" title="Delete">
|
||||
<i class="icon-delete"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
getNamespaces() {
|
||||
const namespaces = new Map();
|
||||
for (const [key, value] of this.memoryData){
|
||||
const parts = key.split('.');
|
||||
let current = namespaces;
|
||||
let path = '';
|
||||
for(let i = 0; i < parts.length - 1; i++){
|
||||
const part = parts[i];
|
||||
path = path ? `${path}.${part}` : part;
|
||||
if (!current.has(part)) {
|
||||
current.set(part, {
|
||||
count: 0,
|
||||
children: new Map()
|
||||
});
|
||||
}
|
||||
current = current.get(part).children;
|
||||
}
|
||||
const finalPart = parts[parts.length - 1];
|
||||
if (!current.has(finalPart)) {
|
||||
current.set(finalPart, {
|
||||
count: 0,
|
||||
children: new Map()
|
||||
});
|
||||
}
|
||||
current.get(finalPart).count++;
|
||||
}
|
||||
return namespaces;
|
||||
}
|
||||
getKeysForNamespace(namespace) {
|
||||
const keys = [];
|
||||
const prefix = namespace === 'global' ? '' : `${namespace}.`;
|
||||
for (const [key, value] of this.memoryData){
|
||||
if (namespace === 'global' || key.startsWith(prefix)) {
|
||||
keys.push(key);
|
||||
}
|
||||
}
|
||||
return keys.sort();
|
||||
}
|
||||
getValueType(value) {
|
||||
if (value === null) return 'null';
|
||||
if (value === undefined) return 'undefined';
|
||||
if (Array.isArray(value)) return 'array';
|
||||
return typeof value;
|
||||
}
|
||||
formatValueForDisplay(value, type) {
|
||||
switch(type){
|
||||
case 'string':
|
||||
return value.length > 50 ? `${value.substring(0, 50)}...` : value;
|
||||
case 'object':
|
||||
return JSON.stringify(value).substring(0, 100) + '...';
|
||||
case 'array':
|
||||
return `[${value.length} items]`;
|
||||
default:
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
updateAnalytics(timeframe = '24h') {
|
||||
const stats = this.calculateStats(timeframe);
|
||||
this.container.querySelector('#total-keys').textContent = stats.totalKeys;
|
||||
this.container.querySelector('#memory-usage').textContent = stats.memoryUsage;
|
||||
this.container.querySelector('#compression-rate').textContent = stats.compressionRate;
|
||||
this.container.querySelector('#access-frequency').textContent = stats.accessFrequency;
|
||||
this.visualizer.updateUsageChart(stats.usageData);
|
||||
this.visualizer.updatePatternChart(stats.patternData);
|
||||
}
|
||||
calculateStats(timeframe) {
|
||||
const now = Date.now();
|
||||
const timeframes = {
|
||||
'1h': 60 * 60 * 1000,
|
||||
'24h': 24 * 60 * 60 * 1000,
|
||||
'7d': 7 * 24 * 60 * 60 * 1000,
|
||||
'30d': 30 * 24 * 60 * 60 * 1000
|
||||
};
|
||||
const cutoff = now - timeframes[timeframe];
|
||||
return {
|
||||
totalKeys: this.memoryData.size,
|
||||
memoryUsage: this.calculateMemoryUsage(),
|
||||
compressionRate: this.compressionManager.getCompressionRate(),
|
||||
accessFrequency: this.calculateAccessFrequency(cutoff),
|
||||
usageData: this.getUsageData(cutoff),
|
||||
patternData: this.getPatternData(cutoff)
|
||||
};
|
||||
}
|
||||
calculateMemoryUsage() {
|
||||
let totalSize = 0;
|
||||
for (const [key, value] of this.memoryData){
|
||||
totalSize += this.getObjectSize(key) + this.getObjectSize(value);
|
||||
}
|
||||
return this.formatBytes(totalSize);
|
||||
}
|
||||
getObjectSize(obj) {
|
||||
let size = 0;
|
||||
if (typeof obj === 'string') {
|
||||
size = obj.length * 2;
|
||||
} else if (typeof obj === 'number') {
|
||||
size = 8;
|
||||
} else if (typeof obj === 'boolean') {
|
||||
size = 1;
|
||||
} else if (obj === null || obj === undefined) {
|
||||
size = 0;
|
||||
} else {
|
||||
size = JSON.stringify(obj).length * 2;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
formatBytes(bytes) {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = [
|
||||
'B',
|
||||
'KB',
|
||||
'MB',
|
||||
'GB'
|
||||
];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
}
|
||||
calculateAccessFrequency(cutoff) {
|
||||
const recentAccess = this.analytics.history.filter((entry)=>entry.timestamp > cutoff);
|
||||
const frequency = recentAccess.length / ((Date.now() - cutoff) / 60000);
|
||||
return frequency.toFixed(2);
|
||||
}
|
||||
getUsageData(cutoff) {
|
||||
return this.analytics.history.filter((entry)=>entry.timestamp > cutoff).map((entry)=>({
|
||||
timestamp: entry.timestamp,
|
||||
operations: entry.operations || 0,
|
||||
memory: entry.memory || 0
|
||||
}));
|
||||
}
|
||||
getPatternData(cutoff) {
|
||||
const patterns = new Map();
|
||||
for (const [key, value] of this.analytics.patterns){
|
||||
if (value.lastAccess > cutoff) {
|
||||
patterns.set(key, value);
|
||||
}
|
||||
}
|
||||
return Array.from(patterns.entries());
|
||||
}
|
||||
async selectNamespace(namespace) {
|
||||
this.currentNamespace = namespace;
|
||||
this.updateKeyValueList();
|
||||
this.container.querySelectorAll('.namespace-item').forEach((item)=>{
|
||||
item.classList.toggle('active', item.dataset.namespace === namespace);
|
||||
});
|
||||
await this.notifyCoordination(`Selected namespace: ${namespace}`);
|
||||
}
|
||||
async addNamespace() {
|
||||
const name = prompt('Enter namespace name:');
|
||||
if (name) {
|
||||
const key = `${name}.placeholder`;
|
||||
await this.setMemoryValue(key, 'Namespace placeholder');
|
||||
await this.loadMemoryData();
|
||||
await this.notifyCoordination(`Added namespace: ${name}`);
|
||||
}
|
||||
}
|
||||
async addKey() {
|
||||
this.openModal('key-editor-modal');
|
||||
this.container.querySelector('#edit-key').value = '';
|
||||
this.container.querySelector('#edit-value').value = '';
|
||||
this.container.querySelector('#edit-type').value = 'string';
|
||||
this.container.querySelector('#edit-namespace').value = this.currentNamespace;
|
||||
}
|
||||
async editKey(key) {
|
||||
const value = this.memoryData.get(key);
|
||||
const type = this.getValueType(value);
|
||||
this.openModal('key-editor-modal');
|
||||
this.container.querySelector('#edit-key').value = key;
|
||||
this.container.querySelector('#edit-value').value = JSON.stringify(value, null, 2);
|
||||
this.container.querySelector('#edit-type').value = type;
|
||||
this.container.querySelector('#edit-namespace').value = this.getNamespaceFromKey(key);
|
||||
}
|
||||
async deleteKey(key) {
|
||||
if (confirm(`Are you sure you want to delete "${key}"?`)) {
|
||||
await this.deleteMemoryValue(key);
|
||||
await this.loadMemoryData();
|
||||
await this.notifyCoordination(`Deleted key: ${key}`);
|
||||
}
|
||||
}
|
||||
async copyKey(key) {
|
||||
const value = this.memoryData.get(key);
|
||||
const text = JSON.stringify({
|
||||
[key]: value
|
||||
}, null, 2);
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
this.showSuccess('Key copied to clipboard');
|
||||
} catch (error) {
|
||||
console.error('Failed to copy to clipboard:', error);
|
||||
this.showError('Failed to copy to clipboard');
|
||||
}
|
||||
}
|
||||
async saveKeyValue(e) {
|
||||
e.preventDefault();
|
||||
const key = this.container.querySelector('#edit-key').value;
|
||||
const type = this.container.querySelector('#edit-type').value;
|
||||
const valueText = this.container.querySelector('#edit-value').value;
|
||||
try {
|
||||
let value;
|
||||
switch(type){
|
||||
case 'string':
|
||||
value = valueText;
|
||||
break;
|
||||
case 'number':
|
||||
value = parseFloat(valueText);
|
||||
break;
|
||||
case 'boolean':
|
||||
value = valueText.toLowerCase() === 'true';
|
||||
break;
|
||||
case 'object':
|
||||
case 'array':
|
||||
value = JSON.parse(valueText);
|
||||
break;
|
||||
default:
|
||||
value = valueText;
|
||||
}
|
||||
await this.setMemoryValue(key, value);
|
||||
await this.loadMemoryData();
|
||||
this.closeModal();
|
||||
await this.notifyCoordination(`Saved key: ${key}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to save key-value:', error);
|
||||
this.showError('Failed to save key-value pair');
|
||||
}
|
||||
}
|
||||
async createBackup() {
|
||||
try {
|
||||
const backup = await this.backupManager.createBackup(this.memoryData);
|
||||
this.showSuccess(`Backup created: ${backup.id}`);
|
||||
await this.notifyCoordination(`Created backup: ${backup.id}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to create backup:', error);
|
||||
this.showError('Failed to create backup');
|
||||
}
|
||||
}
|
||||
async optimizeMemory() {
|
||||
try {
|
||||
const result = await this.compressionManager.optimize(this.memoryData);
|
||||
this.showSuccess(`Memory optimized: ${result.savedBytes} bytes saved`);
|
||||
await this.loadMemoryData();
|
||||
await this.notifyCoordination(`Optimized memory: ${result.savedBytes} bytes saved`);
|
||||
} catch (error) {
|
||||
console.error('Failed to optimize memory:', error);
|
||||
this.showError('Failed to optimize memory');
|
||||
}
|
||||
}
|
||||
async refresh() {
|
||||
await this.loadMemoryData();
|
||||
this.showSuccess('Memory data refreshed');
|
||||
}
|
||||
openModal(modalId) {
|
||||
this.container.querySelector('#modal-overlay').style.display = 'flex';
|
||||
this.container.querySelector(`#${modalId}`).style.display = 'block';
|
||||
}
|
||||
closeModal() {
|
||||
this.container.querySelector('#modal-overlay').style.display = 'none';
|
||||
this.container.querySelectorAll('.modal').forEach((modal)=>{
|
||||
modal.style.display = 'none';
|
||||
});
|
||||
}
|
||||
getNamespaceFromKey(key) {
|
||||
const parts = key.split('.');
|
||||
return parts.length > 1 ? parts.slice(0, -1).join('.') : 'global';
|
||||
}
|
||||
async setMemoryValue(key, value) {
|
||||
const response = await fetch('/api/memory/set', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
key,
|
||||
value
|
||||
})
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to set memory value');
|
||||
}
|
||||
}
|
||||
async deleteMemoryValue(key) {
|
||||
const response = await fetch('/api/memory/delete', {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
key
|
||||
})
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to delete memory value');
|
||||
}
|
||||
}
|
||||
showSuccess(message) {
|
||||
console.log('Success:', message);
|
||||
}
|
||||
showError(message) {
|
||||
console.error('Error:', message);
|
||||
}
|
||||
async notifyCoordination(message) {
|
||||
try {
|
||||
await fetch('/api/coordination/notify', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
message,
|
||||
timestamp: Date.now()
|
||||
})
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to notify coordination:', error);
|
||||
}
|
||||
}
|
||||
startMonitoring() {
|
||||
setInterval(()=>{
|
||||
this.updateAnalytics();
|
||||
}, 30000);
|
||||
}
|
||||
render() {
|
||||
return this.container;
|
||||
}
|
||||
};
|
||||
let BackupManager = class BackupManager {
|
||||
constructor(){
|
||||
this.backups = new Map();
|
||||
}
|
||||
async createBackup(memoryData) {
|
||||
const id = `backup_${Date.now()}`;
|
||||
const backup = {
|
||||
id,
|
||||
timestamp: Date.now(),
|
||||
data: new Map(memoryData),
|
||||
size: this.calculateBackupSize(memoryData)
|
||||
};
|
||||
this.backups.set(id, backup);
|
||||
return backup;
|
||||
}
|
||||
async restoreBackup(backupId) {
|
||||
const backup = this.backups.get(backupId);
|
||||
if (!backup) {
|
||||
throw new Error('Backup not found');
|
||||
}
|
||||
return backup.data;
|
||||
}
|
||||
calculateBackupSize(memoryData) {
|
||||
return JSON.stringify(Array.from(memoryData.entries())).length;
|
||||
}
|
||||
};
|
||||
let SyncManager = class SyncManager {
|
||||
constructor(){
|
||||
this.syncStatus = 'idle';
|
||||
this.lastSync = null;
|
||||
}
|
||||
async sync() {
|
||||
this.syncStatus = 'syncing';
|
||||
try {
|
||||
await new Promise((resolve)=>setTimeout(resolve, 1000));
|
||||
this.lastSync = Date.now();
|
||||
this.syncStatus = 'synchronized';
|
||||
} catch (error) {
|
||||
this.syncStatus = 'error';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
getStatus() {
|
||||
return {
|
||||
status: this.syncStatus,
|
||||
lastSync: this.lastSync
|
||||
};
|
||||
}
|
||||
};
|
||||
let CompressionManager = class CompressionManager {
|
||||
constructor(){
|
||||
this.compressionRate = 0;
|
||||
}
|
||||
async optimize(memoryData) {
|
||||
const originalSize = this.calculateSize(memoryData);
|
||||
await new Promise((resolve)=>setTimeout(resolve, 500));
|
||||
const compressedSize = originalSize * 0.7;
|
||||
const savedBytes = originalSize - compressedSize;
|
||||
this.compressionRate = savedBytes / originalSize * 100;
|
||||
return {
|
||||
savedBytes: Math.floor(savedBytes),
|
||||
compressionRate: this.compressionRate
|
||||
};
|
||||
}
|
||||
getCompressionRate() {
|
||||
return `${this.compressionRate.toFixed(1)}%`;
|
||||
}
|
||||
calculateSize(memoryData) {
|
||||
return JSON.stringify(Array.from(memoryData.entries())).length;
|
||||
}
|
||||
};
|
||||
let MemoryVisualizer = class MemoryVisualizer {
|
||||
constructor(){
|
||||
this.usageChart = null;
|
||||
this.patternChart = null;
|
||||
}
|
||||
updateUsageChart(data) {
|
||||
const canvas = document.getElementById('usage-chart');
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
if (data.length > 0) {
|
||||
ctx.beginPath();
|
||||
ctx.strokeStyle = '#007bff';
|
||||
ctx.lineWidth = 2;
|
||||
const width = canvas.width;
|
||||
const height = canvas.height;
|
||||
const stepX = width / (data.length - 1);
|
||||
const maxValue = Math.max(...data.map((d)=>d.operations));
|
||||
data.forEach((point, index)=>{
|
||||
const x = index * stepX;
|
||||
const y = height - point.operations / maxValue * height;
|
||||
if (index === 0) {
|
||||
ctx.moveTo(x, y);
|
||||
} else {
|
||||
ctx.lineTo(x, y);
|
||||
}
|
||||
});
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
updatePatternChart(data) {
|
||||
const canvas = document.getElementById('pattern-chart');
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
if (data.length > 0) {
|
||||
const width = canvas.width;
|
||||
const height = canvas.height;
|
||||
const barWidth = width / data.length;
|
||||
const maxValue = Math.max(...data.map((d)=>d[1].count || 0));
|
||||
data.forEach((pattern, index)=>{
|
||||
const barHeight = (pattern[1].count || 0) / maxValue * height;
|
||||
const x = index * barWidth;
|
||||
const y = height - barHeight;
|
||||
ctx.fillStyle = '#28a745';
|
||||
ctx.fillRect(x, y, barWidth - 2, barHeight);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
window.MemoryInterface = MemoryInterface;
|
||||
|
||||
//# sourceMappingURL=memory-interface.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/memory-interface.js"],"sourcesContent":["/**\n * Memory Management Interface\n * Comprehensive memory management system for Claude Flow\n */\n\nclass MemoryInterface {\n constructor() {\n this.container = null;\n this.currentNamespace = 'global';\n this.memoryData = new Map();\n this.searchFilters = {};\n this.analytics = {\n usage: new Map(),\n history: [],\n patterns: new Map(),\n };\n this.backupManager = new BackupManager();\n this.syncManager = new SyncManager();\n this.compressionManager = new CompressionManager();\n this.visualizer = new MemoryVisualizer();\n\n this.init();\n }\n\n init() {\n this.createInterface();\n this.setupEventListeners();\n this.startMonitoring();\n this.loadMemoryData();\n }\n\n createInterface() {\n this.container = document.createElement('div');\n this.container.className = 'memory-interface';\n this.container.innerHTML = `\n <div class=\"memory-header\">\n <h2>Memory Management Interface</h2>\n <div class=\"memory-controls\">\n <button class=\"btn-refresh\" title=\"Refresh Data\">\n <i class=\"icon-refresh\"></i>\n </button>\n <button class=\"btn-backup\" title=\"Create Backup\">\n <i class=\"icon-backup\"></i>\n </button>\n <button class=\"btn-compress\" title=\"Optimize Memory\">\n <i class=\"icon-compress\"></i>\n </button>\n <button class=\"btn-sync\" title=\"Sync Status\">\n <i class=\"icon-sync\"></i>\n </button>\n </div>\n </div>\n\n <div class=\"memory-layout\">\n <!-- Namespace Browser -->\n <div class=\"namespace-panel\">\n <div class=\"panel-header\">\n <h3>Namespace Browser</h3>\n <button class=\"btn-add-namespace\" title=\"Add Namespace\">+</button>\n </div>\n <div class=\"namespace-tree\">\n <div class=\"namespace-search\">\n <input type=\"text\" placeholder=\"Search namespaces...\" \n class=\"namespace-search-input\">\n </div>\n <div class=\"namespace-tree-container\">\n <!-- Namespace tree will be populated here -->\n </div>\n </div>\n </div>\n\n <!-- Key-Value Editor -->\n <div class=\"editor-panel\">\n <div class=\"panel-header\">\n <h3>Key-Value Editor</h3>\n <div class=\"editor-controls\">\n <button class=\"btn-add-key\" title=\"Add Key\">+</button>\n <button class=\"btn-bulk-edit\" title=\"Bulk Edit\">Bulk</button>\n <button class=\"btn-export\" title=\"Export\">Export</button>\n </div>\n </div>\n <div class=\"editor-content\">\n <div class=\"editor-search\">\n <input type=\"text\" placeholder=\"Search keys...\" \n class=\"key-search-input\">\n <select class=\"type-filter\">\n <option value=\"\">All Types</option>\n <option value=\"string\">String</option>\n <option value=\"number\">Number</option>\n <option value=\"boolean\">Boolean</option>\n <option value=\"object\">Object</option>\n <option value=\"array\">Array</option>\n </select>\n </div>\n <div class=\"key-value-list\">\n <!-- Key-value pairs will be populated here -->\n </div>\n </div>\n </div>\n\n <!-- Analytics Dashboard -->\n <div class=\"analytics-panel\">\n <div class=\"panel-header\">\n <h3>Memory Analytics</h3>\n <select class=\"analytics-timeframe\">\n <option value=\"1h\">Last Hour</option>\n <option value=\"24h\">Last 24 Hours</option>\n <option value=\"7d\">Last 7 Days</option>\n <option value=\"30d\">Last 30 Days</option>\n </select>\n </div>\n <div class=\"aLine truncated
|
||||
@@ -1,178 +0,0 @@
|
||||
export class MemoryTest {
|
||||
constructor(memoryManager, terminal){
|
||||
this.memoryManager = memoryManager;
|
||||
this.terminal = terminal;
|
||||
}
|
||||
async runTests() {
|
||||
this.terminal.writeInfo('🧪 Starting Memory Manager Tests...');
|
||||
try {
|
||||
await this.testMemoryPanel();
|
||||
await this.testMemoryTools();
|
||||
await this.testNamespaceOperations();
|
||||
await this.testMemoryOperations();
|
||||
this.terminal.writeSuccess('✅ All memory tests completed successfully!');
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`❌ Memory tests failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
async testMemoryPanel() {
|
||||
this.terminal.writeInfo('Testing memory panel...');
|
||||
this.memoryManager.togglePanel();
|
||||
const panelVisible = !document.getElementById('memoryPanel')?.classList.contains('hidden');
|
||||
if (panelVisible) {
|
||||
this.terminal.writeSuccess('✅ Memory panel opens correctly');
|
||||
} else {
|
||||
throw new Error('Memory panel failed to open');
|
||||
}
|
||||
const requiredElements = [
|
||||
'memoryToolsGrid',
|
||||
'namespaceSelect',
|
||||
'memoryTable',
|
||||
'memoryAnalytics',
|
||||
'memoryLog'
|
||||
];
|
||||
for (const elementId of requiredElements){
|
||||
const element = document.getElementById(elementId);
|
||||
if (element) {
|
||||
this.terminal.writeSuccess(`✅ ${elementId} component found`);
|
||||
} else {
|
||||
throw new Error(`Required component missing: ${elementId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
async testMemoryTools() {
|
||||
this.terminal.writeInfo('Testing memory tools...');
|
||||
const tools = Object.keys(this.memoryManager.memoryTools);
|
||||
this.terminal.writeInfo(`Found ${tools.length} memory tools:`);
|
||||
for (const tool of tools){
|
||||
const toolInfo = this.memoryManager.memoryTools[tool];
|
||||
this.terminal.writeLine(` ${toolInfo.icon} ${toolInfo.name} - ${toolInfo.description}`);
|
||||
}
|
||||
if (tools.length === 10) {
|
||||
this.terminal.writeSuccess('✅ All 10 memory tools are configured');
|
||||
} else {
|
||||
throw new Error(`Expected 10 memory tools, found ${tools.length}`);
|
||||
}
|
||||
}
|
||||
async testNamespaceOperations() {
|
||||
this.terminal.writeInfo('Testing namespace operations...');
|
||||
const originalNamespace = this.memoryManager.currentNamespace;
|
||||
await this.memoryManager.switchNamespace('test');
|
||||
if (this.memoryManager.currentNamespace === 'test') {
|
||||
this.terminal.writeSuccess('✅ Namespace switching works');
|
||||
} else {
|
||||
throw new Error('Namespace switching failed');
|
||||
}
|
||||
await this.memoryManager.switchNamespace(originalNamespace);
|
||||
}
|
||||
async testMemoryOperations() {
|
||||
this.terminal.writeInfo('Testing memory operations...');
|
||||
const testData = {
|
||||
size: this.memoryManager.formatSize(1024),
|
||||
ttl: this.memoryManager.formatTTL(Date.now() + 3600000),
|
||||
truncate: this.memoryManager.truncateValue('This is a very long test string that should be truncated'),
|
||||
escape: this.memoryManager.escapeHtml('<script>alert("test")<\/script>')
|
||||
};
|
||||
if (testData.size === '1 KB') {
|
||||
this.terminal.writeSuccess('✅ Size formatting works');
|
||||
} else {
|
||||
throw new Error(`Size formatting failed: ${testData.size}`);
|
||||
}
|
||||
if (testData.ttl.includes('h') && testData.ttl.includes('m')) {
|
||||
this.terminal.writeSuccess('✅ TTL formatting works');
|
||||
} else {
|
||||
throw new Error(`TTL formatting failed: ${testData.ttl}`);
|
||||
}
|
||||
if (testData.truncate.length <= 103) {
|
||||
this.terminal.writeSuccess('✅ Value truncation works');
|
||||
} else {
|
||||
throw new Error('Value truncation failed');
|
||||
}
|
||||
if (!testData.escape.includes("<script>")) {
|
||||
this.terminal.writeSuccess('✅ HTML escaping works');
|
||||
} else {
|
||||
throw new Error('HTML escaping failed');
|
||||
}
|
||||
}
|
||||
async testMockData() {
|
||||
this.terminal.writeInfo('Testing with mock data...');
|
||||
const mockEntries = [
|
||||
{
|
||||
key: 'test/key1',
|
||||
value: 'test value 1',
|
||||
size: 256,
|
||||
ttl: Date.now() + 3600000,
|
||||
namespace: 'test'
|
||||
},
|
||||
{
|
||||
key: 'test/key2',
|
||||
value: JSON.stringify({
|
||||
test: 'data',
|
||||
array: [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
]
|
||||
}),
|
||||
size: 512,
|
||||
ttl: null,
|
||||
namespace: 'test'
|
||||
}
|
||||
];
|
||||
this.memoryManager.updateMemoryTable(mockEntries);
|
||||
const tableBody = document.getElementById('memoryTableBody');
|
||||
const rows = tableBody?.getElementsByTagName('tr');
|
||||
if (rows && rows.length === mockEntries.length) {
|
||||
this.terminal.writeSuccess('✅ Memory table updates correctly');
|
||||
} else {
|
||||
throw new Error('Memory table update failed');
|
||||
}
|
||||
this.memoryManager.filterMemoryEntries('key1');
|
||||
const visibleRows = Array.from(rows).filter((row)=>row.style.display !== 'none');
|
||||
if (visibleRows.length === 1) {
|
||||
this.terminal.writeSuccess('✅ Memory filtering works');
|
||||
} else {
|
||||
throw new Error('Memory filtering failed');
|
||||
}
|
||||
this.memoryManager.filterMemoryEntries('');
|
||||
}
|
||||
generateReport() {
|
||||
const report = {
|
||||
timestamp: new Date().toISOString(),
|
||||
tests: {
|
||||
panel: 'passed',
|
||||
tools: 'passed',
|
||||
namespaces: 'passed',
|
||||
operations: 'passed'
|
||||
},
|
||||
memoryTools: Object.keys(this.memoryManager.memoryTools),
|
||||
features: [
|
||||
'Memory Tools Grid (10 tools)',
|
||||
'Namespace Browser',
|
||||
'Memory Data Table',
|
||||
'Memory Analytics Dashboard',
|
||||
'Operations Log',
|
||||
'Import/Export',
|
||||
'Search & Filter',
|
||||
'Auto-refresh'
|
||||
]
|
||||
};
|
||||
this.terminal.writeInfo('📊 Memory Manager Test Report:');
|
||||
this.terminal.writeLine(JSON.stringify(report, null, 2));
|
||||
return report;
|
||||
}
|
||||
}
|
||||
export async function runMemoryTests() {
|
||||
if (window.memoryManager && window.claudeConsole) {
|
||||
const tester = new MemoryTest(window.memoryManager, window.claudeConsole.terminal);
|
||||
await tester.runTests();
|
||||
await tester.testMockData();
|
||||
return tester.generateReport();
|
||||
} else {
|
||||
console.error('Memory manager or console not available for testing');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
window.runMemoryTests = runMemoryTests;
|
||||
|
||||
//# sourceMappingURL=memory-test.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/memory-test.js"],"sourcesContent":["/**\n * Memory Manager Test Module\n * Tests the memory management functionality\n */\n\nexport class MemoryTest {\n constructor(memoryManager, terminal) {\n this.memoryManager = memoryManager;\n this.terminal = terminal;\n }\n\n /**\n * Run comprehensive memory tests\n */\n async runTests() {\n this.terminal.writeInfo('🧪 Starting Memory Manager Tests...');\n\n try {\n await this.testMemoryPanel();\n await this.testMemoryTools();\n await this.testNamespaceOperations();\n await this.testMemoryOperations();\n\n this.terminal.writeSuccess('✅ All memory tests completed successfully!');\n } catch (error) {\n this.terminal.writeError(`❌ Memory tests failed: ${error.message}`);\n }\n }\n\n /**\n * Test memory panel functionality\n */\n async testMemoryPanel() {\n this.terminal.writeInfo('Testing memory panel...');\n\n // Test panel toggle\n this.memoryManager.togglePanel();\n const panelVisible = !document.getElementById('memoryPanel')?.classList.contains('hidden');\n\n if (panelVisible) {\n this.terminal.writeSuccess('✅ Memory panel opens correctly');\n } else {\n throw new Error('Memory panel failed to open');\n }\n\n // Test panel components\n const requiredElements = [\n 'memoryToolsGrid',\n 'namespaceSelect',\n 'memoryTable',\n 'memoryAnalytics',\n 'memoryLog',\n ];\n\n for (const elementId of requiredElements) {\n const element = document.getElementById(elementId);\n if (element) {\n this.terminal.writeSuccess(`✅ ${elementId} component found`);\n } else {\n throw new Error(`Required component missing: ${elementId}`);\n }\n }\n }\n\n /**\n * Test memory tools\n */\n async testMemoryTools() {\n this.terminal.writeInfo('Testing memory tools...');\n\n const tools = Object.keys(this.memoryManager.memoryTools);\n this.terminal.writeInfo(`Found ${tools.length} memory tools:`);\n\n for (const tool of tools) {\n const toolInfo = this.memoryManager.memoryTools[tool];\n this.terminal.writeLine(` ${toolInfo.icon} ${toolInfo.name} - ${toolInfo.description}`);\n }\n\n if (tools.length === 10) {\n this.terminal.writeSuccess('✅ All 10 memory tools are configured');\n } else {\n throw new Error(`Expected 10 memory tools, found ${tools.length}`);\n }\n }\n\n /**\n * Test namespace operations\n */\n async testNamespaceOperations() {\n this.terminal.writeInfo('Testing namespace operations...');\n\n // Test namespace switching\n const originalNamespace = this.memoryManager.currentNamespace;\n\n // Switch to test namespace\n await this.memoryManager.switchNamespace('test');\n\n if (this.memoryManager.currentNamespace === 'test') {\n this.terminal.writeSuccess('✅ Namespace switching works');\n } else {\n throw new Error('Namespace switching failed');\n }\n\n // Switch back to original namespace\n await this.memoryManager.switchNamespace(originalNamespace);\n }\n\n /**\n * Test memory operations\n */\n async testMemoryOperations() {\n this.terminal.writeInfo('Testing memory operations...');\n\n // Test utility functions\n const testData = {\n size: this.memoryManager.formatSize(1024),\n ttl: this.memoryManager.formatTTL(Date.now() + 3600000),\n truncate: this.memoryManager.truncateValue(\n 'This is a very long test string that should be truncated',\n ),\n escape: this.memoryManager.escapeHtml('<script>alert(\"test\")</script>'),\n };\n\n // Validate utility functions\n if (testData.size === '1 KB') {\n this.terminal.writeSuccess('✅ Size formatting works');\n } else {\n throw new Error(`Size formatting failed: ${testData.size}`);\n }\n\n if (testData.ttl.includes('h') && testData.ttl.includes('m')) {\n this.terminal.writeSuccess('✅ TTL formatting works');\n } else {\n throw new Error(`TTL formatting failed: ${testData.ttl}`);\n }\n\n if (testData.truncate.length <= 103) {\n // 100 + '...'\n this.terminal.writeSuccess('✅ Value truncation works');\n } else {\n throw new Error('Value truncation failed');\n }\n\n if (!testData.escape.includes('<script>')) {\n this.terminal.writeSuccess('✅ HTML escaping works');\n } else {\n throw new Error('HTML escaping failed');\n }\n }\n\n /**\n * Test mock memory data\n */\n async testMockData() {\n this.terminal.writeInfo('Testing with mock data...');\n\n const mockEntries = [\n {\n key: 'test/key1',\n value: 'test value 1',\n size: 256,\n ttl: Date.now() + 3600000,\n namespace: 'test',\n },\n {\n key: 'test/key2',\n value: JSON.stringify({ test: 'data', array: [1, 2, 3] }),\n size: 512,\n ttl: nullLine truncated
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/memory-tools.js"],"sourcesContent":["/**\n * Memory & Persistence Tools Panel\n * Provides interface for memory management and persistence operations\n */\n\nimport { EventEmitter } from './event-emitter.js';\n\nexport class MemoryToolsPanel extends EventEmitter {\n constructor(wsClient) {\n super();\n this.wsClient = wsClient;\n this.isInitialized = false;\n this.backupProgress = new Map();\n this.memoryStats = new Map();\n this.activeOperations = new Set();\n this.cacheMetrics = null;\n\n // DOM elements\n this.elements = {};\n\n // Memory tools configuration\n this.memoryTools = {\n // Core memory tools\n memory_backup: { name: 'Memory Backup', category: 'backup', icon: '💾' },\n memory_restore: { name: 'Memory Restore', category: 'backup', icon: '📥' },\n memory_compress: { name: 'Data Compression', category: 'optimization', icon: '🗜️' },\n memory_sync: { name: 'Cross-Instance Sync', category: 'sync', icon: '🔄' },\n\n // Cache management\n cache_manage: { name: 'Cache Management', category: 'cache', icon: '🗂️' },\n cache_optimize: { name: 'Cache Optimization', category: 'cache', icon: '⚡' },\n\n // State management\n state_snapshot: { name: 'State Snapshot', category: 'state', icon: '📸' },\n context_restore: { name: 'Context Recovery', category: 'state', icon: '🔄' },\n\n // Analytics and persistence\n memory_analytics: { name: 'Memory Analytics', category: 'analytics', icon: '📊' },\n memory_persist: { name: 'Session Persistence', category: 'persistence', icon: '🔐' },\n memory_namespace: { name: 'Namespace Manager', category: 'management', icon: '🏷️' },\n\n // Advanced features\n memory_defrag: { name: 'Memory Defragmentation', category: 'optimization', icon: '🧹' },\n memory_encrypt: { name: 'Memory Encryption', category: 'security', icon: '🔒' },\n memory_replicate: { name: 'Memory Replication', category: 'sync', icon: '📋' },\n };\n\n this.categories = {\n backup: { name: 'Backup & Restore', color: '#007acc' },\n optimization: { name: 'Optimization', color: '#ff6b6b' },\n sync: { name: 'Synchronization', color: '#4ecdc4' },\n cache: { name: 'Cache Management', color: '#45b7d1' },\n state: { name: 'State Management', color: '#96ceb4' },\n analytics: { name: 'Analytics', color: '#feca57' },\n persistence: { name: 'Persistence', color: '#ff9ff3' },\n management: { name: 'Management', color: '#a8e6cf' },\n security: { name: 'Security', color: '#ff8b94' },\n };\n }\n\n /**\n * Initialize the memory tools panel\n */\n async init() {\n if (this.isInitialized) return;\n\n try {\n await this.createPanelUI();\n this.setupEventListeners();\n this.setupWebSocketHandlers();\n await this.loadInitialData();\n\n this.isInitialized = true;\n this.emit('initialized');\n } catch (error) {\n console.error('Failed to initialize memory tools panel:', error);\n this.emit('error', error);\n }\n }\n\n /**\n * Create the memory tools panel UI\n */\n async createPanelUI() {\n // Create main panel container\n const panelContainer = document.createElement('div');\n panelContainer.id = 'memoryToolsPanel';\n panelContainer.className = 'memory-panel hidden';\n\n // Create panel header\n const header = this.createPanelHeader();\n panelContainer.appendChild(header);\n\n // Create main content area\n const content = document.createElement('div');\n content.className = 'memory-content';\n\n // Create tabbed interface\n const tabs = this.createTabs();\n content.appendChild(tabs);\n\n // Create tab content areas\n const tabContents = this.createTabContents();\n content.appendChild(tabContents);\n\n panelContainer.appendChild(content);\n\n // Insert into DOM\n const consoleMain = document.querySelector('.console-main');\n if (consoleMain) {\n consoleMain.appendChild(panelContainer);\n }\n\n // Store DOM elements\n this.elements.panel = panelContainer;\n this.elements.header = header;\n this.elements.content = content;\n this.elements.tabs = tabs;\n this.elements.tabContents = tabContents;\n\n // Add toggle button to main header\n this.addToggleButton();\n\n // Get additional DOM references\n this.elements.memoryMetrics = panelContainer.querySelector('#memoryMetrics');\n this.elements.backupList = panelContainer.querySelector('#backupList');\n this.elements.operationProgress = panelContainer.querySelector('#operationProgress');\n this.elements.cacheStats = panelContainer.querySelector('#cacheStats');\n this.elements.analyticsChart = panelContainer.querySelector('#analyticsChart');\n }\n\n /**\n * Create panel header\n */\n createPanelHeader() {\n const header = document.createEleLine truncated
|
||||
@@ -1,548 +0,0 @@
|
||||
import { SwarmVisualizer } from './swarm-visualizer.js';
|
||||
export class RealTimeDashboard {
|
||||
constructor(container, componentLibrary){
|
||||
this.container = container;
|
||||
this.components = componentLibrary;
|
||||
this.swarmVisualizer = null;
|
||||
this.isActive = false;
|
||||
this.updateInterval = null;
|
||||
this.websocket = null;
|
||||
this.metrics = {
|
||||
history: [],
|
||||
current: null
|
||||
};
|
||||
this.init();
|
||||
}
|
||||
init() {
|
||||
this.createDashboardLayout();
|
||||
this.setupWebSocket();
|
||||
this.startMetricsCollection();
|
||||
console.log('📊 Real-time Dashboard initialized');
|
||||
}
|
||||
createDashboardLayout() {
|
||||
const dashboard = document.createElement('div');
|
||||
dashboard.className = 'claude-realtime-dashboard';
|
||||
dashboard.style.cssText = `
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-template-rows: auto 1fr auto;
|
||||
gap: 16px;
|
||||
height: 100vh;
|
||||
padding: 16px;
|
||||
background: #0a0a0a;
|
||||
color: white;
|
||||
`;
|
||||
const header = this.createDashboardHeader();
|
||||
dashboard.appendChild(header);
|
||||
const content = document.createElement('div');
|
||||
content.style.cssText = `
|
||||
grid-column: 1 / -1;
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr;
|
||||
gap: 16px;
|
||||
overflow: hidden;
|
||||
`;
|
||||
const leftPanel = document.createElement('div');
|
||||
leftPanel.className = 'dashboard-left-panel';
|
||||
this.swarmVisualizer = new SwarmVisualizer(leftPanel, this.components);
|
||||
const rightPanel = this.createRightPanel();
|
||||
content.appendChild(leftPanel);
|
||||
content.appendChild(rightPanel);
|
||||
dashboard.appendChild(content);
|
||||
const footer = this.createDashboardFooter();
|
||||
dashboard.appendChild(footer);
|
||||
this.container.appendChild(dashboard);
|
||||
this.elements = {
|
||||
dashboard,
|
||||
header,
|
||||
content,
|
||||
leftPanel,
|
||||
rightPanel,
|
||||
footer
|
||||
};
|
||||
}
|
||||
createDashboardHeader() {
|
||||
const header = document.createElement('div');
|
||||
header.style.cssText = `
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 16px;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
`;
|
||||
const titleSection = document.createElement('div');
|
||||
titleSection.innerHTML = `
|
||||
<h1 style="margin: 0; color: #00d4ff; font-size: 24px;">
|
||||
🌊 Claude Flow Real-Time Dashboard
|
||||
</h1>
|
||||
<p style="margin: 4px 0 0 0; color: #888; font-size: 14px;">
|
||||
Live swarm monitoring and performance analytics
|
||||
</p>
|
||||
`;
|
||||
const controls = document.createElement('div');
|
||||
controls.style.display = 'flex';
|
||||
controls.style.gap = '12px';
|
||||
const startBtn = this.components.createActionButton({
|
||||
type: 'primary',
|
||||
text: 'Start All',
|
||||
icon: '▶️',
|
||||
onclick: ()=>this.startAllMonitoring()
|
||||
});
|
||||
const stopBtn = this.components.createActionButton({
|
||||
type: 'secondary',
|
||||
text: 'Stop All',
|
||||
icon: '⏹️',
|
||||
onclick: ()=>this.stopAllMonitoring()
|
||||
});
|
||||
const exportBtn = this.components.createActionButton({
|
||||
type: 'secondary',
|
||||
text: 'Export Data',
|
||||
icon: '💾',
|
||||
onclick: ()=>this.exportDashboardData()
|
||||
});
|
||||
controls.appendChild(startBtn.element);
|
||||
controls.appendChild(stopBtn.element);
|
||||
controls.appendChild(exportBtn.element);
|
||||
header.appendChild(titleSection);
|
||||
header.appendChild(controls);
|
||||
this.headerElements = {
|
||||
startBtn,
|
||||
stopBtn,
|
||||
exportBtn
|
||||
};
|
||||
return header;
|
||||
}
|
||||
createRightPanel() {
|
||||
const panel = document.createElement('div');
|
||||
panel.style.cssText = `
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
overflow-y: auto;
|
||||
`;
|
||||
const metricsChart = this.createMetricsChart();
|
||||
panel.appendChild(metricsChart);
|
||||
const healthPanel = this.createHealthPanel();
|
||||
panel.appendChild(healthPanel);
|
||||
const memoryChart = this.createMemoryChart();
|
||||
panel.appendChild(memoryChart);
|
||||
const queueStatus = this.createQueueStatus();
|
||||
panel.appendChild(queueStatus);
|
||||
const activityLog = this.createActivityLog();
|
||||
panel.appendChild(activityLog);
|
||||
return panel;
|
||||
}
|
||||
createMetricsChart() {
|
||||
const metricsChart = this.components.createMetricsChart({
|
||||
title: 'Performance Metrics',
|
||||
width: 350,
|
||||
height: 200,
|
||||
type: 'line'
|
||||
});
|
||||
this.updateMetricsChart(metricsChart);
|
||||
this.metricsChart = metricsChart;
|
||||
return metricsChart.element;
|
||||
}
|
||||
createHealthPanel() {
|
||||
const panel = this.components.createInfoPanel({
|
||||
title: '🏥 System Health'
|
||||
});
|
||||
const healthMetrics = [
|
||||
{
|
||||
name: 'CPU Usage',
|
||||
value: '45%',
|
||||
status: 'good'
|
||||
},
|
||||
{
|
||||
name: 'Memory Usage',
|
||||
value: '2.1GB',
|
||||
status: 'good'
|
||||
},
|
||||
{
|
||||
name: 'Network I/O',
|
||||
value: '120 Mbps',
|
||||
status: 'good'
|
||||
},
|
||||
{
|
||||
name: 'Disk Usage',
|
||||
value: '67%',
|
||||
status: 'warning'
|
||||
},
|
||||
{
|
||||
name: 'Response Time',
|
||||
value: '234ms',
|
||||
status: 'good'
|
||||
}
|
||||
];
|
||||
const healthHTML = healthMetrics.map((metric)=>`
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin: 8px 0;">
|
||||
<span>${metric.name}:</span>
|
||||
<span class="health-metric health-${metric.status}" style="
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
font-weight: bold;
|
||||
${metric.status === 'good' ? 'background: #22c55e; color: white;' : metric.status === 'warning' ? 'background: #f59e0b; color: white;' : 'background: #ef4444; color: white;'}
|
||||
">${metric.value}</span>
|
||||
</div>
|
||||
`).join('');
|
||||
panel.setContent(healthHTML);
|
||||
this.healthPanel = panel;
|
||||
return panel.element;
|
||||
}
|
||||
createMemoryChart() {
|
||||
const memoryChart = this.components.createMetricsChart({
|
||||
title: 'Memory Usage Over Time',
|
||||
width: 350,
|
||||
height: 150,
|
||||
type: 'line'
|
||||
});
|
||||
this.updateMemoryChart(memoryChart);
|
||||
this.memoryChart = memoryChart;
|
||||
return memoryChart.element;
|
||||
}
|
||||
createQueueStatus() {
|
||||
const panel = this.components.createInfoPanel({
|
||||
title: '📋 Task Queue Status'
|
||||
});
|
||||
const queueData = {
|
||||
pending: Math.floor(Math.random() * 20),
|
||||
processing: Math.floor(Math.random() * 8),
|
||||
completed: Math.floor(Math.random() * 150) + 50,
|
||||
failed: Math.floor(Math.random() * 5)
|
||||
};
|
||||
const queueHTML = `
|
||||
<div class="queue-stats" style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
|
||||
<div class="queue-stat">
|
||||
<div style="font-size: 24px; font-weight: bold; color: #f59e0b;">${queueData.pending}</div>
|
||||
<div style="color: #888; font-size: 12px;">Pending</div>
|
||||
</div>
|
||||
<div class="queue-stat">
|
||||
<div style="font-size: 24px; font-weight: bold; color: #00d4ff;">${queueData.processing}</div>
|
||||
<div style="color: #888; font-size: 12px;">Processing</div>
|
||||
</div>
|
||||
<div class="queue-stat">
|
||||
<div style="font-size: 24px; font-weight: bold; color: #22c55e;">${queueData.completed}</div>
|
||||
<div style="color: #888; font-size: 12px;">Completed</div>
|
||||
</div>
|
||||
<div class="queue-stat">
|
||||
<div style="font-size: 24px; font-weight: bold; color: #ef4444;">${queueData.failed}</div>
|
||||
<div style="color: #888; font-size: 12px;">Failed</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
panel.setContent(queueHTML);
|
||||
this.queuePanel = panel;
|
||||
return panel.element;
|
||||
}
|
||||
createActivityLog() {
|
||||
const panel = this.components.createInfoPanel({
|
||||
title: '📝 Recent Activity'
|
||||
});
|
||||
const activities = [
|
||||
{
|
||||
time: '14:23:15',
|
||||
type: 'info',
|
||||
message: 'Agent coder_01 completed task #127'
|
||||
},
|
||||
{
|
||||
time: '14:22:58',
|
||||
type: 'success',
|
||||
message: 'Swarm topology optimized (+12% efficiency)'
|
||||
},
|
||||
{
|
||||
time: '14:22:45',
|
||||
type: 'warning',
|
||||
message: 'Agent analyzer_03 high memory usage (89%)'
|
||||
},
|
||||
{
|
||||
time: '14:22:30',
|
||||
type: 'info',
|
||||
message: 'New task assigned to researcher_02'
|
||||
},
|
||||
{
|
||||
time: '14:22:12',
|
||||
type: 'error',
|
||||
message: 'Connection timeout to agent reviewer_01'
|
||||
}
|
||||
];
|
||||
const activityHTML = activities.map((activity)=>`
|
||||
<div class="activity-item" style="
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 8px 0;
|
||||
padding: 8px;
|
||||
background: #2a2a2a;
|
||||
border-radius: 4px;
|
||||
border-left: 3px solid ${activity.type === 'success' ? '#22c55e' : activity.type === 'warning' ? '#f59e0b' : activity.type === 'error' ? '#ef4444' : '#00d4ff'};
|
||||
">
|
||||
<span style="color: #888; font-size: 12px; min-width: 60px;">${activity.time}</span>
|
||||
<span style="font-size: 14px;">${activity.message}</span>
|
||||
</div>
|
||||
`).join('');
|
||||
panel.setContent(`<div style="max-height: 200px; overflow-y: auto;">${activityHTML}</div>`);
|
||||
this.activityPanel = panel;
|
||||
return panel.element;
|
||||
}
|
||||
createDashboardFooter() {
|
||||
const footer = document.createElement('div');
|
||||
footer.style.cssText = `
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
`;
|
||||
const leftStatus = document.createElement('div');
|
||||
leftStatus.innerHTML = `
|
||||
Status: <span id="dashboard-status" style="color: #22c55e;">●</span> Active |
|
||||
Uptime: <span id="dashboard-uptime">00:00:00</span> |
|
||||
Last Update: <span id="dashboard-last-update">Never</span>
|
||||
`;
|
||||
const rightStatus = document.createElement('div');
|
||||
rightStatus.innerHTML = `
|
||||
Total Messages: <span id="dashboard-messages">0</span> |
|
||||
Data Points: <span id="dashboard-data-points">0</span> |
|
||||
Version: Claude Flow v2.0.0
|
||||
`;
|
||||
footer.appendChild(leftStatus);
|
||||
footer.appendChild(rightStatus);
|
||||
this.footerElements = {
|
||||
status: leftStatus.querySelector('#dashboard-status'),
|
||||
uptime: leftStatus.querySelector('#dashboard-uptime'),
|
||||
lastUpdate: leftStatus.querySelector('#dashboard-last-update'),
|
||||
messages: rightStatus.querySelector('#dashboard-messages'),
|
||||
dataPoints: rightStatus.querySelector('#dashboard-data-points')
|
||||
};
|
||||
return footer;
|
||||
}
|
||||
setupWebSocket() {
|
||||
try {
|
||||
const wsUrl = 'ws://localhost:3000/dashboard';
|
||||
this.websocket = new WebSocket(wsUrl);
|
||||
this.websocket.onopen = ()=>{
|
||||
console.log('📡 Dashboard WebSocket connected');
|
||||
this.updateConnectionStatus(true);
|
||||
};
|
||||
this.websocket.onmessage = (event)=>{
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
this.handleWebSocketMessage(data);
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse WebSocket message:', error);
|
||||
}
|
||||
};
|
||||
this.websocket.onclose = ()=>{
|
||||
console.log('📡 Dashboard WebSocket disconnected');
|
||||
this.updateConnectionStatus(false);
|
||||
setTimeout(()=>this.setupWebSocket(), 5000);
|
||||
};
|
||||
this.websocket.onerror = (error)=>{
|
||||
console.error('📡 Dashboard WebSocket error:', error);
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn('WebSocket not available, using polling fallback');
|
||||
this.startPollingFallback();
|
||||
}
|
||||
}
|
||||
handleWebSocketMessage(data) {
|
||||
switch(data.type){
|
||||
case 'swarm_update':
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.swarmData = data.payload;
|
||||
this.swarmVisualizer.processSwarmData();
|
||||
this.swarmVisualizer.updateStats();
|
||||
}
|
||||
break;
|
||||
case 'metrics_update':
|
||||
this.updateMetricsFromData(data.payload);
|
||||
break;
|
||||
case 'health_update':
|
||||
this.updateHealthStatus(data.payload);
|
||||
break;
|
||||
case 'activity_log':
|
||||
this.addActivityLog(data.payload);
|
||||
break;
|
||||
default:
|
||||
console.log('Unknown WebSocket message type:', data.type);
|
||||
}
|
||||
this.updateLastUpdateTime();
|
||||
}
|
||||
startPollingFallback() {
|
||||
this.updateInterval = setInterval(()=>{
|
||||
this.fetchDashboardData();
|
||||
}, 2000);
|
||||
}
|
||||
async fetchDashboardData() {
|
||||
try {
|
||||
const response = await fetch('/api/claude-flow/dashboard/data');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
this.handleDashboardData(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to fetch dashboard data:', error);
|
||||
this.handleDashboardData(this.generateMockDashboardData());
|
||||
}
|
||||
}
|
||||
generateMockDashboardData() {
|
||||
return {
|
||||
swarm: {
|
||||
agents: 6,
|
||||
active: 4,
|
||||
busy: 2,
|
||||
idle: 2,
|
||||
errors: 0
|
||||
},
|
||||
metrics: {
|
||||
cpuUsage: Math.random() * 30 + 20,
|
||||
memoryUsage: Math.random() * 40 + 40,
|
||||
throughput: Math.random() * 50 + 25,
|
||||
latency: Math.random() * 200 + 100
|
||||
},
|
||||
health: {
|
||||
overall: 'good',
|
||||
services: [
|
||||
'swarm',
|
||||
'memory',
|
||||
'neural'
|
||||
].map((service)=>({
|
||||
name: service,
|
||||
status: Math.random() > 0.8 ? 'warning' : 'good'
|
||||
}))
|
||||
}
|
||||
};
|
||||
}
|
||||
updateMetricsFromData(data) {
|
||||
this.metrics.history.push({
|
||||
timestamp: Date.now(),
|
||||
...data
|
||||
});
|
||||
if (this.metrics.history.length > 50) {
|
||||
this.metrics.history.shift();
|
||||
}
|
||||
this.metrics.current = data;
|
||||
this.updateMetricsChart(this.metricsChart);
|
||||
this.updateMemoryChart(this.memoryChart);
|
||||
}
|
||||
updateMetricsChart(chart) {
|
||||
if (!chart || !this.metrics.history.length) return;
|
||||
const data = this.metrics.history.map((point, index)=>({
|
||||
x: index,
|
||||
value: point.throughput || Math.random() * 100
|
||||
}));
|
||||
chart.updateData(data);
|
||||
}
|
||||
updateMemoryChart(chart) {
|
||||
if (!chart || !this.metrics.history.length) return;
|
||||
const data = this.metrics.history.map((point, index)=>({
|
||||
x: index,
|
||||
value: point.memoryUsage || Math.random() * 100
|
||||
}));
|
||||
chart.updateData(data);
|
||||
}
|
||||
startAllMonitoring() {
|
||||
this.isActive = true;
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.startMonitoring();
|
||||
}
|
||||
this.startMetricsCollection();
|
||||
this.headerElements.startBtn.setDisabled(true);
|
||||
this.headerElements.stopBtn.setDisabled(false);
|
||||
this.updateConnectionStatus(true);
|
||||
console.log('🚀 All dashboard monitoring started');
|
||||
}
|
||||
stopAllMonitoring() {
|
||||
this.isActive = false;
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.stopMonitoring();
|
||||
}
|
||||
if (this.updateInterval) {
|
||||
clearInterval(this.updateInterval);
|
||||
this.updateInterval = null;
|
||||
}
|
||||
this.headerElements.startBtn.setDisabled(false);
|
||||
this.headerElements.stopBtn.setDisabled(true);
|
||||
this.updateConnectionStatus(false);
|
||||
console.log('⏹️ All dashboard monitoring stopped');
|
||||
}
|
||||
startMetricsCollection() {
|
||||
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
|
||||
this.startPollingFallback();
|
||||
}
|
||||
}
|
||||
updateConnectionStatus(connected) {
|
||||
if (this.footerElements.status) {
|
||||
this.footerElements.status.style.color = connected ? '#22c55e' : '#ef4444';
|
||||
this.footerElements.status.textContent = connected ? '●' : '●';
|
||||
}
|
||||
}
|
||||
updateLastUpdateTime() {
|
||||
if (this.footerElements.lastUpdate) {
|
||||
this.footerElements.lastUpdate.textContent = new Date().toLocaleTimeString();
|
||||
}
|
||||
}
|
||||
exportDashboardData() {
|
||||
const exportData = {
|
||||
timestamp: Date.now(),
|
||||
metrics: this.metrics,
|
||||
swarmData: this.swarmVisualizer?.swarmData,
|
||||
version: 'Claude Flow v2.0.0'
|
||||
};
|
||||
const blob = new Blob([
|
||||
JSON.stringify(exportData, null, 2)
|
||||
], {
|
||||
type: 'application/json'
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `claude-flow-dashboard-${Date.now()}.json`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
console.log('💾 Dashboard data exported');
|
||||
}
|
||||
async storeProgressToMemory() {
|
||||
const progressData = {
|
||||
dashboardActive: this.isActive,
|
||||
metricsCount: this.metrics.history.length,
|
||||
swarmVisualizerActive: this.swarmVisualizer?.isActive || false,
|
||||
lastUpdate: Date.now(),
|
||||
components: {
|
||||
swarmVisualizer: 'active',
|
||||
metricsChart: 'active',
|
||||
healthPanel: 'active',
|
||||
activityLog: 'active'
|
||||
}
|
||||
};
|
||||
try {
|
||||
console.log('📊 Storing dashboard progress to memory:', progressData);
|
||||
} catch (error) {
|
||||
console.warn('Failed to store progress to memory:', error);
|
||||
}
|
||||
}
|
||||
destroy() {
|
||||
this.stopAllMonitoring();
|
||||
if (this.websocket) {
|
||||
this.websocket.close();
|
||||
}
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.destroy();
|
||||
}
|
||||
if (this.container) {
|
||||
this.container.innerHTML = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
export default RealTimeDashboard;
|
||||
|
||||
//# sourceMappingURL=real-time-dashboard.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/real-time-dashboard.js"],"sourcesContent":["/**\n * RealTimeDashboard - Enhanced real-time monitoring dashboard for Claude Flow swarms\n * Integrates multiple visualization components with live data updates\n */\n\nimport { SwarmVisualizer } from './swarm-visualizer.js';\n\nexport class RealTimeDashboard {\n constructor(container, componentLibrary) {\n this.container = container;\n this.components = componentLibrary;\n this.swarmVisualizer = null;\n this.isActive = false;\n this.updateInterval = null;\n this.websocket = null;\n this.metrics = {\n history: [],\n current: null\n };\n \n this.init();\n }\n\n /**\n * Initialize dashboard\n */\n init() {\n this.createDashboardLayout();\n this.setupWebSocket();\n this.startMetricsCollection();\n console.log('📊 Real-time Dashboard initialized');\n }\n\n /**\n * Create dashboard layout\n */\n createDashboardLayout() {\n // Main dashboard container\n const dashboard = document.createElement('div');\n dashboard.className = 'claude-realtime-dashboard';\n dashboard.style.cssText = `\n display: grid;\n grid-template-columns: 1fr 1fr;\n grid-template-rows: auto 1fr auto;\n gap: 16px;\n height: 100vh;\n padding: 16px;\n background: #0a0a0a;\n color: white;\n `;\n\n // Header with title and controls\n const header = this.createDashboardHeader();\n dashboard.appendChild(header);\n\n // Main content area\n const content = document.createElement('div');\n content.style.cssText = `\n grid-column: 1 / -1;\n display: grid;\n grid-template-columns: 2fr 1fr;\n gap: 16px;\n overflow: hidden;\n `;\n\n // Left panel - Swarm Visualizer\n const leftPanel = document.createElement('div');\n leftPanel.className = 'dashboard-left-panel';\n this.swarmVisualizer = new SwarmVisualizer(leftPanel, this.components);\n\n // Right panel - Metrics and controls\n const rightPanel = this.createRightPanel();\n\n content.appendChild(leftPanel);\n content.appendChild(rightPanel);\n dashboard.appendChild(content);\n\n // Footer with status information\n const footer = this.createDashboardFooter();\n dashboard.appendChild(footer);\n\n this.container.appendChild(dashboard);\n \n this.elements = {\n dashboard,\n header,\n content,\n leftPanel,\n rightPanel,\n footer\n };\n }\n\n /**\n * Create dashboard header\n */\n createDashboardHeader() {\n const header = document.createElement('div');\n header.style.cssText = `\n grid-column: 1 / -1;\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 16px;\n background: #1a1a1a;\n border: 1px solid #444;\n border-radius: 8px;\n `;\n\n // Title and status\n const titleSection = document.createElement('div');\n titleSection.innerHTML = `\n <h1 style=\"margin: 0; color: #00d4ff; font-size: 24px;\">\n 🌊 Claude Flow Real-Time Dashboard\n </h1>\n <p style=\"margin: 4px 0 0 0; color: #888; font-size: 14px;\">\n Live swarm monitoring and performance analytics\n </p>\n `;\n\n // Control buttons\n const controls = document.createElement('div');\n controls.style.display = 'flex';\n controls.style.gap = '12px';\n\n const startBtn = this.components.createActionButton({\n type: 'primary',\n text: 'Start All',\n icon: '▶️',\n onclick: () => this.startAllMonitoring()\n });\n\n const stopBtn = this.components.createActionButton({\n type: 'secondary',\n text: 'Stop All',\n icon: '⏹️',\n onclick: () => this.stopAllMonitoring()\n });\n\n const exportBtn = this.components.createActionButton({\n type: 'secondary',\n text: 'Export Data',\n icon: '💾',\n onclick: () => this.exportDashboardData()\n });\n\n controls.appendChild(startBtn.element);\n controls.appendChild(stopBtn.element);\n controls.appendChild(exportBtn.element);\n\n header.appendChild(titleSection);\n header.appendChild(controls);\n\n this.headerElements = {\n startBtn,\n stopBtn,\n exportBtn\n };\n\n return header;\n }\n\n /**\n * Create right panel with metrics and controls\n */\n createRightPanel() {\n const panel = document.createElement('div');\n panel.style.cssText = `\n display: flex;\n flex-direction: column;\n gap: 16px;\n overflow-y: auto;\n `;\n\n // Performance metrics chart\n const metricsChart = this.createMetricsChart();\n panel.appendChild(metricsChart);\n\n // System health indicators\n const healthPanel = this.createHealthPanel();\n panel.appendChild(healthPanel);\n\n // Memory usage chart\n const memoryChart = this.createMemoryChart();\n panel.appendChild(memoryChart);\n\nLine truncated
|
||||
@@ -1,406 +0,0 @@
|
||||
export class SettingsManager {
|
||||
constructor(){
|
||||
this.settings = this.loadSettings();
|
||||
this.settingsPanel = null;
|
||||
this.isVisible = false;
|
||||
this.defaults = {
|
||||
serverUrl: 'ws://localhost:3000/ws',
|
||||
authToken: '',
|
||||
autoConnect: true,
|
||||
theme: 'dark',
|
||||
fontSize: 14,
|
||||
lineHeight: 1.4,
|
||||
fontFamily: 'JetBrains Mono',
|
||||
autoScroll: true,
|
||||
showTimestamps: true,
|
||||
enableSounds: false,
|
||||
maxLines: 1000,
|
||||
defaultMode: 'coder',
|
||||
swarmStrategy: 'development',
|
||||
coordinationMode: 'centralized',
|
||||
reconnectAttempts: 5,
|
||||
heartbeatInterval: 30000,
|
||||
commandTimeout: 30000
|
||||
};
|
||||
this.settings = {
|
||||
...this.defaults,
|
||||
...this.settings
|
||||
};
|
||||
this.setupEventListeners();
|
||||
}
|
||||
init() {
|
||||
this.settingsPanel = document.getElementById('settingsPanel');
|
||||
this.setupSettingsPanel();
|
||||
this.applySettings();
|
||||
}
|
||||
setupSettingsPanel() {
|
||||
const settingsToggle = document.getElementById('settingsToggle');
|
||||
if (settingsToggle) {
|
||||
settingsToggle.addEventListener('click', ()=>this.toggle());
|
||||
}
|
||||
const closeButton = document.getElementById('closeSettings');
|
||||
if (closeButton) {
|
||||
closeButton.addEventListener('click', ()=>this.hide());
|
||||
}
|
||||
this.setupFormElements();
|
||||
this.setupActionButtons();
|
||||
document.addEventListener('click', (event)=>{
|
||||
if (this.isVisible && !this.settingsPanel.contains(event.target) && !document.getElementById('settingsToggle').contains(event.target)) {
|
||||
this.hide();
|
||||
}
|
||||
});
|
||||
document.addEventListener('keydown', (event)=>{
|
||||
if (event.key === 'Escape' && this.isVisible) {
|
||||
this.hide();
|
||||
}
|
||||
});
|
||||
}
|
||||
setupFormElements() {
|
||||
this.bindSetting('serverUrl', 'input');
|
||||
this.bindSetting('authToken', 'input');
|
||||
this.bindSetting('fontSize', 'change', (value)=>{
|
||||
this.applyFontSize(parseInt(value));
|
||||
});
|
||||
this.bindSetting('theme', 'change', (value)=>{
|
||||
this.applyTheme(value);
|
||||
});
|
||||
this.bindSetting('lineHeight', 'change', (value)=>{
|
||||
this.applyLineHeight(parseFloat(value));
|
||||
});
|
||||
this.bindSetting('autoScroll', 'change', (value)=>{
|
||||
localStorage.setItem('console_auto_scroll', value);
|
||||
});
|
||||
this.bindSetting('showTimestamps', 'change', (value)=>{
|
||||
localStorage.setItem('console_show_timestamps', value);
|
||||
});
|
||||
this.bindSetting('enableSounds', 'change');
|
||||
this.bindSetting('maxLines', 'input', (value)=>{
|
||||
const maxLines = parseInt(value);
|
||||
if (maxLines >= 100 && maxLines <= 10000) {
|
||||
this.emit('max_lines_changed', maxLines);
|
||||
}
|
||||
});
|
||||
this.bindSetting('defaultMode', 'change');
|
||||
this.bindSetting('swarmStrategy', 'change');
|
||||
this.bindSetting('coordinationMode', 'change');
|
||||
}
|
||||
setupActionButtons() {
|
||||
const connectButton = document.getElementById('connectButton');
|
||||
const disconnectButton = document.getElementById('disconnectButton');
|
||||
if (connectButton) {
|
||||
connectButton.addEventListener('click', ()=>{
|
||||
this.emit('connect_requested', {
|
||||
url: this.get('serverUrl'),
|
||||
token: this.get('authToken')
|
||||
});
|
||||
});
|
||||
}
|
||||
if (disconnectButton) {
|
||||
disconnectButton.addEventListener('click', ()=>{
|
||||
this.emit('disconnect_requested');
|
||||
});
|
||||
}
|
||||
const resetButton = document.createElement('button');
|
||||
resetButton.className = 'reset-settings';
|
||||
resetButton.textContent = 'Reset to Defaults';
|
||||
resetButton.addEventListener('click', ()=>{
|
||||
if (confirm('Reset all settings to defaults? This cannot be undone.')) {
|
||||
this.resetToDefaults();
|
||||
}
|
||||
});
|
||||
const settingsContent = document.querySelector('.settings-content');
|
||||
if (settingsContent) {
|
||||
settingsContent.appendChild(resetButton);
|
||||
}
|
||||
}
|
||||
bindSetting(settingName, eventType, callback) {
|
||||
const element = document.getElementById(settingName);
|
||||
if (!element) return;
|
||||
const value = this.get(settingName);
|
||||
if (element.type === 'checkbox') {
|
||||
element.checked = value;
|
||||
} else {
|
||||
element.value = value;
|
||||
}
|
||||
element.addEventListener(eventType, (event)=>{
|
||||
let newValue;
|
||||
if (element.type === 'checkbox') {
|
||||
newValue = element.checked;
|
||||
} else if (element.type === 'number') {
|
||||
newValue = parseFloat(element.value);
|
||||
} else {
|
||||
newValue = element.value;
|
||||
}
|
||||
this.set(settingName, newValue);
|
||||
if (callback) {
|
||||
callback(newValue);
|
||||
}
|
||||
});
|
||||
}
|
||||
show() {
|
||||
if (this.settingsPanel) {
|
||||
this.settingsPanel.classList.add('visible');
|
||||
this.isVisible = true;
|
||||
const firstInput = this.settingsPanel.querySelector('input, select');
|
||||
if (firstInput) {
|
||||
firstInput.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
hide() {
|
||||
if (this.settingsPanel) {
|
||||
this.settingsPanel.classList.remove('visible');
|
||||
this.isVisible = false;
|
||||
}
|
||||
}
|
||||
toggle() {
|
||||
if (this.isVisible) {
|
||||
this.hide();
|
||||
} else {
|
||||
this.show();
|
||||
}
|
||||
}
|
||||
get(key) {
|
||||
return this.settings[key];
|
||||
}
|
||||
set(key, value) {
|
||||
this.settings[key] = value;
|
||||
this.saveSettings();
|
||||
this.emit('setting_changed', {
|
||||
key,
|
||||
value
|
||||
});
|
||||
}
|
||||
getAll() {
|
||||
return {
|
||||
...this.settings
|
||||
};
|
||||
}
|
||||
setAll(newSettings) {
|
||||
this.settings = {
|
||||
...this.settings,
|
||||
...newSettings
|
||||
};
|
||||
this.saveSettings();
|
||||
this.updateFormElements();
|
||||
this.applySettings();
|
||||
}
|
||||
resetToDefaults() {
|
||||
this.settings = {
|
||||
...this.defaults
|
||||
};
|
||||
this.saveSettings();
|
||||
this.updateFormElements();
|
||||
this.applySettings();
|
||||
this.emit('settings_reset');
|
||||
}
|
||||
loadSettings() {
|
||||
try {
|
||||
const stored = localStorage.getItem('claude_console_settings');
|
||||
return stored ? JSON.parse(stored) : {};
|
||||
} catch (error) {
|
||||
console.error('Failed to load settings:', error);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
saveSettings() {
|
||||
try {
|
||||
localStorage.setItem('claude_console_settings', JSON.stringify(this.settings));
|
||||
} catch (error) {
|
||||
console.error('Failed to save settings:', error);
|
||||
}
|
||||
}
|
||||
applySettings() {
|
||||
this.applyTheme(this.get('theme'));
|
||||
this.applyFontSize(this.get('fontSize'));
|
||||
this.applyLineHeight(this.get('lineHeight'));
|
||||
localStorage.setItem('console_auto_scroll', this.get('autoScroll'));
|
||||
localStorage.setItem('console_show_timestamps', this.get('showTimestamps'));
|
||||
}
|
||||
applyTheme(theme) {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
localStorage.setItem('console_theme', theme);
|
||||
}
|
||||
applyFontSize(fontSize) {
|
||||
document.documentElement.style.setProperty('--font-size-base', `${fontSize}px`);
|
||||
}
|
||||
applyLineHeight(lineHeight) {
|
||||
document.documentElement.style.setProperty('--line-height', lineHeight);
|
||||
}
|
||||
updateFormElements() {
|
||||
Object.keys(this.settings).forEach((key)=>{
|
||||
const element = document.getElementById(key);
|
||||
if (element) {
|
||||
if (element.type === 'checkbox') {
|
||||
element.checked = this.get(key);
|
||||
} else {
|
||||
element.value = this.get(key);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
exportSettings() {
|
||||
const exportData = {
|
||||
timestamp: new Date().toISOString(),
|
||||
version: '1.0.0',
|
||||
settings: this.getAll()
|
||||
};
|
||||
const blob = new Blob([
|
||||
JSON.stringify(exportData, null, 2)
|
||||
], {
|
||||
type: 'application/json'
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `claude-console-settings-${Date.now()}.json`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
async importSettings(file) {
|
||||
try {
|
||||
const text = await file.text();
|
||||
const data = JSON.parse(text);
|
||||
if (data.settings) {
|
||||
this.setAll(data.settings);
|
||||
return true;
|
||||
} else {
|
||||
throw new Error('Invalid settings file format');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to import settings:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
validateSetting(key, value) {
|
||||
const validators = {
|
||||
fontSize: (v)=>v >= 10 && v <= 24,
|
||||
lineHeight: (v)=>v >= 1.0 && v <= 2.0,
|
||||
maxLines: (v)=>v >= 100 && v <= 10000,
|
||||
theme: (v)=>[
|
||||
'dark',
|
||||
'light',
|
||||
'classic',
|
||||
'matrix'
|
||||
].includes(v),
|
||||
defaultMode: (v)=>[
|
||||
'coder',
|
||||
'architect',
|
||||
'analyst',
|
||||
'researcher',
|
||||
'reviewer',
|
||||
'tester',
|
||||
'debugger',
|
||||
'documenter',
|
||||
'optimizer',
|
||||
'designer'
|
||||
].includes(v),
|
||||
swarmStrategy: (v)=>[
|
||||
'development',
|
||||
'research',
|
||||
'analysis',
|
||||
'testing',
|
||||
'optimization',
|
||||
'maintenance'
|
||||
].includes(v),
|
||||
coordinationMode: (v)=>[
|
||||
'centralized',
|
||||
'hierarchical',
|
||||
'distributed',
|
||||
'mesh',
|
||||
'hybrid'
|
||||
].includes(v)
|
||||
};
|
||||
const validator = validators[key];
|
||||
return validator ? validator(value) : true;
|
||||
}
|
||||
updateConnectionStatus(status) {
|
||||
const connectButton = document.getElementById('connectButton');
|
||||
const disconnectButton = document.getElementById('disconnectButton');
|
||||
if (connectButton && disconnectButton) {
|
||||
if (status.connected) {
|
||||
connectButton.disabled = true;
|
||||
disconnectButton.disabled = false;
|
||||
} else {
|
||||
connectButton.disabled = false;
|
||||
disconnectButton.disabled = true;
|
||||
}
|
||||
}
|
||||
this.updateConnectionInfo(status);
|
||||
}
|
||||
updateConnectionInfo(status) {
|
||||
let infoElement = document.getElementById('connectionInfo');
|
||||
if (!infoElement) {
|
||||
infoElement = document.createElement('div');
|
||||
infoElement.id = 'connectionInfo';
|
||||
infoElement.className = 'connection-info';
|
||||
const connectionSection = document.querySelector('.setting-group');
|
||||
if (connectionSection) {
|
||||
connectionSection.appendChild(infoElement);
|
||||
}
|
||||
}
|
||||
const statusClass = status.connected ? 'connected' : status.connecting ? 'connecting' : 'disconnected';
|
||||
infoElement.className = `connection-info ${statusClass}`;
|
||||
const title = status.connected ? 'Connected' : status.connecting ? 'Connecting...' : 'Disconnected';
|
||||
const details = status.connected ? `Connected to ${status.url}\nPending requests: ${status.pendingRequests}\nQueued messages: ${status.queuedMessages}` : status.connecting ? `Attempting to connect to ${status.url}` : status.reconnectAttempts > 0 ? `Disconnected. Reconnect attempts: ${status.reconnectAttempts}` : 'Not connected';
|
||||
infoElement.innerHTML = `
|
||||
<div class="connection-info-title">${title}</div>
|
||||
<div class="connection-info-details">${details}</div>
|
||||
`;
|
||||
}
|
||||
setupEventListeners() {
|
||||
if (window.matchMedia) {
|
||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
mediaQuery.addEventListener('change', (e)=>{
|
||||
if (this.get('theme') === 'auto') {
|
||||
this.applyTheme(e.matches ? 'dark' : 'light');
|
||||
}
|
||||
});
|
||||
}
|
||||
window.addEventListener('resize', ()=>{
|
||||
this.applyFontSize(this.get('fontSize'));
|
||||
});
|
||||
}
|
||||
on(event, callback) {
|
||||
if (!this.eventListeners) {
|
||||
this.eventListeners = new Map();
|
||||
}
|
||||
if (!this.eventListeners.has(event)) {
|
||||
this.eventListeners.set(event, []);
|
||||
}
|
||||
this.eventListeners.get(event).push(callback);
|
||||
}
|
||||
emit(event, data) {
|
||||
if (!this.eventListeners || !this.eventListeners.has(event)) {
|
||||
return;
|
||||
}
|
||||
this.eventListeners.get(event).forEach((callback)=>{
|
||||
try {
|
||||
callback(data);
|
||||
} catch (error) {
|
||||
console.error('Error in settings event listener:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
getClaudeFlowConfig() {
|
||||
return {
|
||||
defaultMode: this.get('defaultMode'),
|
||||
swarmStrategy: this.get('swarmStrategy'),
|
||||
coordinationMode: this.get('coordinationMode')
|
||||
};
|
||||
}
|
||||
getConnectionConfig() {
|
||||
return {
|
||||
url: this.get('serverUrl'),
|
||||
token: this.get('authToken'),
|
||||
autoConnect: this.get('autoConnect'),
|
||||
reconnectAttempts: this.get('reconnectAttempts'),
|
||||
heartbeatInterval: this.get('heartbeatInterval'),
|
||||
commandTimeout: this.get('commandTimeout')
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=settings.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/settings.js"],"sourcesContent":["/**\n * Settings Manager for Claude Code Console\n * Handles configuration and preferences\n */\n\nexport class SettingsManager {\n constructor() {\n this.settings = this.loadSettings();\n this.settingsPanel = null;\n this.isVisible = false;\n\n // Default settings\n this.defaults = {\n // Connection settings\n serverUrl: 'ws://localhost:3000/ws',\n authToken: '',\n autoConnect: true,\n\n // Appearance settings\n theme: 'dark',\n fontSize: 14,\n lineHeight: 1.4,\n fontFamily: 'JetBrains Mono',\n\n // Behavior settings\n autoScroll: true,\n showTimestamps: true,\n enableSounds: false,\n maxLines: 1000,\n\n // Claude Flow settings\n defaultMode: 'coder',\n swarmStrategy: 'development',\n coordinationMode: 'centralized',\n\n // Advanced settings\n reconnectAttempts: 5,\n heartbeatInterval: 30000,\n commandTimeout: 30000,\n };\n\n // Merge defaults with loaded settings\n this.settings = { ...this.defaults, ...this.settings };\n\n this.setupEventListeners();\n }\n\n /**\n * Initialize settings panel\n */\n init() {\n this.settingsPanel = document.getElementById('settingsPanel');\n this.setupSettingsPanel();\n this.applySettings();\n }\n\n /**\n * Setup settings panel event listeners\n */\n setupSettingsPanel() {\n // Toggle button\n const settingsToggle = document.getElementById('settingsToggle');\n if (settingsToggle) {\n settingsToggle.addEventListener('click', () => this.toggle());\n }\n\n // Close button\n const closeButton = document.getElementById('closeSettings');\n if (closeButton) {\n closeButton.addEventListener('click', () => this.hide());\n }\n\n // Settings form elements\n this.setupFormElements();\n\n // Action buttons\n this.setupActionButtons();\n\n // Click outside to close\n document.addEventListener('click', (event) => {\n if (\n this.isVisible &&\n !this.settingsPanel.contains(event.target) &&\n !document.getElementById('settingsToggle').contains(event.target)\n ) {\n this.hide();\n }\n });\n\n // ESC key to close\n document.addEventListener('keydown', (event) => {\n if (event.key === 'Escape' && this.isVisible) {\n this.hide();\n }\n });\n }\n\n /**\n * Setup form element listeners\n */\n setupFormElements() {\n // Connection settings\n this.bindSetting('serverUrl', 'input');\n this.bindSetting('authToken', 'input');\n\n // Appearance settings\n this.bindSetting('fontSize', 'change', (value) => {\n this.applyFontSize(parseInt(value));\n });\n\n this.bindSetting('theme', 'change', (value) => {\n this.applyTheme(value);\n });\n\n this.bindSetting('lineHeight', 'change', (value) => {\n this.applyLineHeight(parseFloat(value));\n });\n\n // Behavior settings\n this.bindSetting('autoScroll', 'change', (value) => {\n localStorage.setItem('console_auto_scroll', value);\n });\n\n this.bindSetting('showTimestamps', 'change', (value) => {\n localStorage.setItem('console_show_timestamps', value);\n });\n\n this.bindSetting('enableSounds', 'change');\n\n this.bindSetting('maxLines', 'input', (value) => {\n const maxLines = parseInt(value);\n if (maxLines >= 100 && maxLines <= 10000) {\n this.emit('max_lines_changed', maxLines);\n }\n });\n\n // Claude Flow settings\n this.bindSetting('defaultMode', 'change');\n this.bindSetting('swarmStrategy', 'change');\n this.bindSetting('coordinationMode', 'change');\n }\n\n /**\n * Setup action buttons\n */\n setupActionButtons() {\n const connectButton = document.getElementById('connectButton');\n const disconnectButton = document.getElementById('disconnectButton');\n\n if (connectButton) {\n connectButton.addEventListener('click', () => {\n this.emit('connect_requested', {\n url: this.get('serverUrl'),\n token: this.get('authToken'),\n });\n });\n }\n\n if (disconnectButton) {\n disconnectButton.addEventListener('click', () => {\n this.emit('disconnect_requested');\n });\n }\n\n // Add reset button\n const resetButton = document.createElement('button');\n resetButton.className = 'reset-settings';\n resetButton.textContent = 'Reset to Defaults';\n resetButton.addEventListener('click', () => {\n if (confirm('Reset all settings to defaults? This cannot be undone.')) {\n this.resetToDefaults();\n }\n });\n\n const settingsContent = document.querySelector('.settings-content');\n if (settingsContent) {\n settingsContent.appendChild(resetButton);\n }\n }\n\n /**\n * Bind setting to form element\n */\n bindSetting(settingName, eventType, callback)Line truncated
|
||||
@@ -1,359 +0,0 @@
|
||||
import { SwarmVisualizer } from './swarm-visualizer.js';
|
||||
import { RealTimeDashboard } from './real-time-dashboard.js';
|
||||
import ComponentLibrary from '../web-ui/components/ComponentLibrary.js';
|
||||
export class SwarmIntegration {
|
||||
constructor(consoleInstance){
|
||||
this.console = consoleInstance;
|
||||
this.components = new ComponentLibrary();
|
||||
this.swarmVisualizer = null;
|
||||
this.dashboard = null;
|
||||
this.isSwarmMode = false;
|
||||
this.init();
|
||||
}
|
||||
init() {
|
||||
this.components.initialize();
|
||||
this.addSwarmCommands();
|
||||
this.addSwarmUI();
|
||||
this.setupSwarmEventHandlers();
|
||||
console.log('🔗 Swarm Integration initialized');
|
||||
}
|
||||
addSwarmCommands() {
|
||||
const swarmCommands = {
|
||||
'swarm': {
|
||||
description: 'Enter swarm visualization mode',
|
||||
handler: ()=>this.enterSwarmMode(),
|
||||
usage: 'swarm'
|
||||
},
|
||||
'swarm-status': {
|
||||
description: 'Show current swarm status',
|
||||
handler: ()=>this.showSwarmStatus(),
|
||||
usage: 'swarm-status'
|
||||
},
|
||||
'swarm-monitor': {
|
||||
description: 'Start real-time swarm monitoring',
|
||||
handler: (args)=>this.startSwarmMonitoring(args),
|
||||
usage: 'swarm-monitor [topology]'
|
||||
},
|
||||
'swarm-stop': {
|
||||
description: 'Stop swarm monitoring',
|
||||
handler: ()=>this.stopSwarmMonitoring(),
|
||||
usage: 'swarm-stop'
|
||||
},
|
||||
'dashboard': {
|
||||
description: 'Open real-time dashboard',
|
||||
handler: ()=>this.openDashboard(),
|
||||
usage: 'dashboard'
|
||||
},
|
||||
'agents': {
|
||||
description: 'List active agents',
|
||||
handler: ()=>this.listAgents(),
|
||||
usage: 'agents'
|
||||
},
|
||||
'topology': {
|
||||
description: 'Change swarm topology',
|
||||
handler: (args)=>this.changeTopology(args),
|
||||
usage: 'topology [mesh|hierarchical|ring|star]'
|
||||
}
|
||||
};
|
||||
if (this.console.commandHandler) {
|
||||
Object.entries(swarmCommands).forEach(([command, config])=>{
|
||||
this.console.commandHandler.registerCommand(command, config);
|
||||
});
|
||||
}
|
||||
}
|
||||
addSwarmUI() {
|
||||
const headerRight = document.querySelector('.header-right');
|
||||
if (headerRight) {
|
||||
const swarmToggle = this.components.createActionButton({
|
||||
type: 'secondary',
|
||||
text: 'Swarm Mode',
|
||||
icon: '🌊',
|
||||
onclick: ()=>this.toggleSwarmMode()
|
||||
});
|
||||
headerRight.insertBefore(swarmToggle.element, headerRight.firstChild);
|
||||
this.swarmToggleButton = swarmToggle;
|
||||
}
|
||||
const statusLeft = document.querySelector('.status-left');
|
||||
if (statusLeft) {
|
||||
const swarmStatus = document.createElement('span');
|
||||
swarmStatus.className = 'status-item';
|
||||
swarmStatus.id = 'swarm-status';
|
||||
swarmStatus.textContent = 'Swarm: Inactive';
|
||||
statusLeft.appendChild(swarmStatus);
|
||||
this.swarmStatusElement = swarmStatus;
|
||||
}
|
||||
}
|
||||
setupSwarmEventHandlers() {
|
||||
if (this.console.wsClient) {
|
||||
this.console.wsClient.on('swarm_update', (data)=>{
|
||||
this.handleSwarmUpdate(data);
|
||||
});
|
||||
this.console.wsClient.on('agent_status', (data)=>{
|
||||
this.handleAgentStatus(data);
|
||||
});
|
||||
}
|
||||
if (this.console.terminal) {
|
||||
this.console.terminal.on('command', (command)=>{
|
||||
if (command.startsWith('swarm')) {
|
||||
this.handleSwarmCommand(command);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
enterSwarmMode() {
|
||||
if (this.isSwarmMode) {
|
||||
this.console.terminal.writeWarning('Already in swarm mode');
|
||||
return;
|
||||
}
|
||||
this.isSwarmMode = true;
|
||||
const swarmContainer = document.createElement('div');
|
||||
swarmContainer.id = 'swarm-visualization-container';
|
||||
swarmContainer.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: rgba(0, 0, 0, 0.95);
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
`;
|
||||
const closeButton = this.components.createActionButton({
|
||||
type: 'secondary',
|
||||
text: 'Exit Swarm Mode',
|
||||
icon: '❌',
|
||||
onclick: ()=>this.exitSwarmMode()
|
||||
});
|
||||
closeButton.element.style.cssText = `
|
||||
position: absolute;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 10001;
|
||||
`;
|
||||
swarmContainer.appendChild(closeButton.element);
|
||||
const visualizerContainer = document.createElement('div');
|
||||
visualizerContainer.style.cssText = `
|
||||
flex: 1;
|
||||
padding: 80px 20px 20px 20px;
|
||||
overflow: auto;
|
||||
`;
|
||||
this.swarmVisualizer = new SwarmVisualizer(visualizerContainer, this.components);
|
||||
swarmContainer.appendChild(visualizerContainer);
|
||||
document.body.appendChild(swarmContainer);
|
||||
this.swarmContainer = swarmContainer;
|
||||
this.updateSwarmStatus('Active');
|
||||
this.swarmToggleButton.setText('Exit Swarm');
|
||||
this.console.terminal.writeSuccess('Entered swarm visualization mode');
|
||||
this.console.terminal.writeInfo('Use "swarm-monitor" to start real-time monitoring');
|
||||
}
|
||||
exitSwarmMode() {
|
||||
if (!this.isSwarmMode) return;
|
||||
this.isSwarmMode = false;
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.destroy();
|
||||
this.swarmVisualizer = null;
|
||||
}
|
||||
if (this.swarmContainer) {
|
||||
this.swarmContainer.remove();
|
||||
this.swarmContainer = null;
|
||||
}
|
||||
this.updateSwarmStatus('Inactive');
|
||||
this.swarmToggleButton.setText('Swarm Mode');
|
||||
this.console.terminal.writeInfo('Exited swarm visualization mode');
|
||||
}
|
||||
toggleSwarmMode() {
|
||||
if (this.isSwarmMode) {
|
||||
this.exitSwarmMode();
|
||||
} else {
|
||||
this.enterSwarmMode();
|
||||
}
|
||||
}
|
||||
showSwarmStatus() {
|
||||
this.console.terminal.writeInfo('📊 Swarm Status:');
|
||||
const status = {
|
||||
active: this.isSwarmMode,
|
||||
agents: Math.floor(Math.random() * 8) + 2,
|
||||
topology: 'mesh',
|
||||
uptime: '2h 34m',
|
||||
tasksCompleted: Math.floor(Math.random() * 100) + 50,
|
||||
averageResponseTime: Math.floor(Math.random() * 500) + 200
|
||||
};
|
||||
this.console.terminal.write(` Mode: ${status.active ? 'Active' : 'Inactive'}`, 'info');
|
||||
this.console.terminal.write(` Agents: ${status.agents}`, 'info');
|
||||
this.console.terminal.write(` Topology: ${status.topology}`, 'info');
|
||||
this.console.terminal.write(` Uptime: ${status.uptime}`, 'info');
|
||||
this.console.terminal.write(` Tasks Completed: ${status.tasksCompleted}`, 'info');
|
||||
this.console.terminal.write(` Avg Response Time: ${status.averageResponseTime}ms`, 'info');
|
||||
}
|
||||
startSwarmMonitoring(args) {
|
||||
if (!this.swarmVisualizer) {
|
||||
this.console.terminal.writeError('Not in swarm mode. Use "swarm" command first.');
|
||||
return;
|
||||
}
|
||||
const topology = args && args[0] ? args[0] : 'mesh';
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.topology = topology;
|
||||
this.swarmVisualizer.startMonitoring();
|
||||
}
|
||||
this.console.terminal.writeSuccess(`Started swarm monitoring with ${topology} topology`);
|
||||
}
|
||||
stopSwarmMonitoring() {
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.stopMonitoring();
|
||||
this.console.terminal.writeInfo('Stopped swarm monitoring');
|
||||
} else {
|
||||
this.console.terminal.writeWarning('Swarm monitoring not active');
|
||||
}
|
||||
}
|
||||
openDashboard() {
|
||||
if (this.dashboard) {
|
||||
this.console.terminal.writeWarning('Dashboard already open');
|
||||
return;
|
||||
}
|
||||
const dashboardContainer = document.createElement('div');
|
||||
dashboardContainer.id = 'dashboard-container';
|
||||
dashboardContainer.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: rgba(0, 0, 0, 0.98);
|
||||
z-index: 20000;
|
||||
`;
|
||||
const closeButton = this.components.createActionButton({
|
||||
type: 'secondary',
|
||||
text: 'Close Dashboard',
|
||||
icon: '❌',
|
||||
onclick: ()=>this.closeDashboard()
|
||||
});
|
||||
closeButton.element.style.cssText = `
|
||||
position: absolute;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 20001;
|
||||
`;
|
||||
dashboardContainer.appendChild(closeButton.element);
|
||||
this.dashboard = new RealTimeDashboard(dashboardContainer, this.components);
|
||||
document.body.appendChild(dashboardContainer);
|
||||
this.dashboardContainer = dashboardContainer;
|
||||
this.console.terminal.writeSuccess('Opened real-time dashboard');
|
||||
}
|
||||
closeDashboard() {
|
||||
if (this.dashboard) {
|
||||
this.dashboard.destroy();
|
||||
this.dashboard = null;
|
||||
}
|
||||
if (this.dashboardContainer) {
|
||||
this.dashboardContainer.remove();
|
||||
this.dashboardContainer = null;
|
||||
}
|
||||
this.console.terminal.writeInfo('Closed dashboard');
|
||||
}
|
||||
listAgents() {
|
||||
this.console.terminal.writeInfo('🤖 Active Agents:');
|
||||
const agents = [
|
||||
{
|
||||
id: 'coder_01',
|
||||
type: 'coder',
|
||||
status: 'active',
|
||||
task: 'Implementing API endpoints'
|
||||
},
|
||||
{
|
||||
id: 'researcher_02',
|
||||
type: 'researcher',
|
||||
status: 'busy',
|
||||
task: 'Analyzing data patterns'
|
||||
},
|
||||
{
|
||||
id: 'reviewer_03',
|
||||
type: 'reviewer',
|
||||
status: 'idle',
|
||||
task: null
|
||||
},
|
||||
{
|
||||
id: 'tester_04',
|
||||
type: 'tester',
|
||||
status: 'active',
|
||||
task: 'Running test suite'
|
||||
}
|
||||
];
|
||||
agents.forEach((agent)=>{
|
||||
const statusColor = agent.status === 'active' ? 'success' : agent.status === 'busy' ? 'warning' : 'info';
|
||||
const taskText = agent.task ? ` | Task: ${agent.task}` : ' | No active task';
|
||||
this.console.terminal.write(` ${agent.id} (${agent.type}) - ${agent.status}${taskText}`, statusColor);
|
||||
});
|
||||
}
|
||||
changeTopology(args) {
|
||||
if (!args || args.length === 0) {
|
||||
this.console.terminal.writeError('Usage: topology [mesh|hierarchical|ring|star]');
|
||||
return;
|
||||
}
|
||||
const topology = args[0];
|
||||
const validTopologies = [
|
||||
'mesh',
|
||||
'hierarchical',
|
||||
'ring',
|
||||
'star'
|
||||
];
|
||||
if (!validTopologies.includes(topology)) {
|
||||
this.console.terminal.writeError(`Invalid topology. Valid options: ${validTopologies.join(', ')}`);
|
||||
return;
|
||||
}
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.topology = topology;
|
||||
this.swarmVisualizer.redrawTopology();
|
||||
this.console.terminal.writeSuccess(`Changed topology to ${topology}`);
|
||||
} else {
|
||||
this.console.terminal.writeWarning('Swarm visualizer not active');
|
||||
}
|
||||
}
|
||||
handleSwarmUpdate(data) {
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.swarmData = data;
|
||||
this.swarmVisualizer.processSwarmData();
|
||||
this.swarmVisualizer.updateStats();
|
||||
}
|
||||
if (this.dashboard) {
|
||||
this.dashboard.handleWebSocketMessage({
|
||||
type: 'swarm_update',
|
||||
payload: data
|
||||
});
|
||||
}
|
||||
}
|
||||
handleAgentStatus(data) {
|
||||
if (data.active !== undefined) {
|
||||
this.updateSwarmStatus(`${data.active} agents active`);
|
||||
}
|
||||
}
|
||||
updateSwarmStatus(status) {
|
||||
if (this.swarmStatusElement) {
|
||||
this.swarmStatusElement.textContent = `Swarm: ${status}`;
|
||||
}
|
||||
}
|
||||
handleSwarmCommand(command) {
|
||||
console.log('Swarm command processed:', command);
|
||||
}
|
||||
getStatus() {
|
||||
return {
|
||||
swarmMode: this.isSwarmMode,
|
||||
visualizerActive: this.swarmVisualizer?.isActive || false,
|
||||
dashboardOpen: !!this.dashboard,
|
||||
componentsLoaded: this.components.isInitialized
|
||||
};
|
||||
}
|
||||
destroy() {
|
||||
this.exitSwarmMode();
|
||||
this.closeDashboard();
|
||||
if (this.swarmToggleButton) {
|
||||
this.swarmToggleButton.element.remove();
|
||||
}
|
||||
if (this.swarmStatusElement) {
|
||||
this.swarmStatusElement.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
export default SwarmIntegration;
|
||||
|
||||
//# sourceMappingURL=swarm-integration.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/swarm-integration.js"],"sourcesContent":["/**\n * SwarmIntegration - Integrates swarm visualizer with existing console\n * Adds swarm monitoring commands and UI elements to the Claude Flow console\n */\n\nimport { SwarmVisualizer } from './swarm-visualizer.js';\nimport { RealTimeDashboard } from './real-time-dashboard.js';\nimport ComponentLibrary from '../web-ui/components/ComponentLibrary.js';\n\nexport class SwarmIntegration {\n constructor(consoleInstance) {\n this.console = consoleInstance;\n this.components = new ComponentLibrary();\n this.swarmVisualizer = null;\n this.dashboard = null;\n this.isSwarmMode = false;\n \n this.init();\n }\n\n /**\n * Initialize swarm integration\n */\n init() {\n this.components.initialize();\n this.addSwarmCommands();\n this.addSwarmUI();\n this.setupSwarmEventHandlers();\n console.log('🔗 Swarm Integration initialized');\n }\n\n /**\n * Add swarm-specific commands to the console\n */\n addSwarmCommands() {\n const swarmCommands = {\n 'swarm': {\n description: 'Enter swarm visualization mode',\n handler: () => this.enterSwarmMode(),\n usage: 'swarm'\n },\n 'swarm-status': {\n description: 'Show current swarm status',\n handler: () => this.showSwarmStatus(),\n usage: 'swarm-status'\n },\n 'swarm-monitor': {\n description: 'Start real-time swarm monitoring',\n handler: (args) => this.startSwarmMonitoring(args),\n usage: 'swarm-monitor [topology]'\n },\n 'swarm-stop': {\n description: 'Stop swarm monitoring',\n handler: () => this.stopSwarmMonitoring(),\n usage: 'swarm-stop'\n },\n 'dashboard': {\n description: 'Open real-time dashboard',\n handler: () => this.openDashboard(),\n usage: 'dashboard'\n },\n 'agents': {\n description: 'List active agents',\n handler: () => this.listAgents(),\n usage: 'agents'\n },\n 'topology': {\n description: 'Change swarm topology',\n handler: (args) => this.changeTopology(args),\n usage: 'topology [mesh|hierarchical|ring|star]'\n }\n };\n\n // Register commands with the console's command handler\n if (this.console.commandHandler) {\n Object.entries(swarmCommands).forEach(([command, config]) => {\n this.console.commandHandler.registerCommand(command, config);\n });\n }\n }\n\n /**\n * Add swarm UI elements to the console\n */\n addSwarmUI() {\n // Add swarm mode toggle to header\n const headerRight = document.querySelector('.header-right');\n if (headerRight) {\n const swarmToggle = this.components.createActionButton({\n type: 'secondary',\n text: 'Swarm Mode',\n icon: '🌊',\n onclick: () => this.toggleSwarmMode()\n });\n \n headerRight.insertBefore(swarmToggle.element, headerRight.firstChild);\n this.swarmToggleButton = swarmToggle;\n }\n\n // Add swarm status to status bar\n const statusLeft = document.querySelector('.status-left');\n if (statusLeft) {\n const swarmStatus = document.createElement('span');\n swarmStatus.className = 'status-item';\n swarmStatus.id = 'swarm-status';\n swarmStatus.textContent = 'Swarm: Inactive';\n statusLeft.appendChild(swarmStatus);\n this.swarmStatusElement = swarmStatus;\n }\n }\n\n /**\n * Setup event handlers for swarm integration\n */\n setupSwarmEventHandlers() {\n // Listen for swarm-related WebSocket messages\n if (this.console.wsClient) {\n this.console.wsClient.on('swarm_update', (data) => {\n this.handleSwarmUpdate(data);\n });\n\n this.console.wsClient.on('agent_status', (data) => {\n this.handleAgentStatus(data);\n });\n }\n\n // Listen for console commands\n if (this.console.terminal) {\n this.console.terminal.on('command', (command) => {\n if (command.startsWith('swarm')) {\n this.handleSwarmCommand(command);\n }\n });\n }\n }\n\n /**\n * Enter swarm visualization mode\n */\n enterSwarmMode() {\n if (this.isSwarmMode) {\n this.console.terminal.writeWarning('Already in swarm mode');\n return;\n }\n\n this.isSwarmMode = true;\n \n // Create swarm container\n const swarmContainer = document.createElement('div');\n swarmContainer.id = 'swarm-visualization-container';\n swarmContainer.style.cssText = `\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: rgba(0, 0, 0, 0.95);\n z-index: 10000;\n display: flex;\n flex-direction: column;\n `;\n\n // Create close button\n const closeButton = this.components.createActionButton({\n type: 'secondary',\n text: 'Exit Swarm Mode',\n icon: '❌',\n onclLine truncated
|
||||
@@ -1,661 +0,0 @@
|
||||
export class SwarmVisualizer {
|
||||
constructor(container, componentLibrary){
|
||||
this.container = container;
|
||||
this.components = componentLibrary;
|
||||
this.swarmData = null;
|
||||
this.agents = new Map();
|
||||
this.connections = new Map();
|
||||
this.topology = 'mesh';
|
||||
this.updateInterval = null;
|
||||
this.isActive = false;
|
||||
this.canvas = null;
|
||||
this.ctx = null;
|
||||
this.canvasSize = {
|
||||
width: 800,
|
||||
height: 600
|
||||
};
|
||||
this.animationFrame = null;
|
||||
this.particles = [];
|
||||
this.init();
|
||||
}
|
||||
init() {
|
||||
this.createUI();
|
||||
this.setupEventHandlers();
|
||||
console.log('🌊 Swarm Visualizer initialized');
|
||||
}
|
||||
createUI() {
|
||||
const mainPanel = this.components.createToolPanel({
|
||||
title: 'Swarm Visualizer',
|
||||
description: 'Real-time swarm topology and agent monitoring'
|
||||
});
|
||||
const controlPanel = this.createControlPanel();
|
||||
mainPanel.append(controlPanel);
|
||||
const statsPanel = this.createStatsPanel();
|
||||
mainPanel.append(statsPanel);
|
||||
const canvasContainer = this.createTopologyCanvas();
|
||||
mainPanel.append(canvasContainer);
|
||||
const agentPanel = this.createAgentPanel();
|
||||
mainPanel.append(agentPanel);
|
||||
this.container.appendChild(mainPanel.element);
|
||||
this.elements = {
|
||||
mainPanel,
|
||||
controlPanel,
|
||||
statsPanel,
|
||||
canvasContainer,
|
||||
agentPanel
|
||||
};
|
||||
}
|
||||
createControlPanel() {
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'swarm-control-panel';
|
||||
const startBtn = this.components.createActionButton({
|
||||
type: 'primary',
|
||||
text: 'Start Monitoring',
|
||||
icon: '▶️',
|
||||
onclick: ()=>this.startMonitoring()
|
||||
});
|
||||
const stopBtn = this.components.createActionButton({
|
||||
type: 'secondary',
|
||||
text: 'Stop',
|
||||
icon: '⏹️',
|
||||
onclick: ()=>this.stopMonitoring()
|
||||
});
|
||||
const topologySelect = document.createElement('select');
|
||||
topologySelect.id = 'topology-selector';
|
||||
topologySelect.innerHTML = `
|
||||
<option value="mesh">Mesh Network</option>
|
||||
<option value="hierarchical">Hierarchical</option>
|
||||
<option value="ring">Ring Topology</option>
|
||||
<option value="star">Star Network</option>
|
||||
`;
|
||||
topologySelect.addEventListener('change', (e)=>{
|
||||
this.topology = e.target.value;
|
||||
this.redrawTopology();
|
||||
});
|
||||
const refreshSelect = document.createElement('select');
|
||||
refreshSelect.id = 'refresh-rate';
|
||||
refreshSelect.innerHTML = `
|
||||
<option value="1000">1 second</option>
|
||||
<option value="2000" selected>2 seconds</option>
|
||||
<option value="5000">5 seconds</option>
|
||||
<option value="10000">10 seconds</option>
|
||||
`;
|
||||
panel.appendChild(startBtn.element);
|
||||
panel.appendChild(stopBtn.element);
|
||||
panel.appendChild(this.createLabel('Topology:', topologySelect));
|
||||
panel.appendChild(this.createLabel('Refresh Rate:', refreshSelect));
|
||||
this.controlElements = {
|
||||
startBtn,
|
||||
stopBtn,
|
||||
topologySelect,
|
||||
refreshSelect
|
||||
};
|
||||
return panel;
|
||||
}
|
||||
createStatsPanel() {
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'swarm-stats-panel';
|
||||
panel.style.display = 'flex';
|
||||
panel.style.gap = '16px';
|
||||
panel.style.flexWrap = 'wrap';
|
||||
this.statsCards = {
|
||||
totalAgents: this.components.createStatsCard({
|
||||
icon: '🤖',
|
||||
value: '0',
|
||||
label: 'Total Agents'
|
||||
}),
|
||||
activeAgents: this.components.createStatsCard({
|
||||
icon: '✅',
|
||||
value: '0',
|
||||
label: 'Active'
|
||||
}),
|
||||
busyAgents: this.components.createStatsCard({
|
||||
icon: '⚙️',
|
||||
value: '0',
|
||||
label: 'Busy'
|
||||
}),
|
||||
idleAgents: this.components.createStatsCard({
|
||||
icon: '💤',
|
||||
value: '0',
|
||||
label: 'Idle'
|
||||
}),
|
||||
errorAgents: this.components.createStatsCard({
|
||||
icon: '❌',
|
||||
value: '0',
|
||||
label: 'Errors'
|
||||
}),
|
||||
throughput: this.components.createStatsCard({
|
||||
icon: '📊',
|
||||
value: '0/min',
|
||||
label: 'Task Throughput'
|
||||
})
|
||||
};
|
||||
Object.values(this.statsCards).forEach((card)=>{
|
||||
panel.appendChild(card.element);
|
||||
});
|
||||
return panel;
|
||||
}
|
||||
createTopologyCanvas() {
|
||||
const container = document.createElement('div');
|
||||
container.className = 'topology-canvas-container';
|
||||
container.style.cssText = `
|
||||
position: relative;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
margin: 16px 0;
|
||||
overflow: hidden;
|
||||
`;
|
||||
this.canvas = document.createElement('canvas');
|
||||
this.canvas.width = this.canvasSize.width;
|
||||
this.canvas.height = this.canvasSize.height;
|
||||
this.canvas.style.display = 'block';
|
||||
this.ctx = this.canvas.getContext('2d');
|
||||
this.canvas.addEventListener('click', (e)=>this.handleCanvasClick(e));
|
||||
this.canvas.addEventListener('mousemove', (e)=>this.handleCanvasHover(e));
|
||||
container.appendChild(this.canvas);
|
||||
return container;
|
||||
}
|
||||
createAgentPanel() {
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'agent-details-panel';
|
||||
panel.style.cssText = `
|
||||
background: #2a2a2a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 8px 0;
|
||||
min-height: 200px;
|
||||
`;
|
||||
const title = document.createElement('h3');
|
||||
title.textContent = 'Agent Details';
|
||||
title.style.color = '#00d4ff';
|
||||
title.style.marginBottom = '12px';
|
||||
const content = document.createElement('div');
|
||||
content.id = 'agent-details-content';
|
||||
content.innerHTML = '<p style="color: #888;">Click on an agent to view details</p>';
|
||||
panel.appendChild(title);
|
||||
panel.appendChild(content);
|
||||
this.agentDetailsContent = content;
|
||||
return panel;
|
||||
}
|
||||
async startMonitoring() {
|
||||
if (this.isActive) return;
|
||||
this.isActive = true;
|
||||
this.controlElements.startBtn.setDisabled(true);
|
||||
this.controlElements.stopBtn.setDisabled(false);
|
||||
const refreshRate = parseInt(this.controlElements.refreshSelect.value);
|
||||
this.updateInterval = setInterval(()=>{
|
||||
this.updateSwarmData();
|
||||
}, refreshRate);
|
||||
this.startAnimation();
|
||||
await this.updateSwarmData();
|
||||
console.log('🔄 Swarm monitoring started');
|
||||
}
|
||||
stopMonitoring() {
|
||||
if (!this.isActive) return;
|
||||
this.isActive = false;
|
||||
this.controlElements.startBtn.setDisabled(false);
|
||||
this.controlElements.stopBtn.setDisabled(true);
|
||||
if (this.updateInterval) {
|
||||
clearInterval(this.updateInterval);
|
||||
this.updateInterval = null;
|
||||
}
|
||||
if (this.animationFrame) {
|
||||
cancelAnimationFrame(this.animationFrame);
|
||||
this.animationFrame = null;
|
||||
}
|
||||
console.log('⏹️ Swarm monitoring stopped');
|
||||
}
|
||||
async updateSwarmData() {
|
||||
try {
|
||||
const response = await fetch('/api/claude-flow/swarm/status');
|
||||
if (response.ok) {
|
||||
this.swarmData = await response.json();
|
||||
this.processSwarmData();
|
||||
this.updateStats();
|
||||
this.redrawTopology();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to fetch swarm data:', error);
|
||||
this.generateMockData();
|
||||
this.processSwarmData();
|
||||
this.updateStats();
|
||||
this.redrawTopology();
|
||||
}
|
||||
}
|
||||
generateMockData() {
|
||||
const agentTypes = [
|
||||
'coder',
|
||||
'researcher',
|
||||
'analyzer',
|
||||
'reviewer',
|
||||
'tester'
|
||||
];
|
||||
const statuses = [
|
||||
'active',
|
||||
'busy',
|
||||
'idle',
|
||||
'error'
|
||||
];
|
||||
const agentCount = Math.floor(Math.random() * 8) + 3;
|
||||
this.swarmData = {
|
||||
id: `swarm_${Date.now()}`,
|
||||
topology: this.topology,
|
||||
agents: [],
|
||||
connections: [],
|
||||
metrics: {
|
||||
totalTasks: Math.floor(Math.random() * 100),
|
||||
completedTasks: Math.floor(Math.random() * 80),
|
||||
failedTasks: Math.floor(Math.random() * 5),
|
||||
averageResponseTime: Math.random() * 1000 + 500,
|
||||
throughput: Math.floor(Math.random() * 20) + 5
|
||||
}
|
||||
};
|
||||
for(let i = 0; i < agentCount; i++){
|
||||
const agent = {
|
||||
id: `agent_${i}`,
|
||||
type: agentTypes[Math.floor(Math.random() * agentTypes.length)],
|
||||
status: statuses[Math.floor(Math.random() * statuses.length)],
|
||||
capabilities: [
|
||||
'task_processing',
|
||||
'memory_access'
|
||||
],
|
||||
currentTask: Math.random() > 0.5 ? `Task ${Math.floor(Math.random() * 100)}` : null,
|
||||
metrics: {
|
||||
tasksCompleted: Math.floor(Math.random() * 50),
|
||||
successRate: Math.random() * 100,
|
||||
averageTime: Math.random() * 2000 + 200,
|
||||
memoryUsage: Math.random() * 100
|
||||
},
|
||||
position: this.calculateAgentPosition(i, agentCount)
|
||||
};
|
||||
this.swarmData.agents.push(agent);
|
||||
}
|
||||
this.generateConnections();
|
||||
}
|
||||
calculateAgentPosition(index, total) {
|
||||
const centerX = this.canvasSize.width / 2;
|
||||
const centerY = this.canvasSize.height / 2;
|
||||
const radius = Math.min(centerX, centerY) * 0.7;
|
||||
switch(this.topology){
|
||||
case 'mesh':
|
||||
case 'ring':
|
||||
const angle = index * 2 * Math.PI / total;
|
||||
return {
|
||||
x: centerX + radius * Math.cos(angle),
|
||||
y: centerY + radius * Math.sin(angle)
|
||||
};
|
||||
case 'hierarchical':
|
||||
const levels = Math.ceil(Math.log2(total));
|
||||
const level = Math.floor(Math.log2(index + 1));
|
||||
const positionInLevel = index - (Math.pow(2, level) - 1);
|
||||
const levelWidth = Math.pow(2, level);
|
||||
return {
|
||||
x: centerX + (positionInLevel - levelWidth / 2 + 0.5) * (this.canvasSize.width / (levelWidth + 1)),
|
||||
y: 100 + level * (this.canvasSize.height - 200) / (levels - 1)
|
||||
};
|
||||
case 'star':
|
||||
if (index === 0) {
|
||||
return {
|
||||
x: centerX,
|
||||
y: centerY
|
||||
};
|
||||
} else {
|
||||
const starAngle = (index - 1) * 2 * Math.PI / (total - 1);
|
||||
return {
|
||||
x: centerX + radius * Math.cos(starAngle),
|
||||
y: centerY + radius * Math.sin(starAngle)
|
||||
};
|
||||
}
|
||||
default:
|
||||
return {
|
||||
x: Math.random() * (this.canvasSize.width - 100) + 50,
|
||||
y: Math.random() * (this.canvasSize.height - 100) + 50
|
||||
};
|
||||
}
|
||||
}
|
||||
generateConnections() {
|
||||
if (!this.swarmData || !this.swarmData.agents) return;
|
||||
const agents = this.swarmData.agents;
|
||||
this.swarmData.connections = [];
|
||||
switch(this.topology){
|
||||
case 'mesh':
|
||||
for(let i = 0; i < agents.length; i++){
|
||||
for(let j = i + 1; j < agents.length; j++){
|
||||
this.swarmData.connections.push({
|
||||
from: agents[i].id,
|
||||
to: agents[j].id,
|
||||
strength: Math.random(),
|
||||
latency: Math.random() * 100 + 10
|
||||
});
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'ring':
|
||||
for(let i = 0; i < agents.length; i++){
|
||||
const next = (i + 1) % agents.length;
|
||||
this.swarmData.connections.push({
|
||||
from: agents[i].id,
|
||||
to: agents[next].id,
|
||||
strength: Math.random(),
|
||||
latency: Math.random() * 50 + 5
|
||||
});
|
||||
}
|
||||
break;
|
||||
case 'star':
|
||||
if (agents.length > 0) {
|
||||
for(let i = 1; i < agents.length; i++){
|
||||
this.swarmData.connections.push({
|
||||
from: agents[0].id,
|
||||
to: agents[i].id,
|
||||
strength: Math.random(),
|
||||
latency: Math.random() * 30 + 5
|
||||
});
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'hierarchical':
|
||||
for(let i = 1; i < agents.length; i++){
|
||||
const parent = Math.floor((i - 1) / 2);
|
||||
this.swarmData.connections.push({
|
||||
from: agents[parent].id,
|
||||
to: agents[i].id,
|
||||
strength: Math.random(),
|
||||
latency: Math.random() * 40 + 5
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
processSwarmData() {
|
||||
if (!this.swarmData) return;
|
||||
this.agents.clear();
|
||||
this.swarmData.agents?.forEach((agent)=>{
|
||||
this.agents.set(agent.id, agent);
|
||||
});
|
||||
this.connections.clear();
|
||||
this.swarmData.connections?.forEach((conn)=>{
|
||||
this.connections.set(`${conn.from}-${conn.to}`, conn);
|
||||
});
|
||||
}
|
||||
updateStats() {
|
||||
if (!this.swarmData) return;
|
||||
const agents = Array.from(this.agents.values());
|
||||
const statusCounts = agents.reduce((acc, agent)=>{
|
||||
acc[agent.status] = (acc[agent.status] || 0) + 1;
|
||||
return acc;
|
||||
}, {});
|
||||
this.statsCards.totalAgents.setValue(agents.length.toString());
|
||||
this.statsCards.activeAgents.setValue((statusCounts.active || 0).toString());
|
||||
this.statsCards.busyAgents.setValue((statusCounts.busy || 0).toString());
|
||||
this.statsCards.idleAgents.setValue((statusCounts.idle || 0).toString());
|
||||
this.statsCards.errorAgents.setValue((statusCounts.error || 0).toString());
|
||||
if (this.swarmData.metrics) {
|
||||
this.statsCards.throughput.setValue(`${this.swarmData.metrics.throughput || 0}/min`);
|
||||
}
|
||||
}
|
||||
redrawTopology() {
|
||||
if (!this.ctx || !this.swarmData) return;
|
||||
this.ctx.fillStyle = '#1a1a1a';
|
||||
this.ctx.fillRect(0, 0, this.canvasSize.width, this.canvasSize.height);
|
||||
this.drawGrid();
|
||||
this.drawConnections();
|
||||
this.drawAgents();
|
||||
this.updateParticles();
|
||||
}
|
||||
drawGrid() {
|
||||
this.ctx.strokeStyle = '#333';
|
||||
this.ctx.lineWidth = 1;
|
||||
this.ctx.setLineDash([
|
||||
2,
|
||||
4
|
||||
]);
|
||||
const gridSize = 50;
|
||||
for(let x = 0; x < this.canvasSize.width; x += gridSize){
|
||||
this.ctx.beginPath();
|
||||
this.ctx.moveTo(x, 0);
|
||||
this.ctx.lineTo(x, this.canvasSize.height);
|
||||
this.ctx.stroke();
|
||||
}
|
||||
for(let y = 0; y < this.canvasSize.height; y += gridSize){
|
||||
this.ctx.beginPath();
|
||||
this.ctx.moveTo(0, y);
|
||||
this.ctx.lineTo(this.canvasSize.width, y);
|
||||
this.ctx.stroke();
|
||||
}
|
||||
this.ctx.setLineDash([]);
|
||||
}
|
||||
drawConnections() {
|
||||
this.connections.forEach((conn, key)=>{
|
||||
const fromAgent = this.agents.get(conn.from);
|
||||
const toAgent = this.agents.get(conn.to);
|
||||
if (fromAgent && toAgent && fromAgent.position && toAgent.position) {
|
||||
this.ctx.strokeStyle = `rgba(0, 212, 255, ${conn.strength * 0.6 + 0.2})`;
|
||||
this.ctx.lineWidth = Math.max(1, conn.strength * 3);
|
||||
this.ctx.setLineDash([]);
|
||||
this.ctx.beginPath();
|
||||
this.ctx.moveTo(fromAgent.position.x, fromAgent.position.y);
|
||||
this.ctx.lineTo(toAgent.position.x, toAgent.position.y);
|
||||
this.ctx.stroke();
|
||||
const midX = (fromAgent.position.x + toAgent.position.x) / 2;
|
||||
const midY = (fromAgent.position.y + toAgent.position.y) / 2;
|
||||
this.ctx.fillStyle = '#666';
|
||||
this.ctx.font = '10px monospace';
|
||||
this.ctx.fillText(`${Math.round(conn.latency)}ms`, midX + 5, midY - 5);
|
||||
}
|
||||
});
|
||||
}
|
||||
drawAgents() {
|
||||
this.agents.forEach((agent)=>{
|
||||
if (!agent.position) return;
|
||||
const { x, y } = agent.position;
|
||||
const radius = 25;
|
||||
const statusColors = {
|
||||
active: '#22c55e',
|
||||
busy: '#f59e0b',
|
||||
idle: '#6b7280',
|
||||
error: '#ef4444'
|
||||
};
|
||||
this.ctx.fillStyle = statusColors[agent.status] || '#6b7280';
|
||||
this.ctx.beginPath();
|
||||
this.ctx.arc(x, y, radius, 0, 2 * Math.PI);
|
||||
this.ctx.fill();
|
||||
this.ctx.strokeStyle = '#fff';
|
||||
this.ctx.lineWidth = 2;
|
||||
this.ctx.stroke();
|
||||
this.ctx.fillStyle = '#fff';
|
||||
this.ctx.font = 'bold 12px monospace';
|
||||
this.ctx.textAlign = 'center';
|
||||
this.ctx.fillText(this.getAgentIcon(agent.type), x, y + 4);
|
||||
this.ctx.fillStyle = '#fff';
|
||||
this.ctx.font = '10px monospace';
|
||||
this.ctx.fillText(agent.id, x, y + radius + 15);
|
||||
if (agent.currentTask) {
|
||||
this.ctx.fillStyle = '#00d4ff';
|
||||
this.ctx.beginPath();
|
||||
this.ctx.arc(x + radius - 5, y - radius + 5, 5, 0, 2 * Math.PI);
|
||||
this.ctx.fill();
|
||||
}
|
||||
});
|
||||
}
|
||||
getAgentIcon(type) {
|
||||
const icons = {
|
||||
coder: '💻',
|
||||
researcher: '🔍',
|
||||
analyzer: '📊',
|
||||
reviewer: '✅',
|
||||
tester: '🧪',
|
||||
coordinator: '🎯',
|
||||
optimizer: '⚡'
|
||||
};
|
||||
return icons[type] || '🤖';
|
||||
}
|
||||
updateParticles() {
|
||||
this.particles = this.particles.filter((p)=>p.life > 0);
|
||||
if (Math.random() < 0.3) {
|
||||
this.connections.forEach((conn, key)=>{
|
||||
const fromAgent = this.agents.get(conn.from);
|
||||
const toAgent = this.agents.get(conn.to);
|
||||
if (fromAgent?.status === 'busy' && toAgent && fromAgent.position && toAgent.position) {
|
||||
this.particles.push({
|
||||
x: fromAgent.position.x,
|
||||
y: fromAgent.position.y,
|
||||
targetX: toAgent.position.x,
|
||||
targetY: toAgent.position.y,
|
||||
progress: 0,
|
||||
life: 1,
|
||||
speed: 0.02,
|
||||
color: conn.strength > 0.7 ? '#00d4ff' : '#888'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
this.particles.forEach((particle)=>{
|
||||
particle.progress += particle.speed;
|
||||
particle.life -= 0.01;
|
||||
const currentX = particle.x + (particle.targetX - particle.x) * particle.progress;
|
||||
const currentY = particle.y + (particle.targetY - particle.y) * particle.progress;
|
||||
this.ctx.fillStyle = particle.color;
|
||||
this.ctx.globalAlpha = particle.life;
|
||||
this.ctx.beginPath();
|
||||
this.ctx.arc(currentX, currentY, 3, 0, 2 * Math.PI);
|
||||
this.ctx.fill();
|
||||
this.ctx.globalAlpha = 1;
|
||||
});
|
||||
}
|
||||
handleCanvasClick(event) {
|
||||
const rect = this.canvas.getBoundingClientRect();
|
||||
const x = event.clientX - rect.left;
|
||||
const y = event.clientY - rect.top;
|
||||
const clickedAgent = Array.from(this.agents.values()).find((agent)=>{
|
||||
if (!agent.position) return false;
|
||||
const distance = Math.sqrt(Math.pow(x - agent.position.x, 2) + Math.pow(y - agent.position.y, 2));
|
||||
return distance <= 25;
|
||||
});
|
||||
if (clickedAgent) {
|
||||
this.showAgentDetails(clickedAgent);
|
||||
}
|
||||
}
|
||||
handleCanvasHover(event) {
|
||||
const rect = this.canvas.getBoundingClientRect();
|
||||
const x = event.clientX - rect.left;
|
||||
const y = event.clientY - rect.top;
|
||||
const hoveredAgent = Array.from(this.agents.values()).find((agent)=>{
|
||||
if (!agent.position) return false;
|
||||
const distance = Math.sqrt(Math.pow(x - agent.position.x, 2) + Math.pow(y - agent.position.y, 2));
|
||||
return distance <= 25;
|
||||
});
|
||||
this.canvas.style.cursor = hoveredAgent ? 'pointer' : 'default';
|
||||
}
|
||||
showAgentDetails(agent) {
|
||||
const metrics = agent.metrics || {};
|
||||
const capabilities = agent.capabilities || [];
|
||||
this.agentDetailsContent.innerHTML = `
|
||||
<div class="agent-details">
|
||||
<div class="agent-header">
|
||||
<h4>${this.getAgentIcon(agent.type)} ${agent.id}</h4>
|
||||
<span class="status-badge status-${agent.status}">${agent.status}</span>
|
||||
</div>
|
||||
|
||||
<div class="agent-info">
|
||||
<div class="info-row">
|
||||
<label>Type:</label>
|
||||
<span>${agent.type}</span>
|
||||
</div>
|
||||
<div class="info-row">
|
||||
<label>Current Task:</label>
|
||||
<span>${agent.currentTask || 'None'}</span>
|
||||
</div>
|
||||
<div class="info-row">
|
||||
<label>Capabilities:</label>
|
||||
<span>${capabilities.join(', ')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="agent-metrics">
|
||||
<h5>Performance Metrics</h5>
|
||||
<div class="metrics-grid">
|
||||
<div class="metric">
|
||||
<label>Tasks Completed:</label>
|
||||
<span>${metrics.tasksCompleted || 0}</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<label>Success Rate:</label>
|
||||
<span>${Math.round(metrics.successRate || 0)}%</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<label>Avg Response Time:</label>
|
||||
<span>${Math.round(metrics.averageTime || 0)}ms</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<label>Memory Usage:</label>
|
||||
<span>${Math.round(metrics.memoryUsage || 0)}MB</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
startAnimation() {
|
||||
const animate = ()=>{
|
||||
if (this.isActive) {
|
||||
this.redrawTopology();
|
||||
this.animationFrame = requestAnimationFrame(animate);
|
||||
}
|
||||
};
|
||||
animate();
|
||||
}
|
||||
createLabel(text, element) {
|
||||
const label = document.createElement('label');
|
||||
label.textContent = text;
|
||||
label.appendChild(element);
|
||||
label.style.cssText = `
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
color: #fff;
|
||||
font-size: 14px;
|
||||
margin: 0 8px;
|
||||
`;
|
||||
return label;
|
||||
}
|
||||
setupEventHandlers() {
|
||||
window.addEventListener('resize', ()=>{
|
||||
this.redrawTopology();
|
||||
});
|
||||
}
|
||||
async storeProgress() {
|
||||
const progress = {
|
||||
isActive: this.isActive,
|
||||
topology: this.topology,
|
||||
agentCount: this.agents.size,
|
||||
connectionCount: this.connections.size,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
try {
|
||||
const response = await fetch('/api/claude-flow/memory/set', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
namespace: 'swarm_1756475726467_c9ey1p9vm',
|
||||
key: 'frontend/swarm_visualizer',
|
||||
value: JSON.stringify(progress)
|
||||
})
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('Failed to store progress:', error);
|
||||
}
|
||||
}
|
||||
destroy() {
|
||||
this.stopMonitoring();
|
||||
if (this.container) {
|
||||
this.container.innerHTML = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
export default SwarmVisualizer;
|
||||
|
||||
//# sourceMappingURL=swarm-visualizer.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/swarm-visualizer.js"],"sourcesContent":["/**\n * SwarmVisualizer - Real-time swarm monitoring and visualization component\n * Provides interactive swarm topology view with live agent status updates\n */\n\nexport class SwarmVisualizer {\n constructor(container, componentLibrary) {\n this.container = container;\n this.components = componentLibrary;\n this.swarmData = null;\n this.agents = new Map();\n this.connections = new Map();\n this.topology = 'mesh';\n this.updateInterval = null;\n this.isActive = false;\n \n // Canvas for topology visualization\n this.canvas = null;\n this.ctx = null;\n this.canvasSize = { width: 800, height: 600 };\n \n // Animation state\n this.animationFrame = null;\n this.particles = [];\n \n this.init();\n }\n\n /**\n * Initialize swarm visualizer\n */\n init() {\n this.createUI();\n this.setupEventHandlers();\n console.log('🌊 Swarm Visualizer initialized');\n }\n\n /**\n * Create the visualizer UI\n */\n createUI() {\n // Main container\n const mainPanel = this.components.createToolPanel({\n title: 'Swarm Visualizer',\n description: 'Real-time swarm topology and agent monitoring'\n });\n\n // Control panel\n const controlPanel = this.createControlPanel();\n mainPanel.append(controlPanel);\n\n // Stats panel\n const statsPanel = this.createStatsPanel();\n mainPanel.append(statsPanel);\n\n // Topology canvas\n const canvasContainer = this.createTopologyCanvas();\n mainPanel.append(canvasContainer);\n\n // Agent details panel\n const agentPanel = this.createAgentPanel();\n mainPanel.append(agentPanel);\n\n this.container.appendChild(mainPanel.element);\n this.elements = {\n mainPanel,\n controlPanel,\n statsPanel,\n canvasContainer,\n agentPanel\n };\n }\n\n /**\n * Create control panel\n */\n createControlPanel() {\n const panel = document.createElement('div');\n panel.className = 'swarm-control-panel';\n\n // Start/Stop controls\n const startBtn = this.components.createActionButton({\n type: 'primary',\n text: 'Start Monitoring',\n icon: '▶️',\n onclick: () => this.startMonitoring()\n });\n\n const stopBtn = this.components.createActionButton({\n type: 'secondary',\n text: 'Stop',\n icon: '⏹️',\n onclick: () => this.stopMonitoring()\n });\n\n // Topology selector\n const topologySelect = document.createElement('select');\n topologySelect.id = 'topology-selector';\n topologySelect.innerHTML = `\n <option value=\"mesh\">Mesh Network</option>\n <option value=\"hierarchical\">Hierarchical</option>\n <option value=\"ring\">Ring Topology</option>\n <option value=\"star\">Star Network</option>\n `;\n topologySelect.addEventListener('change', (e) => {\n this.topology = e.target.value;\n this.redrawTopology();\n });\n\n // Refresh rate selector\n const refreshSelect = document.createElement('select');\n refreshSelect.id = 'refresh-rate';\n refreshSelect.innerHTML = `\n <option value=\"1000\">1 second</option>\n <option value=\"2000\" selected>2 seconds</option>\n <option value=\"5000\">5 seconds</option>\n <option value=\"10000\">10 seconds</option>\n `;\n\n panel.appendChild(startBtn.element);\n panel.appendChild(stopBtn.element);\n panel.appendChild(this.createLabel('Topology:', topologySelect));\n panel.appendChild(this.createLabel('Refresh Rate:', refreshSelect));\n\n this.controlElements = {\n startBtn,\n stopBtn,\n topologySelect,\n refreshSelect\n };\n\n return panel;\n }\n\n /**\n * Create stats panel\n */\n createStatsPanel() {\n const panel = document.createElement('div');\n panel.className = 'swarm-stats-panel';\n panel.style.display = 'flex';\n panel.style.gap = '16px';\n panel.style.flexWrap = 'wrap';\n\n this.statsCards = {\n totalAgents: this.components.createStatsCard({\n icon: '🤖',\n value: '0',\n label: 'Total Agents'\n }),\n activeAgents: this.components.createStatsCard({\n icon: '✅',\n value: '0',\n label: 'Active'\n }),\n busyAgents: this.components.createStatsCard({\n icon: '⚙️',\n value: '0',\n label: 'Busy'\n }),\n idleAgents: this.components.createStatsCard({\n icon: '💤',\n value: '0',\n label: 'Idle'\n }),\n errorAgents: this.components.createStatsCard({\n icon: '❌',\n value: '0',\n label: 'Errors'\n }),\n throughput: this.components.createStatsCard({\n icon: '📊',\n value: '0/min',\n label: 'Task Throughput'\n })\n };\n\n Object.values(this.statsCards).forEach(card => {\n panel.appendChild(card.elementLine truncated
|
||||
@@ -1,444 +0,0 @@
|
||||
export class TerminalEmulator {
|
||||
constructor(outputElement, inputElement){
|
||||
this.outputElement = outputElement;
|
||||
this.inputElement = inputElement;
|
||||
this.history = [];
|
||||
this.historyIndex = -1;
|
||||
this.maxHistorySize = 1000;
|
||||
this.maxOutputLines = 1000;
|
||||
this.currentPrompt = 'claude-flow>';
|
||||
this.isLocked = false;
|
||||
this.commands = [
|
||||
'help',
|
||||
'clear',
|
||||
'status',
|
||||
'connect',
|
||||
'disconnect',
|
||||
'claude-flow',
|
||||
'swarm',
|
||||
'init',
|
||||
'config',
|
||||
'memory',
|
||||
'tools',
|
||||
'agents',
|
||||
'benchmark',
|
||||
'sparc'
|
||||
];
|
||||
this.ansiColors = {
|
||||
30: '#000000',
|
||||
31: '#ff5555',
|
||||
32: '#50fa7b',
|
||||
33: '#f1fa8c',
|
||||
34: '#bd93f9',
|
||||
35: '#ff79c6',
|
||||
36: '#8be9fd',
|
||||
37: '#f8f8f2',
|
||||
90: '#6272a4',
|
||||
91: '#ff6e6e',
|
||||
92: '#69ff94',
|
||||
93: '#ffffa5',
|
||||
94: '#d6acff',
|
||||
95: '#ff92df',
|
||||
96: '#a4ffff',
|
||||
97: '#ffffff'
|
||||
};
|
||||
this.setupInputHandlers();
|
||||
this.setupScrollBehavior();
|
||||
}
|
||||
write(content, type = 'output', timestamp = true) {
|
||||
const entry = this.createOutputEntry(content, type, timestamp);
|
||||
this.outputElement.appendChild(entry);
|
||||
this.limitOutputLines();
|
||||
this.scrollToBottom();
|
||||
return entry;
|
||||
}
|
||||
writeLine(content, type = 'output', timestamp = true) {
|
||||
return this.write(content + '\n', type, timestamp);
|
||||
}
|
||||
writeCommand(command) {
|
||||
return this.write(`${this.currentPrompt} ${command}`, 'command', true);
|
||||
}
|
||||
writeError(message) {
|
||||
return this.writeLine(`Error: ${message}`, 'error');
|
||||
}
|
||||
writeSuccess(message) {
|
||||
return this.writeLine(message, 'success');
|
||||
}
|
||||
writeWarning(message) {
|
||||
return this.writeLine(`Warning: ${message}`, 'warning');
|
||||
}
|
||||
writeInfo(message) {
|
||||
return this.writeLine(message, 'info');
|
||||
}
|
||||
writeHTML(html, type = 'output') {
|
||||
const entry = document.createElement('div');
|
||||
entry.className = 'output-entry';
|
||||
entry.innerHTML = html;
|
||||
if (type) {
|
||||
entry.classList.add(`output-${type}`);
|
||||
}
|
||||
this.outputElement.appendChild(entry);
|
||||
this.limitOutputLines();
|
||||
this.scrollToBottom();
|
||||
return entry;
|
||||
}
|
||||
clear() {
|
||||
this.outputElement.innerHTML = '';
|
||||
this.showWelcomeMessage();
|
||||
}
|
||||
showWelcomeMessage() {
|
||||
const existingWelcome = this.outputElement.querySelector('.welcome-message');
|
||||
if (existingWelcome) {
|
||||
return;
|
||||
}
|
||||
const welcome = document.createElement('div');
|
||||
welcome.className = 'welcome-message';
|
||||
welcome.innerHTML = `
|
||||
<div class="ascii-art">╔═══════════════════════════════════════════════════════════╗
|
||||
║ ║
|
||||
║ 🌊 Claude Flow v2.0.0 ║
|
||||
║ ║
|
||||
║ Welcome to the web-based swarm orchestration ║
|
||||
║ Type 'help' for available commands ║
|
||||
║ Use Ctrl+L to clear console ║
|
||||
║ ║
|
||||
╚═══════════════════════════════════════════════════════════╝</div>
|
||||
`;
|
||||
this.outputElement.appendChild(welcome);
|
||||
}
|
||||
setPrompt(prompt) {
|
||||
this.currentPrompt = prompt;
|
||||
const promptElement = document.getElementById('promptText');
|
||||
if (promptElement) {
|
||||
promptElement.textContent = prompt;
|
||||
}
|
||||
}
|
||||
setLocked(locked) {
|
||||
this.isLocked = locked;
|
||||
this.inputElement.disabled = locked;
|
||||
if (locked) {
|
||||
this.inputElement.placeholder = 'Processing...';
|
||||
} else {
|
||||
this.inputElement.placeholder = 'Enter command...';
|
||||
this.inputElement.focus();
|
||||
}
|
||||
}
|
||||
focus() {
|
||||
if (!this.isLocked) {
|
||||
this.inputElement.focus();
|
||||
}
|
||||
}
|
||||
getInput() {
|
||||
return this.inputElement.value;
|
||||
}
|
||||
setInput(value) {
|
||||
this.inputElement.value = value;
|
||||
}
|
||||
clearInput() {
|
||||
this.inputElement.value = '';
|
||||
}
|
||||
addToHistory(command) {
|
||||
if (command.trim() && this.history[this.history.length - 1] !== command) {
|
||||
this.history.push(command);
|
||||
if (this.history.length > this.maxHistorySize) {
|
||||
this.history.shift();
|
||||
}
|
||||
}
|
||||
this.historyIndex = -1;
|
||||
}
|
||||
navigateHistory(direction) {
|
||||
if (this.history.length === 0) return;
|
||||
if (direction === 'up') {
|
||||
if (this.historyIndex === -1) {
|
||||
this.historyIndex = this.history.length - 1;
|
||||
} else if (this.historyIndex > 0) {
|
||||
this.historyIndex--;
|
||||
}
|
||||
} else if (direction === 'down') {
|
||||
if (this.historyIndex < this.history.length - 1) {
|
||||
this.historyIndex++;
|
||||
} else {
|
||||
this.historyIndex = -1;
|
||||
}
|
||||
}
|
||||
if (this.historyIndex === -1) {
|
||||
this.setInput('');
|
||||
} else {
|
||||
this.setInput(this.history[this.historyIndex]);
|
||||
}
|
||||
}
|
||||
createOutputEntry(content, type, timestamp) {
|
||||
const entry = document.createElement('div');
|
||||
entry.className = 'output-entry';
|
||||
const line = document.createElement('div');
|
||||
line.className = 'output-line';
|
||||
if (timestamp && this.shouldShowTimestamp()) {
|
||||
const timeElement = document.createElement('span');
|
||||
timeElement.className = 'output-timestamp';
|
||||
timeElement.textContent = this.formatTimestamp(new Date());
|
||||
line.appendChild(timeElement);
|
||||
}
|
||||
const contentElement = document.createElement('span');
|
||||
contentElement.className = `output-content ${type}`;
|
||||
if (typeof content === 'string' && content.includes('\x1b[')) {
|
||||
contentElement.innerHTML = this.processAnsiCodes(content);
|
||||
} else {
|
||||
contentElement.textContent = content;
|
||||
}
|
||||
line.appendChild(contentElement);
|
||||
entry.appendChild(line);
|
||||
return entry;
|
||||
}
|
||||
processAnsiCodes(text) {
|
||||
return text.replace(/\x1b\[(\d+)m/g, (match, code)=>{
|
||||
if (code === '0' || code === '00') {
|
||||
return '</span>';
|
||||
}
|
||||
const color = this.ansiColors[code];
|
||||
if (color) {
|
||||
return `<span style="color: ${color}">`;
|
||||
}
|
||||
return '';
|
||||
}).replace(/\x1b\[[\d;]*m/g, '') + '</span>';
|
||||
}
|
||||
formatTimestamp(date) {
|
||||
return date.toLocaleTimeString('en-US', {
|
||||
hour12: false,
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit'
|
||||
});
|
||||
}
|
||||
shouldShowTimestamp() {
|
||||
const showTimestamps = localStorage.getItem('console_show_timestamps');
|
||||
return showTimestamps !== 'false';
|
||||
}
|
||||
limitOutputLines() {
|
||||
const entries = this.outputElement.querySelectorAll('.output-entry');
|
||||
if (entries.length > this.maxOutputLines) {
|
||||
const excessCount = entries.length - this.maxOutputLines;
|
||||
for(let i = 0; i < excessCount; i++){
|
||||
if (entries[i] && !entries[i].classList.contains('welcome-message')) {
|
||||
entries[i].remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
scrollToBottom(smooth = false) {
|
||||
if (this.shouldAutoScroll()) {
|
||||
if (smooth) {
|
||||
this.outputElement.scrollTo({
|
||||
top: this.outputElement.scrollHeight,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
} else {
|
||||
this.outputElement.scrollTop = this.outputElement.scrollHeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
shouldAutoScroll() {
|
||||
const autoScroll = localStorage.getItem('console_auto_scroll');
|
||||
return autoScroll !== 'false';
|
||||
}
|
||||
setupInputHandlers() {
|
||||
this.inputElement.addEventListener('keydown', (event)=>{
|
||||
if (this.isLocked) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
switch(event.key){
|
||||
case 'Enter':
|
||||
event.preventDefault();
|
||||
this.handleEnter();
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
event.preventDefault();
|
||||
this.navigateHistory('up');
|
||||
break;
|
||||
case 'ArrowDown':
|
||||
event.preventDefault();
|
||||
this.navigateHistory('down');
|
||||
break;
|
||||
case 'Tab':
|
||||
event.preventDefault();
|
||||
this.handleTab();
|
||||
break;
|
||||
case 'l':
|
||||
if (event.ctrlKey) {
|
||||
event.preventDefault();
|
||||
this.clear();
|
||||
}
|
||||
break;
|
||||
case 'c':
|
||||
if (event.ctrlKey) {
|
||||
event.preventDefault();
|
||||
this.handleInterrupt();
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
this.inputElement.addEventListener('input', ()=>{
|
||||
if (!this.isLocked) {
|
||||
this.handleInput();
|
||||
}
|
||||
});
|
||||
}
|
||||
handleEnter() {
|
||||
const command = this.getInput().trim();
|
||||
if (command) {
|
||||
this.addToHistory(command);
|
||||
this.writeCommand(command);
|
||||
this.clearInput();
|
||||
this.emit('command', command);
|
||||
}
|
||||
}
|
||||
handleTab() {
|
||||
const input = this.getInput();
|
||||
const matches = this.commands.filter((cmd)=>cmd.startsWith(input));
|
||||
if (matches.length === 1) {
|
||||
this.setInput(matches[0] + ' ');
|
||||
} else if (matches.length > 1) {
|
||||
this.writeLine(`Available commands: ${matches.join(', ')}`, 'info');
|
||||
}
|
||||
}
|
||||
handleInput() {
|
||||
this.emit('input_change', this.getInput());
|
||||
}
|
||||
handleInterrupt() {
|
||||
this.writeLine('^C', 'warning');
|
||||
this.clearInput();
|
||||
this.emit('interrupt');
|
||||
}
|
||||
setupScrollBehavior() {
|
||||
let isUserScrolling = false;
|
||||
let scrollTimeout;
|
||||
let lastScrollTop = 0;
|
||||
this.outputElement.addEventListener('scroll', ()=>{
|
||||
const currentScrollTop = this.outputElement.scrollTop;
|
||||
const maxScrollTop = this.outputElement.scrollHeight - this.outputElement.clientHeight;
|
||||
if (currentScrollTop < lastScrollTop && currentScrollTop < maxScrollTop - 10) {
|
||||
isUserScrolling = true;
|
||||
this.showScrollIndicator();
|
||||
clearTimeout(scrollTimeout);
|
||||
scrollTimeout = setTimeout(()=>{
|
||||
const newScrollTop = this.outputElement.scrollTop;
|
||||
const newMaxScrollTop = this.outputElement.scrollHeight - this.outputElement.clientHeight;
|
||||
if (newScrollTop >= newMaxScrollTop - 50) {
|
||||
isUserScrolling = false;
|
||||
this.hideScrollIndicator();
|
||||
}
|
||||
}, 3000);
|
||||
} else if (currentScrollTop >= maxScrollTop - 10) {
|
||||
isUserScrolling = false;
|
||||
this.hideScrollIndicator();
|
||||
clearTimeout(scrollTimeout);
|
||||
}
|
||||
lastScrollTop = currentScrollTop;
|
||||
});
|
||||
const originalShouldAutoScroll = this.shouldAutoScroll;
|
||||
this.shouldAutoScroll = ()=>{
|
||||
return originalShouldAutoScroll.call(this) && !isUserScrolling;
|
||||
};
|
||||
this.isUserScrolling = ()=>isUserScrolling;
|
||||
this.resumeAutoScroll = ()=>{
|
||||
isUserScrolling = false;
|
||||
this.hideScrollIndicator();
|
||||
this.scrollToBottom(true);
|
||||
};
|
||||
}
|
||||
showScrollIndicator() {
|
||||
let indicator = document.getElementById('scrollIndicator');
|
||||
if (!indicator) {
|
||||
indicator = document.createElement('div');
|
||||
indicator.id = 'scrollIndicator';
|
||||
indicator.className = 'scroll-indicator';
|
||||
indicator.innerHTML = `
|
||||
<span class="scroll-text">Auto-scroll paused</span>
|
||||
<button class="scroll-resume-btn" onclick="window.claudeConsole.terminal.resumeAutoScroll()">
|
||||
↓ Resume
|
||||
</button>
|
||||
`;
|
||||
const consoleContainer = this.outputElement.closest('.console-container');
|
||||
if (consoleContainer) {
|
||||
consoleContainer.appendChild(indicator);
|
||||
} else {
|
||||
document.body.appendChild(indicator);
|
||||
}
|
||||
}
|
||||
indicator.style.display = 'flex';
|
||||
}
|
||||
hideScrollIndicator() {
|
||||
const indicator = document.getElementById('scrollIndicator');
|
||||
if (indicator) {
|
||||
indicator.style.display = 'none';
|
||||
}
|
||||
}
|
||||
async streamText(text, delay = 10) {
|
||||
const entry = this.createOutputEntry('', 'output', true);
|
||||
this.outputElement.appendChild(entry);
|
||||
const contentElement = entry.querySelector('.output-content');
|
||||
for(let i = 0; i < text.length; i++){
|
||||
contentElement.textContent += text[i];
|
||||
this.scrollToBottom();
|
||||
if (delay > 0) {
|
||||
await new Promise((resolve)=>setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
on(event, callback) {
|
||||
if (!this.eventListeners) {
|
||||
this.eventListeners = new Map();
|
||||
}
|
||||
if (!this.eventListeners.has(event)) {
|
||||
this.eventListeners.set(event, []);
|
||||
}
|
||||
this.eventListeners.get(event).push(callback);
|
||||
}
|
||||
emit(event, data) {
|
||||
if (!this.eventListeners || !this.eventListeners.has(event)) {
|
||||
return;
|
||||
}
|
||||
this.eventListeners.get(event).forEach((callback)=>{
|
||||
try {
|
||||
callback(data);
|
||||
} catch (error) {
|
||||
console.error('Error in terminal event listener:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
setMaxLines(maxLines) {
|
||||
this.maxOutputLines = Math.max(100, Math.min(10000, maxLines));
|
||||
this.limitOutputLines();
|
||||
}
|
||||
getStats() {
|
||||
const entries = this.outputElement.querySelectorAll('.output-entry');
|
||||
return {
|
||||
totalLines: entries.length,
|
||||
historySize: this.history.length,
|
||||
isLocked: this.isLocked,
|
||||
currentPrompt: this.currentPrompt
|
||||
};
|
||||
}
|
||||
exportHistory() {
|
||||
const entries = Array.from(this.outputElement.querySelectorAll('.output-entry'));
|
||||
return entries.map((entry)=>{
|
||||
const timestamp = entry.querySelector('.output-timestamp')?.textContent || '';
|
||||
const content = entry.querySelector('.output-content')?.textContent || '';
|
||||
const type = entry.querySelector('.output-content')?.className.split(' ').find((c)=>c.startsWith('output-')) || '';
|
||||
return {
|
||||
timestamp,
|
||||
content,
|
||||
type
|
||||
};
|
||||
});
|
||||
}
|
||||
importHistory(history) {
|
||||
this.clear();
|
||||
history.forEach(({ timestamp, content, type })=>{
|
||||
this.write(content, type.replace('output-', ''), false);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=terminal-emulator.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/terminal-emulator.js"],"sourcesContent":["/**\n * Terminal Emulator for Claude Code Console\n * Provides terminal-like behavior and output formatting\n */\n\nexport class TerminalEmulator {\n constructor(outputElement, inputElement) {\n this.outputElement = outputElement;\n this.inputElement = inputElement;\n this.history = [];\n this.historyIndex = -1;\n this.maxHistorySize = 1000;\n this.maxOutputLines = 1000;\n this.currentPrompt = 'claude-flow>';\n this.isLocked = false;\n\n // Command suggestions\n this.commands = [\n 'help',\n 'clear',\n 'status',\n 'connect',\n 'disconnect',\n 'claude-flow',\n 'swarm',\n 'init',\n 'config',\n 'memory',\n 'tools',\n 'agents',\n 'benchmark',\n 'sparc',\n ];\n\n // ANSI color codes mapping\n this.ansiColors = {\n 30: '#000000', // Black\n 31: '#ff5555', // Red\n 32: '#50fa7b', // Green\n 33: '#f1fa8c', // Yellow\n 34: '#bd93f9', // Blue\n 35: '#ff79c6', // Magenta\n 36: '#8be9fd', // Cyan\n 37: '#f8f8f2', // White\n 90: '#6272a4', // Bright Black (Gray)\n 91: '#ff6e6e', // Bright Red\n 92: '#69ff94', // Bright Green\n 93: '#ffffa5', // Bright Yellow\n 94: '#d6acff', // Bright Blue\n 95: '#ff92df', // Bright Magenta\n 96: '#a4ffff', // Bright Cyan\n 97: '#ffffff', // Bright White\n };\n\n this.setupInputHandlers();\n this.setupScrollBehavior();\n }\n\n /**\n * Write output to terminal\n */\n write(content, type = 'output', timestamp = true) {\n const entry = this.createOutputEntry(content, type, timestamp);\n this.outputElement.appendChild(entry);\n this.limitOutputLines();\n this.scrollToBottom();\n return entry;\n }\n\n /**\n * Write line to terminal\n */\n writeLine(content, type = 'output', timestamp = true) {\n return this.write(content + '\\n', type, timestamp);\n }\n\n /**\n * Write command to terminal\n */\n writeCommand(command) {\n return this.write(`${this.currentPrompt} ${command}`, 'command', true);\n }\n\n /**\n * Write error message\n */\n writeError(message) {\n return this.writeLine(`Error: ${message}`, 'error');\n }\n\n /**\n * Write success message\n */\n writeSuccess(message) {\n return this.writeLine(message, 'success');\n }\n\n /**\n * Write warning message\n */\n writeWarning(message) {\n return this.writeLine(`Warning: ${message}`, 'warning');\n }\n\n /**\n * Write info message\n */\n writeInfo(message) {\n return this.writeLine(message, 'info');\n }\n\n /**\n * Write raw HTML content\n */\n writeHTML(html, type = 'output') {\n const entry = document.createElement('div');\n entry.className = 'output-entry';\n entry.innerHTML = html;\n\n if (type) {\n entry.classList.add(`output-${type}`);\n }\n\n this.outputElement.appendChild(entry);\n this.limitOutputLines();\n this.scrollToBottom();\n return entry;\n }\n\n /**\n * Clear terminal output\n */\n clear() {\n this.outputElement.innerHTML = '';\n this.showWelcomeMessage();\n }\n\n /**\n * Show welcome message\n */\n showWelcomeMessage() {\n // Check if welcome message already exists (from static HTML)\n const existingWelcome = this.outputElement.querySelector('.welcome-message');\n if (existingWelcome) {\n // Welcome message already exists, don't add another one\n return;\n }\n\n const welcome = document.createElement('div');\n welcome.className = 'welcome-message';\n welcome.innerHTML = `\n <div class=\"ascii-art\">╔═══════════════════════════════════════════════════════════╗\n║ ║\n║ 🌊 Claude Flow v2.0.0 ║\n║ ║\n║ Welcome to the web-based swarm orchestration ║\n║ Type 'help' for available commands ║\n║ Use Ctrl+L to clear console ║\n║ ║\n╚═══════════════════════════════════════════════════════════╝</div>\n `;\n this.outputElement.appendChild(welcome);\n }\n\n /**\n * Set prompt text\n */\n setPrompt(prompt) {\n this.currentPrompt = prompt;\n const promptElement = document.getElementById('promptText');\n if (promptElement) {\n promptElement.textContent = prompt;\n }\n }\n\n /**\n * Lock/unlock input\n */\n setLocked(locked) {\n this.isLocked = locked;\n this.inputElement.disabled = locked;\n\n Line truncated
|
||||
@@ -1,360 +0,0 @@
|
||||
export class WebSocketClient {
|
||||
constructor(){
|
||||
this.ws = null;
|
||||
this.url = '';
|
||||
this.authToken = '';
|
||||
this.isConnected = false;
|
||||
this.isConnecting = false;
|
||||
this.reconnectAttempts = 0;
|
||||
this.maxReconnectAttempts = 5;
|
||||
this.reconnectDelay = 1000;
|
||||
this.messageQueue = [];
|
||||
this.requestHandlers = new Map();
|
||||
this.eventListeners = new Map();
|
||||
this.messageId = 1;
|
||||
this.heartbeatInterval = 30000;
|
||||
this.heartbeatTimer = null;
|
||||
this.lastPongReceived = Date.now();
|
||||
this.connectionTimeout = 10000;
|
||||
this.setupEventListeners();
|
||||
}
|
||||
async connect(url, authToken = '') {
|
||||
if (this.isConnecting || this.isConnected) {
|
||||
console.warn('Already connected or connecting');
|
||||
return;
|
||||
}
|
||||
this.url = url;
|
||||
this.authToken = authToken;
|
||||
this.isConnecting = true;
|
||||
try {
|
||||
await this.establishConnection();
|
||||
} catch (error) {
|
||||
this.isConnecting = false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async establishConnection() {
|
||||
return new Promise((resolve, reject)=>{
|
||||
try {
|
||||
this.ws = new WebSocket(this.url);
|
||||
const connectionTimer = setTimeout(()=>{
|
||||
if (this.ws && this.ws.readyState !== WebSocket.OPEN) {
|
||||
this.ws.close();
|
||||
this.isConnecting = false;
|
||||
reject(new Error('Connection timeout'));
|
||||
}
|
||||
}, this.connectionTimeout);
|
||||
this.ws.onopen = ()=>{
|
||||
clearTimeout(connectionTimer);
|
||||
this.isConnected = true;
|
||||
this.isConnecting = false;
|
||||
this.reconnectAttempts = 0;
|
||||
this.lastPongReceived = Date.now();
|
||||
this.emit('connected');
|
||||
this.startHeartbeat();
|
||||
this.processMessageQueue();
|
||||
console.log('WebSocket connected to:', this.url);
|
||||
resolve();
|
||||
};
|
||||
this.ws.onclose = (event)=>{
|
||||
clearTimeout(connectionTimer);
|
||||
this.handleDisconnection(event);
|
||||
};
|
||||
this.ws.onerror = (error)=>{
|
||||
clearTimeout(connectionTimer);
|
||||
console.error('WebSocket error:', error);
|
||||
this.isConnecting = false;
|
||||
this.emit('error', error);
|
||||
if (!this.isConnected) {
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
this.ws.onmessage = (event)=>{
|
||||
this.handleMessage(event);
|
||||
};
|
||||
} catch (error) {
|
||||
this.isConnecting = false;
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
disconnect() {
|
||||
if (this.ws) {
|
||||
this.stopHeartbeat();
|
||||
this.ws.close(1000, 'User initiated disconnect');
|
||||
this.ws = null;
|
||||
}
|
||||
this.isConnected = false;
|
||||
this.isConnecting = false;
|
||||
this.reconnectAttempts = 0;
|
||||
this.messageQueue = [];
|
||||
this.requestHandlers.clear();
|
||||
this.emit('disconnected');
|
||||
}
|
||||
async sendRequest(method, params = {}) {
|
||||
const id = this.generateMessageId();
|
||||
const request = {
|
||||
jsonrpc: '2.0',
|
||||
id,
|
||||
method,
|
||||
params
|
||||
};
|
||||
return new Promise((resolve, reject)=>{
|
||||
this.requestHandlers.set(id, {
|
||||
resolve,
|
||||
reject
|
||||
});
|
||||
this.sendMessage(request);
|
||||
setTimeout(()=>{
|
||||
if (this.requestHandlers.has(id)) {
|
||||
this.requestHandlers.delete(id);
|
||||
reject(new Error(`Request timeout for method: ${method}`));
|
||||
}
|
||||
}, 30000);
|
||||
});
|
||||
}
|
||||
sendNotification(method, params = {}) {
|
||||
const notification = {
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params
|
||||
};
|
||||
this.sendMessage(notification);
|
||||
}
|
||||
sendMessage(message) {
|
||||
if (!this.isConnected) {
|
||||
this.messageQueue.push(message);
|
||||
this.emit('message_queued', message);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const messageStr = JSON.stringify(message);
|
||||
this.ws.send(messageStr);
|
||||
this.emit('message_sent', message);
|
||||
} catch (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
this.emit('send_error', error);
|
||||
}
|
||||
}
|
||||
handleMessage(event) {
|
||||
try {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.method === 'pong') {
|
||||
this.lastPongReceived = Date.now();
|
||||
return;
|
||||
}
|
||||
if (message.id !== undefined && this.requestHandlers.has(message.id)) {
|
||||
const handler = this.requestHandlers.get(message.id);
|
||||
this.requestHandlers.delete(message.id);
|
||||
if (message.error) {
|
||||
handler.reject(new Error(message.error.message || 'Request failed'));
|
||||
} else {
|
||||
handler.resolve(message.result);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (message.method) {
|
||||
this.emit('notification', message);
|
||||
this.emit(`notification_${message.method}`, message.params);
|
||||
}
|
||||
this.emit('message_received', message);
|
||||
} catch (error) {
|
||||
console.error('Failed to parse WebSocket message:', error);
|
||||
this.emit('parse_error', error);
|
||||
}
|
||||
}
|
||||
handleDisconnection(event) {
|
||||
const wasConnected = this.isConnected;
|
||||
this.isConnected = false;
|
||||
this.isConnecting = false;
|
||||
this.stopHeartbeat();
|
||||
console.log('WebSocket disconnected:', event.code, event.reason);
|
||||
if (wasConnected) {
|
||||
this.emit('disconnected', {
|
||||
code: event.code,
|
||||
reason: event.reason
|
||||
});
|
||||
if (event.code !== 1000 && this.reconnectAttempts < this.maxReconnectAttempts) {
|
||||
this.attemptReconnection();
|
||||
}
|
||||
}
|
||||
}
|
||||
async attemptReconnection() {
|
||||
this.reconnectAttempts++;
|
||||
const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
|
||||
console.log(`Attempting reconnection ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms`);
|
||||
this.emit('reconnecting', {
|
||||
attempt: this.reconnectAttempts,
|
||||
delay
|
||||
});
|
||||
setTimeout(async ()=>{
|
||||
try {
|
||||
await this.establishConnection();
|
||||
} catch (error) {
|
||||
console.error('Reconnection failed:', error);
|
||||
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
||||
this.emit('reconnection_failed');
|
||||
} else {
|
||||
this.attemptReconnection();
|
||||
}
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
startHeartbeat() {
|
||||
this.stopHeartbeat();
|
||||
this.heartbeatTimer = setInterval(()=>{
|
||||
if (this.isConnected) {
|
||||
const timeSinceLastPong = Date.now() - this.lastPongReceived;
|
||||
if (timeSinceLastPong > this.heartbeatInterval * 2) {
|
||||
console.warn('Heartbeat timeout - connection may be dead');
|
||||
this.ws.close(1006, 'Heartbeat timeout');
|
||||
return;
|
||||
}
|
||||
this.sendNotification('ping', {
|
||||
timestamp: Date.now()
|
||||
});
|
||||
}
|
||||
}, this.heartbeatInterval);
|
||||
}
|
||||
stopHeartbeat() {
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
processMessageQueue() {
|
||||
while(this.messageQueue.length > 0 && this.isConnected){
|
||||
const message = this.messageQueue.shift();
|
||||
this.sendMessage(message);
|
||||
}
|
||||
}
|
||||
generateMessageId() {
|
||||
return this.messageId++;
|
||||
}
|
||||
setupEventListeners() {
|
||||
document.addEventListener('visibilitychange', ()=>{
|
||||
if (document.hidden) {
|
||||
this.heartbeatInterval = 60000;
|
||||
} else {
|
||||
this.heartbeatInterval = 30000;
|
||||
if (this.isConnected) {
|
||||
this.startHeartbeat();
|
||||
}
|
||||
}
|
||||
});
|
||||
window.addEventListener('beforeunload', ()=>{
|
||||
if (this.isConnected) {
|
||||
this.disconnect();
|
||||
}
|
||||
});
|
||||
}
|
||||
on(event, callback) {
|
||||
if (!this.eventListeners.has(event)) {
|
||||
this.eventListeners.set(event, []);
|
||||
}
|
||||
this.eventListeners.get(event).push(callback);
|
||||
}
|
||||
off(event, callback) {
|
||||
if (this.eventListeners.has(event)) {
|
||||
const listeners = this.eventListeners.get(event);
|
||||
const index = listeners.indexOf(callback);
|
||||
if (index > -1) {
|
||||
listeners.splice(index, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
emit(event, data = null) {
|
||||
if (this.eventListeners.has(event)) {
|
||||
this.eventListeners.get(event).forEach((callback)=>{
|
||||
try {
|
||||
callback(data);
|
||||
} catch (error) {
|
||||
console.error('Error in event listener:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
getStatus() {
|
||||
return {
|
||||
connected: this.isConnected,
|
||||
connecting: this.isConnecting,
|
||||
url: this.url,
|
||||
reconnectAttempts: this.reconnectAttempts,
|
||||
queuedMessages: this.messageQueue.length,
|
||||
pendingRequests: this.requestHandlers.size
|
||||
};
|
||||
}
|
||||
async initializeSession(clientInfo = {}) {
|
||||
const params = {
|
||||
protocolVersion: {
|
||||
major: 2024,
|
||||
minor: 11,
|
||||
patch: 5
|
||||
},
|
||||
clientInfo: {
|
||||
name: 'Claude Flow v2',
|
||||
version: '2.0.0',
|
||||
...clientInfo
|
||||
},
|
||||
capabilities: {
|
||||
logging: {
|
||||
level: 'info'
|
||||
},
|
||||
tools: {
|
||||
listChanged: true
|
||||
},
|
||||
resources: {
|
||||
listChanged: false,
|
||||
subscribe: false
|
||||
},
|
||||
prompts: {
|
||||
listChanged: false
|
||||
}
|
||||
}
|
||||
};
|
||||
try {
|
||||
const result = await this.sendRequest('initialize', params);
|
||||
this.emit('session_initialized', result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.emit('session_error', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async executeCommand(command, args = {}) {
|
||||
try {
|
||||
const result = await this.sendRequest('tools/call', {
|
||||
name: 'claude-flow/execute',
|
||||
arguments: {
|
||||
command,
|
||||
args
|
||||
}
|
||||
});
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('Command execution failed:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async getAvailableTools() {
|
||||
try {
|
||||
const result = await this.sendRequest('tools/list');
|
||||
return result && result.tools ? result.tools : [];
|
||||
} catch (error) {
|
||||
console.error('Failed to get tools:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
async getHealthStatus() {
|
||||
try {
|
||||
return await this.sendRequest('tools/call', {
|
||||
name: 'system/health'
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to get health status:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=websocket-client.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/websocket-client.js"],"sourcesContent":["/**\n * WebSocket Client for Claude Code Console\n * Handles real-time communication with the backend MCP server\n */\n\nexport class WebSocketClient {\n constructor() {\n this.ws = null;\n this.url = '';\n this.authToken = '';\n this.isConnected = false;\n this.isConnecting = false;\n this.reconnectAttempts = 0;\n this.maxReconnectAttempts = 5;\n this.reconnectDelay = 1000;\n this.messageQueue = [];\n this.requestHandlers = new Map();\n this.eventListeners = new Map();\n this.messageId = 1;\n\n // Heartbeat configuration\n this.heartbeatInterval = 30000; // 30 seconds\n this.heartbeatTimer = null;\n this.lastPongReceived = Date.now();\n this.connectionTimeout = 10000; // 10 seconds\n\n this.setupEventListeners();\n }\n\n /**\n * Connect to WebSocket server\n */\n async connect(url, authToken = '') {\n if (this.isConnecting || this.isConnected) {\n console.warn('Already connected or connecting');\n return;\n }\n\n this.url = url;\n this.authToken = authToken;\n this.isConnecting = true;\n\n try {\n await this.establishConnection();\n } catch (error) {\n this.isConnecting = false;\n throw error;\n }\n }\n\n /**\n * Establish WebSocket connection\n */\n async establishConnection() {\n return new Promise((resolve, reject) => {\n try {\n // Create WebSocket connection\n this.ws = new WebSocket(this.url);\n\n // Set up connection timeout\n const connectionTimer = setTimeout(() => {\n if (this.ws && this.ws.readyState !== WebSocket.OPEN) {\n this.ws.close();\n this.isConnecting = false;\n reject(new Error('Connection timeout'));\n }\n }, this.connectionTimeout);\n\n this.ws.onopen = () => {\n clearTimeout(connectionTimer);\n this.isConnected = true;\n this.isConnecting = false;\n this.reconnectAttempts = 0;\n this.lastPongReceived = Date.now();\n\n this.emit('connected');\n this.startHeartbeat();\n this.processMessageQueue();\n\n console.log('WebSocket connected to:', this.url);\n resolve();\n };\n\n this.ws.onclose = (event) => {\n clearTimeout(connectionTimer);\n this.handleDisconnection(event);\n };\n\n this.ws.onerror = (error) => {\n clearTimeout(connectionTimer);\n console.error('WebSocket error:', error);\n this.isConnecting = false;\n this.emit('error', error);\n\n if (!this.isConnected) {\n reject(error);\n }\n };\n\n this.ws.onmessage = (event) => {\n this.handleMessage(event);\n };\n } catch (error) {\n this.isConnecting = false;\n reject(error);\n }\n });\n }\n\n /**\n * Disconnect from WebSocket server\n */\n disconnect() {\n if (this.ws) {\n this.stopHeartbeat();\n this.ws.close(1000, 'User initiated disconnect');\n this.ws = null;\n }\n\n this.isConnected = false;\n this.isConnecting = false;\n this.reconnectAttempts = 0;\n this.messageQueue = [];\n this.requestHandlers.clear();\n\n this.emit('disconnected');\n }\n\n /**\n * Send a request and wait for response\n */\n async sendRequest(method, params = {}) {\n const id = this.generateMessageId();\n const request = {\n jsonrpc: '2.0',\n id,\n method,\n params,\n };\n\n return new Promise((resolve, reject) => {\n // Store request handler\n this.requestHandlers.set(id, { resolve, reject });\n\n // Send request\n this.sendMessage(request);\n\n // Set timeout for request\n setTimeout(() => {\n if (this.requestHandlers.has(id)) {\n this.requestHandlers.delete(id);\n reject(new Error(`Request timeout for method: ${method}`));\n }\n }, 30000); // 30 second timeout\n });\n }\n\n /**\n * Send a notification (no response expected)\n */\n sendNotification(method, params = {}) {\n const notification = {\n jsonrpc: '2.0',\n method,\n params,\n };\n\n this.sendMessage(notification);\n }\n\n /**\n * Send raw message\n */\n sendMessage(message) {\n if (!this.isConnected) {\n // Queue message for later\n this.messageQueue.push(message);\n this.emit('message_queued', message);\n return;\n }\n\n try {\n const messageStr = JSON.stringify(message);\n this.ws.send(messageStr);\n this.emit('message_sent', message);\n } catch (error) {\n console.error('Failed to send message:', error);\n this.emit('send_error', error);\n }\n }\n\n /**\n * Handle incoming messages\n */\n handleMessage(event) {\n try {\n const message = JSON.parse(event.data);\n\Line truncated
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/console/js/workflow-designer.js"],"sourcesContent":["/**\n * Advanced Workflow Designer for Claude Flow\n * Visual drag-and-drop workflow builder with real-time execution\n */\n\nclass WorkflowDesigner {\n constructor(containerId) {\n this.container = document.getElementById(containerId);\n this.canvas = null;\n this.ctx = null;\n this.nodes = new Map();\n this.connections = new Map();\n this.selectedNode = null;\n this.draggedNode = null;\n this.dragOffset = { x: 0, y: 0 };\n this.connectionStart = null;\n this.executionState = new Map();\n this.isExecuting = false;\n this.zoom = 1;\n this.pan = { x: 0, y: 0 };\n\n this.init();\n }\n\n init() {\n this.createUI();\n this.setupEventListeners();\n this.loadTemplates();\n this.setupNodePalette();\n }\n\n createUI() {\n this.container.innerHTML = `\n <div class=\"workflow-designer\">\n <div class=\"toolbar\">\n <div class=\"toolbar-section\">\n <button class=\"btn btn-primary\" id=\"saveWorkflow\">\n <i class=\"fas fa-save\"></i> Save\n </button>\n <button class=\"btn btn-secondary\" id=\"loadWorkflow\">\n <i class=\"fas fa-folder-open\"></i> Load\n </button>\n <button class=\"btn btn-success\" id=\"exportWorkflow\">\n <i class=\"fas fa-download\"></i> Export\n </button>\n <button class=\"btn btn-info\" id=\"importWorkflow\">\n <i class=\"fas fa-upload\"></i> Import\n </button>\n <input type=\"file\" id=\"importFile\" accept=\".json\" style=\"display: none;\">\n </div>\n <div class=\"toolbar-section\">\n <button class=\"btn btn-warning\" id=\"validateWorkflow\">\n <i class=\"fas fa-check-circle\"></i> Validate\n </button>\n <button class=\"btn btn-success\" id=\"executeWorkflow\">\n <i class=\"fas fa-play\"></i> Execute\n </button>\n <button class=\"btn btn-danger\" id=\"stopWorkflow\">\n <i class=\"fas fa-stop\"></i> Stop\n </button>\n </div>\n <div class=\"toolbar-section\">\n <button class=\"btn btn-secondary\" id=\"zoomIn\">\n <i class=\"fas fa-search-plus\"></i>\n </button>\n <button class=\"btn btn-secondary\" id=\"zoomOut\">\n <i class=\"fas fa-search-minus\"></i>\n </button>\n <button class=\"btn btn-secondary\" id=\"zoomReset\">\n <i class=\"fas fa-expand-arrows-alt\"></i>\n </button>\n <button class=\"btn btn-secondary\" id=\"clearCanvas\">\n <i class=\"fas fa-trash\"></i> Clear\n </button>\n </div>\n </div>\n \n <div class=\"designer-body\">\n <div class=\"node-palette\">\n <div class=\"palette-header\">\n <h3>Components</h3>\n <div class=\"palette-search\">\n <input type=\"text\" placeholder=\"Search components...\" id=\"paletteSearch\">\n </div>\n </div>\n <div class=\"palette-content\">\n <div class=\"palette-category\" data-category=\"input\">\n <h4>Input</h4>\n <div class=\"palette-items\"></div>\n </div>\n <div class=\"palette-category\" data-category=\"processing\">\n <h4>Processing</h4>\n <div class=\"palette-items\"></div>\n </div>\n <div class=\"palette-category\" data-category=\"output\">\n <h4>Output</h4>\n <div class=\"palette-items\"></div>\n </div>\n <div class=\"palette-category\" data-category=\"control\">\n <h4>Control Flow</h4>\n <div class=\"palette-items\"></div>\n </div>\n <div class=\"palette-category\" data-category=\"ai\">\n Line truncated
|
||||
@@ -1,220 +0,0 @@
|
||||
const testReport = {
|
||||
timestamp: new Date().toISOString(),
|
||||
passed: [],
|
||||
failed: [],
|
||||
warnings: []
|
||||
};
|
||||
function logTest(name, passed, message = '') {
|
||||
if (passed) {
|
||||
testReport.passed.push(name);
|
||||
console.log(`✅ ${name}`);
|
||||
} else {
|
||||
testReport.failed.push({
|
||||
name,
|
||||
message
|
||||
});
|
||||
console.error(`❌ ${name}: ${message}`);
|
||||
}
|
||||
}
|
||||
function logWarning(message) {
|
||||
testReport.warnings.push(message);
|
||||
console.warn(`⚠️ ${message}`);
|
||||
}
|
||||
function testPanelExists() {
|
||||
const panel = document.getElementById('neuralNetworksPanel');
|
||||
logTest('Neural Networks Panel Exists', !!panel, panel ? '' : 'Panel element not found');
|
||||
return !!panel;
|
||||
}
|
||||
function testToggleButton() {
|
||||
const button = document.getElementById('neuralToggle');
|
||||
logTest('Neural Toggle Button Exists', !!button, button ? '' : 'Toggle button not found');
|
||||
return !!button;
|
||||
}
|
||||
function testPanelToggle() {
|
||||
const button = document.getElementById('neuralToggle');
|
||||
const panel = document.getElementById('neuralNetworksPanel');
|
||||
if (!button || !panel) {
|
||||
logTest('Panel Toggle Functionality', false, 'Required elements not found');
|
||||
return false;
|
||||
}
|
||||
const initiallyHidden = panel.classList.contains('hidden');
|
||||
button.click();
|
||||
const afterClickHidden = panel.classList.contains('hidden');
|
||||
const toggled = initiallyHidden !== afterClickHidden;
|
||||
logTest('Panel Toggle Functionality', toggled, toggled ? '' : 'Panel did not toggle');
|
||||
if (afterClickHidden) {
|
||||
button.click();
|
||||
}
|
||||
return toggled;
|
||||
}
|
||||
function testTabSwitching() {
|
||||
const tabs = [
|
||||
'tools',
|
||||
'training',
|
||||
'models',
|
||||
'patterns',
|
||||
'performance'
|
||||
];
|
||||
let allTabsWork = true;
|
||||
tabs.forEach((tabName)=>{
|
||||
const tabButton = document.querySelector(`[data-tab="${tabName}"]`);
|
||||
const tabContent = document.querySelector(`.neural-tab-content[data-tab="${tabName}"]`);
|
||||
if (!tabButton || !tabContent) {
|
||||
logTest(`Tab "${tabName}" exists`, false, `Tab button or content not found`);
|
||||
allTabsWork = false;
|
||||
return;
|
||||
}
|
||||
tabButton.click();
|
||||
const isActive = tabButton.classList.contains('active') && tabContent.classList.contains('active');
|
||||
logTest(`Tab "${tabName}" switching`, isActive, isActive ? '' : 'Tab did not activate properly');
|
||||
if (!isActive) allTabsWork = false;
|
||||
});
|
||||
return allTabsWork;
|
||||
}
|
||||
function testToolCards() {
|
||||
const toolsTab = document.querySelector('[data-tab="tools"]');
|
||||
if (toolsTab) toolsTab.click();
|
||||
const toolCards = document.querySelectorAll('.neural-tool-card');
|
||||
logTest('Tool cards exist', toolCards.length > 0, `Found ${toolCards.length} tool cards`);
|
||||
if (toolCards.length === 0) return false;
|
||||
let allButtonsWork = true;
|
||||
toolCards.forEach((card, index)=>{
|
||||
const executeBtn = card.querySelector('[data-action="execute"]');
|
||||
const configureBtn = card.querySelector('[data-action="configure"]');
|
||||
if (!executeBtn || !configureBtn) {
|
||||
logWarning(`Tool card ${index} missing buttons`);
|
||||
allButtonsWork = false;
|
||||
}
|
||||
});
|
||||
logTest('All tool cards have buttons', allButtonsWork);
|
||||
return allButtonsWork;
|
||||
}
|
||||
function testTrainingControls() {
|
||||
const trainingTab = document.querySelector('[data-tab="training"]');
|
||||
if (trainingTab) trainingTab.click();
|
||||
const controls = {
|
||||
'Training Type Select': document.getElementById('trainingType'),
|
||||
'Training Data Textarea': document.getElementById('trainingData'),
|
||||
'Epochs Input': document.getElementById('trainingEpochs'),
|
||||
'Learning Rate Input': document.getElementById('learningRate'),
|
||||
'Start Training Button': document.getElementById('startTraining'),
|
||||
'Stop Training Button': document.getElementById('stopTraining')
|
||||
};
|
||||
let allControlsExist = true;
|
||||
Object.entries(controls).forEach(([name, element])=>{
|
||||
const exists = !!element;
|
||||
logTest(`${name} exists`, exists, exists ? '' : 'Control not found');
|
||||
if (!exists) allControlsExist = false;
|
||||
});
|
||||
return allControlsExist;
|
||||
}
|
||||
function testModelControls() {
|
||||
const modelsTab = document.querySelector('[data-tab="models"]');
|
||||
if (modelsTab) modelsTab.click();
|
||||
const loadButton = document.getElementById('loadModel');
|
||||
const createButton = document.getElementById('createModel');
|
||||
const modelsGrid = document.getElementById('modelsGrid');
|
||||
logTest('Load Model button exists', !!loadButton);
|
||||
logTest('Create Model button exists', !!createButton);
|
||||
logTest('Models Grid exists', !!modelsGrid);
|
||||
return !!(loadButton && createButton && modelsGrid);
|
||||
}
|
||||
function testPatternControls() {
|
||||
const patternsTab = document.querySelector('[data-tab="patterns"]');
|
||||
if (patternsTab) patternsTab.click();
|
||||
const analyzeButton = document.getElementById('analyzePatterns');
|
||||
const recognizeButton = document.getElementById('recognizePatterns');
|
||||
const behaviorButton = document.getElementById('analyzeBehavior');
|
||||
const behaviorInput = document.getElementById('behaviorInput');
|
||||
logTest('Analyze Patterns button exists', !!analyzeButton);
|
||||
logTest('Recognize Patterns button exists', !!recognizeButton);
|
||||
logTest('Analyze Behavior button exists', !!behaviorButton);
|
||||
logTest('Behavior Input exists', !!behaviorInput);
|
||||
return !!(analyzeButton && recognizeButton && behaviorButton && behaviorInput);
|
||||
}
|
||||
function testPerformanceControls() {
|
||||
const performanceTab = document.querySelector('[data-tab="performance"]');
|
||||
if (performanceTab) performanceTab.click();
|
||||
const optimizeButton = document.getElementById('optimizeWasm');
|
||||
const compressButton = document.getElementById('compressModels');
|
||||
const benchmarkButton = document.getElementById('runBenchmark');
|
||||
logTest('Optimize WASM button exists', !!optimizeButton);
|
||||
logTest('Compress Models button exists', !!compressButton);
|
||||
logTest('Run Benchmark button exists', !!benchmarkButton);
|
||||
return !!(optimizeButton && compressButton && benchmarkButton);
|
||||
}
|
||||
function testHeaderButtons() {
|
||||
const refreshButton = document.getElementById('refreshNeuralData');
|
||||
const exportButton = document.getElementById('exportNeuralData');
|
||||
const closeButton = document.getElementById('closeNeuralPanel');
|
||||
logTest('Refresh button exists', !!refreshButton);
|
||||
logTest('Export button exists', !!exportButton);
|
||||
logTest('Close button exists', !!closeButton);
|
||||
return !!(refreshButton && exportButton && closeButton);
|
||||
}
|
||||
function testVisualElements() {
|
||||
const statusIndicator = document.getElementById('neuralStatusIndicator');
|
||||
const statusText = document.getElementById('neuralStatusText');
|
||||
const performanceMetrics = document.getElementById('performanceMetrics');
|
||||
logTest('Status indicator exists', !!statusIndicator);
|
||||
logTest('Status text exists', !!statusText);
|
||||
return !!(statusIndicator && statusText);
|
||||
}
|
||||
function testWebSocketIntegration() {
|
||||
const hasNeuralPanel = window.neuralPanel && window.neuralPanel.panel;
|
||||
const hasExtended = window.neuralPanel && window.neuralPanel.extended;
|
||||
logTest('Neural panel global object exists', hasNeuralPanel);
|
||||
logTest('Neural extended functionality exists', hasExtended);
|
||||
if (hasNeuralPanel) {
|
||||
const panel = window.neuralPanel.panel;
|
||||
logTest('Panel is initialized', panel.isInitialized);
|
||||
logTest('WebSocket client exists', !!panel.wsClient);
|
||||
}
|
||||
return hasNeuralPanel && hasExtended;
|
||||
}
|
||||
async function runAllTests() {
|
||||
console.log('🧪 Starting Neural Networks Dialog Tests...\n');
|
||||
if (document.readyState !== 'complete') {
|
||||
await new Promise((resolve)=>window.addEventListener('load', resolve));
|
||||
}
|
||||
await new Promise((resolve)=>setTimeout(resolve, 1000));
|
||||
testPanelExists();
|
||||
testToggleButton();
|
||||
testPanelToggle();
|
||||
testTabSwitching();
|
||||
testToolCards();
|
||||
testTrainingControls();
|
||||
testModelControls();
|
||||
testPatternControls();
|
||||
testPerformanceControls();
|
||||
testHeaderButtons();
|
||||
testVisualElements();
|
||||
testWebSocketIntegration();
|
||||
console.log('\n📊 Test Report Summary:');
|
||||
console.log(`✅ Passed: ${testReport.passed.length}`);
|
||||
console.log(`❌ Failed: ${testReport.failed.length}`);
|
||||
console.log(`⚠️ Warnings: ${testReport.warnings.length}`);
|
||||
if (testReport.failed.length > 0) {
|
||||
console.log('\n❌ Failed Tests:');
|
||||
testReport.failed.forEach((failure)=>{
|
||||
console.log(` - ${failure.name}: ${failure.message}`);
|
||||
});
|
||||
}
|
||||
if (testReport.warnings.length > 0) {
|
||||
console.log('\n⚠️ Warnings:');
|
||||
testReport.warnings.forEach((warning)=>{
|
||||
console.log(` - ${warning}`);
|
||||
});
|
||||
}
|
||||
return testReport;
|
||||
}
|
||||
window.testNeuralNetworks = runAllTests;
|
||||
if (document.readyState === 'complete') {
|
||||
runAllTests();
|
||||
} else {
|
||||
window.addEventListener('load', ()=>{
|
||||
setTimeout(runAllTests, 1000);
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=test-neural-networks.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../src/ui/console/test-neural-networks.js"],"sourcesContent":["/**\n * Neural Networks Dialog Test Script\n * Tests all functionality of the neural networks panel\n */\n\n// Test report object\nconst testReport = {\n timestamp: new Date().toISOString(),\n passed: [],\n failed: [],\n warnings: [],\n};\n\n// Helper function to log test results\nfunction logTest(name, passed, message = '') {\n if (passed) {\n testReport.passed.push(name);\n console.log(`✅ ${name}`);\n } else {\n testReport.failed.push({ name, message });\n console.error(`❌ ${name}: ${message}`);\n }\n}\n\n// Helper function to log warnings\nfunction logWarning(message) {\n testReport.warnings.push(message);\n console.warn(`⚠️ ${message}`);\n}\n\n// Test 1: Check if neural networks panel exists\nfunction testPanelExists() {\n const panel = document.getElementById('neuralNetworksPanel');\n logTest('Neural Networks Panel Exists', !!panel, panel ? '' : 'Panel element not found');\n return !!panel;\n}\n\n// Test 2: Check if toggle button exists\nfunction testToggleButton() {\n const button = document.getElementById('neuralToggle');\n logTest('Neural Toggle Button Exists', !!button, button ? '' : 'Toggle button not found');\n return !!button;\n}\n\n// Test 3: Test panel toggle functionality\nfunction testPanelToggle() {\n const button = document.getElementById('neuralToggle');\n const panel = document.getElementById('neuralNetworksPanel');\n\n if (!button || !panel) {\n logTest('Panel Toggle Functionality', false, 'Required elements not found');\n return false;\n }\n\n // Check initial state\n const initiallyHidden = panel.classList.contains('hidden');\n\n // Click to toggle\n button.click();\n\n // Check if state changed\n const afterClickHidden = panel.classList.contains('hidden');\n const toggled = initiallyHidden !== afterClickHidden;\n\n logTest('Panel Toggle Functionality', toggled, toggled ? '' : 'Panel did not toggle');\n\n // If panel is now visible, keep it open for further tests\n if (afterClickHidden) {\n button.click();\n }\n\n return toggled;\n}\n\n// Test 4: Check all tabs exist and can be switched\nfunction testTabSwitching() {\n const tabs = ['tools', 'training', 'models', 'patterns', 'performance'];\n let allTabsWork = true;\n\n tabs.forEach((tabName) => {\n const tabButton = document.querySelector(`[data-tab=\"${tabName}\"]`);\n const tabContent = document.querySelector(`.neural-tab-content[data-tab=\"${tabName}\"]`);\n\n if (!tabButton || !tabContent) {\n logTest(`Tab \"${tabName}\" exists`, false, `Tab button or content not found`);\n allTabsWork = false;\n return;\n }\n\n // Click the tab\n tabButton.click();\n\n // Check if tab is active\n const isActive =\n tabButton.classList.contains('active') && tabContent.classList.contains('active');\n logTest(\n `Tab \"${tabName}\" switching`,\n isActive,\n isActive ? '' : 'Tab did not activate properly',\n );\n\n if (!isActive) allTabsWork = false;\n });\n\n return allTabsWork;\n}\n\n// Test 5: Check tool cards and their buttons\nfunction testToolCards() {\n // Switch to tools tab first\n const toolsTab = document.querySelector('[data-tab=\"tools\"]');\n if (toolsTab) toolsTab.click();\n\n const toolCards = document.querySelectorAll('.neural-tool-card');\n logTest('Tool cards exist', toolCards.length > 0, `Found ${toolCards.length} tool cards`);\n\n if (toolCards.length === 0) return false;\n\n let allButtonsWork = true;\n toolCards.forEach((card, index) => {\n const executeBtn = card.querySelector('[data-action=\"execute\"]');\n const configureBtn = card.querySelector('[data-action=\"configure\"]');\n\n if (!executeBtn || !configureBtn) {\n logWarning(`Tool card ${index} missing buttons`);\n allButtonsWork = false;\n }\n });\n\n logTest('All tool cards have buttons', allButtonsWork);\n return allButtonsWork;\n}\n\n// Test 6: Check training controls\nfunction testTrainingControls() {\n // Switch to training tab\n const trainingTab = document.querySelector('[data-tab=\"training\"]');\n if (trainingTab) trainingTab.click();\n\n const controls = {\n 'Training Type Select': document.getElementById('trainingType'),\n 'Training Data Textarea': document.getElementById('trainingData'),\n 'Epochs Input': document.getElementById('trainingEpochs'),\n 'Learning Rate Input': document.getElementById('learningRate'),\n 'Start Training Button': document.getElementById('startTraining'),\n 'Stop Training Button': document.getElementById('stopTraining'),\n };\n\n let allControlsExist = true;\n Object.entries(controls).forEach(([name, element]) => {\n const exists = !!element;\n logTest(`${name} exists`, exists, exists ? '' : 'Control not found');\n if (!exists) allControlsExist = false;\n });\n\n return allControlsExist;\n}\n\n// Test 7: Check model management controls\nfLine truncated
|
||||
@@ -1,240 +0,0 @@
|
||||
export class HiveDashboard {
|
||||
orchestrator;
|
||||
protocol;
|
||||
refreshInterval = 1000;
|
||||
updateCallback;
|
||||
constructor(orchestrator, protocol){
|
||||
this.orchestrator = orchestrator;
|
||||
this.protocol = protocol;
|
||||
}
|
||||
startMonitoring(callback) {
|
||||
this.updateCallback = callback;
|
||||
this.update();
|
||||
const interval = setInterval(()=>{
|
||||
this.update();
|
||||
}, this.refreshInterval);
|
||||
return ()=>clearInterval(interval);
|
||||
}
|
||||
update() {
|
||||
const data = this.collectDashboardData();
|
||||
if (this.updateCallback) {
|
||||
this.updateCallback(data);
|
||||
}
|
||||
}
|
||||
collectDashboardData() {
|
||||
const perfMetrics = this.orchestrator.getPerformanceMetrics();
|
||||
const commStats = this.protocol.getStatistics();
|
||||
return {
|
||||
swarmId: 'current-swarm',
|
||||
status: this.determineSwarmStatus(perfMetrics),
|
||||
agents: this.getAgentStatuses(),
|
||||
tasks: this.getTaskProgress(),
|
||||
consensus: this.getConsensusMetrics(),
|
||||
communication: this.getCommunicationStats(commStats),
|
||||
performance: this.getPerformanceMetrics(perfMetrics),
|
||||
timestamp: Date.now()
|
||||
};
|
||||
}
|
||||
determineSwarmStatus(metrics) {
|
||||
if (metrics.executingTasks > 0) return 'executing';
|
||||
if (metrics.pendingTasks > 0) return 'active';
|
||||
if (metrics.completedTasks === metrics.totalTasks) return 'completed';
|
||||
return 'initializing';
|
||||
}
|
||||
getAgentStatuses() {
|
||||
return [
|
||||
{
|
||||
id: 'queen-1',
|
||||
name: 'Queen-Genesis',
|
||||
type: 'queen',
|
||||
status: 'thinking',
|
||||
workload: 85,
|
||||
votes: 15,
|
||||
contributions: 42
|
||||
},
|
||||
{
|
||||
id: 'architect-1',
|
||||
name: 'Architect-1',
|
||||
type: 'architect',
|
||||
status: 'executing',
|
||||
currentTask: 'Design system architecture',
|
||||
workload: 70,
|
||||
votes: 8,
|
||||
contributions: 23
|
||||
},
|
||||
{
|
||||
id: 'worker-1',
|
||||
name: 'Worker-1',
|
||||
type: 'worker',
|
||||
status: 'voting',
|
||||
workload: 45,
|
||||
votes: 12,
|
||||
contributions: 31
|
||||
}
|
||||
];
|
||||
}
|
||||
getTaskProgress() {
|
||||
const taskGraph = this.orchestrator.getTaskGraph();
|
||||
return taskGraph.nodes.map((node)=>({
|
||||
id: node.id,
|
||||
type: node.type,
|
||||
description: `${node.type} task`,
|
||||
status: node.status,
|
||||
assignedTo: node.assignedTo,
|
||||
progress: this.calculateTaskProgress(node.status),
|
||||
dependencies: []
|
||||
}));
|
||||
}
|
||||
calculateTaskProgress(status) {
|
||||
switch(status){
|
||||
case 'completed':
|
||||
return 100;
|
||||
case 'executing':
|
||||
return 50;
|
||||
case 'assigned':
|
||||
return 25;
|
||||
case 'voting':
|
||||
return 10;
|
||||
case 'pending':
|
||||
return 0;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
getConsensusMetrics() {
|
||||
const metrics = this.orchestrator.getPerformanceMetrics();
|
||||
return {
|
||||
totalDecisions: metrics.totalDecisions,
|
||||
approvedDecisions: metrics.approvedDecisions,
|
||||
rejectedDecisions: metrics.totalDecisions - metrics.approvedDecisions,
|
||||
averageConsensus: metrics.consensusRate,
|
||||
currentVotes: []
|
||||
};
|
||||
}
|
||||
getCommunicationStats(stats) {
|
||||
return {
|
||||
totalMessages: stats.totalMessages,
|
||||
messageRate: stats.totalMessages / 10,
|
||||
channelActivity: stats.messagesByType,
|
||||
knowledgeShared: stats.knowledgeEntries
|
||||
};
|
||||
}
|
||||
getPerformanceMetrics(metrics) {
|
||||
return {
|
||||
tasksCompleted: metrics.completedTasks,
|
||||
tasksPending: metrics.pendingTasks,
|
||||
avgExecutionTime: metrics.avgExecutionTime,
|
||||
successRate: metrics.totalTasks > 0 ? metrics.completedTasks / metrics.totalTasks : 0,
|
||||
qualityScore: 0.85
|
||||
};
|
||||
}
|
||||
static formatConsoleOutput(data) {
|
||||
const output = [];
|
||||
output.push('🐝 Hive Mind Dashboard');
|
||||
output.push('═══════════════════════════════════════════════════════════════');
|
||||
output.push(`Status: ${data.status.toUpperCase()} | Time: ${new Date(data.timestamp).toLocaleTimeString()}`);
|
||||
output.push('');
|
||||
output.push('👥 Agent Status');
|
||||
output.push('───────────────────────────────────────────────────────────────');
|
||||
for (const agent of data.agents){
|
||||
const statusIcon = this.getStatusIcon(agent.status);
|
||||
const workloadBar = this.createProgressBar(agent.workload);
|
||||
output.push(`${statusIcon} ${agent.name} (${agent.type})`);
|
||||
output.push(` Status: ${agent.status} | Workload: ${workloadBar} ${agent.workload}%`);
|
||||
if (agent.currentTask) {
|
||||
output.push(` Task: ${agent.currentTask}`);
|
||||
}
|
||||
output.push(` Votes: ${agent.votes} | Contributions: ${agent.contributions}`);
|
||||
output.push('');
|
||||
}
|
||||
output.push('📋 Task Progress');
|
||||
output.push('───────────────────────────────────────────────────────────────');
|
||||
for (const task of data.tasks){
|
||||
const progressBar = this.createProgressBar(task.progress);
|
||||
const statusIcon = this.getTaskStatusIcon(task.status);
|
||||
output.push(`${statusIcon} ${task.type}: ${task.description}`);
|
||||
output.push(` Progress: ${progressBar} ${task.progress}%`);
|
||||
if (task.assignedTo) {
|
||||
output.push(` Assigned to: ${task.assignedTo}`);
|
||||
}
|
||||
output.push('');
|
||||
}
|
||||
output.push('🗳️ Consensus Metrics');
|
||||
output.push('───────────────────────────────────────────────────────────────');
|
||||
output.push(`Total Decisions: ${data.consensus.totalDecisions}`);
|
||||
output.push(`Approved: ${data.consensus.approvedDecisions} | Rejected: ${data.consensus.rejectedDecisions}`);
|
||||
output.push(`Average Consensus: ${(data.consensus.averageConsensus * 100).toFixed(1)}%`);
|
||||
output.push('');
|
||||
output.push('📊 Performance');
|
||||
output.push('───────────────────────────────────────────────────────────────');
|
||||
output.push(`Tasks: ${data.performance.tasksCompleted}/${data.performance.tasksCompleted + data.performance.tasksPending} completed`);
|
||||
output.push(`Success Rate: ${(data.performance.successRate * 100).toFixed(1)}%`);
|
||||
output.push(`Quality Score: ${(data.performance.qualityScore * 100).toFixed(1)}%`);
|
||||
output.push(`Avg Execution Time: ${(data.performance.avgExecutionTime / 1000).toFixed(1)}s`);
|
||||
output.push('');
|
||||
output.push('💬 Communication');
|
||||
output.push('───────────────────────────────────────────────────────────────');
|
||||
output.push(`Total Messages: ${data.communication.totalMessages}`);
|
||||
output.push(`Message Rate: ${data.communication.messageRate.toFixed(1)}/min`);
|
||||
output.push(`Knowledge Shared: ${data.communication.knowledgeShared} entries`);
|
||||
return output.join('\\n');
|
||||
}
|
||||
static getStatusIcon(status) {
|
||||
switch(status){
|
||||
case 'idle':
|
||||
return '😴';
|
||||
case 'thinking':
|
||||
return '🤔';
|
||||
case 'voting':
|
||||
return '🗳️';
|
||||
case 'executing':
|
||||
return '⚡';
|
||||
case 'communicating':
|
||||
return '💬';
|
||||
default:
|
||||
return '❓';
|
||||
}
|
||||
}
|
||||
static getTaskStatusIcon(status) {
|
||||
switch(status){
|
||||
case 'pending':
|
||||
return '⭕';
|
||||
case 'voting':
|
||||
return '🗳️';
|
||||
case 'assigned':
|
||||
return '📌';
|
||||
case 'executing':
|
||||
return '🔄';
|
||||
case 'reviewing':
|
||||
return '🔍';
|
||||
case 'completed':
|
||||
return '✅';
|
||||
case 'failed':
|
||||
return '❌';
|
||||
default:
|
||||
return '❓';
|
||||
}
|
||||
}
|
||||
static createProgressBar(percentage, width = 20) {
|
||||
const filled = Math.round(percentage / 100 * width);
|
||||
const empty = width - filled;
|
||||
return `[${'█'.repeat(filled)}${' '.repeat(empty)}]`;
|
||||
}
|
||||
exportData() {
|
||||
const data = this.collectDashboardData();
|
||||
return JSON.stringify(data, null, 2);
|
||||
}
|
||||
getEventStream() {
|
||||
return async function*() {
|
||||
while(true){
|
||||
yield {
|
||||
type: 'update',
|
||||
timestamp: Date.now()
|
||||
};
|
||||
await new Promise((resolve)=>setTimeout(resolve, 1000));
|
||||
}
|
||||
}();
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=hive-dashboard.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../src/ui/hive-dashboard.ts"],"sourcesContent":["/**\n * Hive Mind Monitoring Dashboard\n * Real-time visualization of swarm activity and consensus\n */\n\nimport { HiveOrchestrator } from '../coordination/hive-orchestrator.js';\nimport { HiveCommunicationProtocol } from '../coordination/hive-protocol.js';\n\nexport interface HiveDashboardData {\n swarmId: string;\n status: 'initializing' | 'active' | 'voting' | 'executing' | 'completed';\n agents: AgentStatus[];\n tasks: TaskProgress[];\n consensus: ConsensusMetrics;\n communication: CommunicationStats;\n performance: PerformanceMetrics;\n timestamp: number;\n}\n\nexport interface AgentStatus {\n id: string;\n name: string;\n type: string;\n status: 'idle' | 'thinking' | 'voting' | 'executing' | 'communicating';\n currentTask?: string;\n workload: number; // 0-100\n votes: number;\n contributions: number;\n}\n\nexport interface TaskProgress {\n id: string;\n type: string;\n description: string;\n status: string;\n assignedTo?: string;\n progress: number; // 0-100\n dependencies: string[];\n votes?: { approve: number; reject: number };\n}\n\nexport interface ConsensusMetrics {\n totalDecisions: number;\n approvedDecisions: number;\n rejectedDecisions: number;\n averageConsensus: number;\n currentVotes: VoteStatus[];\n}\n\nexport interface VoteStatus {\n topic: string;\n votes: { for: number; against: number; pending: number };\n deadline?: number;\n}\n\nexport interface CommunicationStats {\n totalMessages: number;\n messageRate: number; // messages per minute\n channelActivity: Map<string, number>;\n knowledgeShared: number;\n}\n\nexport interface PerformanceMetrics {\n tasksCompleted: number;\n tasksPending: number;\n avgExecutionTime: number;\n successRate: number;\n qualityScore: number;\n}\n\nexport class HiveDashboard {\n private orchestrator: HiveOrchestrator;\n private protocol: HiveCommunicationProtocol;\n private refreshInterval: number = 1000; // 1 second\n private updateCallback?: (data: HiveDashboardData) => void;\n\n constructor(orchestrator: HiveOrchestrator, protocol: HiveCommunicationProtocol) {\n this.orchestrator = orchestrator;\n this.protocol = protocol;\n }\n\n /**\n * Start monitoring with callback for updates\n */\n startMonitoring(callback: (data: HiveDashboardData) => void) {\n this.updateCallback = callback;\n this.update();\n\n // Set up periodic updates\n const interval = setInterval(() => {\n this.update();\n }, this.refreshInterval);\n\n return () => clearInterval(interval);\n }\n\n /**\n * Get current dashboard data\n */\n private update() {\n const data = this.collectDashboardData();\n if (this.updateCallback) {\n this.updateCallback(data);\n }\n }\n\n /**\n * Collect all dashboard data\n */\n private collectDashboardData(): HiveDashboardData {\n const perfMetrics = this.orchestrator.getPerformanceMetrics();\n const commStats = this.protocol.getStatistics();\n\n return {\n swarmId: 'current-swarm',\n status: this.determineSwarmStatus(perfMetrics),\n agents: this.getAgentStatuses(),\n tasks: this.getTaskProgress(),\n consensus: this.getConsensusMetrics(),\n communication: this.getCommunicationStats(commStats),\n performance: this.getPerformanceMetrics(perfMetrics),\n timestamp: Date.now(),\n };\n }\n\n /**\n * Determine overall swarm status\n */\n private determineSwarmStatus(metrics: any): HiveDashboardData['status'] {\n if (metrics.executingTasks > 0) return 'executing';\n if (metrics.pendingTasks > 0) return 'active';\n if (metrics.completedTasks === metrics.totalTasks) return 'completed';\n return 'initializing';\n }\n\n /**\n * Get status of all agents\n */\n private getAgentStatuses(): AgentStatus[] {\n // This would be populated from actual agent data\n return [\n {\n id: 'queen-1',\n name: 'Queen-Genesis',\n type: 'queen',\n status: 'thinking',\n workload: 85,\n votes: 15,\n contributions: 42,\n },\n {\n id: 'architect-1',\n name: 'Architect-1',\n type: 'architect',\n status: 'executing',\n currentTask: 'Design system architecture',\n workload: 70,\n votes: 8,\n contributions: 23,\n },\n {\n id: 'worker-1',\n name: 'Worker-1',\n type: 'worker',\n status: 'voting',\n workload: 45,\n votes: 12,\n contributions: 31,\n },\n ];\n }\n\n /**\n * Get task progress information\n */\n private getTaskProgress(): TaskProgress[] {\n const taskGraph = this.orchestrator.getTaskGraph();\n return taskGraph.nodes.map((node) => ({\n id: node.id,\n type: node.type,\n description: `${node.type} task`,\n status: node.status,\n assignedTo: node.assignedTo,\n progress: this.calculateTaskProgresLine truncated
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../src/ui/web-ui/EnhancedProcessUI.js"],"sourcesContent":["/**\n * Enhanced Process UI - Upgraded version with modular architecture integration\n * Combines existing process management with 71+ MCP tools and advanced features\n */\n\nimport { printSuccess, printError, printWarning, printInfo } from '../../cli/utils.js';\nimport { compat } from '../../cli/runtime-detector.js';\nimport SwarmWebUIIntegration from '../../cli/simple-commands/swarm-webui-integration.js';\nimport EnhancedWebUI from './EnhancedWebUI.js';\n\n// Enhanced color utilities with more options\nconst colors = {\n cyan: (text) => `\\x1b[36m${text}\\x1b[0m`,\n gray: (text) => `\\x1b[90m${text}\\x1b[0m`,\n white: (text) => `\\x1b[37m${text}\\x1b[0m`,\n yellow: (text) => `\\x1b[33m${text}\\x1b[0m`,\n green: (text) => `\\x1b[32m${text}\\x1b[0m`,\n red: (text) => `\\x1b[31m${text}\\x1b[0m`,\n blue: (text) => `\\x1b[34m${text}\\x1b[0m`,\n magenta: (text) => `\\x1b[35m${text}\\x1b[0m`,\n bold: (text) => `\\x1b[1m${text}\\x1b[0m`,\n dim: (text) => `\\x1b[2m${text}\\x1b[0m`,\n bright: (text) => `\\x1b[97m${text}\\x1b[0m`,\n orange: (text) => `\\x1b[38;5;208m${text}\\x1b[0m`,\n purple: (text) => `\\x1b[35m${text}\\x1b[0m`,\n};\n\nconst PROCESSES = [\n { id: 'event-bus', name: 'Event Bus', description: 'Central event distribution system' },\n { id: 'orchestrator', name: 'Orchestrator', description: 'Main coordination engine' },\n { id: 'memory-manager', name: 'Memory Manager', description: 'Persistent memory system' },\n { id: 'terminal-pool', name: 'Terminal Pool', description: 'Terminal session management' },\n { id: 'mcp-server', name: 'MCP Server', description: 'Model Context Protocol server' },\n { id: 'coordinator', name: 'Coordinator', description: 'Task coordination service' },\n { id: 'enhanced-ui', name: 'Enhanced UI', description: 'Advanced web interface system' },\n { id: 'neural-engine', name: 'Neural Engine', description: 'AI neural network processor' },\n];\n\n// Enhanced view modes with new categories\nconst VIEWS = {\n OVERVIEW: 'overview',\n PROCESSES: 'processes',\n STATUS: 'status',\n ORCHESTRATION: 'orchestration',\n MEMORY: 'memory',\n NEURAL: 'neural',\n MONITORING: 'monitoring',\n WORKFLOW: 'workflow',\n GITHUB: 'github',\n DAA: 'daa',\n SYSTEM: 'system',\n CLI: 'cli',\n LOGS: 'logs',\n HELP: 'help',\n};\n\n// Tool category information\nconst TOOL_CATEGORIES = {\n neural: { icon: '🧠', name: 'Neural Network', count: 15, color: colors.cyan },\n memory: { icon: '💾', name: 'Memory Management', count: 10, color: colors.green },\n monitoring: { icon: '📊', name: 'Monitoring & Analysis', count: 13, color: colors.yellow },\n workflow: { icon: '🔄', name: 'Workflow & Automation', count: 11, color: colors.blue },\n github: { icon: '🐙', name: 'GitHub Integration', count: 8, color: colors.magenta },\n daa: { icon: '🤖', name: 'Dynamic Agents', count: 8, color: colors.purple },\n system: { icon: '🛠️', name: 'System Utilities', count: 6, color: colors.orange },\n cli: { icon: '⌨️', name: 'CLI Commands', count: 9, color: colors.white },\n};\n\nexport class EnhancedProcessUI {\n constructor() {\n this.processes = new Map();\n this.running = true;\n this.selectedIndex = 0;\n this.currentView = VIEWS.OVERVIEW;\n this.agents = [];\n this.tasks = [];\n this.memoryStats = {\n totalEntries: 0,\n totalSize: 0,\n namespaces: [],\n };\n this.logs = [];\n this.systemStats = {\n uptime: 0,\n totalTasks: 0,\n completedTasks: 0,\n activeAgents: 0,\n memoryUsage: 0,\n cpuUsage: 0,\n toolsAvailable: 71,\n enhancedMode: false,\n };\n\n // Enhanced UI integration\n this.enhancedWebUI = null;\n this.toolExecutions = new Map();\n this.recentTools = [];\n this.toolStats = new Map();\n\n // Initialize integrations\n this.swarmIntegration = new SwarmWebUIIntegration(this);\n\n // Initialize process states\n PROCESSES.forEach((p) => {\n this.processes.set(p.id, {\n ...p,\n status: 'stopped',\n pid: null,\n uptime: 0,\n cpu: Math.random() * 5,\n memory: Math.random() * 100,\n });\n });\n\n // Start system uptime counter\n setInterval(() => {\n this.systemStats.uptime++;\n }, 1000);\n\n // Initialize enhanced features\n this.initializeEnhancedFeatures();\n }\n\n /**\n * Initialize enhanced features\n */\n async initializeEnhancedFeatures() {\n try {\n // Initialize enhanced web UI\n this.enhancedWebUI = new EnhancedWebUI();\n await this.enhancedWebUI.initialize(this);\n\n this.systemStats.enhancedMode = true;\n this.addLog('success', 'Enhanced UI features initialized');\n\n // Set enhanced UI process as running\n const enhancedUIProcess = this.processes.get('enhanced-ui');\n if (enhancedUIProcess) {\n enhancedUIProcess.statuLine truncated
|
||||
@@ -1,420 +0,0 @@
|
||||
import UIManager from './core/UIManager.js';
|
||||
export class EnhancedWebUI {
|
||||
constructor(){
|
||||
this.uiManager = null;
|
||||
this.isInitialized = false;
|
||||
this.fallbackMode = false;
|
||||
this.originalProcessUI = null;
|
||||
}
|
||||
async initialize(existingProcessUI = null) {
|
||||
try {
|
||||
console.log('🚀 Initializing Enhanced Web UI...');
|
||||
this.originalProcessUI = existingProcessUI;
|
||||
try {
|
||||
this.uiManager = new UIManager();
|
||||
await this.uiManager.initialize();
|
||||
console.log('✅ Enhanced Web UI initialized successfully');
|
||||
this.isInitialized = true;
|
||||
} catch (error) {
|
||||
console.warn('⚠️ Full UI initialization failed, using fallback mode:', error);
|
||||
this.fallbackMode = true;
|
||||
await this.initializeFallbackMode();
|
||||
}
|
||||
if (this.originalProcessUI) {
|
||||
this.integrateWithExistingUI();
|
||||
}
|
||||
return this.isInitialized || this.fallbackMode;
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to initialize Enhanced Web UI:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async initializeFallbackMode() {
|
||||
console.log('🔄 Initializing fallback mode...');
|
||||
this.createFallbackUI();
|
||||
this.fallbackMode = true;
|
||||
console.log('✅ Fallback mode initialized');
|
||||
}
|
||||
createFallbackUI() {
|
||||
if (this.originalProcessUI) {
|
||||
this.addEnhancedViewsToProcessUI();
|
||||
} else {
|
||||
this.createStandaloneUI();
|
||||
}
|
||||
}
|
||||
addEnhancedViewsToProcessUI() {
|
||||
const enhancedViews = {
|
||||
NEURAL: 'neural',
|
||||
MEMORY_MGMT: 'memory_mgmt',
|
||||
MONITORING_ADV: 'monitoring_adv',
|
||||
WORKFLOW_MGMT: 'workflow_mgmt',
|
||||
GITHUB_INT: 'github_int',
|
||||
DAA_CONTROL: 'daa_control',
|
||||
SYSTEM_UTILS: 'system_utils',
|
||||
CLI_BRIDGE: 'cli_bridge'
|
||||
};
|
||||
if (this.originalProcessUI.constructor.VIEWS) {
|
||||
Object.assign(this.originalProcessUI.constructor.VIEWS, enhancedViews);
|
||||
}
|
||||
const originalRender = this.originalProcessUI.render.bind(this.originalProcessUI);
|
||||
this.originalProcessUI.render = ()=>{
|
||||
originalRender();
|
||||
this.handleEnhancedViews();
|
||||
};
|
||||
const originalHandleInput = this.originalProcessUI.handleViewSpecificInput.bind(this.originalProcessUI);
|
||||
this.originalProcessUI.handleViewSpecificInput = async (input)=>{
|
||||
if (await this.handleEnhancedInput(input)) {
|
||||
return;
|
||||
}
|
||||
return originalHandleInput(input);
|
||||
};
|
||||
}
|
||||
handleEnhancedViews() {
|
||||
if (!this.originalProcessUI.currentView) return;
|
||||
switch(this.originalProcessUI.currentView){
|
||||
case 'neural':
|
||||
this.renderNeuralView();
|
||||
break;
|
||||
case 'memory_mgmt':
|
||||
this.renderMemoryManagementView();
|
||||
break;
|
||||
case 'monitoring_adv':
|
||||
this.renderAdvancedMonitoringView();
|
||||
break;
|
||||
case 'workflow_mgmt':
|
||||
this.renderWorkflowManagementView();
|
||||
break;
|
||||
case 'github_int':
|
||||
this.renderGitHubIntegrationView();
|
||||
break;
|
||||
case 'daa_control':
|
||||
this.renderDAAControlView();
|
||||
break;
|
||||
case 'system_utils':
|
||||
this.renderSystemUtilitiesView();
|
||||
break;
|
||||
case 'cli_bridge':
|
||||
this.renderCLIBridgeView();
|
||||
break;
|
||||
}
|
||||
}
|
||||
async handleEnhancedInput(input) {
|
||||
const currentView = this.originalProcessUI.currentView;
|
||||
const enhancedShortcuts = {
|
||||
7: ()=>this.originalProcessUI.currentView = 'neural',
|
||||
8: ()=>this.originalProcessUI.currentView = 'memory_mgmt',
|
||||
9: ()=>this.originalProcessUI.currentView = 'monitoring_adv',
|
||||
0: ()=>this.originalProcessUI.currentView = 'workflow_mgmt'
|
||||
};
|
||||
if (enhancedShortcuts[input]) {
|
||||
enhancedShortcuts[input]();
|
||||
return true;
|
||||
}
|
||||
switch(currentView){
|
||||
case 'neural':
|
||||
return this.handleNeuralInput(input);
|
||||
case 'memory_mgmt':
|
||||
return this.handleMemoryInput(input);
|
||||
case 'monitoring_adv':
|
||||
return this.handleMonitoringInput(input);
|
||||
case 'workflow_mgmt':
|
||||
return this.handleWorkflowInput(input);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
createStandaloneUI() {
|
||||
console.log('🔧 Creating standalone enhanced UI...');
|
||||
console.log('\n🎨 Enhanced Web UI - Standalone Mode');
|
||||
console.log('═'.repeat(60));
|
||||
console.log('📊 Available Tool Categories:');
|
||||
console.log(' 🧠 Neural Network Tools (15 tools)');
|
||||
console.log(' 💾 Memory Management Tools (10 tools)');
|
||||
console.log(' 📊 Monitoring & Analysis Tools (13 tools)');
|
||||
console.log(' 🔄 Workflow & Automation Tools (11 tools)');
|
||||
console.log(' 🐙 GitHub Integration Tools (8 tools)');
|
||||
console.log(' 🤖 Dynamic Agent Architecture Tools (8 tools)');
|
||||
console.log(' 🛠️ System & Utilities Tools (6 tools)');
|
||||
console.log(' ⌨️ CLI Bridge Commands (9 commands)');
|
||||
console.log('═'.repeat(60));
|
||||
console.log('Total: 71+ tools and commands available');
|
||||
console.log('Use the enhanced UI manager for full functionality.');
|
||||
}
|
||||
async navigateToView(viewId, params = {}) {
|
||||
if (this.uiManager && !this.fallbackMode) {
|
||||
return await this.uiManager.navigateToView(viewId, params);
|
||||
} else {
|
||||
if (this.originalProcessUI) {
|
||||
this.originalProcessUI.currentView = viewId;
|
||||
this.originalProcessUI.selectedIndex = 0;
|
||||
} else {
|
||||
console.log(`📄 Navigating to view: ${viewId}`, params);
|
||||
}
|
||||
}
|
||||
}
|
||||
async executeTool(toolName, params = {}) {
|
||||
if (this.uiManager && !this.fallbackMode) {
|
||||
return await this.uiManager.executeMCPTool(toolName, params);
|
||||
} else {
|
||||
console.log(`🔧 Executing tool: ${toolName}`, params);
|
||||
await new Promise((resolve)=>setTimeout(resolve, 500));
|
||||
const mockResult = {
|
||||
success: true,
|
||||
tool: toolName,
|
||||
params,
|
||||
result: `Mock result for ${toolName}`,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
console.log(`✅ Tool ${toolName} completed:`, mockResult.result);
|
||||
return mockResult;
|
||||
}
|
||||
}
|
||||
async getSystemStatus() {
|
||||
if (this.uiManager && !this.fallbackMode) {
|
||||
return await this.uiManager.getSystemStatus();
|
||||
} else {
|
||||
return {
|
||||
mode: 'fallback',
|
||||
toolsAvailable: 71,
|
||||
uiManager: false,
|
||||
enhancedFeatures: false,
|
||||
originalProcessUI: !!this.originalProcessUI
|
||||
};
|
||||
}
|
||||
}
|
||||
integrateWithExistingUI() {
|
||||
console.log('🔗 Integrating with existing process UI...');
|
||||
this.addEnhancedNavigation();
|
||||
this.addToolPalette();
|
||||
this.addQuickActions();
|
||||
}
|
||||
addEnhancedNavigation() {
|
||||
console.log('📊 Added enhanced navigation tabs');
|
||||
}
|
||||
addToolPalette() {
|
||||
console.log('🎨 Added tool palette overlay');
|
||||
}
|
||||
addQuickActions() {
|
||||
console.log('⚡ Added quick action buttons');
|
||||
}
|
||||
renderNeuralView() {
|
||||
console.clear();
|
||||
console.log('🧠 Neural Network Operations');
|
||||
console.log('═'.repeat(50));
|
||||
console.log('Available Tools:');
|
||||
console.log(' [T] Train Neural Network');
|
||||
console.log(' [P] Make Prediction');
|
||||
console.log(' [S] Check Status');
|
||||
console.log(' [A] Analyze Patterns');
|
||||
console.log(' [M] Manage Models');
|
||||
console.log(' [O] Optimize WASM');
|
||||
console.log('\nPress a key to execute tool...');
|
||||
}
|
||||
renderMemoryManagementView() {
|
||||
console.clear();
|
||||
console.log('💾 Memory Management');
|
||||
console.log('═'.repeat(50));
|
||||
console.log('Available Tools:');
|
||||
console.log(' [S] Store Data');
|
||||
console.log(' [R] Retrieve Data');
|
||||
console.log(' [B] Backup Memory');
|
||||
console.log(' [C] Compress Data');
|
||||
console.log(' [Y] Sync Instances');
|
||||
console.log(' [A] Analytics');
|
||||
console.log('\nPress a key to execute tool...');
|
||||
}
|
||||
renderAdvancedMonitoringView() {
|
||||
console.clear();
|
||||
console.log('📊 Advanced Monitoring');
|
||||
console.log('═'.repeat(50));
|
||||
console.log('Available Tools:');
|
||||
console.log(' [P] Performance Report');
|
||||
console.log(' [B] Bottleneck Analysis');
|
||||
console.log(' [T] Token Usage');
|
||||
console.log(' [M] Metrics Collection');
|
||||
console.log(' [H] Health Check');
|
||||
console.log(' [E] Error Analysis');
|
||||
console.log('\nPress a key to execute tool...');
|
||||
}
|
||||
renderWorkflowManagementView() {
|
||||
console.clear();
|
||||
console.log('🔄 Workflow & Automation Management');
|
||||
console.log('═'.repeat(50));
|
||||
console.log('Available Tools (11):');
|
||||
console.log(' [C] Create Workflow');
|
||||
console.log(' [E] Execute Workflow');
|
||||
console.log(' [A] Setup Automation');
|
||||
console.log(' [P] Create Pipeline');
|
||||
console.log(' [S] Manage Scheduler');
|
||||
console.log(' [T] Setup Triggers');
|
||||
console.log(' [W] Workflow Templates');
|
||||
console.log(' [B] Batch Processing');
|
||||
console.log(' [L] Parallel Execution');
|
||||
console.log(' [M] SPARC Modes');
|
||||
console.log(' [O] Task Orchestration');
|
||||
console.log('\nPress a key to execute tool...');
|
||||
}
|
||||
renderGitHubIntegrationView() {
|
||||
console.clear();
|
||||
console.log('🐙 GitHub Integration');
|
||||
console.log('═'.repeat(50));
|
||||
console.log('Available Tools:');
|
||||
console.log(' [A] Analyze Repository');
|
||||
console.log(' [P] Manage Pull Requests');
|
||||
console.log(' [I] Track Issues');
|
||||
console.log(' [R] Release Coordination');
|
||||
console.log(' [W] Workflow Automation');
|
||||
console.log(' [M] Repository Metrics');
|
||||
console.log('\nPress a key to execute tool...');
|
||||
}
|
||||
renderDAAControlView() {
|
||||
console.clear();
|
||||
console.log('🤖 Dynamic Agent Architecture');
|
||||
console.log('═'.repeat(50));
|
||||
console.log('Available Tools:');
|
||||
console.log(' [C] Create Agent');
|
||||
console.log(' [M] Match Capabilities');
|
||||
console.log(' [R] Resource Allocation');
|
||||
console.log(' [L] Lifecycle Management');
|
||||
console.log(' [O] Communication');
|
||||
console.log(' [F] Fault Tolerance');
|
||||
console.log('\nPress a key to execute tool...');
|
||||
}
|
||||
renderSystemUtilitiesView() {
|
||||
console.clear();
|
||||
console.log('🛠️ System Utilities');
|
||||
console.log('═'.repeat(50));
|
||||
console.log('Available Tools:');
|
||||
console.log(' [S] Security Scan');
|
||||
console.log(' [B] Create Backup');
|
||||
console.log(' [R] Restore System');
|
||||
console.log(' [L] Log Analysis');
|
||||
console.log(' [D] Run Diagnostics');
|
||||
console.log(' [C] Manage Config');
|
||||
console.log('\nPress a key to execute tool...');
|
||||
}
|
||||
renderCLIBridgeView() {
|
||||
console.clear();
|
||||
console.log('⌨️ CLI Command Bridge');
|
||||
console.log('═'.repeat(50));
|
||||
console.log('Available Commands:');
|
||||
console.log(' [H] Hive Mind Wizard');
|
||||
console.log(' [G] GitHub Operations');
|
||||
console.log(' [T] Training Commands');
|
||||
console.log(' [A] Analysis Operations');
|
||||
console.log(' [U] Automation Setup');
|
||||
console.log(' [C] Coordination Tools');
|
||||
console.log('\nPress a key to execute command...');
|
||||
}
|
||||
async handleNeuralInput(input) {
|
||||
const actions = {
|
||||
t: ()=>this.executeTool('neural_train'),
|
||||
p: ()=>this.executeTool('neural_predict'),
|
||||
s: ()=>this.executeTool('neural_status'),
|
||||
a: ()=>this.executeTool('neural_patterns'),
|
||||
m: ()=>this.executeTool('model_load'),
|
||||
o: ()=>this.executeTool('wasm_optimize')
|
||||
};
|
||||
if (actions[input]) {
|
||||
await actions[input]();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
async handleMemoryInput(input) {
|
||||
const actions = {
|
||||
s: ()=>this.executeTool('memory_usage', {
|
||||
action: 'store'
|
||||
}),
|
||||
r: ()=>this.executeTool('memory_usage', {
|
||||
action: 'retrieve'
|
||||
}),
|
||||
b: ()=>this.executeTool('memory_backup'),
|
||||
c: ()=>this.executeTool('memory_compress'),
|
||||
y: ()=>this.executeTool('memory_sync'),
|
||||
a: ()=>this.executeTool('memory_analytics')
|
||||
};
|
||||
if (actions[input]) {
|
||||
await actions[input]();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
async handleMonitoringInput(input) {
|
||||
const actions = {
|
||||
p: ()=>this.executeTool('performance_report'),
|
||||
b: ()=>this.executeTool('bottleneck_analyze'),
|
||||
t: ()=>this.executeTool('token_usage'),
|
||||
m: ()=>this.executeTool('metrics_collect'),
|
||||
h: ()=>this.executeTool('health_check'),
|
||||
e: ()=>this.executeTool('error_analysis')
|
||||
};
|
||||
if (actions[input]) {
|
||||
await actions[input]();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
async handleWorkflowInput(input) {
|
||||
const actions = {
|
||||
c: ()=>this.executeTool('workflow_create'),
|
||||
e: ()=>this.executeTool('workflow_execute'),
|
||||
a: ()=>this.executeTool('automation_setup'),
|
||||
p: ()=>this.executeTool('pipeline_create'),
|
||||
s: ()=>this.executeTool('scheduler_manage'),
|
||||
t: ()=>this.executeTool('trigger_setup'),
|
||||
w: ()=>this.executeTool('workflow_template'),
|
||||
b: ()=>this.executeTool('batch_process'),
|
||||
l: ()=>this.executeTool('parallel_execute'),
|
||||
m: ()=>this.executeTool('sparc_mode'),
|
||||
o: ()=>this.executeTool('task_orchestrate')
|
||||
};
|
||||
if (actions[input]) {
|
||||
await actions[input]();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
showHelp() {
|
||||
console.log('\n🎨 Enhanced Web UI Help');
|
||||
console.log('═'.repeat(60));
|
||||
console.log('Navigation:');
|
||||
console.log(' 1-6: Original views');
|
||||
console.log(' 7: Neural Network Tools');
|
||||
console.log(' 8: Memory Management');
|
||||
console.log(' 9: Advanced Monitoring');
|
||||
console.log(' 0: Workflow Management');
|
||||
console.log('\nTool Categories:');
|
||||
console.log(' 🧠 Neural (15 tools): Training, prediction, patterns');
|
||||
console.log(' 💾 Memory (10 tools): Storage, backup, analytics');
|
||||
console.log(' 📊 Monitor (13 tools): Performance, bottlenecks, health');
|
||||
console.log(' 🔄 Workflow (11 tools): Automation, pipelines, scheduling');
|
||||
console.log(' 🐙 GitHub (8 tools): Repository analysis, PR management');
|
||||
console.log(' 🤖 DAA (8 tools): Dynamic agents, consensus, fault tolerance');
|
||||
console.log(' 🛠️ System (6 tools): Security, backup, diagnostics');
|
||||
console.log(' ⌨️ CLI (9 commands): Bridge to command-line tools');
|
||||
console.log('═'.repeat(60));
|
||||
}
|
||||
async shutdown() {
|
||||
console.log('🔄 Shutting down Enhanced Web UI...');
|
||||
if (this.uiManager && !this.fallbackMode) {
|
||||
await this.uiManager.shutdown();
|
||||
}
|
||||
this.isInitialized = false;
|
||||
this.fallbackMode = false;
|
||||
console.log('✅ Enhanced Web UI shutdown complete');
|
||||
}
|
||||
}
|
||||
export default EnhancedWebUI;
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('load', async ()=>{
|
||||
if (window.claudeFlowProcessUI) {
|
||||
console.log('🔗 Enhancing existing process UI...');
|
||||
const enhancedUI = new EnhancedWebUI();
|
||||
await enhancedUI.initialize(window.claudeFlowProcessUI);
|
||||
window.claudeFlowEnhancedUI = enhancedUI;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=EnhancedWebUI.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../src/ui/web-ui/EnhancedWebUI.js"],"sourcesContent":["/**\n * Enhanced Web UI - Main controller integrating modular architecture\n * Provides comprehensive interface for all 71+ MCP tools and CLI commands\n */\n\nimport UIManager from './core/UIManager.js';\nimport { VIEW_CATEGORIES } from './core/UIManager.js';\n\nexport class EnhancedWebUI {\n constructor() {\n this.uiManager = null;\n this.isInitialized = false;\n this.fallbackMode = false;\n this.originalProcessUI = null;\n }\n\n /**\n * Initialize enhanced web UI\n */\n async initialize(existingProcessUI = null) {\n try {\n console.log('🚀 Initializing Enhanced Web UI...');\n\n // Store reference to existing process UI\n this.originalProcessUI = existingProcessUI;\n\n // Try to initialize full UI manager\n try {\n this.uiManager = new UIManager();\n await this.uiManager.initialize();\n\n console.log('✅ Enhanced Web UI initialized successfully');\n this.isInitialized = true;\n } catch (error) {\n console.warn('⚠️ Full UI initialization failed, using fallback mode:', error);\n this.fallbackMode = true;\n await this.initializeFallbackMode();\n }\n\n // Setup integration with existing UI if provided\n if (this.originalProcessUI) {\n this.integrateWithExistingUI();\n }\n\n return this.isInitialized || this.fallbackMode;\n } catch (error) {\n console.error('❌ Failed to initialize Enhanced Web UI:', error);\n throw error;\n }\n }\n\n /**\n * Initialize fallback mode for minimal functionality\n */\n async initializeFallbackMode() {\n console.log('🔄 Initializing fallback mode...');\n\n // Create minimal UI structure\n this.createFallbackUI();\n\n this.fallbackMode = true;\n console.log('✅ Fallback mode initialized');\n }\n\n /**\n * Create fallback UI structure\n */\n createFallbackUI() {\n // Add enhanced views to existing process UI\n if (this.originalProcessUI) {\n this.addEnhancedViewsToProcessUI();\n } else {\n this.createStandaloneUI();\n }\n }\n\n /**\n * Add enhanced views to existing process UI\n */\n addEnhancedViewsToProcessUI() {\n // Extend the VIEWS enum\n const enhancedViews = {\n NEURAL: 'neural',\n MEMORY_MGMT: 'memory_mgmt',\n MONITORING_ADV: 'monitoring_adv',\n WORKFLOW_MGMT: 'workflow_mgmt',\n GITHUB_INT: 'github_int',\n DAA_CONTROL: 'daa_control',\n SYSTEM_UTILS: 'system_utils',\n CLI_BRIDGE: 'cli_bridge',\n };\n\n // Add to original UI's VIEWS if possible\n if (this.originalProcessUI.constructor.VIEWS) {\n Object.assign(this.originalProcessUI.constructor.VIEWS, enhancedViews);\n }\n\n // Extend render method to handle new views\n const originalRender = this.originalProcessUI.render.bind(this.originalProcessUI);\n this.originalProcessUI.render = () => {\n // Call original render first\n originalRender();\n\n // Add enhanced view handling\n this.handleEnhancedViews();\n };\n\n // Extend input handling\n const originalHandleInput = this.originalProcessUI.handleViewSpecificInput.bind(\n this.originalProcessUI,\n );\n this.originalProcessUI.handleViewSpecificInput = async (input) => {\n // Try enhanced views first\n if (await this.handleEnhancedInput(input)) {\n return; // Handled by enhanced UI\n }\n\n // Fall back to original handling\n return originalHandleInput(input);\n };\n }\n\n /**\n * Handle enhanced views in fallback mode\n */\n handleEnhancedViews() {\n if (!this.originalProcessUI.currentView) return;\n\n switch (this.originalProcessUI.currentView) {\n case 'neural':\n this.renderNeuralView();\n break;\n case 'memory_mgmt':\n this.renderMemoryManagementView();\n break;\n case 'monitoring_adv':\n this.renderAdvancedMonitoringView();\n break;\n case 'workflow_mgmt':\n this.renderWorkflowManagementView();\n break;\n case 'github_int':\n this.renderGitHubIntegrationView();\n break;\n case 'daa_control':\n this.renderDAAControlView();\n break;\n case 'system_utils':\n this.renderSystemUtilitiesView();\n break;\n case 'cli_bridge':\n this.renderCLIBridgeView();\n break;\n }\n }\n\n /**\n * Handle enhanced input in fallback mode\n */\n async handleEnhancedInput(input) {\n const currentView = this.originalProcessUI.currentView;\n\n // Enhanced view shortcuts\n const enhancedShortcuts = {\n 7: () => (this.originalProcessUI.currentView = 'neural'),\n 8: () => (this.originalProcessUI.currentView = 'memory_mgmt'),\n 9: () => (this.originalProcessUI.currentView = 'monitoring_adv'),\n 0: () => (this.originalProcessUI.currentView = 'workflow_mgmt'),\Line truncated
|
||||
@@ -1,872 +0,0 @@
|
||||
export class ComponentLibrary {
|
||||
constructor(){
|
||||
this.components = new Map();
|
||||
this.theme = 'dark';
|
||||
this.isInitialized = false;
|
||||
}
|
||||
initialize() {
|
||||
this.registerComponents();
|
||||
this.addComponentStyles();
|
||||
this.isInitialized = true;
|
||||
console.log('🎨 Component Library initialized');
|
||||
}
|
||||
registerComponents() {
|
||||
this.components.set('ToolPanel', this.createToolPanel);
|
||||
this.components.set('MetricsChart', this.createMetricsChart);
|
||||
this.components.set('CommandPalette', this.createCommandPalette);
|
||||
this.components.set('ProgressBar', this.createProgressBar);
|
||||
this.components.set('StatusBadge', this.createStatusBadge);
|
||||
this.components.set('LoadingSpinner', this.createLoadingSpinner);
|
||||
this.components.set('ErrorMessage', this.createErrorMessage);
|
||||
this.components.set('SuccessMessage', this.createSuccessMessage);
|
||||
this.components.set('InfoPanel', this.createInfoPanel);
|
||||
this.components.set('ActionButton', this.createActionButton);
|
||||
this.components.set('ToolGrid', this.createToolGrid);
|
||||
this.components.set('StatsCard', this.createStatsCard);
|
||||
this.components.set('LogViewer', this.createLogViewer);
|
||||
this.components.set('FormBuilder', this.createFormBuilder);
|
||||
this.components.set('TabContainer', this.createTabContainer);
|
||||
}
|
||||
getComponent(name) {
|
||||
const component = this.components.get(name);
|
||||
if (!component) {
|
||||
throw new Error(`Component not found: ${name}`);
|
||||
}
|
||||
return component;
|
||||
}
|
||||
createToolPanel(config) {
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'claude-tool-panel';
|
||||
const header = document.createElement('div');
|
||||
header.className = 'claude-tool-panel-header';
|
||||
const title = document.createElement('h3');
|
||||
title.textContent = config.title;
|
||||
title.className = 'claude-tool-panel-title';
|
||||
const subtitle = document.createElement('p');
|
||||
subtitle.textContent = config.description;
|
||||
subtitle.className = 'claude-tool-panel-subtitle';
|
||||
header.appendChild(title);
|
||||
header.appendChild(subtitle);
|
||||
const content = document.createElement('div');
|
||||
content.className = 'claude-tool-panel-content';
|
||||
panel.appendChild(header);
|
||||
panel.appendChild(content);
|
||||
return {
|
||||
element: panel,
|
||||
content,
|
||||
setTitle: (newTitle)=>{
|
||||
title.textContent = newTitle;
|
||||
},
|
||||
setDescription: (newDesc)=>{
|
||||
subtitle.textContent = newDesc;
|
||||
},
|
||||
clear: ()=>{
|
||||
content.innerHTML = '';
|
||||
},
|
||||
append: (element)=>{
|
||||
content.appendChild(element);
|
||||
}
|
||||
};
|
||||
}
|
||||
createMetricsChart(config) {
|
||||
const container = document.createElement('div');
|
||||
container.className = 'claude-metrics-chart';
|
||||
const title = document.createElement('h4');
|
||||
title.textContent = config.title;
|
||||
title.className = 'claude-chart-title';
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = config.width || 400;
|
||||
canvas.height = config.height || 200;
|
||||
canvas.className = 'claude-chart-canvas';
|
||||
const legend = document.createElement('div');
|
||||
legend.className = 'claude-chart-legend';
|
||||
container.appendChild(title);
|
||||
container.appendChild(canvas);
|
||||
container.appendChild(legend);
|
||||
return {
|
||||
element: container,
|
||||
canvas,
|
||||
updateData: (data)=>this.updateChart(canvas, data, config),
|
||||
setTitle: (newTitle)=>{
|
||||
title.textContent = newTitle;
|
||||
},
|
||||
addLegendItem: (label, color)=>this.addLegendItem(legend, label, color)
|
||||
};
|
||||
}
|
||||
createCommandPalette(config) {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'claude-command-palette-overlay';
|
||||
overlay.style.display = 'none';
|
||||
const palette = document.createElement('div');
|
||||
palette.className = 'claude-command-palette';
|
||||
const input = document.createElement('input');
|
||||
input.type = 'text';
|
||||
input.placeholder = 'Type a command...';
|
||||
input.className = 'claude-command-input';
|
||||
const results = document.createElement('div');
|
||||
results.className = 'claude-command-results';
|
||||
palette.appendChild(input);
|
||||
palette.appendChild(results);
|
||||
overlay.appendChild(palette);
|
||||
return {
|
||||
element: overlay,
|
||||
input,
|
||||
results,
|
||||
show: ()=>{
|
||||
overlay.style.display = 'flex';
|
||||
input.focus();
|
||||
},
|
||||
hide: ()=>{
|
||||
overlay.style.display = 'none';
|
||||
},
|
||||
updateResults: (commands)=>this.updateCommandResults(results, commands),
|
||||
onCommand: null
|
||||
};
|
||||
}
|
||||
createProgressBar(config) {
|
||||
const container = document.createElement('div');
|
||||
container.className = 'claude-progress-container';
|
||||
const label = document.createElement('div');
|
||||
label.className = 'claude-progress-label';
|
||||
label.textContent = config.label || 'Progress';
|
||||
const bar = document.createElement('div');
|
||||
bar.className = 'claude-progress-bar';
|
||||
const fill = document.createElement('div');
|
||||
fill.className = 'claude-progress-fill';
|
||||
fill.style.width = '0%';
|
||||
const text = document.createElement('div');
|
||||
text.className = 'claude-progress-text';
|
||||
text.textContent = '0%';
|
||||
bar.appendChild(fill);
|
||||
bar.appendChild(text);
|
||||
container.appendChild(label);
|
||||
container.appendChild(bar);
|
||||
return {
|
||||
element: container,
|
||||
setProgress: (percent)=>{
|
||||
fill.style.width = `${percent}%`;
|
||||
text.textContent = `${Math.round(percent)}%`;
|
||||
},
|
||||
setLabel: (newLabel)=>{
|
||||
label.textContent = newLabel;
|
||||
}
|
||||
};
|
||||
}
|
||||
createStatusBadge(status, text) {
|
||||
const badge = document.createElement('span');
|
||||
badge.className = `claude-status-badge claude-status-${status}`;
|
||||
badge.textContent = text || status;
|
||||
return {
|
||||
element: badge,
|
||||
setStatus: (newStatus)=>{
|
||||
badge.className = `claude-status-badge claude-status-${newStatus}`;
|
||||
},
|
||||
setText: (newText)=>{
|
||||
badge.textContent = newText;
|
||||
}
|
||||
};
|
||||
}
|
||||
createLoadingSpinner(config = {}) {
|
||||
const container = document.createElement('div');
|
||||
container.className = 'claude-loading-container';
|
||||
const spinner = document.createElement('div');
|
||||
spinner.className = 'claude-loading-spinner';
|
||||
const message = document.createElement('div');
|
||||
message.className = 'claude-loading-message';
|
||||
message.textContent = config.message || 'Loading...';
|
||||
container.appendChild(spinner);
|
||||
container.appendChild(message);
|
||||
return {
|
||||
element: container,
|
||||
setMessage: (newMessage)=>{
|
||||
message.textContent = newMessage;
|
||||
},
|
||||
show: ()=>{
|
||||
container.style.display = 'flex';
|
||||
},
|
||||
hide: ()=>{
|
||||
container.style.display = 'none';
|
||||
}
|
||||
};
|
||||
}
|
||||
createErrorMessage(message, details = null) {
|
||||
const container = document.createElement('div');
|
||||
container.className = 'claude-error-message';
|
||||
const icon = document.createElement('span');
|
||||
icon.textContent = '❌';
|
||||
icon.className = 'claude-error-icon';
|
||||
const text = document.createElement('div');
|
||||
text.className = 'claude-error-text';
|
||||
text.textContent = message;
|
||||
container.appendChild(icon);
|
||||
container.appendChild(text);
|
||||
if (details) {
|
||||
const detailsEl = document.createElement('div');
|
||||
detailsEl.className = 'claude-error-details';
|
||||
detailsEl.textContent = details;
|
||||
container.appendChild(detailsEl);
|
||||
}
|
||||
return {
|
||||
element: container,
|
||||
setMessage: (newMessage)=>{
|
||||
text.textContent = newMessage;
|
||||
},
|
||||
setDetails: (newDetails)=>{
|
||||
if (newDetails) {
|
||||
if (!container.querySelector('.claude-error-details')) {
|
||||
const detailsEl = document.createElement('div');
|
||||
detailsEl.className = 'claude-error-details';
|
||||
container.appendChild(detailsEl);
|
||||
}
|
||||
container.querySelector('.claude-error-details').textContent = newDetails;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
createSuccessMessage(message) {
|
||||
const container = document.createElement('div');
|
||||
container.className = 'claude-success-message';
|
||||
const icon = document.createElement('span');
|
||||
icon.textContent = '✅';
|
||||
icon.className = 'claude-success-icon';
|
||||
const text = document.createElement('div');
|
||||
text.className = 'claude-success-text';
|
||||
text.textContent = message;
|
||||
container.appendChild(icon);
|
||||
container.appendChild(text);
|
||||
return {
|
||||
element: container,
|
||||
setMessage: (newMessage)=>{
|
||||
text.textContent = newMessage;
|
||||
}
|
||||
};
|
||||
}
|
||||
createInfoPanel(config) {
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'claude-info-panel';
|
||||
const header = document.createElement('div');
|
||||
header.className = 'claude-info-header';
|
||||
header.textContent = config.title;
|
||||
const content = document.createElement('div');
|
||||
content.className = 'claude-info-content';
|
||||
panel.appendChild(header);
|
||||
panel.appendChild(content);
|
||||
return {
|
||||
element: panel,
|
||||
content,
|
||||
setTitle: (title)=>{
|
||||
header.textContent = title;
|
||||
},
|
||||
setContent: (html)=>{
|
||||
content.innerHTML = html;
|
||||
},
|
||||
append: (element)=>{
|
||||
content.appendChild(element);
|
||||
},
|
||||
clear: ()=>{
|
||||
content.innerHTML = '';
|
||||
}
|
||||
};
|
||||
}
|
||||
createActionButton(config) {
|
||||
const button = document.createElement('button');
|
||||
button.className = `claude-action-button claude-button-${config.type || 'primary'}`;
|
||||
button.textContent = config.text;
|
||||
if (config.icon) {
|
||||
const icon = document.createElement('span');
|
||||
icon.textContent = config.icon;
|
||||
icon.className = 'claude-button-icon';
|
||||
button.insertBefore(icon, button.firstChild);
|
||||
}
|
||||
if (config.onclick) {
|
||||
button.addEventListener('click', config.onclick);
|
||||
}
|
||||
return {
|
||||
element: button,
|
||||
setText: (text)=>{
|
||||
button.textContent = text;
|
||||
if (config.icon) {
|
||||
const icon = document.createElement('span');
|
||||
icon.textContent = config.icon;
|
||||
icon.className = 'claude-button-icon';
|
||||
button.insertBefore(icon, button.firstChild);
|
||||
}
|
||||
},
|
||||
setDisabled: (disabled)=>{
|
||||
button.disabled = disabled;
|
||||
},
|
||||
setLoading: (loading)=>{
|
||||
if (loading) {
|
||||
button.classList.add('claude-button-loading');
|
||||
button.disabled = true;
|
||||
} else {
|
||||
button.classList.remove('claude-button-loading');
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
createToolGrid(tools, onToolClick) {
|
||||
const grid = document.createElement('div');
|
||||
grid.className = 'claude-tool-grid';
|
||||
tools.forEach((tool)=>{
|
||||
const card = document.createElement('div');
|
||||
card.className = 'claude-tool-card';
|
||||
const icon = document.createElement('div');
|
||||
icon.className = 'claude-tool-icon';
|
||||
icon.textContent = tool.icon || '🔧';
|
||||
const name = document.createElement('div');
|
||||
name.className = 'claude-tool-name';
|
||||
name.textContent = tool.name;
|
||||
const desc = document.createElement('div');
|
||||
desc.className = "claude-tool-description";
|
||||
desc.textContent = tool.description;
|
||||
card.appendChild(icon);
|
||||
card.appendChild(name);
|
||||
card.appendChild(desc);
|
||||
card.addEventListener('click', ()=>onToolClick(tool));
|
||||
grid.appendChild(card);
|
||||
});
|
||||
return {
|
||||
element: grid,
|
||||
updateTools: (newTools)=>{
|
||||
grid.innerHTML = '';
|
||||
newTools.forEach((tool)=>{
|
||||
const card = this.createToolCard(tool, onToolClick);
|
||||
grid.appendChild(card);
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
createStatsCard(config) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'claude-stats-card';
|
||||
const icon = document.createElement('div');
|
||||
icon.className = 'claude-stats-icon';
|
||||
icon.textContent = config.icon;
|
||||
const content = document.createElement('div');
|
||||
content.className = 'claude-stats-content';
|
||||
const value = document.createElement('div');
|
||||
value.className = 'claude-stats-value';
|
||||
value.textContent = config.value;
|
||||
const label = document.createElement('div');
|
||||
label.className = 'claude-stats-label';
|
||||
label.textContent = config.label;
|
||||
content.appendChild(value);
|
||||
content.appendChild(label);
|
||||
card.appendChild(icon);
|
||||
card.appendChild(content);
|
||||
return {
|
||||
element: card,
|
||||
setValue: (newValue)=>{
|
||||
value.textContent = newValue;
|
||||
},
|
||||
setLabel: (newLabel)=>{
|
||||
label.textContent = newLabel;
|
||||
},
|
||||
setIcon: (newIcon)=>{
|
||||
icon.textContent = newIcon;
|
||||
}
|
||||
};
|
||||
}
|
||||
createTabContainer(tabs) {
|
||||
const container = document.createElement('div');
|
||||
container.className = 'claude-tab-container';
|
||||
const tabList = document.createElement('div');
|
||||
tabList.className = 'claude-tab-list';
|
||||
const tabContent = document.createElement('div');
|
||||
tabContent.className = 'claude-tab-content';
|
||||
let activeTab = 0;
|
||||
tabs.forEach((tab, index)=>{
|
||||
const tabButton = document.createElement('button');
|
||||
tabButton.className = `claude-tab-button ${index === 0 ? 'active' : ''}`;
|
||||
tabButton.textContent = tab.label;
|
||||
const tabPane = document.createElement('div');
|
||||
tabPane.className = `claude-tab-pane ${index === 0 ? 'active' : ''}`;
|
||||
tabPane.innerHTML = tab.content;
|
||||
tabButton.addEventListener('click', ()=>{
|
||||
tabList.querySelectorAll('.claude-tab-button').forEach((btn)=>btn.classList.remove('active'));
|
||||
tabContent.querySelectorAll('.claude-tab-pane').forEach((pane)=>pane.classList.remove('active'));
|
||||
tabButton.classList.add('active');
|
||||
tabPane.classList.add('active');
|
||||
activeTab = index;
|
||||
});
|
||||
tabList.appendChild(tabButton);
|
||||
tabContent.appendChild(tabPane);
|
||||
});
|
||||
container.appendChild(tabList);
|
||||
container.appendChild(tabContent);
|
||||
return {
|
||||
element: container,
|
||||
setActiveTab: (index)=>{
|
||||
if (index >= 0 && index < tabs.length) {
|
||||
tabList.children[index].click();
|
||||
}
|
||||
},
|
||||
getActiveTab: ()=>activeTab,
|
||||
addTab: (tab)=>{}
|
||||
};
|
||||
}
|
||||
addComponentStyles() {
|
||||
if (document.getElementById('claude-component-styles')) return;
|
||||
const styles = document.createElement('style');
|
||||
styles.id = 'claude-component-styles';
|
||||
styles.textContent = `
|
||||
/* Tool Panel Styles */
|
||||
.claude-tool-panel {
|
||||
background: #2a2a2a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.claude-tool-panel-header {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.claude-tool-panel-title {
|
||||
margin: 0 0 4px 0;
|
||||
color: #00d4ff;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.claude-tool-panel-subtitle {
|
||||
margin: 0;
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.claude-tool-panel-content {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* Metrics Chart Styles */
|
||||
.claude-metrics-chart {
|
||||
background: #2a2a2a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.claude-chart-title {
|
||||
margin: 0 0 12px 0;
|
||||
color: #00d4ff;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.claude-chart-canvas {
|
||||
display: block;
|
||||
margin: 0 auto;
|
||||
background: #1a1a1a;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.claude-chart-legend {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
margin-top: 8px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* Command Palette Styles */
|
||||
.claude-command-palette-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: flex-start;
|
||||
padding-top: 20vh;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
.claude-command-palette {
|
||||
background: #2a2a2a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
width: 600px;
|
||||
max-width: 90vw;
|
||||
max-height: 60vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.claude-command-input {
|
||||
width: 100%;
|
||||
padding: 16px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: #fff;
|
||||
font-size: 18px;
|
||||
outline: none;
|
||||
border-bottom: 1px solid #444;
|
||||
}
|
||||
|
||||
.claude-command-results {
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
/* Progress Bar Styles */
|
||||
.claude-progress-container {
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.claude-progress-label {
|
||||
color: #fff;
|
||||
margin-bottom: 4px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.claude-progress-bar {
|
||||
position: relative;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 4px;
|
||||
height: 24px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.claude-progress-fill {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #00d4ff, #0099cc);
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.claude-progress-text {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
color: #fff;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
/* Status Badge Styles */
|
||||
.claude-status-badge {
|
||||
display: inline-block;
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.claude-status-success {
|
||||
background: #22c55e;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.claude-status-error {
|
||||
background: #ef4444;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.claude-status-warning {
|
||||
background: #f59e0b;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.claude-status-info {
|
||||
background: #3b82f6;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.claude-status-idle {
|
||||
background: #6b7280;
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* Loading Spinner Styles */
|
||||
.claude-loading-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 32px;
|
||||
}
|
||||
|
||||
.claude-loading-spinner {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: 3px solid #444;
|
||||
border-top: 3px solid #00d4ff;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
.claude-loading-message {
|
||||
margin-top: 12px;
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Message Styles */
|
||||
.claude-error-message,
|
||||
.claude-success-message {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
border-radius: 6px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.claude-error-message {
|
||||
background: #fef2f2;
|
||||
border: 1px solid #fecaca;
|
||||
color: #991b1b;
|
||||
}
|
||||
|
||||
.claude-success-message {
|
||||
background: #f0fdf4;
|
||||
border: 1px solid #bbf7d0;
|
||||
color: #166534;
|
||||
}
|
||||
|
||||
.claude-error-icon,
|
||||
.claude-success-icon {
|
||||
margin-right: 8px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
/* Tool Grid Styles */
|
||||
.claude-tool-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
||||
gap: 16px;
|
||||
margin: 16px 0;
|
||||
}
|
||||
|
||||
.claude-tool-card {
|
||||
background: #2a2a2a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.claude-tool-card:hover {
|
||||
border-color: #00d4ff;
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.claude-tool-icon {
|
||||
font-size: 32px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.claude-tool-name {
|
||||
font-weight: bold;
|
||||
color: #fff;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.claude-tool-description {
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* Stats Card Styles */
|
||||
.claude-stats-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: #2a2a2a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.claude-stats-icon {
|
||||
font-size: 24px;
|
||||
margin-right: 12px;
|
||||
}
|
||||
|
||||
.claude-stats-value {
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
color: #00d4ff;
|
||||
}
|
||||
|
||||
.claude-stats-label {
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* Tab Styles */
|
||||
.claude-tab-container {
|
||||
background: #2a2a2a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.claude-tab-list {
|
||||
display: flex;
|
||||
background: #1a1a1a;
|
||||
border-bottom: 1px solid #444;
|
||||
}
|
||||
|
||||
.claude-tab-button {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: #888;
|
||||
padding: 12px 16px;
|
||||
cursor: pointer;
|
||||
border-bottom: 2px solid transparent;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.claude-tab-button:hover {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.claude-tab-button.active {
|
||||
color: #00d4ff;
|
||||
border-bottom-color: #00d4ff;
|
||||
}
|
||||
|
||||
.claude-tab-content {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.claude-tab-pane {
|
||||
display: none;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.claude-tab-pane.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Button Styles */
|
||||
.claude-action-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.claude-button-primary {
|
||||
background: #00d4ff;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.claude-button-primary:hover {
|
||||
background: #00b8e6;
|
||||
}
|
||||
|
||||
.claude-button-secondary {
|
||||
background: #444;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.claude-button-secondary:hover {
|
||||
background: #555;
|
||||
}
|
||||
|
||||
.claude-button-danger {
|
||||
background: #ef4444;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.claude-button-danger:hover {
|
||||
background: #dc2626;
|
||||
}
|
||||
|
||||
.claude-button-loading {
|
||||
opacity: 0.7;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Info Panel Styles */
|
||||
.claude-info-panel {
|
||||
background: #2a2a2a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
margin: 8px 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.claude-info-header {
|
||||
background: #1a1a1a;
|
||||
padding: 12px 16px;
|
||||
font-weight: bold;
|
||||
color: #00d4ff;
|
||||
border-bottom: 1px solid #444;
|
||||
}
|
||||
|
||||
.claude-info-content {
|
||||
padding: 16px;
|
||||
color: #fff;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(styles);
|
||||
}
|
||||
updateChart(canvas, data, config) {
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
const padding = 40;
|
||||
const chartWidth = canvas.width - padding * 2;
|
||||
const chartHeight = canvas.height - padding * 2;
|
||||
if (config.type === 'line') {
|
||||
this.drawLineChart(ctx, data, padding, chartWidth, chartHeight);
|
||||
} else if (config.type === 'bar') {
|
||||
this.drawBarChart(ctx, data, padding, chartWidth, chartHeight);
|
||||
}
|
||||
}
|
||||
drawLineChart(ctx, data, padding, width, height) {
|
||||
if (!data || data.length === 0) return;
|
||||
const maxValue = Math.max(...data.map((d)=>d.value));
|
||||
const stepX = width / (data.length - 1);
|
||||
ctx.strokeStyle = '#00d4ff';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
data.forEach((point, index)=>{
|
||||
const x = padding + index * stepX;
|
||||
const y = padding + height - point.value / maxValue * height;
|
||||
if (index === 0) {
|
||||
ctx.moveTo(x, y);
|
||||
} else {
|
||||
ctx.lineTo(x, y);
|
||||
}
|
||||
});
|
||||
ctx.stroke();
|
||||
}
|
||||
drawBarChart(ctx, data, padding, width, height) {
|
||||
if (!data || data.length === 0) return;
|
||||
const maxValue = Math.max(...data.map((d)=>d.value));
|
||||
const barWidth = width / data.length * 0.8;
|
||||
const barSpacing = width / data.length * 0.2;
|
||||
ctx.fillStyle = '#00d4ff';
|
||||
data.forEach((point, index)=>{
|
||||
const x = padding + index * (barWidth + barSpacing);
|
||||
const barHeight = point.value / maxValue * height;
|
||||
const y = padding + height - barHeight;
|
||||
ctx.fillRect(x, y, barWidth, barHeight);
|
||||
});
|
||||
}
|
||||
setTheme(theme) {
|
||||
this.theme = theme;
|
||||
}
|
||||
}
|
||||
export default ComponentLibrary;
|
||||
|
||||
//# sourceMappingURL=ComponentLibrary.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/web-ui/components/ComponentLibrary.js"],"sourcesContent":["/**\n * ComponentLibrary - Reusable UI components for Claude Flow Web UI\n * Provides consistent, themeable components across all views\n */\n\nexport class ComponentLibrary {\n constructor() {\n this.components = new Map();\n this.theme = 'dark';\n this.isInitialized = false;\n }\n\n /**\n * Initialize component library\n */\n initialize() {\n this.registerComponents();\n this.addComponentStyles();\n this.isInitialized = true;\n console.log('🎨 Component Library initialized');\n }\n\n /**\n * Register all reusable components\n */\n registerComponents() {\n this.components.set('ToolPanel', this.createToolPanel);\n this.components.set('MetricsChart', this.createMetricsChart);\n this.components.set('CommandPalette', this.createCommandPalette);\n this.components.set('ProgressBar', this.createProgressBar);\n this.components.set('StatusBadge', this.createStatusBadge);\n this.components.set('LoadingSpinner', this.createLoadingSpinner);\n this.components.set('ErrorMessage', this.createErrorMessage);\n this.components.set('SuccessMessage', this.createSuccessMessage);\n this.components.set('InfoPanel', this.createInfoPanel);\n this.components.set('ActionButton', this.createActionButton);\n this.components.set('ToolGrid', this.createToolGrid);\n this.components.set('StatsCard', this.createStatsCard);\n this.components.set('LogViewer', this.createLogViewer);\n this.components.set('FormBuilder', this.createFormBuilder);\n this.components.set('TabContainer', this.createTabContainer);\n }\n\n /**\n * Get component by name\n */\n getComponent(name) {\n const component = this.components.get(name);\n if (!component) {\n throw new Error(`Component not found: ${name}`);\n }\n return component;\n }\n\n /**\n * Create tool panel component\n */\n createToolPanel(config) {\n const panel = document.createElement('div');\n panel.className = 'claude-tool-panel';\n\n const header = document.createElement('div');\n header.className = 'claude-tool-panel-header';\n\n const title = document.createElement('h3');\n title.textContent = config.title;\n title.className = 'claude-tool-panel-title';\n\n const subtitle = document.createElement('p');\n subtitle.textContent = config.description;\n subtitle.className = 'claude-tool-panel-subtitle';\n\n header.appendChild(title);\n header.appendChild(subtitle);\n\n const content = document.createElement('div');\n content.className = 'claude-tool-panel-content';\n\n panel.appendChild(header);\n panel.appendChild(content);\n\n return {\n element: panel,\n content,\n setTitle: (newTitle) => {\n title.textContent = newTitle;\n },\n setDescription: (newDesc) => {\n subtitle.textContent = newDesc;\n },\n clear: () => {\n content.innerHTML = '';\n },\n append: (element) => {\n content.appendChild(element);\n },\n };\n }\n\n /**\n * Create metrics chart component\n */\n createMetricsChart(config) {\n const container = document.createElement('div');\n container.className = 'claude-metrics-chart';\n\n const title = document.createElement('h4');\n title.textContent = config.title;\n title.className = 'claude-chart-title';\n\n const canvas = document.createElement('canvas');\n canvas.width = config.width || 400;\n canvas.height = config.height || 200;\n canvas.className = 'claude-chart-canvas';\n\n const legend = document.createElement('div');\n legend.className = 'claude-chart-legend';\n\n container.appendChild(title);\n container.appendChild(canvas);\n container.appendChild(legend);\n\n return {\n element: container,\n canvas,\n updateData: (data) => this.updateChart(canvas, data, config),\n setTitle: (newTitle) => {\n title.textContent = newTitle;\n },\n addLegendItem: (label, color) => this.addLegendItem(legend, label, color),\n };\n }\n\n /**\n * Create command palette component\n */\n createCommandPalette(config) {\n const overlay = document.createElement('div');\n overlay.className = 'claude-command-palette-overlay';\n overlay.style.display = 'none';\n\n const palette = document.createElement('div');\n palette.className = 'claude-command-palette';\n\n const input = document.createElement('input');\n input.type = 'text';\n input.placeholder = 'Type a command...';\n input.className = 'claude-command-input';\n\n const results = document.createElement('div');\n results.className = 'claude-command-results';\n\n palette.appendChild(input);\n palette.appendChild(results);\n overlay.appendChild(palette);\n\n return {\n element: overlay,\n input,\n results,\n show: () => {\n overlay.style.display = Line truncated
|
||||
@@ -1,359 +0,0 @@
|
||||
export class EventBus {
|
||||
constructor(){
|
||||
this.events = new Map();
|
||||
this.onceEvents = new Map();
|
||||
this.wildcardHandlers = new Map();
|
||||
this.eventHistory = [];
|
||||
this.maxHistorySize = 1000;
|
||||
this.isLogging = true;
|
||||
}
|
||||
on(event, handler, context = null) {
|
||||
if (typeof handler !== 'function') {
|
||||
throw new Error('Event handler must be a function');
|
||||
}
|
||||
if (!this.events.has(event)) {
|
||||
this.events.set(event, []);
|
||||
}
|
||||
const handlerInfo = {
|
||||
handler,
|
||||
context,
|
||||
id: this.generateHandlerId()
|
||||
};
|
||||
this.events.get(event).push(handlerInfo);
|
||||
if (this.isLogging) {
|
||||
console.debug(`📡 EventBus: Subscribed to '${event}'`);
|
||||
}
|
||||
return ()=>this.off(event, handler);
|
||||
}
|
||||
once(event, handler, context = null) {
|
||||
if (typeof handler !== 'function') {
|
||||
throw new Error('Event handler must be a function');
|
||||
}
|
||||
if (!this.onceEvents.has(event)) {
|
||||
this.onceEvents.set(event, []);
|
||||
}
|
||||
const handlerInfo = {
|
||||
handler,
|
||||
context,
|
||||
id: this.generateHandlerId()
|
||||
};
|
||||
this.onceEvents.get(event).push(handlerInfo);
|
||||
if (this.isLogging) {
|
||||
console.debug(`📡 EventBus: Subscribed once to '${event}'`);
|
||||
}
|
||||
return ()=>this.offOnce(event, handler);
|
||||
}
|
||||
onWildcard(pattern, handler, context = null) {
|
||||
if (typeof handler !== 'function') {
|
||||
throw new Error('Event handler must be a function');
|
||||
}
|
||||
if (!this.wildcardHandlers.has(pattern)) {
|
||||
this.wildcardHandlers.set(pattern, []);
|
||||
}
|
||||
const handlerInfo = {
|
||||
handler,
|
||||
context,
|
||||
id: this.generateHandlerId(),
|
||||
regex: this.createWildcardRegex(pattern)
|
||||
};
|
||||
this.wildcardHandlers.get(pattern).push(handlerInfo);
|
||||
if (this.isLogging) {
|
||||
console.debug(`📡 EventBus: Subscribed to wildcard pattern '${pattern}'`);
|
||||
}
|
||||
return ()=>this.offWildcard(pattern, handler);
|
||||
}
|
||||
off(event, handler) {
|
||||
const handlers = this.events.get(event);
|
||||
if (!handlers) return false;
|
||||
const index = handlers.findIndex((h)=>h.handler === handler);
|
||||
if (index === -1) return false;
|
||||
handlers.splice(index, 1);
|
||||
if (handlers.length === 0) {
|
||||
this.events.delete(event);
|
||||
}
|
||||
if (this.isLogging) {
|
||||
console.debug(`📡 EventBus: Unsubscribed from '${event}'`);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
offOnce(event, handler) {
|
||||
const handlers = this.onceEvents.get(event);
|
||||
if (!handlers) return false;
|
||||
const index = handlers.findIndex((h)=>h.handler === handler);
|
||||
if (index === -1) return false;
|
||||
handlers.splice(index, 1);
|
||||
if (handlers.length === 0) {
|
||||
this.onceEvents.delete(event);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
offWildcard(pattern, handler) {
|
||||
const handlers = this.wildcardHandlers.get(pattern);
|
||||
if (!handlers) return false;
|
||||
const index = handlers.findIndex((h)=>h.handler === handler);
|
||||
if (index === -1) return false;
|
||||
handlers.splice(index, 1);
|
||||
if (handlers.length === 0) {
|
||||
this.wildcardHandlers.delete(pattern);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
emit(event, data = null) {
|
||||
const eventInfo = {
|
||||
event,
|
||||
data,
|
||||
timestamp: Date.now(),
|
||||
id: this.generateEventId()
|
||||
};
|
||||
this.addToHistory(eventInfo);
|
||||
if (this.isLogging) {
|
||||
console.debug(`📡 EventBus: Emitting '${event}'`, data);
|
||||
}
|
||||
let handlersExecuted = 0;
|
||||
const handlers = this.events.get(event);
|
||||
if (handlers) {
|
||||
for (const handlerInfo of [
|
||||
...handlers
|
||||
]){
|
||||
try {
|
||||
if (handlerInfo.context) {
|
||||
handlerInfo.handler.call(handlerInfo.context, data, eventInfo);
|
||||
} else {
|
||||
handlerInfo.handler(data, eventInfo);
|
||||
}
|
||||
handlersExecuted++;
|
||||
} catch (error) {
|
||||
console.error(`📡 EventBus: Error in handler for '${event}':`, error);
|
||||
this.emit('error', {
|
||||
event,
|
||||
error,
|
||||
handlerInfo
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const onceHandlers = this.onceEvents.get(event);
|
||||
if (onceHandlers) {
|
||||
for (const handlerInfo of [
|
||||
...onceHandlers
|
||||
]){
|
||||
try {
|
||||
if (handlerInfo.context) {
|
||||
handlerInfo.handler.call(handlerInfo.context, data, eventInfo);
|
||||
} else {
|
||||
handlerInfo.handler(data, eventInfo);
|
||||
}
|
||||
handlersExecuted++;
|
||||
} catch (error) {
|
||||
console.error(`📡 EventBus: Error in once handler for '${event}':`, error);
|
||||
this.emit('error', {
|
||||
event,
|
||||
error,
|
||||
handlerInfo
|
||||
});
|
||||
}
|
||||
}
|
||||
this.onceEvents.delete(event);
|
||||
}
|
||||
for (const [pattern, handlers] of this.wildcardHandlers){
|
||||
for (const handlerInfo of handlers){
|
||||
if (handlerInfo.regex.test(event)) {
|
||||
try {
|
||||
if (handlerInfo.context) {
|
||||
handlerInfo.handler.call(handlerInfo.context, data, eventInfo);
|
||||
} else {
|
||||
handlerInfo.handler(data, eventInfo);
|
||||
}
|
||||
handlersExecuted++;
|
||||
} catch (error) {
|
||||
console.error(`📡 EventBus: Error in wildcard handler for '${pattern}':`, error);
|
||||
this.emit('error', {
|
||||
event,
|
||||
error,
|
||||
handlerInfo,
|
||||
pattern
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return handlersExecuted;
|
||||
}
|
||||
async emitAsync(event, data = null) {
|
||||
const eventInfo = {
|
||||
event,
|
||||
data,
|
||||
timestamp: Date.now(),
|
||||
id: this.generateEventId()
|
||||
};
|
||||
this.addToHistory(eventInfo);
|
||||
if (this.isLogging) {
|
||||
console.debug(`📡 EventBus: Emitting async '${event}'`, data);
|
||||
}
|
||||
const promises = [];
|
||||
const handlers = this.events.get(event);
|
||||
if (handlers) {
|
||||
for (const handlerInfo of [
|
||||
...handlers
|
||||
]){
|
||||
const promise = this.executeHandlerAsync(handlerInfo, data, eventInfo);
|
||||
promises.push(promise);
|
||||
}
|
||||
}
|
||||
const onceHandlers = this.onceEvents.get(event);
|
||||
if (onceHandlers) {
|
||||
for (const handlerInfo of [
|
||||
...onceHandlers
|
||||
]){
|
||||
const promise = this.executeHandlerAsync(handlerInfo, data, eventInfo);
|
||||
promises.push(promise);
|
||||
}
|
||||
this.onceEvents.delete(event);
|
||||
}
|
||||
for (const [pattern, handlers] of this.wildcardHandlers){
|
||||
for (const handlerInfo of handlers){
|
||||
if (handlerInfo.regex.test(event)) {
|
||||
const promise = this.executeHandlerAsync(handlerInfo, data, eventInfo);
|
||||
promises.push(promise);
|
||||
}
|
||||
}
|
||||
}
|
||||
const results = await Promise.allSettled(promises);
|
||||
const failures = results.filter((r)=>r.status === 'rejected');
|
||||
if (failures.length > 0) {
|
||||
console.error(`📡 EventBus: ${failures.length} handlers failed for '${event}'`);
|
||||
failures.forEach((failure)=>{
|
||||
this.emit('error', {
|
||||
event,
|
||||
error: failure.reason
|
||||
});
|
||||
});
|
||||
}
|
||||
return results.length;
|
||||
}
|
||||
async executeHandlerAsync(handlerInfo, data, eventInfo) {
|
||||
try {
|
||||
let result;
|
||||
if (handlerInfo.context) {
|
||||
result = handlerInfo.handler.call(handlerInfo.context, data, eventInfo);
|
||||
} else {
|
||||
result = handlerInfo.handler(data, eventInfo);
|
||||
}
|
||||
if (result && typeof result.then === 'function') {
|
||||
return await result;
|
||||
}
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error(`📡 EventBus: Error in async handler:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
waitFor(event, timeout = 5000) {
|
||||
return new Promise((resolve, reject)=>{
|
||||
let timeoutId;
|
||||
const unsubscribe = this.once(event, (data)=>{
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
resolve(data);
|
||||
});
|
||||
if (timeout > 0) {
|
||||
timeoutId = setTimeout(()=>{
|
||||
unsubscribe();
|
||||
reject(new Error(`Timeout waiting for event '${event}' after ${timeout}ms`));
|
||||
}, timeout);
|
||||
}
|
||||
});
|
||||
}
|
||||
removeAllListeners(event = null) {
|
||||
if (event) {
|
||||
this.events.delete(event);
|
||||
this.onceEvents.delete(event);
|
||||
for (const [pattern, handlers] of this.wildcardHandlers){
|
||||
if (pattern === event) {
|
||||
this.wildcardHandlers.delete(pattern);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.events.clear();
|
||||
this.onceEvents.clear();
|
||||
this.wildcardHandlers.clear();
|
||||
}
|
||||
if (this.isLogging) {
|
||||
console.debug(`📡 EventBus: Removed all listeners${event ? ` for '${event}'` : ''}`);
|
||||
}
|
||||
}
|
||||
listenerCount(event) {
|
||||
const regular = this.events.get(event)?.length || 0;
|
||||
const once = this.onceEvents.get(event)?.length || 0;
|
||||
let wildcard = 0;
|
||||
for (const [pattern, handlers] of this.wildcardHandlers){
|
||||
const regex = this.createWildcardRegex(pattern);
|
||||
if (regex.test(event)) {
|
||||
wildcard += handlers.length;
|
||||
}
|
||||
}
|
||||
return regular + once + wildcard;
|
||||
}
|
||||
eventNames() {
|
||||
const names = new Set();
|
||||
for (const event of this.events.keys()){
|
||||
names.add(event);
|
||||
}
|
||||
for (const event of this.onceEvents.keys()){
|
||||
names.add(event);
|
||||
}
|
||||
return Array.from(names);
|
||||
}
|
||||
getEventHistory(limit = 100) {
|
||||
return this.eventHistory.slice(-limit);
|
||||
}
|
||||
getEventsByPattern(pattern, limit = 100) {
|
||||
const regex = this.createWildcardRegex(pattern);
|
||||
return this.eventHistory.filter((event)=>regex.test(event.event)).slice(-limit);
|
||||
}
|
||||
clearHistory() {
|
||||
this.eventHistory = [];
|
||||
}
|
||||
setLogging(enabled) {
|
||||
this.isLogging = enabled;
|
||||
}
|
||||
createWildcardRegex(pattern) {
|
||||
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.');
|
||||
return new RegExp(`^${escaped}$`);
|
||||
}
|
||||
generateHandlerId() {
|
||||
return `handler_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
generateEventId() {
|
||||
return `event_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
addToHistory(eventInfo) {
|
||||
this.eventHistory.push(eventInfo);
|
||||
if (this.eventHistory.length > this.maxHistorySize) {
|
||||
this.eventHistory = this.eventHistory.slice(-this.maxHistorySize);
|
||||
}
|
||||
}
|
||||
getStats() {
|
||||
return {
|
||||
regularEvents: this.events.size,
|
||||
onceEvents: this.onceEvents.size,
|
||||
wildcardPatterns: this.wildcardHandlers.size,
|
||||
historySize: this.eventHistory.length,
|
||||
totalHandlers: Array.from(this.events.values()).reduce((sum, handlers)=>sum + handlers.length, 0) + Array.from(this.onceEvents.values()).reduce((sum, handlers)=>sum + handlers.length, 0) + Array.from(this.wildcardHandlers.values()).reduce((sum, handlers)=>sum + handlers.length, 0)
|
||||
};
|
||||
}
|
||||
debug() {
|
||||
const stats = this.getStats();
|
||||
console.group('📡 EventBus Debug Info');
|
||||
console.log('Statistics:', stats);
|
||||
console.log('Regular Events:', Array.from(this.events.keys()));
|
||||
console.log('Once Events:', Array.from(this.onceEvents.keys()));
|
||||
console.log('Wildcard Patterns:', Array.from(this.wildcardHandlers.keys()));
|
||||
console.log('Recent History:', this.getEventHistory(10));
|
||||
console.groupEnd();
|
||||
}
|
||||
}
|
||||
export default EventBus;
|
||||
|
||||
//# sourceMappingURL=EventBus.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/web-ui/core/EventBus.js"],"sourcesContent":["/**\n * EventBus - Central event communication system for the Web UI\n * Enables loose coupling between components and real-time updates\n */\n\nexport class EventBus {\n constructor() {\n this.events = new Map();\n this.onceEvents = new Map();\n this.wildcardHandlers = new Map();\n this.eventHistory = [];\n this.maxHistorySize = 1000;\n this.isLogging = true;\n }\n\n /**\n * Subscribe to an event\n */\n on(event, handler, context = null) {\n if (typeof handler !== 'function') {\n throw new Error('Event handler must be a function');\n }\n\n if (!this.events.has(event)) {\n this.events.set(event, []);\n }\n\n const handlerInfo = {\n handler,\n context,\n id: this.generateHandlerId(),\n };\n\n this.events.get(event).push(handlerInfo);\n\n if (this.isLogging) {\n console.debug(`📡 EventBus: Subscribed to '${event}'`);\n }\n\n // Return unsubscribe function\n return () => this.off(event, handler);\n }\n\n /**\n * Subscribe to an event (once only)\n */\n once(event, handler, context = null) {\n if (typeof handler !== 'function') {\n throw new Error('Event handler must be a function');\n }\n\n if (!this.onceEvents.has(event)) {\n this.onceEvents.set(event, []);\n }\n\n const handlerInfo = {\n handler,\n context,\n id: this.generateHandlerId(),\n };\n\n this.onceEvents.get(event).push(handlerInfo);\n\n if (this.isLogging) {\n console.debug(`📡 EventBus: Subscribed once to '${event}'`);\n }\n\n // Return unsubscribe function\n return () => this.offOnce(event, handler);\n }\n\n /**\n * Subscribe to events with wildcard patterns\n */\n onWildcard(pattern, handler, context = null) {\n if (typeof handler !== 'function') {\n throw new Error('Event handler must be a function');\n }\n\n if (!this.wildcardHandlers.has(pattern)) {\n this.wildcardHandlers.set(pattern, []);\n }\n\n const handlerInfo = {\n handler,\n context,\n id: this.generateHandlerId(),\n regex: this.createWildcardRegex(pattern),\n };\n\n this.wildcardHandlers.get(pattern).push(handlerInfo);\n\n if (this.isLogging) {\n console.debug(`📡 EventBus: Subscribed to wildcard pattern '${pattern}'`);\n }\n\n // Return unsubscribe function\n return () => this.offWildcard(pattern, handler);\n }\n\n /**\n * Unsubscribe from an event\n */\n off(event, handler) {\n const handlers = this.events.get(event);\n if (!handlers) return false;\n\n const index = handlers.findIndex((h) => h.handler === handler);\n if (index === -1) return false;\n\n handlers.splice(index, 1);\n\n if (handlers.length === 0) {\n this.events.delete(event);\n }\n\n if (this.isLogging) {\n console.debug(`📡 EventBus: Unsubscribed from '${event}'`);\n }\n\n return true;\n }\n\n /**\n * Unsubscribe from a once event\n */\n offOnce(event, handler) {\n const handlers = this.onceEvents.get(event);\n if (!handlers) return false;\n\n const index = handlers.findIndex((h) => h.handler === handler);\n if (index === -1) return false;\n\n handlers.splice(index, 1);\n\n if (handlers.length === 0) {\n this.onceEvents.delete(event);\n }\n\n return true;\n }\n\n /**\n * Unsubscribe from wildcard pattern\n */\n offWildcard(pattern, handler) {\n const handlers = this.wildcardHandlers.get(pattern);\n if (!handlers) return false;\n\n const index = handlers.findIndex((h) => h.handler === handler);\n if (index === -1) return false;\n\n handlers.splice(index, 1);\n\n if (handlers.length === 0) {\n this.wildcardHandlers.delete(pattern);\n }\n\n return true;\n }\n\n /**\n * Emit an event\n */\n emit(event, data = null) {\n const eventInfo = {\n event,\n data,\n timestamp: Date.now(),\n id: this.generateEventId(),\n };\n\n // Add to history\n this.addToHistory(eventInfo);\n\n if (this.isLogging) {\n console.debug(`📡 EventBus: Emitting '${event}'`, data);\n }\n\n let handlersExecuted = 0;\n\n // Execute regular event handlers\n const handlers = this.events.get(event);\n if (handlers) {\n for (const handlerInfo of [...handlers]) {\n try {\n if (handlerInfo.context) {\n handlerInfo.handler.call(handlerInfo.context, data, eventInfo);\n } else {\n handlerInfo.handler(data, eventInfo);\n }\n handlersExecuted++;\n } catch (error) {\n console.error(`📡 EventBus: Error in handler for '${event}':`, error);\n this.emit('error', { event, error, handlerInfo });\n }\n }\n }\n\n // Execute once event handlers\n const onceHandlers = this.onceEvents.get(event);\n if (onceHandlers) {\n for (const handlerInfo ofLine truncated
|
||||
@@ -1,948 +0,0 @@
|
||||
export class MCPIntegrationLayer {
|
||||
constructor(eventBus){
|
||||
this.eventBus = eventBus;
|
||||
this.mcpTools = new Map();
|
||||
this.toolResults = new Map();
|
||||
this.activeExecutions = new Map();
|
||||
this.cache = new Map();
|
||||
this.isInitialized = false;
|
||||
this.mcpServerStatus = 'unknown';
|
||||
this.toolCategories = {
|
||||
neural: [],
|
||||
memory: [],
|
||||
monitoring: [],
|
||||
workflow: [],
|
||||
github: [],
|
||||
daa: [],
|
||||
system: []
|
||||
};
|
||||
}
|
||||
async initialize() {
|
||||
try {
|
||||
this.mcpServerStatus = await this.checkMCPServerStatus();
|
||||
await this.discoverTools();
|
||||
this.setupToolHandlers();
|
||||
this.initializeCache();
|
||||
this.isInitialized = true;
|
||||
this.eventBus.emit('mcp:initialized', {
|
||||
status: this.mcpServerStatus
|
||||
});
|
||||
console.log('🔌 MCP Integration Layer initialized');
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to initialize MCP Integration Layer:', error);
|
||||
this.mcpServerStatus = 'error';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async checkMCPServerStatus() {
|
||||
try {
|
||||
if (typeof window !== 'undefined' && window.claudeFlowMCP) {
|
||||
return 'connected';
|
||||
}
|
||||
if (typeof process !== 'undefined' && process.env.CLAUDE_FLOW_MCP_ENABLED === 'true') {
|
||||
return 'connected';
|
||||
}
|
||||
return 'mock';
|
||||
} catch (error) {
|
||||
console.warn('MCP Server connection check failed:', error);
|
||||
return 'offline';
|
||||
}
|
||||
}
|
||||
async discoverTools() {
|
||||
const availableTools = {
|
||||
neural: [
|
||||
{
|
||||
name: 'neural_train',
|
||||
description: 'Train neural patterns with WASM SIMD',
|
||||
params: [
|
||||
'pattern_type',
|
||||
'training_data',
|
||||
'epochs'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'neural_predict',
|
||||
description: 'Make AI predictions',
|
||||
params: [
|
||||
'modelId',
|
||||
'input'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'neural_status',
|
||||
description: 'Check neural network status',
|
||||
params: [
|
||||
'modelId'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'neural_patterns',
|
||||
description: 'Analyze cognitive patterns',
|
||||
params: [
|
||||
'action',
|
||||
'operation',
|
||||
'outcome'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'model_load',
|
||||
description: 'Load pre-trained models',
|
||||
params: [
|
||||
'modelPath'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'model_save',
|
||||
description: 'Save trained models',
|
||||
params: [
|
||||
'modelId',
|
||||
'path'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'pattern_recognize',
|
||||
description: 'Pattern recognition',
|
||||
params: [
|
||||
'data',
|
||||
'patterns'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'cognitive_analyze',
|
||||
description: 'Cognitive behavior analysis',
|
||||
params: [
|
||||
'behavior'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'learning_adapt',
|
||||
description: 'Adaptive learning',
|
||||
params: [
|
||||
'experience'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'neural_compress',
|
||||
description: 'Compress neural models',
|
||||
params: [
|
||||
'modelId',
|
||||
'ratio'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'ensemble_create',
|
||||
description: 'Create model ensembles',
|
||||
params: [
|
||||
'models',
|
||||
'strategy'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'transfer_learn',
|
||||
description: 'Transfer learning',
|
||||
params: [
|
||||
'sourceModel',
|
||||
'targetDomain'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'neural_explain',
|
||||
description: 'AI explainability',
|
||||
params: [
|
||||
'modelId',
|
||||
'prediction'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'wasm_optimize',
|
||||
description: 'WASM SIMD optimization',
|
||||
params: [
|
||||
'operation'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'inference_run',
|
||||
description: 'Run neural inference',
|
||||
params: [
|
||||
'modelId',
|
||||
'data'
|
||||
]
|
||||
}
|
||||
],
|
||||
memory: [
|
||||
{
|
||||
name: 'memory_usage',
|
||||
description: 'Store/retrieve persistent memory',
|
||||
params: [
|
||||
'action',
|
||||
'key',
|
||||
'value',
|
||||
'namespace',
|
||||
'ttl'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'memory_backup',
|
||||
description: 'Backup memory stores',
|
||||
params: [
|
||||
'path'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'memory_restore',
|
||||
description: 'Restore from backups',
|
||||
params: [
|
||||
'backupPath'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'memory_compress',
|
||||
description: 'Compress memory data',
|
||||
params: [
|
||||
'namespace'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'memory_sync',
|
||||
description: 'Sync across instances',
|
||||
params: [
|
||||
'target'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'cache_manage',
|
||||
description: 'Manage coordination cache',
|
||||
params: [
|
||||
'action',
|
||||
'key'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'state_snapshot',
|
||||
description: 'Create state snapshots',
|
||||
params: [
|
||||
'name'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'context_restore',
|
||||
description: 'Restore execution context',
|
||||
params: [
|
||||
'snapshotId'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'memory_analytics',
|
||||
description: 'Analyze memory usage',
|
||||
params: [
|
||||
'timeframe'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'memory_persist',
|
||||
description: 'Cross-session persistence',
|
||||
params: [
|
||||
'sessionId'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'memory_namespace',
|
||||
description: 'Namespace management',
|
||||
params: [
|
||||
'namespace',
|
||||
'action'
|
||||
]
|
||||
}
|
||||
],
|
||||
monitoring: [
|
||||
{
|
||||
name: 'performance_report',
|
||||
description: 'Generate performance reports',
|
||||
params: [
|
||||
'format',
|
||||
'timeframe'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'bottleneck_analyze',
|
||||
description: 'Identify performance bottlenecks',
|
||||
params: [
|
||||
'component',
|
||||
'metrics'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'token_usage',
|
||||
description: 'Analyze token consumption',
|
||||
params: [
|
||||
'operation',
|
||||
'timeframe'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'benchmark_run',
|
||||
description: 'Performance benchmarks',
|
||||
params: [
|
||||
'suite'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'metrics_collect',
|
||||
description: 'Collect system metrics',
|
||||
params: [
|
||||
'components'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'trend_analysis',
|
||||
description: 'Analyze performance trends',
|
||||
params: [
|
||||
'metric',
|
||||
'period'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'cost_analysis',
|
||||
description: 'Cost and resource analysis',
|
||||
params: [
|
||||
'timeframe'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'quality_assess',
|
||||
description: 'Quality assessment',
|
||||
params: [
|
||||
'target',
|
||||
'criteria'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'error_analysis',
|
||||
description: 'Error pattern analysis',
|
||||
params: [
|
||||
'logs'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'usage_stats',
|
||||
description: 'Usage statistics',
|
||||
params: [
|
||||
'component'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'health_check',
|
||||
description: 'System health monitoring',
|
||||
params: [
|
||||
'components'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'swarm_monitor',
|
||||
description: 'Real-time swarm monitoring',
|
||||
params: [
|
||||
'swarmId',
|
||||
'interval'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'agent_metrics',
|
||||
description: 'Agent performance metrics',
|
||||
params: [
|
||||
'agentId'
|
||||
]
|
||||
}
|
||||
],
|
||||
workflow: [
|
||||
{
|
||||
name: 'workflow_create',
|
||||
description: 'Create custom workflows',
|
||||
params: [
|
||||
'name',
|
||||
'steps',
|
||||
'triggers'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'workflow_execute',
|
||||
description: 'Execute predefined workflows',
|
||||
params: [
|
||||
'workflowId',
|
||||
'params'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'automation_setup',
|
||||
description: 'Setup automation rules',
|
||||
params: [
|
||||
'rules'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'pipeline_create',
|
||||
description: 'Create CI/CD pipelines',
|
||||
params: [
|
||||
'config'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'scheduler_manage',
|
||||
description: 'Manage task scheduling',
|
||||
params: [
|
||||
'action',
|
||||
'schedule'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'trigger_setup',
|
||||
description: 'Setup event triggers',
|
||||
params: [
|
||||
'events',
|
||||
'actions'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'workflow_template',
|
||||
description: 'Manage workflow templates',
|
||||
params: [
|
||||
'action',
|
||||
'template'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'batch_process',
|
||||
description: 'Batch processing',
|
||||
params: [
|
||||
'items',
|
||||
'operation'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'parallel_execute',
|
||||
description: 'Execute tasks in parallel',
|
||||
params: [
|
||||
'tasks'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'sparc_mode',
|
||||
description: 'Run SPARC development modes',
|
||||
params: [
|
||||
'mode',
|
||||
"task_description",
|
||||
'options'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'task_orchestrate',
|
||||
description: 'Orchestrate complex task workflows',
|
||||
params: [
|
||||
'task',
|
||||
'strategy',
|
||||
'priority',
|
||||
'dependencies'
|
||||
]
|
||||
}
|
||||
],
|
||||
github: [
|
||||
{
|
||||
name: 'github_repo_analyze',
|
||||
description: 'Repository analysis',
|
||||
params: [
|
||||
'repo',
|
||||
'analysis_type'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'github_pr_manage',
|
||||
description: 'Pull request management',
|
||||
params: [
|
||||
'repo',
|
||||
'action',
|
||||
'pr_number'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'github_issue_track',
|
||||
description: 'Issue tracking & triage',
|
||||
params: [
|
||||
'repo',
|
||||
'action'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'github_release_coord',
|
||||
description: 'Release coordination',
|
||||
params: [
|
||||
'repo',
|
||||
'version'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'github_workflow_auto',
|
||||
description: 'Workflow automation',
|
||||
params: [
|
||||
'repo',
|
||||
'workflow'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'github_code_review',
|
||||
description: 'Automated code review',
|
||||
params: [
|
||||
'repo',
|
||||
'pr'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'github_sync_coord',
|
||||
description: 'Multi-repo sync coordination',
|
||||
params: [
|
||||
'repos'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'github_metrics',
|
||||
description: 'Repository metrics',
|
||||
params: [
|
||||
'repo'
|
||||
]
|
||||
}
|
||||
],
|
||||
daa: [
|
||||
{
|
||||
name: 'daa_agent_create',
|
||||
description: 'Create dynamic agents',
|
||||
params: [
|
||||
'agent_type',
|
||||
'capabilities',
|
||||
'resources'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'daa_capability_match',
|
||||
description: 'Match capabilities to tasks',
|
||||
params: [
|
||||
'task_requirements',
|
||||
'available_agents'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'daa_resource_alloc',
|
||||
description: 'Resource allocation',
|
||||
params: [
|
||||
'resources',
|
||||
'agents'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'daa_lifecycle_manage',
|
||||
description: 'Agent lifecycle management',
|
||||
params: [
|
||||
'agentId',
|
||||
'action'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'daa_communication',
|
||||
description: 'Inter-agent communication',
|
||||
params: [
|
||||
'from',
|
||||
'to',
|
||||
'message'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'daa_consensus',
|
||||
description: 'Consensus mechanisms',
|
||||
params: [
|
||||
'agents',
|
||||
'proposal'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'daa_fault_tolerance',
|
||||
description: 'Fault tolerance & recovery',
|
||||
params: [
|
||||
'agentId',
|
||||
'strategy'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'daa_optimization',
|
||||
description: 'Performance optimization',
|
||||
params: [
|
||||
'target',
|
||||
'metrics'
|
||||
]
|
||||
}
|
||||
],
|
||||
system: [
|
||||
{
|
||||
name: 'security_scan',
|
||||
description: 'Security scanning',
|
||||
params: [
|
||||
'target',
|
||||
'depth'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'backup_create',
|
||||
description: 'Create system backups',
|
||||
params: [
|
||||
'components',
|
||||
'destination'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'restore_system',
|
||||
description: 'System restoration',
|
||||
params: [
|
||||
'backupId'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'log_analysis',
|
||||
description: 'Log analysis & insights',
|
||||
params: [
|
||||
'logFile',
|
||||
'patterns'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'diagnostic_run',
|
||||
description: 'System diagnostics',
|
||||
params: [
|
||||
'components'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'config_manage',
|
||||
description: 'Configuration management',
|
||||
params: [
|
||||
'action',
|
||||
'config'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'features_detect',
|
||||
description: 'Feature detection',
|
||||
params: [
|
||||
'component'
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'terminal_execute',
|
||||
description: 'Execute terminal commands',
|
||||
params: [
|
||||
'command',
|
||||
'args'
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
for (const [category, tools] of Object.entries(availableTools)){
|
||||
this.toolCategories[category] = tools;
|
||||
tools.forEach((tool)=>{
|
||||
this.mcpTools.set(tool.name, {
|
||||
...tool,
|
||||
category,
|
||||
lastUsed: null,
|
||||
usageCount: 0
|
||||
});
|
||||
});
|
||||
}
|
||||
console.log(`🔧 Discovered ${this.mcpTools.size} MCP tools across ${Object.keys(this.toolCategories).length} categories`);
|
||||
}
|
||||
async executeTool(toolName, params = {}) {
|
||||
if (!this.isInitialized) {
|
||||
throw new Error('MCP Integration Layer not initialized');
|
||||
}
|
||||
const tool = this.mcpTools.get(toolName);
|
||||
if (!tool) {
|
||||
throw new Error(`Tool not found: ${toolName}`);
|
||||
}
|
||||
if (this.activeExecutions.has(toolName)) {
|
||||
throw new Error(`Tool ${toolName} is already executing`);
|
||||
}
|
||||
const cacheKey = this.getCacheKey(toolName, params);
|
||||
const cached = this.cache.get(cacheKey);
|
||||
if (cached && !this.isCacheExpired(cached)) {
|
||||
return cached.result;
|
||||
}
|
||||
try {
|
||||
this.activeExecutions.set(toolName, {
|
||||
startTime: Date.now(),
|
||||
params
|
||||
});
|
||||
let result;
|
||||
if (this.mcpServerStatus === 'connected') {
|
||||
result = await this.executeRealTool(toolName, params);
|
||||
} else {
|
||||
result = await this.executeMockTool(toolName, params);
|
||||
}
|
||||
tool.lastUsed = Date.now();
|
||||
tool.usageCount++;
|
||||
this.cacheResult(cacheKey, result);
|
||||
this.toolResults.set(toolName, {
|
||||
result,
|
||||
timestamp: Date.now(),
|
||||
params
|
||||
});
|
||||
this.eventBus.emit('tool:executed', {
|
||||
tool: toolName,
|
||||
result,
|
||||
params,
|
||||
duration: Date.now() - this.activeExecutions.get(toolName).startTime
|
||||
});
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.eventBus.emit('tool:error', {
|
||||
tool: toolName,
|
||||
error: error.message,
|
||||
params
|
||||
});
|
||||
throw error;
|
||||
} finally{
|
||||
this.activeExecutions.delete(toolName);
|
||||
}
|
||||
}
|
||||
async executeRealTool(toolName, params) {
|
||||
const mcpToolName = `mcp__claude-flow__${toolName}`;
|
||||
if (typeof window !== 'undefined' && window.claudeFlowMCP) {
|
||||
return await window.claudeFlowMCP.execute(mcpToolName, params);
|
||||
}
|
||||
if (typeof process !== 'undefined') {
|
||||
return this.executeMockTool(toolName, params);
|
||||
}
|
||||
throw new Error('MCP server not available');
|
||||
}
|
||||
async executeMockTool(toolName, params) {
|
||||
await new Promise((resolve)=>setTimeout(resolve, 100 + Math.random() * 500));
|
||||
const mockResults = {
|
||||
neural_train: {
|
||||
success: true,
|
||||
epochs: params.epochs || 50,
|
||||
accuracy: 0.95,
|
||||
loss: 0.05
|
||||
},
|
||||
neural_predict: {
|
||||
prediction: 'sample_prediction',
|
||||
confidence: 0.87
|
||||
},
|
||||
neural_status: {
|
||||
modelId: params.modelId,
|
||||
status: 'ready',
|
||||
accuracy: 0.92
|
||||
},
|
||||
neural_patterns: {
|
||||
patterns: [
|
||||
'pattern1',
|
||||
'pattern2'
|
||||
],
|
||||
insights: 'analysis complete'
|
||||
},
|
||||
memory_usage: {
|
||||
action: params.action,
|
||||
key: params.key,
|
||||
success: true,
|
||||
result: params.action === 'retrieve' ? 'sample_value' : 'stored'
|
||||
},
|
||||
memory_backup: {
|
||||
backupId: 'backup_' + Date.now(),
|
||||
size: '1.2MB',
|
||||
success: true
|
||||
},
|
||||
memory_analytics: {
|
||||
entries: 42,
|
||||
size: '156KB',
|
||||
namespaces: 4
|
||||
},
|
||||
performance_report: {
|
||||
cpu: 45,
|
||||
memory: 67,
|
||||
uptime: 3600,
|
||||
efficiency: 92,
|
||||
bottlenecks: [
|
||||
'network_io',
|
||||
'memory_allocation'
|
||||
]
|
||||
},
|
||||
bottleneck_analyze: {
|
||||
component: params.component,
|
||||
issues: [
|
||||
'high_cpu_usage',
|
||||
'memory_leaks'
|
||||
],
|
||||
recommendations: [
|
||||
'optimize_queries',
|
||||
'increase_cache'
|
||||
]
|
||||
},
|
||||
workflow_create: {
|
||||
workflowId: 'wf_' + Date.now(),
|
||||
status: 'created'
|
||||
},
|
||||
workflow_execute: {
|
||||
workflowId: params.workflowId,
|
||||
status: 'completed',
|
||||
duration: 1500
|
||||
},
|
||||
task_orchestrate: {
|
||||
taskId: 'task_' + Date.now(),
|
||||
status: 'orchestrated',
|
||||
agents: 3
|
||||
},
|
||||
github_repo_analyze: {
|
||||
repo: params.repo,
|
||||
score: 85,
|
||||
issues: 12,
|
||||
complexity: 'medium',
|
||||
recommendations: [
|
||||
'add_tests',
|
||||
'update_dependencies'
|
||||
]
|
||||
},
|
||||
daa_agent_create: {
|
||||
agentId: 'agent_' + Date.now(),
|
||||
type: params.agent_type,
|
||||
status: 'created'
|
||||
},
|
||||
daa_capability_match: {
|
||||
matches: [
|
||||
'agent1',
|
||||
'agent2'
|
||||
],
|
||||
confidence: 0.89
|
||||
},
|
||||
security_scan: {
|
||||
target: params.target,
|
||||
vulnerabilities: 2,
|
||||
score: 'A-',
|
||||
issues: [
|
||||
'outdated_dependencies',
|
||||
'weak_encryption'
|
||||
]
|
||||
},
|
||||
health_check: {
|
||||
status: 'healthy',
|
||||
components: {
|
||||
all: 'ok'
|
||||
},
|
||||
uptime: 3600
|
||||
}
|
||||
};
|
||||
return mockResults[toolName] || {
|
||||
success: true,
|
||||
message: 'Mock execution completed'
|
||||
};
|
||||
}
|
||||
getCacheKey(toolName, params) {
|
||||
return `${toolName}_${JSON.stringify(params)}`;
|
||||
}
|
||||
cacheResult(cacheKey, result) {
|
||||
this.cache.set(cacheKey, {
|
||||
result,
|
||||
timestamp: Date.now(),
|
||||
ttl: 5 * 60 * 1000
|
||||
});
|
||||
}
|
||||
isCacheExpired(cacheEntry) {
|
||||
return Date.now() - cacheEntry.timestamp > cacheEntry.ttl;
|
||||
}
|
||||
setupToolHandlers() {
|
||||
this.eventBus.on('tool:execute', async (data)=>{
|
||||
try {
|
||||
const result = await this.executeTool(data.tool, data.params);
|
||||
this.eventBus.emit('tool:result', {
|
||||
tool: data.tool,
|
||||
result
|
||||
});
|
||||
} catch (error) {
|
||||
this.eventBus.emit('tool:error', {
|
||||
tool: data.tool,
|
||||
error
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
initializeCache() {
|
||||
setInterval(()=>{
|
||||
for (const [key, entry] of this.cache.entries()){
|
||||
if (this.isCacheExpired(entry)) {
|
||||
this.cache.delete(key);
|
||||
}
|
||||
}
|
||||
}, 5 * 60 * 1000);
|
||||
}
|
||||
getAvailableTools() {
|
||||
return Array.from(this.mcpTools.values());
|
||||
}
|
||||
getToolsByCategory(category) {
|
||||
return this.toolCategories[category] || [];
|
||||
}
|
||||
getToolUsageStats() {
|
||||
const stats = {};
|
||||
for (const [name, tool] of this.mcpTools){
|
||||
stats[name] = {
|
||||
usageCount: tool.usageCount,
|
||||
lastUsed: tool.lastUsed,
|
||||
category: tool.category
|
||||
};
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
async getSystemStatus() {
|
||||
return {
|
||||
mcpServerStatus: this.mcpServerStatus,
|
||||
toolsAvailable: this.mcpTools.size,
|
||||
activeExecutions: this.activeExecutions.size,
|
||||
cacheSize: this.cache.size,
|
||||
isInitialized: this.isInitialized
|
||||
};
|
||||
}
|
||||
async getSystemUptime() {
|
||||
if (typeof process !== 'undefined') {
|
||||
return process.uptime();
|
||||
}
|
||||
return Date.now() - (window.claudeFlowStartTime || Date.now());
|
||||
}
|
||||
async getActiveTools() {
|
||||
return Array.from(this.activeExecutions.keys());
|
||||
}
|
||||
async getMemoryUsage() {
|
||||
if (typeof process !== 'undefined') {
|
||||
const usage = process.memoryUsage();
|
||||
return {
|
||||
used: usage.heapUsed,
|
||||
total: usage.heapTotal,
|
||||
external: usage.external
|
||||
};
|
||||
}
|
||||
return {
|
||||
used: 0,
|
||||
total: 0,
|
||||
external: 0
|
||||
};
|
||||
}
|
||||
async getSwarmStatus() {
|
||||
try {
|
||||
const result = await this.executeTool('swarm_status');
|
||||
return result;
|
||||
} catch (error) {
|
||||
return {
|
||||
status: 'offline',
|
||||
error: error.message
|
||||
};
|
||||
}
|
||||
}
|
||||
async shutdown() {
|
||||
this.activeExecutions.clear();
|
||||
this.cache.clear();
|
||||
this.toolResults.clear();
|
||||
this.eventBus.emit('mcp:shutdown');
|
||||
}
|
||||
}
|
||||
export default MCPIntegrationLayer;
|
||||
|
||||
//# sourceMappingURL=MCPIntegrationLayer.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/web-ui/core/MCPIntegrationLayer.js"],"sourcesContent":["/**\n * MCP Integration Layer - Bridge between UI and Claude Flow MCP Tools\n * Handles all MCP tool execution, caching, and result processing\n */\n\nimport { EventBus } from './EventBus.js';\n\nexport class MCPIntegrationLayer {\n constructor(eventBus) {\n this.eventBus = eventBus;\n this.mcpTools = new Map();\n this.toolResults = new Map();\n this.activeExecutions = new Map();\n this.cache = new Map();\n this.isInitialized = false;\n this.mcpServerStatus = 'unknown';\n this.toolCategories = {\n neural: [],\n memory: [],\n monitoring: [],\n workflow: [],\n github: [],\n daa: [],\n system: [],\n };\n }\n\n /**\n * Initialize MCP integration layer\n */\n async initialize() {\n try {\n // Check if MCP server is available\n this.mcpServerStatus = await this.checkMCPServerStatus();\n\n // Discover available tools\n await this.discoverTools();\n\n // Setup tool execution handlers\n this.setupToolHandlers();\n\n // Initialize caching system\n this.initializeCache();\n\n this.isInitialized = true;\n this.eventBus.emit('mcp:initialized', { status: this.mcpServerStatus });\n\n console.log('🔌 MCP Integration Layer initialized');\n } catch (error) {\n console.error('❌ Failed to initialize MCP Integration Layer:', error);\n this.mcpServerStatus = 'error';\n throw error;\n }\n }\n\n /**\n * Check MCP server status\n */\n async checkMCPServerStatus() {\n try {\n // Try to detect available MCP tools\n // This would normally check for actual MCP server connection\n if (typeof window !== 'undefined' && window.claudeFlowMCP) {\n return 'connected';\n }\n\n // Check for Node.js environment with MCP tools\n if (typeof process !== 'undefined' && process.env.CLAUDE_FLOW_MCP_ENABLED === 'true') {\n return 'connected';\n }\n\n return 'mock'; // Use mock mode for development\n } catch (error) {\n console.warn('MCP Server connection check failed:', error);\n return 'offline';\n }\n }\n\n /**\n * Discover available MCP tools\n */\n async discoverTools() {\n const availableTools = {\n // Neural Network Tools\n neural: [\n {\n name: 'neural_train',\n description: 'Train neural patterns with WASM SIMD',\n params: ['pattern_type', 'training_data', 'epochs'],\n },\n {\n name: 'neural_predict',\n description: 'Make AI predictions',\n params: ['modelId', 'input'],\n },\n { name: 'neural_status', description: 'Check neural network status', params: ['modelId'] },\n {\n name: 'neural_patterns',\n description: 'Analyze cognitive patterns',\n params: ['action', 'operation', 'outcome'],\n },\n { name: 'model_load', description: 'Load pre-trained models', params: ['modelPath'] },\n { name: 'model_save', description: 'Save trained models', params: ['modelId', 'path'] },\n {\n name: 'pattern_recognize',\n description: 'Pattern recognition',\n params: ['data', 'patterns'],\n },\n {\n name: 'cognitive_analyze',\n description: 'Cognitive behavior analysis',\n params: ['behavior'],\n },\n { name: 'learning_adapt', description: 'Adaptive learning', params: ['experience'] },\n {\n name: 'neural_compress',\n description: 'Compress neural models',\n params: ['modelId', 'ratio'],\n },\n {\n name: 'ensemble_create',\n description: 'Create model ensembles',\n params: ['models', 'strategy'],\n },\n {\n name: 'transfer_learn',\n description: 'Transfer learning',\n params: ['sourceModel', 'targetDomain'],\n },\n {\n name: 'neural_explain',\n description: 'AI explainability',\n params: ['modelId', 'prediction'],\n },\n { name: 'wasm_optimize', description: 'WASM SIMD optimization', params: ['operation'] },\n { name: 'inference_run', description: 'Run neural inference', params: ['modelId', 'data'] },\n ],\n\n // Memory & Persistence Tools\n memory: [\n {\n name: 'memory_usage',\n description: 'Store/retrieve persistent memory',\n params: ['action', 'key', 'value', 'namespace', 'ttl'],\n },\n { name: 'memory_backup', description: 'Backup memory stores', params: ['path'] },\n { name: 'memory_restore', description: 'Restore from backups', params: ['backupPath'] },\n { name: 'memory_compress', description: 'Compress memory data', params: ['namespace'] },\n { name: 'memory_sync', description: 'Sync across instances', params: ['targeLine truncated
|
||||
@@ -1,356 +0,0 @@
|
||||
export class StateManager {
|
||||
constructor(eventBus){
|
||||
this.eventBus = eventBus;
|
||||
this.state = new Map();
|
||||
this.preferences = new Map();
|
||||
this.toolResults = new Map();
|
||||
this.viewStates = new Map();
|
||||
this.sessionData = new Map();
|
||||
this.storageKey = 'claude-flow-ui-state';
|
||||
this.isInitialized = false;
|
||||
this.autoSaveInterval = 30000;
|
||||
this.autoSaveTimer = null;
|
||||
}
|
||||
async initialize() {
|
||||
try {
|
||||
await this.loadPersistedState();
|
||||
this.setupAutoSave();
|
||||
this.setupEventHandlers();
|
||||
this.isInitialized = true;
|
||||
this.eventBus.emit('state-manager:initialized');
|
||||
console.log('💾 State Manager initialized');
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to initialize State Manager:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async loadPersistedState() {
|
||||
try {
|
||||
let persistedData = null;
|
||||
if (typeof window !== 'undefined' && window.localStorage) {
|
||||
const stored = localStorage.getItem(this.storageKey);
|
||||
if (stored) {
|
||||
persistedData = JSON.parse(stored);
|
||||
}
|
||||
}
|
||||
if (!persistedData && typeof process !== 'undefined') {
|
||||
try {
|
||||
const fs = await import('fs');
|
||||
const path = await import('path');
|
||||
const stateFile = path.join(process.cwd(), '.claude-flow-state.json');
|
||||
if (fs.existsSync(stateFile)) {
|
||||
const data = fs.readFileSync(stateFile, 'utf8');
|
||||
persistedData = JSON.parse(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Could not load state from file system:', error.message);
|
||||
}
|
||||
}
|
||||
if (persistedData) {
|
||||
this.restoreFromData(persistedData);
|
||||
console.log('💾 Loaded persisted state');
|
||||
} else {
|
||||
this.initializeDefaultState();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Could not load persisted state:', error);
|
||||
this.initializeDefaultState();
|
||||
}
|
||||
}
|
||||
restoreFromData(data) {
|
||||
if (data.preferences) {
|
||||
this.preferences = new Map(Object.entries(data.preferences));
|
||||
}
|
||||
if (data.viewStates) {
|
||||
this.viewStates = new Map(Object.entries(data.viewStates));
|
||||
}
|
||||
if (data.toolResults) {
|
||||
this.toolResults = new Map(Object.entries(data.toolResults));
|
||||
}
|
||||
if (data.sessionData) {
|
||||
this.sessionData = new Map(Object.entries(data.sessionData));
|
||||
}
|
||||
if (data.state) {
|
||||
this.state = new Map(Object.entries(data.state));
|
||||
}
|
||||
}
|
||||
initializeDefaultState() {
|
||||
this.preferences.set('theme', 'dark');
|
||||
this.preferences.set('autoSave', true);
|
||||
this.preferences.set('showTooltips', true);
|
||||
this.preferences.set('animationSpeed', 'normal');
|
||||
this.preferences.set('defaultView', 'overview');
|
||||
this.preferences.set('keyboardShortcuts', true);
|
||||
this.preferences.set('realTimeUpdates', true);
|
||||
this.preferences.set('logLevel', 'info');
|
||||
this.state.set('initialized', true);
|
||||
this.state.set('version', '2.0.0');
|
||||
this.state.set('installDate', Date.now());
|
||||
console.log('💾 Initialized default state');
|
||||
}
|
||||
setupAutoSave() {
|
||||
if (!this.getPreference('autoSave', true)) {
|
||||
return;
|
||||
}
|
||||
this.autoSaveTimer = setInterval(()=>{
|
||||
this.persistState();
|
||||
}, this.autoSaveInterval);
|
||||
}
|
||||
async persistState() {
|
||||
try {
|
||||
const stateData = {
|
||||
timestamp: Date.now(),
|
||||
version: '2.0.0',
|
||||
preferences: Object.fromEntries(this.preferences),
|
||||
viewStates: Object.fromEntries(this.viewStates),
|
||||
toolResults: Object.fromEntries(this.toolResults),
|
||||
sessionData: Object.fromEntries(this.sessionData),
|
||||
state: Object.fromEntries(this.state)
|
||||
};
|
||||
if (typeof window !== 'undefined' && window.localStorage) {
|
||||
localStorage.setItem(this.storageKey, JSON.stringify(stateData));
|
||||
}
|
||||
if (typeof process !== 'undefined') {
|
||||
try {
|
||||
const fs = await import('fs');
|
||||
const path = await import('path');
|
||||
const stateFile = path.join(process.cwd(), '.claude-flow-state.json');
|
||||
fs.writeFileSync(stateFile, JSON.stringify(stateData, null, 2));
|
||||
} catch (error) {
|
||||
console.warn('Could not save state to file system:', error.message);
|
||||
}
|
||||
}
|
||||
this.eventBus.emit('state:persisted', {
|
||||
timestamp: Date.now()
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to persist state:', error);
|
||||
this.eventBus.emit('state:error', {
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
}
|
||||
getPreference(key, defaultValue = null) {
|
||||
return this.preferences.get(key) ?? defaultValue;
|
||||
}
|
||||
setPreference(key, value) {
|
||||
this.preferences.set(key, value);
|
||||
this.eventBus.emit('preference:changed', {
|
||||
key,
|
||||
value
|
||||
});
|
||||
if (this.getPreference('autoSave', true)) {
|
||||
this.debouncedSave();
|
||||
}
|
||||
}
|
||||
getPreferences(keys) {
|
||||
const result = {};
|
||||
for (const key of keys){
|
||||
result[key] = this.preferences.get(key);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
setPreferences(preferences) {
|
||||
for (const [key, value] of Object.entries(preferences)){
|
||||
this.preferences.set(key, value);
|
||||
}
|
||||
this.eventBus.emit('preferences:changed', preferences);
|
||||
if (this.getPreference('autoSave', true)) {
|
||||
this.debouncedSave();
|
||||
}
|
||||
}
|
||||
getUserPreferences() {
|
||||
return Object.fromEntries(this.preferences);
|
||||
}
|
||||
getState(key, defaultValue = null) {
|
||||
return this.state.get(key) ?? defaultValue;
|
||||
}
|
||||
setState(key, value) {
|
||||
this.state.set(key, value);
|
||||
this.eventBus.emit('state:changed', {
|
||||
key,
|
||||
value
|
||||
});
|
||||
if (this.getPreference('autoSave', true)) {
|
||||
this.debouncedSave();
|
||||
}
|
||||
}
|
||||
getViewState(viewId) {
|
||||
return this.viewStates.get(viewId);
|
||||
}
|
||||
setViewState(viewId, state) {
|
||||
const existing = this.viewStates.get(viewId) || {};
|
||||
const newState = {
|
||||
...existing,
|
||||
...state,
|
||||
lastUpdate: Date.now()
|
||||
};
|
||||
this.viewStates.set(viewId, newState);
|
||||
this.eventBus.emit('view-state:changed', {
|
||||
viewId,
|
||||
state: newState
|
||||
});
|
||||
if (this.getPreference('autoSave', true)) {
|
||||
this.debouncedSave();
|
||||
}
|
||||
}
|
||||
clearViewState(viewId) {
|
||||
this.viewStates.delete(viewId);
|
||||
this.eventBus.emit('view-state:cleared', {
|
||||
viewId
|
||||
});
|
||||
}
|
||||
getToolResult(toolName) {
|
||||
return this.toolResults.get(toolName);
|
||||
}
|
||||
setToolResult(toolName, result) {
|
||||
const resultData = {
|
||||
result,
|
||||
timestamp: Date.now(),
|
||||
tool: toolName
|
||||
};
|
||||
this.toolResults.set(toolName, resultData);
|
||||
this.eventBus.emit('tool-result:stored', {
|
||||
toolName,
|
||||
result
|
||||
});
|
||||
if (this.toolResults.size > 100) {
|
||||
const entries = Array.from(this.toolResults.entries());
|
||||
entries.sort((a, b)=>b[1].timestamp - a[1].timestamp);
|
||||
this.toolResults.clear();
|
||||
for (const [key, value] of entries.slice(0, 100)){
|
||||
this.toolResults.set(key, value);
|
||||
}
|
||||
}
|
||||
if (this.getPreference('autoSave', true)) {
|
||||
this.debouncedSave();
|
||||
}
|
||||
}
|
||||
getRecentToolResults(limit = 10) {
|
||||
const results = Array.from(this.toolResults.entries()).sort((a, b)=>b[1].timestamp - a[1].timestamp).slice(0, limit);
|
||||
return results.map(([tool, data])=>({
|
||||
tool,
|
||||
...data
|
||||
}));
|
||||
}
|
||||
getSessionData(key) {
|
||||
return this.sessionData.get(key);
|
||||
}
|
||||
setSessionData(key, value) {
|
||||
this.sessionData.set(key, value);
|
||||
this.eventBus.emit('session-data:changed', {
|
||||
key,
|
||||
value
|
||||
});
|
||||
}
|
||||
clearSessionData() {
|
||||
this.sessionData.clear();
|
||||
this.eventBus.emit('session-data:cleared');
|
||||
}
|
||||
exportState() {
|
||||
return {
|
||||
timestamp: Date.now(),
|
||||
version: '2.0.0',
|
||||
preferences: Object.fromEntries(this.preferences),
|
||||
viewStates: Object.fromEntries(this.viewStates),
|
||||
toolResults: Object.fromEntries(this.toolResults),
|
||||
sessionData: Object.fromEntries(this.sessionData),
|
||||
state: Object.fromEntries(this.state)
|
||||
};
|
||||
}
|
||||
importState(stateData) {
|
||||
try {
|
||||
this.restoreFromData(stateData);
|
||||
this.eventBus.emit('state:imported', {
|
||||
timestamp: Date.now()
|
||||
});
|
||||
console.log('💾 State imported successfully');
|
||||
} catch (error) {
|
||||
console.error('Failed to import state:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
resetState() {
|
||||
this.state.clear();
|
||||
this.preferences.clear();
|
||||
this.viewStates.clear();
|
||||
this.toolResults.clear();
|
||||
this.sessionData.clear();
|
||||
this.initializeDefaultState();
|
||||
this.persistState();
|
||||
this.eventBus.emit('state:reset', {
|
||||
timestamp: Date.now()
|
||||
});
|
||||
console.log('💾 State reset to defaults');
|
||||
}
|
||||
clearData(types = []) {
|
||||
if (types.includes('preferences') || types.length === 0) {
|
||||
this.preferences.clear();
|
||||
}
|
||||
if (types.includes('viewStates') || types.length === 0) {
|
||||
this.viewStates.clear();
|
||||
}
|
||||
if (types.includes('toolResults') || types.length === 0) {
|
||||
this.toolResults.clear();
|
||||
}
|
||||
if (types.includes('sessionData') || types.length === 0) {
|
||||
this.sessionData.clear();
|
||||
}
|
||||
this.eventBus.emit('data:cleared', {
|
||||
types,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
}
|
||||
getStateStats() {
|
||||
return {
|
||||
preferences: this.preferences.size,
|
||||
viewStates: this.viewStates.size,
|
||||
toolResults: this.toolResults.size,
|
||||
sessionData: this.sessionData.size,
|
||||
generalState: this.state.size,
|
||||
lastSave: this.state.get('lastSave'),
|
||||
autoSaveEnabled: this.getPreference('autoSave', true)
|
||||
};
|
||||
}
|
||||
debouncedSave() {
|
||||
if (this.saveTimeout) {
|
||||
clearTimeout(this.saveTimeout);
|
||||
}
|
||||
this.saveTimeout = setTimeout(()=>{
|
||||
this.persistState();
|
||||
}, 1000);
|
||||
}
|
||||
async persistAllState() {
|
||||
if (this.saveTimeout) {
|
||||
clearTimeout(this.saveTimeout);
|
||||
}
|
||||
await this.persistState();
|
||||
}
|
||||
setupEventHandlers() {
|
||||
this.eventBus.on('ui:shutdown', async ()=>{
|
||||
await this.persistAllState();
|
||||
});
|
||||
this.eventBus.on('ui:preference:set', (data)=>{
|
||||
this.setPreference(data.key, data.value);
|
||||
});
|
||||
this.eventBus.on('ui:state:set', (data)=>{
|
||||
this.setState(data.key, data.value);
|
||||
});
|
||||
this.eventBus.on('tool:executed', (data)=>{
|
||||
this.setToolResult(data.tool, data.result);
|
||||
});
|
||||
}
|
||||
async shutdown() {
|
||||
if (this.autoSaveTimer) {
|
||||
clearInterval(this.autoSaveTimer);
|
||||
}
|
||||
if (this.saveTimeout) {
|
||||
clearTimeout(this.saveTimeout);
|
||||
}
|
||||
await this.persistAllState();
|
||||
this.eventBus.emit('state-manager:shutdown');
|
||||
}
|
||||
}
|
||||
export default StateManager;
|
||||
|
||||
//# sourceMappingURL=StateManager.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/web-ui/core/StateManager.js"],"sourcesContent":["/**\n * StateManager - Global state persistence and management\n * Handles UI state, user preferences, and data persistence\n */\n\nimport { EventBus } from './EventBus.js';\n\nexport class StateManager {\n constructor(eventBus) {\n this.eventBus = eventBus;\n this.state = new Map();\n this.preferences = new Map();\n this.toolResults = new Map();\n this.viewStates = new Map();\n this.sessionData = new Map();\n this.storageKey = 'claude-flow-ui-state';\n this.isInitialized = false;\n this.autoSaveInterval = 30000; // 30 seconds\n this.autoSaveTimer = null;\n }\n\n /**\n * Initialize state manager\n */\n async initialize() {\n try {\n // Load persisted state\n await this.loadPersistedState();\n\n // Setup auto-save\n this.setupAutoSave();\n\n // Setup event handlers\n this.setupEventHandlers();\n\n this.isInitialized = true;\n this.eventBus.emit('state-manager:initialized');\n\n console.log('💾 State Manager initialized');\n } catch (error) {\n console.error('❌ Failed to initialize State Manager:', error);\n throw error;\n }\n }\n\n /**\n * Load persisted state from storage\n */\n async loadPersistedState() {\n try {\n let persistedData = null;\n\n // Try to load from localStorage in browser\n if (typeof window !== 'undefined' && window.localStorage) {\n const stored = localStorage.getItem(this.storageKey);\n if (stored) {\n persistedData = JSON.parse(stored);\n }\n }\n\n // Try to load from file system in Node.js\n if (!persistedData && typeof process !== 'undefined') {\n try {\n const fs = await import('fs');\n const path = await import('path');\n const stateFile = path.join(process.cwd(), '.claude-flow-state.json');\n\n if (fs.existsSync(stateFile)) {\n const data = fs.readFileSync(stateFile, 'utf8');\n persistedData = JSON.parse(data);\n }\n } catch (error) {\n console.warn('Could not load state from file system:', error.message);\n }\n }\n\n if (persistedData) {\n this.restoreFromData(persistedData);\n console.log('💾 Loaded persisted state');\n } else {\n this.initializeDefaultState();\n }\n } catch (error) {\n console.warn('Could not load persisted state:', error);\n this.initializeDefaultState();\n }\n }\n\n /**\n * Restore state from persisted data\n */\n restoreFromData(data) {\n if (data.preferences) {\n this.preferences = new Map(Object.entries(data.preferences));\n }\n\n if (data.viewStates) {\n this.viewStates = new Map(Object.entries(data.viewStates));\n }\n\n if (data.toolResults) {\n this.toolResults = new Map(Object.entries(data.toolResults));\n }\n\n if (data.sessionData) {\n this.sessionData = new Map(Object.entries(data.sessionData));\n }\n\n if (data.state) {\n this.state = new Map(Object.entries(data.state));\n }\n }\n\n /**\n * Initialize default state\n */\n initializeDefaultState() {\n this.preferences.set('theme', 'dark');\n this.preferences.set('autoSave', true);\n this.preferences.set('showTooltips', true);\n this.preferences.set('animationSpeed', 'normal');\n this.preferences.set('defaultView', 'overview');\n this.preferences.set('keyboardShortcuts', true);\n this.preferences.set('realTimeUpdates', true);\n this.preferences.set('logLevel', 'info');\n\n this.state.set('initialized', true);\n this.state.set('version', '2.0.0');\n this.state.set('installDate', Date.now());\n\n console.log('💾 Initialized default state');\n }\n\n /**\n * Setup auto-save functionality\n */\n setupAutoSave() {\n if (!this.getPreference('autoSave', true)) {\n return;\n }\n\n this.autoSaveTimer = setInterval(() => {\n this.persistState();\n }, this.autoSaveInterval);\n }\n\n /**\n * Persist current state\n */\n async persistState() {\n try {\n const stateData = {\n timestamp: Date.now(),\n version: '2.0.0',\n preferences: Object.fromEntries(this.preferences),\n viewStates: Object.fromEntries(this.viewStates),\n toolResults: Object.fromEntries(this.toolResults),\n sessionData: Object.fromEntries(this.sessionData),\n state: Object.fromEntries(this.state),\n };\n\n // Save to localStorage in browser\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.setItem(this.storageKey, JSON.stringify(stateData));\n }\n\n // Save to file system in Node.js\n if (typeof process !== 'undefined') {\n try {\n const fs = await import('fs');\n const path = await import('path');\n const stateFile = path.join(processLine truncated
|
||||
@@ -1,419 +0,0 @@
|
||||
import { EventBus } from './EventBus.js';
|
||||
import { MCPIntegrationLayer } from './MCPIntegrationLayer.js';
|
||||
import { ViewManager } from './ViewManager.js';
|
||||
import { StateManager } from './StateManager.js';
|
||||
import { ComponentLibrary } from '../components/ComponentLibrary.js';
|
||||
export const VIEW_CATEGORIES = {
|
||||
OVERVIEW: 'overview',
|
||||
PROCESSES: 'processes',
|
||||
NEURAL: 'neural',
|
||||
MEMORY: 'memory',
|
||||
MONITORING: 'monitoring',
|
||||
WORKFLOW: 'workflow',
|
||||
GITHUB: 'github',
|
||||
DAA: 'daa',
|
||||
SYSTEM: 'system',
|
||||
CLI: 'cli',
|
||||
HELP: 'help'
|
||||
};
|
||||
export const MCP_TOOL_CATEGORIES = {
|
||||
NEURAL: [
|
||||
'neural_train',
|
||||
'neural_predict',
|
||||
'neural_status',
|
||||
'neural_patterns',
|
||||
'model_load',
|
||||
'model_save',
|
||||
'pattern_recognize',
|
||||
'cognitive_analyze',
|
||||
'learning_adapt',
|
||||
'neural_compress',
|
||||
'ensemble_create',
|
||||
'transfer_learn',
|
||||
'neural_explain',
|
||||
'wasm_optimize',
|
||||
'inference_run'
|
||||
],
|
||||
MEMORY: [
|
||||
'memory_usage',
|
||||
'memory_backup',
|
||||
'memory_restore',
|
||||
'memory_compress',
|
||||
'memory_sync',
|
||||
'cache_manage',
|
||||
'state_snapshot',
|
||||
'context_restore',
|
||||
'memory_analytics',
|
||||
'memory_persist',
|
||||
'memory_namespace'
|
||||
],
|
||||
MONITORING: [
|
||||
'performance_report',
|
||||
'bottleneck_analyze',
|
||||
'token_usage',
|
||||
'benchmark_run',
|
||||
'metrics_collect',
|
||||
'trend_analysis',
|
||||
'cost_analysis',
|
||||
'quality_assess',
|
||||
'error_analysis',
|
||||
'usage_stats',
|
||||
'health_check',
|
||||
'swarm_monitor',
|
||||
'agent_metrics'
|
||||
],
|
||||
WORKFLOW: [
|
||||
'workflow_create',
|
||||
'workflow_execute',
|
||||
'automation_setup',
|
||||
'pipeline_create',
|
||||
'scheduler_manage',
|
||||
'trigger_setup',
|
||||
'workflow_template',
|
||||
'batch_process',
|
||||
'parallel_execute',
|
||||
'sparc_mode',
|
||||
'task_orchestrate'
|
||||
],
|
||||
GITHUB: [
|
||||
'github_repo_analyze',
|
||||
'github_pr_manage',
|
||||
'github_issue_track',
|
||||
'github_release_coord',
|
||||
'github_workflow_auto',
|
||||
'github_code_review',
|
||||
'github_sync_coord',
|
||||
'github_metrics'
|
||||
],
|
||||
DAA: [
|
||||
'daa_agent_create',
|
||||
'daa_capability_match',
|
||||
'daa_resource_alloc',
|
||||
'daa_lifecycle_manage',
|
||||
'daa_communication',
|
||||
'daa_consensus',
|
||||
'daa_fault_tolerance',
|
||||
'daa_optimization'
|
||||
],
|
||||
SYSTEM: [
|
||||
'security_scan',
|
||||
'backup_create',
|
||||
'restore_system',
|
||||
'log_analysis',
|
||||
'diagnostic_run',
|
||||
'config_manage',
|
||||
'features_detect',
|
||||
'terminal_execute'
|
||||
]
|
||||
};
|
||||
export class UIManager {
|
||||
constructor(){
|
||||
this.eventBus = new EventBus();
|
||||
this.mcpIntegration = new MCPIntegrationLayer(this.eventBus);
|
||||
this.viewManager = new ViewManager(this.eventBus);
|
||||
this.stateManager = new StateManager(this.eventBus);
|
||||
this.componentLibrary = new ComponentLibrary();
|
||||
this.currentView = VIEW_CATEGORIES.OVERVIEW;
|
||||
this.viewHistory = [];
|
||||
this.shortcuts = new Map();
|
||||
this.theme = 'dark';
|
||||
this.isResponsive = true;
|
||||
this.initializeEventHandlers();
|
||||
this.setupKeyboardShortcuts();
|
||||
}
|
||||
async initialize() {
|
||||
try {
|
||||
await this.stateManager.initialize();
|
||||
await this.mcpIntegration.initialize();
|
||||
await this.viewManager.initialize();
|
||||
await this.loadUserPreferences();
|
||||
await this.registerAllViews();
|
||||
this.setupRealTimeUpdates();
|
||||
this.componentLibrary.initialize();
|
||||
this.eventBus.emit('ui:initialized');
|
||||
console.log('🎨 UI Manager initialized successfully');
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to initialize UI Manager:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async registerAllViews() {
|
||||
const viewConfigs = [
|
||||
{
|
||||
id: VIEW_CATEGORIES.OVERVIEW,
|
||||
name: 'Overview',
|
||||
icon: '🏠',
|
||||
description: 'System overview and quick actions',
|
||||
component: 'OverviewView',
|
||||
shortcut: '1'
|
||||
},
|
||||
{
|
||||
id: VIEW_CATEGORIES.PROCESSES,
|
||||
name: 'Processes',
|
||||
icon: '⚙️',
|
||||
description: 'Process management and monitoring',
|
||||
component: 'ProcessView',
|
||||
shortcut: '2'
|
||||
},
|
||||
{
|
||||
id: VIEW_CATEGORIES.NEURAL,
|
||||
name: 'Neural Network',
|
||||
icon: '🧠',
|
||||
description: 'AI model training and neural operations',
|
||||
component: 'NeuralNetworkView',
|
||||
shortcut: '3',
|
||||
toolCount: MCP_TOOL_CATEGORIES.NEURAL.length
|
||||
},
|
||||
{
|
||||
id: VIEW_CATEGORIES.MEMORY,
|
||||
name: 'Memory Bank',
|
||||
icon: '💾',
|
||||
description: 'Memory management and persistence',
|
||||
component: 'MemoryManagementView',
|
||||
shortcut: '4',
|
||||
toolCount: MCP_TOOL_CATEGORIES.MEMORY.length
|
||||
},
|
||||
{
|
||||
id: VIEW_CATEGORIES.MONITORING,
|
||||
name: 'Monitoring',
|
||||
icon: '📊',
|
||||
description: 'Performance monitoring and analysis',
|
||||
component: 'MonitoringView',
|
||||
shortcut: '5',
|
||||
toolCount: MCP_TOOL_CATEGORIES.MONITORING.length
|
||||
},
|
||||
{
|
||||
id: VIEW_CATEGORIES.WORKFLOW,
|
||||
name: 'Workflows',
|
||||
icon: '🔄',
|
||||
description: 'Automation and workflow management',
|
||||
component: 'WorkflowAutomationView',
|
||||
shortcut: '6',
|
||||
toolCount: MCP_TOOL_CATEGORIES.WORKFLOW.length
|
||||
},
|
||||
{
|
||||
id: VIEW_CATEGORIES.GITHUB,
|
||||
name: 'GitHub',
|
||||
icon: '🐙',
|
||||
description: 'GitHub integration and operations',
|
||||
component: 'GitHubIntegrationView',
|
||||
shortcut: '7',
|
||||
toolCount: MCP_TOOL_CATEGORIES.GITHUB.length
|
||||
},
|
||||
{
|
||||
id: VIEW_CATEGORIES.DAA,
|
||||
name: 'Dynamic Agents',
|
||||
icon: '🤖',
|
||||
description: 'Dynamic agent architecture',
|
||||
component: 'DAAView',
|
||||
shortcut: '8',
|
||||
toolCount: MCP_TOOL_CATEGORIES.DAA.length
|
||||
},
|
||||
{
|
||||
id: VIEW_CATEGORIES.SYSTEM,
|
||||
name: 'System',
|
||||
icon: '🛠️',
|
||||
description: 'System utilities and diagnostics',
|
||||
component: 'SystemUtilitiesView',
|
||||
shortcut: '9',
|
||||
toolCount: MCP_TOOL_CATEGORIES.SYSTEM.length
|
||||
},
|
||||
{
|
||||
id: VIEW_CATEGORIES.CLI,
|
||||
name: 'CLI Bridge',
|
||||
icon: '⌨️',
|
||||
description: 'Command-line interface bridge',
|
||||
component: 'CLICommandView',
|
||||
shortcut: '0'
|
||||
},
|
||||
{
|
||||
id: VIEW_CATEGORIES.HELP,
|
||||
name: 'Help',
|
||||
icon: '❓',
|
||||
description: 'Documentation and help',
|
||||
component: 'HelpView',
|
||||
shortcut: '?'
|
||||
}
|
||||
];
|
||||
for (const config of viewConfigs){
|
||||
await this.viewManager.registerView(config);
|
||||
}
|
||||
}
|
||||
async navigateToView(viewId, params = {}) {
|
||||
if (!this.viewManager.hasView(viewId)) {
|
||||
throw new Error(`View not found: ${viewId}`);
|
||||
}
|
||||
if (this.currentView && this.currentView !== viewId) {
|
||||
this.viewHistory.push({
|
||||
viewId: this.currentView,
|
||||
timestamp: Date.now(),
|
||||
params: this.stateManager.getViewState(this.currentView)
|
||||
});
|
||||
}
|
||||
this.currentView = viewId;
|
||||
await this.viewManager.loadView(viewId, params);
|
||||
if (typeof window !== 'undefined' && window.history) {
|
||||
window.history.pushState({
|
||||
viewId,
|
||||
params
|
||||
}, '', `#${viewId}`);
|
||||
}
|
||||
await this.stateManager.setViewState(viewId, params);
|
||||
this.eventBus.emit('ui:navigation', {
|
||||
viewId,
|
||||
params
|
||||
});
|
||||
}
|
||||
async goBack() {
|
||||
if (this.viewHistory.length === 0) return;
|
||||
const previousView = this.viewHistory.pop();
|
||||
await this.navigateToView(previousView.viewId, previousView.params);
|
||||
}
|
||||
async executeMCPTool(toolName, params = {}) {
|
||||
try {
|
||||
this.eventBus.emit('ui:loading', {
|
||||
tool: toolName,
|
||||
params
|
||||
});
|
||||
const result = await this.mcpIntegration.executeTool(toolName, params);
|
||||
await this.handleToolResult(toolName, result, params);
|
||||
this.eventBus.emit('ui:loading:complete', {
|
||||
tool: toolName,
|
||||
result
|
||||
});
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.eventBus.emit('ui:error', {
|
||||
tool: toolName,
|
||||
error,
|
||||
params
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async handleToolResult(toolName, result, originalParams) {
|
||||
const category = this.getToolCategory(toolName);
|
||||
if (category) {
|
||||
this.eventBus.emit(`view:${category}:update`, {
|
||||
tool: toolName,
|
||||
result,
|
||||
params: originalParams
|
||||
});
|
||||
}
|
||||
await this.stateManager.setToolResult(toolName, result);
|
||||
this.eventBus.emit('ui:log', {
|
||||
level: 'info',
|
||||
message: `Executed ${toolName}`,
|
||||
data: {
|
||||
result,
|
||||
params: originalParams
|
||||
}
|
||||
});
|
||||
}
|
||||
getToolCategory(toolName) {
|
||||
for (const [category, tools] of Object.entries(MCP_TOOL_CATEGORIES)){
|
||||
if (tools.includes(toolName)) {
|
||||
return category.toLowerCase();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
setupKeyboardShortcuts() {
|
||||
Object.values(VIEW_CATEGORIES).forEach((viewId, index)=>{
|
||||
const key = (index + 1).toString();
|
||||
this.shortcuts.set(key, ()=>this.navigateToView(viewId));
|
||||
});
|
||||
this.shortcuts.set('ctrl+k', ()=>this.showCommandPalette());
|
||||
this.shortcuts.set('ctrl+/', ()=>this.navigateToView(VIEW_CATEGORIES.HELP));
|
||||
this.shortcuts.set('ctrl+1', ()=>this.navigateToView(VIEW_CATEGORIES.OVERVIEW));
|
||||
this.shortcuts.set('escape', ()=>this.hideAllOverlays());
|
||||
this.shortcuts.set('ctrl+shift+p', ()=>this.showCommandPalette());
|
||||
this.shortcuts.set('ctrl+b', ()=>this.goBack());
|
||||
this.shortcuts.set('ctrl+r', ()=>this.refreshCurrentView());
|
||||
this.shortcuts.set('ctrl+t', ()=>this.toggleTheme());
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('keydown', (event)=>{
|
||||
const key = this.getKeyString(event);
|
||||
const handler = this.shortcuts.get(key);
|
||||
if (handler) {
|
||||
event.preventDefault();
|
||||
handler();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
getKeyString(event) {
|
||||
const parts = [];
|
||||
if (event.ctrlKey) parts.push('ctrl');
|
||||
if (event.shiftKey) parts.push('shift');
|
||||
if (event.altKey) parts.push('alt');
|
||||
if (event.metaKey) parts.push('meta');
|
||||
if (event.key.length === 1) {
|
||||
parts.push(event.key.toLowerCase());
|
||||
} else {
|
||||
parts.push(event.key.toLowerCase());
|
||||
}
|
||||
return parts.join('+');
|
||||
}
|
||||
showCommandPalette() {
|
||||
this.eventBus.emit('ui:command-palette:show');
|
||||
}
|
||||
hideAllOverlays() {
|
||||
this.eventBus.emit('ui:overlays:hide');
|
||||
}
|
||||
async refreshCurrentView() {
|
||||
await this.viewManager.refreshView(this.currentView);
|
||||
}
|
||||
toggleTheme() {
|
||||
this.theme = this.theme === 'dark' ? 'light' : 'dark';
|
||||
this.eventBus.emit('ui:theme:changed', this.theme);
|
||||
}
|
||||
setupRealTimeUpdates() {
|
||||
setInterval(()=>{
|
||||
this.eventBus.emit('ui:real-time:update');
|
||||
}, 5000);
|
||||
this.mcpIntegration.on('tool:result', (result)=>{
|
||||
this.eventBus.emit('ui:real-time:tool-result', result);
|
||||
});
|
||||
}
|
||||
initializeEventHandlers() {
|
||||
this.eventBus.on('tool:execute', async (data)=>{
|
||||
await this.executeMCPTool(data.tool, data.params);
|
||||
});
|
||||
this.eventBus.on('view:navigate', async (data)=>{
|
||||
await this.navigateToView(data.viewId, data.params);
|
||||
});
|
||||
this.eventBus.on('state:persist', async (data)=>{
|
||||
await this.stateManager.persistState(data);
|
||||
});
|
||||
this.eventBus.on('ui:error', (error)=>{
|
||||
console.error('UI Error:', error);
|
||||
});
|
||||
}
|
||||
async loadUserPreferences() {
|
||||
const preferences = await this.stateManager.getUserPreferences();
|
||||
if (preferences) {
|
||||
this.theme = preferences.theme || 'dark';
|
||||
this.isResponsive = preferences.responsive !== false;
|
||||
}
|
||||
}
|
||||
async getSystemStatus() {
|
||||
const status = {
|
||||
uptime: await this.mcpIntegration.getSystemUptime(),
|
||||
activeTools: await this.mcpIntegration.getActiveTools(),
|
||||
memoryUsage: await this.mcpIntegration.getMemoryUsage(),
|
||||
swarmStatus: await this.mcpIntegration.getSwarmStatus(),
|
||||
toolsAvailable: Object.values(MCP_TOOL_CATEGORIES).flat().length,
|
||||
viewsRegistered: this.viewManager.getViewCount()
|
||||
};
|
||||
return status;
|
||||
}
|
||||
async shutdown() {
|
||||
await this.stateManager.persistAllState();
|
||||
await this.mcpIntegration.shutdown();
|
||||
this.eventBus.emit('ui:shutdown');
|
||||
}
|
||||
}
|
||||
export default UIManager;
|
||||
|
||||
//# sourceMappingURL=UIManager.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/web-ui/core/UIManager.js"],"sourcesContent":["/**\n * UIManager - Central UI Controller for Claude Flow Web UI\n * Coordinates all views, handles navigation, and manages global state\n */\n\nimport { EventBus } from './EventBus.js';\nimport { MCPIntegrationLayer } from './MCPIntegrationLayer.js';\nimport { ViewManager } from './ViewManager.js';\nimport { StateManager } from './StateManager.js';\nimport { ComponentLibrary } from '../components/ComponentLibrary.js';\n\n// View category definitions\nexport const VIEW_CATEGORIES = {\n OVERVIEW: 'overview',\n PROCESSES: 'processes',\n NEURAL: 'neural',\n MEMORY: 'memory',\n MONITORING: 'monitoring',\n WORKFLOW: 'workflow',\n GITHUB: 'github',\n DAA: 'daa',\n SYSTEM: 'system',\n CLI: 'cli',\n HELP: 'help',\n};\n\n// MCP Tool Categories mapping\nexport const MCP_TOOL_CATEGORIES = {\n NEURAL: [\n 'neural_train',\n 'neural_predict',\n 'neural_status',\n 'neural_patterns',\n 'model_load',\n 'model_save',\n 'pattern_recognize',\n 'cognitive_analyze',\n 'learning_adapt',\n 'neural_compress',\n 'ensemble_create',\n 'transfer_learn',\n 'neural_explain',\n 'wasm_optimize',\n 'inference_run',\n ],\n MEMORY: [\n 'memory_usage',\n 'memory_backup',\n 'memory_restore',\n 'memory_compress',\n 'memory_sync',\n 'cache_manage',\n 'state_snapshot',\n 'context_restore',\n 'memory_analytics',\n 'memory_persist',\n 'memory_namespace',\n ],\n MONITORING: [\n 'performance_report',\n 'bottleneck_analyze',\n 'token_usage',\n 'benchmark_run',\n 'metrics_collect',\n 'trend_analysis',\n 'cost_analysis',\n 'quality_assess',\n 'error_analysis',\n 'usage_stats',\n 'health_check',\n 'swarm_monitor',\n 'agent_metrics',\n ],\n WORKFLOW: [\n 'workflow_create',\n 'workflow_execute',\n 'automation_setup',\n 'pipeline_create',\n 'scheduler_manage',\n 'trigger_setup',\n 'workflow_template',\n 'batch_process',\n 'parallel_execute',\n 'sparc_mode',\n 'task_orchestrate',\n ],\n GITHUB: [\n 'github_repo_analyze',\n 'github_pr_manage',\n 'github_issue_track',\n 'github_release_coord',\n 'github_workflow_auto',\n 'github_code_review',\n 'github_sync_coord',\n 'github_metrics',\n ],\n DAA: [\n 'daa_agent_create',\n 'daa_capability_match',\n 'daa_resource_alloc',\n 'daa_lifecycle_manage',\n 'daa_communication',\n 'daa_consensus',\n 'daa_fault_tolerance',\n 'daa_optimization',\n ],\n SYSTEM: [\n 'security_scan',\n 'backup_create',\n 'restore_system',\n 'log_analysis',\n 'diagnostic_run',\n 'config_manage',\n 'features_detect',\n 'terminal_execute',\n ],\n};\n\nexport class UIManager {\n constructor() {\n this.eventBus = new EventBus();\n this.mcpIntegration = new MCPIntegrationLayer(this.eventBus);\n this.viewManager = new ViewManager(this.eventBus);\n this.stateManager = new StateManager(this.eventBus);\n this.componentLibrary = new ComponentLibrary();\n\n this.currentView = VIEW_CATEGORIES.OVERVIEW;\n this.viewHistory = [];\n this.shortcuts = new Map();\n this.theme = 'dark';\n this.isResponsive = true;\n\n this.initializeEventHandlers();\n this.setupKeyboardShortcuts();\n }\n\n /**\n * Initialize the complete UI system\n */\n async initialize() {\n try {\n // Initialize core systems\n await this.stateManager.initialize();\n await this.mcpIntegration.initialize();\n await this.viewManager.initialize();\n\n // Load user preferences\n await this.loadUserPreferences();\n\n // Register all views\n await this.registerAllViews();\n\n // Set up real-time updates\n this.setupRealTimeUpdates();\n\n // Initialize component library\n this.componentLibrary.initialize();\n\n this.eventBus.emit('ui:initialized');\n console.log('🎨 UI Manager initialized successfully');\n } catch (error) {\n console.error('❌ Failed to initialize UI Manager:', error);\n throw error;\n }\n }\n\n /**\n * Register all available views\n */\n async registerAllViews() {\n const viewConfigs = [\n {\n id: VIEW_CATEGORIES.OVERVIEW,\n name: 'Overview',\n icon: '🏠',\n description: 'System overview and quick actions',\n component: 'OverviewView',\n shortcut: '1',\n },\n {\n id: VIEW_CATEGORIES.PROCESSES,\n name: 'Processes',\n icon: '⚙️',\n description: 'Process management and monitoring',\n component: 'ProcessView',\n shortcut: '2',\n },\n {\n id: VIEW_CATEGORIES.NEURAL,\n name: 'Neural Network',\n icon: '🧠',\n description: 'AI model training and neural operations',\n component: 'NeuralNetworkView',\n shortcut: '3',\n toolCount: MCP_TOOL_CATEGORIES.NEURALine truncated
|
||||
@@ -1,449 +0,0 @@
|
||||
export class ViewManager {
|
||||
constructor(eventBus){
|
||||
this.eventBus = eventBus;
|
||||
this.registeredViews = new Map();
|
||||
this.loadedViews = new Map();
|
||||
this.currentView = null;
|
||||
this.viewStack = [];
|
||||
this.viewStates = new Map();
|
||||
this.isInitialized = false;
|
||||
this.containerElement = null;
|
||||
this.transitionDuration = 300;
|
||||
}
|
||||
async initialize() {
|
||||
try {
|
||||
if (typeof document !== 'undefined') {
|
||||
this.setupDOMContainer();
|
||||
}
|
||||
this.setupEventHandlers();
|
||||
this.isInitialized = true;
|
||||
this.eventBus.emit('view-manager:initialized');
|
||||
console.log('🖼️ View Manager initialized');
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to initialize View Manager:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
setupDOMContainer() {
|
||||
this.containerElement = document.getElementById('claude-flow-ui') || document.createElement('div');
|
||||
if (!this.containerElement.id) {
|
||||
this.containerElement.id = 'claude-flow-ui';
|
||||
this.containerElement.className = 'claude-flow-main-container';
|
||||
document.body.appendChild(this.containerElement);
|
||||
}
|
||||
this.addTransitionStyles();
|
||||
}
|
||||
addTransitionStyles() {
|
||||
if (document.getElementById('claude-flow-styles')) return;
|
||||
const styles = document.createElement('style');
|
||||
styles.id = 'claude-flow-styles';
|
||||
styles.textContent = `
|
||||
.claude-flow-main-container {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
background: #1a1a1a;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.claude-flow-view {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
transition: all ${this.transitionDuration}ms ease-in-out;
|
||||
overflow-y: auto;
|
||||
padding: 20px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.claude-flow-view.entering {
|
||||
opacity: 0;
|
||||
transform: translateX(50px);
|
||||
}
|
||||
|
||||
.claude-flow-view.exiting {
|
||||
opacity: 0;
|
||||
transform: translateX(-50px);
|
||||
}
|
||||
|
||||
.claude-flow-view.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.claude-flow-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 20px;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 1px solid #333;
|
||||
}
|
||||
|
||||
.claude-flow-title {
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
color: #00d4ff;
|
||||
}
|
||||
|
||||
.claude-flow-breadcrumb {
|
||||
font-size: 14px;
|
||||
color: #888;
|
||||
}
|
||||
|
||||
.claude-flow-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.claude-flow-loading {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 200px;
|
||||
font-size: 18px;
|
||||
color: #888;
|
||||
}
|
||||
|
||||
.claude-flow-error {
|
||||
background: #ff4444;
|
||||
color: white;
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
/* Responsive design */
|
||||
@media (max-width: 768px) {
|
||||
.claude-flow-main-container {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.claude-flow-view {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.claude-flow-title {
|
||||
font-size: 20px;
|
||||
}
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(styles);
|
||||
}
|
||||
async registerView(viewConfig) {
|
||||
if (!viewConfig.id || !viewConfig.component) {
|
||||
throw new Error('View config must have id and component');
|
||||
}
|
||||
const config = {
|
||||
id: viewConfig.id,
|
||||
name: viewConfig.name || viewConfig.id,
|
||||
icon: viewConfig.icon || '📄',
|
||||
description: viewConfig.description || '',
|
||||
component: viewConfig.component,
|
||||
shortcut: viewConfig.shortcut,
|
||||
toolCount: viewConfig.toolCount || 0,
|
||||
lazy: viewConfig.lazy !== false,
|
||||
preload: viewConfig.preload || false,
|
||||
permissions: viewConfig.permissions || [],
|
||||
dependencies: viewConfig.dependencies || [],
|
||||
metadata: viewConfig.metadata || {}
|
||||
};
|
||||
this.registeredViews.set(viewConfig.id, config);
|
||||
if (config.preload) {
|
||||
await this.preloadView(config.id);
|
||||
}
|
||||
this.eventBus.emit('view:registered', {
|
||||
viewId: config.id,
|
||||
config
|
||||
});
|
||||
console.log(`🖼️ Registered view: ${config.name} (${config.id})`);
|
||||
}
|
||||
async loadView(viewId, params = {}) {
|
||||
if (!this.isInitialized) {
|
||||
throw new Error('ViewManager not initialized');
|
||||
}
|
||||
const viewConfig = this.registeredViews.get(viewId);
|
||||
if (!viewConfig) {
|
||||
throw new Error(`View not registered: ${viewId}`);
|
||||
}
|
||||
try {
|
||||
this.eventBus.emit('view:loading', {
|
||||
viewId,
|
||||
params
|
||||
});
|
||||
await this.checkDependencies(viewConfig);
|
||||
if (!this.loadedViews.has(viewId)) {
|
||||
await this.loadViewComponent(viewId, viewConfig);
|
||||
}
|
||||
if (this.currentView && this.currentView !== viewId) {
|
||||
await this.hideCurrentView();
|
||||
}
|
||||
await this.showView(viewId, params);
|
||||
this.currentView = viewId;
|
||||
this.viewStates.set(viewId, {
|
||||
params,
|
||||
loadTime: Date.now(),
|
||||
lastAccess: Date.now()
|
||||
});
|
||||
this.eventBus.emit('view:loaded', {
|
||||
viewId,
|
||||
params
|
||||
});
|
||||
console.log(`🖼️ Loaded view: ${viewConfig.name}`);
|
||||
} catch (error) {
|
||||
this.eventBus.emit('view:error', {
|
||||
viewId,
|
||||
error: error.message,
|
||||
params
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async loadViewComponent(viewId, viewConfig) {
|
||||
try {
|
||||
let ViewComponent;
|
||||
if (typeof document !== 'undefined') {
|
||||
ViewComponent = await this.createDOMView(viewId, viewConfig);
|
||||
} else {
|
||||
ViewComponent = await this.createTerminalView(viewId, viewConfig);
|
||||
}
|
||||
this.loadedViews.set(viewId, {
|
||||
component: ViewComponent,
|
||||
config: viewConfig,
|
||||
element: ViewComponent.element || null,
|
||||
instance: ViewComponent.instance || null,
|
||||
loadTime: Date.now()
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`❌ Failed to load view component ${viewId}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async createDOMView(viewId, viewConfig) {
|
||||
const element = document.createElement('div');
|
||||
element.className = 'claude-flow-view hidden';
|
||||
element.id = `view-${viewId}`;
|
||||
const header = document.createElement('div');
|
||||
header.className = 'claude-flow-header';
|
||||
const titleSection = document.createElement('div');
|
||||
const title = document.createElement('h1');
|
||||
title.className = 'claude-flow-title';
|
||||
title.textContent = `${viewConfig.icon} ${viewConfig.name}`;
|
||||
const breadcrumb = document.createElement('div');
|
||||
breadcrumb.className = 'claude-flow-breadcrumb';
|
||||
breadcrumb.textContent = viewConfig.description;
|
||||
titleSection.appendChild(title);
|
||||
titleSection.appendChild(breadcrumb);
|
||||
header.appendChild(titleSection);
|
||||
const content = document.createElement('div');
|
||||
content.className = 'claude-flow-content';
|
||||
content.id = `content-${viewId}`;
|
||||
element.appendChild(header);
|
||||
element.appendChild(content);
|
||||
this.containerElement.appendChild(element);
|
||||
let instance;
|
||||
try {
|
||||
const module = await this.importViewComponent(viewConfig.component);
|
||||
instance = new module.default(content, this.eventBus, viewConfig);
|
||||
} catch (error) {
|
||||
instance = this.createBasicView(content, viewConfig);
|
||||
}
|
||||
return {
|
||||
element,
|
||||
instance,
|
||||
render: (params)=>instance.render(params),
|
||||
destroy: ()=>instance.destroy?.()
|
||||
};
|
||||
}
|
||||
async createTerminalView(viewId, viewConfig) {
|
||||
let instance;
|
||||
try {
|
||||
const module = await this.importViewComponent(viewConfig.component);
|
||||
instance = new module.default(null, this.eventBus, viewConfig);
|
||||
} catch (error) {
|
||||
instance = this.createBasicTerminalView(viewConfig);
|
||||
}
|
||||
return {
|
||||
element: null,
|
||||
instance,
|
||||
render: (params)=>instance.render(params),
|
||||
destroy: ()=>instance.destroy?.()
|
||||
};
|
||||
}
|
||||
async importViewComponent(componentName) {
|
||||
try {
|
||||
return await import(`../views/${componentName}.js`);
|
||||
} catch (error) {
|
||||
console.warn(`Could not import ${componentName}, using fallback`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
createBasicView(container, viewConfig) {
|
||||
return {
|
||||
render: (params)=>{
|
||||
container.innerHTML = `
|
||||
<div class="claude-flow-loading">
|
||||
<div>
|
||||
<h2>${viewConfig.name}</h2>
|
||||
<p>${viewConfig.description}</p>
|
||||
<p>This view is under development.</p>
|
||||
${viewConfig.toolCount ? `<p>Will support ${viewConfig.toolCount} tools.</p>` : ''}
|
||||
<pre>${JSON.stringify(params, null, 2)}</pre>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
},
|
||||
destroy: ()=>{
|
||||
container.innerHTML = '';
|
||||
}
|
||||
};
|
||||
}
|
||||
createBasicTerminalView(viewConfig) {
|
||||
return {
|
||||
render: (params)=>{
|
||||
console.log(`\n📄 ${viewConfig.name}`);
|
||||
console.log(` ${viewConfig.description}`);
|
||||
if (viewConfig.toolCount) {
|
||||
console.log(` Tools: ${viewConfig.toolCount}`);
|
||||
}
|
||||
console.log(` Params:`, params);
|
||||
console.log(` [This view is under development]\n`);
|
||||
},
|
||||
destroy: ()=>{}
|
||||
};
|
||||
}
|
||||
async showView(viewId, params) {
|
||||
const loadedView = this.loadedViews.get(viewId);
|
||||
if (!loadedView) {
|
||||
throw new Error(`View not loaded: ${viewId}`);
|
||||
}
|
||||
await loadedView.component.render(params);
|
||||
if (loadedView.element) {
|
||||
loadedView.element.classList.remove('hidden');
|
||||
loadedView.element.classList.add('entering');
|
||||
setTimeout(()=>{
|
||||
if (loadedView.element) {
|
||||
loadedView.element.classList.remove('entering');
|
||||
}
|
||||
}, this.transitionDuration);
|
||||
}
|
||||
this.eventBus.emit('view:shown', {
|
||||
viewId,
|
||||
params
|
||||
});
|
||||
}
|
||||
async hideCurrentView() {
|
||||
if (!this.currentView) return;
|
||||
const loadedView = this.loadedViews.get(this.currentView);
|
||||
if (loadedView?.element) {
|
||||
loadedView.element.classList.add('exiting');
|
||||
setTimeout(()=>{
|
||||
if (loadedView.element) {
|
||||
loadedView.element.classList.remove('exiting');
|
||||
loadedView.element.classList.add('hidden');
|
||||
}
|
||||
}, this.transitionDuration);
|
||||
}
|
||||
this.eventBus.emit('view:hidden', {
|
||||
viewId: this.currentView
|
||||
});
|
||||
}
|
||||
async refreshView(viewId) {
|
||||
const viewState = this.viewStates.get(viewId);
|
||||
if (viewState) {
|
||||
await this.loadView(viewId, viewState.params);
|
||||
}
|
||||
}
|
||||
async preloadView(viewId) {
|
||||
const viewConfig = this.registeredViews.get(viewId);
|
||||
if (!viewConfig || this.loadedViews.has(viewId)) {
|
||||
return;
|
||||
}
|
||||
await this.loadViewComponent(viewId, viewConfig);
|
||||
console.log(`🔄 Preloaded view: ${viewConfig.name}`);
|
||||
}
|
||||
async checkDependencies(viewConfig) {
|
||||
if (!viewConfig.dependencies || viewConfig.dependencies.length === 0) {
|
||||
return;
|
||||
}
|
||||
for (const dependency of viewConfig.dependencies){
|
||||
if (!this.loadedViews.has(dependency)) {
|
||||
await this.preloadView(dependency);
|
||||
}
|
||||
}
|
||||
}
|
||||
async unloadView(viewId) {
|
||||
const loadedView = this.loadedViews.get(viewId);
|
||||
if (!loadedView) return;
|
||||
if (loadedView.component.destroy) {
|
||||
await loadedView.component.destroy();
|
||||
}
|
||||
if (loadedView.element) {
|
||||
loadedView.element.remove();
|
||||
}
|
||||
this.loadedViews.delete(viewId);
|
||||
this.viewStates.delete(viewId);
|
||||
this.eventBus.emit('view:unloaded', {
|
||||
viewId
|
||||
});
|
||||
console.log(`🗑️ Unloaded view: ${viewId}`);
|
||||
}
|
||||
getViewConfig(viewId) {
|
||||
return this.registeredViews.get(viewId);
|
||||
}
|
||||
getAllViews() {
|
||||
return Array.from(this.registeredViews.values());
|
||||
}
|
||||
getViewCount() {
|
||||
return this.registeredViews.size;
|
||||
}
|
||||
hasView(viewId) {
|
||||
return this.registeredViews.has(viewId);
|
||||
}
|
||||
getViewState(viewId) {
|
||||
return this.viewStates.get(viewId);
|
||||
}
|
||||
setViewState(viewId, state) {
|
||||
const existing = this.viewStates.get(viewId) || {};
|
||||
this.viewStates.set(viewId, {
|
||||
...existing,
|
||||
...state
|
||||
});
|
||||
}
|
||||
setupEventHandlers() {
|
||||
this.eventBus.on('view:reload', async (data)=>{
|
||||
await this.refreshView(data.viewId);
|
||||
});
|
||||
this.eventBus.on('view:unload', async (data)=>{
|
||||
await this.unloadView(data.viewId);
|
||||
});
|
||||
this.eventBus.on('view:preload', async (data)=>{
|
||||
await this.preloadView(data.viewId);
|
||||
});
|
||||
}
|
||||
getMemoryStats() {
|
||||
return {
|
||||
registeredViews: this.registeredViews.size,
|
||||
loadedViews: this.loadedViews.size,
|
||||
viewStates: this.viewStates.size,
|
||||
currentView: this.currentView
|
||||
};
|
||||
}
|
||||
async shutdown() {
|
||||
for (const viewId of this.loadedViews.keys()){
|
||||
await this.unloadView(viewId);
|
||||
}
|
||||
this.registeredViews.clear();
|
||||
this.viewStates.clear();
|
||||
this.currentView = null;
|
||||
this.eventBus.emit('view-manager:shutdown');
|
||||
}
|
||||
}
|
||||
export default ViewManager;
|
||||
|
||||
//# sourceMappingURL=ViewManager.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/web-ui/core/ViewManager.js"],"sourcesContent":["/**\n * ViewManager - Dynamic view loading and state management\n * Handles all UI views, transitions, and state persistence\n */\n\nimport { EventBus } from './EventBus.js';\n\nexport class ViewManager {\n constructor(eventBus) {\n this.eventBus = eventBus;\n this.registeredViews = new Map();\n this.loadedViews = new Map();\n this.currentView = null;\n this.viewStack = [];\n this.viewStates = new Map();\n this.isInitialized = false;\n this.containerElement = null;\n this.transitionDuration = 300;\n }\n\n /**\n * Initialize view manager\n */\n async initialize() {\n try {\n // Create main view container if in browser\n if (typeof document !== 'undefined') {\n this.setupDOMContainer();\n }\n\n // Setup event handlers\n this.setupEventHandlers();\n\n this.isInitialized = true;\n this.eventBus.emit('view-manager:initialized');\n\n console.log('🖼️ View Manager initialized');\n } catch (error) {\n console.error('❌ Failed to initialize View Manager:', error);\n throw error;\n }\n }\n\n /**\n * Setup DOM container for web environment\n */\n setupDOMContainer() {\n // Create main container\n this.containerElement =\n document.getElementById('claude-flow-ui') || document.createElement('div');\n\n if (!this.containerElement.id) {\n this.containerElement.id = 'claude-flow-ui';\n this.containerElement.className = 'claude-flow-main-container';\n document.body.appendChild(this.containerElement);\n }\n\n // Add CSS for transitions\n this.addTransitionStyles();\n }\n\n /**\n * Add CSS styles for view transitions\n */\n addTransitionStyles() {\n if (document.getElementById('claude-flow-styles')) return;\n\n const styles = document.createElement('style');\n styles.id = 'claude-flow-styles';\n styles.textContent = `\n .claude-flow-main-container {\n width: 100%;\n height: 100vh;\n overflow: hidden;\n position: relative;\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;\n background: #1a1a1a;\n color: #ffffff;\n }\n\n .claude-flow-view {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n opacity: 1;\n transform: translateX(0);\n transition: all ${this.transitionDuration}ms ease-in-out;\n overflow-y: auto;\n padding: 20px;\n box-sizing: border-box;\n }\n\n .claude-flow-view.entering {\n opacity: 0;\n transform: translateX(50px);\n }\n\n .claude-flow-view.exiting {\n opacity: 0;\n transform: translateX(-50px);\n }\n\n .claude-flow-view.hidden {\n display: none;\n }\n\n .claude-flow-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 20px;\n padding-bottom: 10px;\n border-bottom: 1px solid #333;\n }\n\n .claude-flow-title {\n font-size: 24px;\n font-weight: bold;\n color: #00d4ff;\n }\n\n .claude-flow-breadcrumb {\n font-size: 14px;\n color: #888;\n }\n\n .claude-flow-content {\n flex: 1;\n overflow-y: auto;\n }\n\n .claude-flow-loading {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 200px;\n font-size: 18px;\n color: #888;\n }\n\n .claude-flow-error {\n background: #ff4444;\n color: white;\n padding: 15px;\n border-radius: 5px;\n margin: 10px 0;\n }\n\n /* Responsive design */\n @media (max-width: 768px) {\n .claude-flow-main-container {\n padding: 10px;\n }\n \n .claude-flow-view {\n padding: 10px;\n }\n \n .claude-flow-title {\n font-size: 20px;\n }\n }\n `;\n\n document.head.appendChild(styles);\n }\n\n /**\n * Register a view configuration\n */\n async registerView(viewConfig) {\n if (!viewConfig.id || !viewConfig.component) {\n throw new Error('View config must have id and component');\n }\n\n const config = {\n id: viewConfig.id,\n name: viewConfig.name || viewConfig.id,\n icon: viewConfig.icon || '📄',\n description: viewConfig.description || '',\n component: viewConfig.component,\n shortcut: viewConfig.shortcut,\n toolCount: viewConfig.toolCount || 0,\n lazy: viewConfig.lazy !== false, // Default to lazy loading\n preload: viewConfig.preload || false,\n permissions: viewConfig.permissions || [],\n dependencies: viewConfig.dependencies || [],\n metadata: viewConfig.metadata || {},\n };\n\n this.registeredViews.set(viewConfig.idLine truncated
|
||||
@@ -1,242 +0,0 @@
|
||||
export { UIManager, VIEW_CATEGORIES, MCP_TOOL_CATEGORIES } from './core/UIManager.js';
|
||||
export { MCPIntegrationLayer } from './core/MCPIntegrationLayer.js';
|
||||
export { EventBus } from './core/EventBus.js';
|
||||
export { ViewManager } from './core/ViewManager.js';
|
||||
export { StateManager } from './core/StateManager.js';
|
||||
export { ComponentLibrary } from './components/ComponentLibrary.js';
|
||||
export { default as NeuralNetworkView } from './views/NeuralNetworkView.js';
|
||||
export { default as GitHubIntegrationView } from './views/GitHubIntegrationView.js';
|
||||
export { default as WorkflowAutomationView } from './views/WorkflowAutomationView.js';
|
||||
export { default as DAAView } from './views/DAAView.js';
|
||||
export { EnhancedWebUI } from './EnhancedWebUI.js';
|
||||
export { EnhancedProcessUI, launchEnhancedUI } from './EnhancedProcessUI.js';
|
||||
export async function initializeEnhancedUI(options = {}) {
|
||||
const { mode = 'auto', existingUI = null, enableAllFeatures = true } = options;
|
||||
try {
|
||||
if (mode === 'full' || mode === 'auto' && typeof window !== 'undefined') {
|
||||
const { UIManager } = await import('./core/UIManager.js');
|
||||
const uiManager = new UIManager();
|
||||
await uiManager.initialize();
|
||||
return uiManager;
|
||||
} else if (mode === 'enhanced' || mode === 'auto' && existingUI) {
|
||||
const { EnhancedWebUI } = await import('./EnhancedWebUI.js');
|
||||
const enhancedUI = new EnhancedWebUI();
|
||||
await enhancedUI.initialize(existingUI);
|
||||
return enhancedUI;
|
||||
} else {
|
||||
const { EnhancedProcessUI } = await import('./EnhancedProcessUI.js');
|
||||
const processUI = new EnhancedProcessUI();
|
||||
return processUI;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Enhanced UI initialization failed, using fallback:', error);
|
||||
const { EnhancedProcessUI } = await import('./EnhancedProcessUI.js');
|
||||
const processUI = new EnhancedProcessUI();
|
||||
return processUI;
|
||||
}
|
||||
}
|
||||
export async function launchTerminalUI() {
|
||||
const { launchEnhancedUI } = await import('./EnhancedProcessUI.js');
|
||||
return launchEnhancedUI();
|
||||
}
|
||||
export const TOOL_CATEGORIES_INFO = {
|
||||
neural: {
|
||||
name: 'Neural Network Tools',
|
||||
count: 15,
|
||||
tools: [
|
||||
'neural_train',
|
||||
'neural_predict',
|
||||
'neural_status',
|
||||
'neural_patterns',
|
||||
'model_load',
|
||||
'model_save',
|
||||
'pattern_recognize',
|
||||
'cognitive_analyze',
|
||||
'learning_adapt',
|
||||
'neural_compress',
|
||||
'ensemble_create',
|
||||
'transfer_learn',
|
||||
'neural_explain',
|
||||
'wasm_optimize',
|
||||
'inference_run'
|
||||
]
|
||||
},
|
||||
memory: {
|
||||
name: 'Memory & Persistence Tools',
|
||||
count: 10,
|
||||
tools: [
|
||||
'memory_usage',
|
||||
'memory_backup',
|
||||
'memory_restore',
|
||||
'memory_compress',
|
||||
'memory_sync',
|
||||
'cache_manage',
|
||||
'state_snapshot',
|
||||
'context_restore',
|
||||
'memory_analytics',
|
||||
'memory_persist'
|
||||
]
|
||||
},
|
||||
monitoring: {
|
||||
name: 'Monitoring & Analysis Tools',
|
||||
count: 13,
|
||||
tools: [
|
||||
'performance_report',
|
||||
'bottleneck_analyze',
|
||||
'token_usage',
|
||||
'benchmark_run',
|
||||
'metrics_collect',
|
||||
'trend_analysis',
|
||||
'cost_analysis',
|
||||
'quality_assess',
|
||||
'error_analysis',
|
||||
'usage_stats',
|
||||
'health_check',
|
||||
'swarm_monitor',
|
||||
'agent_metrics'
|
||||
]
|
||||
},
|
||||
workflow: {
|
||||
name: 'Workflow & Automation Tools',
|
||||
count: 11,
|
||||
tools: [
|
||||
'workflow_create',
|
||||
'workflow_execute',
|
||||
'automation_setup',
|
||||
'pipeline_create',
|
||||
'scheduler_manage',
|
||||
'trigger_setup',
|
||||
'workflow_template',
|
||||
'batch_process',
|
||||
'parallel_execute',
|
||||
'sparc_mode',
|
||||
'task_orchestrate'
|
||||
]
|
||||
},
|
||||
github: {
|
||||
name: 'GitHub Integration Tools',
|
||||
count: 8,
|
||||
tools: [
|
||||
'github_repo_analyze',
|
||||
'github_pr_manage',
|
||||
'github_issue_track',
|
||||
'github_release_coord',
|
||||
'github_workflow_auto',
|
||||
'github_code_review',
|
||||
'github_sync_coord',
|
||||
'github_metrics'
|
||||
]
|
||||
},
|
||||
daa: {
|
||||
name: 'Dynamic Agent Architecture Tools',
|
||||
count: 8,
|
||||
tools: [
|
||||
'daa_agent_create',
|
||||
'daa_capability_match',
|
||||
'daa_resource_alloc',
|
||||
'daa_lifecycle_manage',
|
||||
'daa_communication',
|
||||
'daa_consensus',
|
||||
'daa_fault_tolerance',
|
||||
'daa_optimization'
|
||||
]
|
||||
},
|
||||
system: {
|
||||
name: 'System & Utilities Tools',
|
||||
count: 6,
|
||||
tools: [
|
||||
'security_scan',
|
||||
'backup_create',
|
||||
'restore_system',
|
||||
'log_analysis',
|
||||
'diagnostic_run',
|
||||
'config_manage'
|
||||
]
|
||||
},
|
||||
cli: {
|
||||
name: 'CLI Command Bridge',
|
||||
count: 9,
|
||||
commands: [
|
||||
'hive-mind',
|
||||
'github',
|
||||
'training',
|
||||
'analysis',
|
||||
'automation',
|
||||
'coordination',
|
||||
'hooks',
|
||||
'mcp',
|
||||
'config'
|
||||
]
|
||||
}
|
||||
};
|
||||
export function getTotalToolCount() {
|
||||
return Object.values(TOOL_CATEGORIES_INFO).reduce((total, category)=>{
|
||||
return total + category.count;
|
||||
}, 0);
|
||||
}
|
||||
export function getArchitectureInfo() {
|
||||
return {
|
||||
version: '2.0.0',
|
||||
totalTools: getTotalToolCount(),
|
||||
categories: Object.keys(TOOL_CATEGORIES_INFO).length,
|
||||
features: [
|
||||
'Modular view system',
|
||||
'MCP tool integration',
|
||||
'Real-time updates',
|
||||
'State persistence',
|
||||
'Event-driven architecture',
|
||||
'Component library',
|
||||
'Responsive design',
|
||||
'Fallback modes',
|
||||
'Tool statistics',
|
||||
'Cross-platform support'
|
||||
],
|
||||
compatibility: {
|
||||
browser: true,
|
||||
node: true,
|
||||
terminal: true,
|
||||
vscode: true
|
||||
}
|
||||
};
|
||||
}
|
||||
if (typeof window !== 'undefined') {
|
||||
window.claudeFlowEnhancedUI = {
|
||||
initialize: initializeEnhancedUI,
|
||||
launch: launchTerminalUI,
|
||||
getInfo: getArchitectureInfo,
|
||||
toolCategories: TOOL_CATEGORIES_INFO
|
||||
};
|
||||
window.addEventListener('DOMContentLoaded', async ()=>{
|
||||
if (window.claudeFlowProcessUI && !window.claudeFlowEnhanced) {
|
||||
try {
|
||||
console.log('🎨 Auto-enhancing existing process UI...');
|
||||
const enhancedUI = await initializeEnhancedUI({
|
||||
mode: 'enhanced',
|
||||
existingUI: window.claudeFlowProcessUI
|
||||
});
|
||||
window.claudeFlowEnhanced = enhancedUI;
|
||||
console.log('✅ Enhanced UI auto-initialization complete');
|
||||
} catch (error) {
|
||||
console.warn('Enhanced UI auto-initialization failed:', error);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = {
|
||||
initializeEnhancedUI,
|
||||
launchTerminalUI,
|
||||
getArchitectureInfo,
|
||||
TOOL_CATEGORIES_INFO,
|
||||
getTotalToolCount
|
||||
};
|
||||
}
|
||||
export default {
|
||||
initializeEnhancedUI,
|
||||
launchTerminalUI,
|
||||
getArchitectureInfo,
|
||||
TOOL_CATEGORIES_INFO,
|
||||
getTotalToolCount
|
||||
};
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../src/ui/web-ui/index.js"],"sourcesContent":["/**\n * Enhanced Web UI - Main Entry Point\n * Modular UI architecture supporting 71+ MCP tools and CLI commands\n */\n\n// Core Architecture Components\nexport { UIManager, VIEW_CATEGORIES, MCP_TOOL_CATEGORIES } from './core/UIManager.js';\nexport { MCPIntegrationLayer } from './core/MCPIntegrationLayer.js';\nexport { EventBus } from './core/EventBus.js';\nexport { ViewManager } from './core/ViewManager.js';\nexport { StateManager } from './core/StateManager.js';\n\n// Component Library\nexport { ComponentLibrary } from './components/ComponentLibrary.js';\n\n// Views\nexport { default as NeuralNetworkView } from './views/NeuralNetworkView.js';\nexport { default as GitHubIntegrationView } from './views/GitHubIntegrationView.js';\nexport { default as WorkflowAutomationView } from './views/WorkflowAutomationView.js';\nexport { default as DAAView } from './views/DAAView.js';\n\n// Main UI Controllers\nexport { EnhancedWebUI } from './EnhancedWebUI.js';\nexport { EnhancedProcessUI, launchEnhancedUI } from './EnhancedProcessUI.js';\n\n/**\n * Initialize Enhanced Web UI System\n * @param {Object} options Configuration options\n * @returns {Promise<EnhancedWebUI>} Initialized UI system\n */\nexport async function initializeEnhancedUI(options = {}) {\n const {\n mode = 'auto', // 'full', 'enhanced', 'fallback', 'auto'\n existingUI = null,\n enableAllFeatures = true,\n } = options;\n\n try {\n if (mode === 'full' || (mode === 'auto' && typeof window !== 'undefined')) {\n // Browser environment - full UI manager\n const { UIManager } = await import('./core/UIManager.js');\n const uiManager = new UIManager();\n await uiManager.initialize();\n return uiManager;\n } else if (mode === 'enhanced' || (mode === 'auto' && existingUI)) {\n // Enhanced process UI\n const { EnhancedWebUI } = await import('./EnhancedWebUI.js');\n const enhancedUI = new EnhancedWebUI();\n await enhancedUI.initialize(existingUI);\n return enhancedUI;\n } else {\n // Terminal/fallback mode\n const { EnhancedProcessUI } = await import('./EnhancedProcessUI.js');\n const processUI = new EnhancedProcessUI();\n return processUI;\n }\n } catch (error) {\n console.warn('Enhanced UI initialization failed, using fallback:', error);\n\n // Always provide fallback\n const { EnhancedProcessUI } = await import('./EnhancedProcessUI.js');\n const processUI = new EnhancedProcessUI();\n return processUI;\n }\n}\n\n/**\n * Launch Enhanced UI in terminal mode\n */\nexport async function launchTerminalUI() {\n const { launchEnhancedUI } = await import('./EnhancedProcessUI.js');\n return launchEnhancedUI();\n}\n\n/**\n * Tool Categories and Counts\n */\nexport const TOOL_CATEGORIES_INFO = {\n neural: {\n name: 'Neural Network Tools',\n count: 15,\n tools: [\n 'neural_train',\n 'neural_predict',\n 'neural_status',\n 'neural_patterns',\n 'model_load',\n 'model_save',\n 'pattern_recognize',\n 'cognitive_analyze',\n 'learning_adapt',\n 'neural_compress',\n 'ensemble_create',\n 'transfer_learn',\n 'neural_explain',\n 'wasm_optimize',\n 'inference_run',\n ],\n },\n memory: {\n name: 'Memory & Persistence Tools',\n count: 10,\n tools: [\n 'memory_usage',\n 'memory_backup',\n 'memory_restore',\n 'memory_compress',\n 'memory_sync',\n 'cache_manage',\n 'state_snapshot',\n 'context_restore',\n 'memory_analytics',\n 'memory_persist',\n ],\n },\n monitoring: {\n name: 'Monitoring & Analysis Tools',\n count: 13,\n tools: [\n 'performance_report',\n 'bottleneck_analyze',\n 'token_usage',\n 'benchmark_run',\n 'metrics_collect',\n 'trend_analysis',\n 'cost_analysis',\n 'quality_assess',\n 'error_analysis',\n 'usage_stats',\n 'health_check',\n 'swarm_monitor',\n 'agent_metrics',\n ],\n },\n workflow: {\n name: 'Workflow & Automation Tools',\n count: 11,\n tools: [\n 'workflow_create',\n 'workflow_execute',\n 'automation_setup',\n 'pipeline_create',\n 'scheduler_manage',\n 'trigger_setup',\n 'workflow_template',\n 'batch_process',\n 'parallel_execute',\n 'sparc_mode',\n 'task_orchestrate',\n ],\n },\n github: {\n name: 'GitHub Integration Tools',\n count: 8,\n tools: [\n 'github_repo_analyze',\n 'github_pr_manage',\n 'github_issue_track',\n 'github_release_coord',\n 'github_workflow_auto',\n 'github_code_review',\n 'github_sync_coord',\n 'github_metrics',\n ],\n },\n daa: {\n name: 'Dynamic Agent Architecture Tools',\n count: 8,\n tools: [\n 'daa_agent_create',\n 'daa_capability_match',\n 'daa_resource_alloc',\n 'daa_lLine truncated
|
||||
@@ -1,326 +0,0 @@
|
||||
export class NeuralPanelTest {
|
||||
constructor(){
|
||||
this.testResults = {
|
||||
panelOpen: false,
|
||||
tabs: {
|
||||
tools: {
|
||||
found: false,
|
||||
clicked: false,
|
||||
content: false
|
||||
},
|
||||
training: {
|
||||
found: false,
|
||||
clicked: false,
|
||||
content: false
|
||||
},
|
||||
models: {
|
||||
found: false,
|
||||
clicked: false,
|
||||
content: false
|
||||
},
|
||||
patterns: {
|
||||
found: false,
|
||||
clicked: false,
|
||||
content: false
|
||||
},
|
||||
performance: {
|
||||
found: false,
|
||||
clicked: false,
|
||||
content: false
|
||||
}
|
||||
},
|
||||
tools: {
|
||||
total: 0,
|
||||
categories: [],
|
||||
executeButtons: 0,
|
||||
configureButtons: 0,
|
||||
tested: []
|
||||
},
|
||||
controls: {
|
||||
refresh: false,
|
||||
export: false,
|
||||
close: false
|
||||
},
|
||||
animations: {
|
||||
smooth: false,
|
||||
transitions: false
|
||||
},
|
||||
responsiveness: {
|
||||
tested: false,
|
||||
mobile: false,
|
||||
tablet: false,
|
||||
desktop: false
|
||||
}
|
||||
};
|
||||
}
|
||||
async runTests() {
|
||||
console.log('🧪 Starting Neural Networks Panel Test Suite');
|
||||
await this.testOpenPanel();
|
||||
await this.testAllTabs();
|
||||
await this.testToolsTab();
|
||||
await this.testPanelControls();
|
||||
await this.testAnimations();
|
||||
await this.testResponsiveness();
|
||||
return this.generateReport();
|
||||
}
|
||||
async testOpenPanel() {
|
||||
console.log('📋 Test 1: Opening Neural Panel');
|
||||
const neuralButton = this.findNeuralButton();
|
||||
if (neuralButton) {
|
||||
console.log('✅ Found Neural button');
|
||||
neuralButton.click();
|
||||
await this.wait(500);
|
||||
const panel = this.findNeuralPanel();
|
||||
if (panel) {
|
||||
this.testResults.panelOpen = true;
|
||||
console.log('✅ Neural panel opened successfully');
|
||||
this.captureState('Panel opened');
|
||||
} else {
|
||||
console.error('❌ Neural panel did not open');
|
||||
}
|
||||
} else {
|
||||
console.error('❌ Could not find Neural button');
|
||||
}
|
||||
}
|
||||
async testAllTabs() {
|
||||
console.log('📋 Test 2: Testing all 5 tabs');
|
||||
const tabs = [
|
||||
'tools',
|
||||
'training',
|
||||
'models',
|
||||
'patterns',
|
||||
'performance'
|
||||
];
|
||||
for (const tabName of tabs){
|
||||
console.log(` Testing ${tabName} tab...`);
|
||||
const tab = this.findTab(tabName);
|
||||
if (tab) {
|
||||
this.testResults.tabs[tabName].found = true;
|
||||
tab.click();
|
||||
await this.wait(300);
|
||||
this.testResults.tabs[tabName].clicked = true;
|
||||
const content = this.findTabContent(tabName);
|
||||
if (content) {
|
||||
this.testResults.tabs[tabName].content = true;
|
||||
console.log(` ✅ ${tabName} tab working correctly`);
|
||||
this.captureState(`${tabName} tab active`);
|
||||
}
|
||||
} else {
|
||||
console.error(` ❌ ${tabName} tab not found`);
|
||||
}
|
||||
}
|
||||
}
|
||||
async testToolsTab() {
|
||||
console.log('📋 Test 3: Testing Tools tab in detail');
|
||||
const toolsTab = this.findTab('tools');
|
||||
if (toolsTab) {
|
||||
toolsTab.click();
|
||||
await this.wait(300);
|
||||
const toolCards = this.findToolCards();
|
||||
this.testResults.tools.total = toolCards.length;
|
||||
console.log(` Found ${toolCards.length} tool cards`);
|
||||
if (toolCards.length === 15) {
|
||||
console.log(' ✅ All 15 tools are displayed');
|
||||
} else {
|
||||
console.log(` ⚠️ Expected 15 tools, found ${toolCards.length}`);
|
||||
}
|
||||
const categories = this.findToolCategories();
|
||||
this.testResults.tools.categories = categories;
|
||||
console.log(` Found ${categories.length} categories: ${categories.join(', ')}`);
|
||||
for(let i = 0; i < Math.min(3, toolCards.length); i++){
|
||||
await this.testToolCard(toolCards[i], i);
|
||||
}
|
||||
const executeButtons = document.querySelectorAll('.execute-btn, [data-action="execute"]');
|
||||
const configButtons = document.querySelectorAll('.config-btn, [data-action="configure"]');
|
||||
this.testResults.tools.executeButtons = executeButtons.length;
|
||||
this.testResults.tools.configureButtons = configButtons.length;
|
||||
console.log(` Found ${executeButtons.length} execute buttons`);
|
||||
console.log(` Found ${configButtons.length} configure buttons`);
|
||||
}
|
||||
}
|
||||
async testToolCard(card, index) {
|
||||
console.log(` Testing tool card ${index + 1}...`);
|
||||
const toolName = card.querySelector('.tool-name, h3, h4')?.textContent || `Tool ${index + 1}`;
|
||||
const execBtn = card.querySelector('.execute-btn, [data-action="execute"]');
|
||||
if (execBtn) {
|
||||
execBtn.click();
|
||||
await this.wait(200);
|
||||
console.log(` ✅ Execute button clicked for ${toolName}`);
|
||||
const response = document.querySelector('.tool-response, .modal, .dialog');
|
||||
if (response) {
|
||||
console.log(` ✅ Response shown for ${toolName}`);
|
||||
const closeBtn = response.querySelector('.close, [data-action="close"]');
|
||||
if (closeBtn) closeBtn.click();
|
||||
}
|
||||
}
|
||||
const configBtn = card.querySelector('.config-btn, [data-action="configure"]');
|
||||
if (configBtn) {
|
||||
configBtn.click();
|
||||
await this.wait(200);
|
||||
console.log(` ✅ Configure button clicked for ${toolName}`);
|
||||
const modal = document.querySelector('.config-modal, .modal');
|
||||
if (modal) {
|
||||
const closeBtn = modal.querySelector('.close, [data-action="close"]');
|
||||
if (closeBtn) closeBtn.click();
|
||||
}
|
||||
}
|
||||
this.testResults.tools.tested.push(toolName);
|
||||
}
|
||||
async testPanelControls() {
|
||||
console.log('📋 Test 4: Testing panel controls');
|
||||
const refreshBtn = this.findControl('refresh');
|
||||
if (refreshBtn) {
|
||||
refreshBtn.click();
|
||||
await this.wait(300);
|
||||
this.testResults.controls.refresh = true;
|
||||
console.log(' ✅ Refresh button works');
|
||||
}
|
||||
const exportBtn = this.findControl('export');
|
||||
if (exportBtn) {
|
||||
exportBtn.click();
|
||||
await this.wait(300);
|
||||
this.testResults.controls.export = true;
|
||||
console.log(' ✅ Export button works');
|
||||
}
|
||||
const closeBtn = this.findControl('close');
|
||||
if (closeBtn) {
|
||||
console.log(' ✅ Close button found (not clicking to keep panel open)');
|
||||
this.testResults.controls.close = true;
|
||||
}
|
||||
}
|
||||
async testAnimations() {
|
||||
console.log('📋 Test 5: Testing animations');
|
||||
const panel = this.findNeuralPanel();
|
||||
if (panel) {
|
||||
const styles = window.getComputedStyle(panel);
|
||||
const hasTransition = styles.transition !== 'none' && styles.transition !== '';
|
||||
if (hasTransition) {
|
||||
this.testResults.animations.transitions = true;
|
||||
console.log(' ✅ CSS transitions detected');
|
||||
}
|
||||
const tabs = document.querySelectorAll('.tab, [role="tab"]');
|
||||
if (tabs.length >= 2) {
|
||||
tabs[0].click();
|
||||
await this.wait(150);
|
||||
tabs[1].click();
|
||||
await this.wait(150);
|
||||
this.testResults.animations.smooth = true;
|
||||
console.log(' ✅ Tab switching animations smooth');
|
||||
}
|
||||
}
|
||||
}
|
||||
async testResponsiveness() {
|
||||
console.log('📋 Test 6: Testing responsiveness');
|
||||
const originalWidth = window.innerWidth;
|
||||
const originalHeight = window.innerHeight;
|
||||
window.resizeTo(375, 667);
|
||||
await this.wait(300);
|
||||
this.testResults.responsiveness.mobile = this.checkLayout();
|
||||
console.log(' ✅ Mobile view tested (375x667)');
|
||||
window.resizeTo(768, 1024);
|
||||
await this.wait(300);
|
||||
this.testResults.responsiveness.tablet = this.checkLayout();
|
||||
console.log(' ✅ Tablet view tested (768x1024)');
|
||||
window.resizeTo(1920, 1080);
|
||||
await this.wait(300);
|
||||
this.testResults.responsiveness.desktop = this.checkLayout();
|
||||
console.log(' ✅ Desktop view tested (1920x1080)');
|
||||
window.resizeTo(originalWidth, originalHeight);
|
||||
this.testResults.responsiveness.tested = true;
|
||||
}
|
||||
findNeuralButton() {
|
||||
return document.querySelector('[data-view="neural"], ' + 'button[aria-label*="Neural"], ' + 'button:contains("Neural"), ' + '.neural-button, ' + '.header-nav button:nth-of-type(5)') || Array.from(document.querySelectorAll('button')).find((btn)=>btn.textContent.includes('Neural') || btn.textContent.includes('🧠'));
|
||||
}
|
||||
findNeuralPanel() {
|
||||
return document.querySelector('.neural-panel, ' + '.panel-neural, ' + '[data-panel="neural"], ' + '.view-panel.active');
|
||||
}
|
||||
findTab(tabName) {
|
||||
return document.querySelector(`[data-tab="${tabName}"], ` + `[role="tab"][aria-label*="${tabName}"], ` + `.tab-${tabName}`) || Array.from(document.querySelectorAll('.tab, [role="tab"]')).find((tab)=>tab.textContent.toLowerCase().includes(tabName));
|
||||
}
|
||||
findTabContent(tabName) {
|
||||
return document.querySelector(`[data-tab-content="${tabName}"], ` + `.tab-content-${tabName}, ` + `.${tabName}-content`);
|
||||
}
|
||||
findToolCards() {
|
||||
return document.querySelectorAll('.tool-card, ' + '.neural-tool-card, ' + '[data-tool], ' + '.tool-item');
|
||||
}
|
||||
findToolCategories() {
|
||||
const categoryElements = document.querySelectorAll('.tool-category, .category-header');
|
||||
return Array.from(categoryElements).map((el)=>el.textContent.trim());
|
||||
}
|
||||
findControl(type) {
|
||||
const selectors = {
|
||||
refresh: '[data-action="refresh"], .refresh-btn, button[aria-label*="Refresh"]',
|
||||
export: '[data-action="export"], .export-btn, button[aria-label*="Export"]',
|
||||
close: '[data-action="close"], .close-btn, button[aria-label*="Close"]'
|
||||
};
|
||||
return document.querySelector(selectors[type]) || Array.from(document.querySelectorAll('button')).find((btn)=>btn.textContent.toLowerCase().includes(type));
|
||||
}
|
||||
checkLayout() {
|
||||
const panel = this.findNeuralPanel();
|
||||
if (!panel) return false;
|
||||
const rect = panel.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0 && rect.top >= 0 && rect.left >= 0;
|
||||
}
|
||||
captureState(description) {
|
||||
console.log(`📸 Screenshot: ${description}`);
|
||||
const state = {
|
||||
timestamp: new Date().toISOString(),
|
||||
description,
|
||||
viewport: `${window.innerWidth}x${window.innerHeight}`,
|
||||
panelVisible: !!this.findNeuralPanel()
|
||||
};
|
||||
return state;
|
||||
}
|
||||
async wait(ms) {
|
||||
return new Promise((resolve)=>setTimeout(resolve, ms));
|
||||
}
|
||||
generateReport() {
|
||||
const report = {
|
||||
summary: {
|
||||
timestamp: new Date().toISOString(),
|
||||
duration: 'Completed',
|
||||
overallStatus: this.calculateOverallStatus()
|
||||
},
|
||||
details: this.testResults,
|
||||
screenshots: [],
|
||||
recommendations: this.generateRecommendations()
|
||||
};
|
||||
console.log('\n📊 TEST REPORT:');
|
||||
console.log('================');
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
return report;
|
||||
}
|
||||
calculateOverallStatus() {
|
||||
const checks = [
|
||||
this.testResults.panelOpen,
|
||||
Object.values(this.testResults.tabs).every((tab)=>tab.found),
|
||||
this.testResults.tools.total === 15,
|
||||
Object.values(this.testResults.controls).some((ctrl)=>ctrl),
|
||||
this.testResults.responsiveness.tested
|
||||
];
|
||||
const passed = checks.filter(Boolean).length;
|
||||
const total = checks.length;
|
||||
return {
|
||||
passed,
|
||||
total,
|
||||
percentage: Math.round(passed / total * 100),
|
||||
status: passed === total ? 'PASS' : passed > total / 2 ? 'PARTIAL' : 'FAIL'
|
||||
};
|
||||
}
|
||||
generateRecommendations() {
|
||||
const recommendations = [];
|
||||
if (!this.testResults.panelOpen) {
|
||||
recommendations.push('Fix Neural button visibility or click handler');
|
||||
}
|
||||
if (this.testResults.tools.total !== 15) {
|
||||
recommendations.push(`Ensure all 15 tools are displayed (found ${this.testResults.tools.total})`);
|
||||
}
|
||||
if (!this.testResults.animations.transitions) {
|
||||
recommendations.push('Add CSS transitions for better UX');
|
||||
}
|
||||
return recommendations;
|
||||
}
|
||||
}
|
||||
export default NeuralPanelTest;
|
||||
|
||||
//# sourceMappingURL=neural-panel-test.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../src/ui/web-ui/neural-panel-test.js"],"sourcesContent":["/**\n * Automated Neural Networks Panel Test Suite\n * Tests all 5 tabs and 15 tools comprehensively\n */\n\nexport class NeuralPanelTest {\n constructor() {\n this.testResults = {\n panelOpen: false,\n tabs: {\n tools: { found: false, clicked: false, content: false },\n training: { found: false, clicked: false, content: false },\n models: { found: false, clicked: false, content: false },\n patterns: { found: false, clicked: false, content: false },\n performance: { found: false, clicked: false, content: false },\n },\n tools: {\n total: 0,\n categories: [],\n executeButtons: 0,\n configureButtons: 0,\n tested: [],\n },\n controls: {\n refresh: false,\n export: false,\n close: false,\n },\n animations: {\n smooth: false,\n transitions: false,\n },\n responsiveness: {\n tested: false,\n mobile: false,\n tablet: false,\n desktop: false,\n },\n };\n }\n\n // Main test runner\n async runTests() {\n console.log('🧪 Starting Neural Networks Panel Test Suite');\n\n // Test 1: Open Neural Panel\n await this.testOpenPanel();\n\n // Test 2: Test all 5 tabs\n await this.testAllTabs();\n\n // Test 3: Test Tools tab in detail\n await this.testToolsTab();\n\n // Test 4: Test panel controls\n await this.testPanelControls();\n\n // Test 5: Test animations\n await this.testAnimations();\n\n // Test 6: Test responsiveness\n await this.testResponsiveness();\n\n // Generate report\n return this.generateReport();\n }\n\n // Test opening the neural panel\n async testOpenPanel() {\n console.log('📋 Test 1: Opening Neural Panel');\n\n // Find neural button in header\n const neuralButton = this.findNeuralButton();\n\n if (neuralButton) {\n console.log('✅ Found Neural button');\n\n // Click and wait\n neuralButton.click();\n await this.wait(500);\n\n // Check if panel opened\n const panel = this.findNeuralPanel();\n if (panel) {\n this.testResults.panelOpen = true;\n console.log('✅ Neural panel opened successfully');\n\n // Take screenshot simulation\n this.captureState('Panel opened');\n } else {\n console.error('❌ Neural panel did not open');\n }\n } else {\n console.error('❌ Could not find Neural button');\n }\n }\n\n // Test all 5 tabs\n async testAllTabs() {\n console.log('📋 Test 2: Testing all 5 tabs');\n\n const tabs = ['tools', 'training', 'models', 'patterns', 'performance'];\n\n for (const tabName of tabs) {\n console.log(` Testing ${tabName} tab...`);\n\n const tab = this.findTab(tabName);\n if (tab) {\n this.testResults.tabs[tabName].found = true;\n\n // Click tab\n tab.click();\n await this.wait(300);\n\n this.testResults.tabs[tabName].clicked = true;\n\n // Check content loaded\n const content = this.findTabContent(tabName);\n if (content) {\n this.testResults.tabs[tabName].content = true;\n console.log(` ✅ ${tabName} tab working correctly`);\n\n // Capture state\n this.captureState(`${tabName} tab active`);\n }\n } else {\n console.error(` ❌ ${tabName} tab not found`);\n }\n }\n }\n\n // Detailed test of Tools tab\n async testToolsTab() {\n console.log('📋 Test 3: Testing Tools tab in detail');\n\n // Switch to Tools tab\n const toolsTab = this.findTab('tools');\n if (toolsTab) {\n toolsTab.click();\n await this.wait(300);\n\n // Find all tool cards\n const toolCards = this.findToolCards();\n this.testResults.tools.total = toolCards.length;\n\n console.log(` Found ${toolCards.length} tool cards`);\n\n if (toolCards.length === 15) {\n console.log(' ✅ All 15 tools are displayed');\n } else {\n console.log(` ⚠️ Expected 15 tools, found ${toolCards.length}`);\n }\n\n // Test categories\n const categories = this.findToolCategories();\n this.testResults.tools.categories = categories;\n console.log(` Found ${categories.length} categories: ${categories.join(', ')}`);\n\n // Test each tool card\n for (let i = 0; i < Math.min(3, toolCards.length); i++) {\n await this.testToolCard(toolCards[i], i);\n }\n\n // Count buttons\n const executeButtons = document.querySelectorAll('.execute-btn, [data-action=\"execute\"]');\n const configButtons = document.querySelectorAll('.config-btn, [data-action=\"configure\"]');\n\n this.testResults.tools.executeButtons = executeButtons.length;\n this.testResults.tools.configureButtons = configButtons.length;\n\n console.log(` Found ${executeBLine truncated
|
||||
@@ -1,64 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
import { GitHubIntegrationView } from './views/GitHubIntegrationView.js';
|
||||
import { EventBus } from './core/EventBus.js';
|
||||
import { runGitHubViewTest } from './views/GitHubIntegrationTest.js';
|
||||
console.log('🧪 Testing GitHub Integration View Setup');
|
||||
console.log('═'.repeat(60));
|
||||
console.log('\n1️⃣ Testing view instantiation...');
|
||||
try {
|
||||
const eventBus = new EventBus();
|
||||
const viewConfig = {
|
||||
id: 'github',
|
||||
name: 'GitHub Integration',
|
||||
icon: '🐙',
|
||||
description: 'GitHub integration and operations',
|
||||
component: 'GitHubIntegrationView',
|
||||
toolCount: 8
|
||||
};
|
||||
const githubView = new GitHubIntegrationView(null, eventBus, viewConfig);
|
||||
console.log('✅ GitHub view instantiated successfully');
|
||||
console.log('\n2️⃣ Testing view initialization...');
|
||||
await githubView.initialize();
|
||||
console.log('✅ GitHub view initialized successfully');
|
||||
console.log('\n3️⃣ Testing terminal mode rendering...');
|
||||
await githubView.render({
|
||||
mode: 'terminal'
|
||||
});
|
||||
console.log('\n4️⃣ Checking GitHub tools availability...');
|
||||
const tools = githubView.githubTools;
|
||||
console.log('Available GitHub tools:');
|
||||
Object.entries(tools).forEach(([key, value])=>{
|
||||
console.log(` ✓ ${key}: ${value}`);
|
||||
});
|
||||
console.log('\n5️⃣ Testing event handling...');
|
||||
let eventReceived = false;
|
||||
eventBus.on('tool:execute', (data)=>{
|
||||
eventReceived = true;
|
||||
console.log('✅ Event received:', data.tool);
|
||||
});
|
||||
await githubView.quickAction('github_repo_analyze', {
|
||||
repo: 'test/repo'
|
||||
});
|
||||
if (eventReceived) {
|
||||
console.log('✅ Event handling working correctly');
|
||||
}
|
||||
console.log('\n6️⃣ Running MCP integration tests...');
|
||||
runGitHubViewTest();
|
||||
console.log('\n🎉 All tests passed! GitHub Integration View is ready.');
|
||||
console.log('═'.repeat(60));
|
||||
} catch (error) {
|
||||
console.error('❌ Test failed:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('\n📊 GitHub Integration View Summary:');
|
||||
console.log(' - 8 GitHub tools integrated');
|
||||
console.log(' - Repository management dashboard');
|
||||
console.log(' - PR/Issue tracking system');
|
||||
console.log(' - Release coordination');
|
||||
console.log(' - Workflow automation');
|
||||
console.log(' - Code review automation');
|
||||
console.log(' - Repository metrics');
|
||||
console.log(' - Multi-repo sync coordination');
|
||||
console.log('\n✅ View is ready for production use!');
|
||||
|
||||
//# sourceMappingURL=test-github-view.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../src/ui/web-ui/test-github-view.js"],"sourcesContent":["#!/usr/bin/env node\n/**\n * Test script for GitHub Integration View\n * Validates that the view is properly integrated and all tools are accessible\n */\n\nimport { GitHubIntegrationView } from './views/GitHubIntegrationView.js';\nimport { EventBus } from './core/EventBus.js';\nimport { runGitHubViewTest } from './views/GitHubIntegrationTest.js';\n\nconsole.log('🧪 Testing GitHub Integration View Setup');\nconsole.log('═'.repeat(60));\n\n// Test 1: View instantiation\nconsole.log('\\n1️⃣ Testing view instantiation...');\ntry {\n const eventBus = new EventBus();\n const viewConfig = {\n id: 'github',\n name: 'GitHub Integration',\n icon: '🐙',\n description: 'GitHub integration and operations',\n component: 'GitHubIntegrationView',\n toolCount: 8,\n };\n\n const githubView = new GitHubIntegrationView(null, eventBus, viewConfig);\n console.log('✅ GitHub view instantiated successfully');\n\n // Test 2: View initialization\n console.log('\\n2️⃣ Testing view initialization...');\n await githubView.initialize();\n console.log('✅ GitHub view initialized successfully');\n\n // Test 3: Terminal mode rendering\n console.log('\\n3️⃣ Testing terminal mode rendering...');\n await githubView.render({ mode: 'terminal' });\n\n // Test 4: Tool availability\n console.log('\\n4️⃣ Checking GitHub tools availability...');\n const tools = githubView.githubTools;\n console.log('Available GitHub tools:');\n Object.entries(tools).forEach(([key, value]) => {\n console.log(` ✓ ${key}: ${value}`);\n });\n\n // Test 5: Event handling\n console.log('\\n5️⃣ Testing event handling...');\n let eventReceived = false;\n eventBus.on('tool:execute', (data) => {\n eventReceived = true;\n console.log('✅ Event received:', data.tool);\n });\n\n // Trigger a test action\n await githubView.quickAction('github_repo_analyze', { repo: 'test/repo' });\n\n if (eventReceived) {\n console.log('✅ Event handling working correctly');\n }\n\n // Test 6: MCP Integration test\n console.log('\\n6️⃣ Running MCP integration tests...');\n runGitHubViewTest();\n\n console.log('\\n🎉 All tests passed! GitHub Integration View is ready.');\n console.log('═'.repeat(60));\n} catch (error) {\n console.error('❌ Test failed:', error);\n process.exit(1);\n}\n\n// Summary\nconsole.log('\\n📊 GitHub Integration View Summary:');\nconsole.log(' - 8 GitHub tools integrated');\nconsole.log(' - Repository management dashboard');\nconsole.log(' - PR/Issue tracking system');\nconsole.log(' - Release coordination');\nconsole.log(' - Workflow automation');\nconsole.log(' - Code review automation');\nconsole.log(' - Repository metrics');\nconsole.log(' - Multi-repo sync coordination');\nconsole.log('\\n✅ View is ready for production use!');\n"],"names":["GitHubIntegrationView","EventBus","runGitHubViewTest","console","log","repeat","eventBus","viewConfig","id","name","icon","description","component","toolCount","githubView","initialize","render","mode","tools","githubTools","Object","entries","forEach","key","value","eventReceived","on","data","tool","quickAction","repo","error","process","exit"],"mappings":";AAMA,SAASA,qBAAqB,QAAQ,mCAAmC;AACzE,SAASC,QAAQ,QAAQ,qBAAqB;AAC9C,SAASC,iBAAiB,QAAQ,mCAAmC;AAErEC,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC,IAAIC,MAAM,CAAC;AAGvBF,QAAQC,GAAG,CAAC;AACZ,IAAI;IACF,MAAME,WAAW,IAAIL;IACrB,MAAMM,aAAa;QACjBC,IAAI;QACJC,MAAM;QACNC,MAAM;QACNC,aAAa;QACbC,WAAW;QACXC,WAAW;IACb;IAEA,MAAMC,aAAa,IAAId,sBAAsB,MAAMM,UAAUC;IAC7DJ,QAAQC,GAAG,CAAC;IAGZD,QAAQC,GAAG,CAAC;IACZ,MAAMU,WAAWC,UAAU;IAC3BZ,QAAQC,GAAG,CAAC;IAGZD,QAAQC,GAAG,CAAC;IACZ,MAAMU,WAAWE,MAAM,CAAC;QAAEC,MAAM;IAAW;IAG3Cd,QAAQC,GAAG,CAAC;IACZ,MAAMc,QAAQJ,WAAWK,WAAW;IACpChB,QAAQC,GAAG,CAAC;IACZgB,OAAOC,OAAO,CAACH,OAAOI,OAAO,CAAC,CAAC,CAACC,KAAKC,MAAM;QACzCrB,QAAQC,GAAG,CAAC,CAAC,IAAI,EAAEmB,IAAI,EAAE,EAAEC,OAAO;IACpC;IAGArB,QAAQC,GAAG,CAAC;IACZ,IAAIqB,gBAAgB;IACpBnB,SAASoB,EAAE,CAAC,gBAAgB,CAACC;QAC3BF,gBAAgB;QAChBtB,QAAQC,GAAG,CAAC,qBAAqBuB,KAAKC,IAAI;IAC5C;IAGA,MAAMd,WAAWe,WAAW,CAAC,uBAAuB;QAAEC,MAAM;IAAY;IAExE,IAAIL,eAAe;QACjBtB,QAAQC,GAAG,CAAC;IACd;IAGAD,QAAQC,GAAG,CAAC;IACZF;IAEAC,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC,IAAIC,MAAM,CAAC;AACzB,EAAE,OAAO0B,OAAO;IACd5B,QAAQ4B,KAAK,CAAC,kBAAkBA;IAChCC,QAAQC,IAAI,CAAC;AACf;AAGA9B,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC"}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/web-ui/views/DAAView.js"],"sourcesContent":["/**\n * Dynamic Agent Architecture (DAA) View\n * Interface for managing dynamic agents, resources, lifecycle, and communication\n * Implements all 8 DAA management tools\n */\n\nexport default class DAAView {\n constructor(container, eventBus, viewConfig) {\n this.container = container;\n this.eventBus = eventBus;\n this.viewConfig = viewConfig;\n this.componentLibrary = null;\n\n // DAA State Management\n this.agents = new Map();\n this.resources = new Map();\n this.communications = [];\n this.consensusHistory = [];\n this.faultEvents = [];\n this.optimizations = [];\n\n this.currentTab = 'overview';\n this.isInitialized = false;\n }\n\n /**\n * Initialize the DAA view\n */\n async initialize() {\n if (this.isInitialized) return;\n\n // Get component library from event bus\n this.eventBus.emit('component-library:get', (library) => {\n this.componentLibrary = library;\n });\n\n // Setup event handlers\n this.setupEventHandlers();\n\n this.isInitialized = true;\n }\n\n /**\n * Render the view with given parameters\n */\n async render(params = {}) {\n if (!this.isInitialized) {\n await this.initialize();\n }\n\n // Clear container\n if (this.container) {\n this.container.innerHTML = '';\n this.createDAAInterface();\n } else {\n // Terminal mode\n this.renderTerminalMode(params);\n }\n }\n\n /**\n * Create DAA interface for browser\n */\n createDAAInterface() {\n // Create tab container with all DAA sections\n const tabs = [\n { label: '📊 Overview', content: this.createOverviewTab() },\n { label: '🤖 Agent Management', content: this.createAgentManagementTab() },\n { label: '🔀 Capability Matching', content: this.createCapabilityMatchingTab() },\n { label: '📦 Resource Allocation', content: this.createResourceAllocationTab() },\n { label: '🔄 Lifecycle Management', content: this.createLifecycleTab() },\n { label: '📡 Communication', content: this.createCommunicationTab() },\n { label: '🤝 Consensus', content: this.createConsensusTab() },\n { label: '🛡️ Fault Tolerance', content: this.createFaultToleranceTab() },\n { label: '⚡ Optimization', content: this.createOptimizationTab() },\n ];\n\n if (this.componentLibrary) {\n const tabContainer = this.componentLibrary.getComponent('TabContainer')(tabs);\n this.container.appendChild(tabContainer.element);\n } else {\n // Fallback without component library\n this.createFallbackInterface();\n }\n }\n\n /**\n * Create overview tab content\n */\n createOverviewTab() {\n return `\n <div class=\"daa-overview\">\n <div class=\"stats-grid\">\n <div id=\"agents-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">🤖</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0</div>\n <div class=\"stat-label\">Active Agents</div>\n </div>\n </div>\n <div id=\"resources-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">📦</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0%</div>\n <div class=\"stat-label\">Resource Usage</div>\n </div>\n </div>\n <div id=\"communications-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">📡</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0</div>\n <div class=\"stat-label\">Messages/min</div>\n </div>\n </div>\n <div id=\"health-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">💚</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">100%</div>\n <div class=\"stat-label\">System Health</div>\n </div>\n </div>\n </div>\n \n <div class=\"daa-tools\">\n <h3>🔧 Quick Actions</h3>\n <div class=\"tool-buttons\">\n <button onclick=\"this.quickCreateAgent()\" class=\"daa-btn primary\">\n 🤖 Create Agent\n </button>\n <button onclick=\"this.quickMatchCapabilities()\" class=\"daa-btn secondary\">\n 🔀 Match Capabilities\n </button>\n <button onclick=\"this.quickAllocateResources()\" class=\"daa-btn secondary\">\n 📦 Allocate Resources\n </button>\n <button onclick=\"this.quickHealthCheck()\" class=\"daa-btn secondary\">\n 🏥 Health Check\n </button>\n </div>\n </div>\n\n <div class=\"agent-visualization\">\n <h3>🌐 Agent Network Visualization</h3>\n <div id=\"agent-network-viz\" class=\"network-container\">\n Line truncated
|
||||
@@ -1,182 +0,0 @@
|
||||
export const GitHubViewMCPIntegration = {
|
||||
tools: {
|
||||
github_repo_analyze: {
|
||||
handler: async (params)=>{
|
||||
console.log('🔍 Analyzing repository:', params.repo);
|
||||
return {
|
||||
code_quality: '85%',
|
||||
security: '92%',
|
||||
performance: '78%',
|
||||
details: 'Repository analysis complete'
|
||||
};
|
||||
}
|
||||
},
|
||||
github_pr_manage: {
|
||||
handler: async (params)=>{
|
||||
console.log('🔄 Managing PR:', params);
|
||||
return {
|
||||
success: true,
|
||||
action: params.action,
|
||||
pr_number: params.pr_number
|
||||
};
|
||||
}
|
||||
},
|
||||
github_issue_track: {
|
||||
handler: async (params)=>{
|
||||
console.log('📋 Tracking issues:', params);
|
||||
return {
|
||||
open: 15,
|
||||
in_progress: 8,
|
||||
closed: 42
|
||||
};
|
||||
}
|
||||
},
|
||||
github_release_coord: {
|
||||
handler: async (params)=>{
|
||||
console.log('🚀 Coordinating release:', params);
|
||||
return {
|
||||
version: params.version,
|
||||
status: 'planned',
|
||||
date: params.date
|
||||
};
|
||||
}
|
||||
},
|
||||
github_workflow_auto: {
|
||||
handler: async (params)=>{
|
||||
console.log('🤖 Automating workflow:', params);
|
||||
return {
|
||||
workflow: params.workflow_name,
|
||||
status: 'created',
|
||||
trigger: params.trigger
|
||||
};
|
||||
}
|
||||
},
|
||||
github_code_review: {
|
||||
handler: async (params)=>{
|
||||
console.log('🔍 Running code review:', params);
|
||||
return {
|
||||
score: '8.5/10',
|
||||
issues: 3,
|
||||
suggestions: 7,
|
||||
findings: [
|
||||
{
|
||||
type: 'security',
|
||||
description: 'Check input validation'
|
||||
},
|
||||
{
|
||||
type: 'performance',
|
||||
description: 'Consider caching results'
|
||||
},
|
||||
{
|
||||
type: 'style',
|
||||
description: 'Inconsistent naming convention'
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
},
|
||||
github_sync_coord: {
|
||||
handler: async (params)=>{
|
||||
console.log('🔄 Syncing repositories:', params);
|
||||
return {
|
||||
synced: params.repos.length,
|
||||
status: 'complete'
|
||||
};
|
||||
}
|
||||
},
|
||||
github_metrics: {
|
||||
handler: async (params)=>{
|
||||
console.log('📊 Fetching metrics:', params);
|
||||
return {
|
||||
commits: {
|
||||
total: 1542,
|
||||
week: 87
|
||||
},
|
||||
pull_requests: {
|
||||
merged: 234,
|
||||
avg_time: '2.3 days'
|
||||
},
|
||||
issues: {
|
||||
resolved: 456,
|
||||
avg_time: '3.5 days'
|
||||
},
|
||||
contributors: {
|
||||
active: 12,
|
||||
new: 3
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
},
|
||||
testIntegration: async ()=>{
|
||||
console.log('🧪 Testing GitHub View MCP Integration');
|
||||
const analysisResult = await GitHubViewMCPIntegration.tools.github_repo_analyze.handler({
|
||||
repo: 'ruvnet/claude-flow',
|
||||
analysis_type: 'code_quality'
|
||||
});
|
||||
console.log('Repository Analysis Result:', analysisResult);
|
||||
const prResult = await GitHubViewMCPIntegration.tools.github_pr_manage.handler({
|
||||
repo: 'ruvnet/claude-flow',
|
||||
action: 'review',
|
||||
pr_number: 123
|
||||
});
|
||||
console.log('PR Management Result:', prResult);
|
||||
const metricsResult = await GitHubViewMCPIntegration.tools.github_metrics.handler({
|
||||
repo: 'ruvnet/claude-flow'
|
||||
});
|
||||
console.log('Metrics Result:', metricsResult);
|
||||
}
|
||||
};
|
||||
export class GitHubMCPBridge {
|
||||
constructor(eventBus){
|
||||
this.eventBus = eventBus;
|
||||
this.setupHandlers();
|
||||
}
|
||||
setupHandlers() {
|
||||
this.eventBus.on('tool:execute', async (data)=>{
|
||||
if (data.source === 'github-view' && data.tool.startsWith('github_')) {
|
||||
try {
|
||||
const handler = GitHubViewMCPIntegration.tools[data.tool]?.handler;
|
||||
if (handler) {
|
||||
const result = await handler(data.params);
|
||||
this.eventBus.emit('tool:executed', {
|
||||
tool: data.tool,
|
||||
result: result,
|
||||
source: 'github-view'
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
this.eventBus.emit('tool:error', {
|
||||
tool: data.tool,
|
||||
error: error.message,
|
||||
source: 'github-view'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
export function runGitHubViewTest() {
|
||||
console.log('\n🐙 GitHub Integration View Test');
|
||||
console.log('═'.repeat(50));
|
||||
GitHubViewMCPIntegration.testIntegration();
|
||||
console.log('\n✅ GitHub View is ready for integration!');
|
||||
console.log('The view supports all 8 GitHub MCP tools:');
|
||||
Object.keys(GitHubViewMCPIntegration.tools).forEach((tool)=>{
|
||||
console.log(` - ${tool}`);
|
||||
});
|
||||
console.log('\n📋 Features implemented:');
|
||||
console.log(' - Repository browser and analysis');
|
||||
console.log(' - PR/Issue management dashboard');
|
||||
console.log(' - Release coordination planning');
|
||||
console.log(' - Workflow automation builder');
|
||||
console.log(' - Code review automation');
|
||||
console.log(' - Repository metrics dashboard');
|
||||
console.log(' - Multi-repo sync coordination');
|
||||
console.log('═'.repeat(50));
|
||||
}
|
||||
if (typeof process !== 'undefined' && process.argv[1] === import.meta.url) {
|
||||
runGitHubViewTest();
|
||||
}
|
||||
|
||||
//# sourceMappingURL=GitHubIntegrationTest.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/web-ui/views/GitHubIntegrationTest.js"],"sourcesContent":["/**\n * GitHub Integration View Test\n * Demonstrates integration with MCP tools\n */\n\n// Example of how the GitHub view interacts with MCP tools\nexport const GitHubViewMCPIntegration = {\n // Tool mappings\n tools: {\n github_repo_analyze: {\n handler: async (params) => {\n console.log('🔍 Analyzing repository:', params.repo);\n return {\n code_quality: '85%',\n security: '92%',\n performance: '78%',\n details: 'Repository analysis complete',\n };\n },\n },\n\n github_pr_manage: {\n handler: async (params) => {\n console.log('🔄 Managing PR:', params);\n return {\n success: true,\n action: params.action,\n pr_number: params.pr_number,\n };\n },\n },\n\n github_issue_track: {\n handler: async (params) => {\n console.log('📋 Tracking issues:', params);\n return {\n open: 15,\n in_progress: 8,\n closed: 42,\n };\n },\n },\n\n github_release_coord: {\n handler: async (params) => {\n console.log('🚀 Coordinating release:', params);\n return {\n version: params.version,\n status: 'planned',\n date: params.date,\n };\n },\n },\n\n github_workflow_auto: {\n handler: async (params) => {\n console.log('🤖 Automating workflow:', params);\n return {\n workflow: params.workflow_name,\n status: 'created',\n trigger: params.trigger,\n };\n },\n },\n\n github_code_review: {\n handler: async (params) => {\n console.log('🔍 Running code review:', params);\n return {\n score: '8.5/10',\n issues: 3,\n suggestions: 7,\n findings: [\n { type: 'security', description: 'Check input validation' },\n { type: 'performance', description: 'Consider caching results' },\n { type: 'style', description: 'Inconsistent naming convention' },\n ],\n };\n },\n },\n\n github_sync_coord: {\n handler: async (params) => {\n console.log('🔄 Syncing repositories:', params);\n return {\n synced: params.repos.length,\n status: 'complete',\n };\n },\n },\n\n github_metrics: {\n handler: async (params) => {\n console.log('📊 Fetching metrics:', params);\n return {\n commits: { total: 1542, week: 87 },\n pull_requests: { merged: 234, avg_time: '2.3 days' },\n issues: { resolved: 456, avg_time: '3.5 days' },\n contributors: { active: 12, new: 3 },\n };\n },\n },\n },\n\n // Example usage\n testIntegration: async () => {\n console.log('🧪 Testing GitHub View MCP Integration');\n\n // Test repository analysis\n const analysisResult = await GitHubViewMCPIntegration.tools.github_repo_analyze.handler({\n repo: 'ruvnet/claude-flow',\n analysis_type: 'code_quality',\n });\n console.log('Repository Analysis Result:', analysisResult);\n\n // Test PR management\n const prResult = await GitHubViewMCPIntegration.tools.github_pr_manage.handler({\n repo: 'ruvnet/claude-flow',\n action: 'review',\n pr_number: 123,\n });\n console.log('PR Management Result:', prResult);\n\n // Test metrics\n const metricsResult = await GitHubViewMCPIntegration.tools.github_metrics.handler({\n repo: 'ruvnet/claude-flow',\n });\n console.log('Metrics Result:', metricsResult);\n },\n};\n\n// Integration with EventBus for real MCP tools\nexport class GitHubMCPBridge {\n constructor(eventBus) {\n this.eventBus = eventBus;\n this.setupHandlers();\n }\n\n setupHandlers() {\n // Listen for tool execution requests from the view\n this.eventBus.on('tool:execute', async (data) => {\n if (data.source === 'github-view' && data.tool.startsWith('github_')) {\n try {\n // In real implementation, this would call the actual MCP tool\n // For now, we use the test handlers\n const handler = GitHubViewMCPIntegration.tools[data.tool]?.handler;\n if (handler) {\n const result = await handler(data.params);\n\n // Emit result back to the view\n this.eventBus.emit('tool:executed', {\n tool: data.tool,\n result: result,\n source: 'github-view',\n });\n }\n } catch (error) {\n this.eventBus.emit('tool:error', {\n tool: data.tool,\n error: error.message,\n source: 'github-view',\n });\n }\n }\n });\n }\n}\n\n// Export test function\nexport function runGitHubViewTest() {\n console.log('\\n🐙 GitHub Integration View Test');\n conLine truncated
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/web-ui/views/GitHubIntegrationView.js"],"sourcesContent":["/**\n * GitHub Integration View - Interface for GitHub operations\n * Handles repository analysis, PR management, issue tracking, and more\n */\n\nexport default class GitHubIntegrationView {\n constructor(container, eventBus, viewConfig) {\n this.container = container;\n this.eventBus = eventBus;\n this.viewConfig = viewConfig;\n this.componentLibrary = null;\n this.repositories = new Map();\n this.pullRequests = new Map();\n this.issues = new Map();\n this.currentTab = 'overview';\n this.isInitialized = false;\n\n // GitHub tools\n this.githubTools = {\n repo_analyze: 'github_repo_analyze',\n pr_manage: 'github_pr_manage',\n issue_track: 'github_issue_track',\n release_coord: 'github_release_coord',\n workflow_auto: 'github_workflow_auto',\n code_review: 'github_code_review',\n sync_coord: 'github_sync_coord',\n metrics: 'github_metrics',\n };\n }\n\n /**\n * Initialize the GitHub integration view\n */\n async initialize() {\n if (this.isInitialized) return;\n\n // Get component library from event bus\n this.eventBus.emit('component-library:get', (library) => {\n this.componentLibrary = library;\n });\n\n // Setup event handlers\n this.setupEventHandlers();\n\n this.isInitialized = true;\n }\n\n /**\n * Render the view with given parameters\n */\n async render(params = {}) {\n if (!this.isInitialized) {\n await this.initialize();\n }\n\n // Clear container\n if (this.container) {\n this.container.innerHTML = '';\n this.createGitHubInterface();\n } else {\n // Terminal mode\n this.renderTerminalMode(params);\n }\n }\n\n /**\n * Create GitHub interface for browser\n */\n createGitHubInterface() {\n // Create tab container\n const tabs = [\n { label: '🏠 Overview', content: this.createOverviewTab() },\n { label: '📁 Repositories', content: this.createRepositoriesTab() },\n { label: '🔄 Pull Requests', content: this.createPullRequestsTab() },\n { label: '📋 Issues', content: this.createIssuesTab() },\n { label: '🚀 Releases', content: this.createReleasesTab() },\n { label: '🤖 Automation', content: this.createAutomationTab() },\n { label: '📊 Analytics', content: this.createAnalyticsTab() },\n { label: '🔍 Code Review', content: this.createCodeReviewTab() },\n ];\n\n if (this.componentLibrary) {\n const tabContainer = this.componentLibrary.getComponent('TabContainer')(tabs);\n this.container.appendChild(tabContainer.element);\n } else {\n // Fallback without component library\n this.createFallbackInterface();\n }\n }\n\n /**\n * Create overview tab content\n */\n createOverviewTab() {\n return `\n <div class=\"github-overview\">\n <div class=\"stats-grid\">\n <div id=\"repos-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">📁</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0</div>\n <div class=\"stat-label\">Repositories</div>\n </div>\n </div>\n <div id=\"prs-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">🔄</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0</div>\n <div class=\"stat-label\">Open PRs</div>\n </div>\n </div>\n <div id=\"issues-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">📋</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0</div>\n <div class=\"stat-label\">Open Issues</div>\n </div>\n </div>\n <div id=\"workflows-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">⚡</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0</div>\n <div class=\"stat-label\">Active Workflows</div>\n </div>\n </div>\n </div>\n \n <div class=\"github-tools\">\n <h3>🔧 Quick Actions</h3>\n <div class=\"tool-buttons\">\n <button onclick=\"window.githubView.analyzeRepository()\" class=\"github-btn primary\">\n 📊 Analyze Repository\n </button>\n <button onclick=\"window.githubView.createPullRequest()\" class=\"github-btn secondary\">\n 🔄 Create PR\n </button>\n <button onclick=\"window.githubView.trackIssues()\" class=\"github-btn secondary\">\n 📋 Track Issues\n </button>\n <button onclick=\"window.githubView.checkMetrics()\" class=\"github-btn secondary\">\n 📈 View Metrics\n </button>\n </div>\n </div>\n\n <div class=\"recent-aLine truncated
|
||||
@@ -1,795 +0,0 @@
|
||||
export default class NeuralNetworkView {
|
||||
constructor(container, eventBus, viewConfig){
|
||||
this.container = container;
|
||||
this.eventBus = eventBus;
|
||||
this.viewConfig = viewConfig;
|
||||
this.componentLibrary = null;
|
||||
this.models = new Map();
|
||||
this.trainingJobs = new Map();
|
||||
this.currentTab = 'overview';
|
||||
this.isInitialized = false;
|
||||
}
|
||||
async initialize() {
|
||||
if (this.isInitialized) return;
|
||||
this.eventBus.emit('component-library:get', (library)=>{
|
||||
this.componentLibrary = library;
|
||||
});
|
||||
this.setupEventHandlers();
|
||||
this.isInitialized = true;
|
||||
}
|
||||
async render(params = {}) {
|
||||
if (!this.isInitialized) {
|
||||
await this.initialize();
|
||||
}
|
||||
if (this.container) {
|
||||
this.container.innerHTML = '';
|
||||
this.createNeuralNetworkInterface();
|
||||
} else {
|
||||
this.renderTerminalMode(params);
|
||||
}
|
||||
}
|
||||
createNeuralNetworkInterface() {
|
||||
const tabs = [
|
||||
{
|
||||
label: '📊 Overview',
|
||||
content: this.createOverviewTab()
|
||||
},
|
||||
{
|
||||
label: '🧠 Training',
|
||||
content: this.createTrainingTab()
|
||||
},
|
||||
{
|
||||
label: '🔮 Prediction',
|
||||
content: this.createPredictionTab()
|
||||
},
|
||||
{
|
||||
label: '🎯 Patterns',
|
||||
content: this.createPatternsTab()
|
||||
},
|
||||
{
|
||||
label: '💾 Models',
|
||||
content: this.createModelsTab()
|
||||
},
|
||||
{
|
||||
label: '⚡ Optimization',
|
||||
content: this.createOptimizationTab()
|
||||
}
|
||||
];
|
||||
if (this.componentLibrary) {
|
||||
const tabContainer = this.componentLibrary.getComponent('TabContainer')(tabs);
|
||||
this.container.appendChild(tabContainer.element);
|
||||
} else {
|
||||
this.createFallbackInterface();
|
||||
}
|
||||
}
|
||||
createOverviewTab() {
|
||||
return `
|
||||
<div class="neural-overview">
|
||||
<div class="stats-grid">
|
||||
<div id="models-stat" class="stat-card">
|
||||
<div class="stat-icon">🧠</div>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value">0</div>
|
||||
<div class="stat-label">Models</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="training-stat" class="stat-card">
|
||||
<div class="stat-icon">⚡</div>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value">0</div>
|
||||
<div class="stat-label">Training Jobs</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="accuracy-stat" class="stat-card">
|
||||
<div class="stat-icon">🎯</div>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value">--</div>
|
||||
<div class="stat-label">Avg Accuracy</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="wasm-stat" class="stat-card">
|
||||
<div class="stat-icon">🚀</div>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value">--</div>
|
||||
<div class="stat-label">WASM Status</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="neural-tools">
|
||||
<h3>🔧 Quick Actions</h3>
|
||||
<div class="tool-buttons">
|
||||
<button onclick="this.startQuickTrain()" class="neural-btn primary">
|
||||
🧠 Quick Train
|
||||
</button>
|
||||
<button onclick="this.checkModels()" class="neural-btn secondary">
|
||||
📋 List Models
|
||||
</button>
|
||||
<button onclick="this.runPrediction()" class="neural-btn secondary">
|
||||
🔮 Test Prediction
|
||||
</button>
|
||||
<button onclick="this.analyzePatterns()" class="neural-btn secondary">
|
||||
🎯 Analyze Patterns
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="recent-activity">
|
||||
<h3>📈 Recent Activity</h3>
|
||||
<div id="activity-log" class="activity-list">
|
||||
<div class="activity-item">
|
||||
<span class="activity-time">--:--</span>
|
||||
<span class="activity-desc">No recent activity</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
createTrainingTab() {
|
||||
return `
|
||||
<div class="neural-training">
|
||||
<div class="training-form">
|
||||
<h3>🧠 Neural Network Training</h3>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Pattern Type:</label>
|
||||
<select id="pattern-type">
|
||||
<option value="coordination">Coordination</option>
|
||||
<option value="optimization">Optimization</option>
|
||||
<option value="prediction">Prediction</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Training Data:</label>
|
||||
<textarea id="training-data" placeholder="Enter training data or file path..."></textarea>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Epochs:</label>
|
||||
<input type="number" id="epochs" value="50" min="1" max="1000">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Learning Rate:</label>
|
||||
<input type="number" id="learning-rate" value="0.001" step="0.001" min="0.0001" max="1">
|
||||
</div>
|
||||
|
||||
<button onclick="this.startTraining()" class="neural-btn primary">
|
||||
⚡ Start Training
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="training-progress">
|
||||
<h3>📊 Training Progress</h3>
|
||||
<div id="training-status" class="status-display">
|
||||
<div class="status-idle">No training in progress</div>
|
||||
</div>
|
||||
|
||||
<div id="training-chart" class="chart-container">
|
||||
<!-- Training progress chart will be inserted here -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="training-history">
|
||||
<h3>📋 Training History</h3>
|
||||
<div id="training-history-list" class="history-list">
|
||||
<!-- Training history will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
createPredictionTab() {
|
||||
return `
|
||||
<div class="neural-prediction">
|
||||
<div class="prediction-form">
|
||||
<h3>🔮 AI Prediction</h3>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Model:</label>
|
||||
<select id="prediction-model">
|
||||
<option value="">Select a model...</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Input Data:</label>
|
||||
<textarea id="prediction-input" placeholder="Enter input data for prediction..."></textarea>
|
||||
</div>
|
||||
|
||||
<button onclick="this.runPrediction()" class="neural-btn primary">
|
||||
🔮 Run Prediction
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="prediction-results">
|
||||
<h3>📊 Prediction Results</h3>
|
||||
<div id="prediction-output" class="results-display">
|
||||
<div class="no-results">No predictions yet</div>
|
||||
</div>
|
||||
|
||||
<div class="confidence-display">
|
||||
<h4>🎯 Confidence Score</h4>
|
||||
<div id="confidence-bar" class="confidence-bar">
|
||||
<div class="confidence-fill" style="width: 0%"></div>
|
||||
<span class="confidence-text">0%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="prediction-history">
|
||||
<h3>📋 Recent Predictions</h3>
|
||||
<div id="prediction-history-list" class="history-list">
|
||||
<!-- Prediction history will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
createPatternsTab() {
|
||||
return `
|
||||
<div class="neural-patterns">
|
||||
<div class="pattern-analysis">
|
||||
<h3>🎯 Pattern Analysis</h3>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Analysis Type:</label>
|
||||
<select id="analysis-type">
|
||||
<option value="analyze">Analyze</option>
|
||||
<option value="learn">Learn</option>
|
||||
<option value="predict">Predict</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Operation:</label>
|
||||
<input type="text" id="pattern-operation" placeholder="Describe the operation...">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Outcome:</label>
|
||||
<input type="text" id="pattern-outcome" placeholder="Expected or actual outcome...">
|
||||
</div>
|
||||
|
||||
<button onclick="this.analyzePattern()" class="neural-btn primary">
|
||||
🎯 Analyze Pattern
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="pattern-results">
|
||||
<h3>📊 Pattern Insights</h3>
|
||||
<div id="pattern-insights" class="insights-display">
|
||||
<div class="no-insights">No pattern analysis yet</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cognitive-analysis">
|
||||
<h3>🧠 Cognitive Analysis</h3>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Behavior to Analyze:</label>
|
||||
<textarea id="behavior-input" placeholder="Describe the behavior or process to analyze..."></textarea>
|
||||
</div>
|
||||
|
||||
<button onclick="this.analyzeCognitive()" class="neural-btn secondary">
|
||||
🧠 Analyze Behavior
|
||||
</button>
|
||||
|
||||
<div id="cognitive-results" class="cognitive-display">
|
||||
<!-- Cognitive analysis results will appear here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
createModelsTab() {
|
||||
return `
|
||||
<div class="neural-models">
|
||||
<div class="model-management">
|
||||
<h3>💾 Model Management</h3>
|
||||
|
||||
<div class="model-actions">
|
||||
<button onclick="this.loadModel()" class="neural-btn primary">
|
||||
📥 Load Model
|
||||
</button>
|
||||
<button onclick="this.saveCurrentModel()" class="neural-btn secondary">
|
||||
💾 Save Model
|
||||
</button>
|
||||
<button onclick="this.createEnsemble()" class="neural-btn secondary">
|
||||
🔗 Create Ensemble
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="model-list">
|
||||
<h3>📋 Available Models</h3>
|
||||
<div id="models-list" class="models-grid">
|
||||
<!-- Model cards will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="model-operations">
|
||||
<h3>🔧 Model Operations</h3>
|
||||
|
||||
<div class="operation-grid">
|
||||
<div class="operation-card">
|
||||
<h4>🗜️ Compress Model</h4>
|
||||
<p>Reduce model size for faster inference</p>
|
||||
<button onclick="this.compressModel()" class="neural-btn">Compress</button>
|
||||
</div>
|
||||
|
||||
<div class="operation-card">
|
||||
<h4>🔄 Transfer Learning</h4>
|
||||
<p>Adapt model to new domain</p>
|
||||
<button onclick="this.transferLearn()" class="neural-btn">Transfer</button>
|
||||
</div>
|
||||
|
||||
<div class="operation-card">
|
||||
<h4>📊 Model Explain</h4>
|
||||
<p>Get AI explainability insights</p>
|
||||
<button onclick="this.explainModel()" class="neural-btn">Explain</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
createOptimizationTab() {
|
||||
return `
|
||||
<div class="neural-optimization">
|
||||
<div class="wasm-optimization">
|
||||
<h3>🚀 WASM SIMD Optimization</h3>
|
||||
|
||||
<div class="optimization-status">
|
||||
<div id="wasm-status" class="status-card">
|
||||
<div class="status-icon">🚀</div>
|
||||
<div class="status-text">Checking WASM status...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="optimization-controls">
|
||||
<button onclick="this.optimizeWasm()" class="neural-btn primary">
|
||||
⚡ Optimize WASM
|
||||
</button>
|
||||
<button onclick="this.checkWasmStatus()" class="neural-btn secondary">
|
||||
📊 Check Status
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="inference-optimization">
|
||||
<h3>🔮 Inference Optimization</h3>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Model for Inference:</label>
|
||||
<select id="inference-model">
|
||||
<option value="">Select model...</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Test Data:</label>
|
||||
<textarea id="inference-data" placeholder="Enter test data array..."></textarea>
|
||||
</div>
|
||||
|
||||
<button onclick="this.runInference()" class="neural-btn primary">
|
||||
🔮 Run Inference
|
||||
</button>
|
||||
|
||||
<div id="inference-results" class="inference-display">
|
||||
<!-- Inference results will appear here -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="performance-metrics">
|
||||
<h3>📈 Performance Metrics</h3>
|
||||
|
||||
<div class="metrics-grid">
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Inference Speed</div>
|
||||
<div id="inference-speed" class="metric-value">-- ms</div>
|
||||
</div>
|
||||
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Memory Usage</div>
|
||||
<div id="memory-usage" class="metric-value">-- MB</div>
|
||||
</div>
|
||||
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">WASM Speedup</div>
|
||||
<div id="wasm-speedup" class="metric-value">--x</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
createFallbackInterface() {
|
||||
this.container.innerHTML = `
|
||||
<div class="neural-network-fallback">
|
||||
<h2>🧠 Neural Network Operations</h2>
|
||||
<p>Advanced neural network interface with 15 integrated tools</p>
|
||||
|
||||
<div class="tool-sections">
|
||||
<div class="tool-section">
|
||||
<h3>🧠 Training & Models</h3>
|
||||
<button onclick="this.quickAction('neural_train')">Train Neural Network</button>
|
||||
<button onclick="this.quickAction('neural_status')">Check Status</button>
|
||||
<button onclick="this.quickAction('model_save')">Save Model</button>
|
||||
<button onclick="this.quickAction('model_load')">Load Model</button>
|
||||
</div>
|
||||
|
||||
<div class="tool-section">
|
||||
<h3>🔮 Prediction & Analysis</h3>
|
||||
<button onclick="this.quickAction('neural_predict')">Make Prediction</button>
|
||||
<button onclick="this.quickAction('neural_patterns')">Analyze Patterns</button>
|
||||
<button onclick="this.quickAction('cognitive_analyze')">Cognitive Analysis</button>
|
||||
<button onclick="this.quickAction('pattern_recognize')">Pattern Recognition</button>
|
||||
</div>
|
||||
|
||||
<div class="tool-section">
|
||||
<h3>⚡ Optimization</h3>
|
||||
<button onclick="this.quickAction('wasm_optimize')">WASM Optimization</button>
|
||||
<button onclick="this.quickAction('neural_compress')">Compress Model</button>
|
||||
<button onclick="this.quickAction('inference_run')">Run Inference</button>
|
||||
<button onclick="this.quickAction('neural_explain')">Explain Model</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="neural-output" class="output-area">
|
||||
<h3>📊 Output</h3>
|
||||
<pre id="output-content">Ready for neural operations...</pre>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
renderTerminalMode(params) {
|
||||
console.log('\n🧠 Neural Network Operations');
|
||||
console.log('═'.repeat(50));
|
||||
console.log('Available Tools (15):');
|
||||
console.log(' 🧠 neural_train - Train neural patterns');
|
||||
console.log(' 🔮 neural_predict - Make AI predictions');
|
||||
console.log(' 📊 neural_status - Check model status');
|
||||
console.log(' 🎯 neural_patterns - Analyze patterns');
|
||||
console.log(' 💾 model_save - Save trained models');
|
||||
console.log(' 📥 model_load - Load models');
|
||||
console.log(' 🎯 pattern_recognize- Pattern recognition');
|
||||
console.log(' 🧠 cognitive_analyze- Behavior analysis');
|
||||
console.log(' 🔄 learning_adapt - Adaptive learning');
|
||||
console.log(' 🗜️ neural_compress - Model compression');
|
||||
console.log(' 🔗 ensemble_create - Model ensembles');
|
||||
console.log(' 🔄 transfer_learn - Transfer learning');
|
||||
console.log(' 📊 neural_explain - AI explainability');
|
||||
console.log(' 🚀 wasm_optimize - WASM optimization');
|
||||
console.log(' 🔮 inference_run - Neural inference');
|
||||
console.log('═'.repeat(50));
|
||||
if (params.tool) {
|
||||
console.log(`\n🔧 Executing: ${params.tool}`);
|
||||
this.quickAction(params.tool, params);
|
||||
}
|
||||
}
|
||||
async quickAction(toolName, params = {}) {
|
||||
try {
|
||||
console.log(`🔧 Executing ${toolName}...`);
|
||||
this.eventBus.emit('tool:execute', {
|
||||
tool: toolName,
|
||||
params: params,
|
||||
source: 'neural-view'
|
||||
});
|
||||
switch(toolName){
|
||||
case 'neural_train':
|
||||
await this.handleTraining(params);
|
||||
break;
|
||||
case 'neural_predict':
|
||||
await this.handlePrediction(params);
|
||||
break;
|
||||
case 'neural_patterns':
|
||||
await this.handlePatternAnalysis(params);
|
||||
break;
|
||||
default:
|
||||
console.log(`Tool ${toolName} executed`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`❌ Error executing ${toolName}:`, error);
|
||||
}
|
||||
}
|
||||
async handleTraining(params) {
|
||||
const trainingParams = {
|
||||
pattern_type: params.pattern_type || 'coordination',
|
||||
training_data: params.training_data || 'sample_data',
|
||||
epochs: params.epochs || 50
|
||||
};
|
||||
console.log('🧠 Training neural network with parameters:', trainingParams);
|
||||
if (this.container) {
|
||||
const statusEl = document.getElementById('training-status');
|
||||
if (statusEl) {
|
||||
statusEl.innerHTML = '<div class="status-training">Training in progress...</div>';
|
||||
}
|
||||
}
|
||||
}
|
||||
async handlePrediction(params) {
|
||||
const predictionParams = {
|
||||
modelId: params.modelId || 'default_model',
|
||||
input: params.input || 'sample_input'
|
||||
};
|
||||
console.log('🔮 Running prediction with parameters:', predictionParams);
|
||||
if (this.container) {
|
||||
const outputEl = document.getElementById('prediction-output');
|
||||
if (outputEl) {
|
||||
outputEl.innerHTML = '<div class="prediction-result">Prediction in progress...</div>';
|
||||
}
|
||||
}
|
||||
}
|
||||
async handlePatternAnalysis(params) {
|
||||
const analysisParams = {
|
||||
action: params.action || 'analyze',
|
||||
operation: params.operation || 'sample_operation',
|
||||
outcome: params.outcome || 'sample_outcome'
|
||||
};
|
||||
console.log('🎯 Analyzing patterns with parameters:', analysisParams);
|
||||
if (this.container) {
|
||||
const insightsEl = document.getElementById('pattern-insights');
|
||||
if (insightsEl) {
|
||||
insightsEl.innerHTML = '<div class="analysis-result">Pattern analysis in progress...</div>';
|
||||
}
|
||||
}
|
||||
}
|
||||
setupEventHandlers() {
|
||||
this.eventBus.on('tool:executed', (data)=>{
|
||||
if (data.source === 'neural-view') {
|
||||
this.handleToolResult(data);
|
||||
}
|
||||
});
|
||||
this.eventBus.on('ui:real-time:update', ()=>{
|
||||
this.updateStats();
|
||||
});
|
||||
this.eventBus.on('ui:theme:changed', (theme)=>{
|
||||
this.updateTheme(theme);
|
||||
});
|
||||
}
|
||||
handleToolResult(data) {
|
||||
console.log(`✅ Tool ${data.tool} completed:`, data.result);
|
||||
if (this.container) {
|
||||
this.updateUIWithResult(data.tool, data.result);
|
||||
}
|
||||
}
|
||||
updateUIWithResult(toolName, result) {
|
||||
switch(toolName){
|
||||
case 'neural_train':
|
||||
this.updateTrainingResults(result);
|
||||
break;
|
||||
case 'neural_predict':
|
||||
this.updatePredictionResults(result);
|
||||
break;
|
||||
case 'neural_patterns':
|
||||
this.updatePatternResults(result);
|
||||
break;
|
||||
}
|
||||
}
|
||||
updateTrainingResults(result) {
|
||||
const statusEl = document.getElementById('training-status');
|
||||
if (statusEl) {
|
||||
statusEl.innerHTML = `
|
||||
<div class="status-complete">
|
||||
✅ Training completed!
|
||||
<div class="training-metrics">
|
||||
<div>Epochs: ${result.epochs}</div>
|
||||
<div>Accuracy: ${result.accuracy}</div>
|
||||
<div>Loss: ${result.loss}</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
updatePredictionResults(result) {
|
||||
const outputEl = document.getElementById('prediction-output');
|
||||
if (outputEl) {
|
||||
outputEl.innerHTML = `
|
||||
<div class="prediction-complete">
|
||||
<div class="prediction-value">${result.prediction}</div>
|
||||
<div class="prediction-confidence">Confidence: ${result.confidence}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
const confidenceBar = document.querySelector('.confidence-fill');
|
||||
const confidenceText = document.querySelector('.confidence-text');
|
||||
if (confidenceBar && confidenceText) {
|
||||
const confidence = Math.round(result.confidence * 100);
|
||||
confidenceBar.style.width = `${confidence}%`;
|
||||
confidenceText.textContent = `${confidence}%`;
|
||||
}
|
||||
}
|
||||
updatePatternResults(result) {
|
||||
const insightsEl = document.getElementById('pattern-insights');
|
||||
if (insightsEl) {
|
||||
insightsEl.innerHTML = `
|
||||
<div class="insights-complete">
|
||||
<div class="insights-title">Pattern Analysis Complete</div>
|
||||
<div class="insights-content">${result.insights}</div>
|
||||
<div class="patterns-found">
|
||||
Patterns: ${result.patterns ? result.patterns.join(', ') : 'None'}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
updateStats() {
|
||||
const modelsStatEl = document.getElementById('models-stat');
|
||||
if (modelsStatEl) {
|
||||
const valueEl = modelsStatEl.querySelector('.stat-value');
|
||||
if (valueEl) valueEl.textContent = this.models.size;
|
||||
}
|
||||
const trainingStatEl = document.getElementById('training-stat');
|
||||
if (trainingStatEl) {
|
||||
const valueEl = trainingStatEl.querySelector('.stat-value');
|
||||
if (valueEl) valueEl.textContent = this.trainingJobs.size;
|
||||
}
|
||||
}
|
||||
updateTheme(theme) {
|
||||
if (this.container) {
|
||||
this.container.classList.remove('theme-dark', 'theme-light');
|
||||
this.container.classList.add(`theme-${theme}`);
|
||||
}
|
||||
}
|
||||
destroy() {
|
||||
console.log('🧠 Neural Network View destroyed');
|
||||
}
|
||||
}
|
||||
if (typeof document !== 'undefined') {
|
||||
const neuralStyles = document.createElement('style');
|
||||
neuralStyles.textContent = `
|
||||
.neural-overview {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 16px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: #2a2a2a;
|
||||
padding: 16px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #444;
|
||||
}
|
||||
|
||||
.stat-icon {
|
||||
font-size: 24px;
|
||||
margin-right: 12px;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
color: #00d4ff;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.neural-tools {
|
||||
margin: 24px 0;
|
||||
}
|
||||
|
||||
.tool-buttons {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.neural-btn {
|
||||
padding: 10px 16px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-weight: 500;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.neural-btn.primary {
|
||||
background: #00d4ff;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.neural-btn.primary:hover {
|
||||
background: #00b8e6;
|
||||
}
|
||||
|
||||
.neural-btn.secondary {
|
||||
background: #444;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.neural-btn.secondary:hover {
|
||||
background: #555;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
color: #fff;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.form-group input,
|
||||
.form-group select,
|
||||
.form-group textarea {
|
||||
width: 100%;
|
||||
padding: 8px 12px;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 4px;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.form-group textarea {
|
||||
height: 100px;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.confidence-bar {
|
||||
position: relative;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 4px;
|
||||
height: 24px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.confidence-fill {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #00d4ff, #0099cc);
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.confidence-text {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
color: #fff;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.operation-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.operation-card {
|
||||
background: #2a2a2a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.operation-card h4 {
|
||||
margin: 0 0 8px 0;
|
||||
color: #00d4ff;
|
||||
}
|
||||
|
||||
.operation-card p {
|
||||
margin: 0 0 12px 0;
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(neuralStyles);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=NeuralNetworkView.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/web-ui/views/NeuralNetworkView.js"],"sourcesContent":["/**\n * Neural Network View - Interface for neural network operations\n * Handles training, prediction, pattern analysis, and model management\n */\n\nexport default class NeuralNetworkView {\n constructor(container, eventBus, viewConfig) {\n this.container = container;\n this.eventBus = eventBus;\n this.viewConfig = viewConfig;\n this.componentLibrary = null;\n this.models = new Map();\n this.trainingJobs = new Map();\n this.currentTab = 'overview';\n this.isInitialized = false;\n }\n\n /**\n * Initialize the neural network view\n */\n async initialize() {\n if (this.isInitialized) return;\n\n // Get component library from event bus\n this.eventBus.emit('component-library:get', (library) => {\n this.componentLibrary = library;\n });\n\n // Setup event handlers\n this.setupEventHandlers();\n\n this.isInitialized = true;\n }\n\n /**\n * Render the view with given parameters\n */\n async render(params = {}) {\n if (!this.isInitialized) {\n await this.initialize();\n }\n\n // Clear container\n if (this.container) {\n this.container.innerHTML = '';\n this.createNeuralNetworkInterface();\n } else {\n // Terminal mode\n this.renderTerminalMode(params);\n }\n }\n\n /**\n * Create neural network interface for browser\n */\n createNeuralNetworkInterface() {\n // Create tab container\n const tabs = [\n { label: '📊 Overview', content: this.createOverviewTab() },\n { label: '🧠 Training', content: this.createTrainingTab() },\n { label: '🔮 Prediction', content: this.createPredictionTab() },\n { label: '🎯 Patterns', content: this.createPatternsTab() },\n { label: '💾 Models', content: this.createModelsTab() },\n { label: '⚡ Optimization', content: this.createOptimizationTab() },\n ];\n\n if (this.componentLibrary) {\n const tabContainer = this.componentLibrary.getComponent('TabContainer')(tabs);\n this.container.appendChild(tabContainer.element);\n } else {\n // Fallback without component library\n this.createFallbackInterface();\n }\n }\n\n /**\n * Create overview tab content\n */\n createOverviewTab() {\n return `\n <div class=\"neural-overview\">\n <div class=\"stats-grid\">\n <div id=\"models-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">🧠</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0</div>\n <div class=\"stat-label\">Models</div>\n </div>\n </div>\n <div id=\"training-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">⚡</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0</div>\n <div class=\"stat-label\">Training Jobs</div>\n </div>\n </div>\n <div id=\"accuracy-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">🎯</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">--</div>\n <div class=\"stat-label\">Avg Accuracy</div>\n </div>\n </div>\n <div id=\"wasm-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">🚀</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">--</div>\n <div class=\"stat-label\">WASM Status</div>\n </div>\n </div>\n </div>\n \n <div class=\"neural-tools\">\n <h3>🔧 Quick Actions</h3>\n <div class=\"tool-buttons\">\n <button onclick=\"this.startQuickTrain()\" class=\"neural-btn primary\">\n 🧠 Quick Train\n </button>\n <button onclick=\"this.checkModels()\" class=\"neural-btn secondary\">\n 📋 List Models\n </button>\n <button onclick=\"this.runPrediction()\" class=\"neural-btn secondary\">\n 🔮 Test Prediction\n </button>\n <button onclick=\"this.analyzePatterns()\" class=\"neural-btn secondary\">\n 🎯 Analyze Patterns\n </button>\n </div>\n </div>\n\n <div class=\"recent-activity\">\n <h3>📈 Recent Activity</h3>\n <div id=\"activity-log\" class=\"activity-list\">\n <div class=\"activity-item\">\n <span class=\"activity-time\">--:--</span>\n <span class=\"activity-desc\">No recent activity</span>\n </div>\n </div>\n </div>\n </div>\n `;\n }\n\n /**\n * Create training tab content\n */\n createTrainingTab() {\n return `\n <div class=\"neural-training\">\n <div class=\"training-form\">\n <h3>🧠 Neural Network Training</h3>\n \n <div class=\"forLine truncated
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["../../../../../src/ui/web-ui/views/WorkflowAutomationView.js"],"sourcesContent":["/**\n * Workflow & Automation View - Interface for workflow and automation tools\n * Handles workflow creation, automation rules, pipelines, scheduling, and SPARC modes\n */\n\nclass WorkflowAutomationView {\n constructor(container, eventBus, viewConfig) {\n this.container = container;\n this.eventBus = eventBus;\n this.viewConfig = viewConfig;\n this.componentLibrary = null;\n this.workflows = new Map();\n this.pipelines = new Map();\n this.automationRules = new Map();\n this.scheduledTasks = new Map();\n this.currentTab = 'overview';\n this.isInitialized = false;\n this.draggedElement = null;\n this.dropZones = new Set();\n }\n\n /**\n * Initialize the workflow & automation view\n */\n async initialize() {\n if (this.isInitialized) return;\n\n // Get component library from event bus\n this.eventBus.emit('component-library:get', (library) => {\n this.componentLibrary = library;\n });\n\n // Setup event handlers\n this.setupEventHandlers();\n\n this.isInitialized = true;\n }\n\n /**\n * Render the view with given parameters\n */\n async render(params = {}) {\n if (!this.isInitialized) {\n await this.initialize();\n }\n\n // Clear container\n if (this.container) {\n this.container.innerHTML = '';\n this.createWorkflowInterface();\n } else {\n // Terminal mode\n this.renderTerminalMode(params);\n }\n }\n\n /**\n * Create workflow interface for browser\n */\n createWorkflowInterface() {\n // Create tab container\n const tabs = [\n { label: '📊 Overview', content: this.createOverviewTab() },\n { label: '🔄 Workflows', content: this.createWorkflowsTab() },\n { label: '⚡ Automation', content: this.createAutomationTab() },\n { label: '🚀 Pipelines', content: this.createPipelinesTab() },\n { label: '📅 Scheduler', content: this.createSchedulerTab() },\n { label: '🎯 SPARC Modes', content: this.createSparcModesTab() },\n { label: '📦 Batch & Parallel', content: this.createBatchTab() },\n ];\n\n if (this.componentLibrary) {\n const tabContainer = this.componentLibrary.getComponent('TabContainer')(tabs);\n this.container.appendChild(tabContainer.element);\n } else {\n // Fallback without component library\n this.createFallbackInterface();\n }\n }\n\n /**\n * Create overview tab content\n */\n createOverviewTab() {\n return `\n <div class=\"workflow-overview\">\n <div class=\"stats-grid\">\n <div id=\"workflows-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">🔄</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0</div>\n <div class=\"stat-label\">Active Workflows</div>\n </div>\n </div>\n <div id=\"pipelines-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">🚀</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0</div>\n <div class=\"stat-label\">Running Pipelines</div>\n </div>\n </div>\n <div id=\"rules-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">⚡</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0</div>\n <div class=\"stat-label\">Automation Rules</div>\n </div>\n </div>\n <div id=\"scheduled-stat\" class=\"stat-card\">\n <div class=\"stat-icon\">📅</div>\n <div class=\"stat-content\">\n <div class=\"stat-value\">0</div>\n <div class=\"stat-label\">Scheduled Tasks</div>\n </div>\n </div>\n </div>\n \n <div class=\"workflow-tools\">\n <h3>🔧 Quick Actions</h3>\n <div class=\"tool-buttons\">\n <button onclick=\"this.createNewWorkflow()\" class=\"workflow-btn primary\">\n 🔄 Create Workflow\n </button>\n <button onclick=\"this.setupAutomation()\" class=\"workflow-btn secondary\">\n ⚡ Setup Automation\n </button>\n <button onclick=\"this.createPipeline()\" class=\"workflow-btn secondary\">\n 🚀 New Pipeline\n </button>\n <button onclick=\"this.runSparcMode()\" class=\"workflow-btn secondary\">\n 🎯 Run SPARC Mode\n </button>\n </div>\n </div>\n\n <div class=\"recent-activity\">\n <h3>📈 Recent Activity</h3>\n <div id=\"workflow-activity-log\" class=\"activity-list\">\n <div class=\"activity-item\">\n <span class=\"activity-time\">--:--</span>\n <span class=\"activity-desc\">No recent activity</span>\n </div>\n </div>\n Line truncated
|
||||
@@ -1,13 +1,11 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import * as fs from 'fs/promises';
|
||||
import * as path from 'path';
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
const execAsync = promisify(exec);
|
||||
let MetricsReader = class MetricsReader {
|
||||
constructor(){
|
||||
this.metricsDir = '.claude-flow/metrics';
|
||||
this.sessionsDir = '.claude-flow/sessions';
|
||||
}
|
||||
export class MetricsReader {
|
||||
metricsDir = '.claude-flow/metrics';
|
||||
sessionsDir = '.claude-flow/sessions';
|
||||
async getSystemMetrics() {
|
||||
try {
|
||||
const filePath = path.join(this.metricsDir, 'system-metrics.json');
|
||||
@@ -18,15 +16,6 @@ let MetricsReader = class MetricsReader {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
async getTaskQueue() {
|
||||
try {
|
||||
const queueFile = '.claude-flow/tasks/queue.json';
|
||||
const content = await fs.readFile(queueFile, 'utf8');
|
||||
return JSON.parse(content);
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
async getTaskMetrics() {
|
||||
try {
|
||||
const filePath = path.join(this.metricsDir, 'task-metrics.json');
|
||||
@@ -47,30 +36,30 @@ let MetricsReader = class MetricsReader {
|
||||
}
|
||||
async getActiveAgents() {
|
||||
try {
|
||||
const perfMetrics = await this.getPerformanceMetrics();
|
||||
const sessionFiles = await this.getSessionFiles();
|
||||
const agents = [];
|
||||
const agentsDir = '.claude-flow/agents';
|
||||
try {
|
||||
const agentFiles = await fs.readdir(agentsDir);
|
||||
for (const file of agentFiles){
|
||||
if (file.endsWith('.json')) {
|
||||
try {
|
||||
const content = await fs.readFile(path.join(agentsDir, file), 'utf8');
|
||||
const agent = JSON.parse(content);
|
||||
agents.push(agent);
|
||||
} catch {}
|
||||
for (const file of sessionFiles){
|
||||
try {
|
||||
const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');
|
||||
const sessionData = JSON.parse(content);
|
||||
if (sessionData.agents && Array.isArray(sessionData.agents)) {
|
||||
agents.push(...sessionData.agents);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
if (agents.length === 0) {
|
||||
const sessionFiles = await this.getSessionFiles();
|
||||
for (const file of sessionFiles){
|
||||
try {
|
||||
const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');
|
||||
const sessionData = JSON.parse(content);
|
||||
if (sessionData.agents && Array.isArray(sessionData.agents)) {
|
||||
agents.push(...sessionData.agents);
|
||||
}
|
||||
} catch {}
|
||||
} catch {}
|
||||
}
|
||||
if (agents.length === 0 && perfMetrics) {
|
||||
const activeCount = perfMetrics.activeAgents || 0;
|
||||
const totalCount = perfMetrics.totalAgents || 0;
|
||||
for(let i = 0; i < totalCount; i++){
|
||||
agents.push({
|
||||
id: `agent-${i + 1}`,
|
||||
name: `Agent ${i + 1}`,
|
||||
type: i === 0 ? 'orchestrator' : 'worker',
|
||||
status: i < activeCount ? 'active' : 'idle',
|
||||
activeTasks: i < activeCount ? 1 : 0,
|
||||
lastActivity: Date.now() - i * 1000
|
||||
});
|
||||
}
|
||||
}
|
||||
return agents;
|
||||
@@ -146,7 +135,7 @@ let MetricsReader = class MetricsReader {
|
||||
}
|
||||
async getMCPServerStatus() {
|
||||
try {
|
||||
const { stdout } = await execAsync('ps aux | grep -E "mcp" | grep -v grep | wc -l');
|
||||
const { stdout } = await execAsync('ps aux | grep -E "mcp-server\\.js|claude-flow mcp start" | grep -v grep | wc -l');
|
||||
const processCount = parseInt(stdout.trim(), 10);
|
||||
const { stdout: orchestratorOut } = await execAsync('ps aux | grep -E "claude-flow start" | grep -v grep | wc -l');
|
||||
const orchestratorRunning = parseInt(orchestratorOut.trim(), 10) > 0;
|
||||
@@ -175,6 +164,15 @@ let MetricsReader = class MetricsReader {
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=metrics-reader.js.map processCount: 0,
|
||||
orchestratorRunning: false,
|
||||
port: null,
|
||||
connections: 0
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
export { MetricsReader };
|
||||
|
||||
|
||||
@@ -1,389 +0,0 @@
|
||||
# Analysis & Monitoring Tools - Claude Flow Web UI
|
||||
|
||||
**Agent 2 - Analysis & Monitoring Tools Developer**
|
||||
|
||||
## Overview
|
||||
|
||||
This implementation provides a comprehensive suite of 13 analysis and monitoring tools for the Claude Flow Web UI, featuring real-time dashboards, interactive visualizations, and export capabilities.
|
||||
|
||||
## 🛠️ Implemented Tools
|
||||
|
||||
### 1. Performance Report (`performance_report`)
|
||||
|
||||
- **Purpose**: Generate comprehensive performance metrics and reports
|
||||
- **Features**: Response time tracking, throughput analysis, error rate monitoring
|
||||
- **API Endpoint**: `/api/analysis/performance-report`
|
||||
|
||||
### 2. Bottleneck Analysis (`bottleneck_analyze`)
|
||||
|
||||
- **Purpose**: Detect and analyze system bottlenecks
|
||||
- **Features**: Component analysis, severity assessment, impact evaluation
|
||||
- **API Endpoint**: `/api/analysis/bottleneck-analyze`
|
||||
|
||||
### 3. Token Usage (`token_usage`)
|
||||
|
||||
- **Purpose**: Track and analyze token consumption patterns
|
||||
- **Features**: Cost analysis, efficiency metrics, usage trends
|
||||
- **API Endpoint**: `/api/analysis/token-usage`
|
||||
|
||||
### 4. Benchmark Run (`benchmark_run`)
|
||||
|
||||
- **Purpose**: Execute performance benchmarks and comparisons
|
||||
- **Features**: Multi-metric benchmarking, baseline comparisons, scoring
|
||||
- **API Endpoint**: `/api/analysis/benchmark-run`
|
||||
|
||||
### 5. Metrics Collection (`metrics_collect`)
|
||||
|
||||
- **Purpose**: Collect comprehensive system metrics
|
||||
- **Features**: System info, resource usage, performance indicators
|
||||
- **API Endpoint**: `/api/analysis/metrics-collect`
|
||||
|
||||
### 6. Trend Analysis (`trend_analysis`)
|
||||
|
||||
- **Purpose**: Detect trends and forecast future patterns
|
||||
- **Features**: Performance trends, usage patterns, predictions
|
||||
- **API Endpoint**: `/api/analysis/trend-analysis`
|
||||
|
||||
### 7. Cost Analysis (`cost_analysis`)
|
||||
|
||||
- **Purpose**: Analyze resource costs and optimization opportunities
|
||||
- **Features**: Cost breakdown, trend analysis, optimization recommendations
|
||||
- **API Endpoint**: `/api/analysis/cost-analysis`
|
||||
|
||||
### 8. Quality Assessment (`quality_assess`)
|
||||
|
||||
- **Purpose**: Assess system quality across multiple dimensions
|
||||
- **Features**: Performance, reliability, security, maintainability metrics
|
||||
- **API Endpoint**: `/api/analysis/quality-assess`
|
||||
|
||||
### 9. Error Analysis (`error_analysis`)
|
||||
|
||||
- **Purpose**: Analyze error patterns and provide resolution guidance
|
||||
- **Features**: Error categorization, pattern identification, resolution recommendations
|
||||
- **API Endpoint**: `/api/analysis/error-analysis`
|
||||
|
||||
### 10. Usage Statistics (`usage_stats`)
|
||||
|
||||
- **Purpose**: Generate comprehensive usage statistics and insights
|
||||
- **Features**: User analytics, session analysis, feature usage tracking
|
||||
- **API Endpoint**: `/api/analysis/usage-stats`
|
||||
|
||||
### 11. Health Check (`health_check`)
|
||||
|
||||
- **Purpose**: Monitor system health across all components
|
||||
- **Features**: Component health scoring, alert generation, status monitoring
|
||||
- **API Endpoint**: `/api/analysis/health-check`
|
||||
|
||||
### 12. Load Monitor (`load_monitor`)
|
||||
|
||||
- **Purpose**: Monitor system load and generate alerts
|
||||
- **Features**: Real-time load tracking, trend analysis, alert generation
|
||||
- **API Endpoint**: `/api/analysis/load-monitor`
|
||||
|
||||
### 13. Capacity Planning (`capacity_plan`)
|
||||
|
||||
- **Purpose**: Plan future capacity requirements
|
||||
- **Features**: Resource projections, timeline planning, scaling recommendations
|
||||
- **API Endpoint**: `/api/analysis/capacity-plan`
|
||||
|
||||
## 📊 Dashboard Features
|
||||
|
||||
### 4-Tab Interface
|
||||
|
||||
1. **Metrics**: Real-time performance and token usage metrics
|
||||
2. **Reports**: Report generation and export functionality
|
||||
3. **Analysis**: Advanced analysis tools and visualizations
|
||||
4. **Health**: System health monitoring and alerts
|
||||
|
||||
### Interactive Charts
|
||||
|
||||
- **Performance Chart**: Line chart showing response time and throughput trends
|
||||
- **Token Usage Chart**: Doughnut chart displaying token distribution
|
||||
- **System Health Chart**: Radar chart showing component health scores
|
||||
- **Load Monitor Chart**: Bar chart tracking system load over time
|
||||
|
||||
### Real-time Features
|
||||
|
||||
- **WebSocket Integration**: Live data updates every 5 seconds
|
||||
- **Connection Status**: Visual indicator of WebSocket connection state
|
||||
- **Auto-refresh**: Automatic data refresh with manual refresh options
|
||||
- **Live Alerts**: Real-time system alerts and notifications
|
||||
|
||||
## 🔧 Technical Implementation
|
||||
|
||||
### Frontend Components
|
||||
|
||||
- **JavaScript**: `/src/ui/console/js/analysis-tools.js`
|
||||
- **CSS**: `/src/ui/console/styles/analysis-tools.css`
|
||||
- **HTML**: `/src/ui/console/analysis-tools.html`
|
||||
|
||||
### Backend API
|
||||
|
||||
- **Router**: `/src/api/routes/analysis.js`
|
||||
- **WebSocket**: Real-time data streaming
|
||||
- **Metrics Storage**: In-memory storage with database integration ready
|
||||
|
||||
### Key Features
|
||||
|
||||
- **Responsive Design**: Mobile-friendly interface
|
||||
- **Export Functionality**: JSON and CSV export options
|
||||
- **Dark Mode Support**: Automatic dark theme detection
|
||||
- **Print Styles**: Print-optimized layouts
|
||||
- **Error Handling**: Comprehensive error handling and user feedback
|
||||
|
||||
## 🚀 Getting Started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 16+
|
||||
- Express.js server
|
||||
- Chart.js library
|
||||
- WebSocket support
|
||||
|
||||
### Installation
|
||||
|
||||
1. Copy the files to your Claude Flow project
|
||||
2. Install dependencies:
|
||||
```bash
|
||||
npm install express ws chart.js
|
||||
```
|
||||
|
||||
### Integration
|
||||
|
||||
1. Add the analysis router to your Express app:
|
||||
|
||||
```javascript
|
||||
const analysisRouter = require('./src/api/routes/analysis');
|
||||
app.use('/api/analysis', analysisRouter);
|
||||
```
|
||||
|
||||
2. Include the CSS and JavaScript files in your HTML:
|
||||
```html
|
||||
<link rel="stylesheet" href="styles/analysis-tools.css" />
|
||||
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
|
||||
<script src="js/analysis-tools.js"></script>
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
1. Navigate to `/analysis-tools.html` in your browser
|
||||
2. Use the tab navigation to switch between different views
|
||||
3. Click tool buttons to execute analysis functions
|
||||
4. Export data using the export buttons
|
||||
5. Monitor real-time updates through the WebSocket connection
|
||||
|
||||
## 📈 Data Flow
|
||||
|
||||
### Real-time Metrics
|
||||
|
||||
1. **Collection**: Server collects metrics from various sources
|
||||
2. **Processing**: Metrics are processed and stored in memory
|
||||
3. **Broadcasting**: WebSocket broadcasts updates to connected clients
|
||||
4. **Visualization**: Charts update automatically with new data
|
||||
|
||||
### Tool Execution
|
||||
|
||||
1. **Request**: User clicks tool button in UI
|
||||
2. **API Call**: Frontend makes HTTP request to analysis API
|
||||
3. **Processing**: Backend processes request and generates results
|
||||
4. **Response**: Results are returned and displayed in UI
|
||||
5. **Notification**: Swarm coordination hooks are triggered
|
||||
|
||||
## 🔍 Monitoring & Alerts
|
||||
|
||||
### Health Monitoring
|
||||
|
||||
- **Component Health**: CPU, Memory, Disk, Network, API, Database
|
||||
- **Health Scores**: 0-100 scale with color-coded indicators
|
||||
- **Alert Thresholds**: Configurable warning and critical levels
|
||||
|
||||
### Performance Monitoring
|
||||
|
||||
- **Response Time**: Average, min, max response times
|
||||
- **Throughput**: Requests per second/minute
|
||||
- **Error Rate**: Percentage of failed requests
|
||||
- **Uptime**: System availability metrics
|
||||
|
||||
### Alert System
|
||||
|
||||
- **Real-time Alerts**: Immediate notification of issues
|
||||
- **Severity Levels**: Info, Warning, Critical
|
||||
- **Auto-dismiss**: Configurable auto-dismiss for info alerts
|
||||
- **Alert History**: Persistent alert logging
|
||||
|
||||
## 📊 Export & Reporting
|
||||
|
||||
### Export Formats
|
||||
|
||||
- **JSON**: Complete data export with metadata
|
||||
- **CSV**: Tabular data export for spreadsheet analysis
|
||||
|
||||
### Report Types
|
||||
|
||||
- **Performance Reports**: Comprehensive performance analysis
|
||||
- **Cost Reports**: Resource cost breakdown and optimization
|
||||
- **Quality Reports**: System quality assessment
|
||||
- **Health Reports**: Component health status
|
||||
|
||||
## 🎨 Customization
|
||||
|
||||
### Styling
|
||||
|
||||
- Modify `analysis-tools.css` for custom styling
|
||||
- Responsive breakpoints for different screen sizes
|
||||
- Dark mode support with CSS media queries
|
||||
|
||||
### Configuration
|
||||
|
||||
- Adjust WebSocket update intervals
|
||||
- Configure alert thresholds
|
||||
- Customize chart colors and types
|
||||
|
||||
### Extension
|
||||
|
||||
- Add new analysis tools following the existing pattern
|
||||
- Implement additional chart types using Chart.js
|
||||
- Extend API endpoints for custom metrics
|
||||
|
||||
## 🔒 Security Considerations
|
||||
|
||||
### Data Protection
|
||||
|
||||
- Client-side data validation
|
||||
- Secure WebSocket connections (WSS in production)
|
||||
- API rate limiting implementation ready
|
||||
|
||||
### Error Handling
|
||||
|
||||
- Graceful error handling for failed requests
|
||||
- User-friendly error messages
|
||||
- Automatic retry mechanisms
|
||||
|
||||
## 🚀 Performance Optimization
|
||||
|
||||
### Frontend Optimization
|
||||
|
||||
- Lazy loading of chart components
|
||||
- Efficient data update strategies
|
||||
- Memory management for long-running sessions
|
||||
|
||||
### Backend Optimization
|
||||
|
||||
- Efficient metrics collection
|
||||
- Optimized database queries (when integrated)
|
||||
- Caching strategies for frequently accessed data
|
||||
|
||||
## 📱 Responsive Design
|
||||
|
||||
### Mobile Support
|
||||
|
||||
- Touch-friendly interface
|
||||
- Responsive chart sizing
|
||||
- Optimized navigation for small screens
|
||||
|
||||
### Tablet Support
|
||||
|
||||
- Optimized layout for tablet devices
|
||||
- Touch gestures for chart interaction
|
||||
- Efficient space utilization
|
||||
|
||||
## 🔧 Development & Testing
|
||||
|
||||
### Development Setup
|
||||
|
||||
1. Start the development server
|
||||
2. Open `analysis-tools.html` in browser
|
||||
3. Monitor console for WebSocket connection status
|
||||
4. Test all tool functions and exports
|
||||
|
||||
### Testing Checklist
|
||||
|
||||
- [ ] All 13 tools execute without errors
|
||||
- [ ] WebSocket connection establishes successfully
|
||||
- [ ] Real-time updates work correctly
|
||||
- [ ] Export functions generate valid files
|
||||
- [ ] Responsive design works on all devices
|
||||
- [ ] Charts render and update properly
|
||||
- [ ] Alert system functions correctly
|
||||
|
||||
## 📚 API Documentation
|
||||
|
||||
### Endpoint Structure
|
||||
|
||||
```
|
||||
GET /api/analysis/{tool-name}
|
||||
```
|
||||
|
||||
### Response Format
|
||||
|
||||
```json
|
||||
{
|
||||
"timestamp": 1234567890,
|
||||
"summary": "Tool execution summary",
|
||||
"data": { ... },
|
||||
"recommendations": [...],
|
||||
"alerts": [...]
|
||||
}
|
||||
```
|
||||
|
||||
### WebSocket Messages
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "metrics_update",
|
||||
"payload": {
|
||||
"performance": { ... },
|
||||
"tokens": { ... },
|
||||
"health": { ... },
|
||||
"load": { ... }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
### Adding New Tools
|
||||
|
||||
1. Add tool button to HTML interface
|
||||
2. Implement tool logic in JavaScript
|
||||
3. Create API endpoint in backend router
|
||||
4. Add styling for new components
|
||||
5. Update documentation
|
||||
|
||||
### Code Style
|
||||
|
||||
- Follow existing naming conventions
|
||||
- Use ES6+ features where appropriate
|
||||
- Maintain consistent error handling
|
||||
- Add comprehensive comments
|
||||
|
||||
## 📞 Support
|
||||
|
||||
For issues or questions regarding the Analysis & Monitoring Tools:
|
||||
|
||||
1. Check the console for error messages
|
||||
2. Verify WebSocket connection status
|
||||
3. Ensure all dependencies are installed
|
||||
4. Review API endpoint responses
|
||||
|
||||
## 🔄 Future Enhancements
|
||||
|
||||
### Planned Features
|
||||
|
||||
- Database integration for persistent metrics
|
||||
- Advanced filtering and search capabilities
|
||||
- Custom dashboard creation
|
||||
- Multi-tenant support
|
||||
- Advanced analytics and ML insights
|
||||
|
||||
### Integration Opportunities
|
||||
|
||||
- External monitoring tools
|
||||
- Third-party alert systems
|
||||
- Business intelligence platforms
|
||||
- Custom metric sources
|
||||
|
||||
---
|
||||
|
||||
**Agent 2 - Analysis & Monitoring Tools Developer**
|
||||
_Complete implementation of 13 analysis and monitoring tools with real-time dashboards and WebSocket integration_
|
||||
@@ -1,256 +0,0 @@
|
||||
# Claude Code Web Console
|
||||
|
||||
A modern web-based terminal interface for Claude Code, providing an authentic console experience with real-time communication to the backend MCP server.
|
||||
|
||||
## Features
|
||||
|
||||
### Terminal Emulation
|
||||
|
||||
- **Authentic Terminal Experience**: Console-style dark theme with monospace fonts
|
||||
- **Real-time Output**: Live streaming of command output with proper formatting
|
||||
- **Command History**: Navigate through previous commands with arrow keys
|
||||
- **Input Handling**: Full keyboard support including Ctrl+L (clear), Ctrl+C (interrupt), Tab (autocomplete)
|
||||
- **ANSI Color Support**: Processes ANSI escape codes for colored output
|
||||
|
||||
### WebSocket Communication
|
||||
|
||||
- **Real-time Bidirectional Communication**: Connects to Claude Code MCP server via WebSocket
|
||||
- **Auto-reconnection**: Automatic reconnection with exponential backoff
|
||||
- **Message Queuing**: Queues messages when disconnected and sends when reconnected
|
||||
- **Heartbeat Mechanism**: Monitors connection health with ping/pong
|
||||
- **Session Management**: Handles MCP protocol initialization and session state
|
||||
|
||||
### Settings Management
|
||||
|
||||
- **Connection Settings**: Server URL, authentication tokens, auto-connect
|
||||
- **Appearance Customization**: Multiple themes (dark, light, classic, matrix), font size, line height
|
||||
- **Behavior Options**: Auto-scroll, timestamps, sound notifications, history limits
|
||||
- **Claude Flow Configuration**: Default SPARC modes, swarm strategies, coordination modes
|
||||
- **Persistent Storage**: Settings saved to localStorage with import/export capabilities
|
||||
|
||||
### Claude Flow Integration
|
||||
|
||||
- **Built-in Commands**: Support for all major Claude Flow commands
|
||||
- **SPARC Mode Support**: Integration with all 17 specialized SPARC modes
|
||||
- **Swarm Management**: Web interface for swarm coordination and monitoring
|
||||
- **Real-time Status**: Live updates of agent status, memory usage, and system metrics
|
||||
|
||||
## Architecture
|
||||
|
||||
### Component Structure
|
||||
|
||||
```
|
||||
src/ui/console/
|
||||
├── index.html # Main HTML structure
|
||||
├── styles/
|
||||
│ ├── console.css # Core console styling
|
||||
│ ├── settings.css # Settings panel styling
|
||||
│ └── responsive.css # Mobile/tablet responsive design
|
||||
└── js/
|
||||
├── console.js # Main application coordinator
|
||||
├── websocket-client.js # WebSocket communication layer
|
||||
├── terminal-emulator.js # Terminal behavior and display
|
||||
├── command-handler.js # Command processing and execution
|
||||
└── settings.js # Configuration management
|
||||
```
|
||||
|
||||
### Integration Points
|
||||
|
||||
- **HTTP Transport**: Web console served at `/console` endpoint
|
||||
- **WebSocket Endpoint**: Real-time communication via `/ws` endpoint
|
||||
- **MCP Protocol**: Full JSON-RPC 2.0 compliant communication
|
||||
- **Static Files**: CSS, JavaScript, and assets served via Express static middleware
|
||||
|
||||
## Usage
|
||||
|
||||
### Starting the Web Console
|
||||
|
||||
1. Start Claude Code with HTTP transport enabled:
|
||||
|
||||
```bash
|
||||
claude-flow start --transport http --port 3000
|
||||
```
|
||||
|
||||
2. Open web browser and navigate to:
|
||||
|
||||
```
|
||||
http://localhost:3000/console
|
||||
```
|
||||
|
||||
3. The console will automatically attempt to connect to the WebSocket endpoint
|
||||
|
||||
### Basic Commands
|
||||
|
||||
- `help` - Show all available commands
|
||||
- `connect [url] [token]` - Connect to Claude Code server
|
||||
- `status` - Show connection and system status
|
||||
- `clear` - Clear console output (or Ctrl+L)
|
||||
- `claude-flow <command>` - Execute Claude Flow commands
|
||||
- `swarm <action>` - Manage swarms
|
||||
- `tools` - List available tools
|
||||
|
||||
### Keyboard Shortcuts
|
||||
|
||||
- **Enter** - Execute command
|
||||
- **Tab** - Autocomplete command
|
||||
- **↑/↓** - Navigate command history
|
||||
- **Ctrl+L** - Clear console
|
||||
- **Ctrl+C** - Send interrupt signal
|
||||
- **ESC** - Close settings panel
|
||||
|
||||
### Settings Panel
|
||||
|
||||
Access via the ⚙️ Settings button to configure:
|
||||
|
||||
- Server connection details
|
||||
- Visual appearance and themes
|
||||
- Console behavior preferences
|
||||
- Claude Flow default settings
|
||||
|
||||
## Themes
|
||||
|
||||
### Available Themes
|
||||
|
||||
1. **Dark** (default) - Modern dark theme with blue accents
|
||||
2. **Light** - Clean light theme for bright environments
|
||||
3. **Classic** - Traditional green-on-black terminal
|
||||
4. **Matrix** - Matrix-inspired green glow effect
|
||||
|
||||
### Custom Styling
|
||||
|
||||
The console uses CSS custom properties for easy theming:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--bg-primary: #0d1117;
|
||||
--text-primary: #c9d1d9;
|
||||
--console-prompt: #58a6ff;
|
||||
--accent-primary: #1f6feb;
|
||||
}
|
||||
```
|
||||
|
||||
## Mobile Support
|
||||
|
||||
### Responsive Design
|
||||
|
||||
- **Tablet Landscape**: Optimized layout with condensed controls
|
||||
- **Tablet Portrait**: Settings panel adapts to smaller screens
|
||||
- **Mobile Landscape**: Minimized header and status bar
|
||||
- **Mobile Portrait**: Full-screen overlay for settings, touch-optimized controls
|
||||
|
||||
### Touch Interactions
|
||||
|
||||
- Minimum 44px touch targets for accessibility
|
||||
- 16px font size on inputs to prevent iOS zoom
|
||||
- Gesture-friendly scrolling and selection
|
||||
- Swipe gestures for panel management
|
||||
|
||||
## Accessibility
|
||||
|
||||
### Features
|
||||
|
||||
- **Semantic HTML**: Proper ARIA labels and roles
|
||||
- **Keyboard Navigation**: Full keyboard accessibility
|
||||
- **Screen Reader Support**: Live regions for output updates
|
||||
- **High Contrast**: Support for high contrast preferences
|
||||
- **Reduced Motion**: Respects prefers-reduced-motion settings
|
||||
- **Focus Management**: Clear focus indicators and logical tab order
|
||||
|
||||
## Browser Compatibility
|
||||
|
||||
### Supported Browsers
|
||||
|
||||
- **Chrome/Chromium** 88+
|
||||
- **Firefox** 85+
|
||||
- **Safari** 14+
|
||||
- **Edge** 88+
|
||||
|
||||
### Required Features
|
||||
|
||||
- ES2020 modules
|
||||
- WebSocket API
|
||||
- CSS Custom Properties
|
||||
- localStorage API
|
||||
- Fetch API
|
||||
|
||||
## Development
|
||||
|
||||
### Local Development
|
||||
|
||||
1. Ensure Claude Code backend is running with HTTP transport
|
||||
2. Open `src/ui/console/index.html` in a web browser
|
||||
3. Modify settings to point to your local server URL
|
||||
|
||||
### Building for Production
|
||||
|
||||
The console is designed to be served as static files:
|
||||
|
||||
```bash
|
||||
# Copy console files to web server
|
||||
cp -r src/ui/console/* /var/www/claude-console/
|
||||
|
||||
# Or serve via Node.js/Express
|
||||
app.use('/console', express.static('src/ui/console'));
|
||||
```
|
||||
|
||||
### Customization
|
||||
|
||||
- Modify CSS custom properties for theming
|
||||
- Extend command handlers for new functionality
|
||||
- Add new WebSocket message handlers for custom notifications
|
||||
- Customize settings panel for additional configuration options
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Authentication
|
||||
|
||||
- Bearer token authentication support
|
||||
- Secure WebSocket connections (WSS) in production
|
||||
- CORS configuration for cross-origin requests
|
||||
- Input validation and sanitization
|
||||
|
||||
### Best Practices
|
||||
|
||||
- Use HTTPS in production environments
|
||||
- Configure proper CORS origins
|
||||
- Implement rate limiting for WebSocket connections
|
||||
- Validate all user inputs before processing
|
||||
|
||||
## Performance
|
||||
|
||||
### Optimizations
|
||||
|
||||
- **Message Queuing**: Efficient handling of high-frequency messages
|
||||
- **Output Limiting**: Configurable maximum lines to prevent memory issues
|
||||
- **Lazy Loading**: Components loaded only when needed
|
||||
- **Debounced Updates**: Status updates batched for performance
|
||||
|
||||
### Memory Management
|
||||
|
||||
- Automatic cleanup of old output lines
|
||||
- Proper event listener cleanup on disconnect
|
||||
- Garbage collection friendly object creation
|
||||
- Minimal DOM manipulation for smooth scrolling
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Connection Failed**: Check server URL and ensure Claude Code is running with HTTP transport
|
||||
2. **WebSocket Errors**: Verify firewall settings and proxy configuration
|
||||
3. **Authentication Issues**: Check bearer token format and validity
|
||||
4. **Mobile Display Issues**: Ensure viewport meta tag is present
|
||||
5. **Theme Not Loading**: Check CSS file paths and custom property support
|
||||
|
||||
### Debug Mode
|
||||
|
||||
Enable debug logging in browser developer tools:
|
||||
|
||||
```javascript
|
||||
// Access global console instance
|
||||
window.claudeConsole.wsClient.debugMode = true;
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Part of the Claude Code project. See main project LICENSE for details.
|
||||
@@ -1,603 +0,0 @@
|
||||
# Claude Flow - Advanced Workflow Designer
|
||||
|
||||
## Overview
|
||||
|
||||
The Claude Flow Workflow Designer is a comprehensive visual workflow builder that enables users to create, execute, and manage complex data processing pipelines through an intuitive drag-and-drop interface. It features real-time execution, AI integration, and advanced validation capabilities.
|
||||
|
||||
## Features
|
||||
|
||||
### 🎨 Visual Interface
|
||||
|
||||
- **Drag-and-Drop Canvas**: Intuitive node-based workflow construction
|
||||
- **Zoom & Pan**: Navigate large workflows with ease
|
||||
- **Grid Snap**: Precision alignment for professional layouts
|
||||
- **Context Menus**: Right-click for quick actions
|
||||
- **Responsive Design**: Works on desktop and mobile devices
|
||||
|
||||
### 🧩 Component Library
|
||||
|
||||
- **Input Components**: File Input, Text Input, URL Input, API Input
|
||||
- **Processing Components**: Transform, Filter, Aggregate, Sort
|
||||
- **Output Components**: File Output, Display, API Output, Notification
|
||||
- **Control Flow**: Condition, Loop, Delay, Parallel execution
|
||||
- **AI Operations**: AI Analyze, AI Generate, AI Classify, AI Summarize
|
||||
|
||||
### 🔗 Connection System
|
||||
|
||||
- **Visual Connections**: Drag between input/output ports
|
||||
- **Type Validation**: Ensures compatible connections
|
||||
- **Connection Management**: Easy editing and removal
|
||||
- **Flow Visualization**: Clear data flow representation
|
||||
|
||||
### 🚀 Execution Engine
|
||||
|
||||
- **Real-time Execution**: Watch workflows run in real-time
|
||||
- **Status Tracking**: Visual indicators for node states
|
||||
- **Progress Monitoring**: Detailed execution logs
|
||||
- **Error Handling**: Comprehensive error reporting
|
||||
|
||||
### ✅ Validation System
|
||||
|
||||
- **Workflow Validation**: Checks for errors and warnings
|
||||
- **Circular Dependency Detection**: Prevents infinite loops
|
||||
- **Required Property Validation**: Ensures complete configuration
|
||||
- **Connection Validation**: Verifies proper data flow
|
||||
|
||||
### 📚 Template Gallery
|
||||
|
||||
- **Pre-built Workflows**: Common patterns and examples
|
||||
- **Template Categories**: Organized by use case
|
||||
- **Quick Start**: Load templates to get started quickly
|
||||
- **Custom Templates**: Save and share your own workflows
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
/workspaces/claude-code-flow/src/ui/console/
|
||||
├── js/
|
||||
│ └── workflow-designer.js # Main workflow designer class
|
||||
├── styles/
|
||||
│ └── workflow-designer.css # Complete styling system
|
||||
├── workflow-designer-demo.html # Demo page with examples
|
||||
└── WORKFLOW_DESIGNER_README.md # This documentation
|
||||
```
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Basic Usage
|
||||
|
||||
1. **Open the Designer**
|
||||
|
||||
```html
|
||||
<div id="workflowDesigner"></div>
|
||||
<script src="js/workflow-designer.js"></script>
|
||||
<script>
|
||||
const designer = new WorkflowDesigner('workflowDesigner');
|
||||
</script>
|
||||
```
|
||||
|
||||
2. **Add Components**
|
||||
|
||||
- Drag components from the left palette
|
||||
- Drop them onto the canvas
|
||||
- Components automatically snap to grid
|
||||
|
||||
3. **Create Connections**
|
||||
|
||||
- Click and drag from output ports (blue circles)
|
||||
- Connect to input ports (green circles)
|
||||
- Connections validate automatically
|
||||
|
||||
4. **Configure Properties**
|
||||
|
||||
- Select any node to see its properties
|
||||
- Edit values in the right panel
|
||||
- Changes apply immediately
|
||||
|
||||
5. **Validate & Execute**
|
||||
- Click "Validate" to check for errors
|
||||
- Click "Execute" to run the workflow
|
||||
- Monitor progress in the execution log
|
||||
|
||||
### Advanced Features
|
||||
|
||||
#### Custom Node Types
|
||||
|
||||
```javascript
|
||||
// Add custom node type
|
||||
designer.nodeTypes.custom = {
|
||||
inputs: [{ name: 'data', type: 'any' }],
|
||||
outputs: [{ name: 'result', type: 'any' }],
|
||||
properties: { customProp: 'defaultValue' },
|
||||
};
|
||||
```
|
||||
|
||||
#### Event Handling
|
||||
|
||||
```javascript
|
||||
// Listen for workflow events
|
||||
designer.addEventListener('nodeAdded', (node) => {
|
||||
console.log('Node added:', node);
|
||||
});
|
||||
|
||||
designer.addEventListener('executionComplete', (results) => {
|
||||
console.log('Execution complete:', results);
|
||||
});
|
||||
```
|
||||
|
||||
#### Save/Load Workflows
|
||||
|
||||
```javascript
|
||||
// Save workflow
|
||||
const workflow = designer.exportWorkflow();
|
||||
localStorage.setItem('myWorkflow', JSON.stringify(workflow));
|
||||
|
||||
// Load workflow
|
||||
const saved = JSON.parse(localStorage.getItem('myWorkflow'));
|
||||
designer.importWorkflow(saved);
|
||||
```
|
||||
|
||||
## Component Types
|
||||
|
||||
### Input Components
|
||||
|
||||
#### File Input
|
||||
|
||||
- **Purpose**: Read data from files
|
||||
- **Properties**:
|
||||
- `path`: File path
|
||||
- `format`: File format (auto, json, csv, txt)
|
||||
- **Outputs**: File data
|
||||
|
||||
#### Text Input
|
||||
|
||||
- **Purpose**: Manual text input
|
||||
- **Properties**:
|
||||
- `value`: Text content
|
||||
- `multiline`: Single or multi-line input
|
||||
- **Outputs**: Text string
|
||||
|
||||
#### URL Input
|
||||
|
||||
- **Purpose**: Fetch data from URLs
|
||||
- **Properties**:
|
||||
- `url`: Target URL
|
||||
- `method`: HTTP method (GET, POST, etc.)
|
||||
- `headers`: HTTP headers
|
||||
- **Outputs**: Response data
|
||||
|
||||
#### API Input
|
||||
|
||||
- **Purpose**: Connect to APIs
|
||||
- **Properties**:
|
||||
- `endpoint`: API endpoint
|
||||
- `method`: HTTP method
|
||||
- `headers`: Request headers
|
||||
- `body`: Request body
|
||||
- **Outputs**: API response
|
||||
|
||||
### Processing Components
|
||||
|
||||
#### Transform
|
||||
|
||||
- **Purpose**: Transform data using custom expressions
|
||||
- **Properties**:
|
||||
- `expression`: JavaScript expression
|
||||
- `language`: Expression language
|
||||
- **Inputs**: Data to transform
|
||||
- **Outputs**: Transformed data
|
||||
|
||||
#### Filter
|
||||
|
||||
- **Purpose**: Filter data based on conditions
|
||||
- **Properties**:
|
||||
- `condition`: Filter condition
|
||||
- `language`: Condition language
|
||||
- **Inputs**: Data to filter
|
||||
- **Outputs**: Filtered data
|
||||
|
||||
#### Aggregate
|
||||
|
||||
- **Purpose**: Aggregate data collections
|
||||
- **Properties**:
|
||||
- `operation`: Aggregation operation (sum, avg, count, etc.)
|
||||
- `field`: Field to aggregate
|
||||
- **Inputs**: Data array
|
||||
- **Outputs**: Aggregated result
|
||||
|
||||
#### Sort
|
||||
|
||||
- **Purpose**: Sort data collections
|
||||
- **Properties**:
|
||||
- `field`: Sort field
|
||||
- `order`: Sort order (asc, desc)
|
||||
- **Inputs**: Data array
|
||||
- **Outputs**: Sorted array
|
||||
|
||||
### Output Components
|
||||
|
||||
#### File Output
|
||||
|
||||
- **Purpose**: Write data to files
|
||||
- **Properties**:
|
||||
- `path`: Output file path
|
||||
- `format`: Output format
|
||||
- **Inputs**: Data to write
|
||||
|
||||
#### Display
|
||||
|
||||
- **Purpose**: Display data in UI
|
||||
- **Properties**:
|
||||
- `format`: Display format (table, json, text)
|
||||
- `title`: Display title
|
||||
- **Inputs**: Data to display
|
||||
|
||||
#### API Output
|
||||
|
||||
- **Purpose**: Send data to APIs
|
||||
- **Properties**:
|
||||
- `endpoint`: Target API endpoint
|
||||
- `method`: HTTP method
|
||||
- `headers`: Request headers
|
||||
- **Inputs**: Data to send
|
||||
- **Outputs**: API response
|
||||
|
||||
#### Notification
|
||||
|
||||
- **Purpose**: Show user notifications
|
||||
- **Properties**:
|
||||
- `type`: Notification type (info, warning, error)
|
||||
- `title`: Notification title
|
||||
- **Inputs**: Message content
|
||||
|
||||
### Control Flow Components
|
||||
|
||||
#### Condition
|
||||
|
||||
- **Purpose**: Conditional data routing
|
||||
- **Properties**:
|
||||
- `expression`: Condition expression
|
||||
- `language`: Expression language
|
||||
- **Inputs**: Condition value, data
|
||||
- **Outputs**: True path, false path
|
||||
|
||||
#### Loop
|
||||
|
||||
- **Purpose**: Iterate over data
|
||||
- **Properties**:
|
||||
- `type`: Loop type (forEach, while, for)
|
||||
- `condition`: Loop condition
|
||||
- **Inputs**: Data to iterate
|
||||
- **Outputs**: Iteration results
|
||||
|
||||
#### Delay
|
||||
|
||||
- **Purpose**: Add delays to workflow
|
||||
- **Properties**:
|
||||
- `duration`: Delay duration
|
||||
- `unit`: Time unit (ms, s, m)
|
||||
- **Inputs**: Data to delay
|
||||
- **Outputs**: Delayed data
|
||||
|
||||
#### Parallel
|
||||
|
||||
- **Purpose**: Parallel execution
|
||||
- **Properties**:
|
||||
- `maxConcurrency`: Maximum concurrent operations
|
||||
- **Inputs**: Data array
|
||||
- **Outputs**: Parallel results
|
||||
|
||||
### AI Components
|
||||
|
||||
#### AI Analyze
|
||||
|
||||
- **Purpose**: Analyze data using AI
|
||||
- **Properties**:
|
||||
- `model`: AI model (gpt-4, claude, etc.)
|
||||
- `temperature`: Response creativity
|
||||
- **Inputs**: Data to analyze
|
||||
- **Outputs**: Analysis results
|
||||
|
||||
#### AI Generate
|
||||
|
||||
- **Purpose**: Generate content using AI
|
||||
- **Properties**:
|
||||
- `model`: AI model
|
||||
- `temperature`: Response creativity
|
||||
- `maxTokens`: Maximum response length
|
||||
- **Inputs**: Generation prompt
|
||||
- **Outputs**: Generated content
|
||||
|
||||
#### AI Classify
|
||||
|
||||
- **Purpose**: Classify data using AI
|
||||
- **Properties**:
|
||||
- `model`: AI model
|
||||
- `categories`: Classification categories
|
||||
- **Inputs**: Data to classify
|
||||
- **Outputs**: Classification results
|
||||
|
||||
#### AI Summarize
|
||||
|
||||
- **Purpose**: Summarize content using AI
|
||||
- **Properties**:
|
||||
- `model`: AI model
|
||||
- `length`: Summary length (short, medium, long)
|
||||
- **Inputs**: Content to summarize
|
||||
- **Outputs**: Summary text
|
||||
|
||||
## API Reference
|
||||
|
||||
### WorkflowDesigner Class
|
||||
|
||||
#### Constructor
|
||||
|
||||
```javascript
|
||||
new WorkflowDesigner(containerId, options);
|
||||
```
|
||||
|
||||
#### Methods
|
||||
|
||||
##### Node Management
|
||||
|
||||
- `createNode(type, x, y)`: Create new node
|
||||
- `deleteNode(node)`: Delete node
|
||||
- `duplicateNode(node)`: Duplicate node
|
||||
- `getNodeAt(x, y)`: Get node at coordinates
|
||||
|
||||
##### Connection Management
|
||||
|
||||
- `createConnection(start, end)`: Create connection
|
||||
- `deleteConnection(connection)`: Delete connection
|
||||
- `getConnectionPointAt(x, y)`: Get connection point
|
||||
|
||||
##### Workflow Operations
|
||||
|
||||
- `validateWorkflow()`: Validate workflow
|
||||
- `executeWorkflow()`: Execute workflow
|
||||
- `stopWorkflow()`: Stop execution
|
||||
- `clearCanvas()`: Clear all nodes
|
||||
|
||||
##### Import/Export
|
||||
|
||||
- `exportWorkflow()`: Export workflow data
|
||||
- `importWorkflow(data)`: Import workflow data
|
||||
- `saveWorkflow()`: Save to localStorage
|
||||
- `loadWorkflow()`: Load from localStorage
|
||||
|
||||
##### View Management
|
||||
|
||||
- `setZoom(zoom)`: Set zoom level
|
||||
- `pan(x, y)`: Pan canvas
|
||||
- `draw()`: Redraw canvas
|
||||
|
||||
### Events
|
||||
|
||||
#### Node Events
|
||||
|
||||
- `nodeAdded`: Node added to canvas
|
||||
- `nodeDeleted`: Node deleted from canvas
|
||||
- `nodeSelected`: Node selected
|
||||
- `nodePropertyChanged`: Node property changed
|
||||
|
||||
#### Connection Events
|
||||
|
||||
- `connectionCreated`: Connection created
|
||||
- `connectionDeleted`: Connection deleted
|
||||
|
||||
#### Workflow Events
|
||||
|
||||
- `workflowValidated`: Workflow validation complete
|
||||
- `executionStarted`: Workflow execution started
|
||||
- `executionComplete`: Workflow execution complete
|
||||
- `executionError`: Workflow execution error
|
||||
|
||||
#### Canvas Events
|
||||
|
||||
- `canvasPan`: Canvas panned
|
||||
- `canvasZoom`: Canvas zoomed
|
||||
- `canvasClick`: Canvas clicked
|
||||
|
||||
## Styling
|
||||
|
||||
### CSS Classes
|
||||
|
||||
#### Layout
|
||||
|
||||
- `.workflow-designer`: Main container
|
||||
- `.toolbar`: Top toolbar
|
||||
- `.designer-body`: Main body area
|
||||
- `.node-palette`: Left component palette
|
||||
- `.canvas-container`: Canvas area
|
||||
- `.properties-panel`: Right properties panel
|
||||
- `.bottom-panel`: Bottom panel with tabs
|
||||
|
||||
#### Components
|
||||
|
||||
- `.palette-item`: Draggable palette items
|
||||
- `.btn`: Button styling
|
||||
- `.tab-button`: Tab navigation buttons
|
||||
- `.context-menu`: Right-click context menu
|
||||
|
||||
#### States
|
||||
|
||||
- `.selected`: Selected node state
|
||||
- `.executing`: Executing node state
|
||||
- `.error`: Error state
|
||||
- `.completed`: Completed state
|
||||
|
||||
### Customization
|
||||
|
||||
#### Custom Themes
|
||||
|
||||
```css
|
||||
/* Dark theme example */
|
||||
.workflow-designer.dark-theme {
|
||||
background: #1a1a1a;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.workflow-designer.dark-theme .node-palette {
|
||||
background: #2d2d2d;
|
||||
border-color: #444444;
|
||||
}
|
||||
```
|
||||
|
||||
#### Custom Node Styles
|
||||
|
||||
```css
|
||||
/* Custom node type styling */
|
||||
.palette-item[data-node-type='custom'] {
|
||||
border-color: #purple;
|
||||
background: #f3e5f5;
|
||||
}
|
||||
|
||||
.palette-item[data-node-type='custom'] i {
|
||||
color: #purple;
|
||||
}
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Data Processing
|
||||
|
||||
```javascript
|
||||
// Create a simple data processing workflow
|
||||
const fileInput = designer.createNode('file-input', 100, 150);
|
||||
const transform = designer.createNode('transform', 300, 150);
|
||||
const display = designer.createNode('display', 500, 150);
|
||||
|
||||
// Configure properties
|
||||
fileInput.properties.path = 'data.json';
|
||||
transform.properties.expression = 'data.map(item => item.value * 2)';
|
||||
display.properties.format = 'table';
|
||||
|
||||
// Connect nodes
|
||||
designer.createConnection(
|
||||
{ node: fileInput, type: 'output', index: 0 },
|
||||
{ node: transform, type: 'input', index: 0 },
|
||||
);
|
||||
designer.createConnection(
|
||||
{ node: transform, type: 'output', index: 0 },
|
||||
{ node: display, type: 'input', index: 0 },
|
||||
);
|
||||
```
|
||||
|
||||
### AI Content Pipeline
|
||||
|
||||
```javascript
|
||||
// Create an AI content processing workflow
|
||||
const textInput = designer.createNode('text-input', 100, 150);
|
||||
const aiAnalyze = designer.createNode('ai-analyze', 300, 150);
|
||||
const condition = designer.createNode('condition', 500, 150);
|
||||
const aiGenerate = designer.createNode('ai-generate', 700, 100);
|
||||
const aiSummarize = designer.createNode('ai-summarize', 700, 200);
|
||||
|
||||
// Configure AI properties
|
||||
aiAnalyze.properties.model = 'gpt-4';
|
||||
aiAnalyze.properties.temperature = 0.7;
|
||||
condition.properties.expression = 'data.confidence > 0.8';
|
||||
aiGenerate.properties.prompt = 'Expand on: {{data}}';
|
||||
aiSummarize.properties.length = 'short';
|
||||
```
|
||||
|
||||
### API Integration
|
||||
|
||||
```javascript
|
||||
// Create an API integration workflow
|
||||
const apiInput = designer.createNode('api-input', 100, 150);
|
||||
const filter = designer.createNode('filter', 300, 150);
|
||||
const aggregate = designer.createNode('aggregate', 500, 150);
|
||||
const apiOutput = designer.createNode('api-output', 700, 150);
|
||||
|
||||
// Configure API properties
|
||||
apiInput.properties.endpoint = 'https://api.example.com/data';
|
||||
apiInput.properties.method = 'GET';
|
||||
filter.properties.condition = 'item.status === "active"';
|
||||
aggregate.properties.operation = 'sum';
|
||||
aggregate.properties.field = 'value';
|
||||
apiOutput.properties.endpoint = 'https://api.example.com/results';
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Workflow Design
|
||||
|
||||
1. **Start Simple**: Begin with basic workflows and add complexity gradually
|
||||
2. **Use Templates**: Leverage pre-built templates for common patterns
|
||||
3. **Validate Early**: Validate workflows before execution
|
||||
4. **Handle Errors**: Always include error handling in workflows
|
||||
5. **Document**: Use descriptive names and comments
|
||||
|
||||
### Performance
|
||||
|
||||
1. **Minimize Connections**: Reduce unnecessary data passing
|
||||
2. **Use Parallel**: Leverage parallel processing where possible
|
||||
3. **Cache Results**: Cache expensive operations
|
||||
4. **Optimize AI**: Use appropriate AI models for tasks
|
||||
5. **Monitor Resources**: Watch memory and CPU usage
|
||||
|
||||
### Security
|
||||
|
||||
1. **Validate Inputs**: Always validate external data
|
||||
2. **Sanitize**: Clean user inputs before processing
|
||||
3. **Secure APIs**: Use proper authentication
|
||||
4. **Limit Access**: Restrict file system access
|
||||
5. **Audit Logs**: Keep execution logs for security
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### Nodes Not Connecting
|
||||
|
||||
- Check port compatibility
|
||||
- Ensure proper drag direction
|
||||
- Verify node positions
|
||||
|
||||
#### Execution Errors
|
||||
|
||||
- Validate workflow first
|
||||
- Check node properties
|
||||
- Review execution logs
|
||||
|
||||
#### Performance Issues
|
||||
|
||||
- Reduce workflow complexity
|
||||
- Use parallel processing
|
||||
- Optimize AI calls
|
||||
|
||||
#### UI Problems
|
||||
|
||||
- Clear browser cache
|
||||
- Check browser compatibility
|
||||
- Verify CSS/JS loading
|
||||
|
||||
### Debug Mode
|
||||
|
||||
```javascript
|
||||
// Enable debug mode
|
||||
designer.debug = true;
|
||||
|
||||
// View debug information
|
||||
console.log(designer.getDebugInfo());
|
||||
```
|
||||
|
||||
## Browser Support
|
||||
|
||||
- Chrome 80+
|
||||
- Firefox 75+
|
||||
- Safari 13+
|
||||
- Edge 80+
|
||||
|
||||
## License
|
||||
|
||||
This component is part of the Claude Flow system and follows the project's licensing terms.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome! Please follow the project's contribution guidelines and ensure all tests pass before submitting pull requests.
|
||||
|
||||
## Support
|
||||
|
||||
For support, please create an issue in the project repository or contact the development team.
|
||||
@@ -1,316 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Claude Flow - Analysis & Monitoring Tools</title>
|
||||
<link rel="stylesheet" href="styles/analysis-tools.css" />
|
||||
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
</head>
|
||||
<body>
|
||||
<div class="analysis-container">
|
||||
<!-- Header -->
|
||||
<header class="analysis-header">
|
||||
<h1 class="analysis-title">Analysis & Monitoring Tools</h1>
|
||||
<div id="connection-status" class="connection-status disconnected">Disconnected</div>
|
||||
</header>
|
||||
|
||||
<!-- Tab Navigation -->
|
||||
<nav class="analysis-tabs">
|
||||
<button class="analysis-tab active" data-tab="metrics">Metrics</button>
|
||||
<button class="analysis-tab" data-tab="reports">Reports</button>
|
||||
<button class="analysis-tab" data-tab="analysis">Analysis</button>
|
||||
<button class="analysis-tab" data-tab="health">Health</button>
|
||||
</nav>
|
||||
|
||||
<!-- Content Area -->
|
||||
<main class="analysis-content">
|
||||
<!-- Metrics Panel -->
|
||||
<div id="metrics-panel" class="analysis-panel active">
|
||||
<div class="metrics-panel">
|
||||
<!-- Performance Metrics -->
|
||||
<div class="metric-section">
|
||||
<h3>📊 Performance Metrics</h3>
|
||||
<div id="performance-metrics" class="metric-grid">
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Response Time</div>
|
||||
<div class="metric-value">--</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Throughput</div>
|
||||
<div class="metric-value">--</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Error Rate</div>
|
||||
<div class="metric-value">--</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Uptime</div>
|
||||
<div class="metric-value">--</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<div class="chart-title">Performance Over Time</div>
|
||||
<div class="chart-container">
|
||||
<canvas id="performance-chart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Token Usage -->
|
||||
<div class="metric-section">
|
||||
<h3>🎯 Token Usage</h3>
|
||||
<div id="token-metrics" class="metric-grid">
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Total Tokens</div>
|
||||
<div class="metric-value">--</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Input Tokens</div>
|
||||
<div class="metric-value">--</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Output Tokens</div>
|
||||
<div class="metric-value">--</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="metric-label">Cache Hit Rate</div>
|
||||
<div class="metric-value">--</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<div class="chart-title">Token Distribution</div>
|
||||
<div class="chart-container">
|
||||
<canvas id="token-usage-chart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tool Actions -->
|
||||
<div class="tool-section">
|
||||
<h3>🔧 Metrics Tools</h3>
|
||||
<div class="tool-grid">
|
||||
<button class="tool-btn" data-tool="performance_report">📈 Performance Report</button>
|
||||
<button class="tool-btn" data-tool="token_usage">🎯 Token Usage</button>
|
||||
<button class="tool-btn" data-tool="metrics_collect">📊 Collect Metrics</button>
|
||||
<button class="tool-btn" data-tool="usage_stats">📋 Usage Statistics</button>
|
||||
</div>
|
||||
<div class="export-section">
|
||||
<button class="export-btn" data-type="metrics" data-format="json">
|
||||
📄 Export JSON
|
||||
</button>
|
||||
<button class="export-btn" data-type="metrics" data-format="csv">
|
||||
📊 Export CSV
|
||||
</button>
|
||||
<button class="refresh-btn" data-section="metrics">🔄 Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Reports Panel -->
|
||||
<div id="reports-panel" class="analysis-panel">
|
||||
<div class="tool-section">
|
||||
<h3>📋 Report Generation</h3>
|
||||
<div class="tool-grid">
|
||||
<button class="tool-btn" data-tool="performance_report">📈 Performance Report</button>
|
||||
<button class="tool-btn" data-tool="cost_analysis">💰 Cost Analysis</button>
|
||||
<button class="tool-btn" data-tool="quality_assess">⭐ Quality Assessment</button>
|
||||
<button class="tool-btn" data-tool="benchmark_run">🏁 Benchmark Report</button>
|
||||
</div>
|
||||
<div class="export-section">
|
||||
<button class="export-btn" data-type="reports" data-format="json">
|
||||
📄 Export JSON
|
||||
</button>
|
||||
<button class="export-btn" data-type="reports" data-format="csv">
|
||||
📊 Export CSV
|
||||
</button>
|
||||
<button class="refresh-btn" data-section="reports">🔄 Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Report Output -->
|
||||
<div class="output-section">
|
||||
<h4>📊 Report Output</h4>
|
||||
<div id="performance-report-output" class="output-content">
|
||||
Click on a report tool above to generate reports...
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Analysis Panel -->
|
||||
<div id="analysis-panel" class="analysis-panel">
|
||||
<div class="tool-section">
|
||||
<h3>🔍 Analysis Tools</h3>
|
||||
<div class="tool-grid">
|
||||
<button class="tool-btn" data-tool="bottleneck_analyze">
|
||||
🚧 Bottleneck Analysis
|
||||
</button>
|
||||
<button class="tool-btn" data-tool="trend_analysis">📈 Trend Analysis</button>
|
||||
<button class="tool-btn" data-tool="error_analysis">❌ Error Analysis</button>
|
||||
<button class="tool-btn" data-tool="capacity_plan">📏 Capacity Planning</button>
|
||||
</div>
|
||||
<div class="export-section">
|
||||
<button class="export-btn" data-type="analysis" data-format="json">
|
||||
📄 Export JSON
|
||||
</button>
|
||||
<button class="export-btn" data-type="analysis" data-format="csv">
|
||||
📊 Export CSV
|
||||
</button>
|
||||
<button class="refresh-btn" data-section="analysis">🔄 Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Analysis Output -->
|
||||
<div class="output-section">
|
||||
<h4>🔍 Analysis Results</h4>
|
||||
<div id="bottleneck-analysis-output" class="output-content">
|
||||
Click on an analysis tool above to view results...
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="output-section">
|
||||
<h4>📈 Trend Analysis</h4>
|
||||
<div id="trends-output" class="output-content">
|
||||
Trend analysis results will appear here...
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="output-section">
|
||||
<h4>❌ Error Analysis</h4>
|
||||
<div id="errors-output" class="output-content">
|
||||
Error analysis results will appear here...
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="output-section">
|
||||
<h4>📏 Capacity Planning</h4>
|
||||
<div id="capacity-output" class="output-content">
|
||||
Capacity planning results will appear here...
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Health Panel -->
|
||||
<div id="health-panel" class="analysis-panel">
|
||||
<div class="metric-section">
|
||||
<h3>🏥 System Health</h3>
|
||||
<div id="health-status">
|
||||
<div class="health-overview">
|
||||
<div class="health-score health-excellent">--</div>
|
||||
<div class="health-label">Overall Health</div>
|
||||
</div>
|
||||
<div class="health-components">
|
||||
<div class="health-component">
|
||||
<span class="component-name">CPU</span>
|
||||
<span class="component-value health-excellent">--%</span>
|
||||
</div>
|
||||
<div class="health-component">
|
||||
<span class="component-name">Memory</span>
|
||||
<span class="component-value health-excellent">--%</span>
|
||||
</div>
|
||||
<div class="health-component">
|
||||
<span class="component-name">Disk</span>
|
||||
<span class="component-value health-excellent">--%</span>
|
||||
</div>
|
||||
<div class="health-component">
|
||||
<span class="component-name">Network</span>
|
||||
<span class="component-value health-excellent">--%</span>
|
||||
</div>
|
||||
<div class="health-component">
|
||||
<span class="component-name">API</span>
|
||||
<span class="component-value health-excellent">--%</span>
|
||||
</div>
|
||||
<div class="health-component">
|
||||
<span class="component-name">Database</span>
|
||||
<span class="component-value health-excellent">--%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-wrapper">
|
||||
<div class="chart-title">System Health Overview</div>
|
||||
<div class="chart-container">
|
||||
<canvas id="system-health-chart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="metric-section">
|
||||
<h3>⚡ Load Monitoring</h3>
|
||||
<div class="chart-wrapper">
|
||||
<div class="chart-title">Load Over Time</div>
|
||||
<div class="chart-container">
|
||||
<canvas id="load-monitor-chart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="tool-section">
|
||||
<h3>🏥 Health Tools</h3>
|
||||
<div class="tool-grid">
|
||||
<button class="tool-btn" data-tool="health_check">🏥 Health Check</button>
|
||||
<button class="tool-btn" data-tool="load_monitor">⚡ Load Monitor</button>
|
||||
</div>
|
||||
<div class="export-section">
|
||||
<button class="export-btn" data-type="health" data-format="json">
|
||||
📄 Export JSON
|
||||
</button>
|
||||
<button class="export-btn" data-type="health" data-format="csv">📊 Export CSV</button>
|
||||
<button class="refresh-btn" data-section="health">🔄 Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Health Output -->
|
||||
<div class="output-section">
|
||||
<h4>🏥 Health Check Results</h4>
|
||||
<div id="health-output" class="output-content">
|
||||
Click on a health tool above to view results...
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="output-section">
|
||||
<h4>⚡ Load Monitor Results</h4>
|
||||
<div id="load-output" class="output-content">
|
||||
Load monitoring results will appear here...
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Alerts -->
|
||||
<div class="metric-section">
|
||||
<h3>🚨 System Alerts</h3>
|
||||
<div id="alerts-container" class="alerts-container">
|
||||
<div class="alert alert-info">
|
||||
<div class="alert-header">
|
||||
<span class="alert-title">System Started</span>
|
||||
<span class="alert-timestamp">12:00:00</span>
|
||||
</div>
|
||||
<div class="alert-message">
|
||||
Analysis & Monitoring Tools initialized successfully
|
||||
</div>
|
||||
<button class="alert-dismiss">×</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- Additional Output Sections (Hidden by default) -->
|
||||
<div style="display: none">
|
||||
<div id="token-usage-output" class="output-content"></div>
|
||||
<div id="benchmark-output" class="output-content"></div>
|
||||
<div id="metrics-output" class="output-content"></div>
|
||||
<div id="costs-output" class="output-content"></div>
|
||||
<div id="quality-output" class="output-content"></div>
|
||||
<div id="stats-output" class="output-content"></div>
|
||||
</div>
|
||||
|
||||
<script src="js/analysis-tools.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,376 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="description" content="Claude Flow Analytics & Monitoring Dashboard" />
|
||||
<title>📊 Claude Flow Analytics Dashboard</title>
|
||||
<link rel="stylesheet" href="styles/console.css" />
|
||||
<link rel="stylesheet" href="styles/analytics.css" />
|
||||
<link rel="stylesheet" href="styles/responsive.css" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Header with branding and controls -->
|
||||
<header class="console-header">
|
||||
<div class="header-left">
|
||||
<h1 class="console-title">
|
||||
<span class="console-icon">📊</span>
|
||||
Claude Flow Analytics
|
||||
</h1>
|
||||
<div class="connection-status" id="connectionStatus">
|
||||
<span class="status-indicator" id="statusIndicator"></span>
|
||||
<span class="status-text" id="statusText">Connecting...</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<button class="header-button" id="refreshData" aria-label="Refresh Data">
|
||||
<span class="icon">🔄</span>
|
||||
Refresh
|
||||
</button>
|
||||
<button class="header-button" id="exportReport" aria-label="Export Report">
|
||||
<span class="icon">📥</span>
|
||||
Export
|
||||
</button>
|
||||
<button class="header-button" id="settingsToggle" aria-label="Toggle Settings">
|
||||
<span class="icon">⚙️</span>
|
||||
Settings
|
||||
</button>
|
||||
<button class="header-button" id="backToConsole" aria-label="Back to Console">
|
||||
<span class="icon">🔙</span>
|
||||
Console
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Main analytics dashboard -->
|
||||
<main class="analytics-main">
|
||||
<!-- Quick stats overview -->
|
||||
<section class="stats-overview">
|
||||
<div class="stat-card" id="performanceCard">
|
||||
<div class="stat-icon">⚡</div>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value" id="performanceScore">--</div>
|
||||
<div class="stat-label">Performance Score</div>
|
||||
<div class="stat-trend" id="performanceTrend">--</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stat-card" id="tokenUsageCard">
|
||||
<div class="stat-icon">🪙</div>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value" id="tokenCount">--</div>
|
||||
<div class="stat-label">Tokens Used</div>
|
||||
<div class="stat-trend" id="tokenTrend">--</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stat-card" id="systemHealthCard">
|
||||
<div class="stat-icon">💚</div>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value" id="healthScore">--</div>
|
||||
<div class="stat-label">System Health</div>
|
||||
<div class="stat-trend" id="healthTrend">--</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stat-card" id="costAnalysisCard">
|
||||
<div class="stat-icon">💰</div>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value" id="estimatedCost">--</div>
|
||||
<div class="stat-label">Estimated Cost</div>
|
||||
<div class="stat-trend" id="costTrend">--</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Analytics tools grid -->
|
||||
<section class="analytics-grid">
|
||||
<!-- Performance Monitoring -->
|
||||
<div class="analytics-panel" id="performancePanel">
|
||||
<div class="panel-header">
|
||||
<h3><span class="panel-icon">📈</span>Performance Monitoring</h3>
|
||||
<div class="panel-controls">
|
||||
<button class="panel-button" id="runBenchmark">Run Benchmark</button>
|
||||
<button class="panel-button" id="analyzeBottlenecks">Find Bottlenecks</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-content">
|
||||
<div class="chart-container">
|
||||
<canvas id="performanceChart"></canvas>
|
||||
</div>
|
||||
<div class="metrics-list" id="performanceMetrics">
|
||||
<!-- Performance metrics will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Token Usage Analytics -->
|
||||
<div class="analytics-panel" id="tokenPanel">
|
||||
<div class="panel-header">
|
||||
<h3><span class="panel-icon">🪙</span>Token Usage Analytics</h3>
|
||||
<div class="panel-controls">
|
||||
<button class="panel-button" id="analyzeTokens">Analyze Usage</button>
|
||||
<button class="panel-button" id="optimizeTokens">Optimize</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-content">
|
||||
<div class="chart-container">
|
||||
<canvas id="tokenChart"></canvas>
|
||||
</div>
|
||||
<div class="token-breakdown" id="tokenBreakdown">
|
||||
<!-- Token breakdown will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- System Health Monitor -->
|
||||
<div class="analytics-panel" id="healthPanel">
|
||||
<div class="panel-header">
|
||||
<h3><span class="panel-icon">🏥</span>System Health Monitor</h3>
|
||||
<div class="panel-controls">
|
||||
<button class="panel-button" id="runHealthCheck">Health Check</button>
|
||||
<button class="panel-button" id="viewDiagnostics">Diagnostics</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-content">
|
||||
<div class="health-status" id="healthStatus">
|
||||
<div class="health-indicator">
|
||||
<span class="health-dot" id="cpuHealth"></span>
|
||||
<span class="health-label">CPU</span>
|
||||
<span class="health-value" id="cpuValue">--</span>
|
||||
</div>
|
||||
<div class="health-indicator">
|
||||
<span class="health-dot" id="memoryHealth"></span>
|
||||
<span class="health-label">Memory</span>
|
||||
<span class="health-value" id="memoryValue">--</span>
|
||||
</div>
|
||||
<div class="health-indicator">
|
||||
<span class="health-dot" id="swarmHealth"></span>
|
||||
<span class="health-label">Swarm</span>
|
||||
<span class="health-value" id="swarmValue">--</span>
|
||||
</div>
|
||||
<div class="health-indicator">
|
||||
<span class="health-dot" id="networkHealth"></span>
|
||||
<span class="health-label">Network</span>
|
||||
<span class="health-value" id="networkValue">--</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-container">
|
||||
<canvas id="healthChart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Error Analysis -->
|
||||
<div class="analytics-panel" id="errorPanel">
|
||||
<div class="panel-header">
|
||||
<h3><span class="panel-icon">🔍</span>Error Analysis</h3>
|
||||
<div class="panel-controls">
|
||||
<button class="panel-button" id="analyzeErrors">Analyze Patterns</button>
|
||||
<button class="panel-button" id="clearErrors">Clear Log</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-content">
|
||||
<div class="error-summary" id="errorSummary">
|
||||
<div class="error-count">
|
||||
<span class="error-count-value" id="errorCount">0</span>
|
||||
<span class="error-count-label">Total Errors</span>
|
||||
</div>
|
||||
<div class="error-rate">
|
||||
<span class="error-rate-value" id="errorRate">0%</span>
|
||||
<span class="error-rate-label">Error Rate</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="error-patterns" id="errorPatterns">
|
||||
<!-- Error patterns will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Quality Assessment -->
|
||||
<div class="analytics-panel" id="qualityPanel">
|
||||
<div class="panel-header">
|
||||
<h3><span class="panel-icon">✅</span>Quality Assessment</h3>
|
||||
<div class="panel-controls">
|
||||
<button class="panel-button" id="runQualityCheck">Assess Quality</button>
|
||||
<button class="panel-button" id="generateReport">Generate Report</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-content">
|
||||
<div class="quality-metrics" id="qualityMetrics">
|
||||
<div class="quality-score">
|
||||
<span class="score-value" id="overallQuality">--</span>
|
||||
<span class="score-label">Overall Quality</span>
|
||||
</div>
|
||||
<div class="quality-breakdown">
|
||||
<div class="quality-item">
|
||||
<span class="quality-name">Code Quality</span>
|
||||
<div class="quality-bar">
|
||||
<div class="quality-fill" id="codeQuality"></div>
|
||||
</div>
|
||||
<span class="quality-percent" id="codeQualityPercent">--</span>
|
||||
</div>
|
||||
<div class="quality-item">
|
||||
<span class="quality-name">Response Quality</span>
|
||||
<div class="quality-bar">
|
||||
<div class="quality-fill" id="responseQuality"></div>
|
||||
</div>
|
||||
<span class="quality-percent" id="responseQualityPercent">--</span>
|
||||
</div>
|
||||
<div class="quality-item">
|
||||
<span class="quality-name">Coordination Quality</span>
|
||||
<div class="quality-bar">
|
||||
<div class="quality-fill" id="coordinationQuality"></div>
|
||||
</div>
|
||||
<span class="quality-percent" id="coordinationQualityPercent">--</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Usage Statistics -->
|
||||
<div class="analytics-panel" id="usagePanel">
|
||||
<div class="panel-header">
|
||||
<h3><span class="panel-icon">📊</span>Usage Statistics</h3>
|
||||
<div class="panel-controls">
|
||||
<button class="panel-button" id="collectStats">Collect Stats</button>
|
||||
<button class="panel-button" id="trendAnalysis">Trend Analysis</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-content">
|
||||
<div class="usage-stats" id="usageStats">
|
||||
<div class="usage-item">
|
||||
<span class="usage-label">Commands Executed</span>
|
||||
<span class="usage-value" id="commandsExecuted">--</span>
|
||||
</div>
|
||||
<div class="usage-item">
|
||||
<span class="usage-label">Files Processed</span>
|
||||
<span class="usage-value" id="filesProcessed">--</span>
|
||||
</div>
|
||||
<div class="usage-item">
|
||||
<span class="usage-label">Swarms Created</span>
|
||||
<span class="usage-value" id="swarmsCreated">--</span>
|
||||
</div>
|
||||
<div class="usage-item">
|
||||
<span class="usage-label">Avg Response Time</span>
|
||||
<span class="usage-value" id="avgResponseTime">--</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-container">
|
||||
<canvas id="usageChart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Real-time activity log -->
|
||||
<section class="activity-log">
|
||||
<div class="log-header">
|
||||
<h3><span class="log-icon">📝</span>Real-time Activity Log</h3>
|
||||
<div class="log-controls">
|
||||
<button class="log-button" id="pauseLog">Pause</button>
|
||||
<button class="log-button" id="clearLog">Clear</button>
|
||||
<button class="log-button" id="exportLog">Export</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="log-content" id="activityLog">
|
||||
<!-- Real-time activity will be displayed here -->
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<!-- Settings panel -->
|
||||
<aside class="settings-panel" id="settingsPanel">
|
||||
<div class="settings-header">
|
||||
<h2>Analytics Settings</h2>
|
||||
<button class="close-button" id="closeSettings" aria-label="Close Settings">×</button>
|
||||
</div>
|
||||
|
||||
<div class="settings-content">
|
||||
<!-- Data Collection Settings -->
|
||||
<section class="setting-group">
|
||||
<h3>Data Collection</h3>
|
||||
<div class="setting-item">
|
||||
<label for="refreshInterval">Refresh Interval (seconds):</label>
|
||||
<select id="refreshInterval">
|
||||
<option value="5">5 seconds</option>
|
||||
<option value="10" selected>10 seconds</option>
|
||||
<option value="30">30 seconds</option>
|
||||
<option value="60">1 minute</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label class="checkbox-label">
|
||||
<input type="checkbox" id="realTimeUpdates" checked />
|
||||
Enable real-time updates
|
||||
</label>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label class="checkbox-label">
|
||||
<input type="checkbox" id="enableNotifications" />
|
||||
Enable alert notifications
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Performance Thresholds -->
|
||||
<section class="setting-group">
|
||||
<h3>Performance Thresholds</h3>
|
||||
<div class="setting-item">
|
||||
<label for="cpuThreshold">CPU Warning Threshold (%):</label>
|
||||
<input type="number" id="cpuThreshold" min="1" max="100" value="80" />
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="memoryThreshold">Memory Warning Threshold (%):</label>
|
||||
<input type="number" id="memoryThreshold" min="1" max="100" value="85" />
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="responseThreshold">Response Time Warning (ms):</label>
|
||||
<input type="number" id="responseThreshold" min="100" max="10000" value="2000" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Data Retention -->
|
||||
<section class="setting-group">
|
||||
<h3>Data Retention</h3>
|
||||
<div class="setting-item">
|
||||
<label for="retentionPeriod">Keep data for:</label>
|
||||
<select id="retentionPeriod">
|
||||
<option value="1">1 day</option>
|
||||
<option value="7" selected>7 days</option>
|
||||
<option value="30">30 days</option>
|
||||
<option value="90">90 days</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="maxLogEntries">Max log entries:</label>
|
||||
<input type="number" id="maxLogEntries" min="100" max="50000" value="10000" />
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Loading indicator -->
|
||||
<div class="loading-overlay" id="loadingOverlay">
|
||||
<div class="loading-spinner">
|
||||
<div class="spinner"></div>
|
||||
<div class="loading-text">Loading analytics data...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- JavaScript modules -->
|
||||
<script type="module" src="js/analytics-dashboard.js"></script>
|
||||
<script type="module" src="js/analytics-tools.js"></script>
|
||||
<script type="module" src="js/chart-manager.js"></script>
|
||||
<script type="module" src="js/websocket-client.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,258 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="description" content="Claude Code Console - Web-based CLI interface" />
|
||||
<title>🌊 Claude Flow v2</title>
|
||||
<link rel="stylesheet" href="styles/console.css" />
|
||||
<link rel="stylesheet" href="styles/settings.css" />
|
||||
<link rel="stylesheet" href="styles/responsive.css" />
|
||||
<link rel="stylesheet" href="styles/swarm-visualizer.css" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Header with branding and controls -->
|
||||
<header class="console-header">
|
||||
<div class="header-left">
|
||||
<h1 class="console-title">
|
||||
<span class="console-icon">🌊</span>
|
||||
Claude Flow v2
|
||||
</h1>
|
||||
<div class="connection-status" id="connectionStatus">
|
||||
<span class="status-indicator" id="statusIndicator"></span>
|
||||
<span class="status-text" id="statusText">Connecting...</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<button class="header-button" id="settingsToggle" aria-label="Toggle Settings">
|
||||
<span class="icon">⚙️</span>
|
||||
Settings
|
||||
</button>
|
||||
<button class="header-button" id="clearConsole" aria-label="Clear Console">
|
||||
<span class="icon">🗑️</span>
|
||||
Clear
|
||||
</button>
|
||||
<button class="header-button" id="fullscreenToggle" aria-label="Toggle Fullscreen">
|
||||
<span class="icon">⛶</span>
|
||||
Fullscreen
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Main content area -->
|
||||
<main class="console-main">
|
||||
<!-- Settings panel (initially hidden) -->
|
||||
<aside class="settings-panel" id="settingsPanel">
|
||||
<div class="settings-header">
|
||||
<h2>Console Settings</h2>
|
||||
<button class="close-button" id="closeSettings" aria-label="Close Settings">×</button>
|
||||
</div>
|
||||
|
||||
<div class="settings-content">
|
||||
<!-- Connection Settings -->
|
||||
<section class="setting-group">
|
||||
<h3>Connection</h3>
|
||||
<div class="setting-item">
|
||||
<label for="serverUrl">Server URL:</label>
|
||||
<input type="text" id="serverUrl" value="ws://localhost:3000/ws" />
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="authToken">Auth Token:</label>
|
||||
<input type="password" id="authToken" placeholder="Bearer token (optional)" />
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label class="checkbox-label">
|
||||
<input type="checkbox" id="autoConnect" checked />
|
||||
Auto-connect on startup
|
||||
</label>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<button class="action-button" id="connectButton">Connect</button>
|
||||
<button class="action-button secondary" id="disconnectButton">Disconnect</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Appearance Settings -->
|
||||
<section class="setting-group">
|
||||
<h3>Appearance</h3>
|
||||
<div class="setting-item">
|
||||
<label for="fontSize">Font Size:</label>
|
||||
<select id="fontSize">
|
||||
<option value="12">12px</option>
|
||||
<option value="14" selected>14px</option>
|
||||
<option value="16">16px</option>
|
||||
<option value="18">18px</option>
|
||||
<option value="20">20px</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="theme">Theme:</label>
|
||||
<select id="theme">
|
||||
<option value="dark" selected>Dark</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="classic">Classic Terminal</option>
|
||||
<option value="matrix">Matrix</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="lineHeight">Line Height:</label>
|
||||
<select id="lineHeight">
|
||||
<option value="1.2">1.2</option>
|
||||
<option value="1.4" selected>1.4</option>
|
||||
<option value="1.6">1.6</option>
|
||||
<option value="1.8">1.8</option>
|
||||
</select>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Console Behavior -->
|
||||
<section class="setting-group">
|
||||
<h3>Behavior</h3>
|
||||
<div class="setting-item">
|
||||
<label class="checkbox-label">
|
||||
<input type="checkbox" id="autoScroll" checked />
|
||||
Auto-scroll to bottom
|
||||
</label>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label class="checkbox-label">
|
||||
<input type="checkbox" id="showTimestamps" checked />
|
||||
Show timestamps
|
||||
</label>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label class="checkbox-label">
|
||||
<input type="checkbox" id="enableSounds" />
|
||||
Enable sound notifications
|
||||
</label>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="maxLines">Max history lines:</label>
|
||||
<input type="number" id="maxLines" min="100" max="10000" value="1000" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Claude Flow Settings -->
|
||||
<section class="setting-group">
|
||||
<h3>Claude Flow</h3>
|
||||
<div class="setting-item">
|
||||
<label for="defaultMode">Default SPARC Mode:</label>
|
||||
<select id="defaultMode">
|
||||
<option value="coder">Coder</option>
|
||||
<option value="architect">Architect</option>
|
||||
<option value="analyzer">Analyzer</option>
|
||||
<option value="researcher">Researcher</option>
|
||||
<option value="reviewer">Reviewer</option>
|
||||
<option value="tester">Tester</option>
|
||||
<option value="debugger">Debugger</option>
|
||||
<option value="documenter">Documenter</option>
|
||||
<option value="optimizer">Optimizer</option>
|
||||
<option value="designer">Designer</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="swarmStrategy">Swarm Strategy:</label>
|
||||
<select id="swarmStrategy">
|
||||
<option value="development">Development</option>
|
||||
<option value="research">Research</option>
|
||||
<option value="analysis">Analysis</option>
|
||||
<option value="testing">Testing</option>
|
||||
<option value="optimization">Optimization</option>
|
||||
<option value="maintenance">Maintenance</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="coordinationMode">Coordination Mode:</label>
|
||||
<select id="coordinationMode">
|
||||
<option value="centralized">Centralized</option>
|
||||
<option value="hierarchical">Hierarchical</option>
|
||||
<option value="distributed">Distributed</option>
|
||||
<option value="mesh">Mesh</option>
|
||||
<option value="hybrid">Hybrid</option>
|
||||
</select>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Console terminal area -->
|
||||
<section class="console-container">
|
||||
<!-- Output area -->
|
||||
<div
|
||||
class="console-output"
|
||||
id="consoleOutput"
|
||||
role="log"
|
||||
aria-live="polite"
|
||||
aria-label="Console Output"
|
||||
>
|
||||
<div class="welcome-message">
|
||||
<div class="ascii-art">
|
||||
🌊 Claude Flow v2.0.0 Welcome to the web-based swarm orchestration console Type 'help'
|
||||
for available commands Use Ctrl+L to clear console
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Input area -->
|
||||
<div class="console-input-area">
|
||||
<div class="input-prompt">
|
||||
<span class="prompt-text" id="promptText">claude-flow></span>
|
||||
<input
|
||||
type="text"
|
||||
class="console-input"
|
||||
id="consoleInput"
|
||||
placeholder="Enter command..."
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
aria-label="Console Command Input"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="input-suggestions"
|
||||
id="inputSuggestions"
|
||||
role="listbox"
|
||||
aria-hidden="true"
|
||||
></div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<!-- Status bar -->
|
||||
<footer class="status-bar">
|
||||
<div class="status-left">
|
||||
<span class="status-item" id="currentMode">Mode: Standalone</span>
|
||||
<span class="status-item" id="activeAgents">Agents: 0</span>
|
||||
<span class="status-item" id="uptime">Uptime: 00:00:00</span>
|
||||
</div>
|
||||
<div class="status-right">
|
||||
<span class="status-item" id="memoryUsage">Memory: --</span>
|
||||
<span class="status-item" id="messageCount">Messages: 0</span>
|
||||
<span class="status-item" id="timestamp"></span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<!-- Loading indicator -->
|
||||
<div class="loading-overlay" id="loadingOverlay">
|
||||
<div class="loading-spinner">
|
||||
<div class="spinner"></div>
|
||||
<div class="loading-text">Connecting to Claude Code...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- JavaScript modules -->
|
||||
<script type="module" src="js/console.js"></script>
|
||||
<script type="module" src="js/websocket-client.js"></script>
|
||||
<script type="module" src="js/settings.js"></script>
|
||||
<script type="module" src="js/command-handler.js"></script>
|
||||
<script type="module" src="js/terminal-emulator.js"></script>
|
||||
<script type="module" src="js/swarm-visualizer.js"></script>
|
||||
<script type="module" src="js/real-time-dashboard.js"></script>
|
||||
<script type="module" src="js/swarm-integration.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,853 +0,0 @@
|
||||
/**
|
||||
* Command Handler for Claude Code Console
|
||||
* Processes and executes console commands
|
||||
*/
|
||||
|
||||
export class CommandHandler {
|
||||
constructor(terminal, wsClient) {
|
||||
this.terminal = terminal;
|
||||
this.wsClient = wsClient;
|
||||
this.isProcessing = false;
|
||||
|
||||
// Built-in commands
|
||||
this.builtinCommands = {
|
||||
help: this.showHelp.bind(this),
|
||||
clear: this.clearConsole.bind(this),
|
||||
status: this.showStatus.bind(this),
|
||||
connect: this.connectToServer.bind(this),
|
||||
disconnect: this.disconnectFromServer.bind(this),
|
||||
tools: this.listTools.bind(this),
|
||||
health: this.checkHealth.bind(this),
|
||||
history: this.showHistory.bind(this),
|
||||
export: this.exportSession.bind(this),
|
||||
theme: this.changeTheme.bind(this),
|
||||
version: this.showVersion.bind(this),
|
||||
};
|
||||
|
||||
// Claude Flow commands
|
||||
this.claudeFlowCommands = {
|
||||
'claude-flow': this.executeClaudeFlow.bind(this),
|
||||
swarm: this.executeSwarm.bind(this),
|
||||
init: this.initializeProject.bind(this),
|
||||
config: this.manageConfig.bind(this),
|
||||
memory: this.manageMemory.bind(this),
|
||||
agents: this.manageAgents.bind(this),
|
||||
benchmark: this.runBenchmark.bind(this),
|
||||
sparc: this.executeSparc.bind(this),
|
||||
};
|
||||
|
||||
// Direct SPARC mode commands
|
||||
this.sparcModeCommands = {
|
||||
coder: this.executeSparcMode.bind(this, 'coder'),
|
||||
architect: this.executeSparcMode.bind(this, 'architect'),
|
||||
analyst: this.executeSparcMode.bind(this, 'analyst'),
|
||||
researcher: this.executeSparcMode.bind(this, 'researcher'),
|
||||
reviewer: this.executeSparcMode.bind(this, 'reviewer'),
|
||||
tester: this.executeSparcMode.bind(this, 'tester'),
|
||||
debugger: this.executeSparcMode.bind(this, 'debugger'),
|
||||
documenter: this.executeSparcMode.bind(this, 'documenter'),
|
||||
optimizer: this.executeSparcMode.bind(this, 'optimizer'),
|
||||
designer: this.executeSparcMode.bind(this, 'designer'),
|
||||
};
|
||||
|
||||
this.allCommands = {
|
||||
...this.builtinCommands,
|
||||
...this.claudeFlowCommands,
|
||||
...this.sparcModeCommands,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a command
|
||||
*/
|
||||
async processCommand(command) {
|
||||
if (this.isProcessing) {
|
||||
this.terminal.writeWarning('Another command is still processing. Please wait...');
|
||||
return;
|
||||
}
|
||||
|
||||
this.isProcessing = true;
|
||||
this.terminal.setLocked(true);
|
||||
|
||||
try {
|
||||
const { cmd, args } = this.parseCommand(command);
|
||||
|
||||
if (this.allCommands[cmd]) {
|
||||
await this.allCommands[cmd](args);
|
||||
} else {
|
||||
await this.executeRemoteCommand(cmd, args);
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(error.message);
|
||||
console.error('Command execution error:', error);
|
||||
} finally {
|
||||
this.isProcessing = false;
|
||||
this.terminal.setLocked(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse command string into command and arguments
|
||||
*/
|
||||
parseCommand(commandString) {
|
||||
const parts = commandString.trim().split(/\s+/);
|
||||
const cmd = parts[0].toLowerCase();
|
||||
const args = parts.slice(1);
|
||||
|
||||
return { cmd, args };
|
||||
}
|
||||
|
||||
/**
|
||||
* Show help information
|
||||
*/
|
||||
async showHelp(args) {
|
||||
if (args.length > 0) {
|
||||
const command = args[0].toLowerCase();
|
||||
if (this.allCommands[command]) {
|
||||
this.showCommandHelp(command);
|
||||
} else {
|
||||
this.terminal.writeError(`Unknown command: ${command}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.terminal.writeInfo('Claude Flow Console Commands:');
|
||||
this.terminal.writeLine('');
|
||||
|
||||
this.terminal.writeInfo('Built-in Commands:');
|
||||
Object.keys(this.builtinCommands).forEach((cmd) => {
|
||||
this.terminal.writeLine(` ${cmd.padEnd(12)} - ${this.getCommandDescription(cmd)}`);
|
||||
});
|
||||
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Claude Flow Commands:');
|
||||
Object.keys(this.claudeFlowCommands).forEach((cmd) => {
|
||||
this.terminal.writeLine(` ${cmd.padEnd(12)} - ${this.getCommandDescription(cmd)}`);
|
||||
});
|
||||
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Tool Commands (from tools list):');
|
||||
this.terminal.writeLine(' system/health - Get system health status');
|
||||
this.terminal.writeLine(
|
||||
' memory/manage - Manage memory (list, store <key> <value>, retrieve <key>)',
|
||||
);
|
||||
this.terminal.writeLine(
|
||||
' agents/manage - Manage agents (list, create <type>, status <id>)',
|
||||
);
|
||||
this.terminal.writeLine(
|
||||
' swarm/orchestrate - Swarm operations (status, create, start, stop)',
|
||||
);
|
||||
this.terminal.writeLine(
|
||||
' sparc/execute - Execute SPARC modes (coder, architect, etc.)',
|
||||
);
|
||||
this.terminal.writeLine(
|
||||
' benchmark/run - Run benchmarks (default, memory, cpu, network)',
|
||||
);
|
||||
this.terminal.writeLine(' claude-flow/execute - Execute Claude Flow commands');
|
||||
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo(
|
||||
'Use "help <command>" for detailed information about a specific command.',
|
||||
);
|
||||
this.terminal.writeInfo(
|
||||
'Use Ctrl+L to clear console, Ctrl+C to interrupt, Tab for autocomplete.',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get command description
|
||||
*/
|
||||
getCommandDescription(command) {
|
||||
const descriptions = {
|
||||
help: 'Show help information',
|
||||
clear: 'Clear console output',
|
||||
status: 'Show connection and system status',
|
||||
connect: 'Connect to Claude Code server',
|
||||
disconnect: 'Disconnect from server',
|
||||
tools: 'List available tools',
|
||||
health: 'Check server health',
|
||||
history: 'Show command history',
|
||||
export: 'Export session data',
|
||||
theme: 'Change console theme',
|
||||
version: 'Show version information',
|
||||
'claude-flow': 'Execute Claude Flow commands',
|
||||
swarm: 'Manage and execute swarms',
|
||||
init: 'Initialize new project',
|
||||
config: 'Manage configuration',
|
||||
memory: 'Manage memory and data',
|
||||
agents: 'Manage agents',
|
||||
benchmark: 'Run benchmarks',
|
||||
sparc: 'Execute SPARC mode commands',
|
||||
};
|
||||
|
||||
return descriptions[command] || 'No description available';
|
||||
}
|
||||
|
||||
/**
|
||||
* Show detailed command help
|
||||
*/
|
||||
showCommandHelp(command) {
|
||||
const helpText = {
|
||||
help: `
|
||||
Usage: help [command]
|
||||
Show help information for all commands or a specific command.
|
||||
|
||||
Examples:
|
||||
help - Show all commands
|
||||
help claude-flow - Show help for claude-flow command`,
|
||||
|
||||
clear: `
|
||||
Usage: clear
|
||||
Clear the console output. You can also use Ctrl+L.`,
|
||||
|
||||
connect: `
|
||||
Usage: connect [url] [token]
|
||||
Connect to Claude Code server.
|
||||
|
||||
Arguments:
|
||||
url - WebSocket URL (default: ws://localhost:3000/ws)
|
||||
token - Authentication token (optional)
|
||||
|
||||
Examples:
|
||||
connect
|
||||
connect ws://localhost:3000/ws
|
||||
connect ws://localhost:3000/ws my-auth-token`,
|
||||
|
||||
'claude-flow': `
|
||||
Usage: claude-flow <subcommand> [options]
|
||||
Execute Claude Flow commands.
|
||||
|
||||
Subcommands:
|
||||
start [mode] - Start Claude Flow in specified mode
|
||||
stop - Stop Claude Flow
|
||||
status - Show Claude Flow status
|
||||
modes - List available SPARC modes
|
||||
|
||||
Examples:
|
||||
claude-flow start coder
|
||||
claude-flow status
|
||||
claude-flow modes`,
|
||||
|
||||
swarm: `
|
||||
Usage: swarm <action> [options]
|
||||
Manage and execute swarms.
|
||||
|
||||
Actions:
|
||||
create <name> - Create new swarm
|
||||
start <name> - Start existing swarm
|
||||
stop <name> - Stop running swarm
|
||||
list - List all swarms
|
||||
status <name> - Show swarm status
|
||||
|
||||
Examples:
|
||||
swarm create my-swarm
|
||||
swarm start my-swarm
|
||||
swarm list`,
|
||||
};
|
||||
|
||||
if (helpText[command]) {
|
||||
this.terminal.writeInfo(helpText[command].trim());
|
||||
} else {
|
||||
this.terminal.writeInfo(`No detailed help available for: ${command}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear console
|
||||
*/
|
||||
async clearConsole() {
|
||||
this.terminal.clear();
|
||||
this.terminal.writeSuccess('Console cleared');
|
||||
}
|
||||
|
||||
/**
|
||||
* Show status
|
||||
*/
|
||||
async showStatus() {
|
||||
const wsStatus = this.wsClient.getStatus();
|
||||
const terminalStats = this.terminal.getStats();
|
||||
|
||||
this.terminal.writeInfo('System Status:');
|
||||
this.terminal.writeLine('');
|
||||
|
||||
this.terminal.writeInfo('Connection:');
|
||||
this.terminal.writeLine(` Status: ${wsStatus.connected ? 'Connected' : 'Disconnected'}`);
|
||||
this.terminal.writeLine(` URL: ${wsStatus.url || 'Not set'}`);
|
||||
this.terminal.writeLine(` Reconnect attempts: ${wsStatus.reconnectAttempts}`);
|
||||
this.terminal.writeLine(` Queued messages: ${wsStatus.queuedMessages}`);
|
||||
this.terminal.writeLine(` Pending requests: ${wsStatus.pendingRequests}`);
|
||||
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Terminal:');
|
||||
this.terminal.writeLine(` Total lines: ${terminalStats.totalLines}`);
|
||||
this.terminal.writeLine(` History size: ${terminalStats.historySize}`);
|
||||
this.terminal.writeLine(` Input locked: ${terminalStats.isLocked}`);
|
||||
this.terminal.writeLine(` Current prompt: ${terminalStats.currentPrompt}`);
|
||||
|
||||
if (wsStatus.connected) {
|
||||
try {
|
||||
const healthStatus = await this.wsClient.getHealthStatus();
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Server Health:');
|
||||
this.terminal.writeLine(` Status: ${healthStatus.healthy ? 'Healthy' : 'Unhealthy'}`);
|
||||
|
||||
if (healthStatus.metrics) {
|
||||
Object.entries(healthStatus.metrics).forEach(([key, value]) => {
|
||||
this.terminal.writeLine(` ${key}: ${value}`);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeWarning('Failed to get server health status');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to server
|
||||
*/
|
||||
async connectToServer(args) {
|
||||
const url = args[0] || 'ws://localhost:3000/ws';
|
||||
const token = args[1] || '';
|
||||
|
||||
this.terminal.writeInfo(`Connecting to ${url}...`);
|
||||
|
||||
try {
|
||||
await this.wsClient.connect(url, token);
|
||||
|
||||
// Initialize session
|
||||
await this.wsClient.initializeSession();
|
||||
|
||||
this.terminal.writeSuccess('Connected successfully');
|
||||
this.terminal.setPrompt('claude-flow>');
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Connection failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect from server
|
||||
*/
|
||||
async disconnectFromServer() {
|
||||
this.wsClient.disconnect();
|
||||
this.terminal.writeSuccess('Disconnected from server');
|
||||
this.terminal.setPrompt('offline>');
|
||||
}
|
||||
|
||||
/**
|
||||
* List available tools
|
||||
*/
|
||||
async listTools() {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tools = await this.wsClient.getAvailableTools();
|
||||
|
||||
this.terminal.writeInfo('Available Tools:');
|
||||
this.terminal.writeLine('');
|
||||
|
||||
if (tools && tools.length > 0) {
|
||||
tools.forEach((tool) => {
|
||||
this.terminal.writeLine(
|
||||
` ${tool.name.padEnd(20)} - ${tool.description || 'No description'}`,
|
||||
);
|
||||
});
|
||||
} else {
|
||||
this.terminal.writeWarning('No tools available');
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Failed to list tools: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check server health
|
||||
*/
|
||||
async checkHealth() {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const health = await this.wsClient.getHealthStatus();
|
||||
|
||||
if (health.healthy) {
|
||||
this.terminal.writeSuccess('Server is healthy');
|
||||
} else {
|
||||
this.terminal.writeError(`Server is unhealthy: ${health.error || 'Unknown error'}`);
|
||||
}
|
||||
|
||||
if (health.metrics) {
|
||||
this.terminal.writeLine('');
|
||||
this.terminal.writeInfo('Metrics:');
|
||||
Object.entries(health.metrics).forEach(([key, value]) => {
|
||||
this.terminal.writeLine(` ${key}: ${value}`);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Health check failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show command history
|
||||
*/
|
||||
async showHistory() {
|
||||
const history = this.terminal.history;
|
||||
|
||||
if (history.length === 0) {
|
||||
this.terminal.writeInfo('No command history');
|
||||
return;
|
||||
}
|
||||
|
||||
this.terminal.writeInfo('Command History:');
|
||||
history.forEach((cmd, index) => {
|
||||
this.terminal.writeLine(` ${(index + 1).toString().padStart(3)}: ${cmd}`);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Export session data
|
||||
*/
|
||||
async exportSession(args) {
|
||||
const format = args[0] || 'json';
|
||||
|
||||
const sessionData = {
|
||||
timestamp: new Date().toISOString(),
|
||||
terminal: this.terminal.exportHistory(),
|
||||
history: this.terminal.history,
|
||||
status: this.wsClient.getStatus(),
|
||||
};
|
||||
|
||||
if (format === 'json') {
|
||||
const blob = new Blob([JSON.stringify(sessionData, null, 2)], { type: 'application/json' });
|
||||
this.downloadFile(blob, `console-session-${Date.now()}.json`);
|
||||
this.terminal.writeSuccess('Session exported as JSON');
|
||||
} else {
|
||||
this.terminal.writeError(`Unsupported export format: ${format}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Change theme
|
||||
*/
|
||||
async changeTheme(args) {
|
||||
const theme = args[0];
|
||||
const validThemes = ['dark', 'light', 'classic', 'matrix'];
|
||||
|
||||
if (!theme) {
|
||||
this.terminal.writeInfo(`Available themes: ${validThemes.join(', ')}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validThemes.includes(theme)) {
|
||||
this.terminal.writeError(`Invalid theme: ${theme}`);
|
||||
return;
|
||||
}
|
||||
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
localStorage.setItem('console_theme', theme);
|
||||
this.terminal.writeSuccess(`Theme changed to: ${theme}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show version information
|
||||
*/
|
||||
async showVersion() {
|
||||
this.terminal.writeInfo('🌊 Claude Flow v2.0.0');
|
||||
this.terminal.writeLine('Advanced swarm orchestration platform');
|
||||
this.terminal.writeLine('Built with modern web technologies');
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute Claude Flow command
|
||||
*/
|
||||
async executeClaudeFlow(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.length === 0) {
|
||||
this.terminal.writeError('Usage: claude-flow <subcommand> [options]');
|
||||
return;
|
||||
}
|
||||
|
||||
const subcommand = args[0];
|
||||
const subArgs = args.slice(1);
|
||||
|
||||
try {
|
||||
const result = await this.wsClient.executeCommand('claude-flow', {
|
||||
subcommand,
|
||||
args: subArgs,
|
||||
});
|
||||
|
||||
this.terminal.writeSuccess(`Claude Flow ${subcommand} executed successfully`);
|
||||
if (result && result.output) {
|
||||
this.terminal.writeLine(result.output);
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Claude Flow command failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute swarm command
|
||||
*/
|
||||
async executeSwarm(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const action = args[0] || 'status';
|
||||
this.terminal.writeInfo(`Executing swarm ${action}...`);
|
||||
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: 'swarm/status',
|
||||
arguments: { action, args: args.slice(1) },
|
||||
});
|
||||
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess('Swarm command executed successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Swarm command failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize project
|
||||
*/
|
||||
async initializeProject(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
this.terminal.writeWarning('Project initialization not yet implemented in web console');
|
||||
}
|
||||
|
||||
/**
|
||||
* Manage configuration
|
||||
*/
|
||||
async manageConfig(args) {
|
||||
this.terminal.writeInfo('Use the Settings panel (⚙️ button) to manage configuration');
|
||||
}
|
||||
|
||||
/**
|
||||
* Manage memory
|
||||
*/
|
||||
async manageMemory(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const operation = args[0] || 'list';
|
||||
const key = args[1];
|
||||
const value = args.slice(2).join(' ');
|
||||
|
||||
this.terminal.writeInfo(`Executing memory ${operation}...`);
|
||||
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: 'memory/manage',
|
||||
arguments: { operation, key, value },
|
||||
});
|
||||
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess('Memory operation completed successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Memory command failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Manage agents
|
||||
*/
|
||||
async manageAgents(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const action = args[0] || 'list';
|
||||
const agentType = args[1];
|
||||
const agentId = args[1];
|
||||
|
||||
this.terminal.writeInfo(`Executing agents ${action}...`);
|
||||
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: 'agents/manage',
|
||||
arguments: { action, agentType, agentId },
|
||||
});
|
||||
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess('Agent operation completed successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Agent command failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run benchmark
|
||||
*/
|
||||
async runBenchmark(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const suite = args[0] || 'default';
|
||||
const iterations = parseInt(args[1]) || 10;
|
||||
|
||||
this.terminal.writeInfo(`Running benchmark suite: ${suite}...`);
|
||||
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: 'benchmark/run',
|
||||
arguments: { suite, iterations },
|
||||
});
|
||||
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess('Benchmark completed successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Benchmark failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute SPARC mode
|
||||
*/
|
||||
async executeSparc(args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.length === 0) {
|
||||
this.terminal.writeInfo('Available SPARC modes:');
|
||||
const modes = [
|
||||
'coder',
|
||||
'architect',
|
||||
'analyst',
|
||||
'researcher',
|
||||
'reviewer',
|
||||
'tester',
|
||||
'debugger',
|
||||
'documenter',
|
||||
'optimizer',
|
||||
'designer',
|
||||
];
|
||||
modes.forEach((mode) => {
|
||||
this.terminal.writeLine(` ${mode}`);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const mode = args[0];
|
||||
const task = args.slice(1).join(' ') || 'General task execution';
|
||||
const options = {};
|
||||
|
||||
this.terminal.writeInfo(`Executing SPARC mode: ${mode}...`);
|
||||
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: 'sparc/execute',
|
||||
arguments: { mode, task, options },
|
||||
});
|
||||
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess(`SPARC ${mode} mode executed successfully`);
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`SPARC execution failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute specific SPARC mode
|
||||
*/
|
||||
async executeSparcMode(mode, args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const task = args.join(' ') || `Execute ${mode} mode tasks`;
|
||||
const options = {};
|
||||
|
||||
this.terminal.writeInfo(`Executing SPARC ${mode} mode...`);
|
||||
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: 'sparc/execute',
|
||||
arguments: { mode, task, options },
|
||||
});
|
||||
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess(`SPARC ${mode} mode executed successfully`);
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`SPARC ${mode} execution failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute remote command via WebSocket
|
||||
*/
|
||||
async executeRemoteCommand(command, args) {
|
||||
if (!this.wsClient.isConnected) {
|
||||
this.terminal.writeError('Not connected to server. Use "connect" command first.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if this is a tool name (contains slash)
|
||||
if (command.includes('/')) {
|
||||
return await this.executeToolDirect(command, args);
|
||||
}
|
||||
|
||||
this.terminal.writeInfo(`Executing remote command: ${command}`);
|
||||
|
||||
const result = await this.wsClient.executeCommand(command, { args });
|
||||
|
||||
if (result && result.output) {
|
||||
this.terminal.writeLine(result.output);
|
||||
} else {
|
||||
this.terminal.writeSuccess('Command executed successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Remote command failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute tool directly by name
|
||||
*/
|
||||
async executeToolDirect(toolName, args) {
|
||||
try {
|
||||
this.terminal.writeInfo(`Executing tool: ${toolName}...`);
|
||||
|
||||
// Prepare arguments based on tool
|
||||
let toolArgs = {};
|
||||
|
||||
switch (toolName) {
|
||||
case 'system/health':
|
||||
toolArgs = { detailed: args.includes('--detailed') };
|
||||
break;
|
||||
|
||||
case 'memory/manage':
|
||||
toolArgs = {
|
||||
operation: args[0] || 'list',
|
||||
key: args[1],
|
||||
value: args.slice(2).join(' '),
|
||||
};
|
||||
break;
|
||||
|
||||
case 'agents/manage':
|
||||
toolArgs = {
|
||||
action: args[0] || 'list',
|
||||
agentType: args[1],
|
||||
agentId: args[1],
|
||||
};
|
||||
break;
|
||||
|
||||
case 'swarm/orchestrate':
|
||||
toolArgs = {
|
||||
action: args[0] || 'status',
|
||||
args: args.slice(1),
|
||||
};
|
||||
break;
|
||||
|
||||
case 'sparc/execute':
|
||||
toolArgs = {
|
||||
mode: args[0] || 'coder',
|
||||
task: args.slice(1).join(' ') || 'General task execution',
|
||||
options: {},
|
||||
};
|
||||
break;
|
||||
|
||||
case 'benchmark/run':
|
||||
toolArgs = {
|
||||
suite: args[0] || 'default',
|
||||
iterations: parseInt(args[1]) || 10,
|
||||
};
|
||||
break;
|
||||
|
||||
case 'claude-flow/execute':
|
||||
toolArgs = {
|
||||
command: args[0] || 'status',
|
||||
args: args.slice(1),
|
||||
};
|
||||
break;
|
||||
|
||||
default:
|
||||
toolArgs = { args };
|
||||
}
|
||||
|
||||
const result = await this.wsClient.sendRequest('tools/call', {
|
||||
name: toolName,
|
||||
arguments: toolArgs,
|
||||
});
|
||||
|
||||
if (result && result.content && result.content[0]) {
|
||||
this.terminal.writeSuccess(result.content[0].text);
|
||||
} else {
|
||||
this.terminal.writeSuccess(`Tool ${toolName} executed successfully`);
|
||||
}
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`Tool execution failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Download file helper
|
||||
*/
|
||||
downloadFile(blob, filename) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get command suggestions
|
||||
*/
|
||||
getCommandSuggestions(input) {
|
||||
const allCommands = Object.keys(this.allCommands);
|
||||
return allCommands.filter((cmd) => cmd.startsWith(input.toLowerCase()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if command exists
|
||||
*/
|
||||
hasCommand(command) {
|
||||
return this.allCommands.hasOwnProperty(command.toLowerCase());
|
||||
}
|
||||
}
|
||||
@@ -1,669 +0,0 @@
|
||||
/**
|
||||
* Main Console Application
|
||||
* Coordinates all components of the Claude Code Console
|
||||
*/
|
||||
|
||||
import { WebSocketClient } from './websocket-client.js';
|
||||
import { TerminalEmulator } from './terminal-emulator.js';
|
||||
import { CommandHandler } from './command-handler.js';
|
||||
import { SettingsManager } from './settings.js';
|
||||
|
||||
class ClaudeCodeConsole {
|
||||
constructor() {
|
||||
// Initialize components
|
||||
this.wsClient = new WebSocketClient();
|
||||
this.terminal = null;
|
||||
this.commandHandler = null;
|
||||
this.settings = new SettingsManager();
|
||||
|
||||
// State management
|
||||
this.isInitialized = false;
|
||||
this.startTime = Date.now();
|
||||
this.messageCount = 0;
|
||||
this.activeAgents = 0;
|
||||
|
||||
// DOM elements
|
||||
this.elements = {};
|
||||
|
||||
// Status update intervals
|
||||
this.statusInterval = null;
|
||||
this.uptimeInterval = null;
|
||||
|
||||
this.setupEventListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the console application
|
||||
*/
|
||||
async init() {
|
||||
if (this.isInitialized) return;
|
||||
|
||||
try {
|
||||
// Show loading overlay
|
||||
this.showLoading('Initializing Claude Code Console...');
|
||||
|
||||
// Get DOM elements
|
||||
this.getDOMElements();
|
||||
|
||||
// Initialize terminal emulator
|
||||
this.terminal = new TerminalEmulator(this.elements.consoleOutput, this.elements.consoleInput);
|
||||
|
||||
// Initialize command handler
|
||||
this.commandHandler = new CommandHandler(this.terminal, this.wsClient);
|
||||
|
||||
// Initialize settings
|
||||
this.settings.init();
|
||||
|
||||
// Setup component interactions
|
||||
this.setupComponentInteractions();
|
||||
|
||||
// Setup UI event handlers
|
||||
this.setupUIEventHandlers();
|
||||
|
||||
// Apply initial settings
|
||||
this.applyInitialSettings();
|
||||
|
||||
// Start status updates
|
||||
this.startStatusUpdates();
|
||||
|
||||
// Hide loading overlay
|
||||
this.hideLoading();
|
||||
|
||||
// Show welcome message
|
||||
this.showWelcomeMessage();
|
||||
|
||||
// Auto-connect if enabled
|
||||
if (this.settings.get('autoConnect')) {
|
||||
await this.autoConnect();
|
||||
}
|
||||
|
||||
this.isInitialized = true;
|
||||
console.log('Claude Code Console initialized successfully');
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize console:', error);
|
||||
this.showError('Failed to initialize console: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get DOM elements
|
||||
*/
|
||||
getDOMElements() {
|
||||
this.elements = {
|
||||
consoleOutput: document.getElementById('consoleOutput'),
|
||||
consoleInput: document.getElementById('consoleInput'),
|
||||
settingsPanel: document.getElementById('settingsPanel'),
|
||||
loadingOverlay: document.getElementById('loadingOverlay'),
|
||||
connectionStatus: document.getElementById('connectionStatus'),
|
||||
statusIndicator: document.getElementById('statusIndicator'),
|
||||
statusText: document.getElementById('statusText'),
|
||||
currentMode: document.getElementById('currentMode'),
|
||||
activeAgents: document.getElementById('activeAgents'),
|
||||
uptime: document.getElementById('uptime'),
|
||||
memoryUsage: document.getElementById('memoryUsage'),
|
||||
messageCount: document.getElementById('messageCount'),
|
||||
timestamp: document.getElementById('timestamp'),
|
||||
clearConsole: document.getElementById('clearConsole'),
|
||||
fullscreenToggle: document.getElementById('fullscreenToggle'),
|
||||
};
|
||||
|
||||
// Validate required elements
|
||||
const required = ['consoleOutput', 'consoleInput', 'loadingOverlay'];
|
||||
for (const elementId of required) {
|
||||
if (!this.elements[elementId]) {
|
||||
throw new Error(`Required element not found: ${elementId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup component interactions
|
||||
*/
|
||||
setupComponentInteractions() {
|
||||
// Terminal -> Command Handler
|
||||
this.terminal.on('command', (command) => {
|
||||
this.commandHandler.processCommand(command);
|
||||
});
|
||||
|
||||
this.terminal.on('interrupt', () => {
|
||||
this.handleInterrupt();
|
||||
});
|
||||
|
||||
// WebSocket -> Terminal
|
||||
this.wsClient.on('connected', () => {
|
||||
this.updateConnectionStatus(true, false);
|
||||
this.terminal.writeSuccess('Connected to Claude Code server');
|
||||
this.terminal.setPrompt('claude-flow>');
|
||||
});
|
||||
|
||||
this.wsClient.on('disconnected', (info) => {
|
||||
this.updateConnectionStatus(false, false);
|
||||
this.terminal.writeWarning('Disconnected from server');
|
||||
this.terminal.setPrompt('offline>');
|
||||
|
||||
if (info && info.code !== 1000) {
|
||||
this.terminal.writeError(`Connection lost: ${info.reason || 'Unknown reason'}`);
|
||||
}
|
||||
});
|
||||
|
||||
this.wsClient.on('reconnecting', (info) => {
|
||||
this.updateConnectionStatus(false, true);
|
||||
this.terminal.writeInfo(
|
||||
`Reconnecting... (${info.attempt}/${this.wsClient.maxReconnectAttempts})`,
|
||||
);
|
||||
});
|
||||
|
||||
this.wsClient.on('error', (error) => {
|
||||
this.terminal.writeError(`WebSocket error: ${error.message || 'Unknown error'}`);
|
||||
});
|
||||
|
||||
this.wsClient.on('message_received', (message) => {
|
||||
this.messageCount++;
|
||||
this.handleIncomingMessage(message);
|
||||
});
|
||||
|
||||
this.wsClient.on('notification', (notification) => {
|
||||
this.handleNotification(notification);
|
||||
});
|
||||
|
||||
// Settings -> Application
|
||||
this.settings.on('connect_requested', async (config) => {
|
||||
await this.connect(config.url, config.token);
|
||||
});
|
||||
|
||||
this.settings.on('disconnect_requested', () => {
|
||||
this.disconnect();
|
||||
});
|
||||
|
||||
this.settings.on('max_lines_changed', (maxLines) => {
|
||||
this.terminal.setMaxLines(maxLines);
|
||||
});
|
||||
|
||||
this.settings.on('setting_changed', ({ key, value }) => {
|
||||
this.handleSettingChange(key, value);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup UI event handlers
|
||||
*/
|
||||
setupUIEventHandlers() {
|
||||
// Clear console button
|
||||
if (this.elements.clearConsole) {
|
||||
this.elements.clearConsole.addEventListener('click', () => {
|
||||
this.terminal.clear();
|
||||
});
|
||||
}
|
||||
|
||||
// Fullscreen toggle
|
||||
if (this.elements.fullscreenToggle) {
|
||||
this.elements.fullscreenToggle.addEventListener('click', () => {
|
||||
this.toggleFullscreen();
|
||||
});
|
||||
}
|
||||
|
||||
// Focus input when clicking on output area
|
||||
if (this.elements.consoleOutput) {
|
||||
this.elements.consoleOutput.addEventListener('click', () => {
|
||||
this.terminal.focus();
|
||||
});
|
||||
}
|
||||
|
||||
// Handle window focus
|
||||
window.addEventListener('focus', () => {
|
||||
this.terminal.focus();
|
||||
});
|
||||
|
||||
// Handle visibility change
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (!document.hidden) {
|
||||
this.updateTimestamp();
|
||||
}
|
||||
});
|
||||
|
||||
// Handle page unload
|
||||
window.addEventListener('beforeunload', () => {
|
||||
this.cleanup();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply initial settings
|
||||
*/
|
||||
applyInitialSettings() {
|
||||
const maxLines = this.settings.get('maxLines');
|
||||
if (maxLines) {
|
||||
this.terminal.setMaxLines(maxLines);
|
||||
}
|
||||
|
||||
// Update connection status in settings
|
||||
this.settings.updateConnectionStatus(this.wsClient.getStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* Show welcome message
|
||||
*/
|
||||
showWelcomeMessage() {
|
||||
this.terminal.showWelcomeMessage();
|
||||
this.terminal.writeInfo('Console ready. Type "help" for available commands.');
|
||||
|
||||
const config = this.settings.getConnectionConfig();
|
||||
if (config.url && !config.autoConnect) {
|
||||
this.terminal.writeInfo(`Use "connect" to connect to ${config.url}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-connect to server
|
||||
*/
|
||||
async autoConnect() {
|
||||
const config = this.settings.getConnectionConfig();
|
||||
|
||||
if (config.url) {
|
||||
this.terminal.writeInfo(`Auto-connecting to ${config.url}...`);
|
||||
await this.connect(config.url, config.token);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to server
|
||||
*/
|
||||
async connect(url, token = '') {
|
||||
try {
|
||||
this.updateConnectionStatus(false, true);
|
||||
await this.wsClient.connect(url, token);
|
||||
await this.wsClient.initializeSession();
|
||||
|
||||
// Update settings with successful connection
|
||||
this.settings.set('serverUrl', url);
|
||||
if (token) {
|
||||
this.settings.set('authToken', token);
|
||||
}
|
||||
} catch (error) {
|
||||
this.updateConnectionStatus(false, false);
|
||||
this.terminal.writeError(`Connection failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect from server
|
||||
*/
|
||||
disconnect() {
|
||||
this.wsClient.disconnect();
|
||||
this.updateConnectionStatus(false, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update connection status in UI
|
||||
*/
|
||||
updateConnectionStatus(connected, connecting) {
|
||||
const status = this.wsClient.getStatus();
|
||||
|
||||
// Update status indicator
|
||||
if (this.elements.statusIndicator) {
|
||||
this.elements.statusIndicator.className =
|
||||
'status-indicator ' + (connected ? 'connected' : connecting ? 'connecting' : '');
|
||||
}
|
||||
|
||||
// Update status text
|
||||
if (this.elements.statusText) {
|
||||
this.elements.statusText.textContent = connected
|
||||
? 'Connected'
|
||||
: connecting
|
||||
? 'Connecting...'
|
||||
: 'Disconnected';
|
||||
}
|
||||
|
||||
// Update settings panel
|
||||
this.settings.updateConnectionStatus(status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle incoming messages
|
||||
*/
|
||||
handleIncomingMessage(message) {
|
||||
// Handle streaming output
|
||||
if (message.method === 'output/stream') {
|
||||
this.handleStreamingOutput(message.params);
|
||||
}
|
||||
|
||||
// Handle Claude Flow notifications
|
||||
if (message.method && message.method.startsWith('claude-flow/')) {
|
||||
this.handleClaudeFlowNotification(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle notifications
|
||||
*/
|
||||
handleNotification(notification) {
|
||||
const { method, params } = notification;
|
||||
|
||||
switch (method) {
|
||||
case 'agent/status':
|
||||
this.handleAgentStatus(params);
|
||||
break;
|
||||
|
||||
case 'swarm/update':
|
||||
this.handleSwarmUpdate(params);
|
||||
break;
|
||||
|
||||
case 'memory/update':
|
||||
this.handleMemoryUpdate(params);
|
||||
break;
|
||||
|
||||
case 'log/message':
|
||||
this.handleLogMessage(params);
|
||||
break;
|
||||
|
||||
case 'connection/established':
|
||||
this.handleConnectionEstablished(params);
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log('Unhandled notification:', method, params);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle streaming output
|
||||
*/
|
||||
handleStreamingOutput(params) {
|
||||
if (params && params.content) {
|
||||
const type = params.type || 'output';
|
||||
|
||||
if (params.streaming) {
|
||||
// Use streaming text effect for long outputs
|
||||
this.terminal.streamText(params.content, 10);
|
||||
} else {
|
||||
this.terminal.write(params.content, type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle Claude Flow notifications
|
||||
*/
|
||||
handleClaudeFlowNotification(message) {
|
||||
const { method, params } = message;
|
||||
|
||||
switch (method) {
|
||||
case 'claude-flow/started':
|
||||
this.terminal.writeSuccess(`Claude Flow started in ${params.mode} mode`);
|
||||
break;
|
||||
|
||||
case 'claude-flow/stopped':
|
||||
this.terminal.writeInfo('Claude Flow stopped');
|
||||
break;
|
||||
|
||||
case 'claude-flow/error':
|
||||
this.terminal.writeError(`Claude Flow error: ${params.message}`);
|
||||
break;
|
||||
|
||||
default:
|
||||
this.terminal.writeInfo(`Claude Flow: ${method} - ${JSON.stringify(params)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle agent status updates
|
||||
*/
|
||||
handleAgentStatus(params) {
|
||||
if (params.active !== undefined) {
|
||||
this.activeAgents = params.active;
|
||||
}
|
||||
|
||||
if (params.message) {
|
||||
this.terminal.writeInfo(`Agent: ${params.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle swarm updates
|
||||
*/
|
||||
handleSwarmUpdate(params) {
|
||||
if (params.message) {
|
||||
this.terminal.writeInfo(`Swarm: ${params.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle memory updates
|
||||
*/
|
||||
handleMemoryUpdate(params) {
|
||||
if (params.message) {
|
||||
this.terminal.writeInfo(`Memory: ${params.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle log messages
|
||||
*/
|
||||
handleLogMessage(params) {
|
||||
if (params.level && params.message) {
|
||||
const type =
|
||||
params.level === 'error' ? 'error' : params.level === 'warn' ? 'warning' : 'info';
|
||||
this.terminal.write(`[${params.level.toUpperCase()}] ${params.message}`, type);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle connection established notification
|
||||
*/
|
||||
handleConnectionEstablished(params) {
|
||||
// Log connection details without cluttering the terminal
|
||||
console.log('Connection established:', params);
|
||||
// Optionally show a brief success message
|
||||
// this.terminal.writeSuccess(`Connected to ${params.server} v${params.version}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle interrupt (Ctrl+C)
|
||||
*/
|
||||
handleInterrupt() {
|
||||
// Could be used to cancel running commands
|
||||
this.terminal.writeWarning('Interrupt signal sent');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle setting changes
|
||||
*/
|
||||
handleSettingChange(key, value) {
|
||||
switch (key) {
|
||||
case 'theme':
|
||||
document.documentElement.setAttribute('data-theme', value);
|
||||
break;
|
||||
|
||||
case 'fontSize':
|
||||
document.documentElement.style.setProperty('--font-size-base', `${value}px`);
|
||||
break;
|
||||
|
||||
case 'lineHeight':
|
||||
document.documentElement.style.setProperty('--line-height', value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start status updates
|
||||
*/
|
||||
startStatusUpdates() {
|
||||
// Update status every 5 seconds
|
||||
this.statusInterval = setInterval(() => {
|
||||
this.updateStatus();
|
||||
}, 5000);
|
||||
|
||||
// Update timestamp every second
|
||||
this.uptimeInterval = setInterval(() => {
|
||||
this.updateUptime();
|
||||
this.updateTimestamp();
|
||||
}, 1000);
|
||||
|
||||
// Initial update
|
||||
this.updateStatus();
|
||||
this.updateUptime();
|
||||
this.updateTimestamp();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update status bar
|
||||
*/
|
||||
updateStatus() {
|
||||
// Update active agents
|
||||
if (this.elements.activeAgents) {
|
||||
this.elements.activeAgents.textContent = `Agents: ${this.activeAgents}`;
|
||||
}
|
||||
|
||||
// Update message count
|
||||
if (this.elements.messageCount) {
|
||||
this.elements.messageCount.textContent = `Messages: ${this.messageCount}`;
|
||||
}
|
||||
|
||||
// Update memory usage (if available)
|
||||
if (this.elements.memoryUsage && performance.memory) {
|
||||
const used = Math.round(performance.memory.usedJSHeapSize / 1024 / 1024);
|
||||
this.elements.memoryUsage.textContent = `Memory: ${used}MB`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update uptime
|
||||
*/
|
||||
updateUptime() {
|
||||
if (this.elements.uptime) {
|
||||
const uptime = Date.now() - this.startTime;
|
||||
const hours = Math.floor(uptime / (1000 * 60 * 60));
|
||||
const minutes = Math.floor((uptime % (1000 * 60 * 60)) / (1000 * 60));
|
||||
const seconds = Math.floor((uptime % (1000 * 60)) / 1000);
|
||||
|
||||
this.elements.uptime.textContent = `Uptime: ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update timestamp
|
||||
*/
|
||||
updateTimestamp() {
|
||||
if (this.elements.timestamp) {
|
||||
this.elements.timestamp.textContent = new Date().toLocaleTimeString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle fullscreen mode
|
||||
*/
|
||||
toggleFullscreen() {
|
||||
if (!document.fullscreenElement) {
|
||||
document.documentElement.requestFullscreen().catch((err) => {
|
||||
console.error('Error attempting to enable fullscreen:', err);
|
||||
});
|
||||
} else {
|
||||
document.exitFullscreen();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show loading overlay
|
||||
*/
|
||||
showLoading(message = 'Loading...') {
|
||||
if (this.elements.loadingOverlay) {
|
||||
const loadingText = this.elements.loadingOverlay.querySelector('.loading-text');
|
||||
if (loadingText) {
|
||||
loadingText.textContent = message;
|
||||
}
|
||||
this.elements.loadingOverlay.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide loading overlay
|
||||
*/
|
||||
hideLoading() {
|
||||
if (this.elements.loadingOverlay) {
|
||||
this.elements.loadingOverlay.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show error message
|
||||
*/
|
||||
showError(message) {
|
||||
this.hideLoading();
|
||||
|
||||
if (this.terminal) {
|
||||
this.terminal.writeError(message);
|
||||
} else {
|
||||
// Fallback if terminal isn't initialized
|
||||
console.error(message);
|
||||
alert(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup global event listeners
|
||||
*/
|
||||
setupEventListeners() {
|
||||
// Handle unhandled promise rejections
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
console.error('Unhandled promise rejection:', event.reason);
|
||||
if (this.terminal) {
|
||||
this.terminal.writeError(`Unhandled error: ${event.reason.message || event.reason}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle errors
|
||||
window.addEventListener('error', (event) => {
|
||||
console.error('Global error:', event.error);
|
||||
if (this.terminal) {
|
||||
this.terminal.writeError(`Application error: ${event.error.message || event.error}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup on shutdown
|
||||
*/
|
||||
cleanup() {
|
||||
// Clear intervals
|
||||
if (this.statusInterval) {
|
||||
clearInterval(this.statusInterval);
|
||||
}
|
||||
|
||||
if (this.uptimeInterval) {
|
||||
clearInterval(this.uptimeInterval);
|
||||
}
|
||||
|
||||
// Disconnect WebSocket
|
||||
if (this.wsClient) {
|
||||
this.wsClient.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get console statistics
|
||||
*/
|
||||
getStats() {
|
||||
return {
|
||||
initialized: this.isInitialized,
|
||||
uptime: Date.now() - this.startTime,
|
||||
messageCount: this.messageCount,
|
||||
activeAgents: this.activeAgents,
|
||||
connection: this.wsClient.getStatus(),
|
||||
terminal: this.terminal ? this.terminal.getStats() : null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize the console when DOM is ready
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
const console = new ClaudeCodeConsole();
|
||||
|
||||
// Make console globally available for debugging
|
||||
window.claudeConsole = console;
|
||||
|
||||
// Initialize the application
|
||||
await console.init();
|
||||
});
|
||||
|
||||
// Export for module usage
|
||||
export { ClaudeCodeConsole };
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,961 +0,0 @@
|
||||
/**
|
||||
* Memory Management Interface
|
||||
* Comprehensive memory management system for Claude Flow
|
||||
*/
|
||||
|
||||
class MemoryInterface {
|
||||
constructor() {
|
||||
this.container = null;
|
||||
this.currentNamespace = 'global';
|
||||
this.memoryData = new Map();
|
||||
this.searchFilters = {};
|
||||
this.analytics = {
|
||||
usage: new Map(),
|
||||
history: [],
|
||||
patterns: new Map(),
|
||||
};
|
||||
this.backupManager = new BackupManager();
|
||||
this.syncManager = new SyncManager();
|
||||
this.compressionManager = new CompressionManager();
|
||||
this.visualizer = new MemoryVisualizer();
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.createInterface();
|
||||
this.setupEventListeners();
|
||||
this.startMonitoring();
|
||||
this.loadMemoryData();
|
||||
}
|
||||
|
||||
createInterface() {
|
||||
this.container = document.createElement('div');
|
||||
this.container.className = 'memory-interface';
|
||||
this.container.innerHTML = `
|
||||
<div class="memory-header">
|
||||
<h2>Memory Management Interface</h2>
|
||||
<div class="memory-controls">
|
||||
<button class="btn-refresh" title="Refresh Data">
|
||||
<i class="icon-refresh"></i>
|
||||
</button>
|
||||
<button class="btn-backup" title="Create Backup">
|
||||
<i class="icon-backup"></i>
|
||||
</button>
|
||||
<button class="btn-compress" title="Optimize Memory">
|
||||
<i class="icon-compress"></i>
|
||||
</button>
|
||||
<button class="btn-sync" title="Sync Status">
|
||||
<i class="icon-sync"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="memory-layout">
|
||||
<!-- Namespace Browser -->
|
||||
<div class="namespace-panel">
|
||||
<div class="panel-header">
|
||||
<h3>Namespace Browser</h3>
|
||||
<button class="btn-add-namespace" title="Add Namespace">+</button>
|
||||
</div>
|
||||
<div class="namespace-tree">
|
||||
<div class="namespace-search">
|
||||
<input type="text" placeholder="Search namespaces..."
|
||||
class="namespace-search-input">
|
||||
</div>
|
||||
<div class="namespace-tree-container">
|
||||
<!-- Namespace tree will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Key-Value Editor -->
|
||||
<div class="editor-panel">
|
||||
<div class="panel-header">
|
||||
<h3>Key-Value Editor</h3>
|
||||
<div class="editor-controls">
|
||||
<button class="btn-add-key" title="Add Key">+</button>
|
||||
<button class="btn-bulk-edit" title="Bulk Edit">Bulk</button>
|
||||
<button class="btn-export" title="Export">Export</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="editor-content">
|
||||
<div class="editor-search">
|
||||
<input type="text" placeholder="Search keys..."
|
||||
class="key-search-input">
|
||||
<select class="type-filter">
|
||||
<option value="">All Types</option>
|
||||
<option value="string">String</option>
|
||||
<option value="number">Number</option>
|
||||
<option value="boolean">Boolean</option>
|
||||
<option value="object">Object</option>
|
||||
<option value="array">Array</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="key-value-list">
|
||||
<!-- Key-value pairs will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Analytics Dashboard -->
|
||||
<div class="analytics-panel">
|
||||
<div class="panel-header">
|
||||
<h3>Memory Analytics</h3>
|
||||
<select class="analytics-timeframe">
|
||||
<option value="1h">Last Hour</option>
|
||||
<option value="24h">Last 24 Hours</option>
|
||||
<option value="7d">Last 7 Days</option>
|
||||
<option value="30d">Last 30 Days</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="analytics-content">
|
||||
<div class="analytics-stats">
|
||||
<div class="stat-card">
|
||||
<h4>Total Keys</h4>
|
||||
<span class="stat-value" id="total-keys">0</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<h4>Memory Usage</h4>
|
||||
<span class="stat-value" id="memory-usage">0 KB</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<h4>Compression Rate</h4>
|
||||
<span class="stat-value" id="compression-rate">0%</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<h4>Access Frequency</h4>
|
||||
<span class="stat-value" id="access-frequency">0/min</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="analytics-charts">
|
||||
<div class="chart-container">
|
||||
<canvas id="usage-chart"></canvas>
|
||||
</div>
|
||||
<div class="chart-container">
|
||||
<canvas id="pattern-chart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Search Interface -->
|
||||
<div class="search-panel">
|
||||
<div class="panel-header">
|
||||
<h3>Advanced Search</h3>
|
||||
<button class="btn-saved-searches" title="Saved Searches">
|
||||
<i class="icon-bookmark"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="search-content">
|
||||
<div class="search-builder">
|
||||
<div class="search-row">
|
||||
<select class="search-field">
|
||||
<option value="key">Key</option>
|
||||
<option value="value">Value</option>
|
||||
<option value="type">Type</option>
|
||||
<option value="namespace">Namespace</option>
|
||||
<option value="created">Created Date</option>
|
||||
<option value="modified">Modified Date</option>
|
||||
</select>
|
||||
<select class="search-operator">
|
||||
<option value="contains">Contains</option>
|
||||
<option value="equals">Equals</option>
|
||||
<option value="startsWith">Starts With</option>
|
||||
<option value="endsWith">Ends With</option>
|
||||
<option value="regex">Regex</option>
|
||||
</select>
|
||||
<input type="text" class="search-value" placeholder="Search value...">
|
||||
<button class="btn-add-filter">+</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="search-filters">
|
||||
<!-- Active filters will be shown here -->
|
||||
</div>
|
||||
<div class="search-results">
|
||||
<!-- Search results will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Backup/Restore Panel -->
|
||||
<div class="backup-panel">
|
||||
<div class="panel-header">
|
||||
<h3>Backup & Restore</h3>
|
||||
<button class="btn-schedule-backup" title="Schedule Backup">
|
||||
<i class="icon-schedule"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="backup-content">
|
||||
<div class="backup-controls">
|
||||
<button class="btn-create-backup">Create Backup</button>
|
||||
<button class="btn-restore-backup">Restore Backup</button>
|
||||
<button class="btn-import-backup">Import Backup</button>
|
||||
</div>
|
||||
<div class="backup-list">
|
||||
<!-- Backup list will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modals -->
|
||||
<div class="modal-overlay" id="modal-overlay">
|
||||
<div class="modal" id="key-editor-modal">
|
||||
<div class="modal-header">
|
||||
<h3>Edit Key-Value Pair</h3>
|
||||
<button class="btn-close-modal">×</button>
|
||||
</div>
|
||||
<div class="modal-content">
|
||||
<form id="key-editor-form">
|
||||
<div class="form-group">
|
||||
<label>Key:</label>
|
||||
<input type="text" id="edit-key" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Type:</label>
|
||||
<select id="edit-type">
|
||||
<option value="string">String</option>
|
||||
<option value="number">Number</option>
|
||||
<option value="boolean">Boolean</option>
|
||||
<option value="object">Object</option>
|
||||
<option value="array">Array</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Value:</label>
|
||||
<textarea id="edit-value" rows="10"></textarea>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Namespace:</label>
|
||||
<select id="edit-namespace">
|
||||
<!-- Namespaces will be populated here -->
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn-save">Save</button>
|
||||
<button type="button" class="btn-cancel">Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
setupEventListeners() {
|
||||
// Header controls
|
||||
this.container.querySelector('.btn-refresh').addEventListener('click', () => this.refresh());
|
||||
this.container
|
||||
.querySelector('.btn-backup')
|
||||
.addEventListener('click', () => this.createBackup());
|
||||
this.container
|
||||
.querySelector('.btn-compress')
|
||||
.addEventListener('click', () => this.optimizeMemory());
|
||||
this.container
|
||||
.querySelector('.btn-sync')
|
||||
.addEventListener('click', () => this.showSyncStatus());
|
||||
|
||||
// Namespace controls
|
||||
this.container
|
||||
.querySelector('.btn-add-namespace')
|
||||
.addEventListener('click', () => this.addNamespace());
|
||||
this.container
|
||||
.querySelector('.namespace-search-input')
|
||||
.addEventListener('input', (e) => this.searchNamespaces(e.target.value));
|
||||
|
||||
// Editor controls
|
||||
this.container.querySelector('.btn-add-key').addEventListener('click', () => this.addKey());
|
||||
this.container.querySelector('.btn-bulk-edit').addEventListener('click', () => this.bulkEdit());
|
||||
this.container
|
||||
.querySelector('.btn-export')
|
||||
.addEventListener('click', () => this.exportMemory());
|
||||
|
||||
// Search controls
|
||||
this.container
|
||||
.querySelector('.key-search-input')
|
||||
.addEventListener('input', (e) => this.searchKeys(e.target.value));
|
||||
this.container
|
||||
.querySelector('.type-filter')
|
||||
.addEventListener('change', (e) => this.filterByType(e.target.value));
|
||||
|
||||
// Analytics controls
|
||||
this.container
|
||||
.querySelector('.analytics-timeframe')
|
||||
.addEventListener('change', (e) => this.updateAnalytics(e.target.value));
|
||||
|
||||
// Search interface
|
||||
this.container
|
||||
.querySelector('.btn-add-filter')
|
||||
.addEventListener('click', () => this.addSearchFilter());
|
||||
this.container
|
||||
.querySelector('.btn-saved-searches')
|
||||
.addEventListener('click', () => this.showSavedSearches());
|
||||
|
||||
// Backup controls
|
||||
this.container
|
||||
.querySelector('.btn-create-backup')
|
||||
.addEventListener('click', () => this.createBackup());
|
||||
this.container
|
||||
.querySelector('.btn-restore-backup')
|
||||
.addEventListener('click', () => this.restoreBackup());
|
||||
this.container
|
||||
.querySelector('.btn-import-backup')
|
||||
.addEventListener('click', () => this.importBackup());
|
||||
|
||||
// Modal controls
|
||||
this.container
|
||||
.querySelector('.btn-close-modal')
|
||||
.addEventListener('click', () => this.closeModal());
|
||||
this.container.querySelector('.modal-overlay').addEventListener('click', (e) => {
|
||||
if (e.target === this.container.querySelector('.modal-overlay')) {
|
||||
this.closeModal();
|
||||
}
|
||||
});
|
||||
|
||||
// Form submission
|
||||
this.container
|
||||
.querySelector('#key-editor-form')
|
||||
.addEventListener('submit', (e) => this.saveKeyValue(e));
|
||||
}
|
||||
|
||||
async loadMemoryData() {
|
||||
try {
|
||||
// Load memory data from Claude Flow's memory system
|
||||
const response = await fetch('/api/memory/list');
|
||||
const data = await response.json();
|
||||
|
||||
this.memoryData = new Map(Object.entries(data));
|
||||
this.updateNamespaceTree();
|
||||
this.updateKeyValueList();
|
||||
this.updateAnalytics();
|
||||
} catch (error) {
|
||||
console.error('Failed to load memory data:', error);
|
||||
this.showError('Failed to load memory data');
|
||||
}
|
||||
}
|
||||
|
||||
updateNamespaceTree() {
|
||||
const container = this.container.querySelector('.namespace-tree-container');
|
||||
const namespaces = this.getNamespaces();
|
||||
|
||||
container.innerHTML = this.renderNamespaceTree(namespaces);
|
||||
|
||||
// Add click handlers for namespace items
|
||||
container.querySelectorAll('.namespace-item').forEach((item) => {
|
||||
item.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.selectNamespace(item.dataset.namespace);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
renderNamespaceTree(namespaces, parent = '', level = 0) {
|
||||
let html = '';
|
||||
|
||||
for (const [namespace, data] of namespaces) {
|
||||
const fullPath = parent ? `${parent}.${namespace}` : namespace;
|
||||
const hasChildren = data.children && data.children.size > 0;
|
||||
|
||||
html += `
|
||||
<div class="namespace-item ${this.currentNamespace === fullPath ? 'active' : ''}"
|
||||
data-namespace="${fullPath}"
|
||||
style="padding-left: ${level * 20}px">
|
||||
<div class="namespace-content">
|
||||
${hasChildren ? '<i class="icon-folder"></i>' : '<i class="icon-file"></i>'}
|
||||
<span class="namespace-name">${namespace}</span>
|
||||
<span class="namespace-count">(${data.count})</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
if (hasChildren) {
|
||||
html += this.renderNamespaceTree(data.children, fullPath, level + 1);
|
||||
}
|
||||
}
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
updateKeyValueList() {
|
||||
const container = this.container.querySelector('.key-value-list');
|
||||
const keys = this.getKeysForNamespace(this.currentNamespace);
|
||||
|
||||
container.innerHTML = keys.map((key) => this.renderKeyValueItem(key)).join('');
|
||||
|
||||
// Add event listeners for key-value items
|
||||
container.querySelectorAll('.key-value-item').forEach((item) => {
|
||||
item
|
||||
.querySelector('.btn-edit')
|
||||
.addEventListener('click', () => this.editKey(item.dataset.key));
|
||||
item
|
||||
.querySelector('.btn-delete')
|
||||
.addEventListener('click', () => this.deleteKey(item.dataset.key));
|
||||
item
|
||||
.querySelector('.btn-copy')
|
||||
.addEventListener('click', () => this.copyKey(item.dataset.key));
|
||||
});
|
||||
}
|
||||
|
||||
renderKeyValueItem(key) {
|
||||
const value = this.memoryData.get(key);
|
||||
const type = this.getValueType(value);
|
||||
const displayValue = this.formatValueForDisplay(value, type);
|
||||
|
||||
return `
|
||||
<div class="key-value-item" data-key="${key}">
|
||||
<div class="key-info">
|
||||
<span class="key-name">${key}</span>
|
||||
<span class="key-type">${type}</span>
|
||||
</div>
|
||||
<div class="value-preview">
|
||||
<span class="value-content">${displayValue}</span>
|
||||
</div>
|
||||
<div class="item-actions">
|
||||
<button class="btn-edit" title="Edit">
|
||||
<i class="icon-edit"></i>
|
||||
</button>
|
||||
<button class="btn-copy" title="Copy">
|
||||
<i class="icon-copy"></i>
|
||||
</button>
|
||||
<button class="btn-delete" title="Delete">
|
||||
<i class="icon-delete"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
getNamespaces() {
|
||||
const namespaces = new Map();
|
||||
|
||||
for (const [key, value] of this.memoryData) {
|
||||
const parts = key.split('.');
|
||||
let current = namespaces;
|
||||
let path = '';
|
||||
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
const part = parts[i];
|
||||
path = path ? `${path}.${part}` : part;
|
||||
|
||||
if (!current.has(part)) {
|
||||
current.set(part, {
|
||||
count: 0,
|
||||
children: new Map(),
|
||||
});
|
||||
}
|
||||
|
||||
current = current.get(part).children;
|
||||
}
|
||||
|
||||
// Count the final key
|
||||
const finalPart = parts[parts.length - 1];
|
||||
if (!current.has(finalPart)) {
|
||||
current.set(finalPart, { count: 0, children: new Map() });
|
||||
}
|
||||
current.get(finalPart).count++;
|
||||
}
|
||||
|
||||
return namespaces;
|
||||
}
|
||||
|
||||
getKeysForNamespace(namespace) {
|
||||
const keys = [];
|
||||
const prefix = namespace === 'global' ? '' : `${namespace}.`;
|
||||
|
||||
for (const [key, value] of this.memoryData) {
|
||||
if (namespace === 'global' || key.startsWith(prefix)) {
|
||||
keys.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
return keys.sort();
|
||||
}
|
||||
|
||||
getValueType(value) {
|
||||
if (value === null) return 'null';
|
||||
if (value === undefined) return 'undefined';
|
||||
if (Array.isArray(value)) return 'array';
|
||||
return typeof value;
|
||||
}
|
||||
|
||||
formatValueForDisplay(value, type) {
|
||||
switch (type) {
|
||||
case 'string':
|
||||
return value.length > 50 ? `${value.substring(0, 50)}...` : value;
|
||||
case 'object':
|
||||
return JSON.stringify(value).substring(0, 100) + '...';
|
||||
case 'array':
|
||||
return `[${value.length} items]`;
|
||||
default:
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
updateAnalytics(timeframe = '24h') {
|
||||
const stats = this.calculateStats(timeframe);
|
||||
|
||||
// Update stat cards
|
||||
this.container.querySelector('#total-keys').textContent = stats.totalKeys;
|
||||
this.container.querySelector('#memory-usage').textContent = stats.memoryUsage;
|
||||
this.container.querySelector('#compression-rate').textContent = stats.compressionRate;
|
||||
this.container.querySelector('#access-frequency').textContent = stats.accessFrequency;
|
||||
|
||||
// Update charts
|
||||
this.visualizer.updateUsageChart(stats.usageData);
|
||||
this.visualizer.updatePatternChart(stats.patternData);
|
||||
}
|
||||
|
||||
calculateStats(timeframe) {
|
||||
const now = Date.now();
|
||||
const timeframes = {
|
||||
'1h': 60 * 60 * 1000,
|
||||
'24h': 24 * 60 * 60 * 1000,
|
||||
'7d': 7 * 24 * 60 * 60 * 1000,
|
||||
'30d': 30 * 24 * 60 * 60 * 1000,
|
||||
};
|
||||
|
||||
const cutoff = now - timeframes[timeframe];
|
||||
|
||||
return {
|
||||
totalKeys: this.memoryData.size,
|
||||
memoryUsage: this.calculateMemoryUsage(),
|
||||
compressionRate: this.compressionManager.getCompressionRate(),
|
||||
accessFrequency: this.calculateAccessFrequency(cutoff),
|
||||
usageData: this.getUsageData(cutoff),
|
||||
patternData: this.getPatternData(cutoff),
|
||||
};
|
||||
}
|
||||
|
||||
calculateMemoryUsage() {
|
||||
let totalSize = 0;
|
||||
for (const [key, value] of this.memoryData) {
|
||||
totalSize += this.getObjectSize(key) + this.getObjectSize(value);
|
||||
}
|
||||
return this.formatBytes(totalSize);
|
||||
}
|
||||
|
||||
getObjectSize(obj) {
|
||||
let size = 0;
|
||||
if (typeof obj === 'string') {
|
||||
size = obj.length * 2; // UTF-16
|
||||
} else if (typeof obj === 'number') {
|
||||
size = 8; // 64-bit float
|
||||
} else if (typeof obj === 'boolean') {
|
||||
size = 1;
|
||||
} else if (obj === null || obj === undefined) {
|
||||
size = 0;
|
||||
} else {
|
||||
size = JSON.stringify(obj).length * 2;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
formatBytes(bytes) {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
calculateAccessFrequency(cutoff) {
|
||||
const recentAccess = this.analytics.history.filter((entry) => entry.timestamp > cutoff);
|
||||
const frequency = recentAccess.length / ((Date.now() - cutoff) / 60000); // per minute
|
||||
return frequency.toFixed(2);
|
||||
}
|
||||
|
||||
getUsageData(cutoff) {
|
||||
// Return usage data for charts
|
||||
return this.analytics.history
|
||||
.filter((entry) => entry.timestamp > cutoff)
|
||||
.map((entry) => ({
|
||||
timestamp: entry.timestamp,
|
||||
operations: entry.operations || 0,
|
||||
memory: entry.memory || 0,
|
||||
}));
|
||||
}
|
||||
|
||||
getPatternData(cutoff) {
|
||||
// Return pattern data for charts
|
||||
const patterns = new Map();
|
||||
|
||||
for (const [key, value] of this.analytics.patterns) {
|
||||
if (value.lastAccess > cutoff) {
|
||||
patterns.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(patterns.entries());
|
||||
}
|
||||
|
||||
// Event handlers
|
||||
async selectNamespace(namespace) {
|
||||
this.currentNamespace = namespace;
|
||||
this.updateKeyValueList();
|
||||
|
||||
// Update active state
|
||||
this.container.querySelectorAll('.namespace-item').forEach((item) => {
|
||||
item.classList.toggle('active', item.dataset.namespace === namespace);
|
||||
});
|
||||
|
||||
await this.notifyCoordination(`Selected namespace: ${namespace}`);
|
||||
}
|
||||
|
||||
async addNamespace() {
|
||||
const name = prompt('Enter namespace name:');
|
||||
if (name) {
|
||||
// Create a placeholder key to establish the namespace
|
||||
const key = `${name}.placeholder`;
|
||||
await this.setMemoryValue(key, 'Namespace placeholder');
|
||||
await this.loadMemoryData();
|
||||
await this.notifyCoordination(`Added namespace: ${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
async addKey() {
|
||||
this.openModal('key-editor-modal');
|
||||
this.container.querySelector('#edit-key').value = '';
|
||||
this.container.querySelector('#edit-value').value = '';
|
||||
this.container.querySelector('#edit-type').value = 'string';
|
||||
this.container.querySelector('#edit-namespace').value = this.currentNamespace;
|
||||
}
|
||||
|
||||
async editKey(key) {
|
||||
const value = this.memoryData.get(key);
|
||||
const type = this.getValueType(value);
|
||||
|
||||
this.openModal('key-editor-modal');
|
||||
this.container.querySelector('#edit-key').value = key;
|
||||
this.container.querySelector('#edit-value').value = JSON.stringify(value, null, 2);
|
||||
this.container.querySelector('#edit-type').value = type;
|
||||
this.container.querySelector('#edit-namespace').value = this.getNamespaceFromKey(key);
|
||||
}
|
||||
|
||||
async deleteKey(key) {
|
||||
if (confirm(`Are you sure you want to delete "${key}"?`)) {
|
||||
await this.deleteMemoryValue(key);
|
||||
await this.loadMemoryData();
|
||||
await this.notifyCoordination(`Deleted key: ${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
async copyKey(key) {
|
||||
const value = this.memoryData.get(key);
|
||||
const text = JSON.stringify({ [key]: value }, null, 2);
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
this.showSuccess('Key copied to clipboard');
|
||||
} catch (error) {
|
||||
console.error('Failed to copy to clipboard:', error);
|
||||
this.showError('Failed to copy to clipboard');
|
||||
}
|
||||
}
|
||||
|
||||
async saveKeyValue(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const key = this.container.querySelector('#edit-key').value;
|
||||
const type = this.container.querySelector('#edit-type').value;
|
||||
const valueText = this.container.querySelector('#edit-value').value;
|
||||
|
||||
try {
|
||||
let value;
|
||||
|
||||
switch (type) {
|
||||
case 'string':
|
||||
value = valueText;
|
||||
break;
|
||||
case 'number':
|
||||
value = parseFloat(valueText);
|
||||
break;
|
||||
case 'boolean':
|
||||
value = valueText.toLowerCase() === 'true';
|
||||
break;
|
||||
case 'object':
|
||||
case 'array':
|
||||
value = JSON.parse(valueText);
|
||||
break;
|
||||
default:
|
||||
value = valueText;
|
||||
}
|
||||
|
||||
await this.setMemoryValue(key, value);
|
||||
await this.loadMemoryData();
|
||||
this.closeModal();
|
||||
await this.notifyCoordination(`Saved key: ${key}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to save key-value:', error);
|
||||
this.showError('Failed to save key-value pair');
|
||||
}
|
||||
}
|
||||
|
||||
async createBackup() {
|
||||
try {
|
||||
const backup = await this.backupManager.createBackup(this.memoryData);
|
||||
this.showSuccess(`Backup created: ${backup.id}`);
|
||||
await this.notifyCoordination(`Created backup: ${backup.id}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to create backup:', error);
|
||||
this.showError('Failed to create backup');
|
||||
}
|
||||
}
|
||||
|
||||
async optimizeMemory() {
|
||||
try {
|
||||
const result = await this.compressionManager.optimize(this.memoryData);
|
||||
this.showSuccess(`Memory optimized: ${result.savedBytes} bytes saved`);
|
||||
await this.loadMemoryData();
|
||||
await this.notifyCoordination(`Optimized memory: ${result.savedBytes} bytes saved`);
|
||||
} catch (error) {
|
||||
console.error('Failed to optimize memory:', error);
|
||||
this.showError('Failed to optimize memory');
|
||||
}
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
await this.loadMemoryData();
|
||||
this.showSuccess('Memory data refreshed');
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
openModal(modalId) {
|
||||
this.container.querySelector('#modal-overlay').style.display = 'flex';
|
||||
this.container.querySelector(`#${modalId}`).style.display = 'block';
|
||||
}
|
||||
|
||||
closeModal() {
|
||||
this.container.querySelector('#modal-overlay').style.display = 'none';
|
||||
this.container.querySelectorAll('.modal').forEach((modal) => {
|
||||
modal.style.display = 'none';
|
||||
});
|
||||
}
|
||||
|
||||
getNamespaceFromKey(key) {
|
||||
const parts = key.split('.');
|
||||
return parts.length > 1 ? parts.slice(0, -1).join('.') : 'global';
|
||||
}
|
||||
|
||||
async setMemoryValue(key, value) {
|
||||
const response = await fetch('/api/memory/set', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key, value }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to set memory value');
|
||||
}
|
||||
}
|
||||
|
||||
async deleteMemoryValue(key) {
|
||||
const response = await fetch('/api/memory/delete', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to delete memory value');
|
||||
}
|
||||
}
|
||||
|
||||
showSuccess(message) {
|
||||
// Implementation for success notification
|
||||
console.log('Success:', message);
|
||||
}
|
||||
|
||||
showError(message) {
|
||||
// Implementation for error notification
|
||||
console.error('Error:', message);
|
||||
}
|
||||
|
||||
async notifyCoordination(message) {
|
||||
try {
|
||||
await fetch('/api/coordination/notify', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message, timestamp: Date.now() }),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to notify coordination:', error);
|
||||
}
|
||||
}
|
||||
|
||||
startMonitoring() {
|
||||
// Start real-time monitoring
|
||||
setInterval(() => {
|
||||
this.updateAnalytics();
|
||||
}, 30000); // Update every 30 seconds
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.container;
|
||||
}
|
||||
}
|
||||
|
||||
// Supporting classes
|
||||
class BackupManager {
|
||||
constructor() {
|
||||
this.backups = new Map();
|
||||
}
|
||||
|
||||
async createBackup(memoryData) {
|
||||
const id = `backup_${Date.now()}`;
|
||||
const backup = {
|
||||
id,
|
||||
timestamp: Date.now(),
|
||||
data: new Map(memoryData),
|
||||
size: this.calculateBackupSize(memoryData),
|
||||
};
|
||||
|
||||
this.backups.set(id, backup);
|
||||
return backup;
|
||||
}
|
||||
|
||||
async restoreBackup(backupId) {
|
||||
const backup = this.backups.get(backupId);
|
||||
if (!backup) {
|
||||
throw new Error('Backup not found');
|
||||
}
|
||||
|
||||
return backup.data;
|
||||
}
|
||||
|
||||
calculateBackupSize(memoryData) {
|
||||
return JSON.stringify(Array.from(memoryData.entries())).length;
|
||||
}
|
||||
}
|
||||
|
||||
class SyncManager {
|
||||
constructor() {
|
||||
this.syncStatus = 'idle';
|
||||
this.lastSync = null;
|
||||
}
|
||||
|
||||
async sync() {
|
||||
this.syncStatus = 'syncing';
|
||||
|
||||
try {
|
||||
// Implement sync logic here
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
this.lastSync = Date.now();
|
||||
this.syncStatus = 'synchronized';
|
||||
} catch (error) {
|
||||
this.syncStatus = 'error';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
getStatus() {
|
||||
return {
|
||||
status: this.syncStatus,
|
||||
lastSync: this.lastSync,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class CompressionManager {
|
||||
constructor() {
|
||||
this.compressionRate = 0;
|
||||
}
|
||||
|
||||
async optimize(memoryData) {
|
||||
// Implement compression logic
|
||||
const originalSize = this.calculateSize(memoryData);
|
||||
|
||||
// Simulate compression
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
|
||||
const compressedSize = originalSize * 0.7; // 30% compression
|
||||
const savedBytes = originalSize - compressedSize;
|
||||
|
||||
this.compressionRate = (savedBytes / originalSize) * 100;
|
||||
|
||||
return {
|
||||
savedBytes: Math.floor(savedBytes),
|
||||
compressionRate: this.compressionRate,
|
||||
};
|
||||
}
|
||||
|
||||
getCompressionRate() {
|
||||
return `${this.compressionRate.toFixed(1)}%`;
|
||||
}
|
||||
|
||||
calculateSize(memoryData) {
|
||||
return JSON.stringify(Array.from(memoryData.entries())).length;
|
||||
}
|
||||
}
|
||||
|
||||
class MemoryVisualizer {
|
||||
constructor() {
|
||||
this.usageChart = null;
|
||||
this.patternChart = null;
|
||||
}
|
||||
|
||||
updateUsageChart(data) {
|
||||
const canvas = document.getElementById('usage-chart');
|
||||
if (!canvas) return;
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
// Simple chart implementation
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
// Draw usage data
|
||||
if (data.length > 0) {
|
||||
ctx.beginPath();
|
||||
ctx.strokeStyle = '#007bff';
|
||||
ctx.lineWidth = 2;
|
||||
|
||||
const width = canvas.width;
|
||||
const height = canvas.height;
|
||||
const stepX = width / (data.length - 1);
|
||||
const maxValue = Math.max(...data.map((d) => d.operations));
|
||||
|
||||
data.forEach((point, index) => {
|
||||
const x = index * stepX;
|
||||
const y = height - (point.operations / maxValue) * height;
|
||||
|
||||
if (index === 0) {
|
||||
ctx.moveTo(x, y);
|
||||
} else {
|
||||
ctx.lineTo(x, y);
|
||||
}
|
||||
});
|
||||
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
updatePatternChart(data) {
|
||||
const canvas = document.getElementById('pattern-chart');
|
||||
if (!canvas) return;
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
// Simple pattern chart implementation
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
// Draw pattern data as bars
|
||||
if (data.length > 0) {
|
||||
const width = canvas.width;
|
||||
const height = canvas.height;
|
||||
const barWidth = width / data.length;
|
||||
const maxValue = Math.max(...data.map((d) => d[1].count || 0));
|
||||
|
||||
data.forEach((pattern, index) => {
|
||||
const barHeight = ((pattern[1].count || 0) / maxValue) * height;
|
||||
const x = index * barWidth;
|
||||
const y = height - barHeight;
|
||||
|
||||
ctx.fillStyle = '#28a745';
|
||||
ctx.fillRect(x, y, barWidth - 2, barHeight);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export for use in other modules
|
||||
window.MemoryInterface = MemoryInterface;
|
||||
@@ -1,247 +0,0 @@
|
||||
/**
|
||||
* Memory Manager Test Module
|
||||
* Tests the memory management functionality
|
||||
*/
|
||||
|
||||
export class MemoryTest {
|
||||
constructor(memoryManager, terminal) {
|
||||
this.memoryManager = memoryManager;
|
||||
this.terminal = terminal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run comprehensive memory tests
|
||||
*/
|
||||
async runTests() {
|
||||
this.terminal.writeInfo('🧪 Starting Memory Manager Tests...');
|
||||
|
||||
try {
|
||||
await this.testMemoryPanel();
|
||||
await this.testMemoryTools();
|
||||
await this.testNamespaceOperations();
|
||||
await this.testMemoryOperations();
|
||||
|
||||
this.terminal.writeSuccess('✅ All memory tests completed successfully!');
|
||||
} catch (error) {
|
||||
this.terminal.writeError(`❌ Memory tests failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test memory panel functionality
|
||||
*/
|
||||
async testMemoryPanel() {
|
||||
this.terminal.writeInfo('Testing memory panel...');
|
||||
|
||||
// Test panel toggle
|
||||
this.memoryManager.togglePanel();
|
||||
const panelVisible = !document.getElementById('memoryPanel')?.classList.contains('hidden');
|
||||
|
||||
if (panelVisible) {
|
||||
this.terminal.writeSuccess('✅ Memory panel opens correctly');
|
||||
} else {
|
||||
throw new Error('Memory panel failed to open');
|
||||
}
|
||||
|
||||
// Test panel components
|
||||
const requiredElements = [
|
||||
'memoryToolsGrid',
|
||||
'namespaceSelect',
|
||||
'memoryTable',
|
||||
'memoryAnalytics',
|
||||
'memoryLog',
|
||||
];
|
||||
|
||||
for (const elementId of requiredElements) {
|
||||
const element = document.getElementById(elementId);
|
||||
if (element) {
|
||||
this.terminal.writeSuccess(`✅ ${elementId} component found`);
|
||||
} else {
|
||||
throw new Error(`Required component missing: ${elementId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test memory tools
|
||||
*/
|
||||
async testMemoryTools() {
|
||||
this.terminal.writeInfo('Testing memory tools...');
|
||||
|
||||
const tools = Object.keys(this.memoryManager.memoryTools);
|
||||
this.terminal.writeInfo(`Found ${tools.length} memory tools:`);
|
||||
|
||||
for (const tool of tools) {
|
||||
const toolInfo = this.memoryManager.memoryTools[tool];
|
||||
this.terminal.writeLine(` ${toolInfo.icon} ${toolInfo.name} - ${toolInfo.description}`);
|
||||
}
|
||||
|
||||
if (tools.length === 10) {
|
||||
this.terminal.writeSuccess('✅ All 10 memory tools are configured');
|
||||
} else {
|
||||
throw new Error(`Expected 10 memory tools, found ${tools.length}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test namespace operations
|
||||
*/
|
||||
async testNamespaceOperations() {
|
||||
this.terminal.writeInfo('Testing namespace operations...');
|
||||
|
||||
// Test namespace switching
|
||||
const originalNamespace = this.memoryManager.currentNamespace;
|
||||
|
||||
// Switch to test namespace
|
||||
await this.memoryManager.switchNamespace('test');
|
||||
|
||||
if (this.memoryManager.currentNamespace === 'test') {
|
||||
this.terminal.writeSuccess('✅ Namespace switching works');
|
||||
} else {
|
||||
throw new Error('Namespace switching failed');
|
||||
}
|
||||
|
||||
// Switch back to original namespace
|
||||
await this.memoryManager.switchNamespace(originalNamespace);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test memory operations
|
||||
*/
|
||||
async testMemoryOperations() {
|
||||
this.terminal.writeInfo('Testing memory operations...');
|
||||
|
||||
// Test utility functions
|
||||
const testData = {
|
||||
size: this.memoryManager.formatSize(1024),
|
||||
ttl: this.memoryManager.formatTTL(Date.now() + 3600000),
|
||||
truncate: this.memoryManager.truncateValue(
|
||||
'This is a very long test string that should be truncated',
|
||||
),
|
||||
escape: this.memoryManager.escapeHtml('<script>alert("test")</script>'),
|
||||
};
|
||||
|
||||
// Validate utility functions
|
||||
if (testData.size === '1 KB') {
|
||||
this.terminal.writeSuccess('✅ Size formatting works');
|
||||
} else {
|
||||
throw new Error(`Size formatting failed: ${testData.size}`);
|
||||
}
|
||||
|
||||
if (testData.ttl.includes('h') && testData.ttl.includes('m')) {
|
||||
this.terminal.writeSuccess('✅ TTL formatting works');
|
||||
} else {
|
||||
throw new Error(`TTL formatting failed: ${testData.ttl}`);
|
||||
}
|
||||
|
||||
if (testData.truncate.length <= 103) {
|
||||
// 100 + '...'
|
||||
this.terminal.writeSuccess('✅ Value truncation works');
|
||||
} else {
|
||||
throw new Error('Value truncation failed');
|
||||
}
|
||||
|
||||
if (!testData.escape.includes('<script>')) {
|
||||
this.terminal.writeSuccess('✅ HTML escaping works');
|
||||
} else {
|
||||
throw new Error('HTML escaping failed');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test mock memory data
|
||||
*/
|
||||
async testMockData() {
|
||||
this.terminal.writeInfo('Testing with mock data...');
|
||||
|
||||
const mockEntries = [
|
||||
{
|
||||
key: 'test/key1',
|
||||
value: 'test value 1',
|
||||
size: 256,
|
||||
ttl: Date.now() + 3600000,
|
||||
namespace: 'test',
|
||||
},
|
||||
{
|
||||
key: 'test/key2',
|
||||
value: JSON.stringify({ test: 'data', array: [1, 2, 3] }),
|
||||
size: 512,
|
||||
ttl: null,
|
||||
namespace: 'test',
|
||||
},
|
||||
];
|
||||
|
||||
// Update table with mock data
|
||||
this.memoryManager.updateMemoryTable(mockEntries);
|
||||
|
||||
// Check if table was populated
|
||||
const tableBody = document.getElementById('memoryTableBody');
|
||||
const rows = tableBody?.getElementsByTagName('tr');
|
||||
|
||||
if (rows && rows.length === mockEntries.length) {
|
||||
this.terminal.writeSuccess('✅ Memory table updates correctly');
|
||||
} else {
|
||||
throw new Error('Memory table update failed');
|
||||
}
|
||||
|
||||
// Test filtering
|
||||
this.memoryManager.filterMemoryEntries('key1');
|
||||
const visibleRows = Array.from(rows).filter((row) => row.style.display !== 'none');
|
||||
|
||||
if (visibleRows.length === 1) {
|
||||
this.terminal.writeSuccess('✅ Memory filtering works');
|
||||
} else {
|
||||
throw new Error('Memory filtering failed');
|
||||
}
|
||||
|
||||
// Reset filter
|
||||
this.memoryManager.filterMemoryEntries('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate test report
|
||||
*/
|
||||
generateReport() {
|
||||
const report = {
|
||||
timestamp: new Date().toISOString(),
|
||||
tests: {
|
||||
panel: 'passed',
|
||||
tools: 'passed',
|
||||
namespaces: 'passed',
|
||||
operations: 'passed',
|
||||
},
|
||||
memoryTools: Object.keys(this.memoryManager.memoryTools),
|
||||
features: [
|
||||
'Memory Tools Grid (10 tools)',
|
||||
'Namespace Browser',
|
||||
'Memory Data Table',
|
||||
'Memory Analytics Dashboard',
|
||||
'Operations Log',
|
||||
'Import/Export',
|
||||
'Search & Filter',
|
||||
'Auto-refresh',
|
||||
],
|
||||
};
|
||||
|
||||
this.terminal.writeInfo('📊 Memory Manager Test Report:');
|
||||
this.terminal.writeLine(JSON.stringify(report, null, 2));
|
||||
|
||||
return report;
|
||||
}
|
||||
}
|
||||
|
||||
// Export test runner function
|
||||
export async function runMemoryTests() {
|
||||
if (window.memoryManager && window.claudeConsole) {
|
||||
const tester = new MemoryTest(window.memoryManager, window.claudeConsole.terminal);
|
||||
await tester.runTests();
|
||||
await tester.testMockData();
|
||||
return tester.generateReport();
|
||||
} else {
|
||||
console.error('Memory manager or console not available for testing');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Make test runner globally available
|
||||
window.runMemoryTests = runMemoryTests;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,715 +0,0 @@
|
||||
/**
|
||||
* RealTimeDashboard - Enhanced real-time monitoring dashboard for Claude Flow swarms
|
||||
* Integrates multiple visualization components with live data updates
|
||||
*/
|
||||
|
||||
import { SwarmVisualizer } from './swarm-visualizer.js';
|
||||
|
||||
export class RealTimeDashboard {
|
||||
constructor(container, componentLibrary) {
|
||||
this.container = container;
|
||||
this.components = componentLibrary;
|
||||
this.swarmVisualizer = null;
|
||||
this.isActive = false;
|
||||
this.updateInterval = null;
|
||||
this.websocket = null;
|
||||
this.metrics = {
|
||||
history: [],
|
||||
current: null
|
||||
};
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize dashboard
|
||||
*/
|
||||
init() {
|
||||
this.createDashboardLayout();
|
||||
this.setupWebSocket();
|
||||
this.startMetricsCollection();
|
||||
console.log('📊 Real-time Dashboard initialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create dashboard layout
|
||||
*/
|
||||
createDashboardLayout() {
|
||||
// Main dashboard container
|
||||
const dashboard = document.createElement('div');
|
||||
dashboard.className = 'claude-realtime-dashboard';
|
||||
dashboard.style.cssText = `
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-template-rows: auto 1fr auto;
|
||||
gap: 16px;
|
||||
height: 100vh;
|
||||
padding: 16px;
|
||||
background: #0a0a0a;
|
||||
color: white;
|
||||
`;
|
||||
|
||||
// Header with title and controls
|
||||
const header = this.createDashboardHeader();
|
||||
dashboard.appendChild(header);
|
||||
|
||||
// Main content area
|
||||
const content = document.createElement('div');
|
||||
content.style.cssText = `
|
||||
grid-column: 1 / -1;
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr;
|
||||
gap: 16px;
|
||||
overflow: hidden;
|
||||
`;
|
||||
|
||||
// Left panel - Swarm Visualizer
|
||||
const leftPanel = document.createElement('div');
|
||||
leftPanel.className = 'dashboard-left-panel';
|
||||
this.swarmVisualizer = new SwarmVisualizer(leftPanel, this.components);
|
||||
|
||||
// Right panel - Metrics and controls
|
||||
const rightPanel = this.createRightPanel();
|
||||
|
||||
content.appendChild(leftPanel);
|
||||
content.appendChild(rightPanel);
|
||||
dashboard.appendChild(content);
|
||||
|
||||
// Footer with status information
|
||||
const footer = this.createDashboardFooter();
|
||||
dashboard.appendChild(footer);
|
||||
|
||||
this.container.appendChild(dashboard);
|
||||
|
||||
this.elements = {
|
||||
dashboard,
|
||||
header,
|
||||
content,
|
||||
leftPanel,
|
||||
rightPanel,
|
||||
footer
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create dashboard header
|
||||
*/
|
||||
createDashboardHeader() {
|
||||
const header = document.createElement('div');
|
||||
header.style.cssText = `
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 16px;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
`;
|
||||
|
||||
// Title and status
|
||||
const titleSection = document.createElement('div');
|
||||
titleSection.innerHTML = `
|
||||
<h1 style="margin: 0; color: #00d4ff; font-size: 24px;">
|
||||
🌊 Claude Flow Real-Time Dashboard
|
||||
</h1>
|
||||
<p style="margin: 4px 0 0 0; color: #888; font-size: 14px;">
|
||||
Live swarm monitoring and performance analytics
|
||||
</p>
|
||||
`;
|
||||
|
||||
// Control buttons
|
||||
const controls = document.createElement('div');
|
||||
controls.style.display = 'flex';
|
||||
controls.style.gap = '12px';
|
||||
|
||||
const startBtn = this.components.createActionButton({
|
||||
type: 'primary',
|
||||
text: 'Start All',
|
||||
icon: '▶️',
|
||||
onclick: () => this.startAllMonitoring()
|
||||
});
|
||||
|
||||
const stopBtn = this.components.createActionButton({
|
||||
type: 'secondary',
|
||||
text: 'Stop All',
|
||||
icon: '⏹️',
|
||||
onclick: () => this.stopAllMonitoring()
|
||||
});
|
||||
|
||||
const exportBtn = this.components.createActionButton({
|
||||
type: 'secondary',
|
||||
text: 'Export Data',
|
||||
icon: '💾',
|
||||
onclick: () => this.exportDashboardData()
|
||||
});
|
||||
|
||||
controls.appendChild(startBtn.element);
|
||||
controls.appendChild(stopBtn.element);
|
||||
controls.appendChild(exportBtn.element);
|
||||
|
||||
header.appendChild(titleSection);
|
||||
header.appendChild(controls);
|
||||
|
||||
this.headerElements = {
|
||||
startBtn,
|
||||
stopBtn,
|
||||
exportBtn
|
||||
};
|
||||
|
||||
return header;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create right panel with metrics and controls
|
||||
*/
|
||||
createRightPanel() {
|
||||
const panel = document.createElement('div');
|
||||
panel.style.cssText = `
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
overflow-y: auto;
|
||||
`;
|
||||
|
||||
// Performance metrics chart
|
||||
const metricsChart = this.createMetricsChart();
|
||||
panel.appendChild(metricsChart);
|
||||
|
||||
// System health indicators
|
||||
const healthPanel = this.createHealthPanel();
|
||||
panel.appendChild(healthPanel);
|
||||
|
||||
// Memory usage chart
|
||||
const memoryChart = this.createMemoryChart();
|
||||
panel.appendChild(memoryChart);
|
||||
|
||||
// Task queue status
|
||||
const queueStatus = this.createQueueStatus();
|
||||
panel.appendChild(queueStatus);
|
||||
|
||||
// Recent activities log
|
||||
const activityLog = this.createActivityLog();
|
||||
panel.appendChild(activityLog);
|
||||
|
||||
return panel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create performance metrics chart
|
||||
*/
|
||||
createMetricsChart() {
|
||||
const metricsChart = this.components.createMetricsChart({
|
||||
title: 'Performance Metrics',
|
||||
width: 350,
|
||||
height: 200,
|
||||
type: 'line'
|
||||
});
|
||||
|
||||
// Sample data
|
||||
this.updateMetricsChart(metricsChart);
|
||||
|
||||
this.metricsChart = metricsChart;
|
||||
return metricsChart.element;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create system health panel
|
||||
*/
|
||||
createHealthPanel() {
|
||||
const panel = this.components.createInfoPanel({
|
||||
title: '🏥 System Health'
|
||||
});
|
||||
|
||||
const healthMetrics = [
|
||||
{ name: 'CPU Usage', value: '45%', status: 'good' },
|
||||
{ name: 'Memory Usage', value: '2.1GB', status: 'good' },
|
||||
{ name: 'Network I/O', value: '120 Mbps', status: 'good' },
|
||||
{ name: 'Disk Usage', value: '67%', status: 'warning' },
|
||||
{ name: 'Response Time', value: '234ms', status: 'good' }
|
||||
];
|
||||
|
||||
const healthHTML = healthMetrics.map(metric => `
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin: 8px 0;">
|
||||
<span>${metric.name}:</span>
|
||||
<span class="health-metric health-${metric.status}" style="
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
font-weight: bold;
|
||||
${metric.status === 'good' ? 'background: #22c55e; color: white;' :
|
||||
metric.status === 'warning' ? 'background: #f59e0b; color: white;' :
|
||||
'background: #ef4444; color: white;'}
|
||||
">${metric.value}</span>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
panel.setContent(healthHTML);
|
||||
this.healthPanel = panel;
|
||||
return panel.element;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create memory usage chart
|
||||
*/
|
||||
createMemoryChart() {
|
||||
const memoryChart = this.components.createMetricsChart({
|
||||
title: 'Memory Usage Over Time',
|
||||
width: 350,
|
||||
height: 150,
|
||||
type: 'line'
|
||||
});
|
||||
|
||||
this.updateMemoryChart(memoryChart);
|
||||
this.memoryChart = memoryChart;
|
||||
return memoryChart.element;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create task queue status
|
||||
*/
|
||||
createQueueStatus() {
|
||||
const panel = this.components.createInfoPanel({
|
||||
title: '📋 Task Queue Status'
|
||||
});
|
||||
|
||||
const queueData = {
|
||||
pending: Math.floor(Math.random() * 20),
|
||||
processing: Math.floor(Math.random() * 8),
|
||||
completed: Math.floor(Math.random() * 150) + 50,
|
||||
failed: Math.floor(Math.random() * 5)
|
||||
};
|
||||
|
||||
const queueHTML = `
|
||||
<div class="queue-stats" style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
|
||||
<div class="queue-stat">
|
||||
<div style="font-size: 24px; font-weight: bold; color: #f59e0b;">${queueData.pending}</div>
|
||||
<div style="color: #888; font-size: 12px;">Pending</div>
|
||||
</div>
|
||||
<div class="queue-stat">
|
||||
<div style="font-size: 24px; font-weight: bold; color: #00d4ff;">${queueData.processing}</div>
|
||||
<div style="color: #888; font-size: 12px;">Processing</div>
|
||||
</div>
|
||||
<div class="queue-stat">
|
||||
<div style="font-size: 24px; font-weight: bold; color: #22c55e;">${queueData.completed}</div>
|
||||
<div style="color: #888; font-size: 12px;">Completed</div>
|
||||
</div>
|
||||
<div class="queue-stat">
|
||||
<div style="font-size: 24px; font-weight: bold; color: #ef4444;">${queueData.failed}</div>
|
||||
<div style="color: #888; font-size: 12px;">Failed</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
panel.setContent(queueHTML);
|
||||
this.queuePanel = panel;
|
||||
return panel.element;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create activity log
|
||||
*/
|
||||
createActivityLog() {
|
||||
const panel = this.components.createInfoPanel({
|
||||
title: '📝 Recent Activity'
|
||||
});
|
||||
|
||||
const activities = [
|
||||
{ time: '14:23:15', type: 'info', message: 'Agent coder_01 completed task #127' },
|
||||
{ time: '14:22:58', type: 'success', message: 'Swarm topology optimized (+12% efficiency)' },
|
||||
{ time: '14:22:45', type: 'warning', message: 'Agent analyzer_03 high memory usage (89%)' },
|
||||
{ time: '14:22:30', type: 'info', message: 'New task assigned to researcher_02' },
|
||||
{ time: '14:22:12', type: 'error', message: 'Connection timeout to agent reviewer_01' }
|
||||
];
|
||||
|
||||
const activityHTML = activities.map(activity => `
|
||||
<div class="activity-item" style="
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 8px 0;
|
||||
padding: 8px;
|
||||
background: #2a2a2a;
|
||||
border-radius: 4px;
|
||||
border-left: 3px solid ${
|
||||
activity.type === 'success' ? '#22c55e' :
|
||||
activity.type === 'warning' ? '#f59e0b' :
|
||||
activity.type === 'error' ? '#ef4444' : '#00d4ff'
|
||||
};
|
||||
">
|
||||
<span style="color: #888; font-size: 12px; min-width: 60px;">${activity.time}</span>
|
||||
<span style="font-size: 14px;">${activity.message}</span>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
panel.setContent(`<div style="max-height: 200px; overflow-y: auto;">${activityHTML}</div>`);
|
||||
this.activityPanel = panel;
|
||||
return panel.element;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create dashboard footer
|
||||
*/
|
||||
createDashboardFooter() {
|
||||
const footer = document.createElement('div');
|
||||
footer.style.cssText = `
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
`;
|
||||
|
||||
const leftStatus = document.createElement('div');
|
||||
leftStatus.innerHTML = `
|
||||
Status: <span id="dashboard-status" style="color: #22c55e;">●</span> Active |
|
||||
Uptime: <span id="dashboard-uptime">00:00:00</span> |
|
||||
Last Update: <span id="dashboard-last-update">Never</span>
|
||||
`;
|
||||
|
||||
const rightStatus = document.createElement('div');
|
||||
rightStatus.innerHTML = `
|
||||
Total Messages: <span id="dashboard-messages">0</span> |
|
||||
Data Points: <span id="dashboard-data-points">0</span> |
|
||||
Version: Claude Flow v2.0.0
|
||||
`;
|
||||
|
||||
footer.appendChild(leftStatus);
|
||||
footer.appendChild(rightStatus);
|
||||
|
||||
this.footerElements = {
|
||||
status: leftStatus.querySelector('#dashboard-status'),
|
||||
uptime: leftStatus.querySelector('#dashboard-uptime'),
|
||||
lastUpdate: leftStatus.querySelector('#dashboard-last-update'),
|
||||
messages: rightStatus.querySelector('#dashboard-messages'),
|
||||
dataPoints: rightStatus.querySelector('#dashboard-data-points')
|
||||
};
|
||||
|
||||
return footer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup WebSocket connection for real-time updates
|
||||
*/
|
||||
setupWebSocket() {
|
||||
try {
|
||||
const wsUrl = 'ws://localhost:3000/dashboard';
|
||||
this.websocket = new WebSocket(wsUrl);
|
||||
|
||||
this.websocket.onopen = () => {
|
||||
console.log('📡 Dashboard WebSocket connected');
|
||||
this.updateConnectionStatus(true);
|
||||
};
|
||||
|
||||
this.websocket.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
this.handleWebSocketMessage(data);
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse WebSocket message:', error);
|
||||
}
|
||||
};
|
||||
|
||||
this.websocket.onclose = () => {
|
||||
console.log('📡 Dashboard WebSocket disconnected');
|
||||
this.updateConnectionStatus(false);
|
||||
// Attempt reconnection after 5 seconds
|
||||
setTimeout(() => this.setupWebSocket(), 5000);
|
||||
};
|
||||
|
||||
this.websocket.onerror = (error) => {
|
||||
console.error('📡 Dashboard WebSocket error:', error);
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.warn('WebSocket not available, using polling fallback');
|
||||
this.startPollingFallback();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle WebSocket messages
|
||||
*/
|
||||
handleWebSocketMessage(data) {
|
||||
switch (data.type) {
|
||||
case 'swarm_update':
|
||||
// Forward to swarm visualizer
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.swarmData = data.payload;
|
||||
this.swarmVisualizer.processSwarmData();
|
||||
this.swarmVisualizer.updateStats();
|
||||
}
|
||||
break;
|
||||
|
||||
case 'metrics_update':
|
||||
this.updateMetricsFromData(data.payload);
|
||||
break;
|
||||
|
||||
case 'health_update':
|
||||
this.updateHealthStatus(data.payload);
|
||||
break;
|
||||
|
||||
case 'activity_log':
|
||||
this.addActivityLog(data.payload);
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log('Unknown WebSocket message type:', data.type);
|
||||
}
|
||||
|
||||
this.updateLastUpdateTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start polling fallback for when WebSocket isn't available
|
||||
*/
|
||||
startPollingFallback() {
|
||||
this.updateInterval = setInterval(() => {
|
||||
this.fetchDashboardData();
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch dashboard data via HTTP
|
||||
*/
|
||||
async fetchDashboardData() {
|
||||
try {
|
||||
const response = await fetch('/api/claude-flow/dashboard/data');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
this.handleDashboardData(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to fetch dashboard data:', error);
|
||||
// Generate mock data for demo
|
||||
this.handleDashboardData(this.generateMockDashboardData());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate mock dashboard data
|
||||
*/
|
||||
generateMockDashboardData() {
|
||||
return {
|
||||
swarm: {
|
||||
agents: 6,
|
||||
active: 4,
|
||||
busy: 2,
|
||||
idle: 2,
|
||||
errors: 0
|
||||
},
|
||||
metrics: {
|
||||
cpuUsage: Math.random() * 30 + 20,
|
||||
memoryUsage: Math.random() * 40 + 40,
|
||||
throughput: Math.random() * 50 + 25,
|
||||
latency: Math.random() * 200 + 100
|
||||
},
|
||||
health: {
|
||||
overall: 'good',
|
||||
services: ['swarm', 'memory', 'neural'].map(service => ({
|
||||
name: service,
|
||||
status: Math.random() > 0.8 ? 'warning' : 'good'
|
||||
}))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update metrics charts with new data
|
||||
*/
|
||||
updateMetricsFromData(data) {
|
||||
// Add to history
|
||||
this.metrics.history.push({
|
||||
timestamp: Date.now(),
|
||||
...data
|
||||
});
|
||||
|
||||
// Keep only last 50 data points
|
||||
if (this.metrics.history.length > 50) {
|
||||
this.metrics.history.shift();
|
||||
}
|
||||
|
||||
this.metrics.current = data;
|
||||
this.updateMetricsChart(this.metricsChart);
|
||||
this.updateMemoryChart(this.memoryChart);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update metrics chart
|
||||
*/
|
||||
updateMetricsChart(chart) {
|
||||
if (!chart || !this.metrics.history.length) return;
|
||||
|
||||
const data = this.metrics.history.map((point, index) => ({
|
||||
x: index,
|
||||
value: point.throughput || Math.random() * 100
|
||||
}));
|
||||
|
||||
chart.updateData(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update memory chart
|
||||
*/
|
||||
updateMemoryChart(chart) {
|
||||
if (!chart || !this.metrics.history.length) return;
|
||||
|
||||
const data = this.metrics.history.map((point, index) => ({
|
||||
x: index,
|
||||
value: point.memoryUsage || Math.random() * 100
|
||||
}));
|
||||
|
||||
chart.updateData(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start all monitoring systems
|
||||
*/
|
||||
startAllMonitoring() {
|
||||
this.isActive = true;
|
||||
|
||||
// Start swarm visualizer
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.startMonitoring();
|
||||
}
|
||||
|
||||
// Start metrics collection
|
||||
this.startMetricsCollection();
|
||||
|
||||
// Update UI state
|
||||
this.headerElements.startBtn.setDisabled(true);
|
||||
this.headerElements.stopBtn.setDisabled(false);
|
||||
this.updateConnectionStatus(true);
|
||||
|
||||
console.log('🚀 All dashboard monitoring started');
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop all monitoring systems
|
||||
*/
|
||||
stopAllMonitoring() {
|
||||
this.isActive = false;
|
||||
|
||||
// Stop swarm visualizer
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.stopMonitoring();
|
||||
}
|
||||
|
||||
// Stop metrics collection
|
||||
if (this.updateInterval) {
|
||||
clearInterval(this.updateInterval);
|
||||
this.updateInterval = null;
|
||||
}
|
||||
|
||||
// Update UI state
|
||||
this.headerElements.startBtn.setDisabled(false);
|
||||
this.headerElements.stopBtn.setDisabled(true);
|
||||
this.updateConnectionStatus(false);
|
||||
|
||||
console.log('⏹️ All dashboard monitoring stopped');
|
||||
}
|
||||
|
||||
/**
|
||||
* Start metrics collection
|
||||
*/
|
||||
startMetricsCollection() {
|
||||
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
|
||||
this.startPollingFallback();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update connection status
|
||||
*/
|
||||
updateConnectionStatus(connected) {
|
||||
if (this.footerElements.status) {
|
||||
this.footerElements.status.style.color = connected ? '#22c55e' : '#ef4444';
|
||||
this.footerElements.status.textContent = connected ? '●' : '●';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update last update time
|
||||
*/
|
||||
updateLastUpdateTime() {
|
||||
if (this.footerElements.lastUpdate) {
|
||||
this.footerElements.lastUpdate.textContent = new Date().toLocaleTimeString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Export dashboard data
|
||||
*/
|
||||
exportDashboardData() {
|
||||
const exportData = {
|
||||
timestamp: Date.now(),
|
||||
metrics: this.metrics,
|
||||
swarmData: this.swarmVisualizer?.swarmData,
|
||||
version: 'Claude Flow v2.0.0'
|
||||
};
|
||||
|
||||
const blob = new Blob([JSON.stringify(exportData, null, 2)], {
|
||||
type: 'application/json'
|
||||
});
|
||||
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `claude-flow-dashboard-${Date.now()}.json`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
console.log('💾 Dashboard data exported');
|
||||
}
|
||||
|
||||
/**
|
||||
* Store progress to swarm memory
|
||||
*/
|
||||
async storeProgressToMemory() {
|
||||
const progressData = {
|
||||
dashboardActive: this.isActive,
|
||||
metricsCount: this.metrics.history.length,
|
||||
swarmVisualizerActive: this.swarmVisualizer?.isActive || false,
|
||||
lastUpdate: Date.now(),
|
||||
components: {
|
||||
swarmVisualizer: 'active',
|
||||
metricsChart: 'active',
|
||||
healthPanel: 'active',
|
||||
activityLog: 'active'
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
// This would normally call the memory API
|
||||
console.log('📊 Storing dashboard progress to memory:', progressData);
|
||||
} catch (error) {
|
||||
console.warn('Failed to store progress to memory:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup resources
|
||||
*/
|
||||
destroy() {
|
||||
this.stopAllMonitoring();
|
||||
|
||||
if (this.websocket) {
|
||||
this.websocket.close();
|
||||
}
|
||||
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.destroy();
|
||||
}
|
||||
|
||||
if (this.container) {
|
||||
this.container.innerHTML = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default RealTimeDashboard;
|
||||
@@ -1,592 +0,0 @@
|
||||
/**
|
||||
* Settings Manager for Claude Code Console
|
||||
* Handles configuration and preferences
|
||||
*/
|
||||
|
||||
export class SettingsManager {
|
||||
constructor() {
|
||||
this.settings = this.loadSettings();
|
||||
this.settingsPanel = null;
|
||||
this.isVisible = false;
|
||||
|
||||
// Default settings
|
||||
this.defaults = {
|
||||
// Connection settings
|
||||
serverUrl: 'ws://localhost:3000/ws',
|
||||
authToken: '',
|
||||
autoConnect: true,
|
||||
|
||||
// Appearance settings
|
||||
theme: 'dark',
|
||||
fontSize: 14,
|
||||
lineHeight: 1.4,
|
||||
fontFamily: 'JetBrains Mono',
|
||||
|
||||
// Behavior settings
|
||||
autoScroll: true,
|
||||
showTimestamps: true,
|
||||
enableSounds: false,
|
||||
maxLines: 1000,
|
||||
|
||||
// Claude Flow settings
|
||||
defaultMode: 'coder',
|
||||
swarmStrategy: 'development',
|
||||
coordinationMode: 'centralized',
|
||||
|
||||
// Advanced settings
|
||||
reconnectAttempts: 5,
|
||||
heartbeatInterval: 30000,
|
||||
commandTimeout: 30000,
|
||||
};
|
||||
|
||||
// Merge defaults with loaded settings
|
||||
this.settings = { ...this.defaults, ...this.settings };
|
||||
|
||||
this.setupEventListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize settings panel
|
||||
*/
|
||||
init() {
|
||||
this.settingsPanel = document.getElementById('settingsPanel');
|
||||
this.setupSettingsPanel();
|
||||
this.applySettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup settings panel event listeners
|
||||
*/
|
||||
setupSettingsPanel() {
|
||||
// Toggle button
|
||||
const settingsToggle = document.getElementById('settingsToggle');
|
||||
if (settingsToggle) {
|
||||
settingsToggle.addEventListener('click', () => this.toggle());
|
||||
}
|
||||
|
||||
// Close button
|
||||
const closeButton = document.getElementById('closeSettings');
|
||||
if (closeButton) {
|
||||
closeButton.addEventListener('click', () => this.hide());
|
||||
}
|
||||
|
||||
// Settings form elements
|
||||
this.setupFormElements();
|
||||
|
||||
// Action buttons
|
||||
this.setupActionButtons();
|
||||
|
||||
// Click outside to close
|
||||
document.addEventListener('click', (event) => {
|
||||
if (
|
||||
this.isVisible &&
|
||||
!this.settingsPanel.contains(event.target) &&
|
||||
!document.getElementById('settingsToggle').contains(event.target)
|
||||
) {
|
||||
this.hide();
|
||||
}
|
||||
});
|
||||
|
||||
// ESC key to close
|
||||
document.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape' && this.isVisible) {
|
||||
this.hide();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup form element listeners
|
||||
*/
|
||||
setupFormElements() {
|
||||
// Connection settings
|
||||
this.bindSetting('serverUrl', 'input');
|
||||
this.bindSetting('authToken', 'input');
|
||||
|
||||
// Appearance settings
|
||||
this.bindSetting('fontSize', 'change', (value) => {
|
||||
this.applyFontSize(parseInt(value));
|
||||
});
|
||||
|
||||
this.bindSetting('theme', 'change', (value) => {
|
||||
this.applyTheme(value);
|
||||
});
|
||||
|
||||
this.bindSetting('lineHeight', 'change', (value) => {
|
||||
this.applyLineHeight(parseFloat(value));
|
||||
});
|
||||
|
||||
// Behavior settings
|
||||
this.bindSetting('autoScroll', 'change', (value) => {
|
||||
localStorage.setItem('console_auto_scroll', value);
|
||||
});
|
||||
|
||||
this.bindSetting('showTimestamps', 'change', (value) => {
|
||||
localStorage.setItem('console_show_timestamps', value);
|
||||
});
|
||||
|
||||
this.bindSetting('enableSounds', 'change');
|
||||
|
||||
this.bindSetting('maxLines', 'input', (value) => {
|
||||
const maxLines = parseInt(value);
|
||||
if (maxLines >= 100 && maxLines <= 10000) {
|
||||
this.emit('max_lines_changed', maxLines);
|
||||
}
|
||||
});
|
||||
|
||||
// Claude Flow settings
|
||||
this.bindSetting('defaultMode', 'change');
|
||||
this.bindSetting('swarmStrategy', 'change');
|
||||
this.bindSetting('coordinationMode', 'change');
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup action buttons
|
||||
*/
|
||||
setupActionButtons() {
|
||||
const connectButton = document.getElementById('connectButton');
|
||||
const disconnectButton = document.getElementById('disconnectButton');
|
||||
|
||||
if (connectButton) {
|
||||
connectButton.addEventListener('click', () => {
|
||||
this.emit('connect_requested', {
|
||||
url: this.get('serverUrl'),
|
||||
token: this.get('authToken'),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (disconnectButton) {
|
||||
disconnectButton.addEventListener('click', () => {
|
||||
this.emit('disconnect_requested');
|
||||
});
|
||||
}
|
||||
|
||||
// Add reset button
|
||||
const resetButton = document.createElement('button');
|
||||
resetButton.className = 'reset-settings';
|
||||
resetButton.textContent = 'Reset to Defaults';
|
||||
resetButton.addEventListener('click', () => {
|
||||
if (confirm('Reset all settings to defaults? This cannot be undone.')) {
|
||||
this.resetToDefaults();
|
||||
}
|
||||
});
|
||||
|
||||
const settingsContent = document.querySelector('.settings-content');
|
||||
if (settingsContent) {
|
||||
settingsContent.appendChild(resetButton);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind setting to form element
|
||||
*/
|
||||
bindSetting(settingName, eventType, callback) {
|
||||
const element = document.getElementById(settingName);
|
||||
if (!element) return;
|
||||
|
||||
// Set initial value
|
||||
const value = this.get(settingName);
|
||||
if (element.type === 'checkbox') {
|
||||
element.checked = value;
|
||||
} else {
|
||||
element.value = value;
|
||||
}
|
||||
|
||||
// Listen for changes
|
||||
element.addEventListener(eventType, (event) => {
|
||||
let newValue;
|
||||
|
||||
if (element.type === 'checkbox') {
|
||||
newValue = element.checked;
|
||||
} else if (element.type === 'number') {
|
||||
newValue = parseFloat(element.value);
|
||||
} else {
|
||||
newValue = element.value;
|
||||
}
|
||||
|
||||
this.set(settingName, newValue);
|
||||
|
||||
if (callback) {
|
||||
callback(newValue);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Show settings panel
|
||||
*/
|
||||
show() {
|
||||
if (this.settingsPanel) {
|
||||
this.settingsPanel.classList.add('visible');
|
||||
this.isVisible = true;
|
||||
|
||||
// Focus first input
|
||||
const firstInput = this.settingsPanel.querySelector('input, select');
|
||||
if (firstInput) {
|
||||
firstInput.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide settings panel
|
||||
*/
|
||||
hide() {
|
||||
if (this.settingsPanel) {
|
||||
this.settingsPanel.classList.remove('visible');
|
||||
this.isVisible = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle settings panel
|
||||
*/
|
||||
toggle() {
|
||||
if (this.isVisible) {
|
||||
this.hide();
|
||||
} else {
|
||||
this.show();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get setting value
|
||||
*/
|
||||
get(key) {
|
||||
return this.settings[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set setting value
|
||||
*/
|
||||
set(key, value) {
|
||||
this.settings[key] = value;
|
||||
this.saveSettings();
|
||||
this.emit('setting_changed', { key, value });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all settings
|
||||
*/
|
||||
getAll() {
|
||||
return { ...this.settings };
|
||||
}
|
||||
|
||||
/**
|
||||
* Set multiple settings
|
||||
*/
|
||||
setAll(newSettings) {
|
||||
this.settings = { ...this.settings, ...newSettings };
|
||||
this.saveSettings();
|
||||
this.updateFormElements();
|
||||
this.applySettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset to default settings
|
||||
*/
|
||||
resetToDefaults() {
|
||||
this.settings = { ...this.defaults };
|
||||
this.saveSettings();
|
||||
this.updateFormElements();
|
||||
this.applySettings();
|
||||
this.emit('settings_reset');
|
||||
}
|
||||
|
||||
/**
|
||||
* Load settings from localStorage
|
||||
*/
|
||||
loadSettings() {
|
||||
try {
|
||||
const stored = localStorage.getItem('claude_console_settings');
|
||||
return stored ? JSON.parse(stored) : {};
|
||||
} catch (error) {
|
||||
console.error('Failed to load settings:', error);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save settings to localStorage
|
||||
*/
|
||||
saveSettings() {
|
||||
try {
|
||||
localStorage.setItem('claude_console_settings', JSON.stringify(this.settings));
|
||||
} catch (error) {
|
||||
console.error('Failed to save settings:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply all settings to the UI
|
||||
*/
|
||||
applySettings() {
|
||||
this.applyTheme(this.get('theme'));
|
||||
this.applyFontSize(this.get('fontSize'));
|
||||
this.applyLineHeight(this.get('lineHeight'));
|
||||
|
||||
// Set individual localStorage items for terminal
|
||||
localStorage.setItem('console_auto_scroll', this.get('autoScroll'));
|
||||
localStorage.setItem('console_show_timestamps', this.get('showTimestamps'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply theme
|
||||
*/
|
||||
applyTheme(theme) {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
localStorage.setItem('console_theme', theme);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply font size
|
||||
*/
|
||||
applyFontSize(fontSize) {
|
||||
document.documentElement.style.setProperty('--font-size-base', `${fontSize}px`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply line height
|
||||
*/
|
||||
applyLineHeight(lineHeight) {
|
||||
document.documentElement.style.setProperty('--line-height', lineHeight);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update form elements with current settings
|
||||
*/
|
||||
updateFormElements() {
|
||||
Object.keys(this.settings).forEach((key) => {
|
||||
const element = document.getElementById(key);
|
||||
if (element) {
|
||||
if (element.type === 'checkbox') {
|
||||
element.checked = this.get(key);
|
||||
} else {
|
||||
element.value = this.get(key);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Export settings
|
||||
*/
|
||||
exportSettings() {
|
||||
const exportData = {
|
||||
timestamp: new Date().toISOString(),
|
||||
version: '1.0.0',
|
||||
settings: this.getAll(),
|
||||
};
|
||||
|
||||
const blob = new Blob([JSON.stringify(exportData, null, 2)], {
|
||||
type: 'application/json',
|
||||
});
|
||||
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `claude-console-settings-${Date.now()}.json`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Import settings
|
||||
*/
|
||||
async importSettings(file) {
|
||||
try {
|
||||
const text = await file.text();
|
||||
const data = JSON.parse(text);
|
||||
|
||||
if (data.settings) {
|
||||
this.setAll(data.settings);
|
||||
return true;
|
||||
} else {
|
||||
throw new Error('Invalid settings file format');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to import settings:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate setting value
|
||||
*/
|
||||
validateSetting(key, value) {
|
||||
const validators = {
|
||||
fontSize: (v) => v >= 10 && v <= 24,
|
||||
lineHeight: (v) => v >= 1.0 && v <= 2.0,
|
||||
maxLines: (v) => v >= 100 && v <= 10000,
|
||||
theme: (v) => ['dark', 'light', 'classic', 'matrix'].includes(v),
|
||||
defaultMode: (v) =>
|
||||
[
|
||||
'coder',
|
||||
'architect',
|
||||
'analyst',
|
||||
'researcher',
|
||||
'reviewer',
|
||||
'tester',
|
||||
'debugger',
|
||||
'documenter',
|
||||
'optimizer',
|
||||
'designer',
|
||||
].includes(v),
|
||||
swarmStrategy: (v) =>
|
||||
['development', 'research', 'analysis', 'testing', 'optimization', 'maintenance'].includes(
|
||||
v,
|
||||
),
|
||||
coordinationMode: (v) =>
|
||||
['centralized', 'hierarchical', 'distributed', 'mesh', 'hybrid'].includes(v),
|
||||
};
|
||||
|
||||
const validator = validators[key];
|
||||
return validator ? validator(value) : true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update connection status in settings
|
||||
*/
|
||||
updateConnectionStatus(status) {
|
||||
const connectButton = document.getElementById('connectButton');
|
||||
const disconnectButton = document.getElementById('disconnectButton');
|
||||
|
||||
if (connectButton && disconnectButton) {
|
||||
if (status.connected) {
|
||||
connectButton.disabled = true;
|
||||
disconnectButton.disabled = false;
|
||||
} else {
|
||||
connectButton.disabled = false;
|
||||
disconnectButton.disabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Update connection info if it exists
|
||||
this.updateConnectionInfo(status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update connection info display
|
||||
*/
|
||||
updateConnectionInfo(status) {
|
||||
let infoElement = document.getElementById('connectionInfo');
|
||||
|
||||
if (!infoElement) {
|
||||
infoElement = document.createElement('div');
|
||||
infoElement.id = 'connectionInfo';
|
||||
infoElement.className = 'connection-info';
|
||||
|
||||
const connectionSection = document.querySelector('.setting-group');
|
||||
if (connectionSection) {
|
||||
connectionSection.appendChild(infoElement);
|
||||
}
|
||||
}
|
||||
|
||||
const statusClass = status.connected
|
||||
? 'connected'
|
||||
: status.connecting
|
||||
? 'connecting'
|
||||
: 'disconnected';
|
||||
|
||||
infoElement.className = `connection-info ${statusClass}`;
|
||||
|
||||
const title = status.connected
|
||||
? 'Connected'
|
||||
: status.connecting
|
||||
? 'Connecting...'
|
||||
: 'Disconnected';
|
||||
|
||||
const details = status.connected
|
||||
? `Connected to ${status.url}\nPending requests: ${status.pendingRequests}\nQueued messages: ${status.queuedMessages}`
|
||||
: status.connecting
|
||||
? `Attempting to connect to ${status.url}`
|
||||
: status.reconnectAttempts > 0
|
||||
? `Disconnected. Reconnect attempts: ${status.reconnectAttempts}`
|
||||
: 'Not connected';
|
||||
|
||||
infoElement.innerHTML = `
|
||||
<div class="connection-info-title">${title}</div>
|
||||
<div class="connection-info-details">${details}</div>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup event listeners
|
||||
*/
|
||||
setupEventListeners() {
|
||||
// Listen for theme changes from system
|
||||
if (window.matchMedia) {
|
||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
mediaQuery.addEventListener('change', (e) => {
|
||||
if (this.get('theme') === 'auto') {
|
||||
this.applyTheme(e.matches ? 'dark' : 'light');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Listen for font size changes from browser zoom
|
||||
window.addEventListener('resize', () => {
|
||||
this.applyFontSize(this.get('fontSize'));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Event emitter functionality
|
||||
*/
|
||||
on(event, callback) {
|
||||
if (!this.eventListeners) {
|
||||
this.eventListeners = new Map();
|
||||
}
|
||||
|
||||
if (!this.eventListeners.has(event)) {
|
||||
this.eventListeners.set(event, []);
|
||||
}
|
||||
|
||||
this.eventListeners.get(event).push(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit event
|
||||
*/
|
||||
emit(event, data) {
|
||||
if (!this.eventListeners || !this.eventListeners.has(event)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.eventListeners.get(event).forEach((callback) => {
|
||||
try {
|
||||
callback(data);
|
||||
} catch (error) {
|
||||
console.error('Error in settings event listener:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Claude Flow configuration
|
||||
*/
|
||||
getClaudeFlowConfig() {
|
||||
return {
|
||||
defaultMode: this.get('defaultMode'),
|
||||
swarmStrategy: this.get('swarmStrategy'),
|
||||
coordinationMode: this.get('coordinationMode'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get connection configuration
|
||||
*/
|
||||
getConnectionConfig() {
|
||||
return {
|
||||
url: this.get('serverUrl'),
|
||||
token: this.get('authToken'),
|
||||
autoConnect: this.get('autoConnect'),
|
||||
reconnectAttempts: this.get('reconnectAttempts'),
|
||||
heartbeatInterval: this.get('heartbeatInterval'),
|
||||
commandTimeout: this.get('commandTimeout'),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,485 +0,0 @@
|
||||
/**
|
||||
* SwarmIntegration - Integrates swarm visualizer with existing console
|
||||
* Adds swarm monitoring commands and UI elements to the Claude Flow console
|
||||
*/
|
||||
|
||||
import { SwarmVisualizer } from './swarm-visualizer.js';
|
||||
import { RealTimeDashboard } from './real-time-dashboard.js';
|
||||
import ComponentLibrary from '../web-ui/components/ComponentLibrary.js';
|
||||
|
||||
export class SwarmIntegration {
|
||||
constructor(consoleInstance) {
|
||||
this.console = consoleInstance;
|
||||
this.components = new ComponentLibrary();
|
||||
this.swarmVisualizer = null;
|
||||
this.dashboard = null;
|
||||
this.isSwarmMode = false;
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize swarm integration
|
||||
*/
|
||||
init() {
|
||||
this.components.initialize();
|
||||
this.addSwarmCommands();
|
||||
this.addSwarmUI();
|
||||
this.setupSwarmEventHandlers();
|
||||
console.log('🔗 Swarm Integration initialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add swarm-specific commands to the console
|
||||
*/
|
||||
addSwarmCommands() {
|
||||
const swarmCommands = {
|
||||
'swarm': {
|
||||
description: 'Enter swarm visualization mode',
|
||||
handler: () => this.enterSwarmMode(),
|
||||
usage: 'swarm'
|
||||
},
|
||||
'swarm-status': {
|
||||
description: 'Show current swarm status',
|
||||
handler: () => this.showSwarmStatus(),
|
||||
usage: 'swarm-status'
|
||||
},
|
||||
'swarm-monitor': {
|
||||
description: 'Start real-time swarm monitoring',
|
||||
handler: (args) => this.startSwarmMonitoring(args),
|
||||
usage: 'swarm-monitor [topology]'
|
||||
},
|
||||
'swarm-stop': {
|
||||
description: 'Stop swarm monitoring',
|
||||
handler: () => this.stopSwarmMonitoring(),
|
||||
usage: 'swarm-stop'
|
||||
},
|
||||
'dashboard': {
|
||||
description: 'Open real-time dashboard',
|
||||
handler: () => this.openDashboard(),
|
||||
usage: 'dashboard'
|
||||
},
|
||||
'agents': {
|
||||
description: 'List active agents',
|
||||
handler: () => this.listAgents(),
|
||||
usage: 'agents'
|
||||
},
|
||||
'topology': {
|
||||
description: 'Change swarm topology',
|
||||
handler: (args) => this.changeTopology(args),
|
||||
usage: 'topology [mesh|hierarchical|ring|star]'
|
||||
}
|
||||
};
|
||||
|
||||
// Register commands with the console's command handler
|
||||
if (this.console.commandHandler) {
|
||||
Object.entries(swarmCommands).forEach(([command, config]) => {
|
||||
this.console.commandHandler.registerCommand(command, config);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add swarm UI elements to the console
|
||||
*/
|
||||
addSwarmUI() {
|
||||
// Add swarm mode toggle to header
|
||||
const headerRight = document.querySelector('.header-right');
|
||||
if (headerRight) {
|
||||
const swarmToggle = this.components.createActionButton({
|
||||
type: 'secondary',
|
||||
text: 'Swarm Mode',
|
||||
icon: '🌊',
|
||||
onclick: () => this.toggleSwarmMode()
|
||||
});
|
||||
|
||||
headerRight.insertBefore(swarmToggle.element, headerRight.firstChild);
|
||||
this.swarmToggleButton = swarmToggle;
|
||||
}
|
||||
|
||||
// Add swarm status to status bar
|
||||
const statusLeft = document.querySelector('.status-left');
|
||||
if (statusLeft) {
|
||||
const swarmStatus = document.createElement('span');
|
||||
swarmStatus.className = 'status-item';
|
||||
swarmStatus.id = 'swarm-status';
|
||||
swarmStatus.textContent = 'Swarm: Inactive';
|
||||
statusLeft.appendChild(swarmStatus);
|
||||
this.swarmStatusElement = swarmStatus;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup event handlers for swarm integration
|
||||
*/
|
||||
setupSwarmEventHandlers() {
|
||||
// Listen for swarm-related WebSocket messages
|
||||
if (this.console.wsClient) {
|
||||
this.console.wsClient.on('swarm_update', (data) => {
|
||||
this.handleSwarmUpdate(data);
|
||||
});
|
||||
|
||||
this.console.wsClient.on('agent_status', (data) => {
|
||||
this.handleAgentStatus(data);
|
||||
});
|
||||
}
|
||||
|
||||
// Listen for console commands
|
||||
if (this.console.terminal) {
|
||||
this.console.terminal.on('command', (command) => {
|
||||
if (command.startsWith('swarm')) {
|
||||
this.handleSwarmCommand(command);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enter swarm visualization mode
|
||||
*/
|
||||
enterSwarmMode() {
|
||||
if (this.isSwarmMode) {
|
||||
this.console.terminal.writeWarning('Already in swarm mode');
|
||||
return;
|
||||
}
|
||||
|
||||
this.isSwarmMode = true;
|
||||
|
||||
// Create swarm container
|
||||
const swarmContainer = document.createElement('div');
|
||||
swarmContainer.id = 'swarm-visualization-container';
|
||||
swarmContainer.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: rgba(0, 0, 0, 0.95);
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
`;
|
||||
|
||||
// Create close button
|
||||
const closeButton = this.components.createActionButton({
|
||||
type: 'secondary',
|
||||
text: 'Exit Swarm Mode',
|
||||
icon: '❌',
|
||||
onclick: () => this.exitSwarmMode()
|
||||
});
|
||||
|
||||
closeButton.element.style.cssText = `
|
||||
position: absolute;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 10001;
|
||||
`;
|
||||
|
||||
swarmContainer.appendChild(closeButton.element);
|
||||
|
||||
// Create swarm visualizer
|
||||
const visualizerContainer = document.createElement('div');
|
||||
visualizerContainer.style.cssText = `
|
||||
flex: 1;
|
||||
padding: 80px 20px 20px 20px;
|
||||
overflow: auto;
|
||||
`;
|
||||
|
||||
this.swarmVisualizer = new SwarmVisualizer(visualizerContainer, this.components);
|
||||
swarmContainer.appendChild(visualizerContainer);
|
||||
|
||||
document.body.appendChild(swarmContainer);
|
||||
this.swarmContainer = swarmContainer;
|
||||
|
||||
// Update UI
|
||||
this.updateSwarmStatus('Active');
|
||||
this.swarmToggleButton.setText('Exit Swarm');
|
||||
|
||||
this.console.terminal.writeSuccess('Entered swarm visualization mode');
|
||||
this.console.terminal.writeInfo('Use "swarm-monitor" to start real-time monitoring');
|
||||
}
|
||||
|
||||
/**
|
||||
* Exit swarm visualization mode
|
||||
*/
|
||||
exitSwarmMode() {
|
||||
if (!this.isSwarmMode) return;
|
||||
|
||||
this.isSwarmMode = false;
|
||||
|
||||
// Clean up swarm visualizer
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.destroy();
|
||||
this.swarmVisualizer = null;
|
||||
}
|
||||
|
||||
// Remove swarm container
|
||||
if (this.swarmContainer) {
|
||||
this.swarmContainer.remove();
|
||||
this.swarmContainer = null;
|
||||
}
|
||||
|
||||
// Update UI
|
||||
this.updateSwarmStatus('Inactive');
|
||||
this.swarmToggleButton.setText('Swarm Mode');
|
||||
|
||||
this.console.terminal.writeInfo('Exited swarm visualization mode');
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle swarm mode
|
||||
*/
|
||||
toggleSwarmMode() {
|
||||
if (this.isSwarmMode) {
|
||||
this.exitSwarmMode();
|
||||
} else {
|
||||
this.enterSwarmMode();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show swarm status
|
||||
*/
|
||||
showSwarmStatus() {
|
||||
this.console.terminal.writeInfo('📊 Swarm Status:');
|
||||
|
||||
// Mock status data - would normally fetch from API
|
||||
const status = {
|
||||
active: this.isSwarmMode,
|
||||
agents: Math.floor(Math.random() * 8) + 2,
|
||||
topology: 'mesh',
|
||||
uptime: '2h 34m',
|
||||
tasksCompleted: Math.floor(Math.random() * 100) + 50,
|
||||
averageResponseTime: Math.floor(Math.random() * 500) + 200
|
||||
};
|
||||
|
||||
this.console.terminal.write(` Mode: ${status.active ? 'Active' : 'Inactive'}`, 'info');
|
||||
this.console.terminal.write(` Agents: ${status.agents}`, 'info');
|
||||
this.console.terminal.write(` Topology: ${status.topology}`, 'info');
|
||||
this.console.terminal.write(` Uptime: ${status.uptime}`, 'info');
|
||||
this.console.terminal.write(` Tasks Completed: ${status.tasksCompleted}`, 'info');
|
||||
this.console.terminal.write(` Avg Response Time: ${status.averageResponseTime}ms`, 'info');
|
||||
}
|
||||
|
||||
/**
|
||||
* Start swarm monitoring
|
||||
*/
|
||||
startSwarmMonitoring(args) {
|
||||
if (!this.swarmVisualizer) {
|
||||
this.console.terminal.writeError('Not in swarm mode. Use "swarm" command first.');
|
||||
return;
|
||||
}
|
||||
|
||||
const topology = args && args[0] ? args[0] : 'mesh';
|
||||
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.topology = topology;
|
||||
this.swarmVisualizer.startMonitoring();
|
||||
}
|
||||
|
||||
this.console.terminal.writeSuccess(`Started swarm monitoring with ${topology} topology`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop swarm monitoring
|
||||
*/
|
||||
stopSwarmMonitoring() {
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.stopMonitoring();
|
||||
this.console.terminal.writeInfo('Stopped swarm monitoring');
|
||||
} else {
|
||||
this.console.terminal.writeWarning('Swarm monitoring not active');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open dashboard
|
||||
*/
|
||||
openDashboard() {
|
||||
if (this.dashboard) {
|
||||
this.console.terminal.writeWarning('Dashboard already open');
|
||||
return;
|
||||
}
|
||||
|
||||
// Create dashboard container
|
||||
const dashboardContainer = document.createElement('div');
|
||||
dashboardContainer.id = 'dashboard-container';
|
||||
dashboardContainer.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: rgba(0, 0, 0, 0.98);
|
||||
z-index: 20000;
|
||||
`;
|
||||
|
||||
// Create close button
|
||||
const closeButton = this.components.createActionButton({
|
||||
type: 'secondary',
|
||||
text: 'Close Dashboard',
|
||||
icon: '❌',
|
||||
onclick: () => this.closeDashboard()
|
||||
});
|
||||
|
||||
closeButton.element.style.cssText = `
|
||||
position: absolute;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 20001;
|
||||
`;
|
||||
|
||||
dashboardContainer.appendChild(closeButton.element);
|
||||
|
||||
// Create dashboard
|
||||
this.dashboard = new RealTimeDashboard(dashboardContainer, this.components);
|
||||
document.body.appendChild(dashboardContainer);
|
||||
this.dashboardContainer = dashboardContainer;
|
||||
|
||||
this.console.terminal.writeSuccess('Opened real-time dashboard');
|
||||
}
|
||||
|
||||
/**
|
||||
* Close dashboard
|
||||
*/
|
||||
closeDashboard() {
|
||||
if (this.dashboard) {
|
||||
this.dashboard.destroy();
|
||||
this.dashboard = null;
|
||||
}
|
||||
|
||||
if (this.dashboardContainer) {
|
||||
this.dashboardContainer.remove();
|
||||
this.dashboardContainer = null;
|
||||
}
|
||||
|
||||
this.console.terminal.writeInfo('Closed dashboard');
|
||||
}
|
||||
|
||||
/**
|
||||
* List agents
|
||||
*/
|
||||
listAgents() {
|
||||
this.console.terminal.writeInfo('🤖 Active Agents:');
|
||||
|
||||
// Mock agent data
|
||||
const agents = [
|
||||
{ id: 'coder_01', type: 'coder', status: 'active', task: 'Implementing API endpoints' },
|
||||
{ id: 'researcher_02', type: 'researcher', status: 'busy', task: 'Analyzing data patterns' },
|
||||
{ id: 'reviewer_03', type: 'reviewer', status: 'idle', task: null },
|
||||
{ id: 'tester_04', type: 'tester', status: 'active', task: 'Running test suite' }
|
||||
];
|
||||
|
||||
agents.forEach(agent => {
|
||||
const statusColor = agent.status === 'active' ? 'success' :
|
||||
agent.status === 'busy' ? 'warning' : 'info';
|
||||
const taskText = agent.task ? ` | Task: ${agent.task}` : ' | No active task';
|
||||
|
||||
this.console.terminal.write(
|
||||
` ${agent.id} (${agent.type}) - ${agent.status}${taskText}`,
|
||||
statusColor
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Change topology
|
||||
*/
|
||||
changeTopology(args) {
|
||||
if (!args || args.length === 0) {
|
||||
this.console.terminal.writeError('Usage: topology [mesh|hierarchical|ring|star]');
|
||||
return;
|
||||
}
|
||||
|
||||
const topology = args[0];
|
||||
const validTopologies = ['mesh', 'hierarchical', 'ring', 'star'];
|
||||
|
||||
if (!validTopologies.includes(topology)) {
|
||||
this.console.terminal.writeError(`Invalid topology. Valid options: ${validTopologies.join(', ')}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.topology = topology;
|
||||
this.swarmVisualizer.redrawTopology();
|
||||
this.console.terminal.writeSuccess(`Changed topology to ${topology}`);
|
||||
} else {
|
||||
this.console.terminal.writeWarning('Swarm visualizer not active');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle swarm update messages
|
||||
*/
|
||||
handleSwarmUpdate(data) {
|
||||
if (this.swarmVisualizer) {
|
||||
this.swarmVisualizer.swarmData = data;
|
||||
this.swarmVisualizer.processSwarmData();
|
||||
this.swarmVisualizer.updateStats();
|
||||
}
|
||||
|
||||
if (this.dashboard) {
|
||||
this.dashboard.handleWebSocketMessage({
|
||||
type: 'swarm_update',
|
||||
payload: data
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle agent status messages
|
||||
*/
|
||||
handleAgentStatus(data) {
|
||||
if (data.active !== undefined) {
|
||||
this.updateSwarmStatus(`${data.active} agents active`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update swarm status in UI
|
||||
*/
|
||||
updateSwarmStatus(status) {
|
||||
if (this.swarmStatusElement) {
|
||||
this.swarmStatusElement.textContent = `Swarm: ${status}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle swarm command
|
||||
*/
|
||||
handleSwarmCommand(command) {
|
||||
// Commands are already handled by the registered handlers
|
||||
// This could be used for additional processing if needed
|
||||
console.log('Swarm command processed:', command);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get integration status
|
||||
*/
|
||||
getStatus() {
|
||||
return {
|
||||
swarmMode: this.isSwarmMode,
|
||||
visualizerActive: this.swarmVisualizer?.isActive || false,
|
||||
dashboardOpen: !!this.dashboard,
|
||||
componentsLoaded: this.components.isInitialized
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup integration
|
||||
*/
|
||||
destroy() {
|
||||
this.exitSwarmMode();
|
||||
this.closeDashboard();
|
||||
|
||||
if (this.swarmToggleButton) {
|
||||
this.swarmToggleButton.element.remove();
|
||||
}
|
||||
|
||||
if (this.swarmStatusElement) {
|
||||
this.swarmStatusElement.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default SwarmIntegration;
|
||||
@@ -1,879 +0,0 @@
|
||||
/**
|
||||
* SwarmVisualizer - Real-time swarm monitoring and visualization component
|
||||
* Provides interactive swarm topology view with live agent status updates
|
||||
*/
|
||||
|
||||
export class SwarmVisualizer {
|
||||
constructor(container, componentLibrary) {
|
||||
this.container = container;
|
||||
this.components = componentLibrary;
|
||||
this.swarmData = null;
|
||||
this.agents = new Map();
|
||||
this.connections = new Map();
|
||||
this.topology = 'mesh';
|
||||
this.updateInterval = null;
|
||||
this.isActive = false;
|
||||
|
||||
// Canvas for topology visualization
|
||||
this.canvas = null;
|
||||
this.ctx = null;
|
||||
this.canvasSize = { width: 800, height: 600 };
|
||||
|
||||
// Animation state
|
||||
this.animationFrame = null;
|
||||
this.particles = [];
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize swarm visualizer
|
||||
*/
|
||||
init() {
|
||||
this.createUI();
|
||||
this.setupEventHandlers();
|
||||
console.log('🌊 Swarm Visualizer initialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the visualizer UI
|
||||
*/
|
||||
createUI() {
|
||||
// Main container
|
||||
const mainPanel = this.components.createToolPanel({
|
||||
title: 'Swarm Visualizer',
|
||||
description: 'Real-time swarm topology and agent monitoring'
|
||||
});
|
||||
|
||||
// Control panel
|
||||
const controlPanel = this.createControlPanel();
|
||||
mainPanel.append(controlPanel);
|
||||
|
||||
// Stats panel
|
||||
const statsPanel = this.createStatsPanel();
|
||||
mainPanel.append(statsPanel);
|
||||
|
||||
// Topology canvas
|
||||
const canvasContainer = this.createTopologyCanvas();
|
||||
mainPanel.append(canvasContainer);
|
||||
|
||||
// Agent details panel
|
||||
const agentPanel = this.createAgentPanel();
|
||||
mainPanel.append(agentPanel);
|
||||
|
||||
this.container.appendChild(mainPanel.element);
|
||||
this.elements = {
|
||||
mainPanel,
|
||||
controlPanel,
|
||||
statsPanel,
|
||||
canvasContainer,
|
||||
agentPanel
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create control panel
|
||||
*/
|
||||
createControlPanel() {
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'swarm-control-panel';
|
||||
|
||||
// Start/Stop controls
|
||||
const startBtn = this.components.createActionButton({
|
||||
type: 'primary',
|
||||
text: 'Start Monitoring',
|
||||
icon: '▶️',
|
||||
onclick: () => this.startMonitoring()
|
||||
});
|
||||
|
||||
const stopBtn = this.components.createActionButton({
|
||||
type: 'secondary',
|
||||
text: 'Stop',
|
||||
icon: '⏹️',
|
||||
onclick: () => this.stopMonitoring()
|
||||
});
|
||||
|
||||
// Topology selector
|
||||
const topologySelect = document.createElement('select');
|
||||
topologySelect.id = 'topology-selector';
|
||||
topologySelect.innerHTML = `
|
||||
<option value="mesh">Mesh Network</option>
|
||||
<option value="hierarchical">Hierarchical</option>
|
||||
<option value="ring">Ring Topology</option>
|
||||
<option value="star">Star Network</option>
|
||||
`;
|
||||
topologySelect.addEventListener('change', (e) => {
|
||||
this.topology = e.target.value;
|
||||
this.redrawTopology();
|
||||
});
|
||||
|
||||
// Refresh rate selector
|
||||
const refreshSelect = document.createElement('select');
|
||||
refreshSelect.id = 'refresh-rate';
|
||||
refreshSelect.innerHTML = `
|
||||
<option value="1000">1 second</option>
|
||||
<option value="2000" selected>2 seconds</option>
|
||||
<option value="5000">5 seconds</option>
|
||||
<option value="10000">10 seconds</option>
|
||||
`;
|
||||
|
||||
panel.appendChild(startBtn.element);
|
||||
panel.appendChild(stopBtn.element);
|
||||
panel.appendChild(this.createLabel('Topology:', topologySelect));
|
||||
panel.appendChild(this.createLabel('Refresh Rate:', refreshSelect));
|
||||
|
||||
this.controlElements = {
|
||||
startBtn,
|
||||
stopBtn,
|
||||
topologySelect,
|
||||
refreshSelect
|
||||
};
|
||||
|
||||
return panel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create stats panel
|
||||
*/
|
||||
createStatsPanel() {
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'swarm-stats-panel';
|
||||
panel.style.display = 'flex';
|
||||
panel.style.gap = '16px';
|
||||
panel.style.flexWrap = 'wrap';
|
||||
|
||||
this.statsCards = {
|
||||
totalAgents: this.components.createStatsCard({
|
||||
icon: '🤖',
|
||||
value: '0',
|
||||
label: 'Total Agents'
|
||||
}),
|
||||
activeAgents: this.components.createStatsCard({
|
||||
icon: '✅',
|
||||
value: '0',
|
||||
label: 'Active'
|
||||
}),
|
||||
busyAgents: this.components.createStatsCard({
|
||||
icon: '⚙️',
|
||||
value: '0',
|
||||
label: 'Busy'
|
||||
}),
|
||||
idleAgents: this.components.createStatsCard({
|
||||
icon: '💤',
|
||||
value: '0',
|
||||
label: 'Idle'
|
||||
}),
|
||||
errorAgents: this.components.createStatsCard({
|
||||
icon: '❌',
|
||||
value: '0',
|
||||
label: 'Errors'
|
||||
}),
|
||||
throughput: this.components.createStatsCard({
|
||||
icon: '📊',
|
||||
value: '0/min',
|
||||
label: 'Task Throughput'
|
||||
})
|
||||
};
|
||||
|
||||
Object.values(this.statsCards).forEach(card => {
|
||||
panel.appendChild(card.element);
|
||||
});
|
||||
|
||||
return panel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create topology canvas
|
||||
*/
|
||||
createTopologyCanvas() {
|
||||
const container = document.createElement('div');
|
||||
container.className = 'topology-canvas-container';
|
||||
container.style.cssText = `
|
||||
position: relative;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
margin: 16px 0;
|
||||
overflow: hidden;
|
||||
`;
|
||||
|
||||
this.canvas = document.createElement('canvas');
|
||||
this.canvas.width = this.canvasSize.width;
|
||||
this.canvas.height = this.canvasSize.height;
|
||||
this.canvas.style.display = 'block';
|
||||
this.ctx = this.canvas.getContext('2d');
|
||||
|
||||
// Canvas event handlers
|
||||
this.canvas.addEventListener('click', (e) => this.handleCanvasClick(e));
|
||||
this.canvas.addEventListener('mousemove', (e) => this.handleCanvasHover(e));
|
||||
|
||||
container.appendChild(this.canvas);
|
||||
return container;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create agent details panel
|
||||
*/
|
||||
createAgentPanel() {
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'agent-details-panel';
|
||||
panel.style.cssText = `
|
||||
background: #2a2a2a;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 8px 0;
|
||||
min-height: 200px;
|
||||
`;
|
||||
|
||||
const title = document.createElement('h3');
|
||||
title.textContent = 'Agent Details';
|
||||
title.style.color = '#00d4ff';
|
||||
title.style.marginBottom = '12px';
|
||||
|
||||
const content = document.createElement('div');
|
||||
content.id = 'agent-details-content';
|
||||
content.innerHTML = '<p style="color: #888;">Click on an agent to view details</p>';
|
||||
|
||||
panel.appendChild(title);
|
||||
panel.appendChild(content);
|
||||
|
||||
this.agentDetailsContent = content;
|
||||
return panel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start monitoring
|
||||
*/
|
||||
async startMonitoring() {
|
||||
if (this.isActive) return;
|
||||
|
||||
this.isActive = true;
|
||||
this.controlElements.startBtn.setDisabled(true);
|
||||
this.controlElements.stopBtn.setDisabled(false);
|
||||
|
||||
// Start data updates
|
||||
const refreshRate = parseInt(this.controlElements.refreshSelect.value);
|
||||
this.updateInterval = setInterval(() => {
|
||||
this.updateSwarmData();
|
||||
}, refreshRate);
|
||||
|
||||
// Start animation loop
|
||||
this.startAnimation();
|
||||
|
||||
// Initial data fetch
|
||||
await this.updateSwarmData();
|
||||
|
||||
console.log('🔄 Swarm monitoring started');
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop monitoring
|
||||
*/
|
||||
stopMonitoring() {
|
||||
if (!this.isActive) return;
|
||||
|
||||
this.isActive = false;
|
||||
this.controlElements.startBtn.setDisabled(false);
|
||||
this.controlElements.stopBtn.setDisabled(true);
|
||||
|
||||
if (this.updateInterval) {
|
||||
clearInterval(this.updateInterval);
|
||||
this.updateInterval = null;
|
||||
}
|
||||
|
||||
if (this.animationFrame) {
|
||||
cancelAnimationFrame(this.animationFrame);
|
||||
this.animationFrame = null;
|
||||
}
|
||||
|
||||
console.log('⏹️ Swarm monitoring stopped');
|
||||
}
|
||||
|
||||
/**
|
||||
* Update swarm data from memory
|
||||
*/
|
||||
async updateSwarmData() {
|
||||
try {
|
||||
// Fetch swarm status from memory
|
||||
const response = await fetch('/api/claude-flow/swarm/status');
|
||||
if (response.ok) {
|
||||
this.swarmData = await response.json();
|
||||
this.processSwarmData();
|
||||
this.updateStats();
|
||||
this.redrawTopology();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to fetch swarm data:', error);
|
||||
// Fallback to mock data for demo
|
||||
this.generateMockData();
|
||||
this.processSwarmData();
|
||||
this.updateStats();
|
||||
this.redrawTopology();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate mock data for demonstration
|
||||
*/
|
||||
generateMockData() {
|
||||
const agentTypes = ['coder', 'researcher', 'analyzer', 'reviewer', 'tester'];
|
||||
const statuses = ['active', 'busy', 'idle', 'error'];
|
||||
const agentCount = Math.floor(Math.random() * 8) + 3;
|
||||
|
||||
this.swarmData = {
|
||||
id: `swarm_${Date.now()}`,
|
||||
topology: this.topology,
|
||||
agents: [],
|
||||
connections: [],
|
||||
metrics: {
|
||||
totalTasks: Math.floor(Math.random() * 100),
|
||||
completedTasks: Math.floor(Math.random() * 80),
|
||||
failedTasks: Math.floor(Math.random() * 5),
|
||||
averageResponseTime: Math.random() * 1000 + 500,
|
||||
throughput: Math.floor(Math.random() * 20) + 5
|
||||
}
|
||||
};
|
||||
|
||||
// Generate agents
|
||||
for (let i = 0; i < agentCount; i++) {
|
||||
const agent = {
|
||||
id: `agent_${i}`,
|
||||
type: agentTypes[Math.floor(Math.random() * agentTypes.length)],
|
||||
status: statuses[Math.floor(Math.random() * statuses.length)],
|
||||
capabilities: ['task_processing', 'memory_access'],
|
||||
currentTask: Math.random() > 0.5 ? `Task ${Math.floor(Math.random() * 100)}` : null,
|
||||
metrics: {
|
||||
tasksCompleted: Math.floor(Math.random() * 50),
|
||||
successRate: Math.random() * 100,
|
||||
averageTime: Math.random() * 2000 + 200,
|
||||
memoryUsage: Math.random() * 100
|
||||
},
|
||||
position: this.calculateAgentPosition(i, agentCount)
|
||||
};
|
||||
this.swarmData.agents.push(agent);
|
||||
}
|
||||
|
||||
// Generate connections based on topology
|
||||
this.generateConnections();
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate agent position based on topology
|
||||
*/
|
||||
calculateAgentPosition(index, total) {
|
||||
const centerX = this.canvasSize.width / 2;
|
||||
const centerY = this.canvasSize.height / 2;
|
||||
const radius = Math.min(centerX, centerY) * 0.7;
|
||||
|
||||
switch (this.topology) {
|
||||
case 'mesh':
|
||||
case 'ring':
|
||||
const angle = (index * 2 * Math.PI) / total;
|
||||
return {
|
||||
x: centerX + radius * Math.cos(angle),
|
||||
y: centerY + radius * Math.sin(angle)
|
||||
};
|
||||
|
||||
case 'hierarchical':
|
||||
const levels = Math.ceil(Math.log2(total));
|
||||
const level = Math.floor(Math.log2(index + 1));
|
||||
const positionInLevel = index - (Math.pow(2, level) - 1);
|
||||
const levelWidth = Math.pow(2, level);
|
||||
return {
|
||||
x: centerX + (positionInLevel - levelWidth/2 + 0.5) * (this.canvasSize.width / (levelWidth + 1)),
|
||||
y: 100 + level * (this.canvasSize.height - 200) / (levels - 1)
|
||||
};
|
||||
|
||||
case 'star':
|
||||
if (index === 0) {
|
||||
return { x: centerX, y: centerY };
|
||||
} else {
|
||||
const starAngle = ((index - 1) * 2 * Math.PI) / (total - 1);
|
||||
return {
|
||||
x: centerX + radius * Math.cos(starAngle),
|
||||
y: centerY + radius * Math.sin(starAngle)
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
return {
|
||||
x: Math.random() * (this.canvasSize.width - 100) + 50,
|
||||
y: Math.random() * (this.canvasSize.height - 100) + 50
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate connections between agents
|
||||
*/
|
||||
generateConnections() {
|
||||
if (!this.swarmData || !this.swarmData.agents) return;
|
||||
|
||||
const agents = this.swarmData.agents;
|
||||
this.swarmData.connections = [];
|
||||
|
||||
switch (this.topology) {
|
||||
case 'mesh':
|
||||
// Full mesh - everyone connected to everyone
|
||||
for (let i = 0; i < agents.length; i++) {
|
||||
for (let j = i + 1; j < agents.length; j++) {
|
||||
this.swarmData.connections.push({
|
||||
from: agents[i].id,
|
||||
to: agents[j].id,
|
||||
strength: Math.random(),
|
||||
latency: Math.random() * 100 + 10
|
||||
});
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'ring':
|
||||
// Ring topology - each agent connected to next
|
||||
for (let i = 0; i < agents.length; i++) {
|
||||
const next = (i + 1) % agents.length;
|
||||
this.swarmData.connections.push({
|
||||
from: agents[i].id,
|
||||
to: agents[next].id,
|
||||
strength: Math.random(),
|
||||
latency: Math.random() * 50 + 5
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
case 'star':
|
||||
// Star topology - all connected to central agent
|
||||
if (agents.length > 0) {
|
||||
for (let i = 1; i < agents.length; i++) {
|
||||
this.swarmData.connections.push({
|
||||
from: agents[0].id,
|
||||
to: agents[i].id,
|
||||
strength: Math.random(),
|
||||
latency: Math.random() * 30 + 5
|
||||
});
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'hierarchical':
|
||||
// Tree structure connections
|
||||
for (let i = 1; i < agents.length; i++) {
|
||||
const parent = Math.floor((i - 1) / 2);
|
||||
this.swarmData.connections.push({
|
||||
from: agents[parent].id,
|
||||
to: agents[i].id,
|
||||
strength: Math.random(),
|
||||
latency: Math.random() * 40 + 5
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process swarm data and update internal state
|
||||
*/
|
||||
processSwarmData() {
|
||||
if (!this.swarmData) return;
|
||||
|
||||
// Update agents map
|
||||
this.agents.clear();
|
||||
this.swarmData.agents?.forEach(agent => {
|
||||
this.agents.set(agent.id, agent);
|
||||
});
|
||||
|
||||
// Update connections map
|
||||
this.connections.clear();
|
||||
this.swarmData.connections?.forEach(conn => {
|
||||
this.connections.set(`${conn.from}-${conn.to}`, conn);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update statistics display
|
||||
*/
|
||||
updateStats() {
|
||||
if (!this.swarmData) return;
|
||||
|
||||
const agents = Array.from(this.agents.values());
|
||||
const statusCounts = agents.reduce((acc, agent) => {
|
||||
acc[agent.status] = (acc[agent.status] || 0) + 1;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
this.statsCards.totalAgents.setValue(agents.length.toString());
|
||||
this.statsCards.activeAgents.setValue((statusCounts.active || 0).toString());
|
||||
this.statsCards.busyAgents.setValue((statusCounts.busy || 0).toString());
|
||||
this.statsCards.idleAgents.setValue((statusCounts.idle || 0).toString());
|
||||
this.statsCards.errorAgents.setValue((statusCounts.error || 0).toString());
|
||||
|
||||
if (this.swarmData.metrics) {
|
||||
this.statsCards.throughput.setValue(`${this.swarmData.metrics.throughput || 0}/min`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Redraw topology visualization
|
||||
*/
|
||||
redrawTopology() {
|
||||
if (!this.ctx || !this.swarmData) return;
|
||||
|
||||
// Clear canvas
|
||||
this.ctx.fillStyle = '#1a1a1a';
|
||||
this.ctx.fillRect(0, 0, this.canvasSize.width, this.canvasSize.height);
|
||||
|
||||
// Draw grid
|
||||
this.drawGrid();
|
||||
|
||||
// Draw connections
|
||||
this.drawConnections();
|
||||
|
||||
// Draw agents
|
||||
this.drawAgents();
|
||||
|
||||
// Draw particles for active connections
|
||||
this.updateParticles();
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw background grid
|
||||
*/
|
||||
drawGrid() {
|
||||
this.ctx.strokeStyle = '#333';
|
||||
this.ctx.lineWidth = 1;
|
||||
this.ctx.setLineDash([2, 4]);
|
||||
|
||||
const gridSize = 50;
|
||||
for (let x = 0; x < this.canvasSize.width; x += gridSize) {
|
||||
this.ctx.beginPath();
|
||||
this.ctx.moveTo(x, 0);
|
||||
this.ctx.lineTo(x, this.canvasSize.height);
|
||||
this.ctx.stroke();
|
||||
}
|
||||
|
||||
for (let y = 0; y < this.canvasSize.height; y += gridSize) {
|
||||
this.ctx.beginPath();
|
||||
this.ctx.moveTo(0, y);
|
||||
this.ctx.lineTo(this.canvasSize.width, y);
|
||||
this.ctx.stroke();
|
||||
}
|
||||
|
||||
this.ctx.setLineDash([]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw connections between agents
|
||||
*/
|
||||
drawConnections() {
|
||||
this.connections.forEach((conn, key) => {
|
||||
const fromAgent = this.agents.get(conn.from);
|
||||
const toAgent = this.agents.get(conn.to);
|
||||
|
||||
if (fromAgent && toAgent && fromAgent.position && toAgent.position) {
|
||||
this.ctx.strokeStyle = `rgba(0, 212, 255, ${conn.strength * 0.6 + 0.2})`;
|
||||
this.ctx.lineWidth = Math.max(1, conn.strength * 3);
|
||||
this.ctx.setLineDash([]);
|
||||
|
||||
this.ctx.beginPath();
|
||||
this.ctx.moveTo(fromAgent.position.x, fromAgent.position.y);
|
||||
this.ctx.lineTo(toAgent.position.x, toAgent.position.y);
|
||||
this.ctx.stroke();
|
||||
|
||||
// Draw latency indicator
|
||||
const midX = (fromAgent.position.x + toAgent.position.x) / 2;
|
||||
const midY = (fromAgent.position.y + toAgent.position.y) / 2;
|
||||
|
||||
this.ctx.fillStyle = '#666';
|
||||
this.ctx.font = '10px monospace';
|
||||
this.ctx.fillText(`${Math.round(conn.latency)}ms`, midX + 5, midY - 5);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw agent nodes
|
||||
*/
|
||||
drawAgents() {
|
||||
this.agents.forEach(agent => {
|
||||
if (!agent.position) return;
|
||||
|
||||
const { x, y } = agent.position;
|
||||
const radius = 25;
|
||||
|
||||
// Agent status colors
|
||||
const statusColors = {
|
||||
active: '#22c55e',
|
||||
busy: '#f59e0b',
|
||||
idle: '#6b7280',
|
||||
error: '#ef4444'
|
||||
};
|
||||
|
||||
// Draw agent circle
|
||||
this.ctx.fillStyle = statusColors[agent.status] || '#6b7280';
|
||||
this.ctx.beginPath();
|
||||
this.ctx.arc(x, y, radius, 0, 2 * Math.PI);
|
||||
this.ctx.fill();
|
||||
|
||||
// Draw agent border
|
||||
this.ctx.strokeStyle = '#fff';
|
||||
this.ctx.lineWidth = 2;
|
||||
this.ctx.stroke();
|
||||
|
||||
// Draw agent type icon
|
||||
this.ctx.fillStyle = '#fff';
|
||||
this.ctx.font = 'bold 12px monospace';
|
||||
this.ctx.textAlign = 'center';
|
||||
this.ctx.fillText(this.getAgentIcon(agent.type), x, y + 4);
|
||||
|
||||
// Draw agent ID
|
||||
this.ctx.fillStyle = '#fff';
|
||||
this.ctx.font = '10px monospace';
|
||||
this.ctx.fillText(agent.id, x, y + radius + 15);
|
||||
|
||||
// Draw current task indicator
|
||||
if (agent.currentTask) {
|
||||
this.ctx.fillStyle = '#00d4ff';
|
||||
this.ctx.beginPath();
|
||||
this.ctx.arc(x + radius - 5, y - radius + 5, 5, 0, 2 * Math.PI);
|
||||
this.ctx.fill();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get icon for agent type
|
||||
*/
|
||||
getAgentIcon(type) {
|
||||
const icons = {
|
||||
coder: '💻',
|
||||
researcher: '🔍',
|
||||
analyzer: '📊',
|
||||
reviewer: '✅',
|
||||
tester: '🧪',
|
||||
coordinator: '🎯',
|
||||
optimizer: '⚡'
|
||||
};
|
||||
return icons[type] || '🤖';
|
||||
}
|
||||
|
||||
/**
|
||||
* Update and draw particles for active connections
|
||||
*/
|
||||
updateParticles() {
|
||||
// Remove old particles
|
||||
this.particles = this.particles.filter(p => p.life > 0);
|
||||
|
||||
// Add new particles for active connections
|
||||
if (Math.random() < 0.3) {
|
||||
this.connections.forEach((conn, key) => {
|
||||
const fromAgent = this.agents.get(conn.from);
|
||||
const toAgent = this.agents.get(conn.to);
|
||||
|
||||
if (fromAgent?.status === 'busy' && toAgent && fromAgent.position && toAgent.position) {
|
||||
this.particles.push({
|
||||
x: fromAgent.position.x,
|
||||
y: fromAgent.position.y,
|
||||
targetX: toAgent.position.x,
|
||||
targetY: toAgent.position.y,
|
||||
progress: 0,
|
||||
life: 1,
|
||||
speed: 0.02,
|
||||
color: conn.strength > 0.7 ? '#00d4ff' : '#888'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Update and draw particles
|
||||
this.particles.forEach(particle => {
|
||||
particle.progress += particle.speed;
|
||||
particle.life -= 0.01;
|
||||
|
||||
const currentX = particle.x + (particle.targetX - particle.x) * particle.progress;
|
||||
const currentY = particle.y + (particle.targetY - particle.y) * particle.progress;
|
||||
|
||||
this.ctx.fillStyle = particle.color;
|
||||
this.ctx.globalAlpha = particle.life;
|
||||
this.ctx.beginPath();
|
||||
this.ctx.arc(currentX, currentY, 3, 0, 2 * Math.PI);
|
||||
this.ctx.fill();
|
||||
this.ctx.globalAlpha = 1;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle canvas click events
|
||||
*/
|
||||
handleCanvasClick(event) {
|
||||
const rect = this.canvas.getBoundingClientRect();
|
||||
const x = event.clientX - rect.left;
|
||||
const y = event.clientY - rect.top;
|
||||
|
||||
// Find clicked agent
|
||||
const clickedAgent = Array.from(this.agents.values()).find(agent => {
|
||||
if (!agent.position) return false;
|
||||
const distance = Math.sqrt(
|
||||
Math.pow(x - agent.position.x, 2) + Math.pow(y - agent.position.y, 2)
|
||||
);
|
||||
return distance <= 25;
|
||||
});
|
||||
|
||||
if (clickedAgent) {
|
||||
this.showAgentDetails(clickedAgent);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle canvas hover events
|
||||
*/
|
||||
handleCanvasHover(event) {
|
||||
const rect = this.canvas.getBoundingClientRect();
|
||||
const x = event.clientX - rect.left;
|
||||
const y = event.clientY - rect.top;
|
||||
|
||||
// Check if hovering over agent
|
||||
const hoveredAgent = Array.from(this.agents.values()).find(agent => {
|
||||
if (!agent.position) return false;
|
||||
const distance = Math.sqrt(
|
||||
Math.pow(x - agent.position.x, 2) + Math.pow(y - agent.position.y, 2)
|
||||
);
|
||||
return distance <= 25;
|
||||
});
|
||||
|
||||
this.canvas.style.cursor = hoveredAgent ? 'pointer' : 'default';
|
||||
}
|
||||
|
||||
/**
|
||||
* Show agent details
|
||||
*/
|
||||
showAgentDetails(agent) {
|
||||
const metrics = agent.metrics || {};
|
||||
const capabilities = agent.capabilities || [];
|
||||
|
||||
this.agentDetailsContent.innerHTML = `
|
||||
<div class="agent-details">
|
||||
<div class="agent-header">
|
||||
<h4>${this.getAgentIcon(agent.type)} ${agent.id}</h4>
|
||||
<span class="status-badge status-${agent.status}">${agent.status}</span>
|
||||
</div>
|
||||
|
||||
<div class="agent-info">
|
||||
<div class="info-row">
|
||||
<label>Type:</label>
|
||||
<span>${agent.type}</span>
|
||||
</div>
|
||||
<div class="info-row">
|
||||
<label>Current Task:</label>
|
||||
<span>${agent.currentTask || 'None'}</span>
|
||||
</div>
|
||||
<div class="info-row">
|
||||
<label>Capabilities:</label>
|
||||
<span>${capabilities.join(', ')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="agent-metrics">
|
||||
<h5>Performance Metrics</h5>
|
||||
<div class="metrics-grid">
|
||||
<div class="metric">
|
||||
<label>Tasks Completed:</label>
|
||||
<span>${metrics.tasksCompleted || 0}</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<label>Success Rate:</label>
|
||||
<span>${Math.round(metrics.successRate || 0)}%</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<label>Avg Response Time:</label>
|
||||
<span>${Math.round(metrics.averageTime || 0)}ms</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<label>Memory Usage:</label>
|
||||
<span>${Math.round(metrics.memoryUsage || 0)}MB</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start animation loop
|
||||
*/
|
||||
startAnimation() {
|
||||
const animate = () => {
|
||||
if (this.isActive) {
|
||||
this.redrawTopology();
|
||||
this.animationFrame = requestAnimationFrame(animate);
|
||||
}
|
||||
};
|
||||
animate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create form label
|
||||
*/
|
||||
createLabel(text, element) {
|
||||
const label = document.createElement('label');
|
||||
label.textContent = text;
|
||||
label.appendChild(element);
|
||||
label.style.cssText = `
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
color: #fff;
|
||||
font-size: 14px;
|
||||
margin: 0 8px;
|
||||
`;
|
||||
return label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup event handlers
|
||||
*/
|
||||
setupEventHandlers() {
|
||||
// Window resize handler
|
||||
window.addEventListener('resize', () => {
|
||||
this.redrawTopology();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Store progress to memory
|
||||
*/
|
||||
async storeProgress() {
|
||||
const progress = {
|
||||
isActive: this.isActive,
|
||||
topology: this.topology,
|
||||
agentCount: this.agents.size,
|
||||
connectionCount: this.connections.size,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/claude-flow/memory/set', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
namespace: 'swarm_1756475726467_c9ey1p9vm',
|
||||
key: 'frontend/swarm_visualizer',
|
||||
value: JSON.stringify(progress)
|
||||
})
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('Failed to store progress:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup resources
|
||||
*/
|
||||
destroy() {
|
||||
this.stopMonitoring();
|
||||
if (this.container) {
|
||||
this.container.innerHTML = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default SwarmVisualizer;
|
||||
@@ -1,683 +0,0 @@
|
||||
/**
|
||||
* Terminal Emulator for Claude Code Console
|
||||
* Provides terminal-like behavior and output formatting
|
||||
*/
|
||||
|
||||
export class TerminalEmulator {
|
||||
constructor(outputElement, inputElement) {
|
||||
this.outputElement = outputElement;
|
||||
this.inputElement = inputElement;
|
||||
this.history = [];
|
||||
this.historyIndex = -1;
|
||||
this.maxHistorySize = 1000;
|
||||
this.maxOutputLines = 1000;
|
||||
this.currentPrompt = 'claude-flow>';
|
||||
this.isLocked = false;
|
||||
|
||||
// Command suggestions
|
||||
this.commands = [
|
||||
'help',
|
||||
'clear',
|
||||
'status',
|
||||
'connect',
|
||||
'disconnect',
|
||||
'claude-flow',
|
||||
'swarm',
|
||||
'init',
|
||||
'config',
|
||||
'memory',
|
||||
'tools',
|
||||
'agents',
|
||||
'benchmark',
|
||||
'sparc',
|
||||
];
|
||||
|
||||
// ANSI color codes mapping
|
||||
this.ansiColors = {
|
||||
30: '#000000', // Black
|
||||
31: '#ff5555', // Red
|
||||
32: '#50fa7b', // Green
|
||||
33: '#f1fa8c', // Yellow
|
||||
34: '#bd93f9', // Blue
|
||||
35: '#ff79c6', // Magenta
|
||||
36: '#8be9fd', // Cyan
|
||||
37: '#f8f8f2', // White
|
||||
90: '#6272a4', // Bright Black (Gray)
|
||||
91: '#ff6e6e', // Bright Red
|
||||
92: '#69ff94', // Bright Green
|
||||
93: '#ffffa5', // Bright Yellow
|
||||
94: '#d6acff', // Bright Blue
|
||||
95: '#ff92df', // Bright Magenta
|
||||
96: '#a4ffff', // Bright Cyan
|
||||
97: '#ffffff', // Bright White
|
||||
};
|
||||
|
||||
this.setupInputHandlers();
|
||||
this.setupScrollBehavior();
|
||||
}
|
||||
|
||||
/**
|
||||
* Write output to terminal
|
||||
*/
|
||||
write(content, type = 'output', timestamp = true) {
|
||||
const entry = this.createOutputEntry(content, type, timestamp);
|
||||
this.outputElement.appendChild(entry);
|
||||
this.limitOutputLines();
|
||||
this.scrollToBottom();
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write line to terminal
|
||||
*/
|
||||
writeLine(content, type = 'output', timestamp = true) {
|
||||
return this.write(content + '\n', type, timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write command to terminal
|
||||
*/
|
||||
writeCommand(command) {
|
||||
return this.write(`${this.currentPrompt} ${command}`, 'command', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write error message
|
||||
*/
|
||||
writeError(message) {
|
||||
return this.writeLine(`Error: ${message}`, 'error');
|
||||
}
|
||||
|
||||
/**
|
||||
* Write success message
|
||||
*/
|
||||
writeSuccess(message) {
|
||||
return this.writeLine(message, 'success');
|
||||
}
|
||||
|
||||
/**
|
||||
* Write warning message
|
||||
*/
|
||||
writeWarning(message) {
|
||||
return this.writeLine(`Warning: ${message}`, 'warning');
|
||||
}
|
||||
|
||||
/**
|
||||
* Write info message
|
||||
*/
|
||||
writeInfo(message) {
|
||||
return this.writeLine(message, 'info');
|
||||
}
|
||||
|
||||
/**
|
||||
* Write raw HTML content
|
||||
*/
|
||||
writeHTML(html, type = 'output') {
|
||||
const entry = document.createElement('div');
|
||||
entry.className = 'output-entry';
|
||||
entry.innerHTML = html;
|
||||
|
||||
if (type) {
|
||||
entry.classList.add(`output-${type}`);
|
||||
}
|
||||
|
||||
this.outputElement.appendChild(entry);
|
||||
this.limitOutputLines();
|
||||
this.scrollToBottom();
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear terminal output
|
||||
*/
|
||||
clear() {
|
||||
this.outputElement.innerHTML = '';
|
||||
this.showWelcomeMessage();
|
||||
}
|
||||
|
||||
/**
|
||||
* Show welcome message
|
||||
*/
|
||||
showWelcomeMessage() {
|
||||
// Check if welcome message already exists (from static HTML)
|
||||
const existingWelcome = this.outputElement.querySelector('.welcome-message');
|
||||
if (existingWelcome) {
|
||||
// Welcome message already exists, don't add another one
|
||||
return;
|
||||
}
|
||||
|
||||
const welcome = document.createElement('div');
|
||||
welcome.className = 'welcome-message';
|
||||
welcome.innerHTML = `
|
||||
<div class="ascii-art">╔═══════════════════════════════════════════════════════════╗
|
||||
║ ║
|
||||
║ 🌊 Claude Flow v2.0.0 ║
|
||||
║ ║
|
||||
║ Welcome to the web-based swarm orchestration ║
|
||||
║ Type 'help' for available commands ║
|
||||
║ Use Ctrl+L to clear console ║
|
||||
║ ║
|
||||
╚═══════════════════════════════════════════════════════════╝</div>
|
||||
`;
|
||||
this.outputElement.appendChild(welcome);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set prompt text
|
||||
*/
|
||||
setPrompt(prompt) {
|
||||
this.currentPrompt = prompt;
|
||||
const promptElement = document.getElementById('promptText');
|
||||
if (promptElement) {
|
||||
promptElement.textContent = prompt;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lock/unlock input
|
||||
*/
|
||||
setLocked(locked) {
|
||||
this.isLocked = locked;
|
||||
this.inputElement.disabled = locked;
|
||||
|
||||
if (locked) {
|
||||
this.inputElement.placeholder = 'Processing...';
|
||||
} else {
|
||||
this.inputElement.placeholder = 'Enter command...';
|
||||
this.inputElement.focus();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Focus input
|
||||
*/
|
||||
focus() {
|
||||
if (!this.isLocked) {
|
||||
this.inputElement.focus();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current input value
|
||||
*/
|
||||
getInput() {
|
||||
return this.inputElement.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set input value
|
||||
*/
|
||||
setInput(value) {
|
||||
this.inputElement.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear input
|
||||
*/
|
||||
clearInput() {
|
||||
this.inputElement.value = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Add command to history
|
||||
*/
|
||||
addToHistory(command) {
|
||||
if (command.trim() && this.history[this.history.length - 1] !== command) {
|
||||
this.history.push(command);
|
||||
|
||||
if (this.history.length > this.maxHistorySize) {
|
||||
this.history.shift();
|
||||
}
|
||||
}
|
||||
|
||||
this.historyIndex = -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate command history
|
||||
*/
|
||||
navigateHistory(direction) {
|
||||
if (this.history.length === 0) return;
|
||||
|
||||
if (direction === 'up') {
|
||||
if (this.historyIndex === -1) {
|
||||
this.historyIndex = this.history.length - 1;
|
||||
} else if (this.historyIndex > 0) {
|
||||
this.historyIndex--;
|
||||
}
|
||||
} else if (direction === 'down') {
|
||||
if (this.historyIndex < this.history.length - 1) {
|
||||
this.historyIndex++;
|
||||
} else {
|
||||
this.historyIndex = -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.historyIndex === -1) {
|
||||
this.setInput('');
|
||||
} else {
|
||||
this.setInput(this.history[this.historyIndex]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create output entry element
|
||||
*/
|
||||
createOutputEntry(content, type, timestamp) {
|
||||
const entry = document.createElement('div');
|
||||
entry.className = 'output-entry';
|
||||
|
||||
const line = document.createElement('div');
|
||||
line.className = 'output-line';
|
||||
|
||||
// Add timestamp if enabled
|
||||
if (timestamp && this.shouldShowTimestamp()) {
|
||||
const timeElement = document.createElement('span');
|
||||
timeElement.className = 'output-timestamp';
|
||||
timeElement.textContent = this.formatTimestamp(new Date());
|
||||
line.appendChild(timeElement);
|
||||
}
|
||||
|
||||
// Add content
|
||||
const contentElement = document.createElement('span');
|
||||
contentElement.className = `output-content ${type}`;
|
||||
|
||||
// Process ANSI codes if present
|
||||
if (typeof content === 'string' && content.includes('\x1b[')) {
|
||||
contentElement.innerHTML = this.processAnsiCodes(content);
|
||||
} else {
|
||||
contentElement.textContent = content;
|
||||
}
|
||||
|
||||
line.appendChild(contentElement);
|
||||
entry.appendChild(line);
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process ANSI escape codes
|
||||
*/
|
||||
processAnsiCodes(text) {
|
||||
// Simple ANSI processing - convert color codes to HTML
|
||||
return (
|
||||
text
|
||||
.replace(/\x1b\[(\d+)m/g, (match, code) => {
|
||||
if (code === '0' || code === '00') {
|
||||
return '</span>'; // Reset
|
||||
}
|
||||
|
||||
const color = this.ansiColors[code];
|
||||
if (color) {
|
||||
return `<span style="color: ${color}">`;
|
||||
}
|
||||
|
||||
return '';
|
||||
})
|
||||
.replace(/\x1b\[[\d;]*m/g, '') + // Remove other ANSI codes
|
||||
'</span>'
|
||||
); // Ensure we close any open spans
|
||||
}
|
||||
|
||||
/**
|
||||
* Format timestamp
|
||||
*/
|
||||
formatTimestamp(date) {
|
||||
return date.toLocaleTimeString('en-US', {
|
||||
hour12: false,
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if timestamps should be shown
|
||||
*/
|
||||
shouldShowTimestamp() {
|
||||
const showTimestamps = localStorage.getItem('console_show_timestamps');
|
||||
return showTimestamps !== 'false';
|
||||
}
|
||||
|
||||
/**
|
||||
* Limit output lines
|
||||
*/
|
||||
limitOutputLines() {
|
||||
const entries = this.outputElement.querySelectorAll('.output-entry');
|
||||
|
||||
if (entries.length > this.maxOutputLines) {
|
||||
const excessCount = entries.length - this.maxOutputLines;
|
||||
for (let i = 0; i < excessCount; i++) {
|
||||
if (entries[i] && !entries[i].classList.contains('welcome-message')) {
|
||||
entries[i].remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scroll to bottom
|
||||
*/
|
||||
scrollToBottom(smooth = false) {
|
||||
if (this.shouldAutoScroll()) {
|
||||
if (smooth) {
|
||||
this.outputElement.scrollTo({
|
||||
top: this.outputElement.scrollHeight,
|
||||
behavior: 'smooth',
|
||||
});
|
||||
} else {
|
||||
this.outputElement.scrollTop = this.outputElement.scrollHeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if auto-scroll is enabled
|
||||
*/
|
||||
shouldAutoScroll() {
|
||||
const autoScroll = localStorage.getItem('console_auto_scroll');
|
||||
return autoScroll !== 'false';
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup input event handlers
|
||||
*/
|
||||
setupInputHandlers() {
|
||||
this.inputElement.addEventListener('keydown', (event) => {
|
||||
if (this.isLocked) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
|
||||
switch (event.key) {
|
||||
case 'Enter':
|
||||
event.preventDefault();
|
||||
this.handleEnter();
|
||||
break;
|
||||
|
||||
case 'ArrowUp':
|
||||
event.preventDefault();
|
||||
this.navigateHistory('up');
|
||||
break;
|
||||
|
||||
case 'ArrowDown':
|
||||
event.preventDefault();
|
||||
this.navigateHistory('down');
|
||||
break;
|
||||
|
||||
case 'Tab':
|
||||
event.preventDefault();
|
||||
this.handleTab();
|
||||
break;
|
||||
|
||||
case 'l':
|
||||
if (event.ctrlKey) {
|
||||
event.preventDefault();
|
||||
this.clear();
|
||||
}
|
||||
break;
|
||||
|
||||
case 'c':
|
||||
if (event.ctrlKey) {
|
||||
event.preventDefault();
|
||||
this.handleInterrupt();
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
this.inputElement.addEventListener('input', () => {
|
||||
if (!this.isLocked) {
|
||||
this.handleInput();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle Enter key
|
||||
*/
|
||||
handleEnter() {
|
||||
const command = this.getInput().trim();
|
||||
|
||||
if (command) {
|
||||
this.addToHistory(command);
|
||||
this.writeCommand(command);
|
||||
this.clearInput();
|
||||
|
||||
// Emit command event
|
||||
this.emit('command', command);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle Tab key (autocomplete)
|
||||
*/
|
||||
handleTab() {
|
||||
const input = this.getInput();
|
||||
const matches = this.commands.filter((cmd) => cmd.startsWith(input));
|
||||
|
||||
if (matches.length === 1) {
|
||||
this.setInput(matches[0] + ' ');
|
||||
} else if (matches.length > 1) {
|
||||
this.writeLine(`Available commands: ${matches.join(', ')}`, 'info');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle input changes
|
||||
*/
|
||||
handleInput() {
|
||||
// Could be used for live suggestions in the future
|
||||
this.emit('input_change', this.getInput());
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle Ctrl+C interrupt
|
||||
*/
|
||||
handleInterrupt() {
|
||||
this.writeLine('^C', 'warning');
|
||||
this.clearInput();
|
||||
this.emit('interrupt');
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup scroll behavior
|
||||
*/
|
||||
setupScrollBehavior() {
|
||||
let isUserScrolling = false;
|
||||
let scrollTimeout;
|
||||
let lastScrollTop = 0;
|
||||
|
||||
this.outputElement.addEventListener('scroll', () => {
|
||||
const currentScrollTop = this.outputElement.scrollTop;
|
||||
const maxScrollTop = this.outputElement.scrollHeight - this.outputElement.clientHeight;
|
||||
|
||||
// Check if user scrolled up (away from bottom)
|
||||
if (currentScrollTop < lastScrollTop && currentScrollTop < maxScrollTop - 10) {
|
||||
isUserScrolling = true;
|
||||
|
||||
// Show scroll indicator if not already visible
|
||||
this.showScrollIndicator();
|
||||
|
||||
clearTimeout(scrollTimeout);
|
||||
// Don't auto-resume scrolling for 3 seconds after user scrolls up
|
||||
scrollTimeout = setTimeout(() => {
|
||||
// Only resume auto-scroll if user is back near the bottom
|
||||
const newScrollTop = this.outputElement.scrollTop;
|
||||
const newMaxScrollTop = this.outputElement.scrollHeight - this.outputElement.clientHeight;
|
||||
|
||||
if (newScrollTop >= newMaxScrollTop - 50) {
|
||||
isUserScrolling = false;
|
||||
this.hideScrollIndicator();
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
// If user scrolled to bottom, resume auto-scrolling immediately
|
||||
else if (currentScrollTop >= maxScrollTop - 10) {
|
||||
isUserScrolling = false;
|
||||
this.hideScrollIndicator();
|
||||
clearTimeout(scrollTimeout);
|
||||
}
|
||||
|
||||
lastScrollTop = currentScrollTop;
|
||||
});
|
||||
|
||||
// Override shouldAutoScroll to check user scrolling
|
||||
const originalShouldAutoScroll = this.shouldAutoScroll;
|
||||
this.shouldAutoScroll = () => {
|
||||
return originalShouldAutoScroll.call(this) && !isUserScrolling;
|
||||
};
|
||||
|
||||
// Store reference for manual scroll control
|
||||
this.isUserScrolling = () => isUserScrolling;
|
||||
this.resumeAutoScroll = () => {
|
||||
isUserScrolling = false;
|
||||
this.hideScrollIndicator();
|
||||
this.scrollToBottom(true); // Smooth scroll to bottom
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Show scroll indicator
|
||||
*/
|
||||
showScrollIndicator() {
|
||||
let indicator = document.getElementById('scrollIndicator');
|
||||
|
||||
if (!indicator) {
|
||||
indicator = document.createElement('div');
|
||||
indicator.id = 'scrollIndicator';
|
||||
indicator.className = 'scroll-indicator';
|
||||
indicator.innerHTML = `
|
||||
<span class="scroll-text">Auto-scroll paused</span>
|
||||
<button class="scroll-resume-btn" onclick="window.claudeConsole.terminal.resumeAutoScroll()">
|
||||
↓ Resume
|
||||
</button>
|
||||
`;
|
||||
|
||||
// Position it relative to the console container
|
||||
const consoleContainer = this.outputElement.closest('.console-container');
|
||||
if (consoleContainer) {
|
||||
consoleContainer.appendChild(indicator);
|
||||
} else {
|
||||
document.body.appendChild(indicator);
|
||||
}
|
||||
}
|
||||
|
||||
indicator.style.display = 'flex';
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide scroll indicator
|
||||
*/
|
||||
hideScrollIndicator() {
|
||||
const indicator = document.getElementById('scrollIndicator');
|
||||
if (indicator) {
|
||||
indicator.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream text output with typing effect
|
||||
*/
|
||||
async streamText(text, delay = 10) {
|
||||
const entry = this.createOutputEntry('', 'output', true);
|
||||
this.outputElement.appendChild(entry);
|
||||
|
||||
const contentElement = entry.querySelector('.output-content');
|
||||
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
contentElement.textContent += text[i];
|
||||
this.scrollToBottom();
|
||||
|
||||
if (delay > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add event listener
|
||||
*/
|
||||
on(event, callback) {
|
||||
if (!this.eventListeners) {
|
||||
this.eventListeners = new Map();
|
||||
}
|
||||
|
||||
if (!this.eventListeners.has(event)) {
|
||||
this.eventListeners.set(event, []);
|
||||
}
|
||||
|
||||
this.eventListeners.get(event).push(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit event
|
||||
*/
|
||||
emit(event, data) {
|
||||
if (!this.eventListeners || !this.eventListeners.has(event)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.eventListeners.get(event).forEach((callback) => {
|
||||
try {
|
||||
callback(data);
|
||||
} catch (error) {
|
||||
console.error('Error in terminal event listener:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Set maximum output lines
|
||||
*/
|
||||
setMaxLines(maxLines) {
|
||||
this.maxOutputLines = Math.max(100, Math.min(10000, maxLines));
|
||||
this.limitOutputLines();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get terminal statistics
|
||||
*/
|
||||
getStats() {
|
||||
const entries = this.outputElement.querySelectorAll('.output-entry');
|
||||
|
||||
return {
|
||||
totalLines: entries.length,
|
||||
historySize: this.history.length,
|
||||
isLocked: this.isLocked,
|
||||
currentPrompt: this.currentPrompt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Export terminal history
|
||||
*/
|
||||
exportHistory() {
|
||||
const entries = Array.from(this.outputElement.querySelectorAll('.output-entry'));
|
||||
|
||||
return entries.map((entry) => {
|
||||
const timestamp = entry.querySelector('.output-timestamp')?.textContent || '';
|
||||
const content = entry.querySelector('.output-content')?.textContent || '';
|
||||
const type =
|
||||
entry
|
||||
.querySelector('.output-content')
|
||||
?.className.split(' ')
|
||||
.find((c) => c.startsWith('output-')) || '';
|
||||
|
||||
return { timestamp, content, type };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Import terminal history
|
||||
*/
|
||||
importHistory(history) {
|
||||
this.clear();
|
||||
|
||||
history.forEach(({ timestamp, content, type }) => {
|
||||
this.write(content, type.replace('output-', ''), false);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,480 +0,0 @@
|
||||
/**
|
||||
* WebSocket Client for Claude Code Console
|
||||
* Handles real-time communication with the backend MCP server
|
||||
*/
|
||||
|
||||
export class WebSocketClient {
|
||||
constructor() {
|
||||
this.ws = null;
|
||||
this.url = '';
|
||||
this.authToken = '';
|
||||
this.isConnected = false;
|
||||
this.isConnecting = false;
|
||||
this.reconnectAttempts = 0;
|
||||
this.maxReconnectAttempts = 5;
|
||||
this.reconnectDelay = 1000;
|
||||
this.messageQueue = [];
|
||||
this.requestHandlers = new Map();
|
||||
this.eventListeners = new Map();
|
||||
this.messageId = 1;
|
||||
|
||||
// Heartbeat configuration
|
||||
this.heartbeatInterval = 30000; // 30 seconds
|
||||
this.heartbeatTimer = null;
|
||||
this.lastPongReceived = Date.now();
|
||||
this.connectionTimeout = 10000; // 10 seconds
|
||||
|
||||
this.setupEventListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to WebSocket server
|
||||
*/
|
||||
async connect(url, authToken = '') {
|
||||
if (this.isConnecting || this.isConnected) {
|
||||
console.warn('Already connected or connecting');
|
||||
return;
|
||||
}
|
||||
|
||||
this.url = url;
|
||||
this.authToken = authToken;
|
||||
this.isConnecting = true;
|
||||
|
||||
try {
|
||||
await this.establishConnection();
|
||||
} catch (error) {
|
||||
this.isConnecting = false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Establish WebSocket connection
|
||||
*/
|
||||
async establishConnection() {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
// Create WebSocket connection
|
||||
this.ws = new WebSocket(this.url);
|
||||
|
||||
// Set up connection timeout
|
||||
const connectionTimer = setTimeout(() => {
|
||||
if (this.ws && this.ws.readyState !== WebSocket.OPEN) {
|
||||
this.ws.close();
|
||||
this.isConnecting = false;
|
||||
reject(new Error('Connection timeout'));
|
||||
}
|
||||
}, this.connectionTimeout);
|
||||
|
||||
this.ws.onopen = () => {
|
||||
clearTimeout(connectionTimer);
|
||||
this.isConnected = true;
|
||||
this.isConnecting = false;
|
||||
this.reconnectAttempts = 0;
|
||||
this.lastPongReceived = Date.now();
|
||||
|
||||
this.emit('connected');
|
||||
this.startHeartbeat();
|
||||
this.processMessageQueue();
|
||||
|
||||
console.log('WebSocket connected to:', this.url);
|
||||
resolve();
|
||||
};
|
||||
|
||||
this.ws.onclose = (event) => {
|
||||
clearTimeout(connectionTimer);
|
||||
this.handleDisconnection(event);
|
||||
};
|
||||
|
||||
this.ws.onerror = (error) => {
|
||||
clearTimeout(connectionTimer);
|
||||
console.error('WebSocket error:', error);
|
||||
this.isConnecting = false;
|
||||
this.emit('error', error);
|
||||
|
||||
if (!this.isConnected) {
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
this.ws.onmessage = (event) => {
|
||||
this.handleMessage(event);
|
||||
};
|
||||
} catch (error) {
|
||||
this.isConnecting = false;
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect from WebSocket server
|
||||
*/
|
||||
disconnect() {
|
||||
if (this.ws) {
|
||||
this.stopHeartbeat();
|
||||
this.ws.close(1000, 'User initiated disconnect');
|
||||
this.ws = null;
|
||||
}
|
||||
|
||||
this.isConnected = false;
|
||||
this.isConnecting = false;
|
||||
this.reconnectAttempts = 0;
|
||||
this.messageQueue = [];
|
||||
this.requestHandlers.clear();
|
||||
|
||||
this.emit('disconnected');
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a request and wait for response
|
||||
*/
|
||||
async sendRequest(method, params = {}) {
|
||||
const id = this.generateMessageId();
|
||||
const request = {
|
||||
jsonrpc: '2.0',
|
||||
id,
|
||||
method,
|
||||
params,
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// Store request handler
|
||||
this.requestHandlers.set(id, { resolve, reject });
|
||||
|
||||
// Send request
|
||||
this.sendMessage(request);
|
||||
|
||||
// Set timeout for request
|
||||
setTimeout(() => {
|
||||
if (this.requestHandlers.has(id)) {
|
||||
this.requestHandlers.delete(id);
|
||||
reject(new Error(`Request timeout for method: ${method}`));
|
||||
}
|
||||
}, 30000); // 30 second timeout
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a notification (no response expected)
|
||||
*/
|
||||
sendNotification(method, params = {}) {
|
||||
const notification = {
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params,
|
||||
};
|
||||
|
||||
this.sendMessage(notification);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send raw message
|
||||
*/
|
||||
sendMessage(message) {
|
||||
if (!this.isConnected) {
|
||||
// Queue message for later
|
||||
this.messageQueue.push(message);
|
||||
this.emit('message_queued', message);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const messageStr = JSON.stringify(message);
|
||||
this.ws.send(messageStr);
|
||||
this.emit('message_sent', message);
|
||||
} catch (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
this.emit('send_error', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle incoming messages
|
||||
*/
|
||||
handleMessage(event) {
|
||||
try {
|
||||
const message = JSON.parse(event.data);
|
||||
|
||||
// Handle pong response
|
||||
if (message.method === 'pong') {
|
||||
this.lastPongReceived = Date.now();
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle responses to requests
|
||||
if (message.id !== undefined && this.requestHandlers.has(message.id)) {
|
||||
const handler = this.requestHandlers.get(message.id);
|
||||
this.requestHandlers.delete(message.id);
|
||||
|
||||
if (message.error) {
|
||||
handler.reject(new Error(message.error.message || 'Request failed'));
|
||||
} else {
|
||||
handler.resolve(message.result);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle notifications and other messages
|
||||
if (message.method) {
|
||||
this.emit('notification', message);
|
||||
this.emit(`notification_${message.method}`, message.params);
|
||||
}
|
||||
|
||||
this.emit('message_received', message);
|
||||
} catch (error) {
|
||||
console.error('Failed to parse WebSocket message:', error);
|
||||
this.emit('parse_error', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle disconnection
|
||||
*/
|
||||
handleDisconnection(event) {
|
||||
const wasConnected = this.isConnected;
|
||||
this.isConnected = false;
|
||||
this.isConnecting = false;
|
||||
this.stopHeartbeat();
|
||||
|
||||
console.log('WebSocket disconnected:', event.code, event.reason);
|
||||
|
||||
if (wasConnected) {
|
||||
this.emit('disconnected', { code: event.code, reason: event.reason });
|
||||
|
||||
// Attempt reconnection if not a clean close
|
||||
if (event.code !== 1000 && this.reconnectAttempts < this.maxReconnectAttempts) {
|
||||
this.attemptReconnection();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to reconnect
|
||||
*/
|
||||
async attemptReconnection() {
|
||||
this.reconnectAttempts++;
|
||||
const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
|
||||
|
||||
console.log(
|
||||
`Attempting reconnection ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms`,
|
||||
);
|
||||
this.emit('reconnecting', { attempt: this.reconnectAttempts, delay });
|
||||
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
await this.establishConnection();
|
||||
} catch (error) {
|
||||
console.error('Reconnection failed:', error);
|
||||
|
||||
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
||||
this.emit('reconnection_failed');
|
||||
} else {
|
||||
this.attemptReconnection();
|
||||
}
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start heartbeat mechanism
|
||||
*/
|
||||
startHeartbeat() {
|
||||
this.stopHeartbeat();
|
||||
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
if (this.isConnected) {
|
||||
// Check if we received a recent pong
|
||||
const timeSinceLastPong = Date.now() - this.lastPongReceived;
|
||||
|
||||
if (timeSinceLastPong > this.heartbeatInterval * 2) {
|
||||
console.warn('Heartbeat timeout - connection may be dead');
|
||||
this.ws.close(1006, 'Heartbeat timeout');
|
||||
return;
|
||||
}
|
||||
|
||||
// Send ping
|
||||
this.sendNotification('ping', { timestamp: Date.now() });
|
||||
}
|
||||
}, this.heartbeatInterval);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop heartbeat mechanism
|
||||
*/
|
||||
stopHeartbeat() {
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process queued messages
|
||||
*/
|
||||
processMessageQueue() {
|
||||
while (this.messageQueue.length > 0 && this.isConnected) {
|
||||
const message = this.messageQueue.shift();
|
||||
this.sendMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate unique message ID
|
||||
*/
|
||||
generateMessageId() {
|
||||
return this.messageId++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up internal event listeners
|
||||
*/
|
||||
setupEventListeners() {
|
||||
// Handle page visibility changes
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden) {
|
||||
// Page is hidden - reduce heartbeat frequency
|
||||
this.heartbeatInterval = 60000; // 1 minute
|
||||
} else {
|
||||
// Page is visible - restore normal heartbeat
|
||||
this.heartbeatInterval = 30000; // 30 seconds
|
||||
if (this.isConnected) {
|
||||
this.startHeartbeat();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Handle page unload
|
||||
window.addEventListener('beforeunload', () => {
|
||||
if (this.isConnected) {
|
||||
this.disconnect();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add event listener
|
||||
*/
|
||||
on(event, callback) {
|
||||
if (!this.eventListeners.has(event)) {
|
||||
this.eventListeners.set(event, []);
|
||||
}
|
||||
this.eventListeners.get(event).push(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove event listener
|
||||
*/
|
||||
off(event, callback) {
|
||||
if (this.eventListeners.has(event)) {
|
||||
const listeners = this.eventListeners.get(event);
|
||||
const index = listeners.indexOf(callback);
|
||||
if (index > -1) {
|
||||
listeners.splice(index, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit event
|
||||
*/
|
||||
emit(event, data = null) {
|
||||
if (this.eventListeners.has(event)) {
|
||||
this.eventListeners.get(event).forEach((callback) => {
|
||||
try {
|
||||
callback(data);
|
||||
} catch (error) {
|
||||
console.error('Error in event listener:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get connection status
|
||||
*/
|
||||
getStatus() {
|
||||
return {
|
||||
connected: this.isConnected,
|
||||
connecting: this.isConnecting,
|
||||
url: this.url,
|
||||
reconnectAttempts: this.reconnectAttempts,
|
||||
queuedMessages: this.messageQueue.length,
|
||||
pendingRequests: this.requestHandlers.size,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize Claude Code session
|
||||
*/
|
||||
async initializeSession(clientInfo = {}) {
|
||||
const params = {
|
||||
protocolVersion: { major: 2024, minor: 11, patch: 5 },
|
||||
clientInfo: {
|
||||
name: 'Claude Flow v2',
|
||||
version: '2.0.0',
|
||||
...clientInfo,
|
||||
},
|
||||
capabilities: {
|
||||
logging: { level: 'info' },
|
||||
tools: { listChanged: true },
|
||||
resources: { listChanged: false, subscribe: false },
|
||||
prompts: { listChanged: false },
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const result = await this.sendRequest('initialize', params);
|
||||
this.emit('session_initialized', result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.emit('session_error', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute Claude Flow command
|
||||
*/
|
||||
async executeCommand(command, args = {}) {
|
||||
try {
|
||||
const result = await this.sendRequest('tools/call', {
|
||||
name: 'claude-flow/execute',
|
||||
arguments: { command, args },
|
||||
});
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('Command execution failed:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get available tools
|
||||
*/
|
||||
async getAvailableTools() {
|
||||
try {
|
||||
const result = await this.sendRequest('tools/list');
|
||||
// The server returns { tools: [...] }, so we need to extract the tools array
|
||||
return result && result.tools ? result.tools : [];
|
||||
} catch (error) {
|
||||
console.error('Failed to get tools:', error);
|
||||
return []; // Return empty array on error instead of throwing
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get server health status
|
||||
*/
|
||||
async getHealthStatus() {
|
||||
try {
|
||||
return await this.sendRequest('tools/call', {
|
||||
name: 'system/health',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to get health status:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,252 +0,0 @@
|
||||
# Neural Networks UI Implementation - Complete Demo
|
||||
|
||||
## 🧠 Neural Developer Agent - Implementation Complete
|
||||
|
||||
### Overview
|
||||
|
||||
Successfully implemented comprehensive Neural Networks interface for Claude Flow Web UI with all 15 missing neural processing tools.
|
||||
|
||||
### ✅ Implementation Completed
|
||||
|
||||
#### 📁 Files Created
|
||||
|
||||
1. **`neural-networks.js`** - Main neural panel implementation
|
||||
2. **`neural-networks-extended.js`** - Complete tool implementations
|
||||
3. **`neural-networks.css`** - Comprehensive styling
|
||||
4. **Updated `console.js`** - Integration with main console
|
||||
5. **Updated `index.html`** - CSS import
|
||||
|
||||
#### 🛠️ Neural Tools Implemented (15/15)
|
||||
|
||||
##### Core Functions
|
||||
|
||||
- ✅ **neural_status** - Check neural system status
|
||||
- ✅ **neural_train** - Train patterns with WASM acceleration
|
||||
- ✅ **neural_predict** - Make predictions with trained models
|
||||
- ✅ **neural_patterns** - Analyze neural patterns
|
||||
|
||||
##### Model Management
|
||||
|
||||
- ✅ **model_save** - Save trained models to disk
|
||||
- ✅ **model_load** - Load saved models from disk
|
||||
|
||||
##### Pattern Recognition & Analysis
|
||||
|
||||
- ✅ **pattern_recognize** - Recognize specific patterns in data
|
||||
- ✅ **cognitive_analyze** - Analyze cognitive behavior patterns
|
||||
|
||||
##### Advanced Neural Features
|
||||
|
||||
- ✅ **learning_adapt** - Implement adaptive learning algorithms
|
||||
- ✅ **neural_compress** - Compress neural models for efficiency
|
||||
- ✅ **ensemble_create** - Create ensemble models from multiple networks
|
||||
- ✅ **transfer_learn** - Transfer learning between domains
|
||||
- ✅ **neural_explain** - Model explainability and interpretability
|
||||
|
||||
##### Performance & Optimization
|
||||
|
||||
- ✅ **wasm_optimize** - WASM optimization for neural processing
|
||||
- ✅ **inference_run** - High-performance neural inference execution
|
||||
|
||||
### 🎯 User Interface Features
|
||||
|
||||
#### Tabbed Interface
|
||||
|
||||
1. **Tools Tab** - Grid view of all 15 neural tools organized by category
|
||||
2. **Training Tab** - Real-time training progress with live metrics
|
||||
3. **Models Tab** - Model management with save/load/performance metrics
|
||||
4. **Patterns Tab** - Pattern recognition and cognitive analysis
|
||||
5. **Performance Tab** - System metrics and optimization controls
|
||||
|
||||
#### Real-time Features
|
||||
|
||||
- ⚡ Live training progress with progress bars and metrics
|
||||
- 📊 Real-time performance monitoring
|
||||
- 🔄 Auto-updating status indicators
|
||||
- 📈 Interactive pattern visualizations
|
||||
- 💾 Persistent model registry
|
||||
|
||||
#### Tool Categories
|
||||
|
||||
- **Core Functions** (4 tools) - Essential neural operations
|
||||
- **Training** (1 tool) - Neural network training
|
||||
- **Inference** (2 tools) - Prediction and inference
|
||||
- **Analysis** (3 tools) - Pattern and cognitive analysis
|
||||
- **Management** (2 tools) - Model persistence
|
||||
- **Advanced** (3 tools) - Ensemble, transfer learning, adaptive learning
|
||||
- **Optimization** (2 tools) - WASM optimization and compression
|
||||
|
||||
### 🚀 Technical Implementation
|
||||
|
||||
#### Architecture
|
||||
|
||||
- **Modular Design** - Separate panel, extended functionality, and styling
|
||||
- **Event-Driven** - Uses EventEmitter for component communication
|
||||
- **WebSocket Integration** - Real-time communication with MCP tools
|
||||
- **Responsive UI** - Works on desktop and mobile devices
|
||||
|
||||
#### Key Classes
|
||||
|
||||
```javascript
|
||||
// Main panel with UI management
|
||||
class NeuralNetworksPanel extends EventEmitter
|
||||
|
||||
// Extended functionality with tool implementations
|
||||
class NeuralNetworksExtended
|
||||
|
||||
// Integration points
|
||||
window.neuralPanel = { panel, extended }
|
||||
```
|
||||
|
||||
#### MCP Tool Integration
|
||||
|
||||
All tools call corresponding `mcp__claude-flow__` tools:
|
||||
|
||||
```javascript
|
||||
await this.callMCPTool('neural_status', params);
|
||||
await this.callMCPTool('neural_train', { pattern_type, training_data, epochs });
|
||||
await this.callMCPTool('neural_predict', { modelId, input });
|
||||
// ... etc for all 15 tools
|
||||
```
|
||||
|
||||
### 🎨 UI/UX Features
|
||||
|
||||
#### Visual Design
|
||||
|
||||
- **Glassmorphism** - Modern translucent panels with backdrop blur
|
||||
- **Smooth Animations** - Slide-in panels, fade transitions, progress animations
|
||||
- **Dark/Light Themes** - Automatic theme adaptation
|
||||
- **Responsive Grid** - Adaptive tool card layouts
|
||||
- **Status Indicators** - Real-time status with color-coded indicators
|
||||
|
||||
#### Interactive Elements
|
||||
|
||||
- **Tool Cards** - Hover effects with action buttons (Execute/Configure)
|
||||
- **Progress Visualization** - Animated progress bars for training
|
||||
- **Model Cards** - Interactive model management interface
|
||||
- **Tab Navigation** - Smooth tab switching with data loading
|
||||
- **Performance Metrics** - Real-time system metrics display
|
||||
|
||||
### 📊 Testing Results
|
||||
|
||||
#### MCP Tool Testing
|
||||
|
||||
```bash
|
||||
✅ neural_status - SUCCESS (tool executed successfully)
|
||||
✅ neural_train - SUCCESS (model_coordination_1751839334863 created, 69.1% accuracy)
|
||||
✅ neural_patterns - SUCCESS (coordination_analysis completed)
|
||||
```
|
||||
|
||||
#### UI Integration Testing
|
||||
|
||||
- ✅ Panel loads without errors
|
||||
- ✅ All 15 tools display correctly in categorized grid
|
||||
- ✅ Tab navigation works smoothly
|
||||
- ✅ WebSocket integration functional
|
||||
- ✅ Real-time updates working
|
||||
- ✅ Responsive design verified
|
||||
|
||||
### 🔧 Usage Instructions
|
||||
|
||||
#### Accessing Neural Networks Panel
|
||||
|
||||
1. Open Claude Flow Web UI console
|
||||
2. Click **🧠 Neural** button in header
|
||||
3. Panel slides in from right side
|
||||
4. Navigate between tabs for different functionalities
|
||||
|
||||
#### Training a Neural Network
|
||||
|
||||
1. Go to **Training** tab
|
||||
2. Select training type (coordination/optimization/prediction)
|
||||
3. Enter training data
|
||||
4. Set epochs and learning rate
|
||||
5. Click **🚀 Start Training**
|
||||
6. Watch real-time progress
|
||||
|
||||
#### Managing Models
|
||||
|
||||
1. Go to **Models** tab
|
||||
2. View loaded models with performance metrics
|
||||
3. Use **📂 Load Model** or **➕ Create Model**
|
||||
4. Click model actions: Predict, Explain, Save
|
||||
|
||||
#### Pattern Analysis
|
||||
|
||||
1. Go to **Patterns** tab
|
||||
2. Click **🔍 Analyze Patterns** for pattern discovery
|
||||
3. Use **🎯 Recognize Patterns** for specific pattern matching
|
||||
4. Enter behavior data for cognitive analysis
|
||||
|
||||
#### Performance Monitoring
|
||||
|
||||
1. Go to **Performance** tab
|
||||
2. View real-time neural processing metrics
|
||||
3. Use optimization actions:
|
||||
- **⚡ Optimize WASM** for speed improvements
|
||||
- **🗜️ Compress Models** for size reduction
|
||||
- **📊 Run Benchmark** for performance testing
|
||||
|
||||
### 🔄 Coordination with Swarm
|
||||
|
||||
#### Memory Storage
|
||||
|
||||
```javascript
|
||||
// Stored implementation progress in swarm memory
|
||||
mcp__claude -
|
||||
flow__memory_usage({
|
||||
action: 'store',
|
||||
key: 'neural_dev/implementation_complete',
|
||||
value: 'Neural Networks UI Implementation COMPLETED...',
|
||||
});
|
||||
```
|
||||
|
||||
#### Agent Coordination
|
||||
|
||||
- **UI_Architect**: Coordinated on responsive layout and component structure
|
||||
- **MCP_Integrator**: Integrated all 15 MCP claude-flow neural tools
|
||||
- **Analytics_Developer**: Shared real-time metrics and visualization components
|
||||
|
||||
### 📈 Performance Metrics
|
||||
|
||||
#### Implementation Stats
|
||||
|
||||
- **15/15 Tools** - 100% neural tool coverage
|
||||
- **5 UI Tabs** - Complete interface organization
|
||||
- **3 Core Files** - Modular, maintainable codebase
|
||||
- **Real-time Updates** - Live training and performance monitoring
|
||||
- **Responsive Design** - Desktop and mobile support
|
||||
|
||||
#### Neural Processing Capabilities
|
||||
|
||||
- **Pattern Training** - WASM-accelerated neural training
|
||||
- **Model Management** - Save/load/compress neural models
|
||||
- **Real-time Inference** - High-performance prediction execution
|
||||
- **Cognitive Analysis** - Behavior pattern recognition
|
||||
- **Transfer Learning** - Cross-domain knowledge transfer
|
||||
- **Ensemble Models** - Multi-model combination strategies
|
||||
- **Explainable AI** - Model interpretability features
|
||||
|
||||
### 🎉 Deliverables Complete
|
||||
|
||||
✅ **Neural Networks View** - Complete tabbed interface
|
||||
✅ **15 Tool Interfaces** - All neural tools implemented
|
||||
✅ **Training Progress Visualization** - Real-time progress tracking
|
||||
✅ **Model Management Interface** - Full model lifecycle support
|
||||
✅ **Pattern Visualization Components** - Interactive pattern analysis
|
||||
✅ **Performance Metrics Display** - Comprehensive system monitoring
|
||||
|
||||
### 🚀 Next Steps
|
||||
|
||||
The Neural Networks interface is fully functional and ready for:
|
||||
|
||||
1. **Production Use** - All tools working with MCP integration
|
||||
2. **User Testing** - Interface ready for end-user feedback
|
||||
3. **Feature Extensions** - Easy to add new neural tools
|
||||
4. **Performance Optimization** - WASM optimization ready to deploy
|
||||
|
||||
---
|
||||
|
||||
**Neural_Developer Agent - Mission Accomplished! 🧠✨**
|
||||
|
||||
All 15 neural processing tools successfully implemented with comprehensive Web UI interface, real-time monitoring, and full MCP integration. The neural networks interface provides a complete solution for neural processing in Claude Flow v2.0.0.
|
||||
@@ -1,938 +0,0 @@
|
||||
/**
|
||||
* Analysis & Monitoring Tools Styles
|
||||
* Agent 2 - Analysis & Monitoring Tools Developer
|
||||
*
|
||||
* Features:
|
||||
* - Responsive dashboard layout
|
||||
* - 4 main tabs: Metrics, Reports, Analysis, Health
|
||||
* - Real-time chart styling
|
||||
* - Interactive tool panels
|
||||
* - Export functionality styles
|
||||
*/
|
||||
|
||||
/* Main Analysis Container */
|
||||
.analysis-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
background: #f8fafc;
|
||||
font-family:
|
||||
'Inter',
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
'Segoe UI',
|
||||
Roboto,
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
/* Header Section */
|
||||
.analysis-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1rem 2rem;
|
||||
background: white;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.analysis-title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
color: #1f2937;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.connection-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.connection-status.connected {
|
||||
background: #dcfce7;
|
||||
color: #166534;
|
||||
}
|
||||
|
||||
.connection-status.connected::before {
|
||||
content: '●';
|
||||
color: #10b981;
|
||||
}
|
||||
|
||||
.connection-status.disconnected {
|
||||
background: #fef2f2;
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.connection-status.disconnected::before {
|
||||
content: '●';
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.connection-status.error {
|
||||
background: #fff7ed;
|
||||
color: #ea580c;
|
||||
}
|
||||
|
||||
.connection-status.error::before {
|
||||
content: '●';
|
||||
color: #f97316;
|
||||
}
|
||||
|
||||
/* Tab Navigation */
|
||||
.analysis-tabs {
|
||||
display: flex;
|
||||
background: white;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
padding: 0 2rem;
|
||||
}
|
||||
|
||||
.analysis-tab {
|
||||
padding: 1rem 1.5rem;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
background: none;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: #6b7280;
|
||||
border-bottom: 2px solid transparent;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.analysis-tab:hover {
|
||||
color: #3b82f6;
|
||||
background: #f9fafb;
|
||||
}
|
||||
|
||||
.analysis-tab.active {
|
||||
color: #3b82f6;
|
||||
border-bottom-color: #3b82f6;
|
||||
}
|
||||
|
||||
/* Content Area */
|
||||
.analysis-content {
|
||||
flex: 1;
|
||||
padding: 2rem;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.analysis-panel {
|
||||
display: none;
|
||||
animation: fadeIn 0.3s ease-in-out;
|
||||
}
|
||||
|
||||
.analysis-panel.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Metrics Panel */
|
||||
.metrics-panel {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.metric-section {
|
||||
background: white;
|
||||
border-radius: 0.75rem;
|
||||
padding: 1.5rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
border: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.metric-section h3 {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: #1f2937;
|
||||
margin: 0 0 1rem 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.metric-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.metric-card {
|
||||
text-align: center;
|
||||
padding: 1rem;
|
||||
background: #f9fafb;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.metric-label {
|
||||
font-size: 0.75rem;
|
||||
color: #6b7280;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.metric-value {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.metric-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.75rem 0;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
}
|
||||
|
||||
.metric-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.metric-item label {
|
||||
font-size: 0.875rem;
|
||||
color: #6b7280;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.metric-item span {
|
||||
font-size: 0.875rem;
|
||||
color: #1f2937;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* Charts */
|
||||
.chart-container {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
background: white;
|
||||
border-radius: 0.75rem;
|
||||
padding: 1.5rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
border: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.chart-title {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: #1f2937;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
/* Health Status */
|
||||
.health-overview {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.health-score {
|
||||
font-size: 3rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 0.5rem;
|
||||
border-radius: 50%;
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.health-excellent {
|
||||
background: #10b981;
|
||||
}
|
||||
|
||||
.health-good {
|
||||
background: #3b82f6;
|
||||
}
|
||||
|
||||
.health-warning {
|
||||
background: #f59e0b;
|
||||
}
|
||||
|
||||
.health-critical {
|
||||
background: #ef4444;
|
||||
}
|
||||
|
||||
.health-label {
|
||||
font-size: 0.875rem;
|
||||
color: #6b7280;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.health-components {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.health-component {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1rem;
|
||||
background: #f9fafb;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.component-name {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.component-value {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 0.25rem;
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* Tool Buttons */
|
||||
.tool-section {
|
||||
background: white;
|
||||
border-radius: 0.75rem;
|
||||
padding: 1.5rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
border: 1px solid #e5e7eb;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.tool-section h3 {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: #1f2937;
|
||||
margin: 0 0 1rem 0;
|
||||
}
|
||||
|
||||
.tool-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.tool-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem 1rem;
|
||||
background: #3b82f6;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.tool-btn:hover {
|
||||
background: #2563eb;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.tool-btn:disabled {
|
||||
background: #9ca3af;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.tool-btn.loading {
|
||||
background: #9ca3af;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.tool-btn.loading::after {
|
||||
content: '';
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border: 2px solid #ffffff;
|
||||
border-top: 2px solid transparent;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
/* Export Buttons */
|
||||
.export-section {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.export-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 1rem;
|
||||
background: #10b981;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.export-btn:hover {
|
||||
background: #059669;
|
||||
}
|
||||
|
||||
.refresh-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 1rem;
|
||||
background: #6b7280;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.refresh-btn:hover {
|
||||
background: #4b5563;
|
||||
}
|
||||
|
||||
/* Output Sections */
|
||||
.output-section {
|
||||
background: white;
|
||||
border-radius: 0.75rem;
|
||||
padding: 1.5rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
border: 1px solid #e5e7eb;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.output-section h4 {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: #1f2937;
|
||||
margin: 0 0 1rem 0;
|
||||
}
|
||||
|
||||
.output-content {
|
||||
background: #f9fafb;
|
||||
border-radius: 0.5rem;
|
||||
padding: 1rem;
|
||||
border: 1px solid #e5e7eb;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
min-height: 100px;
|
||||
white-space: pre-wrap;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
/* Reports */
|
||||
.report-summary {
|
||||
background: #f0f9ff;
|
||||
border: 1px solid #bae6fd;
|
||||
border-radius: 0.5rem;
|
||||
padding: 1rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.report-summary h3 {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: #0c4a6e;
|
||||
margin: 0 0 0.5rem 0;
|
||||
}
|
||||
|
||||
.report-summary p {
|
||||
color: #0369a1;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.report-recommendations {
|
||||
background: #f0fdf4;
|
||||
border: 1px solid #bbf7d0;
|
||||
border-radius: 0.5rem;
|
||||
padding: 1rem;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.report-recommendations h4 {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: #166534;
|
||||
margin: 0 0 0.5rem 0;
|
||||
}
|
||||
|
||||
.report-recommendations ul {
|
||||
margin: 0;
|
||||
padding-left: 1.5rem;
|
||||
color: #15803d;
|
||||
}
|
||||
|
||||
.report-recommendations li {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
/* Analysis Results */
|
||||
.analysis-results {
|
||||
background: white;
|
||||
border-radius: 0.75rem;
|
||||
padding: 1.5rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
border: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.bottleneck-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.bottleneck-item {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto auto;
|
||||
gap: 1rem;
|
||||
padding: 1rem;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid #e5e7eb;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.bottleneck-item.severity-low {
|
||||
background: #f0fdf4;
|
||||
border-color: #bbf7d0;
|
||||
}
|
||||
|
||||
.bottleneck-item.severity-medium {
|
||||
background: #fff7ed;
|
||||
border-color: #fed7aa;
|
||||
}
|
||||
|
||||
.bottleneck-item.severity-high {
|
||||
background: #fef2f2;
|
||||
border-color: #fecaca;
|
||||
}
|
||||
|
||||
.bottleneck-component {
|
||||
font-weight: 600;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.bottleneck-severity {
|
||||
padding: 0.25rem 0.75rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.severity-low .bottleneck-severity {
|
||||
background: #10b981;
|
||||
}
|
||||
|
||||
.severity-medium .bottleneck-severity {
|
||||
background: #f59e0b;
|
||||
}
|
||||
|
||||
.severity-high .bottleneck-severity {
|
||||
background: #ef4444;
|
||||
}
|
||||
|
||||
.bottleneck-impact {
|
||||
font-size: 0.875rem;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
/* Usage Stats */
|
||||
.usage-overview {
|
||||
background: white;
|
||||
border-radius: 0.75rem;
|
||||
padding: 1.5rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
border: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.usage-stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.usage-stat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 1rem;
|
||||
background: #f9fafb;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.usage-stat label {
|
||||
font-size: 0.75rem;
|
||||
color: #6b7280;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.usage-stat span {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
/* Alerts */
|
||||
.alerts-container {
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.alert {
|
||||
padding: 1rem;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid;
|
||||
position: relative;
|
||||
animation: slideIn 0.3s ease-out;
|
||||
}
|
||||
|
||||
.alert-info {
|
||||
background: #f0f9ff;
|
||||
border-color: #bae6fd;
|
||||
color: #0c4a6e;
|
||||
}
|
||||
|
||||
.alert-warning {
|
||||
background: #fff7ed;
|
||||
border-color: #fed7aa;
|
||||
color: #9a3412;
|
||||
}
|
||||
|
||||
.alert-critical {
|
||||
background: #fef2f2;
|
||||
border-color: #fecaca;
|
||||
color: #991b1b;
|
||||
}
|
||||
|
||||
.alert-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.alert-title {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.alert-timestamp {
|
||||
font-size: 0.75rem;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
.alert-message {
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.alert-dismiss {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 1.25rem;
|
||||
cursor: pointer;
|
||||
color: currentColor;
|
||||
opacity: 0.5;
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
|
||||
.alert-dismiss:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Error Messages */
|
||||
.error-message {
|
||||
position: fixed;
|
||||
top: 1rem;
|
||||
right: 1rem;
|
||||
background: #fef2f2;
|
||||
border: 1px solid #fecaca;
|
||||
color: #991b1b;
|
||||
padding: 1rem;
|
||||
border-radius: 0.5rem;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
z-index: 1000;
|
||||
animation: slideIn 0.3s ease-out;
|
||||
}
|
||||
|
||||
/* Responsive Design */
|
||||
@media (max-width: 768px) {
|
||||
.analysis-header {
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.analysis-tabs {
|
||||
padding: 0 1rem;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.analysis-content {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.metrics-panel {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.tool-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.metric-grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
|
||||
.health-components {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.export-section {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.bottleneck-item {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.usage-stats {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.analysis-title {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.analysis-tab {
|
||||
padding: 0.75rem 1rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.metric-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.usage-stats {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.chart-container {
|
||||
height: 250px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Loading States */
|
||||
.loading-spinner {
|
||||
display: inline-block;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border: 3px solid #f3f4f6;
|
||||
border-top: 3px solid #3b82f6;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
.loading-overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(255, 255, 255, 0.8);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 0.75rem;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
/* Hover Effects */
|
||||
.metric-card:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.chart-wrapper:hover {
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
/* Focus States */
|
||||
.tool-btn:focus,
|
||||
.export-btn:focus,
|
||||
.refresh-btn:focus {
|
||||
outline: 2px solid #3b82f6;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.analysis-tab:focus {
|
||||
outline: 2px solid #3b82f6;
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
/* Dark Mode Support */
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.analysis-container {
|
||||
background: #111827;
|
||||
color: #f9fafb;
|
||||
}
|
||||
|
||||
.analysis-header {
|
||||
background: #1f2937;
|
||||
border-bottom-color: #374151;
|
||||
}
|
||||
|
||||
.analysis-title {
|
||||
color: #f9fafb;
|
||||
}
|
||||
|
||||
.analysis-tabs {
|
||||
background: #1f2937;
|
||||
border-bottom-color: #374151;
|
||||
}
|
||||
|
||||
.analysis-tab {
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
.analysis-tab:hover {
|
||||
color: #60a5fa;
|
||||
background: #374151;
|
||||
}
|
||||
|
||||
.analysis-tab.active {
|
||||
color: #60a5fa;
|
||||
border-bottom-color: #60a5fa;
|
||||
}
|
||||
|
||||
.metric-section,
|
||||
.tool-section,
|
||||
.chart-wrapper,
|
||||
.output-section,
|
||||
.analysis-results,
|
||||
.usage-overview {
|
||||
background: #1f2937;
|
||||
border-color: #374151;
|
||||
}
|
||||
|
||||
.metric-card,
|
||||
.health-component,
|
||||
.usage-stat {
|
||||
background: #374151;
|
||||
border-color: #4b5563;
|
||||
}
|
||||
|
||||
.metric-value,
|
||||
.metric-item span,
|
||||
.component-name,
|
||||
.usage-stat span {
|
||||
color: #f9fafb;
|
||||
}
|
||||
|
||||
.metric-label,
|
||||
.metric-item label,
|
||||
.usage-stat label {
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
.output-content {
|
||||
background: #374151;
|
||||
border-color: #4b5563;
|
||||
color: #f9fafb;
|
||||
}
|
||||
}
|
||||
|
||||
/* Print Styles */
|
||||
@media print {
|
||||
.analysis-container {
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.analysis-tabs,
|
||||
.export-section,
|
||||
.tool-section {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.analysis-content {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.analysis-panel {
|
||||
display: block !important;
|
||||
}
|
||||
|
||||
.chart-container {
|
||||
height: 400px;
|
||||
}
|
||||
}
|
||||
@@ -1,620 +0,0 @@
|
||||
/* Console CSS - Terminal-like web interface for Claude Code */
|
||||
|
||||
:root {
|
||||
/* Dark theme colors */
|
||||
--bg-primary: #0d1117;
|
||||
--bg-secondary: #161b22;
|
||||
--bg-tertiary: #21262d;
|
||||
--text-primary: #c9d1d9;
|
||||
--text-secondary: #8b949e;
|
||||
--text-accent: #58a6ff;
|
||||
--text-success: #3fb950;
|
||||
--text-warning: #d29922;
|
||||
--text-error: #f85149;
|
||||
--border-primary: #30363d;
|
||||
--border-secondary: #21262d;
|
||||
--accent-primary: #1f6feb;
|
||||
--accent-hover: #388bfd;
|
||||
--console-bg: #0d1117;
|
||||
--console-text: #c9d1d9;
|
||||
--console-prompt: #58a6ff;
|
||||
--console-cursor: #c9d1d9;
|
||||
|
||||
/* Typography */
|
||||
--font-mono: 'JetBrains Mono', 'Consolas', 'Monaco', 'Courier New', monospace;
|
||||
--font-size-base: 14px;
|
||||
--font-size-small: 12px;
|
||||
--line-height: 1.4;
|
||||
|
||||
/* Spacing */
|
||||
--spacing-xs: 4px;
|
||||
--spacing-sm: 8px;
|
||||
--spacing-md: 16px;
|
||||
--spacing-lg: 24px;
|
||||
--spacing-xl: 32px;
|
||||
|
||||
/* Animation */
|
||||
--transition-fast: 150ms ease;
|
||||
--transition-medium: 250ms ease;
|
||||
--transition-slow: 350ms ease;
|
||||
}
|
||||
|
||||
/* Light theme override */
|
||||
[data-theme='light'] {
|
||||
--bg-primary: #ffffff;
|
||||
--bg-secondary: #f6f8fa;
|
||||
--bg-tertiary: #eaeef2;
|
||||
--text-primary: #24292f;
|
||||
--text-secondary: #656d76;
|
||||
--text-accent: #0969da;
|
||||
--text-success: #1a7f37;
|
||||
--text-warning: #9a6700;
|
||||
--text-error: #d1242f;
|
||||
--border-primary: #d0d7de;
|
||||
--border-secondary: #eaeef2;
|
||||
--console-bg: #ffffff;
|
||||
--console-text: #24292f;
|
||||
--console-prompt: #0969da;
|
||||
--console-cursor: #24292f;
|
||||
}
|
||||
|
||||
/* Classic terminal theme */
|
||||
[data-theme='classic'] {
|
||||
--bg-primary: #000000;
|
||||
--bg-secondary: #1a1a1a;
|
||||
--bg-tertiary: #2d2d2d;
|
||||
--text-primary: #00ff00;
|
||||
--text-secondary: #008000;
|
||||
--text-accent: #00ff00;
|
||||
--text-success: #00ff00;
|
||||
--text-warning: #ffff00;
|
||||
--text-error: #ff0000;
|
||||
--border-primary: #333333;
|
||||
--console-bg: #000000;
|
||||
--console-text: #00ff00;
|
||||
--console-prompt: #00ff00;
|
||||
--console-cursor: #00ff00;
|
||||
}
|
||||
|
||||
/* Matrix theme */
|
||||
[data-theme='matrix'] {
|
||||
--bg-primary: #000000;
|
||||
--bg-secondary: #001100;
|
||||
--bg-tertiary: #002200;
|
||||
--text-primary: #00ff41;
|
||||
--text-secondary: #008f11;
|
||||
--text-accent: #00ff41;
|
||||
--text-success: #00ff41;
|
||||
--text-warning: #ffff00;
|
||||
--text-error: #ff0000;
|
||||
--border-primary: #003300;
|
||||
--console-bg: #000000;
|
||||
--console-text: #00ff41;
|
||||
--console-prompt: #00ff41;
|
||||
--console-cursor: #00ff41;
|
||||
}
|
||||
|
||||
/* Global styles */
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100%;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-base);
|
||||
line-height: var(--line-height);
|
||||
background-color: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* Header */
|
||||
.console-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: var(--spacing-sm) var(--spacing-md);
|
||||
background-color: var(--bg-secondary);
|
||||
border-bottom: 1px solid var(--border-primary);
|
||||
min-height: 56px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-lg);
|
||||
}
|
||||
|
||||
.console-title {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-sm);
|
||||
}
|
||||
|
||||
.console-icon {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.connection-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-sm);
|
||||
font-size: var(--font-size-small);
|
||||
}
|
||||
|
||||
.status-indicator {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background-color: var(--text-error);
|
||||
animation: pulse 2s infinite;
|
||||
}
|
||||
|
||||
.status-indicator.connected {
|
||||
background-color: var(--text-success);
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.status-indicator.connecting {
|
||||
background-color: var(--text-warning);
|
||||
}
|
||||
|
||||
.header-right {
|
||||
display: flex;
|
||||
gap: var(--spacing-sm);
|
||||
}
|
||||
|
||||
.header-button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-xs);
|
||||
padding: var(--spacing-sm) var(--spacing-md);
|
||||
background-color: transparent;
|
||||
color: var(--text-secondary);
|
||||
border: 1px solid var(--border-primary);
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-small);
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
|
||||
.header-button:hover {
|
||||
background-color: var(--bg-tertiary);
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border-secondary);
|
||||
}
|
||||
|
||||
.header-button:active {
|
||||
background-color: var(--accent-primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.header-button .icon {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* Main content */
|
||||
.console-main {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
min-height: 0;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Console container */
|
||||
.console-container {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: var(--console-bg);
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* Console output */
|
||||
.console-output {
|
||||
flex: 1;
|
||||
padding: var(--spacing-md);
|
||||
overflow-y: auto;
|
||||
font-family: var(--font-mono);
|
||||
color: var(--console-text);
|
||||
line-height: var(--line-height);
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.console-output::-webkit-scrollbar {
|
||||
width: 12px;
|
||||
}
|
||||
|
||||
.console-output::-webkit-scrollbar-track {
|
||||
background-color: var(--bg-secondary);
|
||||
}
|
||||
|
||||
.console-output::-webkit-scrollbar-thumb {
|
||||
background-color: var(--border-primary);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.console-output::-webkit-scrollbar-thumb:hover {
|
||||
background-color: var(--border-secondary);
|
||||
}
|
||||
|
||||
/* Welcome message */
|
||||
.welcome-message {
|
||||
color: var(--text-accent);
|
||||
margin-bottom: var(--spacing-lg);
|
||||
}
|
||||
|
||||
.ascii-art {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-small);
|
||||
line-height: 1.2;
|
||||
color: var(--text-accent);
|
||||
white-space: pre;
|
||||
font-weight: normal;
|
||||
letter-spacing: 0;
|
||||
word-spacing: 0;
|
||||
text-align: left;
|
||||
font-variant-ligatures: none;
|
||||
font-feature-settings: 'liga' 0;
|
||||
overflow-x: auto;
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Console output entries */
|
||||
.output-entry {
|
||||
margin-bottom: var(--spacing-xs);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.output-line {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--spacing-sm);
|
||||
}
|
||||
|
||||
.output-timestamp {
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--font-size-small);
|
||||
min-width: 80px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.output-content {
|
||||
flex: 1;
|
||||
color: var(--console-text);
|
||||
}
|
||||
|
||||
.output-content.command {
|
||||
color: var(--console-prompt);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.output-content.success {
|
||||
color: var(--text-success);
|
||||
}
|
||||
|
||||
.output-content.warning {
|
||||
color: var(--text-warning);
|
||||
}
|
||||
|
||||
.output-content.error {
|
||||
color: var(--text-error);
|
||||
}
|
||||
|
||||
.output-content.info {
|
||||
color: var(--text-accent);
|
||||
}
|
||||
|
||||
/* Console input area */
|
||||
.console-input-area {
|
||||
background-color: var(--bg-secondary);
|
||||
border-top: 1px solid var(--border-primary);
|
||||
padding: var(--spacing-md);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.input-prompt {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-sm);
|
||||
}
|
||||
|
||||
.prompt-text {
|
||||
color: var(--console-prompt);
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.console-input {
|
||||
flex: 1;
|
||||
background-color: transparent;
|
||||
border: none;
|
||||
outline: none;
|
||||
color: var(--console-text);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-base);
|
||||
line-height: var(--line-height);
|
||||
padding: var(--spacing-xs) 0;
|
||||
caret-color: var(--console-cursor);
|
||||
}
|
||||
|
||||
.console-input::placeholder {
|
||||
color: var(--text-secondary);
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
/* Input suggestions */
|
||||
.input-suggestions {
|
||||
margin-top: var(--spacing-sm);
|
||||
background-color: var(--bg-tertiary);
|
||||
border: 1px solid var(--border-primary);
|
||||
border-radius: 4px;
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.input-suggestions.visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.suggestion-item {
|
||||
padding: var(--spacing-sm) var(--spacing-md);
|
||||
cursor: pointer;
|
||||
color: var(--text-primary);
|
||||
border-bottom: 1px solid var(--border-secondary);
|
||||
}
|
||||
|
||||
.suggestion-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.suggestion-item:hover,
|
||||
.suggestion-item.selected {
|
||||
background-color: var(--accent-primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.suggestion-command {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.suggestion-description {
|
||||
font-size: var(--font-size-small);
|
||||
color: var(--text-secondary);
|
||||
margin-top: var(--spacing-xs);
|
||||
}
|
||||
|
||||
/* Status bar */
|
||||
.status-bar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: var(--spacing-xs) var(--spacing-md);
|
||||
background-color: var(--bg-secondary);
|
||||
border-top: 1px solid var(--border-primary);
|
||||
font-size: var(--font-size-small);
|
||||
color: var(--text-secondary);
|
||||
flex-shrink: 0;
|
||||
min-height: 32px;
|
||||
}
|
||||
|
||||
.status-left,
|
||||
.status-right {
|
||||
display: flex;
|
||||
gap: var(--spacing-md);
|
||||
}
|
||||
|
||||
.status-item {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Loading overlay */
|
||||
.loading-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: rgba(0, 0, 0, 0.8);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.loading-overlay.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.loading-spinner {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--spacing-lg);
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 3px solid var(--border-primary);
|
||||
border-top-color: var(--accent-primary);
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
.loading-text {
|
||||
color: var(--text-primary);
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
/* Animations */
|
||||
@keyframes pulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes blink {
|
||||
0%,
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
51%,
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Cursor animation */
|
||||
.console-input:focus::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 2px;
|
||||
background-color: var(--console-cursor);
|
||||
animation: blink 1s infinite;
|
||||
}
|
||||
|
||||
/* Selection styles */
|
||||
::selection {
|
||||
background-color: var(--accent-primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
::-moz-selection {
|
||||
background-color: var(--accent-primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* Focus styles */
|
||||
.console-input:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
button:focus-visible {
|
||||
outline: 2px solid var(--accent-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* Error states */
|
||||
.error-message {
|
||||
color: var(--text-error);
|
||||
background-color: rgba(248, 81, 73, 0.1);
|
||||
border: 1px solid var(--text-error);
|
||||
border-radius: 4px;
|
||||
padding: var(--spacing-md);
|
||||
margin: var(--spacing-md) 0;
|
||||
}
|
||||
|
||||
/* Success states */
|
||||
.success-message {
|
||||
color: var(--text-success);
|
||||
background-color: rgba(63, 185, 80, 0.1);
|
||||
border: 1px solid var(--text-success);
|
||||
border-radius: 4px;
|
||||
padding: var(--spacing-md);
|
||||
margin: var(--spacing-md) 0;
|
||||
}
|
||||
|
||||
/* Warning states */
|
||||
.warning-message {
|
||||
color: var(--text-warning);
|
||||
background-color: rgba(210, 153, 34, 0.1);
|
||||
border: 1px solid var(--text-warning);
|
||||
border-radius: 4px;
|
||||
padding: var(--spacing-md);
|
||||
margin: var(--spacing-md) 0;
|
||||
}
|
||||
|
||||
/* Info states */
|
||||
.info-message {
|
||||
color: var(--text-accent);
|
||||
background-color: rgba(88, 166, 255, 0.1);
|
||||
border: 1px solid var(--text-accent);
|
||||
border-radius: 4px;
|
||||
padding: var(--spacing-md);
|
||||
margin: var(--spacing-md) 0;
|
||||
}
|
||||
|
||||
/* Scroll indicator */
|
||||
.scroll-indicator {
|
||||
position: absolute;
|
||||
bottom: 60px;
|
||||
right: var(--spacing-md);
|
||||
background-color: var(--bg-tertiary);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-primary);
|
||||
border-radius: 8px;
|
||||
padding: var(--spacing-sm) var(--spacing-md);
|
||||
display: none;
|
||||
align-items: center;
|
||||
gap: var(--spacing-sm);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
||||
backdrop-filter: blur(8px);
|
||||
z-index: 100;
|
||||
font-size: var(--font-size-small);
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
|
||||
.scroll-indicator:hover {
|
||||
background-color: var(--bg-secondary);
|
||||
border-color: var(--border-secondary);
|
||||
}
|
||||
|
||||
.scroll-text {
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.scroll-resume-btn {
|
||||
background-color: var(--accent-primary);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
padding: var(--spacing-xs) var(--spacing-sm);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-small);
|
||||
cursor: pointer;
|
||||
transition: background-color var(--transition-fast);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.scroll-resume-btn:hover {
|
||||
background-color: var(--accent-hover);
|
||||
}
|
||||
|
||||
.scroll-resume-btn:active {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user