Elffuss BraidHub

utopia-ia/elffuss-code public

Hard Work runs as a conversation turn, so ■ stops it and it is saved

runHardWork() ran outside the conversation queue: the send button never
became ■, the conversation did not count as busy (the CEO did not wait), and
the question and answer lived only in the DOM, gone on a tab switch or a
reload. Hard Work is now a queue item of kind 'hard': conversations.js runs
it through a runner that main.js registers (setHardWorkRunner), with the
turn's stop signal. The runner records the question and the answer in the
conversation history, reports progress through a 'progress' event that the
thinking bubble shows, and wraps the provider so every sub-call gets the
signal and none starts once ■ was pressed. A stopped run shows "(Parado.)"
and records no answer, like any other stopped turn.

Turning Hard Work off restores t('ph') instead of a hard-coded Spanish
placeholder, and its progress and result lines go through i18n.

tests/hardwork-queue.mjs (?test-opfs, seeded project, stand-in provider for
the map and reduce calls): ■ is shown while it works, the answer is in the
chat and in the history and survives a reload, ■ aborts the sub-call in
flight and no other one starts, and the placeholder comes back. Against the
previous code 6 checks fail.
Changesetac1cc01879321916c7d5c556223b42849e29def195e160dae6fd1b97a8d81342
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 15:43 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 14:12 +02:00
Parents405072fe561a

Browse the files at this changeset

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 @@
245245 }
246246
247247 // ---- 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
250251 // colas persistidas ANTES de que existiera el modo Objetivo guardaban texto
251252 // suelto (strings) — normalizeItem() los sigue aceptando como 'chat'.
252253 let inferenceLock = Promise.resolve();
@@ -305,6 +306,21 @@
305306 pump(conv);
306307 }
307308
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+
308324 // true cuando le toca el turno; false si la parada llega antes.
309325 function turnoOParada(turno, signal) {
310326 if (signal.aborted) return Promise.resolve(false);
@@ -387,6 +403,7 @@
387403 };
388404 try {
389405 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 });
390407 else await conv.agent.handle(item.text, onEvent, { signal });
391408 } finally {
392409 if (!parada && !signal.aborted) {
modified web/js/i18n.js +10 −0
@@ -126,6 +126,11 @@
126126 // ronda UX 2026-10: cola, guardar, avisos honestos
127127 queuedTitle: "En cola: sale en cuanto termine lo de ahora",
128128 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}",
129134 },
130135 en: {
131136 ph: 'Type here… (@ attaches a file)',
@@ -247,6 +252,11 @@
247252 // UX round 2026-10: queue, save, honest notices
248253 queuedTitle: "Queued: it goes out as soon as the current work ends",
249254 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}",
250260 },
251261 };
252262
modified web/js/main.js +48 −26
@@ -309,6 +309,7 @@
309309 if (ev.type === 'text') addMsg('assistant', ev.text);
310310 if (ev.type === 'tool') { activeThinking?.tool(ev.call.tool); addTool(ev.call.tool, ev.call.args?.path || ev.call.args?.query || ''); }
311311 if (ev.type === 'tool_result') addToolResult(ev.result);
312+ if (ev.type === 'progress') activeThinking?.tool(ev.text);
312313 if (ev.type === 'error') addMsg('assistant err', ev.text);
313314 if (ev.type === 'aborted') addMsg('assistant muted', ev.text);
314315 // 🎯 Modo Objetivo: la tarjeta de plan se crea con 'plan' y se repinta
@@ -317,13 +318,14 @@
317318 }
318319 }
319320
320-function send(text) {
321+function send(text, modo) {
321322 const active = conv.getActive();
322323 if (!active) return;
323324 // Si la elfa ya está con algo, el mensaje espera su turno y se ve así (⏳).
324325 const burbuja = addMsg(active.pumping || active.queue.length ? 'user queued' : 'user', text);
325326 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);
327329 else conv.send(active.id, text);
328330 }
329331
@@ -1786,45 +1788,65 @@
17861788 $('btn-hardwork').addEventListener('click', () => {
17871789 hardMode = !hardMode;
17881790 $('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');
17901794 });
17911795
17921796 // 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+ };
17991821 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') });
18051823 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'));
18071826 const res = await hardWork({
1808- question, context, provider,
1827+ question, context, provider: conParada,
18091828 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') });
18141834 },
18151835 });
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') : '') + '_');
18181838 } 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 });
18211843 }
1822-}
1844+});
18231845
18241846 // resolver @rutas del mensaje: se leen y se adjuntan como contexto
18251847 const _send = send;
18261848 send = async (text) => {
1827- if (hardMode) return runHardWork(text);
1849+ if (hardMode) return _send(text, 'hard');
18281850 const refs = [...text.matchAll(/@([\w./-]+\.\w+)/g)].map(m => m[1]);
18291851 if (refs.length) {
18301852 let ctx = '';