Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

51.6 KB
Raw Blame
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { PublishedPageCard } from "../../shared/published-page.ts";
import { FAKE_DESKTOP_TOKEN, FAKE_HOME, FAKE_TOKEN_URL, fakePagesService } from "../testing/fake-pages.ts";
import { applyIncludedPagesMessage, pagesHomeSignature } from "./access.ts";
import { PageBundleError, readPageBundle, skippedNote } from "./bundle.ts";
import * as bundle from "./bundle.ts";
import { PagesStore, PublishedPagesStore } from "./store.ts";
import { createPublishedPages } from "./service.ts";
import { createPagesInternalRoutes, createPublishedPageRoutes, type AppPages } from "../routes/published-pages.ts";
import { PASS } from "../routes/table.ts";

const SITE = { "index.html": "<!doctype html><h1>Bake sale</h1>", "style.css": "h1{color:red}" };
let dir: string;

beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "omb-pages-")); });
afterEach(() => {
  applyIncludedPagesMessage({ type: "openmausbot:included-pages", access: null });
  rmSync(dir, { recursive: true, force: true });
});

function writeSite(folder: string, files: Record<string, string> = SITE) {
  for (const [path, text] of Object.entries(files)) {
    mkdirSync(join(folder, path, ".."), { recursive: true });
    writeFileSync(join(folder, path), text);
  }
  return folder;
}
const signIn = () => applyIncludedPagesMessage({ type: "openmausbot:included-pages", access: { url: FAKE_TOKEN_URL, token: FAKE_DESKTOP_TOKEN } });

function deferred() {
  let resolve!: () => void;
  const promise = new Promise<void>((done) => { resolve = done; });
  return { promise, resolve };
}

function setup(options: { home?: boolean; quota?: number; selfHosted?: boolean; liveRoots?: (botId: string, threadId: string) => readonly string[] | null; paused?: () => boolean } = {}) {
  const service = fakePagesService({ quota: options.quota });
  const work = join(dir, "work"), data = join(dir, "data");
  mkdirSync(work, { recursive: true });
  const cards: Array<{ threadId: string; id: string; text: string; card: PublishedPageCard }> = [];
  let ids = 0;
  const pages = createPublishedPages({ dataDir: data, cloudHome: options.home ? FAKE_HOME : null, selfHosted: options.selfHosted, fetch: (input, init) => service.fetch(input, init),
    pageOrigin: () => "https://cloud.example.test",
    ...(options.liveRoots ? { liveRoots: options.liveRoots } : {}), ...(options.paused ? { paused: options.paused } : {}),
    patch: (threadId, messageId, text, card) => { const shown = cards.find((each) => each.id === messageId && each.threadId === threadId); if (shown) Object.assign(shown, { text, card }); } });
  const post = (threadId: string) => (text: string, card: PublishedPageCard) => { const id = `m${++ids}`; cards.push({ threadId, id, text, card }); return id; };
  const publish = (input: { path: string; title?: string; pageId?: string; botId?: string; threadId?: string; live?: boolean; visibility?: "public" | "owner";
    call?: { assertActive?: () => void; signal?: AbortSignal } }) => pages.publisher.publish({
    botId: input.botId ?? "bot-1", threadId: input.threadId ?? "thread-1", path: input.path, title: input.title ?? "Bake sale",
    ...(input.pageId ? { pageId: input.pageId } : {}), ...(input.live !== undefined ? { live: input.live } : {}),
    ...(input.visibility ? { visibility: input.visibility } : {}), ...(input.call ? { call: input.call } : {}), roots: [work], post: post(input.threadId ?? "thread-1") });
  return { service, pages, work, data, cards, publish };
}
const ownerUrl = (pageId: string) => `https://cloud.example.test/api/published-pages/${pageId}/`;

describe("publishing a page", () => {
  it("asks the person to sign in to MausBot when this app has no account, and publishes nothing", async () => {
    const f = setup();
    writeSite(join(f.work, "site"));
    const outcome = await f.publish({ path: "site" });
    expect(outcome).toEqual({ status: 403, text: "Publishing a page needs a MausBot account. Sign in to MausBot in the app's Settings, then ask again." });
    expect(f.service.minted).toEqual([]);
    expect(f.cards).toEqual([]);
  });

  it("says publishing isn't available on a self-hosted server, never \"sign in\", since it has no Settings sign-in to hand over", async () => {
    const f = setup({ selfHosted: true });
    writeSite(join(f.work, "site"));
    const outcome = await f.publish({ path: "site" });
    expect(outcome).toEqual({ status: 503, text: "Publishing pages isn't available on self-hosted servers yet." });
    expect(f.service.minted).toEqual([]);
    expect(f.cards).toEqual([]);
  });

  it("says publishing isn't turned on yet, never \"sign in\", when this signed-in desktop's Admin offers no pages", async () => {
    const f = setup();
    applyIncludedPagesMessage({ type: "openmausbot:included-pages", access: null, offered: false });
    writeSite(join(f.work, "site"));
    const outcome = await f.publish({ path: "site" });
    expect(outcome.text).toBe("Publishing pages isn't turned on for this account yet.");
    expect(f.service.minted).toEqual([]);
    expect(f.cards).toEqual([]);
    applyIncludedPagesMessage({ type: "openmausbot:included-pages", access: null });
    expect((await f.publish({ path: "site" })).text).toMatch(/^Publishing a page needs a MausBot account/u);
  });

  it("publishes a folder to a new link with a card showing the link and the usage, and remembers it", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    const outcome = await f.publish({ path: "site" });
    expect(outcome.status).toBe(200);
    const [page] = [...f.service.pages.keys()];
    const url = `https://${page}.mausbot.page/`;
    expect(outcome.text).toContain(`Published “Bake sale” at ${url}`);
    expect(outcome.text).toContain("This account now has 1 of 5 pages.");
    expect(outcome.text.split("\n").at(-1)).toBe("Free pages carry a small “Made with MausBot” badge.");
    expect(f.cards).toEqual([{ threadId: "thread-1", id: "m1", text: `Published “Bake sale”: ${url} (1 of 5 pages)`,
      card: { state: "live", title: "Bake sale", pageId: page, url, usage: { pages: 1, limit: 5 } } }]);
    expect(Object.fromEntries(f.service.pages.get(page!)!.files)).toEqual(SITE);
    expect(new PublishedPagesStore(join(f.data, "published-pages.json")).get(page!)).toMatchObject({ url, title: "Bake sale", botId: "bot-1",
      cards: [{ threadId: "thread-1", messageId: "m1" }] });
  });

  it("republishes the same folder to the same link, also from a new conversation, and with an explicit page id", async () => {
    const f = setup();
    signIn();
    const site = writeSite(join(f.work, "site"));
    await f.publish({ path: "site" });
    writeFileSync(join(site, "index.html"), "<h1>Tomorrow's menu</h1>");
    const again = await f.publish({ path: join(site), threadId: "routine-run-2" });
    const [page] = [...f.service.pages.keys()];
    expect(again.text).toContain(`Updated “Bake sale” at the same link: https://${page}.mausbot.page/`);
    expect(f.service.minted.map((call) => call.action)).toEqual(["create", "update"]);
    expect(f.service.pages.size).toBe(1);
    expect(f.service.pages.get(page!)!.files.get("index.html")).toBe("<h1>Tomorrow's menu</h1>");
    writeSite(join(f.work, "other"), { "index.html": "<p>Other</p>" });
    // A page id from the link updates that page even when this app didn't publish it (the same account elsewhere).
    f.pages.store.forget(page!);
    await f.publish({ path: "other", pageId: page });
    expect(f.service.minted.at(-1)).toEqual({ action: "update", pageId: page, caller: "desktop" });
    expect(f.service.pages.get(page!)!.files.get("index.html")).toBe("<p>Other</p>");
    expect(f.cards.map((card) => card.card.url)).toEqual(Array(3).fill(`https://${page}.mausbot.page/`));
  });

  it("gives a folder whose page was unpublished elsewhere a new link instead of failing", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    await f.publish({ path: "site" });
    const [first] = [...f.service.pages.keys()];
    f.service.pages.delete(first!);
    const again = await f.publish({ path: "site" });
    expect(again.status).toBe(200);
    expect([...f.service.pages.keys()]).toHaveLength(1);
    expect([...f.service.pages.keys()][0]).not.toBe(first);
  });

  it("recovers a lost PUT response by updating the remembered page instead of creating another", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    const fetch = f.service.fetch;
    f.service.fetch = async (input, init) => {
      const response = await fetch(input, init);
      if (init?.method === "PUT") throw new TypeError("response lost");
      return response;
    };
    const outcome = await f.publish({ path: "site" });
    const [pageId] = [...f.service.pages.keys()];
    expect(outcome).toMatchObject({ status: 503, card: { pageId, uncertain: true } });
    expect(new PublishedPagesStore(join(f.data, "published-pages.json")).get(pageId!)).toMatchObject({ uncertain: true });
    f.service.fetch = fetch;
    expect(await f.publish({ path: "site" })).toMatchObject({ status: 200, card: { pageId } });
    expect(f.service.pages.size).toBe(1);
    expect(f.service.minted.map((each) => each.action)).toEqual(["create", "update"]);
    expect(new PublishedPagesStore(join(f.data, "published-pages.json")).get(pageId!)?.uncertain).toBeUndefined();
  });

  it.each([402, 410, 413])("drops a new pending record when the Worker confirms rejection with %s", async (status) => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    const fetch = f.service.fetch;
    f.service.fetch = (input, init) => init?.method === "PUT" ? Promise.resolve(Response.json({}, { status })) : fetch(input, init);
    expect((await f.publish({ path: "site" })).status).not.toBe(200);
    expect(f.service.pages.size).toBe(0);
    expect(f.pages.store.list()).toEqual([]);
    expect(f.cards.every(({ card }) => card.state === "limit")).toBe(true);
  });

  it("at the plan's limit, says so for the bot to pass on and shows a card offering more pages, with the usage", async () => {
    const f = setup({ quota: 1 });
    signIn();
    writeSite(join(f.work, "one"));
    writeSite(join(f.work, "two"));
    await f.publish({ path: "one" });
    const refused = await f.publish({ path: "two", title: "Second" });
    expect(refused.status).toBe(402);
    expect(refused.text).toBe("You’ve used your 1 free pages. MausBot Cloud gives you more, and pages without the badge. Tell the person this in your reply.");
    expect(f.cards.at(-1)).toMatchObject({ text: "You’ve used your 1 free pages. MausBot Cloud gives you more, and pages without the badge.",
      card: { state: "limit", title: "Second", upgrade: true, plan: "free", usage: { pages: 1, limit: 1 } } });
  });

  it("shows the limit card once a conversation: asked again there, the bot gives the file instead", async () => {
    const f = setup({ quota: 1 });
    signIn();
    for (const name of ["one", "two", "three"]) writeSite(join(f.work, name));
    await f.publish({ path: "one" });
    await f.publish({ path: "two" });
    const again = await f.publish({ path: "three" });
    expect(again.status).toBe(402);
    expect(again.text).toContain("give the person the file instead, in one sentence, and do not publish again");
    expect(f.cards.filter(({ card }) => card.state === "limit")).toHaveLength(1);
    await f.publish({ path: "three", threadId: "thread-2" });
    expect(f.cards.filter(({ card }) => card.state === "limit").map(({ threadId }) => threadId)).toEqual(["thread-1", "thread-2"]);
  });

  it("publishes as a Cloud home with a request signed by its bootstrap secret", async () => {
    const f = setup({ home: true });
    writeSite(join(f.work, "site"));
    expect((await f.publish({ path: "site" })).status).toBe(200);
    expect(f.service.minted).toEqual([{ action: "create", caller: "home" }]);
  });

  it("refuses a missing path, a path outside the working folder, a single file that isn't a page, and a folder without index.html", async () => {
    const f = setup();
    signIn();
    expect(await f.publish({ path: "nowhere" })).toMatchObject({ status: 404 });
    const outside = writeSite(join(dir, "outside"));
    expect(await f.publish({ path: outside })).toMatchObject({ status: 403, text: expect.stringContaining("working folder") });
    writeFileSync(join(f.work, "notes.md"), "# hi");
    expect(await f.publish({ path: "notes.md" })).toMatchObject({ status: 400, text: expect.stringContaining(".html") });
    writeSite(join(f.work, "noindex"), { "home.html": "<p>hi</p>" });
    expect(await f.publish({ path: "noindex" })).toMatchObject({ status: 400, text: expect.stringContaining("index.html") });
    expect(await f.publish({ path: "notes.md", title: "  " })).toMatchObject({ status: 400 });
    expect(f.service.minted).toEqual([]);
  });

  it("publishes a single .html file as the page, and leaves out hidden files, server code and links out of the folder", async () => {
    const f = setup();
    signIn();
    writeFileSync(join(f.work, "card.html"), "<p>Card</p>");
    await f.publish({ path: "card.html", title: "Card" });
    const [single] = [...f.service.pages.values()];
    expect(Object.fromEntries(single!.files)).toEqual({ "index.html": "<p>Card</p>" });
    const site = writeSite(join(f.work, "site"), { ...SITE, ".env": "SECRET=1", ".git/config": "x", "app.py": "print()", "node_modules/a.js": "x", "img/logo.svg": "<svg/>" });
    writeFileSync(join(dir, "secret.txt"), "outside");
    symlinkSync(join(dir, "secret.txt"), join(site, "linked.txt"));
    const outcome = await f.publish({ path: "site" });
    expect(outcome.text.split("\n").at(-1))
      .toBe("Left out app.py (pages can't carry .py files), linked.txt (links a page can't follow), node_modules/ (package and cache folders) and .env, .git/ (hidden).");
    const published = [...f.service.pages.values()][1]!;
    expect([...published.files.keys()].sort()).toEqual(["img/logo.svg", "index.html", "style.css"]);
  });

  it("publishes a dashboard's csv, parquet, arrow and map data with it, and leaves out a wasm file", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "dash"), { "index.html": "<p>Sales</p>", "data.parquet": "PAR1", "data/backup.csv": "a\n1\n", "data/live.arrow": "ARROW1",
      "data/land.geojson": "{}", "duckdb.wasm": "x" });
    const outcome = await f.publish({ path: "dash" });
    expect(outcome.text).toContain("Left out duckdb.wasm (pages can't carry .wasm files).");
    const [published] = [...f.service.pages.values()];
    expect([...published!.files.keys()].sort()).toEqual(["data.parquet", "data/backup.csv", "data/land.geojson", "data/live.arrow", "index.html"]);
  });

  it("says why each file was left out, a few names per reason, and how many more", async () => {
    const site = writeSite(join(dir, "site"), { "index.html": "<p>x</p>", "page#2.js": "x", [`${"d/".repeat(10)}deep.js`]: "x" });
    expect((await readPageBundle(site, [dir])).skipped).toEqual([{ path: "d/".repeat(10), why: "deep" }, { path: "page#2.js", why: "name" }]);
    expect(skippedNote([])).toBe("");
    const py = ["a.py", "b.py", "c.py", "d.py", "e.py"].map((path) => ({ path, why: "type" as const }));
    expect(skippedNote([{ path: ".env", why: "hidden" }, ...py, { path: "x.foo", why: "type" }, { path: "Makefile", why: "type" }, { path: "a#b.js", why: "name" }]))
      .toBe("Left out a.py, b.py, c.py and 2 more (pages can't carry .py files), x.foo (pages can't carry .foo files), " +
        "Makefile (pages can't carry files without an extension), a#b.js (names with characters a page can't hold) and 1 more.");
  });

  it("refuses a folder over a page's bytes or files before asking for a token", async () => {
    const f = setup();
    signIn();
    const site = writeSite(join(f.work, "big"), { "index.html": "x".repeat(2000), "a.css": "a", "b.css": "b" });
    await expect(readPageBundle(site, [f.work], { bytes: 1000, files: 200 })).rejects.toThrow(PageBundleError);
    await expect(readPageBundle(site, [f.work], { bytes: 5000, files: 2 })).rejects.toThrow(/more than 2 files/);
    expect((await readPageBundle(site, [f.work], { bytes: 5000, files: 3 })).files).toHaveLength(3);
    writeFileSync(join(site, "huge.png"), Buffer.alloc(5 * 1024 * 1024 + 1));
    expect(await f.publish({ path: "big" })).toMatchObject({ status: 413 });
    expect(f.service.minted).toEqual([]);
  });

  it("publishes one page when the same folder is published twice at once", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    const outcomes = await Promise.all([f.publish({ path: "site" }), f.publish({ path: "site", threadId: "thread-2" })]);
    expect(outcomes.map((outcome) => outcome.status)).toEqual([200, 200]);
    expect(f.service.pages.size).toBe(1);
    expect(f.service.minted.map((call) => call.action)).toEqual(["create", "update"]);
    expect(f.pages.store.list()).toHaveLength(1);
    expect(f.pages.store.list()[0]!.cards).toHaveLength(2);
  });

  it("says plainly when publishing can't be reached", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    f.service.state.down = true;
    expect(await f.publish({ path: "site" })).toEqual({ status: 503, text: "Publishing isn't available right now. Try again in a few minutes." });
  });
});

describe("an owner-only published page", () => {
  it("is kept on this server without asking the pages service for anything, even with no MausBot account", async () => {
    const f = setup();
    writeSite(join(f.work, "report"), { "index.html": "<!doctype html><h1>Traffic</h1>", "data.csv": "day,hits\nmon,3\n" });
    const outcome = await f.publish({ path: "report", title: "Traffic", visibility: "owner" });
    expect(outcome.status).toBe(200);
    const [record] = f.pages.store.list();
    const url = ownerUrl(record!.pageId);
    expect(outcome.text).toContain(`Published “Traffic” for you only: ${url}`);
    expect(outcome.text).toContain("Only you can open it");
    expect(f.service.minted).toEqual([]);
    expect(f.service.pages.size).toBe(0);
    expect(f.cards).toEqual([{ threadId: "thread-1", id: "m1", text: `“Traffic” is published for you: ${url}. Only you can open it.`,
      card: { state: "live", title: "Traffic", pageId: record!.pageId, url, visibility: "owner" } }]);
    expect(f.pages.files.read(record!.pageId, "")?.toString()).toBe("<!doctype html><h1>Traffic</h1>");
    expect(f.pages.files.read(record!.pageId, "data.csv")?.toString()).toBe("day,hits\nmon,3\n");
    expect(new PublishedPagesStore(join(f.data, "owner-pages.json")).get(record!.pageId)).toMatchObject({ url, visibility: "owner" });
    expect(new PublishedPagesStore(join(f.data, "published-pages.json")).list()).toEqual([]);
  });

  it("keeps its link when published again, and takes its files away with Unpublish", async () => {
    const f = setup();
    writeSite(join(f.work, "report"));
    await f.publish({ path: "report", visibility: "owner" });
    const [record] = f.pages.store.list();
    writeFileSync(join(f.work, "report", "style.css"), "h1{color:blue}");
    const again = await f.publish({ path: "report", visibility: "owner" });
    expect(again.text).toContain(`Updated “Bake sale” at the same link: ${ownerUrl(record!.pageId)}`);
    expect(f.pages.store.list()).toHaveLength(1);
    expect(f.pages.files.read(record!.pageId, "style.css")?.toString()).toBe("h1{color:blue}");
    expect(await f.pages.publisher.unpublish({ pageId: record!.pageId })).toMatchObject({ status: 200, card: { state: "unpublished", visibility: "owner" } });
    expect(f.pages.files.has(record!.pageId)).toBe(false);
    expect(f.pages.store.list()).toEqual([]);
    expect(f.service.minted).toEqual([]);
    expect(f.cards.map(({ card }) => [card.state, card.visibility])).toEqual([["unpublished", "owner"], ["unpublished", "owner"]]);
  });

  it("takes the public copy down when a published page becomes owner-only, and updates its cards", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "report"));
    await f.publish({ path: "report" });
    const [publicRecord] = f.pages.store.list();
    expect(f.service.pages.size).toBe(1);
    const switched = await f.publish({ path: "report", visibility: "owner" });
    expect(switched.status).toBe(200);
    expect(f.service.minted.map((call) => call.action)).toEqual(["create", "delete"]);
    expect(f.service.pages.size).toBe(0);
    expect(f.pages.store.get(publicRecord!.pageId)).toMatchObject({ visibility: "owner" });
    expect(new PublishedPagesStore(join(f.data, "published-pages.json")).list()).toEqual([]);
    // The card that showed the old public link now carries the owner-only one.
    expect(f.cards.map(({ card }) => [card.pageId, card.visibility])).toEqual([[publicRecord!.pageId, "owner"], [publicRecord!.pageId, "owner"]]);
    expect(f.cards[0]!.card).toMatchObject({ state: "live", visibility: "owner", url: ownerUrl(publicRecord!.pageId) });
    // Unpublishing marks both cards, including the one from before the switch.
    expect(await f.pages.publisher.unpublish({ pageId: publicRecord!.pageId })).toMatchObject({ status: 200 });
    expect(f.cards.map(({ card }) => card.state)).toEqual(["unpublished", "unpublished"]);
  });

  it("publishes again to the pages Worker with a new link when an owner-only page becomes public", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "report"));
    await f.publish({ path: "report", visibility: "owner" });
    const [local] = f.pages.store.list();
    const switched = await f.publish({ path: "report", visibility: "public" });
    expect(switched.status).toBe(200);
    const [remote] = [...f.service.pages.keys()];
    expect(remote).not.toBe(local!.pageId);
    expect(f.service.minted).toEqual([{ action: "create", caller: "desktop" }]);
    expect(f.pages.files.has(local!.pageId)).toBe(false);
    expect(new PublishedPagesStore(join(f.data, "owner-pages.json")).list()).toEqual([]);
    expect(f.cards.map(({ card }) => [card.pageId, card.visibility])).toEqual([[remote, undefined], [remote, undefined]]);
    expect(f.cards[0]!.card).toMatchObject({ state: "live", url: `https://${remote}.mausbot.page/` });
    // Unpublishing marks both cards, including the owner-only one from before the switch.
    expect(await f.pages.publisher.unpublish({ pageId: remote! })).toMatchObject({ status: 200 });
    expect(f.cards.map(({ card }) => card.state)).toEqual(["unpublished", "unpublished"]);
  });

  it("takes down a public copy this server has no record of when an explicit page id is made owner-only, and refuses when it can't", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    await f.publish({ path: "site" });
    const [page] = [...f.service.pages.keys()];
    f.pages.store.forget(page!);
    writeSite(join(f.work, "draft"), { "index.html": "<h1>Draft</h1>" });
    f.service.state.down = true;
    const refused = await f.publish({ path: "draft", pageId: page, title: "Draft", visibility: "owner" });
    expect(refused.status).toBe(503);
    expect(refused.text).toContain("could not be made owner-only");
    expect(f.pages.files.has(page!)).toBe(false);
    expect(f.pages.store.get(page!)).toBeNull();
    f.service.state.down = false;
    const switched = await f.publish({ path: "draft", pageId: page, title: "Draft", visibility: "owner" });
    expect(switched.status).toBe(200);
    expect(f.service.minted.map((call) => call.action)).toEqual(["create", "delete"]);
    expect(f.service.pages.size).toBe(0);
    expect(f.pages.files.read(page!, "")?.toString()).toBe("<h1>Draft</h1>");
    expect(f.pages.store.get(page!)).toMatchObject({ visibility: "owner", title: "Draft" });
  });

  it("changes nothing when the tool call has ended before an owner-only save or unpublish", async () => {
    const f = setup();
    writeSite(join(f.work, "report"));
    expect((await f.publish({ path: "report", visibility: "owner" })).status).toBe(200);
    const [record] = f.pages.store.list();
    writeFileSync(join(f.work, "report", "late.txt"), "later");
    const stop = new AbortController();
    stop.abort();
    expect(await f.publish({ path: "report", visibility: "owner", call: { signal: stop.signal } })).toMatchObject({ status: 503 });
    expect(f.pages.files.read(record!.pageId, "late.txt")).toBeNull();
    expect(f.cards).toHaveLength(1);
    await expect(f.publish({ path: "report", visibility: "owner", call: { assertActive: () => { throw new Error("the turn ended"); } } }))
      .rejects.toThrow("the turn ended");
    expect(f.pages.files.read(record!.pageId, "late.txt")).toBeNull();
    expect(await f.pages.publisher.unpublish({ pageId: record!.pageId, call: { signal: stop.signal } })).toMatchObject({ status: 503 });
    expect(f.pages.files.has(record!.pageId)).toBe(true);
    expect(f.pages.store.get(record!.pageId)).not.toBeNull();
    expect(f.cards.map(({ card }) => card.state)).toEqual(["live"]);
  });

  it("republishes a live owner-only page from its folder without touching the pages Worker", async () => {
    const f = setup();
    const site = writeSite(join(f.work, "report"));
    await f.publish({ path: "report", visibility: "owner", live: true });
    const [record] = f.pages.store.list();
    writeFileSync(join(site, "style.css"), "h1{color:red}");
    expect(await f.pages.publisher.refreshLive(Date.now() + 61_000)).toBe(1);
    expect(f.pages.files.read(record!.pageId, "style.css")?.toString()).toBe("h1{color:red}");
    expect(f.service.minted).toEqual([]);
    expect(f.pages.store.get(record!.pageId)).toMatchObject({ live: true, visibility: "owner" });
  });
});

describe("pages stored before the visibility setting", () => {
  it("read as public, and keep no visibility once published again", async () => {
    const data = join(dir, "legacy-data");
    mkdirSync(data, { recursive: true });
    const source = await bundle.pageSource(writeSite(join(dir, "legacy-work", "site")), [join(dir, "legacy-work")]);
    const pageId = "a".repeat(32), url = `https://${pageId}.mausbot.page/`;
    writeFileSync(join(data, "published-pages.json"), JSON.stringify({ version: 1, pages: [{ pageId, url, title: "Old report", botId: "bot-1", source,
      cards: [], createdAt: 1, updatedAt: 2, live: true }] }));
    const store = new PagesStore(data);
    expect(store.get(pageId)).toMatchObject({ url, title: "Old report" });
    expect(store.get(pageId)).not.toHaveProperty("visibility");
    expect(store.list()).toHaveLength(1);
    // A service opened on that data publishes the same folder to the Worker, exactly as before the setting existed.
    const service = fakePagesService();
    service.pages.set(pageId, { title: "Old report", files: new Map() });
    signIn();
    const pages = createPublishedPages({ dataDir: data, cloudHome: null, fetch: (input, init) => service.fetch(input, init),
      pageOrigin: () => "https://cloud.example.test", patch: () => {} });
    const outcome = await pages.publisher.publish({ botId: "bot-1", threadId: "thread-1", path: join(dir, "legacy-work", "site"), title: "Old report",
      roots: [join(dir, "legacy-work")], post: () => "m1" });
    expect(outcome.status).toBe(200);
    expect(service.minted).toEqual([{ action: "update", pageId, caller: "desktop" }]);
    expect(new PublishedPagesStore(join(data, "published-pages.json")).get(pageId)).not.toHaveProperty("visibility");
    expect(new PublishedPagesStore(join(data, "owner-pages.json")).list()).toEqual([]);
  });
});

describe("a page tool call whose turn ends", () => {
  function tool(f: ReturnType<typeof setup>, options: { stopDuringFolders?: boolean; stopAfterToken?: boolean; signal?: AbortSignal } = {}) {
    const turn = { active: true };
    const fetch = f.service.fetch;
    const handler = createPagesInternalRoutes(f.pages.publisher);
    if (options.stopAfterToken) {
      f.service.fetch = async (input, init) => {
        const response = await fetch(input, init);
        if (new Request(input, init).url === FAKE_TOKEN_URL) turn.active = false;
        return response;
      };
    }
    const sent: { status?: number } = {};
    const call = (path: string, body: unknown) => handler({ method: "POST", path, res: {} as never, botId: "bot-1", threadId: "thread-1",
      json: ((_res: unknown, status: number) => { sent.status = status; }) as never,
      readBody: async () => body,
      folders: async () => { if (options.stopDuringFolders) turn.active = false; return { roots: [f.work], vmWorkspace: null }; },
      requireActive: () => { if (!turn.active) throw Object.assign(new Error("the internal turn capability has expired"), { status: 401 }); },
      signal: options.signal ?? new AbortController().signal,
      post: () => "m1" });
    return { call, sent };
  }

  it("publishes nothing when Stop ends the turn while its folders are resolved", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    const { call, sent } = tool(f, { stopDuringFolders: true });
    await expect(call("/api/internal/pages/publish", { path: "site", title: "Bake sale" })).rejects.toMatchObject({ status: 401 });
    expect(sent.status).toBeUndefined();
    expect(f.service.minted).toEqual([]);
    expect(f.service.pages.size).toBe(0);
  });

  it("uploads nothing when the turn ends after the upload token was minted", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    const { call } = tool(f, { stopAfterToken: true });
    await expect(call("/api/internal/pages/publish", { path: "site", title: "Bake sale" })).rejects.toMatchObject({ status: 401 });
    expect(f.service.minted).toHaveLength(1);
    expect(f.service.pages.size).toBe(0);
    expect(f.pages.store.list()).toEqual([]);
  });

  it("takes nothing down when the turn ends before unpublish_page reaches the service", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    await f.publish({ path: "site" });
    const { call } = tool(f, { stopDuringFolders: true });
    await expect(call("/api/internal/pages/unpublish", { path: "site" })).rejects.toMatchObject({ status: 401 });
    expect(f.service.minted.map((each) => each.action)).toEqual(["create"]);
    expect(f.service.pages.size).toBe(1);
  });

  it("asks the pages service for nothing once the tool call's request is gone", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    const gone = new AbortController();
    gone.abort();
    const { call } = tool(f, { signal: gone.signal });
    await call("/api/internal/pages/publish", { path: "site", title: "Bake sale" }).catch(() => undefined);
    expect(f.service.minted).toEqual([]);
    expect(f.service.pages.size).toBe(0);
  });

  it("keeps a removable page when the request goes while the committed upload's answer is still arriving", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    const gone = new AbortController();
    const fetch = f.service.fetch;
    f.service.fetch = async (input, init) => {
      const response = await fetch(input, init);
      if (init?.method !== "PUT") return response;
      const signal = init.signal!;
      const body = new ReadableStream({ start: (stream) => signal.addEventListener("abort", () => stream.error(signal.reason)) });
      setTimeout(() => gone.abort());
      return new Response(body, { status: response.status, headers: response.headers });
    };
    const { call, sent } = tool(f, { signal: gone.signal });
    await call("/api/internal/pages/publish", { path: "site", title: "Bake sale" });
    expect(sent.status).toBe(503);
    const [pageId] = [...f.service.pages.keys()];
    expect(new PublishedPagesStore(join(f.data, "published-pages.json")).get(pageId!)).toMatchObject({ uncertain: true, cards: [{ threadId: "thread-1", messageId: "m1" }] });
    expect(await f.pages.publisher.unpublish({ path: "site", botId: "bot-1", roots: [f.work] })).toMatchObject({ status: 200 });
    expect(f.service.pages.size).toBe(0);
    expect(f.pages.store.list()).toEqual([]);
  });
});

describe("unpublishing a page", () => {
  it("takes it down by id or by the folder it came from, and marks every card that showed it", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    writeSite(join(f.work, "menu"));
    await f.publish({ path: "site" });
    await f.publish({ path: "site", threadId: "thread-2" });
    await f.publish({ path: "menu", title: "Menu" });
    const [site, menu] = [...f.service.pages.keys()];
    const outcome = await f.pages.publisher.unpublish({ pageId: site });
    expect(outcome).toMatchObject({ status: 200, text: "Unpublished “Bake sale”. Its link no longer opens.", card: { state: "unpublished", usage: { pages: 1, limit: 5 } } });
    expect(f.cards.filter((card) => card.card.pageId === site).map((card) => [card.threadId, card.card.state, card.text])).toEqual([
      ["thread-1", "unpublished", "Unpublished “Bake sale”. Its link no longer opens."], ["thread-2", "unpublished", "Unpublished “Bake sale”. Its link no longer opens."]]);
    const byPath = await f.pages.publisher.unpublish({ path: "menu", botId: "bot-1", roots: [f.work] });
    expect(byPath.status).toBe(200);
    expect(f.service.pages.has(menu!)).toBe(false);
    expect(await f.pages.publisher.unpublish({ path: "menu", botId: "bot-1", roots: [f.work] })).toMatchObject({ status: 404 });
    expect(await f.pages.publisher.unpublish({ pageId: "NOT-AN-ID" })).toMatchObject({ status: 400 });
    expect(await f.pages.publisher.unpublish({})).toMatchObject({ status: 400 });
  });

  it("forgets a page that is already gone", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    await f.publish({ path: "site" });
    const [page] = [...f.service.pages.keys()];
    f.service.pages.delete(page!);
    expect(await f.pages.publisher.unpublish({ pageId: page })).toMatchObject({ status: 200, text: "That page was already taken down.", card: { state: "unpublished" } });
    expect(f.pages.store.get(page!)).toBeNull();
  });

  it.each(["path", "page id"])("unpublishes by %s while a missing page is replaced", async (by) => {
    const f = setup();
    signIn();
    const source = await bundle.pageSource(writeSite(join(f.work, "site")), [f.work]);
    await f.publish({ path: "site" });
    const [oldId] = [...f.service.pages.keys()];
    f.service.pages.delete(oldId!);
    const arrived = deferred(), answered = deferred();
    const fetch = f.service.fetch;
    f.service.fetch = async (input, init) => {
      const response = await fetch(input, init);
      if (init?.method === "PUT" && response.status === 410) { arrived.resolve(); await answered.promise; }
      return response;
    };
    const update = f.publish({ path: "site" });
    await arrived.promise;
    const lookup = vi.spyOn(bundle, "pageSource").mockResolvedValue(source);
    const unpublished = f.pages.publisher.unpublish(by === "path" ? { path: "site", botId: "bot-1", roots: [f.work] } : { pageId: oldId });
    await Promise.resolve();
    lookup.mockRestore();
    answered.resolve();
    expect((await update).status).toBe(200);
    const replacement = f.cards.at(-1)!.card.pageId!;
    expect(replacement).not.toBe(oldId);
    expect(await unpublished).toMatchObject({ status: 200, card: { pageId: by === "path" ? replacement : oldId } });
    expect(f.service.pages.has(replacement)).toBe(by !== "path");
    expect(f.pages.store.get(replacement) === null).toBe(by === "path");
    expect(f.cards.at(-1)!.card.state).toBe(by === "path" ? "unpublished" : "live");
  });

  it("unpublishes by path after the first publish in flight creates its record", async () => {
    const f = setup();
    signIn();
    const source = await bundle.pageSource(writeSite(join(f.work, "site")), [f.work]);
    const arrived = deferred(), answered = deferred();
    const fetch = f.service.fetch;
    f.service.fetch = async (input, init) => {
      const response = await fetch(input, init);
      if (init?.method === "PUT") { arrived.resolve(); await answered.promise; }
      return response;
    };
    const publish = f.publish({ path: "site" });
    await arrived.promise;
    const lookup = vi.spyOn(bundle, "pageSource").mockResolvedValue(source);
    const unpublished = f.pages.publisher.unpublish({ path: "site", botId: "bot-1", roots: [f.work] });
    await Promise.resolve();
    lookup.mockRestore();
    answered.resolve();
    expect((await publish).status).toBe(200);
    expect((await unpublished).status).toBe(200);
    expect(f.service.pages.size).toBe(0);
    expect(f.pages.store.list()).toEqual([]);
    expect(f.cards.map((card) => card.card.state)).toEqual(["unpublished"]);
  });

  it.each([["the same folder", false], ["another folder by its page id", true]])("takes a page down after an update from %s already in flight, so the update's late answer leaves no record or live card", async (_case, byId) => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    writeSite(join(f.work, "draft"));
    await f.publish({ path: "site" });
    const [page] = [...f.service.pages.keys()];
    let release!: () => void;
    const answered = new Promise<void>((resolve) => { release = resolve; });
    let uploaded!: () => void;
    const stored = new Promise<void>((resolve) => { uploaded = resolve; });
    const fetch = f.service.fetch;
    f.service.fetch = async (input, init) => {
      const response = await fetch(input, init);
      if (init?.method === "PUT") { uploaded(); await answered; }
      return response;
    };
    const update = f.publish(byId ? { path: "draft", pageId: page } : { path: "site" });
    await stored;
    const unpublished = f.pages.publisher.unpublish({ pageId: page });
    await new Promise((resolve) => setTimeout(resolve, 20));
    release();
    expect((await update).status).toBe(200);
    expect((await unpublished).status).toBe(200);
    expect(f.service.pages.size).toBe(0);
    expect(f.pages.store.get(page!)).toBeNull();
    expect(f.cards.map((card) => card.card.state)).toEqual(["unpublished", "unpublished"]);
  });

  it("takes a page down after its folder's update in flight, though an update from another folder by its page id moved the page meanwhile", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    writeSite(join(f.work, "draft"));
    await f.publish({ path: "site" });
    const [page] = [...f.service.pages.keys()];
    let release!: () => void;
    const answered = new Promise<void>((resolve) => { release = resolve; });
    let uploaded!: () => void;
    const stored = new Promise<void>((resolve) => { uploaded = resolve; });
    let held = false;
    const fetch = f.service.fetch;
    f.service.fetch = async (input, init) => {
      const response = await fetch(input, init);
      if (init?.method === "PUT" && !held) { held = true; uploaded(); await answered; }
      return response;
    };
    const fromSite = f.publish({ path: "site" });
    await stored;
    // The draft's folder is read before it queues, so its read resolving proves the update below is queued ahead of the
    // unpublish.
    const read = vi.spyOn(bundle, "readPageBundle");
    const fromDraft = f.publish({ path: "draft", pageId: page });
    await vi.waitFor(() => expect(read).toHaveBeenCalled());
    await read.mock.results[0]!.value;
    await new Promise((resolve) => setTimeout(resolve));
    read.mockRestore();
    const unpublished = f.pages.publisher.unpublish({ pageId: page });
    release();
    expect((await Promise.all([fromSite, fromDraft, unpublished])).map((outcome) => outcome.status)).toEqual([200, 200, 200]);
    expect(f.service.pages.size).toBe(0);
    expect(f.pages.store.get(page!)).toBeNull();
    expect(f.cards.map((card) => card.card.state)).toEqual(["unpublished", "unpublished", "unpublished"]);
  });

  it("updates the page a folder's publish waited for, though the folder moved to another page meanwhile", async () => {
    const f = setup();
    signIn();
    for (const folder of ["site", "other", "draft", "draft2"]) writeSite(join(f.work, folder));
    await f.publish({ path: "site" });
    await f.publish({ path: "other" });
    const [p, q] = [...f.service.pages.keys()];
    const holds = new Map<number, { arrived: () => void; answered: Promise<void> }>();
    const hold = (put: number) => {
      let arrived!: () => void, release!: () => void;
      const reached = new Promise<void>((resolve) => { arrived = resolve; });
      holds.set(put, { arrived, answered: new Promise<void>((resolve) => { release = resolve; }) });
      return { reached, release: () => release() };
    };
    let puts = 0;
    const fetch = f.service.fetch;
    f.service.fetch = async (input, init) => {
      const response = await fetch(input, init);
      const held = init?.method === "PUT" ? holds.get(++puts) : undefined;
      if (held) { held.arrived(); await held.answered; }
      return response;
    };
    const first = hold(1), third = hold(3);
    const fromDraft = f.publish({ path: "draft", pageId: p });
    await first.reached;
    // The folder's publish must pick its page (p) before anything below moves the folder to q.
    const read = vi.spyOn(bundle, "readPageBundle");
    const fromSite = f.publish({ path: "site" });
    await vi.waitFor(() => expect(read).toHaveBeenCalled());
    await read.mock.results[0]!.value;
    await new Promise((resolve) => setTimeout(resolve));
    read.mockRestore();
    await f.publish({ path: "site", pageId: q });
    first.release();
    await third.reached;
    await f.publish({ path: "draft2", pageId: q });
    expect((await f.pages.publisher.unpublish({ pageId: q })).status).toBe(200);
    third.release();
    await Promise.all([fromDraft, fromSite]);
    expect(f.service.pages.has(q!)).toBe(false);
    expect(f.pages.store.get(q!)).toBeNull();
    expect(f.pages.store.get(p!)).not.toBeNull();
  });
});

describe("sharing a chat page from its card", () => {
  function route(f: ReturnType<typeof setup>, page: AppPages["page"] = () => ({ ok: true, title: "Pricing", files: [{ path: "index.html", data: Buffer.from("<!DOCTYPE html><h1>Pricing</h1>") }], rev: 2 })) {
    const shown: Array<{ threadId: string; messageId: string; card: PublishedPageCard }> = [];
    const handler = createPublishedPageRoutes(f.pages.publisher, {
      botOf: (threadId) => (threadId === "room-1" ? null : { id: "bot-1" }),
      page,
      published: (threadId, messageId) => {
        const last = shown.filter((each) => each.threadId === threadId && each.messageId === messageId).at(-1)?.card;
        return last?.state === "live" ? last.pageId ?? null : null;
      },
      show: (threadId, messageId, card) => { shown.push({ threadId, messageId, card }); return messageId; },
    });
    const call = async (method: string, path: string, body?: unknown) => {
      let answer: { status: number; body: any } | null = null;
      const out = await handler({
        req: {} as never, res: {} as never, url: new URL(`http://x${path}`), path, method, auth: {} as never,
        json: ((_res: unknown, status: number, value: unknown) => { answer = { status, body: value }; }) as never,
        readBody: (async () => body) as never,
      });
      return out === PASS ? PASS : answer!;
    };
    return { call, shown };
  }

  it("publishes the page's files, gives its own card the link, and keeps that link on the next share", async () => {
    const f = setup();
    signIn();
    const { call, shown } = route(f);
    const path = "/api/threads/thread-1/messages/m7/app/publish";
    const first = await call("POST", path, { rev: 2 }) as { status: number; body: any };
    expect(first).toMatchObject({ status: 200, body: { ok: true, card: { state: "live", title: "Pricing" } } });
    const [pageId] = [...f.service.pages.keys()];
    expect(f.service.pages.get(pageId!)!.files.get("index.html")).toBe("<!DOCTYPE html><h1>Pricing</h1>");
    expect(shown).toEqual([{ threadId: "thread-1", messageId: "m7", card: first.body.card }]);
    expect(f.cards).toEqual([]);
    expect(await call("POST", path, {})).toMatchObject({ status: 200, body: { card: { pageId } } });
    expect(f.service.pages.size).toBe(1);
    expect(f.service.minted.map((each) => each.action)).toEqual(["create", "update"]);
  });

  it("publishes a folder page's files beside index.html under the folder's own link", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "dash"), { "index.html": "<h1>Dash</h1>", "data.csv": "a\n1" });
    await f.publish({ path: "dash", title: "Dash" });
    const [pageId] = [...f.service.pages.keys()];
    const { call } = route(f, () => ({ ok: true, title: "Dash", rev: 0, folder: join(realpathSync.native(f.work), "dash"),
      files: [{ path: "index.html", data: Buffer.from("<h1>Dash, again</h1>") }, { path: "data.csv", data: Buffer.from("a\n2") }] }));
    expect(await call("POST", "/api/threads/thread-1/messages/m9/app/publish", {})).toMatchObject({ status: 200, body: { card: { pageId } } });
    expect(Object.fromEntries(f.service.pages.get(pageId!)!.files)).toEqual({ "index.html": "<h1>Dash, again</h1>", "data.csv": "a\n2" });
  });

  it("refuses a room, a bad body and a page that can't be built, and shows no card for the plan's limit", async () => {
    const f = setup({ quota: 0 });
    signIn();
    const { call, shown } = route(f);
    expect(await call("POST", "/api/threads/thread-1/messages/m7/app/publish", {})).toMatchObject({ status: 402, body: { card: { state: "limit", upgrade: true } } });
    expect(shown).toEqual([]);
    expect(await call("POST", "/api/threads/room-1/messages/m7/app/publish", {})).toMatchObject({ status: 404 });
    expect(await call("POST", "/api/threads/thread-1/messages/m7/app/publish", { rev: "2" })).toMatchObject({ status: 400 });
    const broken = route(f, () => ({ ok: false, status: 422, error: "jsx: line 2: Unexpected token." }));
    expect(await broken.call("POST", "/api/threads/thread-1/messages/m7/app/publish", {})).toEqual({ status: 422, body: { error: "jsx: line 2: Unexpected token." } });
    expect(await call("GET", "/api/threads/thread-1/messages/m7/app/publish")).toBe(PASS);
    expect(await call("POST", "/api/threads/thread-1/messages/m7/app")).toBe(PASS);
  });
});

describe("pages access", () => {
  it("takes only a well-formed pages token for the Admin over https from the desktop", () => {
    expect(applyIncludedPagesMessage({ type: "openmausbot:included-x", access: null })).toBe(false);
    expect(() => applyIncludedPagesMessage({ type: "openmausbot:included-pages", access: { url: "http://cloud.example.test/x", token: FAKE_DESKTOP_TOKEN } })).toThrow();
    expect(() => applyIncludedPagesMessage({ type: "openmausbot:included-pages", access: { url: FAKE_TOKEN_URL, token: "omb_xd_short" } })).toThrow();
    expect(applyIncludedPagesMessage({ type: "openmausbot:included-pages", access: { url: FAKE_TOKEN_URL, token: FAKE_DESKTOP_TOKEN } })).toBe(true);
  });

  it("signs a home's request exactly as the Admin checks it", () => {
    // The same vector is pinned in openmaus-cloud tests/cloud-pages.test.ts.
    expect(pagesHomeSignature("s".repeat(43), "cm-test-home", "1792670400", "nonce-nonce-nonce-1", '{"action":"create"}')).toBe("smys7kDYS99REKsdwsd9OaXv6pH_hP1Wajaq3KrTiVo");
  });
});

describe("a live published page", () => {
  const publishLive = (f: ReturnType<typeof setup>, live?: boolean) => f.pages.publisher.publish({
    botId: "bot-1", threadId: "thread-1", path: "site", title: "Bake sale", roots: [f.work], post: () => "m1", ...(live !== undefined ? { live } : {}) });

  it("carries a version and a reload check in its index.html, and is remembered as live", async () => {
    const f = setup();
    signIn();
    writeSite(join(f.work, "site"));
    expect((await publishLive(f, true)).status).toBe(200);
    const [page] = [...f.service.pages.keys()];
    const html = f.service.pages.get(page!)!.files.get("index.html")!;
    expect(html.startsWith("<!doctype html><meta name=\"omb-live\" content=\"")).toBe(true);
    expect(html).toContain("location.reload()");
    expect(html.endsWith("<h1>Bake sale</h1>")).toBe(true);
    expect(f.service.pages.get(page!)!.files.get("style.css")).toBe(SITE["style.css"]);
    expect(f.pages.store.get(page!)).toMatchObject({ live: true });
  });

  it("publishes again to the same link when its folder changes, at most once a minute, and never a page that isn't live", async () => {
    const f = setup();
    signIn();
    const site = writeSite(join(f.work, "site"));
    await publishLive(f, true);
    writeSite(join(f.work, "still"), { "index.html": "<p>Still</p>" });
    await f.pages.publisher.publish({ botId: "bot-1", threadId: "thread-1", path: "still", title: "Still", roots: [f.work], post: () => "m2" });
    const [page] = [...f.service.pages.keys()];
    const version = () => /content="([^"]+)"/u.exec(f.service.pages.get(page!)!.files.get("index.html")!)?.[1];
    const first = version();
    expect(await f.pages.publisher.refreshLive(Date.now() + 61_000)).toBe(0);
    writeFileSync(join(site, "style.css"), "h1{color:blue}");
    expect(await f.pages.publisher.refreshLive(Date.now() + 1_000)).toBe(0);
    expect(await f.pages.publisher.refreshLive(Date.now() + 61_000)).toBe(1);
    expect(f.service.pages.get(page!)!.files.get("style.css")).toBe("h1{color:blue}");
    expect(version()).not.toBe(first);
    expect(f.service.minted.map((call) => call.action)).toEqual(["create", "create", "update"]);
    expect(await f.pages.publisher.refreshLive(Date.now() + 130_000)).toBe(0);
    // Publishing it again keeps it live unless told otherwise.
    await publishLive(f);
    expect(f.pages.store.get(page!)).toMatchObject({ live: true });
    await publishLive(f, false);
    expect(f.pages.store.get(page!)).not.toHaveProperty("live");
    expect(f.service.pages.get(page!)!.files.get("index.html")).toBe(SITE["index.html"]);
  });

  it("stops being published again once its bot can no longer read the folder, and keeps its link", async () => {
    let roots: readonly string[] | null = null;
    const asked: string[] = [];
    const f = setup({ liveRoots: (botId, threadId) => { asked.push(`${botId} ${threadId}`); return roots; } });
    roots = [f.work];
    signIn();
    const site = writeSite(join(f.work, "site"));
    await publishLive(f, true);
    const [page] = [...f.service.pages.keys()];
    writeFileSync(join(site, "style.css"), "h1{color:blue}");
    expect(await f.pages.publisher.refreshLive(Date.now() + 61_000)).toBe(1);
    expect(asked).toContain("bot-1 thread-1");
    roots = null;
    writeFileSync(join(site, "style.css"), "h1{color:green}");
    expect(await f.pages.publisher.refreshLive(Date.now() + 130_000)).toBe(0);
    expect(f.pages.store.get(page!)).not.toHaveProperty("live");
    expect(f.pages.store.get(page!)).toMatchObject({ url: expect.any(String) });
    expect(f.service.pages.get(page!)!.files.get("style.css")).toBe("h1{color:blue}");
    expect(f.service.minted.map((call) => call.action)).toEqual(["create", "update"]);
  });

  it("waits while the workspace is backed up, restored or moved", async () => {
    let paused = false;
    const f = setup({ paused: () => paused });
    signIn();
    const site = writeSite(join(f.work, "site"));
    await publishLive(f, true);
    writeFileSync(join(site, "style.css"), "h1{color:blue}");
    paused = true;
    expect(await f.pages.publisher.refreshLive(Date.now() + 61_000)).toBe(0);
    paused = false;
    expect(await f.pages.publisher.refreshLive(Date.now() + 61_000)).toBe(1);
  });

  it("waits ten minutes before trying a folder that can't be published as it is", async () => {
    const f = setup();
    signIn();
    const site = writeSite(join(f.work, "site"));
    await publishLive(f, true);
    const start = Date.now();
    rmSync(join(site, "index.html"));
    expect(await f.pages.publisher.refreshLive(start + 61_000)).toBe(0);
    writeFileSync(join(site, "index.html"), "<h1>Back</h1>");
    expect(await f.pages.publisher.refreshLive(start + 130_000)).toBe(0);
    expect(await f.pages.publisher.refreshLive(start + 662_000)).toBe(1);
    expect(f.service.minted.map((call) => call.action)).toEqual(["create", "update"]);
  });
});