Elffuss BraidHub

utopia-ia/elffuss-code public

main · 7.0 KiBRawPermalink
1// Clonar un repo público (GitHub) y abrirlo como proyecto — RESUMIBLE. Usa un
2// repo real, público y estable (octocat/Spoon-Knife, 3 ficheros) para validar
3// contra la red de verdad, no simulada. showDirectoryPicker se sustituye por
4// una carpeta OPFS persistente (el picker nativo del SO no es automatizable),
5// que sobrevive a recargas de página — igual que una carpeta real en disco.
6import { chromium } from 'playwright';
7const BASE = process.env.BASE || 'http://localhost:8799';
8const REPO_URL = 'https://github.com/octocat/Spoon-Knife';
9let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
10
11const b = await chromium.launch();
12const ctx = await b.newContext();
13await ctx.addInitScript(() => {
14 try { localStorage.setItem('elffusscode.model', 'rules'); } catch {}
15 window.showDirectoryPicker = async () => {
16 const opfs = await navigator.storage.getDirectory();
17 return opfs.getDirectoryHandle('clone-test-dir', { create: true });
18 };
19});
20const p = await ctx.newPage({ viewport: { width: 1300, height: 850 } });
21p.on('console', m => { if (m.type() === 'error') console.log(' err:', m.text().slice(0, 140)); });
22
23const dirNames = () => p.evaluate(async () => {
24 const o = await navigator.storage.getDirectory();
25 const dir = await o.getDirectoryHandle('clone-test-dir', { create: true });
26 const names = []; for await (const e of dir.values()) names.push(e.name);
27 return names.sort();
28});
29const readFile = name => p.evaluate(async (n) => {
30 const o = await navigator.storage.getDirectory();
31 const dir = await o.getDirectoryHandle('clone-test-dir', { create: true });
32 return (await (await dir.getFileHandle(n)).getFile()).text();
33}, name);
34
35// ── clonado básico: repo REAL, contenido REAL ──────────────────────────────
36await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(600);
37await p.fill('#clone-url', REPO_URL);
38await p.click('#clone-btn');
39await p.waitForFunction(() => !document.getElementById('ide').hidden, null, { timeout: 30000 }).catch(() => {});
40ok('el IDE se abre tras clonar', await p.evaluate(() => !document.getElementById('ide').hidden));
41const files1 = await dirNames();
42ok('los 3 ficheros REALES del repo se descargaron', files1.join(',') === 'README.md,index.html,styles.css', files1.join(','));
43const readme1 = await readFile('README.md');
44ok('el contenido es el REAL del repo (no inventado)', /Well hello there|Spoon-Knife|forking/i.test(readme1), readme1.slice(0, 50));
45
46// ── resumibilidad: descarga a medias (1/3) → reanudar → completa ──────────
47await p.evaluate(async () => {
48 // limpiar la carpeta y dejar SOLO 1 de los 3 ficheros, como si la descarga
49 // se hubiera cortado ahí (simula "el usuario cerró a media descarga")
50 const o = await navigator.storage.getDirectory();
51 try { await o.removeEntry('clone-test-dir', { recursive: true }); } catch {}
52 const dir = await o.getDirectoryHandle('clone-test-dir', { create: true });
53 const fh = await dir.getFileHandle('README.md', { create: true });
54 const w = await fh.createWritable(); await w.write('contenido a medias, de la sesión anterior'); await w.close();
55});
56await p.evaluate(async (repoUrl) => {
57 const db = await import('/js/db.js');
58 // simula una descarga REALMENTE interrumpida: enterIDE() nunca llegó a
59 // llamarse, así que no debe quedar un «project» previo (si no,
60 // restoreProject() reabriría la IDE de golpe y taparía el banner)
61 await db.del('kv', 'project').catch(() => {});
62 const opfs = await navigator.storage.getDirectory();
63 const handle = await opfs.getDirectoryHandle('clone-test-dir', { create: true });
64 const job = {
65 url: repoUrl, handle, host: 'github', owner: 'octocat', repo: 'Spoon-Knife', branch: 'main', skipped: 0,
66 files: [{ path: 'README.md', size: 780 }, { path: 'index.html', size: 355 }, { path: 'styles.css', size: 256 }],
67 done: ['README.md'], // solo 1 de 3 quedó hecho antes de «cerrar la pestaña»
68 };
69 await db.set('kv', 'cloneJob', job);
70}, REPO_URL);
71
72// nueva "sesión": recargar la página desde cero (como si el usuario volviera)
73await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(600);
74ok('al volver, aparece el banner de reanudar (no fuerza empezar de cero)', await p.locator('#resume-clone:not([hidden])').count() > 0);
75const bannerText = await p.locator('#resume-clone .rc-text').innerText();
76ok('el banner muestra el progreso correcto (1/3)', /1\/3/.test(bannerText), bannerText);
77
78// las peticiones a README.md NO deben repetirse al reanudar (ya estaba hecho)
79const refetched = [];
80p.on('request', req => { if (/raw\.githubusercontent\.com.*README\.md/.test(req.url())) refetched.push(req.url()); });
81await p.click('#resume-clone-btn');
82await p.waitForFunction(() => !document.getElementById('ide').hidden, null, { timeout: 30000 }).catch(() => {});
83ok('README.md NO se vuelve a descargar al reanudar (ya estaba hecho)', refetched.length === 0, `${refetched.length} peticiones`);
84const filesResumed = await dirNames();
85ok('tras reanudar, los 3 ficheros están completos', filesResumed.join(',') === 'README.md,index.html,styles.css', filesResumed.join(','));
86const readme2 = await readFile('README.md');
87ok('el fichero ya-hecho conserva SU contenido (no se pisó con uno nuevo)', readme2 === 'contenido a medias, de la sesión anterior', readme2);
88const styles = await readFile('styles.css');
89ok('el fichero pendiente sí se descargó de verdad (contenido real, no vacío)', styles.length > 10, styles.slice(0, 30));
90const jobAfter = await p.evaluate(async () => { const db = await import('/js/db.js'); return db.get('kv', 'cloneJob').catch(() => null); });
91ok('el trabajo se limpia de IndexedDB al completarse', !jobAfter);
92
93// ── descartar: no descarga nada, limpia el job ─────────────────────────────
94await p.evaluate(async (repoUrl) => {
95 const db = await import('/js/db.js');
96 await db.del('kv', 'project').catch(() => {});
97 const opfs = await navigator.storage.getDirectory();
98 const handle = await opfs.getDirectoryHandle('clone-test-dir', { create: true });
99 await db.set('kv', 'cloneJob', { url: repoUrl, handle, host: 'github', owner: 'octocat', repo: 'Spoon-Knife', branch: 'main', files: [{ path: 'a', size: 1 }, { path: 'b', size: 1 }], done: [] });
100}, REPO_URL);
101await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(600);
102await p.click('#discard-clone-btn');
103await p.waitForTimeout(200);
104ok('«Descartar» oculta el banner', await p.evaluate(() => document.getElementById('resume-clone').hidden));
105const jobDiscarded = await p.evaluate(async () => { const db = await import('/js/db.js'); return db.get('kv', 'cloneJob').catch(() => null); });
106ok('«Descartar» limpia el trabajo de IndexedDB', !jobDiscarded);
107
108console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CLONAR REPO (real + resumible) OK');
109await b.close();
110process.exit(fails ? 1 : 0);