Elffuss BraidHub

utopia-ia/elffuss-code public

main · 14.1 KiBRawPermalink
1// Extension mode for Code's own suites, unchanged:
2//
3// BASE=http://127.0.0.1:<port> node --import ./lib/x2-mode.mjs codeedit.mjs
4//
5// (tests/run-modes.sh runs every suite this way and without it.)
6//
7// A Node preload that patches Playwright's chromium.launch and
8// launchPersistentContext. Before a page of the suite first goes to a Code
9// origin (http://127.0.0.1:<port>, the only host that has a sandbox in
10// development), that page visits <origin>/manifest.json?x2seed and installs two
11// synthetic code extensions there with Code's own store.js, then carries on to
12// where the suite was going:
13// noop one command (so the palette and F1 carry an extension command)
14// observer hover, completion and symbol providers for every file, always
15// empty, never a formatter (so every feature the suite uses goes
16// through the sandbox and back)
17// Both have their code on, so whenever the suite opens the IDE, host.js starts
18// the sandbox and they run in it while the suite works.
19//
20// The seeding runs in that small document of Code's own origin (a JSON file
21// that is always there, so no 404 shows up in the console of suites that count
22// console errors). Nothing is added to web/, and no request is routed (a
23// Playwright route would turn off the HTTP cache for the whole context and make
24// this mode differ from the default one in a way users never see).
25//
26// Checks, printed with ✅/❌ so run-modes.sh counts them, for each browser when
27// the suite closes it:
28// · premise: the seed installed both extensions with their code on;
29// · every page that opened the IDE got the sandbox running (before the suite
30// navigates away, reloads or closes it, this waits for that, so the check
31// never passes because nobody looked); pages opened with ?noext or ?noext2,
32// where the user turned code off, must NOT have loaded the bridge at all;
33// · no level 2 errors: the bridge never in "error", no [x2] warnings, no page
34// error from js/ext2/;
35// · nothing requested from the sandbox site but its two documents.
36// A failed check makes the suite exit 1 whatever it said itself. When no page
37// opened the IDE at all, the suite says "x2-mode: not exercised" and
38// run-modes.sh shows that instead of a plain PASS.
39//
40// X2_SEEDED (set here) names the two seeded extensions, for the one suite
41// that counts installed extensions itself (extensions.mjs).
42
43import { createRequire } from 'node:module';
44import { chromium } from 'playwright';
45import { NOOP, OBSERVER, recordFor } from './x2-fixtures.mjs';
46
47const CODE_ORIGIN = /^http:\/\/127\.0\.0\.1:\d+$/;
48const SEED_PATH = '/manifest.json?x2seed';
49const SANDBOX_DOCS = new Set(['/x2/v1/sandbox.html', '/x2/v1/exthost-iframe.html']);
50const WAIT_RUNNING = 90000;
51const SEEDED = [NOOP, OBSERVER].map(f => recordFor(f));
52const SEEDED_IDS = SEEDED.map(r => r.rec.id);
53// para la suite del nivel 1, que cuenta y desinstala solo las suyas
54process.env.X2_SEEDED = SEEDED_IDS.join(',');
55
56let failed = 0;
57const say = (good, text) => { console.log((good ? '✅' : '❌') + ' x2-mode: ' + text); if (!good) failed++; };
58const note = text => console.log(' x2-mode: ' + text);
59const sleep = ms => new Promise(r => setTimeout(r, ms));
60
61// En cada documento de Code (marco principal): avisa cuando el IDE abre
62// (el editor de Monaco dentro de #editor) y, en cuanto la página carga
63// js/ext2/bridge.js (lo hace host.js), el estado del puente. Importar ese
64// mismo módulo da la misma instancia: no carga nada que la página no cargara.
65const INIT = `(() => {
66 if (window.top !== window || !${CODE_ORIGIN}.test(location.origin) || location.pathname + location.search === ${JSON.stringify(SEED_PATH)}) return;
67 const doc = Math.random().toString(36).slice(2) + Date.now().toString(36);
68 const tell = d => console.debug('[x2mode]' + JSON.stringify(Object.assign({ doc, at: location.pathname + location.search }, d)));
69 tell({ open: true });
70 let ide = false, hooked = false;
71 const look = () => { if (!ide && document.querySelector('#editor .monaco-editor')) { ide = true; tell({ ide: true }); } };
72 new MutationObserver(look).observe(document, { childList: true, subtree: true });
73 const hook = () => {
74 if (hooked) return;
75 hooked = true;
76 tell({ bridge: true });
77 import('/js/ext2/bridge.js').then(m => {
78 let last = '';
79 const send = () => {
80 const s = m.state();
81 const error = s.error ? String(s.error.message || s.error).slice(0, 300) : null;
82 const k = s.state + '|' + error + '|' + (s.violations || 0);
83 if (k !== last) { last = k; tell({ state: s.state, error, violations: s.violations || 0 }); }
84 };
85 m.onChange(send);
86 send();
87 setInterval(send, 400);
88 }, e => tell({ hookError: String(e && e.message || e) }));
89 };
90 try {
91 new PerformanceObserver(l => { for (const e of l.getEntries()) if (e.name.includes('/js/ext2/bridge.js')) hook(); })
92 .observe({ type: 'resource', buffered: true });
93 } catch (e) { tell({ hookError: 'no PerformanceObserver' }); }
94})();`;
95
96const browsers = []; // { id, contexts: [] }
97let anyBrowser = false;
98let ideSeen = 0; // páginas que abrieron el IDE (con el código encendido)
99
100async function track(browserRec, ctx) {
101 const st = {
102 seeded: new Map(), // origin → ids seeded with code on
103 docs: new Map(), // doc → { page, at, ide, states: [], error }
104 current: new WeakMap(), // page → doc
105 sandboxBad: [], sandboxOk: 0,
106 x2errors: [],
107 ports: new Set(),
108 };
109 browserRec.contexts.push(st);
110 await ctx.addInitScript({ content: INIT });
111 ctx.on('console', msg => {
112 const text = msg.text();
113 if (text.startsWith('[x2mode]')) {
114 let d;
115 try { d = JSON.parse(text.slice(8)); } catch { return; }
116 const page = msg.page();
117 let rec = st.docs.get(d.doc);
118 if (!rec) { rec = { page, at: d.at, ide: false, ideAt: 0, bridge: false, states: [], error: null, hookError: null }; st.docs.set(d.doc, rec); }
119 if (page) st.current.set(page, d.doc);
120 if (d.ide) { rec.ide = true; rec.ideAt = Date.now(); }
121 if (d.bridge) rec.bridge = true;
122 if (d.state) rec.states.push(d.state);
123 if (d.error) rec.error = d.error;
124 if (d.violations) rec.violations = d.violations;
125 if (d.hookError) rec.hookError = d.hookError;
126 return;
127 }
128 if (/\[x2\]/.test(text) && (msg.type() === 'warning' || msg.type() === 'error')) st.x2errors.push(text.slice(0, 300));
129 });
130 ctx.on('weberror', e => {
131 const err = e.error();
132 const stack = String(err?.stack || '');
133 if (/\/js\/ext2\//.test(stack)) st.x2errors.push('page error: ' + String(err?.message || err).slice(0, 200));
134 });
135 ctx.on('request', r => {
136 let u;
137 try { u = new URL(r.url()); } catch { return; }
138 if (u.hostname !== 'localhost' || !st.ports.has(u.port)) return;
139 if (SANDBOX_DOCS.has(u.pathname)) st.sandboxOk++;
140 else st.sandboxBad.push(u.pathname + u.search);
141 });
142 ctx.on('page', p => wrapPage(p, st));
143 for (const p of ctx.pages()) wrapPage(p, st);
144 const origNewPage = ctx.newPage.bind(ctx);
145 ctx.newPage = async (...a) => { const p = await origNewPage(...a); wrapPage(p, st); return p; };
146 const origClose = ctx.close.bind(ctx);
147 ctx.close = async (...a) => { await Promise.all(ctx.pages().map(p => settle(p, st))); return origClose(...a); };
148 return st;
149}
150
151async function seed(page, origin, st, goto) {
152 st.seeded.set(origin, []);
153 st.ports.add(new URL(origin).port);
154 await goto(origin + SEED_PATH, { waitUntil: 'domcontentloaded' });
155 const ids = await page.evaluate(async recs => {
156 const store = await import('/js/ext/store.js');
157 for (const { rec, files } of recs) {
158 const m = new Map();
159 for (const [p, t] of Object.entries(files)) m.set(store.codeKey(rec.id, rec.version, p), new TextEncoder().encode(t).buffer);
160 await store.put(rec, m);
161 }
162 return (await store.list()).filter(r => r.enabled && r.runs).map(r => r.id);
163 }, SEEDED).catch(e => { st.x2errors.push('seed: ' + String(e?.message || e).slice(0, 200)); return []; });
164 st.seeded.set(origin, ids);
165}
166
167// Antes de que la prueba se vaya de un documento que abrió el IDE: que el
168// recinto haya llegado a algo (en marcha o error), o se acaba el tiempo. Si la
169// página ni siquiera cargó el puente al poco de abrir el IDE, no se espera más
170// (el informe lo dirá: «never started»).
171async function settle(page, st) {
172 const doc = st.current.get(page);
173 const rec = doc && st.docs.get(doc);
174 if (!rec || !rec.ide || page.isClosed() || /[?&]noext2?(?:[=&]|$)/.test(rec.at)) return;
175 const end = Date.now() + WAIT_RUNNING;
176 const done = () => rec.states.some(s => s === 'running' || s === 'error');
177 while (Date.now() < end && !page.isClosed() && !done() && (rec.bridge || Date.now() - rec.ideAt < 15000)) await sleep(150);
178}
179
180const wrapped = new WeakSet();
181function wrapPage(page, st) {
182 if (wrapped.has(page)) return;
183 wrapped.add(page);
184 const goto = page.goto.bind(page);
185 page.goto = async (url, opts) => {
186 await settle(page, st);
187 let origin = null;
188 try { origin = new URL(url).origin; } catch { /* about:blank, data: … */ }
189 if (origin && CODE_ORIGIN.test(origin) && !st.seeded.has(origin)) await seed(page, origin, st, goto);
190 return goto(url, opts);
191 };
192 const reload = page.reload.bind(page);
193 page.reload = async (...a) => { await settle(page, st); return reload(...a); };
194 const close = page.close.bind(page);
195 page.close = async (...a) => { await settle(page, st); return close(...a); };
196}
197
198function report(browserRec) {
199 for (const st of browserRec.contexts) {
200 for (const [origin, ids] of st.seeded) {
201 const missing = SEEDED_IDS.filter(id => !ids.includes(id));
202 say(!missing.length, missing.length ? `the seed did not install ${missing.join(', ')} on ${origin}` : `${ids.length} code extensions installed and on (${SEEDED_IDS.join(', ')})`);
203 }
204 // con ?noext o ?noext2 el usuario apagó el código a propósito: ahí el
205 // recinto NO debe arrancar, y eso también se comprueba
206 const off = d => /[?&]noext2?(?:[=&]|$)/.test(d.at);
207 const switched = [...st.docs.values()].filter(d => d.ide && off(d));
208 if (switched.length) {
209 const ran = switched.filter(d => d.bridge || d.states.length);
210 say(!ran.length, `with ?noext or ?noext2 the sandbox stayed off (${switched.length} pages)` + (ran.length ? ' — it ran in: ' + ran.map(d => d.at).join(', ') : ''));
211 }
212 const ide = [...st.docs.values()].filter(d => d.ide && !off(d));
213 ideSeen += ide.length;
214 if (!st.seeded.size && !ide.length) { note('this context never opened Code'); continue; }
215 if (!ide.length) { note('no page opened the IDE in this context'); }
216 else {
217 const notRunning = ide.filter(d => !d.states.includes('running'));
218 say(!notRunning.length, `the sandbox was running in every page that opened the IDE (${ide.length - notRunning.length} of ${ide.length})`
219 + (notRunning.length ? ' — not in: ' + notRunning.map(d => `${d.at} [${d.states.join('>') || 'never started'}${d.error ? ': ' + d.error : ''}${d.hookError ? '; ' + d.hookError : ''}]`).slice(0, 4).join(', ') : ''));
220 }
221 const broken = [...st.docs.values()].filter(d => d.states.includes('error') || d.violations);
222 const errs = [...st.x2errors, ...broken.map(d => `${d.at}: bridge ${d.states.join('>')}${d.error ? ' (' + d.error + ')' : ''}${d.violations ? ', ' + d.violations + ' violations' : ''}`)];
223 say(!errs.length, 'no level 2 errors' + (errs.length ? ' — ' + errs.slice(0, 4).join(' | ') : ''));
224 say(!st.sandboxBad.length, `from the sandbox site, only its two documents (${st.sandboxOk} requests)` + (st.sandboxBad.length ? ' — also: ' + st.sandboxBad.slice(0, 4).join(' ') : ''));
225 }
226}
227
228function wrapBrowser(browser) {
229 anyBrowser = true;
230 const rec = { contexts: [], reported: false };
231 browsers.push(rec);
232 const origNewContext = browser.newContext.bind(browser);
233 browser.newContext = async (...a) => { const ctx = await origNewContext(...a); await track(rec, ctx); return ctx; };
234 const origClose = browser.close.bind(browser);
235 browser.close = async (...a) => {
236 if (!rec.reported) {
237 await Promise.all(browser.contexts().flatMap(c => c.pages()).map(p => {
238 const st = rec.contexts.find(s => s.current.has(p));
239 return st ? settle(p, st) : null;
240 }));
241 rec.reported = true;
242 report(rec);
243 }
244 return origClose(...a);
245 };
246 return browser;
247}
248
249// El `chromium` de `import 'playwright'` y el de require('playwright') (las
250// baterías lo cargan así) son objetos distintos: se parchean los dos.
251function patch(bt) {
252 if (!bt || bt.__x2mode) return;
253 bt.__x2mode = true;
254 const origLaunch = bt.launch.bind(bt);
255 bt.launch = async (...a) => wrapBrowser(await origLaunch(...a));
256 const origPersistent = bt.launchPersistentContext.bind(bt);
257 bt.launchPersistentContext = async (...a) => {
258 const ctx = await origPersistent(...a);
259 anyBrowser = true;
260 const rec = { contexts: [], reported: false };
261 browsers.push(rec);
262 const st = await track(rec, ctx);
263 const origClose = ctx.close; // ya envuelto por track (settle)
264 ctx.close = async (...b) => { if (!rec.reported) { await Promise.all(ctx.pages().map(p => settle(p, st))); rec.reported = true; report(rec); } return origClose(...b); };
265 return ctx;
266 };
267}
268patch(chromium);
269patch(createRequire(import.meta.url)('playwright').chromium);
270
271// Si la prueba sale sin cerrar el navegador: lo que se sepa, sin esperar.
272const origExit = process.exit.bind(process);
273let finished = false;
274function finish() {
275 if (finished) return;
276 finished = true;
277 for (const rec of browsers) if (!rec.reported) { rec.reported = true; report(rec); }
278 if (!anyBrowser) note('no browser in this suite');
279 // Sin ninguna página que abriera el IDE, el recinto nunca corrió: la suite
280 // pasó, pero el modo extensiones no la ha probado. run-modes.sh lo enseña así.
281 if (!ideSeen) console.log(' x2-mode: not exercised: no page opened the IDE, so the sandbox never ran in this suite');
282}
283process.exit = code => { finish(); return origExit(failed ? 1 : code); };
284process.on('exit', code => { finish(); if (failed && !code) process.exitCode = 1; });