Elffuss BraidHub

utopia-ia/elffuss-code public

main · 21.8 KiBRawPermalink
1// Commands of a real web extension in Code, and Code's own shortcuts beside it.
2//
3// node tests/x2_commands.mjs (own server; without the pinned .vsix
4// in tests/.cache and no network: NOT RUN)
5//
6// Tyriar.sort-lines 1.12.0 (pinned, SHA-256 checked) is installed with its code
7// through Code's own install path for a .vsix file, next to "hostile", a
8// synthetic extension built here whose command titles are HTML and whose
9// keybindings ask for Code's and the browser's chords and for sort-lines' F9.
10//
11// K1 both install with their code and the sandbox runs them
12// K2 Code's palette (Cmd+Shift+P, ">"): sort-lines' commands with its
13// name; choosing one sorts the selection
14// K3 F1 (Monaco's command list): the same commands; running one works
15// K4 F9 with the editor focused sorts the selection: one undo step, the
16// tab shows unsaved changes, Cmd+S writes the file to the project
17// K5 the editor's context menu carries the command sort-lines puts there
18// K6 hostile's chords for Cmd+P, Cmd+Shift+P, Ctrl+`, Cmd+S, F1,
19// Cmd+Shift+O and Cmd+W are not bound, and its F9 loses to sort-lines;
20// the Extensions panel lists each with the reason
21// K7 with both running, Cmd+P, Cmd+Shift+P, Ctrl+`, "@" in the palette,
22// Cmd+Shift+O and Cmd+S do exactly what they do with no extension
23// (the same steps in a profile without extensions)
24// K8 hostile titles stay text in the palette, F1, the context menu and the
25// panel: no element is created and no handler runs
26// K9 the beacon gets nothing, the sandbox site only its two documents, no
27// page errors
28import { chromium } from 'playwright';
29import { startServer } from './lib/x2-server.mjs';
30import { startBeacon } from './lib/beacon.mjs';
31import { fetchVsix, PINNED } from './lib/x2-vsix.mjs';
32import { zip } from './ext_fixtures.mjs';
33
34let fails = 0;
35const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
36const sleep = ms => new Promise(r => setTimeout(r, ms));
37async function until(fn, { timeout = 20000, every = 150 } = {}) {
38 const end = Date.now() + timeout;
39 let v;
40 while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
41 return v;
42}
43const MOD = process.platform === 'darwin' ? 'Meta' : 'Control';
44
45let sortLines;
46try { sortLines = (await fetchVsix({ ...PINNED.find(p => p.name === 'sort-lines'), offline: process.env.X2_OFFLINE === '1' })).bytes; }
47catch (e) { console.log(`⏭️ NOT RUN x2_commands — Tyriar.sort-lines@1.12.0: ${e.message}`); process.exit(0); }
48
49// «hostile»: títulos con HTML y atajos que no le tocan
50const EVIL_TITLE = '<img src=x onerror="window.__pwned=1">Hostile <b>title</b>';
51const hostile = zip(Object.entries({
52 'extension/package.json': JSON.stringify({
53 name: 'hostile', publisher: 'elffuss-test', version: '1.0.0', displayName: 'Hostile <i>name</i>', license: 'MIT',
54 engines: { vscode: '^1.80.0' }, browser: './extension.js', activationEvents: [],
55 contributes: {
56 commands: [
57 { command: 'hostile.run', title: EVIL_TITLE, category: '<svg onload="window.__pwned=2">X2' },
58 { command: 'hostile.alt', title: 'Hostile alt' },
59 { command: 'hostile.count', title: 'Hostile count' },
60 ],
61 menus: { 'editor/context': [{ command: 'hostile.run', group: 'z_hostile' }] },
62 keybindings: [
63 ['cmd+p', 'ctrl+p'], ['cmd+shift+p', 'ctrl+shift+p'], ['ctrl+`', 'ctrl+`'], ['cmd+s', 'ctrl+s'], ['f1', 'f1'],
64 ['cmd+shift+o', 'ctrl+shift+o'], ['cmd+w', 'ctrl+w'], ['f9', 'f9'],
65 ].map(([mac, key]) => ({ command: 'hostile.run', key, mac }))
66 .concat([{ command: 'hostile.alt', key: 'alt+f9', when: 'editorTextFocus' }]),
67 },
68 }),
69 'extension/extension.js': `const vscode = require('vscode');
70exports.activate = c => {
71 c.subscriptions.push(vscode.commands.registerCommand('hostile.run', () => { globalThis.__hostileRan = (globalThis.__hostileRan || 0) + 1; return 'hostile ran'; }));
72 c.subscriptions.push(vscode.commands.registerCommand('hostile.count', () => String(globalThis.__hostileRan || 0)));
73 c.subscriptions.push(vscode.commands.registerCommand('hostile.alt', async () => {
74 const ed = vscode.window.activeTextEditor;
75 if (ed) await ed.edit(b => b.insert(new vscode.Position(0, 0), 'ALT '));
76 return 'alt';
77 }));
78};
79`,
80}));
81
82const srv = await startServer();
83const beacon = await startBeacon();
84const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] });
85const errors = [];
86
87async function profile() {
88 const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 } });
89 await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
90 const page = await ctx.newPage();
91 page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(e.message); });
92 page.on('dialog', d => d.dismiss());
93 await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
94 await page.evaluate(async () => {
95 const o = await navigator.storage.getDirectory();
96 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(); };
97 await w('fruits.txt', 'pear\napple\nfig\n');
98 await w('app.js', 'function zeta() {}\nfunction alpha() {}\nclass Beta { gamma() {} }\n');
99 });
100 return { ctx, page };
101}
102const openIde = async page => {
103 await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
104 await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
105};
106const open = (page, p) => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
107const value = page => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
108const setValue = (page, v) => page.evaluate(v => window.monaco.editor.getEditors()[0].getModel().setValue(v), v);
109const select = (page, a, b, c, d) => page.evaluate(([a, b, c, d]) => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: a, startColumn: b, endLineNumber: c, endColumn: d }); ed.focus(); }, [a, b, c, d]);
110const readOpfs = (page, name) => page.evaluate(async n => { const o = await navigator.storage.getDirectory(); return (await (await o.getFileHandle(n)).getFile()).text(); }, name);
111const dirty = page => page.evaluate(() => document.querySelector('#tabs-bar .tab.active .tab-x')?.classList.contains('dirty') || false);
112const bridgeState = page => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state());
113const focusEditor = async page => { await page.evaluate(() => window.monaco.editor.getEditors()[0].focus()); await sleep(100); };
114async function installFile(page, name, bytes) {
115 return page.evaluate(async ({ name, b64 }) => {
116 const bin = atob(b64);
117 const u8 = new Uint8Array(bin.length);
118 for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
119 const h = await (await import('/js/ide.js')).loadExt();
120 return (await h.install(new File([u8], name), { withCode: true })).id;
121 }, { name, b64: Buffer.from(bytes).toString('base64') });
122}
123const closeOverlays = async page => {
124 await page.keyboard.press('Escape');
125 await page.evaluate(() => { const p = document.getElementById('palette'); if (p) p.hidden = true; });
126 await sleep(150);
127};
128
129// K7: lo que hacen los atajos de Code, igual con extensiones que sin ellas
130async function shortcuts(page) {
131 const out = {};
132 await open(page, 'app.js');
133 await focusEditor(page);
134 await page.keyboard.press(`${MOD}+KeyP`);
135 out.cmdP = await until(() => page.evaluate(() => { const p = document.getElementById('palette'); return p && !p.hidden ? { open: true, value: document.getElementById('pal-input').value } : null; }), { timeout: 5000 });
136 await closeOverlays(page);
137 await focusEditor(page);
138 await page.keyboard.press(`${MOD}+Shift+KeyP`);
139 out.cmdShiftP = await until(() => page.evaluate(() => { const p = document.getElementById('palette'); return p && !p.hidden ? { open: true, value: document.getElementById('pal-input').value } : null; }), { timeout: 5000 });
140 await closeOverlays(page);
141 await focusEditor(page);
142 const termBefore = await page.evaluate(() => document.getElementById('terminal-panel').hidden);
143 await page.keyboard.press('Control+Backquote');
144 const termAfter = await until(() => page.evaluate(b => (document.getElementById('terminal-panel').hidden !== b ? String(document.getElementById('terminal-panel').hidden) : null), termBefore), { timeout: 5000 });
145 out.ctrlBackquote = { before: termBefore, after: termAfter };
146 await page.evaluate(() => { const t = document.getElementById('terminal-panel'); if (!t.hidden) document.getElementById('act-term')?.click(); });
147 await sleep(200);
148 // «@» en la paleta → Ir a símbolo (quickOutline de Monaco)
149 await focusEditor(page);
150 await page.keyboard.press(`${MOD}+KeyP`);
151 await page.waitForSelector('#palette:not([hidden])');
152 await page.fill('#pal-input', '@');
153 await sleep(200);
154 out.atRows = await page.evaluate(() => [...document.querySelectorAll('#palette .pal-item .pi-hint')].map(x => x.textContent));
155 await page.keyboard.press('Enter');
156 out.atOutline = await until(() => page.evaluate(() => {
157 const w = document.querySelector('.quick-input-widget');
158 if (!w || w.style.display === 'none') return null;
159 const names = [...w.querySelectorAll('.monaco-list-row .label-name')].map(x => x.textContent.trim()).filter(Boolean);
160 return names.length ? names.sort() : null;
161 }), { timeout: 8000 });
162 await page.keyboard.press('Escape');
163 await sleep(200);
164 await focusEditor(page);
165 await page.keyboard.press(`${MOD}+Shift+KeyO`);
166 out.cmdShiftO = await until(() => page.evaluate(() => {
167 const w = document.querySelector('.quick-input-widget');
168 if (!w || w.style.display === 'none') return null;
169 const names = [...w.querySelectorAll('.monaco-list-row .label-name')].map(x => x.textContent.trim()).filter(Boolean);
170 return names.length ? names.sort() : null;
171 }), { timeout: 8000 });
172 await page.keyboard.press('Escape');
173 await sleep(200);
174 // Cmd+S guarda
175 await open(page, 'fruits.txt');
176 await setValue(page, 'saved-by-shortcut\n');
177 await focusEditor(page);
178 await page.keyboard.press(`${MOD}+KeyS`);
179 out.cmdS = await until(async () => ((await readOpfs(page, 'fruits.txt')) === 'saved-by-shortcut\n' && !(await dirty(page)) ? 'saved' : null), { timeout: 5000 });
180 await setValue(page, 'pear\napple\nfig\n');
181 await page.keyboard.press(`${MOD}+KeyS`);
182 await until(async () => (await readOpfs(page, 'fruits.txt')) === 'pear\napple\nfig\n', { timeout: 5000 });
183 return out;
184}
185
186// ── sin extensiones: la referencia ──
187const plain = await profile();
188await openIde(plain.page);
189const ref = await shortcuts(plain.page);
190await plain.ctx.close();
191
192// ── K1: sort-lines y hostile, con su código ──
193const { ctx, page } = await profile();
194await openIde(page);
195const idSort = await installFile(page, 'sort-lines.vsix', sortLines);
196const idHostile = await installFile(page, 'hostile.vsix', hostile);
197const st = await until(async () => { const s = await bridgeState(page); return s.state === 'running' && s.commands.length >= 17 ? s : null; }, { timeout: 90000 });
198ok('K1 sort-lines and hostile install with their code; the sandbox runs them', !!st && idSort === 'tyriar.sort-lines' && idHostile === 'elffuss-test.hostile',
199 JSON.stringify({ state: st?.state, commands: st?.commands?.length, ids: [idSort, idHostile] }));
200
201// ── K2: la paleta de Code ──
202await open(page, 'fruits.txt');
203await select(page, 1, 1, 3, 4);
204await page.keyboard.press(`${MOD}+Shift+KeyP`);
205await page.waitForSelector('#palette:not([hidden])');
206await page.fill('#pal-input', '>sort lines (descending, case');
207const palRows = await until(() => page.evaluate(() => {
208 const rows = [...document.querySelectorAll('#palette .pal-item')].map(r => ({ name: r.querySelector('.pi-name').textContent, hint: r.querySelector('.pi-hint').textContent }));
209 return rows.length ? rows : null;
210}));
211ok('K2 Code’s palette lists sort-lines’ command, with the extension’s name', !!palRows && palRows.some(r => r.name === 'Sort lines (descending, case sensitive)' && r.hint === 'Sort lines'), JSON.stringify(palRows));
212await page.keyboard.press('Enter');
213ok('K2 choosing it sorts the selection (descending)', !!(await until(async () => (await value(page)) === 'pear\nfig\napple\n')), JSON.stringify(await value(page)));
214
215// ── K3: F1 ──
216await setValue(page, 'pear\napple\nfig\n');
217await select(page, 1, 1, 3, 4);
218await page.keyboard.press('F1');
219await page.waitForSelector('.quick-input-widget .quick-input-box input', { state: 'visible' });
220await page.keyboard.type('Sort lines (ascending, case sensitive)');
221const f1Rows = await until(() => page.evaluate(() => {
222 const names = [...document.querySelectorAll('.quick-input-widget .monaco-list-row .label-name')].map(x => x.textContent.trim());
223 return names.length ? names : null;
224}));
225ok('K3 F1 lists it too', !!f1Rows && f1Rows.includes('Sort lines (ascending, case sensitive)'), JSON.stringify(f1Rows?.slice(0, 4)));
226await page.keyboard.press('Enter');
227ok('K3 running it from F1 sorts the selection', !!(await until(async () => (await value(page)) === 'apple\nfig\npear\n')), JSON.stringify(await value(page)));
228
229// ── K4: F9, un paso de deshacer, cambios sin guardar, Cmd+S ──
230await setValue(page, 'pear\napple\nfig\n');
231await page.keyboard.press(`${MOD}+KeyS`);
232await until(async () => !(await dirty(page)));
233await select(page, 1, 1, 3, 4);
234await page.keyboard.press('F9');
235ok('K4 F9 with the editor focused sorts the selection', !!(await until(async () => (await value(page)) === 'apple\nfig\npear\n')), JSON.stringify(await value(page)));
236ok('K4 the tab shows unsaved changes', !!(await until(() => dirty(page))));
237await focusEditor(page);
238await page.keyboard.press(`${MOD}+KeyZ`);
239ok('K4 one undo step brings the file back', !!(await until(async () => (await value(page)) === 'pear\napple\nfig\n')), JSON.stringify(await value(page)));
240await page.keyboard.press(`${MOD}+Shift+KeyZ`);
241await until(async () => (await value(page)) === 'apple\nfig\npear\n');
242await page.keyboard.press(`${MOD}+KeyS`);
243ok('K4 Cmd+S writes the sorted file to the project, and the tab is clean', !!(await until(async () => (await readOpfs(page, 'fruits.txt')) === 'apple\nfig\npear\n' && !(await dirty(page)))), JSON.stringify(await readOpfs(page, 'fruits.txt')));
244
245// ── K5: menú contextual del editor ──
246await focusEditor(page);
247const box = await page.locator('#editor .view-lines').boundingBox();
248await page.mouse.click(box.x + 40, box.y + 8, { button: 'right' });
249// (el menú contextual de Monaco vive en un shadow root: los localizadores de
250// Playwright lo atraviesan, querySelector no)
251const menu = await until(async () => {
252 const items = (await page.locator('.monaco-menu .action-label').allTextContents()).map(t => t.trim()).filter(Boolean);
253 return items.length ? { items, imgs: await page.locator('.monaco-menu img, .monaco-menu svg[onload]').count() } : null;
254}, { timeout: 8000 });
255ok('K5 the editor’s context menu carries sort-lines’ command', !!menu && menu.items.includes('Sort lines (ascending, case sensitive)'), JSON.stringify(menu?.items?.slice(-6)));
256ok('K8 …and hostile’s title there is text', !!menu && menu.items.some(t => t.includes('<img src=x')) && menu.imgs === 0, JSON.stringify(menu?.items?.filter(t => /Hostile/.test(t))));
257await page.keyboard.press('Escape');
258
259// ── K6: atajos reservados y el conflicto, en el panel ──
260const skipped = (await bridgeState(page)).extensions.find(e => e.id === idHostile)?.skipped || [];
261const why = k => skipped.find(s => s.key === k)?.why || '';
262// la tecla que cuenta en esta plataforma (mac en macOS, key en las demás)
263const reserved = ['cmd+p', 'cmd+shift+p', 'ctrl+`', 'cmd+s', 'f1', 'cmd+shift+o', 'cmd+w'].map(k => (process.platform === 'darwin' ? k : k.replace('cmd', 'ctrl')));
264ok('K6 hostile’s chords for Code’s and the browser’s shortcuts are not bound', reserved.every(k => /reserved/.test(why(k))), JSON.stringify(skipped));
265ok('K6 its F9 loses to sort-lines, which was there first', /conflicts with tyriar\.sort-lines/.test(why('f9')), JSON.stringify(skipped.filter(s => s.key === 'f9')));
266await open(page, 'fruits.txt');
267await setValue(page, 'b\na\n');
268await select(page, 1, 1, 2, 2);
269await page.keyboard.press('F9');
270ok('K6 so F9 still runs sort-lines', !!(await until(async () => (await value(page)) === 'a\nb\n')), JSON.stringify(await value(page)));
271await focusEditor(page);
272await page.keyboard.press('Alt+F9');
273ok('K6 a chord nobody else has works (hostile’s Alt+F9)', !!(await until(async () => (await value(page)).startsWith('ALT '))), JSON.stringify(await value(page)));
274await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); });
275const keysRow = page.locator(`#ext-installed .ext-row[data-id="${idHostile}"] .ext-x2-keys`);
276await until(async () => (await keysRow.count()) === 1);
277await keysRow.locator('summary').click();
278const listed = await keysRow.locator('li').allTextContents();
279ok('K6 the Extensions panel lists each one with the reason', listed.length === 8 && listed.filter(t => /reserved/.test(t)).length === 7 && listed.some(t => /f9 .*Sort lines|f9 .*tyriar/.test(t)), JSON.stringify(listed));
280const panelHostile = await page.evaluate(id => {
281 const row = document.querySelector(`#ext-installed .ext-row[data-id="${id}"]`);
282 return { text: row?.textContent || '', els: row ? row.querySelectorAll('.ext-x2-cmds img, .ext-x2-cmds svg, .ext-x2-cmds b, .ext-name i').length : -1 };
283}, idHostile);
284ok('K8 the panel shows hostile’s name and command titles as text', panelHostile.text.includes('Hostile <i>name</i>') && panelHostile.text.includes('<img src=x') && panelHostile.els === 0, JSON.stringify(panelHostile).slice(0, 300));
285await page.click('#settings-close').catch(() => {});
286
287// ── K8: títulos hostiles en la paleta y en F1 ──
288await open(page, 'fruits.txt');
289await focusEditor(page);
290await page.keyboard.press(`${MOD}+Shift+KeyP`);
291await page.waitForSelector('#palette:not([hidden])');
292await page.fill('#pal-input', '>hostile');
293const palHostile = await until(() => page.evaluate(() => {
294 const rows = [...document.querySelectorAll('#palette .pal-item')];
295 return rows.length ? { names: rows.map(r => r.querySelector('.pi-name').textContent), hints: rows.map(r => r.querySelector('.pi-hint').textContent), els: document.querySelectorAll('#palette img, #palette svg, #palette .pal-item b').length } : null;
296}));
297ok('K8 Code’s palette shows the hostile title and name as text', !!palHostile && palHostile.names.some(n => n.includes(EVIL_TITLE)) && palHostile.hints.includes('Hostile <i>name</i>') && palHostile.els === 0, JSON.stringify(palHostile));
298await closeOverlays(page);
299await focusEditor(page);
300await page.keyboard.press('F1');
301await page.waitForSelector('.quick-input-widget .quick-input-box input', { state: 'visible' });
302await page.keyboard.type('Hostile');
303const f1Hostile = await until(() => page.evaluate(() => {
304 const w = document.querySelector('.quick-input-widget');
305 const names = [...w.querySelectorAll('.monaco-list-row .label-name')].map(x => x.textContent.trim());
306 return names.length ? { names, els: w.querySelectorAll('img, svg[onload]').length } : null;
307}));
308ok('K8 F1 shows the hostile title as text', !!f1Hostile && f1Hostile.names.some(n => n.includes('<img src=x')) && f1Hostile.els === 0, JSON.stringify(f1Hostile));
309await page.keyboard.press('Escape');
310ok('K8 no handler from a title ran', !(await page.evaluate(() => window.__pwned)));
311
312// ── K7: los atajos de Code, con las dos en marcha ──
313const withExt = await shortcuts(page);
314const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
315ok('K7 Cmd+P opens Code’s file palette, as without extensions', same(withExt.cmdP, ref.cmdP) && withExt.cmdP?.value === '', JSON.stringify([withExt.cmdP, ref.cmdP]));
316ok('K7 Cmd+Shift+P opens it on commands (">"), as without extensions', same(withExt.cmdShiftP, ref.cmdShiftP) && withExt.cmdShiftP?.value === '>', JSON.stringify([withExt.cmdShiftP, ref.cmdShiftP]));
317ok('K7 Ctrl+` toggles the terminal, as without extensions', same(withExt.ctrlBackquote, ref.ctrlBackquote) && ref.ctrlBackquote.after === 'false', JSON.stringify([withExt.ctrlBackquote, ref.ctrlBackquote]));
318ok('K7 "@" in the palette goes to the file’s symbols, as without extensions', same(withExt.atRows, ref.atRows) && same(withExt.atOutline, ref.atOutline) && (ref.atOutline || []).includes('alpha'), JSON.stringify([withExt.atOutline, ref.atOutline]));
319ok('K7 Cmd+Shift+O opens the same outline', same(withExt.cmdShiftO, ref.cmdShiftO) && (ref.cmdShiftO || []).includes('zeta'), JSON.stringify([withExt.cmdShiftO, ref.cmdShiftO]));
320ok('K7 Cmd+S saves, as without extensions', withExt.cmdS === 'saved' && ref.cmdS === 'saved', JSON.stringify([withExt.cmdS, ref.cmdS]));
321const ranCount = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('hostile.count'));
322ok('K7 none of those chords ran hostile’s command (its counter is 0)', ranCount === '0', String(ranCount));
323
324// ── K9: privacidad ──
325const sbx = [...new Set(srv.requests.filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]))];
326ok('K9 the sandbox site was asked only for its two documents', sbx.length > 0 && sbx.every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sbx.join(' '));
327ok('K9 beacon: 0 hits', beacon.hits.length === 0, JSON.stringify(beacon.hits.slice(0, 3)));
328ok('K9 no page errors', errors.length === 0, errors.slice(0, 3).join(' | '));
329
330await ctx.close();
331await browser.close();
332await beacon.close();
333await srv.close();
334console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
335process.exit(fails ? 1 : 0);