utopia-ia/elffuss-code public
Changesets · Branches · Tags · Compare
| Changeset | ac1cc01879321916c7d5c556223b42849e29def195e160dae6fd1b97a8d81342 |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-10-10 15:43 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-10-11 14:12 +02:00 |
| Parents | 405072fe561a |
4 files changed
added tests/hardwork-queue.mjs +107 −0
| @@ -0,0 +1,107 @@ | ||
| 1 | +// ⛏ Hard Work como un turno MÁS de la conversación: se para con ■ y se guarda. | |
| 2 | +// | |
| 3 | +// Antes runHardWork corría por fuera de la cola: el botón nunca pasaba a ■ (no | |
| 4 | +// había forma de pararlo), la conversación no constaba como ocupada y la | |
| 5 | +// pregunta y la respuesta vivían solo en el DOM, así que desaparecían al | |
| 6 | +// cambiar de pestaña o recargar. Y al apagarlo dejaba un placeholder fijo en | |
| 7 | +// español. | |
| 8 | +// | |
| 9 | +// Proveedor de mentira (sin modelo): contesta a las sub-llamadas del map y del | |
| 10 | +// reduce, lento, y cuenta las llamadas para ver que tras ■ no sale ninguna más. | |
| 11 | +// | |
| 12 | +// BASE=http://127.0.0.1:8898 node tests/hardwork-queue.mjs | |
| 13 | +import { chromium } from 'playwright'; | |
| 14 | +const BASE = process.env.BASE || 'http://localhost:8799'; | |
| 15 | +let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; | |
| 16 | + | |
| 17 | +const b = await chromium.launch(); | |
| 18 | +const ctx = await b.newContext({ locale: 'es-ES' }); | |
| 19 | +await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} }); | |
| 20 | +const p = await ctx.newPage({ viewport: { width: 1400, height: 900 } }); | |
| 21 | +const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 160))); | |
| 22 | + | |
| 23 | +const arranca = async () => { | |
| 24 | + await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); | |
| 25 | + await p.waitForFunction(() => window.elffussClaw?.conv?.getActive?.(), null, { timeout: 15000 }); | |
| 26 | +}; | |
| 27 | +// proyecto sembrado en OPFS (?test-opfs lo abre como carpeta del proyecto) | |
| 28 | +const siembra = (kb) => p.evaluate(async (kb) => { | |
| 29 | + const root = await navigator.storage.getDirectory(); | |
| 30 | + const escribe = async (name, txt) => { const w = await (await root.getFileHandle(name, { create: true })).createWritable(); await w.write(txt); await w.close(); }; | |
| 31 | + const relleno = n => Array.from({ length: n }, (_, i) => `function f${i}() { return ${i}; } // línea de relleno`).join('\n'); | |
| 32 | + await escribe('app.js', relleno(kb * 20)); | |
| 33 | + await escribe('util.js', relleno(kb * 20)); | |
| 34 | + await escribe('README.md', '# Proyecto de prueba\nUsa app.js y util.js.'); | |
| 35 | +}, kb); | |
| 36 | +const ponProveedor = (pausa) => p.evaluate((pausa) => { | |
| 37 | + const dormir = ms => new Promise(r => setTimeout(r, ms)); | |
| 38 | + window.__hw = { llamadas: 0, trasParar: 0, parado: false, abortadas: 0 }; | |
| 39 | + window.elffussClaw.conv.setProvider({ name: 'hw-falso', async chat(h, sys, cb, signal) { | |
| 40 | + window.__hw.llamadas++; | |
| 41 | + if (window.__hw.parado) window.__hw.trasParar++; | |
| 42 | + for (let i = 0; i < 10; i++) { | |
| 43 | + if (signal?.aborted) { window.__hw.abortadas++; throw new DOMException('Parado', 'AbortError'); } | |
| 44 | + await dormir(pausa / 10); | |
| 45 | + } | |
| 46 | + return /sintetizador/.test(sys) ? 'respuesta final de prueba' : 'hallazgo en este trozo'; | |
| 47 | + } }); | |
| 48 | +}, pausa); | |
| 49 | +const hardWork = async (encender) => { | |
| 50 | + const on = await p.evaluate(() => document.getElementById('btn-hardwork').classList.contains('on')); | |
| 51 | + if (on === encender) return; | |
| 52 | + if (await p.locator('#modos-menu').isHidden()) await p.click('#btn-modos'); | |
| 53 | + await p.click('#btn-hardwork'); | |
| 54 | +}; | |
| 55 | + | |
| 56 | +await arranca(); | |
| 57 | +await siembra(2); | |
| 58 | +await ponProveedor(60); | |
| 59 | +await hardWork(true); | |
| 60 | +await p.fill('#prompt', '¿qué hace este proyecto?'); | |
| 61 | +await p.press('#prompt', 'Enter'); | |
| 62 | +await p.waitForFunction(() => document.getElementById('btn-send').classList.contains('is-stop'), null, { timeout: 5000 }).catch(() => {}); | |
| 63 | +const durante = await p.evaluate(() => ({ stop: document.getElementById('btn-send').classList.contains('is-stop'), busy: window.elffussClaw.conv.isBusy() })); | |
| 64 | +ok('1 · mientras trabaja, el botón es ■ y la conversación está ocupada', durante.stop && durante.busy, JSON.stringify(durante)); | |
| 65 | +await p.waitForFunction(() => !window.elffussClaw.conv.isBusy(), null, { timeout: 30000 }); | |
| 66 | +const fin = await p.evaluate(() => { | |
| 67 | + const h = window.elffussClaw.conv.getActive().agent.history; | |
| 68 | + return { log: document.getElementById('chat-log').innerText, ultimos: h.slice(-2).map(m => m.role + ':' + m.content.slice(0, 60)), id: window.elffussClaw.conv.getActive().id }; | |
| 69 | +}); | |
| 70 | +ok('1 · la respuesta aparece en el chat', fin.log.includes('respuesta final de prueba') && fin.log.includes('Hard Work (RLM)'), fin.log.slice(-200)); | |
| 71 | +ok('1 · pregunta y respuesta quedan en el historial de la conversación', fin.ultimos[0] === 'user:¿qué hace este proyecto?' && fin.ultimos[1]?.startsWith('assistant:respuesta final de prueba'), JSON.stringify(fin.ultimos)); | |
| 72 | + | |
| 73 | +// 2 · sobrevive a recargar | |
| 74 | +await arranca(); | |
| 75 | +const tras = await p.evaluate(() => ({ id: window.elffussClaw.conv.getActive().id, log: document.getElementById('chat-log').innerText })); | |
| 76 | +ok('2 · tras recargar, la pregunta y la respuesta siguen en la conversación', tras.id === fin.id && tras.log.includes('¿qué hace este proyecto?') && tras.log.includes('respuesta final de prueba'), tras.log.slice(0, 300)); | |
| 77 | + | |
| 78 | +// 3 · ■ lo para: no sale ninguna sub-llamada más y no se apunta respuesta | |
| 79 | +await siembra(12); | |
| 80 | +await ponProveedor(400); | |
| 81 | +await hardWork(true); | |
| 82 | +await p.fill('#prompt', 'audita todo el proyecto'); | |
| 83 | +await p.press('#prompt', 'Enter'); | |
| 84 | +await p.waitForFunction(() => window.__hw.llamadas >= 1, null, { timeout: 8000 }); | |
| 85 | +await p.waitForTimeout(150); | |
| 86 | +await p.evaluate(() => { window.__hw.parado = true; }); | |
| 87 | +await p.click('#btn-send'); | |
| 88 | +await p.waitForFunction(() => !window.elffussClaw.conv.isBusy(), null, { timeout: 8000 }).catch(() => {}); | |
| 89 | +await p.waitForTimeout(600); | |
| 90 | +const r3 = await p.evaluate(() => { | |
| 91 | + const h = window.elffussClaw.conv.getActive().agent.history; | |
| 92 | + return { busy: window.elffussClaw.conv.isBusy(), hw: window.__hw, ultimo: h.at(-1)?.role + ':' + h.at(-1)?.content.slice(0, 40), log: document.getElementById('chat-log').innerText.slice(-120) }; | |
| 93 | +}); | |
| 94 | +ok('3 · ■ para el Hard Work (deja de estar ocupado)', !r3.busy, JSON.stringify(r3)); | |
| 95 | +ok('3 · la sub-llamada en curso recibe la parada y no sale ninguna más', r3.hw.abortadas >= 1 && r3.hw.trasParar === 0, JSON.stringify(r3.hw)); | |
| 96 | +ok('3 · se ve «(Parado.)» y no se apunta respuesta', r3.log.includes('(Parado.)') && r3.ultimo === 'user:audita todo el proyecto', JSON.stringify(r3)); | |
| 97 | + | |
| 98 | +// 4 · al apagarlo vuelve el placeholder de la interfaz | |
| 99 | +await hardWork(false); | |
| 100 | +const ph = await p.evaluate(() => document.getElementById('prompt').placeholder); | |
| 101 | +ok('4 · al apagar Hard Work vuelve el placeholder normal', ph === 'Escribe aquí… (@ adjunta un archivo)', ph); | |
| 102 | + | |
| 103 | +console.log('\n errores JS:', errs[0] || 'ninguno'); | |
| 104 | +ok('sin errores de página', errs.length === 0, errs.join(' | ')); | |
| 105 | +console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ HARD WORK EN LA COLA: SE PARA Y SE GUARDA'); | |
| 106 | +await b.close(); | |
| 107 | +process.exit(fails ? 1 : 0); |
modified web/js/conversations.js +19 −2
| @@ -245,8 +245,9 @@ | ||
| 245 | 245 | } |
| 246 | 246 | |
| 247 | 247 | // ---- envío / procesado ---- |
| 248 | -// items de la cola: {kind:'chat'|'goal', text} — 'chat' es un turno normal | |
| 249 | -// (agent.handle), 'goal' dispara el planificador/ejecutor de goal.js. Las | |
| 248 | +// items de la cola: {kind:'chat'|'goal'|'hard', text} — 'chat' es un turno normal | |
| 249 | +// (agent.handle), 'goal' dispara el planificador/ejecutor de goal.js, 'hard' | |
| 250 | +// el Hard Work (ver setHardWorkRunner). Las | |
| 250 | 251 | // colas persistidas ANTES de que existiera el modo Objetivo guardaban texto |
| 251 | 252 | // suelto (strings) — normalizeItem() los sigue aceptando como 'chat'. |
| 252 | 253 | let inferenceLock = Promise.resolve(); |
| @@ -305,6 +306,21 @@ | ||
| 305 | 306 | pump(conv); |
| 306 | 307 | } |
| 307 | 308 | |
| 309 | +// ⛏ Hard Work: lee el proyecto entero por partes. Va por la MISMA cola que el | |
| 310 | +// resto: así el ■ lo para, la conversación se ve ocupada (el cerebro CEO | |
| 311 | +// espera) y la pregunta y la respuesta se guardan como cualquier turno. Antes | |
| 312 | +// corría por fuera: no se podía parar y desaparecía al cambiar de pestaña. | |
| 313 | +// Quien sabe leer el proyecto (main.js) registra cómo se ejecuta. | |
| 314 | +let hardWorkRunner = null; | |
| 315 | +export function setHardWorkRunner(fn) { hardWorkRunner = fn; } | |
| 316 | +export function startHardWork(id, text) { | |
| 317 | + const conv = convs.get(id); | |
| 318 | + if (!conv) return; | |
| 319 | + conv.queue.push({ kind: 'hard', text }); | |
| 320 | + persistConv(conv); | |
| 321 | + pump(conv); | |
| 322 | +} | |
| 323 | + | |
| 308 | 324 | // true cuando le toca el turno; false si la parada llega antes. |
| 309 | 325 | function turnoOParada(turno, signal) { |
| 310 | 326 | if (signal.aborted) return Promise.resolve(false); |
| @@ -387,6 +403,7 @@ | ||
| 387 | 403 | }; |
| 388 | 404 | try { |
| 389 | 405 | if (item.kind === 'goal') await runGoal(conv, item.text, onEvent, { signal }); |
| 406 | + else if (item.kind === 'hard' && hardWorkRunner) await hardWorkRunner(conv, item.text, onEvent, { signal }); | |
| 390 | 407 | else await conv.agent.handle(item.text, onEvent, { signal }); |
| 391 | 408 | } finally { |
| 392 | 409 | if (!parada && !signal.aborted) { |
modified web/js/i18n.js +10 −0
| @@ -126,6 +126,11 @@ | ||
| 126 | 126 | // ronda UX 2026-10: cola, guardar, avisos honestos |
| 127 | 127 | queuedTitle: "En cola: sale en cuanto termine lo de ahora", |
| 128 | 128 | queuedCancelled: "Descartado: pulsaste ■ antes de que le tocara", |
| 129 | + hwPhasePlan: "Hard Work · {n} partes ({k}k){trim}", | |
| 130 | + hwPhaseMap: "Hard Work · leyendo {i}/{n}", | |
| 131 | + hwPhaseGroup: "Hard Work · fundiendo {g}/{n}", | |
| 132 | + hwResult: "⛏ Hard Work (RLM): {n} partes, {k} con señal.", | |
| 133 | + hwFailed: "Hard Work falló: {e}", | |
| 129 | 134 | }, |
| 130 | 135 | en: { |
| 131 | 136 | ph: 'Type here… (@ attaches a file)', |
| @@ -247,6 +252,11 @@ | ||
| 247 | 252 | // UX round 2026-10: queue, save, honest notices |
| 248 | 253 | queuedTitle: "Queued: it goes out as soon as the current work ends", |
| 249 | 254 | queuedCancelled: "Dropped: you pressed ■ before its turn", |
| 255 | + hwPhasePlan: "Hard Work · {n} chunks ({k}k){trim}", | |
| 256 | + hwPhaseMap: "Hard Work · reading {i}/{n}", | |
| 257 | + hwPhaseGroup: "Hard Work · merging {g}/{n}", | |
| 258 | + hwResult: "⛏ Hard Work (RLM): {n} chunks, {k} with signal.", | |
| 259 | + hwFailed: "Hard Work failed: {e}", | |
| 250 | 260 | }, |
| 251 | 261 | }; |
| 252 | 262 |
modified web/js/main.js +48 −26
| @@ -309,6 +309,7 @@ | ||
| 309 | 309 | if (ev.type === 'text') addMsg('assistant', ev.text); |
| 310 | 310 | if (ev.type === 'tool') { activeThinking?.tool(ev.call.tool); addTool(ev.call.tool, ev.call.args?.path || ev.call.args?.query || ''); } |
| 311 | 311 | if (ev.type === 'tool_result') addToolResult(ev.result); |
| 312 | + if (ev.type === 'progress') activeThinking?.tool(ev.text); | |
| 312 | 313 | if (ev.type === 'error') addMsg('assistant err', ev.text); |
| 313 | 314 | if (ev.type === 'aborted') addMsg('assistant muted', ev.text); |
| 314 | 315 | // 🎯 Modo Objetivo: la tarjeta de plan se crea con 'plan' y se repinta |
| @@ -317,13 +318,14 @@ | ||
| 317 | 318 | } |
| 318 | 319 | } |
| 319 | 320 | |
| 320 | -function send(text) { | |
| 321 | +function send(text, modo) { | |
| 321 | 322 | const active = conv.getActive(); |
| 322 | 323 | if (!active) return; |
| 323 | 324 | // Si la elfa ya está con algo, el mensaje espera su turno y se ve así (⏳). |
| 324 | 325 | const burbuja = addMsg(active.pumping || active.queue.length ? 'user queued' : 'user', text); |
| 325 | 326 | if (burbuja.classList.contains('queued')) burbuja.title = t('queuedTitle'); |
| 326 | - if (goalMode) conv.startGoal(active.id, text); | |
| 327 | + if (modo === 'hard') conv.startHardWork(active.id, text); | |
| 328 | + else if (goalMode) conv.startGoal(active.id, text); | |
| 327 | 329 | else conv.send(active.id, text); |
| 328 | 330 | } |
| 329 | 331 | |
| @@ -1786,45 +1788,65 @@ | ||
| 1786 | 1788 | $('btn-hardwork').addEventListener('click', () => { |
| 1787 | 1789 | hardMode = !hardMode; |
| 1788 | 1790 | $('btn-hardwork').classList.toggle('on', hardMode); |
| 1789 | - $('prompt').placeholder = hardMode ? t("hwPlaceholder") : 'Pídele código a Elffuss…'; | |
| 1791 | + // Al apagarlo vuelve el texto de siempre, en el idioma de la interfaz: antes | |
| 1792 | + // quedaba un «Pídele código a Elffuss…» fijo y en español. | |
| 1793 | + $('prompt').placeholder = hardMode ? t("hwPlaceholder") : t('ph'); | |
| 1790 | 1794 | }); |
| 1791 | 1795 | |
| 1792 | 1796 | // Trabaja el proyecto abierto por partes: trocea, pregunta a cada parte y funde. |
| 1793 | -async function runHardWork(question) { | |
| 1794 | - const active = conv.getActive(); | |
| 1795 | - if (!active) return; | |
| 1796 | - addMsg('user', question); | |
| 1797 | - const thinking = thinkingBubble(); | |
| 1798 | - const fail = msg => { thinking.remove(); addMsg('assistant', msg); }; | |
| 1797 | +// Corre como un turno MÁS de la conversación (conversations.js → 'hard'): el ■ | |
| 1798 | +// lo para, la conversación se ve ocupada y la pregunta y la respuesta quedan en | |
| 1799 | +// su historial, así que sobreviven a cambiar de pestaña y a recargar. Antes | |
| 1800 | +// corría por fuera de la cola: el botón nunca pasaba a ■ y todo vivía solo en | |
| 1801 | +// el DOM. | |
| 1802 | +conv.setHardWorkRunner(async (c, question, onEvent, { signal }) => { | |
| 1803 | + const hist = c.agent.history; | |
| 1804 | + hist.push({ role: 'user', content: question, ts: Date.now() }); | |
| 1805 | + const responde = texto => { | |
| 1806 | + hist.push({ role: 'assistant', content: texto, ts: Date.now() }); | |
| 1807 | + onEvent({ type: 'text', text: texto }); | |
| 1808 | + }; | |
| 1809 | + const parado = () => onEvent({ type: 'aborted', text: '(Parado.)' }); | |
| 1810 | + const provider = conv.getProvider(); | |
| 1811 | + if (!provider || provider === rules) return responde(t('hwNeedBrain')); | |
| 1812 | + const root = codeTools.handle(); | |
| 1813 | + if (!root) return responde(t('hwNeedProject')); | |
| 1814 | + // Cada sub-llamada recibe la parada (corta la generación en curso) y, si ya | |
| 1815 | + // se pulsó ■, la siguiente ni se lanza. | |
| 1816 | + const conParada = { | |
| 1817 | + chat: (h, sys, cb) => signal.aborted | |
| 1818 | + ? Promise.reject(new DOMException('Parado', 'AbortError')) | |
| 1819 | + : provider.chat(h, sys, cb, signal), | |
| 1820 | + }; | |
| 1799 | 1821 | try { |
| 1800 | - const provider = conv.getProvider(); | |
| 1801 | - if (!provider || provider === rules) return fail(t("hwNeedBrain")); | |
| 1802 | - const root = codeTools.handle(); | |
| 1803 | - if (!root) return fail(t("hwNeedProject")); | |
| 1804 | - thinking.tool(t("hwReading")); | |
| 1822 | + onEvent({ type: 'progress', text: t('hwReading') }); | |
| 1805 | 1823 | const context = await gatherFolder(root, { maxBytes: 1.5e6 }); |
| 1806 | - if (!context.trim()) return fail(t("hwNoFiles")); | |
| 1824 | + if (signal.aborted) return parado(); | |
| 1825 | + if (!context.trim()) return responde(t('hwNoFiles')); | |
| 1807 | 1826 | const res = await hardWork({ |
| 1808 | - question, context, provider, | |
| 1827 | + question, context, provider: conParada, | |
| 1809 | 1828 | onProgress: p => { |
| 1810 | - if (p.phase === 'plan') thinking.tool(`Hard Work · ${p.chunks} partes (${Math.round(p.chars / 1000)}k)${p.truncated ? t("hwTrimmed") : ''}`); | |
| 1811 | - else if (p.phase === 'map') thinking.tool(`Hard Work · leyendo ${p.i}/${p.n}`); | |
| 1812 | - else if (p.phase === 'reduce-group') thinking.tool(`Hard Work · fundiendo ${p.g}/${p.n}`); | |
| 1813 | - else if (p.phase === 'reduce') thinking.tool(t("hwPhaseReduce")); | |
| 1829 | + if (signal.aborted) return; | |
| 1830 | + if (p.phase === 'plan') onEvent({ type: 'progress', text: t('hwPhasePlan', { n: p.chunks, k: Math.round(p.chars / 1000), trim: p.truncated ? t('hwTrimmed') : '' }) }); | |
| 1831 | + else if (p.phase === 'map') onEvent({ type: 'progress', text: t('hwPhaseMap', { i: p.i, n: p.n }) }); | |
| 1832 | + else if (p.phase === 'reduce-group') onEvent({ type: 'progress', text: t('hwPhaseGroup', { g: p.g, n: p.n }) }); | |
| 1833 | + else if (p.phase === 'reduce') onEvent({ type: 'progress', text: t('hwPhaseReduce') }); | |
| 1814 | 1834 | }, |
| 1815 | 1835 | }); |
| 1816 | - thinking.remove(); | |
| 1817 | - addMsg('assistant', res.answer + `\n\n_⛏ Hard Work (RLM): ${res.chunks} partes, ${res.kept} con señal.${res.truncated ? t("hwResultTrunc") : ''}_`); | |
| 1836 | + if (signal.aborted) return parado(); | |
| 1837 | + responde(res.answer + '\n\n_' + t('hwResult', { n: res.chunks, k: res.kept }) + (res.truncated ? t('hwResultTrunc') : '') + '_'); | |
| 1818 | 1838 | } catch (e) { |
| 1819 | - thinking.remove(); | |
| 1820 | - addMsg('assistant err', 'Hard Work falló: ' + (e?.message || String(e))); | |
| 1839 | + if (signal.aborted || e?.name === 'AbortError') return parado(); | |
| 1840 | + const texto = t('hwFailed', { e: e?.message || String(e) }); | |
| 1841 | + hist.push({ role: 'assistant', content: texto, ts: Date.now() }); | |
| 1842 | + onEvent({ type: 'error', text: texto }); | |
| 1821 | 1843 | } |
| 1822 | -} | |
| 1844 | +}); | |
| 1823 | 1845 | |
| 1824 | 1846 | // resolver @rutas del mensaje: se leen y se adjuntan como contexto |
| 1825 | 1847 | const _send = send; |
| 1826 | 1848 | send = async (text) => { |
| 1827 | - if (hardMode) return runHardWork(text); | |
| 1849 | + if (hardMode) return _send(text, 'hard'); | |
| 1828 | 1850 | const refs = [...text.matchAll(/@([\w./-]+\.\w+)/g)].map(m => m[1]); |
| 1829 | 1851 | if (refs.length) { |
| 1830 | 1852 | let ctx = ''; |