/** * Cotton Fetch in the object (src/fetch.ts): a link pushed into the fetch * table by the phone's door, a plain create or Cotton MCP is queued with its * kind and what it wants; the Mac reads the queue, claims a row, says its * progress, lands its records or fails with one sentence; the owner cancels * (the Mac's next word is refused) and tries again. Every link, title and id * is invented. */ import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; import { checkSource, oneSentence, provisionalTitle, sourceKindOf, withFetchDefaults } from "../src/fetch.ts"; import { Store } from "../src/store.ts"; import { DATABASE_ID, PERSONAL_TABLES, answer, http, personalObject, FILMS_OPEN } from "./personal.ts"; import { sealRow } from "./seal-device.ts"; type Doc = Record; const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug)); const MAGNET = "magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&dn=An+Invented+Film+%281954%29&tr=udp%3A%2F%2Ftracker.example%3A1337"; const PAGE = "https://video.example/watch?v=invented01"; const FILE = "https://files.example/books/an-invented-book.epub"; async function act(slug: string, credential: string, name: string, args: Record = {}) { return http>(slug, "POST", "/v1/act", { act: name, args }, { authorization: `Bearer ${credential}` }); } async function row(slug: string, id: string): Promise { const data = await runInDurableObject(stub(slug), (_i, state) => new Store(state.storage.sql, () => new Date()).get("fetch", id)?.data ?? null); expect(data, `fetch ${id}`).not.toBeNull(); return data!; } const pendingOf = async (slug: string, auth: string) => (await http<{ rows: Doc[] }>(slug, "GET", "/v1/fetch/pending", undefined, { authorization: `Bearer ${auth}` })).body.rows; /** RULE (owner, 5 Nov 2026: Cotton Fetch): a link's spelling says what it is until the Mac knows better. */ describe("a link's kind", () => { it("reads a magnet or a .torrent as a torrent, a file's extension as a file, anything else as a page", () => { expect(sourceKindOf(MAGNET)).toBe("torrent"); expect(sourceKindOf("https://archive.example/download/x/x_archive.torrent")).toBe("torrent"); expect(sourceKindOf(FILE)).toBe("file"); expect(sourceKindOf("https://img.example/a/picture.JPG?size=large")).toBe("file"); expect(sourceKindOf(PAGE)).toBe("page"); expect(sourceKindOf("https://video.example/")).toBe("page"); }); it("takes only a magnet naming a torrent or an http(s) address", () => { expect(checkSource(` ${PAGE} `)).toBe(PAGE); for (const bad of ["", "ftp://files.example/a.zip", "magnet:?dn=nothing", "not a link", "javascript:alert(1)"]) { expect(() => checkSource(bad), bad).toThrow(); } }); it("titles a row by the magnet's name, the file's name, else the host and path", () => { expect(provisionalTitle(MAGNET)).toBe("An Invented Film (1954)"); expect(provisionalTitle(FILE)).toBe("an-invented-book.epub"); expect(provisionalTitle(PAGE)).toBe("video.example/watch"); }); it("completes a created row: wants by its kind unless given, queued, added now", () => { const now = "2026-11-05T14:00:00.000Z"; expect(withFetchDefaults({ source: PAGE }, now)).toMatchObject({ source: PAGE, source_kind: "page", wants: "video", state: "queued", added_on: now }); expect(withFetchDefaults({ source: MAGNET }, now)).toMatchObject({ source_kind: "torrent", wants: "files" }); expect(withFetchDefaults({ source: PAGE, wants: "audio", title: "Mine" }, now)).toMatchObject({ wants: "audio", title: "Mine" }); expect(() => withFetchDefaults({ source: PAGE, wants: "everything" }, now)).toThrow(); }); it("keeps one sentence of a fetcher's reason, never its stack", () => { expect(oneSentence("ERROR: [invented] x: This video is DRM protected\nTraceback (most recent call last):\n File …")).toBe("ERROR: [invented] x: This video is DRM protected"); expect(oneSentence("a".repeat(400)).length).toBe(300); }); }); /** RULE (owner, 5 Nov 2026): the queue lives in the database, so the phone, the share sheet or any assistant pushes into it and the Mac fetches. */ describe("the fetch queue", () => { const SLUG = "fetch-queue"; let credential = ""; let owner = ""; let page = ""; let torrent = ""; it("queues a link from the phone's door, a plain create and Cotton MCP, oldest first, for the owner only", async () => { // Fetch is still pending: its landing names a fetched file by its book's title, so books are open here until the landing moves to the Mac. ({ credential, owner } = await personalObject(SLUG, { open: [...FILMS_OPEN.open, "book", "fetch", "fetch_file"] })); const added = await act(SLUG, credential, "fetch_add", { source: PAGE, wants: "audio" }); expect(added.status, JSON.stringify(added.body)).toBe(200); page = String(added.body.fetch); expect(added.body.made).toEqual({ table: "fetch", id: page }); expect(await row(SLUG, page)).toMatchObject({ source: PAGE, wants: "audio", source_kind: "page", state: "queued", title: "video.example/watch" }); const created = await act(SLUG, credential, "create", { table: "fetch", data: { source: MAGNET } }); expect(created.status, JSON.stringify(created.body)).toBe(200); torrent = (created.body.made as { id: string }).id; expect(await row(SLUG, torrent)).toMatchObject({ source_kind: "torrent", wants: "files", state: "queued", title: "An Invented Film (1954)" }); const made = (await answer<{ record: { id: string } }>(SLUG, owner, "create_record", { table: "fetch", data: { source: FILE } })).record; expect(await row(SLUG, made.id)).toMatchObject({ source_kind: "file", wants: "files", state: "queued" }); expect((await act(SLUG, credential, "fetch_add", { source: "ftp://files.example/a.zip" })).body.code).toBe("bad_source"); const rows = await pendingOf(SLUG, owner); expect(rows.map((r) => r.id)).toEqual([page, torrent, made.id]); expect(rows[0]).toEqual({ id: page, source: PAGE, wants: "audio", source_kind: "page", title: "video.example/watch" }); expect((await http(SLUG, "GET", "/v1/fetch/pending")).status, "the queue is the owner's").toBe(403); }); it("lets one Mac claim a queued row, refuses a second claim, and takes its progress", async () => { const claim = await act(SLUG, owner, "fetch_claim", { id: page, machine: "m-invented" }); expect(claim.status, JSON.stringify(claim.body)).toBe(200); expect(claim.body).toMatchObject({ fetch: page, state: "fetching" }); const again = await act(SLUG, owner, "fetch_claim", { id: page, machine: "m-other" }); expect([again.status, again.body.code]).toEqual([409, "not_queued"]); expect((await pendingOf(SLUG, owner)).map((r) => r.id)).not.toContain(page); const held = await http<{ rows: Doc[]; held: Doc[] }>(SLUG, "GET", "/v1/fetch/pending?machine=m-invented", undefined, { authorization: `Bearer ${owner}` }); expect(held.body.held.map((r) => r.id), "a Mac restarted mid-fetch takes up what it holds").toEqual([page]); expect((await http<{ held: Doc[] }>(SLUG, "GET", "/v1/fetch/pending?machine=m-other", undefined, { authorization: `Bearer ${owner}` })).body.held).toEqual([]); const picture = `${DATABASE_ID}/photos/${"a".repeat(64)}.jpg`; const progress = await act(SLUG, owner, "fetch_progress", { id: page, progress: 0.425, bytes: 4_250_000, of_bytes: 10_000_000, speed_bps: 1_000_000, eta_seconds: 5.7, title: "An Invented Short", picture }); expect(progress.status, JSON.stringify(progress.body)).toBe(200); expect(await row(SLUG, page)).toMatchObject({ state: "fetching", machine: "m-invented", progress: 42, bytes: 4_250_000, of_bytes: 10_000_000, eta_seconds: 6, title: "An Invented Short", picture }); expect((await act(SLUG, owner, "fetch_progress", { id: page, progress: 2 })).body.code).toBe("bad_args"); expect((await act(SLUG, owner, "fetch_progress", { id: page, picture: "https://elsewhere.example/a.jpg" })).body.code).toBe("bad_picture"); expect((await act(SLUG, owner, "fetch_progress", { id: torrent, progress: 0.1 })).body.code, "a row nobody claimed").toBe("not_fetching"); expect((await act(SLUG, owner, "fetch_progress", { id: page, landing: true })).body.state).toBe("landing"); }); it("lands its records, each linked by its kind, and is done", async () => { const book = await act(SLUG, credential, "create", { table: "book", data: { title: "An Invented Short", author: "Invented Studio" } }); expect(book.status, JSON.stringify(book.body)).toBe(200); const bookId = (book.body.made as { id: string }).id; const missing = await act(SLUG, owner, "fetch_landed", { id: page, landed: [{ table: "book", id: "book-gone" }] }); expect([missing.status, missing.body.code]).toEqual([404, "no_such_record"]); expect((await act(SLUG, owner, "fetch_landed", { id: page, landed: [{ table: "person", id: bookId }] })).body.code).toBe("bad_args"); const landed = await act(SLUG, owner, "fetch_landed", { id: page, landed: [{ table: "book", id: bookId, bytes: 2_430_774 }, { table: "book", id: bookId, bytes: 2_430_774 }] }); expect(landed.status, JSON.stringify(landed.body)).toBe(200); expect(landed.body).toMatchObject({ fetch: page, state: "done", landed: 1 }); const done = await row(SLUG, page); expect(done).toMatchObject({ state: "done", progress: 100, landed_count: 1, bytes: 2_430_774, of_bytes: 2_430_774 }); const files = await runInDurableObject(stub(SLUG), (_i, state) => [...new Store(state.storage.sql, () => new Date()).scan("fetch_file")].map((r) => r.data)); expect(files).toEqual([expect.objectContaining({ fetch: page, name: "An Invented Short", kind: "book", book: bookId })]); expect(done.finished_on).toEqual(expect.any(String)); expect(done.speed_bps ?? null).toBeNull(); }); // RULE: an episode's file names its series too, from the episode's own clear links (its series, else its season's // film), so a phone that holds no episodes can tell from the file which title it belongs to. it("names an episode's series on its file, by the episode's series or its season's film", async () => { const made = async (table: string, data: Record) => { const answered = await act(SLUG, credential, "create", { table, data }); expect(answered.status, JSON.stringify(answered.body)).toBe(200); return (answered.body.made as { id: string }).id; }; const series = await made("film", { title: "An Invented Series", kind: "series", status: "want_to_watch" }); const season = await made("film_season", { film: series, number: 2, title: "Season 2" }); const own = await made("film_episode", { series, season, number: 1, title: "Own Link" }); const bySeason = await made("film_episode", { season, number: 2, title: "Season Only" }); const fetch = String((await act(SLUG, credential, "fetch_add", { source: "https://files.example/an-invented-series-s02.mkv" })).body.fetch); await act(SLUG, owner, "fetch_claim", { id: fetch, machine: "m-invented" }); const landed = await act(SLUG, owner, "fetch_landed", { id: fetch, landed: [{ table: "film_episode", id: own }, { table: "film_episode", id: bySeason }] }); expect(landed.status, JSON.stringify(landed.body)).toBe(200); const files = await runInDurableObject(stub(SLUG), (_i, state) => [...new Store(state.storage.sql, () => new Date()).scan("fetch_file")].map((r) => r.data).filter((d) => d.fetch === fetch)); expect(files.map((f) => [f.episode, f.series]).sort()).toEqual([[own, series], [bySeason, series]].sort()); }); it("fails with one sentence, is tried again from scratch, and a cancel stops the Mac's next word", async () => { await act(SLUG, owner, "fetch_claim", { id: torrent, machine: "m-invented" }); const failed = await act(SLUG, owner, "fetch_failed", { id: torrent, error: "No peers found in 10 minutes\n at aria2 …" }); expect(failed.body).toMatchObject({ fetch: torrent, state: "failed" }); expect(await row(SLUG, torrent)).toMatchObject({ state: "failed", error: "No peers found in 10 minutes" }); expect((await act(SLUG, credential, "fetch_cancel", { fetch: torrent })).body.code, "a failed row is not on its way").toBe("not_active"); const retried = await act(SLUG, credential, "fetch_retry", { fetch: torrent }); expect(retried.body).toMatchObject({ fetch: torrent, state: "queued" }); const queued = await row(SLUG, torrent); expect(queued.state).toBe("queued"); for (const key of ["error", "machine", "started_on", "finished_on", "progress"]) expect(queued[key] ?? null, key).toBeNull(); expect((await act(SLUG, credential, "fetch_retry", { fetch: torrent })).body.code, "a queued row is not stopped").toBe("not_stopped"); await act(SLUG, owner, "fetch_claim", { id: torrent, machine: "m-invented" }); expect((await act(SLUG, credential, "fetch_cancel", { fetch: torrent })).body).toMatchObject({ state: "cancelled" }); const next = await act(SLUG, owner, "fetch_progress", { id: torrent, progress: 0.5 }); expect([next.status, next.body.code]).toEqual([409, "fetch_cancelled"]); expect((await act(SLUG, owner, "fetch_failed", { id: torrent, error: "killed" })).body.state, "a cancelled row stays cancelled").toBe("cancelled"); expect((await row(SLUG, torrent)).state).toBe("cancelled"); }); }); /** RULE (Cotton Fetch, 5 Nov 2026): a page fetched as video lands a clip with its page; the owner's film table, holding rows, grows them add-only. */ describe("the film table a fetch lands in", () => { it("grows kind clip, source_url and uploader on a film table holding rows, every held column and row kept", async () => { const SLUG = "fetch-film-keep"; const { credential } = await personalObject(SLUG, FILMS_OPEN); const kit = PERSONAL_TABLES.find((t) => t.id === "film")!; const columns = (kit.columns as Doc[]).filter((c) => c.key !== "source_url" && c.key !== "uploader").map((c) => (c.key === "kind" ? { ...c, choices: ["film", "series"], labels: { film: "Film", series: "Series" } } : c)); const before = { ...kit, columns, seal: null }; await runInDurableObject(stub(SLUG), (_i, state) => { const store = new Store(state.storage.sql, () => new Date()); store.replaceDefinitions("table", [...store.definitions("table").filter((t) => t.id !== "film"), before as Doc]); state.storage.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('film', 'f-held', ?, NULL, 1, 0, ?, ?)", JSON.stringify({ title: "An Invented Film", kind: "film" }), "2026-11-01T00:00:00.000Z", "2026-11-01T00:00:00.000Z"); state.storage.sql.exec("UPDATE meta SET value = 'an-older-kit' WHERE key = 'kit_version'"); }); const defs = await http<{ tables: Doc[] }>(SLUG, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` }); const film = defs.body.tables.find((t) => t.id === "film")!; const kind = (film.columns as Doc[]).find((c) => c.key === "kind")!; expect(kind.choices).toEqual(["film", "series", "clip"]); expect((kind.labels as Doc).clip).toBe("Clip"); const keys = (film.columns as Doc[]).map((c) => c.key); expect(keys.slice(0, columns.length), "every held column stays, in its place").toEqual(columns.map((c) => c.key)); expect(keys).toEqual(expect.arrayContaining(["source_url", "uploader"])); // The kit's film is sealed: the regrown table keeps its seal, so a clip's words go up only inside sealed_enc. const words = { title: "An Invented Short", source_url: "https://video.example/watch?v=invented01", uploader: "Invented Studio" }; expect((await act(SLUG, credential, "create", { table: "film", data: { kind: "clip", ...words } })).status).toBe(400); const clip = await act(SLUG, credential, "create", { table: "film", id: "f-clip", data: { kind: "clip", ...(await sealRow(new Uint8Array(32).fill(5), "film", "f-clip", 1, words)) } }); expect(clip.status, JSON.stringify(clip.body)).toBe(200); }); }); /** RULE (6 Nov 2026): a saved page's Fetch queues the page's link wearing the page's own title until the Mac's. */ describe("a page card's Fetch", () => { it("queues the link under the title the card said, and a link alone under one read off it", async () => { const { credential } = await personalObject("fetch-page-card", { open: [...FILMS_OPEN.open, "fetch"] }); const titled = await act("fetch-page-card", credential, "fetch_add", { source: PAGE, wants: "audio", title: " An Invented Short Film " }); expect(titled.status, JSON.stringify(titled.body)).toBe(200); expect(await row("fetch-page-card", String(titled.body.fetch))).toMatchObject({ source: PAGE, wants: "audio", source_kind: "page", state: "queued", title: "An Invented Short Film" }); const bare = await act("fetch-page-card", credential, "fetch_add", { source: PAGE, title: " " }); expect(await row("fetch-page-card", String(bare.body.fetch))).toMatchObject({ wants: "video", title: "video.example/watch" }); }); }); /** * RULE (e2e rulings R1, R2; 16 Nov 2026): a fetch row's link, * title and error are sealed. Queued from the phone's door it lands sealed at * arrival; the Mac's queue names its kind and what it wants, never its link * (the Mac's fetch run opens that as a device); a sealed row a * device writes says its kind beside its seal; a landed file is named by the * name the Mac gives, never by reading a sealed record. */ describe("the fetch queue under the seal", () => { it("lands a queued link sealed, names no link in the Mac's queue, and names a landed file by the Mac's name", async () => { const slug = "fetch-sealed"; const { credential, owner } = await personalObject(slug, { arrival: true }); const added = await act(slug, credential, "fetch_add", { source: PAGE, wants: "audio" }); expect(added.status, JSON.stringify(added.body)).toBe(200); const id = String(added.body.fetch); const held = await row(slug, id); expect(String(held.dek_enc)).toMatch(/^a1:/); expect(held).toMatchObject({ state: "queued", wants: "audio", source_kind: "page" }); expect(JSON.stringify(held)).not.toContain("invented01"); const pending = await http<{ rows: Doc[] }>(slug, "GET", "/v1/fetch/pending", undefined, { authorization: `Bearer ${owner}` }); expect(pending.body.rows).toEqual([{ id, source: "", wants: "audio", source_kind: "page", title: "" }]); const sealedRow = await act(slug, credential, "create", { table: "fetch", id: "f-device", data: { ...(await sealRow(new Uint8Array(32).fill(6), "fetch", "f-device", 1, { source: "magnet:?xt=urn:btih:invented", title: "An invented torrent" })) } }); expect(sealedRow.body.code, "a sealed row says its kind beside its seal").toBe("bad_args"); const withKind = await act(slug, credential, "create", { table: "fetch", id: "f-device", data: { source_kind: "torrent", ...(await sealRow(new Uint8Array(32).fill(6), "fetch", "f-device", 1, { source: "magnet:?xt=urn:btih:invented", title: "An invented torrent" })) } }); expect(withKind.status, JSON.stringify(withKind.body)).toBe(200); expect(await row(slug, "f-device")).toMatchObject({ state: "queued", wants: "files", source_kind: "torrent" }); expect((await act(slug, owner, "fetch_claim", { id, machine: "m-invented" })).status).toBe(200); const book = await act(slug, owner, "create", { table: "book", data: { title: "An Invented Short", author: "Invented Studio" } }); expect(book.status, JSON.stringify(book.body)).toBe(200); const bookId = (book.body.made as { id: string }).id; const landed = await act(slug, owner, "fetch_landed", { id, landed: [{ table: "book", id: bookId, name: "An Invented Short.epub", bytes: 2_430_774 }] }); expect(landed.status, JSON.stringify(landed.body)).toBe(200); const files = await runInDurableObject(stub(slug), (_i, state) => [...new Store(state.storage.sql, () => new Date()).scan("fetch_file")].map((r) => r.data)); expect(files).toHaveLength(1); expect(files[0]).toMatchObject({ fetch: id, kind: "book", book: bookId }); expect(String(files[0]!.dek_enc)).toMatch(/^a1:/); expect(JSON.stringify(files[0])).not.toContain("Invented Short"); }); }); /** * RULE (owner, 18 Nov 2026): a done download is fetched once * more so the films it landed come back keeping their originals. Its link is * untouched and its last run's figures cleared; a second fetch that fails, is * cancelled or is taken up by a restarted Mac never leaves a good download * looking broken: it is done again, what it landed still linked, the reason * kept apart. Its landing links each record once. */ describe("a done download fetched again", () => { const SLUG = "fetch-again"; let credential = ""; let owner = ""; let id = ""; const film = async (fid: string) => { const made = await act(SLUG, credential, "create", { table: "film", id: fid, data: { title: `An Invented Film ${fid}`, kind: "film" } }); expect(made.status, JSON.stringify(made.body)).toBe(200); }; const files = () => runInDurableObject(stub(SLUG), (_i, state) => [...new Store(state.storage.sql, () => new Date()).scan("fetch_file")].filter((r) => r.data.fetch === id).map((r) => r.data)); const again = async () => { const asked = await act(SLUG, owner, "fetch_again", { fetch: id }); expect(asked.status, JSON.stringify(asked.body)).toBe(200); expect(asked.body).toMatchObject({ fetch: id, state: "queued" }); }; it("queues only a done row, its link untouched, its figures cleared and the run marked as a second fetch", async () => { ({ credential, owner } = await personalObject(SLUG, { open: [...FILMS_OPEN.open, "fetch", "fetch_file"] })); await film("f-old"); id = String((await act(SLUG, credential, "fetch_add", { source: MAGNET })).body.fetch); const early = await act(SLUG, owner, "fetch_again", { fetch: id }); expect([early.status, early.body.code]).toEqual([409, "not_done"]); expect(String(early.body.message)).toContain("only a done one is fetched again"); await act(SLUG, owner, "fetch_claim", { id, machine: "m-invented" }); expect((await act(SLUG, owner, "fetch_landed", { id, landed: [{ table: "film", id: "f-old", name: "An Invented Film (1954).mkv", bytes: 7_000 }] })).status).toBe(200); expect((await act(SLUG, credential, "fetch_again", {})).body.code).toBe("bad_args"); await again(); const queued = await row(SLUG, id); expect(queued).toMatchObject({ state: "queued", source: MAGNET, source_kind: "torrent", landed_count: 1 }); expect(queued.again_on).toEqual(expect.any(String)); for (const key of ["progress", "bytes", "of_bytes", "machine", "started_on", "finished_on", "error", "again_outcome", "again_error"]) expect(queued[key] ?? null, key).toBeNull(); const pending = (await pendingOf(SLUG, owner)).find((r) => r.id === id)!; const linked = await files(); expect(linked).toHaveLength(1); expect(pending.again, "the Mac is told what the download landed before, by record").toEqual({ before: [{ file: expect.any(String), table: "film", id: "f-old" }] }); expect((await act(SLUG, owner, "fetch_again", { fetch: id })).body.code, "a queued row is not done").toBe("not_done"); }); it("links each record once on landing: a record it holds already gets no second fetch_file row, a new one does", async () => { await act(SLUG, owner, "fetch_claim", { id, machine: "m-invented" }); const same = await act(SLUG, owner, "fetch_landed", { id, landed: [{ table: "film", id: "f-old", name: "An Invented Film (1954).mkv", bytes: 7_000 }] }); expect(same.body).toMatchObject({ state: "done", landed: 1 }); expect(await files()).toHaveLength(1); expect(await row(SLUG, id)).toMatchObject({ state: "done", again_outcome: "landed", landed_count: 1, bytes: 7_000, progress: 100 }); await film("f-new"); await again(); await act(SLUG, owner, "fetch_claim", { id, machine: "m-invented" }); const grown = await act(SLUG, owner, "fetch_landed", { id, landed: [{ table: "film", id: "f-old", bytes: 7_000 }, { table: "film", id: "f-new", name: "Another Invented Film.mkv", bytes: 3_000 }] }); expect(grown.body).toMatchObject({ state: "done", landed: 2 }); expect((await files()).map((f) => f.film).sort()).toEqual(["f-new", "f-old"]); expect(await row(SLUG, id)).toMatchObject({ again_outcome: "landed", landed_count: 2, bytes: 10_000 }); }); it("is done again when the second fetch fails, the reason kept apart and the Mac's next word refused", async () => { await again(); await act(SLUG, owner, "fetch_claim", { id, machine: "m-invented" }); const failed = await act(SLUG, owner, "fetch_failed", { id, error: "No peers found in 10 minutes\n at aria2 …" }); expect(failed.body).toMatchObject({ fetch: id, state: "done" }); const done = await row(SLUG, id); expect(done).toMatchObject({ state: "done", again_outcome: "failed", again_error: "No peers found in 10 minutes", progress: 100, landed_count: 2 }); expect(done.error ?? null, "a good download does not look broken").toBeNull(); expect(await files()).toHaveLength(2); expect((await act(SLUG, owner, "fetch_progress", { id, progress: 0.5 })).body.code).toBe("fetch_cancelled"); expect((await act(SLUG, owner, "fetch_failed", { id, error: "again" })).body.state).toBe("done"); expect((await row(SLUG, id)).again_error).toBe("No peers found in 10 minutes"); expect((await act(SLUG, credential, "fetch_retry", { fetch: id })).body.code, "a done row is not tried again: it is fetched again").toBe("not_stopped"); }); it("is done again when the owner cancels the second fetch, waiting or fetching", async () => { await again(); expect((await act(SLUG, credential, "fetch_cancel", { fetch: id })).body).toMatchObject({ fetch: id, state: "done" }); expect(await row(SLUG, id)).toMatchObject({ state: "done", again_outcome: "cancelled" }); expect((await pendingOf(SLUG, owner)).map((r) => r.id)).not.toContain(id); await again(); await act(SLUG, owner, "fetch_claim", { id, machine: "m-invented" }); expect((await act(SLUG, credential, "fetch_cancel", { fetch: id })).body.state).toBe("done"); const next = await act(SLUG, owner, "fetch_progress", { id, progress: 0.5 }); expect([next.status, next.body.code], "the Mac stops").toEqual([409, "fetch_cancelled"]); expect((await act(SLUG, owner, "fetch_landed", { id, landed: [] })).body.code, "nor lands it").toBe("fetch_cancelled"); expect((await act(SLUG, owner, "fetch_failed", { id, error: "killed" })).body.state).toBe("done"); const done = await row(SLUG, id); expect(done).toMatchObject({ state: "done", again_outcome: "cancelled", landed_count: 2 }); expect(done.error ?? null).toBeNull(); expect(await files()).toHaveLength(2); }); it("is taken up again by a Mac restarted mid-run, still a second fetch, and done again whether it fails or lands", async () => { await again(); await act(SLUG, owner, "fetch_claim", { id, machine: "m-invented" }); await act(SLUG, owner, "fetch_progress", { id, progress: 0.3, landing: false }); const held = await http<{ held: Doc[] }>(SLUG, "GET", "/v1/fetch/pending?machine=m-invented", undefined, { authorization: `Bearer ${owner}` }); const mine = held.body.held.find((r) => r.id === id)!; expect(mine.again, "the restarted Mac still knows what it landed before").toEqual({ before: expect.arrayContaining([expect.objectContaining({ table: "film", id: "f-old" }), expect.objectContaining({ table: "film", id: "f-new" })]) }); expect((await act(SLUG, owner, "fetch_failed", { id, error: "fetch:run stopped: the Mac restarted and the torrent is gone" })).body.state).toBe("done"); expect(await row(SLUG, id)).toMatchObject({ state: "done", again_outcome: "failed", landed_count: 2 }); await again(); await act(SLUG, owner, "fetch_claim", { id, machine: "m-invented" }); await act(SLUG, owner, "fetch_progress", { id, landing: true }); expect((await act(SLUG, owner, "fetch_landed", { id, landed: [{ table: "film", id: "f-new", bytes: 3_000 }] })).body).toMatchObject({ state: "done", landed: 1 }); expect(await row(SLUG, id)).toMatchObject({ again_outcome: "landed", landed_count: 1 }); expect(await files()).toHaveLength(2); }); }); /** RULE (e2e rulings R1): a sealed download is fetched again by its clear columns alone; why it failed again stays sealed, like its error. */ describe("a sealed download fetched again", () => { it("queues it without opening its link, and keeps the second fetch's reason inside the seal", async () => { const slug = "fetch-again-sealed"; const { credential, owner } = await personalObject(slug, { arrival: true }); const id = String((await act(slug, credential, "fetch_add", { source: PAGE })).body.fetch); await act(slug, owner, "fetch_claim", { id, machine: "m-invented" }); const book = await act(slug, owner, "create", { table: "book", data: { title: "An Invented Short", author: "Invented Studio" } }); const bookId = (book.body.made as { id: string }).id; expect((await act(slug, owner, "fetch_landed", { id, landed: [{ table: "book", id: bookId, name: "An Invented Short.epub" }] })).status).toBe(200); const asked = await act(slug, owner, "fetch_again", { fetch: id }); expect(asked.status, JSON.stringify(asked.body)).toBe(200); const pending = await http<{ rows: Doc[] }>(slug, "GET", "/v1/fetch/pending", undefined, { authorization: `Bearer ${owner}` }); expect(pending.body.rows).toEqual([{ id, source: "", wants: "video", source_kind: "page", title: "", again: { before: [{ file: expect.any(String), table: "book", id: bookId }] } }]); await act(slug, owner, "fetch_claim", { id, machine: "m-invented" }); expect((await act(slug, owner, "fetch_failed", { id, error: "ERROR: [invented] invented01: This video is private" })).body.state).toBe("done"); const held = await row(slug, id); expect(held).toMatchObject({ state: "done", again_outcome: "failed" }); expect(JSON.stringify(held)).not.toContain("private"); }); }); /** RULE: `pnpm fetch:again` reads which done downloads landed films keeping no original, by clear columns alone: ids and counts, never a link or a title. */ describe("the downloads to fetch again", () => { it("names done downloads never fetched again whose films stream without an original, and counts the running, the dead, the tried and the films no download accounts for", async () => { const slug = "fetch-again-plan"; const { credential, owner } = await personalObject(slug, { open: [...FILMS_OPEN.open, "fetch", "fetch_file"] }); const film = async (id: string, data: Doc) => expect((await act(slug, credential, "create", { table: "film", id, data: { title: `An Invented Film ${id}`, kind: "film", ...data } })).status).toBe(200); await film("f-bare", { file: `${DATABASE_ID}/films/f-bare/master.m3u8` }); await film("f-kept", { file: `${DATABASE_ID}/films/f-kept/master.m3u8`, original: `${DATABASE_ID}/films/f-kept/original/${"a".repeat(16)}/index.json` }); await film("f-poster", {}); await film("f-dead", { file: `${DATABASE_ID}/films/f-dead/master.m3u8` }); await film("f-run", { file: `${DATABASE_ID}/films/f-run/master.m3u8` }); await film("f-hand", { file: `${DATABASE_ID}/films/f-hand/master.m3u8` }); const done = async (landed: string[]) => { const id = String((await act(slug, credential, "fetch_add", { source: `${PAGE}-${landed.join("-") || "none"}` })).body.fetch); await act(slug, owner, "fetch_claim", { id, machine: "m-invented" }); expect((await act(slug, owner, "fetch_landed", { id, landed: landed.map((f) => ({ table: "film", id: f })) })).status).toBe(200); return id; }; const due = await done(["f-bare", "f-kept"]); await done(["f-kept"]); await done(["f-poster"]); const dead = await done(["f-dead"]); await act(slug, owner, "fetch_again", { fetch: dead }); await act(slug, owner, "fetch_claim", { id: dead, machine: "m-invented" }); await act(slug, owner, "fetch_failed", { id: dead, error: "No peers found in 10 minutes" }); const running = await done(["f-run"]); await act(slug, owner, "fetch_again", { fetch: running }); const plan = await http(slug, "GET", "/v1/fetch/again", undefined, { authorization: `Bearer ${owner}` }); expect(plan.status, JSON.stringify(plan.body)).toBe(200); expect(plan.body).toEqual({ fetch: [due], running: 1, dead: 1, tried: 0, unaccounted: 1 }); expect((await http(slug, "GET", "/v1/fetch/again")).status, "the owner's").toBe(403); }); }); /** RULE (owner, 18 Nov 2026): a landing download says where it is on its row, and a finished one says nothing stale. */ describe("a download's stage", () => { it("is kept while it lands, cleared when it lands, and taken again for a landed film's smaller copies", async () => { const SLUG = "fetch-stage"; const { credential, owner } = await personalObject(SLUG, { open: [...FILMS_OPEN.open, "fetch", "fetch_file"] }); const added = await act(SLUG, credential, "fetch_add", { source: FILE }); const id = String((added.body.made as { id: string }).id); expect((await act(SLUG, owner, "fetch_stage", { id, stage: "sending", done: 1, of: 2 })).status).toBe(409); await act(SLUG, owner, "fetch_claim", { id, machine: "m-invented" }); expect((await act(SLUG, owner, "fetch_stage", { id, stage: "guessing" })).status).toBe(400); expect((await act(SLUG, owner, "fetch_stage", { id, stage: "sending", done: 2310, of: 3974, line: "Sending · 2,310 of 3,974 files" })).status).toBe(200); const landing = await row(SLUG, id); expect(landing).toMatchObject({ stage: "sending", stage_done: 2310, stage_of: 3974, stage_line: "Sending · 2,310 of 3,974 files" }); expect(landing.stage_at).toBeTruthy(); expect((await act(SLUG, owner, "fetch_landed", { id, landed: [] })).status).toBe(200); expect((await row(SLUG, id)).stage ?? null).toBeNull(); expect((await act(SLUG, owner, "fetch_stage", { id, stage: "smaller_copies", done: 60, of: 600, line: "Making smaller copies · 1 of 10 min" })).status).toBe(200); expect(await row(SLUG, id)).toMatchObject({ state: "done", stage: "smaller_copies" }); expect((await act(SLUG, owner, "fetch_stage", { id })).status).toBe(200); expect((await row(SLUG, id)).stage_line ?? null).toBeNull(); }); });