Elffuss BraidHub

utopia-ia/elffuss-claw public

coordinated: a keyboard-navigable command menu, shortcut help, chips that are buttons

Command menu (/):
- The button has aria-haspopup=menu, aria-expanded, aria-controls and a
  translated name; the menu is role=menu with menuitem rows. Opening it with
  the button puts focus on the first item; ↑/↓, Home and End move; Escape
  closes it and returns focus to the button. Before, ↓ did nothing, Escape did
  not close it and the items were reachable only with Shift+Tab.
- Typing "/" opens it and filters by prefix ("/sk" leaves /skills), ↑/↓ mark
  an item (aria-activedescendant on the prompt), Enter runs it, Escape closes
  it. A bare "/" is never sent to the model (it was sent as a chat message).
- After a command the prompt is empty and focused (it kept "/" and focus
  stayed on the hidden item).
- /modelo focuses the model picker (it opened Settings, where only external
  providers live); /ajustes opens Settings; /carpeta opens the folder picker
  directly; /limpiar is the new conversation with Undo; /atajos shows the
  shortcuts.
- Outside a text field, "/" goes to the prompt with the menu open and "?"
  shows a shortcuts dialog (Enter, ↑/↓, /, Esc, ?). There was no keyboard help.

Chips: real buttons (they were spans out of the tab order), built from the
page language with six entries in every language. There were five in i18n
and six in the HTML, overwritten by position: Spanish showed "Abre
https://example.com" twice and English kept one in Spanish. "Authorize a
folder" calls the folder picker in the click itself (the kernel's
autorizarCarpeta) instead of asking the model, whose turn ended after the
browser's user-activation window, so the native picker could not open.

tests/ux-teclado.mjs: the button and the menu with the keyboard, filtering,
Enter, the bare "/", /modelo, "?" and "/" outside the prompt, the six chips
in Spanish and English, and the folder chip calling a stand-in picker in the
click. It fails on the previous tree.

Coordinated: ui.js (init), kernel.js (autorizarCarpeta and the ui.init
call), i18n.js (chips, applyI18n, new keys), index.html (#chips) and
elffuss.css have uncommitted edits in the live tree in other places.
Changeseteea5aa2c1d023b6fcbdaccc7de46535861aca15f945a4b68f6f4f3fdd95fca6a
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-10 17:01 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 17:49 +02:00
Parentsbb8ba1865530

Browse the files at this changeset

6 files changed

added tests/ux-teclado.mjs +91 −0
@@ -0,0 +1,91 @@
1+// Teclado, menú de comandos y chips.
2+// · «/» (botón): menú de verdad (aria-haspopup/expanded, role=menu), el foco
3+// entra, ↑/↓ se mueven, Escape cierra y devuelve el foco.
4+// · Escribiendo «/sk» filtra, Enter ejecuta el marcado y la caja queda limpia y
5+// con el foco; un «/» suelto no se manda nunca; /modelo lleva al selector.
6+// · «?» fuera de la caja enseña los atajos; «/» fuera de la caja abre el menú.
7+// · Chips: botones, seis, sin repetidos, en el idioma de la página; «Autoriza
8+// una carpeta» abre el selector en el propio clic.
9+//
10+// BASE=http://localhost:8743 node tests/ux-teclado.mjs
11+import { navegador, contexto, pagina, ok, hasta, espera, fin } from './ux-comun.mjs';
12+
13+const b = await navegador();
14+const { ctx } = await contexto(b, { grants: ['fs', 'apps'] });
15+await ctx.addInitScript(() => {
16+ window.__picker = 0;
17+ window.showDirectoryPicker = async () => {
18+ window.__picker++;
19+ const r = await navigator.storage.getDirectory();
20+ return r.getDirectoryHandle('mi-carpeta', { create: true });
21+ };
22+});
23+const { p, errores } = await pagina(ctx);
24+const menuAbierto = () => p.evaluate(() => !document.getElementById('cmd-menu').hidden);
25+const foco = () => p.evaluate(() => document.activeElement?.id || document.activeElement?.className || document.activeElement?.tagName);
26+
27+// ── el botón «/» ────────────────────────────────────────────────────────────
28+const slash = p.locator('#btn-slash');
29+ok('el botón «/» anuncia un menú y tiene nombre', await slash.getAttribute('aria-haspopup') === 'menu'
30+ && await slash.getAttribute('aria-expanded') === 'false' && await slash.getAttribute('aria-label') === 'Comandos y skills');
31+await slash.click();
32+ok('al abrirlo: aria-expanded, role=menu y el foco en la primera opción', await menuAbierto() && await slash.getAttribute('aria-expanded') === 'true'
33+ && await p.evaluate(() => document.getElementById('cmd-menu').getAttribute('role') === 'menu' && document.activeElement?.getAttribute('role') === 'menuitem'
34+ && document.activeElement.textContent.startsWith('/reloj')));
35+await p.keyboard.press('ArrowDown');
36+ok('↓ pasa a la siguiente opción', await p.evaluate(() => document.activeElement?.textContent.startsWith('/carpeta')));
37+await p.keyboard.press('Escape');
38+ok('Escape cierra el menú y devuelve el foco al botón', !(await menuAbierto()) && await foco() === 'btn-slash');
39+
40+// ── escribiendo «/» ─────────────────────────────────────────────────────────
41+await p.focus('#prompt');
42+await p.keyboard.type('/sk');
43+ok('«/sk» filtra: solo /skills', await hasta(async () => (await p.locator('#cmd-menu .cmd-item b').allTextContents()).join(',') === '/skills'));
44+await p.keyboard.press('Enter');
45+ok('Enter ejecuta el comando marcado (abre Skills)', await hasta(() => p.evaluate(() => document.getElementById('panel-skills').classList.contains('active'))));
46+ok('…la caja queda vacía y con el foco, y no se mandó «/sk» al modelo', await p.inputValue('#prompt') === '' && await foco() === 'prompt'
47+ && await p.locator('#log .msg.user').count() === 0);
48+await p.keyboard.type('/');
49+await p.keyboard.press('Escape');
50+ok('Escape con «/» escrito cierra el menú', !(await menuAbierto()));
51+await p.keyboard.press('Enter');
52+await espera(300);
53+ok('un «/» suelto con Enter no se manda nunca', await p.locator('#log .msg.user').count() === 0);
54+await p.fill('#prompt', '');
55+await p.keyboard.type('/mod');
56+await p.keyboard.press('Enter');
57+ok('/modelo lleva al selector de modelo', await hasta(async () => await foco() === 'model-select'));
58+
59+// ── atajos fuera de la caja ─────────────────────────────────────────────────
60+await p.click('#tabs button[data-tab="vista"]');
61+await p.keyboard.press('?');
62+ok('«?» fuera de la caja enseña los atajos', await hasta(() => p.evaluate(() => document.getElementById('atajos')?.open)));
63+await p.keyboard.press('Escape');
64+ok('…y Escape los cierra', await hasta(() => p.evaluate(() => !document.getElementById('atajos').open)));
65+await p.click('#tabs button[data-tab="vista"]');
66+await p.keyboard.press('/');
67+ok('«/» fuera de la caja va a la caja con el menú abierto', await hasta(async () => await foco() === 'prompt' && await menuAbierto()));
68+await p.keyboard.press('Escape');
69+await p.fill('#prompt', '');
70+
71+// ── chips ───────────────────────────────────────────────────────────────────
72+const chips = await p.$$eval('#chips .chip', cs => cs.map(c => ({ tag: c.tagName, t: c.textContent, a: c.dataset.accion || '' })));
73+ok('seis chips, botones, sin repetidos', chips.length === 6 && chips.every(c => c.tag === 'BUTTON') && new Set(chips.map(c => c.t)).size === 6, JSON.stringify(chips));
74+ok('…incluidas las de skill e imágenes', chips.some(c => /skill/.test(c.t)) && chips.some(c => /auroras/.test(c.t)));
75+await p.locator('#chips .chip[data-accion="carpeta"]').click();
76+ok('«Autoriza una carpeta» abre el selector en el propio clic (sin esperar al modelo)', await hasta(() => p.evaluate(() => window.__picker === 1)));
77+ok('…y la carpeta queda autorizada y dicha en el chat', await hasta(async () => /Carpeta «mi-carpeta» autorizada/.test(await p.locator('#log').innerText())));
78+await p.locator('#chips .chip', { hasText: 'Hazme un reloj' }).click();
79+ok('un chip normal se manda como mensaje', await hasta(async () => /Hazme un reloj/.test(await p.locator('#log .msg.user').allInnerTexts().then(a => a.join(' ')))));
80+{
81+ const { ctx: c2 } = await contexto(b, { locale: 'en-US' });
82+ const { p: e } = await pagina(c2);
83+ const en = await e.$$eval('#chips .chip', cs => cs.map(c => c.textContent));
84+ const es = ['Hazme un reloj', 'Crea una app de notas', 'Autoriza una carpeta', 'Créame una skill para organizar mis descargas', 'Busca fotos de auroras boreales', 'Abre https://example.com'];
85+ ok('en inglés: seis chips en inglés', en.length === 6 && !en.some(t => es.includes(t)) && en[0] === 'Make me a clock', JSON.stringify(en));
86+ ok('en inglés el botón «/» se llama «Commands and skills»', await e.getAttribute('#btn-slash', 'aria-label') === 'Commands and skills');
87+ await c2.close();
88+}
89+
90+ok('sin errores de página', errores.length === 0, errores.slice(0, 3).join(' | '));
91+await fin(b, 'TECLADO: menú «/» navegable y filtrable, atajos, chips que son botones');
modified web/css/elffuss.css +12 −2
@@ -141,15 +141,18 @@
141141
142142 #chips { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 14px; }
143143 .chip {
144+ font: inherit;
144145 font-size: .78rem;
145146 color: var(--muted);
147+ background: none;
146148 border: 1px solid var(--line);
147149 border-radius: 999px;
148150 padding: 4px 12px;
149151 cursor: pointer;
150152 transition: all .15s;
151153 }
152-.chip:hover { color: var(--fg); border-color: var(--accent); }
154+.chip:hover, .chip:focus-visible { color: var(--fg); border-color: var(--accent); }
155+.chip:focus-visible { outline: 2px solid var(--accent2); outline-offset: 1px; }
153156
154157 /* El campo de texto va en SU PROPIA FILA y los botones debajo.
155158 Antes compartía fila con ellos, y como los botones se inyectan desde el JS la
@@ -550,7 +553,14 @@
550553 }
551554 #cmd-menu[hidden] { display: none; }
552555 .cmd-item { display: flex; justify-content: space-between; gap: 12px; width: 100%; text-align: left; background: none; border: none; color: var(--fg); padding: 8px 12px; border-radius: 8px; cursor: pointer; font-size: .86rem; }
553-.cmd-item:hover { background: #ffffff10; }
556+.cmd-item:hover, .cmd-item.activo, .cmd-item:focus-visible { background: #ffffff14; outline: none; }
557+.cmd-item.activo { box-shadow: inset 2px 0 0 var(--accent2); }
558+.cmd-vacio { padding: 8px 12px; color: var(--muted); font-size: .82rem; }
559+/* atajos de teclado («?» o /atajos) */
560+dl.atajos { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; margin: 8px 0 4px; font-size: .88rem; }
561+dl.atajos dt { text-align: right; }
562+dl.atajos dd { margin: 0; color: var(--muted); }
563+kbd { font-family: ui-monospace, monospace; font-size: .8rem; background: var(--bg3); border: 1px solid var(--line); border-bottom-width: 2px; border-radius: 5px; padding: 1px 6px; }
554564 .cmd-item b { font-family: ui-monospace, monospace; font-weight: 600; }
555565 .cmd-item span { color: var(--muted); font-size: .76rem; }
556566 #chat { position: relative; }
modified web/index.html +7 −7
@@ -59,13 +59,13 @@
5959 Puedo usar tus carpetas (si me das permiso), guardar secretos cifrados,
6060 programar tareas y navegar por ti. Todo se queda en tu máquina.</div>
6161 </div>
62- <div id="chips">
63- <span class="chip">Hazme un reloj</span>
64- <span class="chip">Crea una app de notas</span>
65- <span class="chip">Autoriza una carpeta</span>
66- <span class="chip">Créame una skill para organizar mis descargas</span>
67- <span class="chip">Busca fotos de auroras boreales</span>
68- <span class="chip">Abre https://example.com</span>
62+ <div id="chips" role="group" aria-label="Sugerencias">
63+ <button type="button" class="chip">Hazme un reloj</button>
64+ <button type="button" class="chip">Crea una app de notas</button>
65+ <button type="button" class="chip" data-accion="carpeta">Autoriza una carpeta</button>
66+ <button type="button" class="chip">Créame una skill para organizar mis descargas</button>
67+ <button type="button" class="chip">Busca fotos de auroras boreales</button>
68+ <button type="button" class="chip">Abre https://example.com</button>
6969 </div>
7070 <div id="cmd-menu" hidden></div>
7171 <form id="composer">
modified web/js/i18n.js +36 −9
@@ -5,7 +5,11 @@
55 es: {
66 welcome: 'Un sistema operativo con alma que vive en tu navegador. Aquí las apps no se instalan: se crean cuando las pides y aparecen a la derecha. Puedo usar tus carpetas (si me das permiso), guardar secretos cifrados, programar tareas y navegar por ti. Todo se queda en tu máquina.',
77 hi: 'Hola, soy Elffuss.',
8- chips: ['Hazme un reloj', 'Crea una app de notas', 'Autoriza una carpeta', 'Recuérdame en 1 minuto que estire', 'Abre https://example.com'],
8+ // Seis, alineadas con las del HTML (la 3.ª abre el selector de carpetas, ver
9+ // CHIP_ACCIONES). Eran cinco y se pisaban por posición con las seis del HTML:
10+ // en español salía «Abre https://example.com» dos veces y en inglés la sexta
11+ // se quedaba en español.
12+ chips: ['Hazme un reloj', 'Crea una app de notas', 'Autoriza una carpeta', 'Créame una skill para organizar mis descargas', 'Busca fotos de auroras boreales', 'Abre https://example.com'],
913 tabs: { vista: 'Vista', apps: 'Apps', tareas: 'Tareas', vault: 'Bóveda', skills: 'Skills', permisos: 'Permisos', ajustes: 'Ajustes' },
1014 ph: 'Pídeme lo que necesites… (/ para comandos)',
1115 perms: 'Permisos', empty: 'Aquí aparece lo que Elffuss crea.', tryit: 'Prueba: «hazme un reloj»',
@@ -53,7 +57,7 @@
5357 writeSomething: 'escribe algo primero', sentThanks: '¡enviado, gracias!',
5458 flipChat: '💬 Chat', flipView: '✳ Vista',
5559 cmClock: 'crear un reloj', cmFolder: 'autorizar una carpeta', cmSkills: 'gestionar skills y plugins',
56- cmModel: 'modelo y API keys', cmTasks: 'ver tareas programadas', cmVault: 'secretos cifrados', cmClear: 'nueva conversación',
60+ cmModel: 'elegir el modelo (arriba)', cmTasks: 'ver tareas programadas', cmVault: 'secretos cifrados', cmClear: 'nueva conversación',
5761 pClock: 'hazme un reloj', pFolder: 'autoriza una carpeta',
5862 // permisos (modal + panel + detalles por tool)
5963 permWord: 'Permiso', permDeny: 'Denegar', permAllow: 'Permitir',
@@ -179,11 +183,16 @@
179183 folderRemoveSoulNext: 'La Mente escribe en esta carpeta; pasará a escribir en «{next}».',
180184 folderRemoveSoulNone: 'La Mente escribe en esta carpeta; sin carpetas no podrá guardar propuestas.',
181185 folderRemoved: 'Carpeta «{name}» quitada', folderRemovedWatches: '{n} automatización(es) quitada(s)',
186+ chipsL: 'Sugerencias', cmdMenuL: 'Comandos y skills', cmSettings: 'modelos externos y API keys', cmKeys: 'atajos de teclado',
187+ cmNone: 'Ningún comando empieza así', keysTitle: 'Atajos de teclado',
188+ keyEnter: 'Enviar (si estoy trabajando, va a la cola)', keyHist: 'Recuperar lo que enviaste antes',
189+ keySlash: 'Comandos: escribe para filtrar, ↑/↓ y Enter para elegir', keyEsc: 'Cerrar lo que esté abierto: menú, panel, la Mente, un diálogo',
190+ keyHelp: 'Esta ayuda (fuera de la caja de texto)',
182191 },
183192 en: {
184193 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.',
185194 hi: 'Hi, I’m Elffuss.',
186- chips: ['Make me a clock', 'Create a notes app', 'Authorize a folder', 'Remind me in 1 minute to stretch', 'Open https://example.com'],
195+ chips: ['Make me a clock', 'Create a notes app', 'Authorize a folder', 'Create a skill to organize my downloads', 'Find photos of the northern lights', 'Open https://example.com'],
187196 tabs: { vista: 'View', apps: 'Apps', tareas: 'Tasks', vault: 'Vault', skills: 'Skills', permisos: 'Permissions', ajustes: 'Settings' },
188197 ph: 'Ask me anything… (/ for commands)',
189198 perms: 'Permissions', empty: 'Whatever Elffuss creates shows up here.', tryit: 'Try: “make me a clock”',
@@ -229,7 +238,7 @@
229238 writeSomething: 'write something first', sentThanks: 'sent, thank you!',
230239 flipChat: '💬 Chat', flipView: '✳ View',
231240 cmClock: 'make a clock', cmFolder: 'authorize a folder', cmSkills: 'manage skills & plugins',
232- cmModel: 'model & API keys', cmTasks: 'see scheduled tasks', cmVault: 'encrypted secrets', cmClear: 'new conversation',
241+ cmModel: 'pick the model (at the top)', cmTasks: 'see scheduled tasks', cmVault: 'encrypted secrets', cmClear: 'new conversation',
233242 pClock: 'make me a clock', pFolder: 'authorize a folder',
234243 permWord: 'Permission', permDeny: 'Deny', permAllow: 'Allow',
235244 permDenied: 'Permission “{label}” denied by the user',
@@ -354,11 +363,16 @@
354363 folderRemoveSoulNext: 'The Mind writes in this folder; it will write in “{next}” instead.',
355364 folderRemoveSoulNone: 'The Mind writes in this folder; with no folders it cannot save proposals.',
356365 folderRemoved: 'Folder “{name}” removed', folderRemovedWatches: '{n} automation(s) removed',
366+ chipsL: 'Suggestions', cmdMenuL: 'Commands and skills', cmSettings: 'external models and API keys', cmKeys: 'keyboard shortcuts',
367+ cmNone: 'No command starts like that', keysTitle: 'Keyboard shortcuts',
368+ keyEnter: 'Send (while I am working, it is queued)', keyHist: 'Recall what you sent before',
369+ keySlash: 'Commands: type to filter, ↑/↓ and Enter to choose', keyEsc: 'Close whatever is open: menu, panel, the Mind, a dialog',
370+ keyHelp: 'This help (outside the text box)',
357371 },
358372 uk: {
359373 welcome: "Операційна система з душею, що живе у твоєму браузері. Тут застосунки не встановлюють — їх створюють на твій запит, і вони з’являються праворуч. Можу працювати з твоїми теками (за дозволом), зберігати зашифровані секрети, планувати завдання й гортати за тебе. Усе лишається на твоєму пристрої.",
360374 hi: "Привіт, я Elffuss.",
361- chips: ["Зроби мені годинник", "Створи застосунок нотаток", "Дозволь теку", "Нагадай за 1 хв розім’ятися", "Відкрий https://example.com"],
375+ chips: ["Зроби мені годинник", "Створи застосунок нотаток", "Дозволь теку", "Створи навичку, щоб упорядкувати мої завантаження", "Знайди фото північного сяйва", "Відкрий https://example.com"],
362376 tabs: {
363377 vista: "Вигляд",
364378 apps: "Застосунки",
@@ -432,7 +446,7 @@
432446 fr: {
433447 welcome: "Un système d’exploitation avec une âme qui vit dans ton navigateur. Ici les apps ne s’installent pas : elles se créent quand tu les demandes, à droite. Je peux utiliser tes dossiers (avec permission), garder des secrets chiffrés, planifier des tâches et naviguer pour toi. Tout reste sur ta machine.",
434448 hi: "Salut, je suis Elffuss.",
435- chips: ["Fais-moi une horloge", "Crée une app de notes", "Autorise un dossier", "Rappelle-moi dans 1 min de m’étirer", "Ouvre https://example.com"],
449+ chips: ["Fais-moi une horloge", "Crée une app de notes", "Autorise un dossier", "Crée-moi une skill pour ranger mes téléchargements", "Cherche des photos d’aurores boréales", "Ouvre https://example.com"],
436450 tabs: {
437451 vista: "Vue",
438452 apps: "Apps",
@@ -506,7 +520,7 @@
506520 de: {
507521 welcome: "Ein Betriebssystem mit Seele, das in deinem Browser lebt. Apps werden hier nicht installiert – sie entstehen, wenn du fragst, und erscheinen rechts. Ich kann deine Ordner nutzen (mit Erlaubnis), verschlüsselte Geheimnisse speichern, Aufgaben planen und für dich surfen. Alles bleibt auf deinem Gerät.",
508522 hi: "Hallo, ich bin Elffuss.",
509- chips: ["Bau mir eine Uhr", "Erstelle eine Notiz-App", "Ordner freigeben", "Erinnere mich in 1 Min ans Strecken", "Öffne https://example.com"],
523+ chips: ["Bau mir eine Uhr", "Erstelle eine Notiz-App", "Ordner freigeben", "Erstelle mir einen Skill, der meine Downloads ordnet", "Such Fotos von Polarlichtern", "Öffne https://example.com"],
510524 tabs: {
511525 vista: "Ansicht",
512526 apps: "Apps",
@@ -580,7 +594,7 @@
580594 pt: {
581595 welcome: "Um sistema operativo com alma que vive no teu navegador. Aqui as apps não se instalam: criam-se quando pedes e aparecem à direita. Posso usar as tuas pastas (com permissão), guardar segredos cifrados, agendar tarefas e navegar por ti. Tudo fica na tua máquina.",
582596 hi: "Olá, sou a Elffuss.",
583- chips: ["Faz-me um relógio", "Cria uma app de notas", "Autoriza uma pasta", "Lembra-me em 1 min de me esticar", "Abre https://example.com"],
597+ chips: ["Faz-me um relógio", "Cria uma app de notas", "Autoriza uma pasta", "Cria-me uma skill para organizar as minhas transferências", "Procura fotos de auroras boreais", "Abre https://example.com"],
584598 tabs: {
585599 vista: "Vista",
586600 apps: "Apps",
@@ -667,6 +681,8 @@
667681 return vars ? s.replace(/\{(\w+)\}/g, (_, k) => (vars[k] ?? '')) : s;
668682 }
669683
684+const CHIP_ACCIONES = [null, null, 'carpeta', null, null, null];
685+
670686 export function applyI18n() {
671687 const code = uiLang();
672688 const t = L[code] || L.en;
@@ -687,7 +703,18 @@
687703 b.textContent = t.hi;
688704 sys.append(b, ' ' + t.welcome);
689705 }
690- document.querySelectorAll('#chips .chip').forEach((c, i) => { if (t.chips[i]) c.textContent = t.chips[i]; });
706+ // Los chips salen del idioma, enteros (antes se sobrescribían por posición y
707+ // sobraban o faltaban). La acción va por posición: la 3.ª abre el selector.
708+ const chips = $('#chips');
709+ if (chips && Array.isArray(t.chips)) {
710+ chips.replaceChildren(...t.chips.map((txt, i) => {
711+ const b = document.createElement('button');
712+ b.type = 'button'; b.className = 'chip'; b.textContent = txt;
713+ if (CHIP_ACCIONES[i]) b.dataset.accion = CHIP_ACCIONES[i];
714+ return b;
715+ }));
716+ chips.setAttribute('aria-label', t.chipsL || L.en.chipsL);
717+ }
691718 document.querySelectorAll('#tabs button').forEach(b => { const k = b.dataset.tab; if (t.tabs[k]) b.textContent = t.tabs[k]; });
692719 $('#tabs')?.setAttribute('aria-label', t.tabsLabel || L.en.tabsLabel);
693720 const ph = $('#prompt'); if (ph) ph.placeholder = t.ph;
modified web/js/kernel.js +14 −1
@@ -790,7 +790,20 @@
790790 }
791791
792792 skills.initSkills();
793-ui.init({ onSend: send, onStop: stopCurrent, onModelChange: changeModel, onSettingsChanged: refreshModelOptions });
793+// «Autoriza una carpeta» (el chip y /carpeta): el selector nativo se abre AQUÍ,
794+// en el clic. Mandándoselo al modelo se abría al final de su turno, cuando el
795+// navegador ya no lo permitía (pide un gesto reciente del usuario).
796+async function autorizarCarpeta() {
797+ try {
798+ const r = await fs.pickFolder();
799+ ui.addMsg('assistant', r);
800+ agent.history.push({ role: 'user', content: t('pFolder'), ts: Date.now() }, { role: 'assistant', content: r, ts: Date.now() });
801+ db.set('kv', 'history', agent.history.slice(-80)).catch(() => {});
802+ } catch (e) {
803+ if (e?.name !== 'AbortError') ui.toast('⚠️ ' + (e?.message || e)); // cancelar el selector no es un error
804+ }
805+}
806+ui.init({ onSend: send, onStop: stopCurrent, onModelChange: changeModel, onSettingsChanged: refreshModelOptions, onPickFolder: autorizarCarpeta });
794807 ui.mountDiskChip(); // cuánto ocupan los modelos en este navegador, y cómo vaciarlo
795808 // Botón «liberar el modelo» del panel de consumo: suelta la RAM sin recargar.
796809 ui.setOnFreeModel(async () => {
modified web/js/ui.js +142 −20
@@ -1311,7 +1311,7 @@
13111311 }
13121312
13131313 // ---------- arranque ----------
1314-export function init({ onSend, onStop = () => {}, onModelChange, onSettingsChanged }) {
1314+export function init({ onSend, onStop = () => {}, onModelChange, onSettingsChanged, onPickFolder = () => onSend(tr('pFolder')) }) {
13151315 perms.setAsker(askPermission);
13161316 apps.setRenderer((name, html) => renderApp(name, html, { ruta: true }));
13171317 apps.setOnRemoved(vaciarVisor);
@@ -1351,7 +1351,7 @@
13511351 // va a la cola como siempre, y sin texto no hace nada —un segundo Enter
13521352 // dado por inercia no debe tirar el trabajo en curso—. Parar es el ■.
13531353 const text = $('prompt').value.trim();
1354- if (!text) return;
1354+ if (!text || text === '/') return; // un «/» suelto es abrir el menú, no un mensaje
13551355 $('prompt').value = '';
13561356 if (hist[hist.length - 1] !== text) hist.push(text);
13571357 if (hist.length > 100) hist = hist.slice(-100);
@@ -1359,8 +1359,15 @@
13591359 hIdx = -1; draft = '';
13601360 onSend(text);
13611361 });
1362- document.querySelectorAll('#chips .chip').forEach(c =>
1363- c.addEventListener('click', () => onSend(c.textContent)));
1362+ // Chips: botones (antes <span> sin foco). «Autoriza una carpeta» abre el
1363+ // selector de carpetas EN el clic: pasándoselo al modelo, el selector nativo
1364+ // llegaba después de su turno y el navegador ya no lo dejaba abrir.
1365+ $('chips').addEventListener('click', e => {
1366+ const c = e.target.closest('.chip');
1367+ if (!c) return;
1368+ if (c.dataset.accion === 'carpeta') onPickFolder();
1369+ else onSend(c.textContent.trim());
1370+ });
13641371 document.querySelectorAll('#tabs button').forEach(b =>
13651372 b.addEventListener('click', () => selectTab(b.dataset.tab, { push: true })));
13661373 // Flechas, Inicio y Fin entre pestañas (patrón de tablist): solo la activa
@@ -1398,33 +1405,148 @@
13981405 setWorking(working); // icono, título y aria del botón enviar/parar
13991406 $('btn-slash').innerHTML = UI.slash;
14001407
1401- // menú de comandos (/) en el chat, estilo plugin de Claude Code
1408+ // menú de comandos (/) en el chat, estilo plugin de Claude Code.
1409+ // Un menú de verdad: role=menu, ↑/↓/Inicio/Fin, Enter, Escape, y el foco
1410+ // vuelve a donde toca. Escribiendo «/» filtra por prefijo («/sk» → /skills) y
1411+ // Enter ejecuta el marcado; un «/» suelto nunca se manda al modelo. Después
1412+ // de ejecutar, la caja queda limpia y con el foco.
1413+ const verPanel = tab => { selectTab(tab, { push: true }); if (isMobile()) flipTo('viz'); };
14021414 const cmds = [
14031415 { label: '/reloj', hint: tr('cmClock'), run: () => onSend(tr('pClock')) },
1404- { label: '/carpeta', hint: tr('cmFolder'), run: () => onSend(tr('pFolder')) },
1405- { label: '/skills', hint: tr('cmSkills'), run: () => { selectTab('skills'); if (isMobile()) flipTo('viz'); } },
1406- { label: '/modelo', hint: tr('cmModel'), run: () => { selectTab('ajustes'); if (isMobile()) flipTo('viz'); } },
1407- { label: '/tareas', hint: tr('cmTasks'), run: () => { selectTab('tareas'); if (isMobile()) flipTo('viz'); } },
1408- { label: '/vault', hint: tr('cmVault'), run: () => { selectTab('vault'); if (isMobile()) flipTo('viz'); } },
1416+ { label: '/carpeta', hint: tr('cmFolder'), run: () => onPickFolder() }, // el selector nativo se abre en el gesto
1417+ { label: '/skills', hint: tr('cmSkills'), run: () => verPanel('skills') },
1418+ { label: '/modelo', hint: tr('cmModel'), run: () => enfocarSelectorModelo(), foco: false },
1419+ { label: '/ajustes', hint: tr('cmSettings'), run: () => verPanel('ajustes') },
1420+ { label: '/tareas', hint: tr('cmTasks'), run: () => verPanel('tareas') },
1421+ { label: '/vault', hint: tr('cmVault'), run: () => verPanel('vault') },
14091422 { label: '/limpiar', hint: tr('cmClear'), run: () => $('btn-clear').click() },
1423+ { label: '/atajos', hint: tr('cmKeys'), run: () => mostrarAtajos(), foco: false },
14101424 ];
14111425 const cmdMenu = $('cmd-menu');
1412- const openCmd = () => {
1426+ const slash = $('btn-slash');
1427+ const caja = $('prompt');
1428+ cmdMenu.setAttribute('role', 'menu');
1429+ cmdMenu.setAttribute('aria-label', tr('cmdMenuL'));
1430+ slash.setAttribute('aria-haspopup', 'menu');
1431+ slash.setAttribute('aria-controls', 'cmd-menu');
1432+ slash.setAttribute('aria-expanded', 'false');
1433+ slash.title = tr('cmdMenuL');
1434+ slash.setAttribute('aria-label', tr('cmdMenuL'));
1435+ const sinTilde = x => x.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
1436+ let visibles = [], activo = -1;
1437+ const filas = () => [...cmdMenu.querySelectorAll('.cmd-item')];
1438+ const marcar = i => {
1439+ const fs = filas();
1440+ activo = fs.length ? (i + fs.length) % fs.length : -1;
1441+ fs.forEach((f, j) => f.classList.toggle('activo', j === activo));
1442+ if (activo >= 0) { caja.setAttribute('aria-activedescendant', fs[activo].id); fs[activo].scrollIntoView({ block: 'nearest' }); }
1443+ else caja.removeAttribute('aria-activedescendant');
1444+ };
1445+ const pintarMenu = (filtro = '/') => {
1446+ const f = sinTilde(filtro);
1447+ visibles = cmds.filter(c => sinTilde(c.label).startsWith(f));
14131448 cmdMenu.replaceChildren();
1414- for (const c of cmds) {
1449+ visibles.forEach((c, i) => {
14151450 const row = document.createElement('button');
1451+ row.type = 'button';
14161452 row.className = 'cmd-item';
1417- row.innerHTML = `<b>${c.label}</b><span>${c.hint}</span>`;
1418- row.onclick = () => { cmdMenu.hidden = true; c.run(); };
1453+ row.id = 'cmd-' + i;
1454+ row.setAttribute('role', 'menuitem');
1455+ row.tabIndex = -1;
1456+ const b = document.createElement('b'); b.textContent = c.label;
1457+ const h = document.createElement('span'); h.textContent = c.hint;
1458+ row.append(b, h);
1459+ row.onclick = () => ejecutar(c);
14191460 cmdMenu.appendChild(row);
1420- }
1461+ });
1462+ if (!visibles.length) cmdMenu.appendChild(el('div', 'cmd-vacio', tr('cmNone')));
1463+ marcar(0);
1464+ };
1465+ const abrirMenu = (filtro = '/') => {
1466+ pintarMenu(filtro);
14211467 cmdMenu.hidden = false;
1468+ slash.setAttribute('aria-expanded', 'true');
1469+ };
1470+ const cerrarMenu = ({ foco = null } = {}) => {
1471+ if (cmdMenu.hidden) return;
1472+ cmdMenu.hidden = true;
1473+ slash.setAttribute('aria-expanded', 'false');
1474+ caja.removeAttribute('aria-activedescendant');
1475+ activo = -1;
1476+ foco?.focus();
14221477 };
1423- $('btn-slash').addEventListener('click', () => cmdMenu.hidden ? openCmd() : (cmdMenu.hidden = true));
1424- $('prompt').addEventListener('input', e => {
1425- if (e.target.value === '/') openCmd(); else if (cmdMenu && !cmdMenu.hidden && !e.target.value.startsWith('/')) cmdMenu.hidden = true;
1426- });
1427- document.addEventListener('click', e => { if (!e.target.closest('#cmd-menu, #btn-slash, #prompt')) cmdMenu.hidden = true; });
1478+ const ejecutar = c => {
1479+ cerrarMenu();
1480+ if (caja.value.trim().startsWith('/')) caja.value = '';
1481+ c.run();
1482+ if (c.foco !== false) caja.focus();
1483+ };
1484+ slash.addEventListener('click', () => {
1485+ if (!cmdMenu.hidden) { cerrarMenu({ foco: slash }); return; }
1486+ abrirMenu('/');
1487+ filas()[0]?.focus();
1488+ });
1489+ // Dentro del menú (abierto con el botón): flechas, Inicio/Fin, Escape.
1490+ cmdMenu.addEventListener('keydown', e => {
1491+ const fs = filas();
1492+ const i = fs.indexOf(document.activeElement);
1493+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Home' || e.key === 'End') {
1494+ e.preventDefault();
1495+ const j = e.key === 'Home' ? 0 : e.key === 'End' ? fs.length - 1 : i + (e.key === 'ArrowDown' ? 1 : -1);
1496+ marcar(j); fs[activo]?.focus();
1497+ } else if (e.key === 'Escape') {
1498+ e.preventDefault(); e.stopPropagation();
1499+ cerrarMenu({ foco: slash });
1500+ } else if (e.key === 'Tab') {
1501+ cerrarMenu();
1502+ }
1503+ });
1504+ // Escribiendo «/…» en la caja: filtra, ↑/↓ marcan, Enter ejecuta, Escape cierra.
1505+ caja.addEventListener('input', () => {
1506+ const v = caja.value;
1507+ if (/^\/\S*$/.test(v)) abrirMenu(v);
1508+ else cerrarMenu();
1509+ });
1510+ caja.addEventListener('keydown', e => {
1511+ if (cmdMenu.hidden) return;
1512+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); marcar(activo + (e.key === 'ArrowDown' ? 1 : -1)); }
1513+ else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cerrarMenu(); }
1514+ else if (e.key === 'Enter' && activo >= 0 && visibles[activo]) { e.preventDefault(); ejecutar(visibles[activo]); }
1515+ });
1516+ document.addEventListener('click', e => { if (!e.target.closest('#cmd-menu, #btn-slash, #prompt')) cerrarMenu(); });
1517+
1518+ // Atajos globales fuera de un campo de texto: «/» va a la caja con el menú
1519+ // abierto y «?» enseña la lista de atajos.
1520+ document.addEventListener('keydown', e => {
1521+ if (e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return;
1522+ const t = e.target;
1523+ if (t?.closest?.('input, textarea, select, [contenteditable], dialog, #mind-overlay')) return;
1524+ if (e.key === '/') { e.preventDefault(); if (isMobile()) flipTo('chat'); caja.focus(); caja.value = '/'; abrirMenu('/'); }
1525+ else if (e.key === '?') { e.preventDefault(); mostrarAtajos(); }
1526+ });
1527+}
1528+
1529+// La lista de atajos (antes no había ayuda de teclado en ninguna parte).
1530+function mostrarAtajos() {
1531+ let d = $('atajos');
1532+ if (!d) {
1533+ d = document.createElement('dialog');
1534+ d.id = 'atajos';
1535+ d.setAttribute('aria-labelledby', 'atajos-t');
1536+ const h = el('h3', null, tr('keysTitle'));
1537+ h.id = 'atajos-t';
1538+ const dl = document.createElement('dl');
1539+ dl.className = 'atajos';
1540+ for (const [k, v] of [['Enter', 'keyEnter'], ['↑ / ↓', 'keyHist'], ['/', 'keySlash'], ['Esc', 'keyEsc'], ['?', 'keyHelp']]) {
1541+ const dt = el('dt'); dt.appendChild(el('kbd', null, k));
1542+ dl.append(dt, el('dd', null, tr(v)));
1543+ }
1544+ const cerrar = btn(tr('close'), 'primary', () => d.close());
1545+ const fila = el('div', 'row right'); fila.appendChild(cerrar);
1546+ d.append(h, dl, fila);
1547+ document.body.appendChild(d);
1548+ }
1549+ if (!d.open) d.showModal();
14281550 }
14291551
14301552