FerrellSyntheticIntelligence commited on
Commit
5b2365f
·
verified ·
1 Parent(s): a4abe4e

Upload ide/app.js with huggingface_hub

Browse files
Files changed (1) hide show
  1. ide/app.js +748 -0
ide/app.js ADDED
@@ -0,0 +1,748 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ── FSI_FELON IDE — Underwater Fusion Lab (Phase 2) ── */
2
+
3
+ const API = 'http://' + location.hostname + ':9090';
4
+
5
+ document.addEventListener('DOMContentLoaded', () => {
6
+ const tabs = document.querySelectorAll('.sidebar-tab');
7
+ const panels = document.querySelectorAll('.panel');
8
+ const splash = document.getElementById('splash');
9
+
10
+ // ── Psycho Mode animation (hidden) ──
11
+ function psychoAnimate(outEl, writeFn, data, onDone) {
12
+ const manifesto = data.manifesto || [];
13
+ const variants = data.variants || [];
14
+ const project = data.project || 'project';
15
+ const totalLoc = data.total_loc || 0;
16
+ const files = data.files || 0;
17
+
18
+ let delay = 0;
19
+ manifesto.forEach(line => {
20
+ setTimeout(() => writeFn(' ' + line, 'psycho-manifesto'), delay);
21
+ delay += 800;
22
+ });
23
+ setTimeout(() => {
24
+ writeFn('', '');
25
+ writeFn('╔══════════════════════════════════════╗', 'psycho-banner');
26
+ writeFn('║ P S Y C H O M O D E ║', 'psycho-banner');
27
+ writeFn('║ E N G A G E D ║', 'psycho-banner');
28
+ writeFn('╚══════════════════════════════════════╝', 'psycho-banner');
29
+ writeFn('', '');
30
+ writeFn(' Building: ' + project, 'psycho-banner');
31
+ }, delay + 400);
32
+ delay += 1200;
33
+ variants.forEach((v, i) => {
34
+ setTimeout(() => writeFn(' ' + v, 'forge'), delay + i * 300);
35
+ });
36
+ delay += variants.length * 300 + 400;
37
+ setTimeout(() => {
38
+ writeFn('', '');
39
+ writeFn('╔══════════════════════════════════════╗', 'psycho-summary');
40
+ writeFn('║ 6 VARIANTS | ' + String(totalLoc).padEnd(5) + ' LOC | ' + String(files).padEnd(4) + ' FILES ║', 'psycho-summary');
41
+ writeFn('╚══════════════════════════════════════╝', 'psycho-summary');
42
+ writeFn('', '');
43
+ writeFn(' You wanted psycho. You got it.', 'psycho-banner');
44
+ if (onDone) onDone();
45
+ }, delay + 400);
46
+ }
47
+
48
+ // ── Nanobot click sequence for psycho unlock (hidden) ──
49
+ const PSYCHO_ORGAN_SEQ = ['Antennae', 'Spine', 'Hippocampus', 'Cerebellum', 'Prefrontal', 'Dream'];
50
+ let psychoClickSeq = [];
51
+ let psychoClickTimer = null;
52
+
53
+ document.addEventListener('click', (e) => {
54
+ const bot = e.target.closest('.nanobot');
55
+ if (!bot) return;
56
+ const organ = bot.dataset && bot.dataset.organ;
57
+ if (!organ) return;
58
+ const expected = PSYCHO_ORGAN_SEQ[psychoClickSeq.length];
59
+ if (organ === expected) {
60
+ psychoClickSeq.push(organ);
61
+ if (psychoClickTimer) clearTimeout(psychoClickTimer);
62
+ psychoClickTimer = setTimeout(() => { psychoClickSeq = []; }, 3000);
63
+ if (psychoClickSeq.length === PSYCHO_ORGAN_SEQ.length) {
64
+ psychoClickSeq = [];
65
+ const project = editor ? (editor.value.split('\n')[0] || 'project').trim().slice(0, 40) : 'project';
66
+ api('/api/psycho/unlock', { project: project }).then(data => {
67
+ if (data.psycho && termOutput && termInput) {
68
+ psychoAnimate(termOutput, (text, cls) => {
69
+ const d = document.createElement('div');
70
+ d.className = 'terminal-line ' + cls;
71
+ d.textContent = text;
72
+ termOutput.appendChild(d);
73
+ termOutput.scrollTop = termOutput.scrollHeight;
74
+ }, data, () => {
75
+ document.querySelector('[data-panel="deep"]').click();
76
+ });
77
+ }
78
+ });
79
+ }
80
+ } else {
81
+ psychoClickSeq = [];
82
+ }
83
+ });
84
+
85
+ // ── API client ──
86
+ async function api(path, body) {
87
+ try {
88
+ const r = await fetch(API + path, {
89
+ method: body ? 'POST' : 'GET',
90
+ headers: { 'Content-Type': 'application/json' },
91
+ body: body ? JSON.stringify(body) : null,
92
+ });
93
+ return await r.json();
94
+ } catch (e) {
95
+ return { output: ['[API] Server offline — run server.py'], error: true };
96
+ }
97
+ }
98
+
99
+ // ── Splash fade ──
100
+ setTimeout(() => { if (splash) splash.style.opacity = '0'; }, 3200);
101
+ setTimeout(() => { if (splash) splash.style.display = 'none'; }, 4000);
102
+
103
+ // ── Onboarding ──
104
+ const onboarding = document.getElementById('onboarding');
105
+ const onboardingBtn = document.getElementById('onboarding-start-btn');
106
+ const onboardingCheck = document.getElementById('onboarding-dismiss-check');
107
+ if (onboarding && !localStorage.getItem('fsi_onboarded')) {
108
+ setTimeout(() => { onboarding.classList.add('visible'); }, 4200);
109
+ }
110
+ if (onboardingBtn && onboarding) {
111
+ onboardingBtn.addEventListener('click', () => {
112
+ if (onboardingCheck && onboardingCheck.checked) {
113
+ localStorage.setItem('fsi_onboarded', 'true');
114
+ }
115
+ onboarding.classList.remove('visible');
116
+ });
117
+ }
118
+
119
+ // ── Star particles ──
120
+ const starContainer = document.querySelector('.splash-stars');
121
+ if (starContainer) {
122
+ for (let i = 0; i < 60; i++) {
123
+ const s = document.createElement('div');
124
+ s.className = 'splash-particle';
125
+ const size = 1 + Math.random() * 2;
126
+ s.style.width = size + 'px';
127
+ s.style.height = size + 'px';
128
+ s.style.left = Math.random() * 100 + '%';
129
+ s.style.top = Math.random() * 30 + '%';
130
+ s.style.animationDelay = Math.random() * 2 + 's';
131
+ s.style.animationDuration = (1.5 + Math.random() * 2) + 's';
132
+ s.style.background = Math.random() > 0.7 ? '#ff6b35' : '#00d4ff';
133
+ starContainer.appendChild(s);
134
+ }
135
+ }
136
+
137
+ // ── Bubbles ──
138
+ for (let i = 0; i < 40; i++) {
139
+ const b = document.createElement('div');
140
+ b.className = 'bubble';
141
+ const size = 2 + Math.random() * 6;
142
+ b.style.width = size + 'px';
143
+ b.style.height = size + 'px';
144
+ b.style.left = Math.random() * 100 + '%';
145
+ b.style.bottom = '-10px';
146
+ b.style.animationDuration = (6 + Math.random() * 8) + 's';
147
+ b.style.animationDelay = Math.random() * 8 + 's';
148
+ b.style.opacity = 0.1 + Math.random() * 0.2;
149
+ document.body.appendChild(b);
150
+ }
151
+
152
+ // ── Tab Switching ──
153
+ tabs.forEach(tab => {
154
+ tab.addEventListener('click', () => {
155
+ const target = tab.dataset.panel;
156
+ tabs.forEach(t => t.classList.remove('active'));
157
+ panels.forEach(p => p.classList.remove('active'));
158
+ tab.classList.add('active');
159
+ const panel = document.getElementById('panel-' + target);
160
+ if (panel) panel.classList.add('active');
161
+ if (target === 'vault') loadVaultTree();
162
+ });
163
+ });
164
+
165
+ // ── Editor: Sync line numbers ──
166
+ const editor = document.getElementById('code-editor');
167
+ const gutter = document.getElementById('editor-gutter');
168
+ if (editor && gutter) {
169
+ const updateGutter = () => {
170
+ const lines = editor.value.split('\n');
171
+ gutter.innerHTML = lines.map((_, i) => '<div>' + (i + 1) + '</div>').join('');
172
+ };
173
+ editor.addEventListener('input', updateGutter);
174
+ editor.addEventListener('scroll', () => { gutter.scrollTop = editor.scrollTop; });
175
+ updateGutter();
176
+ }
177
+
178
+ // ── Terminal ──
179
+ const termInput = document.getElementById('terminal-input');
180
+ const termOutput = document.getElementById('terminal-output');
181
+ const termHistory = [];
182
+ let termIdx = -1;
183
+
184
+ if (termInput && termOutput) {
185
+ const write = (text, cls = '') => {
186
+ const d = document.createElement('div');
187
+ d.className = 'terminal-line ' + cls;
188
+ d.textContent = text;
189
+ termOutput.appendChild(d);
190
+ termOutput.scrollTop = termOutput.scrollHeight;
191
+ };
192
+
193
+ write('╔══════════════════════════════════════╗', 'info');
194
+ write('║ FSI_FELON Terminal v4.0 ║', 'info');
195
+ write('║ Connecting to backend... ║', 'info');
196
+ write('╚══════════════════════════════════════╝', 'info');
197
+ write('');
198
+
199
+ termInput.addEventListener('keydown', (e) => {
200
+ if (e.key === 'Enter') {
201
+ const cmd = termInput.value.trim();
202
+ if (!cmd) return;
203
+ write('fsi> ' + cmd);
204
+ termHistory.push(cmd);
205
+ termIdx = termHistory.length;
206
+ termInput.value = '';
207
+ termInput.disabled = true;
208
+
209
+ if (cmd.toLowerCase() === 'clear') {
210
+ termOutput.innerHTML = '';
211
+ termInput.disabled = false;
212
+ termInput.focus();
213
+ return;
214
+ }
215
+
216
+ api('/api/command', { cmd: cmd }).then(data => {
217
+ const lines = data.output || ['[API] No response'];
218
+ // Check for psycho mode (structured response)
219
+ if (data.psycho) {
220
+ psychoAnimate(termOutput, write, data, () => {
221
+ termInput.disabled = false;
222
+ termInput.focus();
223
+ });
224
+ } else {
225
+ lines.forEach(line => {
226
+ if (line === '__CLEAR__') {
227
+ termOutput.innerHTML = '';
228
+ return;
229
+ }
230
+ let cls = 'info';
231
+ if (line.includes('CHIMERA') || line.includes('ROUTED')) cls = 'chimera';
232
+ else if (line.includes('Error') || line.includes('Unknown') || line.includes('error')) cls = 'error';
233
+ else if (line.includes('✓') || line.includes('WOOGITY')) cls = 'prompt';
234
+ else if (line.includes('FORGE') || line.includes('BUILD')) cls = 'forge';
235
+ else if (line.includes('KELI') || line.includes('WHITE') || line.includes('RABBIT')) cls = 'rabbit';
236
+ else if (line.includes('DREAM')) cls = 'dream';
237
+ else if (line.includes('TEST')) cls = 'test';
238
+ write(' ' + line, cls);
239
+ });
240
+ termInput.disabled = false;
241
+ termInput.focus();
242
+ }
243
+ });
244
+ } else if (e.key === 'ArrowUp') {
245
+ if (termIdx > 0) { termIdx--; termInput.value = termHistory[termIdx]; }
246
+ e.preventDefault();
247
+ } else if (e.key === 'ArrowDown') {
248
+ if (termIdx < termHistory.length - 1) { termIdx++; termInput.value = termHistory[termIdx]; }
249
+ else { termIdx = termHistory.length; termInput.value = ''; }
250
+ e.preventDefault();
251
+ }
252
+ });
253
+ }
254
+
255
+ // ── Forge It Button (Workshop → Forge) ──
256
+ const forgeBtn = document.getElementById('forge-btn');
257
+ if (forgeBtn) {
258
+ forgeBtn.addEventListener('click', async () => {
259
+ const code = editor ? editor.value : '';
260
+ const lines = code.split('\n').filter(l => l.trim() && !l.trim().startsWith('#'));
261
+ const desc = (lines[0] || 'project').replace(/^def\s+|^class\s+|^#\s*/g, '').trim().slice(0, 60) || 'project';
262
+ forgeBtn.textContent = '⚡ Forging...';
263
+ forgeBtn.disabled = true;
264
+
265
+ const forgePanel = document.getElementById('panel-forge');
266
+ document.querySelector('[data-panel="forge"]').click();
267
+
268
+ const forgeOutput = document.getElementById('forge-output');
269
+ const card = document.createElement('div');
270
+ card.className = 'forge-card';
271
+ card.innerHTML = '<div class="forge-card-header"><span style="font-weight:400;font-size:14px;color:#c8d6e5">' + desc + '</span><span class="forge-badge badge-pending">⟳ RUN</span></div><div style="font-size:12px;color:rgba(200,214,229,0.45)">Building...</div>';
272
+ forgeOutput.prepend(card);
273
+
274
+ const data = await api('/api/build', { desc: desc, code: code });
275
+ const files = data.files || '—';
276
+ const loc = data.loc || '—';
277
+ const time = data.time || '—';
278
+ card.innerHTML = '<div class="forge-card-header"><span style="font-weight:400;font-size:14px;color:#c8d6e5">' + desc + '</span><span class="forge-badge badge-success">✓ PASS</span></div><div style="font-size:12px;color:rgba(200,214,229,0.45)">' + files + ' files · ' + loc + ' LOC · ' + time + '</div>';
279
+
280
+ forgeBtn.textContent = '⚡ Forge It';
281
+ forgeBtn.disabled = false;
282
+ });
283
+ }
284
+
285
+ // ── Sidebar Status Polling ──
286
+ const statusRows = document.querySelectorAll('.sidebar-status .value');
287
+ async function pollStatus() {
288
+ const data = await api('/api/stats');
289
+ if (data.training && statusRows.length >= 3) {
290
+ const t = data.training;
291
+ statusRows[0].textContent = 'step ' + t.step + ' · loss ' + t.loss;
292
+ statusRows[1].textContent = (data.chimera ? data.chimera.organs : '—') + ' organs · ' + (data.chimera ? (data.chimera.accuracy * 100).toFixed(0) + '% route' : '—');
293
+ const meshEl = document.getElementById('sidebar-mesh-peers');
294
+ if (meshEl) {
295
+ const id = await api('/api/mesh/identity');
296
+ meshEl.textContent = (id.peers || 0) + ' peers';
297
+ }
298
+ statusRows[3].textContent = (t.tokens_per_sec || '—') + ' tok/s';
299
+ }
300
+ }
301
+ setInterval(pollStatus, 2000);
302
+
303
+ // ── Vault File Tree ──
304
+ const vaultTree = document.getElementById('vault-tree');
305
+ const uploadZone = document.querySelector('.vault-upload-zone');
306
+
307
+ async function loadVaultTree() {
308
+ if (!vaultTree) return;
309
+ const data = await api('/api/files?path=' + encodeURIComponent('/tmp/fsi_felon/workspace'));
310
+ if (data.error || !data.files) {
311
+ vaultTree.innerHTML = '<div class="tree-item"><span style="color:#ff6b35;">⚠ ' + (data.error || 'Could not load workspace') + '</span></div>';
312
+ return;
313
+ }
314
+ let html = '<div class="tree-item folder" data-path="/tmp/fsi_felon/workspace"><span class="icon">📂</span><span>workspace</span></div>';
315
+ const renderItems = (items, depth) => {
316
+ for (const item of items) {
317
+ if (item.type === 'folder') {
318
+ html += '<div class="tree-item folder" style="padding-left:' + (16 + depth * 20) + 'px" data-path="' + item.path + '"><span class="icon">' + (item.children ? '📁' : '📂') + '</span><span>' + item.name + '</span></div>';
319
+ if (item.children) renderItems(item.children, depth + 1);
320
+ } else {
321
+ const size = item.size ? ' <span style="color:rgba(200,214,229,0.35);font-size:10px;">' + (item.size > 1024 ? (item.size / 1024).toFixed(1) + 'KB' : item.size + 'B') + '</span>' : '';
322
+ html += '<div class="tree-item file" style="padding-left:' + (16 + depth * 20) + 'px" data-path="' + item.path + '"><span class="icon">📄</span><span>' + item.name + size + '</span></div>';
323
+ }
324
+ }
325
+ };
326
+ renderItems(data.files, 0);
327
+ vaultTree.innerHTML = html;
328
+ }
329
+
330
+ // Click file in vault → open in workshop
331
+ document.addEventListener('click', (e) => {
332
+ const item = e.target.closest('.tree-item.file');
333
+ if (!item) return;
334
+ const path = item.dataset.path;
335
+ if (!path) return;
336
+ api('/api/download?path=' + encodeURIComponent(path)).then(data => {
337
+ if (data.content && editor) {
338
+ editor.value = data.content;
339
+ if (gutter) {
340
+ const lines = data.content.split('\n');
341
+ gutter.innerHTML = lines.map((_, i) => '<div>' + (i + 1) + '</div>').join('');
342
+ }
343
+ document.querySelector('[data-panel="workshop"]').click();
344
+ }
345
+ });
346
+ });
347
+
348
+ // Upload zone
349
+ if (uploadZone) {
350
+ const input = document.createElement('input');
351
+ input.type = 'file';
352
+ input.style.display = 'none';
353
+ document.body.appendChild(input);
354
+
355
+ uploadZone.addEventListener('click', () => input.click());
356
+ uploadZone.addEventListener('dragover', (e) => { e.preventDefault(); uploadZone.style.borderColor = '#00d4ff'; });
357
+ uploadZone.addEventListener('dragleave', () => { uploadZone.style.borderColor = ''; });
358
+ uploadZone.addEventListener('drop', (e) => {
359
+ e.preventDefault();
360
+ uploadZone.style.borderColor = '';
361
+ const files = e.dataTransfer.files;
362
+ if (files.length) uploadFile(files[0]);
363
+ });
364
+ input.addEventListener('change', () => {
365
+ if (input.files.length) uploadFile(input.files[0]);
366
+ input.value = '';
367
+ });
368
+
369
+ async function uploadFile(file) {
370
+ const reader = new FileReader();
371
+ reader.onload = async (e) => {
372
+ const data = await api('/api/upload', {
373
+ filename: file.name,
374
+ content: e.target.result,
375
+ path: '/tmp/fsi_felon/workspace',
376
+ });
377
+ if (data.success) loadVaultTree();
378
+ };
379
+ reader.readAsText(file);
380
+ }
381
+ }
382
+
383
+ // ── Dream: Chimera stats into nanobot status ──
384
+ const canvas = document.getElementById('dream-canvas');
385
+ if (canvas) {
386
+ const count = 25;
387
+ const bots = [];
388
+ const colors = ['#00d4ff', '#ff6b35', '#ff3366', '#00ff88', '#ffffff'];
389
+ const organNames = ['Antennae', 'Spine', 'Hippocampus', 'Cerebellum', 'Prefrontal', 'Dream'];
390
+
391
+ for (let i = 0; i < count; i++) {
392
+ const bot = document.createElement('div');
393
+ bot.className = 'nanobot';
394
+ const size = 4 + Math.random() * 4;
395
+ const color = colors[Math.floor(Math.random() * colors.length)];
396
+ const x = Math.random() * 92 + 4;
397
+ const y = Math.random() * 88 + 4;
398
+ bot.style.width = size + 'px';
399
+ bot.style.height = size + 'px';
400
+ bot.style.left = x + '%';
401
+ bot.style.top = y + '%';
402
+ bot.style.background = color;
403
+ bot.style.boxShadow = '0 0 ' + (4 + Math.random() * 8) + 'px ' + color + '60';
404
+ bot.style.animation = 'nanobotFloat ' + (3 + Math.random() * 4) + 's ease-in-out infinite';
405
+ bot.style.animationDelay = Math.random() * 3 + 's';
406
+ const organName = organNames[Math.floor(Math.random() * organNames.length)];
407
+ bot.dataset.organ = organName;
408
+ canvas.appendChild(bot);
409
+ bots.push({
410
+ el: bot, x: x, y: y,
411
+ vx: (Math.random() - 0.5) * 0.15,
412
+ vy: (Math.random() - 0.5) * 0.15,
413
+ color: color, size: size,
414
+ organ: organName,
415
+ });
416
+ }
417
+
418
+ const trails = [];
419
+ for (let i = 0; i < 15; i++) {
420
+ const t = document.createElement('div');
421
+ t.className = 'nanobot-trail';
422
+ const ts = 1 + Math.random() * 2;
423
+ t.style.width = ts + 'px';
424
+ t.style.height = ts + 'px';
425
+ t.style.background = '#00d4ff';
426
+ t.style.animationDelay = Math.random() * 3 + 's';
427
+ canvas.appendChild(t);
428
+ trails.push(t);
429
+ }
430
+
431
+ const lineLayer = document.createElement('div');
432
+ lineLayer.style.position = 'absolute';
433
+ lineLayer.style.inset = '0';
434
+ lineLayer.style.pointerEvents = 'none';
435
+ lineLayer.style.zIndex = '0';
436
+ canvas.appendChild(lineLayer);
437
+
438
+ const lines = [];
439
+ for (let i = 0; i < 40; i++) {
440
+ const l = document.createElement('div');
441
+ l.className = 'nanobot-line';
442
+ l.style.background = 'rgba(0,212,255,0.15)';
443
+ l.style.height = '1px';
444
+ lineLayer.appendChild(l);
445
+ lines.push(l);
446
+ }
447
+
448
+ const statusEl = canvas.querySelector('.dream-status');
449
+ const updateStatus = () => {
450
+ if (!statusEl) return;
451
+ api('/api/stats').then(data => {
452
+ const c = data.chimera || {};
453
+ const t = data.training || {};
454
+ statusEl.innerHTML = '<span>Swarm: ' + bots.length + ' active</span><span>Organs: ' + (c.organs || '—') + ' · ' + (c.accuracy ? (c.accuracy * 100).toFixed(0) + '%' : '—') + '</span><span>Loss: ' + (t.loss || '—') + '</span>';
455
+ });
456
+ };
457
+
458
+ let frame = 0;
459
+ const animate = () => {
460
+ frame++;
461
+ bots.forEach(b => {
462
+ b.x += b.vx + Math.sin(frame * 0.01 + b.y) * 0.02;
463
+ b.y += b.vy + Math.cos(frame * 0.01 + b.x) * 0.02;
464
+ if (b.x < 0 || b.x > 94) { b.vx *= -1; b.x = Math.max(0, Math.min(94, b.x)); }
465
+ if (b.y < 0 || b.y > 94) { b.vy *= -1; b.y = Math.max(0, Math.min(94, b.y)); }
466
+ b.el.style.left = b.x + '%';
467
+ b.el.style.top = b.y + '%';
468
+ });
469
+
470
+ const connections = [];
471
+ for (let i = 0; i < bots.length; i++) {
472
+ for (let j = i + 1; j < bots.length; j++) {
473
+ const dx = bots[i].x - bots[j].x;
474
+ const dy = bots[i].y - bots[j].y;
475
+ const dist = Math.sqrt(dx * dx + dy * dy);
476
+ if (dist < 12) connections.push({ i, j, dist });
477
+ }
478
+ }
479
+
480
+ const w = canvas.offsetWidth;
481
+ const h = canvas.offsetHeight;
482
+ lines.forEach((l, idx) => {
483
+ if (idx < connections.length) {
484
+ const c = connections[idx];
485
+ const b1 = bots[c.i];
486
+ const b2 = bots[c.j];
487
+ const x1 = b1.x / 100 * w;
488
+ const y1 = b1.y / 100 * h;
489
+ const x2 = b2.x / 100 * w;
490
+ const y2 = b2.y / 100 * h;
491
+ const len = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
492
+ const angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
493
+ l.style.left = x1 + 'px';
494
+ l.style.top = y1 + 'px';
495
+ l.style.width = len + 'px';
496
+ l.style.transform = 'rotate(' + angle + 'deg)';
497
+ l.style.opacity = Math.max(0, (1 - c.dist / 12) * 0.6);
498
+ } else {
499
+ l.style.opacity = '0';
500
+ }
501
+ });
502
+
503
+ trails.forEach((t, idx) => {
504
+ const bot = bots[idx % bots.length];
505
+ t.style.left = (bot.x + (Math.random() - 0.5) * 5) + '%';
506
+ t.style.top = (bot.y + (Math.random() - 0.5) * 5) + '%';
507
+ });
508
+
509
+ if (frame % 30 === 0) updateStatus();
510
+ requestAnimationFrame(animate);
511
+ };
512
+ animate();
513
+ }
514
+
515
+ // ── Mesh: Node Identity & Sharing ──
516
+ const meshNodeId = document.getElementById('mesh-node-id');
517
+ const meshPubkey = document.getElementById('mesh-pubkey');
518
+ const meshUptime = document.getElementById('mesh-uptime');
519
+ const meshPeers = document.getElementById('mesh-peers');
520
+ const meshSharedCount = document.getElementById('mesh-shared-count');
521
+ const meshFeed = document.getElementById('mesh-feed');
522
+ const meshInsights = document.getElementById('mesh-insights-content');
523
+ const meshPublishBtn = document.getElementById('mesh-publish-btn');
524
+ const meshToggleGlobal = document.getElementById('mesh-toggle-global');
525
+ const meshToggleBench = document.getElementById('mesh-toggle-benchmarks');
526
+ const meshToggleDreams = document.getElementById('mesh-toggle-dreams');
527
+ const meshToggleStats = document.getElementById('mesh-toggle-stats');
528
+
529
+ async function pollMesh() {
530
+ const identity = await api('/api/mesh/identity');
531
+ if (identity.node_id && meshNodeId) {
532
+ meshNodeId.textContent = identity.node_id;
533
+ meshPubkey.textContent = identity.pubkey_fingerprint || '—';
534
+ const up = identity.uptime || 0;
535
+ const h = Math.floor(up / 3600);
536
+ const m = Math.floor((up % 3600) / 60);
537
+ const s = up % 60;
538
+ meshUptime.textContent = h + 'h ' + m + 'm ' + s + 's';
539
+ meshPeers.textContent = identity.peers || 0;
540
+ }
541
+ const discover = await api('/api/mesh/discover');
542
+ if (discover.items && meshFeed) {
543
+ if (discover.items.length === 0) {
544
+ meshFeed.innerHTML = '<div class="mesh-feed-empty">&#x1F578; No peers yet — shared content from other nodes appears here when they connect.</div>';
545
+ } else {
546
+ meshFeed.innerHTML = discover.items.map(item => {
547
+ const ts = item.timestamp ? new Date(item.timestamp * 1000).toLocaleString() : '';
548
+ return '<div class="mesh-feed-item">' +
549
+ '<div class="mesh-feed-item-header">' +
550
+ '<span class="mesh-feed-item-name">' + escapeHtml(item.name) + '</span>' +
551
+ '<span class="mesh-feed-item-node">' + (item.node_id ? item.node_id.slice(0, 8) + '..' : '—') + '</span>' +
552
+ '</div>' +
553
+ '<div class="mesh-feed-item-meta"><span>' + escapeHtml(item.type || 'project') + '</span><span>' + ts + '</span></div>' +
554
+ '</div>';
555
+ }).join('');
556
+ }
557
+ }
558
+ const shareData = await api('/api/mesh/discover?local=true');
559
+ if (shareData.items && meshSharedCount) {
560
+ meshSharedCount.textContent = shareData.items.length + ' items shared';
561
+ }
562
+ }
563
+
564
+ function escapeHtml(s) {
565
+ const d = document.createElement('div');
566
+ d.textContent = s;
567
+ return d.innerHTML;
568
+ }
569
+
570
+ // Publish current project to mesh
571
+ if (meshPublishBtn && editor) {
572
+ meshPublishBtn.addEventListener('click', async () => {
573
+ const code = editor.value;
574
+ const desc = (code.split('\n').filter(l => l.trim() && !l.trim().startsWith('#'))[0] || 'untitled').replace(/^def\s+|^class\s+|^#\s*/g, '').trim().slice(0, 60) || 'untitled';
575
+ meshPublishBtn.textContent = '&#x1F4E4; Publishing...';
576
+ meshPublishBtn.disabled = true;
577
+ await api('/api/mesh/share', {
578
+ name: desc,
579
+ content: code,
580
+ type: 'project',
581
+ share_benchmarks: meshToggleBench ? meshToggleBench.checked : true,
582
+ share_dreams: meshToggleDreams ? meshToggleDreams.checked : false,
583
+ share_stats: meshToggleStats ? meshToggleStats.checked : false,
584
+ });
585
+ meshPublishBtn.textContent = '&#x2713; Published';
586
+ setTimeout(() => {
587
+ meshPublishBtn.textContent = '&#x1F4E4; Publish Current Project';
588
+ meshPublishBtn.disabled = false;
589
+ }, 2000);
590
+ pollMesh();
591
+ });
592
+ }
593
+
594
+ // Chimera cross-node insights — triggered when editor content changes
595
+ let insightTimer = null;
596
+ if (editor && meshInsights) {
597
+ editor.addEventListener('input', () => {
598
+ clearTimeout(insightTimer);
599
+ insightTimer = setTimeout(async () => {
600
+ const code = editor.value.trim();
601
+ if (code.length < 30) return;
602
+ const result = await api('/api/mesh/related', { text: code.slice(0, 500) });
603
+ if (result.related && result.related.length > 0) {
604
+ meshInsights.innerHTML = result.related.map(r =>
605
+ '<div class="mesh-insight-card">' +
606
+ '<div class="mesh-insight-card-title">&#x1F4AD; ' + escapeHtml(r.name) + '</div>' +
607
+ '<div class="mesh-insight-card-desc">' + escapeHtml(r.description || 'Related public project') + ' &middot; node ' + (r.node_id ? r.node_id.slice(0, 8) + '..' : '—') + '</div>' +
608
+ '</div>'
609
+ ).join('');
610
+ } else {
611
+ meshInsights.innerHTML = '<div class="mesh-feed-empty">&#x1F4AD; Working on something? Chimera will search the mesh for related public work.</div>';
612
+ }
613
+ }, 1500);
614
+ });
615
+ }
616
+
617
+ setInterval(pollMesh, 5000);
618
+
619
+ // ── Device: APK Builder ──
620
+ const deviceSdk = document.getElementById('device-sdk');
621
+ const deviceAdb = document.getElementById('device-adb');
622
+ const deviceGradle = document.getElementById('device-gradle');
623
+ const deviceDevices = document.getElementById('device-devices');
624
+ const deviceOutput = document.getElementById('device-output');
625
+ const deviceApkStatus = document.getElementById('device-apk-status');
626
+ const deviceVerifyOutput = document.getElementById('device-verify-output');
627
+ const deviceGenBtn = document.getElementById('device-gen-btn');
628
+ const deviceBuildBtn = document.getElementById('device-build-btn');
629
+ const deviceVerifyBtn = document.getElementById('device-verify-btn');
630
+ const deviceInstallBtn = document.getElementById('device-install-btn');
631
+
632
+ let currentApk = null;
633
+
634
+ function deviceWrite(text, cls = '') {
635
+ if (!deviceOutput) return;
636
+ if (deviceOutput.querySelector('.device-output-empty')) {
637
+ deviceOutput.innerHTML = '';
638
+ }
639
+ const d = document.createElement('div');
640
+ d.className = 'device-output-line ' + cls;
641
+ d.textContent = text;
642
+ deviceOutput.appendChild(d);
643
+ deviceOutput.scrollTop = deviceOutput.scrollHeight;
644
+ }
645
+
646
+ async function pollDevice() {
647
+ const env = await api('/api/android/env');
648
+ if (deviceSdk) {
649
+ deviceSdk.textContent = env.sdk ? 'installed' : 'not found';
650
+ deviceSdk.className = 'device-value' + (env.sdk ? ' good' : ' bad');
651
+ }
652
+ if (deviceAdb) {
653
+ deviceAdb.textContent = env.adb ? 'available' : 'not found';
654
+ deviceAdb.className = 'device-value' + (env.adb ? ' good' : ' bad');
655
+ }
656
+ if (deviceGradle) {
657
+ deviceGradle.textContent = env.gradle || 'not found';
658
+ deviceGradle.className = 'device-value' + (env.gradle ? ' good' : ' bad');
659
+ }
660
+ if (deviceDevices) {
661
+ deviceDevices.textContent = (env.devices || 0) + ' connected';
662
+ deviceDevices.className = 'device-value' + (env.devices > 0 ? ' good' : '');
663
+ }
664
+ }
665
+
666
+ if (deviceGenBtn) {
667
+ deviceGenBtn.addEventListener('click', async () => {
668
+ const name = document.getElementById('device-app-name').value || 'FSIApp';
669
+ const pkg = document.getElementById('device-package').value || 'com.fsi.app';
670
+ const activity = document.getElementById('device-activity').value || 'MainActivity';
671
+ deviceWrite('Generating project: ' + name + '...', 'info');
672
+ deviceGenBtn.disabled = true;
673
+ const result = await api('/api/android/generate', { name, package: pkg, activity });
674
+ if (result.success) {
675
+ deviceWrite('Project generated: ' + result.path, 'success');
676
+ } else {
677
+ deviceWrite(result.error || 'Generation failed', 'error');
678
+ }
679
+ deviceGenBtn.disabled = false;
680
+ });
681
+ }
682
+
683
+ if (deviceBuildBtn) {
684
+ deviceBuildBtn.addEventListener('click', async () => {
685
+ const name = document.getElementById('device-app-name').value || 'FSIApp';
686
+ const pkg = document.getElementById('device-package').value || 'com.fsi.app';
687
+ const activity = document.getElementById('device-activity').value || 'MainActivity';
688
+ deviceWrite('Building APK: ' + name + '...', 'info');
689
+ deviceWrite('First build takes 3-5 min (downloads deps)...', 'info');
690
+ deviceBuildBtn.disabled = true;
691
+ deviceBuildBtn.textContent = '⚙️ Building...';
692
+ const result = await api('/api/android/build', { name, package: pkg, activity });
693
+ if (result.success && result.apk) {
694
+ currentApk = result.apk;
695
+ deviceWrite('APK built: ' + result.apk, 'success');
696
+ deviceWrite('Size: ' + (result.size_mb || '?') + ' MB', 'info');
697
+ deviceApkStatus.textContent = 'APK ready: ' + result.apk;
698
+ deviceVerifyBtn.disabled = false;
699
+ deviceInstallBtn.disabled = false;
700
+ } else {
701
+ deviceWrite(result.error || 'Build failed', 'error');
702
+ }
703
+ deviceBuildBtn.disabled = false;
704
+ deviceBuildBtn.textContent = '🔥 Build APK';
705
+ });
706
+ }
707
+
708
+ if (deviceVerifyBtn) {
709
+ deviceVerifyBtn.addEventListener('click', async () => {
710
+ deviceVerifyBtn.disabled = true;
711
+ deviceVerifyOutput.textContent = 'Verifying...';
712
+ const result = await api('/api/android/verify');
713
+ if (result.valid) {
714
+ deviceVerifyOutput.innerHTML =
715
+ '✓ Valid APK\n' +
716
+ 'Package: ' + (result.package || '—') + '\n' +
717
+ 'Version: ' + (result.version_name || '—') + ' (' + (result.version_code || '—') + ')\n' +
718
+ 'Min SDK: ' + (result.min_sdk || '—') + '\n' +
719
+ 'Target SDK: ' + (result.target_sdk || '—') + '\n' +
720
+ 'Activity: ' + (result.activity || '—') + '\n' +
721
+ 'Size: ' + (result.size ? (result.size / 1024 / 1024).toFixed(2) + ' MB' : '—');
722
+ } else {
723
+ deviceVerifyOutput.textContent = '✗ ' + (result.error || 'Verification failed');
724
+ }
725
+ deviceVerifyBtn.disabled = false;
726
+ });
727
+ }
728
+
729
+ if (deviceInstallBtn) {
730
+ deviceInstallBtn.addEventListener('click', async () => {
731
+ deviceInstallBtn.disabled = true;
732
+ deviceInstallBtn.textContent = '⏳ Installing...';
733
+ const result = await api('/api/android/install');
734
+ if (result.success) {
735
+ deviceVerifyOutput.textContent = '✓ Installed successfully';
736
+ } else {
737
+ deviceVerifyOutput.textContent = '✗ ' + (result.error || 'Install failed');
738
+ }
739
+ deviceInstallBtn.disabled = false;
740
+ deviceInstallBtn.textContent = '📤 Install';
741
+ });
742
+ }
743
+
744
+ setInterval(pollDevice, 10000);
745
+
746
+ // ── Initial vault load ──
747
+ loadVaultTree();
748
+ });