Elffuss BraidHub

utopia-ia/elffuss-claw public

coordinated: permission dialog answers Escape, queues requests; toasts can be closed

Permission dialog (web/js/ui.js askPermission):
- Escape, or any other close, now counts as Deny. Before, Escape closed the
  dialog without settling the promise: the turn hung on "Elffuss is using
  app.create" and every later message stayed queued until a reload.
- Requests are queued. A second request used to overwrite the button
  handlers of the first one, which could then never be answered.
- The dialog opens in the next task. When a request came from an Enter key
  press (the vault password field), the dialog opened inside that same key
  event, focus landed on Deny and the same key press activated it.
- The dialog is labelled by its title and described by its text, and focus
  goes back to where it was when it closes.

Toasts: a close button, a pause while hovered or focused, a duration that
depends on the length of the text, and an optional action button
(toast(text, { accion: { label, run } })), used by later fixes for Undo and
"go to" actions. #toasts is a polite status region and #log a log region;
the thinking bubble is hidden from screen readers (it changes on every token)
and the log is marked busy while it is shown.

tests/ux-comun.mjs holds the helpers of the new UX tests (basic mode, no
model, third-party hosts blocked). tests/ux-dialogos.mjs covers Escape, the
queue of requests, the Enter key case and the toasts; against the previous
tree it fails at the first Escape.

Coordinated: ui.js, index.html, elffuss.css and i18n.js have uncommitted
edits in the live tree. The hunks here touch toast(), askPermission(),
thinkingBubble() (which the live tree also extends with a prefill bar: keep
both), the #log, #toasts and dialog tags, the toast CSS and new i18n keys at
the end of the es and en blocks.

Integration (onto stop-fix 7147228, which sits on main 10073b7): the live-tree
edits named above are main's 66c2865 now. stop-fix 5f91e5a had fixed the same
dialog its own way (close = deny, one dialog, a newer request denies the one
on screen). This keeps this commit's askPermission (Escape = deny, its own
queue, opens in the next task, focus goes back) and stop-fix's queue in
permissions.js; the two queues only serialize twice. The thinking bubble keeps
stop-fix's stopping() and partial() and this commit's aria-busy release, and
markCancelled(), announce() and clearLog() stay next to the new toast().
Changesetab79fa6b790fe63035abfb83dc8d2c6ca30ca8b9079d6f45d19035847ce92dc2
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 15:53 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 17:45 +02:00
Parents06bd031f65c7

Browse the files at this changeset

6 files changed

added tests/ux-comun.mjs +86 −0
@@ -0,0 +1,86 @@
1+// Utilidades comunes de los tests de UX (tests/ux-*.mjs). Sin modelo ni GPU:
2+// modo básico, determinista. Las peticiones a terceros se cortan aquí para que
3+// ningún test dependa de la red ni toque producción; three.js (la Mente) es lo
4+// único que se deja pasar, y solo si un test abre la Mente.
5+//
6+// python3 server/serve.py 8743 & BASE=http://localhost:8743 node tests/ux-<algo>.mjs
7+import { chromium } from 'playwright';
8+
9+export const BASE = process.env.BASE || 'http://localhost:8743';
10+export const OUT = process.env.SCRATCH || '';
11+
12+let fails = 0;
13+export const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
14+export const fallos = () => fails;
15+export const espera = ms => new Promise(r => setTimeout(r, ms));
16+export async function hasta(cond, { veces = 200, cada = 50 } = {}) {
17+ for (let i = 0; i < veces; i++) { if (await cond()) return true; await espera(cada); }
18+ return false;
19+}
20+
21+// Lo que NO puede salir de la máquina en un test: el modelo grande, el broker,
22+// SoundCloud, Hugging Face, GitHub (salvo que el test lo stubee), producción.
23+const CORTAR = [
24+ /^https:\/\/([a-z0-9-]+\.)?soundcloud\.com\//,
25+ /^https:\/\/([a-z0-9-]+\.)?huggingface\.co\//,
26+ /^https:\/\/([a-z0-9-]+\.)?hf\.co\//,
27+ /^https:\/\/(m\d+|models)\.elffuss\.(com|utopiaia\.com)\//,
28+ /^https:\/\/([a-z0-9-]+\.)?elffuss\.com\//,
29+ /^https:\/\/([a-z0-9-]+\.)?openverse\.org\//,
30+ /^https:\/\/([a-z0-9-]+\.)?duckduckgo\.com\//,
31+ /^https:\/\/cdn\.sheetjs\.com\//,
32+ /^https:\/\/cdn\.jsdelivr\.net\/npm\/@huggingface\//,
33+ /^https:\/\/cdn\.jsdelivr\.net\/npm\/@mlc-ai\//,
34+ /^https:\/\/cdn\.jsdelivr\.net\/npm\/@litert/,
35+ /^https:\/\/([a-z0-9-]+\.)?googleapis\.com\//,
36+ /^https:\/\/(api\.github\.com|raw\.githubusercontent\.com)\//,
37+];
38+
39+export async function navegador() { return chromium.launch(); }
40+
41+// Contexto con Claw en modo básico, ya «bienvenido» y con los permisos que se
42+// pidan. `rutas` permite stubear una URL externa: (url, route) → true si la
43+// atendió.
44+export async function contexto(b, { locale = 'es-ES', viewport = { width: 1400, height: 900 }, welcomed = true,
45+ model = 'rules', grants = null, rutas = null, isMobile = false, hasTouch = false, extraInit = null } = {}) {
46+ const ctx = await b.newContext({ locale, viewport, acceptDownloads: true, isMobile, hasTouch });
47+ const fuera = [];
48+ await ctx.route('**/*', async route => {
49+ const url = route.request().url();
50+ if (url.startsWith(BASE) || url.startsWith('data:') || url.startsWith('blob:')) return route.continue();
51+ if (rutas && await rutas(url, route)) return;
52+ fuera.push(route.request().method() + ' ' + url.slice(0, 140));
53+ if (CORTAR.some(rx => rx.test(url))) return route.abort();
54+ return route.continue();
55+ });
56+ await ctx.addInitScript(({ welcomed, model, grants, extraInit }) => {
57+ try {
58+ if (welcomed) localStorage.setItem('elffuss.welcomed', '1');
59+ if (model) localStorage.setItem('elffuss.model', model);
60+ if (grants) localStorage.setItem('elffuss.grants', JSON.stringify(grants));
61+ if (extraInit) for (const [k, v] of Object.entries(extraInit)) localStorage.setItem(k, v);
62+ } catch { /* */ }
63+ }, { welcomed, model, grants, extraInit });
64+ return { ctx, fuera };
65+}
66+
67+export async function pagina(ctx, ruta = '/') {
68+ const p = await ctx.newPage();
69+ const errores = [];
70+ p.on('pageerror', e => { if (!/allow-same-origin/.test(e.message)) errores.push(e.message); });
71+ p.on('dialog', d => { p.__dialogos = (p.__dialogos || []).concat(d.message()); (p.__aceptar === false ? d.dismiss() : d.accept()).catch(() => {}); });
72+ await p.goto(BASE + ruta, { waitUntil: 'domcontentloaded' });
73+ await p.waitForFunction(() => !!window.elffuss?.agent, null, { timeout: 15000 });
74+ return { p, errores };
75+}
76+
77+export const kv = (p, key) => p.evaluate(async k => (await import('/js/db.js')).get('kv', k), key);
78+export const avisos = p => p.$$eval('#toasts .toast .toast-txt', ts => ts.map(t => t.textContent));
79+export async function escribir(p, texto) { await p.fill('#prompt', texto); await p.press('#prompt', 'Enter'); }
80+export const reposo = p => hasta(() => p.evaluate(() => !document.getElementById('send').classList.contains('is-stop')
81+ && !document.querySelector('#log .msg.thinking')));
82+
83+export function fin(b, titulo) {
84+ console.log(fails ? `\n❌ ${fails} FALLO(S)` : `\n✅ ${titulo}`);
85+ return b.close().then(() => process.exit(fails ? 1 : 0));
86+}
added tests/ux-dialogos.mjs +96 −0
@@ -0,0 +1,96 @@
1+// Diálogo de permisos y avisos (toasts), con el teclado y con el ratón.
2+// · Escape en el diálogo de permisos DENIEGA: el turno termina y la cola sigue
3+// (antes la promesa no se resolvía nunca y todo se quedaba colgado).
4+// · Dos peticiones a la vez van en cola: la segunda no pisa a la primera.
5+// · Un permiso pedido desde un Enter no se deniega con esa misma pulsación.
6+// · Los avisos se cierran, pueden llevar acción y se anuncian (región viva).
7+//
8+// BASE=http://localhost:8743 node tests/ux-dialogos.mjs
9+import { navegador, contexto, pagina, ok, hasta, espera, escribir, reposo, avisos, fin, OUT } from './ux-comun.mjs';
10+
11+const b = await navegador();
12+const { ctx } = await contexto(b, { grants: [] });
13+const { p, errores } = await pagina(ctx);
14+
15+// ── 1 · Escape = Denegar, y el turno no se cuelga ───────────────────────────
16+await escribir(p, 'hazme un reloj');
17+ok('el modo básico pide permiso de Apps', await hasta(() => p.evaluate(() => document.getElementById('perm-dialog').open)));
18+if (OUT) await p.screenshot({ path: OUT + '/ux-permiso.png' });
19+await p.keyboard.press('Escape');
20+ok('Escape cierra el diálogo', await hasta(() => p.evaluate(() => !document.getElementById('perm-dialog').open)));
21+ok('…y cuenta como «Denegar» (la herramienta recibe el permiso denegado)', await hasta(async () =>
22+ /denegado por el usuario/.test(await p.locator('#log').innerText())));
23+ok('el turno termina: el botón vuelve a ➤ y no queda la burbuja de «usando…»', await reposo(p));
24+await escribir(p, 'hola');
25+ok('lo siguiente que escribes se procesa (la cola no se ha quedado atascada)', await hasta(async () =>
26+ (await p.locator('#log .msg.assistant').allTextContents()).some(t => /modo básico/.test(t))));
27+ok('no queda nada esperando en la cola', await p.locator('.msg.user.queued').count() === 0);
28+
29+// ── 2 · dos peticiones a la vez: en cola, una detrás de otra ────────────────
30+await p.evaluate(() => {
31+ window.__r = {};
32+ import('/js/permissions.js').then(pm => {
33+ pm.require('web', 'primera').then(() => { window.__r.web = 'ok'; }, () => { window.__r.web = 'no'; });
34+ pm.require('tasks', 'segunda').then(() => { window.__r.tasks = 'ok'; }, () => { window.__r.tasks = 'no'; });
35+ });
36+});
37+ok('se abre la primera petición', await hasta(() => p.evaluate(() =>
38+ document.getElementById('perm-dialog').open && /Internet/.test(document.getElementById('perm-title').textContent))));
39+await p.click('#perm-allow');
40+ok('al contestarla, se abre la segunda (no se pisaron)', await hasta(() => p.evaluate(() =>
41+ document.getElementById('perm-dialog').open && /Tareas/.test(document.getElementById('perm-title').textContent))));
42+await p.click('#perm-deny');
43+ok('cada una recibe SU respuesta', await hasta(() => p.evaluate(() => window.__r.web === 'ok' && window.__r.tasks === 'no')),
44+ JSON.stringify(await p.evaluate(() => window.__r)));
45+
46+// ── 3 · un Enter que pide permiso no lo deniega con la misma pulsación ──────
47+await p.evaluate(() => {
48+ const i = document.createElement('input');
49+ i.id = 'campo-prueba';
50+ document.body.appendChild(i);
51+ i.addEventListener('keydown', e => {
52+ if (e.key !== 'Enter') return;
53+ window.__mem = 'pendiente';
54+ import('/js/permissions.js').then(pm => pm.require('memory', 'desde un Enter')
55+ .then(() => { window.__mem = 'concedido'; }, () => { window.__mem = 'denegado'; }));
56+ });
57+ i.focus();
58+});
59+await p.keyboard.press('Enter');
60+await espera(500);
61+ok('el diálogo sigue abierto tras el Enter que lo pidió', await p.evaluate(() => document.getElementById('perm-dialog').open && window.__mem === 'pendiente'),
62+ await p.evaluate(() => window.__mem));
63+ok('el foco está dentro del diálogo', await p.evaluate(() => document.getElementById('perm-dialog').contains(document.activeElement)));
64+await p.click('#perm-allow');
65+ok('y contestar con el ratón lo concede', await hasta(() => p.evaluate(() => window.__mem === 'concedido')));
66+ok('al cerrarse, el foco vuelve al campo de donde salió', await p.evaluate(() => document.activeElement?.id === 'campo-prueba'));
67+
68+// ── 4 · avisos: región viva, se cierran, llevan acción ──────────────────────
69+const vivo = await p.evaluate(() => ({
70+ toasts: document.getElementById('toasts').getAttribute('role'),
71+ log: document.getElementById('log').getAttribute('role'),
72+ dialogo: document.getElementById('perm-dialog').getAttribute('aria-labelledby'),
73+}));
74+ok('#toasts y #log son regiones vivas; el diálogo tiene título', vivo.toasts === 'status' && vivo.log === 'log' && vivo.dialogo === 'perm-title', JSON.stringify(vivo));
75+await p.evaluate(async () => {
76+ const ui = await import('/js/ui.js');
77+ window.__accion = 0;
78+ ui.toast('aviso con acción', { accion: { label: 'Hazlo', run: () => { window.__accion++; } } });
79+ ui.toast('aviso para cerrar');
80+});
81+const conAccion = p.locator('#toasts .toast', { hasText: 'aviso con acción' });
82+await conAccion.locator('.toast-accion').click();
83+ok('la acción del aviso se ejecuta y el aviso se va', await p.evaluate(() => window.__accion) === 1 && await conAccion.count() === 0);
84+const paraCerrar = p.locator('#toasts .toast', { hasText: 'aviso para cerrar' });
85+ok('el ✕ tiene nombre accesible', /Cerrar/.test(await paraCerrar.locator('.toast-x').getAttribute('aria-label')));
86+await paraCerrar.locator('.toast-x').click();
87+ok('✕ cierra el aviso', await paraCerrar.count() === 0);
88+await p.evaluate(async () => (await import('/js/ui.js')).toast('aviso con el ratón encima', { ms: 600 }));
89+await p.hover('#toasts .toast:last-child');
90+await espera(1100);
91+ok('con el ratón encima, el aviso no se va', await p.locator('#toasts .toast', { hasText: 'aviso con el ratón encima' }).count() === 1);
92+await p.mouse.move(5, 5);
93+ok('y al quitarlo, sí', await hasta(async () => await p.locator('#toasts .toast', { hasText: 'aviso con el ratón encima' }).count() === 0));
94+
95+ok('sin errores de página', errores.length === 0, errores.slice(0, 3).join(' | '));
96+await fin(b, 'DIÁLOGOS Y AVISOS: Escape deniega, la cola sigue, sin pisarse y sin denegar por un Enter');
modified web/css/elffuss.css +13 −0
@@ -351,8 +351,21 @@
351351 max-width: 340px;
352352 box-shadow: 0 8px 30px rgba(0, 0, 0, .5);
353353 animation: slidein .2s ease-out;
354+ display: flex; align-items: flex-start; gap: 8px;
354355 }
355356 @keyframes slidein { from { transform: translateX(20px); opacity: 0; } }
357+.toast .toast-txt { flex: 1; min-width: 0; }
358+.toast .toast-accion {
359+ flex: none; background: none; border: 1px solid var(--accent); color: var(--fg);
360+ border-radius: 6px; padding: 2px 8px; font-size: .8rem; cursor: pointer; white-space: nowrap;
361+}
362+.toast .toast-accion:hover { background: color-mix(in srgb, var(--accent) 20%, transparent); }
363+.toast .toast-x {
364+ flex: none; background: none; border: none; color: var(--muted); cursor: pointer;
365+ font-size: .8rem; padding: 0 2px; line-height: 1.4;
366+}
367+.toast .toast-x:hover { color: var(--fg); }
368+@media (prefers-reduced-motion: reduce) { .toast { animation: none; } }
356369 #model-progress {
357370 position: fixed; bottom: 18px; left: 18px; z-index: 50;
358371 background: var(--bg3); border: 1px solid var(--line); border-radius: 10px;
modified web/index.html +3 −3
@@ -52,7 +52,7 @@
5252
5353 <main>
5454 <section id="chat">
55- <div id="log">
55+ <div id="log" role="log" aria-live="polite" aria-relevant="additions">
5656 <div class="msg sys"><img class="avatar" src="img/elffuss.svg" alt=""><b>Hola, soy Elffuss.</b>
5757 Un sistema operativo con alma que vive en tu navegador.
5858 Aquí las apps no se instalan: <i>se crean</i> cuando las pides y aparecen a la derecha.
@@ -105,7 +105,7 @@
105105 </section>
106106 </main>
107107
108-<dialog id="perm-dialog">
108+<dialog id="perm-dialog" aria-labelledby="perm-title" aria-describedby="perm-desc perm-detail">
109109 <h3 id="perm-title"></h3>
110110 <p id="perm-desc"></p>
111111 <p id="perm-detail" class="muted"></p>
@@ -116,7 +116,7 @@
116116 </dialog>
117117
118118 <button id="btn-flip" title="cambiar entre chat y vista">Vista</button>
119-<div id="toasts"></div>
119+<div id="toasts" role="status" aria-live="polite" aria-relevant="additions"></div>
120120 <div id="model-progress" hidden>
121121 <div class="track"><div id="model-bar"></div></div>
122122 <span id="model-progress-text"></span>
modified web/js/i18n.js +4 −0
@@ -99,6 +99,8 @@
9999 useNoRam: "no medible en este navegador",
100100 extTitle: "Modelos externos (avanzado)",
101101 extDesc: "Elffuss corre en TU máquina y nada sale de ella. Estas opciones son la excepción: mandan tus mensajes a un servidor de fuera. Solo si tú lo activas a mano. Las claves se guardan en este navegador y las llamadas van directas al proveedor.",
102+ // ── arreglos de UX (ronda 20261010) ──
103+ close: 'Cerrar', undo: 'Deshacer',
102104 },
103105 en: {
104106 welcome: 'An operating system with a soul that lives in your browser. Here apps aren’t installed: they’re created when you ask, appearing on the right. I can use your folders (with permission), store encrypted secrets, schedule tasks and browse for you. Everything stays on your machine.',
@@ -194,6 +196,8 @@
194196 useNoRam: "not measurable in this browser",
195197 extTitle: "External models (advanced)",
196198 extDesc: "Elffuss runs on YOUR machine and nothing leaves it. These options are the exception: they send your messages to an outside server. Only if you turn them on yourself. Keys stay in this browser and calls go straight to the provider.",
199+ // ── UX fixes (round 20261010) ──
200+ close: 'Close', undo: 'Undo',
197201 },
198202 uk: {
199203 welcome: "Операційна система з душею, що живе у твоєму браузері. Тут застосунки не встановлюють — їх створюють на твій запит, і вони з’являються праворуч. Можу працювати з твоїми теками (за дозволом), зберігати зашифровані секрети, планувати завдання й гортати за тебе. Усе лишається на твоєму пристрої.",
modified web/js/ui.js +95 −26
@@ -88,6 +88,11 @@
8888 const gen = document.createElement('div');
8989 gen.className = 'gen';
9090 div.append(img, label, dots, gen);
91+ // #log es una región viva (role=log en index.html). La burbuja se oculta a los
92+ // lectores de pantalla: cambia de texto con cada token y se leería sin parar.
93+ // Mientras trabaja, el log queda «ocupado» y lo que llegue se anuncia al final.
94+ div.setAttribute('aria-hidden', 'true');
95+ $('log').setAttribute('aria-busy', 'true');
9196 $('log').appendChild(div);
9297 $('log').scrollTop = $('log').scrollHeight;
9398 // Barra del PREFILL. El prefill es la espera larga —leer el prompt antes de
@@ -152,7 +157,7 @@
152157 // Lo que llegó a escribir, si era texto para el usuario (no una herramienta
153158 // a medias, que se enseña como «creando app…»): lo que se conserva al parar.
154159 partial() { return humanizeStreamPreview(buf) ? '' : buf.trim(); },
155- remove() { div.remove(); },
160+ remove() { div.remove(); if (!document.querySelector('#log .msg.thinking')) $('log').removeAttribute('aria-busy'); },
156161 };
157162 }
158163
@@ -187,49 +192,113 @@
187192 for (const el of [...$('log').children]) if (!el.classList.contains('sys')) el.remove();
188193 }
189194
190-export function toast(text, ms = 4500) {
195+// Avisos. Antes se iban a los 4,5 s pasara lo que pasara: uno de 184 caracteres
196+// (el de Hard Work) no daba tiempo a leerlo, no había forma de quitarlos ni de
197+// pararlos, y ninguno llevaba a ningún sitio. Ahora:
198+// · duran según lo que hay que leer, y se paran con el ratón o el foco encima;
199+// · se cierran con ✕;
200+// · pueden llevar UNA acción («Deshacer», «Ver tarea», «Elegir ahora»…);
201+// · #toasts es una región viva (index.html): un lector de pantalla los anuncia.
202+// `opts` admite un número (ms), como antes, o { ms, accion: { label, run } }.
203+export function toast(text, opts = {}) {
204+ if (typeof opts === 'number') opts = { ms: opts };
205+ const { accion = null, ms = null } = opts || {};
191206 const t = document.createElement('div');
192207 t.className = 'toast';
193- t.textContent = text;
208+ const txt = document.createElement('span');
209+ txt.className = 'toast-txt';
210+ txt.textContent = text;
211+ t.appendChild(txt);
212+ let timer = null, restante = 0, desde = 0, parado = false;
213+ const quitar = () => { clearTimeout(timer); t.remove(); };
214+ if (accion?.label && typeof accion.run === 'function') {
215+ const b = document.createElement('button');
216+ b.type = 'button';
217+ b.className = 'toast-accion';
218+ b.textContent = accion.label;
219+ b.onclick = () => { quitar(); try { accion.run(); } catch (e) { console.warn('[elffuss] acción del aviso:', e); } };
220+ t.appendChild(b);
221+ }
222+ const x = document.createElement('button');
223+ x.type = 'button';
224+ x.className = 'toast-x';
225+ x.textContent = '✕';
226+ x.title = tr('close');
227+ x.setAttribute('aria-label', tr('close'));
228+ x.onclick = quitar;
229+ t.appendChild(x);
194230 $('toasts').appendChild(t);
195- setTimeout(() => t.remove(), ms);
231+ // ~50 ms por carácter, entre 4 y 12 s; con acción, unos segundos más para
232+ // que dé tiempo a decidir.
233+ restante = ms ?? (Math.min(12000, Math.max(4000, 1500 + String(text).length * 50)) + (accion ? 4000 : 0));
234+ const arrancar = () => { desde = Date.now(); clearTimeout(timer); timer = setTimeout(quitar, restante); };
235+ const pausar = () => { if (parado) return; parado = true; clearTimeout(timer); restante = Math.max(1500, restante - (Date.now() - desde)); };
236+ const seguir = () => { if (!parado || t.matches(':hover') || t.contains(document.activeElement)) return; parado = false; arrancar(); };
237+ t.addEventListener('mouseenter', pausar);
238+ t.addEventListener('mouseleave', seguir);
239+ t.addEventListener('focusin', pausar);
240+ t.addEventListener('focusout', () => setTimeout(seguir, 0));
241+ arrancar();
242+ return t;
196243 }
197244
198245 // ---------- modal de permisos ----------
199-// Contesta SIEMPRE, también si el diálogo se cierra sin pulsar nada (Escape):
200-// cerrar es «no». Antes Escape lo cerraba sin contestar, y la herramienta que
201-// lo pidió esperaba para siempre —y con ella el turno, la cola de detrás y el
202-// cerebro CEO, que no arrancaba otro ciclo—.
203-// Las peticiones llegan de una en una (permissions.js las pone en fila). Si
204-// aun así entrara otra con el diálogo abierto, la que se estaba enseñando se
205-// da por denegada en vez de quedarse sin respuesta: los botones son unos.
206-let permEnCurso = null; // done() de la petición que enseña el diálogo
246+// Tres cosas que fallaban, las tres con el teclado:
247+// · Escape cerraba el diálogo SIN contestar: la promesa no se resolvía nunca,
248+// el turno se quedaba colgado en «Elffuss está usando…» y todo lo que
249+// escribieras después esperaba en la cola hasta recargar —y con ella el
250+// cerebro CEO, que no arrancaba otro ciclo—. Ahora Escape (y cualquier otro
251+// cierre) es «Denegar».
252+// · Dos peticiones a la vez se pisaban los botones: la segunda reasignaba los
253+// onclick de la primera, que ya no se podía contestar. Ahora van en cola,
254+// una detrás de otra (permissions.js ya las pone en fila por ámbito; esta
255+// cola cubre además a quien llame aquí directamente).
256+// · Si la petición nacía de un Enter (p. ej. en la contraseña de la Bóveda),
257+// el diálogo se abría DENTRO de ese mismo evento, el foco caía en «Denegar»
258+// y la misma pulsación lo activaba: denegado sin haberlo visto. Ahora se
259+// abre en la tarea siguiente, cuando esa tecla ya ha terminado.
260+let colaPermisos = Promise.resolve();
207261 export function askPermission(scope, meta, detail) {
262+ const turno = colaPermisos.then(() => mostrarPermiso(scope, meta, detail));
263+ colaPermisos = turno.catch(() => {});
264+ return turno;
265+}
266+
267+function mostrarPermiso(scope, meta, detail) {
208268 return new Promise(resolve => {
209269 const dlg = $('perm-dialog');
210- permEnCurso?.(false);
211- let contestada = false;
270+ $('perm-title').textContent = `${meta?.icon || '❓'} ${tr('permWord')}: ${meta?.label || scope}`;
271+ $('perm-desc').textContent = meta?.desc || '';
272+ $('perm-detail').textContent = detail || '';
273+ const previo = document.activeElement;
274+ let hecho = false, mostrado = false;
212275 const done = ok => {
213- if (contestada) return;
214- contestada = true;
215- if (permEnCurso === done) permEnCurso = null;
276+ if (hecho) return;
277+ hecho = true;
278+ $('perm-allow').onclick = null;
279+ $('perm-deny').onclick = null;
280+ dlg.removeEventListener('cancel', alCancelar);
216281 dlg.removeEventListener('close', alCerrar);
217282 if (dlg.open) dlg.close();
218283 refreshPerms();
284+ if (previo && previo !== document.body && document.contains(previo)) {
285+ try { previo.focus({ preventScroll: true }); } catch { /* — */ }
286+ }
219287 resolve(ok);
220288 };
221- // El evento «close» llega DESPUÉS de cerrarse, ya en otra tarea: si para
222- // entonces el diálogo vuelve a estar abierto, es el cierre de la petición
223- // anterior y no va con esta.
224- const alCerrar = () => { if (!dlg.open) done(false); };
225- permEnCurso = done;
226- $('perm-title').textContent = `${meta?.icon || '❓'} ${tr('permWord')}: ${meta?.label || scope}`;
227- $('perm-desc').textContent = meta?.desc || '';
228- $('perm-detail').textContent = detail || '';
289+ const alCancelar = e => { e.preventDefault(); done(false); }; // Escape = Denegar
290+ // Cualquier otro cierre, también. Pero solo el de ESTE diálogo: el evento
291+ // «close» de la petición anterior llega en una tarea aparte, cuando esta ya
292+ // ha empezado a escuchar, y sin la guarda la denegaba antes de enseñarla.
293+ const alCerrar = () => { if (mostrado && !dlg.open) done(false); };
229294 $('perm-allow').onclick = () => done(true);
230295 $('perm-deny').onclick = () => done(false);
296+ dlg.addEventListener('cancel', alCancelar);
231297 dlg.addEventListener('close', alCerrar);
232- if (!dlg.open) dlg.showModal();
298+ setTimeout(() => {
299+ if (hecho) return;
300+ try { dlg.showModal(); mostrado = true; } catch { done(false); }
301+ }, 0);
233302 });
234303 }
235304