screw-bugs 0.1.8 → 0.1.9

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.
@@ -1,11 +1,12 @@
1
1
  import { Effect, FileSystem, Layer, Path, Schema } from 'effect';
2
2
  import { ChildProcessSpawner } from 'effect/process';
3
3
  import { chromium } from 'playwright-core';
4
- import { Browser, BrowserNotFound } from '../core/index.js';
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, newSession } from './page.js';
8
+ import { deviceLabel, deviceScale, launchArgs, newSession } from './page.js';
9
+ import { videoRecording } from './recorder.js';
9
10
  /** Order matters: prefer what the user already has installed. */
10
11
  const candidates = [
11
12
  { kind: 'chrome', channel: 'chrome' },
@@ -14,9 +15,10 @@ const candidates = [
14
15
  ];
15
16
  const LAUNCH_TIMEOUT_MS = 30_000;
16
17
  /** Boundary: Playwright's launch is a promise; failures are collected into BrowserNotFound. */
17
- const launch = (candidate, headed) => Effect.tryPromise(() => chromium.launch({
18
+ const launch = (candidate, headed, device) => Effect.tryPromise(() => chromium.launch({
18
19
  ...(candidate.channel ? { channel: candidate.channel } : {}),
19
20
  headless: !headed,
21
+ args: [...launchArgs(device)],
20
22
  timeout: LAUNCH_TIMEOUT_MS,
21
23
  // The CLI handles SIGINT and SIGTERM (src/cli/signals.ts) and closes the browser with its
22
24
  // scope. Playwright's own handlers would close it at once (and exit with 130 on Ctrl+C),
@@ -24,11 +26,11 @@ const launch = (candidate, headed) => Effect.tryPromise(() => chromium.launch({
24
26
  handleSIGINT: false,
25
27
  handleSIGTERM: false,
26
28
  }));
27
- /** The first browser that launches, closed with the scope. */
28
- const launchAny = (headed) => Effect.gen(function* () {
29
+ /** The first browser that launches, for sessions on `device`; closed with the scope. */
30
+ const launchAny = (headed, device = 'desktop') => Effect.gen(function* () {
29
31
  const errors = [];
30
32
  for (const candidate of candidates) {
31
- const result = yield* Effect.result(Effect.acquireRelease(launch(candidate, headed), (browser) =>
33
+ const result = yield* Effect.result(Effect.acquireRelease(launch(candidate, headed, device), (browser) =>
32
34
  // Everything it was for has ended by now; a browser that fails to close changes none of
33
35
  // it, and ends with the process.
34
36
  Effect.tryPromise(() => browser.close()).pipe(Effect.ignore)));
@@ -41,14 +43,28 @@ const launchAny = (headed) => Effect.gen(function* () {
41
43
  cause: errors,
42
44
  });
43
45
  });
44
- const open = (options) => launchAny(options.headed).pipe(Effect.map(({ candidate, browser }) => ({
46
+ /**
47
+ * How a session's video at `video` is recorded, with Playwright's ffmpeg; fails, saying what is
48
+ * missing, when there is no ffmpeg to record with.
49
+ */
50
+ const recording = (video) => findFfmpeg.pipe(Effect.flatMap((lookup) => lookup.found && lookup.path !== undefined
51
+ ? videoRecording({ ...video, ffmpeg: lookup.path })
52
+ : Effect.fail(new PageActionFailed({
53
+ message: `The session could not be recorded as video (run \`npx screw-bugs doctor\` to see what is missing): ${ffmpegProblem(lookup)}.`,
54
+ }))));
55
+ const open = (options, platform) => launchAny(options.headed, options.device).pipe(Effect.map(({ candidate, browser }) => ({
45
56
  info: {
46
57
  kind: candidate.kind,
47
58
  type: browser.browserType().name(),
48
59
  channel: candidate.channel,
49
60
  version: browser.version(),
50
61
  },
51
- newSession: (session) => newSession(browser, session.device, session.video, true, session.session),
62
+ newSession: (session) => Effect.gen(function* () {
63
+ const video = session.video === undefined
64
+ ? undefined
65
+ : yield* recording(session.video).pipe(Effect.provideContext(platform));
66
+ return yield* newSession(browser, session.device, video, true, session.session, deviceScale(options.device ?? 'desktop'));
67
+ }),
52
68
  })));
53
69
  /**
54
70
  * Launches the installed Chrome, else Edge, else Playwright's downloaded Chromium. Needs the
@@ -59,6 +75,7 @@ export const BrowserPlaywright = Layer.effect(Browser, Effect.gen(function* () {
59
75
  const fs = yield* FileSystem.FileSystem;
60
76
  const path = yield* Path.Path;
61
77
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
78
+ const platform = yield* Effect.context();
62
79
  const videoSupport = Effect.gen(function* () {
63
80
  const lookup = yield* findFfmpeg;
64
81
  if (lookup.found)
@@ -66,12 +83,12 @@ export const BrowserPlaywright = Layer.effect(Browser, Effect.gen(function* () {
66
83
  return { ok: false, problem: ffmpegProblem(lookup), command: yield* installFfmpegCommand };
67
84
  }).pipe(Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path));
68
85
  return {
69
- detect: Effect.scoped(open({ headed: false })).pipe(Effect.map((session) => session.info)),
86
+ detect: Effect.scoped(open({ headed: false }, platform)).pipe(Effect.map((session) => session.info)),
70
87
  videoSupport,
71
88
  stillVideo: (file) => findFfmpeg.pipe(Effect.flatMap((lookup) => lookup.found && lookup.path !== undefined
72
89
  ? stillVideo(lookup.path, file)
73
90
  : Effect.succeed(undefined)), Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
74
- open,
91
+ open: (options) => open(options, platform),
75
92
  deviceLabel,
76
93
  annotate: (jobs) => Effect.scoped(launchAny(false).pipe(Effect.flatMap(({ browser }) => annotateAll(browser, jobs)))),
77
94
  signIn: (url) => launchAny(false).pipe(Effect.flatMap(({ browser }) => signInBrowser(browser, url))),
@@ -1,7 +1,9 @@
1
1
  import { Effect, Schema, type Scope } from 'effect';
2
+ import type { PlatformError } from 'effect/PlatformError';
2
3
  import { type Frame, type FrameLocator, type Browser as PlaywrightBrowser, type Page } from 'playwright-core';
3
4
  import { type BrowserPage, PageActionFailed } from '../core/index.js';
4
5
  import { type Device, type Point, type VisualViewport } from '../schema/index.js';
6
+ import type { FrameSize, Recorder } from './recorder.js';
5
7
  /** Waiting for an element to appear before acting on it, unless the step gives `timeoutMs`. */
6
8
  export declare const ACTION_TIMEOUT_MS = 5000;
7
9
  /**
@@ -25,21 +27,25 @@ export declare const NAVIGATION_START_MS = 250;
25
27
  export declare const MOBILE_DEVICE = "iPhone 17";
26
28
  /** The device as reports show it; the engine is named because mobile is not real Safari. */
27
29
  export declare const deviceLabel: (device: Device) => string;
30
+ /** The device pixels per CSS pixel `device` is shown at (3 on the phone). */
31
+ export declare const deviceScale: (device: Device) => number;
28
32
  /**
29
- * Session videos fit in this box, keeping the viewport's shape. It is larger than every viewport
30
- * we set (desktop 1280x800), so videos are recorded 1:1: scaling frames down (as a 1280x720 box
31
- * once did, to 1152x720) resamples every glyph and blurs text. Chromium's screencast sends frames
32
- * in CSS pixels, so a box larger than the viewport would only pad the frame, not sharpen it.
33
+ * Chromium's flags for a browser whose sessions are on `device`: one above 1x renders at its
34
+ * device pixels (`--force-device-scale-factor`), so the screencast, which sends frames at the
35
+ * browser's own scale and ignores the emulated one, records the phone at full resolution. The
36
+ * emulated scale stays what pages see (`devicePixelRatio`) and what screenshots are taken at.
37
+ */
38
+ export declare const launchArgs: (device: Device) => ReadonlyArray<string>;
39
+ /**
40
+ * The size of a session's video: the viewport at the scale the browser renders at (`launchArgs`),
41
+ * the size of the screencast's frames, so a video is never scaled. Each side is rounded down to
42
+ * an even number, as video needs: an odd last row or column of the page (an iPhone 17's 2043rd
43
+ * row at 3x) is left out (see `ffmpegArgs`).
33
44
  */
34
- export declare const VIDEO_MAX: {
35
- readonly width: 1920;
36
- readonly height: 1080;
37
- };
38
- /** The size of a session's video for a viewport: the viewport, scaled down into `VIDEO_MAX`. */
39
45
  export declare const videoSize: (viewport: {
40
46
  readonly width: number;
41
47
  readonly height: number;
42
- }) => {
48
+ }, scale: number) => {
43
49
  width: number;
44
50
  height: number;
45
51
  };
@@ -387,28 +393,44 @@ export declare const ELSEWHERE_TIMEOUT_MS = 1000;
387
393
  /** How long a new recorded tab may take to paint its video's first frame. */
388
394
  export declare const FIRST_FRAME_TIMEOUT_MS = 2000;
389
395
  /**
390
- * When a recorded tab's video starts, in epoch ms; undefined when no frame came in time.
396
+ * When a recorded tab's video starts, in epoch ms (`first`, the recorder's first frame);
397
+ * undefined when no frame came in time.
391
398
  *
392
- * Playwright's video starts at the first frame the browser sends, not when the tab opens, and
393
- * every frame sits on the video at its paint time from there. Steps are timed from the video's
394
- * start, so it has to be known. The blank tab's own paint often comes before the browser starts
395
- * sending frames; then the first frame was the first page's, after its load, and every step came
396
- * up on the video early by that long: a field filled on the video while the walkthrough still
397
- * played the step before. So the blank tab is repainted (white and almost white, by turns) until
398
- * a frame comes, before any page of the run loads; a repaint that only arrives once a page has
399
- * loaded leaves it alone. A listener that starts after a frame is handed the latest one at once,
400
- * which for a blank tab is its first. Frame times are the browser's wall clock, the one `Clock`
401
- * reads in a run. The listener is let go of when this ends, timed out or not.
399
+ * The video starts at the first frame the browser sends, not when the tab opens, and every
400
+ * frame sits on the video at its paint time from there. Steps are timed from the video's start,
401
+ * so it has to be known. The blank tab's own paint often comes before the browser starts sending
402
+ * frames; then the first frame was the first page's, after its load, and every step came up on
403
+ * the video early by that long: a field filled on the video while the walkthrough still played
404
+ * the step before. So the blank tab is repainted (white and almost white, by turns) until a frame
405
+ * comes, before any page of the run loads; a repaint that only arrives once a page has loaded
406
+ * leaves it alone. Frame times are the browser's wall clock, the one `Clock` reads in a run.
402
407
  */
403
- export declare const firstFrameAt: (page: Page) => Effect.Effect<number | undefined, never, never>;
404
- export declare const newSession: (browser: PlaywrightBrowser, device: Device, video: {
405
- readonly dir: string;
408
+ export declare const firstFrameAt: (page: Page, first: Effect.Effect<number>) => Effect.Effect<number | undefined, never, never>;
409
+ /** Where a session's video goes, and how it is recorded (`videoRecording`). */
410
+ export interface SessionVideo {
411
+ /** The video, a `.webm`. */
406
412
  readonly path: string;
407
- } | undefined,
413
+ /** Starts recording a tab into `path` at `size`. */
414
+ readonly record: (page: Page, size: FrameSize) => Effect.Effect<Recorder, PlatformError | Error, Scope.Scope>;
415
+ }
416
+ /**
417
+ * One session: a fresh context (no cookies or storage from other runs) with one tab that every
418
+ * case of the session runs in, recorded as one continuous video. Tabs and windows a case opens
419
+ * are in the same context and are closed before the next case; only the session's own tab is
420
+ * recorded. Closed with its scope; the video is saved then too, so a run that is stopped keeps
421
+ * it.
422
+ *
423
+ * The video is recorded by screw-bugs (`startRecorder`), not Playwright's `recordVideo`, so that
424
+ * a step's screenshot never shows on it (see `recorder.ts`). Recording needs Playwright's ffmpeg:
425
+ * a session with `video` that cannot be recorded fails rather than run without one.
426
+ */
427
+ export declare const newSession: (browser: PlaywrightBrowser, device: Device, video: SessionVideo | undefined,
408
428
  /** Whether to watch the input the page gets, for recording actions; for tests to compare. */
409
429
  observed?: boolean,
410
430
  /** A saved session (an account's storage state, as JSON text) the context starts from. */
411
- savedSession?: string) => Effect.Effect<{
431
+ savedSession?: string,
432
+ /** The scale `browser` renders at (see `launchArgs`): its screencast frames, so its videos. */
433
+ renderScale?: number) => Effect.Effect<{
412
434
  page: BrowserPage;
413
435
  beginCase: (options: {
414
436
  readonly continues?: boolean;
@@ -31,16 +31,28 @@ 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
+ /** The device pixels per CSS pixel `device` is shown at (3 on the phone). */
35
+ export const deviceScale = (device) => {
36
+ const options = contextOptions(device);
37
+ return 'deviceScaleFactor' in options ? options.deviceScaleFactor : 1;
38
+ };
34
39
  /**
35
- * Session videos fit in this box, keeping the viewport's shape. It is larger than every viewport
36
- * we set (desktop 1280x800), so videos are recorded 1:1: scaling frames down (as a 1280x720 box
37
- * once did, to 1152x720) resamples every glyph and blurs text. Chromium's screencast sends frames
38
- * in CSS pixels, so a box larger than the viewport would only pad the frame, not sharpen it.
40
+ * Chromium's flags for a browser whose sessions are on `device`: one above 1x renders at its
41
+ * device pixels (`--force-device-scale-factor`), so the screencast, which sends frames at the
42
+ * browser's own scale and ignores the emulated one, records the phone at full resolution. The
43
+ * emulated scale stays what pages see (`devicePixelRatio`) and what screenshots are taken at.
39
44
  */
40
- export const VIDEO_MAX = { width: 1920, height: 1080 };
41
- /** The size of a session's video for a viewport: the viewport, scaled down into `VIDEO_MAX`. */
42
- export const videoSize = (viewport) => {
43
- const scale = Math.min(1, VIDEO_MAX.width / viewport.width, VIDEO_MAX.height / viewport.height);
45
+ export const launchArgs = (device) => {
46
+ const scale = deviceScale(device);
47
+ return scale > 1 ? [`--force-device-scale-factor=${scale}`] : [];
48
+ };
49
+ /**
50
+ * The size of a session's video: the viewport at the scale the browser renders at (`launchArgs`),
51
+ * the size of the screencast's frames, so a video is never scaled. Each side is rounded down to
52
+ * an even number, as video needs: an odd last row or column of the page (an iPhone 17's 2043rd
53
+ * row at 3x) is left out (see `ffmpegArgs`).
54
+ */
55
+ export const videoSize = (viewport, scale) => {
44
56
  const even = (n) => Math.max(2, Math.floor((n * scale) / 2) * 2);
45
57
  return { width: even(viewport.width), height: even(viewport.height) };
46
58
  };
@@ -954,7 +966,9 @@ const MeasuredOnScreen = Schema.Struct({
954
966
  const FILE_INPUT = 'input[type=file]';
955
967
  const pageOperations = (page, watch, input,
956
968
  /** How the page is drawn, for placing a press in the video (see `framePoint`). */
957
- drawn) => {
969
+ drawn,
970
+ /** Keeps what a screenshot does to the page's rendering off the video (`Recorder.hold`). */
971
+ hold) => {
958
972
  const { settle, refused } = watch;
959
973
  /** Finds the first visible match, or fails with a plain "not found". */
960
974
  const element = (target, timeout) => Effect.gen(function* () {
@@ -1815,7 +1829,7 @@ drawn) => {
1815
1829
  // page's own were (`seen`), or the page was zoomed meanwhile and the boxes cannot be placed.
1816
1830
  const scaleNow = seen === undefined ? undefined : yield* visualScaleNow;
1817
1831
  const visual = visualOf(seen, scaleNow, fullPage);
1818
- const bytes = yield* attempt(() => page.screenshot({ path, fullPage, timeout: SCREENSHOT_TIMEOUT_MS }), (error) => `Could not take a screenshot: ${firstLine(error)}`);
1832
+ const bytes = yield* hold(attempt(() => page.screenshot({ path, fullPage, timeout: SCREENSHOT_TIMEOUT_MS }), (error) => `Could not take a screenshot: ${firstLine(error)}`));
1819
1833
  const { width, height } = pngSize(bytes);
1820
1834
  const scale = state?.scale ?? (viewport ? width / viewport.width : 1);
1821
1835
  const [dx, dy] = fullPage && state ? [state.scrollX, state.scrollY] : [0, 0];
@@ -2007,59 +2021,50 @@ export const FIRST_FRAME_TIMEOUT_MS = 2_000;
2007
2021
  /** How often the blank tab is repainted until its video has a first frame. */
2008
2022
  const REPAINT_EVERY_MS = 50;
2009
2023
  /**
2010
- * When a recorded tab's video starts, in epoch ms; undefined when no frame came in time.
2024
+ * When a recorded tab's video starts, in epoch ms (`first`, the recorder's first frame);
2025
+ * undefined when no frame came in time.
2011
2026
  *
2012
- * Playwright's video starts at the first frame the browser sends, not when the tab opens, and
2013
- * every frame sits on the video at its paint time from there. Steps are timed from the video's
2014
- * start, so it has to be known. The blank tab's own paint often comes before the browser starts
2015
- * sending frames; then the first frame was the first page's, after its load, and every step came
2016
- * up on the video early by that long: a field filled on the video while the walkthrough still
2017
- * played the step before. So the blank tab is repainted (white and almost white, by turns) until
2018
- * a frame comes, before any page of the run loads; a repaint that only arrives once a page has
2019
- * loaded leaves it alone. A listener that starts after a frame is handed the latest one at once,
2020
- * which for a blank tab is its first. Frame times are the browser's wall clock, the one `Clock`
2021
- * reads in a run. The listener is let go of when this ends, timed out or not.
2027
+ * The video starts at the first frame the browser sends, not when the tab opens, and every
2028
+ * frame sits on the video at its paint time from there. Steps are timed from the video's start,
2029
+ * so it has to be known. The blank tab's own paint often comes before the browser starts sending
2030
+ * frames; then the first frame was the first page's, after its load, and every step came up on
2031
+ * the video early by that long: a field filled on the video while the walkthrough still played
2032
+ * the step before. So the blank tab is repainted (white and almost white, by turns) until a frame
2033
+ * comes, before any page of the run loads; a repaint that only arrives once a page has loaded
2034
+ * leaves it alone. Frame times are the browser's wall clock, the one `Clock` reads in a run.
2022
2035
  */
2023
- export const firstFrameAt = (page) => Effect.gen(function* () {
2024
- let frame;
2025
- let seen = () => undefined;
2026
- // Boundary: Playwright hands frames to a callback.
2027
- const first = new Promise((resolve) => {
2028
- seen = resolve;
2029
- });
2030
- yield* Effect.acquireRelease(attempt(() => page.screencast.start({
2031
- onFrame: ({ timestamp }) => {
2032
- frame ??= timestamp;
2033
- seen();
2034
- },
2035
- }), firstLine), (listening) => attempt(() => listening.dispose(), firstLine).pipe(Effect.timeoutOption(ACTION_TIMEOUT_MS), Effect.ignore));
2036
- for (let turn = 0; frame === undefined; turn++) {
2036
+ export const firstFrameAt = (page, first) => Effect.gen(function* () {
2037
+ for (let turn = 0;; turn++) {
2037
2038
  const color = turn % 2 === 1 ? '#fff' : '#fefefe';
2038
2039
  yield* attempt(() => page.evaluate(`location.href === 'about:blank' && (document.documentElement.style.backgroundColor = '${color}')`), firstLine).pipe(Effect.ignore);
2039
- yield* Effect.promise(() => first).pipe(Effect.timeoutOption(REPAINT_EVERY_MS));
2040
+ const frame = yield* first.pipe(Effect.timeoutOption(REPAINT_EVERY_MS));
2041
+ if (frame._tag === 'Some')
2042
+ return frame.value;
2040
2043
  }
2041
- return frame;
2042
- }).pipe(Effect.scoped, Effect.timeoutOption(FIRST_FRAME_TIMEOUT_MS), Effect.map((first) => (first._tag === 'Some' ? first.value : undefined)), Effect.orElseSucceed(() => undefined));
2043
- /**
2044
- * One session: a fresh context (no cookies or storage from other runs) with one tab that every
2045
- * case of the session runs in, recorded as one continuous video. Tabs and windows a case opens
2046
- * are in the same context and are closed before the next case. Closed with its scope; the video
2047
- * is saved then too, so a run that is stopped keeps it.
2048
- *
2049
- * Playwright records each tab's video separately, so only the session's own tab is kept: the
2050
- * videos of tabs the cases opened are deleted. Recording needs Playwright's ffmpeg: a session
2051
- * with `video` that cannot be recorded fails rather than run without one.
2052
- */
2044
+ }).pipe(Effect.timeoutOption(FIRST_FRAME_TIMEOUT_MS), Effect.map((first) => (first._tag === 'Some' ? first.value : undefined)));
2053
2045
  /** A saved storage state as Playwright takes it; its cookies and origins are Playwright's own. */
2054
2046
  const StorageStateShape = Schema.Struct({
2055
2047
  cookies: Schema.Array(Schema.Unknown),
2056
2048
  origins: Schema.Array(Schema.Unknown),
2057
2049
  });
2050
+ /**
2051
+ * One session: a fresh context (no cookies or storage from other runs) with one tab that every
2052
+ * case of the session runs in, recorded as one continuous video. Tabs and windows a case opens
2053
+ * are in the same context and are closed before the next case; only the session's own tab is
2054
+ * recorded. Closed with its scope; the video is saved then too, so a run that is stopped keeps
2055
+ * it.
2056
+ *
2057
+ * The video is recorded by screw-bugs (`startRecorder`), not Playwright's `recordVideo`, so that
2058
+ * a step's screenshot never shows on it (see `recorder.ts`). Recording needs Playwright's ffmpeg:
2059
+ * a session with `video` that cannot be recorded fails rather than run without one.
2060
+ */
2058
2061
  export const newSession = (browser, device, video,
2059
2062
  /** Whether to watch the input the page gets, for recording actions; for tests to compare. */
2060
2063
  observed = true,
2061
2064
  /** A saved session (an account's storage state, as JSON text) the context starts from. */
2062
- savedSession) => Effect.gen(function* () {
2065
+ savedSession,
2066
+ /** The scale `browser` renders at (see `launchArgs`): its screencast frames, so its videos. */
2067
+ renderScale = 1) => Effect.gen(function* () {
2063
2068
  const clock = yield* Effect.clockWith((clock) => Effect.succeed(clock));
2064
2069
  const options = contextOptions(device);
2065
2070
  const failed = (error) => `Could not open a new browser tab: ${firstLine(error)}`;
@@ -2067,34 +2072,38 @@ savedSession) => Effect.gen(function* () {
2067
2072
  const storageState = savedSession === undefined
2068
2073
  ? undefined
2069
2074
  : yield* Schema.decodeUnknownEffect(Schema.fromJsonString(StorageStateShape))(savedSession).pipe(Effect.mapError((cause) => new PageActionFailed({ message: 'The saved session is not valid.', cause })));
2070
- /** A context with its tab; with `record`, both are recorded. Boundary: Playwright promises. */
2071
- const open = (record) => Effect.acquireRelease(attempt(() => browser.newContext({
2075
+ /** A context with its tab. Boundary: Playwright promises. */
2076
+ const { context, page } = yield* Effect.acquireRelease(attempt(() => browser.newContext({
2072
2077
  ...options,
2073
2078
  ...(storageState !== undefined
2074
2079
  ? {
2075
2080
  storageState: storageState,
2076
2081
  }
2077
2082
  : {}),
2078
- ...(record && video !== undefined
2079
- ? { recordVideo: { dir: video.dir, size: videoSize(options.viewport) } }
2080
- : {}),
2081
2083
  }), failed),
2082
2084
  // Only reached when opening it went wrong, or once the session closed it already
2083
- // (`closeAll`): a failure to close it again cannot change what the session found.
2085
+ // (`close`): a failure to close it again cannot change what the session found.
2084
2086
  (context) => attempt(() => context.close(), firstLine).pipe(Effect.ignore)).pipe(Effect.flatMap((context) => attempt(() => context.newPage(), failed).pipe(Effect.map((page) => ({ context, page })))));
2085
2087
  // Video is not optional: a session that cannot be recorded does not run.
2086
- const { context, page } = yield* video === undefined
2087
- ? open(false)
2088
- : open(true).pipe(Effect.mapError((error) => new PageActionFailed({
2089
- message: `The session could not be recorded as video (run \`npx screw-bugs doctor\` to see what is missing): ${error.message}`,
2088
+ const recorder = video === undefined
2089
+ ? undefined
2090
+ : yield* video.record(page, videoSize(options.viewport, renderScale)).pipe(Effect.mapError((error) => new PageActionFailed({
2091
+ message: `The session could not be recorded as video (run \`npx screw-bugs doctor\` to see what is missing): ${firstLine(error)}`,
2092
+ cause: error,
2090
2093
  })));
2091
2094
  const tabOpenedAt = clock.currentTimeMillisUnsafe();
2092
- const videoStartedAt = video === undefined ? tabOpenedAt : ((yield* firstFrameAt(page)) ?? tabOpenedAt);
2095
+ const videoStartedAt = recorder === undefined
2096
+ ? tabOpenedAt
2097
+ : ((yield* firstFrameAt(page, recorder.firstFrame)) ?? tabOpenedAt);
2098
+ // An ffmpeg that cannot write the video ends once it has a frame: nothing runs unrecorded.
2099
+ if (recorder !== undefined)
2100
+ yield* recorder.ready.pipe(Effect.mapError((error) => new PageActionFailed({
2101
+ message: `The session could not be recorded as video (run \`npx screw-bugs doctor\` to see what is missing): ${error.message}`,
2102
+ cause: error,
2103
+ })));
2093
2104
  // Boundary: Playwright reports crashes and closes through event callbacks.
2094
2105
  let closing = false;
2095
2106
  let crashed;
2096
- const opened = [];
2097
- context.on('page', (other) => opened.push(other));
2098
2107
  page.on('crash', () => {
2099
2108
  crashed ??= 'the page crashed.';
2100
2109
  });
@@ -2106,33 +2115,14 @@ savedSession) => Effect.gen(function* () {
2106
2115
  if (!closing)
2107
2116
  crashed ??= 'the browser closed.';
2108
2117
  });
2109
- /** Closes the context, then saves the session's video and deletes the other tabs' videos. */
2110
- let closed;
2111
- const closeAll = () => (closed ??= (async () => {
2118
+ /** Closes the context, then ends and saves the session's video. */
2119
+ const closeAll = yield* Effect.cached(Effect.gen(function* () {
2112
2120
  closing = true;
2113
- await context.close().catch(() => undefined);
2114
- const recorded = page.video();
2115
- if (video === undefined)
2116
- return undefined;
2117
- if (recorded === null)
2118
- return 'The session was not recorded.';
2119
- try {
2120
- await recorded.saveAs(video.path);
2121
- await recorded.delete();
2122
- }
2123
- catch (error) {
2124
- return `The video could not be saved: ${firstLine(error)}`;
2125
- }
2126
- for (const other of opened)
2127
- if (other !== page)
2128
- await other
2129
- .video()
2130
- ?.delete()
2131
- .catch(() => undefined);
2132
- return undefined;
2133
- })());
2121
+ yield* attempt(() => context.close(), firstLine).pipe(Effect.ignore);
2122
+ return recorder === undefined ? undefined : yield* recorder.finish;
2123
+ }));
2134
2124
  // Closing never fails the session: what went wrong is said about the video, which it is for.
2135
- const close = attempt(closeAll, (error) => `The video could not be saved: ${firstLine(error)}`).pipe(Effect.catchTag('PageActionFailed', (error) => Effect.succeed(video === undefined ? undefined : error.message)), Effect.timeoutOption(CLOSE_TIMEOUT_MS), Effect.map((problem) => ({
2125
+ const close = closeAll.pipe(Effect.timeoutOption(CLOSE_TIMEOUT_MS), Effect.map((problem) => ({
2136
2126
  videoProblem: problem._tag === 'Some'
2137
2127
  ? problem.value
2138
2128
  : `The video was not saved within ${seconds(CLOSE_TIMEOUT_MS)}.`,
@@ -2146,13 +2136,20 @@ savedSession) => Effect.gen(function* () {
2146
2136
  atOrigin: device === 'mobile' && observed ? yield* widgetAtOrigin(browser) : false,
2147
2137
  };
2148
2138
  return {
2149
- page: pageOperations(page, watch, input, drawn),
2139
+ page: pageOperations(page, watch, input, drawn,
2140
+ // Only a capture in device pixels disturbs the screencast, also in a browser rendering at
2141
+ // that scale: one at 1x (a desktop's) sends the page as it is, and holding would only
2142
+ // drop frames of what it does meanwhile.
2143
+ recorder !== undefined && deviceScale(device) > 1 ? recorder.hold : (effect) => effect),
2150
2144
  beginCase: (options) => Effect.tryPromise(async () => {
2151
2145
  for (const other of context.pages())
2152
2146
  if (other !== page)
2153
2147
  await other.close();
2154
2148
  }).pipe(Effect.timeoutOption(ACTION_TIMEOUT_MS), Effect.ignore, Effect.andThen(Effect.sync(() => watch.reset(options?.continues === true)))),
2155
- crashed: Effect.sync(() => crashed),
2149
+ // A recording that stopped ends the session as a crash does: it does not go on unrecorded.
2150
+ crashed: Effect.suspend(() => crashed !== undefined || recorder === undefined
2151
+ ? Effect.succeed(crashed)
2152
+ : recorder.stopped),
2156
2153
  videoStartedAt,
2157
2154
  close,
2158
2155
  };
@@ -0,0 +1,154 @@
1
+ import { Effect, FileSystem } from 'effect';
2
+ import { ChildProcessSpawner } from 'effect/process';
3
+ import type { Page } from 'playwright-core';
4
+ /**
5
+ * A session's video, recorded by screw-bugs itself rather than by Playwright's `recordVideo`:
6
+ * the tab's screencast frames (JPEG, from `page.screencast`) go to Playwright's ffmpeg as
7
+ * Matroska on its stdin, which writes VP9 WebM at a constant frame rate, as Playwright's own
8
+ * recorder does (same container, encoder settings, frame times and last frame).
9
+ *
10
+ * Two frames are left out, so the video only ever shows the page as it renders on its own:
11
+ *
12
+ * - A frame that does not fit the video's size (`fits`). Chromium sends frames at the browser's
13
+ * own scale whatever size is asked for, except around a device-pixel capture on an emulated
14
+ * phone in a browser at 1x, where one may come at full device size (3x); Playwright's recorder
15
+ * crops it into the video, which shows the page's top left corner magnified for one frame.
16
+ * - A frame painted while a screenshot is taken (`hold`). Every device-pixel capture (the step
17
+ * screenshots) changes how the page renders for a moment: on a phone, text comes out crisper
18
+ * and darker, then pale again, a flicker at every step. Such a frame is painted during the
19
+ * capture and often only arrives after it, so frames are judged by when they were painted.
20
+ *
21
+ * The video then holds the last frame it kept, as for any frame the browser does not send.
22
+ */
23
+ /**
24
+ * The most frames a second the video has (Playwright's recorder's rate). Unlike Playwright's, it
25
+ * has only the frames the page changed in (the screencast sends one only then), so a still page
26
+ * costs next to nothing to encode and store (`framePacer`).
27
+ */
28
+ export declare const VIDEO_FPS = 25;
29
+ /**
30
+ * How much smaller than the video a frame may be (Chromium rounds the screencast's size). One a
31
+ * pixel larger is the page's odd last row or column, which the video leaves out (`videoSize`).
32
+ */
33
+ export declare const FRAME_SLACK = 4;
34
+ /** How long the video shows its last frame at least, after it came (as in Playwright). */
35
+ export declare const LAST_FRAME_MS = 1000;
36
+ /**
37
+ * How many frames may wait for ffmpeg (seconds of video at `VIDEO_FPS`, some MB of JPEG). While
38
+ * it is that far behind, new frames are dropped and the video holds the last one it has.
39
+ */
40
+ export declare const BACKLOG_FRAMES: number;
41
+ /** How long ffmpeg may take, after the first frame, to open the video it writes. */
42
+ export declare const READY_TIMEOUT_MS = 3000;
43
+ export interface FrameSize {
44
+ readonly width: number;
45
+ readonly height: number;
46
+ }
47
+ /** A JPEG's size, from its first start-of-frame segment; undefined when it has none. */
48
+ 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;
51
+ /**
52
+ * Which frames go on the video, and where: a frame's time on the video is its paint time (epoch
53
+ * ms) after the first kept frame's, so the video starts at its first frame, as Playwright's does.
54
+ */
55
+ export declare const frameGate: (video: FrameSize) => {
56
+ /** A screenshot starts being taken `at`; call the result when it was taken. */
57
+ hold: (at: number) => (end: number) => void;
58
+ /**
59
+ * 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).
62
+ */
63
+ admit: (size: FrameSize | undefined, timestamp: number) => number | undefined;
64
+ /** When the first kept frame was painted, in epoch ms. */
65
+ first: () => number | undefined;
66
+ /** The time on the video of a frame painted at `timestamp`. */
67
+ at: (timestamp: number) => number;
68
+ };
69
+ export type FrameGate = ReturnType<typeof frameGate>;
70
+ /**
71
+ * When the video's last frame goes again, to end it: as Playwright does, at least `LAST_FRAME_MS`
72
+ * after it was painted, or as long after as the session went on without a new one.
73
+ */
74
+ export declare const lastFrameTime: (paintedAt: number, sinceItCameMs: number) => number;
75
+ /**
76
+ * At most one frame for each `1000 / VIDEO_FPS` ms of the video, never losing the page's latest
77
+ * state: the first frame in a slot after the last written one is written at once; a later one in
78
+ * that slot waits, replacing the one waiting, and is written at the start of the next slot when a
79
+ * frame comes after that slot, or at the end (`flush`). `ms` (time on the video) only grows.
80
+ */
81
+ export declare const framePacer: <F>() => {
82
+ /** What to write now, in order, for a frame at `ms` on the video. */
83
+ add: (frame: F, ms: number) => Array<{
84
+ readonly frame: F;
85
+ readonly ms: number;
86
+ }>;
87
+ /** The frame still waiting, if one is, to write before the video ends. */
88
+ flush: () => {
89
+ frame: F;
90
+ ms: number;
91
+ }[];
92
+ };
93
+ /** EBML's variable-length size. */
94
+ export declare const vint: (value: number) => Uint8Array;
95
+ /** The stream's start: its EBML header, a segment of unknown size, its info and its track. */
96
+ export declare const matroskaHeader: () => Uint8Array;
97
+ /** One frame: a cluster at `ms` holding it as a key frame of track 1. */
98
+ export declare const matroskaFrame: (ms: number, jpeg: Uint8Array) => Uint8Array;
99
+ /** Playwright's ffmpeg arguments for its recorder, writing WebM to `file`. */
100
+ export declare const ffmpegArgs: (size: FrameSize, file: string) => ReadonlyArray<string>;
101
+ export interface Recorder {
102
+ /** When the first frame on the video was painted, in epoch ms; waits for it. */
103
+ readonly firstFrame: Effect.Effect<number>;
104
+ /** Runs `effect` (a screenshot) keeping the frames painted meanwhile off the video. */
105
+ readonly hold: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
106
+ /**
107
+ * Ends the video and saves it at its path: why it could not be, else undefined. Call once the
108
+ * tab is closed, so no frame comes after. Only the first call ends it; later ones say the same.
109
+ */
110
+ readonly finish: Effect.Effect<string | undefined>;
111
+ /**
112
+ * Waits, after the first frame (or once there is none), until ffmpeg has opened the video it
113
+ * writes, for at most `READY_TIMEOUT_MS`; fails when ffmpeg has ended instead, or has not
114
+ * opened it by then (no frame came, or it is stuck).
115
+ */
116
+ readonly ready: Effect.Effect<void, Error>;
117
+ /** Why the video stopped being recorded before `finish`, once ffmpeg ended early. */
118
+ readonly stopped: Effect.Effect<string | undefined>;
119
+ }
120
+ /**
121
+ * 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.
125
+ */
126
+ export declare const startRecorder: (page: Page, options: {
127
+ readonly ffmpeg: string;
128
+ readonly file: string;
129
+ readonly size: FrameSize;
130
+ }) => Effect.Effect<{
131
+ firstFrame: Effect.Effect<number, never, never>;
132
+ hold: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
133
+ finish: Effect.Effect<string | undefined, never, never>;
134
+ ready: Effect.Effect<undefined, Error, never>;
135
+ stopped: Effect.Effect<string | undefined, never, never>;
136
+ }, Error | import("effect/PlatformError").PlatformError, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | import("effect/Scope").Scope>;
137
+ /**
138
+ * How a session with a video at `path` (in the folder `dir`, made when missing) is recorded with
139
+ * the ffmpeg at `ffmpeg`, on the platform this runs on.
140
+ */
141
+ export declare const videoRecording: (video: {
142
+ readonly dir: string;
143
+ readonly path: string;
144
+ readonly ffmpeg: string;
145
+ }) => Effect.Effect<{
146
+ path: string;
147
+ record: (page: Page, size: FrameSize) => Effect.Effect<{
148
+ firstFrame: Effect.Effect<number, never, never>;
149
+ hold: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
150
+ finish: Effect.Effect<string | undefined, never, never>;
151
+ ready: Effect.Effect<undefined, Error, never>;
152
+ stopped: Effect.Effect<string | undefined, never, never>;
153
+ }, Error | import("effect/PlatformError").PlatformError, import("effect/Scope").Scope>;
154
+ }, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem>;
@@ -0,0 +1,382 @@
1
+ import { Clock, Deferred, Effect, Exit, FileSystem, Queue, Stream } from 'effect';
2
+ import { ChildProcess, ChildProcessSpawner } from 'effect/process';
3
+ /**
4
+ * A session's video, recorded by screw-bugs itself rather than by Playwright's `recordVideo`:
5
+ * the tab's screencast frames (JPEG, from `page.screencast`) go to Playwright's ffmpeg as
6
+ * Matroska on its stdin, which writes VP9 WebM at a constant frame rate, as Playwright's own
7
+ * recorder does (same container, encoder settings, frame times and last frame).
8
+ *
9
+ * Two frames are left out, so the video only ever shows the page as it renders on its own:
10
+ *
11
+ * - A frame that does not fit the video's size (`fits`). Chromium sends frames at the browser's
12
+ * own scale whatever size is asked for, except around a device-pixel capture on an emulated
13
+ * phone in a browser at 1x, where one may come at full device size (3x); Playwright's recorder
14
+ * crops it into the video, which shows the page's top left corner magnified for one frame.
15
+ * - A frame painted while a screenshot is taken (`hold`). Every device-pixel capture (the step
16
+ * screenshots) changes how the page renders for a moment: on a phone, text comes out crisper
17
+ * and darker, then pale again, a flicker at every step. Such a frame is painted during the
18
+ * capture and often only arrives after it, so frames are judged by when they were painted.
19
+ *
20
+ * The video then holds the last frame it kept, as for any frame the browser does not send.
21
+ */
22
+ /**
23
+ * The most frames a second the video has (Playwright's recorder's rate). Unlike Playwright's, it
24
+ * has only the frames the page changed in (the screencast sends one only then), so a still page
25
+ * costs next to nothing to encode and store (`framePacer`).
26
+ */
27
+ export const VIDEO_FPS = 25;
28
+ /**
29
+ * How much smaller than the video a frame may be (Chromium rounds the screencast's size). One a
30
+ * pixel larger is the page's odd last row or column, which the video leaves out (`videoSize`).
31
+ */
32
+ export const FRAME_SLACK = 4;
33
+ /** How long the video shows its last frame at least, after it came (as in Playwright). */
34
+ export const LAST_FRAME_MS = 1_000;
35
+ /** How long ffmpeg gets to end after it was asked to stop, before it is killed. */
36
+ const FFMPEG_KILL_AFTER = '2 seconds';
37
+ /**
38
+ * How many frames may wait for ffmpeg (seconds of video at `VIDEO_FPS`, some MB of JPEG). While
39
+ * it is that far behind, new frames are dropped and the video holds the last one it has.
40
+ */
41
+ export const BACKLOG_FRAMES = 10 * VIDEO_FPS;
42
+ /** How long ffmpeg may take, after the first frame, to open the video it writes. */
43
+ export const READY_TIMEOUT_MS = 3_000;
44
+ /** How often whether it has is looked at. */
45
+ const READY_POLL = '50 millis';
46
+ /** A JPEG's size, from its first start-of-frame segment; undefined when it has none. */
47
+ export const jpegSize = (bytes) => {
48
+ if (bytes[0] !== 0xff || bytes[1] !== 0xd8)
49
+ return undefined;
50
+ const u16 = (at) => (bytes[at] << 8) | bytes[at + 1];
51
+ let at = 2;
52
+ while (at + 3 < bytes.length) {
53
+ if (bytes[at] !== 0xff)
54
+ return undefined;
55
+ const marker = bytes[at + 1];
56
+ // Fill bytes before a marker.
57
+ if (marker === 0xff) {
58
+ at += 1;
59
+ continue;
60
+ }
61
+ // Markers without a length.
62
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) {
63
+ at += 2;
64
+ continue;
65
+ }
66
+ // Start of frame (baseline, progressive and the rest), not DHT, JPG or DAC.
67
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc)
68
+ return at + 8 < bytes.length ? { height: u16(at + 5), width: u16(at + 7) } : undefined;
69
+ // Start of scan or end of image: no frame header came first.
70
+ if (marker === 0xda || marker === 0xd9)
71
+ return undefined;
72
+ at += 2 + u16(at + 2);
73
+ }
74
+ return undefined;
75
+ };
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 &&
79
+ frame.width >= video.width - FRAME_SLACK &&
80
+ frame.height >= video.height - FRAME_SLACK;
81
+ /**
82
+ * Which frames go on the video, and where: a frame's time on the video is its paint time (epoch
83
+ * ms) after the first kept frame's, so the video starts at its first frame, as Playwright's does.
84
+ */
85
+ export const frameGate = (video) => {
86
+ /** Screenshots being taken (`end` undefined) or taken, by when, in epoch ms. */
87
+ let holds = [];
88
+ let first;
89
+ let lastMs;
90
+ const held = (timestamp) => holds.some((h) => timestamp >= h.start && (h.end === undefined || timestamp <= h.end));
91
+ return {
92
+ /** A screenshot starts being taken `at`; call the result when it was taken. */
93
+ hold: (at) => {
94
+ const window = { start: at, end: undefined };
95
+ holds.push(window);
96
+ return (end) => {
97
+ window.end = Math.max(end, at);
98
+ };
99
+ },
100
+ /**
101
+ * 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).
104
+ */
105
+ 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)
110
+ return undefined;
111
+ first ??= timestamp;
112
+ lastMs = ms;
113
+ // A screenshot taken before this frame was painted cannot hold back any later frame.
114
+ holds = holds.filter((h) => h.end === undefined || h.end >= timestamp);
115
+ return ms;
116
+ },
117
+ /** When the first kept frame was painted, in epoch ms. */
118
+ first: () => first,
119
+ /** The time on the video of a frame painted at `timestamp`. */
120
+ at: (timestamp) => Math.round(timestamp - (first ?? timestamp)),
121
+ };
122
+ };
123
+ /**
124
+ * When the video's last frame goes again, to end it: as Playwright does, at least `LAST_FRAME_MS`
125
+ * after it was painted, or as long after as the session went on without a new one.
126
+ */
127
+ export const lastFrameTime = (paintedAt, sinceItCameMs) => paintedAt + Math.max(sinceItCameMs, LAST_FRAME_MS);
128
+ /**
129
+ * At most one frame for each `1000 / VIDEO_FPS` ms of the video, never losing the page's latest
130
+ * state: the first frame in a slot after the last written one is written at once; a later one in
131
+ * that slot waits, replacing the one waiting, and is written at the start of the next slot when a
132
+ * frame comes after that slot, or at the end (`flush`). `ms` (time on the video) only grows.
133
+ */
134
+ export const framePacer = () => {
135
+ const slotMs = 1000 / VIDEO_FPS;
136
+ let lastSlot;
137
+ let waiting;
138
+ /** The waiting frame, at the earliest time in the slot after the last written one. */
139
+ const takeWaiting = () => {
140
+ const next = lastSlot + 1;
141
+ const out = { frame: waiting.frame, ms: Math.max(waiting.ms, Math.ceil(next * slotMs)) };
142
+ lastSlot = next;
143
+ waiting = undefined;
144
+ return out;
145
+ };
146
+ return {
147
+ /** What to write now, in order, for a frame at `ms` on the video. */
148
+ add: (frame, ms) => {
149
+ const slot = Math.floor(ms / slotMs);
150
+ const out = waiting !== undefined && slot > lastSlot + 1 ? [takeWaiting()] : [];
151
+ if (waiting === undefined && (lastSlot === undefined || slot > lastSlot)) {
152
+ out.push({ frame, ms });
153
+ lastSlot = slot;
154
+ }
155
+ else
156
+ waiting = { frame, ms };
157
+ return out;
158
+ },
159
+ /** The frame still waiting, if one is, to write before the video ends. */
160
+ flush: () => (waiting === undefined ? [] : [takeWaiting()]),
161
+ };
162
+ };
163
+ // Matroska (EBML) as Playwright's recorder writes it: one MJPEG track whose frames each come in
164
+ // a cluster of their own with its time in ms.
165
+ const hex = (text) => Uint8Array.from(text.match(/../g), (b) => Number.parseInt(b, 16));
166
+ const concat = (parts) => {
167
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
168
+ let at = 0;
169
+ for (const part of parts) {
170
+ out.set(part, at);
171
+ at += part.length;
172
+ }
173
+ return out;
174
+ };
175
+ /** EBML's variable-length size. */
176
+ export const vint = (value) => {
177
+ let length = 1;
178
+ while (value >= 2 ** (7 * length) - 1)
179
+ length++;
180
+ const out = new Uint8Array(length);
181
+ let v = value;
182
+ for (let i = length - 1; i >= 0; i--) {
183
+ out[i] = v & 0xff;
184
+ v = Math.floor(v / 256);
185
+ }
186
+ out[0] |= 1 << (8 - length);
187
+ return out;
188
+ };
189
+ const uint = (value) => {
190
+ const bytes = [];
191
+ for (let v = value; v > 0; v = Math.floor(v / 256))
192
+ bytes.unshift(v & 0xff);
193
+ return Uint8Array.from(bytes.length === 0 ? [0] : bytes);
194
+ };
195
+ const text = (value) => new TextEncoder().encode(value);
196
+ const element = (id, payload) => concat([hex(id), vint(payload.length), payload]);
197
+ /** The stream's start: its EBML header, a segment of unknown size, its info and its track. */
198
+ export const matroskaHeader = () => concat([
199
+ element('1A45DFA3', concat([
200
+ element('4286', uint(1)),
201
+ element('42F7', uint(1)),
202
+ element('42F2', uint(4)),
203
+ element('42F3', uint(8)),
204
+ element('4282', text('matroska')),
205
+ element('4287', uint(4)),
206
+ element('4285', uint(2)),
207
+ ])),
208
+ hex('18538067'),
209
+ Uint8Array.from([1, 255, 255, 255, 255, 255, 255, 255]),
210
+ // Times in ms.
211
+ element('1549A966', concat([
212
+ element('2AD7B1', uint(1_000_000)),
213
+ element('4D80', text('screw-bugs')),
214
+ element('5741', text('screw-bugs')),
215
+ ])),
216
+ element('1654AE6B', element('AE', concat([
217
+ element('D7', uint(1)),
218
+ element('73C5', uint(1)),
219
+ element('83', uint(1)),
220
+ element('9C', uint(0)),
221
+ element('86', text('V_MJPEG')),
222
+ // Required, but each JPEG gives its own size; 1x1 as Playwright, which found that a
223
+ // larger one can make ffmpeg read a short progressive JPEG as an interlaced field.
224
+ element('E0', concat([element('B0', uint(1)), element('BA', uint(1))])),
225
+ ]))),
226
+ ]);
227
+ /** One frame: a cluster at `ms` holding it as a key frame of track 1. */
228
+ export const matroskaFrame = (ms, jpeg) => {
229
+ const block = concat([hex('A3'), vint(4 + jpeg.length), vint(1), Uint8Array.from([0, 0, 0x80])]);
230
+ const timestamp = element('E7', uint(ms));
231
+ return concat([
232
+ hex('1F43B675'),
233
+ vint(timestamp.length + block.length + jpeg.length),
234
+ timestamp,
235
+ block,
236
+ jpeg,
237
+ ]);
238
+ };
239
+ /** Playwright's ffmpeg arguments for its recorder, writing WebM to `file`. */
240
+ export const ffmpegArgs = (size, file) => {
241
+ const { width: w, height: h } = size;
242
+ const pixelRateScale = Math.max(1, (w * h * VIDEO_FPS) / (800 * 450 * 25));
243
+ const threads = Math.min(8, Math.ceil(pixelRateScale / 4));
244
+ return [
245
+ '-loglevel error -nostdin',
246
+ '-f matroska -fpsprobesize 0 -probesize 32 -analyzeduration 0 -i pipe:0',
247
+ // Each frame at its own time, none repeated: `framePacer` keeps to `VIDEO_FPS` at most.
248
+ '-y -an -fps_mode passthrough',
249
+ // Playwright's settings but the quality: crf 30, not 8, which is near lossless and twice as
250
+ // big, with text that looks the same.
251
+ '-c:v libvpx-vp9 -qmin 0 -qmax 50 -crf 30 -deadline realtime -cpu-used 8 -lag-in-frames 0',
252
+ `-b:v ${Math.round(pixelRateScale * 1000)}k -threads ${threads}`,
253
+ `-tile-columns ${Math.ceil(Math.log2(threads))} -row-mt 1`,
254
+ // 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
256
+ // an odd-height 4:2:0 frame (the JPEG's) to even and pads it back, greying its last row.
257
+ `-vf crop='min(iw,${w})':'min(ih,${h})':0:0,pad=${w}:${h}:0:0:gray`,
258
+ '-f webm',
259
+ ]
260
+ .flatMap((options) => options.split(' '))
261
+ .concat(file);
262
+ };
263
+ const ffmpegEnded = (code) => typeof code === 'number' ? `ffmpeg ended with code ${code}` : `ffmpeg failed: ${code}`;
264
+ /**
265
+ * 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.
269
+ */
270
+ export const startRecorder = (page, options) => Effect.gen(function* () {
271
+ const fs = yield* FileSystem.FileSystem;
272
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
273
+ const clock = yield* Effect.clockWith((clock) => Effect.succeed(clock));
274
+ const partial = `${options.file}.part`;
275
+ const gate = frameGate(options.size);
276
+ // Bounded, so an ffmpeg that stops reading never makes frames pile up in memory.
277
+ const queue = yield* Queue.make({
278
+ capacity: BACKLOG_FRAMES,
279
+ strategy: 'dropping',
280
+ });
281
+ const first = yield* Deferred.make();
282
+ const handle = yield* spawner.spawn(ChildProcess.make(options.ffmpeg, [...ffmpegArgs(options.size, partial)], {
283
+ stdin: Stream.fromQueue(queue),
284
+ stdout: 'ignore',
285
+ stderr: 'ignore',
286
+ forceKillAfter: FFMPEG_KILL_AFTER,
287
+ }));
288
+ // Once ffmpeg has ended, frames are no longer queued for it.
289
+ const exited = yield* Deferred.make();
290
+ let endedWith;
291
+ yield* handle.exitCode.pipe(Effect.map(Number), Effect.catch((error) => Effect.succeed(error.message)), Effect.tap((code) => Effect.andThen(Effect.sync(() => {
292
+ endedWith = code;
293
+ }), Deferred.succeed(exited, code))), Effect.andThen(Queue.shutdown(queue)), Effect.forkScoped);
294
+ Queue.offerUnsafe(queue, matroskaHeader());
295
+ let ended = false;
296
+ const pacer = framePacer();
297
+ /** The latest frame on the video (written, or waiting in `pacer`). */
298
+ let last;
299
+ // Boundary: Playwright hands frames to a callback. It only queues them.
300
+ const onFrame = ({ data, timestamp, }) => {
301
+ if (ended)
302
+ return;
303
+ const ms = gate.admit(jpegSize(data), timestamp);
304
+ if (ms === undefined)
305
+ return;
306
+ const now = pacer.add(data, ms);
307
+ // Not on the video when ffmpeg is gone or too far behind.
308
+ for (const frame of now)
309
+ if (!Queue.offerUnsafe(queue, matroskaFrame(frame.ms, frame.frame)) && frame.frame === data)
310
+ return;
311
+ last = { jpeg: data, paintedAt: timestamp, came: clock.currentTimeMillisUnsafe() };
312
+ if (now.length > 0)
313
+ Deferred.doneUnsafe(first, Exit.succeed(gate.first()));
314
+ };
315
+ yield* Effect.acquireRelease(Effect.tryPromise({
316
+ // Two pixels more than the video, so the page's odd last row or column comes as it is:
317
+ // 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,
322
+ }),
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));
325
+ const finish = yield* Effect.cached(Effect.gen(function* () {
326
+ ended = true;
327
+ const now = yield* Clock.currentTimeMillis;
328
+ if (last !== undefined) {
329
+ const end = matroskaFrame(gate.at(lastFrameTime(last.paintedAt, now - last.came)), last.jpeg);
330
+ // The page's last state and the frame that gives the video its length wait for room,
331
+ // unlike the others; the session's close bounds how long (`CLOSE_TIMEOUT_MS`).
332
+ for (const frame of [...pacer.flush().map((f) => matroskaFrame(f.ms, f.frame)), end])
333
+ while (endedWith === undefined && !Queue.offerUnsafe(queue, frame))
334
+ yield* Effect.sleep(READY_POLL);
335
+ }
336
+ yield* Queue.end(queue);
337
+ const code = yield* Deferred.await(exited);
338
+ if (last === undefined) {
339
+ yield* fs.remove(partial).pipe(Effect.ignore);
340
+ return 'The tab never showed a frame, so there is no video.';
341
+ }
342
+ if (code !== 0) {
343
+ yield* fs.remove(partial).pipe(Effect.ignore);
344
+ return `The video could not be saved: ${ffmpegEnded(code)}.`;
345
+ }
346
+ return yield* fs.rename(partial, options.file).pipe(Effect.as(undefined), Effect.catch((error) => Effect.succeed(`The video could not be saved: ${error.message}`)));
347
+ }));
348
+ return {
349
+ firstFrame: Deferred.await(first),
350
+ hold: (effect) => Effect.acquireUseRelease(Clock.currentTimeMillis.pipe(Effect.map(gate.hold)), () => effect, (release) => Clock.currentTimeMillis.pipe(Effect.map(release))),
351
+ finish,
352
+ ready: Effect.gen(function* () {
353
+ yield* Effect.raceFirst(Deferred.await(first), Deferred.await(exited)).pipe(Effect.timeoutOption(READY_TIMEOUT_MS));
354
+ const opened = yield* Effect.gen(function* () {
355
+ while (endedWith === undefined && !(yield* fs.exists(partial)))
356
+ yield* Effect.sleep(READY_POLL);
357
+ }).pipe(Effect.ignore, Effect.timeoutOption(READY_TIMEOUT_MS));
358
+ if (endedWith !== undefined)
359
+ return yield* Effect.fail(new Error(`${ffmpegEnded(endedWith)}.`));
360
+ if (opened._tag === 'None')
361
+ return yield* Effect.fail(new Error(`ffmpeg did not start writing the video within ${READY_TIMEOUT_MS / 1000} s.`));
362
+ }),
363
+ stopped: Effect.sync(() => ended || endedWith === undefined
364
+ ? undefined
365
+ : `the video stopped being recorded (${ffmpegEnded(endedWith)}).`),
366
+ };
367
+ });
368
+ /**
369
+ * How a session with a video at `path` (in the folder `dir`, made when missing) is recorded with
370
+ * the ffmpeg at `ffmpeg`, on the platform this runs on.
371
+ */
372
+ export const videoRecording = (video) => Effect.gen(function* () {
373
+ const platform = yield* Effect.context();
374
+ return {
375
+ path: video.path,
376
+ record: (page, size) => Effect.gen(function* () {
377
+ 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 });
380
+ }).pipe(Effect.provideContext(platform)),
381
+ };
382
+ });
@@ -1,5 +1,5 @@
1
1
  {
2
- "id": "2026-11-18T08:05:09.559Z-50a8fd73",
3
- "builtAt": "2026-11-18T08:05:09.559Z",
4
- "commit": "70dceb4f143198bbc0cd7186dde36323422809db"
2
+ "id": "2026-11-18T15:59:29.049Z-56409fa9",
3
+ "builtAt": "2026-11-18T15:59:29.049Z",
4
+ "commit": "b14b4e16b08bf564288261d44bbf6d89fbf2d061"
5
5
  }
@@ -9,7 +9,7 @@ import { placeMarks } from './marks.js';
9
9
  import { pageUnplaced } from './viewport.js';
10
10
  import { AccountBook, Browser, Notifier, ReportRenderer, Storage, } from './services.js';
11
11
  import { runCase } from './steps.js';
12
- import { VIDEO_HEAD_BYTES, videoProblemOf, webmDurationMs } from './video.js';
12
+ import { stillWithin, VIDEO_HEAD_BYTES, videoProblemOf, webmDurationMs } from './video.js';
13
13
  const messageOf = (error) => error instanceof Error ? error.message : String(error);
14
14
  /**
15
15
  * The longest one write of `report.html` or `ledger.json` may take. A run's
@@ -316,7 +316,10 @@ export class Engine extends Context.Service()('screw-bugs/Engine') {
316
316
  return ended;
317
317
  // Where the video stands still, for the walkthrough's "Skip inactive".
318
318
  measuring = ended;
319
- const still = yield* browser.stillVideo(storage.filePath(jobId, video));
319
+ const measured = yield* browser.stillVideo(storage.filePath(jobId, video));
320
+ const still = measured === undefined || videoDurationMs === undefined
321
+ ? measured
322
+ : stillWithin(measured, videoDurationMs);
320
323
  measuring = undefined;
321
324
  return still === undefined ? ended : { number, fields: { ...ended.fields, still } };
322
325
  });
@@ -352,7 +355,10 @@ export class Engine extends Context.Service()('screw-bugs/Engine') {
352
355
  // Proof of life for other processes reading the ledger; stops with this scope.
353
356
  yield* Effect.sleep(HEARTBEAT_INTERVAL_MS).pipe(Effect.andThen(update((current) => current)), Effect.ignore, Effect.forever, Effect.forkScoped);
354
357
  yield* notifier.notify({ jobId, state: 'running', message: 'Run started.' });
355
- const browserSession = yield* browser.open({ headed: false });
358
+ const browserSession = yield* browser.open({
359
+ headed: false,
360
+ device: spec.device ?? 'desktop',
361
+ });
356
362
  // One session: one test user in one browser, recorded as one video. Its cases run
357
363
  // one after another in job order and share cookies and storage.
358
364
  const video = videoFile(1);
@@ -390,6 +390,11 @@ declare const Browser_base: Context.ServiceClass<Browser, "screw-bugs/Browser",
390
390
  readonly stillVideo: (file: string) => Effect.Effect<ReadonlyArray<StillStretch> | undefined>;
391
391
  readonly open: (options: {
392
392
  readonly headed: boolean;
393
+ /**
394
+ * The device its sessions are on (desktop when left out): the browser renders at its scale,
395
+ * so their videos have its resolution.
396
+ */
397
+ readonly device?: Device | undefined;
393
398
  }) => Effect.Effect<BrowserSession, BrowserNotFound, Scope.Scope>;
394
399
  /** What `device` emulates, for people reading a run: "Desktop", "iPhone 17 (Chromium)". */
395
400
  readonly deviceLabel: (device: Device) => string;
@@ -45,3 +45,9 @@ export declare const frameChanged: (previous: GrayImage, next: GrayImage) => boo
45
45
  * last frame for a run that lasts to the end. In time order.
46
46
  */
47
47
  export declare const stillStretches: (frames: ReadonlyArray<GrayImage>, frameMs: number) => ReadonlyArray<StillStretch>;
48
+ /**
49
+ * `stretches` cut at the end of a video `videoMs` long, leaving out those no longer
50
+ * `STILL_MIN_MS` long. Read back at a constant rate, a video with a frame only where the page
51
+ * changed can run on past its end: ffmpeg shows its last frame as long as the gap before it.
52
+ */
53
+ export declare const stillWithin: (stretches: ReadonlyArray<StillStretch>, videoMs: number) => ReadonlyArray<StillStretch>;
@@ -231,3 +231,11 @@ export const stillStretches = (frames, frameMs) => {
231
231
  add(start * frameMs, frames.length * frameMs);
232
232
  return stretches;
233
233
  };
234
+ /**
235
+ * `stretches` cut at the end of a video `videoMs` long, leaving out those no longer
236
+ * `STILL_MIN_MS` long. Read back at a constant rate, a video with a frame only where the page
237
+ * changed can run on past its end: ffmpeg shows its last frame as long as the gap before it.
238
+ */
239
+ export const stillWithin = (stretches, videoMs) => stretches
240
+ .map((s) => ({ fromMs: s.fromMs, toMs: Math.min(s.toMs, videoMs) }))
241
+ .filter((s) => s.toMs - s.fromMs >= STILL_MIN_MS);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "screw-bugs",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "Local browser QA for coding agents (MCP), people and CI.",
5
5
  "keywords": [
6
6
  "browser",