Elffuss BraidHub

utopia-ia/elffuss-code public

File links in the chat are real links, and the proposal button stays

- `paths` in answers become <a class="file-link" href="#/file/path:line">,
  focusable and opened with Enter, and "path:line" opens the file at that
  line. They were <code> elements with an onclick: mouse only, no line.
  The path in a tool row ("● code.read src/app.js") and every hit of a
  search result ("src/app.js:2: …") are links too.
- #/file/path[:line] opens that file when the IDE starts or the hash
  changes, so a link opened in a new tab or a reload lands on the same
  spot.
- The CEO report's "▶ Ejecutar esta propuesta" button existed only in the
  live DOM and was gone after a tab switch or a reload. The proposal is
  stored with the message (conversations.appendMessage takes an extra
  object) and renderActiveLog() paints the button again. Its labels are in
  i18n.

tests/chatlinks.mjs (?test-opfs, seeded file): the path:line link and Enter
on it, search-hit and tool-row links, the button and the italics after a
reload, and the #/file route on load. Against the previous code it fails at
the first check.
Changeset9397a186eb6c0b87d6973cec2fd7927611f3b526edd45d237381fb19abc4b0aa
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 16:41 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 14:15 +02:00
Parents1617517edb13

Browse the files at this changeset

5 files changed

added tests/chatlinks.mjs +100 −0
@@ -0,0 +1,100 @@
1+// Enlaces del chat a ficheros, y el botón de la propuesta que sobrevive.
2+//
3+// 1. `ruta:línea` en una respuesta es un enlace de verdad (<a>, con Tab y
4+// Enter) que abre el fichero EN esa línea. Antes era un <code> con un
5+// onclick: solo ratón y sin línea.
6+// 2. La ruta de una fila de herramienta («● code.read src/app.js») y cada
7+// acierto de una búsqueda («src/app.js:2: …») también se abren.
8+// 3. #/file/ruta:línea en la URL abre ese fichero al cargar.
9+// 4. «▶ Ejecutar esta propuesta» del informe del cerebro sigue ahí tras
10+// recargar (antes solo vivía en el DOM del momento), y su _cursiva_ se
11+// pinta como cursiva (salían los guiones bajos).
12+//
13+// BASE=http://127.0.0.1:8898 node tests/chatlinks.mjs
14+import { chromium } from 'playwright';
15+const BASE = process.env.BASE || 'http://localhost:8799';
16+let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
17+
18+const b = await chromium.launch();
19+const ctx = await b.newContext({ locale: 'es-ES' });
20+await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
21+const p = await ctx.newPage({ viewport: { width: 1500, height: 900 } });
22+const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 160)));
23+
24+await p.goto(BASE + '/manifest.json');
25+await p.evaluate(async () => {
26+ const root = await navigator.storage.getDirectory();
27+ const escribe = async (path, txt) => {
28+ const parts = path.split('/'); const name = parts.pop(); let d = root;
29+ for (const x of parts) d = await d.getDirectoryHandle(x, { create: true });
30+ const w = await (await d.getFileHandle(name, { create: true })).createWritable(); await w.write(txt); await w.close();
31+ };
32+ await escribe('src/app.js', 'linea 1\nlinea 2 con unaPalabraRara\nlinea 3\nlinea 4\n');
33+});
34+const arranca = async (hash = '') => {
35+ await p.goto(BASE + '/?test-opfs' + hash, { waitUntil: 'domcontentloaded' });
36+ await p.waitForFunction(() => window.monaco && window.elffussClaw?.conv?.getActive?.(), null, { timeout: 30000 });
37+ await p.waitForTimeout(300);
38+};
39+const posicion = () => p.evaluate(() => ({ activa: document.querySelector('#tabs-bar .tab.active')?.dataset.path, linea: window.monaco?.editor?.getEditors?.()[0]?.getPosition()?.lineNumber }));
40+const libre = () => p.waitForFunction(() => !window.elffussClaw.conv.isBusy(), null, { timeout: 10000 });
41+
42+await arranca();
43+
44+// 1 · ruta:línea en una respuesta
45+await p.evaluate(async () => {
46+ const conv = window.elffussClaw.conv;
47+ conv.setProvider({ chat: async () => 'Mira `src/app.js:3` y también `README.md`.' });
48+ window.elffussClaw.send('¿dónde está?');
49+});
50+await libre();
51+await p.waitForTimeout(200);
52+const enlace = await p.evaluate(() => { const a = [...document.querySelectorAll('#chat-log a.file-link')].find(x => x.textContent === 'src/app.js:3'); return a ? { href: a.getAttribute('href'), tab: a.tabIndex } : null; });
53+ok('1 · `src/app.js:3` es un enlace (<a href="#/file/…:3">)', enlace?.href === '#/file/src/app.js:3' && enlace.tab === 0, JSON.stringify(enlace));
54+await p.locator('#chat-log a.file-link', { hasText: 'src/app.js:3' }).focus();
55+await p.keyboard.press('Enter');
56+await p.waitForTimeout(500);
57+ok('1 · Enter en el enlace abre el fichero en la línea 3', JSON.stringify(await posicion()) === '{"activa":"src/app.js","linea":3}', JSON.stringify(await posicion()));
58+
59+// 2 · fila de herramienta y aciertos de búsqueda (modo básico: reglas)
60+const reglas = await p.evaluate(async () => { const r = await import('/js/providers/rules.js'); window.elffussClaw.conv.setProvider(r); });
61+await p.fill('#prompt', 'busca unaPalabraRara');
62+await p.press('#prompt', 'Enter');
63+await libre();
64+await p.waitForTimeout(300);
65+const busqueda = await p.evaluate(() => [...document.querySelectorAll('#chat-log .tool-result pre a.file-link')].map(a => a.textContent));
66+ok('2 · cada acierto de la búsqueda es un enlace fichero:línea', busqueda.includes('src/app.js:2'), JSON.stringify(busqueda));
67+await p.evaluate(() => document.querySelector('#chat-log .tool-result')?.setAttribute('open', ''));
68+await p.locator('#chat-log .tool-result pre a.file-link', { hasText: 'src/app.js:2' }).first().click();
69+await p.waitForTimeout(500);
70+ok('2 · …y abre el fichero en esa línea', JSON.stringify(await posicion()) === '{"activa":"src/app.js","linea":2}', JSON.stringify(await posicion()));
71+await p.fill('#prompt', 'lee src/app.js');
72+await p.press('#prompt', 'Enter');
73+await libre();
74+await p.waitForTimeout(200);
75+const fila = await p.evaluate(() => [...document.querySelectorAll('#chat-log .msg.tool .targ a.file-link')].map(a => a.textContent));
76+ok('2 · la ruta de la fila de herramienta es un enlace', fila.includes('src/app.js'), JSON.stringify(fila));
77+
78+// 4 · informe del cerebro con su botón, también tras recargar
79+await p.evaluate(async () => {
80+ const m = await import('/js/main.js');
81+ m.reportImprovements({ path: '.elffuss/soul/x.md', md: '# Propuesta\nhaz algo', proposals: [{ dept: 'Calidad', text: 'Añadir validación a la entrada del formulario.' }] });
82+});
83+await p.waitForTimeout(300);
84+const informe = await p.evaluate(() => { const ms = [...document.querySelectorAll('#chat-log .msg.assistant')]; const u = ms.at(-1); return { boton: !!u?.querySelector('.proposal-exec-btn'), cursiva: !!u?.querySelector('i'), crudo: /_Guardado/.test(u?.textContent || '') }; });
85+ok('4 · el informe trae su botón «▶ Ejecutar esta propuesta»', informe.boton, JSON.stringify(informe));
86+ok('4 · su _cursiva_ se pinta como cursiva (sin guiones bajos sueltos)', informe.cursiva && !informe.crudo, JSON.stringify(informe));
87+await arranca();
88+const trasRecargar = await p.evaluate(() => [...document.querySelectorAll('#chat-log .msg.assistant')].some(m => m.querySelector('.proposal-exec-btn') && /Calidad/.test(m.textContent)));
89+ok('4 · tras recargar, el botón sigue ahí', trasRecargar);
90+
91+// 3 · #/file/ruta:línea
92+await arranca('#/file/src/app.js:4');
93+await p.waitForTimeout(600);
94+ok('3 · #/file/src/app.js:4 abre el fichero en la línea 4 al cargar', JSON.stringify(await posicion()) === '{"activa":"src/app.js","linea":4}', JSON.stringify(await posicion()));
95+
96+console.log('\n errores JS:', errs[0] || 'ninguno');
97+ok('sin errores de página', errs.length === 0, errs.join(' | '));
98+console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ ENLACES DEL CHAT Y BOTÓN DE PROPUESTA OK');
99+await b.close();
100+process.exit(fails ? 1 : 0);
modified web/css/code.css +3 −0
@@ -378,6 +378,9 @@
378378 }
379379 .msg.md code.file-link { cursor: pointer; color: var(--accent2); border-color: var(--accent2); text-decoration: underline dotted; }
380380 .msg.md code.file-link:hover { background: rgba(124,92,255,.18); }
381+a.file-link { color: var(--accent2); text-decoration: underline dotted; }
382+.msg.md code.file-link a.file-link { color: inherit; text-decoration: inherit; }
383+a.file-link:focus-visible { outline: 2px solid var(--accent2); outline-offset: 1px; border-radius: 3px; }
381384 .msg.md pre.codeblock {
382385 position: relative; background: #0d1117; border: 1px solid var(--line);
383386 border-radius: 8px; padding: 10px 12px; margin: 8px 0; overflow-x: auto;
modified web/js/conversations.js +4 −2
@@ -188,10 +188,12 @@
188188 // añade un mensaje fuera del ciclo normal de envío (p.ej. el informe
189189 // autónomo del cerebro CEO) al historial REAL de una conversación — si no,
190190 // solo viviría en el DOM y desaparecería al cambiar de pestaña o recargar.
191-export async function appendMessage(id, role, content) {
191+// `extra` se guarda junto al mensaje (p. ej. la propuesta que acompaña al
192+// informe del cerebro, para volver a pintar su botón al recargar).
193+export async function appendMessage(id, role, content, extra = {}) {
192194 const c = convs.get(id);
193195 if (!c) return;
194- c.agent.history.push({ role, content, ts: Date.now() });
196+ c.agent.history.push({ ...extra, role, content, ts: Date.now() });
195197 c.updatedAt = Date.now();
196198 await persistConv(c);
197199 }
modified web/js/i18n.js +2 −0
@@ -206,6 +206,7 @@
206206 termResizeLabel: "Altura del terminal (↑/↓)",
207207 ctxFull: "Contexto casi lleno ({pct}%). Los mensajes viejos se comprimen solos; para empezar limpio, abre una conversación nueva con «+».",
208208 ctxUse: "Contexto: {tok} de ~{max} tokens ({free}% libre)",
209+ openPathTitle: "abrir {path} en el editor", proposalSent: "▶ enviado a la cola…",
209210 clearModelsConfirm: "Vas a borrar {size} de modelos guardados en este navegador.\n\nNo se pierde nada tuyo: solo los pesos descargados. La próxima vez habrá que bajarlos otra vez.\n\n¿Seguir?",
210211 clearModelsShared: "Ojo: el almacén compartido de Elffuss no se pudo consultar desde aquí; puede quedar algo guardado ahí.",
211212 clearModelsDone: "💾 Liberados {size}.", clearModelsFailed: "No se pudo vaciar: {what}.",
@@ -413,6 +414,7 @@
413414 termResizeLabel: "Terminal height (↑/↓)",
414415 ctxFull: "Context almost full ({pct}%). Old messages are compressed automatically; to start clean, open a new conversation with “+”.",
415416 ctxUse: "Context: {tok} of ~{max} tokens ({free}% free)",
417+ openPathTitle: "open {path} in the editor", proposalSent: "▶ sent to the queue…",
416418 clearModelsConfirm: "You are about to delete {size} of models stored in this browser.\n\nNothing of yours is lost: only the downloaded weights. Next time they will be downloaded again.\n\nContinue?",
417419 clearModelsShared: "Note: Elffuss's shared store could not be checked from here; something may remain stored there.",
418420 clearModelsDone: "💾 Freed {size}.", clearModelsFailed: "Couldn't clear: {what}.",
modified web/js/main.js +63 −21
@@ -90,17 +90,44 @@
9090
9191 // ---------- chat ----------
9292 // Los `paths` entre backticks del chat (README.md, .elffuss/soul/x.md…) se
93-// vuelven clicables → abren el fichero en el editor directamente, sin tener
94-// que ir a buscarlos a mano.
93+// vuelven ENLACES que abren el fichero en el editor (y en su línea si viene
94+// «ruta:línea»). Son <a href="#/file/ruta:línea">: se llega con Tab, se abren
95+// con Enter, y el enlace sirve para volver a ese sitio (ver abreDesdeHash).
96+// Antes eran <code> con un onclick: solo ratón y sin línea.
97+const RUTA_RE = /^([\w.-]+(?:\/[\w.-]+)*\.[a-z0-9]{1,10})(?::(\d+))?$/i;
98+function enlaceFichero(path, line, texto) {
99+ const a = document.createElement('a');
100+ a.className = 'file-link';
101+ a.href = '#/file/' + encodeURI(path) + (line ? ':' + line : '');
102+ a.textContent = texto;
103+ a.title = t('openPathTitle', { path: path + (line ? ':' + line : '') });
104+ a.onclick = e => {
105+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return; // pestaña nueva: que lo abra el navegador
106+ e.preventDefault();
107+ openFile(path).then(() => { if (line) gotoLine(+line); });
108+ };
109+ return a;
110+}
95111 function linkifyFilePaths(root) {
96112 root.querySelectorAll('code').forEach(el => {
97- const t = el.textContent.trim();
98- if (!/^[\w.-]+(\/[\w.-]+)*\.[a-z0-9]{1,10}$/i.test(t) || /[{}()<>]/.test(t)) return;
113+ if (el.closest('pre')) return;
114+ const txt = el.textContent.trim();
115+ const m = txt.match(RUTA_RE);
116+ if (!m || /[{}()<>]/.test(txt)) return;
99117 el.classList.add('file-link');
100- el.title = 'abrir ' + t;
101- el.onclick = () => openFile(t);
118+ el.replaceChildren(enlaceFichero(m[1], m[2], txt));
102119 });
103120 }
121+// #/file/ruta[:línea] abre ese fichero: lo usan los enlaces de arriba (abrir
122+// en otra pestaña) y sirve para volver al mismo sitio tras recargar.
123+function abreDesdeHash() {
124+ let h = location.hash;
125+ try { h = decodeURI(h); } catch { /* — */ }
126+ const m = h.match(/^#\/file\/(.+?)(?::(\d+))?$/);
127+ if (!m || !codeTools.handle()) return;
128+ openFile(m[1]).then(() => { if (m[2]) gotoLine(+m[2]); });
129+}
130+addEventListener('hashchange', abreDesdeHash);
104131
105132 // Todo lo que pinta el chat entra por aquí. Lo que se escribió mientras la elfa
106133 // trabajaba espera AL FINAL, marcado «en cola» (⏳): lo que va llegando del turno
@@ -144,7 +171,10 @@
144171 if (arg) {
145172 const a = document.createElement('span');
146173 a.className = 'targ';
147- a.textContent = String(arg).slice(0, 60);
174+ const txt = String(arg).slice(0, 60);
175+ // «● code.read src/app.js»: la ruta se abre con un clic (o Enter)
176+ const m = String(arg).match(RUTA_RE);
177+ if (m) a.appendChild(enlaceFichero(m[1], m[2], txt)); else a.textContent = txt;
148178 div.appendChild(a);
149179 }
150180 appendLog(div);
@@ -159,7 +189,12 @@
159189 const sum = document.createElement('summary');
160190 sum.textContent = (err ? '⚠️ ' : '') + result.split('\n')[0].slice(0, 90);
161191 const pre = document.createElement('pre');
162- pre.textContent = result.slice(0, 1500);
192+ // Los resultados de búsqueda («ruta:línea: texto») enlazan cada acierto.
193+ for (const linea of result.slice(0, 1500).split('\n')) {
194+ const m = linea.match(/^([\w.-]+(?:\/[\w.-]+)*\.[a-z0-9]{1,10}):(\d+):(.*)$/i);
195+ if (m) pre.append(enlaceFichero(m[1], m[2], `${m[1]}:${m[2]}`), ':' + m[3] + '\n');
196+ else pre.append(linea + '\n');
197+ }
163198 det.append(sum, pre);
164199 appendLog(det);
165200 $('chat-log').scrollTop = $('chat-log').scrollHeight;
@@ -252,7 +287,10 @@
252287 } else {
253288 const call = parseToolCall(m.content);
254289 if (call) addTool(call.tool, call.args?.path || call.args?.query || '');
255- else addMsg('assistant', m.content);
290+ else {
291+ const div = addMsg('assistant', m.content);
292+ if (m.propuesta) botonPropuesta(div, m.propuesta);
293+ }
256294 }
257295 }
258296 if (active.pumping) activeThinking = thinkingBubble();
@@ -1254,6 +1292,7 @@
12541292 renderTabsBar();
12551293 renderActiveLog();
12561294 addMsg('sys', t('welcome', { name }));
1295+ abreDesdeHash();
12571296 refreshGit();
12581297 preloadModel(); // por si el arranque en la landing no llegó a dispararse
12591298 }
@@ -1634,6 +1673,15 @@
16341673 // del chat — usado tanto por el botón del chat como por el de la notificación.
16351674 function executeProposal(md) { send(t('pProposal') + md); }
16361675
1676+// Botón REAL para ejecutar la propuesta desde el propio chat.
1677+function botonPropuesta(div, md) {
1678+ const btn = document.createElement('button');
1679+ btn.className = 'proposal-exec-btn';
1680+ btn.textContent = t('mindExec');
1681+ btn.onclick = () => { btn.disabled = true; btn.textContent = t('proposalSent'); executeProposal(md); };
1682+ div.appendChild(btn);
1683+}
1684+
16371685 export function reportImprovements(ev) {
16381686 const props = ev.proposals || [];
16391687 if (!props.length) return;
@@ -1643,19 +1691,13 @@
16431691 (ev.path ? `\n\n_Guardado en \`${ev.path}\`. Dale a la elfa para verlo en la Mente, o ábrelo en el editor._` : '');
16441692 const div = addMsg('assistant', body);
16451693 // se guarda en el historial REAL de la conversación activa — si no, el
1646- // aviso vive solo en el DOM y desaparece al cambiar de pestaña o recargar
1647- const active = conv.getActive();
1648- if (active) conv.appendMessage(active.id, 'assistant', body);
1649- // botón REAL para ejecutar la propuesta desde el propio chat (antes solo
1650- // se podía desde el panel de la Mente, había que ir a buscarlo)
1694+ // aviso vive solo en el DOM y desaparece al cambiar de pestaña o recargar.
1695+ // Con la propuesta al lado: el botón «▶ Ejecutar» se vuelve a pintar al
1696+ // repintar el chat (antes solo existía en el DOM del momento).
16511697 const md = ev.md || body;
1652- if (div) {
1653- const btn = document.createElement('button');
1654- btn.className = 'proposal-exec-btn';
1655- btn.textContent = '▶ Ejecutar esta propuesta';
1656- btn.onclick = () => { btn.disabled = true; btn.textContent = '▶ enviado a la cola…'; executeProposal(md); };
1657- div.appendChild(btn);
1658- }
1698+ const active = conv.getActive();
1699+ if (active) conv.appendMessage(active.id, 'assistant', body, { propuesta: md });
1700+ if (div) botonPropuesta(div, md);
16591701 if (isNoteworthy(ev)) notify(`Elffuss encontró ${props.length} mejora${props.length === 1 ? '' : 's'}`, props.map(p => p.dept).join(' · '), md);
16601702 }
16611703 // SOLO notifica si el permiso YA está concedido. Nunca pide permiso aquí: