| 1 | // Crea una app de complejidad media (varios ficheros, varias funciones) con |
| 2 | // el modelo REAL (Gemma-4, no el modo básico), sacando una captura cada |
| 3 | // pocos segundos mientras trabaja — abriendo distintos ficheros conforme van |
| 4 | // apareciendo, para que se vea tanto el chat como el código real. Al final |
| 5 | // monta esas capturas en un GIF animado del proceso completo (ffmpeg). |
| 6 | import { chromium } from 'playwright'; |
| 7 | import { CHROME_ARGS } from './chrome-args.mjs'; |
| 8 | import { execFileSync } from 'node:child_process'; |
| 9 | import { mkdirSync, readdirSync } from 'node:fs'; |
| 10 | |
| 11 | const OUT = (process.env.SCRATCH || '/tmp/elffuss-test') + '/appbuild'; |
| 12 | const FRAMES = OUT + '/frames'; |
| 13 | mkdirSync(FRAMES, { recursive: true }); |
| 14 | const BASE = process.env.BASE || 'https://code.elffuss.com'; |
| 15 | const INTERVAL_MS = 3000; |
| 16 | |
| 17 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 18 | |
| 19 | async function waitIdle(p, maxMs = 180000) { |
| 20 | const t0 = Date.now(); |
| 21 | while (Date.now() - t0 < maxMs) { |
| 22 | const sending = await p.locator('#btn-send.sending').count().catch(() => 0); |
| 23 | if (!sending) return true; |
| 24 | await p.waitForTimeout(500); |
| 25 | } |
| 26 | return false; |
| 27 | } |
| 28 | |
| 29 | const PROFILE = (process.env.SCRATCH || '/tmp/elffuss-test') + '/profile-code-gemma'; |
| 30 | const ctx = await chromium.launchPersistentContext(PROFILE, { |
| 31 | args: ['--autoplay-policy=no-user-gesture-required', '--enable-unsafe-webgpu', ...CHROME_ARGS], |
| 32 | viewport: { width: 1440, height: 900 }, |
| 33 | }); |
| 34 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'litert:gemma-e2b'); } catch {} }); |
| 35 | const p = ctx.pages()[0] || await ctx.newPage(); |
| 36 | p.on('pageerror', e => console.log(' pageerror:', e.message.slice(0, 160))); |
| 37 | |
| 38 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 39 | await p.waitForTimeout(2000); |
| 40 | await p.evaluate(async () => { |
| 41 | const root = await navigator.storage.getDirectory(); |
| 42 | for await (const name of root.keys()) await root.removeEntry(name, { recursive: true }).catch(() => {}); |
| 43 | const ide = await import('/js/ide.js'); |
| 44 | await ide.refreshTree(root); |
| 45 | }); |
| 46 | // el perfil persistente (para no re-descargar el modelo) también acumula el |
| 47 | // HISTORIAL DE CHAT de ejecuciones anteriores en IndexedDB — sin limpiarlo, |
| 48 | // el modelo hereda contexto viejo (ficheros/rutas de otras pruebas) y se |
| 49 | // confunde. Se limpia aparte del árbol de ficheros y se recarga. |
| 50 | await p.evaluate(async () => { |
| 51 | const db = await import('/js/db.js'); |
| 52 | await db.del('kv', 'conversations').catch(() => {}); |
| 53 | try { localStorage.removeItem('elffusscode.openTabs'); localStorage.removeItem('elffusscode.activeConv'); } catch {} |
| 54 | }); |
| 55 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 56 | await p.waitForTimeout(1500); |
| 57 | console.log('1) proyecto vacío + conversación limpia'); |
| 58 | |
| 59 | console.log('2) cargando Gemma-4 E2B real…'); |
| 60 | let loaded = false; |
| 61 | { |
| 62 | const t0 = Date.now(); |
| 63 | while (Date.now() - t0 < 300000) { |
| 64 | const cls = await p.locator('#model-dot').getAttribute('class').catch(() => ''); |
| 65 | if (cls && /\bon\b/.test(cls)) { loaded = true; break; } |
| 66 | await p.waitForTimeout(1000); |
| 67 | } |
| 68 | } |
| 69 | if (!loaded) throw new Error('Gemma NO cargó a tiempo'); |
| 70 | console.log('3) Gemma-4 cargado'); |
| 71 | |
| 72 | // --- captura periódica EN PARALELO: cada INTERVAL_MS, si hay un fichero |
| 73 | // nuevo en el árbol que aún no se ha enseñado, lo abre antes de capturar — |
| 74 | // así el GIF va alternando chat + ficheros reales conforme se crean. |
| 75 | let frameN = 0, capturing = true; |
| 76 | const shown = new Set(); |
| 77 | async function treeFiles() { |
| 78 | // data-path (no el texto visible: ese lleva el icono pegado al nombre, p.ej. "JSapp.js") |
| 79 | return p.locator('#tree .file').evaluateAll(els => els.map(e => e.dataset.path).filter(Boolean)); |
| 80 | } |
| 81 | async function openFile(path) { |
| 82 | return p.locator(`#tree .file[data-path="${path}"]`).first().click({ force: true }).catch(() => {}); |
| 83 | } |
| 84 | async function captureLoop() { |
| 85 | while (capturing) { |
| 86 | try { |
| 87 | const files = await treeFiles(); |
| 88 | const fresh = files.find(f => !shown.has(f)); |
| 89 | if (fresh) { |
| 90 | await openFile(fresh); |
| 91 | shown.add(fresh); |
| 92 | await p.waitForTimeout(200); |
| 93 | } |
| 94 | } catch { /* árbol repintándose, sigue */ } |
| 95 | frameN++; |
| 96 | await p.screenshot({ path: `${FRAMES}/f${String(frameN).padStart(3, '0')}.png` }).catch(() => {}); |
| 97 | await new Promise(r => setTimeout(r, INTERVAL_MS)); |
| 98 | } |
| 99 | } |
| 100 | const loopDone = captureLoop(); |
| 101 | |
| 102 | // Se pide en VARIOS turnos (uno por fichero) en vez de todo de golpe: un |
| 103 | // modelo pequeño local corta el JSON a mitad de generación si le pides los |
| 104 | // 3 ficheros en una sola respuesta (límite de tokens), y el parser no puede |
| 105 | // rescatar nada de un tool-call incompleto — no escribe NADA. Por turnos, |
| 106 | // cada respuesta es corta y cabe entera; además da más momentos distintos |
| 107 | // para las capturas (más realista: así se construye una app de verdad). |
| 108 | // MUY conciso a propósito: el modelo local corta la generación si el |
| 109 | // contenido de un fichero es largo (HTML/CSS/JS "normales" ya bastan para |
| 110 | // truncar el JSON del tool-call a medio camino) — pidiendo código mínimo, |
| 111 | // sin comentarios, cabe entero en una generación. |
| 112 | const PROMPTS = [ |
| 113 | 'Crea index.html mínimo (15 líneas máx, sin comentarios) para una lista de tareas: input#nueva, botón#add, <ul id="lista">. Enlaza style.css y app.js.', |
| 114 | 'Ahora style.css mínimo (15 líneas máx, sin comentarios): tema oscuro simple, .done con text-decoration:line-through.', |
| 115 | 'Ahora app.js mínimo (20 líneas máx, sin comentarios): al pulsar #add, añade un <li> a #lista con el texto de #nueva y un botón «x» para borrarlo; click en el <li> alterna la clase done. Guarda y carga el array en localStorage.', |
| 116 | ]; |
| 117 | let allIdle = true; |
| 118 | for (let i = 0; i < PROMPTS.length; i++) { |
| 119 | await p.click('#prompt'); |
| 120 | await p.type('#prompt', PROMPTS[i], { delay: 15 }); |
| 121 | await p.press('#prompt', 'Enter'); |
| 122 | console.log(`4.${i + 1}) turno ${i + 1}/${PROMPTS.length} — ${PROMPTS[i].slice(0, 40)}…`); |
| 123 | const idle = await waitIdle(p, 120000); |
| 124 | if (!idle) allIdle = false; |
| 125 | await p.waitForTimeout(1000); |
| 126 | } |
| 127 | ok('la elfa terminó los 3 turnos sin quedarse colgada', allIdle); |
| 128 | |
| 129 | // unos frames finales mostrando cada fichero creado, uno a uno |
| 130 | const finalFiles = await treeFiles(); |
| 131 | for (const f of finalFiles) { |
| 132 | await openFile(f); |
| 133 | await p.waitForTimeout(500); |
| 134 | frameN++; |
| 135 | await p.screenshot({ path: `${FRAMES}/f${String(frameN).padStart(3, '0')}.png` }).catch(() => {}); |
| 136 | } |
| 137 | |
| 138 | capturing = false; |
| 139 | await loopDone; |
| 140 | console.log(`5) captura terminada — ${frameN} frames`); |
| 141 | |
| 142 | // --- el "resultado" de verdad: la app RENDERIZADA, no solo el código fuente |
| 143 | // (Vista previa del index.html), con una interacción real para probar que |
| 144 | // funciona — sin esto el GIF nunca enseña lo que se construyó, solo cómo. |
| 145 | let previewOk = false; |
| 146 | try { |
| 147 | await p.locator('#tabs-bar .tab', { hasText: 'index.html' }).click({ button: 'right' }); |
| 148 | await p.waitForTimeout(200); |
| 149 | await p.click('#tab-menu .tm-item:has-text("Vista previa")'); |
| 150 | await p.waitForTimeout(700); |
| 151 | frameN++; |
| 152 | await p.screenshot({ path: `${FRAMES}/f${String(frameN).padStart(3, '0')}.png` }).catch(() => {}); |
| 153 | |
| 154 | const frame = p.frameLocator('#md-preview-pane iframe'); |
| 155 | await frame.locator('#nueva').fill('Comprar pan', { timeout: 5000 }); |
| 156 | await frame.locator('#add').click({ timeout: 5000 }); |
| 157 | await p.waitForTimeout(400); |
| 158 | const liText = await frame.locator('#lista').innerText().catch(() => ''); |
| 159 | previewOk = /Comprar pan/.test(liText); |
| 160 | frameN++; |
| 161 | await p.screenshot({ path: `${FRAMES}/f${String(frameN).padStart(3, '0')}.png` }).catch(() => {}); |
| 162 | // un pelín más de vida: márcala como completada si el CSS .done existe |
| 163 | await frame.locator('#lista li').first().click({ timeout: 3000 }).catch(() => {}); |
| 164 | await p.waitForTimeout(400); |
| 165 | frameN++; |
| 166 | await p.screenshot({ path: `${FRAMES}/f${String(frameN).padStart(3, '0')}.png` }).catch(() => {}); |
| 167 | } catch (e) { console.log(' (vista previa interactiva falló:', e.message.slice(0, 150), ')'); } |
| 168 | ok('la app RENDERIZADA funciona de verdad (añadir tarea real en la vista previa)', previewOk); |
| 169 | console.log(`6) vista previa capturada — ${frameN} frames en total`); |
| 170 | |
| 171 | // --- diagnóstico: verdad de OPFS + historial real del agente, sin fiarse |
| 172 | // solo del DOM del árbol (por si acaso no se ha refrescado) --- |
| 173 | const opfsFiles = await p.evaluate(async () => (await (await import('/js/tools/code.js')).fileList())); |
| 174 | console.log('DIAG opfsFiles:', JSON.stringify(opfsFiles)); |
| 175 | const histTail = await p.evaluate(async () => { |
| 176 | const conv = await import('/js/conversations.js'); |
| 177 | const active = conv.getActive(); |
| 178 | return (active?.agent?.history || []).slice(-6).map(m => ({ role: m.role, content: String(m.content).slice(0, 2000) })); |
| 179 | }); |
| 180 | console.log('DIAG historyTail:', JSON.stringify(histTail, null, 2)); |
| 181 | |
| 182 | // --- comprobaciones sobre lo construido de verdad --- |
| 183 | ok('creó VARIOS ficheros (complejidad media, no uno solo)', finalFiles.length >= 3, finalFiles.join(', ')); |
| 184 | ok('index.html está entre los creados', finalFiles.some(f => /index\.html/i.test(f))); |
| 185 | ok('hay CSS y JS reales (no solo el HTML)', finalFiles.some(f => /\.css$/i.test(f)) && finalFiles.some(f => /\.js$/i.test(f))); |
| 186 | |
| 187 | const jsFile = finalFiles.find(f => /\.js$/i.test(f)); |
| 188 | if (jsFile) { |
| 189 | try { |
| 190 | const jsContent = await p.evaluate(async f => (await (await import('/js/tools/code.js')).read({ path: f })), jsFile); |
| 191 | ok('el JS real menciona localStorage (persistencia pedida)', /localStorage/.test(jsContent), jsFile); |
| 192 | } catch (e) { ok('el JS real menciona localStorage (persistencia pedida)', false, e.message.slice(0, 100)); } |
| 193 | } |
| 194 | |
| 195 | const toolCalls = await p.locator('#chat-log .msg.tool').count(); |
| 196 | ok('el chat muestra tool-calls reales de code.write', toolCalls >= 3, String(toolCalls)); |
| 197 | |
| 198 | await ctx.close(); |
| 199 | |
| 200 | // --- monta el GIF con ffmpeg (paleta optimizada, más ligero que un GIF ingenuo) --- |
| 201 | const frameFiles = readdirSync(FRAMES).filter(f => f.endsWith('.png')).sort(); |
| 202 | ok(`hay frames capturados de verdad (${frameFiles.length})`, frameFiles.length >= 3); |
| 203 | |
| 204 | const gifPath = OUT + '/proceso.gif'; |
| 205 | try { |
| 206 | execFileSync('ffmpeg', ['-y', '-framerate', '1.2', '-i', `${FRAMES}/f%03d.png`, |
| 207 | '-vf', 'scale=900:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse', |
| 208 | gifPath], { stdio: 'pipe' }); |
| 209 | ok('el GIF del proceso se generó', true); |
| 210 | } catch (e) { |
| 211 | ok('el GIF del proceso se generó', false, e.message.slice(0, 200)); |
| 212 | } |
| 213 | |
| 214 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ APP DE COMPLEJIDAD MEDIA + CAPTURAS PERIÓDICAS + GIF OK'); |
| 215 | console.log('GIF en:', gifPath); |
| 216 | process.exit(fails ? 1 : 0); |