Elffuss BraidHub

utopia-ia/elffuss-code public

Skills panel: installed and browse kept apart, one action per row

The panel mixed everything in one list: the browse results were appended at
the bottom below "Add repo", far from the button that opened them; custom
catalogs had two actions per row; installing closed the panel; names were cut
to "Co..." at phone width; catalog names and errors were Spanish only.

Now there are two headed sections, Installed and Browse catalogs. A catalog
opens its list inside its own card (Browse/Hide with aria-expanded). Each row
has one action; a custom catalog is removed from inside its list. Installing
keeps the panel open, turns the button into "Installed" (aria-disabled, focus
kept), adds the skill above, announces it and posts the usage note in the
chat. Removing updates in place and moves focus to the next row or the
heading. Rows wrap at phone width. Catalog names, errors and the usage note
follow the UI language (es/en).

Test: tests/skills-panel-ux.mjs
Changeset578b9e98be75713ade9d89ab9e62284d69ef7f290bc0ab35e5f5d286bc570132
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-12 09:53 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-12 09:53 +02:00
Parentsdb6defa10cbc

Browse the files at this changeset

5 files changed

added tests/skills-panel-ux.mjs +141 −0
@@ -0,0 +1,141 @@
1+// Panel de Skills: claro de usar, con teclado y en el teléfono. GitHub se
2+// stubea aquí (nada sale a la red).
3+//
4+// 1. Dos partes que no se mezclan: «Instaladas» y «Explorar catálogos», cada
5+// una con su encabezado, y una sola acción por fila.
6+// 2. «Explorar» abre la lista DENTRO de la tarjeta del catálogo (antes se
7+// añadía al final del panel, debajo de «Añadir repo») y otra vez la cierra
8+// (aria-expanded).
9+// 3. «Instalar» NO cierra el panel: el botón pasa a «Instalada ✓», conserva
10+// el foco, la skill aparece arriba y el chat recibe el «cómo usarla».
11+// 4. «Quitar» la quita al momento, el foco no cae a <body> y la lista
12+// abierta vuelve a ofrecer «Instalar».
13+// 5. Un catálogo añadido por ti se quita desde dentro de su lista.
14+// 6. En el teléfono los nombres no se cortan («Co…») ni hay desplazamiento
15+// lateral, y los botones caben.
16+// 7. En inglés, todo en inglés (también los nombres de los catálogos y los
17+// errores).
18+//
19+// BASE=http://127.0.0.1:8898 node tests/skills-panel-ux.mjs
20+import { chromium } from 'playwright';
21+const BASE = process.env.BASE || 'http://localhost:8799';
22+let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
23+
24+const REPO = 'anthropics/skills';
25+const ARBOL = { tree: [{ path: 'skills/pdf/SKILL.md' }, { path: 'skills/docx/SKILL.md' }] };
26+const md = n => `---\nname: ${n}\ndescription: Hace cosas de ${n}.\n---\nInstrucciones de ${n}.`;
27+const b = await chromium.launch();
28+async function abre(locale, viewport, movil = false) {
29+ const ctx = await b.newContext({ locale, viewport, isMobile: movil, hasTouch: movil });
30+ await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
31+ await ctx.route('**/*', r => {
32+ const u = r.request().url();
33+ if (u.startsWith('https://api.github.com/repos/')) return u.includes('/no/existe/') ? r.fulfill({ status: 404, body: '{}' }) : r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(ARBOL) });
34+ if (u.startsWith('https://raw.githubusercontent.com/')) return r.fulfill({ status: 200, contentType: 'text/plain', body: md(u.match(/skills\/([^/]+)\/SKILL/)?.[1] || 'x') });
35+ if (/soundcloud|huggingface|hf\.co/.test(u)) return r.abort();
36+ return r.continue();
37+ });
38+ const p = await ctx.newPage();
39+ p.errs = []; p.on('pageerror', e => p.errs.push(e.message.slice(0, 160)));
40+ await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' });
41+ await p.waitForFunction(() => window.elffussClaw?.conv?.getActive?.(), null, { timeout: 30000 });
42+ return { ctx, p };
43+}
44+const foco = p => p.evaluate(() => { const a = document.activeElement; return !a || a === document.body ? 'BODY' : (a.getAttribute('aria-label') || a.textContent || a.id).trim().slice(0, 60); });
45+const enter = async (p, loc) => { await loc.focus(); await p.keyboard.press('Enter'); };
46+
47+// ── escritorio, en español y con teclado ──
48+{
49+ const { ctx, p } = await abre('es-ES', { width: 1280, height: 800 });
50+ await p.click('#act-skills');
51+ await p.waitForSelector('#settings-panel .sk-catalogos .sk-cat');
52+ const heads = await p.$$eval('#settings-panel .skills-panel h4', hs => hs.map(h => h.textContent));
53+ ok('1 · dos partes con encabezado: Instaladas y Explorar catálogos', heads.length === 2 && /^Instaladas \(0\)$/.test(heads[0]) && /^Explorar catálogos$/.test(heads[1]), JSON.stringify(heads));
54+ const acciones = await p.$$eval('#settings-panel .sk-catalogos .sk-cat', fs => fs.map(f => f.querySelectorAll(':scope > button').length));
55+ ok('1 · cada catálogo tiene UNA acción', acciones.length >= 3 && acciones.every(n => n === 1), JSON.stringify(acciones));
56+
57+ const tarjeta = p.locator(`#settings-panel .sk-cat[data-repo="${REPO}"]`);
58+ const explorar = tarjeta.locator(':scope > button');
59+ await enter(p, explorar);
60+ await p.waitForFunction(r => document.querySelector(`.sk-cat[data-repo="${r}"] .sk-browse .sk-install`), REPO);
61+ ok('2 · «Explorar» abre la lista DENTRO de la tarjeta del catálogo', await tarjeta.locator('.sk-browse .sk-row').count() === 2
62+ && await explorar.getAttribute('aria-expanded') === 'true' && await explorar.innerText() === 'Ocultar');
63+ ok('2 · …y el foco sigue en el botón', (await foco(p)) === 'Explorar anthropics/skills', await foco(p));
64+
65+ const nombre = (await tarjeta.locator('.sk-install', { hasText: 'Instalar' }).first().getAttribute('aria-label')).replace(/^Instalar: /, '');
66+ const instalar = tarjeta.locator(`.sk-install[data-nombre="${nombre}"]`);
67+ await enter(p, instalar);
68+ await p.waitForFunction(() => document.querySelectorAll('#settings-panel .sk-instaladas .sk-row').length === 1);
69+ ok('3 · instalar NO cierra el panel', await p.isVisible('#settings-panel'));
70+ ok('3 · el botón pasa a «Instalada ✓» (inerte) y conserva el foco', await instalar.getAttribute('aria-disabled') === 'true'
71+ && (await foco(p)) === `Instalada ✓: ${nombre}`, await foco(p));
72+ ok('3 · la skill aparece arriba y el contador sube', /^Instaladas \(1\)$/.test(await p.textContent('#sk-inst-h'))
73+ && (await p.innerText('#settings-panel .sk-instaladas .sk-row b')) === nombre);
74+ ok('3 · el aviso lo dice y el chat tiene el «cómo usarla»', /instalada/.test(await p.innerText('.skills-panel > .sk-msg'))
75+ && await p.evaluate(n => [...document.querySelectorAll('#chat-log .msg')].some(m => m.textContent.includes(`Skill «${n}» instalada`)), nombre));
76+
77+ await enter(p, p.locator('#settings-panel .sk-instaladas .sk-remove').first());
78+ await p.waitForTimeout(200);
79+ ok('4 · «Quitar» la quita al momento', /^Instaladas \(0\)$/.test(await p.textContent('#sk-inst-h')));
80+ ok('4 · …el foco no cae a <body> (va al encabezado)', (await foco(p)) === 'Instaladas (0)', await foco(p));
81+ ok('4 · …y la lista abierta vuelve a ofrecer «Instalar»', await p.locator(`#settings-panel .sk-install[aria-label="Instalar: ${nombre}"]`).getAttribute('aria-disabled') === null);
82+
83+ await explorar.click();
84+ ok('2 · otra vez «Ocultar» la cierra', await tarjeta.locator('.sk-browse').isHidden() && await explorar.getAttribute('aria-expanded') === 'false');
85+
86+ // un catálogo propio
87+ await p.fill('#settings-panel .sk-add input', 'https://github.com/alguien/mis-skills');
88+ await p.keyboard.press('Enter');
89+ const propia = p.locator('#settings-panel .sk-cat[data-repo="alguien/mis-skills"]');
90+ await propia.waitFor();
91+ ok('5 · añadir un repo lo enseña con una sola acción y el foco en «Explorar»', await propia.locator(':scope > button').count() === 1
92+ && (await foco(p)) === 'Explorar alguien/mis-skills', await foco(p));
93+ await propia.locator(':scope > button').click();
94+ const quitarRepo = propia.locator('.sk-remove-repo');
95+ await quitarRepo.waitFor();
96+ await enter(p, quitarRepo);
97+ await p.waitForTimeout(250);
98+ ok('5 · …y se quita desde dentro de su lista (el foco va al encabezado)', await p.locator('#settings-panel .sk-cat[data-repo="alguien/mis-skills"]').count() === 0
99+ && (await foco(p)) === 'Explorar catálogos', await foco(p));
100+ ok('sin errores de página', !p.errs.length, p.errs.join(' | '));
101+ await ctx.close();
102+}
103+
104+// ── teléfono ──
105+{
106+ const { ctx, p } = await abre('es-ES', { width: 390, height: 844 }, true);
107+ await p.tap('#btn-drawer');
108+ await p.waitForTimeout(200);
109+ await p.tap('#act-skills');
110+ await p.waitForSelector('#settings-panel .sk-cat');
111+ await p.locator(`#settings-panel .sk-cat[data-repo="${REPO}"] > button`).tap();
112+ await p.waitForSelector('#settings-panel .sk-browse .sk-install');
113+ const m = await p.evaluate(() => {
114+ const cortados = [...document.querySelectorAll('#settings-panel .sk-info b')].filter(b => b.scrollWidth > b.clientWidth + 1).map(b => b.textContent);
115+ const fuera = [...document.querySelectorAll('#settings-panel button')].filter(b => { const r = b.getBoundingClientRect(); return r.width && (r.right > innerWidth || r.left < 0); }).map(b => b.textContent);
116+ return { cortados, fuera, scrollX: document.documentElement.scrollWidth - innerWidth };
117+ });
118+ ok('6 · en el teléfono ningún nombre se corta', !m.cortados.length, JSON.stringify(m.cortados));
119+ ok('6 · …ningún botón se sale de la pantalla y no hay desplazamiento lateral', !m.fuera.length && m.scrollX <= 0, JSON.stringify(m));
120+ ok('6 · sin errores de página', !p.errs.length, p.errs.join(' | '));
121+ await ctx.close();
122+}
123+
124+// ── en inglés ──
125+{
126+ const { ctx, p } = await abre('en-US', { width: 1280, height: 800 });
127+ await p.click('#act-skills');
128+ await p.waitForSelector('#settings-panel .sk-cat');
129+ const txt = await p.textContent('#settings-panel');
130+ ok('7 · en inglés: título, partes y catálogos en inglés', /Skills for Elffuss/.test(txt) && /Installed \(0\)/.test(txt) && /Browse catalogs/i.test(txt)
131+ && /Community · Mega collection/.test(txt) && !/Comunidad|Catálogos|Instaladas|Explorar/.test(txt), txt.slice(0, 400));
132+ await p.fill('#settings-panel .sk-add input', 'esto no vale');
133+ await p.keyboard.press('Enter');
134+ await p.waitForTimeout(200);
135+ ok('7 · …y el error de un repo que no vale, también', /Type owner\/repo/.test(await p.innerText('#settings-panel .sk-add + .sk-msg')), await p.innerText('#settings-panel .sk-add + .sk-msg'));
136+ ok('7 · sin errores de página', !p.errs.length, p.errs.join(' | '));
137+ await ctx.close();
138+}
139+await b.close();
140+console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ panel de Skills: claro, con teclado, en el teléfono y en inglés');
141+process.exit(fails ? 1 : 0);
modified web/css/code.css +34 −12
@@ -300,8 +300,6 @@
300300 #model-bar { height: 100%; width: 0; background: linear-gradient(90deg, var(--accent), var(--accent2)); transition: width .25s; }
301301 #model-progress .mp-acciones { display: flex; gap: 6px; }
302302 #model-progress .mp-acciones button { background: var(--bg2); color: var(--fg); border: 1px solid var(--line); border-radius: 7px; padding: 4px 10px; font: inherit; font-size: .78rem; cursor: pointer; }
303-.sk-msg { font-size: .74rem; }
304-.sk-msg.err { color: #ff8fb0; }
305303
306304 /* ---------- chat ---------- */
307305 #chat { display: flex; flex-direction: column; border-left: 1px solid var(--line); background: var(--bg2); min-height: 0; }
@@ -499,16 +497,40 @@
499497 #menu .menu-item span { color: var(--muted); font-size: .74rem; }
500498 #chat { position: relative; }
501499
502-/* panel de skills */
503-.skills-panel h3 { margin: 0 0 4px; font-size: 1rem; }
504-.sk-h { font-size: .72rem; color: var(--muted); text-transform: uppercase; letter-spacing: .05em; margin: 12px 0 6px; }
505-.sk-row { display: flex; align-items: center; gap: 8px; padding: 7px 10px; background: var(--bg3); border: 1px solid var(--line); border-radius: 8px; margin-bottom: 6px; font-size: .82rem; }
506-.sk-row b { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
507-.sk-row .muted { color: var(--muted); font-size: .74rem; max-width: 40%; overflow: hidden; text-overflow: ellipsis; }
508-.sk-row a { color: var(--accent2); font-size: .74rem; text-decoration: none; }
509-.sk-row input { flex: 1; background: var(--bg); border: 1px solid var(--line); color: var(--fg); border-radius: 6px; padding: 6px 9px; font-size: .78rem; }
510-.sk-row button.primary { background: linear-gradient(135deg, var(--accent), var(--accent2)); border: none; color: #fff; border-radius: 6px; padding: 5px 11px; cursor: pointer; font-size: .76rem; }
511-.sk-row button.ghost { background: none; border: 1px solid var(--line); color: var(--muted); border-radius: 6px; padding: 5px 9px; cursor: pointer; font-size: .76rem; }
500+/* panel de skills: «Instaladas» y «Explorar catálogos», una acción por fila.
501+ El contenido no pasa de un ancho legible aunque el panel ocupe toda la
502+ pantalla; los nombres largos parten en vez de cortarse («Co…» en el móvil). */
503+.skills-panel { width: 100%; max-width: 880px; display: flex; flex-direction: column; gap: 4px; font-size: .84rem; }
504+.skills-panel .sk-intro { margin: 0 0 4px; line-height: 1.45; }
505+.skills-panel > .sk-msg { margin: 0; min-height: 1.2em; }
506+.skills-panel section { display: flex; flex-direction: column; }
507+.sk-h { font-size: .72rem; color: var(--muted); text-transform: uppercase; letter-spacing: .05em; margin: 12px 0 6px; font-weight: 600; }
508+.sk-h:focus { outline: none; }
509+.sk-h:focus-visible { outline: 2px solid var(--accent2); outline-offset: 2px; }
510+.sk-nota, .sk-vacio { margin: 0 0 8px; font-size: .78rem; }
511+.sk-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
512+.sk-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; padding: 8px 10px; background: var(--bg3); border: 1px solid var(--line); border-radius: 8px; font-size: .82rem; }
513+.sk-info { flex: 1 1 200px; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
514+.sk-info b { overflow-wrap: anywhere; }
515+.sk-info .muted, .sk-info a { font-size: .74rem; overflow-wrap: anywhere; }
516+.sk-row .muted { color: var(--muted); }
517+.sk-row a { color: var(--accent2); text-decoration: none; }
518+.sk-row a:hover { text-decoration: underline; }
519+.sk-row > button { flex: 0 0 auto; min-width: 84px; }
520+.sk-browse { flex: 1 0 100%; margin-top: 6px; padding-top: 8px; border-top: 1px solid var(--line); }
521+.sk-browse[hidden] { display: none; }
522+.sk-browse .sk-row { background: var(--bg2); }
523+.sk-add { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
524+.sk-add input { flex: 1 1 220px; min-width: 0; background: var(--bg); border: 1px solid var(--line); color: var(--fg); border-radius: 6px; padding: 7px 9px; font-size: .8rem; }
525+.skills-panel button.primary { background: linear-gradient(135deg, var(--accent), var(--accent2)); border: none; color: #fff; border-radius: 6px; padding: 6px 12px; cursor: pointer; font-size: .78rem; }
526+.skills-panel button.ghost { background: none; border: 1px solid var(--line); color: var(--fg); border-radius: 6px; padding: 6px 12px; cursor: pointer; font-size: .78rem; }
527+.skills-panel button[aria-disabled="true"] { opacity: .7; cursor: default; }
528+.skills-panel button[aria-busy="true"] { cursor: progress; }
529+.skills-panel button:focus-visible { outline: 2px solid var(--accent2); outline-offset: 2px; }
530+.sk-remove-repo { margin-top: 8px; }
531+.sk-msg { font-size: .76rem; }
532+.sk-msg.err { color: #ff8fb0; }
533+
512534 /* El panel de Ajustes / Skills / Extensiones se SUPERPONE (no empuja el IDE) y
513535 ocupa ENTERO el hueco de trabajo: de la cabecera al pie y del borde del
514536 explorador al de la ventana. Antes era una persiana de la altura de su
modified web/js/i18n.js +22 −2
@@ -224,9 +224,19 @@
224224 errNet: "no se pudo descargar (¿sin conexión, o un bloqueador?)", errGpu: "este navegador no da acceso a una GPU (WebGPU); prueba el modelo ligero o el modo Básico",
225225 errQuota: "no queda espacio en el navegador para guardarlo (libera con 💾)", errMem: "no cabe en la memoria de esta máquina; prueba uno más pequeño", errUnknown: "error desconocido",
226226 skTitle: "🧩 Skills para Elffuss", skIntro: "Instala instrucciones especializadas (formato SKILL.md) desde repos públicos. Todo se guarda en tu navegador. Se ve el repo y lo que se inyecta.",
227- skInstalled: "Instaladas ({n})", skNone: "Ninguna todavía.", skCatalogs: "Catálogos (repos)", skRemoveNamed: "Quitar {name}", skRemoveRepo: "Quitar el catálogo {repo}",
227+ skInstalled: "Instaladas ({n})", skRemoveNamed: "Quitar {name}", skRemoveRepo: "Quitar el catálogo {repo}",
228228 skLoading: "Cargando {repo}…", skFound: "{repo} — {n} skills", skInstall: "Instalar", skInstalledOne: "Instalada ✓",
229229 skNoNet: "No pude consultar {repo}: sin conexión con GitHub (o límite de peticiones). Prueba otra vez en un momento.", skLoadFailed: "No pude listar {repo}: {e}",
230+ skCatalogs: "Explorar catálogos", skCatalogsHint: "Abre un catálogo para ver sus skills e instalar la que necesites.",
231+ skNone: "Ninguna todavía. Abre un catálogo de abajo e instala la que necesites.",
232+ skHide: "Ocultar", skBrowseNamed: "Explorar {repo}", skMore: "…y {n} más: busca en el repo con el enlace ↗.",
233+ skInstalledMsg: "«{name}» instalada. En el chat tienes cómo usarla.", skRemovedMsg: "«{name}» quitada.", skRepoAdded: "Catálogo {repo} añadido.",
234+ skUsageInstalled: "Skill «{name}» instalada.", skUsageFollow: "Ya la sigo en cada conversación. Para usarla, pídeme por ejemplo:", skUsageAbout: "algo relacionado con «{name}»",
235+ skErr_badRepo: "Escribe owner/repo (o pega la URL de GitHub).", skErr_rate: "GitHub limita las peticiones sin cuenta (60 por hora). Prueba otra vez en unos minutos.",
236+ skErr_noRepo: "No encuentro ese repo: ¿existe y es público?", skErr_noMd: "No pude descargar su SKILL.md.",
237+ "skSrc_bbgnsurftech/claude-skills-collection": "Comunidad · Mega-colección (1000+ skills)",
238+ "skSrc_anthropics/skills": "Anthropic · Agent Skills (oficial)",
239+ "skSrc_anthropics/claude-plugins-official": "Anthropic · Plugins oficiales",
230240 setGoalLabel: "Tratar el próximo mensaje como un objetivo: lo descompone en tareas y las ejecuta una a una",
231241 setGoalNote: "Igual que 🎯 Goal en «Modos»: un planificador crea la lista de tareas y un ejecutor las va cumpliendo, marcando cada una como hecha o fallida (si una falla, las siguientes se saltan en vez de seguir a ciegas).",
232242 setTelAuto: "Enviar automáticamente los errores técnicos que ocurran, para poder arreglarlos",
@@ -463,9 +473,19 @@
463473 errNet: "it couldn't be downloaded (offline, or a blocker?)", errGpu: "this browser gives no access to a GPU (WebGPU); try the light model or Basic mode",
464474 errQuota: "there is no room left in the browser to store it (free some with 💾)", errMem: "it doesn't fit in this machine's memory; try a smaller one", errUnknown: "unknown error",
465475 skTitle: "🧩 Skills for Elffuss", skIntro: "Install specialised instructions (SKILL.md format) from public repos. Everything is stored in your browser. You can see the repo and what gets injected.",
466- skInstalled: "Installed ({n})", skNone: "None yet.", skCatalogs: "Catalogs (repos)", skRemoveNamed: "Remove {name}", skRemoveRepo: "Remove the {repo} catalog",
476+ skInstalled: "Installed ({n})", skRemoveNamed: "Remove {name}", skRemoveRepo: "Remove the {repo} catalog",
467477 skLoading: "Loading {repo}…", skFound: "{repo} — {n} skills", skInstall: "Install", skInstalledOne: "Installed ✓",
468478 skNoNet: "Couldn't reach {repo}: no connection to GitHub (or rate limited). Try again in a moment.", skLoadFailed: "Couldn't list {repo}: {e}",
479+ skCatalogs: "Browse catalogs", skCatalogsHint: "Open a catalog to see its skills and install the one you need.",
480+ skNone: "None yet. Open a catalog below and install the one you need.",
481+ skHide: "Hide", skBrowseNamed: "Browse {repo}", skMore: "…and {n} more: look in the repo with the ↗ link.",
482+ skInstalledMsg: "“{name}” installed. The chat shows how to use it.", skRemovedMsg: "“{name}” removed.", skRepoAdded: "Catalog {repo} added.",
483+ skUsageInstalled: "Skill “{name}” installed.", skUsageFollow: "I follow it in every conversation from now on. To use it, ask me for example:", skUsageAbout: "something about “{name}”",
484+ skErr_badRepo: "Type owner/repo (or paste the GitHub URL).", skErr_rate: "GitHub limits requests without an account (60 per hour). Try again in a few minutes.",
485+ skErr_noRepo: "I can't find that repo: does it exist and is it public?", skErr_noMd: "Couldn't download its SKILL.md.",
486+ "skSrc_bbgnsurftech/claude-skills-collection": "Community · Mega collection (1000+ skills)",
487+ "skSrc_anthropics/skills": "Anthropic · Agent Skills (official)",
488+ "skSrc_anthropics/claude-plugins-official": "Anthropic · Official plugins",
469489 setGoalLabel: "Treat the next message as a goal: break it into tasks and run them one by one",
470490 setGoalNote: "Same as 🎯 Goal under “Modes”: a planner writes the task list and an executor works through it, marking each one done or failed (if one fails, the next ones are skipped instead of carrying on blindly).",
471491 setTelAuto: "Automatically send technical errors when they happen, so they can be fixed",
modified web/js/main.js +168 −94
@@ -2753,123 +2753,197 @@
27532753 };
27542754
27552755 // ---------- panel de skills (transparente: repo + lista + SKILL.md) ----------
2756-// Mismo diálogo que Ajustes. Los fallos se dicen DENTRO del panel, en palabras
2757-// de persona y con «Reintentar» (antes: «⚠️ FAILED TO FETCH» en mayúsculas, y
2758-// un alert() del navegador al añadir un repo que no valía o al instalar).
2756+// Mismo sitio que Ajustes. Dos partes que no se mezclan: «Instaladas» arriba y
2757+// «Explorar catálogos» debajo. Cada fila tiene UNA acción (Quitar, Explorar,
2758+// Instalar); la lista de un catálogo se abre DENTRO de su tarjeta (antes se
2759+// añadía al final del panel, debajo de «Añadir repo», lejos del botón que la
2760+// abrió). Instalar ya no cierra el panel: el botón pasa a «Instalada ✓», la
2761+// skill aparece arriba y el «cómo usarla» queda en el chat. El foco no se va a
2762+// <body>: tras instalar sigue en el botón y tras quitar va a la fila siguiente.
2763+// Los fallos se dicen DENTRO del panel, en palabras de persona y con
2764+// «Reintentar».
2765+const skNombreFuente = s => { const k = 'skSrc_' + s.repo; const v = t(k); return v === k ? s.label : v; };
2766+const skError = e => { const k = e?.code ? 'skErr_' + e.code : ''; const v = k ? t(k) : ''; return v && v !== k ? v : (e?.message || String(e)); };
2767+// Ocupado o hecho, pero SIN disabled: un botón deshabilitado pierde el foco.
2768+const skInerte = (b, si) => { if (si) b.setAttribute('aria-disabled', 'true'); else b.removeAttribute('aria-disabled'); };
2769+const skUso = entry => skills.usageMessage(entry, { installed: t('skUsageInstalled'), follow: t('skUsageFollow'), about: t('skUsageAbout') });
2770+
2771+function skFila(nombre, meta, boton) {
2772+ const row = el('li', 'sk-row');
2773+ const info = el('div', 'sk-info');
2774+ info.append(el('b', null, nombre));
2775+ if (meta) info.append(meta);
2776+ row.append(info);
2777+ if (boton) row.append(boton);
2778+ return row;
2779+}
2780+function skAviso(box, texto, err = false) {
2781+ const m = box.querySelector('.skills-panel > .sk-msg');
2782+ if (!m) return;
2783+ m.textContent = texto;
2784+ m.classList.toggle('err', err);
2785+}
2786+function skPintaBotonInstalar(b, instalada, nombre) {
2787+ b.className = (instalada ? 'ghost' : 'primary') + ' sk-install';
2788+ b.textContent = instalada ? t('skInstalledOne') : t('skInstall');
2789+ b.setAttribute('aria-label', (instalada ? t('skInstalledOne') : t('skInstall')) + ': ' + nombre);
2790+ skInerte(b, instalada);
2791+}
2792+
2793+function skPintaInstaladas(box, { enfocar = -1 } = {}) {
2794+ const sec = box.querySelector('.sk-instaladas');
2795+ const inst = skills.installed();
2796+ const h = el('h4', 'sk-h', t('skInstalled', { n: inst.length }));
2797+ h.id = 'sk-inst-h'; h.tabIndex = -1;
2798+ sec.replaceChildren(h);
2799+ if (!inst.length) { sec.append(el('p', 'muted sk-vacio', t('skNone'))); }
2800+ else {
2801+ const ul = el('ul', 'sk-list');
2802+ for (const s of inst) {
2803+ const rm = el('button', 'ghost sk-remove', t('skRemove'));
2804+ rm.type = 'button';
2805+ rm.setAttribute('aria-label', t('skRemoveNamed', { name: s.name }));
2806+ rm.onclick = async () => {
2807+ const i = skills.installed().findIndex(x => x.name === s.name);
2808+ await skills.remove(s.name);
2809+ for (const b of box.querySelectorAll('.sk-browse button.sk-install'))
2810+ if (b.dataset.repo === s.repo && b.dataset.path === s.path) skPintaBotonInstalar(b, false, b.dataset.nombre);
2811+ skPintaInstaladas(box, { enfocar: i });
2812+ skAviso(box, t('skRemovedMsg', { name: s.name }));
2813+ };
2814+ ul.append(skFila(s.name, el('span', 'muted', s.repo || 'local'), rm));
2815+ }
2816+ sec.append(ul);
2817+ }
2818+ if (enfocar >= 0) {
2819+ const quitar = [...sec.querySelectorAll('.sk-remove')];
2820+ (quitar[Math.min(enfocar, quitar.length - 1)] || h).focus();
2821+ }
2822+}
2823+
27592824 async function openSkillsPanel() {
27602825 const box = settingsShell(t('skTitle'), 'skills');
2761- const wrap = document.createElement('div');
2762- wrap.className = 'skills-panel';
2763- const intro = document.createElement('p');
2764- intro.className = 'muted';
2765- intro.textContent = t('skIntro');
2766- wrap.appendChild(intro);
2826+ const wrap = el('div', 'skills-panel');
2827+ wrap.append(el('p', 'muted sk-intro', t('skIntro')));
2828+ const msg = el('p', 'muted sk-msg'); msg.setAttribute('role', 'status');
2829+ wrap.append(msg);
2830+ const instSec = el('section', 'sk-instaladas'); instSec.setAttribute('aria-labelledby', 'sk-inst-h');
2831+ const catSec = el('section', 'sk-catalogos'); catSec.setAttribute('aria-labelledby', 'sk-cat-h');
2832+ wrap.append(instSec, catSec);
27672833 box.appendChild(wrap);
2834+ skPintaInstaladas(box);
27682835
2769- // instaladas
2770- const inst = skills.installed();
2771- const instBox = document.createElement('div');
2772- instBox.append(el('div', 'sk-h', t('skInstalled', { n: inst.length })));
2773- for (const s of inst) {
2774- const row = document.createElement('div');
2775- row.className = 'sk-row';
2776- row.append(el('b', null, s.name), el('span', 'muted', s.repo || 'local'));
2777- const rm = document.createElement('button');
2778- rm.className = 'ghost'; rm.textContent = t("skRemove");
2779- rm.setAttribute('aria-label', t('skRemoveNamed', { name: s.name }));
2780- rm.onclick = async () => { await skills.remove(s.name); openSkillsPanel(); };
2781- row.appendChild(rm);
2782- instBox.appendChild(row);
2836+ const hc = el('h4', 'sk-h', t('skCatalogs')); hc.id = 'sk-cat-h'; hc.tabIndex = -1;
2837+ catSec.append(hc, el('p', 'muted sk-nota', t('skCatalogsHint')));
2838+ const lista = el('ul', 'sk-list');
2839+ catSec.append(lista);
2840+ for (const s of await skills.sources()) {
2841+ const enlace = el('a', null, s.repo + ' ↗');
2842+ enlace.href = `https://github.com/${s.repo}`; enlace.target = '_blank'; enlace.rel = 'noopener noreferrer';
2843+ const ver = el('button', 'primary sk-explore', t('skBrowse'));
2844+ ver.type = 'button';
2845+ ver.setAttribute('aria-expanded', 'false');
2846+ ver.setAttribute('aria-label', t('skBrowseNamed', { repo: s.repo }));
2847+ const fila = skFila(skNombreFuente(s), enlace, ver);
2848+ fila.classList.add('sk-cat');
2849+ fila.dataset.repo = s.repo;
2850+ const cuerpo = el('div', 'sk-browse');
2851+ cuerpo.dataset.repo = s.repo;
2852+ cuerpo.id = 'sk-browse-' + s.repo.replace(/[^\w-]/g, '_');
2853+ cuerpo.hidden = true;
2854+ ver.setAttribute('aria-controls', cuerpo.id);
2855+ fila.append(cuerpo);
2856+ ver.onclick = () => {
2857+ if (ver.getAttribute('aria-busy') === 'true') return;
2858+ const abrir = cuerpo.hidden;
2859+ cuerpo.hidden = !abrir;
2860+ ver.setAttribute('aria-expanded', String(abrir));
2861+ ver.textContent = abrir ? t('skHide') : t('skBrowse');
2862+ ver.className = (abrir ? 'ghost' : 'primary') + ' sk-explore';
2863+ if (abrir && !cuerpo.dataset.cargado) browseRepo(s, cuerpo, ver, box);
2864+ };
2865+ lista.append(fila);
27832866 }
2784- if (!inst.length) instBox.append(el('p', 'muted', t('skNone')));
2785- box.appendChild(instBox);
27862867
2787- // fuentes + añadir repo
2788- const srcs = await skills.sources();
2789- const srcBox = document.createElement('div');
2790- srcBox.append(el('div', 'sk-h', t('skCatalogs')));
2791- for (const s of srcs) {
2792- const row = document.createElement('div');
2793- row.className = 'sk-row';
2794- const a = document.createElement('a');
2795- a.href = `https://github.com/${s.repo}`; a.target = '_blank'; a.rel = 'noopener noreferrer';
2796- a.textContent = s.repo + ' ↗';
2797- row.append(el('b', null, s.label), a);
2798- const browse = document.createElement('button');
2799- browse.className = 'primary'; browse.textContent = t("skBrowse");
2800- browse.onclick = () => browseRepo(s.repo, box);
2801- row.appendChild(browse);
2802- if (!s.official) {
2803- const rm = document.createElement('button');
2804- rm.className = 'ghost'; rm.textContent = '🗑';
2805- rm.setAttribute('aria-label', t('skRemoveRepo', { repo: s.repo }));
2806- rm.onclick = async () => { await skills.removeSource(s.repo); openSkillsPanel(); };
2807- row.appendChild(rm);
2808- }
2809- srcBox.appendChild(row);
2810- }
2811- const addRow = document.createElement('div');
2812- addRow.className = 'sk-row';
2813- const inp = document.createElement('input');
2814- inp.placeholder = t("skAddRepoPh");
2868+ // añadir un catálogo: es un formulario (Enter envía)
2869+ const form = el('form', 'sk-add');
2870+ const inp = el('input');
2871+ inp.placeholder = t('skAddRepoPh');
28152872 inp.setAttribute('aria-label', t('skAddRepo'));
2816- const add = document.createElement('button');
2817- add.className = 'primary'; add.textContent = t("skAddRepo");
2873+ inp.autocomplete = 'off'; inp.spellcheck = false;
2874+ const add = el('button', 'primary', t('skAddRepo'));
2875+ add.type = 'submit';
28182876 const addMsg2 = el('div', 'muted sk-msg'); addMsg2.setAttribute('role', 'status');
2819- add.onclick = async () => {
2820- addMsg2.textContent = '';
2821- try { await skills.addSource(inp.value); openSkillsPanel(); }
2822- catch (e) { addMsg2.textContent = '⚠️ ' + (e?.message || e); addMsg2.classList.add('err'); inp.focus(); }
2877+ form.onsubmit = async ev => {
2878+ ev.preventDefault();
2879+ addMsg2.textContent = ''; addMsg2.classList.remove('err');
2880+ try {
2881+ const repo = await skills.addSource(inp.value);
2882+ await openSkillsPanel();
2883+ const nueva = $('settings-panel').querySelector(`.sk-cat[data-repo="${CSS.escape(repo)}"] .sk-explore`);
2884+ nueva?.focus();
2885+ skAviso($('settings-panel'), t('skRepoAdded', { repo }));
2886+ } catch (e) { addMsg2.textContent = '⚠️ ' + skError(e); addMsg2.classList.add('err'); inp.focus(); }
28232887 };
2824- inp.addEventListener('keydown', e => { if (e.key === 'Enter') add.click(); });
2825- addRow.append(inp, add);
2826- srcBox.append(addRow, addMsg2);
2827- box.appendChild(srcBox);
2888+ form.append(inp, add);
2889+ catSec.append(form, addMsg2);
28282890 }
28292891
2830-async function browseRepo(repo, box) {
2831- box.querySelector(`.sk-browse[data-repo="${CSS.escape(repo)}"]`)?.remove();
2832- const list = document.createElement('div');
2833- list.className = 'sk-browse';
2834- list.dataset.repo = repo;
2835- list.setAttribute('aria-live', 'polite');
2836- list.append(el('div', 'sk-h', t('skLoading', { repo })));
2837- box.appendChild(list);
2892+async function browseRepo(src, cuerpo, ver, box) {
2893+ const repo = src.repo;
2894+ ver.setAttribute('aria-busy', 'true');
2895+ cuerpo.replaceChildren(el('p', 'muted sk-nota', t('skLoading', { repo })));
28382896 try {
28392897 const found = await skills.listFromRepo(repo);
2840- list.replaceChildren(el('div', 'sk-h', t('skFound', { repo, n: found.length })));
2898+ cuerpo.dataset.cargado = '1';
2899+ cuerpo.replaceChildren(el('p', 'muted sk-nota', t('skFound', { repo, n: found.length })));
2900+ const ul = el('ul', 'sk-list');
28412901 for (const sk of found.slice(0, 120)) {
2842- const row = document.createElement('div');
2843- row.className = 'sk-row';
2844- row.append(el('b', null, sk.name), el('span', 'muted', sk.dir));
2845- const btn = document.createElement('button');
2846- const on = skills.isInstalled(sk.repo, sk.path);
2847- btn.className = on ? 'ghost' : 'primary';
2848- btn.textContent = on ? t('skInstalledOne') : t('skInstall');
2849- btn.setAttribute('aria-label', (on ? t('skInstalledOne') : t('skInstall')) + ': ' + sk.name);
2902+ const btn = el('button');
2903+ btn.type = 'button';
2904+ Object.assign(btn.dataset, { repo: sk.repo, path: sk.path, nombre: sk.name });
2905+ skPintaBotonInstalar(btn, skills.isInstalled(sk.repo, sk.path), sk.name);
2906+ const fila = skFila(sk.name, el('span', 'muted', sk.dir), btn);
28502907 btn.onclick = async () => {
2851- btn.textContent = '…'; btn.disabled = true;
2908+ if (btn.getAttribute('aria-disabled') === 'true') return;
2909+ btn.textContent = '…'; btn.setAttribute('aria-busy', 'true'); skInerte(btn, true);
2910+ fila.querySelector('.sk-msg')?.remove();
28522911 try {
28532912 const entry = await skills.installFromRepo(sk);
2854- btn.textContent = t('skInstalledOne'); btn.className = 'ghost';
2855- cierraAjustes(); // cierra el panel
2856- addMsg('assistant', skills.usageMessage(entry)); // «cómo usarla» en el chat
2913+ btn.removeAttribute('aria-busy');
2914+ skPintaBotonInstalar(btn, true, sk.name);
2915+ skPintaInstaladas(box);
2916+ addMsg('assistant', skUso(entry)); // «cómo usarla» en el chat
2917+ skAviso(box, t('skInstalledMsg', { name: entry.name }));
28572918 } catch (e) {
2858- btn.textContent = t('skInstall'); btn.disabled = false;
2859- row.append(el('span', 'muted sk-msg err', '⚠️ ' + (e?.message || e)));
2919+ btn.removeAttribute('aria-busy');
2920+ skPintaBotonInstalar(btn, false, sk.name);
2921+ fila.querySelector('.sk-info').append(el('span', 'sk-msg err', '⚠️ ' + skError(e)));
28602922 }
28612923 };
2862- row.appendChild(btn);
2863- list.appendChild(row);
2924+ ul.append(fila);
28642925 }
2926+ cuerpo.append(ul);
2927+ if (found.length > 120) cuerpo.append(el('p', 'muted sk-nota', t('skMore', { n: found.length - 120 })));
28652928 } catch (e) {
2866- const msg = /Failed to fetch|NetworkError|network/i.test(String(e?.message)) ? t('skNoNet', { repo }) : t('skLoadFailed', { repo, e: e?.message || e });
2867- const retry = document.createElement('button');
2868- retry.className = 'primary'; retry.textContent = t('retry');
2869- retry.onclick = () => browseRepo(repo, box);
2929+ const offline = /Failed to fetch|NetworkError|network/i.test(String(e?.message));
2930+ const texto = offline ? t('skNoNet', { repo }) : t('skLoadFailed', { repo, e: skError(e) });
2931+ const retry = el('button', 'primary', t('retry'));
2932+ retry.type = 'button';
2933+ retry.onclick = () => browseRepo(src, cuerpo, ver, box);
28702934 const fila = el('div', 'sk-row');
2871- fila.append(el('span', 'sk-msg err', '⚠️ ' + msg), retry);
2872- list.replaceChildren(el('div', 'sk-h', repo), fila);
2935+ fila.append(el('span', 'sk-msg err', '⚠️ ' + texto), retry);
2936+ cuerpo.replaceChildren(fila);
2937+ } finally {
2938+ ver.removeAttribute('aria-busy');
2939+ }
2940+ // Un catálogo añadido por ti se quita desde dentro (así cada fila tiene una
2941+ // sola acción): al final de su lista.
2942+ if (!src.official) {
2943+ const rm = el('button', 'ghost sk-remove-repo', t('skRemoveRepo', { repo }));
2944+ rm.type = 'button';
2945+ rm.onclick = async () => { await skills.removeSource(repo); await openSkillsPanel(); $('settings-panel').querySelector('#sk-cat-h')?.focus(); };
2946+ cuerpo.append(rm);
28732947 }
28742948 }
28752949
modified web/js/skills.js +15 −8
@@ -6,6 +6,10 @@
66 // SKILL.md que se inyecta. Se guardan en IndexedDB (nada sale del navegador).
77 import * as db from './db.js';
88
9+// Un error con `code` lo traduce el panel (skErr_<code>); el mensaje en
10+// español queda para quien llame sin interfaz (las herramientas del agente).
11+const fallo = (code, msg) => Object.assign(new Error(msg), { code });
12+
913 const KEY = 'skills'; // skills instaladas
1014 const SRC_KEY = 'skills.sources'; // repos personalizados añadidos por el usuario
1115 const MAX_SKILL = 12_000; // caracteres del cuerpo que se inyectan al modelo
@@ -57,12 +61,15 @@
5761 }
5862
5963 // Mensaje «cómo usarla» tras instalar: qué hace + un ejemplo de qué pedir.
60-export function usageMessage(skill) {
64+// `txt` trae los textos en el idioma de la interfaz ({name} se sustituye); sin
65+// él, en español.
66+export function usageMessage(skill, txt = {}) {
6167 const desc = (skill.description || '').trim();
62- const ejemplo = firstExample(skill) || `algo relacionado con «${skill.name}»`;
63- return `✳ **Skill «${skill.name}» instalada.**\n\n` +
68+ const f = (s, d) => (s || d).replace('{name}', skill.name);
69+ const ejemplo = firstExample(skill) || f(txt.about, 'algo relacionado con «{name}»');
70+ return `✳ **${f(txt.installed, 'Skill «{name}» instalada.')}**\n\n` +
6471 (desc ? desc + '\n\n' : '') +
65- `Ya la sigo en cada conversación. Para usarla, pídeme por ejemplo:\n\n> ${ejemplo}`;
72+ `${f(txt.follow, 'Ya la sigo en cada conversación. Para usarla, pídeme por ejemplo:')}\n\n> ${ejemplo}`;
6673 }
6774
6875 // Intenta sacar un ejemplo de uso del cuerpo del SKILL.md (líneas de ejemplo/uso).
@@ -89,7 +96,7 @@
8996 }
9097 export async function addSource(repoOrUrl, label) {
9198 const repo = repoOrUrl.trim().replace(/^https?:\/\/github\.com\//, '').replace(/\.git$/, '').replace(/\/$/, '');
92- if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw new Error('Usa owner/repo (o la URL de GitHub)');
99+ if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw fallo('badRepo', 'Usa owner/repo (o la URL de GitHub)');
93100 const custom = (await db.get('kv', SRC_KEY).catch(() => null)) || [];
94101 if (!custom.some(s => s.repo === repo) && !DEFAULT_SOURCES.some(s => s.repo === repo))
95102 custom.push({ repo, label: label || repo });
@@ -108,9 +115,9 @@
108115 for (const b of ['main', 'master']) {
109116 const r = await fetch(`https://api.github.com/repos/${repo}/git/trees/${b}?recursive=1`);
110117 if (r.ok) { tree = await r.json(); branch = b; break; }
111- if (r.status === 403) throw new Error('GitHub limitó las peticiones (60/h sin login). Reintenta en unos minutos.');
118+ if (r.status === 403) throw fallo('rate', 'GitHub limitó las peticiones (60/h sin login). Reintenta en unos minutos.');
112119 }
113- if (!tree) throw new Error('No pude leer el repo (¿existe y es público?)');
120+ if (!tree) throw fallo('noRepo', 'No pude leer el repo (¿existe y es público?)');
114121 return (tree.tree || [])
115122 .filter(n => /(^|\/)SKILL\.md$/i.test(n.path))
116123 .map(n => ({ repo, branch, path: n.path, dir: n.path.replace(/\/SKILL\.md$/i, ''), name: n.path.replace(/\/SKILL\.md$/i, '').split('/').pop() || repo }))
@@ -124,7 +131,7 @@
124131 const r = await fetch(`https://raw.githubusercontent.com/${entry.repo}/${b}/${entry.path}`);
125132 if (r.ok) { md = await r.text(); break; }
126133 }
127- if (md == null) throw new Error('No pude descargar el SKILL.md');
134+ if (md == null) throw fallo('noMd', 'No pude descargar el SKILL.md');
128135 const skill = parseSkill(md, entry.name);
129136 return install({ ...skill, repo: entry.repo, path: entry.path });
130137 }