screw-bugs 0.1.1 → 0.1.3

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 (57) hide show
  1. package/README.md +70 -20
  2. package/dist/browser-playwright/launch.js +3 -1
  3. package/dist/browser-playwright/page.d.ts +3 -11
  4. package/dist/browser-playwright/page.js +17 -1
  5. package/dist/browser-playwright/sign-in.d.ts +77 -0
  6. package/dist/browser-playwright/sign-in.js +217 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli/app.js +4 -1
  9. package/dist/cli/commands.js +68 -3
  10. package/dist/cli/exit-codes.d.ts +6 -0
  11. package/dist/cli/exit-codes.js +6 -0
  12. package/dist/cli/mcp.js +17 -3
  13. package/dist/cli/operations.d.ts +31 -3
  14. package/dist/cli/operations.js +95 -3
  15. package/dist/cli/sign-in.d.ts +79 -0
  16. package/dist/cli/sign-in.js +305 -0
  17. package/dist/core/accounts.d.ts +40 -0
  18. package/dist/core/accounts.js +95 -0
  19. package/dist/core/engine.d.ts +8 -4
  20. package/dist/core/engine.js +39 -9
  21. package/dist/core/errors.d.ts +19 -0
  22. package/dist/core/errors.js +6 -0
  23. package/dist/core/index.d.ts +1 -0
  24. package/dist/core/index.js +1 -0
  25. package/dist/core/services.d.ts +77 -8
  26. package/dist/core/services.js +4 -1
  27. package/dist/report/bug.d.ts +2 -2
  28. package/dist/report/bug.js +5 -4
  29. package/dist/report/html.d.ts +1 -1
  30. package/dist/report/html.js +3 -2
  31. package/dist/report/icons.d.ts +2 -0
  32. package/dist/report/icons.js +4 -3
  33. package/dist/report/index.d.ts +2 -1
  34. package/dist/report/index.js +2 -1
  35. package/dist/report/markup.d.ts +2 -13
  36. package/dist/report/markup.js +8 -62
  37. package/dist/report/menu-bar.d.ts +60 -0
  38. package/dist/report/menu-bar.js +153 -0
  39. package/dist/report/player.d.ts +9 -4
  40. package/dist/report/player.js +24 -13
  41. package/dist/report/sign-in.d.ts +41 -0
  42. package/dist/report/sign-in.js +539 -0
  43. package/dist/report/styles.js +10 -34
  44. package/dist/report/walkthrough.d.ts +3 -2
  45. package/dist/report/walkthrough.js +50 -40
  46. package/dist/schema/accounts.d.ts +137 -0
  47. package/dist/schema/accounts.js +112 -0
  48. package/dist/schema/index.d.ts +1 -0
  49. package/dist/schema/index.js +1 -0
  50. package/dist/schema/job.d.ts +27 -6
  51. package/dist/schema/job.js +12 -2
  52. package/dist/schema/ledger.d.ts +5 -1
  53. package/dist/store-local/accounts.d.ts +8 -4
  54. package/dist/store-local/accounts.js +82 -7
  55. package/dist/store-local/paths.d.ts +4 -1
  56. package/dist/store-local/paths.js +4 -1
  57. package/package.json +2 -2
package/README.md CHANGED
@@ -6,8 +6,9 @@ screw-bugs has no AI of its own and never calls a model. Your coding agent (or y
6
6
  test and writes the cases as structured steps. screw-bugs runs them in a real headless browser,
7
7
  saves screenshots, and reports a status for each case.
8
8
 
9
- > **Status: early.** `setup`, `doctor`, `init`, `run`, `status`, `report` and `runs` work. `answer`,
10
- > `accounts`, `share` and `analytics on|off` exit with code 5 and say they are not implemented yet.
9
+ > **Status: early.** `setup`, `doctor`, `init`, `run`, `status`, `report`, `accounts` and `runs`
10
+ > work. `answer`, `share` and `analytics on|off` exit with code 5 and say they are not implemented
11
+ > yet.
11
12
 
12
13
  ## Install
13
14
 
@@ -82,7 +83,7 @@ Set up screw-bugs (local browser QA for coding agents, over MCP) in this project
82
83
 
83
84
  ## Requirements
84
85
 
85
- Node.js 22.13 or newer, and Google Chrome or Microsoft Edge (or Playwright's Chromium). Check with:
86
+ Node.js 22.19 or newer, and Google Chrome or Microsoft Edge (or Playwright's Chromium). Check with:
86
87
 
87
88
  ```sh
88
89
  npx screw-bugs@latest doctor
@@ -672,25 +673,74 @@ navigation to a `data:` URL; nothing happens then.
672
673
  | `blocked` | A step could not run, such as a target not found or a failed page load |
673
674
  | `not_verified` | Never reached: no browser, or the run was stopped |
674
675
 
676
+ ### Test accounts
677
+
678
+ A job can run signed in as a test user. You sign in to the account once, in a live view of a
679
+ browser screw-bugs runs, and screw-bugs saves the session; every later run of a job with that
680
+ account starts signed in. What you type there goes to that browser and nowhere else: it is never
681
+ logged, recorded or saved; only the session (the app's cookies and storage) is kept.
682
+
683
+ ```json
684
+ { "url": "http://localhost:3000/billing", "account": "trial-user", "cases": [] }
685
+ ```
686
+
687
+ `account` is a label, or `{ "label": "paid-user", "about": "Pro plan, paying monthly" }` to name a
688
+ new one and say what kind of user it is. Without `account`, a run is signed out: a fresh browser
689
+ with no cookies or storage, whatever accounts are saved, for public pages, the sign-up or sign-in
690
+ flow itself, or what a visitor sees. The saved accounts are listed in
691
+ `.screw-bugs/accounts.json` (label, `about`, origin, when it was saved; never a secret), so your
692
+ agent can pick the one whose `about` fits what it tests, such as a user on a trial or a paying one.
693
+
694
+ When the account has no saved session for the job URL's origin, nothing starts. Over MCP, the
695
+ reply gives a link to the live view (`http://127.0.0.1:<port>/<token>/`); open it, sign in as that
696
+ user (OAuth redirects and codes by email or an app work; passkeys and security keys do not, since
697
+ they need your own device), press **Save sign-in**, then
698
+ have your agent start the job again. From the CLI, `screw-bugs run` exits with code 9
699
+ (`SignInNeeded`) and prints the command that opens the live view:
700
+
701
+ ```sh
702
+ npx screw-bugs accounts sign-in trial-user --url http://localhost:3000 --about "On a 14-day trial"
703
+ ```
704
+
705
+ - **On another device.** The live view listens on 127.0.0.1, so by default it opens only on this
706
+ machine (in your coding tool's browser, for example). To sign in from your phone or another
707
+ computer on your network or tailnet, set `SCREW_BUGS_SIGN_IN_HOST` to an address of this machine
708
+ that it can reach, such as its Tailscale IP (`tailscale ip -4`); the link then uses that address.
709
+ It never listens on every interface. The link holds a random token and works only while that
710
+ sign-in is open; it closes when you save or cancel, after 15 minutes without use, or when the
711
+ MCP server or the command stops.
712
+ - **Keeping it current.** A session is saved for one origin; a job on another origin (staging
713
+ instead of localhost) asks you to sign in again, and saving replaces the session. A session whose
714
+ cookies have all expired asks too. When a session stops working sooner (the run lands on a sign-in
715
+ page), the agent sends `{ "label": "trial-user", "renew": true }` once, and you sign in again;
716
+ `renew` does not ask again for 10 minutes after a save. Signing in again with another `--about`
717
+ updates what the account is. `screw-bugs accounts` lists them and `accounts remove <label>`
718
+ removes one.
719
+ - **Where it is kept.** `.screw-bugs/accounts/<label>.json`, readable by you alone (mode 0600, in a
720
+ 0700 folder; on Windows it has the folder's access), and never committed (`.screw-bugs/` ignores
721
+ itself). Only the cookies the browser sends to the app's host and its own origin's storage are
722
+ kept, so another site's sign-in (GitHub's, for an OAuth sign-in) is not. A cookie of a sibling
723
+ host (`api.acme.dev` for an app at `app.acme.dev`) is not kept either.
724
+
675
725
  ## CLI
676
726
 
677
- | Command | What it does |
678
- | ----------------------------------------- | ---------------------------------------------- |
679
- | `doctor` | Check Node, browser, video, disk and updates |
680
- | `run [--spec job.json] [--url <url>]` | Run cases and wait; exit 1 unless all passed |
681
- | `status <job-id>` | State and case results of a run |
682
- | `answer <job-id> <question-id>` | Answer a question a waiting run asked |
683
- | `mcp` | Serve the MCP server over stdio |
684
- | `setup [--agent <name>] [--no-downloads]` | Set up this project in one command (above) |
685
- | `init` | Write `screw-bugs.json` for this project |
686
- | `accounts` | Manage test accounts for logins |
687
- | `report <job-id> [--format markdown]` | Write the report, or print a PR summary |
688
- | `report <job-id> --serve [--port N]` | Serve the report at a `http://127.0.0.1` URL |
689
- | `walkthrough <job-id> [--serve]` | Write (or serve) the run's video walkthrough |
690
- | `findings <job-id> <file\|->` | Submit an agent's write-up of an ended run |
691
- | `share <job-id>` | Share a report through screw-bugs Cloud |
692
- | `runs` | List recent runs |
693
- | `analytics` | Show whether analytics are on (off by default) |
727
+ | Command | What it does |
728
+ | ---------------------------------------------- | ---------------------------------------------- |
729
+ | `doctor` | Check Node, browser, video, disk and updates |
730
+ | `run [--spec job.json] [--url <url>]` | Run cases and wait; exit 1 unless all passed |
731
+ | `status <job-id>` | State and case results of a run |
732
+ | `answer <job-id> <question-id>` | Answer a question a waiting run asked |
733
+ | `mcp` | Serve the MCP server over stdio |
734
+ | `setup [--agent <name>] [--no-downloads]` | Set up this project in one command (above) |
735
+ | `init` | Write `screw-bugs.json` for this project |
736
+ | `accounts [sign-in <label> \| remove <label>]` | List, sign in to or remove test accounts |
737
+ | `report <job-id> [--format markdown]` | Write the report, or print a PR summary |
738
+ | `report <job-id> --serve [--port N]` | Serve the report at a `http://127.0.0.1` URL |
739
+ | `walkthrough <job-id> [--serve]` | Write (or serve) the run's video walkthrough |
740
+ | `findings <job-id> <file\|->` | Submit an agent's write-up of an ended run |
741
+ | `share <job-id>` | Share a report through screw-bugs Cloud |
742
+ | `runs` | List recent runs |
743
+ | `analytics` | Show whether analytics are on (off by default) |
694
744
 
695
745
  Every command accepts `--json`. `run --url <url>` alone checks that the page loads. `init --url
696
746
  <url>` saves a default URL, so a bare `run` uses it.
@@ -2,6 +2,7 @@ import { Effect, FileSystem, Layer, Path, Schema } from 'effect';
2
2
  import { chromium } from 'playwright-core';
3
3
  import { Browser, BrowserNotFound } from '../core/index.js';
4
4
  import { annotateAll } from './annotate.js';
5
+ import { signInBrowser } from './sign-in.js';
5
6
  import { deviceLabel, newSession } from './page.js';
6
7
  /** Order matters: prefer what the user already has installed. */
7
8
  const candidates = [
@@ -45,7 +46,7 @@ const open = (options) => launchAny(options.headed).pipe(Effect.map(({ candidate
45
46
  channel: candidate.channel,
46
47
  version: browser.version(),
47
48
  },
48
- newSession: (session) => newSession(browser, session.device, session.video),
49
+ newSession: (session) => newSession(browser, session.device, session.video, true, session.session),
49
50
  })));
50
51
  /**
51
52
  * Launches the installed Chrome, else Edge, else Playwright's downloaded Chromium. Needs the
@@ -66,6 +67,7 @@ export const BrowserPlaywright = Layer.effect(Browser, Effect.gen(function* () {
66
67
  open,
67
68
  deviceLabel,
68
69
  annotate: (jobs) => Effect.scoped(launchAny(false).pipe(Effect.flatMap(({ browser }) => annotateAll(browser, jobs)))),
70
+ signIn: (url) => launchAny(false).pipe(Effect.flatMap(({ browser }) => signInBrowser(browser, url))),
69
71
  };
70
72
  }));
71
73
  const PlaywrightPackage = Schema.Struct({ version: Schema.String });
@@ -401,22 +401,14 @@ export declare const FIRST_FRAME_TIMEOUT_MS = 2000;
401
401
  * reads in a run. The listener is let go of when this ends, timed out or not.
402
402
  */
403
403
  export declare const firstFrameAt: (page: Page) => Effect.Effect<number | undefined, never, never>;
404
- /**
405
- * One session: a fresh context (no cookies or storage from other runs) with one tab that every
406
- * case of the session runs in, recorded as one continuous video. Tabs and windows a case opens
407
- * are in the same context and are closed before the next case. Closed with its scope; the video
408
- * is saved then too, so a run that is stopped keeps it.
409
- *
410
- * Playwright records each tab's video separately, so only the session's own tab is kept: the
411
- * videos of tabs the cases opened are deleted. Recording needs Playwright's ffmpeg: a session
412
- * with `video` that cannot be recorded fails rather than run without one.
413
- */
414
404
  export declare const newSession: (browser: PlaywrightBrowser, device: Device, video: {
415
405
  readonly dir: string;
416
406
  readonly path: string;
417
407
  } | undefined,
418
408
  /** Whether to watch the input the page gets, for recording actions; for tests to compare. */
419
- observed?: boolean) => Effect.Effect<{
409
+ observed?: boolean,
410
+ /** A saved session (an account's storage state, as JSON text) the context starts from. */
411
+ savedSession?: string) => Effect.Effect<{
420
412
  page: BrowserPage;
421
413
  beginCase: (options: {
422
414
  readonly continues?: boolean;
@@ -2037,15 +2037,31 @@ export const firstFrameAt = (page) => Effect.gen(function* () {
2037
2037
  * videos of tabs the cases opened are deleted. Recording needs Playwright's ffmpeg: a session
2038
2038
  * with `video` that cannot be recorded fails rather than run without one.
2039
2039
  */
2040
+ /** A saved storage state as Playwright takes it; its cookies and origins are Playwright's own. */
2041
+ const StorageStateShape = Schema.Struct({
2042
+ cookies: Schema.Array(Schema.Unknown),
2043
+ origins: Schema.Array(Schema.Unknown),
2044
+ });
2040
2045
  export const newSession = (browser, device, video,
2041
2046
  /** Whether to watch the input the page gets, for recording actions; for tests to compare. */
2042
- observed = true) => Effect.gen(function* () {
2047
+ observed = true,
2048
+ /** A saved session (an account's storage state, as JSON text) the context starts from. */
2049
+ savedSession) => Effect.gen(function* () {
2043
2050
  const clock = yield* Effect.clockWith((clock) => Effect.succeed(clock));
2044
2051
  const options = contextOptions(device);
2045
2052
  const failed = (error) => `Could not open a new browser tab: ${firstLine(error)}`;
2053
+ // Read by the caller and checked there; Playwright takes it as an object.
2054
+ const storageState = savedSession === undefined
2055
+ ? undefined
2056
+ : yield* Schema.decodeUnknownEffect(Schema.fromJsonString(StorageStateShape))(savedSession).pipe(Effect.mapError((cause) => new PageActionFailed({ message: 'The saved session is not valid.', cause })));
2046
2057
  /** A context with its tab; with `record`, both are recorded. Boundary: Playwright promises. */
2047
2058
  const open = (record) => Effect.acquireRelease(attempt(() => browser.newContext({
2048
2059
  ...options,
2060
+ ...(storageState !== undefined
2061
+ ? {
2062
+ storageState: storageState,
2063
+ }
2064
+ : {}),
2049
2065
  ...(record && video !== undefined
2050
2066
  ? { recordVideo: { dir: video.dir, size: videoSize(options.viewport) } }
2051
2067
  : {}),
@@ -0,0 +1,77 @@
1
+ import { Effect } from 'effect';
2
+ import type { Browser as PlaywrightBrowser, BrowserContext } from 'playwright-core';
3
+ import { PageActionFailed, type SignInFrame, type SignInSite } from '../core/index.js';
4
+ import type { SignInInput } from '../schema/index.js';
5
+ /** The live view's viewport until the viewer says how much room it has. */
6
+ export declare const SIGN_IN_VIEWPORT: {
7
+ readonly width: 1280;
8
+ readonly height: 800;
9
+ };
10
+ /** The viewports a viewer may ask for, in CSS pixels: a phone's up to a large desktop's. */
11
+ export declare const SIGN_IN_VIEWPORT_RANGE: {
12
+ readonly width: {
13
+ readonly min: 320;
14
+ readonly max: 1600;
15
+ };
16
+ readonly height: {
17
+ readonly min: 400;
18
+ readonly max: 1200;
19
+ };
20
+ };
21
+ /** How long one input may take before it is given up (a page that hangs never holds the view). */
22
+ export declare const SIGN_IN_INPUT_TIMEOUT_MS = 5000;
23
+ /** How long the first page load may take; the view opens on whatever it got by then. */
24
+ export declare const SIGN_IN_LOAD_TIMEOUT_MS = 15000;
25
+ /** How long reading the app's title and icons may take; the view opens without them after. */
26
+ export declare const SIGN_IN_SITE_TIMEOUT_MS = 3000;
27
+ /**
28
+ * The storage state of `context` with only what the app at `origin` gets: the cookies the browser
29
+ * sends to its host (`sentTo`) and its own origin's storage. Another site's sign-in page (such as
30
+ * GitHub's, for OAuth) is dropped.
31
+ */
32
+ export declare const stateOfSite: (state: Awaited<ReturnType<BrowserContext['storageState']>>, origin: string) => {
33
+ cookies: {
34
+ name: string;
35
+ value: string;
36
+ domain: string;
37
+ path: string;
38
+ expires: number;
39
+ httpOnly: boolean;
40
+ secure: boolean;
41
+ sameSite: "Strict" | "Lax" | "None";
42
+ }[];
43
+ origins: {
44
+ origin: string;
45
+ localStorage: Array<{
46
+ name: string;
47
+ value: string;
48
+ }>;
49
+ }[];
50
+ };
51
+ /** An icon a page declares: its `<link>`'s attributes. */
52
+ export interface IconLink {
53
+ readonly rel: string;
54
+ readonly href: string;
55
+ readonly type: string;
56
+ readonly sizes: string;
57
+ }
58
+ /**
59
+ * Icons best first, for the sharpest one to show: an SVG (it scales), then the largest declared
60
+ * size (`any` counting as large), then `apple-touch-icon` ones (large, but often padded); the
61
+ * page's own order among equals.
62
+ */
63
+ export declare const bestIconsFirst: (links: ReadonlyArray<IconLink>) => ReadonlyArray<IconLink>;
64
+ /**
65
+ * A browser a person drives from the live view (see `SignInBrowser`): one context of its own at
66
+ * `url`, its active tab streamed as JPEG frames through CDP's screencast (Chromium only), and their
67
+ * input played into that tab with Playwright's mouse and keyboard. Closed with the scope.
68
+ */
69
+ export declare const signInBrowser: (browser: PlaywrightBrowser, url: string) => Effect.Effect<{
70
+ site: SignInSite | {
71
+ title: string | undefined;
72
+ icons: string[];
73
+ };
74
+ frame: (after: number, waitMs: number) => Effect.Effect<SignInFrame | undefined, never, never>;
75
+ input: (event: SignInInput) => Effect.Effect<boolean>;
76
+ save: (origin: string) => Effect.Effect<string, PageActionFailed, never>;
77
+ }, PageActionFailed, import("effect/Scope").Scope>;
@@ -0,0 +1,217 @@
1
+ import { Duration, Effect, Option, Schedule } from 'effect';
2
+ import { PageActionFailed, sentTo, SITE_ICONS_MAX, siteTitle, } from '../core/index.js';
3
+ /** The live view's viewport until the viewer says how much room it has. */
4
+ export const SIGN_IN_VIEWPORT = { width: 1280, height: 800 };
5
+ /** The viewports a viewer may ask for, in CSS pixels: a phone's up to a large desktop's. */
6
+ export const SIGN_IN_VIEWPORT_RANGE = {
7
+ width: { min: 320, max: 1600 },
8
+ height: { min: 400, max: 1200 },
9
+ };
10
+ /** How long one input may take before it is given up (a page that hangs never holds the view). */
11
+ export const SIGN_IN_INPUT_TIMEOUT_MS = 5_000;
12
+ /** How long the first page load may take; the view opens on whatever it got by then. */
13
+ export const SIGN_IN_LOAD_TIMEOUT_MS = 15_000;
14
+ /** How long reading the app's title and icons may take; the view opens without them after. */
15
+ export const SIGN_IN_SITE_TIMEOUT_MS = 3_000;
16
+ /** How often a request for the next frame looks for one. */
17
+ const FRAME_POLL_MS = 40;
18
+ /** JPEG quality of the frames: enough to read a form, small enough for a phone on the go. */
19
+ const FRAME_QUALITY = 70;
20
+ const clamp = (value, range) => Math.min(range.max, Math.max(range.min, Math.round(value)));
21
+ const firstLine = (error) => (error instanceof Error ? error.message : String(error)).split('\n')[0].trim();
22
+ /** Boundary: Playwright's API is promises. */
23
+ const attempt = (run) => Effect.tryPromise({
24
+ try: run,
25
+ catch: (error) => new PageActionFailed({ message: firstLine(error), cause: error }),
26
+ });
27
+ /**
28
+ * The storage state of `context` with only what the app at `origin` gets: the cookies the browser
29
+ * sends to its host (`sentTo`) and its own origin's storage. Another site's sign-in page (such as
30
+ * GitHub's, for OAuth) is dropped.
31
+ */
32
+ export const stateOfSite = (state, origin) => ({
33
+ cookies: state.cookies.filter((cookie) => sentTo(origin, cookie.domain)),
34
+ origins: state.origins.filter((entry) => URL.parse(entry.origin)?.origin === URL.parse(origin)?.origin),
35
+ });
36
+ /**
37
+ * Icons best first, for the sharpest one to show: an SVG (it scales), then the largest declared
38
+ * size (`any` counting as large), then `apple-touch-icon` ones (large, but often padded); the
39
+ * page's own order among equals.
40
+ */
41
+ export const bestIconsFirst = (links) => {
42
+ const rank = (link) => {
43
+ const svg = link.type.toLowerCase() === 'image/svg+xml' || /\.svg(?:[?#]|$)/i.test(link.href);
44
+ const sizes = link.sizes.toLowerCase().split(/\s+/);
45
+ const size = Math.max(0, ...sizes.map((each) => (each === 'any' ? 512 : Number.parseInt(each, 10) || 0)));
46
+ const touch = !/(^|\s)icon(\s|$)/i.test(link.rel);
47
+ return (touch ? 0 : 100_000) + (svg ? 10_000 : 0) + Math.min(size, 1024);
48
+ };
49
+ return links
50
+ .map((link, index) => ({ link, index, rank: rank(link) }))
51
+ .sort((a, b) => b.rank - a.rank || a.index - b.index)
52
+ .map(({ link }) => link);
53
+ };
54
+ /**
55
+ * How the app at `origin` names itself (see `SignInSite`), from `page` once loaded: its title, and
56
+ * the addresses of its icons (its `<link rel="icon">` tags, best first by `bestIconsFirst`, then
57
+ * `/favicon.ico`) on `origin` only.
58
+ * A page that went on to another site (such as GitHub's sign-in) gives no title and only the
59
+ * app's `/favicon.ico`. Nothing is fetched here: the live view's server fetches the icon itself,
60
+ * without this browser's cookies.
61
+ */
62
+ const readSite = (page, origin) => Effect.gen(function* () {
63
+ const onSite = URL.parse(page.url())?.origin === origin;
64
+ const title = onSite
65
+ ? siteTitle(yield* attempt(() => page.title()).pipe(Effect.orElseSucceed(() => '')))
66
+ : undefined;
67
+ const links = onSite
68
+ ? yield* attempt(async () => {
69
+ const found = [];
70
+ const tags = page.locator('link[rel~="icon" i][href], link[rel~="apple-touch-icon" i][href]');
71
+ for (const link of (await tags.all()).slice(0, 20))
72
+ found.push({
73
+ rel: (await link.getAttribute('rel')) ?? '',
74
+ href: (await link.getAttribute('href')) ?? '',
75
+ type: (await link.getAttribute('type')) ?? '',
76
+ sizes: (await link.getAttribute('sizes')) ?? '',
77
+ });
78
+ return found;
79
+ }).pipe(Effect.orElseSucceed(() => []))
80
+ : [];
81
+ const icons = [
82
+ ...bestIconsFirst(links).map((link) => URL.parse(link.href, page.url())?.href),
83
+ URL.parse('/favicon.ico', origin)?.href,
84
+ ].filter((href) => href !== undefined && URL.parse(href)?.origin === origin);
85
+ return { title, icons: [...new Set(icons)].slice(0, SITE_ICONS_MAX) };
86
+ }).pipe(Effect.timeoutOption(Duration.millis(SIGN_IN_SITE_TIMEOUT_MS)), Effect.map((site) => Option.getOrElse(site, () => ({ title: undefined, icons: [] }))));
87
+ /**
88
+ * A browser a person drives from the live view (see `SignInBrowser`): one context of its own at
89
+ * `url`, its active tab streamed as JPEG frames through CDP's screencast (Chromium only), and their
90
+ * input played into that tab with Playwright's mouse and keyboard. Closed with the scope.
91
+ */
92
+ export const signInBrowser = (browser, url) => Effect.gen(function* () {
93
+ const context = yield* Effect.acquireRelease(attempt(() => browser.newContext({ viewport: SIGN_IN_VIEWPORT })), (context) => attempt(() => context.close()).pipe(Effect.ignore));
94
+ const first = yield* attempt(() => context.newPage());
95
+ // Boundary: Playwright reports frames, new tabs and closed tabs through event callbacks, so
96
+ // this state is plain variables they update.
97
+ let latest;
98
+ let seq = 0;
99
+ let viewport = { ...SIGN_IN_VIEWPORT };
100
+ let active = first;
101
+ let cast;
102
+ const open = [first];
103
+ /** Streams `page`'s frames from now on, and stops the tab streamed before. */
104
+ const stream = async (page) => {
105
+ const before = cast;
106
+ cast = undefined;
107
+ await before?.detach().catch(() => undefined);
108
+ if (page.isClosed() || page !== active)
109
+ return;
110
+ const session = await page.context().newCDPSession(page);
111
+ cast = session;
112
+ session.on('Page.screencastFrame', (frame) => {
113
+ session.send('Page.screencastFrameAck', { sessionId: frame.sessionId }).catch(() => { });
114
+ if (cast !== session)
115
+ return;
116
+ latest = {
117
+ seq: ++seq,
118
+ jpeg: frame.data,
119
+ width: Math.round(frame.metadata.deviceWidth),
120
+ height: Math.round(frame.metadata.deviceHeight),
121
+ url: page.url(),
122
+ };
123
+ });
124
+ await session.send('Page.startScreencast', {
125
+ format: 'jpeg',
126
+ quality: FRAME_QUALITY,
127
+ maxWidth: viewport.width,
128
+ maxHeight: viewport.height,
129
+ everyNthFrame: 1,
130
+ });
131
+ };
132
+ /** Makes `page` the one shown and driven. */
133
+ const activate = (page) => {
134
+ active = page;
135
+ stream(page).catch(() => undefined);
136
+ };
137
+ context.on('page', (page) => {
138
+ open.push(page);
139
+ page.setViewportSize(viewport).catch(() => undefined);
140
+ page.on('close', () => {
141
+ open.splice(open.indexOf(page), 1);
142
+ const last = open.at(-1);
143
+ if (active === page && last !== undefined)
144
+ activate(last);
145
+ });
146
+ activate(page);
147
+ });
148
+ first.on('close', () => {
149
+ open.splice(open.indexOf(first), 1);
150
+ const last = open.at(-1);
151
+ if (active === first && last !== undefined)
152
+ activate(last);
153
+ });
154
+ yield* attempt(() => stream(first));
155
+ // A page that is slow or fails to load still opens: the person sees what it shows.
156
+ yield* attempt(() => first.goto(url, { timeout: SIGN_IN_LOAD_TIMEOUT_MS })).pipe(Effect.ignore);
157
+ const site = yield* readSite(first, URL.parse(url)?.origin ?? url);
158
+ /**
159
+ * Runs one input against the active tab, giving it up after a while; whether it was played
160
+ * (false when Playwright failed or it timed out, so the live view can say so).
161
+ */
162
+ const play = (run) => attempt(() => run(active)).pipe(Effect.timeout(Duration.millis(SIGN_IN_INPUT_TIMEOUT_MS)), Effect.as(true), Effect.orElseSucceed(() => false));
163
+ const input = (event) => {
164
+ switch (event.type) {
165
+ case 'mouse':
166
+ return play(async (page) => {
167
+ await page.mouse.move(event.x, event.y);
168
+ const options = {
169
+ ...(event.button !== undefined ? { button: event.button } : {}),
170
+ ...(event.clickCount !== undefined ? { clickCount: event.clickCount } : {}),
171
+ };
172
+ if (event.kind === 'down')
173
+ await page.mouse.down(options);
174
+ if (event.kind === 'up')
175
+ await page.mouse.up(options);
176
+ });
177
+ case 'wheel':
178
+ return play(async (page) => {
179
+ await page.mouse.move(event.x, event.y);
180
+ await page.mouse.wheel(event.dx, event.dy);
181
+ });
182
+ case 'key':
183
+ return play((page) => page.keyboard.press([...(event.modifiers ?? []), event.key].join('+')));
184
+ case 'text':
185
+ return play((page) => page.keyboard.insertText(event.text));
186
+ case 'nav':
187
+ return play((page) => event.kind === 'back'
188
+ ? page.goBack({ waitUntil: 'commit' })
189
+ : event.kind === 'forward'
190
+ ? page.goForward({ waitUntil: 'commit' })
191
+ : page.reload({ waitUntil: 'commit' }));
192
+ case 'viewport':
193
+ return Effect.suspend(() => {
194
+ const next = {
195
+ width: clamp(event.width, SIGN_IN_VIEWPORT_RANGE.width),
196
+ height: clamp(event.height, SIGN_IN_VIEWPORT_RANGE.height),
197
+ };
198
+ if (next.width === viewport.width && next.height === viewport.height)
199
+ return Effect.succeed(true);
200
+ viewport = next;
201
+ return Effect.forEach(open, (page) => attempt(() => page.setViewportSize(next)), {
202
+ discard: true,
203
+ }).pipe(
204
+ // The screencast keeps the size it started with; start it again at the new one.
205
+ Effect.andThen(attempt(() => stream(active))), Effect.timeout(Duration.millis(SIGN_IN_INPUT_TIMEOUT_MS)),
206
+ // A viewport that could not change loses nothing the person did.
207
+ Effect.ignore, Effect.as(true));
208
+ });
209
+ }
210
+ };
211
+ const frame = (after, waitMs) => Effect.sync(() => (latest !== undefined && latest.seq > after ? latest : undefined)).pipe(Effect.repeat({
212
+ until: (found) => found !== undefined,
213
+ schedule: Schedule.spaced(Duration.millis(FRAME_POLL_MS)),
214
+ }), Effect.timeoutOption(Duration.millis(waitMs)), Effect.map((found) => Option.getOrUndefined(found)));
215
+ const save = (origin) => attempt(() => context.storageState({ indexedDB: true })).pipe(Effect.map((state) => `${JSON.stringify(stateOfSite(state, origin), null, 2)}\n`));
216
+ return { site, frame, input, save };
217
+ });
@@ -1,5 +1,5 @@
1
1
  {
2
- "id": "2026-11-12T23:03:45.746Z-3e69166f",
3
- "builtAt": "2026-11-12T23:03:45.746Z",
4
- "commit": "03c1d38f8dc97cafd0094c71661f8aa9f30de50b"
2
+ "id": "2026-11-13T00:59:51.438Z-4af8fe21",
3
+ "builtAt": "2026-11-13T00:59:51.438Z",
4
+ "commit": "ec971e4c0742db6553f710b938697b5eeaa1131c"
5
5
  }
package/dist/cli/app.js CHANGED
@@ -14,6 +14,7 @@ import { ReportLinks, ReportServerLauncher, SERVE_REPORTS_COMMAND } from './repo
14
14
  import { ReportServer } from './report-server.js';
15
15
  import { PlaywrightDownloads, Setup } from './setup.js';
16
16
  import { ShareSource } from './share.js';
17
+ import { SignIns } from './sign-in.js';
17
18
  import { CLI_WAIT, UpdateCheck } from './update-check.js';
18
19
  /** Progress goes nowhere yet; the terminal and MCP notifiers come with real runs. */
19
20
  const NotifierSilent = Layer.succeed(Notifier, { notify: () => Effect.void });
@@ -40,7 +41,9 @@ export const appLayer = (projectRoot) => {
40
41
  const engine = engineLayer(projectRoot);
41
42
  // What the report servers share runs with: the same engine as everything else.
42
43
  const share = ShareSource.layer.pipe(Layer.provide(engine));
43
- const operations = Operations.layer(projectRoot).pipe(Layer.provide(engine),
44
+ const operations = Operations.layer(projectRoot).pipe(
45
+ // Sign-ins open on first need, with the engine's browser and account book.
46
+ Layer.provide(SignIns.layer.pipe(Layer.provide(NodeHttpClient.layerNodeHttp))), Layer.provide(engine),
44
47
  // Starts nothing until the MCP server first gives a report URL.
45
48
  Layer.merge(ReportServer.layer(projectRoot).pipe(Layer.provide(share))),
46
49
  // For `report --serve` and `walkthrough --serve`.
@@ -1,13 +1,14 @@
1
- import { Console, Data, Effect, Option, Path } from 'effect';
1
+ import { Console, Data, Duration, Effect, Option, Path } from 'effect';
2
2
  import { Argument, Command, Flag } from 'effect/cli';
3
3
  import { summaryOf } from '../schema/index.js';
4
4
  import { renderPrSummary } from '../report/index.js';
5
5
  import { readFindingsFile, readSpecFile } from './config.js';
6
- import { analyticsEnabled, isNonInteractive } from './environment.js';
6
+ import { analyticsEnabled, isCi, isNonInteractive } from './environment.js';
7
7
  import { ExitCode } from './exit-codes.js';
8
8
  import { Failure, notImplemented } from './failure.js';
9
9
  import { allPassed, countsSentence, formatEvidence, formatFindings, serveMcp, } from './mcp.js';
10
10
  import { Operations } from './operations.js';
11
+ import { SIGN_IN_IDLE } from './sign-in.js';
11
12
  import { ReportLinks } from './report-links.js';
12
13
  import { fileUrl, startReportServer } from './report-server.js';
13
14
  import { AGENT_IDS, DOWNLOAD_NAMES, Setup } from './setup.js';
@@ -398,6 +399,70 @@ const answer = Command.make('answer', {
398
399
  yield* (yield* Operations).answer(flags);
399
400
  yield* flags.json ? printJson({ ok: true }) : Console.log('Answer sent.');
400
401
  }))).pipe(Command.withDescription('Answer a question a waiting run has asked'));
402
+ const accountsList = Command.make('accounts', { json }, (flags) => handle(flags.json)(Effect.gen(function* () {
403
+ const { file, accounts } = yield* (yield* Operations).accounts;
404
+ if (flags.json)
405
+ return yield* printJson({ ok: true, file, accounts });
406
+ if (accounts.length === 0)
407
+ return yield* Console.log('No test accounts yet. Sign in to one with `npx screw-bugs accounts sign-in <label> --url <url> --about "<what kind of user>"`.');
408
+ const width = Math.max(...accounts.map((a) => a.label.length));
409
+ yield* Console.log([
410
+ ...accounts.map((a) => `${a.label.padEnd(width)} ${a.origin} saved ${a.savedAt.slice(0, 16).replace('T', ' ')} UTC` +
411
+ (a.about !== undefined ? ` ${a.about}` : '')),
412
+ file,
413
+ ].join('\n'));
414
+ })));
415
+ const accountSignIn = Command.make('sign-in', {
416
+ json,
417
+ label: Argument.String('label'),
418
+ url: Flag.String('url').pipe(Flag.withDescription('URL of the app to sign in on; the account is saved for its origin')),
419
+ about: Flag.String('about').pipe(Flag.withDescription('What kind of user this is, such as "On a 14-day trial", for agents picking an account'), Flag.optional),
420
+ }, (flags) => handle(flags.json)(Effect.gen(function* () {
421
+ if (yield* isCi)
422
+ return yield* new Failure({
423
+ code: ExitCode.Usage,
424
+ reason: 'sign_in_in_ci',
425
+ message: 'Signing in to a test account needs a person, so it never runs in CI.',
426
+ });
427
+ const { link, done } = yield* (yield* Operations).signIn({
428
+ label: flags.label,
429
+ url: flags.url,
430
+ about: Option.getOrUndefined(flags.about),
431
+ });
432
+ // The link goes out before the wait, also with --json (to stderr, so stdout stays JSON).
433
+ const lines = [
434
+ `Open this link, sign in as ${flags.label} and press Save sign-in. It closes after ` +
435
+ `${Duration.toMinutes(SIGN_IN_IDLE)} minutes without use, or with Ctrl+C.`,
436
+ link,
437
+ ].join('\n');
438
+ yield* flags.json ? Console.error(lines) : Console.log(lines);
439
+ const outcome = yield* done;
440
+ if (outcome !== 'saved')
441
+ return yield* new Failure({
442
+ code: ExitCode.SignInNeeded,
443
+ reason: 'sign_in_not_saved',
444
+ message: outcome === 'idle'
445
+ ? `Nothing was saved: the sign-in page was not used for ${Duration.toMinutes(SIGN_IN_IDLE)} minutes.`
446
+ : 'Nothing was saved: the sign-in was cancelled.',
447
+ });
448
+ const { file } = yield* (yield* Operations).accounts;
449
+ yield* flags.json
450
+ ? printJson({ ok: true, label: flags.label, file })
451
+ : Console.log(`Saved test account ${flags.label}.\n${file}`);
452
+ }))).pipe(Command.withDescription('Sign in to a test account in a live view of a browser (any browser that reaches this machine), and save its session'));
453
+ const accountRemove = Command.make('remove', { json, label: Argument.String('label') }, (flags) => handle(flags.json)(Effect.gen(function* () {
454
+ const removed = yield* (yield* Operations).removeAccount(flags.label);
455
+ if (!removed)
456
+ return yield* new Failure({
457
+ code: ExitCode.Usage,
458
+ reason: 'account_not_found',
459
+ message: `There is no test account ${flags.label}.`,
460
+ });
461
+ yield* flags.json
462
+ ? printJson({ ok: true, label: flags.label })
463
+ : Console.log(`Removed test account ${flags.label} and its session.`);
464
+ }))).pipe(Command.withDescription('Remove a test account and its saved session'));
465
+ const accounts = accountsList.pipe(Command.withDescription('List the test accounts runs can start signed in as; sign in to one, or remove one'), Command.withSubcommands([accountSignIn, accountRemove]));
401
466
  const mcp = Command.make('mcp', {}, () => serveMcp).pipe(Command.withDescription('Serve the screw-bugs MCP server over stdio, for coding agents'));
402
467
  const analytics = Command.make('analytics', { json, setting: Argument.String('on|off').pipe(Argument.optional) }, (flags) => handle(flags.json)(Effect.gen(function* () {
403
468
  if (Option.isSome(flags.setting))
@@ -415,7 +480,7 @@ export const root = Command.make('screw-bugs').pipe(Command.withDescription('Loc
415
480
  mcp,
416
481
  setup,
417
482
  init,
418
- stub('accounts', 'Manage the test accounts runs can log in with'),
483
+ accounts,
419
484
  report,
420
485
  walkthrough,
421
486
  findings,
@@ -26,6 +26,12 @@ export declare const ExitCode: {
26
26
  * safely, or not writable), so it left the file alone. The output gives the entry to add.
27
27
  */
28
28
  readonly SetupIncomplete: 8;
29
+ /**
30
+ * The job's test account has no session a run can start from (none saved, saved for another
31
+ * origin, expired, or `renew`), so nothing was started. The message gives the link (MCP) or
32
+ * the command (CLI) for a person to sign in; then start the run again.
33
+ */
34
+ readonly SignInNeeded: 9;
29
35
  /** A bug in screw-bugs. */
30
36
  readonly Internal: 70;
31
37
  /**
@@ -26,6 +26,12 @@ export const ExitCode = {
26
26
  * safely, or not writable), so it left the file alone. The output gives the entry to add.
27
27
  */
28
28
  SetupIncomplete: 8,
29
+ /**
30
+ * The job's test account has no session a run can start from (none saved, saved for another
31
+ * origin, expired, or `renew`), so nothing was started. The message gives the link (MCP) or
32
+ * the command (CLI) for a person to sign in; then start the run again.
33
+ */
34
+ SignInNeeded: 9,
29
35
  /** A bug in screw-bugs. */
30
36
  Internal: 70,
31
37
  /**