import { writeFile } from "node:fs/promises"; import { test, expect } from "@playwright/test"; import { channelStage, generateReport, pathExists, readJson, resetData, resolvePath, writeSettings, testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; // "Work through speakers" (lane/speakers-run): the Speakers lane's one // control, the voice fingerprints a sidecar must carry before its audio may go, // clean-after-capture, and the readout on the lane card, the Cleanup stage and // /cleanup. The engine is the fake DIARIZE_BIN (e2e/fixtures/bin/ // fake-diarize.mjs): voiceprints by default, `--voiceprints-only` as the // wrapper's voiceprint step. const SLUG = "test-transcribe"; const AUTH = { authorization: "Bearer test-worker-token" }; const SLOW = 120_000; function dataRel(videoId: string, file: string): string { return `${testPaths().transcriptsDir}/channels/${SLUG}/data/${videoId}/${file}`; } // The channel's availability verdict (availability-verdict.json beside its // config) — what the Quick check writes after a listing, and the only thing // clean after capture trusts: `ids` named by a listing at `checkedAt`, and the // last check it asked for. async function seedVerdict(v: { checkedAt: string | null; ids: string[]; requestedAt?: string }): Promise { await writeFile( resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/availability-verdict.json`), JSON.stringify({ version: 1, ...v }) + "\n", ); } async function seedTranscript(videoId: string): Promise { await writeFile(resolvePath(dataRel(videoId, "transcript.json")), '{"transcription":[{"text":"hi"}]}\n'); } // A FRESH sidecar (the identity the settings below produce) from before // voiceprints existed. async function seedPlainDiarization(videoId: string): Promise { await writeFile( resolvePath(dataRel(videoId, "diarization.json")), JSON.stringify({ videoId, generatedAt: "2026-08-07T00:00:00.000Z", audioSeconds: 10, durationMs: 1000, speakers: 1, turns: [{ start: 0, end: 10, speaker: 0 }], engine: { engine: "fake-diarize", segmentationModel: "null", embeddingModel: "null", threshold: 0.5 }, }) + "\n", ); } function settings(over: { held?: boolean; narrowed?: boolean; diarization?: Record } = {}) { return { adminTitle: "Test Admin", maxTranscriptPageBytes: 8388608, sleepBetweenDownloadsSeconds: 0, minFreeDiskGB: 0, verifyAvailabilityBeforeClean: false, syncScheduler: { fullSweepIntervalMinutes: 0 }, diarization: { enabled: true, inlineAfterTranscribe: false, threshold: 0.5, threads: 1, python: "python3", segModel: "/dev/null", embModel: "/dev/null", concurrency: 1, ...over.diarization, }, backfill: { concurrency: 1, allowRedownload: false }, autoQueue: { backfill: { held: over.held ?? false, ...(over.narrowed === false ? {} : { operations: ["diarization"] }) } }, }; } type Lane = { enabled?: boolean; held?: boolean }; async function lane(): Promise { const s = await readJson<{ autoQueue?: { backfill?: Lane } }>(testPaths().settingsFile).catch( () => ({}) as { autoQueue?: { backfill?: Lane } }, ); return s.autoQueue?.backfill ?? {}; } test.afterEach(async ({ request }) => { // Never leave an armed lane for the next spec. await request.post(`${baseUrl}/api/ops/lane`, { headers: AUTH, data: { lane: "backfill", enabled: false } }); }); test("a paused Speakers lane: the stage says Run speaker work waits for it, and offers the lane's one control", async ({ page }) => { test.setTimeout(SLOW); await resetData("one-transcribe-channel-with-audio"); await writeSettings(settings({ held: true })); await seedTranscript("vidA"); await generateReport(page, SLUG); await page.goto(channelStage(SLUG, "speakers")); const paused = page.getByLabel("speakers lane paused"); await expect(paused).toContainText("The Speakers lane is paused, so Run speaker work waits for it.", { timeout: 30_000 }); const work = paused.getByRole("button", { name: "work through speakers" }); await expect(work).toBeEnabled({ timeout: 30_000 }); await work.click(); await expect.poll(async () => ({ held: (await lane()).held, armed: (await lane()).enabled }), { timeout: 30_000 }).toEqual({ held: false, armed: true }); }); test("a sidecar without voice fingerprints keeps its audio until Diarize speakers adds them from its own turns", async ({ page }) => { test.setTimeout(SLOW); await resetData("one-transcribe-channel-with-audio"); await writeSettings(settings()); await seedTranscript("vidA"); await seedPlainDiarization("vidA"); await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); await generateReport(page, SLUG); await page.goto(channelStage(SLUG, "cleanup")); await page.getByRole("button", { name: "Clean audio", exact: true }).click(); await expect(page.getByLabel("Clean audio output")).toContainText("awaiting voice fingerprint", { timeout: 30_000 }); expect(await pathExists(dataRel("vidA", "audio.m4a"))).toBe(true); await page.getByRole("button", { name: "Diarize speakers", exact: true }).click(); await expect .poll( async () => { const r = await readJson<{ generatedAt: string; voiceprints?: unknown[] }>(dataRel("vidA", "diarization.json")).catch(() => null); return r ? { generatedAt: r.generatedAt, voiceprints: r.voiceprints?.length ?? 0 } : null; }, { timeout: 60_000 }, ) // The same turns' sidecar — generatedAt kept — now with its fingerprint. .toEqual({ generatedAt: "2026-08-07T00:00:00.000Z", voiceprints: 1 }); await page.goto(channelStage(SLUG, "cleanup")); await page.getByRole("button", { name: "Clean audio", exact: true }).click(); await expect(page.getByLabel("Clean audio output")).toContainText("Cleaned 1 audio file", { timeout: 30_000 }); expect(await pathExists(dataRel("vidA", "audio.m4a"))).toBe(false); }); test("clean after capture: Run speaker work removes a captured video's audio at once, and the readout counts it", async ({ page, request }) => { test.setTimeout(SLOW); await resetData("one-transcribe-channel-with-audio"); await writeSettings(settings({ diarization: { cleanAfterCapture: true } })); await seedTranscript("vidA"); // The channel was listed an hour ago by its Quick check, and the listing named // vidA: the one verdict clean after capture deletes on. await seedVerdict({ checkedAt: new Date(Date.now() - 3_600_000).toISOString(), ids: ["vidA", "vidB", "vidC"] }); await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); await generateReport(page, SLUG); const before = await request.get(`${baseUrl}/api/ops/speakers`, { headers: AUTH }); expect(before.status()).toBe(200); const freedBefore = ((await before.json()) as { freedVideos: number }).freedVideos; await page.goto(channelStage(SLUG, "speakers")); await page.getByRole("button", { name: "Run speaker work", exact: true }).click(); await expect.poll(async () => pathExists(dataRel("vidA", "diarization.json")), { timeout: 60_000 }).toBe(true); await expect.poll(async () => pathExists(dataRel("vidA", "audio.m4a")), { timeout: 60_000 }).toBe(false); await expect(page.getByLabel("Run speaker work output")).toContainText("after capture", { timeout: 30_000 }); const after = await request.get(`${baseUrl}/api/ops/speakers`, { headers: AUTH }); const body = (await after.json()) as { freedVideos: number; line: string; lane: { cleanAfterCapture: boolean } }; expect(body.freedVideos).toBe(freedBefore + 1); expect(body.lane.cleanAfterCapture).toBe(true); expect(body.line).toMatch(/^waiting: .* · freed this run: .* · /); }); test("clean after capture with no fresh listing: the captured video keeps its audio, awaiting an availability check", async ({ page }) => { test.setTimeout(SLOW); await resetData("one-transcribe-channel-with-audio"); await writeSettings(settings({ diarization: { cleanAfterCapture: true } })); await seedTranscript("vidA"); // The last listing is two days old (older than cleanVerdictMaxAgeHours, 24), // and a check was asked for an hour ago — so nothing new is requested here, // and nothing may be deleted on the old listing. await seedVerdict({ checkedAt: new Date(Date.now() - 48 * 3_600_000).toISOString(), ids: ["vidA", "vidB", "vidC"], requestedAt: new Date(Date.now() - 3_600_000).toISOString(), }); await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); await generateReport(page, SLUG); await page.goto(channelStage(SLUG, "speakers")); await page.getByRole("button", { name: "Run speaker work", exact: true }).click(); await expect.poll(async () => pathExists(dataRel("vidA", "diarization.json")), { timeout: 60_000 }).toBe(true); const output = page.getByLabel("Run speaker work output"); await expect(output).toContainText("awaiting an availability check", { timeout: 60_000 }); await expect(output).toContainText("a check was requested at"); expect(await pathExists(dataRel("vidA", "audio.m4a"))).toBe(true); }); test("the readout: the Cleanup stage names the audio held for speakers; /cleanup and the lane card print the line", async ({ page }) => { test.setTimeout(SLOW); await resetData("one-transcribe-channel-with-audio"); // Held: nothing is dispatched, and the paused lane is what /cleanup's gate 4 // must call a hold that will not clear on its own. await writeSettings(settings({ held: true })); await seedTranscript("vidA"); await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); await generateReport(page, SLUG); await page.goto(`/channels/${SLUG}`); await expect(page.getByText(/held for speakers \(1 video\)/).first()).toBeVisible({ timeout: 30_000 }); await page.goto("/cleanup"); const readout = page.getByLabel("speakers readout"); await expect(readout).toContainText("waiting:", { timeout: 30_000 }); await expect(readout).toContainText("in 1 video"); await expect(readout.getByRole("button", { name: "work through speakers" })).toBeVisible(); await expect(page.getByLabel("audio hold sieve").locator('li[data-gate="4"]')).toContainText("will not clear on its own"); await page.goto("/"); await expect(page.getByLabel("speakers readout")).toContainText("waiting:", { timeout: 30_000 }); }); test("Work through speakers refuses an un-narrowed lane, in one sentence naming the command", async ({ page }) => { test.setTimeout(SLOW); await resetData("one-transcribe-channel-with-audio"); await writeSettings(settings({ held: true, narrowed: false })); await seedTranscript("vidA"); await generateReport(page, SLUG); await page.goto(channelStage(SLUG, "speakers")); const paused = page.getByLabel("speakers lane paused"); await paused.getByRole("button", { name: "work through speakers" }).click(); await expect(page.getByText(/is not narrowed to speaker diarization/).first()).toBeVisible({ timeout: 30_000 }); await expect(page.getByText(/"operations":\["diarization"\]/).first()).toBeVisible(); expect((await lane()).held).toBe(true); expect((await lane()).enabled ?? false).toBe(false); });