File size: 9,212 Bytes
1b1180b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
255
256
257
258
259
260
261
262
263
264
import React, { useState, useEffect, useRef } from 'react';
import { Zap, Brain, Settings, Moon, ChevronRight, Send, Bot, Server, Sparkles, Circle, User, AlertCircle } from 'lucide-react';
import { createClient } from '@supabase/supabase-js';
import ChatInterface from './components/ChatInterface';
import VisualizationPanel from './components/VisualizationPanel';
import Sidebar from './components/Sidebar';
import Header from './components/Header';
import CognitionCocooner from './services/CognitionCocooner';
import AICore from './services/AICore';
import { CodetteResponse } from './components/CodetteComponents';

interface Message {
  role: string;
  content: string;
  timestamp: Date;
  metadata?: CodetteResponse;
}

// Initialize Supabase client
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseKey = import.meta.env.VITE_SUPABASE_ANON_KEY;

if (!supabaseUrl || !supabaseKey) {
  throw new Error('Missing Supabase environment variables');
}

const supabase = createClient(supabaseUrl, supabaseKey);

const App: React.FC = () => {
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [darkMode, setDarkMode] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [aiState, setAiState] = useState({
    quantumState: [0.3, 0.7, 0.5],
    chaosState: [0.2, 0.8, 0.4, 0.6],
    activePerspectives: ['newton', 'davinci', 'neural_network', 'philosophical'],
    ethicalScore: 0.93,
    processingPower: 0.72
  });
  const [cocoons, setCocoons] = useState<Array<{id: string, type: string, wrapped: any}>>([]);
  const [isProcessing, setIsProcessing] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [currentUserId, setCurrentUserId] = useState<string | null>(null);
  
  const aiCore = useRef<AICore | null>(null);
  const cocooner = useRef(new CognitionCocooner());

  useEffect(() => {
    try {
      aiCore.current = new AICore();
      setError(null);
    } catch (err: any) {
      console.error('Error initializing AI Core:', err);
      setError(err.message);
    }
  }, []);

  useEffect(() => {
    // Check if user is already authenticated
    const checkAuth = async () => {
      try {
        const { data: { session }, error } = await supabase.auth.getSession();
        
        if (error) {
          console.error('Auth check error:', error.message);
          return;
        }

        if (session?.user) {
          setCurrentUserId(session.user.id);
          const { data: { role } } = await supabase.rpc('get_user_role');
          setIsAdmin(role === 'admin');
        }
      } catch (error: any) {
        console.error('Auth check error:', error.message);
      }
    };

    checkAuth();
  }, []);
  
  useEffect(() => {
    if (!error) {
      setMessages([
        {
          role: 'assistant',
          content: 'Hello! I am Codette, an advanced AI assistant with recursive reasoning, self-learning capabilities, and multi-agent intelligence. How can I assist you today?',
          timestamp: new Date(),
          metadata: {
            text: 'Hello! I am Codette, an advanced AI assistant with recursive reasoning, self-learning capabilities, and multi-agent intelligence. How can I assist you today?',
            instabilityFlag: false,
            perspectivesUsed: ['greeting', 'introduction'],
            cocoonLog: ['Initializing Codette AI...', 'Quantum state stabilized'],
            forceRefresh: () => handleForceRefresh('Hello! I am Codette, an advanced AI assistant with recursive reasoning, self-learning capabilities, and multi-agent intelligence. How can I assist you today?')
          }
        }
      ]);
    }
  }, [error]);
  
  const handleForceRefresh = async (content: string) => {
    if (!aiCore.current) return;
    
    setIsProcessing(true);
    try {
      const response = await aiCore.current.processInput(content, true, currentUserId || undefined);
      
      const assistantMessage: Message = {
        role: 'assistant',
        content: response,
        timestamp: new Date(),
        metadata: {
          text: response,
          instabilityFlag: Math.random() > 0.8,
          perspectivesUsed: aiState.activePerspectives.slice(0, 3),
          cocoonLog: [`Regenerating response for: ${content}`, `Generated new response at ${new Date().toISOString()}`],
          forceRefresh: () => handleForceRefresh(content)
        }
      };
      
      setMessages(prev => [...prev.slice(0, -1), assistantMessage]);
    } catch (error) {
      console.error('Error regenerating response:', error);
    } finally {
      setIsProcessing(false);
    }
  };
  
  const toggleSidebar = () => {
    setSidebarOpen(!sidebarOpen);
  };
  
  const toggleDarkMode = () => {
    setDarkMode(!darkMode);
    document.documentElement.classList.toggle('dark');
  };
  
  const sendMessage = async (content: string) => {
    if (!aiCore.current) {
      setError('AI Core is not initialized. Please check your configuration.');
      return;
    }

    const userMessage: Message = {
      role: 'user',
      content,
      timestamp: new Date()
    };
    
    setMessages(prev => [...prev, userMessage]);
    setIsProcessing(true);
    
    try {
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      const thought = { query: content, timestamp: new Date() };
      const cocoonId = cocooner.current.wrap(thought);
      setCocoons(prev => [...prev, { 
        id: cocoonId, 
        type: 'prompt', 
        wrapped: thought 
      }]);
      
      const response = await aiCore.current.processInput(content, false, currentUserId || undefined);
      
      setAiState(prev => ({
        ...prev,
        quantumState: [Math.random(), Math.random(), Math.random()].map(v => v.toFixed(2)).map(Number),
        chaosState: [Math.random(), Math.random(), Math.random(), Math.random()].map(v => v.toFixed(2)).map(Number),
        ethicalScore: Number((prev.ethicalScore + Math.random() * 0.1 - 0.05).toFixed(2)),
        processingPower: Number((prev.processingPower + Math.random() * 0.1 - 0.05).toFixed(2))
      }));
      
      const assistantMessage: Message = {
        role: 'assistant',
        content: response,
        timestamp: new Date(),
        metadata: {
          text: response,
          instabilityFlag: Math.random() > 0.8,
          perspectivesUsed: aiState.activePerspectives.slice(0, 3),
          cocoonLog: [`Processing query: ${content}`, `Generated response at ${new Date().toISOString()}`],
          forceRefresh: () => handleForceRefresh(content)
        }
      };
      
      setMessages(prev => [...prev, assistantMessage]);
    } catch (error: any) {
      console.error('Error processing message:', error);
      
      setMessages(prev => [...prev, {
        role: 'system',
        content: 'An error occurred while processing your request. Please check your configuration and try again.',
        timestamp: new Date()
      }]);
    } finally {
      setIsProcessing(false);
    }
  };
  
  if (error) {
    return (
      <div className={`min-h-screen flex items-center justify-center p-4 ${darkMode ? 'dark bg-gray-900 text-white' : 'bg-gray-50 text-gray-900'}`}>
        <div className={`max-w-md w-full p-6 rounded-lg shadow-lg ${darkMode ? 'bg-gray-800' : 'bg-white'}`}>
          <div className="flex items-center justify-center mb-4">
            <AlertCircle className="text-red-500" size={48} />
          </div>
          <h1 className="text-xl font-bold text-center mb-4">Configuration Error</h1>
          <p className="text-center mb-6">{error}</p>
          <div className={`p-4 rounded-md ${darkMode ? 'bg-gray-700' : 'bg-gray-100'}`}>
            <p className="text-sm">
              Please ensure you have:
              <ol className="list-decimal ml-5 mt-2 space-y-1">
                <li>Created a .env file</li>
                <li>Added your OpenAI API key to the .env file</li>
                <li>Added your Supabase configuration</li>
              </ol>
            </p>
          </div>
        </div>
      </div>
    );
  }
  
  return (
    <div className={`flex flex-col h-screen transition-colors duration-300 ${darkMode ? 'dark bg-gray-900 text-white' : 'bg-gray-50 text-gray-900'}`}>
      <Header 
        toggleSidebar={toggleSidebar}
        toggleDarkMode={toggleDarkMode} 
        darkMode={darkMode} 
        aiState={aiState}
      />
      
      <div className="flex flex-1 overflow-hidden">
        <Sidebar 
          isOpen={sidebarOpen} 
          cocoons={cocoons} 
          aiState={aiState}
          darkMode={darkMode}
          supabase={supabase}
          isAdmin={isAdmin}
          setIsAdmin={setIsAdmin}
        />
        
        <main className="flex-1 flex flex-col md:flex-row overflow-hidden">
          <ChatInterface 
            messages={messages} 
            sendMessage={sendMessage} 
            isProcessing={isProcessing}
            darkMode={darkMode}
          />
          
          <VisualizationPanel 
            aiState={aiState} 
            darkMode={darkMode}
          />
        </main>
      </div>
    </div>
  );
};

export default App;