Elffuss BraidHub

utopia-ia/elffuss-code public

main · 25.4 KiBRawPermalink
1// Gestor de extensiones con código (parte B2): todo por el panel, con Open VSX
2// simulado (tests/lib/openvsx-mock.mjs) que sirve los .vsix REALES fijados de
3// Tyriar.sort-lines 1.12.0 y esbenp.prettier-vscode 12.4.0 (tests/.cache/vsix,
4// SHA-256 comprobada) y tres manifiestos sintéticos.
5//
6// node tests/x2_manager.mjs (sin los .vsix en caché ni red: NOT RUN)
7//
8// Comprueba: buscar no carga nada del nivel 2; el detalle dice qué funcionará
9// (R4); el consentimiento enseña el tamaño ANTES de bajar nada y Cancelar no
10// cambia nada; instalar y ejecutar; los comandos con su botón «Ejecutar»;
11// Prettier formatea; el formateador por lenguaje; los ajustes (validados);
12// tras recargar todo vuelve solo; apagar el código de una; desinstalar (sin
13// ficheros en IndexedDB y sin recinto al final); el filtro «Funciona en Code»;
14// la suma SHA-256 obligatoria; «Necesita Node»; el ancho de un teléfono; y que
15// a Open VSX solo le habla la página de Code, el recinto pide solo sus dos
16// documentos y la baliza queda a 0.
17import { chromium } from 'playwright';
18import { startServer } from './lib/x2-server.mjs';
19import { startBeacon } from './lib/beacon.mjs';
20import { fetchVsix, PINNED } from './lib/x2-vsix.mjs';
21import { mockOpenVsx } from './lib/openvsx-mock.mjs';
22import { openZip } from '../web/js/ext/unzip.js';
23import { parseJsonc } from '../web/js/ext/formats.js';
24
25let fails = 0;
26const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
27const sleep = ms => new Promise(r => setTimeout(r, ms));
28async function until(fn, { timeout = 30000, every = 200 } = {}) {
29 const end = Date.now() + timeout;
30 let v;
31 while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
32 return v;
33}
34
35// ── paquetes ──
36const packages = [];
37for (const p of PINNED) {
38 let v;
39 try { v = await fetchVsix({ ...p, offline: process.env.X2_OFFLINE === '1' }); }
40 catch (e) { console.log(`⏭️ NOT RUN x2_manager — ${p.namespace}.${p.name}@${p.version}: ${e.message}`); process.exit(0); }
41 const zip = openZip(v.bytes, { maxEntry: 32 << 20, maxTotal: 64 << 20 });
42 const manifest = parseJsonc(new TextDecoder().decode(await zip.read('extension/package.json')));
43 packages.push({ namespace: p.namespace, name: p.name, version: p.version, manifest, vsix: v.bytes, published: v.sha256, downloadCount: 1000 });
44}
45const fake = (name, extra) => ({ namespace: 'elffuss-test', name, version: '1.0.0', keywords: ['elffuss-filter'], published: null,
46 manifest: { name, publisher: 'elffuss-test', version: '1.0.0', displayName: 'Fake ' + name, engines: { vscode: '^1.80.0' }, ...extra } });
47packages.push(
48 fake('nodeonly', { main: './out/ext.js', contributes: { commands: [{ command: 'n.x', title: 'X' }] } }),
49 fake('nohash', { browser: './web.js', contributes: { commands: [{ command: 'h.x', title: 'X' }] } }),
50 fake('themeonly', { contributes: { themes: [{ label: 'T', uiTheme: 'vs-dark', path: './t.json' }] } }),
51);
52// el .vsix de nohash existe pero Open VSX no publica su suma
53packages.find(p => p.name === 'nohash').vsix = packages[0].vsix;
54
55const srv = await startServer();
56const beacon = await startBeacon();
57const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] });
58const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 } });
59await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
60const mock = await mockOpenVsx(ctx, packages);
61const page = await ctx.newPage();
62const requests = [], errors = [];
63ctx.on('request', r => requests.push(r.url()));
64page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(e.message); });
65const x2errors = []; // lo que el recinto avisa por consola ([x2] …)
66page.on('console', m => { if (/\[x2\]/.test(m.text()) && /already exists|ext\.add/.test(m.text())) x2errors.push(m.text().slice(0, 200)); });
67page.on('dialog', d => d.accept()); // confirmar desinstalar
68await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
69await page.evaluate(async () => {
70 const o = await navigator.storage.getDirectory();
71 const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
72 await w('fruits.txt', 'pear\napple\nfig\n');
73 await w('ugly.js', 'const x = {a:1,b:[1,2,3]}\n');
74});
75const openIde = async () => {
76 await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
77 await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
78};
79await openIde();
80const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
81const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
82const setValue = v => page.evaluate(v => window.monaco.editor.getEditors()[0].getModel().setValue(v), v);
83const formatDoc = () => page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
84const L2 = u => /\/vendor\/x2\/|\/js\/ext2\//.test(u);
85// abrir un fichero cierra el panel (como siempre): se vuelve a abrir para usarlo
86const panel = async () => { await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); }); await until(() => page.evaluate(() => !document.getElementById('settings-panel').hidden && !!document.getElementById('ext-panel'))); };
87const row = id => page.locator(`#ext-results .ext-row[data-id="${id}"]`);
88const installed = id => page.locator(`#ext-installed .ext-row[data-id="${id}"]`);
89const search = async q => { await page.fill('#ext-q', q); await page.press('#ext-q', 'Enter'); };
90const codeState = id => page.evaluate(id => document.querySelector(`#ext-installed .ext-row[data-id="${id}"] .ext-x2-state`)?.textContent || null, id);
91const idbKeys = prefix => page.evaluate(prefix => new Promise((res, rej) => {
92 const r = indexedDB.open('elffuss-code-ext', 1);
93 r.onsuccess = () => { const q = r.result.transaction('files').objectStore('files').getAllKeys(); q.onsuccess = () => { res(q.result.filter(k => String(k).startsWith(prefix)).length); r.result.close(); }; q.onerror = () => rej(q.error); };
94 r.onerror = () => rej(r.error);
95}), prefix);
96
97// ── M1–M5: buscar, detalle, consentimiento ──
98await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); });
99await until(() => page.evaluate(() => !!document.getElementById('ext-panel')));
100ok('M1 sin extensiones con código, la explicación de siempre (que ya dice que su código solo corre si lo enciendes)', /No extension code runs unless you turn it on for one extension/.test(await page.textContent('#ext-panel .ext-intro')));
101requests.length = 0;
102await search('sort');
103await until(async () => (await row('Tyriar.sort-lines').count()) === 1);
104ok('M2 buscar no carga nada del nivel 2', !requests.some(L2), requests.filter(L2).join(' '));
105await row('Tyriar.sort-lines').locator('.ext-name').click();
106const det1 = await until(async () => { const t = await row('Tyriar.sort-lines').locator('.ext-detail').innerText(); return /Not tested in Code yet/.test(t) ? t : null; });
107ok('M3 el detalle dice qué funcionará: se ejecuta en el recinto con sus comandos, aún no probada', !!det1 && /Runs in Code’s sandbox: \d+ commands/.test(det1) && /No internet; sees only the files you open/.test(det1), det1);
108const btns = await row('Tyriar.sort-lines').evaluate(r => ({ code: r.querySelector('.ext-install-code')?.textContent, install: r.querySelector('.ext-install')?.getAttribute('aria-disabled'), why: r.querySelector('.ext-install')?.title }));
109ok('M3b «Instalar y ejecutar su código…»; «Instalar» a secas queda inerte (solo trae código)', btns.code === 'Install and run its code…' && btns.install === 'true' && /only brings code/.test(btns.why), JSON.stringify(btns));
110ok('M3c abrir el detalle no baja el recinto ni lo abre', !requests.some(u => u.includes('/vendor/x2/')) && !requests.some(u => u.startsWith(srv.sandboxOrigin)));
111await row('Tyriar.sort-lines').locator('.ext-install-code').click();
112const consent = await until(() => page.evaluate(() => {
113 const d = document.querySelector('#x2-consent [role="dialog"]');
114 // (lo que pesa la extensión llega de una petición HEAD, sin hacer esperar al diálogo)
115 return d && /This extension: \d/.test(d.textContent) ? { text: d.textContent, focused: document.activeElement?.textContent, buttons: [...d.querySelectorAll('button')].map(b => b.textContent) } : null;
116}));
117ok('M4 consentimiento: qué verá, sin internet, el tamaño del recinto y que se baja al aceptar', !!consent && /Run the code of Sort lines\?/.test(consent.text) && /can’t read your project, conversations or keys/.test(consent.text)
118 && /Code’s extension runtime: 2\.6 MB, downloaded once and then cached/.test(consent.text) && /downloaded from Open VSX when you accept/.test(consent.text)
119 && consent.focused === 'Cancel' && consent.buttons.join() === 'Cancel,Install and run code', JSON.stringify(consent));
120const mbOf = n => (n / 1e6).toFixed(1) + ' MB';
121ok('M4a …y lo que pesa la extensión, antes de bajarla (una petición HEAD)', consent.text.includes(`This extension: ${mbOf(packages[0].vsix.length)}, downloaded from Open VSX when you accept`) && mock.sizeLookups().length === 1, JSON.stringify({ text: consent.text.slice(-200), heads: mock.sizeLookups() }));
122ok('M4b con el diálogo abierto todavía no se ha bajado nada', !requests.some(u => u.includes('/vendor/x2/')) && !mock.downloads().length);
123await page.keyboard.press('Escape');
124await sleep(500);
125ok('M5 Cancelar: nada instalado ni bajado', (await installed('tyriar.sort-lines').count()) === 0 && !mock.downloads().length && !requests.some(u => u.includes('/vendor/x2/')));
126
127// ── M6–M8: instalar sort-lines y ejecutar su comando desde el panel ──
128await row('Tyriar.sort-lines').locator('.ext-install-code').click();
129await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
130await page.click('#x2-consent button:has-text("Install and run code")');
131// sort-lines arranca con su primer comando: «lista» hasta entonces
132const READY = s => s === 'running' || s === 'ready (starts when first used)';
133const st1 = await until(async () => { const s = await codeState('tyriar.sort-lines'); return READY(s) ? s : null; }, { timeout: 90000 });
134ok('M6 instalada con su código: el recinto arrancó y ella está lista', !!st1, String(await codeState('tyriar.sort-lines')));
135ok('M6a aceptar en el diálogo no cierra el panel de extensiones', !(await page.evaluate(() => document.getElementById('settings-panel').hidden)));
136ok('M6b la explicación del panel pasa a la del nivel 2', /sealed sandbox on a separate site/.test(await page.textContent('#ext-panel .ext-intro')));
137const vendorReqs = requests.filter(u => u.includes('/vendor/x2/'));
138ok('M6c el recinto se bajó una vez (3 ficheros verificados)', vendorReqs.length === 3, vendorReqs.join(' '));
139const cmds = await until(async () => { const c = await installed('tyriar.sort-lines').locator('.ext-x2-cmds li').allInnerTexts(); return c.length >= 10 ? c : null; });
140ok('M7 sus comandos, cada uno con su botón Ejecutar (también en el teléfono)', !!cmds && cmds.some(t => /Sort lines \(ascending, case sensitive\)/.test(t)), JSON.stringify(cmds?.slice(0, 3)));
141await open('fruits.txt');
142await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 3, endColumn: 4 }); });
143await sleep(300);
144await panel();
145await installed('tyriar.sort-lines').locator('[data-k="cmd:sortLines.sortLines"]').click();
146ok('M8 Ejecutar desde el panel ordena el fichero abierto', !!(await until(async () => (await value()) === 'apple\nfig\npear\n')), JSON.stringify(await value()));
147
148// ── M9–M13: Prettier ──
149await panel();
150await search('prettier');
151await until(async () => (await row('esbenp.prettier-vscode').count()) === 1);
152await row('esbenp.prettier-vscode').locator('.ext-name').click();
153const det2 = await until(async () => { const t = await row('esbenp.prettier-vscode').locator('.ext-detail').innerText(); return /Tested in Code/.test(t) ? t : null; });
154ok('M9 Prettier: lo declarativo, el código en el recinto y el resultado del censo (formateador)', !!det2 && /Works now \(no code\): \d+ languages?/.test(det2) && /Runs in Code’s sandbox/.test(det2) && /Tested in Code: starts.*formatter/.test(det2), det2);
155await row('esbenp.prettier-vscode').locator('.ext-install-code').click();
156const consent2 = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-consent [role="dialog"]'); return d && /This extension: \d/.test(d.textContent) ? { text: d.textContent, buttons: [...d.querySelectorAll('button')].map(b => b.textContent) } : null; }));
157ok('M10 su tamaño (el del .vsix, antes de bajarlo) y la opción de instalarla sin su código', !!consent2 && consent2.text.includes(`This extension: ${mbOf(packages.find(p => p.name === 'prettier-vscode').vsix.length)}, downloaded`) && consent2.buttons.includes('Install without its code'), JSON.stringify(consent2));
158await page.click('#x2-consent button:has-text("Install and run code")');
159await until(async () => ((await codeState('esbenp.prettier-vscode')) === 'running' ? 1 : null), { timeout: 90000 });
160await open('ugly.js');
161let formatted = null;
162for (let i = 0; i < 20 && !formatted; i++) { await formatDoc(); formatted = await until(async () => ((await value()) === 'const x = { a: 1, b: [1, 2, 3] };\n' ? 1 : null), { timeout: 1500 }); }
163ok('M11 Format Document con Prettier', !!formatted, JSON.stringify(await value()));
164// formateador por lenguaje: el de serie para javascript, y vuelta a Prettier
165await panel();
166const fmt = installed('esbenp.prettier-vscode').locator('.ext-x2-fmt');
167await until(async () => (await fmt.count()) === 1);
168await fmt.locator('summary').click();
169await fmt.locator('[data-k="fmt:javascript"]').selectOption('builtin');
170await setValue('const y = {a:1}\n');
171await sleep(800);
172await formatDoc();
173ok('M12 «el de serie» para javascript: formatea Monaco, sin el punto y coma de Prettier', !!(await until(async () => ((await value()) === 'const y = { a: 1 }\n' ? 1 : null), { timeout: 8000 })), JSON.stringify(await value()));
174await installed('esbenp.prettier-vscode').locator('.ext-x2-fmt').evaluate(d => { d.open = true; });
175await installed('esbenp.prettier-vscode').locator('[data-k="fmt:javascript"]').selectOption('extension');
176await setValue('const y = {a:1}\n');
177await sleep(800);
178let back = null;
179for (let i = 0; i < 10 && !back; i++) { await formatDoc(); back = await until(async () => ((await value()) === 'const y = { a: 1 };\n' ? 1 : null), { timeout: 1500 }); }
180ok('M12b y de vuelta a Prettier', !!back, JSON.stringify(await value()));
181// ajustes en JSON, validados contra los que declara Prettier
182const settings = installed('esbenp.prettier-vscode').locator('.ext-x2-settings');
183await settings.locator('summary').click();
184await settings.locator('textarea').fill('{"prettier.nope": 1}');
185await settings.locator('[data-k="x2save"]').click();
186const bad = await until(async () => { const t = await settings.locator('.ext-x2-msg').textContent(); return /unknown setting/.test(t) ? t : null; });
187ok('M13 un ajuste que la extensión no declara se rechaza', !!bad && (await settings.locator('.ext-x2-msg').getAttribute('role')) === 'alert', String(bad));
188await installed('esbenp.prettier-vscode').locator('.ext-x2-settings').evaluate(d => { d.open = true; });
189await installed('esbenp.prettier-vscode').locator('.ext-x2-settings textarea').fill('{"prettier.singleQuote": true}');
190await installed('esbenp.prettier-vscode').locator('.ext-x2-settings [data-k="x2save"]').click();
191await until(async () => /Settings applied/.test(await installed('esbenp.prettier-vscode').locator('.ext-x2-msg').textContent()));
192await setValue('const s = "a"\n');
193let quoted = null;
194for (let i = 0; i < 20 && !quoted; i++) { await formatDoc(); quoted = await until(async () => ((await value()) === "const s = 'a';\n" ? 1 : null), { timeout: 1500 }); }
195ok('M13b sus ajustes llegan a la extensión («prettier.singleQuote»)', !!quoted, JSON.stringify(await value()));
196
197// ── M14: al recargar todo vuelve solo (instaladas, encendidas, con sus ajustes) ──
198await openIde();
199await open('ugly.js');
200await until(() => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state().state === 'running'), { timeout: 90000 });
201await setValue('const t = "b"\n');
202let again = null;
203for (let i = 0; i < 30 && !again; i++) { await formatDoc(); again = await until(async () => ((await value()) === "const t = 'b';\n" ? 1 : null), { timeout: 1500 }); }
204ok('M14 tras recargar: el recinto arranca solo con las dos y los ajustes siguen', !!again, JSON.stringify(await value()));
205await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); });
206await until(async () => READY(await codeState('tyriar.sort-lines')) && (await codeState('esbenp.prettier-vscode')) === 'running', { timeout: 60000 });
207
208// ── M15: el ancho de un teléfono ──
209await page.setViewportSize({ width: 390, height: 844 });
210await sleep(500);
211const phone = await page.evaluate(() => ({ sw: document.documentElement.scrollWidth, w: window.innerWidth, runBtn: !!document.querySelector('#ext-installed .ext-x2-cmd') }));
212ok('M15 a 390 px: sin desplazamiento horizontal y con los botones Ejecutar a mano', phone.sw <= phone.w && phone.runBtn, JSON.stringify(phone));
213await page.setViewportSize({ width: 1280, height: 860 });
214
215// ── M16–M18: apagar, desinstalar ──
216await installed('tyriar.sort-lines').locator('[data-k="x2run"]').click();
217// (quitar una extensión del host de extensiones no para su código: el recinto
218// se rehace con las demás, así que la otra vuelve a «en marcha» enseguida)
219ok('M16 apagar el código de una: queda instalada y apagada; la otra sigue', !!(await until(async () => (await codeState('tyriar.sort-lines')) === 'off'))
220 && !!(await until(async () => (await codeState('esbenp.prettier-vscode')) === 'running', { timeout: 60000 }))
221 && !(await page.evaluate(() => (window.elffussClaw?.commands || []).some(c => c.x2 === 'tyriar.sort-lines'))));
222await open('fruits.txt');
223await setValue('zz\nyy\n');
224await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 2, endColumn: 3 }); });
225await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('sortLines.sortLines'));
226await sleep(800);
227ok('M16b y su código está parado de verdad: su comando ya no hace nada en el recinto', (await value()) === 'zz\nyy\n', JSON.stringify(await value()));
228await panel();
229// volver a encenderla en la misma sesión (el recinto sigue en marcha por Prettier):
230// sus ficheros se vuelven a registrar y sus comandos funcionan
231await installed('tyriar.sort-lines').locator('[data-k="x2run"]').click();
232const back2 = await until(async () => { const s = await codeState('tyriar.sort-lines'); return READY(s) ? s : null; }, { timeout: 30000 });
233await open('fruits.txt');
234await setValue('zz\nyy\n');
235await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 2, endColumn: 3 }); });
236await panel();
237await installed('tyriar.sort-lines').locator('[data-k="cmd:sortLines.sortLines"]').click();
238ok('M16c apagar y volver a encender su código en la misma sesión: vuelve a funcionar, sin ficheros «que ya existen»', !!back2 && !!(await until(async () => (await value()) === 'yy\nzz\n')) && x2errors.length === 0, JSON.stringify({ back2, v: await value(), x2errors: x2errors.slice(0, 2) }));
239await installed('tyriar.sort-lines').locator('.ext-uninstall').click();
240ok('M17 desinstalar sort-lines: sin fila y sin ficheros en IndexedDB', !!(await until(async () => (await installed('tyriar.sort-lines').count()) === 0)) && (await idbKeys('tyriar.sort-lines@')) === 0);
241await installed('esbenp.prettier-vscode').locator('.ext-uninstall').click();
242await until(async () => (await installed('esbenp.prettier-vscode').count()) === 0);
243ok('M18 desinstalar la última: sin recinto, sin ficheros y la explicación de siempre', !!(await until(() => page.evaluate(() => !document.getElementById('x2-sandbox'))))
244 && (await idbKeys('esbenp.prettier-vscode@')) === 0 && /No extension code runs unless you turn it on for one extension/.test(await page.textContent('#ext-panel .ext-intro')));
245
246// ── M19–M21: filtro, suma obligatoria, Node ──
247await search('elffuss-filter');
248await until(async () => (await page.locator('#ext-results .ext-row').count()) === 3);
249await page.click('#ext-works');
250const filtered = await until(async () => {
251 const ids = await page.locator('#ext-results .ext-row').evaluateAll(rs => rs.filter(r => !r.hidden).map(r => r.dataset.id));
252 const head = await page.textContent('#ext-results .sk-h');
253 return ids.length === 2 && /checked 3 of 3/.test(head) ? { ids, head } : null;
254});
255ok('M19 «Funciona en Code»: fuera la de Node; quedan la del tema y la de código para navegador', !!filtered && !filtered.ids.includes('elffuss-test.nodeonly'), JSON.stringify(filtered));
256ok('M19b con el filtro se avisa de que Open VSX ve esas consultas', await page.isVisible('#ext-works-note'));
257// el consentimiento cabe en un teléfono
258await page.setViewportSize({ width: 390, height: 844 });
259await row('elffuss-test.nohash').locator('.ext-install-code').click();
260const fit = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-consent [role="dialog"]'); if (!d) return null; const r = d.getBoundingClientRect(); const b = [...d.querySelectorAll('button')].map(x => x.getBoundingClientRect()); return { left: r.left, right: r.right, w: window.innerWidth, sw: document.documentElement.scrollWidth, buttonsIn: b.every(x => x.left >= 0 && x.right <= window.innerWidth) }; }));
261ok('M19c a 390 px el consentimiento cabe, con sus botones', !!fit && fit.left >= 0 && fit.right <= fit.w && fit.sw <= fit.w && fit.buttonsIn, JSON.stringify(fit));
262await page.keyboard.press('Escape');
263await page.setViewportSize({ width: 1280, height: 860 });
264await sleep(300);
265await row('elffuss-test.nohash').locator('.ext-install-code').click();
266await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
267await page.click('#x2-consent button:has-text("Install and run code")');
268const nosha = await until(async () => { const t = await page.textContent('#ext-msg'); return /publishes no SHA-256/.test(t) ? t : null; });
269ok('M20 sin suma SHA-256 publicada, su código no se instala (y ni se baja)', !!nosha && (await page.getAttribute('#ext-msg', 'role')) === 'alert' && !mock.downloads().some(d => d.includes('nohash'))
270 && (await installed('elffuss-test.nohash').count()) === 0, String(nosha));
271await page.click('#ext-works');
272await until(async () => (await page.locator('#ext-results .ext-row').count()) === 3);
273await row('elffuss-test.nodeonly').locator('.ext-name').click();
274const det3 = await until(async () => { const t = await row('elffuss-test.nodeonly').locator('.ext-detail').innerText(); return /Needs Node/.test(t) ? t : null; });
275ok('M21 la de Node dice que no está disponible en el navegador, sin botón de ejecutar', !!det3 && (await row('elffuss-test.nodeonly').locator('.ext-install-code').count()) === 0, det3);
276
277// ── M23: instalar un .vsix suelto que solo trae código ──
278await page.setInputFiles('#ext-file', { name: 'sort-lines.vsix', mimeType: 'application/zip', buffer: packages[0].vsix });
279const fileConsent = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-consent [role="dialog"]'); return d ? d.textContent : null; }));
280ok('M23 un .vsix con solo código pide el consentimiento y dice que no hay suma publicada', !!fileConsent && /From a \.vsix file: there is no published SHA-256/.test(fileConsent), String(fileConsent).slice(0, 160));
281await page.click('#x2-consent button:has-text("Install and run code")');
282ok('M23b instalada desde el fichero con su código, y en marcha', !!(await until(async () => { const s = await codeState('tyriar.sort-lines'); return s === 'running' || s === 'ready (starts when first used)'; }, { timeout: 90000 })));
283await installed('tyriar.sort-lines').locator('.ext-uninstall').click();
284await until(async () => (await installed('tyriar.sort-lines').count()) === 0);
285
286// ── M22: privacidad ──
287await sleep(500);
288const fromSandbox = mock.log.filter(r => !r.frame.startsWith(srv.codeOrigin));
289ok('M22 a Open VSX solo le habla la página de Code (ninguna petición del recinto)', mock.log.length > 0 && fromSandbox.length === 0, JSON.stringify(fromSandbox.slice(0, 3)));
290const sbx = [...new Set(srv.requests.filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]))];
291ok('M22b del recinto solo sus dos documentos', sbx.every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sbx.join(' '));
292ok('M22c baliza: 0 visitas', beacon.hits.length === 0, JSON.stringify(beacon.hits.slice(0, 3)));
293ok('M22d sin errores de página', errors.length === 0, errors.slice(0, 3).join(' | '));
294
295await browser.close();
296await beacon.close();
297await srv.close();
298console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
299process.exit(fails ? 1 : 0);