screw-bugs 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +49 -34
  2. package/dist/browser-playwright/capture.js +1 -1
  3. package/dist/browser-playwright/launch.js +27 -10
  4. package/dist/browser-playwright/page.d.ts +48 -26
  5. package/dist/browser-playwright/page.js +86 -89
  6. package/dist/browser-playwright/recorder.d.ts +154 -0
  7. package/dist/browser-playwright/recorder.js +382 -0
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli/app.js +6 -2
  10. package/dist/cli/commands.js +4 -3
  11. package/dist/cli/doctor.d.ts +17 -2
  12. package/dist/cli/doctor.js +62 -4
  13. package/dist/cli/mcp.js +2 -2
  14. package/dist/cli/report-server.d.ts +19 -10
  15. package/dist/cli/report-server.js +43 -18
  16. package/dist/cli/share.js +2 -2
  17. package/dist/cli/sign-in.d.ts +9 -3
  18. package/dist/cli/sign-in.js +12 -9
  19. package/dist/cli/tailnet.d.ts +57 -0
  20. package/dist/cli/tailnet.js +82 -0
  21. package/dist/core/index.d.ts +1 -14
  22. package/dist/core/index.js +3 -14
  23. package/dist/report/index.d.ts +1 -10
  24. package/dist/report/index.js +3 -10
  25. package/dist/schema/index.d.ts +1 -9
  26. package/dist/schema/index.js +3 -9
  27. package/package.json +14 -14
  28. package/dist/core/accounts.d.ts +0 -40
  29. package/dist/core/accounts.js +0 -95
  30. package/dist/core/css.d.ts +0 -95
  31. package/dist/core/css.js +0 -436
  32. package/dist/core/engine.d.ts +0 -75
  33. package/dist/core/engine.js +0 -554
  34. package/dist/core/errors.d.ts +0 -85
  35. package/dist/core/errors.js +0 -36
  36. package/dist/core/evidence.d.ts +0 -14
  37. package/dist/core/evidence.js +0 -131
  38. package/dist/core/labels.d.ts +0 -47
  39. package/dist/core/labels.js +0 -199
  40. package/dist/core/liveness.d.ts +0 -45
  41. package/dist/core/liveness.js +0 -66
  42. package/dist/core/marks.d.ts +0 -63
  43. package/dist/core/marks.js +0 -410
  44. package/dist/core/services.d.ts +0 -574
  45. package/dist/core/services.js +0 -25
  46. package/dist/core/share.d.ts +0 -68
  47. package/dist/core/share.js +0 -318
  48. package/dist/core/steps.d.ts +0 -106
  49. package/dist/core/steps.js +0 -722
  50. package/dist/core/uploads.d.ts +0 -49
  51. package/dist/core/uploads.js +0 -133
  52. package/dist/core/video.d.ts +0 -47
  53. package/dist/core/video.js +0 -233
  54. package/dist/core/viewport.d.ts +0 -28
  55. package/dist/core/viewport.js +0 -50
  56. package/dist/report/assets.d.ts +0 -34
  57. package/dist/report/assets.js +0 -105
  58. package/dist/report/bug.d.ts +0 -11
  59. package/dist/report/bug.js +0 -20
  60. package/dist/report/html.d.ts +0 -47
  61. package/dist/report/html.js +0 -923
  62. package/dist/report/icons.d.ts +0 -51
  63. package/dist/report/icons.js +0 -93
  64. package/dist/report/live.d.ts +0 -7
  65. package/dist/report/live.js +0 -135
  66. package/dist/report/logos.d.ts +0 -4
  67. package/dist/report/logos.js +0 -19
  68. package/dist/report/markup.d.ts +0 -50
  69. package/dist/report/markup.js +0 -156
  70. package/dist/report/menu-bar.d.ts +0 -60
  71. package/dist/report/menu-bar.js +0 -157
  72. package/dist/report/player.d.ts +0 -102
  73. package/dist/report/player.js +0 -315
  74. package/dist/report/pr-summary.d.ts +0 -11
  75. package/dist/report/pr-summary.js +0 -119
  76. package/dist/report/sha256.d.ts +0 -9
  77. package/dist/report/sha256.js +0 -97
  78. package/dist/report/share-page.d.ts +0 -48
  79. package/dist/report/share-page.js +0 -291
  80. package/dist/report/shots.d.ts +0 -59
  81. package/dist/report/shots.js +0 -280
  82. package/dist/report/sign-in.d.ts +0 -41
  83. package/dist/report/sign-in.js +0 -568
  84. package/dist/report/styles.d.ts +0 -3
  85. package/dist/report/styles.js +0 -274
  86. package/dist/report/view.d.ts +0 -296
  87. package/dist/report/view.js +0 -702
  88. package/dist/report/walkthrough.d.ts +0 -93
  89. package/dist/report/walkthrough.js +0 -716
  90. package/dist/schema/accounts.d.ts +0 -137
  91. package/dist/schema/accounts.js +0 -121
  92. package/dist/schema/config.d.ts +0 -7
  93. package/dist/schema/config.js +0 -6
  94. package/dist/schema/doctor.d.ts +0 -46
  95. package/dist/schema/doctor.js +0 -30
  96. package/dist/schema/evidence.d.ts +0 -1115
  97. package/dist/schema/evidence.js +0 -565
  98. package/dist/schema/findings.d.ts +0 -161
  99. package/dist/schema/findings.js +0 -82
  100. package/dist/schema/job.d.ts +0 -1905
  101. package/dist/schema/job.js +0 -577
  102. package/dist/schema/ledger.d.ts +0 -1124
  103. package/dist/schema/ledger.js +0 -285
  104. package/dist/schema/share.d.ts +0 -55
  105. package/dist/schema/share.js +0 -64
  106. package/dist/schema/status.d.ts +0 -7
  107. package/dist/schema/status.js +0 -11
package/README.md CHANGED
@@ -720,7 +720,8 @@ flow itself, or what a visitor sees. The saved accounts are listed in
720
720
  agent can pick the one whose `about` fits what it tests, such as a user on a trial or a paying one.
721
721
 
722
722
  When the account has no saved session for the job URL's origin, nothing starts. Over MCP, the
723
- reply gives a link to the live view (`http://127.0.0.1:<port>/<token>/`); open it, sign in as that
723
+ reply gives a link to the live view (`http://127.0.0.1:<port>/<token>/`, or this machine's tailnet
724
+ name in place of `127.0.0.1` when Tailscale is running); open it, sign in as that
724
725
  user (OAuth redirects and codes by email or an app work; passkeys and security keys do not, since
725
726
  they need your own device), press **Save sign-in**, then
726
727
  have your agent start the job again. `start_run` also takes an optional `waitSeconds` (0–600,
@@ -739,10 +740,12 @@ you can sign in meanwhile. From the CLI, `screw-bugs run` exits with code 9
739
740
  npx screw-bugs accounts sign-in trial-user --url http://localhost:3000 --about "On a 14-day trial"
740
741
  ```
741
742
 
742
- - **On another device.** The live view listens on 127.0.0.1, so by default it opens only on this
743
- machine (in your coding tool's browser, for example). To sign in from your phone or another
744
- computer on your network or tailnet, set `SCREW_BUGS_SIGN_IN_HOST` as `SCREW_BUGS_REPORT_HOST`
745
- (below): this machine's full MagicDNS name or its Tailscale IP (`tailscale ip -4`). The link
743
+ - **On another device.** When Tailscale is running, the live view listens at this machine's
744
+ MagicDNS name, so you can sign in from your phone or another computer on your tailnet; without
745
+ it, on 127.0.0.1, so it opens only on this machine (in your coding tool's browser, for example).
746
+ It follows `SCREW_BUGS_REPORT_HOST` (below; `127.0.0.1` keeps it on this machine), or set
747
+ `SCREW_BUGS_SIGN_IN_HOST` for the live view alone: `tailnet`, this machine's full MagicDNS name
748
+ or its Tailscale IP (`tailscale ip -4`). The link
746
749
  then uses what you set, and with a name the IP it resolves to works too. It never listens on
747
750
  every interface. The link holds a random token and works only while that
748
751
  sign-in is open; it closes when you save or cancel, after 15 minutes without use, or when the
@@ -762,24 +765,24 @@ npx screw-bugs accounts sign-in trial-user --url http://localhost:3000 --about "
762
765
 
763
766
  ## CLI
764
767
 
765
- | Command | What it does |
766
- | ---------------------------------------------- | ---------------------------------------------- |
767
- | `doctor` | Check Node, browser, video, disk and updates |
768
- | `run [--spec job.json] [--url <url>]` | Run cases and wait; exit 1 unless all passed |
769
- | `status <job-id>` | State and case results of a run |
770
- | `answer <job-id> <question-id>` | Answer a question a waiting run asked |
771
- | `mcp` | Serve the MCP server over stdio |
772
- | `setup [--agent <name>] [--no-downloads]` | Set up this project in one command (above) |
773
- | `init` | Write `screw-bugs.json` for this project |
774
- | `accounts [sign-in <label> \| remove <label>]` | List, sign in to or remove test accounts |
775
- | `report <job-id> [--format markdown]` | Write the report, or print a PR summary |
776
- | `report <job-id> --serve [--port N]` | Serve the report at a `http://127.0.0.1` URL |
777
- | `walkthrough <job-id> [--serve]` | Write (or serve) the run's video walkthrough |
778
- | `findings <job-id> <file\|->` | Submit an agent's write-up of an ended run |
779
- | `schema <job\|findings>` | Print the JSON Schema of a job or write-up |
780
- | `share <job-id>` | Share a report through Screw Bugs Cloud |
781
- | `runs` | List recent runs |
782
- | `analytics` | Show whether analytics are on (off by default) |
768
+ | Command | What it does |
769
+ | ---------------------------------------------- | ------------------------------------------------------- |
770
+ | `doctor` | Check Node, browser, video, disk, Tailscale and updates |
771
+ | `run [--spec job.json] [--url <url>]` | Run cases and wait; exit 1 unless all passed |
772
+ | `status <job-id>` | State and case results of a run |
773
+ | `answer <job-id> <question-id>` | Answer a question a waiting run asked |
774
+ | `mcp` | Serve the MCP server over stdio |
775
+ | `setup [--agent <name>] [--no-downloads]` | Set up this project in one command (above) |
776
+ | `init` | Write `screw-bugs.json` for this project |
777
+ | `accounts [sign-in <label> \| remove <label>]` | List, sign in to or remove test accounts |
778
+ | `report <job-id> [--format markdown]` | Write the report, or print a PR summary |
779
+ | `report <job-id> --serve [--port N]` | Serve the report at a local or tailnet URL |
780
+ | `walkthrough <job-id> [--serve]` | Write (or serve) the run's video walkthrough |
781
+ | `findings <job-id> <file\|->` | Submit an agent's write-up of an ended run |
782
+ | `schema <job\|findings>` | Print the JSON Schema of a job or write-up |
783
+ | `share <job-id>` | Share a report through Screw Bugs Cloud |
784
+ | `runs` | List recent runs |
785
+ | `analytics` | Show whether analytics are on (off by default) |
783
786
 
784
787
  Every command accepts `--json`. `run --url <url>` alone checks that the page loads. `init --url
785
788
  <url>` saves a default URL, so a bare `run` uses it.
@@ -853,8 +856,8 @@ with the highlights drawn over it (a checkbox hides them) and the element the st
853
856
  arrow keys step through the case's screenshots. "Steps and details" opens the case's steps with
854
857
  their timecodes and the agent's write-up of it. Then what to test next, and the run's details
855
858
  (what it checks, target, times, video, version, raw files). Scrolling the cases drives the player:
856
- the case at the reading line plays, in a loop unless "Loop case" is off, when the cases follow the
857
- video instead. Code lays out the page and decides every status, except that the agent's write-up
859
+ the case at the reading line plays and the cases follow the video; with "Loop case" on (it starts
860
+ off) the case plays in a loop instead. Code lays out the page and decides every status, except that the agent's write-up
858
861
  may mark a case failed (its card then says so, as the agent's verdict, beside the code's result);
859
862
  the write-up fills fixed slots and is labelled as its own.
860
863
 
@@ -960,7 +963,7 @@ leaves the report as it is. The report links it near the top when it exists.
960
963
 
961
964
  ```sh
962
965
  screw-bugs walkthrough <job-id> # (re)write it (not the report) and print its URL
963
- screw-bugs walkthrough <job-id> --serve # serve it at a http://127.0.0.1 URL, as report --serve
966
+ screw-bugs walkthrough <job-id> --serve # serve it at a local or tailnet URL, as report --serve
964
967
  ```
965
968
 
966
969
  With `--json`, `walkthrough` prints `{ "ok": true, "path": "...", "reportPath": "...", "reportUrl":
@@ -993,11 +996,18 @@ desktop app, cannot open `file://` pages, but they can open `http://127.0.0.1`.
993
996
  - From a terminal, `screw-bugs report <job-id> --serve` (or `walkthrough <job-id> --serve`) writes
994
997
  the report as `report` does, prints its URL (or the walkthrough's) and serves until Ctrl+C (which exits with 130, like any interrupted command). With
995
998
  `--json` it prints `{ "url": "...", "ok": true, "path": "...", "reused": false }`.
996
- - **On another device.** The report server listens on 127.0.0.1, so by default its links open only
997
- on this machine. To open reports from your phone or another computer on your network or
998
- tailnet, set `SCREW_BUGS_REPORT_HOST` in the MCP server's environment (or the shell that runs
999
- the commands) to this machine's full MagicDNS name (`pop-os.tail1234.ts.net`, from `tailscale
1000
- status --self`) or its Tailscale IP (`tailscale ip -4`). Links then use what you set. The
999
+ - **On another device.** When Tailscale is running, the report server listens at this machine's
1000
+ MagicDNS name (asked from Tailscale when screw-bugs starts), so its links open on your phone or
1001
+ another computer on your tailnet, and on every other device on it. Without Tailscale (and always
1002
+ in CI, `CI=true`) it listens on 127.0.0.1, so links open only on this machine. `doctor` says
1003
+ which. To keep reports and sign-ins on this machine with Tailscale running, set
1004
+ `SCREW_BUGS_REPORT_HOST=127.0.0.1` in the MCP server's environment (or the shell that runs the
1005
+ commands); on a Linux desktop, for every agent and terminal, put that line in
1006
+ `~/.config/environment.d/screw-bugs.conf` and log out and back in. You can also set it to
1007
+ `tailnet` (the MagicDNS name; when Tailscale is not running, reports stay on 127.0.0.1 and one
1008
+ line on stderr says so, until screw-bugs restarts), this machine's full MagicDNS name
1009
+ (`pop-os.tail1234.ts.net`, from `tailscale status --self`) or its Tailscale IP (`tailscale ip
1010
+ -4`). The sign-in live view follows this setting unless `SCREW_BUGS_SIGN_IN_HOST` is set. Links then use what you set. The
1001
1011
  server listens only on the one address that resolves to, never on every interface, and answers
1002
1012
  requests addressed to the name you set or to that address, so `http://100.x.y.z:…` works with
1003
1013
  the name set (but a bare `http://pop-os:…` only when you set `pop-os`). A name is looked up each
@@ -1050,7 +1060,9 @@ This check cannot stop a process from taking the port after it, such as one that
1050
1060
  moment between another screw-bugs process stopping and this one trying the port again. Links given
1051
1061
  out then reach that process until screw-bugs serves on the port again.
1052
1062
 
1053
- Both listen on 127.0.0.1 only, answer only requests addressed to `127.0.0.1` or `localhost`, and
1063
+ Both listen on one address: 127.0.0.1, or this machine's tailnet name when Tailscale is running
1064
+ (see On another device, above). They answer only requests addressed to that host or its address (and, on
1065
+ 127.0.0.1, `localhost`), and
1054
1066
  serve only the project's run folders, read-only: reports, screenshots, videos and JSON files. They
1055
1067
  never list folders or serve dotfiles, anything outside `.screw-bugs/runs` or symlinks out of it.
1056
1068
  Videos are served with HTTP range requests, so they play and seek (unlike `python3 -m
@@ -1201,5 +1213,8 @@ It uses your Claude subscription: a full run is three Sonnet sessions, about a m
1201
1213
  roughly 70k input tokens (mostly cached) and a few thousand output tokens. It is never run in CI.
1202
1214
 
1203
1215
  `src/` holds one folder per module, each published as a sub-path (`screw-bugs/core`,
1204
- `screw-bugs/schema`, ...). `schema`, `core` and `report` must not import Node, Playwright or other
1205
- modules' internals; `pnpm lint` enforces this.
1216
+ `screw-bugs/schema`, ...). `schema`, `core` and `report` are their own package,
1217
+ [`@screw-bugs/core`](packages/core/README.md) (`packages/core`), which screw-bugs re-exports: it
1218
+ depends only on `effect` and runs on Cloudflare Workers, so it must not import Node, Playwright,
1219
+ any other package or other modules' internals. `pnpm lint` enforces this, and `pnpm check:workers`
1220
+ bundles it for Workers and renders a report with only Workers' globals.
@@ -399,7 +399,7 @@ export const captureState = (options) => {
399
399
  const alt = altOf(el, tag, role);
400
400
  return { label, name, text, alt, testId: testId === null ? undefined : String(testId) };
401
401
  };
402
- // The keys of `candidateKeys` in src/schema; the two must make the same strings.
402
+ // The keys of `candidateKeys` in @screw-bugs/core's schema; the two must make the same strings.
403
403
  const matchText = (text) => text.replace(/\s+/g, ' ').trim().toLowerCase();
404
404
  const keysOf = (c) => [
405
405
  ...(c.role !== undefined ? [JSON.stringify(['role', matchText(c.role)])] : []),
@@ -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
  };