commit 29bb4b76e5ec9adcdfd657f04afe41bfd8f5a06d parent f02fe660e73fdf26aab8b507352b4eb0c921220b Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sat, 21 Nov 2026 05:24:08 -0500 editor: counted confirmation on every unchecked clean button, the plan carried, and Cancel for a scheduled clean retry Review 1 of lane clean-unverified. - With a channel's cleanAudioWithoutChecking on, Clean audio on the Cleanup stage, the /cleanup card and the dashboard and widget buttons say "without checking" and show the same counted confirmation; the run carries the confirmed video ids. A plain Clean audio drawn while the key was off refuses if it was turned on since. Turning the key on asks first, stating what it changes. - Clean without checking and `pnpm ops cleanup {"unchecked": true}` carry their plan (ops counts it at the call); the dry run answers the ids too. - A rate-limited clean's retry is scheduled off the queue and re-armed at boot (below the idle gate). Cancel reaches it from the deferred job's row and `pnpm ops job cancel <id>`, the Cleanup stage's Cancel retry, any new clean a person starts on the channel, and a /jobs cancel of the queued retry job. - Replay of the clean kinds goes through cleanReplayFor. - OPERATING.md: the plan, the off-queue retry and its Cancel, and that a listing 429 during a checked clean counts toward the platform's pace and hold. COMMANDS.md and CHANNEL.md regenerated; CHANGELOG. Co-Authored-By: Claude <noreply@anthropic.com> Diffstat:
22 files changed, 549 insertions(+), 164 deletions(-)
diff --git a/CHANNEL.md b/CHANNEL.md @@ -45,7 +45,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `excludeFromCleanup` | config | Leave this channel's reclaimable bytes out of the aggregate "cleanable data" total on /cleanup and its badge. The per-channel cleanup sweeps stay available; only the running total changes. | | `excludeFromCompaction` | config | Keep this channel's saved videos out of compaction (`compact-saved-videos`, a re-encode to AV1 that becomes the active copy): neither the selector nor an explicit list touches them. For a channel whose stored bytes are kept as evidence. Absent = false. | | `cleanAfterCaptureUnverified` | config | Let clean-after-capture (settings `diarization.cleanAfterCapture`) delete this channel's audio with NO availability check. Only for a channel with no `url`: with no source there is nothing to list, so the automatic per-video clean holds every such channel ("no source to check: clean by hand") unless this is true. The manual Clean audio sweep is unaffected. Absent/false = held. | -| `cleanAudioWithoutChecking` | config | Every clean of this channel's transcribed audio runs WITHOUT the availability check: the Clean audio button, the /cleanup row, `pnpm ops cleanup` and clean after capture alike ask the source nothing, so the audio of a video no longer available anywhere is removed too (it is no longer pinned do-not-clean). Every other protection holds: do-not-clean marks, the keep-latest window, the speaker holds (awaiting diarization / voice fingerprint), untranscribed videos, an unreachable or moving media drive. Those jobs run as "Clean audio without checking". For a platform whose VODs expire by design (Twitch, Kick), where "gone from the source" is the normal state; never set by platform. Absent/false = checked. Set on the channel's Cleanup stage or with `pnpm ops channel-config {"cleanAudioWithoutChecking": true}`. | +| `cleanAudioWithoutChecking` | config | Every clean of this channel's transcribed audio runs WITHOUT the availability check: the Clean audio button, the /cleanup row, `pnpm ops cleanup` and clean after capture alike ask the source nothing, so the audio of a video no longer available anywhere is removed too (it is no longer pinned do-not-clean). Every other protection holds: do-not-clean marks, the keep-latest window, the speaker holds (awaiting diarization / voice fingerprint), untranscribed videos, an unreachable or moving media drive. Those jobs run as "Clean audio without checking"; the key is read again when each starts, and a saved video container is never pruned by them. A new channel never starts with it (createChannel drops it). For a platform whose VODs expire by design (Twitch, Kick), where "gone from the source" is the normal state; never set by platform. Absent/false = checked. Set on the channel's Cleanup stage or with `pnpm ops channel-config {"cleanAudioWithoutChecking": true}`. | | `syncIntervalMinutes` | config | Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync. AN INSTAGRAM CHANNEL is synced seldom, because every sync is a logged-in read: absent = every 12 hours at the most often (the global default when that is longer), and a value of its own is never under 240 (4 hours); 0 still turns it off (`common/jobs/syncScheduler.ts`). | | `fullSweepIntervalMinutes` | config | Full-sweep cadence: a sync upgrades itself to a full sweep when `now - lastFullSweepAt >= fullSweepIntervalMinutes`. Absent = inherit `syncScheduler.fullSweepIntervalMinutes`; 0 = never sweep (every sync is a paged walk); positives clamp to [1, 44640]. | | `skipLiveDownloads` | config | Per-channel override for the global `skipLiveDownloads`. Absent = inherit; false = allow downloading currently-live / upcoming videos. | diff --git a/COMMANDS.md b/COMMANDS.md @@ -204,7 +204,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | | | `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | | | `drop-saved-alternate` | drop-saved-alternate deletes one saved alternate of one video, as its "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}. "file" is a name `get saved-alternates` lists under "alternates"; the active copy, an unlisted name and any path are refused, and so is a store being moved. The file goes from the store and its entry from saved-video.json (the rest of the pointer is untouched); one already gone is cleaned from the pointer ("existed": false). "dryRun": true answers the same and changes nothing. No undo. An ORIGINAL ("keptAs": "original", the source of a compacted copy) needs "confirmOriginal": true; the compacted copy is read back from disk (size, sha256, container, length) before it goes; a video not freshly checked on its platform needs a review of this copy recorded first; and nothing goes while a download or persist of the video is queued or running, or while it is being compacted. A FORMER original ("former-original") needs its own "confirmFormerOriginal": true, and the same gone/review rule. | | -| `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. "unchecked": true (transcribed only) is "Clean without checking": the source is not asked, so the audio of videos no longer available anywhere goes too; every other protection holds; the job is "Clean audio without checking". With "dryRun": true it answers what it would remove — {plan: {videos, files, bytes, protected, awaitingDiarization, awaitingVoiceprint, inspected}} — and starts nothing. A checked clean the source rate-limits ends deferred and retries itself on the channel queue after at least 15 min (twice at most), then gives up. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait`<br>`pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}'` | +| `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. "unchecked": true (transcribed only) is "Clean without checking": the source is not asked, so the audio of videos no longer available anywhere goes too; every other protection holds; the job is "Clean audio without checking". With "dryRun": true it answers what it would remove — {plan: {ids, videos, files, bytes, protected, awaitingDiarization, awaitingVoiceprint, inspected}} — and starts nothing; without it the plan is counted at the call and the job removes at most those videos' audio. It never touches a saved video. A checked clean the source rate-limits ends deferred and schedules a retry off the queue after at least 15 min (twice at most), then gives up; `job cancel <the deferred job id>` cancels the retry. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait`<br>`pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}'` | | `diarize` | diarize runs a channel's "Diarize speakers" as a job: {"slug"}. Every video still holding audio with no current diarization.json is diarized, and a diarized one without voice fingerprints gets them from its own turns — the voiceprint backfill, one channel at a time. Runs while the Speakers lane is paused; nothing is deleted. | `pnpm ops diarize --json '{"slug":"x"}' --wait` | | `web-search` | web-search searches the web (DuckDuckGo's HTML page) and answers the results: {"query", "n"?: 6 (at most 20)} -> {results: \[{title, url, snippet}\]}. Read only, through the editor's one web queue: one request at a time, 3 s apart, backing off on a 429 or 503. For context; a web page is never cited as what someone said. | `pnpm ops web-search --json '{"query":"second shop opening","n":5}'` | | `web-fetch` | web-fetch reads one web page as plain text: {"url", "maxChars"?: 12000 (at most 60000)} -> {page: {url, finalUrl, status, contentType, title?, text, truncated}}. http and https only; a private or loopback host (by name, by address, or by what its name resolves to, every redirect checked) is refused before any request, and so is a page that is not text (a PDF, an image). Read only, on the same web queue as web-search. | `pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}'` | diff --git a/OPERATING.md b/OPERATING.md @@ -1110,20 +1110,39 @@ pnpm ops channel-config --json '{"slug":"example","cleanAudioWithoutChecking":tr - **Clean without checking** (the Cleanup stage, `"unchecked": true`) skips that check and asks the source nothing, so the audio of videos no longer available anywhere is removed too. Every other protection holds: do-not-clean, the keep-latest window, awaiting diarization or voice fingerprint, untranscribed videos, and a media drive that is - unreachable or being moved. The page shows the dry plan's numbers first (`dryRun`: files, bytes, videos, what it - keeps) and asks; the job is titled "Clean audio without checking". A Retry of that job is unchecked only when it was - the button's. -- **`cleanAudioWithoutChecking`** on a channel (CHANNEL.md; the Cleanup stage's checkbox) makes every clean of it - unchecked: Clean audio, the /cleanup row, `cleanup` over ops and clean after capture. Off unless set; never set by - platform. Clean after capture still holds a URL-less channel (`cleanAfterCaptureUnverified`) and a whole-recording - one (`diarization.cleanWholeRecordingAudio`) — those holds are not the availability check. + unreachable or being moved (asked again immediately before anything is removed). It never touches a saved video: + the saved-video retention prune runs only in a checked Clean audio. The page counts first (`dryRun`: files, bytes, + videos, what it keeps, and the video `ids`) and asks: "Remove N audio files (X) from M transcribed videos without + checking? The source is not asked, so the audio of videos no longer available anywhere is removed too." The job + carries those ids and removes **at most** them: a video protected since is skipped, one that became eligible since + is left for the next run ("not in the confirmed plan" in its log). Over ops, a call without `dryRun` counts at the + call and carries that plan. The job is titled "Clean audio without checking". A Retry of it, or a restart that + caught it queued, runs it again with its carried plan only; with no plan it removes nothing and ends failed, + "Confirmed plan lost; confirm again". +- **`cleanAudioWithoutChecking`** on a channel (CHANNEL.md; the Cleanup stage's checkbox, which asks before turning it + on) makes every clean of it unchecked: Clean audio, the /cleanup card, the dashboard's buttons, `cleanup` over ops + and clean after capture. Each button then shows the same counted confirmation and carries its plan; a `cleanup` + call with no flag, and clean after capture, discover when they start. The key is read again when the job starts: if + it was turned off meanwhile, the job runs checked and says so in its log. Off unless set; never set by platform; a + new channel never starts with it. Clean after capture still holds a URL-less channel + (`cleanAfterCaptureUnverified`) and a whole-recording one (`diarization.cleanWholeRecordingAudio`) — those holds + are not the availability check. Audio an earlier checked clean pinned as "deleted from source (pre-clean check)" + stays do-not-clean: unpin it on the video page (or `pnpm ops do-not-clean --json '{"slug":"example","id":"<id>","keep":false}'`) to let + it go. - **A checked clean the source rate-limits** (HTTP 429 on the channel listing or on a confirmation probe) deletes - nothing it could not verify and ends **deferred** on /jobs, with its counts. It queues one retry of itself on the - channel's queue, not before 15 minutes or the platform's cooldown (the one downloads and Sync share), whichever is - later; the retry waits on /jobs ("waiting …: retrying a clean the source rate-limited") and holds the channel queue - while it does. Cancel that job to cancel the retry. After 2 retries the next rate limit ends the job **failed**: - "Gave up: rate-limited … It needs a person". A failure that is not a rate limit (a network error, an extractor - break) ends failed, "Could not verify availability …", and retries nothing. + nothing it could not verify and ends **deferred** on /jobs, with its counts. **The 429 counts toward the + platform's pace and hold**: a rate-limited listing records the platform's cooldown as Sync does + (`recordDownloadBackoff`), which widens that platform's request pace and counts toward a platform hold, so + downloads, Sync, fetch-windows and imports on that platform wait too. It schedules ONE retry, not before 15 minutes + or the platform's cooldown, whichever is later. The retry waits **off the queue** — a record in + `.jobs/clean-retries.json` and a timer — so it holds neither the channel's queue nor a job slot, and it is queued + as "Clean audio (rate-limit retry)" only when its time comes (later still if the cooldown is still running then). + The record survives a restart: the retry keeps its attempt and its time. **Cancel** the deferred job to cancel the + retry (`pnpm ops job cancel <deferred job id>`), or use **Cancel retry** on the + Cleanup stage; any Clean audio or Clean without checking a person starts on the channel replaces it. After 2 + retries the next rate limit ends the job **failed**: "Gave up: rate-limited … It needs a person". A failure that is + not a rate limit (a network error, an extractor break) ends failed, "Could not verify availability …", and retries + nothing. ## Record a live stream; import a file diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -3,22 +3,25 @@ ## [Unreleased] - **Clean audio without checking, and a rate-limited clean that says so.** - The channel page's Cleanup stage has **Clean without checking…** beside Clean audio. It first counts what it would - remove (files, bytes, videos, and what it keeps; no request to the source) and asks: "Remove N audio file(s) (X) - from M transcribed video(s)? The source is not asked, so the audio of videos no longer available anywhere is - removed too." Every other protection holds: do-not-clean, keep-latest, awaiting diarization or voice fingerprint, - untranscribed videos, an unreachable or moving media drive. The job is titled **Clean audio without checking**. - CLI: `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}'` (the counts), - then without `dryRun`. + remove (files, bytes, videos, and what it keeps; no request to the source) and asks: "Remove N audio files (X) + from M transcribed videos without checking? The source is not asked, so the audio of videos no longer available + anywhere is removed too." The job carries the counted videos' ids and removes at most those. Every other + protection holds: do-not-clean, keep-latest, awaiting diarization or voice fingerprint, untranscribed videos, an + unreachable or moving media drive (asked again just before anything is removed). It never touches a saved video. + The job is titled **Clean audio without checking**. CLI: `pnpm ops cleanup --json + '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}'` (the counts and ids), then without `dryRun`. - New channel key `cleanAudioWithoutChecking` (off unless set): every clean of the channel runs unchecked — the - button, /cleanup, `pnpm ops cleanup` and clean after capture. A checkbox on the Cleanup stage sets it; Twitch and - Kick channels show a hint, nothing is set by platform. CLI: `pnpm ops channel-config --json - '{"slug":"x","cleanAudioWithoutChecking":true}'`. + button, /cleanup, the dashboard's buttons, `pnpm ops cleanup` and clean after capture. Every button then shows the + same counted confirmation. A checkbox on the Cleanup stage sets it and asks first; Twitch and Kick channels show + a hint, nothing is set by platform, and a new channel never starts with it. A queued job reads the key again when + it starts. CLI: `pnpm ops channel-config --json '{"slug":"x","cleanAudioWithoutChecking":true}'`. - A checked clean the source rate-limits (HTTP 429 on the listing or a confirmation probe) still deletes nothing it - could not verify, and now ends **deferred** with its counts instead of a plain done. It queues one retry on the - channel's queue, not before 15 minutes or the platform's cooldown, whichever is later; the retry waits on /jobs - and cancelling it cancels the retry. After two retries it ends failed, "Gave up: rate-limited", for a person. A - failure that is not a rate limit ends failed, "Could not verify availability", with no retry. A rate-limited - listing now records the platform cooldown, as Sync does. + could not verify, and now ends **deferred** with its counts instead of a plain done. It schedules one retry, not + before 15 minutes or the platform's cooldown, whichever is later. The retry waits off the queue and survives a + restart; it runs as **Clean audio (rate-limit retry)** when its time comes. Cancel the deferred job, or Cancel + retry on the Cleanup stage, to cancel it. After two retries it ends failed, "Gave up: rate-limited", for a + person. A failure that is not a rate limit ends failed, "Could not verify availability", with no retry. A + rate-limited listing now records the platform cooldown, as Sync does. - **umtool: the gap mark's border is the deck's accent colour.** - The operator picked variant B. The border is drawn in the deck's accent, the colour of the deck's accent rule and the dots in its source line, at full opacity. The box behind the text is near-black at 90 %, and the text diff --git a/editor/app/api/ops/_writes.test.ts b/editor/app/api/ops/_writes.test.ts @@ -275,6 +275,9 @@ test("cleanup unchecked dryRun answers the confirmation's plan and starts nothin for (const k of ["inspected", "videos", "files", "bytes", "protected", "awaitingDiarization", "awaitingVoiceprint"]) { assert.equal(typeof plan[k], "number", k); } + // The ids a confirmed run carries, one per video counted. + assert.ok(Array.isArray(plan.ids)); + assert.equal((plan.ids as unknown[]).length, plan.videos); const wrongSweep = await callPost(cleanup, { slug: SLUG, sweep: "extra-formats", unchecked: true }); assert.equal(wrongSweep.status, 400); assert.match(String(wrongSweep.body.error), /"unchecked" applies to the "transcribed" sweep only/); diff --git a/editor/app/api/ops/cleanup/route.ts b/editor/app/api/ops/cleanup/route.ts @@ -36,9 +36,14 @@ export const dynamic = "force-dynamic"; // availability check is skipped and the source is not asked, so the audio of // videos no longer available anywhere goes too; every other protection holds. // "dryRun": true (unchecked only) answers the confirmation's numbers — -// {plan: {inspected, videos, files, bytes, protected, awaitingDiarization, -// awaitingVoiceprint}} — and starts nothing. A channel whose config sets -// cleanAudioWithoutChecking runs "transcribed" unchecked without the flag. +// {plan: {inspected, ids, videos, files, bytes, protected, +// awaitingDiarization, awaitingVoiceprint}} — and starts nothing. Without +// "dryRun" the plan is computed at the call and carried by the job, which +// removes at most those videos' audio (what became protected since is +// skipped; what became eligible since is left for the next run). A channel +// whose config sets cleanAudioWithoutChecking runs "transcribed" unchecked +// without the flag, discovering at start (nobody confirmed a count); the key +// is re-read when the job starts. const SWEEPS = { transcribed: cleanAudioAction, "extra-formats": cleanExtraAudioFormatsAction, @@ -63,7 +68,14 @@ export async function POST(request: Request) { if (!r.ok) return opsFail(r.error); return NextResponse.json({ ok: true, dryRun: true, plan: r.plan }); } - if (unchecked) return jobResponse(await cleanAudioUncheckedAction(slug)); + // A non-dry unchecked call is its own confirmation: its plan is computed + // NOW and carried, so the job removes at most what this call would have + // answered (the intersection with what is still eligible when it starts). + if (unchecked) { + const r = await planCleanAudioUncheckedAction(slug); + if (!r.ok) return opsFail(r.error); + return jobResponse(await cleanAudioUncheckedAction(slug, undefined, r.plan.ids)); + } return jobResponse(await SWEEPS[sweep](slug)); }); } diff --git a/editor/app/channels/[slug]/cleanRetryScheduler.ts b/editor/app/channels/[slug]/cleanRetryScheduler.ts @@ -0,0 +1,67 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getRegistry, onJobEnd } from "yt-dlp-transcript-common/jobs/registry"; +import { platformCooldownRemainingMs } from "yt-dlp-transcript-common/jobs/downloadBackoff"; +import { + armCleanRetriesAtBoot, + cancelCleanRetries, + type CleanRetryDeps, +} from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; + +// THE EDITOR'S WIRING of a rate-limited clean's off-queue retry +// (common/controller/cleanRetrySchedule.ts): how its timer queues the retry +// job (cleanAudioRetryAction, on the channel's queue), how a cancel reaches a +// job it already queued (the registry's cancel), and the platform cooldown it +// re-reads. Not a "use server" module: nothing here is a client-callable +// action. +export function cleanRetryDeps(): CleanRetryDeps { + const paths = getPaths(); + return { + cooldownRemainingMs: (pf) => platformCooldownRemainingMs(pf, paths), + enqueue: async (entry) => { + // Lazy: whisperActions imports this module. + const { cleanAudioRetryAction } = await import("./whisperActions"); + const r = await cleanAudioRetryAction(entry.slug, { + attempt: entry.attempt, + of: entry.of, + notBefore: entry.notBefore, + platform: entry.platform, + id: entry.id, + }); + if (!r.ok) return { ok: false, error: r.error }; + // Nobody reads this job's stream; it is followed on /jobs. + void r.stream.cancel().catch(() => {}); + return { ok: true, jobId: r.jobId }; + }, + cancelJob: (jobId) => getRegistry().cancel(jobId), + log: (m) => console.log(m), + }; +} + +// A RETRY JOB CANCELLED WHILE QUEUED is a person's decision (a /jobs Cancel, +// Drain all): its record goes too, or the next boot would re-arm it. Not at +// shutdown — the reaper's cancels are nobody's, and the boot re-arms those. +// (A retry that ran removes its own record when it ends.) Once per process. +declare global { + // eslint-disable-next-line no-var + var __yttCleanRetryEndListener__: boolean | undefined; +} +if (!globalThis.__yttCleanRetryEndListener__) { + globalThis.__yttCleanRetryEndListener__ = true; + onJobEnd((job) => { + if (job.kind !== "clean-audio-retry" || job.status !== "cancelled") return; + if (getRegistry().isShuttingDown()) return; + void cancelCleanRetries(getPaths(), { id: job.id }, cleanRetryDeps()).catch(() => {}); + }); +} + +// The boot (instrumentation.ts, below the idle gate): arm every scheduled +// retry again from its record. +export async function armCleanRetriesOnBoot(): Promise<void> { + const out = await armCleanRetriesAtBoot(getPaths(), cleanRetryDeps()); + if (out.armed.length || out.dropped.length) { + console.log( + `[boot] clean retries: ${out.armed.length} re-armed from their schedule` + + (out.dropped.length ? `, ${out.dropped.length} dropped (interrupted twice)` : ""), + ); + } +} diff --git a/editor/app/channels/[slug]/components/stages/CleanWithoutChecking.tsx b/editor/app/channels/[slug]/components/stages/CleanWithoutChecking.tsx @@ -2,12 +2,18 @@ import { useState } from "react"; import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; -import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import type { AudioCleanPlan } from "yt-dlp-transcript-common/controller/cleanAudioFromTranscribed"; +import type { ScheduledCleanRetry } from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; +import { + TURN_ON_CONFIRMATION, + cleanConfirmationText, +} from "yt-dlp-transcript-common/lib/cleanAudioConfirm"; import { cancelJobAction } from "../../../../jobs/actions"; import { setCleanAudioWithoutCheckingAction } from "../../../actions"; import { useHydrated } from "../../../../operations/components/useOperationsStatus"; import { + cancelCleanRetryAction, + cleanAudioAction, cleanAudioUncheckedAction, planCleanAudioUncheckedAction, } from "../../whisperActions"; @@ -17,25 +23,20 @@ import { // key is never set by platform. const EXPIRING_VOD_PLATFORMS = new Set(["twitch", "kick"]); -const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; - -// The confirmation's sentence, from the dry plan (no network, no deletes). -export function confirmationText(plan: AudioCleanPlan): { ask: string; kept: string } { - return { - ask: - `Remove ${plural(plan.files, "audio file")} (${formatBytes(plan.bytes)}) from ${plural(plan.videos, "transcribed video")}? ` + - "The source is not asked, so the audio of videos no longer available anywhere is removed too.", - kept: - `Kept: ${plan.protected} marked do not clean or in the keep-latest window, ` + - `${plan.awaitingDiarization} awaiting diarization, ${plan.awaitingVoiceprint} awaiting voice fingerprint. ` + - "Videos with no transcript are not touched.", - }; -} - -// "Clean without checking": a one-off clean of this channel's transcribed -// audio with the availability check skipped. Two steps: the plan is computed -// first and stated, then a second button runs it. -export function CleanWithoutCheckingSection({ slug }: { slug: string }) { +// A clean without checking, in two steps: the plan is counted (no network, no +// deletes) and stated, then a second button runs THAT plan — the job carries +// its video ids and removes at most those. `mode`: "button" is the one-off +// "Clean without checking"; "channel-setting" is Clean audio on a channel whose +// key is on (the key is read again when the job starts). +export function CleanWithoutCheckingSection({ + slug, + mode = "button", + queueKey, +}: { + slug: string; + mode?: "button" | "channel-setting"; + queueKey?: string; +}) { const hydrated = useHydrated(); const [plan, setPlan] = useState<AudioCleanPlan | null>(null); const [error, setError] = useState<string | null>(null); @@ -48,13 +49,19 @@ export function CleanWithoutCheckingSection({ slug }: { slug: string }) { if (r.ok) setPlan(r.plan); else setError(r.error); }; - const text = plan ? confirmationText(plan) : null; + const text = plan ? cleanConfirmationText(plan) : null; + const run = (ids: string[]) => + mode === "button" ? cleanAudioUncheckedAction(slug, queueKey, ids) : cleanAudioAction(slug, queueKey, ids); return ( <div aria-label="clean without checking section" className="flex flex-col gap-2 rounded border border-border p-3"> <div> - <h4 className="text-sm font-semibold">Clean without checking</h4> + <h4 className="text-sm font-semibold"> + {mode === "button" ? "Clean without checking" : "Clean audio without checking"} + </h4> <p className="text-xs text-muted-foreground"> - The same clean, without asking the source whether each video is still there. + {mode === "button" + ? "The same clean, without asking the source whether each video is still there." + : "This channel cleans without checking: the source is not asked."} </p> </div> {!plan && ( @@ -65,7 +72,7 @@ export function CleanWithoutCheckingSection({ slug }: { slug: string }) { disabled={!hydrated || busy} className="rounded border border-border bg-card px-3 py-1 text-sm hover:bg-accent disabled:opacity-50" > - {busy ? "Counting…" : "Clean without checking…"} + {busy ? "Counting…" : mode === "button" ? "Clean without checking…" : "Clean audio without checking…"} </button> </div> )} @@ -76,20 +83,16 @@ export function CleanWithoutCheckingSection({ slug }: { slug: string }) { )} {plan && text && ( <div role="group" aria-label="confirm clean without checking" className="flex flex-col gap-2"> - {plan.files === 0 ? ( - <p className="text-sm">Nothing to remove: no transcribed video here holds audio a clean would take.</p> - ) : ( - <p className="text-sm font-medium">{text.ask}</p> - )} + <p className="text-sm font-medium">{text.ask}</p> <p className="text-xs text-muted-foreground">{text.kept}</p> <div className="flex flex-wrap items-start gap-2"> {plan.files > 0 && ( <StreamActionLog - trigger={() => cleanAudioUncheckedAction(slug)} + trigger={() => run(plan.ids)} cancelAction={cancelJobAction} - buttonLabel={`Remove ${plural(plan.files, "file")} without checking`} + buttonLabel={text.button} runningLabel="Cleaning…" - label="Clean without checking" + label={mode === "button" ? "Clean without checking" : "Clean audio without checking"} /> )} <button @@ -106,7 +109,8 @@ export function CleanWithoutCheckingSection({ slug }: { slug: string }) { ); } -// The channel key cleanAudioWithoutChecking, set to a value. +// The channel key cleanAudioWithoutChecking, set to a value. Turning it ON +// asks first, stating what it changes; turning it off does not. export function AlwaysCleanWithoutCheckingToggle({ slug, on, @@ -118,22 +122,51 @@ export function AlwaysCleanWithoutCheckingToggle({ }) { const hydrated = useHydrated(); const [pending, setPending] = useState(false); + const [asking, setAsking] = useState(false); + const set = async (value: boolean) => { + setPending(true); + await setCleanAudioWithoutCheckingAction(slug, value); + setPending(false); + setAsking(false); + }; return ( <div className="flex flex-col gap-1"> <label className="flex items-center gap-2 text-sm"> <input type="checkbox" - checked={on} + checked={on || asking} disabled={!hydrated || pending} - onChange={async (e) => { - setPending(true); - await setCleanAudioWithoutCheckingAction(slug, e.target.checked); - setPending(false); + onChange={(e) => { + if (e.target.checked) setAsking(true); + else if (asking) setAsking(false); + else void set(false); }} aria-label="always clean this channel without checking" /> Always clean this channel without checking </label> + {asking && !on && ( + <div role="group" aria-label="confirm always clean without checking" className="flex flex-col gap-2 rounded border border-border p-2"> + <p className="text-sm">{TURN_ON_CONFIRMATION}</p> + <div className="flex gap-2"> + <button + type="button" + disabled={pending} + onClick={() => void set(true)} + className="rounded border border-border bg-card px-3 py-1 text-sm hover:bg-accent disabled:opacity-50" + > + Turn on + </button> + <button + type="button" + onClick={() => setAsking(false)} + className="rounded border border-border px-3 py-1 text-sm hover:bg-accent" + > + Cancel + </button> + </div> + </div> + )} <p className="text-xs text-muted-foreground"> Every clean of this channel — the buttons here, /cleanup, pnpm ops and clean after capture — deletes audio without asking the source whether the video is still there, so a video removed upstream loses its only copy. @@ -146,3 +179,35 @@ export function AlwaysCleanWithoutCheckingToggle({ </div> ); } + +// A rate-limited Clean audio's retry, scheduled off the queue: when, and a +// Cancel that reaches it. +export function ScheduledCleanRetryNote({ slug, retry }: { slug: string; retry: ScheduledCleanRetry }) { + const hydrated = useHydrated(); + const [state, setState] = useState<"idle" | "busy" | "cancelled">("idle"); + if (state === "cancelled") { + return <p className="text-xs text-muted-foreground">Retry cancelled.</p>; + } + const when = new Date(retry.notBefore).toLocaleString(); + return ( + <div aria-label="scheduled clean retry" className="flex flex-wrap items-center gap-2 text-sm"> + <span> + {retry.state === "enqueued" + ? `The source rate-limited the last Clean audio: retry ${retry.attempt} of 2 is queued.` + : `The source rate-limited the last Clean audio: retry ${retry.attempt} of 2 is scheduled, not before ${when}.`} + </span> + <button + type="button" + disabled={!hydrated || state === "busy"} + onClick={async () => { + setState("busy"); + await cancelCleanRetryAction(slug); + setState("cancelled"); + }} + className="rounded border border-border px-2 py-0.5 text-xs hover:bg-accent disabled:opacity-50" + > + Cancel retry + </button> + </div> + ); +} diff --git a/editor/app/channels/[slug]/components/stages/CleanupStage.tsx b/editor/app/channels/[slug]/components/stages/CleanupStage.tsx @@ -9,7 +9,7 @@ import { QueueControl } from "../../../../components/QueueControl"; import { cancelJobAction } from "../../../../jobs/actions"; import { checkKeptDeletedAction, - cleanAudioAction, + cleanAudioButtonAction, cleanExtraAudioFormatsAction, diarizeChannelAction, purgeSupersededAutoSubsAction, @@ -21,7 +21,9 @@ import { VideoIdList } from "../VideoIdList"; import { AlwaysCleanWithoutCheckingToggle, CleanWithoutCheckingSection, + ScheduledCleanRetryNote, } from "./CleanWithoutChecking"; +import type { ScheduledCleanRetry } from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; type Props = { slug: string; @@ -55,6 +57,8 @@ type Props = { // availability check), and its platform, for the expiring-VOD hint. cleanWithoutChecking: boolean; platform: string; + // A rate-limited Clean audio's retry, waiting off the queue (or queued). + scheduledCleanRetry: ScheduledCleanRetry | null; }; export function CleanupStage({ @@ -75,6 +79,7 @@ export function CleanupStage({ diarizationEnabled, cleanWithoutChecking, platform, + scheduledCleanRetry, }: Props) { const defaultQueueKey = `channel:${slug}`; const [cleanQueue, setCleanQueue] = useState(defaultQueueKey); @@ -124,29 +129,34 @@ export function CleanupStage({ title="Clean audio for transcribed videos" desc="Delete audio.* files in any video directory that has a transcript.json (whisper output). YouTube videos with only auto-sub .vtt files have no audio and are skipped automatically. While diarization is on, a video awaiting its speakers or voice fingerprints keeps its audio." /> - {cleanWithoutChecking && ( - <p className="text-sm font-medium"> - This channel cleans without checking: the source is not asked. - </p> - )} <ReclaimEstimate bytes={transcribedAudioBytes} /> - <StreamActionLog - trigger={() => cleanAudioAction(slug, cleanQueue)} - cancelAction={cancelJobAction} - buttonLabel="Clean audio" - runningLabel="Cleaning…" - label="Clean audio" - extraControls={ - <QueueControl - value={cleanQueue} - onChange={setCleanQueue} - defaultQueueKey={defaultQueueKey} - existingQueues={existingQueues} - actionLabel="Clean audio" + {scheduledCleanRetry && <ScheduledCleanRetryNote slug={slug} retry={scheduledCleanRetry} />} + {cleanWithoutChecking ? ( + // THE KEY IS ON: Clean audio runs without checking, so it shows the + // same counted confirmation as the one-off button and carries the + // confirmed plan. + <CleanWithoutCheckingSection slug={slug} mode="channel-setting" queueKey={cleanQueue} /> + ) : ( + <> + <StreamActionLog + trigger={() => cleanAudioButtonAction(slug, cleanQueue)} + cancelAction={cancelJobAction} + buttonLabel="Clean audio" + runningLabel="Cleaning…" + label="Clean audio" + extraControls={ + <QueueControl + value={cleanQueue} + onChange={setCleanQueue} + defaultQueueKey={defaultQueueKey} + existingQueues={existingQueues} + actionLabel="Clean audio" + /> + } /> - } - /> - {!cleanWithoutChecking && <CleanWithoutCheckingSection slug={slug} />} + <CleanWithoutCheckingSection slug={slug} queueKey={cleanQueue} /> + </> + )} <AlwaysCleanWithoutCheckingToggle slug={slug} on={cleanWithoutChecking} platform={platform} /> </div> {supersededAutoSubsIds.length > 0 && ( diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -1,4 +1,5 @@ import { displayPath, hidePrivateSites } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; +import { readCleanRetries } from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; import { isPrivateSite } from "yt-dlp-transcript-common/lib/siteSchema"; import path from "node:path"; import { Suspense, type ReactNode } from "react"; @@ -825,6 +826,9 @@ export default async function ChannelDetailPage({ diarizationEnabled={settings.diarization.enabled} cleanWithoutChecking={config!.cleanAudioWithoutChecking === true} platform={config!.platform ?? detectUrlPlatform(config!.url ?? "") ?? ""} + scheduledCleanRetry={ + (await readCleanRetries(paths).catch(() => [])).find((r) => r.slug === slug && r.state !== "running") ?? null + } /> ); } diff --git a/editor/app/channels/[slug]/whisperActions.ts b/editor/app/channels/[slug]/whisperActions.ts @@ -22,13 +22,21 @@ import { clearFailedTranscriptions } from "yt-dlp-transcript-common/controller/f import { planAudioClean, type AudioCleanPlan, - type UncheckedReason, } from "yt-dlp-transcript-common/controller/cleanAudioFromTranscribed"; import { + cleanAudioRequestFor, runCleanAudioJob, uncheckedReasonFor, + type CleanAudioRequest, type CleanRetry, } from "yt-dlp-transcript-common/controller/cleanAudioJob"; +import { + cancelCleanRetries, + finishCleanRetry, + scheduleCleanRetry, + startCleanRetry, +} from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; +import { cleanRetryDeps } from "./cleanRetryScheduler"; import { diarizeAll } from "yt-dlp-transcript-common/controller/diarizeAll"; import { purgeSupersededAutoSubs } from "yt-dlp-transcript-common/controller/purgeSupersededAutoSubs"; import { checkKeptDeleted } from "yt-dlp-transcript-common/controller/checkKeptDeleted"; @@ -306,31 +314,67 @@ export async function removeWrongFormatAudioAction( // "Clean audio": the checked sweep — unless the channel's config sets // cleanAudioWithoutChecking, when it runs as "Clean audio without checking" -// (its own job kind, so the job list says so). `retry` is a rate-limited -// clean's queued retry (controller/cleanAudioJob.ts), never a caller's. +// (its own job kind, so the job list says so; the key is read again when the +// job starts). `plan` is a confirmed plan's video ids (a button that showed +// the counted confirmation): the run removes at most those. A clean a person +// starts supersedes the channel's scheduled rate-limit retry, if any. export async function cleanAudioAction( slug: string, queueKey?: string, - retry?: CleanRetry, + plan?: string[], ): Promise<StreamActionResult> { const paths = getPaths(); const config = await readChannelConfig(paths, slug).catch(() => null); - const byChannel = uncheckedReasonFor(config); - if (byChannel) return runCleanAudio(slug, queueKey, byChannel); - return runCleanAudio(slug, queueKey, undefined, retry); + await supersedeCleanRetries(slug); + return runCleanAudio(slug, queueKey, cleanAudioRequestFor(config, { plan })); +} + +// A PLAIN "Clean audio" BUTTON drawn while the channel's key was off. If the +// key is on by the time it is pressed, it would run without checking with no +// count shown, so it refuses and says to reload: the page then draws the +// counted confirmation (ruling 6). +export async function cleanAudioButtonAction( + slug: string, + queueKey?: string, +): Promise<StreamActionResult> { + const config = await readChannelConfig(getPaths(), slug).catch(() => null); + if (uncheckedReasonFor(config)) { + return { + ok: false, + info: true, + error: "This channel now cleans without checking: reload the page to see what would be removed before cleaning.", + }; + } + return cleanAudioAction(slug, queueKey); } -// "Clean without checking": the one-off, explicit unchecked sweep. The source -// is not asked; every other protection of the sweep holds. +// "Clean without checking": the one-off, explicit unchecked sweep of a plan a +// person confirmed (its ids, from planCleanAudioUncheckedAction). The source is +// not asked; every other protection of the sweep holds; at most the plan's +// videos lose their audio. A call with no plan queues a job that removes +// nothing and ends failed, "Confirmed plan lost; confirm again". export async function cleanAudioUncheckedAction( slug: string, queueKey?: string, + plan?: string[], +): Promise<StreamActionResult> { + await supersedeCleanRetries(slug); + return runCleanAudio(slug, queueKey, cleanAudioRequestFor(null, { explicit: "button", plan })); +} + +// The retry of a rate-limited clean, queued by its schedule at its not-before +// time (controller/cleanRetrySchedule.ts) — never a person's call: a retry +// whose record is gone (cancelled, superseded) does not run. +export async function cleanAudioRetryAction( + slug: string, + retry: CleanRetry, ): Promise<StreamActionResult> { - return runCleanAudio(slug, queueKey, "button"); + return runCleanAudio(slug, undefined, { kind: "clean-audio-transcribed" }, retry); } // The confirmation's numbers: what a clean without checking would remove now -// (controller planAudioClean — no network, no deletes). +// (controller planAudioClean — no network, no deletes), and the ids a +// confirmed run carries. export async function planCleanAudioUncheckedAction( slug: string, ): Promise<{ ok: true; plan: AudioCleanPlan } | { ok: false; error: string }> { @@ -341,14 +385,43 @@ export async function planCleanAudioUncheckedAction( } } +// What a Clean audio button would do NOW: checked, or without checking (the +// channel's key) — and then the counted plan its confirmation shows (ruling 6: +// every button that would run unchecked shows the same counted confirmation). +export async function prepareCleanAudioAction( + slug: string, +): Promise<{ ok: true; withoutChecking: boolean; plan?: AudioCleanPlan } | { ok: false; error: string }> { + const paths = getPaths(); + const config = await readChannelConfig(paths, slug).catch(() => null); + if (!uncheckedReasonFor(config)) return { ok: true, withoutChecking: false }; + const r = await planCleanAudioUncheckedAction(slug); + return r.ok ? { ok: true, withoutChecking: true, plan: r.plan } : r; +} + +// The Cleanup stage's "Cancel retry": cancel this channel's scheduled retry of +// a rate-limited clean (and its job, if the schedule has queued it). +export async function cancelCleanRetryAction(slug: string): Promise<{ ok: boolean; cancelled: number }> { + const removed = await cancelCleanRetries(getPaths(), { slug }, cleanRetryDeps()); + safeRevalidate([`/channels/${slug}`]); + return { ok: true, cancelled: removed.length }; +} + +async function supersedeCleanRetries(slug: string): Promise<void> { + const removed = await cancelCleanRetries(getPaths(), { slug }, cleanRetryDeps()).catch(() => []); + for (const r of removed) { + console.log(`[clean-retry] ${r.id}: superseded by a new clean of ${slug}.`); + } +} + function runCleanAudio( slug: string, queueKey: string | undefined, - unchecked?: UncheckedReason, + req: CleanAudioRequest, retry?: CleanRetry, ): Promise<StreamActionResult> { const paths = getPaths(); - const kind = unchecked ? "clean-audio-unchecked" : "clean-audio-transcribed"; + const kind = retry ? "clean-audio-retry" : req.kind; + const { unchecked, plan } = req; // A retry runs on the CHANNEL's queue, whatever queue the request took. const key = retry ? channelQueueKey(slug) : resolveQueueKey(channelQueueKey(slug), queueKey); return runManagedFunction({ @@ -359,28 +432,50 @@ function runCleanAudio( spec: { kind, slug, - params: { queueKey, ...(unchecked ? { unchecked } : {}), ...(retry ? { retry } : {}) }, - }, - fn: async (onLog, signal, _setProgress, ctx) => { - const out = await runCleanAudioJob({ - channelSlug: slug, - paths, - jobId: ctx.jobId, + params: { + queueKey, ...(unchecked ? { unchecked } : {}), + ...(plan ? { plan } : {}), ...(retry ? { retry } : {}), - onLog, - signal, - deps: { - enqueueRetry: async (next) => { - const r = await cleanAudioAction(slug, undefined, next); - return r.ok ? { ok: true, jobId: r.jobId } : { ok: false, error: r.error }; + }, + }, + fn: async (onLog, signal, _setProgress, ctx) => { + // A retry runs only while its schedule's record says so. + if (retry?.id && !(await startCleanRetry(paths, retry.id, ctx.jobId))) { + onLog("This retry was cancelled or superseded before it started: nothing was asked or cleaned."); + return; + } + try { + const out = await runCleanAudioJob({ + channelSlug: slug, + paths, + jobId: ctx.jobId, + ...(unchecked ? { unchecked } : {}), + ...(plan ? { plan } : {}), + ...(retry ? { retry } : {}), + onLog, + signal, + deps: { + scheduleRetry: async (next) => { + try { + const entry = await scheduleCleanRetry( + paths, + { slug, attempt: next.attempt, of: next.of, notBefore: next.notBefore, platform: next.platform, deferredJobId: ctx.jobId }, + cleanRetryDeps(), + ); + return { ok: true, id: entry.id }; + } catch (err) { + return { ok: false, error: (err as Error).message }; + } + }, }, - ...(ctx.setPaced ? { setPaced: ctx.setPaced } : {}), - }, - }); - safeRevalidate([`/channels/${slug}`]); - if (out.end === "deferred") throw new JobDeferredError(out.sentence, out.until); - if (out.end === "failed") throw new Error(out.sentence); + }); + safeRevalidate([`/channels/${slug}`]); + if (out.end === "deferred") throw new JobDeferredError(out.sentence, out.until); + if (out.end === "failed") throw new Error(out.sentence); + } finally { + if (retry?.id) await finishCleanRetry(paths, retry.id).catch(() => {}); + } }, }); } diff --git a/editor/app/cleanup/components/ChannelCleanupCard.tsx b/editor/app/cleanup/components/ChannelCleanupCard.tsx @@ -7,12 +7,13 @@ import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { Badge } from "yt-dlp-transcript-common/components/ui/badge"; import { cancelJobAction } from "../../jobs/actions"; import { - cleanAudioAction, + cleanAudioButtonAction, cleanExtraAudioFormatsAction, removeWrongFormatAudioAction, clearFailedTranscriptionsAction, } from "../../channels/[slug]/whisperActions"; import { ChannelCleanupToggle } from "./ChannelCleanupToggle"; +import { CleanWithoutCheckingSection } from "../../channels/[slug]/components/stages/CleanWithoutChecking"; export type ChannelCleanupCardProps = { slug: string; @@ -23,6 +24,9 @@ export type ChannelCleanupCardProps = { foreignBytes: number; hasTargetFormat: boolean; failedTranscriptions: number; + // The channel's cleanAudioWithoutChecking: its Clean audio runs unchecked, + // so the card shows the counted confirmation instead of a one-click button. + withoutChecking?: boolean; }; export function ChannelCleanupCard({ @@ -34,6 +38,7 @@ export function ChannelCleanupCard({ foreignBytes, hasTargetFormat, failedTranscriptions, + withoutChecking = false, }: ChannelCleanupCardProps) { const queueKey = `channel:${slug}`; const [armed, setArmed] = useState(false); @@ -80,15 +85,23 @@ export function ChannelCleanupCard({ {transcribedBytes > 0 && ( <SweepRow estimate={transcribedBytes} - caption="Audio in transcribed video dirs" + caption={ + withoutChecking + ? "Audio in transcribed video dirs (cleaned without checking)" + : "Audio in transcribed video dirs" + } > - <StreamActionLog - trigger={() => cleanAudioAction(slug, queueKey)} - cancelAction={cancelJobAction} - buttonLabel="Clean audio" - runningLabel="Cleaning…" - label={`Clean audio ${slug}`} - /> + {withoutChecking ? ( + <CleanWithoutCheckingSection slug={slug} mode="channel-setting" queueKey={queueKey} /> + ) : ( + <StreamActionLog + trigger={() => cleanAudioButtonAction(slug, queueKey)} + cancelAction={cancelJobAction} + buttonLabel="Clean audio" + runningLabel="Cleaning…" + label={`Clean audio ${slug}`} + /> + )} </SweepRow> )} diff --git a/editor/app/cleanup/lib/loadCleanup.ts b/editor/app/cleanup/lib/loadCleanup.ts @@ -230,6 +230,8 @@ export type CleanableChannelRow = { count: number; // Reclaim estimate for the primary "clean audio" sweep, net of protection. bytes: number; + // The channel's cleanAudioWithoutChecking (its Clean audio button says so). + withoutChecking?: boolean; }; // Lean per-channel breakdown for the sidebar badge and the widget API — the @@ -256,7 +258,12 @@ export async function cleanableChannels( // Nothing to reclaim and nothing to sweep — drop the row. Zero-byte rows // contribute nothing to the total, so dropping them keeps it unchanged. if (bytes <= 0 && count <= 0) return null; - return { slug: channel.slug, count, bytes }; + return { + slug: channel.slug, + count, + bytes, + ...(channel.config.cleanAudioWithoutChecking === true ? { withoutChecking: true } : {}), + }; }); return rows .filter((r): r is CleanableChannelRow => r !== null) diff --git a/editor/app/cleanup/page.tsx b/editor/app/cleanup/page.tsx @@ -177,6 +177,7 @@ export default async function CleanupPage() { foreignBytes={r.foreignBytes} hasTargetFormat={r.hasTargetFormat} failedTranscriptions={r.failedTranscriptions} + withoutChecking={r.channel.config.cleanAudioWithoutChecking === true} /> ))} </section> diff --git a/editor/app/components/actions/InlineActionButton.tsx b/editor/app/components/actions/InlineActionButton.tsx @@ -10,8 +10,10 @@ import { import { cleanAudioAction, cleanExtraAudioFormatsAction, + prepareCleanAudioAction, transcribeMissingAction, } from "../../channels/[slug]/whisperActions"; +import { cleanConfirmationText } from "yt-dlp-transcript-common/lib/cleanAudioConfirm"; import { clearIncompleteTranscriptsAction, redownloadIncompleteBucketAction, @@ -28,7 +30,9 @@ type Variant = | { kind: "redownloadIncomplete"; slug: string } | { kind: "clearIncomplete"; slug: string } | { kind: "redownloadShortAudio"; slug: string } - | { kind: "cleanTranscribedAudio"; slug: string } + // `withoutChecking`: the channel's cleanAudioWithoutChecking as the page + // read it (the label); the click asks the server again either way. + | { kind: "cleanTranscribedAudio"; slug: string; withoutChecking?: boolean } | { kind: "cleanExtraFormats"; slug: string } | { kind: "backfillChannel"; slug: string } // The digest lane's LOCAL half only. The metered lane is behind a settings @@ -141,13 +145,63 @@ export function InlineActionButton({ }) { const [status, setStatus] = useState<Status>({ kind: "idle" }); const [pending, startTransition] = useTransition(); - const base = LABEL[variant.kind]; + const base = + variant.kind === "cleanTranscribedAudio" && variant.withoutChecking + ? { idle: "Clean audio without checking", running: "Queuing…" } + : LABEL[variant.kind]; const labels = label ? { ...base, idle: label } : base; const slug = variant.slug; const ariaLabel = `${labels.idle.toLowerCase()} ${slug}`; + // CLEAN AUDIO asks the server first what it would do now: checked (the + // plain confirm), or WITHOUT CHECKING (the channel's key) — then the counted + // confirmation every unchecked button shows, and the run carries that plan. + async function cleanTranscribed() { + setStatus({ kind: "running" }); + const prep = await prepareCleanAudioAction(slug); + if (!prep.ok) { + setStatus({ kind: "error", message: prep.error }); + return; + } + let result: StreamActionResult; + if (prep.withoutChecking && prep.plan) { + const text = cleanConfirmationText(prep.plan); + if (prep.plan.files === 0) { + setStatus({ kind: "done", message: "nothing to remove" }); + return; + } + if (!window.confirm(`${text.ask}\n\n${text.kept}`)) { + setStatus({ kind: "idle" }); + return; + } + result = await cleanAudioAction(slug, undefined, prep.plan.ids); + } else { + if (!window.confirm(CONFIRM.cleanTranscribedAudio!(slug))) { + setStatus({ kind: "idle" }); + return; + } + result = await cleanAudioAction(slug); + } + if (!result.ok) { + setStatus({ kind: "error", message: result.error }); + return; + } + void result.stream.cancel(); + setStatus({ kind: "queued", jobId: result.jobId }); + } + function handleClick() { + if (variant.kind === "cleanTranscribedAudio") { + startTransition(async () => { + try { + await cleanTranscribed(); + } catch (e) { + setStatus({ kind: "error", message: (e as Error).message }); + } + }); + return; + } const confirmMessage = CONFIRM[variant.kind]?.(slug); if (confirmMessage && !window.confirm(confirmMessage)) return; setStatus({ kind: "running" }); diff --git a/editor/app/components/channelWork/sections.tsx b/editor/app/components/channelWork/sections.tsx @@ -226,7 +226,11 @@ export function channelWorkSections(): SectionConfig[] { }, primaryAction: (r) => ( <InlineActionButton - variant={{ kind: "cleanTranscribedAudio", slug: r.channel.slug }} + variant={{ + kind: "cleanTranscribedAudio", + slug: r.channel.slug, + withoutChecking: r.channel.config.cleanAudioWithoutChecking === true, + }} /> ), }, diff --git a/editor/app/jobs/actions.ts b/editor/app/jobs/actions.ts @@ -24,6 +24,8 @@ import { readJobMeta } from "yt-dlp-transcript-common/jobs/jobMeta"; import type { JobSpec } from "yt-dlp-transcript-common/jobs/jobSpec"; import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; import { runJobSpec } from "./runJobSpec"; +import { cancelCleanRetries } from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; +import { cleanRetryDeps } from "../channels/[slug]/cleanRetryScheduler"; import { stuckJobIds } from "./active/buildActiveJobs"; export async function cancelJobAction(id: string): Promise<{ ok: boolean }> { @@ -31,8 +33,12 @@ export async function cancelJobAction(id: string): Promise<{ ok: boolean }> { // work on (a whisper-video, once its audio is down: JobRecord.handedOffTo) // cancels the job doing that work now — the panel is still showing it. const ok = getRegistry().cancel(jobDoingTheWork(id)); + // A CLEAN THE SOURCE RATE-LIMITED ended deferred and scheduled its retry + // off-queue (controller/cleanRetrySchedule.ts): Cancel of that job — or of + // the retry's own queued job — cancels the scheduled retry. + const retries = await cancelCleanRetries(getPaths(), { id }, cleanRetryDeps()).catch(() => []); revalidatePath("/jobs"); - return { ok }; + return { ok: ok || retries.length > 0 }; } // Escape hatch for a WEDGED slot (see registry.forceRelease): unconditionally diff --git a/editor/app/jobs/components/JobRow.tsx b/editor/app/jobs/components/JobRow.tsx @@ -183,6 +183,8 @@ function videoHref(job: JobRowView): string | null { // anything live, and Force-release anything running or stuck (the escape hatch // for a Cancel that leaves a queue wedged; see registry.forceRelease — a stuck // terminal/evicted row has no Cancel to offer, so it gets this instead). +const CLEAN_KINDS_WITH_RETRY = new Set(["clean-audio-transcribed", "clean-audio-unchecked", "clean-audio-retry"]); + export function JobRowActions({ job, forceRelease = "running-or-stuck", @@ -210,6 +212,11 @@ export function JobRowActions({ {(job.status === "running" || job.status === "queued") && ( <CancelJobButton jobId={job.id} /> )} + {/* A Clean audio the source rate-limited ended deferred and scheduled its + retry off the queue: Cancel here cancels that retry (cancelJobAction). */} + {job.status === "done" && job.deferred && CLEAN_KINDS_WITH_RETRY.has(job.kind) && ( + <CancelJobButton jobId={job.id} /> + )} {((forceRelease === "running-or-stuck" && job.status === "running") || Boolean(job.stuck)) && <ForceReleaseJobButton jobId={job.id} />} </> diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -12,6 +12,7 @@ import { savePageNowBatchAction } from "../channels/[slug]/waybackLiveActions"; import { xRunAction } from "../review/xRunActions"; import { coerceClipCopy } from "yt-dlp-transcript-common/lib/clipWindow"; import { isStoredUrlMode } from "yt-dlp-transcript-common/lib/storedMediaUrl"; +import { cleanReplayFor } from "yt-dlp-transcript-common/controller/cleanAudioJob"; import { readChannelSnapshot } from "yt-dlp-transcript-common/controller/channelSnapshot"; import type { JobSpec, ReplayBucket } from "yt-dlp-transcript-common/jobs/jobSpec"; import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; @@ -144,6 +145,15 @@ function params(spec: JobSpec): { return { p, queueKey: str(p.queueKey) }; } +const replayClean: ReplayHandler = async (spec) => { + const { p, queueKey } = params(spec); + const r = cleanReplayFor(spec.kind, p); + if (!r.ok) return r; + return r.call === "unchecked" + ? cleanAudioUncheckedAction(spec.slug, queueKey, r.plan) + : cleanAudioAction(spec.slug, queueKey, r.plan); +}; + // A PUBLISH STAGE (release 18): the spec IS the stage request, so a retry // re-enqueues it as it was — same run id, same preconditions, which the child // re-asks on disk. A spec the stage row would refuse is refused here. @@ -534,26 +544,15 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { const { queueKey } = params(spec); return purgeSupersededAutoSubsAction(spec.slug, queueKey); }, - // A Retry is a person's: a fresh request (a rate-limited clean's `retry` - // chain is not carried), and the channel's cleanAudioWithoutChecking, as it - // is NOW, decides checked or not. - "clean-audio-transcribed": (spec) => { - const { queueKey } = params(spec); - return cleanAudioAction(spec.slug, queueKey); - }, - // UNCHECKED ONLY WITH THE SAME EXPLICIT FLAG (lane clean-unverified): the - // button's run says `unchecked: "button"` and replays unchecked; a run the - // channel key made unchecked replays through cleanAudioAction, so a key - // turned off since is a checked clean; a spec with neither is refused. - "clean-audio-unchecked": async (spec) => { - const { p, queueKey } = params(spec); - if (p.unchecked === "button") return cleanAudioUncheckedAction(spec.slug, queueKey); - if (p.unchecked === "channel-setting") return cleanAudioAction(spec.slug, queueKey); - return { - ok: false, - error: "This clean without checking carries no unchecked flag to replay it with — run Clean audio or Clean without checking instead.", - }; - }, + // THE CLEAN KINDS (lane clean-unverified): one rule, cleanReplayFor + // (controller/cleanAudioJob.ts). A Retry is a person's — and the boot's + // re-queue of a job a restart caught queued: Clean audio again (the key as + // it is now decides), a retry's Retry a fresh chain, and an unchecked + // "button" run again WITH ITS CARRIED PLAN only (no plan: a job that + // removes nothing and ends "Confirmed plan lost; confirm again"). + "clean-audio-transcribed": replayClean, + "clean-audio-retry": replayClean, + "clean-audio-unchecked": replayClean, "diarize-channel": (spec) => { const { queueKey } = params(spec); return diarizeChannelAction(spec.slug, queueKey); diff --git a/editor/app/widget/components/MonitorWidget.tsx b/editor/app/widget/components/MonitorWidget.tsx @@ -964,7 +964,7 @@ function CleanableChannelsStrip({ {interactive && ( <div className="flex flex-wrap items-center gap-1.5"> <InlineActionButton - variant={{ kind: "cleanTranscribedAudio", slug: c.slug }} + variant={{ kind: "cleanTranscribedAudio", slug: c.slug, withoutChecking: c.withoutChecking === true }} /> </div> )} diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts @@ -325,6 +325,19 @@ export async function register() { /* a runner that fails to start must not block server readiness */ } + // A RATE-LIMITED CLEAN'S SCHEDULED RETRY (lane clean-unverified): each + // record in `.jobs/clean-retries.json` gets its timer again, so a retry + // survives a restart with its attempt count and never runs before its + // not-before time. Below the idle gate: a retry lists the channel. An idle + // boot keeps the records for the next boot. + // See common/controller/cleanRetrySchedule.ts. + try { + const { armCleanRetriesOnBoot } = await import("./app/channels/[slug]/cleanRetryScheduler"); + void armCleanRetriesOnBoot().catch(() => {}); + } catch { + /* a schedule that fails to arm must not block server readiness */ + } + // AN `auto` RESEARCH RUN CONTINUES BY ITSELF (release 28 F1): the job-end // listener and one scan of the research runs now; the heartbeat scans again // on each beat. Below the idle gate: a continuation is a generation job. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1630,10 +1630,13 @@ export function usage() { ' only) is "Clean without checking": the source is not asked, so the audio', ' of videos no longer available anywhere goes too; every other protection', ' holds; the job is "Clean audio without checking". With "dryRun": true it', - ' answers what it would remove — {plan: {videos, files, bytes, protected,', - ' awaitingDiarization, awaitingVoiceprint, inspected}} — and starts nothing.', - ' A checked clean the source rate-limits ends deferred and retries itself', - ' on the channel queue after at least 15 min (twice at most), then gives up.', + ' answers what it would remove — {plan: {ids, videos, files, bytes,', + ' protected, awaitingDiarization, awaitingVoiceprint, inspected}} — and', + ' starts nothing; without it the plan is counted at the call and the job', + ' removes at most those videos\' audio. It never touches a saved video.', + ' A checked clean the source rate-limits ends deferred and schedules a', + ' retry off the queue after at least 15 min (twice at most), then gives', + ' up; `job cancel <the deferred job id>` cancels the retry.', "", 'relocate moves channels\' media to a location: {"slugs", "locationId" |', ' "root"}. "dryRun": true answers each channel\'s preview (bytes to copy,',