screw-bugs 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +906 -2
  3. package/bin/screw-bugs.js +29 -0
  4. package/dist/browser-playwright/annotate.d.ts +9 -0
  5. package/dist/browser-playwright/annotate.js +86 -0
  6. package/dist/browser-playwright/capture.d.ts +232 -0
  7. package/dist/browser-playwright/capture.js +1049 -0
  8. package/dist/browser-playwright/frames.d.ts +77 -0
  9. package/dist/browser-playwright/frames.js +191 -0
  10. package/dist/browser-playwright/index.d.ts +2 -0
  11. package/dist/browser-playwright/index.js +2 -0
  12. package/dist/browser-playwright/input.d.ts +44 -0
  13. package/dist/browser-playwright/input.js +116 -0
  14. package/dist/browser-playwright/launch.d.ts +21 -0
  15. package/dist/browser-playwright/launch.js +86 -0
  16. package/dist/browser-playwright/page.d.ts +387 -0
  17. package/dist/browser-playwright/page.js +1930 -0
  18. package/dist/build-info.json +5 -0
  19. package/dist/cli/app.d.ts +19 -0
  20. package/dist/cli/app.js +70 -0
  21. package/dist/cli/build-info.d.ts +52 -0
  22. package/dist/cli/build-info.js +82 -0
  23. package/dist/cli/commands.d.ts +14 -0
  24. package/dist/cli/commands.js +308 -0
  25. package/dist/cli/config.d.ts +16 -0
  26. package/dist/cli/config.js +71 -0
  27. package/dist/cli/doctor.d.ts +19 -0
  28. package/dist/cli/doctor.js +113 -0
  29. package/dist/cli/environment.d.ts +20 -0
  30. package/dist/cli/environment.js +34 -0
  31. package/dist/cli/exit-codes.d.ts +29 -0
  32. package/dist/cli/exit-codes.js +28 -0
  33. package/dist/cli/failure.d.ts +20 -0
  34. package/dist/cli/failure.js +15 -0
  35. package/dist/cli/index.d.ts +6 -0
  36. package/dist/cli/index.js +6 -0
  37. package/dist/cli/install-method.d.ts +96 -0
  38. package/dist/cli/install-method.js +148 -0
  39. package/dist/cli/main.d.ts +1 -0
  40. package/dist/cli/main.js +10 -0
  41. package/dist/cli/mcp.d.ts +30 -0
  42. package/dist/cli/mcp.js +309 -0
  43. package/dist/cli/node-version.d.ts +3 -0
  44. package/dist/cli/node-version.js +22 -0
  45. package/dist/cli/operations.d.ts +127 -0
  46. package/dist/cli/operations.js +337 -0
  47. package/dist/cli/package-info.d.ts +22 -0
  48. package/dist/cli/package-info.js +25 -0
  49. package/dist/cli/report-server.d.ts +170 -0
  50. package/dist/cli/report-server.js +387 -0
  51. package/dist/cli/signals.d.ts +37 -0
  52. package/dist/cli/signals.js +61 -0
  53. package/dist/cli/stamp-build.d.ts +1 -0
  54. package/dist/cli/stamp-build.js +9 -0
  55. package/dist/cli/update-check.d.ts +140 -0
  56. package/dist/cli/update-check.js +316 -0
  57. package/dist/cli/uploads.d.ts +16 -0
  58. package/dist/cli/uploads.js +80 -0
  59. package/dist/core/css.d.ts +95 -0
  60. package/dist/core/css.js +436 -0
  61. package/dist/core/engine.d.ts +65 -0
  62. package/dist/core/engine.js +436 -0
  63. package/dist/core/errors.d.ts +66 -0
  64. package/dist/core/errors.js +30 -0
  65. package/dist/core/evidence.d.ts +14 -0
  66. package/dist/core/evidence.js +127 -0
  67. package/dist/core/index.d.ts +12 -0
  68. package/dist/core/index.js +12 -0
  69. package/dist/core/labels.d.ts +47 -0
  70. package/dist/core/labels.js +199 -0
  71. package/dist/core/liveness.d.ts +45 -0
  72. package/dist/core/liveness.js +64 -0
  73. package/dist/core/marks.d.ts +63 -0
  74. package/dist/core/marks.js +410 -0
  75. package/dist/core/services.d.ts +444 -0
  76. package/dist/core/services.js +22 -0
  77. package/dist/core/steps.d.ts +96 -0
  78. package/dist/core/steps.js +656 -0
  79. package/dist/core/uploads.d.ts +49 -0
  80. package/dist/core/uploads.js +133 -0
  81. package/dist/core/video.d.ts +16 -0
  82. package/dist/core/video.js +101 -0
  83. package/dist/core/viewport.d.ts +28 -0
  84. package/dist/core/viewport.js +50 -0
  85. package/dist/report/html.d.ts +37 -0
  86. package/dist/report/html.js +762 -0
  87. package/dist/report/index.d.ts +5 -0
  88. package/dist/report/index.js +5 -0
  89. package/dist/report/markup.d.ts +27 -0
  90. package/dist/report/markup.js +75 -0
  91. package/dist/report/pr-summary.d.ts +11 -0
  92. package/dist/report/pr-summary.js +110 -0
  93. package/dist/report/sha256.d.ts +9 -0
  94. package/dist/report/sha256.js +97 -0
  95. package/dist/report/styles.d.ts +1 -0
  96. package/dist/report/styles.js +328 -0
  97. package/dist/report/view.d.ts +141 -0
  98. package/dist/report/view.js +368 -0
  99. package/dist/report/walkthrough.d.ts +75 -0
  100. package/dist/report/walkthrough.js +458 -0
  101. package/dist/schema/config.d.ts +7 -0
  102. package/dist/schema/config.js +6 -0
  103. package/dist/schema/doctor.d.ts +46 -0
  104. package/dist/schema/doctor.js +23 -0
  105. package/dist/schema/evidence.d.ts +994 -0
  106. package/dist/schema/evidence.js +521 -0
  107. package/dist/schema/findings.d.ts +159 -0
  108. package/dist/schema/findings.js +80 -0
  109. package/dist/schema/index.d.ts +7 -0
  110. package/dist/schema/index.js +7 -0
  111. package/dist/schema/job.d.ts +1724 -0
  112. package/dist/schema/job.js +505 -0
  113. package/dist/schema/ledger.d.ts +951 -0
  114. package/dist/schema/ledger.js +193 -0
  115. package/dist/schema/status.d.ts +7 -0
  116. package/dist/schema/status.js +11 -0
  117. package/dist/store-local/accounts.d.ts +7 -0
  118. package/dist/store-local/accounts.js +9 -0
  119. package/dist/store-local/index.d.ts +3 -0
  120. package/dist/store-local/index.js +3 -0
  121. package/dist/store-local/paths.d.ts +10 -0
  122. package/dist/store-local/paths.js +17 -0
  123. package/dist/store-local/storage.d.ts +20 -0
  124. package/dist/store-local/storage.js +170 -0
  125. package/package.json +73 -4
@@ -0,0 +1,762 @@
1
+ import { Layer } from 'effect';
2
+ import { clampBox, clipBox, contentWithin, outsetBox, placeLabels, ReportRenderer, SESSION_NOTE, } from '../core/index.js';
3
+ import { isWebUrl, runFiles, } from '../schema/index.js';
4
+ import { badge, byAgent, byCode, html, icon, Markup, safeRelative, textParts, themeSwitch, } from './markup.js';
5
+ import { cspHash } from './sha256.js';
6
+ import { renderWalkthrough } from './walkthrough.js';
7
+ import { styles } from './styles.js';
8
+ import { caseViews, countsOf, CROP_NARROW as NARROW, CROP_WIDE as WIDE, cropAround, durationOf, fixesOf, formatBytes, formatTime, formatTimecode, fragmentSeconds, notTestedCount, severityLabel, statusLabel, statuses, stepParts, uploadNotes, waitNote, } from './view.js';
9
+ /**
10
+ * The page's one script, allowed by its hash in the Content Security Policy. It sets the theme
11
+ * (light, dark, or the system's) before anything is painted and keeps the choice where the browser
12
+ * allows (a page opened from disk may not); it shows the theme switch, which is hidden without
13
+ * script; it makes timecode links (and each player's "Play from" button) seek the case's video in
14
+ * place instead of opening the file; and when a screenshot or video cannot load (the page opened
15
+ * where its run folder is not, as in a viewer that shows only the HTML), it says so in its figure
16
+ * and hides the boxes drawn over it. Errors can come before it runs, so it also looks for media
17
+ * that already failed (a video has no source yet while it starts loading, so only one that has
18
+ * picked its file and has none counts). Players load nothing until played (`preload="none"`), so a
19
+ * video that was never played is never called broken, and it plays one video at a time: when one
20
+ * starts, every other that loaded anything lets go of its file. On a server without HTTP range
21
+ * requests, a video that has started holds a connection for as long as it is loaded, and a few of
22
+ * those would keep the screenshots from ever loading. Without script, the theme follows the
23
+ * system, timecodes and "Play from" still open the video at their time, and a screenshot that
24
+ * cannot load shows the same words, which lie under the image.
25
+ */
26
+ export const REPORT_SCRIPT = `(()=>{const d=document,r=d.documentElement,k='screw-bugs-theme';const set=m=>{r.dataset.theme=m;d.querySelectorAll('[data-theme-set]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.themeSet===m)))};const bad=e=>{const f=e.closest('figure');if(!f||f.classList.contains('broken'))return;f.classList.add('broken');f.querySelectorAll('.unloaded').forEach(u=>{u.hidden=false;u.removeAttribute('aria-hidden')})};const off=o=>{if(o.readyState===0&&o.networkState!==2)return;const s=o.getAttribute('src');o.pause();o.removeAttribute('src');o.load();if(s!==null)o.setAttribute('src',s);const f=o.closest('figure');if(f)f.classList.remove('started')};let m='system';try{m=localStorage.getItem(k)||m}catch(e){}r.dataset.theme=m;d.addEventListener('error',e=>{const t=e.target;if(t instanceof Element&&t.matches('figure img,figure video,figure source'))bad(t)},true);d.addEventListener('play',e=>{const v=e.target;if(!(v instanceof HTMLVideoElement))return;const f=v.closest('figure');if(f)f.classList.add('started');d.querySelectorAll('video').forEach(o=>{if(o!==v)off(o)})},true);const scan=()=>{d.querySelectorAll('figure img').forEach(i=>{if(i.complete&&i.naturalWidth===0)bad(i)});d.querySelectorAll('figure video').forEach(v=>{if(v.error||(v.networkState===3&&v.currentSrc))bad(v)})};d.addEventListener('DOMContentLoaded',()=>{set(r.dataset.theme);const t=d.getElementById('theme');if(t)t.hidden=false;scan()});addEventListener('load',scan);d.addEventListener('click',e=>{const b=e.target.closest('[data-theme-set]');if(b){set(b.dataset.themeSet);try{localStorage.setItem(k,b.dataset.themeSet)}catch(e){}return}const a=e.target.closest('a[data-v]');if(!a)return;const v=d.getElementById(a.dataset.v);if(!v||v.closest('.broken'))return;e.preventDefault();if(a.closest('figure')!==v.closest('figure'))v.scrollIntoView({block:'center',behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth'});const go=()=>{v.currentTime=Number(a.dataset.t);v.play().catch(()=>{})};if(v.readyState>0)go();else{v.addEventListener('loadedmetadata',go,{once:true});v.play().catch(()=>{})}})})();`;
27
+ /** Built outside `html` so no formatter ever adds whitespace inside: the hash is of exact text. */
28
+ const scriptTag = new Markup(`<script>${REPORT_SCRIPT}</script>`);
29
+ /**
30
+ * Nothing loads from the network. Images and video load from the run folder by relative path
31
+ * (`'self'`, and `file:` for a report opened from disk); styles are inline; the only script is
32
+ * {@link REPORT_SCRIPT}, by its hash.
33
+ */
34
+ export const REPORT_CSP = "default-src 'none'; img-src 'self' file: data:; media-src 'self' file:; " +
35
+ `style-src 'unsafe-inline'; script-src ${cspHash(REPORT_SCRIPT)}; base-uri 'none'; form-action 'none'`;
36
+ const caseAnchor = (id) => `case-${id}`;
37
+ const videoId = (entry) => `video-${entry.id}`;
38
+ /**
39
+ * A timecode: a link that opens the video at that time, which the page's script turns into a seek
40
+ * of the case's own player. The time is in the text either way.
41
+ */
42
+ const timecode = (video, entry, ms, label) => {
43
+ const href = safeRelative(video?.path);
44
+ const text = formatTimecode(ms);
45
+ if (href === undefined)
46
+ return html `<span class="tc off">${text}</span>`;
47
+ const t = fragmentSeconds(ms);
48
+ return html `<a
49
+ class="tc"
50
+ href="${`${href}#t=${t}`}"
51
+ data-v="${videoId(entry)}"
52
+ data-t="${t}"
53
+ aria-label="${`Play the video from ${text}${label ? `: ${label}` : ''}`}"
54
+ >${text}</a
55
+ >`;
56
+ };
57
+ const stepStateLabel = {
58
+ done: 'Ran',
59
+ decided: 'Decided the result',
60
+ 'not-run': 'Not run',
61
+ unknown: '',
62
+ };
63
+ /** The files an upload step sends: name, size once it ran, and what the job says each is. */
64
+ const uploadFiles = (step) => {
65
+ const files = uploadNotes(step.step, step.timing?.files);
66
+ return files.length === 0
67
+ ? ''
68
+ : html `<span class="step-files"
69
+ >${files.map((file) => html `<span class="step-file"
70
+ ><code>${file.name}</code>${file.size !== undefined
71
+ ? html ` <span class="note">${formatBytes(file.size)}</span>`
72
+ : ''}${file.note !== undefined ? html ` <span class="note">(${file.note})</span>` : ''}${file.about !== undefined ? html `: ${file.about}` : ''}</span
73
+ >`)}</span
74
+ >`;
75
+ };
76
+ const stepRow = (view, step) => {
77
+ const wait = waitNote(step.step, step.state === 'done' || step.state === 'decided');
78
+ const marker = step.state === 'decided'
79
+ ? icon(view.entry.status)
80
+ : step.state === 'done'
81
+ ? icon('done')
82
+ : icon('skipped');
83
+ return html `<li
84
+ class="step st-${step.state}${step.state === 'decided' ? ` s-${view.entry.status}` : ''}"
85
+ ${step.state === 'decided' ? html ` aria-current="step"` : ''}
86
+ >
87
+ <span class="step-n">${step.index}</span>
88
+ <span class="step-mark">${marker}</span>
89
+ <span class="step-text"
90
+ >${textParts(stepParts(step.step))}${step.implicit
91
+ ? html ` <span class="note">(added: every case starts at the job URL)</span>`
92
+ : ''}${wait !== undefined ? html ` <span class="note">(${wait})</span>` : ''}${uploadFiles(step)}</span
93
+ >
94
+ <span class="step-time"
95
+ >${step.timing ? timecode(view.video, view.entry, step.timing.startMs) : ''}</span
96
+ >
97
+ ${stepStateLabel[step.state] ? html `<span class="step-state">${stepStateLabel[step.state]}</span>` : ''}
98
+ </li>`;
99
+ };
100
+ const shotCaption = (view, shot) => {
101
+ const name = view.entry.evidenceNames?.[shot.path] ?? shot.shot?.name;
102
+ if (name !== undefined)
103
+ return name;
104
+ // Older runs have no names; their file names were `<name>.png` or `<case>-<name>.png`.
105
+ const file = shot.path.split('/').at(-1) ?? shot.path;
106
+ return file
107
+ .replace(new RegExp(`^${view.entry.id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}-`), '')
108
+ .replace(/\.png$/, '');
109
+ };
110
+ const pct = (n, of) => `${Math.round((n / of) * 1e6) / 1e4}%`;
111
+ /** A box over the part of an image a frame shows, as CSS percentages of that part. */
112
+ const boxStyle = (box, frame) => `left:${pct(box.x - frame.x, frame.width)};top:${pct(box.y - frame.y, frame.height)};` +
113
+ `width:${pct(box.width, frame.width)};height:${pct(box.height, frame.height)}`;
114
+ /*
115
+ * Sizes of what is drawn over a frame, in CSS pixels, for a frame `f` CSS pixels wide: the same
116
+ * as the styles work out with container units (`.mk`, `.mk-n`), so labels are placed where they
117
+ * will be. Lines and labels get thinner and smaller on narrow frames, down to a readable least.
118
+ */
119
+ const clamp = (least, value, most) => Math.min(most, Math.max(least, value));
120
+ /** How far a box's line and its rings reach outside the element: gap, line, outer rings. */
121
+ const reach = (f) => clamp(1, 0.0025 * f, 2) + clamp(1.5, 0.004 * f, 3) + 2;
122
+ /** A label: bold text with its padding and ring. */
123
+ const labelSize = (text, f) => {
124
+ const font = clamp(10, 0.02 * f, 12);
125
+ return { width: text.length * 0.62 * font + font + 3, height: font * 1.4 + 5 };
126
+ };
127
+ /** How far a label sits from the outer ring of its box. */
128
+ const LABEL_GAP = 4;
129
+ /**
130
+ * The sides of `box` that are cut by the frame (`cut-*`: the element goes on past it, so its line
131
+ * there is not shown) or, where the frame shows it whole, on the edge of the image (`fl-*`: no
132
+ * room outside, so its line there is drawn inside). A side the frame cuts is never drawn, even
133
+ * when the element reaches the image's edge further on: a line there would cover what is marked
134
+ * and say the element ends where it does not. Labels line up with the frame's edge on either.
135
+ */
136
+ const edgeSides = (box, frame, width, height) => {
137
+ const side = (name, pastFrame, atImage) => pastFrame ? ` cut-${name}` : atImage ? ` fl-${name}` : '';
138
+ const [right, bottom] = [box.x + box.width, box.y + box.height];
139
+ return [
140
+ side('l', box.x < frame.x - 0.5, box.x <= 0.5),
141
+ side('t', box.y < frame.y - 0.5, box.y <= 0.5),
142
+ side('r', right > frame.x + frame.width + 0.5, right >= width - 0.5),
143
+ side('b', bottom > frame.y + frame.height + 0.5, bottom >= height - 0.5),
144
+ ].join('');
145
+ };
146
+ /**
147
+ * The boxes over the part of an image a frame shows (`frame`, in image pixels): each over its
148
+ * element, with its line drawn outside it, and its label outside that, clear of the other boxes
149
+ * and off the page's other `elements` where it can be. Labels are placed for the narrowest the
150
+ * frame is shown (`minWidth` CSS pixels), where they take most of the image.
151
+ */
152
+ const overlays = (items, frame, size, minWidth, elements) => {
153
+ const scale = frame.width / minWidth;
154
+ const inFrame = (box) => {
155
+ const part = clipBox(box, frame);
156
+ return { ...part, x: part.x - frame.x, y: part.y - frame.y };
157
+ };
158
+ const boxes = items.map((item) => clipBox(item.box, frame));
159
+ const places = placeLabels(frame, items.map((item) => {
160
+ const label = labelSize(item.label, minWidth);
161
+ return {
162
+ box: inFrame(outsetBox(item.box, reach(minWidth) * scale)),
163
+ label: { width: label.width * scale, height: label.height * scale },
164
+ // The step's label goes below its element when it can: a step acts mostly on fields and
165
+ // buttons, with their own labels above; and it keeps clear of the agent's numbers above.
166
+ prefer: item.kind === 'step' ? 'below' : 'above',
167
+ };
168
+ }), LABEL_GAP * scale, elements.map(inFrame).filter((box) => box.width > 0 && box.height > 0));
169
+ return items.map((item, i) => {
170
+ const { spot, shift } = places[i];
171
+ // A shift is in image pixels; labels have a CSS size, so it goes back to CSS pixels.
172
+ return html `<span
173
+ class="${`mk mk-${item.kind}${edgeSides(item.box, frame, size.width, size.height)}`}"
174
+ style="${boxStyle(boxes[i], frame)}"
175
+ ><span
176
+ class="mk-n at-${spot}"
177
+ ${shift > 0 ? html ` style="${`margin-left:${Math.round(shift / scale)}px`}"` : ''}
178
+ >${item.label}</span
179
+ ></span
180
+ >`;
181
+ });
182
+ };
183
+ /** The image in a frame that shows only `frame`'s part of it, scaled up to fill the frame. */
184
+ const zoomedStyle = (frame, imageWidth) => `width:${pct(imageWidth, frame.width)};left:${pct(-frame.x, frame.width)};top:${pct(-frame.y, frame.height)}`;
185
+ const markWord = { red: 'Problem', green: 'As expected' };
186
+ /** Where to open a report whose screenshots or video cannot load. */
187
+ const OPEN_FROM_RUN_FOLDER = 'Open this report from its run folder in a browser';
188
+ /**
189
+ * What a screenshot's frame says when its image cannot load. It lies under the image, so without
190
+ * script it shows only then; the page's script also hides the boxes drawn over the frame and lets
191
+ * assistive technology read it.
192
+ */
193
+ const unloadedShot = (href) => html `<span class="unloaded" aria-hidden="true"
194
+ ><strong>Screenshot didn't load:</strong> <code>${href}</code>. ${OPEN_FROM_RUN_FOLDER}.</span
195
+ >`;
196
+ const sameCrop = (a, b) => a === b ||
197
+ (a !== undefined &&
198
+ b !== undefined &&
199
+ a.x === b.x &&
200
+ a.y === b.y &&
201
+ a.width === b.width &&
202
+ a.height === b.height);
203
+ /**
204
+ * The frames a screenshot is shown in: zoomed in on its boxes (whole when it has none, or they
205
+ * take most of it), with the boxes drawn over the untouched image, linking to `link`. One frame,
206
+ * or one for wide and one for narrow figures when their crops differ.
207
+ */
208
+ const framesOf = (options) => {
209
+ const { src, link, external, size, items, elements, alt } = options;
210
+ const boxes = items.map((item) => ({ ...item.box, content: item.content }));
211
+ const [wide, narrow] = size
212
+ ? [WIDE, NARROW].map((crop) => cropAround(size.width, size.height, boxes, crop))
213
+ : [undefined, undefined];
214
+ const variants = sameCrop(wide, narrow)
215
+ ? [{ crop: wide, variant: '', min: NARROW.frame }]
216
+ : [
217
+ { crop: wide, variant: ' v-wide', min: WIDE.frame },
218
+ { crop: narrow, variant: ' v-narrow', min: NARROW.frame },
219
+ ];
220
+ const frames = variants.map(({ crop, variant, min }) => {
221
+ const frame = crop ?? (size ? { x: 0, y: 0, width: size.width, height: size.height } : undefined);
222
+ return html `<a
223
+ class="${`frame${crop ? ' zoom' : ''}${variant}`}"
224
+ href="${link}"
225
+ ${external ? html ` target="_blank" rel="noopener"` : ''}
226
+ ${frame ? html ` style="${`aspect-ratio:${frame.width} / ${frame.height}`}"` : ''}
227
+ >${unloadedShot(src)}<img
228
+ src="${src}"
229
+ alt="${alt(crop !== undefined)}"
230
+ loading="lazy"
231
+ ${crop && size ? html ` style="${zoomedStyle(crop, size.width)}"` : ''}
232
+ />${size && frame ? overlays(items, frame, size, min, elements) : ''}</a
233
+ >`;
234
+ });
235
+ /** The note that a frame is zoomed in, for each frame that is. */
236
+ const zoomed = variants
237
+ .filter(({ crop }) => crop !== undefined)
238
+ .map(({ variant }) => html ` <span class="${`zoomed${variant}`}">(zoomed in; opens whole)</span>`);
239
+ return { frames, zoomed };
240
+ };
241
+ /**
242
+ * A screenshot with its marks drawn over the untouched image: the agent's numbered red and green
243
+ * highlights, and (dashed) the element the step acted on. A screenshot with marks zooms in on
244
+ * them; the image file is the same, and opens whole. A checkbox shows and hides the marks, with
245
+ * no script. Below it, what each mark is, including the ones that could not be placed.
246
+ */
247
+ const shotFigure = (view, shot, prominent) => {
248
+ const href = safeRelative(shot.path);
249
+ const caption = prominent ? 'The page when the case stopped' : shotCaption(view, shot);
250
+ if (href === undefined)
251
+ return html `<figure class="shot missing">
252
+ <figcaption>${caption}: ${shot.path} (not shown)</figcaption>
253
+ </figure>`;
254
+ const record = shot.shot;
255
+ const size = record && record.width > 0 && record.height > 0 ? record : undefined;
256
+ const measured = size && record?.target;
257
+ // Older runs could record a box off the image; it is said in words instead of drawn.
258
+ const targetBox = measured && clampBox(measured, size.width, size.height) !== undefined ? measured : undefined;
259
+ const targetProblem = targetBox === undefined
260
+ ? (record?.targetProblem ??
261
+ (measured ? 'the element was outside this screenshot' : undefined))
262
+ : undefined;
263
+ const placed = shot.marks.map((mark, i) => ({ mark, n: i + 1 }));
264
+ const drawn = size ? placed.filter(({ mark }) => mark.box !== undefined) : [];
265
+ const toggleId = `marks-${record?.id ?? href.replace(/[^A-Za-z0-9]/g, '-')}`;
266
+ const hasMarks = drawn.length > 0 || targetBox !== undefined;
267
+ const items = [
268
+ ...drawn.map(({ mark, n }) => ({
269
+ kind: mark.mark,
270
+ box: mark.box,
271
+ content: mark.content,
272
+ label: String(n),
273
+ })),
274
+ ...(targetBox
275
+ ? [
276
+ {
277
+ kind: 'step',
278
+ box: targetBox,
279
+ content: contentWithin(record?.targetContent, targetBox),
280
+ label: `Step ${record?.step}`,
281
+ },
282
+ ]
283
+ : []),
284
+ ];
285
+ const on = drawn.length > 0
286
+ ? `its ${drawn.length === 1 ? 'marked element' : 'marked elements'}`
287
+ : `the element step ${record?.step} acted on`;
288
+ const { frames, zoomed } = framesOf({
289
+ src: href,
290
+ link: href,
291
+ external: true,
292
+ size,
293
+ items,
294
+ elements: shot.elements,
295
+ alt: (zoom) => `Screenshot: ${caption}${zoom ? `, zoomed in on ${on}` : ''}${drawn.length > 0 ? `, with ${drawn.length} marked ${drawn.length === 1 ? 'element' : 'elements'}` : ''}`,
296
+ });
297
+ return html `<figure
298
+ class="shot${prominent ? ' prominent' : ''}${shot.marks.length > 0 ? ' marked' : ''}"
299
+ >
300
+ ${hasMarks ? html `<input type="checkbox" class="mk-toggle" id="${toggleId}" checked />` : ''}
301
+ ${frames}
302
+ <figcaption>
303
+ <span class="cap">
304
+ <span>${caption}</span>
305
+ ${record ? html `<span class="shot-id">${record.id}</span>` : ''}
306
+ ${record?.atMs !== undefined ? timecode(view.video, view.entry, record.atMs) : ''}
307
+ ${hasMarks ? html `<label class="mk-switch" for="${toggleId}">Marks</label>` : ''}
308
+ </span>
309
+ <span class="file"
310
+ ><a href="${href}" target="_blank" rel="noopener">${href}</a>${zoomed}</span
311
+ >
312
+ </figcaption>
313
+ ${placed.length > 0 || targetBox || targetProblem
314
+ ? html `<ol class="mk-legend">
315
+ ${targetBox ? html `<li class="lg-step" value="0"><span class="key"></span>Step ${record?.step} acted on this element <span class="note">(code)</span></li>` : ''}
316
+ ${targetProblem ? html `<li class="lg-step unplaced" value="0"><span class="key"></span>Step ${record?.step} acted on an element not drawn here <span class="note">(code; not drawn: ${targetProblem})</span></li>` : ''}
317
+ ${placed.map(({ mark, n }) => markLegend(mark, n))}
318
+ </ol>`
319
+ : ''}
320
+ </figure>`;
321
+ };
322
+ const markLegend = (mark, n) => html `<li class="lg-${mark.mark}${mark.box ? '' : ' unplaced'}" value="${n}">
323
+ <span class="key">${n}</span>
324
+ <span
325
+ ><strong>${markWord[mark.mark]}</strong>${mark.note ? html `: ${mark.note}` : ''}
326
+ <span class="note"
327
+ >(${mark.target}${mark.box
328
+ ? mark.ignored
329
+ ? `; ${mark.ignored}`
330
+ : ''
331
+ : html `; not drawn: ${mark.problem ?? 'not found'}`})</span
332
+ ></span
333
+ >
334
+ </li>`;
335
+ const list = (items) => items && items.length > 0
336
+ ? html `<ul>
337
+ ${items.map((item) => html `<li>${item}</li>`)}
338
+ </ul>`
339
+ : html `<p class="note">Nothing noted.</p>`;
340
+ /** The agent's did / worked / didn't, key moments and unchecked observations for one case. */
341
+ const caseWriteUp = (view) => {
342
+ const written = view.findings;
343
+ if (written === undefined)
344
+ return '';
345
+ const moments = written.keyMoments ?? [];
346
+ const observed = written.observed ?? [];
347
+ return html `<div class="agent writeup">
348
+ <p class="agent-head">${byAgent}</p>
349
+ <div class="outcome">
350
+ <div class="did">
351
+ <h4>What we did</h4>
352
+ ${list(written.did)}
353
+ </div>
354
+ <div>
355
+ <h4 class="ok">What worked</h4>
356
+ ${list(written.worked)}
357
+ </div>
358
+ <div>
359
+ <h4 class="bad">What didn't</h4>
360
+ ${list(written.didnt)}
361
+ </div>
362
+ </div>
363
+ ${moments.length > 0
364
+ ? html `<h4>Key moments</h4>
365
+ <ol class="moments">
366
+ ${moments
367
+ .toSorted((a, b) => a.ms - b.ms)
368
+ .map((m) => html `<li>
369
+ ${timecode(view.video, view.entry, m.ms, m.label)}<span>${m.label}</span>
370
+ </li>`)}
371
+ </ol>`
372
+ : ''}
373
+ ${observed.length > 0
374
+ ? html `<div class="observed">
375
+ <h4>Observed, not checked by a step</h4>
376
+ <ul>
377
+ ${observed.map((o) => html `<li>${o}</li>`)}
378
+ </ul>
379
+ </div>`
380
+ : ''}
381
+ </div>`;
382
+ };
383
+ const videoBlock = (view) => {
384
+ const { video, entry } = view;
385
+ if (video === undefined)
386
+ return '';
387
+ const href = safeRelative(video.path);
388
+ const start = entry.startMs ?? 0;
389
+ const problem = video.problem
390
+ ? html `<p class="video-problem" role="note">
391
+ <strong>Video missing or incomplete.</strong> ${video.problem}
392
+ </p>`
393
+ : '';
394
+ if (href === undefined)
395
+ return problem;
396
+ const from = fragmentSeconds(start);
397
+ return html `<figure class="player">
398
+ <div class="screen">
399
+ <video
400
+ id="${videoId(entry)}"
401
+ controls
402
+ preload="none"
403
+ playsinline
404
+ src="${`${href}#t=${from}`}"
405
+ ></video>
406
+ <a
407
+ class="play"
408
+ href="${`${href}#t=${from}`}"
409
+ data-v="${videoId(entry)}"
410
+ data-t="${from}"
411
+ aria-label="${`Play the video from ${formatTimecode(start)}, where this case starts`}"
412
+ >${icon('play')}<span>Play from <strong>${formatTimecode(start)}</strong></span></a
413
+ >
414
+ </div>
415
+ <p class="unloaded" hidden>
416
+ <strong>Video didn't load:</strong> <a href="${href}">${href}</a>. ${OPEN_FROM_RUN_FOLDER}, or
417
+ open the file directly.
418
+ </p>
419
+ <figcaption class="filebar">
420
+ <span
421
+ >Session ${video.session.number} video, from
422
+ ${timecode(video, entry, start)}${entry.endMs !== undefined ? html ` to ${formatTimecode(entry.endMs)}` : ''}</span
423
+ >
424
+ <a class="file" href="${href}">${href}</a>
425
+ </figcaption>
426
+ ${problem}
427
+ </figure>`;
428
+ };
429
+ const caseSection = (view, position) => {
430
+ const { entry } = view;
431
+ const open = entry.status !== 'passed';
432
+ const steps = html `<ol class="steps">
433
+ ${view.steps.map((step) => stepRow(view, step))}
434
+ </ol>`;
435
+ const success = view.spec?.success?.trim();
436
+ const continued = entry.continuedFrom === undefined
437
+ ? ''
438
+ : html `<p class="continued">
439
+ <span class="label">Continued</span> from case
440
+ <a href="#${caseAnchor(entry.continuedFrom)}"><code>${entry.continuedFrom}</code></a
441
+ >, on the page it ended on
442
+ </p>`;
443
+ return html `<section
444
+ class="case s-${entry.status}"
445
+ id="${caseAnchor(entry.id)}"
446
+ aria-labelledby="${`${caseAnchor(entry.id)}-title`}"
447
+ >
448
+ <header class="case-head">
449
+ <span class="case-n">${String(position).padStart(2, '0')}</span>
450
+ <h3 id="${`${caseAnchor(entry.id)}-title`}">${entry.title}</h3>
451
+ ${badge(entry.status)}
452
+ </header>
453
+ <p class="case-id">
454
+ <code>${entry.id}</code
455
+ >${view.spec ? '' : html ` · <span class="note">no steps recorded for this case</span>`}
456
+ </p>
457
+ ${continued}${success ? html `<p class="success"><span class="label">Success looks like</span> ${success}</p>` : ''}
458
+ ${entry.reason ? html `<p class="reason">${entry.reason}</p>` : ''} ${videoBlock(view)}
459
+ ${caseWriteUp(view)} ${view.failureShot ? shotFigure(view, view.failureShot, true) : ''}
460
+ ${view.otherShots.length > 0
461
+ ? html `<h4 class="label">Screenshots</h4>
462
+ <div class="shots">
463
+ ${view.otherShots.map((shot) => shotFigure(view, shot, false))}
464
+ </div>`
465
+ : ''}
466
+ ${view.steps.length === 0
467
+ ? ''
468
+ : open
469
+ ? html `<h4 class="label">Steps ${byCode}</h4>
470
+ ${steps}`
471
+ : html `<details class="steps-toggle">
472
+ <summary>
473
+ ${view.steps.length} ${view.steps.length === 1 ? 'step' : 'steps'}, all ran
474
+ </summary>
475
+ ${steps}
476
+ </details>`}
477
+ </section>`;
478
+ };
479
+ /**
480
+ * The counts in a sentence. With areas the agent did not test, a run whose cases all passed says
481
+ * `7 of 7 cases passed · 3 areas not tested`, never that all passed.
482
+ */
483
+ const verdict = (bundle) => {
484
+ const { cases, state } = bundle.ledger;
485
+ const passed = cases.filter((c) => c.status === 'passed').length;
486
+ if (state !== 'finished' && state !== 'errored')
487
+ return `In progress: ${passed} of ${cases.length} passed so far`;
488
+ const gaps = notTestedCount(bundle);
489
+ if (state === 'finished' && passed === cases.length && gaps === undefined)
490
+ return cases.length === 1 ? 'The case passed' : `All ${cases.length} cases passed`;
491
+ return `${passed} of ${cases.length} ${cases.length === 1 ? 'case' : 'cases'} passed${gaps ? ` · ${gaps}` : ''}`;
492
+ };
493
+ /** What the agent did not test and why, by the counts, so a green run is not read as complete. */
494
+ const notTestedBlock = (bundle) => {
495
+ const items = bundle.findings?.notTested ?? [];
496
+ if (items.length === 0)
497
+ return '';
498
+ return html `<section class="not-tested" id="not-tested" aria-labelledby="not-tested-title">
499
+ <h2 id="not-tested-title">Not tested ${byAgent}</h2>
500
+ <ul>
501
+ ${items.map((item) => html `<li><strong>${item.what}</strong> <span class="why">${item.why}</span></li>`)}
502
+ </ul>
503
+ </section>`;
504
+ };
505
+ /** The counts and one row per case, all decided by code. */
506
+ const results = (bundle, views) => {
507
+ const counts = countsOf(bundle.ledger.cases);
508
+ const total = bundle.ledger.cases.length;
509
+ const bar = statuses
510
+ .filter((s) => counts[s] > 0)
511
+ .map((s) => html `<span class="seg s-${s}" style="${`flex-grow:${counts[s]}`}"></span>`);
512
+ return html `<div class="results" aria-labelledby="results-title">
513
+ <h2 id="results-title" class="label">Results</h2>
514
+ <div class="tiles">
515
+ ${statuses.map((s) => html `<div class="tile s-${s}${counts[s] === 0 ? ' zero' : ''}">
516
+ <span class="tile-count">${counts[s]}</span>
517
+ <span class="tile-label">${icon(s)}${statusLabel[s]}</span>
518
+ </div>`)}
519
+ </div>
520
+ ${total > 0 ? html `<div class="bar" aria-hidden="true">${bar}</div>` : ''}
521
+ <ol class="index">
522
+ ${views.map((view, i) => html `<li class="s-${view.entry.status}">
523
+ <a href="${`#${caseAnchor(view.entry.id)}`}"
524
+ ><span class="case-n">${String(i + 1).padStart(2, '0')}</span
525
+ ><span class="index-title">${view.entry.title}</span>${badge(view.entry.status)}</a
526
+ >
527
+ </li>`)}
528
+ </ol>
529
+ </div>`;
530
+ };
531
+ /** A crop of a screenshot around its drawn marks, for a fix; it links to the case. */
532
+ const cropFigure = (view, shot) => {
533
+ const record = shot.shot;
534
+ const href = safeRelative(shot.path);
535
+ const placed = shot.marks.map((mark, i) => ({ mark, n: i + 1 })).filter((p) => p.mark.box);
536
+ if (!record || href === undefined || placed.length === 0)
537
+ return '';
538
+ const { frames } = framesOf({
539
+ src: href,
540
+ link: `#${caseAnchor(view.entry.id)}`,
541
+ external: false,
542
+ size: record.width > 0 && record.height > 0 ? record : undefined,
543
+ items: placed.map(({ mark, n }) => ({
544
+ kind: mark.mark,
545
+ box: mark.box,
546
+ content: mark.content,
547
+ label: String(n),
548
+ })),
549
+ elements: shot.elements,
550
+ alt: () => `Part of screenshot ${record.id} of case ${view.entry.id}, with marks`,
551
+ });
552
+ return html `<figure class="crop">
553
+ ${frames}
554
+ <figcaption>
555
+ ${placed.map(({ mark, n }) => html `<span class="lg-${mark.mark}"><span class="key">${n}</span>${mark.note ?? markWord[mark.mark]}</span>`)}
556
+ <span class="note">Screenshot ${record.id}, case <code>${view.entry.id}</code></span>
557
+ </figcaption>
558
+ </figure>`;
559
+ };
560
+ /** The agent's fixes, most severe first, each with its cases (and their code-decided status). */
561
+ const fixesSection = (bundle, views) => {
562
+ const fixes = fixesOf(bundle);
563
+ if (bundle.findings === undefined)
564
+ return '';
565
+ const byId = new Map(views.map((v) => [v.entry.id, v]));
566
+ return html `<section class="band agent-band" id="fix" aria-labelledby="fix-title">
567
+ <div class="band-head">
568
+ <h2 id="fix-title">What to fix</h2>
569
+ ${byAgent}
570
+ </div>
571
+ ${fixes.length === 0
572
+ ? html `<p class="note">The agent listed nothing to fix.</p>`
573
+ : html `<p class="legend">
574
+ Most severe first.
575
+ <span class="lg-red"><span class="key"></span>Red marks a problem</span>
576
+ <span class="lg-green"
577
+ ><span class="key"></span>green marks what is as expected.</span
578
+ >
579
+ </p>
580
+ <ol class="fixes">
581
+ ${fixes.map((fix, i) => {
582
+ const cases = fix.caseIds.flatMap((id) => byId.get(id) ?? []);
583
+ const shown = cases
584
+ .flatMap((view) => [view.failureShot, ...view.otherShots]
585
+ .filter((s) => s !== undefined)
586
+ .filter((s) => s.marks.some((m) => m.box))
587
+ .map((shot) => ({ view, shot })))
588
+ .toSorted((a, b) => Number(b.shot.marks.some((m) => m.mark === 'red')) -
589
+ Number(a.shot.marks.some((m) => m.mark === 'red')))[0];
590
+ return html `<li class="fix">
591
+ <div class="rail">
592
+ <span class="rank">${i + 1}</span>
593
+ <span class="sev sev-${fix.severity}">${severityLabel[fix.severity]}</span>
594
+ </div>
595
+ <div class="fix-body">
596
+ <h3>${fix.title}</h3>
597
+ <p>${fix.why}</p>
598
+ <p class="fix-cases">
599
+ ${cases.map((view) => html `<a href="${`#${caseAnchor(view.entry.id)}`}">${view.entry.title}</a>
600
+ ${badge(view.entry.status)}`)}
601
+ </p>
602
+ ${shown ? cropFigure(shown.view, shown.shot) : ''}
603
+ </div>
604
+ </li>`;
605
+ })}
606
+ </ol>`}
607
+ </section>`;
608
+ };
609
+ const metaItem = (term, value) => html `<div>
610
+ <dt>${term}</dt>
611
+ <dd>${value}</dd>
612
+ </div>`;
613
+ const videoSummary = (bundle) => {
614
+ const sessions = bundle.ledger.sessions ?? [];
615
+ if (sessions.length === 0)
616
+ return html `<span class="note">none recorded</span>`;
617
+ return sessions.map((session) => {
618
+ const href = safeRelative(session.video);
619
+ const length = session.videoDurationMs !== undefined ? ` (${formatTimecode(session.videoDurationMs)})` : '';
620
+ return html `<span class="video-line"
621
+ >${href ? html `<a href="${href}">${href}</a>${length}` : html `<span class="note">no video</span>`}${session.videoProblem || !href
622
+ ? html ` <span class="warn"
623
+ >Video missing or incomplete:
624
+ ${session.videoProblem ?? 'the video file was not saved.'}</span
625
+ >`
626
+ : ''}</span
627
+ >`;
628
+ });
629
+ };
630
+ /**
631
+ * A self-contained HTML report: inline CSS, one tiny inline script, no fonts or network.
632
+ * Screenshots and the video are linked by paths relative to the run folder, so the page works from
633
+ * disk and after the folder is zipped or moved. Code lays out every part and decides every status;
634
+ * the agent's write-up, when it submitted one, fills fixed slots and is labelled as its own.
635
+ * Every piece of text from the job, the page or the agent is escaped.
636
+ */
637
+ export const renderHtmlReport = (bundle) => {
638
+ const { spec, ledger, summary, findings } = bundle;
639
+ const views = caseViews(bundle);
640
+ const ended = ledger.state === 'finished' || ledger.state === 'errored';
641
+ const allPassed = ledger.state === 'finished' && ledger.cases.every((c) => c.status === 'passed');
642
+ const untested = notTestedCount(bundle) !== undefined;
643
+ const instructions = spec.instructions?.trim();
644
+ const duration = durationOf(bundle.startedAt, bundle.finishedAt);
645
+ const host = URL.canParse(spec.url) ? new URL(spec.url).host : spec.url;
646
+ const nextTests = findings?.nextTests ?? [];
647
+ const walkthrough = safeRelative(bundle.files.walkthrough);
648
+ const page = html `<!doctype html>
649
+ <html lang="en">
650
+ <head>
651
+ <meta charset="utf-8" />
652
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
653
+ <meta name="color-scheme" content="light dark" />
654
+ <meta http-equiv="Content-Security-Policy" content="${REPORT_CSP}" />
655
+ <title>
656
+ ${`${findings?.headline ?? verdict(bundle)} · screw-bugs report ${bundle.jobId}`}
657
+ </title>
658
+ <style>
659
+ ${new Markup(styles)}
660
+ </style>
661
+ </head>
662
+ <body>
663
+ ${scriptTag}
664
+ <div class="${`page device-${bundle.device.kind}`}">
665
+ <header class="masthead">
666
+ <span class="brand">screw-bugs <span class="brand-sub">QA report</span></span>
667
+ <span class="job"><code>${bundle.jobId}</code></span>
668
+ ${walkthrough
669
+ ? html `<a class="walkthrough-link" href="${walkthrough}"
670
+ >${icon('play')}Walkthrough</a
671
+ >`
672
+ : ''}
673
+ ${themeSwitch}
674
+ </header>
675
+
676
+ <section class="intro">
677
+ <p class="kicker">${host} · ${bundle.device.label} · ${formatTime(bundle.startedAt)}</p>
678
+ ${findings
679
+ ? html `<div class="agent headline-block">
680
+ ${byAgent}
681
+ <h1 class="headline">${findings.headline}</h1>
682
+ </div>`
683
+ : html `<h1 class="headline">${verdict(bundle)}</h1>`}
684
+ <p class="standfirst">${summary.text}</p>
685
+ ${summary.derived ? html `<p class="derived">Summarized from case titles</p>` : ''}
686
+ ${instructions
687
+ ? html `<blockquote class="asked">
688
+ <p class="label">Asked</p>
689
+ <p class="asked-text">${instructions}</p>
690
+ </blockquote>`
691
+ : ''}
692
+ <p class="verdict ${allPassed ? (untested ? 'partial' : 'good') : ended ? 'bad' : ''}">
693
+ ${byCode} ${verdict(bundle)}
694
+ </p>
695
+ ${notTestedBlock(bundle)}
696
+ ${ledger.error
697
+ ? html `<div class="alert" role="note">
698
+ <strong>The run stopped early.</strong> ${ledger.error}
699
+ </div>`
700
+ : ''}
701
+ ${results(bundle, views)}
702
+ </section>
703
+
704
+ ${fixesSection(bundle, views)}
705
+
706
+ <section class="details" aria-labelledby="details-title">
707
+ <h2 id="details-title" class="label">Run details ${byCode}</h2>
708
+ <dl class="meta">
709
+ ${metaItem('Target', isWebUrl(spec.url) ? html `<a href="${spec.url}" rel="noopener noreferrer">${spec.url}</a>` : spec.url)}
710
+ ${metaItem('Job state', html `<span class="state state-${ledger.state}">${ledger.state.replaceAll('_', ' ')}</span>`)}
711
+ ${metaItem('Device', bundle.device.label)}
712
+ ${metaItem('Started', html `<time datetime="${bundle.startedAt}">${formatTime(bundle.startedAt)}</time>`)}
713
+ ${metaItem('Finished', bundle.finishedAt
714
+ ? html `<time datetime="${bundle.finishedAt}"
715
+ >${formatTime(bundle.finishedAt)}</time
716
+ >`
717
+ : html `<span class="note">not yet</span>`)}
718
+ ${metaItem('Duration', duration ?? html `<span class="note">n/a</span>`)}
719
+ ${metaItem('Video', videoSummary(bundle))}
720
+ ${metaItem('screw-bugs', ledger.version ?? html `<span class="note">unknown</span>`)}
721
+ </dl>
722
+ ${ledger.sessions && ledger.sessions.length > 0 ? html `<p class="session-note">${SESSION_NOTE}</p>` : ''}
723
+ </section>
724
+
725
+ <section class="cases" aria-labelledby="cases-title">
726
+ <h2 id="cases-title" class="label">Cases</h2>
727
+ ${views.map((view, i) => caseSection(view, i + 1))}
728
+ </section>
729
+
730
+ ${nextTests.length > 0
731
+ ? html `<section class="band agent-band" id="next" aria-labelledby="next-title">
732
+ <div class="band-head">
733
+ <h2 id="next-title">What to test next</h2>
734
+ ${byAgent}
735
+ </div>
736
+ <ol class="next">
737
+ ${nextTests.map((t) => html `<li>${t}</li>`)}
738
+ </ol>
739
+ </section>`
740
+ : ''}
741
+
742
+ <footer class="foot">
743
+ <p>
744
+ <strong>Statuses decided by code in a real browser; write-up by the agent.</strong>
745
+ ${findings ? '' : html `The agent has not submitted a write-up for this run.`}
746
+ </p>
747
+ <p>
748
+ Raw data: <a href="${bundle.files.ledger}">${bundle.files.ledger}</a> ·
749
+ <a href="${runFiles.job}">${runFiles.job}</a> ·
750
+ <a href="${runFiles.evidence}">${runFiles.evidence}</a>${findings ? html ` · <a href="${runFiles.findings}">${runFiles.findings}</a>` : ''}
751
+ </p>
752
+ </footer>
753
+ </div>
754
+ </body>
755
+ </html> `;
756
+ return page.value;
757
+ };
758
+ /** The report module's renderer, for the engine to write a run's report. */
759
+ export const ReportRendererHtml = Layer.succeed(ReportRenderer, {
760
+ html: (bundle) => renderHtmlReport(bundle),
761
+ walkthrough: (bundle) => renderWalkthrough(bundle),
762
+ });