import { test, expect, type APIRequestContext } from "@playwright/test"; import { spawnSync } from "node:child_process"; import { createServer, type Server } from "node:http"; import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import { dirname, extname, join, normalize, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { startFakeOllama, type FakeOllama } from "../../common/testing/llm/fakeOllama.mjs"; import { writeDraftCorpus } from "../../common/testing/draft/corpus.mjs"; import { baseUrl } from "./baseUrl"; import { resetData, testPaths } from "./helpers"; // A PUBLIC ARCHIVE IS A FIRST-CLASS SOURCE (demo epic D1, item 7): a fresh // editor with NO channels of its own, a STUB ARCHIVE (the synthetic draft // corpus served over loopback HTTP as a published site serves it — an older // corpus.json, no per-channel platform, so the resolver's record fallback is // what names the platform), and nothing fetched from the network: // // connect /sites → Connected archives: Read it (the probe), Connect // sweep a question over the archive on the local model (the fake ollama, // the recorded pipeline run): its links on the STUB's origin // project umtool's chain, step by step as its job runs them (current, // windows, manifest): the editor registers the cited channel // REMOTE-ONLY and fetches its windows (the fake yt-dlp); the // project's QR origin is the stub // link a citation's link opens on the stub at its second // // The stub's own page at `/` says which moment it was asked for. const AUTH = { authorization: "Bearer test-worker-token" }; const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", ".."); const RUNS = join(REPO, "common", "testing", "draft", "runs"); const CHAIN_RUN = join(REPO, "umtool", "lib", "report", "chain-run.mjs"); const TYPES: Record = { ".json": "application/json", ".html": "text/html" }; async function startStubArchive(dir: string): Promise<{ url: string; asked: string[]; close: () => Promise }> { const asked: string[] = []; const server: Server = createServer(async (req, res) => { const u = new URL(req.url ?? "/", "http://stub"); asked.push(u.pathname); if (u.pathname === "/" || u.pathname === "/index.html") { // The archive's viewer, as far as a link needs it: which moment. const v = u.searchParams.get("v") ?? ""; const t = u.searchParams.get("t") ?? ""; res.writeHead(200, { "content-type": "text/html" }); res.end(`stub archive

v=${v} t=${t}

`); return; } const file = normalize(join(dir, decodeURIComponent(u.pathname))); if (!file.startsWith(dir)) { res.writeHead(403).end(); return; } try { const body = await readFile(file); res.writeHead(200, { "content-type": TYPES[extname(file)] ?? "application/octet-stream", "access-control-allow-origin": "*" }); res.end(body); } catch { res.writeHead(404).end("not found"); } }); await new Promise((r) => server.listen(0, "127.0.0.1", () => r())); const port = (server.address() as { port: number }).port; return { url: `http://127.0.0.1:${port}`, asked, close: () => new Promise((r) => server.close(() => r())) }; } async function jobUntil(request: APIRequestContext, id: string, ms = 120_000) { const t0 = Date.now(); let last = ""; while (Date.now() - t0 < ms) { const res = await request.get(`${baseUrl}/api/ops/job/${id}?tail=60`, { headers: AUTH }); const body = (await res.json()) as { job?: { status?: string }; status?: string; tail?: string[] }; last = body.job?.status ?? body.status ?? ""; if (["done", "failed", "cancelled"].includes(last)) return body; await new Promise((r) => setTimeout(r, 400)); } throw new Error(`job ${id} is still ${last}`); } test.describe.configure({ mode: "serial" }); let stub: Awaited>; let ol: FakeOllama; let scratch: string; test.beforeAll(async () => { scratch = await mkdtemp(join(os.tmpdir(), "e2e-remote-archive-")); const dir = join(scratch, "archive"); await writeDraftCorpus(dir); // A build of its own, so no other run's cached copy answers for it. const corpus = JSON.parse(await readFile(join(dir, "corpus.json"), "utf8")); await writeFile(join(dir, "corpus.json"), JSON.stringify({ ...corpus, spec: 5, generatedAt: new Date().toISOString() })); // A record's page is a video platform's (an archive's own URL is refused // otherwise): YouTube's watch pages, which the fake yt-dlp answers. for (const c of corpus.channels as { slug: string }[]) { const page = join(dir, "transcripts", c.slug, "page-0000.json"); const records = JSON.parse(await readFile(page, "utf8")) as { id: string; webpageUrl?: string }[]; await writeFile(page, JSON.stringify(records.map((r) => ({ ...r, webpageUrl: `https://www.youtube.com/watch?v=${r.id}` })))); } stub = await startStubArchive(dir); ol = await startFakeOllama(); }); test.afterAll(async () => { await stub?.close(); await ol?.close(); await rm(scratch, { recursive: true, force: true }); }); test("a fresh editor with no channels: connect the stub archive, sweep it on the local model, fetch the cut's windows as a remote-only channel, open a link at its second", async ({ page, request }) => { test.setTimeout(300_000); await resetData(null); const paths = testPaths(); expect(await readdir(join(paths.transcriptsDir, "channels"))).toEqual([]); const settings = JSON.parse(await readFile(paths.settingsFile, "utf8")); const projects = join(scratch, "projects"); await writeFile(paths.settingsFile, JSON.stringify({ ...settings, minFreeDiskGB: 0, generation: { ...(settings.generation ?? {}), ollamaUrl: ol.url, projectsRoot: projects } }, null, 2)); await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); // ─── connect, in the UI ─── await page.goto(`${baseUrl}/sites`); const panel = page.locator("[data-connected-archives]"); await expect(panel.getByText("No archive connected.")).toBeVisible(); await panel.getByLabel("archive origin").fill(`${stub.url}/`); await panel.getByRole("button", { name: "Read it" }).click(); const probe = panel.locator(`[data-archive-probe="${stub.url}"]`); await expect(probe).toContainText("Synth Kitchen"); await expect(probe).toContainText(/2 channels · \d+ videos/); await panel.getByRole("button", { name: "Connect" }).click(); await expect(panel.getByRole("list", { name: "connected archives" }).locator("li")).toHaveCount(1); const listed = await (await request.get(`${baseUrl}/api/ops/archives`, { headers: AUTH })).json(); expect(listed.archives).toEqual([expect.objectContaining({ origin: stub.url })]); // ─── a question, swept over the archive on the local model ─── const run = JSON.parse(await readFile(join(RUNS, "sweep-pipeline.json"), "utf8")); for (const turn of run.turns) ol.push(turn); const draft = await request.post(`${baseUrl}/api/ops/report-draft`, { headers: AUTH, data: { task: "sweep", article: "remote-e2e", model: run.model, question: run.question, channels: run.channels, source: `remote:${stub.url}` }, }); const started = (await draft.json()) as { ok?: boolean; error?: string; jobId?: string }; expect(draft.status(), started.error).toBe(200); const job = await jobUntil(request, started.jobId!); expect(job.job?.status ?? job.status, (job.tail ?? []).join("\n")).toBe("done"); const itDir = join(paths.transcriptsDir, "reports", "remote-e2e", "iterations", "1"); const iteration = JSON.parse(await readFile(join(itDir, "iteration.json"), "utf8")); expect(iteration.scope.source).toBe(`remote:${stub.url}`); const report = JSON.parse(await readFile(join(itDir, "report.json"), "utf8")); const cited = Object.values(report.citations as Record).filter((c) => c.kind === "video"); expect(cited.length).toBeGreaterThan(0); const sweep = await readFile(join(itDir, "sweep.md"), "utf8"); const links = [...sweep.matchAll(/\((https?:\/\/[^)\s]+\?v=[^)\s]+)\)/g)].map((m) => m[1]); expect(links.length).toBeGreaterThan(0); for (const l of links) expect(l.startsWith(`${stub.url}/?v=`), l).toBe(true); // Nothing was asked of the editor's own corpus (it has none), and the stub was read. expect(stub.asked).toContain("/corpus.json"); expect(stub.asked.some((p) => p.startsWith("/transcripts/synth-kitchen/"))).toBe(true); // ─── the project: the chain's steps as its job runs them ─── const env: Record = { ...(process.env as Record), TRANSCRIPTS_DIR: paths.transcriptsDir, SETTINGS_FILE: paths.settingsFile, EXPORT_PUBLIC_DIR: join(scratch, "public"), EXPORT_INDEX_DIR: join(scratch, ".export-index"), EXPORT_BUILDS_DIR: join(scratch, ".export-builds"), ARCHIVE_CACHE_DIR: join(scratch, ".archive-cache"), ARCHILYZER_EDITOR_URL: baseUrl, WORKER_TOKEN: "test-worker-token", }; delete env.ARTICLES_DIR; const step = (name: string) => { const r = spawnSync(process.execPath, ["--import", "tsx", CHAIN_RUN, "step", "remote-e2e", "1", name, "--projects-root", projects], { cwd: REPO, env: env as NodeJS.ProcessEnv, encoding: "utf8", timeout: 180_000, }); return { code: r.status, out: `${r.stdout}\n${r.stderr}` }; }; for (const name of ["current", "windows", "manifest"]) { const r = step(name); expect(r.code, `${name}: ${r.out}`).toBe(0); } // The cited channel is registered REMOTE-ONLY: config only, its platform from the archive's record. const config = JSON.parse(await readFile(join(paths.transcriptsDir, "channels", "synth-kitchen", "config.json"), "utf8")); expect(config).toMatchObject({ remoteOnly: true, remoteArchive: stub.url, platform: "youtube", downloadMode: "manual" }); expect(config.url).toBeUndefined(); // Every cited window is on disk under it. for (const c of cited) { const clips = await readdir(join(paths.transcriptsDir, "channels", c.channel, "data", c.id, "clips")).catch(() => [] as string[]); expect(clips.filter((f) => f.endsWith(".mp4")).length, `${c.channel}/${c.id}`).toBeGreaterThan(0); } const manifest = JSON.parse(await readFile(join(projects, "remote-e2e", "i1", "video.manifest.json"), "utf8")); expect(manifest.provenance.siteOrigin).toBe(stub.url); // The channel list says what it is. await page.goto(`${baseUrl}/channels`); await expect(page.getByRole("note", { name: "remote-only channel synth-kitchen" })).toBeVisible(); // ─── a citation's link opens on the stub at its second ─── const link = links[0]; const at = new URL(link); const t = at.searchParams.get("t"); expect(t, link).not.toBeNull(); const [channel, id] = (at.searchParams.get("v") ?? "").split("/"); // The second is the cited moment's: a citation of that recording starts there. expect(cited.some((c) => c.channel === channel && c.id === id && Math.floor(c.start) === Number(t)), `${link} against ${JSON.stringify(cited)}`).toBe(true); await page.goto(link); await expect(page.locator("#moment")).toHaveAttribute("data-t", t!); await expect(page.locator("#moment")).toHaveAttribute("data-v", `${channel}/${id}`); });