everydaycats commited on
Commit
490b09b
·
verified ·
1 Parent(s): 1b2b030

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +22 -162
app.js CHANGED
@@ -106,8 +106,10 @@ server.on('upgrade', async (request, socket, head) => {
106
  });
107
 
108
  // WS Logic
 
 
 
109
  wss.on('connection', (ws, req, user) => {
110
- // Note: 'uid' is what we encoded into the JWT in the Auth Proxy
111
  const userId = user.uid;
112
 
113
  if (!clients.has(userId)) clients.set(userId, new Set());
@@ -120,182 +122,39 @@ wss.on('connection', (ws, req, user) => {
120
  try {
121
  const data = JSON.parse(message.toString());
122
 
 
123
  if (data.type === 'prompt') {
124
  ws.send(JSON.stringify({ type: 'status', status: 'thinking' }));
125
-
126
  const response = await fetch(`${CORE_URL}/process`, {
127
- method: 'POST',
128
- headers: { 'Content-Type': 'application/json' },
129
- body: JSON.stringify({
130
- userId: userId,
131
- projectId: data.projectId,
132
- prompt: data.content,
133
- context: data.context,
134
- task_type: 'chat'
135
- })
136
  });
137
-
138
  if (!response.ok) throw new Error("Core API Failed");
139
  const result = await response.json();
140
-
141
  ws.send(JSON.stringify({ type: 'response', text: result.text, should_reload: result.should_reload, usage: result.usage }));
142
  }
143
- } catch (e) {
144
- console.error("WS Error", e);
145
- ws.send(JSON.stringify({ type: 'error', message: "Processing Error" }));
146
- }
147
- });
148
-
149
- ws.on('close', () => {
150
- if (clients.has(userId)) clients.get(userId).delete(ws);
151
- });
152
- });
153
-
154
- setInterval(() => {
155
- wss.clients.forEach((ws) => {
156
- if (ws.isAlive === false) return ws.terminate();
157
- ws.isAlive = false;
158
- ws.ping();
159
- });
160
- }, 30000);
161
-
162
- server.listen(PORT, () => console.log(`🚀 Gateway on ${PORT}`));
163
 
164
- /* import express from 'express';
165
- import { createServer } from 'http';
166
- import { WebSocketServer, WebSocket } from 'ws';
167
- import cors from 'cors';
168
- import jwt from 'jsonwebtoken';
169
- import { v4 as uuidv4 } from 'uuid';
170
- import { createClient } from '@supabase/supabase-js';
171
-
172
- const PORT = 7860;
173
- const SUPABASE_URL = process.env.SUPABASE_URL;
174
- const SUPABASE_KEY = process.env.SUPABASE_SERVICE_KEY;
175
- const CORE_URL = process.env.CORE_URL || "http://localhost:7862"; // Point to Core
176
-
177
- if (!SUPABASE_URL) { console.error("❌ Config Missing"); process.exit(1); }
178
-
179
- const app = express();
180
- const server = createServer(app);
181
- const wss = new WebSocketServer({ noServer: true });
182
- const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
183
-
184
- const clients = new Map(); // UserId -> Set<WebSocket>
185
-
186
- app.use(cors());
187
- app.use(express.json({ limit: '50mb' }));
188
-
189
- app.get('/', (req, res) => res.send('Gateway Active'));
190
-
191
- // Internal Notification Webhook (Called by Core)
192
- app.post('/internal/notify', (req, res) => {
193
- const { user_id, type, message } = req.body;
194
- if (clients.has(user_id)) {
195
- clients.get(user_id).forEach(ws => {
196
- if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type, message }));
197
- });
198
- return res.json({ success: true });
199
- }
200
- res.json({ success: false });
201
- });
202
-
203
- // Inside Gateway WebSocket upgrade or API middleware
204
- async function verifyThrustToken(token) {
205
- const decoded = jwt.decode(token);
206
- if (!decoded || !decoded.sid) return null;
207
-
208
- // 1. Fetch the secret and verify existence in one go
209
- const { data: session } = await supabase
210
- .from('user_sessions')
211
- .select('session_secret')
212
- .eq('id', decoded.sid)
213
- .single();
214
-
215
- if (!session) return null; // Session was deleted/revoked
216
-
217
- try {
218
- // 2. Verify signature against the stored secret
219
- return jwt.verify(token, session.session_secret);
220
- } catch (e) {
221
- return null;
222
- }
223
- }
224
-
225
- // WS Upgrade
226
-
227
- server.on('upgrade', async (request, socket, head) => {
228
- const url = new URL(request.url, `http://${request.headers.host}`);
229
- const token = url.searchParams.get('token');
230
-
231
- if (!token) {
232
- socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
233
- socket.destroy();
234
- return;
235
- }
236
-
237
- // 1. You MUST await the async function
238
- const decodedData = await verifyThrustToken(token);
239
-
240
- // 2. Logic: If decodedData is null, verification failed
241
- if (!decodedData) {
242
- socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
243
- socket.destroy();
244
- return;
245
- }
246
-
247
- // 3. Handle the upgrade and pass the decoded data (user info)
248
- wss.handleUpgrade(request, socket, head, (ws) => {
249
- // decodedData now contains your 'sid' and whatever else was in the JWT
250
- wss.emit('connection', ws, request, decodedData);
251
- });
252
- });
253
-
254
- // WS Logic
255
- wss.on('connection', (ws, req, user) => {
256
- const userId = user.id || user.sub;
257
- if (!clients.has(userId)) clients.set(userId, new Set());
258
-
259
- clients.get(userId).add(ws);
260
-
261
- ws.isAlive = true;
262
- ws.on('pong', () => { ws.isAlive = true; });
263
-
264
- ws.on('message', async (message) => {
265
- try {
266
- const data = JSON.parse(message.toString());
267
-
268
- if (data.type === 'prompt') {
269
- ws.send(JSON.stringify({ type: 'status', status: 'thinking' }));
270
-
271
- // Call Core
272
- const response = await fetch(`${CORE_URL}/process`, {
273
- method: 'POST',
274
- headers: { 'Content-Type': 'application/json' },
275
  body: JSON.stringify({
276
  userId: userId,
277
  projectId: data.projectId,
278
- prompt: data.content,
279
- context: data.context,
280
- task_type: 'chat' // Default to chat for WS
281
  })
282
  });
283
-
284
- if (!response.ok) throw new Error("Core API Failed");
285
-
286
- const result = await response.json();
287
-
288
- // Send to Client
289
- ws.send(JSON.stringify({
290
- type: 'response',
291
- text: result.text,
292
- should_reload: result.should_reload,
293
- usage: result.usage
294
- }));
295
  }
 
296
  } catch (e) {
297
  console.error("WS Error", e);
298
- ws.send(JSON.stringify({ type: 'error', message: "Processing Error" }));
299
  }
300
  });
301
 
@@ -304,7 +163,8 @@ wss.on('connection', (ws, req, user) => {
304
  });
305
  });
306
 
307
- // Keep Alive
 
308
  setInterval(() => {
309
  wss.clients.forEach((ws) => {
310
  if (ws.isAlive === false) return ws.terminate();
@@ -314,4 +174,4 @@ setInterval(() => {
314
  }, 30000);
315
 
316
  server.listen(PORT, () => console.log(`🚀 Gateway on ${PORT}`));
317
- */
 
106
  });
107
 
108
  // WS Logic
109
+
110
+
111
+
112
  wss.on('connection', (ws, req, user) => {
 
113
  const userId = user.uid;
114
 
115
  if (!clients.has(userId)) clients.set(userId, new Set());
 
122
  try {
123
  const data = JSON.parse(message.toString());
124
 
125
+ // 1. CHAT PROMPTS
126
  if (data.type === 'prompt') {
127
  ws.send(JSON.stringify({ type: 'status', status: 'thinking' }));
 
128
  const response = await fetch(`${CORE_URL}/process`, {
129
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
130
+ body: JSON.stringify({ userId, projectId: data.projectId, prompt: data.content, context: data.context, task_type: 'chat' })
 
 
 
 
 
 
 
131
  });
 
132
  if (!response.ok) throw new Error("Core API Failed");
133
  const result = await response.json();
 
134
  ws.send(JSON.stringify({ type: 'response', text: result.text, should_reload: result.should_reload, usage: result.usage }));
135
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
+ // 2. BACKGROUND 3-MINUTE CONTEXT SYNC
138
+ if (data.type === 'context_sync') {
139
+ const payloadData = data.data;
140
+ const currentTime = new Date().toLocaleString(); // Anchor time for the AI
141
+
142
+ const formattedPrompt = `[WORKSPACE UPDATE - CURRENT TIME: ${currentTime}]\n\nActivity Log (Past 3 Minutes):\n${payloadData.buffer}\n\nGit Diffs (Modified Files):\n${payloadData.diffs}\n\nNew Untracked Files:\n${payloadData.new_files}`;
143
+
144
+ await fetch(`${CORE_URL}/process`, {
145
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  body: JSON.stringify({
147
  userId: userId,
148
  projectId: data.projectId,
149
+ prompt: formattedPrompt,
150
+ images: payloadData.images,
151
+ task_type: 'log_ingestion'
152
  })
153
  });
 
 
 
 
 
 
 
 
 
 
 
 
154
  }
155
+
156
  } catch (e) {
157
  console.error("WS Error", e);
 
158
  }
159
  });
160
 
 
163
  });
164
  });
165
 
166
+
167
+
168
  setInterval(() => {
169
  wss.clients.forEach((ws) => {
170
  if (ws.isAlive === false) return ws.terminate();
 
174
  }, 30000);
175
 
176
  server.listen(PORT, () => console.log(`🚀 Gateway on ${PORT}`));
177
+