iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / installer / test / flow.mjsmain at aacbc74

// THE DOMAIN WIZARD, END TO END, against a fake Cloudflare (fake-cloudflare.mjs): the built app
// (dist/client) and the Worker (worker/index.js) served locally, four paths, a captioned video.
//   pnpm build && node test/flow.mjs [--mobile] [--headed]
// Writes test/out/<desktop|mobile>/flow.mp4, screenshots of each step, and exits non-zero on failure.
import http from "node:http";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { dirname, extname, join } from "node:path";
import { chromium, devices } from "@playwright/test";
import { startFakeCloudflare } from "./fake-cloudflare.mjs";
import { recordDeployment } from "../pretend/world.js";
import { AHEAD, COMMIT, plan, stateAt, STEPS } from "../worker/pretend-run.js";
import { useCommits } from "../worker/stack-commits.js";
import { trustOf } from "../worker/access.js";
import { firstOwnerTicket, withTicket } from "../worker/first-owner.js";

const here = dirname(fileURLToPath(import.meta.url));
const app = join(here, "..");
const worker = (await import(join(app, "worker/index.js"))).default;
const tablet = process.argv.includes("--tablet"); // a narrow window on a laptop: the phone layout, no touch
const quiet = process.argv.includes("--quiet"); // no captions: screenshots of the page alone
const mobile = process.argv.includes("--mobile") || tablet;
const headed = process.argv.includes("--headed");
const OUT = join(
  here,
  "out",
  (tablet ? "tablet" : mobile ? "mobile" : "desktop") + (quiet ? "-plain" : ""),
);
rmSync(OUT, { recursive: true, force: true });
mkdirSync(OUT, { recursive: true });

// ── the fake Cloudflare, the Worker and its static files ──
const cf = await startFakeCloudflare({
  user: { email: "ada@example.com", first: "Ada", last: "Lovelace" },
  accounts: [{ id: "a".repeat(32), name: "Ada's account", paid: true, r2: true }],
  taken: ["adalovelace.com", "lovelace.com", "ada.com"],
});
// someone else has the first workers.dev name from Ada's email: the wizard takes the second
cf.state.takenSubdomains.push("iterate-ada-example");
const kv = new Map();
// The Deployer, faked: the pretend run (worker/pretend-run.js) at four times its speed. Like the real
// one (worker/deploy-run.js) it takes the token with it and gives it up at the run's end.
const runs = new Map();
/** The commit of iterate that a stack runs, where its boundary Worker says one: by the run's key. */
const stackRuns = new Map();
// this Cloud has the one commit that the pretend run deploys
useCommits(`${COMMIT}\n`);
/** The next run fails at its deploy step (the pretend run's "broken" zone), and then gives up its access. */
let failNextRun = false;
/** The next run works on a stack older than its Dash and its self-test page (the
 *  pretend run's "stale" zone): the run says that it saw neither answer. */
let staleNextRun = false;
/** The next run deploys, and then its access still works after the revoke (the pretend run's "sticky" zone). */
let stickNextRun = false;
/** The next run finds an iterate from before 11 November 2026 (the pretend run's "older" zone). */
let olderNextRun = false;
const claimed = new Set();
const fakeDeployer = (key) => ({
  async start(args) {
    const awkward = failNextRun
      ? "broken"
      : staleNextRun
        ? "stale"
        : stickNextRun
          ? "sticky"
          : olderNextRun
            ? "older"
            : null;
    const planned = plan(
      {
        ...args,
        ...(awkward && { zone: `${awkward}.${args.zone}` }),
        runs: stackRuns.get(key),
      },
      1,
    );
    failNextRun = false;
    staleNextRun = false;
    stickNextRun = false;
    olderNextRun = false;
    const run = { ...planned, startedAt: Date.now(), zone: args.zone, args };
    // as the real one: a first deploy makes the first owner's ticket, and the page gets it once
    const owner = args.ownerEmails ? args.ownerEmails[0] : args.recoverOwner;
    run.first = owner ? await firstOwnerTicket(owner) : null;
    runs.set(key, run);
    return { began: true, state: stateAt(run, 0) };
  },
  async status(shown = false) {
    const run = runs.get(key);
    if (!run)
      return {
        status: "idle",
        startedAt: null,
        endedAt: null,
        lines: [],
        steps: STEPS,
        result: null,
      };
    const state = stateAt(run, (Date.now() - run.startedAt) * 4);
    if (state.status !== "running" && !run.revoked) {
      run.revoked = true;
      await fetch(env.CF_REVOKE, {
        method: "POST",
        body: new URLSearchParams({ token: run.args.token, client_secret: env.CLIENT_SECRET }),
      });
    }
    if (shown && state.status === "succeeded" && run.first && !run.given) {
      run.given = true;
      return withTicket(state, run.first);
    }
    return state;
  },
  async kept() {
    return {
      records: runs.has(key)
        ? [{ where: "Durable Object storage", key: "state", what: "The run's state and its log." }]
        : [],
    };
  },
});
const CLIENT = join(app, "dist/client");
const types = {
  ".html": "text/html; charset=utf-8",
  ".js": "text/javascript",
  ".css": "text/css",
  ".svg": "image/svg+xml",
};
// the Cloud's key, made here; and the deployment the wizard makes is faked here, so that the Cloud's
// enrolment after a run reaches no real host. It answers nothing until `deployment.answers`, as a
// new address does; then it serves its key and takes the Cloud's statement.
const p256 = () =>
  crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);
const cloudKey = await p256();
const spki = Buffer.from(await crypto.subtle.exportKey("spki", (await p256()).publicKey));
const deployment = {
  answers: false,
  // its Dash is mounted: a signed-out visit is sent to its sign-in
  onboarding: false,
  key: {
    mind: "adalovelace-dev",
    key: Buffer.from(await crypto.subtle.digest("SHA-256", spki)).toString("base64url"),
    publicKey: spki.toString("base64url"),
  },
};
/** Domains of Path 7's other stacks: each one's iterate answers, and nothing else on it does. */
const OTHER_DOMAINS = ["ada-family.dev", "adavault.dev", "adashared.dev", "iterate.com"];
const realFetch = globalThis.fetch;
globalThis.fetch = (input, init) => {
  const url = new URL(input.url || input);
  const other = OTHER_DOMAINS.find((domain) => url.hostname.endsWith(`.${domain}`));
  if (other)
    return Promise.resolve(
      url.hostname === `iterate.${other}`
        ? new Response("ok")
        : new Response("Not found", { status: 404 }),
    );
  if (url.hostname === "dash.adalovelace.dev")
    return Promise.resolve(
      deployment.answers && deployment.onboarding
        ? new Response(null, {
            status: 302,
            headers: { location: "https://iterate.adalovelace.dev/oauth2/auth?client_id=host" },
          })
        : new Response("Not found", { status: 404 }),
    );
  if (url.hostname !== "iterate.adalovelace.dev") return realFetch(input, init);
  if (!deployment.answers) return Promise.resolve(new Response("", { status: 404 }));
  return Promise.resolve(
    url.pathname === "/keys/stack.json" ? Response.json(deployment.key) : new Response("ok"),
  );
};
const env = {
  CLIENT_ID: "fake-client",
  CLIENT_SECRET: "fake-secret",
  CF_API: `${cf.origin}/client/v4`,
  CF_AUTH: `${cf.origin}/oauth2/auth`,
  CF_TOKEN: `${cf.origin}/oauth2/token`,
  CF_REVOKE: `${cf.origin}/oauth2/revoke`,
  CF_DASH: `${cf.origin}/dash/`,
  CLOUD_KEY: JSON.stringify(await crypto.subtle.exportKey("jwk", cloudKey.privateKey)),
  SESSIONS: {
    get: async (k) => kv.get(k) ?? null,
    put: async (k, v) => void kv.set(k, v),
    delete: async (k) => void kv.delete(k),
  },
  DEPLOYER: {
    // `sign-ins` keeps which sign-in's token is spoken for (worker/cloudflare-access.js)
    getByName: (key) =>
      key === "sign-ins"
        ? { claim: async (id) => !claimed.has(id) && !!claimed.add(id) }
        : fakeDeployer(key),
  },
  ROUTES: {
    idFromName: (name) => name,
    get: () => ({
      clientsOf: async (domain) => (domain === "adalovelace.dev" ? { github: 2 } : {}),
    }),
  },
  // Workers' static assets, single-page: a file if there is one, else index.html
  ASSETS: {
    fetch: async (request) => {
      const path = new URL(request.url).pathname;
      const file = join(CLIENT, path);
      const hit = path !== "/" && existsSync(file) ? file : join(CLIENT, "index.html");
      return new Response(readFileSync(hit), {
        headers: { "content-type": types[extname(hit)] || "application/octet-stream" },
      });
    },
  },
};
const site = http.createServer(async (req, res) => {
  const body = await new Promise((r) => {
    const c = [];
    req.on("data", (d) => c.push(d));
    req.on("end", () => r(Buffer.concat(c)));
  });
  const answer = await worker.fetch(
    new Request(`http://${req.headers.host}${req.url}`, {
      method: req.method,
      headers: req.headers,
      body: ["GET", "HEAD"].includes(req.method) ? undefined : body,
    }),
    env,
  );
  // each Set-Cookie is its own header: an object of the headers keeps the last one only
  const cookies = answer.headers.getSetCookie();
  res.writeHead(answer.status, {
    ...Object.fromEntries(answer.headers),
    ...(cookies.length ? { "set-cookie": cookies } : {}),
  });
  res.end(Buffer.from(await answer.arrayBuffer()));
});
await new Promise((r) => site.listen(0, "127.0.0.1", r));
const SITE = `http://localhost:${site.address().port}`;

// ── the browser, recorded ──
const size = tablet
  ? { width: 820, height: 1100 }
  : mobile
    ? { width: 390, height: 844 }
    : { width: 1280, height: 900 };
const browser = await chromium.launch({ headless: !headed });
const context = await browser.newContext({
  ...(mobile && !tablet ? { ...devices["iPhone 13"], defaultBrowserType: undefined } : {}),
  viewport: size,
  recordVideo: { dir: OUT, size },
  colorScheme: "dark", // the page must stay light whatever the system prefers
  locale: "en-GB", // the registrant's country starts as the browser's
  permissions: ["clipboard-read", "clipboard-write"], // "Copy for an agent", read back
});
const page = await context.newPage();
page.setDefaultTimeout(15_000);
const pause = (ms) => page.waitForTimeout(ms);
let failures = 0,
  shot = 0;
const check = async (what, fn) => {
  try {
    await fn();
    console.log(`  ✓ ${what}`);
  } catch (error) {
    failures++;
    console.log(
      `  ✗ ${what}\n    ${String(error.message || error)
        .split("\n")
        .slice(0, 4)
        .join("\n    ")}`,
    );
    await page.screenshot({ path: join(OUT, `fail-${failures}.png`), fullPage: true });
    throw error;
  }
};
const snap = (name) =>
  page.screenshot({
    path: join(OUT, `${String(++shot).padStart(2, "0")}-${name}.png`),
    fullPage: true,
  });
const caption = async (text, ms = 1400) => {
  if (quiet) return;
  await page
    .evaluate((t) => {
      let el = document.getElementById("__caption");
      if (!el) {
        el = document.createElement("div");
        el.id = "__caption";
        el.style.cssText =
          "position:fixed;left:50%;bottom:18px;transform:translateX(-50%);z-index:99999;background:rgba(17,17,17,.9);color:#fff;font:600 15px/1.4 system-ui;padding:10px 16px;border-radius:12px;width:max-content;max-width:calc(100% - 24px);text-align:center;box-shadow:0 6px 24px rgba(0,0,0,.3);pointer-events:none";
        document.body.appendChild(el);
      }
      el.textContent = t;
    }, text)
    .catch(() => {});
  await pause(ms);
};
const see = (re) => page.getByText(re).first().waitFor();
const inCloudflare = async (linkName, buttonText) => {
  const [tab] = await Promise.all([
    context.waitForEvent("page"),
    page.getByRole("link", { name: linkName }).first().click(),
  ]);
  await tab.waitForLoadState();
  await tab.getByRole("button", { name: buttonText }).click();
  await tab.getByText("Saved for").waitFor();
  await tab.close();
  await page.bringToFront();
  await page.evaluate(() => window.dispatchEvent(new Event("focus")));
};
/** A step asks for Cloudflare again: connect, tick the account, and come back. */
const reconnect = async (from = "[data-reconnect]") => {
  await page.locator(from).getByRole("link", { name: "Connect Cloudflare" }).click();
  await page.locator("label.acct", { hasText: "iterate" }).locator("input").check();
  await page.getByRole("button", { name: "Authorize" }).click();
};
/** Back a step: the Back button on a phone, the step list beside the content on a wide screen. */
const goBack = async (step) =>
  mobile
    ? page.getByRole("button", { name: "Back", exact: true }).click()
    : page
        .getByRole("navigation", { name: "Steps" })
        .getByRole("button", { name: new RegExp(`^${step}`) })
        .click();

/** The shell's sidebar on `p`: there on a wide screen (as its rail), behind the trigger on a phone. */
const openSidebar = async (p) => {
  if (mobile && !tablet) await p.getByRole("button", { name: "Toggle sidebar" }).click();
  return p.locator('[data-slot="sidebar"]:visible, [data-sidebar="sidebar"]:visible').first();
};
const closeSidebar = async (p) => {
  if (mobile && !tablet) await p.keyboard.press("Escape");
};

const fillContact = async () => {
  await page.getByLabel("Phone").fill("020 7123 4567"); // as people write it: the page adds +44.
  await page.getByLabel("Street").fill("12 St James's Square");
  await page.getByLabel("City").fill("London");
  await page.getByLabel("Postcode").fill("SW1Y 4LB");
};

try {
  console.log(`Path 1 (${mobile ? "mobile" : "desktop"}): a new account, then buy a domain`);
  await page.goto(SITE);
  await check(
    "the shell: a sidebar that starts as its rail, the iterate mark, nobody signed in",
    async () => {
      await page.getByRole("heading", { level: 2 }).first().waitFor();
      if (await page.locator("header img").count()) throw new Error("the old header is back");
      if (!mobile || tablet) {
        const state = await page
          .locator('[data-slot="sidebar"]')
          .first()
          .getAttribute("data-state");
        if (state !== "collapsed") throw new Error(`the sidebar starts ${state}`);
      }
      const bar = await openSidebar(page);
      await bar
        .locator('[data-slot="sidebar-header"] img, [data-slot="sidebar-header"] svg')
        .first()
        .waitFor();
      if (await bar.getByRole("button", { name: "Account" }).count())
        throw new Error("an account menu with nobody signed in");
      if (await page.getByRole("button", { name: "Search" }).count())
        throw new Error("a Search button with nothing to search");
      await closeSidebar(page);
      await snap("shell");
    },
  );
  await check(
    "the first step asks where iterate should run, a new account by default",
    async () => {
      await page.getByRole("radio", { name: /A new Cloudflare account/ }).waitFor();
      if (!(await page.getByRole("radio", { name: /A new Cloudflare account/ }).isChecked()))
        throw new Error("not new");
    },
  );
  await check(
    "nobody signed in is told that sign-up is by personal walkthrough, with the way to the waiting list",
    async () => {
      await page
        .locator("[data-walkthrough-only]")
        .getByText(/Sign-up is by personal walkthrough only/)
        .waitFor();
      const href = await page.locator("[data-waiting-list]").getAttribute("href");
      if (href !== "https://iterate.com/#waiting-list") throw new Error(`leads to ${href}`);
    },
  );
  await check("light mode, even on a dark system", async () => {
    const bg = await page.evaluate(() => getComputedStyle(document.body).backgroundColor);
    const [r, g, b] = bg.match(/\d+/g).map(Number);
    if (r + g + b < 600) throw new Error(`body is ${bg}`);
  });
  await snap("start");
  await caption(
    "Setting up iterate. First: where should it run? A new Cloudflare account is recommended.",
    2000,
  );
  await check(
    "a new account: the page says that Cloudflare can list accounts and any one will do, and says what iterate keeps",
    async () => {
      await page
        .locator("[data-any-account]")
        .getByText(/If it asks you to pick an account, pick any one/)
        .waitFor();
      await page
        .locator("[data-keeps-no-access]")
        .getByText(/iterate keeps no long-lived access to your Cloudflare account/)
        .waitFor();
      // iterate keeps no access (no offline_access), so the page must not say it does
      if (await page.getByText(/Stay signed in/).count())
        throw new Error("says it stays signed in");
    },
  );
  await snap("heads-up");
  await caption("Cloudflare can show an account list: pick any one.", 1600);
  await check("no dialog stands between the choice and Cloudflare", async () => {
    await page.getByRole("link", { name: "Continue with Cloudflare" }).click();
    await page.waitForURL((url) => !url.href.startsWith(SITE));
  });
  await check("the first consent asks only who you are", async () => {
    const scope =
      new URL(page.url()).searchParams.get("scope") ||
      (await page.locator("input[name=scope]").inputValue());
    if (scope !== "user-details.read") throw new Error(scope);
  });
  await caption(
    "Cloudflare's consent page (a fake one). This first one only asks who you are.",
    1800,
  );
  await page.locator("input[name=account]").first().check();
  await page.getByRole("button", { name: "Authorize" }).click();

  await check(
    "the page says a new account is made now, and the step list shows the parts",
    async () => {
      await page.getByRole("heading", { name: "Create a new Cloudflare account" }).waitFor();
      if (mobile) await page.locator("[data-step-menu]").click();
      const nav = page.getByRole("navigation", { name: "Steps" });
      await nav.getByRole("button", { name: /Connect Cloudflare account/ }).waitFor(); // "1", then its name
      await nav.locator('[data-substep="done"]', { hasText: "New or existing account" }).waitFor();
      await nav.locator('[data-substep="now"]', { hasText: "Create a new account" }).waitFor();
      await nav.locator('[data-substep="todo"]', { hasText: "Give iterate access" }).waitFor();
      if (mobile) await page.keyboard.press("Escape");
    },
  );
  await check(
    "the sign-in's cookie goes with the page's own requests alone, and a write that the page did not send is refused",
    async () => {
      const cookies = await context.cookies(SITE);
      const sid = cookies.find((cookie) => cookie.name === "sid");
      if (!sid || sid.sameSite !== "Strict" || !sid.httpOnly) throw new Error(JSON.stringify(sid));
      if (cookies.some((cookie) => cookie.name.startsWith("state-")))
        throw new Error("the state's cookie stayed after the sign-in");
      // not through the browser: a page cannot choose its Origin
      const write = (headers) =>
        new Promise((resolve, reject) =>
          http
            .request(
              {
                host: "127.0.0.1",
                port: site.address().port,
                path: "/api/account/forget",
                method: "POST",
                headers: { host: new URL(SITE).host, cookie: `sid=${sid.value}`, ...headers },
              },
              (res) => resolve(res.resume().statusCode),
            )
            .on("error", reject)
            .end(headers["content-type"] ? "{}" : undefined),
        );
      const answers = [
        await write({ origin: "http://agents.localhost" }),
        await write({}),
        await write({ origin: SITE, "content-type": "text/plain" }),
      ];
      if (answers.join() !== "403,403,415") throw new Error(`answers ${answers.join()}`);
    },
  );
  await check("it fills in the name and email Cloudflare gave", async () => {
    if ((await page.getByLabel("Your name").inputValue()) !== "Ada Lovelace")
      throw new Error("name");
    if ((await page.getByLabel("Your email").inputValue()) !== "ada@example.com")
      throw new Error("email");
    if ((await page.getByLabel("Account name").inputValue()) !== "iterate-ada-example")
      throw new Error("account name");
  });
  await check(
    "before the account is made, it says that Cloudflare asks twice, and what to tick",
    async () => {
      await see(/Then Cloudflare asks a second time, for the new account/);
      await see(/turn on Account API Tokens Write, then press Authorize/);
      await page.locator("[data-without-tokens]").waitFor();
    },
  );
  await check("…and explains each permission of the full consent", async () => {
    await page.getByRole("button", { name: "What iterate asks Cloudflare for" }).click();
    await see(/Buy the domain you pick, in your account, when you confirm/);
  });
  await check(
    "…says why the list is long, and names the rest of the account that it asks",
    async () => {
      await see(/The account is iterate's own sandbox/);
      const rest = await page.locator("[data-wider]").innerText();
      for (const part of ["Workers, storage and data", "pipelines.write", "account-settings.write"])
        if (!rest.includes(part)) throw new Error(`no ${part} in: ${rest.slice(0, 200)}`);
      // the token scope is the one the person ticks: the words above the button name it
      if (rest.includes("account-api-tokens.write")) throw new Error("the token scope is in WIDER");
    },
  );
  await snap("create");
  await caption("We create a Cloudflare account named iterate for them.", 1600);
  await page.getByRole("button", { name: "Create account" }).click();
  await check(
    "the full consent follows at once, with all the permissions and the token scope",
    async () => {
      const n = Number(await page.locator("[data-permissions]").getAttribute("data-permissions"));
      if (!(n >= 117)) throw new Error(`${n} permissions`);
      if (
        !new URL(page.url()).searchParams
          .get("scope")
          ?.split(" ")
          .includes("account-api-tokens.write")
      )
        throw new Error("no token scope asked");
    },
  );
  await check("Cloudflare made the account, and its page lists it", () =>
    page.locator("label.acct", { hasText: "iterate" }).waitFor(),
  );
  await page.locator("label.acct", { hasText: "iterate" }).locator("input").check();
  await caption("…for the new account, which they select.");
  await page.getByRole("button", { name: "Authorize" }).click();

  await check("after the consent comes the domain, before any payment: three ways", async () => {
    await page.getByRole("heading", { name: "Pick a domain" }).waitFor();
    for (const h of ["buy", "have", "elsewhere"])
      await page.locator(`button[data-how="${h}"]`).waitFor();
    if (await page.locator("[data-item]").count()) throw new Error("the checklist is here");
  });
  await check(
    "…and with the new account connected, the Cloud no longer keeps that it made it",
    async () => {
      if (kv.has("created:" + "u".repeat(32))) throw new Error("still remembered");
    },
  );
  await snap("pick");
  await caption("Pick a domain: buy one, use one in Cloudflare, or one from elsewhere.", 2200);
  // an hour passes: Cloudflare ends the access, and iterate keeps no way to renew it
  await fetch(`${cf.origin}/_test/expire-tokens`, { method: "POST" });
  await page.locator('[data-how="buy"]').click();
  await check("when the access to Cloudflare is over, the step asks to connect again", () =>
    page.locator("[data-reconnect]").getByRole("link", { name: "Connect Cloudflare" }).waitFor(),
  );
  await snap("reconnect");
  await caption(
    "iterate keeps no lasting access to Cloudflare. After an hour, the step asks for it again…",
    2200,
  );
  await reconnect();
  await caption("…and they are back where they were.", 1200);
  await check("once they choose how, the other ways are gone, with a way back", async () => {
    await page.locator('[data-trail="How"]').getByText("Buy a new domain").waitFor();
    await page
      .locator('[data-trail="How"]')
      .getByRole("button", { name: /Change/ })
      .waitFor();
    if (await page.locator("[data-how]").count()) throw new Error("the other ways still show");
  });
  await check("six suggestions with prices, more on request, taken ones marked", async () => {
    await page.locator("[data-domain]").first().waitFor();
    if ((await page.locator("[data-domain]").count()) !== 6)
      throw new Error(`${await page.locator("[data-domain]").count()} shown`);
    await page.getByRole("button", { name: /^Show \d+ more$/ }).click();
    await page.locator('button[data-domain="adalovelace.dev"]').waitFor();
    await page.locator('[data-domain="adalovelace.com"][data-taken]').waitFor();
    if (await page.locator('button[data-domain="adalovelace.com"]').count())
      throw new Error("a taken name can be pressed");
  });
  await check("no test-mode switch for customers", async () => {
    if (await page.getByText(/Test mode/).count()) throw new Error("test mode shown");
  });
  await snap("suggestions");
  await caption(
    "Ideas from their name, checked with Cloudflare, with prices. Taken names are greyed out.",
    2200,
  );
  await page.locator('[data-domain="adalovelace.dev"]').click();
  await check(
    "a name to buy is chosen here and bought later: the page goes on to the account, and the step list says so",
    async () => {
      await page.getByRole("heading", { name: "Get your account ready" }).waitFor();
      if (await page.getByRole("button", { name: /Buy for/ }).count())
        throw new Error("a Buy button on an account that cannot pay yet");
      await page.locator("[data-buy-waits]").getByText("adalovelace.dev").waitFor();
      if (mobile) await page.locator("[data-step-menu]").click();
      const nav = page.getByRole("navigation", { name: "Steps" });
      await nav.getByRole("button", { name: /^Pick a domain adalovelace\.dev to buy/ }).waitFor();
      await nav.locator('[data-substep="todo"]', { hasText: "Buy adalovelace.dev" }).waitFor();
      if (mobile) await page.keyboard.press("Escape");
    },
  );

  const item = (title, state) =>
    page.locator(
      `[data-item="${title}"][data-state="${{ ok: "done", no: "todo" }[state] || state}"]`,
    );
  await check(
    "the checklist shows card, Workers Paid and R2 missing, card first; workers.dev is set by itself",
    async () => {
      for (const t of ["Payment method", "Workers Paid", "R2 storage"])
        await item(t, "no").waitFor();
      await item("workers.dev address", "ok").waitFor();
      await see(/iterate-ada-example-gzg4wi\.workers\.dev/);
      const order = await page
        .locator("[data-item]")
        .evaluateAll((els) => els.map((e) => e.dataset.item));
      if (order.indexOf("Payment method") > order.indexOf("Workers Paid"))
        throw new Error(order.join(", "));
    },
  );
  await check(
    "on an account the wizard made, the card's item says what Cloudflare's billing page can say at first",
    () =>
      item("Payment method", "no")
        .getByText(/can say “contact your administrator” for a minute or two/)
        .waitFor(),
  );
  await check("the step list shows the checklist as parts, the card next", async () => {
    await page.getByRole("heading", { name: "Get your account ready" }).waitFor();
    if (
      await page
        .locator("[data-step]")
        .getByText(/Into .*Cloudflare account/)
        .count()
    )
      throw new Error("the page still says which account");
    if (mobile) await page.locator("[data-step-menu]").click();
    const nav = page.getByRole("navigation", { name: "Steps" });
    await nav
      .getByRole("button", { name: /^Connect Cloudflare account iterate-ada-example ?Change$/ })
      .waitFor();
    await nav.locator('[data-substep="now"]', { hasText: "Payment method" }).waitFor();
    // two items of the account (workers.dev is done by itself), and the purchase of the name chosen before
    if ((await nav.locator('[data-substep="todo"]').count()) !== 3) throw new Error("not 3 to do");
    if (mobile) await page.keyboard.press("Escape");
  });
  await check("a step that polls has Check again, which asks Cloudflare at once", async () => {
    // The page's own question comes every 3 seconds: this one is on its way within one. It is
    // pressed twice, and each answer is waited for, before anything changes at Cloudflare: the
    // log then has the same answer twice running, which it counts as one row.
    for (let press = 0; press < 2; press++) {
      const asked = page.waitForRequest((r) => r.url().includes("/api/readiness"), {
        timeout: 1000,
      });
      await page.locator("[data-check-again]").click();
      await (await asked).response();
      await page.locator("[data-check-again]:not([disabled])").waitFor();
    }
  });
  await snap("ready-missing");
  await caption(
    "Each item turns green when Cloudflare says it's done. The page checks every 3 seconds.",
    4500,
  );
  await caption("First a payment method: it pays for everything after.", 1400);
  await inCloudflare("Add card", "Add payment method");
  await check("the payment method turns green, with the card", async () => {
    await item("Payment method", "ok").waitFor();
    await see(/Visa ending 4242/);
  });
  await inCloudflare("Subscribe", "Subscribe to Workers Paid");
  await check("Workers Paid turns green by itself", () => item("Workers Paid", "ok").waitFor());
  await caption("Subscribed, and it turned green by itself. Now R2.", 1400);
  await inCloudflare(/Turn on/, "Enable R2");
  await check("R2 turns green", () => item("R2 storage", "ok").waitFor());
  await check("going back to step 1 shows what was chosen, and Continue returns", async () => {
    await goBack("Connect Cloudflare account");
    if (mobile) {
      // a phone's Back goes one step: the domain is between the checklist and the account
      await page.locator('[data-chosen="adalovelace.dev"][data-to-buy]').waitFor();
      await goBack();
    }
    await page.getByRole("heading", { name: "Your Cloudflare account" }).waitFor();
    await see(/Authorized by ada@example\.com/);
    if (await page.getByRole("link", { name: "Authorize iterate" }).count())
      throw new Error("asks to authorize again");
  });
  await check("the sidebar's foot: who is signed in, and Sign out behind it", async () => {
    const bar = await openSidebar(page);
    await bar.getByRole("button", { name: "Account" }).click();
    await page.getByRole("menu").getByText("ada@example.com").waitFor();
    await page.getByRole("menuitem", { name: "Sign out" }).waitFor();
    await pause(300); // the menu fades in
    await snap("account-menu");
    await page.keyboard.press("Escape");
    await closeSidebar(page);
  });
  await check("…and on with the account: the name to buy, then the checklist", async () => {
    await page.getByRole("button", { name: "Continue", exact: true }).click();
    await page
      .locator('[data-chosen="adalovelace.dev"][data-to-buy]')
      .getByText(/You buy it in the next step/)
      .waitFor();
    await page.getByRole("button", { name: "Continue", exact: true }).click();
    await page.locator('[data-item="Payment method"]').waitFor();
  });
  if (mobile) {
    await check(
      'narrow: "Step 3 of 6" opens the list of steps, and a reached one is a way to it',
      async () => {
        const toggle = page.locator("[data-step-menu]");
        await toggle.click();
        const nav = page.getByRole("navigation", { name: "Steps" });
        // what was chosen at step 1: the account's name alone, on one line, and no "Change" link
        await nav
          .getByRole("button", { name: /^Connect Cloudflare account iterate-ada-example ?Change$/ })
          .waitFor();
        if (
          await nav
            .getByText("Change", { exact: true })
            .evaluateAll((els) => els.filter((el) => !el.classList.contains("sr-only")).length)
        )
          throw new Error('"Change" shows as text');
        if (await nav.getByRole("button", { name: /Deploy iterate/ }).isEnabled())
          throw new Error("a step not reached yet can be opened");
        await snap("step-menu");
        await nav.getByRole("button", { name: /^Connect Cloudflare account/ }).click();
        await page.getByRole("heading", { name: "Your Cloudflare account" }).waitFor();
        if (await nav.count()) throw new Error("the list stays open");
        await toggle.click();
        await page.keyboard.press("Escape");
        await nav.waitFor({ state: "detached" });
        await toggle.click();
        await nav.getByRole("button", { name: /Get your account ready/ }).click();
        await page.locator('[data-item="Payment method"]').waitFor();
      },
    );
  }
  if (!mobile)
    await check(
      "the step list beside the content shows what was done, and all parts ticked",
      async () => {
        const nav = page.getByRole("navigation", { name: "Steps" });
        await nav
          .getByRole("button", {
            name: /^Connect Cloudflare account iterate-ada-example ?Change$/,
          })
          .waitFor();
        await nav.locator('[data-substep="done"]', { hasText: "workers.dev address" }).waitFor();
        if ((await nav.locator('[data-substep="done"]').count()) !== 4)
          throw new Error("not 4 done");
        await nav.locator('[data-substep="now"]', { hasText: "Buy adalovelace.dev" }).waitFor();
      },
    );
  await snap("ready-green");
  await caption("All green. Now the domain they chose is paid for.", 1200);

  await check(
    "with every item green, the chosen name is bought here: who it's registered to, and the choice changeable",
    async () => {
      const buy = page.locator("[data-buy-chosen]");
      await buy.getByRole("heading", { name: "Register adalovelace.dev" }).waitFor();
      await buy
        .locator('[data-chosen="adalovelace.dev"]')
        .getByRole("button", { name: "Change" })
        .waitFor();
      if (await page.locator("[data-check-again]").count())
        throw new Error("Check again, with nothing left to check");
      if (await page.getByRole("button", { name: "Continue", exact: true }).count())
        throw new Error("a way on before the domain is bought");
    },
  );
  await check("a missing detail is named, and its field marked", async () => {
    await page.getByRole("button", { name: /Buy for/ }).click();
    await page
      .getByRole("alert")
      .getByText(/Fill in: Phone, Street, City, Postcode/)
      .waitFor();
    if ((await page.getByLabel("Street").getAttribute("aria-invalid")) !== "true")
      throw new Error("Street not marked");
  });
  await caption("Only when buying: who the domain is registered to.", 1400);
  await fillContact();
  await check("the marks go when they fill the fields in", async () => {
    if (await page.getByLabel("Street").getAttribute("aria-invalid"))
      throw new Error("Street still marked");
    if (await page.getByRole("alert").count()) throw new Error("the problem still shows");
  });
  await check(
    "a real purchase asks for no typing: the button names the price, and the card is named beside it",
    async () => {
      if (await page.getByLabel(/to confirm/).count()) throw new Error("type-to-confirm is back");
      await page.getByRole("button", { name: "Buy for $12.18" }).waitFor();
      await see(/Cloudflare charges your Visa ending 4242/);
    },
  );
  await pause(300); // the borders fade back
  await snap("purchase");
  await caption(
    "A real purchase: the button names the price, and what is charged is beside it.",
    1400,
  );
  await page.getByRole("button", { name: /Buy for/ }).click();
  await check("buying moves on to deploying iterate", async () => {
    await page.getByRole("heading", { name: "Deploy iterate" }).waitFor();
    await see(/iterate\.adalovelace\.dev/);
    if (!mobile)
      await page.getByRole("navigation", { name: "Steps" }).getByText("adalovelace.dev").waitFor();
  });
  await snap("deploy");
  await caption(
    "Bought. Next, iterate itself: deployed into their account from a container of ours.",
    2000,
  );
  await check("the deploy asks for the owner's email alone: no name, no password", async () => {
    if ((await page.getByLabel("Your email").inputValue()) !== "ada@example.com")
      throw new Error("email");
    if (await page.getByLabel(/Name of the new deployment/).count()) throw new Error("a name");
    if (await page.locator("main input[type=password]").count()) throw new Error("a password");
    // the owner signs in with a passkey: the page does not promise a mailed code
    if (await page.getByText(/code mailed/).count()) throw new Error("a mailed code");
    await page.getByText(/You sign in with a passkey/).waitFor();
    if (await page.getByText(/iterate takes all of/).count())
      throw new Error("a warning for a domain just bought");
  });
  await snap("deploy-setup");
  failNextRun = true;
  await page.locator("[data-step]").getByRole("button", { name: "Deploy iterate" }).click();
  await check(
    "a deploy that fails names the step that failed, not the run's last step, and says what to do",
    async () => {
      await page.locator('[data-phase="deploy"][data-state="failed"]').waitFor();
      for (const [id, state] of [
        ["check", "done"],
        ["answer", "todo"],
        ["verify", "todo"],
        ["forget", "done"],
      ])
        if ((await page.locator(`[data-phase="${id}"]`).getAttribute("data-state")) !== state)
          throw new Error(`the step ${id} is not ${state}`);
      const problem = page.locator('[data-deploy-failed="deploy"]');
      await problem.getByText("The deploy failed at “Deploy iterate”").waitFor();
      const error = await problem.locator("[data-deploy-error]").innerText();
      if (!/You do not have access to Cloudflare Containers/.test(error)) throw new Error(error);
      if (/revoked the access/.test(await problem.innerText()))
        throw new Error("the problem names the giving up of the access");
      await problem.getByText(/stays in your Cloudflare account\. Try again/).waitFor();
      // the activity log's newest line (the bar shows it) is the failure, not "give up the access"
      await page
        .locator("[data-log-bar], [data-log]")
        .filter({ hasText: "The deploy on adalovelace.dev failed at “Deploy iterate”" })
        .first()
        .waitFor({ state: "attached" });
    },
  );
  await snap("deploy-failed");
  await check(
    "…and its log copies for an agent: the domain, the step, the error, every line",
    async () => {
      await page.getByRole("button", { name: "Copy for an agent" }).click();
      await page.locator("[data-copy-deploy-log]").getByText("Copied").waitFor();
      const copied = await page.evaluate(() => navigator.clipboard.readText());
      for (const part of [
        "a deploy of iterate to adalovelace.dev",
        "It failed at the step “Deploy iterate”",
        "You do not have access to Cloudflare Containers",
        "```text\n",
        "== step forget",
      ])
        if (!copied.includes(part)) throw new Error(`no “${part}” in:\n${copied}`);
    },
  );
  await check("…and after a new consent the same button tries again", async () => {
    await page.getByRole("link", { name: "Connect Cloudflare to try again" }).click();
    await page.locator("label.acct", { hasText: "iterate" }).locator("input").check();
    await page.getByRole("button", { name: "Authorize" }).click();
    await page.locator("[data-step]").getByRole("button", { name: "Try again" }).click();
    await page.locator("[data-deploy-failed]").waitFor({ state: "detached" });
  });
  await check("the deploy runs the run's steps, with a live log", async () => {
    await page.locator('[data-phase="check"][data-state="done"]').waitFor();
    // open while the run goes: nothing to press
    await page.locator("[data-deploy-log]").getByText("› deploy").waitFor();
    await page.getByRole("button", { name: "Hide the deploy log" }).waitFor();
  });
  await caption("Each step of the deploy ticks off, and the log streams in.", 1600);
  const run = [...runs.values()].at(-1).args;
  await check(
    "the run got the domain, the owner, who it trusts and iterate Cloud's key, and took the access with it",
    async () => {
      if (run.zone !== "adalovelace.dev" || run.name !== "adalovelace-dev")
        throw new Error(`${run.zone} as ${run.name}`);
      if (run.ownerEmails.join() !== "ada@example.com") throw new Error("the owner");
      // a new stack trusts no hosted app to sign people in
      if (run.trustedClients !== undefined) throw new Error("the trusted clients");
      if (JSON.stringify(run.keys) !== JSON.stringify(await trustOf(env)))
        throw new Error("the Cloud's key");
      if (run.cloudOrigin !== SITE) throw new Error(`the Cloud's origin: ${run.cloudOrigin}`);
      if (!run.token) throw new Error("no token");
      if ([...kv.keys()].some((k) => k.startsWith("t:")))
        throw new Error("the session still holds a token");
      if (![...kv.keys()].some((k) => /^dep:[0-9a-f]{32}:adalovelace-dev$/.test(k)))
        throw new Error("no record that the run exists");
    },
  );
  await check("it does not say live before the new address answers, and asks again", async () => {
    await page.locator("[data-waiting]").waitFor();
    const again = await page.waitForResponse(
      (r) => r.request().method() === "GET" && new URL(r.url()).pathname === "/api/deploy",
      { timeout: 8000 },
    );
    const d = await again.json();
    if (d.state.status !== "succeeded" || d.enrolled !== false)
      throw new Error(`status ${d.state.status}, enrolled ${d.enrolled}`);
    if (await page.locator("[data-deployed]").count()) throw new Error("it says live already");
    if (await page.getByText("iterate is live on adalovelace.dev").count())
      throw new Error("the log says live already");
  });
  await snap("deploy-waiting");
  deployment.answers = true;
  await check("iterate is live on the domain, with the way on under it", async () => {
    await page.locator('[data-deployed="adalovelace.dev"]').getByText("iterate is live").waitFor();
    await page
      .locator("[data-deployed]")
      .getByRole("button", { name: "Set up AI agents" })
      .waitFor();
    if (cf.state.tokens[run.token]) throw new Error("the token still works at Cloudflare");
  });
  await check("the Cloud knows the deployment's key", () => {
    if (!kv.has("enrolled:adalovelace.dev")) throw new Error("no record of the enrolment");
  });
  await snap("deployed");
  await check(
    "after a first deploy the passkey comes first: a link that signs the owner in once, with no mail",
    async () => {
      const { ticket, variable } = [...runs.values()].at(-1).first;
      // it is the next step on the "live" card already: the ticket's time runs
      const card = page.locator("[data-deployed]");
      await card.locator("[data-next-passkey]").waitFor();
      // a long domain may break anywhere; the ordinary words beside it never break in the middle
      const breaks = await card
        .locator("p", { hasText: "in your Cloudflare account" })
        .evaluate((p) => getComputedStyle(p).wordBreak);
      if (breaks === "break-all") throw new Error("the card breaks ordinary words");
      const onCard = await card.locator("a[data-first-passkey]").getAttribute("href");
      await card.getByRole("button", { name: "Set up AI agents" }).click();
      await page
        .locator("[data-step]")
        .getByRole("button", { name: "Continue", exact: true })
        .click();
      const href = await page
        .locator('[data-try-item="passkey"] a[data-first-passkey]')
        .getAttribute("href");
      // the ticket is in the fragment alone: it reaches no server's address or log
      // on the last page the stack is asked to send the owner on to its onboarding chat; on the
      // card it is not, because the agents have no AI yet and the person comes back to the wizard
      const onboarding = "https://dash.adalovelace.dev/agents/agents/main";
      const want = `https://iterate.adalovelace.dev/keys/first?next=${encodeURIComponent(onboarding)}#${ticket}`;
      if (href !== want) throw new Error(href);
      if (onCard !== `https://iterate.adalovelace.dev/keys/first#${ticket}`)
        throw new Error(`on the card: ${onCard}`);
      const start = await page
        .locator('[data-try-item="open"] a[data-onboarding]')
        .getAttribute("href");
      if (start !== onboarding) throw new Error(`onboarding: ${start}`);
      // no outside Dash: a new stack trusts no outside client. Its own Dash, an app on dash.<domain>, is the
      // third line: after the agent, before the self-test
      if (await page.locator('[data-try-item="mind"]').count()) throw new Error("a Dash line");
      const ids = await page
        .locator("[data-try-item]")
        .evaluateAll((els) => els.map((e) => e.dataset.tryItem));
      if (ids.slice(0, 4).join() !== "passkey,open,dash,self-test")
        throw new Error(`the order: ${ids}`);
      const dash = await page.locator('[data-try-item="dash"] a[data-dash]').getAttribute("href");
      if (dash !== "https://dash.adalovelace.dev/") throw new Error(`the Dash: ${dash}`);
      // the self-test runs on the stack, as its owner: the Cloud links to it
      const selfTest = await page.locator("[data-self-test]").first().getAttribute("href");
      if (!ids.includes("self-test") || !selfTest?.endsWith("iterate.adalovelace.dev/self-test"))
        throw new Error(`the self-test: ${selfTest}`);
      // the stack is told the owner, the ticket's hash and an end within 24 hours: not the ticket
      const told = JSON.parse(variable);
      const hash = createHash("sha256").update(ticket).digest("hex");
      if (told.email !== "ada@example.com" || told.hash !== hash) throw new Error(variable);
      const left = told.expires - Date.now();
      if (left <= 0 || left > 24 * 3600_000) throw new Error(`it ends in ${left} ms`);
      if (Buffer.from(ticket, "base64url").length !== 32 || variable.includes(ticket))
        throw new Error("the ticket");
      // the Cloud gave it once, and the page keeps it in memory alone
      const seen = await page.evaluate(async (ticket) => {
        const again = await (
          await fetch(`/api/deploy?account=${"a".repeat(32)}&zone=adalovelace.dev`)
        ).json();
        return {
          again: JSON.stringify(again).includes(ticket),
          text: document.body.innerText.includes(ticket),
          stored: JSON.stringify([{ ...localStorage }, { ...sessionStorage }]).includes(ticket),
          address: location.href.includes(ticket),
        };
      }, ticket);
      const where = Object.keys(seen).filter((k) => seen[k]);
      if (where.length) throw new Error(`the ticket is also in: ${where}`);
    },
  );
  await snap("try-first");
  await check(
    "back in this tab after the passkey's link, the Try step says the passkey is added",
    async () => {
      // the link opens in another tab: here it does not open, and the tab is left and shown again
      await page.locator('[data-try-item="passkey"] a[data-first-passkey]').evaluate((a) => {
        a.addEventListener("click", (e) => e.preventDefault(), { once: true });
        a.click();
      });
      // a tab switch in Safari, and in Firefox, fires visibilitychange alone: no blur or focus
      await page.evaluate(() => {
        Object.defineProperty(document, "visibilityState", { configurable: true, value: "hidden" });
        document.dispatchEvent(new Event("visibilitychange"));
        // the own property goes, and Document.prototype's "visible" shows again
        delete document.visibilityState;
        document.dispatchEvent(new Event("visibilitychange"));
      });
      await page.locator('[data-try-item="passkey"]').getByText("Passkey added").waitFor();
      if (await page.locator("a[data-first-passkey]").count())
        throw new Error("it still asks for the first passkey");
      const ids = await page
        .locator("[data-try-item]")
        .evaluateAll((els) => els.map((e) => e.dataset.tryItem));
      if (ids.slice(0, 2).join() !== "open,passkey") throw new Error(`the order: ${ids}`);
    },
  );
  // back over the AI agents step to Deploy
  await page.goBack();
  await page.getByRole("heading", { name: "Set up AI agents" }).waitFor();
  await page.goBack();
  await page.getByRole("heading", { name: "Deploy iterate" }).waitFor();
  await check("…and so does the live card on the Deploy step", async () => {
    await page.locator("[data-deployed] [data-passkey-added]").waitFor();
    if (await page.locator("[data-deployed] [data-next-passkey]").count())
      throw new Error("the card still asks for the first passkey");
  });
  const firstTicket = [...runs.values()].at(-1).first.ticket;
  await check(
    "a lost passkey: an update that the owner asks for makes a new link, for the owner's address",
    async () => {
      await page.getByRole("button", { name: "Lost your passkey?" }).click();
      await page.locator("[data-recover]").getByText("ada@example.com").waitFor();
      await reconnect("[data-recover]");
      // back from Cloudflare the section is open still, and the plain update is not in the way
      const again = page.locator("[data-recover]").getByRole("button", {
        name: "Update and get a new link",
      });
      await again.waitFor();
      if (await page.locator("[data-update]").isVisible())
        throw new Error("the plain update is open");
      await again.click();
      await page.locator('[data-phase="check"]').first().waitFor();
      const { args, first } = [...runs.values()].at(-1);
      if (args === run || args.ownerEmails) throw new Error("the recovery writes a config");
      if (args.recoverOwner !== "ada@example.com") throw new Error(`for ${args.recoverOwner}`);
      if (JSON.parse(first.variable).email !== "ada@example.com" || first.ticket === firstTicket)
        throw new Error("the ticket");
      const card = page.locator('[data-deployed="adalovelace.dev"]');
      await card.locator("[data-next-passkey]").waitFor();
      const href = await card.locator("a[data-first-passkey]").getAttribute("href");
      if (!href.endsWith(`#${first.ticket}`)) throw new Error(href);
      if (cf.state.tokens[args.token]) throw new Error("the token still works at Cloudflare");
    },
  );
  await snap("recovered");
  await check("an update asks for Cloudflare again, and sends no owner and no config", async () => {
    await page.getByRole("button", { name: "Update iterate" }).click();
    await reconnect("[data-update]");
    await page.locator("[data-update]").getByRole("button", { name: "Update iterate" }).click();
    await page.locator('[data-phase="check"]').first().waitFor();
    const update = [...runs.values()].at(-1).args;
    if (update === run || update.ownerEmails || update.recoverOwner)
      throw new Error("the update names an owner");
    await page.locator('[data-deployed="adalovelace.dev"]').waitFor();
    if (cf.state.tokens[update.token]) throw new Error("the token still works at Cloudflare");
  });
  await page.locator("[data-step]").getByRole("button", { name: "Set up AI agents" }).click();
  await check(
    "Set up AI agents: the ChatGPT plan first, then an OpenAI key, then Cloudflare credit",
    async () => {
      await page.getByRole("heading", { name: "Set up AI agents" }).waitFor();
      const order = await page
        .locator("[data-ai] [data-try-item]")
        .evaluateAll((els) => els.map((e) => e.dataset.tryItem));
      if (order.join() !== "chatgpt,openai,cloudflare") throw new Error(order.join());
      await page.locator('[data-try-item="chatgpt"]').getByText("Recommended").waitFor();
      await page.waitForFunction(() =>
        document.body.innerHTML.includes(
          "npx iterate@latest chatgpt connect iterate.adalovelace.dev",
        ),
      );
      const href = (id) => page.locator(`[data-try-item="${id}"] a`).getAttribute("href");
      // the key is typed on the deployment, with its agent, so no link here
      if (await page.locator('[data-try-item="openai"] a').count())
        throw new Error("a link for the key");
      const credit = await href("cloudflare");
      if (!/^[0-9a-f]{32}\/ai\/ai-gateway$/.test(credit.replace(env.CF_DASH, "")))
        throw new Error(credit);
    },
  );
  await snap("ai");
  await caption(
    "Then the AI provider for their agents: their ChatGPT plan, a key, or Cloudflare credit.",
  );
  await check(
    "the CLI's end of a ChatGPT connect, in another tab, turns this tab's AI step to connected, with no reload",
    async () => {
      if (await page.locator("[data-ai-connected]").count()) throw new Error("connected too early");
      const loads = [];
      page.on("load", () => loads.push(page.url()));
      const tab = await context.newPage();
      // a link that names no mind records nothing
      await tab.goto(`${SITE}/connected?ai=chatgpt&domain=nothing`);
      await tab.getByRole("heading", { name: "This link names no mind" }).waitFor();
      await page.waitForTimeout(300);
      if (await page.locator("[data-ai-connected]").count()) throw new Error("a bad link counted");
      // the CLI names the mind as its address, iterate.<domain>
      await tab.goto(`${SITE}/connected?ai=chatgpt&domain=iterate.adalovelace.dev`);
      await tab.getByRole("heading", { name: "Connected. Go back to iterate Cloud." }).waitFor();
      await tab.close();
      await page
        .locator('[data-ai-connected="chatgpt"]')
        .getByText("ChatGPT is connected")
        .waitFor();
      if (loads.length) throw new Error(`the wizard tab loaded again: ${loads.join()}`);
    },
  );
  await snap("ai-connected");
  await page.locator("[data-step]").getByRole("button", { name: "Continue", exact: true }).click();
  // after an update the first owner's ticket is gone (the stack drops it), so the mailed code is first
  await check(
    "Try iterate: the stack's onboarding chat first, a passkey, the self-test, the Dash, people, then Claude Code",
    async () => {
      const href = (id) => page.locator(`[data-try-item="${id}"] a`).getAttribute("href");
      if ((await href("open")) !== "https://dash.adalovelace.dev/agents/agents/main")
        throw new Error(await href("open"));
      if ((await href("self-test")) !== "https://iterate.adalovelace.dev/self-test")
        throw new Error(await href("self-test"));
      if (
        (await href("passkey")) !==
        `https://iterate.adalovelace.dev/keys?next=${encodeURIComponent("https://dash.adalovelace.dev/agents/agents/main")}`
      )
        throw new Error(await href("passkey"));
      if ((await href("people")) !== "https://iterate.adalovelace.dev/members")
        throw new Error(await href("people"));
      await page.waitForFunction(() =>
        document.body.innerHTML.includes(
          "claude mcp add --transport http adalovelace-dev https://iterate.adalovelace.dev/mcp",
        ),
      );
      // the run saw every page answer: nothing is said to be missing
      if (await page.getByText(/^Not on adalovelace\.dev yet/).count())
        throw new Error("a page is said to be missing");
    },
  );
  await snap("try");
  await check(
    "with no access to Cloudflare, the list shows the deployment this tab made, above the way to connect",
    async () => {
      // a tab opened from this one has its wizard's state; the update gave up the access
      const [list] = await Promise.all([
        context.waitForEvent("page"),
        page.evaluate(() => void open("/deployments")),
      ]);
      const card = list.locator('[data-just-deployed="adalovelace.dev"]');
      await card.waitFor();
      const start = await card.locator("a[data-start]").getAttribute("href");
      if (start !== "https://iterate.adalovelace.dev/") throw new Error(start);
      const connect = list.locator("[data-connect]");
      await connect.getByRole("link", { name: "Connect Cloudflare" }).waitFor();
      const [above, below] = await Promise.all([card.boundingBox(), connect.boundingBox()]);
      if (above.y >= below.y) throw new Error("the card is not above the way to connect");
      await list.close();
      await page.bringToFront();
    },
  );
  await caption("And then: things to try in their own iterate.", 2200);
  await check("the browser's Back and Forward move between steps", async () => {
    await page.goBack();
    await page.getByRole("heading", { name: "Set up AI agents" }).waitFor();
    await page.goForward();
    await page.getByRole("heading", { name: "Try iterate" }).waitFor();
  });
  await check("the bar shows the newest thing that happened, in words", async () => {
    const text = await page.locator("[data-log-bar]").innerText();
    if (!/iterate is live on adalovelace\.dev/.test(text)) throw new Error(text);
  });
  await check("it lists every record iterate Cloud keeps, and none is a token", async () => {
    await page.getByRole("button", { name: "What iterate Cloud keeps" }).click();
    const kept = await page.locator("[data-kept]").innerText();
    for (const key of ["s:<your session>", "dep:<your account>:adalovelace-dev", "state"])
      if (!kept.includes(key)) throw new Error(`no ${key}`);
    if (kept.includes("t:<your session>")) throw new Error("a token is kept");
  });
  await page.getByRole("button", { name: "Activity log" }).click();
  await check("the log opens as a sheet over the page", () =>
    page.getByRole("dialog", { name: "Activity log" }).waitFor(),
  );
  await check("the log counts repeated checks instead of listing each", async () => {
    await page.locator("[data-log]").waitFor();
    const rows = await page.locator("[data-entry^='GET /api/readiness']").allInnerTexts();
    if (!rows.some((t) => t.includes("×"))) throw new Error("not counted");
  });
  await check(
    "the log says what happened in words, with Cloudflare's answers under it",
    async () => {
      const made = page.locator("[data-entry='POST /api/account']");
      await made.getByText("Created the Cloudflare account “iterate-ada-example”").waitFor();
      await made.getByText("POST /accounts").waitFor();
      // the availability check's 10031 and 10032 are its answer: the automatic address is no failure
      const set = page.locator("[data-entry='POST /api/subdomain']");
      await set
        .getByText("Set the workers.dev address to iterate-ada-example-gzg4wi.workers.dev")
        .waitFor();
      if (await set.locator(".text-destructive").count())
        throw new Error("the automatic workers.dev address is logged as a failure");
      await page.locator("[data-log]").getByText("Using the domain adalovelace.dev").waitFor();
    },
  );
  await check(
    "the deploy is in the log too: an entry per step, its output on request",
    async () => {
      // two runs by now (the deploy and the update): the first of the two entries
      const step = page
        .locator("[data-kind='deploy']", { hasText: "wait for iterate to answer" })
        .first();
      await step.waitFor();
      await step.getByText("Output").click();
      if (!(await step.locator("pre").innerText()).trim()) throw new Error("no output");
      if (await page.locator("[data-entry='GET /api/deploy']").count())
        throw new Error("each poll of the deploy is listed");
    },
  );
  await pause(400); // the sheet slides in
  await snap("log");
  await pause(1400);
  await page.getByRole("button", { name: "Close" }).click();
  if (!mobile)
    await check(
      "on a very wide screen the log is a panel beside the wizard, not over it",
      async () => {
        await page.setViewportSize({ width: 1600, height: 900 });
        await page.getByRole("button", { name: "Activity log" }).click();
        await page.locator("aside[aria-label='Activity log']").waitFor();
        if (await page.getByRole("dialog").count())
          throw new Error("a modal on a very wide screen");
        const [panel, main] = await Promise.all([
          page.locator("aside[aria-label='Activity log']").boundingBox(),
          page.locator("[data-step]").boundingBox(),
        ]);
        if (panel.x < main.x + main.width) throw new Error("the panel covers the step");
        await snap("log-wide");
        await page
          .locator("aside[aria-label='Activity log']")
          .getByRole("button", { name: "Close" })
          .click();
        await page.setViewportSize(size);
      },
    );
  await page.evaluate(() => window.scrollTo(0, 0));
  const backToDomain = async () => {
    if (!mobile) await goBack("Pick a domain");
    else
      while (!(await page.getByRole("heading", { name: "Pick a domain" }).count())) {
        await goBack();
        await page.waitForTimeout(150);
      }
    await page.getByRole("heading", { name: "Pick a domain" }).waitFor();
  };

  /** On the domain step with a domain chosen: back to its first decision, and another way. */
  const anotherWay = async (how) => {
    await page.getByRole("button", { name: "Use a different domain" }).click();
    await page.locator(`[data-how="${how}"]`).click();
  };

  console.log("Path 2: a domain registered elsewhere");
  await backToDomain();
  await check("back on the step, the domain in use shows, with the way on", async () => {
    await page
      .locator('[data-chosen="adalovelace.dev"]')
      .getByText("iterate goes on this domain.")
      .waitFor();
    await page.getByRole("button", { name: "Continue", exact: true }).waitFor();
  });
  await snap("domain-chosen");
  await page.getByRole("button", { name: "Use a different domain" }).click();
  await check("the deploy took the access to Cloudflare: another domain needs it again", () =>
    page.locator("[data-reconnect]").waitFor(),
  );
  await reconnect();
  await page.locator('[data-how="elsewhere"]').click();
  await page.getByLabel("Your domain").fill("adas-notes.com");
  await page.getByRole("button", { name: "Add to Cloudflare" }).click();
  await check("two nameservers to set", async () => {
    await see(/Point adas-notes\.com at Cloudflare/);
    // Kumo's ClipboardText: the value is shown, and copied by its button
    await page.waitForFunction(() =>
      ["kayleigh.ns.cloudflare.com", "nolan.ns.cloudflare.com"].every((n) =>
        document.body.innerHTML.includes(n),
      ),
    );
  });
  await snap("nameservers");
  await caption(
    "A domain from elsewhere: we add it, they set two nameservers at their registrar.",
    2200,
  );
  await fetch(`${cf.origin}/_test/nameservers?zone=adas-notes.com`, { method: "POST" });
  await page.getByRole("button", { name: "Check again" }).click();
  await check("the zone turns active and it moves on to deploying", async () => {
    await page.getByRole("heading", { name: "Deploy iterate" }).waitFor();
  });
  await check("a domain they bring is warned: iterate takes all of it", () =>
    see(/iterate takes all of adas-notes\.com/),
  );
  await snap("deploy-takes-all");
  await caption("Cloudflare sees them. On to deploying.", 1400);
  await backToDomain();

  console.log("Path 3: a domain already in the account");
  // an account with more domains than one page of Cloudflare's list (50)
  const held = cf.state.zones.find((z) => z.name === "adalovelace.dev");
  const many = Array.from({ length: 60 }, (_, i) => ({
    ...held,
    id: i.toString(16).padStart(32, "f"),
    name: `zone-${String(i).padStart(2, "0")}.example`,
  }));
  cf.state.zones.push(...many);
  await anotherWay("have");
  await check("it lists the account's domains", () =>
    page.locator('[data-zone="adalovelace.dev"]').waitFor(),
  );
  await check(
    "it lists all of them, past Cloudflare's first page, with a filter above",
    async () => {
      await page.locator('[data-zone="zone-59.example"]').waitFor();
      const filter = page.getByRole("searchbox", { name: "Filter your domains" });
      await filter.fill("zone-5");
      await snap("domain-filter");
      await filter.fill("nothing-like-this");
      await see(/No domain in this account matches/);
      await filter.fill("ADAlove");
      await page.locator('[data-zone="adalovelace.dev"]').waitFor();
      const rows = await page.locator("[data-zone]").count();
      if (rows !== 1) throw new Error(`the filter left ${rows} rows, not 1`);
    },
  );
  cf.state.zones = cf.state.zones.filter((z) => !many.includes(z));
  await page.locator('[data-zone="adalovelace.dev"]').click();
  await check("an active domain moves on at once", () =>
    page.getByRole("heading", { name: "Deploy iterate" }).waitFor(),
  );
  await caption("A domain already in Cloudflare: pick it, and on.", 1400);
  await backToDomain();

  console.log("Path 4: Cloudflare refuses the purchase");
  await anotherWay("buy");
  await page.getByRole("button", { name: /^Show \d+ more$/ }).click();
  await check('a domain they already hold says so, not "Taken"', () =>
    page.locator('[data-domain="adalovelace.dev"][data-yours]').waitFor(),
  );
  await page.locator('[data-domain="adalovelace.xyz"]').click();
  await check(
    "on an account that is ready, a second name is bought at once, with Cloudflare's contact on file: no form",
    async () => {
      await page.getByRole("heading", { name: "Get your account ready" }).waitFor();
      await see(/contact already on file/);
      if (await page.getByLabel("City").count()) throw new Error("form shown");
    },
  );
  // the account stops paying after the checklist said it can: Cloudflare's refusal is what is left
  cf.state.accounts.find((a) => a.name === "iterate-ada-example").paid = false;
  await page.getByRole("button", { name: /Buy for/ }).click();
  await check("no card: it says to add a payment method, with a link", async () => {
    await page.getByRole("alert").getByText("Add a card to buy this domain").waitFor();
    await page
      .getByRole("alert")
      .getByRole("link", { name: /Add card/ })
      .waitFor();
  });
  await check(
    "…it doesn't name a card then, and the log has the refusal as a problem",
    async () => {
      if (await page.getByText(/Cloudflare charges/).count())
        throw new Error("it still names a card");
      const text = await page.locator("[data-log-bar]").innerText();
      if (!/Cloudflare didn't register adalovelace\.xyz/.test(text)) throw new Error(text);
      await page.locator("[data-log-bar] .text-destructive").waitFor();
    },
  );
  await pause(300); // the Buy button fades to its quiet look
  await snap("no-card");
  await caption("If Cloudflare refuses, they see what to do and where, not an error code.", 2400);
  console.log("Path 5: an existing account, one consent");
  const other = await browser.newContext({ viewport: size, colorScheme: "light" });
  const p2 = await other.newPage();
  p2.setDefaultTimeout(15_000);
  await p2.goto(SITE);
  await p2.getByRole("radio", { name: /An account I already have/ }).click();
  await p2.getByRole("link", { name: "Continue with Cloudflare" }).click();
  await check("an existing account: one consent, with all permissions", async () => {
    const n = Number(await p2.locator("[data-permissions]").getAttribute("data-permissions"));
    if (!(n > 5)) throw new Error(`${n} permissions`);
  });
  await p2.locator("label.acct", { hasText: "Ada's account" }).locator("input").check();
  await p2.getByRole("button", { name: "Authorize" }).click();
  await check("…and straight to the domain for it", async () => {
    await p2.locator('[data-how="have"]').waitFor();
    if (mobile) await p2.locator("[data-step-menu]").click();
    await p2
      .getByRole("navigation", { name: "Steps" })
      .getByRole("button", { name: /^Connect Cloudflare account Ada's account ?Change$/ })
      .waitFor();
    if (mobile) await p2.keyboard.press("Escape");
  });
  // a domain that is in this account already
  cf.state.zones.push({
    ...cf.state.zones.find((z) => z.name === "adalovelace.dev"),
    id: "e".repeat(32),
    account: "a".repeat(32),
    name: "adas-site.example",
  });
  // Ada's account has no workers.dev address now, and both names from her email are taken
  cf.state.accounts.find((a) => a.name === "Ada's account").subdomain = null;
  await p2.locator('[data-how="have"]').click();
  await p2.locator('[data-zone="adas-site.example"]').click();
  await check(
    "both names from the email are taken: the log names them, and Create address is there",
    async () => {
      await p2.getByRole("heading", { name: "Get your account ready" }).waitFor();
      await p2.getByRole("button", { name: "Activity log" }).click();
      await p2
        .locator("[data-entry='POST /api/subdomain']")
        .getByText(
          "iterate-ada-example.workers.dev and iterate-ada-example-gzg4wi.workers.dev are taken",
        )
        .waitFor();
      await p2.keyboard.press("Escape");
      await p2
        .locator('[data-item="workers.dev address"]')
        .getByRole("button", { name: "Create address" })
        .click();
    },
  );
  await check(
    "a domain of theirs, then the account: with every item green, Continue is the large thing on the page",
    async () => {
      await p2.getByRole("heading", { name: "Get your account ready" }).waitFor();
      const done = p2.locator("[data-ready-done]");
      await done.getByText("Your account is ready.").waitFor();
      const box = await done.getByRole("button", { name: "Continue", exact: true }).boundingBox();
      if (box.height < 48) throw new Error(`Continue is ${box.height}px high`);
      if (await p2.locator("[data-check-again]").count())
        throw new Error("Check again, with nothing left to check");
      if (await p2.getByRole("button", { name: /Buy for/ }).count())
        throw new Error("a purchase, for a domain they have");
    },
  );
  await p2.screenshot({ path: join(OUT, "ready-continue.png"), fullPage: true });
  await check("…and Continue goes to the deploy on that domain", async () => {
    await p2.getByRole("button", { name: "Continue", exact: true }).click();
    await p2.getByRole("heading", { name: "Deploy iterate" }).waitFor();
    await p2.getByText("iterate.adas-site.example").waitFor();
  });
  await check(
    "Sign out: the session ends, the tab forgets, and the page is the first one",
    async () => {
      const bar = await openSidebar(p2);
      await bar.getByRole("button", { name: "Account" }).click();
      await p2.getByRole("menuitem", { name: "Sign out" }).click();
      await p2.getByRole("link", { name: "Continue with Cloudflare" }).waitFor();
      const left = await p2.evaluate(async () => ({
        me: await fetch("/api/me").then((r) => (r.ok ? r.json() : null)),
        kept: JSON.parse(sessionStorage.getItem("wizard") || "{}").me || null,
      }));
      if (left.me?.user) throw new Error("the session is still there");
      if (left.kept) throw new Error("the tab still knows who it was");
      const again = await openSidebar(p2);
      if (await again.getByRole("button", { name: "Account" }).count())
        throw new Error("an account menu after signing out");
    },
  );
  await other.close();

  console.log("Path 6: making another new account, and backing out of the new account");
  const third = await browser.newContext({ viewport: size, colorScheme: "light" });
  const p3 = await third.newPage();
  p3.setDefaultTimeout(15_000);
  await p3.goto(SITE);
  await p3.getByRole("link", { name: "Continue with Cloudflare" }).click();
  await p3.locator("input[name=account]").first().check();
  await p3.getByRole("button", { name: "Authorize" }).click();
  await p3.getByLabel("Account name").fill("iterate-first");
  await p3.getByRole("button", { name: "Create account" }).click();
  // on Cloudflare's page for the new account: back, with no consent for it
  await p3.locator("label.acct", { hasText: "iterate-first" }).waitFor();
  await p3.goBack();
  await p3.locator('[data-account="iterate-first"]').waitFor();
  await check(
    "Make another account: the first stays in Cloudflare, the Cloud forgets it, and the form is back",
    async () => {
      await p3.getByRole("button", { name: "Make another account" }).click();
      await p3.getByText("“iterate-first” stays in your Cloudflare account").waitFor();
      await p3.getByRole("button", { name: "Create account" }).waitFor();
      for (let i = 0; i < 40 && kv.has("created:" + "u".repeat(32)); i++)
        await p3.waitForTimeout(50);
      if (kv.has("created:" + "u".repeat(32))) throw new Error("still remembered");
    },
  );
  await p3.getByLabel("Account name").fill("iterate-tryout");
  const asksTokens = (url) =>
    !!new URL(url).searchParams.get("scope")?.split(" ").includes("account-api-tokens.write");
  await check(
    "Authorize without it makes the account first, then asks the consent without the token scope",
    async () => {
      await p3.locator("[data-without-tokens]").click();
      await p3.locator("label.acct", { hasText: "iterate-tryout" }).waitFor();
      if (asksTokens(p3.url())) throw new Error("the token scope is asked");
    },
  );
  // on Cloudflare's page for the new account: back, with no consent for it
  await p3.goBack();
  await p3.locator('[data-account="iterate-tryout"]').waitFor();
  await check(
    "…and the created page remembers the choice: the plain consent, no tick",
    async () => {
      const href = await p3.getByRole("link", { name: "Authorize iterate" }).getAttribute("href");
      if (asksTokens(new URL(href, SITE).href) || /telemetry|cloudflare=/.test(href))
        throw new Error(`asks the token scope: ${href}`);
      if (await p3.locator("[data-token-tick]").count()) throw new Error("still says what to tick");
    },
  );
  await check("another tab doesn't offer to make a second account", async () => {
    const tab = await third.newPage();
    await tab.goto(SITE);
    await tab.locator('[data-account="iterate-tryout"]').waitFor();
    await tab.close();
  });
  await check("the way out is the step list: back to new or existing", async () => {
    if (mobile) await p3.locator("[data-step-menu]").click();
    await p3
      .getByRole("navigation", { name: "Steps" })
      .getByRole("button", { name: "New or existing account" })
      .click();
    await p3.getByRole("heading", { name: "Connect a Cloudflare account" }).waitFor();
    // connected already: on from here, with no second trip to Cloudflare for a new account
    await p3.getByRole("button", { name: "Continue", exact: true }).click();
    await p3.locator('[data-account="iterate-tryout"]').waitFor();
    if (mobile) await p3.locator("[data-step-menu]").click();
    await p3
      .getByRole("navigation", { name: "Steps" })
      .getByRole("button", { name: "New or existing account" })
      .click();
    await p3.getByRole("radio", { name: /An account I already have/ }).click();
    await p3.getByRole("button", { name: "Continue", exact: true }).click();
  });
  await check("backing out says the new account stays, with a link to it", async () => {
    await p3.getByText("“iterate-tryout” stays in your Cloudflare account").waitFor();
    await p3.getByRole("link", { name: /Open it/ }).waitFor();
    await p3.getByRole("link", { name: "Authorize iterate" }).waitFor();
  });
  await check("…and after backing out, a new tab doesn't bring it back", async () => {
    await p3.waitForFunction(() => true);
    for (let i = 0; i < 40 && kv.has("created:" + "u".repeat(32)); i++) await p3.waitForTimeout(50);
    if (kv.has("created:" + "u".repeat(32))) throw new Error("still remembered");
  });
  await third.close();

  console.log("Path 7: an account that already holds iterate: your deployments");
  // what a deploy leaves in the account (the real one's Workers), which the fake run does not
  const heldZone = cf.state.zones.find((z) => z.name === "adalovelace.dev");
  recordDeployment(cf.state, {
    account: heldZone.account,
    name: "adalovelace-dev",
    domain: "adalovelace.dev",
  });
  deployment.answers = true;
  deployment.onboarding = false;
  const fourth = await browser.newContext({
    ...(mobile && !tablet ? { ...devices["iPhone 13"], defaultBrowserType: undefined } : {}),
    viewport: size,
    colorScheme: "light",
  });
  const p4 = await fourth.newPage();
  p4.setDefaultTimeout(15_000);
  const snap4 = (name) =>
    p4.screenshot({ path: join(OUT, `deployments-${name}.png`), fullPage: true });
  const card = p4.locator('[data-deployment="adalovelace.dev"]');
  await check("signed out, the page of deployments asks for Cloudflare first", async () => {
    await p4.goto(`${SITE}/deployments`);
    await p4.locator("[data-connect]").getByRole("link", { name: "Connect Cloudflare" }).waitFor();
    await snap4("signed-out");
  });
  await check(
    "after the consent, an account that holds iterate lands on the list, not in the wizard",
    async () => {
      await p4.goto(SITE);
      await p4.getByRole("radio", { name: /An account I already have/ }).click();
      await p4.getByRole("link", { name: "Continue with Cloudflare" }).click();
      // the account of Path 1, which holds the domain (Path 6 left one named iterate-tryout too)
      await p4.getByRole("checkbox", { name: "iterate-ada-example", exact: true }).check();
      // the list is read from Cloudflare when it is asked: while that takes long (an account
      // with hundreds of domains), the page says what it waits for
      await p4.route(
        "**/api/deployments",
        async (route) => {
          await new Promise((done) => setTimeout(done, 2500));
          await route.continue();
        },
        { times: 1 },
      );
      await p4.getByRole("button", { name: "Authorize" }).click();
      await p4.locator("[data-entering]", { hasText: "Reading your Cloudflare account" }).waitFor();
      await p4.getByRole("heading", { name: "Your deployments" }).waitFor();
      await card.waitFor();
      if (new URL(p4.url()).pathname !== "/deployments") throw new Error(`at ${p4.url()}`);
    },
  );
  await check(
    "the deployment: it answers, the commit of the run from here, its start page",
    async () => {
      await card.locator('[data-answers="true"]').waitFor();
      const runs = await card.locator("[data-runs]").innerText();
      if (!/deployed from here/.test(runs)) throw new Error(`it runs: ${runs}`);
      const start = await card.locator("[data-start]").getAttribute("href");
      if (start !== "https://iterate.adalovelace.dev/") throw new Error(`start page: ${start}`);
    },
  );
  await check("no link to an onboarding chat whose Dash does not answer", async () => {
    await card.locator("[data-no-onboarding]").waitFor();
    if (await card.locator("[data-onboarding]").count()) throw new Error("a link to a dead page");
  });
  await check("the shared apps: GitHub delivers for two accounts, the rest do not", async () => {
    const github = await card.locator('[data-app="github"]').innerText();
    if (!/GitHub: 2 accounts/.test(github)) throw new Error(github);
    const off = await card.locator('[data-delivers="false"]').count();
    if (off !== 3) throw new Error(`${off} apps not connected, not 3`);
  });
  await check("Erase and replace is offered on the deployment", async () => {
    if (await card.locator("[data-erase]").isDisabled()) throw new Error("it cannot be pressed");
  });
  await snap4("list");
  deployment.onboarding = true;
  await p4.getByRole("button", { name: "Check again" }).click();
  await check("once its Dash answers, the link is there", async () => {
    const href = await card.locator("[data-onboarding]").getAttribute("href");
    if (href !== "https://dash.adalovelace.dev/agents/agents/main")
      throw new Error(`onboarding: ${href}`);
  });
  await check("the sidebar, opened, lists the deployment and New deployment", async () => {
    // a wide screen has the rail: its last button opens it
    if (!mobile || tablet)
      await p4
        .locator('[data-slot="sidebar"] button', { hasText: "Collapse sidebar" })
        .first()
        .click();
    const bar = await openSidebar(p4);
    await bar.locator('[data-nav-deployment="adalovelace.dev"]').waitFor();
    await bar.locator('[data-nav="new"]').waitFor();
    await p4.waitForTimeout(500); // the sidebar opens with a transition
    await snap4("sidebar");
    await closeSidebar(p4);
  });
  /** Back on the list. A run takes the access to Cloudflare with it: then with a new consent. */
  const toList = async () => {
    await p4.goto(`${SITE}/deployments`);
    const connect = p4.locator("[data-connect]").getByRole("link", { name: "Connect Cloudflare" });
    await connect.or(card).first().waitFor();
    if (!(await connect.isVisible())) return;
    await connect.click();
    await p4.getByRole("checkbox", { name: "iterate-ada-example", exact: true }).check();
    await p4.getByRole("button", { name: "Authorize" }).click();
    await card.waitFor();
  };
  await check("Update iterate says on the card what it does, and starts nothing yet", async () => {
    await card.locator("[data-update]").click();
    await card
      .locator('[data-asking="update"]')
      .getByText(/deploys the newest iterate on adalovelace\.dev/)
      .waitFor();
    if (new URL(p4.url()).pathname !== "/deployments") throw new Error(`left for ${p4.url()}`);
    await snap4("update-asked");
  });
  await check("…and Update now shows the run go, not a deploy that is over", async () => {
    // this stack is older than its Dash and its self-test page: the run sees neither,
    // and neither answers afterwards
    staleNextRun = true;
    deployment.onboarding = false;
    await card.locator("[data-confirm]").click();
    await p4.getByRole("heading", { name: "Deploy iterate" }).waitFor();
    await p4.locator("[data-phase]").first().waitFor();
    if (await p4.locator("[data-deployed]").count())
      throw new Error("it says “iterate is live” while the update has just started");
    await p4.locator('[data-deployed="adalovelace.dev"]').waitFor({ timeout: 90_000 });
  });
  await check(
    "no button leads to a page that the run did not see answer: the AI step names no onboarding chat",
    async () => {
      await p4
        .locator('[data-deployed="adalovelace.dev"]')
        .getByRole("button", { name: "Set up AI agents" })
        .click();
      await p4
        .locator("[data-ai]")
        .getByRole("button", { name: "Continue", exact: true })
        .waitFor();
      if (await p4.getByText(/Ask the agent in onboarding/).count())
        throw new Error("it sends the person to an onboarding chat that is not there");
    },
  );
  await check(
    "…and Try iterate has no onboarding, no Dash, no self-test, and says what is not there",
    async () => {
      await p4.locator("[data-ai]").getByRole("button", { name: "Continue", exact: true }).click();
      const list = p4.locator("[data-try]");
      await list.locator("[data-members]").waitFor();
      for (const gone of ["[data-onboarding]", "[data-self-test]", "[data-dash]"])
        if (await list.locator(gone).count()) throw new Error(`${gone} is shown`);
      // the pages that did answer keep their buttons
      await list.getByText(/claude mcp add --transport http [a-z0-9-]+ https/).waitFor();
      await list.getByText("Not on adalovelace.dev yet: the Dash and the self-test page").waitFor();
      await list.getByRole("button", { name: "Go to Deploy" }).waitFor();
      await snap4("try-pages-missing");
    },
  );
  await check(
    "a page that the run was too early for gets its button once it answers: the page looks again",
    async () => {
      deployment.onboarding = true;
      await p4.reload();
      const list = p4.locator("[data-try]");
      await list.locator("[data-onboarding]").waitFor();
      const open = await list.locator("[data-onboarding]").getAttribute("href");
      if (open !== "https://dash.adalovelace.dev/agents/agents/main") throw new Error(open);
      // the onboarding chat is on the Dash
      await list.locator("[data-dash]").waitFor();
      await list.getByText("Not on adalovelace.dev yet: the self-test page").waitFor();
      if (await list.locator("[data-self-test]").count()) throw new Error("a self-test button");
    },
  );
  await check("Lost your passkey? says on the card whom the new link signs in", async () => {
    await toList();
    await card.locator("[data-recover]").click();
    const asked = card.locator('[data-asking="recover"]');
    await asked.getByText(/gives you a link that signs you in as/).waitFor();
    const owner = await asked.locator("b").innerText();
    if (!owner.includes("@")) throw new Error(`the link signs in ${owner}`);
    if (new URL(p4.url()).pathname !== "/deployments") throw new Error(`left for ${p4.url()}`);
    await snap4("recover-asked");
  });
  await check("…and its update ends on the link for a new passkey", async () => {
    await card.getByRole("button", { name: "Update and get a new link" }).click();
    await p4.locator("[data-phase]").first().waitFor();
    if (await p4.locator("[data-deployed]").count())
      throw new Error("it says “iterate is live” while the update has just started");
    await p4.locator("[data-first-passkey]").waitFor({ timeout: 90_000 });
    await snap4("recover-done");
  });
  await check(
    "with the list's plain consent, Update iterate offers the consent for telemetry and the mind's Cloudflare connection, and the update without them",
    async () => {
      await toList();
      await card.locator("[data-update]").click();
      const asked = card.locator('[data-asking="update"]');
      await asked.locator('[data-left-off="telemetry cloudflare"]').waitFor();
      const href = await asked.locator("[data-update-consent]").getAttribute("href");
      if (href !== "/connect?level=full&telemetry=1&cloudflare=1")
        throw new Error(`the consent is ${href}`);
      const button = (await asked.locator("[data-confirm]").innerText()).trim();
      if (button !== "Update without them") throw new Error(`the button says: ${button}`);
      await snap4("update-offers-consent");
      await asked.getByRole("button", { name: "Cancel" }).click();
    },
  );
  await check(
    "an update from the list that fails is tried again for the deployment's owner, not for whoever is signed in",
    async () => {
      // the owner is another address than the person at Cloudflare (ada@example.com)
      const kept = [...kv.keys()].find(
        (k) => k.startsWith("dep:") && k.endsWith(":adalovelace-dev"),
      );
      kv.set(kept, JSON.stringify({ ...JSON.parse(kv.get(kept)), owner: "owner@adalovelace.dev" }));
      await toList();
      failNextRun = true;
      await card.locator("[data-update]").click();
      await card.locator("[data-confirm]").click();
      await p4.locator("[data-deploy-failed]").waitFor({ timeout: 60_000 });
      await p4.getByRole("link", { name: "Connect Cloudflare to try again" }).click();
      await p4.getByRole("checkbox", { name: "iterate-ada-example", exact: true }).check();
      await p4.getByRole("button", { name: "Authorize" }).click();
      await p4.getByRole("button", { name: "Try again" }).click();
      await p4.locator('[data-deployed="adalovelace.dev"]').waitFor({ timeout: 90_000 });
      const owners = runs.get(kept.slice("dep:".length)).args.ownerEmails;
      if (owners?.join() !== "owner@adalovelace.dev")
        throw new Error(`the retry deployed for ${JSON.stringify(owners)}`);
    },
  );
  await check(
    "New deployment is a button on the list itself, and opens the wizard at its first question: a new Cloudflare account, or one they have",
    async () => {
      await toList();
      await p4.locator("[data-deployments] [data-new-deployment]").click();
      await p4.getByRole("heading", { name: "Connect a Cloudflare account" }).waitFor();
      await p4.getByRole("radio", { name: /A new Cloudflare account/ }).waitFor();
      await p4.getByRole("radio", { name: /An account I already have/ }).waitFor();
      // they hold a deployment: nothing here sends them to the waiting list
      if (await p4.locator("[data-walkthrough-only]").count())
        throw new Error("a person with a deployment is sent to the waiting list");
      // connected already: on from here, with no second trip to Cloudflare
      await p4.locator("[data-account-continue]").click();
      await p4.getByRole("heading", { name: "Create a new Cloudflare account" }).waitFor();
      await p4.getByLabel("Account name").waitFor();
      await snap4("new-account");
    },
  );
  await check("…and the other choice goes on with the accounts they connected", async () => {
    await toList();
    await p4.locator("[data-deployments] [data-new-deployment]").click();
    await p4.getByRole("radio", { name: /An account I already have/ }).click();
    await p4.locator("[data-account-continue]").click();
    // the account in use with the way to another, or the accounts to pick from when none is
    await p4
      .getByRole("heading", {
        name: /^(Your Cloudflare account|Which account should iterate use\?)$/,
      })
      .waitFor();
  });
  if (!mobile || tablet)
    await check(
      "the sidebar is its rail again on each page, also after somebody opened it",
      async () => {
        await toList();
        const bar = p4.locator('[data-slot="sidebar"]').first();
        if ((await bar.getAttribute("data-state")) !== "collapsed")
          throw new Error(`the list's sidebar starts ${await bar.getAttribute("data-state")}`);
        await p4
          .locator('[data-slot="sidebar"] button', { hasText: "Collapse sidebar" })
          .first()
          .click();
        await p4.locator('[data-slot="sidebar"][data-state="expanded"]').first().waitFor();
        // to another page of the Cloud, by the open sidebar's own link
        await p4.locator('[data-nav="new"]').first().click();
        await p4.getByRole("heading", { name: "Connect a Cloudflare account" }).waitFor();
        const next = await p4.locator('[data-slot="sidebar"]').first().getAttribute("data-state");
        if (next !== "collapsed") throw new Error(`the wizard's sidebar is ${next}`);
        // and after a load of the page
        await p4
          .locator('[data-slot="sidebar"] button', { hasText: "Collapse sidebar" })
          .first()
          .click();
        await p4.locator('[data-slot="sidebar"][data-state="expanded"]').first().waitFor();
        await p4.reload();
        await p4.locator('[data-slot="sidebar"]').first().waitFor();
        const loaded = await p4.locator('[data-slot="sidebar"]').first().getAttribute("data-state");
        if (loaded !== "collapsed") throw new Error(`after a reload the sidebar is ${loaded}`);
      },
    );
  await check("another iterate opens the wizard, and the wizard stays", async () => {
    await toList();
    // "another", not "a second": a person may have two already
    await p4
      .locator("[data-another]")
      .getByRole("button", { name: "Add another iterate to this account" })
      .click();
    // the wizard's step, at any width (a phone has no step list beside it)
    await p4.locator("[data-step]").waitFor();
    await p4.waitForTimeout(500);
    if (new URL(p4.url()).pathname !== "/") throw new Error(`sent back to ${p4.url()}`);
  });
  await check(
    "Erase and replace shows what is on the domain, read from Cloudflare now",
    async () => {
      await toList();
      await card.locator("[data-erase]").click();
      await p4
        .getByRole("heading", { name: "Everything on adalovelace.dev will be erased." })
        .waitFor();
      const held = cf.state.accounts.find((a) => a.id === heldZone.account);
      if (!held.paid) {
        // a list the erase needs and cannot read: the page says so, and offers no erase
        await p4
          .locator("[data-erase-refused]")
          .getByText(/read the containers/)
          .waitFor();
        if (await p4.locator("[data-erase-form]").count()) throw new Error("an erase is offered");
        await snap4("erase-refused");
        held.paid = true;
        await p4.getByRole("button", { name: "Read again" }).click();
      }
      await p4.locator('[data-erase-group="iterate"] [data-erase-item]').first().waitFor();
      await p4
        .locator("[data-erase-kept]")
        .getByText(/The domain itself, its nameservers/)
        .waitFor();
      const owner = await p4.locator("[data-erase-owner]").inputValue();
      if (owner !== "owner@adalovelace.dev") throw new Error(`the new owner is ${owner}`);
      await snap4("erase-list");
    },
  );
  await check("…and only the domain's own name agrees to it", async () => {
    const start = p4.locator("[data-erase-start]");
    if (!(await start.isDisabled())) throw new Error("it starts with nothing typed");
    await p4.locator("[data-erase-typed]").fill("adalovelace.com");
    if (!(await start.isDisabled())) throw new Error("it starts with another domain's name");
    const refused = await p4.evaluate(async () => {
      const answer = await fetch("/api/deploy", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          account: "a".repeat(32),
          zone: "adalovelace.dev",
          email: "ada@example.com",
          erase: "0".repeat(24),
          typed: "adalovelace.com",
        }),
      });
      return answer.status;
    });
    if (refused < 400) throw new Error(`the Worker starts an erase nobody agreed to: ${refused}`);
    await p4.locator("[data-erase-typed]").fill("Adalovelace.dev ");
    if (await start.isDisabled()) throw new Error("it does not start with the domain's name");
  });
  await check("…then the run erases first, and deploys as on an empty domain", async () => {
    await p4.locator("[data-erase-start]").click();
    await p4.getByRole("heading", { name: "Deploy iterate" }).waitFor();
    await p4.locator('[data-phase="erase"]').waitFor();
    await snap4("erase-run");
    await p4.locator('[data-deployed="adalovelace.dev"]').waitFor({ timeout: 90_000 });
    const erasing = [...runs.values()].find((r) => r.zone === "adalovelace.dev").args;
    if (!/^[0-9a-f]{24}$/.test(erasing.erase || "")) throw new Error(`erase: ${erasing.erase}`);
    if (erasing.ownerEmails?.join() !== "owner@adalovelace.dev") throw new Error("the new owner");
    if (erasing.recoverOwner) throw new Error("an erase is no recovery");
  });
  await check(
    "a run whose access still works after the revoke fails, and says how to remove it",
    async () => {
      await toList();
      stickNextRun = true;
      await card.locator("[data-update]").click();
      await card.locator("[data-confirm]").click();
      const problem = p4.locator('[data-deploy-failed="forget"]');
      await problem.waitFor({ timeout: 90_000 });
      await problem.getByText(/Remove “Iterate Cloud” yourself/).waitFor();
      await problem.getByText(/iterate itself was deployed/).waitFor();
      for (const [id, state] of [
        ["verify", "done"],
        ["forget", "failed"],
      ])
        if ((await p4.locator(`[data-phase="${id}"]`).getAttribute("data-state")) !== state)
          throw new Error(`the step ${id} is not ${state}`);
      await p4.getByText(/a new consent does not end the old access/).waitFor();
      await snap4("access-not-given-up");
    },
  );
  await check(
    "an update of an iterate from before the rename stops, and offers Erase and replace",
    async () => {
      await toList();
      olderNextRun = true;
      // the run before this one failed, so the card opens the wizard's Deploy step
      await card.locator("[data-update]").click();
      await p4.getByRole("button", { name: "Try again" }).click();
      const problem = p4.locator('[data-deploy-failed="check"]');
      await problem.waitFor({ timeout: 90_000 });
      await problem.getByText(/It cannot be updated in place\. Erase and replace it/).waitFor();
      const erase = p4.locator("[data-erase-older]");
      const href = await erase.getAttribute("href");
      if (!/^\/erase\?account=[0-9a-f]{32}&domain=adalovelace\.dev$/.test(href || ""))
        throw new Error(`the erase link: ${href}`);
      if (await p4.getByRole("button", { name: "Try again" }).count())
        throw new Error("Try again is offered for a stack that cannot be updated");
      if (await p4.getByText(/Connect Cloudflare to try again/).count())
        throw new Error("a new consent is offered for a stack that cannot be updated");
      await snap4("older-stack");
    },
  );
  deployment.answers = false;
  await check(
    "an iterate from before the rename is not offered an update that can only stop: the card says so, and offers the erase",
    async () => {
      // what only a stack from before the rename has in the account: its older boundary Worker
      const account = cf.state.accounts.find((a) => a.id === heldZone.account);
      const before = account.existing.workers;
      account.existing.workers = [...before, "iterate-adalovelace-dev-ingress"];
      try {
        await toList();
        await card
          .locator("[data-older]")
          .getByText(/cannot be updated in place/)
          .waitFor();
        for (const gone of ["[data-update]", "[data-recover]"])
          if (await card.locator(gone).count()) throw new Error(`${gone} is offered`);
        if (!(await card.locator("[data-erase]").isEnabled())) throw new Error("no erase");
        await snap4("older");
      } finally {
        account.existing.workers = before;
      }
      await toList();
      await card.locator("[data-update]").waitFor();
    },
  );
  await check(
    "a leftover with no Worker that serves the domain is listed as incomplete, with the erase alone",
    async () => {
      const account = cf.state.accounts.find((a) => a.id === heldZone.account);
      const before = account.existing.workers;
      account.existing.workers = before.filter((id) => !/-(boundary|ingress)$/.test(id));
      try {
        await toList();
        await card.locator("[data-incomplete]").getByText("Incomplete").waitFor();
        await card
          .locator("[data-incomplete-note]")
          .getByText(/did not finish/)
          .waitFor();
        for (const gone of ["[data-update]", "[data-recover]", "[data-answers]"])
          if (await card.locator(gone).count()) throw new Error(`${gone} is shown`);
        if (!(await card.locator("[data-erase]").isEnabled())) throw new Error("no erase");
        await snap4("incomplete");
      } finally {
        account.existing.workers = before;
      }
      await toList();
      await card.locator("[data-update]").waitFor();
    },
  );
  await check("a deployment that does not answer says so, and offers no dead link", async () => {
    await toList();
    await card.locator('[data-answers="false"]').waitFor();
    if (await card.locator("[data-start], [data-onboarding]").count())
      throw new Error("a link to a deployment that does not answer");
    await snap4("does-not-answer");
  });
  deployment.answers = true;

  // ── stacks that this Cloud did not deploy, found by what serves the zone ──
  // `jeeves` on ada-family.dev was deployed from a computer under a name of its own; `vaulted`
  // keeps its vault key outside Cloudflare; adashared.dev also serves another person's Worker;
  // iterate.com is on the list of domains that are never erased.
  const others = [
    ["ada-family.dev", "jeeves"],
    ["adavault.dev", "vaulted"],
    ["adashared.dev", "adashared-dev"],
    ["iterate.com", "iterate"],
  ];
  others.forEach(([domain, name], i) => {
    cf.state.zones.push({ ...heldZone, id: `${i + 1}`.repeat(32), name: domain });
    recordDeployment(cf.state, { account: heldZone.account, name, domain });
  });
  const cardOf = (domain) => p4.locator(`[data-deployment="${domain}"]`);
  const jeeves = cardOf("ada-family.dev");
  await check(
    "a stack deployed from a computer under another name is listed on the domain it serves, with an update and no way back in",
    async () => {
      await toList();
      await jeeves.locator('[data-answers="true"]').waitFor();
      await jeeves.locator("[data-update]").waitFor();
      for (const gone of ["[data-not-from-here]", "[data-recover]", "[data-older]"])
        if (await jeeves.locator(gone).count()) throw new Error(`${gone} is shown`);
      await snap4("found-by-route");
    },
  );
  await check(
    "…and its update runs under the stack's own name, with no owner and no config from here",
    async () => {
      await jeeves.locator("[data-update]").click();
      await jeeves.locator("[data-confirm]").click();
      await p4.locator('[data-deployed="ada-family.dev"]').waitFor({ timeout: 90_000 });
      const key = `${heldZone.account}:jeeves`;
      const args = runs.get(key)?.args;
      if (args?.name !== "jeeves") throw new Error(`the run's name: ${args?.name}`);
      if (args.zone !== "ada-family.dev") throw new Error(`the run's zone: ${args.zone}`);
      for (const given of ["ownerEmails", "recoverOwner", "erase"])
        if (args[given]) throw new Error(`the run got ${given}`);
      if (kv.get(`stack:${heldZone.account}:ada-family.dev`) !== "jeeves")
        throw new Error("the Cloud did not keep which stack serves the domain");
      const row = JSON.parse(kv.get(`dep:${key}`) || "null");
      if (!row?.adopted || row.owner) throw new Error(`the record: ${JSON.stringify(row)}`);
      if (runs.has(`${heldZone.account}:ada-family-dev`))
        throw new Error("a run started under the name made from the domain");
      await snap4("found-by-route-updated");
    },
  );
  await check("…and afterwards the list still offers the update, and no way back in", async () => {
    await toList();
    await jeeves.locator("[data-update]").waitFor();
    const said = await jeeves.locator("[data-runs]").innerText();
    if (!/deployed from here/.test(said)) throw new Error(`it runs: ${said}`);
    for (const gone of ["[data-not-from-here]", "[data-recover]"])
      if (await jeeves.locator(gone).count()) throw new Error(`${gone} is shown`);
  });
  await check(
    "a stack that keeps its vault key outside Cloudflare: the update stops with nothing changed, and offers no other try",
    async () => {
      const vault = cardOf("adavault.dev");
      await vault.locator("[data-update]").click();
      await vault.locator("[data-confirm]").click();
      const problem = p4.locator('[data-deploy-failed="check"]');
      await problem.waitFor({ timeout: 90_000 });
      await problem.getByText(/keeps its vault key outside Cloudflare/).waitFor();
      await p4.locator("[data-back-to-list]").waitFor();
      if (await p4.getByRole("button", { name: "Try again" }).count())
        throw new Error("Try again is offered");
      if (await p4.getByText(/Connect Cloudflare to try again/).count())
        throw new Error("a new consent is offered");
      await snap4("vault-key-stop");
      await toList();
      await vault
        .locator("[data-key-outside]")
        .getByText(/Update it from a computer that holds the key/)
        .waitFor();
      for (const gone of ["[data-update]", "[data-recover]", "[data-not-from-here]"])
        if (await vault.locator(gone).count()) throw new Error(`${gone} is shown`);
      await snap4("vault-key-card");
    },
  );
  // ── a stack that runs an iterate this Cloud does not have: somebody updated it from a computer
  // after this Cloud's image was built, or deployed it from another branch ──
  const aheadKey = `${heldZone.account}:adaahead-dev`;
  const aheadZone = { ...heldZone, id: "9".repeat(32), name: "adaahead.dev" };
  cf.state.zones.push(aheadZone);
  const aheadRuns = (commit) => {
    recordDeployment(cf.state, {
      account: heldZone.account,
      name: "adaahead-dev",
      domain: "adaahead.dev",
      commit,
    });
    stackRuns.set(aheadKey, commit);
  };
  aheadRuns(AHEAD);
  const ahead = cardOf("adaahead.dev");
  const short = { theirs: AHEAD.slice(0, 9), cloud: COMMIT.slice(0, 9) };
  await check(
    "a stack that runs an iterate this Cloud does not have: the card says so, and offers no plain update",
    async () => {
      await toList();
      const said = await ahead.locator("[data-foreign]").innerText();
      const want = `This deployment runs iterate at ${short.theirs}, which this Cloud does not have: it is newer than the Cloud, or from another branch. Update is off until the Cloud is updated.`;
      if (said.replace(/\s+/g, " ").trim() !== want) throw new Error(`the card says: ${said}`);
      await ahead.locator("[data-update-anyway]").waitFor();
      for (const gone of ["[data-update]", "[data-not-from-here]"])
        if (await ahead.locator(gone).count()) throw new Error(`${gone} is shown`);
      const runsSaid = await ahead.locator("[data-runs]").innerText();
      if (!runsSaid.includes(short.theirs)) throw new Error(`it runs: ${runsSaid}`);
      await snap4("ahead-card");
    },
  );
  /** A start with no “anyway”, as the wizard's Deploy step or another page would send it: the
   *  run's own check stops it. Comes back when that run has ended. */
  const stoppedPlainUpdate = async () => {
    const before = runs.get(aheadKey);
    const status = await p4.evaluate(
      async ({ account, zone, zoneId }) =>
        (
          await fetch("/api/deploy", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ account, zone, zoneId }),
          })
        ).status,
      { account: heldZone.account, zone: "adaahead.dev", zoneId: aheadZone.id },
    );
    if (status !== 200) throw new Error(`the start answered ${status}`);
    const run = runs.get(aheadKey);
    if (run === before) throw new Error("no run began");
    if (run.args.anyway) throw new Error("the run got an “anyway” that nobody sent");
    const end = stateAt(run, run.end);
    if (end.status !== "failed" || run.deployed)
      throw new Error(`the run: ${end.status}, deployed ${run.deployed}`);
    const stop = end.lines.find((line) => line.startsWith("Stopped: "));
    if (!stop?.startsWith(`Stopped: This deployment runs iterate at ${short.theirs}, which`))
      throw new Error(`the run says: ${stop}`);
    // the run ends before the next press: while a run is running, a start begins no other
    await p4.waitForTimeout(Math.max(0, run.startedAt + run.end / 4 - Date.now()) + 300);
  };
  /** The panel's own button after “Update anyway” on the card, and the run that then goes through. */
  const confirmsAnyway = async () => {
    await ahead.locator("[data-confirm]").click();
    await p4.locator('[data-deployed="adaahead.dev"]').waitFor({ timeout: 90_000 });
    const run = runs.get(aheadKey);
    if (run.args.anyway !== AHEAD) throw new Error(`the run's anyway: ${run.args.anyway}`);
    const end = stateAt(run, run.end);
    if (end.result?.replaced !== AHEAD)
      throw new Error(`the result: ${JSON.stringify(end.result)}`);
    if (!end.lines.includes(`replaces ${AHEAD}`)) throw new Error("the log names no commit");
    return run;
  };
  await check(
    "…and a plain update that something else sends stops at the run's own check, with nothing deployed",
    stoppedPlainUpdate,
  );
  await check(
    "…and “Update anyway” says which commit it replaces with which, and then the run goes through",
    async () => {
      await toList();
      await ahead.locator("[data-update-anyway]").click();
      const replaces = await ahead.locator("[data-replaces]").innerText();
      for (const part of [short.theirs, short.cloud])
        if (!replaces.includes(part)) throw new Error(`the panel says: ${replaces}`);
      const button = (await ahead.locator("[data-confirm]").innerText()).trim();
      const want = `Update anyway: this replaces ${short.theirs} with ${short.cloud}`;
      if (button !== want) throw new Error(`the button says: ${button}`);
      await snap4("ahead-update-anyway");
      await confirmsAnyway();
    },
  );
  await check("…and afterwards it is a deployment like the others", async () => {
    // what the deploy does: the boundary Worker now names the Cloud's commit
    aheadRuns(COMMIT);
    await toList();
    await ahead.locator("[data-update]").waitFor();
    for (const gone of ["[data-foreign]", "[data-update-anyway]"])
      if (await ahead.locator(gone).count()) throw new Error(`${gone} is shown`);
    const said = await ahead.locator("[data-runs]").innerText();
    if (!/deployed from here/.test(said)) throw new Error(`it runs: ${said}`);
  });
  await check(
    "a stack that this Cloud deployed for an owner, after a run that failed: “Update anyway” is still there, and its run is an update",
    async () => {
      // a stack with an owner in this Cloud's record, which runs a commit the Cloud does not have
      const owned = { ...JSON.parse(kv.get(`dep:${aheadKey}`)), owner: "ada@adaahead.dev" };
      kv.set(`dep:${aheadKey}`, JSON.stringify(owned));
      aheadRuns(AHEAD);
      // and whose last run from here failed
      await stoppedPlainUpdate();
      await toList();
      await ahead.locator("[data-foreign]").waitFor();
      for (const gone of ["[data-update]", "[data-recover]"])
        if (await ahead.locator(gone).count()) throw new Error(`${gone} is shown`);
      await snap4("ahead-after-failed-run");
      await ahead.locator("[data-update-anyway]").click();
      const run = await confirmsAnyway();
      // an update: the stack keeps its owner and its config, and no ticket is made
      if (run.args.ownerEmails || run.args.recoverOwner || run.first)
        throw new Error(`not an update: ${JSON.stringify(run.args.ownerEmails)}`);
      if (JSON.parse(kv.get(`dep:${aheadKey}`)).owner !== "ada@adaahead.dev")
        throw new Error("the record lost the owner");
      aheadRuns(COMMIT);
      await toList();
    },
  );
  await check(
    "no erase is offered on iterate's own domain, nor on a domain that serves another Worker",
    async () => {
      for (const [domain, why] of [
        ["iterate.com", /never erases/],
        ["adashared.dev", /also serves the Worker shop-of-ada/],
      ]) {
        const it = cardOf(domain);
        await it.locator("[data-no-erase]").getByText(why).waitFor();
        if (await it.locator("[data-erase]").count()) throw new Error(`an erase of ${domain}`);
        await it.locator("[data-update]").waitFor();
      }
      await snap4("no-erase");
    },
  );
  await check("…and the Worker refuses both, whatever the page sends", async () => {
    const answers = await p4.evaluate(
      async ({ account, zones }) => {
        const out = {};
        for (const [zone, zoneId] of zones) {
          const list = await fetch(`/api/erase?account=${account}&zone=${zone}`).then((r) =>
            r.json(),
          );
          const start = await fetch("/api/deploy", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({
              account,
              zone,
              zoneId,
              email: "ada@example.com",
              erase: list.digest || "0".repeat(24),
              typed: zone,
            }),
          });
          out[zone] = { refusals: list.refusals || [], digest: list.digest, start: start.status };
        }
        return out;
      },
      {
        account: heldZone.account,
        zones: ["iterate.com", "adashared.dev"].map((domain) => [
          domain,
          cf.state.zones.find((z) => z.name === domain).id,
        ]),
      },
    );
    if (!/never erases/.test(answers["iterate.com"].refusals.join()))
      throw new Error(`iterate.com: ${JSON.stringify(answers["iterate.com"])}`);
    if (answers["iterate.com"].start < 400) throw new Error("an erase of iterate.com started");
    if (!/shop-of-ada, which is not iterate's/.test(answers["adashared.dev"].refusals.join()))
      throw new Error(`adashared.dev: ${JSON.stringify(answers["adashared.dev"])}`);
    if (answers["adashared.dev"].start < 400) throw new Error("an erase of adashared.dev started");
    for (const domain of ["iterate.com", "adashared.dev"])
      if ([...runs.values()].some((r) => r.zone === domain && r.args.erase))
        throw new Error(`a run erases ${domain}`);
  });
  await check(
    "when the access ended, Connect Cloudflare on the list comes back to the list",
    async () => {
      // this tab has a domain chosen (it opened the wizard's Deploy step above): still the list
      await fetch(`${cf.origin}/_test/expire-tokens`, { method: "POST" });
      await p4.goto(`${SITE}/deployments`);
      await p4.locator("[data-connect]").getByRole("link", { name: "Connect Cloudflare" }).click();
      await p4.getByRole("checkbox", { name: "iterate-ada-example", exact: true }).check();
      await p4.getByRole("button", { name: "Authorize" }).click();
      await card.waitFor();
      if (new URL(p4.url()).pathname !== "/deployments") throw new Error(`at ${p4.url()}`);
    },
  );
  await fourth.close();
} catch (error) {
  // a check() reported its own; anything else is a failure too
  if (!failures) {
    failures++;
    console.log(
      `  ✗ ${String(error.message || error)
        .split("\n")
        .slice(0, 12)
        .join("\n    ")}`,
    );
    await page.screenshot({ path: join(OUT, "fail.png"), fullPage: true }).catch(() => {});
  }
} finally {
  var video = await page.video()?.path();
  await context.close();
  await browser.close();
  site.close();
  await cf.close();
}

for (const f of readdirSync(OUT))
  if (f.endsWith(".webm") && join(OUT, f) !== video) rmSync(join(OUT, f));
if (video && existsSync(video)) {
  renameSync(video, join(OUT, "flow.webm"));
  try {
    execFileSync("ffmpeg", [
      "-y",
      "-loglevel",
      "error",
      "-i",
      join(OUT, "flow.webm"),
      "-c:v",
      "libx264",
      "-pix_fmt",
      "yuv420p",
      "-movflags",
      "+faststart",
      join(OUT, "flow.mp4"),
    ]);
  } catch (e) {
    console.log("ffmpeg:", e.message);
  }
}
console.log(failures ? `\n${failures} check failed` : "\nall checks passed");
console.log(`out: ${OUT}`);
process.exit(failures ? 1 : 0);