screw-bugs 0.1.10 → 0.1.12

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.
package/README.md CHANGED
@@ -146,7 +146,7 @@ evidence.json`). Then the paths:
146
146
 
147
147
  ```text
148
148
  Job 20261029-104857-3f9a01c2 is finished: 1 passed, 1 failed, 0 blocked, 0 not verified; watch it step by step in walkthrough.html (the URL below).
149
- - blog-link (failed): Step 2 (click link "Blog"): The page it opened returned HTTP 404.
149
+ - blog-link (failed): Clicking the "Blog" link: The page it opened returned HTTP 404.
150
150
  step 2 at 5400 ms; shots 02-01 02-02; timecodes 5000 5100 5400 6300; url http://localhost:3000/blog; http 404 http://localhost:3000/blog; text "Not found"
151
151
  - home (passed)
152
152
  shots 01-01; timecodes 0 120 4900
@@ -186,7 +186,16 @@ fixed slots with short texts:
186
186
  "title": "Show an error for a wrong password",
187
187
  "severity": "high",
188
188
  "caseIds": ["wrong-password"],
189
- "why": "Users are left on the form with no idea what happened."
189
+ "why": "Users are left on the form with no idea what happened.",
190
+ "evidence": [
191
+ { "shot": "02-02", "target": { "label": "Password" }, "mark": "red", "note": "No error" },
192
+ {
193
+ "shot": "01-03",
194
+ "target": { "role": "alert" },
195
+ "mark": "green",
196
+ "note": "Sign-up shows one"
197
+ }
198
+ ]
190
199
  }
191
200
  ],
192
201
  "cases": [
@@ -208,12 +217,16 @@ fixed slots with short texts:
208
217
  "observed": ["The button stays enabled while signing in."]
209
218
  }
210
219
  ],
211
- "notTested": [{ "what": "Password reset", "why": "The test inbox was not available." }],
220
+ "notTested": [
221
+ { "what": "Password reset", "why": "The test inbox was not available." },
222
+ { "what": "Signing out", "why": "Sign-in failed first.", "caseId": "wrong-password" }
223
+ ],
212
224
  "nextTests": ["A locked account"]
213
225
  }
214
226
  ```
215
227
 
216
- Case IDs, screenshot IDs and timecodes must be ones `run_status` gave for that case; findings that
228
+ Case IDs, screenshot IDs and timecodes must be ones `run_status` gave for that case (a fix's
229
+ `evidence` may use a screenshot of any case of the run); findings that
217
230
  do not fit are rejected with one line per problem saying what to change (exit code 6), and nothing
218
231
  is saved. A case named that does not exist is one of those problems.
219
232
 
@@ -262,9 +275,24 @@ only on what the screenshot shows: an element that was in the page or frame but
262
275
  it was taken (transparent, such as a section that had not faded in yet, or cut away by its box or
263
276
  by its frame) gets no box and says why; and when another match is on the screenshot, matches
264
277
  outside it (a copy far below a viewport screenshot, or outside the part of its frame that shows)
265
- or not visible are left out, and the legend says how many. `notTested` lists what the run did not
266
- cover and why; the report shows it next to the counts, and a run whose cases all passed then reads
267
- "7 of 7 cases passed · 3 areas not tested" rather than "All 7 cases passed". `observed` lines are
278
+ or not visible are left out, and the legend says how many. A highlight's optional `region` marks
279
+ only a part of its element, as fractions of the element's box (`{ "x": 0.4, "y": 0.6, "width":
280
+ 0.3, "height": 0.2 }`), such as a line of text inside a picture: code clips it to the box it found
281
+ and draws the part, with the whole element dashed around it; the agent still never gives
282
+ coordinates on the screenshot.
283
+
284
+ A fix's `evidence` is marks like highlights, on screenshots of any case, in the order to compare
285
+ them: give a mismatch both sides (the preview, then the page it should match). The report shows
286
+ each fix as an issue, with its evidence side by side, each screenshot zoomed in on those marks and
287
+ captioned with the mark's note and its case; every other mark on that screenshot is drawn too.
288
+ A fix without evidence shows its cases' Actual and Expected screenshots, and a failed case no fix
289
+ names gets an issue of its own. A mark that is both a case's highlight and a fix's evidence (the
290
+ same element, colour and region) is drawn once.
291
+
292
+ `notTested` lists what the run did not cover and why (and, with `caseId`, the case that did not
293
+ finish and left it out); the report shows it in the fold "What I didn't check" with the cases that
294
+ could not finish, and a run whose cases all passed then reads "7 of 7 cases passed · 3 areas not tested"
295
+ rather than "All 7 cases passed". `observed` lines are
268
296
  shown as "observed, not checked by a step". The findings go to `findings.json`; screenshots with
269
297
  highlights get a copy with the boxes drawn in, under `annotated/` (named for that write-up, so a
270
298
  copy drawn for an earlier one is never shown), and the report is written again, so it shows the
@@ -280,6 +308,7 @@ Limits (each text is one line, not blank; findings past them are rejected with w
280
308
  | `did`, `worked`, `didnt` (per case) | at most 8 lines each, 160 characters a line |
281
309
  | `failed` (per case) | 160 characters |
282
310
  | `highlights` (per case) | at most 6; `note` 120 characters |
311
+ | `evidence` (per fix) | at most 4; `note` 60 characters |
283
312
  | `keyMoments` (per case) | at most 8; `label` 80 characters |
284
313
  | `observed` (per case) | at most 5 lines, 200 characters a line |
285
314
  | `notTested` | at most 8; `what` 100 characters, `why` 160 |
@@ -334,8 +363,8 @@ Chromium: this catches responsive layout and touch problems, not Safari-only bug
334
363
 
335
364
  | Step | Fields | What it does |
336
365
  | -------------- | ------------------------------------- | --------------------------------------------------------------- |
337
- | `goto` | `url` | Open a URL; paths resolve against the job URL. HTTP 400+ fails. |
338
- | `reload` | | Reload the page; judged like `goto` |
366
+ | `goto` | `url`, `status`? | Open a URL; paths resolve against the job URL. HTTP 400+ fails. |
367
+ | `reload` | `status`? | Reload the page; judged like `goto` |
339
368
  | `click` | `target` | Click an element; a page it opens with HTTP 400+ fails |
340
369
  | `hover` | `target` | Move the pointer over an element, for controls shown on hover |
341
370
  | `fill` | `target`, `value` | Replace the value of an input |
@@ -349,6 +378,15 @@ Chromium: this catches responsive layout and touch problems, not Safari-only bug
349
378
  | `scroll` | one of `target`, `to`, `by`; `frame`? | Scroll, then screenshot the view |
350
379
  | `screenshot` | `name` | Save a full-page screenshot as evidence |
351
380
 
381
+ To test that a page is supposed to answer with an error, such as a real not-found page for an
382
+ unknown path, give `goto` or `reload` the exact HTTP status its page must answer with:
383
+ `{ "action": "goto", "url": "/reports", "status": 404 }`, then check the page as usual
384
+ (`{ "action": "expectText", "text": "Page not found" }`). That page (after redirects; not a later
385
+ load, nor one in a new tab) must then answer with exactly that status: any other fails the step,
386
+ a 200 included (a "soft 404"), such as `Opening /reports: The page returned HTTP 200, not the
387
+ expected 404.` Without `status`, any status below 400 is fine. The report shows it in the step
388
+ (`Go to /reports (expects HTTP 404)`).
389
+
352
390
  Every step that waits (all but `screenshot`) takes an optional `timeoutMs`, from 100 to 180000
353
391
  (three minutes): how long to wait for its element, text, URL, state or frame (default 5000), or
354
392
  for the page it loads (`goto`, `reload`, `press`; default 15000). A page that a `click`, `fill`, `upload` or an
@@ -403,8 +441,8 @@ second, so text that shows a moment late still counts. It passes only when every
403
441
  second read everything it had to. The reason says where it was found:
404
442
 
405
443
  ```text
406
- Step 3 (expectNoText "Acme"): "Acme" is on the page (image alt "Acme logo" in .clients).
407
- Step 4 (expectNoText "Hooli"): "Hooli" is on the page, in iframe css "iframe.preview" (image alt "Hooli").
444
+ Checking that "Acme" is not shown after opening /about: "Acme" is on the page (image alt "Acme logo" in .clients).
445
+ Checking that "Hooli" is not shown: "Hooli" is on the page, in iframe css "iframe.preview" (image alt "Hooli").
408
446
  ```
409
447
 
410
448
  A page (or frame, or target) that shows nothing at all within the wait blocks the case
@@ -501,7 +539,7 @@ name (or, for a step with `frame`, in the page itself or in another frame), the
501
539
  to change, in the form a step takes it:
502
540
 
503
541
  ```text
504
- Step 4 (expectText "Get in touch"): Not found within 5 s; it is in an iframe: add "frame":{"css":"iframe[title='Portfolio preview']"}.
542
+ Looking for "Get in touch" after clicking "Contact": Not found within 5 s; it is in an iframe: add "frame":{"css":"iframe[title='Portfolio preview']"}.
505
543
  ```
506
544
 
507
545
  The frame is named as a person would: by its ID, test ID, name, title or ARIA label, else by a
@@ -664,8 +702,8 @@ started, or the `timeoutMs` of its step), then judges every page load since the
664
702
  started:
665
703
 
666
704
  - An HTTP error status (400 or above) fails that step, such as
667
- `Step 2 (click link "Blog"): The page it opened returned HTTP 404.` A redirect counts by the page
668
- it ends at.
705
+ `Clicking the "Blog" link: The page it opened returned HTTP 404.` A redirect counts by the page
706
+ it ends at. A `goto` or `reload` with `status` judges its own page by that status alone.
669
707
  - A page that could not be loaded at all blocks it
670
708
  (`The page it opened in a new tab or window could not be loaded: net::ERR_CONNECTION_REFUSED.`),
671
709
  and so does one that did not get its response within 15 seconds
@@ -843,19 +881,20 @@ report rules below do not change.
843
881
  ### Report
844
882
 
845
883
  Every run that ends, finished or errored, writes `report.html` into its folder. One page, one
846
- player: at the top the target, the number of cases, how long the run took and the device, what was
847
- asked (two lines, with the rest a click away) and a filter per status. Below, the run's video in a
848
- browser window (a phone, for a run on a phone) with the page's address at each moment, as the run
849
- recorded it, and beside it the evaluation and one card per case. The evaluation is the agent's
850
- headline with the counts under it, one line per fix (most severe first), the agent's first fix as
851
- "Fix first", and what was not tested and why; without a write-up, the counts alone. Each card has
852
- the case's status (an icon and its word), its time on the video, why it did not pass, and its
853
- screenshots: for a case that did not pass, the page when it stopped as "Actual" (beside one the
854
- agent marked only in green as "Expected"), else small thumbnails. A screenshot opens in a viewer
855
- with the highlights drawn over it (a checkbox hides them) and the element the step acted on; the
856
- arrow keys step through the case's screenshots. "Steps and details" opens the case's steps with
857
- their timecodes and the agent's write-up of it. Then what to test next, and the run's details
858
- (what it checks, target, times, video, version, raw files). Scrolling the cases drives the player:
884
+ player: the run's video in a browser window (a phone, for a run on a phone) with the page's address
885
+ at each moment, as the run recorded it, its timeline in one segment per case, and the case playing
886
+ now; on a phone the player stays pinned at the top while the rest scrolls. Beside it: the run's
887
+ title, how long it ran and its counts, and the verdict (the agent's headline; without a write-up,
888
+ the counts). Then the issues, numbered, most severe first: each fix with its evidence side by side
889
+ (the screenshot that shows the bug on a red tile), each screenshot with its time on the video, the
890
+ mark's note and its case. Then one card per case: its status (an icon and its word), its time on
891
+ the video, why it did not pass, and its screenshots as a pile (for a case that did not pass, the
892
+ page when it stopped, in red). A screenshot opens in a viewer with the highlights drawn over it and
893
+ the element the step acted on, the issue's or case's title and the legend of its marks under it;
894
+ the arrow keys step through the case's screenshots. "Steps and details" opens the case's steps with their timecodes and the agent's
895
+ write-up of it. Last, three folds: what was not checked and why, what to test next, and the run's
896
+ details (what was asked, what it checks, target, device, browser, times, video, version, raw
897
+ files, and which parts are the agent's write-up). Scrolling the cases drives the player:
859
898
  the case at the reading line plays and the cases follow the video; with "Loop case" on (it starts
860
899
  off) the case plays in a loop instead. Code lays out the page and decides every status, except that the agent's write-up
861
900
  may mark a case failed (its card then says so, as the agent's verdict, beside the code's result);
@@ -868,7 +907,8 @@ load by relative paths, so it opens from disk and still works when the run folde
868
907
  moved. It has a light and a dark theme: it follows the
869
908
  system, and a switch picks one (kept in the browser where it allows). Without script it follows the
870
909
  system, the video has the browser's own controls, timecodes are plain links that open the video at
871
- that time and screenshots open the image. One video loads at a time, so the screenshots load from
910
+ that time. A screenshot opens only in the report's viewer (a card over the page, dimmed and
911
+ blurred), never in a tab. One video loads at a time, so the screenshots load from
872
912
  any static server, also one without HTTP range requests such as `python3 -m http.server`.
873
913
  `run`, `status` and the MCP tool `run_status` give its path once the run has ended.
874
914
 
@@ -1,6 +1,10 @@
1
1
  import { Effect, FileSystem, Layer, Path } from 'effect';
2
2
  import { ChildProcessSpawner } from 'effect/process';
3
3
  import { Browser } from '../core/index.js';
4
+ /** How long the doctor's test recording keeps its session open, after its first frame. */
5
+ export declare const TEST_RECORDING_MS = 500;
6
+ /** How long each of the doctor's test recordings may take (launching the browser included). */
7
+ export declare const TEST_RECORDING_TIMEOUT_MS = 60000;
4
8
  /**
5
9
  * Launches the installed Chrome, else Edge, else Playwright's downloaded Chromium. Needs the
6
10
  * platform (`FileSystem`, `Path`) to find Playwright's ffmpeg, and `ChildProcessSpawner` to run it
@@ -1,12 +1,12 @@
1
- import { Effect, FileSystem, Layer, Path, Schema } from 'effect';
1
+ import { Context, Effect, FileSystem, Layer, Path, Schema } from 'effect';
2
2
  import { ChildProcessSpawner } from 'effect/process';
3
3
  import { chromium } from 'playwright-core';
4
4
  import { Browser, BrowserNotFound, PageActionFailed, } from '../core/index.js';
5
5
  import { annotateAll } from './annotate.js';
6
6
  import { stillVideo } from './still.js';
7
7
  import { signInBrowser } from './sign-in.js';
8
- import { deviceLabel, deviceScale, launchArgs, newSession } from './page.js';
9
- import { videoRecording } from './recorder.js';
8
+ import { deviceLabel, deviceScale, deviceViewport, launchArgs, newSession, videoSize, } from './page.js';
9
+ import { RecordingFailed, sizeText, videoProblemReason, videoRecording } from './recorder.js';
10
10
  /** Order matters: prefer what the user already has installed. */
11
11
  const candidates = [
12
12
  { kind: 'chrome', channel: 'chrome' },
@@ -66,6 +66,81 @@ const open = (options, platform) => launchAny(options.headed, options.device).pi
66
66
  return yield* newSession(browser, session.device, video, true, session.session, deviceScale(options.device ?? 'desktop'));
67
67
  }),
68
68
  })));
69
+ /** How long the doctor's test recording keeps its session open, after its first frame. */
70
+ export const TEST_RECORDING_MS = 500;
71
+ /** How long each of the doctor's test recordings may take (launching the browser included). */
72
+ export const TEST_RECORDING_TIMEOUT_MS = 60_000;
73
+ /** The size of `device`'s session video, which its test recording should have. */
74
+ const deviceVideo = (device) => videoSize(deviceViewport(device), deviceScale(device));
75
+ /**
76
+ * One test recording: a session on `device` opened as a run opens one (`open` at its scale, then
77
+ * its `newSession`, with the recorder a run uses), on a blank page, closed after
78
+ * `TEST_RECORDING_MS`; its video saved in a temporary folder and read back with ffmpeg
79
+ * (`stillVideo`).
80
+ */
81
+ const testRecording = (device, platform, readBack) => Effect.gen(function* () {
82
+ const fs = yield* FileSystem.FileSystem;
83
+ const path = yield* Path.Path;
84
+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: 'screw-bugs-doctor-' });
85
+ const videoDir = path.join(dir, 'video');
86
+ const file = path.join(videoDir, 'session-1.webm');
87
+ const browser = yield* open({ headed: false, device }, platform);
88
+ const session = yield* browser.newSession({
89
+ device,
90
+ video: { dir: videoDir, path: file },
91
+ });
92
+ yield* Effect.sleep(TEST_RECORDING_MS);
93
+ const { videoProblem } = yield* session.close;
94
+ if (videoProblem !== undefined)
95
+ return {
96
+ ok: false,
97
+ reason: videoProblemReason(videoProblem),
98
+ problem: videoProblem,
99
+ };
100
+ const bytes = yield* fs.stat(file).pipe(Effect.map((info) => Number(info.size)), Effect.orElseSucceed(() => 0));
101
+ if (bytes === 0)
102
+ return {
103
+ ok: false,
104
+ reason: 'output',
105
+ problem: 'The test video was not saved, or is empty.',
106
+ };
107
+ if ((yield* readBack(file)) === undefined)
108
+ return {
109
+ ok: false,
110
+ reason: 'output',
111
+ problem: 'The test video was saved, but ffmpeg could not read it back.',
112
+ };
113
+ return { ok: true, detail: sizeText(deviceVideo(device)) };
114
+ }).pipe(Effect.scoped, Effect.provideContext(platform), Effect.timeoutOption(TEST_RECORDING_TIMEOUT_MS), Effect.map((result) => result._tag === 'Some'
115
+ ? result.value
116
+ : {
117
+ ok: false,
118
+ reason: 'browser',
119
+ problem: `The test recording did not end within ${TEST_RECORDING_TIMEOUT_MS / 1000} s.`,
120
+ }), Effect.catch((error) => Effect.succeed(error._tag === 'PageActionFailed' && error.cause instanceof RecordingFailed
121
+ ? { ok: false, reason: error.cause.reason, problem: error.cause.message }
122
+ : { ok: false, reason: 'browser', problem: error.message })));
123
+ /**
124
+ * `Browser.checkRecording`: a test recording on a desktop, then one on a phone (`testRecording`),
125
+ * since a phone's is recorded at its own scale from a window that can be wider than it (macOS
126
+ * keeps one at least 500 wide). The first that fails says what went wrong, a phone's saying so.
127
+ */
128
+ const checkRecording = (platform, readBack) => Effect.gen(function* () {
129
+ const desktop = yield* testRecording('desktop', platform, readBack);
130
+ if (!desktop.ok)
131
+ return desktop;
132
+ const phone = yield* testRecording('mobile', platform, readBack);
133
+ if (!phone.ok)
134
+ return {
135
+ ...phone,
136
+ problem: `On a phone, ${phone.problem.charAt(0).toLowerCase()}${phone.problem.slice(1)}`,
137
+ };
138
+ return {
139
+ ok: true,
140
+ detail: `Recorded a ${desktop.detail} desktop and a ${phone.detail} phone test video ` +
141
+ 'and played them back',
142
+ };
143
+ });
69
144
  /**
70
145
  * Launches the installed Chrome, else Edge, else Playwright's downloaded Chromium. Needs the
71
146
  * platform (`FileSystem`, `Path`) to find Playwright's ffmpeg, and `ChildProcessSpawner` to run it
@@ -82,12 +157,14 @@ export const BrowserPlaywright = Layer.effect(Browser, Effect.gen(function* () {
82
157
  return { ok: true };
83
158
  return { ok: false, problem: ffmpegProblem(lookup), command: yield* installFfmpegCommand };
84
159
  }).pipe(Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path));
160
+ const still = (file) => findFfmpeg.pipe(Effect.flatMap((lookup) => lookup.found && lookup.path !== undefined
161
+ ? stillVideo(lookup.path, file)
162
+ : Effect.succeed(undefined)), Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
85
163
  return {
86
164
  detect: Effect.scoped(open({ headed: false }, platform)).pipe(Effect.map((session) => session.info)),
87
165
  videoSupport,
88
- stillVideo: (file) => findFfmpeg.pipe(Effect.flatMap((lookup) => lookup.found && lookup.path !== undefined
89
- ? stillVideo(lookup.path, file)
90
- : Effect.succeed(undefined)), Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
166
+ checkRecording: checkRecording(Context.add(platform, Path.Path, path), still),
167
+ stillVideo: still,
91
168
  open: (options) => open(options, platform),
92
169
  deviceLabel,
93
170
  annotate: (jobs) => Effect.scoped(launchAny(false).pipe(Effect.flatMap(({ browser }) => annotateAll(browser, jobs)))),
@@ -27,6 +27,11 @@ export declare const NAVIGATION_START_MS = 250;
27
27
  export declare const MOBILE_DEVICE = "iPhone 17";
28
28
  /** The device as reports show it; the engine is named because mobile is not real Safari. */
29
29
  export declare const deviceLabel: (device: Device) => string;
30
+ /** `device`'s viewport, in CSS pixels. */
31
+ export declare const deviceViewport: (device: Device) => {
32
+ readonly width: number;
33
+ readonly height: number;
34
+ };
30
35
  /** The device pixels per CSS pixel `device` is shown at (3 on the phone). */
31
36
  export declare const deviceScale: (device: Device) => number;
32
37
  /**
@@ -49,6 +54,35 @@ export declare const videoSize: (viewport: {
49
54
  width: number;
50
55
  height: number;
51
56
  };
57
+ /** How long fitting a session's window to its viewport (`fitWindow`) may take. */
58
+ export declare const FIT_WINDOW_TIMEOUT_MS = 2000;
59
+ /**
60
+ * Makes the contents of `page`'s browser window at least as big as `viewport` (CSS pixels, so
61
+ * the window's DIP whatever scale it renders at), through CDP's `Browser.setContentsSize`, before
62
+ * the screencast starts: its frames show what the window's contents show. Playwright sizes a
63
+ * headless window to the viewport as a whole, so where the window keeps room for a toolbar
64
+ * (Chrome's headless mode on macOS: 87 px of a 1280×800 window), the frames come that much
65
+ * shorter than the viewport and the video, which needs them whole, gets none. Elsewhere the
66
+ * contents already fit and nothing changes. The emulated viewport, and so the page, is as before.
67
+ * A browser without the method (or without CDP) is left as it is: the recorder then says which
68
+ * size of frames it got.
69
+ *
70
+ * Gives the window's size afterwards (CSS pixels, the toolbar's room included), or undefined when
71
+ * it could not be read: a window may stay wider than the viewport (on macOS no narrower than 500,
72
+ * wider than a phone's 402), and the screencast then sends the whole window's contents with the
73
+ * viewport in their top left corner (`windowFrames`).
74
+ */
75
+ export declare const fitWindow: (page: Page, viewport: {
76
+ readonly width: number;
77
+ readonly height: number;
78
+ }) => Effect.Effect<FrameSize | undefined>;
79
+ /**
80
+ * The largest frame the screencast may send for a window of `window` CSS pixels (`fitWindow`) at
81
+ * `scale`: the window's contents at the scale the browser renders at, the viewport in their top
82
+ * left corner, which the video crops (`ffmpegArgs`). Undefined (frames the video's size only)
83
+ * when the window's size is not known.
84
+ */
85
+ export declare const windowFrames: (window: FrameSize | undefined, scale: number) => FrameSize | undefined;
52
86
  /** How long closing a session (and saving its video) may take. */
53
87
  export declare const CLOSE_TIMEOUT_MS = 30000;
54
88
  /** How long measuring an element for a screenshot or reading page facts may take. */
@@ -410,8 +444,11 @@ export declare const firstFrameAt: (page: Page, first: Effect.Effect<number>) =>
410
444
  export interface SessionVideo {
411
445
  /** The video, a `.webm`. */
412
446
  readonly path: string;
413
- /** Starts recording a tab into `path` at `size`. */
414
- readonly record: (page: Page, size: FrameSize) => Effect.Effect<Recorder, PlatformError | Error, Scope.Scope>;
447
+ /**
448
+ * Starts recording a tab into `path` at `size`, from frames up to `window` (`windowFrames`) with
449
+ * the viewport in their top left corner.
450
+ */
451
+ readonly record: (page: Page, size: FrameSize, window?: FrameSize) => Effect.Effect<Recorder, PlatformError | Error, Scope.Scope>;
415
452
  }
416
453
  /**
417
454
  * One session: a fresh context (no cookies or storage from other runs) with one tab that every
@@ -31,6 +31,8 @@ export const MOBILE_DEVICE = 'iPhone 17';
31
31
  /** The device as reports show it; the engine is named because mobile is not real Safari. */
32
32
  export const deviceLabel = (device) => device === 'mobile' ? `${MOBILE_DEVICE} (Chromium)` : 'Desktop';
33
33
  const contextOptions = (device) => device === 'mobile' ? devices[MOBILE_DEVICE] : { viewport: { width: 1280, height: 800 } };
34
+ /** `device`'s viewport, in CSS pixels. */
35
+ export const deviceViewport = (device) => contextOptions(device).viewport;
34
36
  /** The device pixels per CSS pixel `device` is shown at (3 on the phone). */
35
37
  export const deviceScale = (device) => {
36
38
  const options = contextOptions(device);
@@ -56,6 +58,49 @@ export const videoSize = (viewport, scale) => {
56
58
  const even = (n) => Math.max(2, Math.floor((n * scale) / 2) * 2);
57
59
  return { width: even(viewport.width), height: even(viewport.height) };
58
60
  };
61
+ /** How long fitting a session's window to its viewport (`fitWindow`) may take. */
62
+ export const FIT_WINDOW_TIMEOUT_MS = 2_000;
63
+ /**
64
+ * Makes the contents of `page`'s browser window at least as big as `viewport` (CSS pixels, so
65
+ * the window's DIP whatever scale it renders at), through CDP's `Browser.setContentsSize`, before
66
+ * the screencast starts: its frames show what the window's contents show. Playwright sizes a
67
+ * headless window to the viewport as a whole, so where the window keeps room for a toolbar
68
+ * (Chrome's headless mode on macOS: 87 px of a 1280×800 window), the frames come that much
69
+ * shorter than the viewport and the video, which needs them whole, gets none. Elsewhere the
70
+ * contents already fit and nothing changes. The emulated viewport, and so the page, is as before.
71
+ * A browser without the method (or without CDP) is left as it is: the recorder then says which
72
+ * size of frames it got.
73
+ *
74
+ * Gives the window's size afterwards (CSS pixels, the toolbar's room included), or undefined when
75
+ * it could not be read: a window may stay wider than the viewport (on macOS no narrower than 500,
76
+ * wider than a phone's 402), and the screencast then sends the whole window's contents with the
77
+ * viewport in their top left corner (`windowFrames`).
78
+ */
79
+ export const fitWindow = (page, viewport) => Effect.gen(function* () {
80
+ const session = yield* Effect.acquireRelease(attempt(() => page.context().newCDPSession(page), firstLine), (session) => attempt(() => session.detach(), firstLine).pipe(Effect.timeoutOption(FIT_WINDOW_TIMEOUT_MS), Effect.ignore));
81
+ const before = yield* attempt(() => session.send('Browser.getWindowForTarget'), firstLine);
82
+ const resized = yield* attempt(() => session.send('Browser.setContentsSize', {
83
+ windowId: before.windowId,
84
+ width: viewport.width,
85
+ height: viewport.height,
86
+ }), firstLine).pipe(Effect.as(true), Effect.orElseSucceed(() => false));
87
+ const { bounds } = resized
88
+ ? yield* attempt(() => session.send('Browser.getWindowForTarget'), firstLine)
89
+ : before;
90
+ // A browser may leave the bounds, or their size, out.
91
+ return bounds?.width !== undefined && bounds.height !== undefined
92
+ ? { width: bounds.width, height: bounds.height }
93
+ : undefined;
94
+ }).pipe(Effect.scoped, Effect.timeoutOption(FIT_WINDOW_TIMEOUT_MS), Effect.map(Option.getOrUndefined), Effect.orElseSucceed(() => undefined));
95
+ /**
96
+ * The largest frame the screencast may send for a window of `window` CSS pixels (`fitWindow`) at
97
+ * `scale`: the window's contents at the scale the browser renders at, the viewport in their top
98
+ * left corner, which the video crops (`ffmpegArgs`). Undefined (frames the video's size only)
99
+ * when the window's size is not known.
100
+ */
101
+ export const windowFrames = (window, scale) => window === undefined
102
+ ? undefined
103
+ : { width: Math.ceil(window.width * scale), height: Math.ceil(window.height * scale) };
59
104
  /** How long closing a session (and saving its video) may take. */
60
105
  export const CLOSE_TIMEOUT_MS = 30_000;
61
106
  /** How long measuring an element for a screenshot or reading page facts may take. */
@@ -320,6 +365,10 @@ const watchContext = (context, page, clock) => {
320
365
  return undefined;
321
366
  if ('error' in outcome)
322
367
  return { ...base, _tag: 'LoadFailed', error: outcome.error };
368
+ if (load.expected !== undefined)
369
+ return outcome.status === load.expected
370
+ ? undefined
371
+ : { ...base, _tag: 'UnexpectedStatus', status: outcome.status, expected: load.expected };
323
372
  return outcome.status >= 400
324
373
  ? { ...base, _tag: 'HttpError', status: outcome.status }
325
374
  : undefined;
@@ -359,6 +408,21 @@ const watchContext = (context, page, clock) => {
359
408
  return first;
360
409
  }),
361
410
  refused: Effect.sync(() => refused),
411
+ /**
412
+ * Makes the load that `response` (the page a goto or reload ended at) ends expect `status`.
413
+ * The load ends with that response, if it has not yet: a 3xx without a place to go is the
414
+ * page itself, which the response listener above never ends a load with. False when that
415
+ * load is not one of those watched.
416
+ */
417
+ expect: (response, status) => {
418
+ const request = response.request();
419
+ const load = loads.get(firstOf(request));
420
+ if (load === undefined)
421
+ return false;
422
+ load.expected = status;
423
+ ended(request, { status: response.status() });
424
+ return true;
425
+ },
362
426
  httpErrors: () => httpErrors,
363
427
  /**
364
428
  * Forgets everything of the last case: its loads (one still going is no longer judged), where
@@ -1304,19 +1368,28 @@ hold) => {
1304
1368
  * nothing; undefined when that could not be read. False without CDP.
1305
1369
  */
1306
1370
  const closedShows = (doc, sessions) => readClosed([doc], undefined, sessions).pipe(Effect.map((results) => results === 'no-cdp' ? false : results.some((r) => r._tag === 'content' && r.shows)), Effect.orElseSucceed(() => undefined));
1371
+ /**
1372
+ * Has the page a goto or reload loaded judged by the status it expects, if it expects one
1373
+ * (see `Navigation`); fails when it loaded no page of its own whose status could be checked.
1374
+ */
1375
+ const expectStatus = (response, status) => status === undefined || (response !== null && watch.expect(response, status))
1376
+ ? Effect.void
1377
+ : Effect.fail(new PageActionFailed({
1378
+ message: 'No new page loaded, so its HTTP status could not be checked.',
1379
+ }));
1307
1380
  return {
1308
1381
  // The page starts loading when they are called: that is when they acted.
1309
1382
  goto: (url, wait) => {
1310
1383
  const timeout = wait?.timeoutMs ?? NAVIGATION_TIMEOUT_MS;
1311
1384
  return attempt(() => page.goto(url, { timeout, waitUntil: 'load' }), (error) => isTimeout(error)
1312
1385
  ? `The page did not load within ${seconds(timeout)}.`
1313
- : `Could not open ${url}: ${firstLine(error)}`).pipe(Effect.as({ afterMs: 0 }));
1386
+ : `Could not open ${url}: ${firstLine(error)}`).pipe(Effect.flatMap((response) => expectStatus(response, wait?.status)), Effect.as({ afterMs: 0 }));
1314
1387
  },
1315
1388
  reload: (wait) => {
1316
1389
  const timeout = wait?.timeoutMs ?? NAVIGATION_TIMEOUT_MS;
1317
1390
  return attempt(() => page.reload({ timeout, waitUntil: 'load' }), (error) => isTimeout(error)
1318
1391
  ? `The page did not reload within ${seconds(timeout)}.`
1319
- : `Could not reload the page: ${firstLine(error)}`).pipe(Effect.as({ afterMs: 0 }));
1392
+ : `Could not reload the page: ${firstLine(error)}`).pipe(Effect.flatMap((response) => expectStatus(response, wait?.status)), Effect.as({ afterMs: 0 }));
1320
1393
  },
1321
1394
  click: (target, wait) => Effect.gen(function* () {
1322
1395
  const began = yield* Clock.currentTimeMillis;
@@ -2084,10 +2157,14 @@ renderScale = 1) => Effect.gen(function* () {
2084
2157
  // Only reached when opening it went wrong, or once the session closed it already
2085
2158
  // (`close`): a failure to close it again cannot change what the session found.
2086
2159
  (context) => attempt(() => context.close(), firstLine).pipe(Effect.ignore)).pipe(Effect.flatMap((context) => attempt(() => context.newPage(), failed).pipe(Effect.map((page) => ({ context, page })))));
2160
+ // The screencast sends what the window's contents show, which must hold the whole viewport.
2161
+ const window = video === undefined ? undefined : yield* fitWindow(page, options.viewport);
2087
2162
  // Video is not optional: a session that cannot be recorded does not run.
2088
2163
  const recorder = video === undefined
2089
2164
  ? undefined
2090
- : yield* video.record(page, videoSize(options.viewport, renderScale)).pipe(Effect.mapError((error) => new PageActionFailed({
2165
+ : yield* video
2166
+ .record(page, videoSize(options.viewport, renderScale), windowFrames(window, renderScale))
2167
+ .pipe(Effect.mapError((error) => new PageActionFailed({
2091
2168
  message: `The session could not be recorded as video (run \`npx screw-bugs doctor\` to see what is missing): ${firstLine(error)}`,
2092
2169
  cause: error,
2093
2170
  })));