File size: 10,575 Bytes
ac82073
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import { useState, useEffect, useRef } from 'react';
import Editor from '@monaco-editor/react';
import { Bot, Terminal, Code, Play, FileCode, Plus, Settings, Activity, Zap, Cpu } from 'lucide-react';

export default function AgentWorkspace() {
  const [files, setFiles] = useState([
    { name: 'main.py', language: 'python', content: '# Welcome to the Autonomous Agent Workspace\n# Initialize your multi-agent system below\n\nimport os\nimport json\nfrom core.agent import Agent\n\ndef main():\n    print("System Online...")\n    \nif __name__ == "__main__":\n    main()' },
    { name: 'config.json', language: 'json', content: '{\n  "model": "gpt-4",\n  "temperature": 0.7,\n  "max_tokens": 2048\n}' },
    { name: 'styles.css', language: 'css', content: '.container {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  height: 100vh;\n}' }
  ]);
  
  const [activeFile, setActiveFile] = useState(files[0]);
  const [logs, setLogs] = useState([]);
  const [isProcessing, setIsProcessing] = useState(false);
  const endOfLogsRef = useRef(null);

  const scrollToBottom = () => {
    endOfLogsRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [logs]);

  const addLog = (agent, message, type = 'info') => {
    const timestamp = new Date().toLocaleTimeString('en-US', { hour12: false, hour: "numeric", minute: "numeric", second: "numeric" });
    const colors = {
      'Architect': 'text-purple-400',
      'Coder': 'text-cyan-400',
      'Reviewer': 'text-emerald-400',
      'System': 'text-yellow-400'
    };
    
    setLogs(prev => [...prev, {
      id: Date.now() + Math.random(),
      agent,
      message,
      type,
      timestamp,
      color: colors[agent] || 'text-slate-300'
    }]);
  };

  const handleEditorChange = (value) => {
    const updatedFiles = files.map(f => 
      f.name === activeFile.name ? { ...f, content: value } : f
    );
    setFiles(updatedFiles);
    setActiveFile({ ...activeFile, content: value });
  };

  const simulateCollaboration = async () => {
    setIsProcessing(true);
    setLogs([]);
    
    // Step 1: System Start
    addLog('System', 'Initializing autonomous agent swarm...', 'system');
    await new Promise(r => setTimeout(r, 800));
    
    // Step 2: Architect Agent
    addLog('Architect', 'Analyzing project structure requirements.', 'info');
    await new Promise(r => setTimeout(r, 1500));
    addLog('Architect', 'Proposing modular architecture for scalability.', 'success');
    
    // Update main.py
    const newPythonContent = `# Autonomous Agent System - Generated by Agents
import os
import json
from core.agent import Agent
from core.task_manager import TaskManager

class AgentSwarm:
    def __init__(self, config):
        self.agents = []
        self.config = config
        self.initialize_agents()
        
    def initialize_agents(self):
        """Initialize specialized agents for different tasks"""
        print(f"Initializing {self.config.get('swarm_size', 3)} agents...")
        
    def execute_task(self, task):
        """Distribute task to most suitable agent"""
        print(f"Executing: {task}")
        return {"status": "completed", "result": "Success"}

def main():
    config = {"swarm_size": 5, "mode": "collaborative"}
    swarm = AgentSwarm(config)
    swarm.execute_task("System Optimization")

if __name__ == "__main__":
    main()`;
    
    setFiles(prev => prev.map(f => f.name === 'main.py' ? { ...f, content: newPythonContent } : f));
    if(activeFile.name === 'main.py') setActiveFile({ ...activeFile, content: newPythonContent });
    await new Promise(r => setTimeout(r, 1000));

    // Step 3: Coder Agent
    addLog('Coder', 'Refining implementation in main.py.', 'info');
    await new Promise(r => setTimeout(r, 1200));
    addLog('Coder', 'Adding error handling and async support.', 'warning');
    
    // Create new file
    const newFile = { 
      name: 'utils.js', 
      language: 'javascript', 
      content: '// Utility functions for the Agent Swarm\n\nexport const debounce = (func, wait) => {\n  let timeout;\n  return function executedFunction(...args) {\n    const later = () => {\n      clearTimeout(timeout);\n      func(...args);\n    };\n    clearTimeout(timeout);\n    timeout = setTimeout(later, wait);\n  };\n};\n\nexport const generateId = () => {\n  return Math.random().toString(36).substr(2, 9);\n};' 
    };
    
    setFiles(prev => [...prev, newFile]);
    addLog('Coder', 'Created new module: utils.js', 'success');
    await new Promise(r => setTimeout(r, 1000));

    // Step 4: Reviewer Agent
    addLog('Reviewer', 'Scanning code for vulnerabilities...', 'info');
    await new Promise(r => setTimeout(r, 1500));
    addLog('Reviewer', 'Linting passed. No critical issues found.', 'success');
    addLog('Reviewer', 'Optimizing import statements.', 'warning');

    // Step 5: Finalize
    addLog('System', 'Swarm collaboration complete. Project updated.', 'system');
    setIsProcessing(false);
  };

  return (
    <div className="flex flex-col h-[700px] bg-slate-900 rounded-xl border border-slate-700 shadow-2xl overflow-hidden">
      {/* Toolbar */}
      <div className="h-12 bg-slate-800 border-b border-slate-700 flex items-center justify-between px-4">
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2 text-slate-300">
            <Cpu className="w-4 h-4 text-indigo-400" />
            <span className="font-semibold text-sm">Agent Workspace</span>
          </div>
          <div className="h-4 w-px bg-slate-600"></div>
          <div className="flex items-center gap-2">
            {files.map((file) => (
              <button
                key={file.name}
                onClick={() => setActiveFile(file)}
                className={`flex items-center gap-1.5 px-3 py-1 rounded-md text-xs font-medium transition-all ${
                  activeFile.name === file.name
                    ? 'bg-indigo-600 text-white shadow-md'
                    : 'text-slate-400 hover:text-white hover:bg-slate-700'
                }`}
              >
                <FileCode className="w-3.5 h-3.5" />
                {file.name}
              </button>
            ))}
            <button className="text-slate-500 hover:text-white p-1 rounded hover:bg-slate-700 transition-colors">
              <Plus className="w-4 h-4" />
            </button>
          </div>
        </div>
        
        <button
          onClick={simulateCollaboration}
          disabled={isProcessing}
          className={`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${
            isProcessing 
              ? 'bg-slate-700 text-slate-400 cursor-not-allowed' 
              : 'bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 text-white shadow-lg shadow-indigo-900/30'
          }`}
        >
          {isProcessing ? (
            <>
              <Activity className="w-4 h-4 animate-pulse" />
              Agents Working...
            </>
          ) : (
            <>
              <Zap className="w-4 h-4" />
              Deploy Agents
            </>
          )}
        </button>
      </div>

      {/* Main Content Area */}
      <div className="flex flex-1 overflow-hidden">
        {/* Left: Agent Stream */}
        <div className="w-80 bg-slate-950 border-r border-slate-800 flex flex-col">
          <div className="p-3 border-b border-slate-800 flex items-center justify-between">
            <div className="flex items-center gap-2 text-xs font-semibold text-slate-400 uppercase tracking-wider">
              <Terminal className="w-3.5 h-3.5" />
              Agent Stream
            </div>
            <div className={`flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-medium ${
              isProcessing ? 'bg-emerald-900/50 text-emerald-400' : 'bg-slate-800 text-slate-500'
            }`}>
              <span className={`w-1.5 h-1.5 rounded-full ${isProcessing ? 'bg-emerald-400 animate-pulse' : 'bg-slate-600'}`}></span>
              {isProcessing ? 'Live' : 'Idle'}
            </div>
          </div>
          
          <div className="flex-1 overflow-y-auto p-3 space-y-3">
            {logs.length === 0 && !isProcessing && (
              <div className="h-full flex flex-col items-center justify-center text-slate-600 space-y-3">
                <Bot className="w-10 h-10 opacity-20" />
                <p className="text-xs text-center px-4">Deploy agents to start collaborative coding session.</p>
              </div>
            )}
            
            {logs.map((log) => (
              <div key={log.id} className="flex gap-2 text-sm animate-in fade-in slide-in-from-bottom-2 duration-300">
                <div className="flex-shrink-0 w-16 text-right">
                  <span className={`text-xs font-mono ${log.color} font-medium`}>{log.agent}</span>
                </div>
                <div className="flex-1">
                  <div className="bg-slate-900 p-2 rounded-lg border border-slate-800/50">
                    <p className="text-slate-300 text-xs leading-relaxed">{log.message}</p>
                  </div>
                  <span className="text-[10px] text-slate-600 font-mono ml-1">{log.timestamp}</span>
                </div>
              </div>
            ))}
            <div ref={endOfLogsRef} />
          </div>
        </div>

        {/* Right: Monaco Editor */}
        <div className="flex-1 flex flex-col bg-[#1e1e1e]">
          <div className="bg-[#252526] h-8 flex items-center px-4 border-b border-black">
             <span className="text-xs text-slate-400 font-mono flex items-center gap-2">
               <Code className="w-3 h-3" />
               {activeFile.name}
             </span>
          </div>
          <div className="flex-1 relative">
             <Editor
               height="100%"
               language={activeFile.language}
               theme="vs-dark"
               value={activeFile.content}
               onChange={handleEditorChange}
               options={{
                 minimap: { enabled: false },
                 fontSize: 14,
                 lineNumbers: 'on',
                 roundedSelection: false,
                 scrollBeyondLastLine: false,
                 automaticLayout: true,
                 tabSize: 2,
                 wordWrap: 'on',
                 padding: { top: 16 }

             />
          </div>
        </div>
      </div>
    </div>
  );
}