Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 79471fb4e705aa6648924f02c368bd032b4d613e
parent 1289b8770348d72e547016c6ef179e8e6e00dab2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 21 Oct 2026 18:05:00 -0400

editor: the dashboard's cookie refresh banner (Recheck, Dismiss, Re-run stopped jobs), the cookieAlerts view, ops services/recheck-service, doctor's service cookies

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/bin/doctor.ts | 29+++++++++++++++++++++++++++++
Mcommon/views/names.ts | 2++
Aeditor/app/api/ops/dismiss-service/route.ts | 17+++++++++++++++++
Aeditor/app/api/ops/recheck-service/route.ts | 21+++++++++++++++++++++
Aeditor/app/api/ops/rerun-service-jobs/route.ts | 19+++++++++++++++++++
Aeditor/app/api/ops/services/route.ts | 15+++++++++++++++
Meditor/app/api/view/[name]/route.test.ts | 6+++++-
Meditor/app/api/view/views.ts | 6++++++
Meditor/app/channels/[slug]/components/SocialChannelPanel.tsx | 10++++++++++
Meditor/app/channels/[slug]/socialActions.ts | 7+++++++
Aeditor/app/components/dashboard/CookieAlertsPanel.tsx | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/components/dashboard/DashboardCockpit.tsx | 17+++++++++++++++++
Aeditor/app/lib/cookieAlerts.ts | 40++++++++++++++++++++++++++++++++++++++++
Aeditor/app/operations/serviceCookiesActions.ts | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/page.tsx | 5++++-
Meditor/app/settings/archiveSessionActions.ts | 7+++++++
Aeditor/e2e/cookie-alerts.spec.ts | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/fixtures/bin/fake-ytdlp.mjs | 34++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 27++++++++++++++++++++++++++-
19 files changed, 639 insertions(+), 3 deletions(-)

diff --git a/common/bin/doctor.ts b/common/bin/doctor.ts @@ -338,6 +338,35 @@ export async function collectDoctorReport(deps: DoctorDeps): Promise<DoctorRepor add(DP, "platforms", "info", "no auto-queue state yet — nothing has been rate-limited"); } + // ── service cookies ────────────────────────────────────────────────────── + // The cookie refresh alerts (lib/serviceCookies.ts): a service whose cookies + // look stale — Rumble's embed 403s on two videos in a row, YouTube's bot + // check, Odysee's Cloudflare page, a forum's browser check, archive.today's + // check page. A warning with the fix; read-only (the reader never writes). + const SC = "service cookies"; + if (paths.transcriptsDir && existsSync(paths.transcriptsDir)) { + const { readServiceCookieState } = await import("../lib/serviceCookies-server"); + const { buildServiceCookieAlerts } = await import("../lib/serviceCookies"); + const nowMs = (deps.now ?? new Date()).getTime(); + const view = buildServiceCookieAlerts(await readServiceCookieState(paths), { + now: nowMs, + browser: settings?.cookiesFromBrowser || undefined, + }); + for (const a of view.alerts) { + if (a.state === "stale") { + add(SC, a.service, "warn", `cookies look stale — ${a.detail}. Fix: ${a.fix}, then Recheck on the dashboard (or \`pnpm ops recheck-service\`)`); + } else { + add(SC, a.service, "info", `${a.headline} (cleared ${stamp(new Date(a.clearedAt ?? a.lastSeen))}, ${a.clearedBy ?? "clean"})`); + } + } + for (const p of view.pending) { + add(SC, p.service, "info", `one ${p.kind} seen (${p.videos.join(", ") || "no video named"}) — a second video refused in a row raises the alert`); + } + if (view.alerts.every((a) => a.state !== "stale")) { + add(SC, "services", "ok", "no service's cookies look stale"); + } + } + // ── settings ───────────────────────────────────────────────────────────── const S = "settings"; const settingsText = readOrNull(paths.settingsFile); diff --git a/common/views/names.ts b/common/views/names.ts @@ -26,6 +26,7 @@ export const VIEW_NAMES = [ "widgetSync", "widgetActionable", "cleanable", + "cookieAlerts", ] as const; export type ViewName = (typeof VIEW_NAMES)[number]; @@ -52,4 +53,5 @@ export const VIEW_CONTRACT: Record<ViewName, "observe" | "construct"> = { widgetSync: "construct", widgetActionable: "construct", cleanable: "construct", + cookieAlerts: "construct", }; diff --git a/editor/app/api/ops/dismiss-service/route.ts b/editor/app/api/ops/dismiss-service/route.ts @@ -0,0 +1,17 @@ +import { NextResponse } from "next/server"; +import { dismissServiceCookiesAction } from "../../../operations/serviceCookiesActions"; +import { ops, opsFail, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { service } +// +// The cookie refresh banner's Dismiss: the alert is cleared as if the service +// had answered cleanly. Answers the sentence ({ ok, message }). +export async function POST(request: Request) { + return ops(request, ["service"], async (body) => { + const res = await dismissServiceCookiesAction(reqString(body, "service")); + if (!res.ok) return opsFail(res.error); + return NextResponse.json({ ok: true, message: res.message }); + }); +} diff --git a/editor/app/api/ops/recheck-service/route.ts b/editor/app/api/ops/recheck-service/route.ts @@ -0,0 +1,21 @@ +import { NextResponse } from "next/server"; +import { recheckServiceCookiesAction } from "../../../operations/serviceCookiesActions"; +import { ops, opsFail, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { service: "rumble" | "youtube" | "odysee" | "archive.today" | <forum host> } +// +// The cookie refresh banner's Recheck: ONE request through the service's own +// path (a yt-dlp metadata request for its last clean video; a forum page +// through the host's profile; archive.today's request again), as a one-step +// job (kind `recheck-service-cookies`) the answer waits for: +// { ok, jobId, result: "clean" | "stale" | "failed", message }. "clean" +// clears the alert. +export async function POST(request: Request) { + return ops(request, ["service"], async (body) => { + const res = await recheckServiceCookiesAction(reqString(body, "service")); + if (!res.ok) return opsFail(res.error, 400, res.jobId ? { jobId: res.jobId } : {}); + return NextResponse.json({ ok: true, jobId: res.jobId, result: res.result, message: res.message }); + }); +} diff --git a/editor/app/api/ops/rerun-service-jobs/route.ts b/editor/app/api/ops/rerun-service-jobs/route.ts @@ -0,0 +1,19 @@ +import { NextResponse } from "next/server"; +import { rerunServiceStoppedJobsAction } from "../../../operations/serviceCookiesActions"; +import { ops, opsFail, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { service } +// +// The "OK again" banner's Re-run stopped jobs: every job the service's cookie +// alert stopped (failed or cancelled), retried from its replay descriptor +// ahead of the queue, as /jobs' Retry. Refused while the cookies still look +// stale. { ok, jobIds, skipped: [{id, error}], message }; --wait follows jobIds. +export async function POST(request: Request) { + return ops(request, ["service"], async (body) => { + const res = await rerunServiceStoppedJobsAction(reqString(body, "service")); + if (!res.ok) return opsFail(res.error); + return NextResponse.json({ ok: true, jobIds: res.jobIds, skipped: res.skipped, message: res.message }); + }); +} diff --git a/editor/app/api/ops/services/route.ts b/editor/app/api/ops/services/route.ts @@ -0,0 +1,15 @@ +import { loadCookieAlerts } from "../../../lib/cookieAlerts"; +import { readRoute } from "../_read"; + +export const dynamic = "force-dynamic"; + +// GET /api/ops/services +// +// The dashboard's cookie refresh alerts (`loadCookieAlerts`, the same payload +// /api/view/cookieAlerts serves): each service whose cookies look stale +// ("stale") or answered cleanly again within the day ("ok-again", with the +// jobs the alert stopped), and the services with a first signal waiting for a +// second (`pending` — Rumble's two-videos rule). +export async function GET(request: Request) { + return readRoute(request, [], async () => ({ ...(await loadCookieAlerts()) })); +} diff --git a/editor/app/api/view/[name]/route.test.ts b/editor/app/api/view/[name]/route.test.ts @@ -53,6 +53,10 @@ const PAIRS: Array<[string, string]> = [ ["/api/widget/cleanable", "/api/view/cleanable"], ]; +// Views born after the consolidation: there is no old path to rewrite, so +// they are served only at /api/view/<name>. +const NEW_VIEWS = ["cookieAlerts"]; + async function view(name: string): Promise<number> { const res = await GET(new Request(`http://localhost/api/view/${name}`), { params: Promise.resolve({ name }), @@ -87,7 +91,7 @@ test("each old path is a rewrite to its view, and every view has one", async () } assert.deepEqual( [...VIEW_NAMES].sort(), - PAIRS.map(([, v]) => v.slice("/api/view/".length)).sort(), + [...PAIRS.map(([, v]) => v.slice("/api/view/".length)), ...NEW_VIEWS].sort(), ); }); diff --git a/editor/app/api/view/views.ts b/editor/app/api/view/views.ts @@ -11,6 +11,7 @@ import { buildAutoQueueStatusPayload } from "../../operations/status"; import { buildSchedulerStatusPayload } from "../../scheduler/status"; import { widgetSyncInputs } from "../../widget/lib/syncInputs"; import { cleanableChannels } from "../../cleanup/lib/loadCleanup"; +import { loadCookieAlerts } from "../../lib/cookieAlerts"; import { loadActionableSummary, widgetActionableRows, @@ -75,4 +76,9 @@ export const VIEWS: Record<ViewName, (req: Request) => Promise<Response>> = { // snapshot read serving both, as before. cleanable: async () => NextResponse.json(buildCleanablePayload(await cleanableChannels(getPaths()))), + + // The dashboard's cookie refresh alerts: a service whose cookies look stale + // (or are OK again, with the jobs it stopped). One small file and each + // recorded job's status. + cookieAlerts: async () => NextResponse.json(await loadCookieAlerts(getPaths())), }; diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx @@ -6,6 +6,7 @@ // Its only failure surfaces are "the fetch failed" and "we need credentials", // which is exactly what the state sidecar records. +import Link from "next/link"; import { useState, useTransition } from "react"; import { checkPostAvailabilityAction, @@ -411,6 +412,15 @@ export function SocialChannelPanel({ {forum ? "Needs the forum session: the forum showed a check (or a login) the headless browser could not get past. Use Connect forum session below, clear it in the window, close it, and fetch again." : "Needs credentials: the fetcher could not authenticate. Configure cookies-from-browser for this channel (or globally) and re-run."} + {forum && ( + <> + {" "} + <Link href="/" className="underline underline-offset-2"> + The dashboard + </Link>{" "} + carries the forum&apos;s cookie alert, with Recheck. + </> + )} </p> )} {state.lastError && ( diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -71,6 +71,8 @@ import { type ForumSessionStatus, } from "yt-dlp-transcript-common/social/forumSession"; import { parseXenforoThreadUrl } from "yt-dlp-transcript-common/social/xenforoParse"; +import { noteServiceCookieClean } from "yt-dlp-transcript-common/lib/serviceCookies-server"; +import { forumServiceKey } from "yt-dlp-transcript-common/lib/serviceCookies"; // Switch which SocialFetcher drives this channel. The fetchers differ in what // they can actually reach — for X, gallery-dl needs credentials for depth, @@ -395,6 +397,11 @@ export async function connectForumSessionAction( const record = await connectForumSession(getPaths(), ch.url, { onLog: (line) => console.log(`[forum-session] ${line}`), }); + // A window that closed on the thread clears the forum's cookie refresh + // alert (the dashboard's banner). + if (record.cleared) { + await noteServiceCookieClean(getPaths(), forumServiceKey(ch.host), { url: ch.url, channel: slug }, { by: "connect" }); + } revalidatePath(`/channels/${slug}`); return { ok: true, record }; } catch (e) { diff --git a/editor/app/components/dashboard/CookieAlertsPanel.tsx b/editor/app/components/dashboard/CookieAlertsPanel.tsx @@ -0,0 +1,133 @@ +"use client"; + +// THE COOKIE REFRESH BANNERS (plans/cookie-refresh-alerts.md): one per service +// whose cookies look stale — "Rumble needs fresh cookies: open rumble.com in +// firefox" — with Recheck (one request through the service's own path) and +// Dismiss; once the service answers cleanly again, "OK again" with Re-run for +// the jobs it stopped. The dashboard's top slot, like the first-run checklist. + +import Link from "next/link"; +import { useState, useTransition } from "react"; +import type { + ServiceCookieAlertView, + ServiceCookieAlertsPayload, +} from "yt-dlp-transcript-common/lib/serviceCookies"; +import { + dismissServiceCookiesAction, + recheckServiceCookiesAction, + rerunServiceStoppedJobsAction, +} from "../../operations/serviceCookiesActions"; + +const BUTTON = + "rounded-md border border-border bg-card px-2.5 py-1 text-xs hover:bg-muted disabled:opacity-50"; + +function AlertCard({ alert, onChange }: { alert: ServiceCookieAlertView; onChange: () => void }) { + const [note, setNote] = useState<{ text: string; error: boolean } | null>(null); + const [pending, start] = useTransition(); + const stale = alert.state === "stale"; + const act = (fn: () => Promise<{ ok: boolean; message?: string; error?: string }>) => + start(async () => { + setNote(null); + const r = await fn(); + setNote(r.ok ? { text: r.message ?? "", error: false } : { text: r.error ?? "Failed.", error: true }); + onChange(); + }); + const channel = alert.evidence.channel; + return ( + <section + role="alert" + aria-label={`${alert.label} cookies`} + data-service={alert.service} + data-state={alert.state} + className={`rounded-md border bg-card px-4 py-3 ${stale ? "border-destructive/50" : "border-brand/40"}`} + > + <div className="flex flex-wrap items-start justify-between gap-3"> + <div className="flex min-w-0 flex-col gap-1"> + <p className={`text-sm font-medium ${stale ? "text-destructive" : "text-brand"}`}>{alert.headline}</p> + <p className="text-xs text-muted-foreground break-words"> + {alert.detail} + {alert.family === "forum" && channel && ( + <> + {" · "} + <Link href={`/channels/${channel}`} className="underline underline-offset-2 hover:text-foreground"> + channel page + </Link> + </> + )} + {alert.family === "archive" && ( + <> + {" · "} + <Link href="/settings" className="underline underline-offset-2 hover:text-foreground"> + Settings + </Link> + </> + )} + </p> + {alert.evidence.line && ( + <code className="block max-w-full truncate text-[11px] text-muted-foreground" title={alert.evidence.line}> + {alert.evidence.line} + </code> + )} + </div> + <div className="flex shrink-0 flex-wrap items-center gap-1.5"> + {stale && alert.canRecheck && ( + <button + type="button" + className={BUTTON} + disabled={pending} + onClick={() => act(() => recheckServiceCookiesAction(alert.service))} + > + {pending ? "Checking…" : "Recheck"} + </button> + )} + {!stale && alert.stoppedJobs.length > 0 && ( + <button + type="button" + className={BUTTON} + disabled={pending} + onClick={() => act(() => rerunServiceStoppedJobsAction(alert.service))} + > + Re-run stopped jobs + </button> + )} + {stale && ( + <button + type="button" + className={BUTTON} + disabled={pending} + onClick={() => act(() => dismissServiceCookiesAction(alert.service))} + > + Dismiss + </button> + )} + </div> + </div> + {note && ( + <p + role="status" + aria-label={`${alert.label} cookies result`} + className={`mt-2 text-xs ${note.error ? "text-destructive" : "text-muted-foreground"}`} + > + {note.text} + </p> + )} + </section> + ); +} + +export function CookieAlertsPanel({ + data, + onChange, +}: { + data: ServiceCookieAlertsPayload; + onChange: () => void; +}) { + if (data.alerts.length === 0) return null; + return ( + <div className="flex flex-col gap-2" aria-label="Cookie refresh alerts"> + {data.alerts.map((a) => ( + <AlertCard key={a.service} alert={a} onChange={onChange} /> + ))} + </div> + ); +} diff --git a/editor/app/components/dashboard/DashboardCockpit.tsx b/editor/app/components/dashboard/DashboardCockpit.tsx @@ -9,6 +9,8 @@ import { PipelineBand } from "./PipelineBand"; import { NeedsWorkPanel } from "./NeedsWorkPanel"; import { QuickAddPanel } from "./QuickAddPanel"; import { FirstRunPanel, type FirstRunState } from "./FirstRunPanel"; +import { CookieAlertsPanel } from "./CookieAlertsPanel"; +import type { ServiceCookieAlertsPayload } from "yt-dlp-transcript-common/lib/serviceCookies"; import type { ChannelRowView } from "yt-dlp-transcript-common/views/channelRow"; import { ChannelsTable } from "../../channels/components/ChannelsTable"; import { @@ -36,8 +38,12 @@ export type DashboardCockpitInitial = { changelogSource: string | null; // Set while the corpus has no channel (app/page.tsx): the first-run checklist. firstRun?: FirstRunState | null; + // The cookie refresh alerts (lib/cookieAlerts.ts), polled SLOW after this. + cookieAlerts?: ServiceCookieAlertsPayload; }; +const EMPTY_COOKIE_ALERTS: ServiceCookieAlertsPayload = { alerts: [], pending: [] }; + // The mission-control cockpit. A server component (app/page.tsx) SSRs the // initial payloads for a flicker-free first paint; this client shell then polls // the same /api endpoints the widget uses so the whole surface updates in place. @@ -73,10 +79,21 @@ export function DashboardCockpit({ SLOW_MS, initial.sync, ); + const { data: cookieAlerts, refetch: refetchCookieAlerts } = + usePolledPayload<ServiceCookieAlertsPayload>( + "/api/view/cookieAlerts", + true, + SLOW_MS, + initial.cookieAlerts ?? EMPTY_COOKIE_ALERTS, + ); return ( <div className="flex flex-col gap-6"> <h1 className="sr-only">Dashboard</h1> + <CookieAlertsPanel + data={cookieAlerts ?? EMPTY_COOKIE_ALERTS} + onChange={() => void refetchCookieAlerts()} + /> {initial.firstRun && <FirstRunPanel state={initial.firstRun} />} <PipelineBand jobs={jobs} diff --git a/editor/app/lib/cookieAlerts.ts b/editor/app/lib/cookieAlerts.ts @@ -0,0 +1,40 @@ +// THE DASHBOARD'S COOKIE REFRESH ALERTS (plans/cookie-refresh-alerts.md): the +// state file read, each recorded job's status asked of the registry (else its +// sidecar), and the pure builder (lib/serviceCookies.ts) over both. Served as +// the `cookieAlerts` view and SSR-seeded by app/page.tsx. + +import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths"; +import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; +import { readJobMeta } from "yt-dlp-transcript-common/jobs/jobMeta"; +import { + buildServiceCookieAlerts, + type ServiceCookieAlertsPayload, +} from "yt-dlp-transcript-common/lib/serviceCookies"; +import { + configuredCookieBrowser, + readServiceCookieState, +} from "yt-dlp-transcript-common/lib/serviceCookies-server"; + +export async function loadCookieAlerts( + paths: Paths = getPaths(), + now: number = Date.now(), +): Promise<ServiceCookieAlertsPayload> { + const state = await readServiceCookieState(paths); + const ids = new Set<string>(); + for (const e of Object.values(state.services)) { + if (!e.raisedAt) continue; + for (const j of e.jobs) ids.add(j.id); + } + const statuses = new Map<string, string>(); + const registry = getRegistry(); + for (const id of ids) { + const live = registry.get(id)?.status; + const status = live ?? (await readJobMeta(paths, id))?.status; + if (status) statuses.set(id, status); + } + return buildServiceCookieAlerts(state, { + now, + browser: configuredCookieBrowser(), + statusOf: (id) => statuses.get(id), + }); +} diff --git a/editor/app/operations/serviceCookiesActions.ts b/editor/app/operations/serviceCookiesActions.ts @@ -0,0 +1,113 @@ +"use server"; + +// THE COOKIE REFRESH ALERT'S BUTTONS (plans/cookie-refresh-alerts.md), shared +// by the dashboard banner and `/api/ops/service-cookies`: +// +// Recheck ONE request through the service's own path, as a one-step job +// (kind `recheck-service-cookies`, its own queue) that the click +// waits for — the alert clears when it comes back clean. +// Dismiss the operator's word: the alert is cleared as if the service +// had answered. +// Re-run every job the alert stopped (failed or cancelled), retried +// from its replay descriptor ahead of the queue, as /jobs' Retry. + +import { revalidatePath } from "next/cache"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { runManagedFunction } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { isServiceKey, serviceLabel } from "yt-dlp-transcript-common/lib/serviceCookies"; +import { + dismissServiceCookieAlert, + markServiceCookieRerun, +} from "yt-dlp-transcript-common/lib/serviceCookies-server"; +import { + recheckServiceCookies, + type RecheckOutcome, +} from "yt-dlp-transcript-common/controller/recheckServiceCookies"; +import { retryJobAction } from "../jobs/actions"; +import { loadCookieAlerts } from "../lib/cookieAlerts"; + +function refuse(service: string): string | null { + return isServiceKey(service) ? null : `Not a service: ${service}`; +} + +export async function recheckServiceCookiesAction( + service: string, +): Promise< + | { ok: true; jobId: string; result: RecheckOutcome["result"]; message: string } + | { ok: false; error: string; jobId?: string } +> { + const bad = refuse(service); + if (bad) return { ok: false, error: bad }; + const paths = getPaths(); + let outcome: RecheckOutcome | null = null; + const res = await runManagedFunction({ + kind: "recheck-service-cookies", + queueKey: `service-cookies:${service}`, + paths, + fn: async (onLog, signal) => { + outcome = await recheckServiceCookies({ paths, service, onLog, signal }); + }, + }); + if (!res.ok) return { ok: false, error: res.error }; + void res.stream.cancel(); + const done = await res.done; + revalidatePath("/"); + const o = outcome as RecheckOutcome | null; + if (done.status !== "done" || !o) { + return { ok: false, jobId: res.jobId, error: `The ${serviceLabel(service)} recheck ended ${done.status}.` }; + } + return { ok: true, jobId: res.jobId, result: o.result, message: o.message }; +} + +export async function dismissServiceCookiesAction( + service: string, +): Promise<{ ok: true; message: string } | { ok: false; error: string }> { + const bad = refuse(service); + if (bad) return { ok: false, error: bad }; + const had = await dismissServiceCookieAlert(getPaths(), service); + revalidatePath("/"); + return { + ok: true, + message: had + ? `${serviceLabel(service)}'s cookie alert dismissed.` + : `${serviceLabel(service)} had no cookie alert to dismiss.`, + }; +} + +export async function rerunServiceStoppedJobsAction( + service: string, +): Promise< + | { ok: true; jobIds: string[]; skipped: { id: string; error: string }[]; message: string } + | { ok: false; error: string } +> { + const bad = refuse(service); + if (bad) return { ok: false, error: bad }; + const paths = getPaths(); + const alert = (await loadCookieAlerts(paths)).alerts.find((a) => a.service === service); + if (!alert) return { ok: false, error: `${serviceLabel(service)} has no cookie alert.` }; + if (alert.state === "stale") { + return { ok: false, error: `${serviceLabel(service)}'s cookies still look stale — Recheck first.` }; + } + const jobIds: string[] = []; + const skipped: { id: string; error: string }[] = []; + for (const j of alert.stoppedJobs) { + const res = await retryJobAction(j.id); + if (res.ok) { + void res.stream.cancel(); + jobIds.push(res.jobId); + } else { + skipped.push({ id: j.id, error: res.error }); + } + } + await markServiceCookieRerun(paths, service, jobIds); + revalidatePath("/"); + return { + ok: true, + jobIds, + skipped, + message: + `Re-ran ${jobIds.length} job${jobIds.length === 1 ? "" : "s"} ${serviceLabel(service)}'s cookies stopped` + + (skipped.length ? `; ${skipped.length} could not be (${skipped.map((s) => `${s.id}: ${s.error}`).join("; ")})` : "") + + ".", + }; +} diff --git a/editor/app/page.tsx b/editor/app/page.tsx @@ -19,6 +19,7 @@ import { buildWorkersPayload } from "./workers/buildWorkers"; import { buildWidgetSyncPayload } from "yt-dlp-transcript-common/views/widgetSync"; import { widgetSyncInputs } from "./widget/lib/syncInputs"; import { DashboardCockpit } from "./components/dashboard/DashboardCockpit"; +import { loadCookieAlerts } from "./lib/cookieAlerts"; import { buildChannelRowView, channelVolumeOf, @@ -133,9 +134,10 @@ export default async function Dashboard({ // active site for the SSR seed. const actionable = buildWidgetActionablePayload(widgetActionableRows(rows)); - const [jobs, sync] = await Promise.all([ + const [jobs, sync, cookieAlerts] = await Promise.all([ buildActiveJobsPayload(), widgetSyncInputs().then(buildWidgetSyncPayload), + loadCookieAlerts(paths), ]); const workers = buildWorkersPayload(); const changelogSource = loadChangelog(); @@ -150,6 +152,7 @@ export default async function Dashboard({ channels, changelogSource, firstRun: summary.rows.length === 0 ? firstRunState(paths) : null, + cookieAlerts, }} /> ); diff --git a/editor/app/settings/archiveSessionActions.ts b/editor/app/settings/archiveSessionActions.ts @@ -20,6 +20,8 @@ import { import { isArchiveTodayUrl } from "yt-dlp-transcript-common/lib/archives/mementos"; import { sanitizeArchives, type ArchivesSettings } from "yt-dlp-transcript-common/lib/archives/settings"; import { saveSettings } from "./saveSettings"; +import { noteServiceCookieClean } from "yt-dlp-transcript-common/lib/serviceCookies-server"; +import { ARCHIVE_TODAY_SERVICE } from "yt-dlp-transcript-common/lib/serviceCookies"; export async function archiveSessionStatusAction(): Promise<ArchiveSessionStatus> { return readArchiveSessionStatus(getPaths()); @@ -36,6 +38,11 @@ export async function connectArchiveSessionAction( const record = await connectArchiveSession(getPaths(), at, { onLog: (line) => console.log(`[archive-session] ${line}`), }); + // A window that closed on a page that is not a check clears the cookie + // refresh alert for archive.today (the dashboard's banner). + if (record.cleared) { + await noteServiceCookieClean(getPaths(), ARCHIVE_TODAY_SERVICE, undefined, { by: "connect" }); + } revalidatePath("/settings"); return { ok: true, record }; } catch (e) { diff --git a/editor/e2e/cookie-alerts.spec.ts b/editor/e2e/cookie-alerts.spec.ts @@ -0,0 +1,134 @@ +// COOKIE REFRESH ALERTS (plans/cookie-refresh-alerts.md), end to end. +// +// The 2026-10-21 case in miniature: a fetch-windows batch on Rumble whose +// embeds 403 (the browser's Cloudflare clearance cookie had gone stale). The +// fake yt-dlp answers `embed403` URLs with the real RumbleEmbed 403 line until +// the spec drops `fake-ytdlp.fresh-cookies` in the channel dir — the operator +// opening rumble.com in the browser. Two different videos refused in a row +// raise the banner; Recheck (one metadata request) clears it once the fake +// answers; "Re-run stopped jobs" retries the batch it stopped. +// +// Same token as /api/ops/* (WORKER_TOKEN=test-worker-token on the test server). + +import { readFile, writeFile } from "node:fs/promises"; +import { test, expect, type APIRequestContext } from "@playwright/test"; +import { resetData, resolvePath, testPaths, writeSettings } from "./helpers"; +import { baseUrl } from "./baseUrl"; + +const AUTH = { authorization: "Bearer test-worker-token" }; +const SLUG = "test-youtube"; +const channelRel = (p: string) => `${testPaths().transcriptsDir}/channels/${SLUG}/${p}`; + +async function jobStatus(request: APIRequestContext, jobId: string): Promise<string> { + const r = await request.get(`${baseUrl}/api/ops/job/${jobId}`, { headers: AUTH }); + const body = (await r.json()) as { job?: { status?: string } }; + return body.job?.status ?? ""; +} + +async function waitJob(request: APIRequestContext, jobId: string, timeout = 90_000): Promise<string> { + let status = ""; + await expect + .poll( + async () => { + status = await jobStatus(request, jobId); + return status; + }, + { timeout }, + ) + .not.toMatch(/^(queued|running|)$/); + return status; +} + +test.beforeEach(async () => { + await resetData("youtube-with-playlist"); + await writeSettings({ minFreeDiskGB: 0 }); +}); + +test("two Rumble embeds refused raise the banner; Recheck with fresh cookies clears it; the stopped batch re-runs", async ({ + page, + request, +}) => { + test.setTimeout(180_000); + const items = [ + { slug: SLUG, id: "embed403a", webpageUrl: "https://rumble.com/vembed403a-first.html", from: 5, to: 10, clipId: "c01" }, + { slug: SLUG, id: "embed403b", webpageUrl: "https://rumble.com/vembed403b-second.html", from: 5, to: 10, clipId: "c02" }, + ]; + const post = await request.post(`${baseUrl}/api/ops/fetch-windows`, { + headers: AUTH, + data: { requestedBy: "umtool", manifest: "cookie-alerts", items }, + }); + expect(post.status()).toBe(200); + const body = (await post.json()) as { jobs: { platform: string; jobId: string }[] }; + expect(body.jobs).toHaveLength(1); + expect(body.jobs[0].platform).toBe("rumble"); + const batchId = body.jobs[0].jobId; + expect(await waitJob(request, batchId)).toBe("failed"); + + // The stopping job's log names the cause and the fix. + const log = await readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${batchId}.log`), "utf8"); + expect(log).toMatch(/a removed video does this too; a second video refused in a row raises the cookie alert/); + expect(log).toMatch(/stopped: Rumble cookies look stale — open rumble\.com in .*, then Recheck on the dashboard\./); + + // The read side says the same. + const services = await request.get(`${baseUrl}/api/ops/services`, { headers: AUTH }); + expect(services.status()).toBe(200); + const s = (await services.json()) as { alerts: { service: string; state: string; stoppedJobs: { id: string }[] }[] }; + expect(s.alerts.map((a) => [a.service, a.state])).toEqual([["rumble", "stale"]]); + + // The banner, top of the dashboard. + await page.goto(`${baseUrl}/`); + const banner = page.getByRole("alert", { name: "Rumble cookies" }); + await expect(banner).toContainText("Rumble needs fresh cookies: open rumble.com in"); + await expect(banner).toContainText("2 embed 403s on different videos"); + + // Recheck while the cookies are still stale: it stays. + await banner.getByRole("button", { name: "Recheck" }).click(); + await expect(page.getByRole("status", { name: "Rumble cookies result" })).toContainText("still refused", { + timeout: 30_000, + }); + await expect(banner).toHaveAttribute("data-state", "stale"); + + // The operator opens rumble.com in the browser; Recheck clears it. + await writeFile(resolvePath(channelRel("fake-ytdlp.fresh-cookies")), "fresh"); + await banner.getByRole("button", { name: "Recheck" }).click(); + await expect(banner).toHaveAttribute("data-state", "ok-again", { timeout: 30_000 }); + await expect(banner).toContainText("Rumble cookies OK again — re-run the 1 job it stopped"); + const invocations = await readFile(resolvePath(channelRel("fake-ytdlp.invocations")), "utf8"); + expect(invocations).toContain("recheck:https://rumble.com/vembed403b-second.html"); + + // Re-run the batch it stopped: the windows fetch now. + await banner.getByRole("button", { name: "Re-run stopped jobs" }).click(); + await expect(page.getByRole("status", { name: "Rumble cookies result" })).toContainText("Re-ran 1 job", { + timeout: 30_000, + }); + const after = (await (await request.get(`${baseUrl}/api/ops/services`, { headers: AUTH })).json()) as { + alerts: { service: string; rerunJobIds?: string[] }[]; + }; + const rerun = after.alerts.find((a) => a.service === "rumble")?.rerunJobIds ?? []; + expect(rerun).toHaveLength(1); + expect(await waitJob(request, rerun[0])).toBe("done"); +}); + +test("ops: get services is behind the token; recheck-service refuses a name that is not a service", async ({ request }) => { + expect((await request.get(`${baseUrl}/api/ops/services`)).status()).toBe(401); + const empty = await request.get(`${baseUrl}/api/ops/services`, { headers: AUTH }); + expect(empty.status()).toBe(200); + expect(await empty.json()).toMatchObject({ ok: true, alerts: [], pending: [] }); + const bad = await request.post(`${baseUrl}/api/ops/recheck-service`, { + headers: AUTH, + data: { service: "you tube/../x" }, + }); + expect(bad.status()).toBe(400); + const nothing = await request.post(`${baseUrl}/api/ops/recheck-service`, { + headers: AUTH, + data: { service: "odysee" }, + }); + // Nothing recorded for Odysee: the probe has nothing to ask, and says so. + expect(nothing.status()).toBe(200); + expect(await nothing.json()).toMatchObject({ ok: true, result: "failed" }); + const dismiss = await request.post(`${baseUrl}/api/ops/dismiss-service`, { + headers: AUTH, + data: { service: "youtube" }, + }); + expect(await dismiss.json()).toMatchObject({ ok: true, message: "YouTube had no cookie alert to dismiss." }); +}); diff --git a/editor/e2e/fixtures/bin/fake-ytdlp.mjs b/editor/e2e/fixtures/bin/fake-ytdlp.mjs @@ -71,6 +71,25 @@ function failCookieGate(url) { process.exit(1); } +// The `embed403` sentinel: Rumble's embed JSON metadata refused with a 403 — +// what a stale Cloudflare clearance cookie looks like — until the spec writes +// `fake-ytdlp.fresh-cookies` into the cwd (the channel dir): the operator +// having opened rumble.com in the browser. +function embed403Blocked(url) { + return (url ?? "").toLowerCase().includes("embed403") && !existsSync("fake-ytdlp.fresh-cookies"); +} + +function failEmbed403(url) { + // The embed id differs per video, as Rumble's does (v<page id> → e<…>). + const embed = `e${(urlIdYouTube(url) ?? "x").replace(/[^A-Za-z0-9]/g, "").slice(0, 10)}`; + process.stderr.write(`[RumbleEmbed] Extracting URL: https://rumble.com/embed/${embed}\n`); + process.stderr.write(`[RumbleEmbed] ${embed}: Downloading JSON metadata\n`); + process.stderr.write( + `ERROR: [RumbleEmbed] ${embed}: Unable to download JSON metadata: HTTP Error 403: Forbidden (caused by <HTTPError 403: Forbidden>)\n`, + ); + process.exit(1); +} + function urlIdYouTube(u) { try { const parsed = new URL(u); @@ -553,6 +572,17 @@ async function main() { process.exit(101); } + // THE COOKIE RECHECK (controller/recheckServiceCookies.ts): one metadata + // request, `--skip-download --print id`, nothing written. Branched before + // everything else that passes --skip-download. + if (has("--skip-download") && arg("--print") === "id") { + const url = lastNonFlag() ?? ""; + await appendFile("fake-ytdlp.invocations", `recheck:${url} cookies=${cookieArg()} argv=${argv.join(" ")}\n`); + if (embed403Blocked(url)) failEmbed403(url); + process.stdout.write(`${urlIdYouTube(url)}\n`); + return; + } + // CLIP WINDOW (fetchWindowManaged): --download-sections *<from>-<to> with an // absolute -o. Branched FIRST because nothing else passes --download-sections // and because its -o is a dotfile .part under data/<id>/clips/, which no @@ -582,6 +612,10 @@ async function main() { ); process.exit(1); } + // `embed403`: Rumble's embed JSON refused while the browser's Cloudflare + // cookie is stale — the cookie refresh alert's signal (2026-10-21) — + // until the spec drops `fake-ytdlp.fresh-cookies` in the channel dir. + if (embed403Blocked(url)) failEmbed403(url); // `win403`: Rumble's Cloudflare / googlevideo refusing the media request — // a `network` failure, which the fetch-windows batch counts toward its // two-in-a-row backoff. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -101,6 +101,8 @@ // pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}' // pnpm ops fetch-windows --file windows.json --wait // pnpm ops get tags eva-collab +// pnpm ops get services +// pnpm ops recheck-service --json '{"service":"rumble"}' // pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}' // pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait // pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait @@ -244,6 +246,9 @@ const GETTERS = { "auto-queue": () => "/api/ops/auto-queue", // The sync scheduler: each channel's schedule, the tick log. scheduler: () => "/api/ops/scheduler", + // The dashboard's cookie refresh alerts: each service whose cookies look + // stale (or are OK again, with the jobs the alert stopped). + services: () => "/api/ops/services", // One channel's cleanup row: what each sweep would reclaim, what holds the rest. cleanup: (slug) => `/api/ops/cleanup/${encodeURIComponent(slug)}`, // What a channel holds, by date, and its gaps (release 19 A9): each video @@ -291,6 +296,7 @@ const GET_ARG_OPTIONAL = new Set([ "workers", "auto-queue", "scheduler", + "services", "generation-usage", ]); @@ -444,6 +450,12 @@ const ACTIONS = [ // ({slug, sweep}). "settings", "clear-platform-hold", + // COOKIE REFRESH ALERTS: a service's alert rechecked with one request + // through its own path ({service}), dismissed ({service}), or the jobs it + // stopped re-run once it is OK again ({service}). + "recheck-service", + "dismiss-service", + "rerun-service-jobs", "workers", "transcribe-one", "delete-file", @@ -900,7 +912,7 @@ export function usage() { " pnpm ops job retry-failed [--wait]", " pnpm ops job wait <id>... [--wait-timeout <seconds>]", " pnpm ops get settings [<key>]", - " pnpm ops get storage | sites | workers | auto-queue | scheduler", + " pnpm ops get storage | sites | workers | auto-queue | scheduler | services", " pnpm ops get cleanup <slug>", " pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]", " pnpm ops get transcript <videoId> [--slug <slug>]", @@ -941,6 +953,10 @@ export function usage() { " is the status.)", "get workers, get auto-queue and get scheduler are /workers, the four lanes", " of /operations, and /operations/sync — the payloads those pages poll.", + "get services is the dashboard's cookie refresh alerts: each service", + " (rumble, youtube, odysee, archive.today, a forum host) whose cookies look", + " stale, or are OK again with the jobs the alert stopped; \"pending\" lists", + " a first Rumble embed 403 waiting for a second video.", "get cleanup <slug> is one channel's /cleanup row: what each sweep would", " reclaim (they overlap — never add them), what holds the rest, and the", " failed-transcriptions count. measured: false means unknown, not zero.", @@ -1023,6 +1039,15 @@ export function usage() { 'clear-platform-hold clears a platform\'s rate-limit hold, backoff and raised', ' pace, as the lane strip\'s Clear hold: {"platform"}. Answers the sentence.', "", + 'recheck-service asks a service whose cookie refresh alert is up ONE request', + ' through its own path, as the dashboard banner\'s Recheck: {"service"}', + ' ("rumble", "youtube", "odysee", "archive.today" or a forum host). Waits', + ' for it: {jobId, result: "clean" | "stale" | "failed", message}; "clean"', + " clears the alert (and a yt-dlp service's backoff, as any clean request).", + 'dismiss-service clears a service\'s cookie alert by hand: {"service"}.', + 'rerun-service-jobs retries every job a service\'s cookie alert stopped, once', + ' it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them.', + "", 'workers switches transcription workers as /workers does: {"op": "enable" |', ' "disable" | "drain", "ids": [...]} — the live pool; a restart restores', ' the launch default. An unknown id is named; the others still apply.',