Repository navigation
Expand file tree
/
Copy pathtest-harness.html
More file actions
479 lines (447 loc) · 23.3 KB
/
Copy pathtest-harness.html
File metadata and controls
479 lines (447 loc) · 23.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>mechcheck extension harness</title>
<style>
body { font: 14px/1.6 system-ui, sans-serif; margin: 0; padding: 24px; background: #eef1f6; color: #171a21; }
h1 { font-size: 16px; margin: 0 0 4px; }
p { margin: 0 0 16px; color: #4a5162; max-width: 60ch; }
pre { background: #fff; border: 1px solid #d8dde6; border-radius: 6px; padding: 12px; font-size: 12px; overflow: auto; }
@media (prefers-color-scheme: dark) {
body { background: #0e1116; color: #e5e8ef; } p { color: #a3abbd; }
pre { background: #151922; border-color: #2a303c; }
}
</style>
</head>
<body>
<h1>mechcheck extension harness</h1>
<p>Stands in for Overleaf: it fakes the <code>chrome.*</code> APIs, serves a small
project from a mocked <code>fetch</code>, and then drives the real content
script. Open this file in a browser to exercise the panel without installing
anything or touching a live project.</p>
<pre id="log">running…</pre>
<script>
/* ---- a chrome API stand-in, just enough for the content script ---- */
const memory = { sync: {}, local: {} };
window.chrome = {
storage: {
sync: { get: async k => (k in memory.sync ? { [k]: memory.sync[k] } : {}),
set: async o => Object.assign(memory.sync, o) },
local: { get: async k => (k in memory.local ? { [k]: memory.local[k] } : {}),
set: async o => Object.assign(memory.local, o) },
},
runtime: {
// Pretend the service worker answered; the engine only needs a JSON body.
sendMessage: async msg => ({ ok: true, data: null }),
onMessage: { addListener: () => {} },
},
tabs: { query: async () => [], sendMessage: async () => {} },
};
/* ---- a project, served the way Overleaf serves one ---- */
const PROJECT = {
"main.tex": String.raw`\documentclass[sigconf,review]{acmart}
\begin{document}
\title{A Study of Automated Vehicles}
\author{Mark Colley}
\begin{abstract}
We ran a study with participants and found significant effects.
\end{abstract}
\section{Introduction}
The Automated Driving System (ADS) is new. Participants (N=24) took part.
The effect was significant, p < .05, F = 4.7. This is is a problem.
The Automated Driving System (ADS) appears again here.
\begin{figure}
\includegraphics[width=\linewidth]{plot.pdf}
\caption{Results of the study}
\label{fig:res}
\end{figure}
See Figure~\ref{fig:res}. The red line shows the baseline. TODO fix this.
\bibliographystyle{plain}
\bibliography{refs}
\end{document}`,
"refs.bib": String.raw`@article{etal, author = {Smith, John et al.}, title = {Bad Authors},
journal = {J}, year = {2021}, pages = {45-58}}`,
};
/* Build a real zip in the browser, so readZip is exercised for real rather
than bypassed: stored (uncompressed) entries, which the reader supports. */
function crc32(bytes) {
let c, table = [];
for (let n = 0; n < 256; n++) {
c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1;
table[n] = c >>> 0;
}
let crc = 0xFFFFFFFF;
for (const b of bytes) crc = table[(crc ^ b) & 0xFF] ^ (crc >>> 8);
return (crc ^ 0xFFFFFFFF) >>> 0;
}
function makeZip(entries) {
const enc = new TextEncoder();
const chunks = [], central = [];
let offset = 0;
for (const [name, text] of Object.entries(entries)) {
const nameBytes = enc.encode(name), data = enc.encode(text);
const sum = crc32(data);
const local = new DataView(new ArrayBuffer(30));
local.setUint32(0, 0x04034b50, true); local.setUint16(4, 20, true);
local.setUint16(8, 0, true); // stored
local.setUint32(14, sum, true);
local.setUint32(18, data.length, true); local.setUint32(22, data.length, true);
local.setUint16(26, nameBytes.length, true);
chunks.push(new Uint8Array(local.buffer), nameBytes, data);
const cd = new DataView(new ArrayBuffer(46));
cd.setUint32(0, 0x02014b50, true); cd.setUint16(4, 20, true); cd.setUint16(6, 20, true);
cd.setUint16(10, 0, true);
cd.setUint32(16, sum, true);
cd.setUint32(20, data.length, true); cd.setUint32(24, data.length, true);
cd.setUint16(28, nameBytes.length, true);
cd.setUint32(42, offset, true);
central.push(new Uint8Array(cd.buffer), nameBytes);
offset += 30 + nameBytes.length + data.length;
}
const centralSize = central.reduce((n, c) => n + c.length, 0);
const eocd = new DataView(new ArrayBuffer(22));
eocd.setUint32(0, 0x06054b50, true);
eocd.setUint16(8, Object.keys(entries).length, true);
eocd.setUint16(10, Object.keys(entries).length, true);
eocd.setUint32(12, centralSize, true); eocd.setUint32(16, offset, true);
const all = [...chunks, ...central, new Uint8Array(eocd.buffer)];
const total = all.reduce((n, c) => n + c.length, 0);
const out = new Uint8Array(total);
let pos = 0;
for (const c of all) { out.set(c, pos); pos += c.length; }
return out;
}
/* ---- a stand-in for Overleaf's editor ----
The marker code reads a file tree and a CodeMirror gutter out of the host
page, so this is that markup. It is not a tidied version of it: it is
copied from what live Overleaf actually served on 2026-09-22, including
the two things that broke the first attempt --
* the tree row renders its icons as Material Symbols ligatures, so its
textContent is "descriptionmain.texmore_vertMenu" and only aria-label
or .item-name gives the real name; and
* CodeMirror keeps a hidden zero-height .cm-gutterElement holding the
widest line number, to size the gutter, which is not a line.
A stand-in that leaves those out passes while the real thing shows nothing,
which is exactly what happened. Re-run test 1 in docs/testing.md when
Overleaf changes: only that can say this is still faithful. */
function buildFakeEditor(lineCount = 20, spacerText = "99") {
const tree = document.createElement("ul");
tree.setAttribute("role", "tree");
const row = (name, selected) => `
<li role="treeitem" ${selected ? 'class="selected" aria-selected="true"' : ""}
aria-label="${name}" translate="no">
<div class="entity" role="presentation" data-file-type="doc">
<div class="entity-name entity-name-react" role="presentation">
<div class="file-tree-entity-details">
<span class="material-symbols file-tree-icon unfilled"
aria-hidden="true" translate="no">description</span>
<div class="item-name"><span>${name}</span></div>
</div>
<div class="menu-button btn-group">
<button class="entity-menu-toggle btn btn-sm" aria-label="Open ${name} action menu">
<span class="material-symbols" aria-hidden="true" translate="no">more_vert</span>
<span class="visually-hidden">Menu</span>
</button>
</div>
</div>
</div>
</li>`;
tree.innerHTML = row("main.tex", true) + row("refs.bib", false);
const editor = document.createElement("div");
editor.className = "cm-editor";
editor.style.cssText = "position:relative;width:820px;font:13px/18px monospace";
const scroller = document.createElement("div");
scroller.className = "cm-scroller";
scroller.style.cssText = "display:flex;overflow:auto;max-height:400px";
const gutters = document.createElement("div");
gutters.className = "cm-gutters";
const lineNumbers = document.createElement("div");
lineNumbers.className = "cm-gutter cm-lineNumbers";
// The measuring spacer comes first, exactly as CodeMirror emits it.
const spacer = document.createElement("div");
spacer.className = "cm-gutterElement";
spacer.style.cssText = "height:0;visibility:hidden";
spacer.textContent = spacerText;
lineNumbers.appendChild(spacer);
for (let n = 1; n <= lineCount; n++) {
const el = document.createElement("div");
el.className = "cm-gutterElement";
el.style.height = "18px";
el.textContent = String(n);
lineNumbers.appendChild(el);
}
// The fold gutter has its own .cm-gutterElement children, with no numbers.
const fold = document.createElement("div");
fold.className = "cm-gutter cm-foldGutter";
for (let n = 1; n <= lineCount; n++) {
const el = document.createElement("div");
el.className = "cm-gutterElement";
el.style.height = "18px";
el.textContent = " ";
fold.appendChild(el);
}
gutters.append(lineNumbers, fold);
// The text itself. The inline notes underline a span of a line, so the
// lines have to carry the real source -- and split across spans, the way
// syntax highlighting leaves them, or a walk over one text node would
// pass while the real thing failed.
const content = document.createElement("div");
content.className = "cm-content";
content.style.cssText = "flex:1;white-space:pre";
const source = PROJECT["main.tex"].split("\n");
for (let n = 1; n <= lineCount; n++) {
const el = document.createElement("div");
el.className = "cm-line";
el.style.height = "18px";
const text = source[n - 1] || "";
const cut = Math.floor(text.length / 2);
el.append(document.createTextNode(text.slice(0, cut)));
const tail = document.createElement("span");
tail.textContent = text.slice(cut);
el.appendChild(tail);
content.appendChild(el);
}
// Live Overleaf rendered 54 line elements against 53 gutter numbers, and
// code that paired the two by counting put every note on the wrong line.
// This is an element matching .cm-line that no number lines up with: it
// takes no space, so it shifts the count without shifting the page, which
// is what makes counting wrong and geometry right.
const orphan = document.createElement("div");
orphan.className = "cm-line";
orphan.style.cssText = "position:absolute;top:-9999px";
orphan.textContent = "% a row the gutter does not number";
content.insertBefore(orphan, content.children[5] || null);
scroller.append(gutters, content);
editor.appendChild(scroller);
document.body.append(tree, editor);
return { tree, editor, scroller, gutters, lineNumbers, spacer, content };
}
const ZIP = makeZip(PROJECT);
window.fetch = async (url) => {
const path = String(url);
if (path.includes("/download/zip"))
return new Response(ZIP, { status: 200, headers: { "Content-Type": "application/zip" } });
return new Response("", { status: 404 }); // no compiled output in the harness
};
</script>
<script src="engine.js"></script>
<script src="content.js"></script>
<script>
(async () => {
const log = [];
const say = (name, ok, detail = "") => log.push(`${ok ? "ok " : "FAIL "} ${name}${detail ? " — " + detail : ""}`);
const C = window.__mechcheckContent;
try {
say("content script exposed its internals", !!C);
// A floor, not an exact count: pinning the number makes this fail
// every time a rule is added, which is not a defect.
say("engine is loaded", !!globalThis.mechcheck && globalThis.mechcheck.RULES.length >= 100,
globalThis.mechcheck ? globalThis.mechcheck.RULES.length + " rules" : "missing");
// The harness page is not /project/<id>, so the panel must not auto-mount.
say("does not mount outside a project page", !document.getElementById("mechcheck-host"));
C.ensureUI();
const host = document.getElementById("mechcheck-host");
say("panel mounts on demand", !!host && !!host.shadowRoot);
const files = await C.fetchProjectZip("0123456789abcdef01234567");
say("reads the project zip Overleaf serves", files.size === 2, [...files.keys()].join(", "));
const result = await globalThis.mechcheck.runChecks(files, {
profile: "paper-anonymous", stage: "submission", venue: "autoui", verify: false });
C.render(result, { profile: "paper-anonymous", verify: false });
const shadow = host.shadowRoot;
const rendered = shadow.querySelectorAll(".finding").length;
say("findings render in the shadow root", rendered > 5, rendered + " rows");
say("the launcher badge counts problems", shadow.querySelector(".badge").textContent !== "",
shadow.querySelector(".badge").textContent);
say("severity stripes are applied", !!shadow.querySelector(".finding.error"));
const fired = new Set(result.findings.map(f => f.rule));
for (const id of ["VEN002", "ANON001", "ACC001", "ABB001", "STY001", "BIB006"])
say(`${id} fires through the extension path`, fired.has(id));
// filtering
shadow.querySelectorAll(".pill")[2].click(); // hide info
say("filters redraw the list", shadow.querySelectorAll(".finding").length < rendered);
say("report renders as Markdown", C.reportMarkdown(result).includes("mechcheck —"));
// the fix path: a button that becomes enabled, then a corrected file
const fixBtn = shadow.querySelector(".fix");
say("the fix button reports how many are fixable",
/Fix \d+/.test(fixBtn.textContent) && !fixBtn.disabled, fixBtn.textContent);
const fixes = globalThis.mechcheck.applyFixes(result);
say("a corrected file is produced", fixes.files.size >= 1,
[...fixes.files.keys()].join(", "));
say("the corrected file still looks like LaTeX",
(fixes.files.get("main.tex") || "").includes(String.raw`\begin{document}`));
say("alt text is never among the fixes",
!fixes.applied.some(a => a.rule.startsWith("ACC")),
fixes.applied.map(a => a.rule).join(","));
C.showFixes(result);
say("clicking Fix shows the corrected file to copy",
shadow.querySelector(".body").textContent.includes("Copy corrected file"));
// marks beside the lines, against a stand-in for Overleaf's editor.
// The spacer is given the number of a line that really has a finding, so
// that anything reading it as a line is caught here rather than in Chrome.
const byLine = C.findingsByLine(result, "main.tex");
const trapLine = [...byLine.keys()][0];
const fake = buildFakeEditor(20, String(trapLine));
say("the open file is read from the file tree", C.openFileName() === "main.tex", C.openFileName());
say("the tree row's own text would have given the wrong name",
fake.tree.querySelector('[aria-selected="true"]').textContent.replace(/\s+/g, "")
!== "main.tex");
say("findings are grouped by the line they sit on", byLine.size > 0, byLine.size + " lines");
say("a finding in another file is not grouped here",
![...byLine.values()].flat().some(f => f.file && f.file !== "main.tex"));
const placed = C.placeMarkers(result);
const marks = document.querySelectorAll(".mechcheck-gutter-mark");
say("marks are placed in the gutter", placed > 0 && marks.length === placed, placed + " marks");
say("each mark sits beside the line it is about", [...marks].every(mark => {
const line = mark.getAttribute("data-mechcheck-line");
return mark.parentElement.textContent.trim().startsWith(line);
}));
say("a mark carries the finding as its tooltip",
[...marks].every(m => /^[A-Z]{3,4}\d{3}: /.test(m.title || "")));
say("the worst severity on a line wins its colour",
[...marks].every(m => /\b(error|warn|info)\b/.test(m.className)));
say("marks are styled from one injected sheet",
document.querySelectorAll("#mechcheck-marker-styles").length === 1);
say("the hidden measuring spacer is not treated as a line",
!fake.spacer.querySelector(".mechcheck-gutter-mark"), "spacer reads " + trapLine);
say("every mark sits on a line with a height",
[...marks].every(m => m.parentElement.offsetHeight > 0));
say("the fold gutter gets no marks",
!fake.editor.querySelector(".cm-foldGutter .mechcheck-gutter-mark"));
// the finding written where the problem is
const written = C.placeAnnotations(result);
const notes = [...document.querySelectorAll(".mechcheck-inline-note")];
const rules = [...document.querySelectorAll(".mechcheck-inline-rule")];
say("a note is written beside the line", written > 0 && notes.length === written,
written + " notes");
say("the note names its rule and says what is wrong",
notes.every(n => /^[A-Z]{3,4}\d{3}\s{2}\S/.test(n.textContent)), notes[0] && notes[0].textContent);
say("a line with two findings says so once", notes.every(n => {
const line = +n.getAttribute("data-mechcheck-line");
const count = C.findingsByLine(result, "main.tex").get(line).length;
return count === 1 || / \+\d+ more$/.test(n.textContent);
}));
say("the full list is in the note's tooltip",
notes.every(n => (n.title || "").split("\n").length
=== C.findingsByLine(result, "main.tex")
.get(+n.getAttribute("data-mechcheck-line")).length));
say("lines are found by where they are, not by counting", (() => {
const source = PROJECT["main.tex"].split("\n");
const map = C.renderedLines(fake.editor);
// past the unnumbered row, which is where counting goes wrong
return [2, 7, 12, 18].every(n => map.get(n) && map.get(n).textContent === source[n - 1]);
})());
say("the unnumbered row is matched to no line", (() => {
const map = C.renderedLines(fake.editor);
return ![...map.values()].some(el => el.textContent.startsWith("% a row the gutter"));
})());
say("the offending words are underlined", rules.length > 0, rules.length + " underlines");
say("the underline covers the words the message names", (() => {
const source = PROJECT["main.tex"].split("\n");
const map = C.renderedLines(fake.editor);
return [...C.findingsByLine(result, "main.tex")].every(([line, here]) =>
!map.get(line) || here.every(f => {
const span = C.spanFor(f, source[line - 1] || "");
if (!span) return true;
// A quote only decides the span when the line really contains it;
// otherwise the column decides, and the span is a word instead.
const quoted = /[`'‘"]([^`'’"\n]{2,60})['’`"]/.exec(f.message || "");
const text = source[line - 1] || "";
if (!quoted || !text.includes(quoted[1])) return /^\S+$/.test(text.slice(span[0], span[1]));
return text.slice(span[0], span[1]) === quoted[1];
}));
})());
say("a note clears the text of its own line", notes.every(n => {
const line = C.renderedLines(fake.editor).get(+n.getAttribute("data-mechcheck-line"));
if (!line) return true;
const box = n.getBoundingClientRect();
const range = document.createRange(); range.selectNodeContents(line);
return [...range.getClientRects()].filter(r => r.width)
.every(r => Math.abs(r.top - box.top) > 6 || box.left >= r.right - 0.5);
}));
say("every underline has a width and a place",
rules.every(r => parseFloat(r.style.width) > 0 && r.style.left !== ""));
say("notes and underlines sit on a layer, not in the text",
[...notes, ...rules].every(el => el.closest(".cm-content") === null)
&& !!fake.editor.querySelector(":scope > .mechcheck-inline-layer"));
say("the text itself is untouched", (() => {
const source = PROJECT["main.tex"].split("\n");
const map = C.renderedLines(fake.editor);
return [...map].every(([line, el]) => el.textContent === source[line - 1]);
})());
// The span is a guess, so it has to be a checkable one.
say("a quoted literal is found in the line",
JSON.stringify(C.spanFor({message: "repeated word `is is`", col: 10},
"the word is is repeated")) === JSON.stringify([9, 14]));
say("the reported column picks which occurrence",
JSON.stringify(C.spanFor({message: "repeated word `is is`", col: 12},
"is is and is is")) === JSON.stringify([10, 15]));
say("a literal that is not on the line underlines nothing",
C.spanFor({message: "missing `\\Description`"}, "a line without it") === null);
say("with no quote it underlines the word at the column",
JSON.stringify(C.spanFor({message: "no quote here", col: 7}, "abcde fghij k"))
=== JSON.stringify([6, 11]));
say("a column landing on a space underlines nothing",
C.spanFor({message: "no quote here", col: 6}, "abcde fghij k") === null);
say("a column past the end of the line underlines nothing",
C.spanFor({message: "no quote here", col: 99}, "short") === null);
say("turning notes off removes every one",
C.setAnnotationsEnabled(false) === 0
&& document.querySelectorAll(".mechcheck-inline-note").length === 0);
say("turning them back on restores them", C.setAnnotationsEnabled(true) === written);
say("one redraw refreshes both kinds", (() => {
const both = C.redrawDecorations();
return both && both.marks === placed && both.notes === written;
})());
const again = C.placeMarkers(result);
say("re-placing does not duplicate marks",
document.querySelectorAll(".mechcheck-gutter-mark").length === again, String(again));
say("turning marks off removes every one",
C.setMarkersEnabled(false) === 0
&& document.querySelectorAll(".mechcheck-gutter-mark").length === 0);
say("turning them back on restores them", C.setMarkersEnabled(true) === placed);
// A line that scrolls out of view takes its mark with it; one that
// scrolls in gets a fresh one on the next pass.
fake.lineNumbers.querySelectorAll(".cm-gutterElement")[1].remove();
say("a line scrolled out of view loses its mark",
C.placeMarkers(result) <= placed);
C.clearMarkers(); C.clearAnnotations();
fake.editor.remove(); fake.tree.remove();
say("no editor means no marks and no error", C.placeMarkers(result) === 0);
say("no editor means no notes and no error", C.placeAnnotations(result) === 0);
// error path
C.renderError(new Error("Overleaf refused the download (HTTP 403)."));
say("failure is explained, not silent", shadow.querySelector(".empty").textContent.includes("403"));
// 1-click recheck UI, Fix back/recheck navigation, truncated Markdown report, and blocked relayFetch guard
say("launcher pill exposes a dedicated 1-click recheck button", !!shadow.querySelector(".recheck"));
say("panel header exposes a dedicated recheck button", !!shadow.querySelector(".recheck-head"));
C.render(result, { profile: "paper-anonymous", verify: false });
C.showFixes(result);
say("Fix view offers Back to findings and Recheck now actions",
!!shadow.querySelector(".back-findings") && !!shadow.querySelector(".recheck-after-fix"));
shadow.querySelector(".back-findings").click();
await new Promise(r => setTimeout(r, 10));
say("Back to findings restores the findings list", shadow.querySelectorAll(".finding").length > 0);
const cappedResult = {
...result,
findings: result.findings.slice(0, 1),
truncated: result.findings.slice(1, 4),
truncatedByRule: { STY001: 3 },
};
say("reportMarkdown counts held-back findings in totals",
C.reportMarkdown(cappedResult).includes("held back (3 total)"));
const seenBuild = C.handleOutputResource("/project/0123456789abcdef01234567/build/199a-new/output/output.pdf", false);
say("compile output watcher tracks new Overleaf build URLs",
seenBuild && C.discoverOutputUrls("0123456789abcdef01234567").get("output.pdf").includes("199a-new"));
} catch (err) {
log.push("FAIL harness threw — " + (err && err.stack || err));
}
const failed = log.filter(l => l.startsWith("FAIL")).length;
log.push("", `${log.filter(l => l.startsWith("ok")).length} passed, ${failed} failed`);
document.getElementById("log").textContent = log.join("\n");
window.__harnessResult = { failed, log };
})();
</script>
</body>
</html>