screw-bugs 0.1.9 → 0.1.10

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 (102) hide show
  1. package/README.md +49 -34
  2. package/dist/browser-playwright/capture.js +1 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli/app.js +6 -2
  5. package/dist/cli/commands.js +4 -3
  6. package/dist/cli/doctor.d.ts +17 -2
  7. package/dist/cli/doctor.js +62 -4
  8. package/dist/cli/mcp.js +2 -2
  9. package/dist/cli/report-server.d.ts +19 -10
  10. package/dist/cli/report-server.js +43 -18
  11. package/dist/cli/share.js +2 -2
  12. package/dist/cli/sign-in.d.ts +9 -3
  13. package/dist/cli/sign-in.js +12 -9
  14. package/dist/cli/tailnet.d.ts +57 -0
  15. package/dist/cli/tailnet.js +82 -0
  16. package/dist/core/index.d.ts +1 -14
  17. package/dist/core/index.js +3 -14
  18. package/dist/report/index.d.ts +1 -10
  19. package/dist/report/index.js +3 -10
  20. package/dist/schema/index.d.ts +1 -9
  21. package/dist/schema/index.js +3 -9
  22. package/package.json +14 -14
  23. package/dist/core/accounts.d.ts +0 -40
  24. package/dist/core/accounts.js +0 -95
  25. package/dist/core/css.d.ts +0 -95
  26. package/dist/core/css.js +0 -436
  27. package/dist/core/engine.d.ts +0 -75
  28. package/dist/core/engine.js +0 -560
  29. package/dist/core/errors.d.ts +0 -85
  30. package/dist/core/errors.js +0 -36
  31. package/dist/core/evidence.d.ts +0 -14
  32. package/dist/core/evidence.js +0 -131
  33. package/dist/core/labels.d.ts +0 -47
  34. package/dist/core/labels.js +0 -199
  35. package/dist/core/liveness.d.ts +0 -45
  36. package/dist/core/liveness.js +0 -66
  37. package/dist/core/marks.d.ts +0 -63
  38. package/dist/core/marks.js +0 -410
  39. package/dist/core/services.d.ts +0 -579
  40. package/dist/core/services.js +0 -25
  41. package/dist/core/share.d.ts +0 -68
  42. package/dist/core/share.js +0 -318
  43. package/dist/core/steps.d.ts +0 -106
  44. package/dist/core/steps.js +0 -722
  45. package/dist/core/uploads.d.ts +0 -49
  46. package/dist/core/uploads.js +0 -133
  47. package/dist/core/video.d.ts +0 -53
  48. package/dist/core/video.js +0 -241
  49. package/dist/core/viewport.d.ts +0 -28
  50. package/dist/core/viewport.js +0 -50
  51. package/dist/report/assets.d.ts +0 -34
  52. package/dist/report/assets.js +0 -105
  53. package/dist/report/bug.d.ts +0 -11
  54. package/dist/report/bug.js +0 -20
  55. package/dist/report/html.d.ts +0 -47
  56. package/dist/report/html.js +0 -923
  57. package/dist/report/icons.d.ts +0 -51
  58. package/dist/report/icons.js +0 -93
  59. package/dist/report/live.d.ts +0 -7
  60. package/dist/report/live.js +0 -135
  61. package/dist/report/logos.d.ts +0 -4
  62. package/dist/report/logos.js +0 -19
  63. package/dist/report/markup.d.ts +0 -50
  64. package/dist/report/markup.js +0 -156
  65. package/dist/report/menu-bar.d.ts +0 -60
  66. package/dist/report/menu-bar.js +0 -157
  67. package/dist/report/player.d.ts +0 -102
  68. package/dist/report/player.js +0 -315
  69. package/dist/report/pr-summary.d.ts +0 -11
  70. package/dist/report/pr-summary.js +0 -119
  71. package/dist/report/sha256.d.ts +0 -9
  72. package/dist/report/sha256.js +0 -97
  73. package/dist/report/share-page.d.ts +0 -48
  74. package/dist/report/share-page.js +0 -291
  75. package/dist/report/shots.d.ts +0 -59
  76. package/dist/report/shots.js +0 -280
  77. package/dist/report/sign-in.d.ts +0 -41
  78. package/dist/report/sign-in.js +0 -568
  79. package/dist/report/styles.d.ts +0 -3
  80. package/dist/report/styles.js +0 -274
  81. package/dist/report/view.d.ts +0 -296
  82. package/dist/report/view.js +0 -702
  83. package/dist/report/walkthrough.d.ts +0 -93
  84. package/dist/report/walkthrough.js +0 -716
  85. package/dist/schema/accounts.d.ts +0 -137
  86. package/dist/schema/accounts.js +0 -121
  87. package/dist/schema/config.d.ts +0 -7
  88. package/dist/schema/config.js +0 -6
  89. package/dist/schema/doctor.d.ts +0 -46
  90. package/dist/schema/doctor.js +0 -30
  91. package/dist/schema/evidence.d.ts +0 -1115
  92. package/dist/schema/evidence.js +0 -565
  93. package/dist/schema/findings.d.ts +0 -161
  94. package/dist/schema/findings.js +0 -82
  95. package/dist/schema/job.d.ts +0 -1905
  96. package/dist/schema/job.js +0 -577
  97. package/dist/schema/ledger.d.ts +0 -1124
  98. package/dist/schema/ledger.js +0 -285
  99. package/dist/schema/share.d.ts +0 -55
  100. package/dist/schema/share.js +0 -64
  101. package/dist/schema/status.d.ts +0 -7
  102. package/dist/schema/status.js +0 -11
@@ -1,560 +0,0 @@
1
- import { Cause, Clock, Context, DateTime, Effect, Fiber, Layer, Schema, Semaphore } from 'effect';
2
- import { accountLabel, annotatedFile, casesOf, Findings, findingsRevision, reportBundleOf, runFiles, ShotPage, videoFile, } from '../schema/index.js';
3
- import { FindingsRejected, NotImplemented, RunNotEnded, SignInNeeded, StorageFailed, } from './errors.js';
4
- import { aboutOf, needsSignIn, originOf } from './accounts.js';
5
- import { checkFindings, evidencePackOf } from './evidence.js';
6
- import { AppVersion, HEARTBEAT_INTERVAL_MS, markUnreached, ProcessId, RUN_INTERRUPTED, } from './liveness.js';
7
- import { elementBoxes } from './labels.js';
8
- import { placeMarks } from './marks.js';
9
- import { pageUnplaced } from './viewport.js';
10
- import { AccountBook, Browser, Notifier, ReportRenderer, Storage, } from './services.js';
11
- import { runCase } from './steps.js';
12
- import { stillWithin, VIDEO_HEAD_BYTES, videoProblemOf, webmDurationMs } from './video.js';
13
- const messageOf = (error) => error instanceof Error ? error.message : String(error);
14
- /**
15
- * The longest one write of `report.html` or `ledger.json` may take. A run's
16
- * writes are uninterruptible, so its final state is never half recorded; this bound keeps a hung
17
- * disk from holding up the first Ctrl+C forever. A write that times out never leaves a half-written
18
- * file: storage writes a temporary file, then renames it.
19
- */
20
- export const WRITE_TIMEOUT_MS = 5_000;
21
- /**
22
- * How many times a report is rendered at most when what it is made from keeps changing as it is
23
- * written (see `renderReport`).
24
- */
25
- export const REPORT_ATTEMPTS = 3;
26
- /** `write`, failing with StorageFailed if it takes longer than `WRITE_TIMEOUT_MS`. */
27
- const bounded = (what, write) => write.pipe(Effect.timeoutOrElse({
28
- duration: WRITE_TIMEOUT_MS,
29
- orElse: () => Effect.fail(new StorageFailed({
30
- message: `Writing ${what} took longer than ${WRITE_TIMEOUT_MS / 1000} s.`,
31
- })),
32
- }));
33
- /** Executes runs. The CLI and the MCP server are thin callers of this. */
34
- export class Engine extends Context.Service()('screw-bugs/Engine') {
35
- static layer = Layer.effect(Engine, Effect.gen(function* () {
36
- const browser = yield* Browser;
37
- const storage = yield* Storage;
38
- const accounts = yield* AccountBook;
39
- const notifier = yield* Notifier;
40
- const renderer = yield* ReportRenderer;
41
- const pid = yield* ProcessId;
42
- const version = yield* AppVersion;
43
- // Runs live as long as the engine: one command, or the whole MCP server process.
44
- const scope = yield* Effect.scope;
45
- const running = new Map();
46
- const now = DateTime.now.pipe(Effect.map(DateTime.formatIso));
47
- /** Every ledger write says which process wrote it and that it was alive just now. */
48
- const stamped = (ledger) => now.pipe(Effect.map((heartbeatAt) => ({
49
- ...ledger,
50
- heartbeatAt,
51
- ...(pid !== undefined ? { pid } : {}),
52
- })));
53
- const decodeFindings = Schema.decodeUnknownEffect(Schema.fromJsonString(Findings));
54
- const decodePage = Schema.decodeUnknownEffect(Schema.fromJsonString(ShotPage));
55
- /** Only the URL of a saved page state: the rest is not decoded for it. */
56
- const decodePageUrl = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Struct({ url: ShotPage.fields.url })));
57
- /**
58
- * The saved findings of a run and their revision (`findingsRevision`); a damaged file reads
59
- * as none, so the report still renders.
60
- */
61
- const findingsOf = (jobId) => Effect.gen(function* () {
62
- const text = yield* storage.readFile(jobId, runFiles.findings);
63
- if (text === undefined)
64
- return undefined;
65
- const findings = yield* decodeFindings(text).pipe(Effect.orElseSucceed(() => undefined));
66
- return findings === undefined
67
- ? undefined
68
- : { findings, revision: findingsRevision(text) };
69
- });
70
- const shotsOf = (ledger) => new Map(ledger.cases.flatMap((c) => (c.shots ?? []).map((shot) => [shot.id, shot])));
71
- /** The page state saved with a screenshot; a missing or damaged file reads as none. */
72
- const pageOf = (jobId, shot) => Effect.gen(function* () {
73
- if (shot.page === undefined)
74
- return undefined;
75
- const text = yield* storage.readFile(jobId, shot.page);
76
- return text === undefined
77
- ? undefined
78
- : yield* decodePage(text).pipe(Effect.orElseSucceed(() => undefined));
79
- }).pipe(Effect.orElseSucceed(() => undefined));
80
- /** Places the highlights of `findings`, reading the page state of the screenshots they use. */
81
- const marksOf = (job, ledger, findings) => Effect.gen(function* () {
82
- const shots = shotsOf(ledger);
83
- const used = new Set(findings.cases.flatMap((c) => (c.highlights ?? []).map((h) => h.shot)));
84
- const withPages = new Map();
85
- const device = job.spec.device ?? 'desktop';
86
- for (const id of used) {
87
- const shot = shots.get(id);
88
- if (shot === undefined)
89
- continue;
90
- const page = yield* pageOf(job.jobId, shot);
91
- withPages.set(id, {
92
- shot,
93
- page,
94
- unplaced: page === undefined ? undefined : pageUnplaced(page, device),
95
- });
96
- }
97
- return placeMarks(findings, withPages);
98
- });
99
- /**
100
- * The boxes of the page's elements on every screenshot that gets a box drawn (the element a
101
- * step acted on, or a placed highlight), by screenshot ID: labels keep off them.
102
- */
103
- const elementsOf = (job, ledger, marks) => Effect.gen(function* () {
104
- const elements = {};
105
- const device = job.spec.device ?? 'desktop';
106
- for (const shot of shotsOf(ledger).values()) {
107
- const boxed = (marks[shot.id] ?? []).some((m) => m.box !== undefined);
108
- if (shot.target === undefined && !boxed)
109
- continue;
110
- const page = yield* pageOf(job.jobId, shot);
111
- // Boxes that may not be where the image shows them are no use to keep labels off.
112
- if (page !== undefined && pageUnplaced(page, device) === undefined)
113
- elements[shot.id] = elementBoxes(page);
114
- }
115
- return elements;
116
- });
117
- /**
118
- * The page's URL when each screenshot was taken, by screenshot ID, from its saved page
119
- * state: the address the reports' players show. A missing or damaged file gives none.
120
- */
121
- const urlsOf = (jobId, ledger) => Effect.gen(function* () {
122
- const urls = {};
123
- for (const shot of shotsOf(ledger).values()) {
124
- if (shot.page === undefined)
125
- continue;
126
- const text = yield* storage.readFile(jobId, shot.page);
127
- if (text === undefined)
128
- continue;
129
- const page = yield* decodePageUrl(text).pipe(Effect.orElseSucceed(() => undefined));
130
- if (page !== undefined)
131
- urls[shot.id] = page.url;
132
- }
133
- return urls;
134
- }).pipe(Effect.orElseSucceed(() => ({})));
135
- /**
136
- * The report bundle: the run, plus the agent's write-up and its placed marks, if any. Only
137
- * annotated copies drawn for these very findings are in it. `inputs` names what the
138
- * write-up was made from, to tell whether it is still current.
139
- */
140
- const assemble = (job, ledger) => Effect.gen(function* () {
141
- const saved = yield* findingsOf(job.jobId);
142
- const urls = yield* urlsOf(job.jobId, ledger);
143
- if (saved === undefined) {
144
- const elements = yield* elementsOf(job, ledger, {});
145
- return { bundle: reportBundleOf(job, ledger, { elements, urls }, version), inputs: '' };
146
- }
147
- const { findings, revision } = saved;
148
- const marks = yield* marksOf(job, ledger, findings);
149
- const elements = yield* elementsOf(job, ledger, marks);
150
- const annotated = {};
151
- for (const [id, placed] of Object.entries(marks)) {
152
- if (!placed.some((m) => m.box !== undefined))
153
- continue;
154
- const file = annotatedFile(id, revision);
155
- if ((yield* storage.probe(job.jobId, file, 0)) !== undefined)
156
- annotated[id] = file;
157
- }
158
- return {
159
- bundle: reportBundleOf(job, ledger, { findings, marks, annotated, elements, urls }, version),
160
- inputs: JSON.stringify([revision, annotated]),
161
- };
162
- });
163
- /**
164
- * Writes the report. Another process may save new findings (and write its report) while this
165
- * one renders, and this write may land after that one: so once written, what the report is
166
- * made from is read again, and while it changed, the report is rendered again. The write
167
- * that lands last was checked after it landed, so it shows the findings saved by then; any
168
- * saved later are written by whoever saved them. No lock: nothing is left to clean up.
169
- */
170
- const renderReport = (job, ledger, interrupted = false) => Effect.gen(function* () {
171
- const write = (own) => {
172
- // The walkthrough goes first, so the report links it only once it is there; a
173
- // walkthrough that could not be written leaves the report without the link.
174
- if (!interrupted)
175
- return writeWalkthroughOf(job, own).pipe(Effect.as({
176
- ...own,
177
- files: { ...own.files, walkthrough: runFiles.walkthrough },
178
- }), Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.succeed(own)), Effect.flatMap((bundle) => bounded(runFiles.html, storage.writeReport(job.jobId, renderer.html(bundle))).pipe(Effect.map((path) => ({ path, bundle })))));
179
- const bundle = { ...own, files: { ...own.files, html: runFiles.interruptedHtml } };
180
- return bounded(runFiles.interruptedHtml, storage.writeInterruptedReport(job.jobId, renderer.html(bundle))).pipe(Effect.map((path) => ({ path, bundle })));
181
- };
182
- return yield* untilCurrent(job, ledger, write);
183
- });
184
- /** Writes `walkthrough.html` from a bundle; returns its path. */
185
- const writeWalkthroughOf = (job, bundle) => Effect.sync(() => renderer.walkthrough(bundle)).pipe(Effect.flatMap((page) => bounded(runFiles.walkthrough, storage.writeFile(job.jobId, runFiles.walkthrough, page))), Effect.as(storage.filePath(job.jobId, runFiles.walkthrough)));
186
- /**
187
- * Writes with `write` what is made from the run's bundle, then reads what that is made from
188
- * again, and writes again while it changed (at most `REPORT_ATTEMPTS` times), so the write
189
- * that lands last is current. No lock: nothing is left to clean up.
190
- */
191
- const untilCurrent = (job, ledger, write) => Effect.gen(function* () {
192
- let current = yield* assemble(job, ledger);
193
- for (let attempt = 1;; attempt++) {
194
- const written = yield* write(current.bundle);
195
- const now = yield* assemble(job, ledger);
196
- if (now.inputs === current.inputs || attempt === REPORT_ATTEMPTS)
197
- return written;
198
- current = now;
199
- }
200
- });
201
- /** Writes `evidence.json`, the evidence pack an agent writes its findings from. */
202
- const writeEvidence = (job, ledger) => bounded(runFiles.evidence, storage.writeFile(job.jobId, runFiles.evidence, `${JSON.stringify(evidencePackOf(job, ledger), null, 2)}\n`));
203
- /**
204
- * Writes the report of a run that just ended, and returns the pages written with it,
205
- * relative to the run folder, for `live.html` to link. The report is derived from the ledger
206
- * and can be rewritten with `screw-bugs report`, so failing to write it never changes the
207
- * run's result: the notifier says so.
208
- */
209
- const reportOnEnd = (ledger) => storage.readJob(ledger.jobId).pipe(Effect.flatMap((job) => writeEvidence(job, ledger).pipe(Effect.andThen(renderReport(job, ledger)))), Effect.map(({ bundle }) => ({
210
- report: runFiles.html,
211
- walkthrough: bundle.files.walkthrough,
212
- })), Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause)
213
- ? Effect.failCause(cause)
214
- : notifier
215
- .notify({
216
- jobId: ledger.jobId,
217
- state: ledger.state,
218
- message: `The run ended, but report.html could not be written: ${messageOf(Cause.squash(cause)).replace(/\.$/, '')}. ` +
219
- `Run \`screw-bugs report ${ledger.jobId}\` to try again.`,
220
- })
221
- .pipe(Effect.as({}))));
222
- const device = (spec) => ({
223
- deviceLabel: browser.deviceLabel(spec.device ?? 'desktop'),
224
- });
225
- const notVerified = (spec) => casesOf(spec).map((c) => ({
226
- id: c.id,
227
- title: c.title,
228
- status: 'not_verified',
229
- evidence: [],
230
- }));
231
- /** Every case starts not verified; each is replaced by its result as soon as it ends. */
232
- const execute = (jobId, spec, uploads, savedSession) => Effect.gen(function* () {
233
- const cases = casesOf(spec);
234
- const sources = new Map(uploads.map((source) => [source.path, source]));
235
- let ledger = {
236
- jobId,
237
- state: 'running',
238
- startedAt: yield* now,
239
- cases: notVerified(spec),
240
- ...device(spec),
241
- ...(version !== undefined ? { version } : {}),
242
- };
243
- /**
244
- * Where the job is (see `RunProgress`): set as each case and step starts, and saved with
245
- * the next ledger write (the heartbeat, or the case's end), never a write of its own.
246
- */
247
- let progress;
248
- /** The ledger with the progress as it is now; only a running ledger has one. */
249
- const withProgress = (next) => {
250
- const { progress: _, ...rest } = next;
251
- return next.state === 'running' && progress !== undefined
252
- ? { ...rest, progress }
253
- : rest;
254
- };
255
- /**
256
- * Writes `live.html` from the ledger just written, with the pages its report came with
257
- * once the run ended. Only a page to watch: a failed write changes nothing else.
258
- */
259
- const writeLive = (next, pages) => bounded(runFiles.live, Effect.sync(() => renderer.live({ spec, ledger: next, ...pages })).pipe(Effect.flatMap((page) => storage.writeFile(jobId, runFiles.live, page)))).pipe(Effect.catchCause(() => Effect.void));
260
- /**
261
- * One write at a time, each finished even when interrupted (but bounded, see
262
- * `WRITE_TIMEOUT_MS`), so a heartbeat never lands over a newer ledger such as the final one.
263
- * Once a ledger has ended, only another final write may follow it (`stop` after a final
264
- * write that failed): a write that was waiting its turn behind it (the heartbeat) writes
265
- * nothing, as it would rewrite live.html without the report's links.
266
- */
267
- const writes = yield* Semaphore.make(1);
268
- const write = (change, ends) => writes.withPermits(1)(Effect.uninterruptible(Effect.gen(function* () {
269
- if (!ends && ledger.state !== 'running')
270
- return;
271
- const next = yield* stamped(withProgress(change(ledger)));
272
- // The report goes first, so whoever sees the run end in the ledger can open it;
273
- // then live.html, so whoever sees it running there can open that.
274
- const pages = ends ? yield* reportOnEnd(next) : {};
275
- yield* writeLive(next, pages);
276
- ledger = next;
277
- yield* bounded('ledger.json', storage.writeLedger(next));
278
- })));
279
- const update = (change) => write(change, false);
280
- const save = (next) => update(() => next);
281
- /** The final write: evidence.json and report.html, then the ended ledger. */
282
- const end = (next) => write(() => next, true);
283
- /** The session that is open, if one is: its number, video and when its video started. */
284
- let open;
285
- /**
286
- * The session that ended while its video is being measured, so a run interrupted then
287
- * still records it (without `still`).
288
- */
289
- let measuring;
290
- /**
291
- * Checks the video of the open session once its browser is closed: it exists, is not
292
- * empty, and is about as long as the session ran (`videoProblemOf`); with `measure`, also
293
- * where it stands still (`Browser.stillVideo`).
294
- */
295
- const sessionEnd = (measure) => Effect.gen(function* () {
296
- if (open === undefined)
297
- return measuring;
298
- const { number, video, startedAt } = open;
299
- open = undefined;
300
- const durationMs = Math.round((yield* Clock.currentTimeMillis) - startedAt);
301
- const file = yield* storage.probe(jobId, video, VIDEO_HEAD_BYTES);
302
- const videoDurationMs = file === undefined ? undefined : webmDurationMs(file.head);
303
- const problem = videoProblemOf(file === undefined ? undefined : { size: file.size, durationMs: videoDurationMs }, durationMs);
304
- const saved = file !== undefined && file.size > 0;
305
- const ended = {
306
- number,
307
- fields: {
308
- endedAt: yield* now,
309
- durationMs,
310
- ...(saved ? { video } : {}),
311
- ...(videoDurationMs !== undefined ? { videoDurationMs } : {}),
312
- ...(problem !== undefined ? { videoProblem: problem } : {}),
313
- },
314
- };
315
- if (!measure || !saved)
316
- return ended;
317
- // Where the video stands still, for the walkthrough's "Skip inactive".
318
- measuring = ended;
319
- const measured = yield* browser.stillVideo(storage.filePath(jobId, video));
320
- const still = measured === undefined || videoDurationMs === undefined
321
- ? measured
322
- : stillWithin(measured, videoDurationMs);
323
- measuring = undefined;
324
- return still === undefined ? ended : { number, fields: { ...ended.fields, still } };
325
- });
326
- /** The sessions of `current` with the one that just ended filled in. */
327
- const withSession = (current, ended, videoProblem) => current.sessions === undefined
328
- ? {}
329
- : {
330
- sessions: current.sessions.map((s) => s.number !== ended?.number
331
- ? s
332
- : {
333
- ...s,
334
- ...ended.fields,
335
- // The browser's own reason, such as recording not being possible, says more.
336
- ...(videoProblem !== undefined ? { videoProblem } : {}),
337
- }),
338
- };
339
- /** Ends the job early: whatever has not run stays not verified, with `reason`. */
340
- const stop = (error, reason) => Effect.gen(function* () {
341
- // An interrupted run ends at once: its video is not measured.
342
- const ended = yield* sessionEnd(error !== RUN_INTERRUPTED);
343
- yield* end({
344
- ...ledger,
345
- state: 'errored',
346
- finishedAt: yield* now,
347
- error,
348
- cases: markUnreached(ledger.cases, reason),
349
- ...withSession(ledger, ended),
350
- });
351
- yield* notifier.notify({ jobId, state: 'errored', message: error });
352
- });
353
- const runAll = Effect.scoped(Effect.gen(function* () {
354
- yield* save(ledger);
355
- // Proof of life for other processes reading the ledger; stops with this scope.
356
- yield* Effect.sleep(HEARTBEAT_INTERVAL_MS).pipe(Effect.andThen(update((current) => current)), Effect.ignore, Effect.forever, Effect.forkScoped);
357
- yield* notifier.notify({ jobId, state: 'running', message: 'Run started.' });
358
- const browserSession = yield* browser.open({
359
- headed: false,
360
- device: spec.device ?? 'desktop',
361
- });
362
- // One session: one test user in one browser, recorded as one video. Its cases run
363
- // one after another in job order and share cookies and storage.
364
- const video = videoFile(1);
365
- const session = yield* browserSession.newSession({
366
- device: spec.device ?? 'desktop',
367
- session: savedSession,
368
- video: {
369
- dir: storage.filePath(jobId, runFiles.videoDir),
370
- path: storage.filePath(jobId, video),
371
- },
372
- });
373
- open = { number: 1, video, startedAt: session.videoStartedAt };
374
- const startedAt = yield* now;
375
- const { type, channel, version } = browserSession.info;
376
- yield* update((current) => ({
377
- ...current,
378
- browser: { type, ...(channel !== undefined ? { channel } : {}), version },
379
- sessions: [
380
- {
381
- number: 1,
382
- startedAt,
383
- ...(spec.account !== undefined ? { account: accountLabel(spec.account) } : {}),
384
- },
385
- ],
386
- }));
387
- const sinceVideo = Clock.currentTimeMillis.pipe(Effect.map((ms) => ms - session.videoStartedAt));
388
- let crash;
389
- for (const [index, caseSpec] of cases.entries()) {
390
- // A case that continues goes on from the page the one before it left, whatever
391
- // that case came to; the first case of a job cannot (see `JobSpec`).
392
- const continuedFrom = caseSpec.continue === true ? cases[index - 1]?.id : undefined;
393
- progress = { case: index + 1 };
394
- yield* session.beginCase({ continues: continuedFrom !== undefined });
395
- const entry = yield* runCase(session.page, caseSpec, {
396
- continuedFrom,
397
- jobUrl: spec.url,
398
- caseNumber: index + 1,
399
- evidenceFile: (fileName) => ({
400
- path: storage.evidencePath(jobId, fileName),
401
- relative: `${runFiles.evidenceDir}/${fileName}`,
402
- }),
403
- now: sinceVideo,
404
- savePage: (fileName, page) => storage.writeFile(jobId, `${runFiles.evidenceDir}/${fileName}`, JSON.stringify(page)),
405
- uploads: (path) => sources.get(path),
406
- onStep: (step, kind) => Effect.sync(() => {
407
- progress = { case: index + 1, step, kind };
408
- }),
409
- });
410
- // Saved with this case's result: the next case, which starts now, if there is one.
411
- progress = index + 1 < cases.length ? { case: index + 2 } : undefined;
412
- yield* update((current) => ({
413
- ...current,
414
- cases: current.cases.with(index, { ...entry, session: 1 }),
415
- }));
416
- // A failed or blocked case does not stop the session; a browser that is gone does.
417
- const crashed = yield* session.crashed;
418
- if (crashed !== undefined) {
419
- crash = { caseId: caseSpec.id, message: crashed };
420
- break;
421
- }
422
- }
423
- const { videoProblem } = yield* session.close;
424
- const ended = yield* sessionEnd(true);
425
- if (crash !== undefined) {
426
- const error = `The browser stopped working during case "${crash.caseId}": ${crash.message}`;
427
- yield* end({
428
- ...ledger,
429
- state: 'errored',
430
- finishedAt: yield* now,
431
- error,
432
- cases: markUnreached(ledger.cases, `The browser stopped working during case "${crash.caseId}", so this case did not run.`),
433
- ...withSession(ledger, ended, videoProblem),
434
- });
435
- return yield* notifier.notify({ jobId, state: 'errored', message: error });
436
- }
437
- yield* end({
438
- ...ledger,
439
- state: 'finished',
440
- finishedAt: yield* now,
441
- ...withSession(ledger, ended, videoProblem),
442
- });
443
- yield* notifier.notify({ jobId, state: 'finished', message: 'Run finished.' });
444
- }));
445
- yield* runAll.pipe(Effect.catchTags({
446
- BrowserNotFound: () => stop('No browser could be launched. Run `npx screw-bugs doctor` to see what is missing.'),
447
- // The browser stopped answering, so later cases cannot run either.
448
- PageActionFailed: (e) => stop(`The browser stopped working: ${e.message}`),
449
- }), Effect.onInterrupt(() => stop(RUN_INTERRUPTED).pipe(Effect.ignore)), Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause)
450
- ? Effect.void
451
- : stop('The run hit an internal error. Please report it.').pipe(Effect.ignore)));
452
- });
453
- const status = (jobId) => storage.readLedger(jobId);
454
- /**
455
- * Draws the placed marks onto copies of their screenshots, named for the findings of
456
- * `revision`; returns the copies written.
457
- */
458
- const bake = (jobId, ledger, marks, revision) => Effect.gen(function* () {
459
- const shots = shotsOf(ledger);
460
- const jobs = [];
461
- for (const [id, placed] of Object.entries(marks)) {
462
- const shot = shots.get(id);
463
- const boxed = placed.flatMap((m, i) => m.box === undefined ? [] : [{ box: m.box, color: m.mark, label: String(i + 1) }]);
464
- if (shot === undefined || boxed.length === 0)
465
- continue;
466
- const page = yield* pageOf(jobId, shot);
467
- jobs.push({
468
- image: storage.filePath(jobId, shot.path),
469
- out: storage.filePath(jobId, annotatedFile(id, revision)),
470
- width: shot.width,
471
- height: shot.height,
472
- marks: boxed,
473
- ...(page !== undefined ? { obstacles: elementBoxes(page) } : {}),
474
- });
475
- }
476
- if (jobs.length === 0)
477
- return [];
478
- // Copies are a convenience for pull requests; without a browser there are none.
479
- return yield* browser.annotate(jobs).pipe(Effect.orElseSucceed(() => []));
480
- });
481
- /**
482
- * The session (storage state as JSON text) a job's run starts from: none without an account, else its saved
483
- * session, if that may still work (see `needsSignIn`).
484
- */
485
- const sessionFor = (spec) => Effect.gen(function* () {
486
- if (spec.account === undefined)
487
- return undefined;
488
- const label = accountLabel(spec.account);
489
- const saved = yield* accounts.find(label);
490
- const why = needsSignIn(spec.account, spec.url, saved, yield* Clock.currentTimeMillis);
491
- // The text as it was checked: the file may be replaced or removed before the run opens it.
492
- if (why === undefined && saved?.sessionText !== undefined)
493
- return saved.sessionText;
494
- return yield* new SignInNeeded({
495
- label,
496
- about: aboutOf(spec.account, saved),
497
- origin: originOf(spec.url) ?? spec.url,
498
- url: spec.url,
499
- why: why ?? { _tag: 'none' },
500
- });
501
- });
502
- return Engine.of({
503
- startRun: (spec, options) => Effect.gen(function* () {
504
- const session = yield* sessionFor(spec);
505
- const jobId = yield* storage.createRun(spec);
506
- yield* storage.writeLedger(yield* stamped({ jobId, state: 'queued', cases: notVerified(spec), ...device(spec) }));
507
- const fiber = yield* execute(jobId, spec, options?.uploads ?? [], session).pipe(Effect.ensuring(Effect.sync(() => running.delete(jobId))), Effect.forkIn(scope));
508
- running.set(jobId, fiber);
509
- return jobId;
510
- }),
511
- awaitRun: (jobId) => Effect.gen(function* () {
512
- const fiber = running.get(jobId);
513
- if (fiber)
514
- yield* Fiber.await(fiber);
515
- return yield* status(jobId);
516
- }),
517
- stopRun: (jobId) => Effect.suspend(() => {
518
- const fiber = running.get(jobId);
519
- return fiber ? Fiber.interrupt(fiber) : Effect.void;
520
- }),
521
- status,
522
- answer: () => Effect.fail(new NotImplemented({ feature: 'Answering questions' })),
523
- writeReport: (jobId, options) => Effect.gen(function* () {
524
- const job = yield* storage.readJob(jobId);
525
- return yield* renderReport(job, yield* status(jobId), options?.interrupted);
526
- }),
527
- writeWalkthrough: (jobId) => Effect.gen(function* () {
528
- const job = yield* storage.readJob(jobId);
529
- const ledger = yield* status(jobId);
530
- return yield* untilCurrent(job, ledger, (bundle) => writeWalkthroughOf(job, bundle));
531
- }),
532
- bundle: (jobId) => Effect.gen(function* () {
533
- const job = yield* storage.readJob(jobId);
534
- const { bundle } = yield* assemble(job, yield* status(jobId));
535
- // Names the walkthrough as the written report does, when the run has one: a share
536
- // built from this bundle shows it only then. Only beside the run's own report: a
537
- // walkthrough left by a run that died before writing it belongs to no report.
538
- const walkthrough = yield* storage.probe(jobId, runFiles.walkthrough, 0);
539
- const report = yield* storage.probe(jobId, runFiles.html, 0);
540
- return walkthrough === undefined || report === undefined
541
- ? bundle
542
- : { ...bundle, files: { ...bundle.files, walkthrough: runFiles.walkthrough } };
543
- }),
544
- submitFindings: (jobId, findings) => Effect.gen(function* () {
545
- const job = yield* storage.readJob(jobId);
546
- const ledger = yield* status(jobId);
547
- if (ledger.state !== 'finished' && ledger.state !== 'errored')
548
- return yield* new RunNotEnded({ jobId });
549
- const problems = checkFindings(findings, evidencePackOf(job, ledger));
550
- if (problems.length > 0)
551
- return yield* new FindingsRejected({ problems });
552
- const text = `${JSON.stringify(findings, null, 2)}\n`;
553
- yield* bounded(runFiles.findings, storage.writeFile(jobId, runFiles.findings, text));
554
- const marks = yield* marksOf(job, ledger, findings);
555
- const annotated = yield* bake(jobId, ledger, marks, findingsRevision(text));
556
- return { path: storage.filePath(jobId, runFiles.findings), marks, annotated };
557
- }),
558
- });
559
- }));
560
- }
@@ -1,85 +0,0 @@
1
- import type { SignInWhy } from '../schema/index.js';
2
- declare const NotImplemented_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
3
- readonly _tag: "NotImplemented";
4
- } & Readonly<A>;
5
- /** A planned feature that this version does not have yet. */
6
- export declare class NotImplemented extends NotImplemented_base<{
7
- readonly feature: string;
8
- }> {
9
- get message(): string;
10
- }
11
- declare const BrowserNotFound_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
12
- readonly _tag: "BrowserNotFound";
13
- } & Readonly<A>;
14
- /** None of the supported browsers could be launched. */
15
- export declare class BrowserNotFound extends BrowserNotFound_base<{
16
- readonly tried: ReadonlyArray<string>;
17
- readonly cause?: unknown;
18
- }> {
19
- }
20
- declare const RunNotFound_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
21
- readonly _tag: "RunNotFound";
22
- } & Readonly<A>;
23
- export declare class RunNotFound extends RunNotFound_base<{
24
- readonly jobId: string;
25
- }> {
26
- }
27
- declare const StorageFailed_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
28
- readonly _tag: "StorageFailed";
29
- } & Readonly<A>;
30
- /** Run files could not be read or written. */
31
- export declare class StorageFailed extends StorageFailed_base<{
32
- readonly message: string;
33
- readonly cause?: unknown;
34
- }> {
35
- }
36
- declare const PageActionFailed_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
37
- readonly _tag: "PageActionFailed";
38
- } & Readonly<A>;
39
- /**
40
- * A page action could not be carried out: no element matched, navigation failed, the page
41
- * crashed. `message` is plain language and short; it never holds DOM or browser logs.
42
- */
43
- export declare class PageActionFailed extends PageActionFailed_base<{
44
- readonly message: string;
45
- readonly cause?: unknown;
46
- /** Set when what the step acts on was not there in time: no element matched it. */
47
- readonly notFound?: boolean;
48
- }> {
49
- }
50
- declare const RunNotEnded_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
51
- readonly _tag: "RunNotEnded";
52
- } & Readonly<A>;
53
- /** A run that has not ended yet cannot take findings: its evidence is not final. */
54
- export declare class RunNotEnded extends RunNotEnded_base<{
55
- readonly jobId: string;
56
- }> {
57
- }
58
- declare const FindingsRejected_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
59
- readonly _tag: "FindingsRejected";
60
- } & Readonly<A>;
61
- /** Findings that do not fit the run: one plain line per problem, saying what to change. */
62
- export declare class FindingsRejected extends FindingsRejected_base<{
63
- readonly problems: ReadonlyArray<string>;
64
- }> {
65
- get message(): string;
66
- }
67
- declare const SignInNeeded_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
68
- readonly _tag: "SignInNeeded";
69
- } & Readonly<A>;
70
- /**
71
- * A job's account has no session a run can start from (see `needsSignIn`): nothing was started,
72
- * and a person has to sign in to it first.
73
- */
74
- export declare class SignInNeeded extends SignInNeeded_base<{
75
- readonly label: string;
76
- /** What kind of user it is: the job's `about`, else the saved one. */
77
- readonly about: string | undefined;
78
- /** The origin of the job URL, where the person signs in. */
79
- readonly origin: string;
80
- /** The job URL, where the live view opens. */
81
- readonly url: string;
82
- readonly why: SignInWhy;
83
- }> {
84
- }
85
- export {};