| 1 | // ⛏ Hard Work con un cerebro de prueba (proveedor «Ollama local» apuntando a un |
| 2 | // servidor de mentira compatible con OpenAI, en un puerto que da el sistema). |
| 3 | // · Es para el PRÓXIMO mensaje que escribes: aria-pressed, y se apaga al |
| 4 | // mandarlo. Los chips no lo gastan ni van por Hard Work. |
| 5 | // · Cuenta lo que pasó: rondas de mejora reales, «solo el borrador» si la |
| 6 | // reescritura no salió, y el error si la app no se pudo guardar. |
| 7 | // · Con carpeta, no lee los ficheros que parecen secretos (.env). |
| 8 | // · Un mensaje de Hard Work que espera en la cola lo sigue siendo tras recargar. |
| 9 | // |
| 10 | // BASE=http://localhost:8743 node tests/ux-hardwork.mjs |
| 11 | import { createServer } from 'node:http'; |
| 12 | import { navegador, contexto, ok, hasta, espera, escribir, reposo, fin, BASE } from './ux-comun.mjs'; |
| 13 | |
| 14 | const peticiones = []; // { sistema, usuario } |
| 15 | let reescrituraMala = false; |
| 16 | const HTML = cuerpo => `<!doctype html><html><head><title>naves</title></head><body>${cuerpo}</body></html>`; |
| 17 | const servidor = createServer((req, res) => { |
| 18 | const cors = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'content-type, authorization', 'Access-Control-Allow-Methods': 'POST, OPTIONS' }; |
| 19 | if (req.method === 'OPTIONS') { res.writeHead(204, cors); res.end(); return; } |
| 20 | let cuerpo = ''; |
| 21 | req.on('data', d => { cuerpo += d; }); |
| 22 | req.on('end', () => { |
| 23 | let msgs = []; |
| 24 | try { msgs = JSON.parse(cuerpo).messages || []; } catch { /* */ } |
| 25 | const sistema = msgs.find(m => m.role === 'system')?.content || ''; |
| 26 | const usuario = msgs.filter(m => m.role === 'user').map(m => m.content).join('\n'); |
| 27 | peticiones.push({ sistema, usuario }); |
| 28 | let out = 'respuesta normal'; |
| 29 | if (/crítico de videojuegos/.test(sistema)) out = '1. le falta color'; |
| 30 | else if (/mejorando tu propia app/.test(sistema)) out = reescrituraMala ? 'no sé hacerlo' : HTML('MEJORADA'); |
| 31 | else if (/creando una app web/.test(sistema)) out = HTML('BORRADOR'); |
| 32 | else if (/analista|sintetizador/.test(sistema)) out = 'resumen de la parte'; |
| 33 | const responder = () => { |
| 34 | res.writeHead(200, { ...cors, 'Content-Type': 'text/event-stream' }); |
| 35 | res.write(`data: ${JSON.stringify({ choices: [{ delta: { content: out } }] })}\n\n`); |
| 36 | res.write('data: [DONE]\n\n'); |
| 37 | res.end(); |
| 38 | }; |
| 39 | // «LENTO»: un turno que tarda, para que lo siguiente espere en la cola. |
| 40 | if (/LENTO/.test(usuario.split('\n').at(-1) || '')) setTimeout(responder, 3000); else responder(); |
| 41 | }); |
| 42 | }); |
| 43 | await new Promise(r => servidor.listen(0, '127.0.0.1', r)); |
| 44 | const PUERTO = servidor.address().port; |
| 45 | |
| 46 | const b = await navegador(); |
| 47 | const { ctx } = await contexto(b, { |
| 48 | model: 'ext:ollama', grants: ['apps'], |
| 49 | extraInit: { 'elffuss.providers': JSON.stringify({ ollama: { enabled: true, baseURL: `http://localhost:${PUERTO}/v1`, model: 'falso', apiKey: 'ollama' } }) }, |
| 50 | }); |
| 51 | const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } }); |
| 52 | const errores = []; |
| 53 | p.on('pageerror', e => { if (!/allow-same-origin/.test(e.message)) errores.push(e.message); }); |
| 54 | await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); |
| 55 | ok('el cerebro de prueba queda cargado', await hasta(() => p.evaluate(() => |
| 56 | document.getElementById('model-select')?.value === 'ext:ollama' && document.getElementById('model-status')?.classList.contains('on')))); |
| 57 | const hw = p.locator('#btn-hardwork'); |
| 58 | const pulsado = async () => await hw.getAttribute('aria-pressed'); |
| 59 | const ultimoAsistente = () => p.locator('#log .msg.assistant').last().innerText(); |
| 60 | |
| 61 | ok('el botón dice su estado (aria-pressed=false) y tiene título traducido', await pulsado() === 'false' && /próximo mensaje/.test(await hw.getAttribute('title'))); |
| 62 | await hw.click(); |
| 63 | ok('al pulsarlo: aria-pressed=true y la caja lo dice', await pulsado() === 'true' && /Hard Work para este mensaje/.test(await p.getAttribute('#prompt', 'placeholder'))); |
| 64 | |
| 65 | // ── un mensaje con Hard Work: rondas reales, y se apaga solo ──────────────── |
| 66 | let desde = peticiones.length; |
| 67 | await escribir(p, 'hazme un juego de naves'); |
| 68 | ok('…y al mandarlo se apaga (era para ese mensaje)', await pulsado() === 'false'); |
| 69 | ok('trabaja en dos pasadas y lo dice con las rondas que hubo', await hasta(async () => /rondas de mejora: 1/.test(await ultimoAsistente()))); |
| 70 | ok('la app guardada es la mejorada', await p.evaluate(() => /MEJORADA/.test(document.getElementById('appframe').srcdoc))); |
| 71 | ok('(borrador, crítica y reescritura: 3 llamadas)', peticiones.length - desde === 3, `${peticiones.length - desde}`); |
| 72 | await reposo(p); |
| 73 | |
| 74 | // ── los chips no gastan ni usan Hard Work ─────────────────────────────────── |
| 75 | await hw.click(); |
| 76 | desde = peticiones.length; |
| 77 | await p.locator('#chips .chip', { hasText: 'Crea una app de notas' }).click(); |
| 78 | await reposo(p); |
| 79 | ok('con Hard Work puesto, un chip va como mensaje normal', peticiones.slice(desde).every(x => /^Eres Elffuss: un sistema operativo/.test(x.sistema)) && peticiones.length > desde); |
| 80 | ok('…y Hard Work sigue puesto para lo que escribas', await pulsado() === 'true'); |
| 81 | |
| 82 | // ── la reescritura no sale: «solo el borrador» ────────────────────────────── |
| 83 | reescrituraMala = true; |
| 84 | await escribir(p, 'hazme otro juego'); |
| 85 | ok('si la reescritura no sale, dice que solo hizo el borrador', await hasta(async () => /solo el borrador/.test(await ultimoAsistente()))); |
| 86 | reescrituraMala = false; |
| 87 | await reposo(p); |
| 88 | |
| 89 | // ── no se puede guardar la app: lo dice ───────────────────────────────────── |
| 90 | await p.evaluate(async () => (await import('/js/permissions.js')).revoke('apps')); |
| 91 | await hw.click(); |
| 92 | await escribir(p, 'hazme un tercer juego'); |
| 93 | await hasta(() => p.evaluate(() => document.getElementById('perm-dialog').open)); |
| 94 | await p.keyboard.press('Escape'); // denegar el permiso de Apps |
| 95 | ok('si la app no se puede guardar, lo dice (y no «Listo»)', await hasta(async () => |
| 96 | /no pude guardar la app/.test(await p.locator('#log .msg.assistant.err').last().innerText().catch(() => '')))); |
| 97 | await reposo(p); |
| 98 | |
| 99 | // ── un mensaje de Hard Work que espera en la cola sigue siéndolo tras recargar ─ |
| 100 | // (antes la cola guardaba solo el texto y, al recargar, iba como chat normal) |
| 101 | await espera(300); |
| 102 | if (await p.evaluate(() => document.getElementById('perm-dialog').open)) await p.click('#perm-deny'); |
| 103 | await escribir(p, 'LENTO turno normal'); |
| 104 | await hasta(() => peticiones.some(x => /LENTO turno normal/.test(x.usuario))); |
| 105 | if (await pulsado() !== 'true') await hw.click(); |
| 106 | await escribir(p, 'hazme un juego de naves EN-COLA'); |
| 107 | const cola = await p.evaluate(async () => (await import('/js/db.js')).get('kv', 'queue')); |
| 108 | ok('el mensaje de Hard Work se guarda en la cola CON su elección', Array.isArray(cola) |
| 109 | && cola.some(x => /EN-COLA/.test(x.text) && x.hard === true), JSON.stringify(cola)); |
| 110 | desde = peticiones.length; |
| 111 | await p.reload({ waitUntil: 'domcontentloaded' }); |
| 112 | ok('tras recargar, va por Hard Work (no como chat normal)', await hasta(() => |
| 113 | peticiones.slice(desde).some(x => /creando una app web/.test(x.sistema) && /EN-COLA/.test(x.usuario)), { veces: 400 }), |
| 114 | JSON.stringify(peticiones.slice(desde).map(x => x.sistema.slice(0, 40) + ' | ' + x.usuario.slice(-30)))); |
| 115 | ok('…y nunca como turno normal', !peticiones.slice(desde).some(x => /^Eres Elffuss: un sistema operativo/.test(x.sistema) && /EN-COLA/.test(x.usuario.split('\n').at(-1)))); |
| 116 | await reposo(p); |
| 117 | |
| 118 | // ── con carpeta: .env no se lee ───────────────────────────────────────────── |
| 119 | await p.evaluate(async () => { |
| 120 | const raiz = await (await navigator.storage.getDirectory()).getDirectoryHandle('proyecto', { create: true }); |
| 121 | const escribe = async (n, t) => { const f = await raiz.getFileHandle(n, { create: true }); const w = await f.createWritable(); await w.write(t); await w.close(); }; |
| 122 | await escribe('README.md', '# Proyecto\nCONTENIDO-LEGIBLE de la documentación.'); |
| 123 | await escribe('.env', 'API_KEY=SECRETO-NO-LEER-123'); |
| 124 | await escribe('credentials.json', '{"token":"OTRO-SECRETO-456"}'); |
| 125 | await (await import('/js/db.js')).set('fs', 'proyecto', raiz); |
| 126 | (await import('/js/permissions.js')).require('fs'); |
| 127 | }); |
| 128 | await espera(200); |
| 129 | if (await p.evaluate(() => document.getElementById('perm-dialog').open)) await p.click('#perm-allow'); |
| 130 | desde = peticiones.length; |
| 131 | await hw.click(); |
| 132 | await escribir(p, '¿de qué va este proyecto?'); |
| 133 | await hasta(async () => /Hard Work \(RLM\)/.test(await p.locator('#log').innerText()), { veces: 300 }); |
| 134 | const enviado = peticiones.slice(desde).map(x => x.usuario).join('\n'); |
| 135 | ok('con carpeta, Hard Work lee los documentos…', /CONTENIDO-LEGIBLE/.test(enviado)); |
| 136 | ok('…pero NO .env ni lo que parece una credencial', !/SECRETO-NO-LEER|OTRO-SECRETO/.test(enviado)); |
| 137 | |
| 138 | ok('sin errores de página', errores.length === 0, errores.slice(0, 3).join(' | ')); |
| 139 | servidor.close(); |
| 140 | await fin(b, 'HARD WORK: para un mensaje, cuenta lo que hizo y no lee secretos'); |