screw-bugs 0.1.11 → 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
@@ -363,8 +363,8 @@ Chromium: this catches responsive layout and touch problems, not Safari-only bug
363
363
 
364
364
  | Step | Fields | What it does |
365
365
  | -------------- | ------------------------------------- | --------------------------------------------------------------- |
366
- | `goto` | `url` | Open a URL; paths resolve against the job URL. HTTP 400+ fails. |
367
- | `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` |
368
368
  | `click` | `target` | Click an element; a page it opens with HTTP 400+ fails |
369
369
  | `hover` | `target` | Move the pointer over an element, for controls shown on hover |
370
370
  | `fill` | `target`, `value` | Replace the value of an input |
@@ -378,6 +378,15 @@ Chromium: this catches responsive layout and touch problems, not Safari-only bug
378
378
  | `scroll` | one of `target`, `to`, `by`; `frame`? | Scroll, then screenshot the view |
379
379
  | `screenshot` | `name` | Save a full-page screenshot as evidence |
380
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
+
381
390
  Every step that waits (all but `screenshot`) takes an optional `timeoutMs`, from 100 to 180000
382
391
  (three minutes): how long to wait for its element, text, URL, state or frame (default 5000), or
383
392
  for the page it loads (`goto`, `reload`, `press`; default 15000). A page that a `click`, `fill`, `upload` or an
@@ -432,8 +441,8 @@ second, so text that shows a moment late still counts. It passes only when every
432
441
  second read everything it had to. The reason says where it was found:
433
442
 
434
443
  ```text
435
- Step 3 (expectNoText "Acme"): "Acme" is on the page (image alt "Acme logo" in .clients).
436
- 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").
437
446
  ```
438
447
 
439
448
  A page (or frame, or target) that shows nothing at all within the wait blocks the case
@@ -530,7 +539,7 @@ name (or, for a step with `frame`, in the page itself or in another frame), the
530
539
  to change, in the form a step takes it:
531
540
 
532
541
  ```text
533
- 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']"}.
534
543
  ```
535
544
 
536
545
  The frame is named as a person would: by its ID, test ID, name, title or ARIA label, else by a
@@ -693,8 +702,8 @@ started, or the `timeoutMs` of its step), then judges every page load since the
693
702
  started:
694
703
 
695
704
  - An HTTP error status (400 or above) fails that step, such as
696
- `Step 2 (click link "Blog"): The page it opened returned HTTP 404.` A redirect counts by the page
697
- 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.
698
707
  - A page that could not be loaded at all blocks it
699
708
  (`The page it opened in a new tab or window could not be loaded: net::ERR_CONNECTION_REFUSED.`),
700
709
  and so does one that did not get its response within 15 seconds
@@ -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
  })));
@@ -1,4 +1,4 @@
1
- import { Effect, FileSystem } from 'effect';
1
+ import { type Cause, Effect, FileSystem } from 'effect';
2
2
  import { ChildProcessSpawner } from 'effect/process';
3
3
  import type { Page } from 'playwright-core';
4
4
  /**
@@ -44,21 +44,72 @@ export interface FrameSize {
44
44
  readonly width: number;
45
45
  readonly height: number;
46
46
  }
47
+ /** `1280×800`. */
48
+ export declare const sizeText: (size: FrameSize) => string;
49
+ declare const RecordingFailed_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]; }>) => Cause.YieldableError & {
50
+ readonly _tag: "RecordingFailed";
51
+ } & Readonly<A>;
52
+ /**
53
+ * Why a session's video could not be recorded, by what went wrong, so `doctor` can tell them
54
+ * apart: the browser's frames were all left out for their size (`frames_rejected`), the tab sent
55
+ * none (`no_frames`), ffmpeg could not start or encode (`encoder`), or the video could not be
56
+ * written or read back (`output`).
57
+ */
58
+ export declare class RecordingFailed extends RecordingFailed_base<{
59
+ readonly reason: 'frames_rejected' | 'no_frames' | 'encoder' | 'output';
60
+ readonly message: string;
61
+ readonly cause?: unknown;
62
+ }> {
63
+ }
64
+ /**
65
+ * What the recorder says when every frame the browser sent was left out for its size: the last
66
+ * such size, against the video's. A window smaller than the viewport (a headless window on
67
+ * macOS whose contents lost the toolbar's height) sends frames cut short.
68
+ */
69
+ export declare const rejectedFramesText: (observed: FrameSize | undefined, count: number, video: FrameSize) => string;
47
70
  /** A JPEG's size, from its first start-of-frame segment; undefined when it has none. */
48
71
  export declare const jpegSize: (bytes: Uint8Array) => FrameSize | undefined;
49
- /** Whether a frame of `frame`'s size shows the page whole in a video of `video`'s. */
50
- export declare const fits: (frame: FrameSize, video: FrameSize) => boolean;
72
+ /**
73
+ * Whether a frame of `frame`'s size shows the page whole in a video of `video`'s: the video's
74
+ * size, a little smaller or a pixel larger; or, from a window wider or taller than the viewport
75
+ * (`window`, see `windowFrames`), up to the window's size, the viewport in its top left corner,
76
+ * which the video crops. A frame larger than the window (a device-pixel capture's, in a browser at
77
+ * 1x) is never one.
78
+ */
79
+ export declare const fits: (frame: FrameSize, video: FrameSize, window?: FrameSize) => boolean;
80
+ /**
81
+ * The most a window of `window`'s size lets in once a frame of `first`'s size was kept: as tall as
82
+ * that frame and a pixel, no more than the window, and as wide as the window. The window's height
83
+ * can count room its contents do not have (macOS keeps a toolbar's: 1280×887 for 1280×800 of
84
+ * contents), and a full-page screenshot makes the screencast send one frame the size of the page,
85
+ * whose top left corner is the page's, not the viewport's: within the window's size, the video
86
+ * would show it cropped, and keep showing it until the page paints again. The first kept frame is
87
+ * as tall as the window's contents: the session waits for it (`Recorder.ready`) before any step,
88
+ * and frames from before the window was fit are shorter than the video, never kept. Its width is
89
+ * not bounded the same way: a phone's frames in a window wider than it (Chrome 158 on macOS) are
90
+ * the window's width at first and the viewport's after a navigation, and either may come first.
91
+ */
92
+ export declare const firstBound: (first: FrameSize, window: FrameSize | undefined) => {
93
+ width: number;
94
+ height: number;
95
+ } | undefined;
51
96
  /**
52
97
  * Which frames go on the video, and where: a frame's time on the video is its paint time (epoch
53
98
  * ms) after the first kept frame's, so the video starts at its first frame, as Playwright's does.
99
+ * `window` is as for `fits` until a frame is kept; from then on the frames it lets in are at most
100
+ * as tall as that first frame and a pixel (`firstBound`).
54
101
  */
55
- export declare const frameGate: (video: FrameSize) => {
102
+ export declare const frameGate: (video: FrameSize, window?: FrameSize) => {
56
103
  /** A screenshot starts being taken `at`; call the result when it was taken. */
57
104
  hold: (at: number) => (end: number) => void;
58
105
  /**
59
106
  * The frame's time on the video in ms when it is kept, else undefined: when it does not fit
60
- * (`size` undefined is a frame that could not be read), was painted while a screenshot was
61
- * taken, or does not come after the last kept frame (the video's frames only go forward).
107
+ * (`size` undefined is a frame that could not be read) or was painted while a screenshot was
108
+ * taken. Frames come in the order the page painted them, but not always stamped so: Chrome
109
+ * stamps the frame a screencast sends when it starts (again, `startRecorder`) with when it
110
+ * started, which can be before the last frame it sent was stamped. A frame stamped at or
111
+ * before the last kept one goes a millisecond after it, so the video's frames only go forward
112
+ * and the latest is always the page's latest state.
62
113
  */
63
114
  admit: (size: FrameSize | undefined, timestamp: number) => number | undefined;
64
115
  /** When the first kept frame was painted, in epoch ms. */
@@ -101,7 +152,10 @@ export declare const ffmpegArgs: (size: FrameSize, file: string) => ReadonlyArra
101
152
  export interface Recorder {
102
153
  /** When the first frame on the video was painted, in epoch ms; waits for it. */
103
154
  readonly firstFrame: Effect.Effect<number>;
104
- /** Runs `effect` (a screenshot) keeping the frames painted meanwhile off the video. */
155
+ /**
156
+ * Runs `effect` (a screenshot) keeping the frames painted meanwhile off the video, then starts
157
+ * the screencast again, so the page as it is after it comes too.
158
+ */
105
159
  readonly hold: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
106
160
  /**
107
161
  * Ends the video and saves it at its path: why it could not be, else undefined. Call once the
@@ -113,27 +167,34 @@ export interface Recorder {
113
167
  * writes, for at most `READY_TIMEOUT_MS`; fails when ffmpeg has ended instead, or has not
114
168
  * opened it by then (no frame came, or it is stuck).
115
169
  */
116
- readonly ready: Effect.Effect<void, Error>;
117
- /** Why the video stopped being recorded before `finish`, once ffmpeg ended early. */
170
+ readonly ready: Effect.Effect<void, RecordingFailed>;
171
+ /**
172
+ * Why the video stopped being recorded before `finish`: ffmpeg ended early, or the screencast
173
+ * could not be started again on a tab still open.
174
+ */
118
175
  readonly stopped: Effect.Effect<string | undefined>;
119
176
  }
177
+ /** The kind of problem a session's close gave about its video (`finish`, or its timeout). */
178
+ export declare const videoProblemReason: (problem: string) => RecordingFailed['reason'];
120
179
  /**
121
180
  * Records `page`'s video into `file` (a `.webm`) with the ffmpeg at `ffmpeg`, at `size` (see
122
- * `videoSize`). Written to a file beside it first and moved there by `finish`, so a run whose
123
- * process dies leaves no half-written video where a video is looked for. Fails when ffmpeg or
124
- * the screencast cannot start; with the scope, ffmpeg and the screencast are stopped.
181
+ * `videoSize`), from frames up to `window` (see `fits`). Written to a file beside it first and
182
+ * moved there by `finish`, so a run whose process dies leaves no half-written video where a
183
+ * video is looked for. Fails when ffmpeg or the screencast cannot start; with the scope, ffmpeg
184
+ * and the screencast are stopped.
125
185
  */
126
186
  export declare const startRecorder: (page: Page, options: {
127
187
  readonly ffmpeg: string;
128
188
  readonly file: string;
129
189
  readonly size: FrameSize;
190
+ readonly window?: FrameSize | undefined;
130
191
  }) => Effect.Effect<{
131
192
  firstFrame: Effect.Effect<number, never, never>;
132
193
  hold: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
133
194
  finish: Effect.Effect<string | undefined, never, never>;
134
- ready: Effect.Effect<undefined, Error, never>;
195
+ ready: Effect.Effect<undefined, RecordingFailed, never>;
135
196
  stopped: Effect.Effect<string | undefined, never, never>;
136
- }, Error | import("effect/PlatformError").PlatformError, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | import("effect/Scope").Scope>;
197
+ }, RecordingFailed, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | import("effect/Scope").Scope>;
137
198
  /**
138
199
  * How a session with a video at `path` (in the folder `dir`, made when missing) is recorded with
139
200
  * the ffmpeg at `ffmpeg`, on the platform this runs on.
@@ -144,11 +205,12 @@ export declare const videoRecording: (video: {
144
205
  readonly ffmpeg: string;
145
206
  }) => Effect.Effect<{
146
207
  path: string;
147
- record: (page: Page, size: FrameSize) => Effect.Effect<{
208
+ record: (page: Page, size: FrameSize, window?: FrameSize) => Effect.Effect<{
148
209
  firstFrame: Effect.Effect<number, never, never>;
149
210
  hold: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
150
211
  finish: Effect.Effect<string | undefined, never, never>;
151
- ready: Effect.Effect<undefined, Error, never>;
212
+ ready: Effect.Effect<undefined, RecordingFailed, never>;
152
213
  stopped: Effect.Effect<string | undefined, never, never>;
153
- }, Error | import("effect/PlatformError").PlatformError, import("effect/Scope").Scope>;
214
+ }, RecordingFailed, import("effect/Scope").Scope>;
154
215
  }, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem>;
216
+ export {};
@@ -1,4 +1,4 @@
1
- import { Clock, Deferred, Effect, Exit, FileSystem, Queue, Stream } from 'effect';
1
+ import { Clock, Data, Deferred, Effect, Exit, FileSystem, Queue, Stream } from 'effect';
2
2
  import { ChildProcess, ChildProcessSpawner } from 'effect/process';
3
3
  /**
4
4
  * A session's video, recorded by screw-bugs itself rather than by Playwright's `recordVideo`:
@@ -43,6 +43,25 @@ export const BACKLOG_FRAMES = 10 * VIDEO_FPS;
43
43
  export const READY_TIMEOUT_MS = 3_000;
44
44
  /** How often whether it has is looked at. */
45
45
  const READY_POLL = '50 millis';
46
+ /** `1280×800`. */
47
+ export const sizeText = (size) => `${size.width}×${size.height}`;
48
+ /**
49
+ * Why a session's video could not be recorded, by what went wrong, so `doctor` can tell them
50
+ * apart: the browser's frames were all left out for their size (`frames_rejected`), the tab sent
51
+ * none (`no_frames`), ffmpeg could not start or encode (`encoder`), or the video could not be
52
+ * written or read back (`output`).
53
+ */
54
+ export class RecordingFailed extends Data.TaggedError('RecordingFailed') {
55
+ }
56
+ /**
57
+ * What the recorder says when every frame the browser sent was left out for its size: the last
58
+ * such size, against the video's. A window smaller than the viewport (a headless window on
59
+ * macOS whose contents lost the toolbar's height) sends frames cut short.
60
+ */
61
+ export const rejectedFramesText = (observed, count, video) => observed === undefined
62
+ ? `the browser sent ${count} frame${count === 1 ? '' : 's'} that could not be read, so ffmpeg got none.`
63
+ : `the browser sent ${sizeText(observed)} frames, but the video needs ${sizeText(video)} ` +
64
+ `(${count} frame${count === 1 ? '' : 's'} left out), so ffmpeg got none.`;
46
65
  /** A JPEG's size, from its first start-of-frame segment; undefined when it has none. */
47
66
  export const jpegSize = (bytes) => {
48
67
  if (bytes[0] !== 0xff || bytes[1] !== 0xd8)
@@ -73,16 +92,40 @@ export const jpegSize = (bytes) => {
73
92
  }
74
93
  return undefined;
75
94
  };
76
- /** Whether a frame of `frame`'s size shows the page whole in a video of `video`'s. */
77
- export const fits = (frame, video) => frame.width <= video.width + 1 &&
78
- frame.height <= video.height + 1 &&
95
+ /**
96
+ * Whether a frame of `frame`'s size shows the page whole in a video of `video`'s: the video's
97
+ * size, a little smaller or a pixel larger; or, from a window wider or taller than the viewport
98
+ * (`window`, see `windowFrames`), up to the window's size, the viewport in its top left corner,
99
+ * which the video crops. A frame larger than the window (a device-pixel capture's, in a browser at
100
+ * 1x) is never one.
101
+ */
102
+ export const fits = (frame, video, window) => frame.width <= Math.max(video.width + 1, window?.width ?? 0) &&
103
+ frame.height <= Math.max(video.height + 1, window?.height ?? 0) &&
79
104
  frame.width >= video.width - FRAME_SLACK &&
80
105
  frame.height >= video.height - FRAME_SLACK;
106
+ /**
107
+ * The most a window of `window`'s size lets in once a frame of `first`'s size was kept: as tall as
108
+ * that frame and a pixel, no more than the window, and as wide as the window. The window's height
109
+ * can count room its contents do not have (macOS keeps a toolbar's: 1280×887 for 1280×800 of
110
+ * contents), and a full-page screenshot makes the screencast send one frame the size of the page,
111
+ * whose top left corner is the page's, not the viewport's: within the window's size, the video
112
+ * would show it cropped, and keep showing it until the page paints again. The first kept frame is
113
+ * as tall as the window's contents: the session waits for it (`Recorder.ready`) before any step,
114
+ * and frames from before the window was fit are shorter than the video, never kept. Its width is
115
+ * not bounded the same way: a phone's frames in a window wider than it (Chrome 158 on macOS) are
116
+ * the window's width at first and the viewport's after a navigation, and either may come first.
117
+ */
118
+ export const firstBound = (first, window) => window === undefined
119
+ ? undefined
120
+ : { width: window.width, height: Math.min(window.height, first.height + 1) };
81
121
  /**
82
122
  * Which frames go on the video, and where: a frame's time on the video is its paint time (epoch
83
123
  * ms) after the first kept frame's, so the video starts at its first frame, as Playwright's does.
124
+ * `window` is as for `fits` until a frame is kept; from then on the frames it lets in are at most
125
+ * as tall as that first frame and a pixel (`firstBound`).
84
126
  */
85
- export const frameGate = (video) => {
127
+ export const frameGate = (video, window) => {
128
+ let bound = window;
86
129
  /** Screenshots being taken (`end` undefined) or taken, by when, in epoch ms. */
87
130
  let holds = [];
88
131
  let first;
@@ -99,15 +142,20 @@ export const frameGate = (video) => {
99
142
  },
100
143
  /**
101
144
  * The frame's time on the video in ms when it is kept, else undefined: when it does not fit
102
- * (`size` undefined is a frame that could not be read), was painted while a screenshot was
103
- * taken, or does not come after the last kept frame (the video's frames only go forward).
145
+ * (`size` undefined is a frame that could not be read) or was painted while a screenshot was
146
+ * taken. Frames come in the order the page painted them, but not always stamped so: Chrome
147
+ * stamps the frame a screencast sends when it starts (again, `startRecorder`) with when it
148
+ * started, which can be before the last frame it sent was stamped. A frame stamped at or
149
+ * before the last kept one goes a millisecond after it, so the video's frames only go forward
150
+ * and the latest is always the page's latest state.
104
151
  */
105
152
  admit: (size, timestamp) => {
106
- if (size === undefined || !fits(size, video) || held(timestamp))
107
- return undefined;
108
- const ms = Math.round(timestamp - (first ?? timestamp));
109
- if (lastMs !== undefined && ms <= lastMs)
153
+ if (size === undefined || !fits(size, video, bound) || held(timestamp))
110
154
  return undefined;
155
+ const painted = Math.round(timestamp - (first ?? timestamp));
156
+ const ms = lastMs !== undefined && painted <= lastMs ? lastMs + 1 : painted;
157
+ if (first === undefined)
158
+ bound = firstBound(size, bound);
111
159
  first ??= timestamp;
112
160
  lastMs = ms;
113
161
  // A screenshot taken before this frame was painted cannot hold back any later frame.
@@ -252,7 +300,8 @@ export const ffmpegArgs = (size, file) => {
252
300
  `-b:v ${Math.round(pixelRateScale * 1000)}k -threads ${threads}`,
253
301
  `-tile-columns ${Math.ceil(Math.log2(threads))} -row-mt 1`,
254
302
  // A frame a little smaller than the video (see `FRAME_SLACK`) is padded, as Playwright does;
255
- // one a pixel larger loses its odd row or column first. Cropped before it is padded: `pad` cuts
303
+ // one a pixel larger loses its odd row or column first, and one of a window wider or taller
304
+ // than the viewport (`fits`) all but the viewport in its corner. Cropped before padded: `pad` cuts
256
305
  // an odd-height 4:2:0 frame (the JPEG's) to even and pads it back, greying its last row.
257
306
  `-vf crop='min(iw,${w})':'min(ih,${h})':0:0,pad=${w}:${h}:0:0:gray`,
258
307
  '-f webm',
@@ -260,31 +309,44 @@ export const ffmpegArgs = (size, file) => {
260
309
  .flatMap((options) => options.split(' '))
261
310
  .concat(file);
262
311
  };
312
+ /** The kind of problem a session's close gave about its video (`finish`, or its timeout). */
313
+ export const videoProblemReason = (problem) => problem.includes('never showed a frame')
314
+ ? 'no_frames'
315
+ : problem.includes('ffmpeg') || problem.includes('not saved within')
316
+ ? 'encoder'
317
+ : 'output';
263
318
  const ffmpegEnded = (code) => typeof code === 'number' ? `ffmpeg ended with code ${code}` : `ffmpeg failed: ${code}`;
264
319
  /**
265
320
  * Records `page`'s video into `file` (a `.webm`) with the ffmpeg at `ffmpeg`, at `size` (see
266
- * `videoSize`). Written to a file beside it first and moved there by `finish`, so a run whose
267
- * process dies leaves no half-written video where a video is looked for. Fails when ffmpeg or
268
- * the screencast cannot start; with the scope, ffmpeg and the screencast are stopped.
321
+ * `videoSize`), from frames up to `window` (see `fits`). Written to a file beside it first and
322
+ * moved there by `finish`, so a run whose process dies leaves no half-written video where a
323
+ * video is looked for. Fails when ffmpeg or the screencast cannot start; with the scope, ffmpeg
324
+ * and the screencast are stopped.
269
325
  */
270
326
  export const startRecorder = (page, options) => Effect.gen(function* () {
271
327
  const fs = yield* FileSystem.FileSystem;
272
328
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
273
329
  const clock = yield* Effect.clockWith((clock) => Effect.succeed(clock));
274
330
  const partial = `${options.file}.part`;
275
- const gate = frameGate(options.size);
331
+ const gate = frameGate(options.size, options.window);
276
332
  // Bounded, so an ffmpeg that stops reading never makes frames pile up in memory.
277
333
  const queue = yield* Queue.make({
278
334
  capacity: BACKLOG_FRAMES,
279
335
  strategy: 'dropping',
280
336
  });
281
337
  const first = yield* Deferred.make();
282
- const handle = yield* spawner.spawn(ChildProcess.make(options.ffmpeg, [...ffmpegArgs(options.size, partial)], {
338
+ const handle = yield* spawner
339
+ .spawn(ChildProcess.make(options.ffmpeg, [...ffmpegArgs(options.size, partial)], {
283
340
  stdin: Stream.fromQueue(queue),
284
341
  stdout: 'ignore',
285
342
  stderr: 'ignore',
286
343
  forceKillAfter: FFMPEG_KILL_AFTER,
287
- }));
344
+ }))
345
+ .pipe(Effect.mapError((error) => new RecordingFailed({
346
+ reason: 'encoder',
347
+ message: `ffmpeg did not start: ${error.message}`,
348
+ cause: error,
349
+ })));
288
350
  // Once ffmpeg has ended, frames are no longer queued for it.
289
351
  const exited = yield* Deferred.make();
290
352
  let endedWith;
@@ -293,6 +355,9 @@ export const startRecorder = (page, options) => Effect.gen(function* () {
293
355
  }), Deferred.succeed(exited, code))), Effect.andThen(Queue.shutdown(queue)), Effect.forkScoped);
294
356
  Queue.offerUnsafe(queue, matroskaHeader());
295
357
  let ended = false;
358
+ /** Frames left out for their size (or unreadable) before the first kept one, and the last. */
359
+ let rejected = { count: 0, size: undefined };
360
+ let seen = 0;
296
361
  const pacer = framePacer();
297
362
  /** The latest frame on the video (written, or waiting in `pacer`). */
298
363
  let last;
@@ -300,7 +365,12 @@ export const startRecorder = (page, options) => Effect.gen(function* () {
300
365
  const onFrame = ({ data, timestamp, }) => {
301
366
  if (ended)
302
367
  return;
303
- const ms = gate.admit(jpegSize(data), timestamp);
368
+ seen++;
369
+ const size = jpegSize(data);
370
+ if (gate.first() === undefined &&
371
+ (size === undefined || !fits(size, options.size, options.window)))
372
+ rejected = { count: rejected.count + 1, size };
373
+ const ms = gate.admit(size, timestamp);
304
374
  if (ms === undefined)
305
375
  return;
306
376
  const now = pacer.add(data, ms);
@@ -312,16 +382,70 @@ export const startRecorder = (page, options) => Effect.gen(function* () {
312
382
  if (now.length > 0)
313
383
  Deferred.doneUnsafe(first, Exit.succeed(gate.first()));
314
384
  };
315
- yield* Effect.acquireRelease(Effect.tryPromise({
385
+ // Boundary: Playwright's screencast is a promise API, and the tab tells of loads by events.
386
+ const cast = () => page.screencast.start({
316
387
  // Two pixels more than the video, so the page's odd last row or column comes as it is:
317
388
  // the screencast shrinks, resampling, a frame not smaller than the size it is asked for
318
- // (1206x2043 for 1206x2043, as for 1206x2042; not for 1206x2044).
319
- try: () => page.screencast.start({
320
- size: { width: options.size.width + 2, height: options.size.height + 2 },
321
- onFrame,
389
+ // (1206x2043 for 1206x2043, as for 1206x2042; not for 1206x2044). From a window larger
390
+ // than the viewport, as large as the window, so the viewport in its corner is not shrunk.
391
+ size: {
392
+ width: Math.max(options.size.width, options.window?.width ?? 0) + 2,
393
+ height: Math.max(options.size.height, options.window?.height ?? 0) + 2,
394
+ },
395
+ onFrame,
396
+ });
397
+ let casting;
398
+ let released = false;
399
+ let restarting = Promise.resolve();
400
+ /** Why the screencast could not be started again on a tab still open, once it could not. */
401
+ let restartFailed;
402
+ /**
403
+ * Starts the screencast again, after the restarts asked for before; it sends the page as it is
404
+ * then. Chrome's headless mode (158, macOS) may send no frame of a document the tab loads after
405
+ * the screencast started: the video would show the page before it for good.
406
+ */
407
+ const restart = () => {
408
+ restarting = restarting
409
+ .then(async () => {
410
+ if (released)
411
+ return;
412
+ const previous = casting;
413
+ casting = undefined;
414
+ await previous?.dispose().catch(() => undefined);
415
+ let firstError;
416
+ for (let attempt = 0; attempt < 2 && !released && casting === undefined; attempt++)
417
+ try {
418
+ casting = await cast();
419
+ }
420
+ catch (error) {
421
+ firstError ??= error;
422
+ // Playwright counts a start that failed as started: stopped first, it can start again.
423
+ await page.screencast.stop().catch(() => undefined);
424
+ // A tab that closed is told of as such (the session's `crashed`), not as this.
425
+ if (attempt === 1 && !page.isClosed())
426
+ restartFailed ??= String(firstError).split('\n')[0];
427
+ }
428
+ })
429
+ .catch(() => undefined);
430
+ };
431
+ yield* Effect.acquireRelease(Effect.tryPromise({
432
+ try: async () => {
433
+ casting = await cast();
434
+ page.on('domcontentloaded', restart);
435
+ page.on('load', restart);
436
+ },
437
+ catch: (error) => new RecordingFailed({
438
+ reason: 'no_frames',
439
+ message: `the screencast did not start: ${String(error).split('\n')[0]}`,
440
+ cause: error,
322
441
  }),
323
- catch: (error) => new Error(`the screencast did not start: ${String(error).split('\n')[0]}`),
324
- }), (listening) => Effect.tryPromise(() => listening.dispose()).pipe(Effect.timeoutOption('2 seconds'), Effect.ignore));
442
+ }), () => Effect.tryPromise(async () => {
443
+ released = true;
444
+ page.off('domcontentloaded', restart);
445
+ page.off('load', restart);
446
+ await restarting;
447
+ await casting?.dispose();
448
+ }).pipe(Effect.timeoutOption('2 seconds'), Effect.ignore));
325
449
  const finish = yield* Effect.cached(Effect.gen(function* () {
326
450
  ended = true;
327
451
  const now = yield* Clock.currentTimeMillis;
@@ -347,22 +471,48 @@ export const startRecorder = (page, options) => Effect.gen(function* () {
347
471
  }));
348
472
  return {
349
473
  firstFrame: Deferred.await(first),
350
- hold: (effect) => Effect.acquireUseRelease(Clock.currentTimeMillis.pipe(Effect.map(gate.hold)), () => effect, (release) => Clock.currentTimeMillis.pipe(Effect.map(release))),
474
+ // Frames painted while the screenshot is taken are left out; a page that paints nothing
475
+ // after it (a load whose only frame came meanwhile) would leave the frame before it on the
476
+ // video, so the screencast is started again after it, which sends the page as it is.
477
+ hold: (effect) => Effect.acquireUseRelease(Clock.currentTimeMillis.pipe(Effect.map(gate.hold)), () => effect, (release) => Clock.currentTimeMillis.pipe(Effect.map(release), Effect.andThen(Effect.sync(restart)))),
351
478
  finish,
352
479
  ready: Effect.gen(function* () {
353
480
  yield* Effect.raceFirst(Deferred.await(first), Deferred.await(exited)).pipe(Effect.timeoutOption(READY_TIMEOUT_MS));
481
+ if (endedWith === undefined && gate.first() === undefined) {
482
+ // Nothing went to ffmpeg: say what came instead, the sizes when frames were left out.
483
+ if (rejected.count > 0)
484
+ return yield* new RecordingFailed({
485
+ reason: 'frames_rejected',
486
+ message: rejectedFramesText(rejected.size, rejected.count, options.size),
487
+ });
488
+ if (seen === 0)
489
+ return yield* new RecordingFailed({
490
+ reason: 'no_frames',
491
+ message: `the tab sent no frame within ${READY_TIMEOUT_MS / 1000} s, so ffmpeg got none.`,
492
+ });
493
+ }
354
494
  const opened = yield* Effect.gen(function* () {
355
495
  while (endedWith === undefined && !(yield* fs.exists(partial)))
356
496
  yield* Effect.sleep(READY_POLL);
357
497
  }).pipe(Effect.ignore, Effect.timeoutOption(READY_TIMEOUT_MS));
358
498
  if (endedWith !== undefined)
359
- return yield* Effect.fail(new Error(`${ffmpegEnded(endedWith)}.`));
499
+ return yield* new RecordingFailed({
500
+ reason: 'encoder',
501
+ message: `${ffmpegEnded(endedWith)}.`,
502
+ });
360
503
  if (opened._tag === 'None')
361
- return yield* Effect.fail(new Error(`ffmpeg did not start writing the video within ${READY_TIMEOUT_MS / 1000} s.`));
504
+ return yield* new RecordingFailed({
505
+ reason: 'encoder',
506
+ message: `ffmpeg did not start writing the video within ${READY_TIMEOUT_MS / 1000} s.`,
507
+ });
362
508
  }),
363
- stopped: Effect.sync(() => ended || endedWith === undefined
509
+ stopped: Effect.sync(() => ended
364
510
  ? undefined
365
- : `the video stopped being recorded (${ffmpegEnded(endedWith)}).`),
511
+ : endedWith !== undefined
512
+ ? `the video stopped being recorded (${ffmpegEnded(endedWith)}).`
513
+ : restartFailed !== undefined
514
+ ? `the video stopped being recorded (the screencast could not be started again: ${restartFailed}).`
515
+ : undefined),
366
516
  };
367
517
  });
368
518
  /**
@@ -373,10 +523,19 @@ export const videoRecording = (video) => Effect.gen(function* () {
373
523
  const platform = yield* Effect.context();
374
524
  return {
375
525
  path: video.path,
376
- record: (page, size) => Effect.gen(function* () {
526
+ record: (page, size, window) => Effect.gen(function* () {
377
527
  const fs = yield* FileSystem.FileSystem;
378
- yield* fs.makeDirectory(video.dir, { recursive: true });
379
- return yield* startRecorder(page, { ffmpeg: video.ffmpeg, file: video.path, size });
528
+ yield* fs.makeDirectory(video.dir, { recursive: true }).pipe(Effect.mapError((error) => new RecordingFailed({
529
+ reason: 'output',
530
+ message: `the video's folder could not be made: ${error.message}`,
531
+ cause: error,
532
+ })));
533
+ return yield* startRecorder(page, {
534
+ ffmpeg: video.ffmpeg,
535
+ file: video.path,
536
+ size,
537
+ window,
538
+ });
380
539
  }).pipe(Effect.provideContext(platform)),
381
540
  };
382
541
  });
@@ -1,5 +1,6 @@
1
1
  import { Duration, Effect, Option, Schedule } from 'effect';
2
2
  import { PageActionFailed, sentTo, SITE_ICONS_MAX, siteTitle, } from '../core/index.js';
3
+ import { fitWindow } from './page.js';
3
4
  /** The live view's viewport until the viewer says how much room it has. */
4
5
  export const SIGN_IN_VIEWPORT = { width: 1280, height: 800 };
5
6
  /** The viewports a viewer may ask for, in CSS pixels: a phone's up to a large desktop's. */
@@ -101,10 +102,17 @@ export const signInBrowser = (browser, url) => Effect.gen(function* () {
101
102
  let cast;
102
103
  const open = [first];
103
104
  /** Streams `page`'s frames from now on, and stops the tab streamed before. */
104
- const stream = async (page) => {
105
+ const restream = async (page) => {
105
106
  const before = cast;
106
107
  cast = undefined;
107
108
  await before?.detach().catch(() => undefined);
109
+ if (page.isClosed() || page !== active)
110
+ return;
111
+ const shown = { ...viewport };
112
+ // The frames show the window's contents, which must hold the whole viewport (see
113
+ // `fitWindow`); where the window stays wider, they show more, the viewport in their corner.
114
+ // Boundary: this runs from Playwright's event callbacks, so as a promise.
115
+ const window = await Effect.runPromise(fitWindow(page, shown));
108
116
  if (page.isClosed() || page !== active)
109
117
  return;
110
118
  const session = await page.context().newCDPSession(page);
@@ -116,19 +124,40 @@ export const signInBrowser = (browser, url) => Effect.gen(function* () {
116
124
  latest = {
117
125
  seq: ++seq,
118
126
  jpeg: frame.data,
119
- width: Math.round(frame.metadata.deviceWidth),
120
- height: Math.round(frame.metadata.deviceHeight),
127
+ ...shown,
128
+ contents: {
129
+ width: Math.round(frame.metadata.deviceWidth),
130
+ height: Math.round(frame.metadata.deviceHeight),
131
+ },
121
132
  url: page.url(),
122
133
  };
123
134
  });
135
+ // As large as the window, so the viewport in its corner is not shrunk.
124
136
  await session.send('Page.startScreencast', {
125
137
  format: 'jpeg',
126
138
  quality: FRAME_QUALITY,
127
- maxWidth: viewport.width,
128
- maxHeight: viewport.height,
139
+ maxWidth: Math.max(shown.width, window?.width ?? 0),
140
+ maxHeight: Math.max(shown.height, window?.height ?? 0),
129
141
  everyNthFrame: 1,
130
142
  });
131
143
  };
144
+ /** `restream`, one at a time, so two never both stream (one of them never stopped). */
145
+ let streaming = Promise.resolve();
146
+ const stream = (page) => (streaming = streaming.catch(() => undefined).then(() => restream(page)));
147
+ /**
148
+ * Starts the stream again whenever `page` loads a document: Chrome (158) sends no frame of a
149
+ * new document to a screencast started on the one before, so the live view would keep showing
150
+ * the page it left (the sign-in form, after the app redirects). On its DOM and once it loaded,
151
+ * so a page slow to load still shows as soon as it can.
152
+ */
153
+ const follow = (page) => {
154
+ const again = () => {
155
+ if (page === active)
156
+ stream(page).catch(() => undefined);
157
+ };
158
+ page.on('domcontentloaded', again);
159
+ page.on('load', again);
160
+ };
132
161
  /** Makes `page` the one shown and driven. */
133
162
  const activate = (page) => {
134
163
  active = page;
@@ -136,6 +165,7 @@ export const signInBrowser = (browser, url) => Effect.gen(function* () {
136
165
  };
137
166
  context.on('page', (page) => {
138
167
  open.push(page);
168
+ follow(page);
139
169
  page.setViewportSize(viewport).catch(() => undefined);
140
170
  page.on('close', () => {
141
171
  open.splice(open.indexOf(page), 1);
@@ -151,6 +181,7 @@ export const signInBrowser = (browser, url) => Effect.gen(function* () {
151
181
  if (active === first && last !== undefined)
152
182
  activate(last);
153
183
  });
184
+ follow(first);
154
185
  yield* attempt(() => stream(first));
155
186
  // A page that is slow or fails to load still opens: the person sees what it shows.
156
187
  yield* attempt(() => first.goto(url, { timeout: SIGN_IN_LOAD_TIMEOUT_MS })).pipe(Effect.ignore);
@@ -1,5 +1,5 @@
1
1
  {
2
- "id": "2026-11-20T22:33:17.848Z-f23b348d",
3
- "builtAt": "2026-11-20T22:33:17.848Z",
4
- "commit": "dc1484a8aafb8268724d9cbbb5612f980dbcefa9"
2
+ "id": "2026-11-26T15:11:17.849Z-bed7cd7b",
3
+ "builtAt": "2026-11-26T15:11:17.849Z",
4
+ "commit": "f5f1d3478c3dcd2c62d148e9b53aad78e881d3c6"
5
5
  }
@@ -33,12 +33,12 @@ const usage = (message) => Effect.fail(new Failure({ code: ExitCode.Usage, reaso
33
33
  const stub = (name, description) => Command.make(name, { json }, (flags) => handle(flags.json)(Effect.fail(notImplemented(name)))).pipe(Command.withDescription(description));
34
34
  const formatDoctorHuman = (report) => report.checks
35
35
  .flatMap((check) => [
36
- `${check.ok ? '✓' : check.severity === 'warning' ? '!' : '✗'} ${check.id.padEnd(8)} ${check.detail}`,
36
+ `${check.ok ? '✓' : check.severity === 'warning' ? '!' : '✗'} ${check.id.padEnd(9)} ${check.detail}`,
37
37
  ...(check.fix
38
38
  ? [
39
- ` Fix: ${check.fix.action}`,
40
- ...(check.fix.command ? [` Run: ${check.fix.command}`] : []),
41
- ` Why: ${check.fix.why}`,
39
+ ` Fix: ${check.fix.action}`,
40
+ ...(check.fix.command ? [` Run: ${check.fix.command}`] : []),
41
+ ` Why: ${check.fix.why}`,
42
42
  ]
43
43
  : []),
44
44
  ])
@@ -1,6 +1,6 @@
1
1
  import { Effect, type FileSystem, type Path } from 'effect';
2
2
  import { type FfmpegLookup } from '../browser-playwright/index.js';
3
- import { Browser, type BrowserInfo } from '../core/index.js';
3
+ import { Browser, type BrowserInfo, type RecordingCheck } from '../core/index.js';
4
4
  import type { DoctorCheck, DoctorReport } from '../schema/index.js';
5
5
  import { type BuildInfo } from './build-info.js';
6
6
  import { PackageInfo } from './package-info.js';
@@ -17,6 +17,11 @@ export declare const checkNode: (current: string, range: string) => DoctorCheck;
17
17
  export declare const checkBrowser: (found: BrowserInfo | undefined, installCommand: string) => DoctorCheck;
18
18
  /** A failure: every run is recorded as video, so without ffmpeg no run starts. */
19
19
  export declare const checkVideo: (lookup: FfmpegLookup, installCommand: string) => DoctorCheck;
20
+ /**
21
+ * The test recording (`Browser.checkRecording`): a failure, said by what went wrong, since a run
22
+ * that cannot be recorded does not start. `ffmpegCommand` downloads Playwright's ffmpeg again.
23
+ */
24
+ export declare const checkRecorded: (result: RecordingCheck, ffmpegCommand: string) => DoctorCheck;
20
25
  export declare const checkDisk: (path: string, freeBytes: number | undefined) => DoctorCheck;
21
26
  /** The host settings as set, trimmed; empty when unset. */
22
27
  export interface HostSettings {
@@ -68,6 +68,51 @@ export const checkVideo = (lookup, installCommand) => lookup.found
68
68
  why: 'screw-bugs records every browser session as a video with it; runs need that video.',
69
69
  },
70
70
  };
71
+ /** Where to report a recording that fails on a machine that has everything it needs. */
72
+ const ISSUES_URL = 'https://github.com/uxstudioteam/screw-bugs/issues';
73
+ /**
74
+ * The test recording (`Browser.checkRecording`): a failure, said by what went wrong, since a run
75
+ * that cannot be recorded does not start. `ffmpegCommand` downloads Playwright's ffmpeg again.
76
+ */
77
+ export const checkRecorded = (result, ffmpegCommand) => {
78
+ if (result.ok)
79
+ return { id: 'recording', ok: true, detail: result.detail };
80
+ const failed = (detail, fix) => ({
81
+ id: 'recording',
82
+ ok: false,
83
+ detail: `${detail}: ${result.problem.charAt(0).toLowerCase()}${result.problem.slice(1).replace(/\.$/, '')}.`,
84
+ ...(fix ? { fix } : {}),
85
+ });
86
+ const why = 'Every run is recorded as a video; a session that cannot be recorded does not run.';
87
+ switch (result.reason) {
88
+ case 'frames_rejected':
89
+ return failed('A test recording got no frame of the right size', {
90
+ action: `Report this, with your OS and browser version, at ${ISSUES_URL}.`,
91
+ why: `${why} The browser's window showed less (or more) than the page it was given.`,
92
+ });
93
+ case 'no_frames':
94
+ return failed('A test recording got no frame from the browser', {
95
+ action: `Update the browser; if it still fails, report this at ${ISSUES_URL}.`,
96
+ why,
97
+ });
98
+ case 'encoder':
99
+ return failed("Playwright's ffmpeg could not encode a test recording", {
100
+ action: "Download Playwright's ffmpeg again with the command.",
101
+ command: ffmpegCommand,
102
+ why,
103
+ });
104
+ case 'output':
105
+ return failed('A test recording could not be saved or read back', {
106
+ action: 'Check that the temporary folder is writable and the disk has room.',
107
+ why,
108
+ });
109
+ case 'browser':
110
+ return failed('A test recording could not open a browser session', {
111
+ action: `Check that the browser starts on this machine; if it does, report this at ${ISSUES_URL}.`,
112
+ why,
113
+ });
114
+ }
115
+ };
71
116
  export const checkDisk = (path, freeBytes) => {
72
117
  if (freeBytes === undefined) {
73
118
  return {
@@ -170,13 +215,16 @@ export const runDoctor = (projectRoot, lookupFfmpeg = findFfmpeg, update) => Eff
170
215
  tailnetCheck,
171
216
  ], { concurrency: 'unbounded' });
172
217
  const installCommand = found ? '' : yield* installBrowserCommand;
173
- const ffmpegCommand = ffmpeg.found ? '' : yield* installFfmpegCommand;
218
+ const ffmpegCommand = yield* installFfmpegCommand;
219
+ // Only with a browser and ffmpeg: without them, their own checks say what is missing.
220
+ const recorded = found !== undefined && ffmpeg.found ? yield* browser.checkRecording : undefined;
174
221
  const checks = [
175
222
  checkRunning(name, Option.match(running, { onNone: () => version, onSome: (found) => found.version }), Option.getOrUndefined(running)?.build),
176
223
  // Boundary: the version of the Node running us; there is no Effect service for it.
177
224
  checkNode(process.versions.node, engines.node),
178
225
  checkBrowser(found, installCommand),
179
- checkVideo(ffmpeg, ffmpegCommand),
226
+ checkVideo(ffmpeg, ffmpeg.found ? '' : ffmpegCommand),
227
+ ...(recorded ? [checkRecorded(recorded, ffmpegCommand)] : []),
180
228
  checkDisk(projectRoot, free),
181
229
  ...(tailnet ? [tailnet] : []),
182
230
  ...(updateCheck ? [updateCheck] : []),
package/dist/cli/mcp.js CHANGED
@@ -264,6 +264,9 @@ const StartRunInput = Schema.Struct({
264
264
  'Omit for one "page loads" case ' +
265
265
  '(loads the URL, passes without an HTTP error, takes a screenshot). Step examples: ' +
266
266
  '{"action":"goto","url":"/login"}, ' +
267
+ '{"action":"goto","url":"/no-such-page","status":404} (for a page that must answer with ' +
268
+ 'an error status, such as a not-found page: that exact status passes, any other fails, ' +
269
+ '200 included; without status an HTTP error fails the case), ' +
267
270
  '{"action":"fill","target":{"label":"Email"},"value":"a@b.co"}, ' +
268
271
  '{"action":"click","target":{"role":"button","name":"Sign in"}}, ' +
269
272
  '{"action":"hover","target":{"text":"Hi there"}} (moves the pointer over it, for controls ' +
@@ -272,7 +275,7 @@ const StartRunInput = Schema.Struct({
272
275
  '{"action":"expectNoText","text":"Acme"} (passes when it does not show as text, image ' +
273
276
  'alt text or ARIA label, in the page and its frames, or with frame or target only there), ' +
274
277
  '{"action":"expectUrl","includes":"/dashboard"}, {"action":"screenshot","name":"home"}, ' +
275
- '{"action":"reload"}, ' +
278
+ '{"action":"reload"} (also takes status), ' +
276
279
  '{"action":"upload","target":{"role":"button","name":"Upload"},"files":[{"path":"fixtures/resume.pdf","about":"A 2-page PDF résumé of a fictional designer"}]}, ' +
277
280
  '{"action":"waitFor","target":{"css":".restyling"},"state":"detached"} (state visible, ' +
278
281
  'hidden, attached or detached; default visible), ' +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "screw-bugs",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
4
4
  "description": "Local browser QA for coding agents (MCP), people and CI.",
5
5
  "keywords": [
6
6
  "browser",
@@ -46,7 +46,7 @@
46
46
  "dependencies": {
47
47
  "@effect/platform-node": "^4.1.0",
48
48
  "@modelcontextprotocol/server": "2.4.0",
49
- "@screw-bugs/core": "0.1.11",
49
+ "@screw-bugs/core": "0.1.12",
50
50
  "effect": "^4.1.0",
51
51
  "playwright-core": "1.64.1"
52
52
  },