Archilyzer · Source

archilyzer

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

commit b0f7dfabf4dde34838c3d10687a573f5609e80af
parent 3777ee405bbfa766e0602b3ecf82b76455de3c0d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 10 Oct 2026 17:29:26 -0400

Merge r24/hygiene (H5 the /sites save race, H6 pnpm ops site-config) into r24/integration

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

Diffstat:
MCOMMANDS.md | 1+
MOPERATING.md | 3+++
Meditor/CHANGELOG.md | 2++
Aeditor/app/api/ops/site-config/route.test.ts | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/site-config/route.ts | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/lib/formState.test.ts | 14++++++++++++++
Meditor/app/lib/formState.ts | 17+++++++++++++++++
Aeditor/app/lib/useRefreshAfterSave.ts | 15+++++++++++++++
Meditor/app/sites/actions.ts | 24+++++++++++++-----------
Meditor/app/sites/components/HomepageConfigForm.tsx | 21+++++++++++++--------
Meditor/app/sites/components/SiteForm.tsx | 43++++++++++++++++++++++++-------------------
Meditor/app/sites/components/SiteListActions.tsx | 7+++++++
Meditor/app/sites/lib/homepageActions.ts | 12++++++------
Meditor/e2e/sites-crud.spec.ts | 41+++++++++++++++++++++++++++++++++++++++++
Mplans/release-24.md | 77++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mscripts/archilyzer-ops.mjs | 14++++++++++++++
16 files changed, 454 insertions(+), 45 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -80,6 +80,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) |---|---|---| | `channel-priority` | channel-priority sets channels' priority, as the /channels deck's tier control does: {"slugs", "tier": "normal" \| "low" \| "paused"} sets the base tier; with "operation" (sync, transcription, download, digest, backfill) it pins that operation's tier, "tier": null clearing it back to the base; "preset": "sync-only" \| "clear" is the deck's two shortcuts and takes no tier. A manual change clears an automatic pause. | `pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'` | | `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "&lt;regex with named groups year, month, day&gt;"} (CHANNEL.md, recordedDate). | `pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` | +| `site-config` | site-config sets two keys of a site as its form does: {"siteId"} and any of "citedChannels" (the WHOLE cited scope, channel slugs: what the site's reports may cite without publishing the channel; \[\] clears it; a slug the pool holds is dropped) and "publishAuto" ("off" \| "build" \| "preview" \| "production", the publish lane's policy; a deploying one needs a Pages project, a private site is clamped to "build"). Only those two keys; an unknown site or channel is refused before anything is written. Answers the saved values. | `pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'`<br>`pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'` | | `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'` | | `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` | | `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` | diff --git a/OPERATING.md b/OPERATING.md @@ -167,6 +167,9 @@ pnpm archilyzer publish build example-site --out /srv/example-private citation whose media is not prepared yet passes with `--allow-missing-media` (`"allowMissingMedia": true` on the ops `build` verb). - The publish lane: `pnpm ops lane --json '{"lane":"publish","action":"start"}'` (`"held": true` pauses it). +- A site's policy, and the channels its reports may cite without publishing them, without the site form: + `pnpm ops site-config --json '{"siteId":"example-site","publishAuto":"build","citedChannels":["example-critic"]}'` + (`citedChannels` is the whole cited scope; `[]` clears it). - Details, policies and the hub and homepage: [PUBLISH.md](PUBLISH.md). ## Research with the MCP diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog ## [Unreleased] +- **`pnpm ops site-config` sets a site's cited-only channels and publish policy.** `{"siteId", "citedChannels"?: [slug…], "publishAuto"?: "off" | "build" | "preview" | "production"}` (`POST /api/ops/site-config`) writes through the site form's own validation: a slug the pool holds is dropped, a deploying policy without a Pages project is refused, and a private site is clamped to `build`. An unknown site, channel or key is refused before anything is written. The answer is the saved values. +- **"Saved." on /sites comes at once.** Saving the hub config or a site, deleting a site and migrating settings into a first site sometimes waited up to ~6 s for the page's refresh before saying anything, the button stuck on "Saving…". They now save without making the page refresh wait, show what was saved straight away, and then refresh the page. - **A channel taken off a site, or moved to its cited scope, is withdrawn at the edge.** The next build of the site replaces every `transcripts/`, `subs/`, `posts/` and `digests/` path its last build served for that channel with an empty file of the same shape, served no-store (the way withheld X posts already are), and keeps doing so while the channel stays out. The channel's cited moments and clips still publish. A site's deploy now reads its withdrawn paths back in its live check, as the hub's does. - **Persisting a Wayback or archive.org record no longer undoes its title and date.** A re-download that rewrites `metadata.info.json` keeps the title, upload date and other fields `archilyzer wayback refresh --titles`, `archive-org refresh` or the feed backfill set, when the source only has its placeholder for them; a value the source genuinely changed still lands. A record a persist already reverted gets them back on its next download. - **A site's reports can cite a channel the site does not publish.** A channel row outside the site's pool on the site form now has a **Cited only** box (`citedChannels` in site.json — see SITE.md); `/sites` shows "· N cited" beside the channel count. A report on that site may cite the channel: its moment pages and their clips publish, but not its browse page, transcripts, search entry or corpus.json entry, and its moments link no corpus page. A channel in the pool is never cited-only: ticking **Include** clears the box. A citation of a channel in neither list is still refused at compose (`not-in-site`), and the refusal now names both keys. A build or deploy whose bundle holds a cited-only channel's transcripts, subs, posts, digests, stats or archives, or lists it in corpus.json or site.json, is refused; a change to its transcripts or posts makes the site stale. Renaming a channel renames it in `citedChannels` too, and `pnpm ops get sites` lists the key. A site padding its pool with a channel only to cite it can move the channel to **Cited only**. Needs a restart of the editor for the form; rebuild each site that uses it. diff --git a/editor/app/api/ops/site-config/route.test.ts b/editor/app/api/ops/site-config/route.test.ts @@ -0,0 +1,100 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { setupOpsCorpus, callPost } from "../_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/site-config/route.test.ts" +// +// `site-config` (release 24 H6): a site's cited-only channels and its publish +// policy, written through patchSite — so through writeSite, as the site form's +// save is. Every refusal comes before anything is written. + +const corpus = await setupOpsCorpus(null); +for (const slug of ["pooled", "critic", "other-critic"]) { + await corpus.writeChannelConfig(slug, { url: `https://www.youtube.com/@${slug}` }); +} +const pool = { channels: [{ slug: "pooled", groupId: "default" }] }; +await corpus.writeSite("citing", pool); +await corpus.writeSite("mine", { ...pool, audience: "private" }); +await corpus.writeSite("shipped", { ...pool, cloudflareProject: "shipped-pages" }); + +const { POST } = await import("./route"); +test.after(() => corpus.cleanup()); + +const siteFile = async (id: string) => + JSON.parse(await readFile(path.join(corpus.transcripts, "sites", id, "site.json"), "utf8")) as Record< + string, + unknown + >; + +test("sets the cited scope, drops a pooled slug as the parser does, and [] clears it", async () => { + const set = await callPost(POST, { + siteId: "citing", + citedChannels: ["critic", "pooled", "other-critic", "critic", " "], + }); + assert.equal(set.status, 200, JSON.stringify(set.body)); + assert.deepEqual(set.body, { + ok: true, + siteId: "citing", + citedChannels: ["critic", "other-critic"], + publishAuto: "off", + }); + const file = await siteFile("citing"); + assert.deepEqual(file.citedChannels, [{ slug: "critic" }, { slug: "other-critic" }]); + assert.deepEqual(file.channels, [{ slug: "pooled", groupId: "default" }], "the pool is untouched"); + + const cleared = await callPost(POST, { siteId: "citing", citedChannels: [] }); + assert.equal(cleared.status, 200, JSON.stringify(cleared.body)); + assert.deepEqual(cleared.body.citedChannels, []); + assert.equal("citedChannels" in (await siteFile("citing")), false, "an empty scope is not written"); +}); + +test("publishAuto round-trips; a deploying policy needs a Pages project; a private site is clamped to build", async () => { + for (const policy of ["build", "preview", "production", "off"]) { + const r = await callPost(POST, { siteId: "shipped", publishAuto: policy }); + assert.equal(r.status, 200, JSON.stringify(r.body)); + assert.equal(r.body.publishAuto, policy); + const file = await siteFile("shipped"); + if (policy === "off") assert.equal("publish" in file, false); + else assert.deepEqual(file.publish, { auto: policy }); + } + const before = await siteFile("citing"); + const refused = await callPost(POST, { siteId: "citing", publishAuto: "production" }); + assert.equal(refused.status, 400); + assert.match(refused.body.error ?? "", /publish\.auto "production" deploys the site, and it has no cloudflareProject/); + assert.deepEqual(await siteFile("citing"), before, "nothing written"); + + // A private site is never deployed: "production" is saved as "build". + const clamped = await callPost(POST, { siteId: "mine", publishAuto: "production" }); + assert.equal(clamped.status, 200, JSON.stringify(clamped.body)); + assert.equal(clamped.body.publishAuto, "build"); + assert.deepEqual((await siteFile("mine")).publish, { auto: "build" }); + // Both keys in one call. + const both = await callPost(POST, { siteId: "shipped", citedChannels: ["critic"], publishAuto: "build" }); + assert.deepEqual(both.body, { ok: true, siteId: "shipped", citedChannels: ["critic"], publishAuto: "build" }); +}); + +test("refusals, each before anything is written: keys, site, slugs, policy, nothing to change", async () => { + const before = await siteFile("citing"); + const cases: [Record<string, unknown>, RegExp][] = [ + [{ siteId: "citing", channels: ["critic"] }, /unknown key\(s\): channels — this route accepts siteId, citedChannels, publishAuto/], + [{ siteId: "citing", citedChannels: ["critic"], listed: false }, /unknown key\(s\): listed/], + [{ siteId: "no-such-site", citedChannels: ["critic"] }, /Site "no-such-site" not found/], + [{ siteId: "Bad Id", publishAuto: "build" }, /not a valid site id/], + [{ citedChannels: ["critic"] }, /"siteId" is required/], + [{ siteId: "citing", citedChannels: ["critic", "no-such-channel"] }, /not a channel: "no-such-channel"/], + [{ siteId: "citing", citedChannels: ["../etc"] }, /not a valid channel slug/], + [{ siteId: "citing", citedChannels: "critic" }, /"citedChannels" must be an array of channel slugs/], + [{ siteId: "citing", publishAuto: "sometimes" }, /"publishAuto" must be one of off, build, preview, production/], + [{ siteId: "citing" }, /nothing to change/], + ]; + for (const [body, re] of cases) { + const r = await callPost(POST, body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.match(r.body.error ?? "", re, JSON.stringify(body)); + } + assert.deepEqual(await siteFile("citing"), before, "nothing written by any refusal"); + assert.equal((await callPost(POST, { siteId: "citing", publishAuto: "build" }, {})).status, 401); +}); diff --git a/editor/app/api/ops/site-config/route.ts b/editor/app/api/ops/site-config/route.ts @@ -0,0 +1,108 @@ +import { existsSync } from "node:fs"; +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { + isValidSiteId, + patchSite, + siteConfigFile, + sitePublishPolicy, + type Site, +} from "yt-dlp-transcript-common/lib/site"; +import { PUBLISH_POLICIES, type PublishPolicy } from "yt-dlp-transcript-common/lib/settingsSchema"; +import { channelExists, isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; +import { OpsInputError, ops, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { +// siteId: string, +// citedChannels?: string[], // the WHOLE cited scope; [] clears it +// publishAuto?: "off" | "build" | "preview" | "production", +// } +// — at least one of the two. Only these keys for now (release 24 H6): a +// session sets a site's cited-only channels, or its publish policy, without +// the editor UI. +// +// THROUGH patchSite, so through writeSite: the same validation and the same +// on-disk shape the site form's save gets. A slug the pool already holds is +// dropped from `citedChannels`, as the parser drops it; a deploying policy +// (`preview`, `production`) on a site with no Pages project is refused; a +// private site's policy is clamped to `build`. The answer is what was saved. +// +// Every refusal is said before anything is written: an unknown key (ops()), +// an unknown site, a slug that is not a channel, a policy that is not one. +export async function POST(request: Request) { + return ops(request, ["siteId", "citedChannels", "publishAuto"], async (body) => { + const siteId = reqString(body, "siteId"); + if (!isValidSiteId(siteId)) { + throw new OpsInputError(`"${siteId}" is not a valid site id (lowercase letters, numbers and hyphens)`); + } + const cited = readCited(body.citedChannels); + const publishAuto = readPolicy(body.publishAuto); + if (cited === undefined && publishAuto === undefined) { + throw new OpsInputError('nothing to change — give "citedChannels" or "publishAuto"'); + } + const paths = getPaths(); + if (!existsSync(siteConfigFile(paths, siteId))) { + throw new OpsInputError(`Site "${siteId}" not found`); + } + if (cited !== undefined) { + const missing: string[] = []; + for (const slug of cited) { + if (!(await channelExists(paths, slug))) missing.push(slug); + } + if (missing.length > 0) { + throw new OpsInputError( + `not a channel: ${missing.map((s) => `"${s}"`).join(", ")} — "citedChannels" names channel slugs`, + ); + } + } + const changes: Partial<Omit<Site, "siteId">> = {}; + if (cited !== undefined) changes.citedChannels = cited.map((slug) => ({ slug })); + if (publishAuto !== undefined) { + changes.publish = publishAuto === "off" ? undefined : { auto: publishAuto }; + } + let saved: Site | null; + try { + saved = await patchSite(siteId, changes, paths); + } catch (err) { + // writeSite's refusals (a deploying policy with no Pages project) are + // the request's fault, said in its words. + throw new OpsInputError((err as Error).message); + } + if (!saved) throw new OpsInputError(`Site "${siteId}" not found`); + return NextResponse.json({ + ok: true, + siteId, + citedChannels: (saved.citedChannels ?? []).map((c) => c.slug), + publishAuto: sitePublishPolicy(saved), + }); + }); +} + +// `citedChannels`: absent, or an array of channel slugs (blank and repeated +// entries are the parser's to drop; anything else is refused here). +function readCited(raw: unknown): string[] | undefined { + if (raw === undefined) return undefined; + if (!Array.isArray(raw) || raw.some((s) => typeof s !== "string")) { + throw new OpsInputError('"citedChannels" must be an array of channel slugs'); + } + const slugs = [...new Set((raw as string[]).map((s) => s.trim()).filter(Boolean))]; + // A slug reaches a path.join under channelsDir: never one that traverses. + for (const slug of slugs) { + if (!isValidChannelSlug(slug)) { + throw new OpsInputError( + `"${slug}" is not a valid channel slug (letters, digits, ".", "_", "-"; must start with a letter or digit)`, + ); + } + } + return slugs; +} + +function readPolicy(raw: unknown): PublishPolicy | undefined { + if (raw === undefined) return undefined; + if (typeof raw !== "string" || !(PUBLISH_POLICIES as readonly string[]).includes(raw)) { + throw new OpsInputError(`"publishAuto" must be one of ${PUBLISH_POLICIES.join(", ")}`); + } + return raw as PublishPolicy; +} diff --git a/editor/app/lib/formState.test.ts b/editor/app/lib/formState.test.ts @@ -7,6 +7,7 @@ import { seedValue, type FormErrorState, type FormState, + seedAfterSave, } from "./formState"; // Run with: pnpm --filter editor test @@ -103,3 +104,16 @@ test("the channels flavour reads through the same helpers", () => { // An error with no values (an action that returns none) seeds from initial. assert.equal(seedValue({ error: "no" }, "name", "Stored"), "Stored"); }); + +test("seedAfterSave: a success that carries values seeds like a failure; anything else is the state as is", () => { + const values = { title: "Saved title", downloads: "on" }; + const seed = seedAfterSave({ ok: true, values }); + assert.equal(seedValue(seed, "title", "Old"), "Saved title"); + assert.equal(seedChecked(seed, "downloads", false), true); + assert.equal(seedChecked(seed, "archives", true), false, "absent from a saved submit is unticked"); + const ok = { ok: true }; + assert.equal(seedAfterSave(ok), ok); + const failed = { ok: false, error: "no", values }; + assert.equal(seedAfterSave(failed), failed); + assert.equal(seedAfterSave(undefined), undefined); +}); diff --git a/editor/app/lib/formState.ts b/editor/app/lib/formState.ts @@ -89,3 +89,20 @@ export function seedChecked( const values = failedValues(state); return values ? Object.hasOwn(values, name) : initial; } + +// A SAVE THAT DOES NOT REVALIDATE (release 24 H5). A server action that calls +// revalidatePath makes the router refresh the page as the action lands, and +// React commits the action's state WITH that refresh. Now and then the refresh +// did not settle until the next router update (the AutoRefresh tick, ~5 s), so +// "Saved." — and the form's reset — waited with it. The /sites forms therefore +// save without revalidating, hand back what was submitted, and refresh the +// page themselves once the state has landed (useRefreshAfterSave): the +// confirmation never waits on a page render, and the page still follows. +// +// `seedAfterSave` is the seed for such a form: after a success that carries +// `values`, the fields seed from what was saved — React's reset after the +// action then shows it, before the refresh brings the stored copy — and +// otherwise the state as it is (a failure's values, or nothing). +export function seedAfterSave(state: SeedSource): SeedSource { + return state && state.ok === true && state.values ? { values: state.values } : state; +} diff --git a/editor/app/lib/useRefreshAfterSave.ts b/editor/app/lib/useRefreshAfterSave.ts @@ -0,0 +1,15 @@ +"use client"; + +import { useEffect } from "react"; +import { useRouter } from "next/navigation"; + +// Refresh the page once a save's state has landed (lib/formState.ts +// seedAfterSave, release 24 H5): the save does not revalidate, so its +// confirmation commits on its own, and this brings the rest of the page — +// a heading, a list, a Publish row — up to date in a transition of its own. +export function useRefreshAfterSave(state: { ok?: boolean } | null | undefined): void { + const router = useRouter(); + useEffect(() => { + if (state && state.ok === true) router.refresh(); + }, [state, router]); +} diff --git a/editor/app/sites/actions.ts b/editor/app/sites/actions.ts @@ -1,7 +1,6 @@ "use server"; import { PUBLISH_POLICIES, type PublishPolicy } from "yt-dlp-transcript-common/lib/settingsSchema"; -import { revalidatePath } from "next/cache"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { parseAccent, @@ -31,13 +30,13 @@ import { } from "yt-dlp-transcript-common/lib/channelGroups"; import { migrateToSites } from "yt-dlp-transcript-common/controller/migrateToSites"; import { socialLinksForSave } from "yt-dlp-transcript-common/lib/socialLinks"; -import { formValues, type FormState } from "../lib/formState"; +import { formValues, type FormState, type FormValues } from "../lib/formState"; import { reportSiteKeysFromForm } from "./lib/reportSiteKeys"; import { citedChannelsFromForm } from "./lib/citedChannelsFromForm"; // A failure carries what was submitted, so SiteForm keeps what was typed // (lib/formState.ts). -export type SaveResult = FormState<{ siteId: string }>; +export type SaveResult = FormState<{ siteId: string; values: FormValues }>; export async function saveSiteAction( _prev: SaveResult | undefined, @@ -301,11 +300,13 @@ export async function saveSiteAction( values, }; } - revalidatePath("/sites"); - // "layout": the h1 above every tab reads siteTitle, and a literal path would - // revalidate only the settings page (revalidatePath.md). - revalidatePath("/sites/[siteId]", "layout"); - return { ok: true, siteId }; + // NO revalidatePath (release 24 H5): React commits a revalidating action's + // state with the router's refresh of the page, which now and then did not + // settle until the next AutoRefresh tick, so "Saved." came up to ~6 s late. + // SiteForm seeds from `values` and refreshes the page itself once "Saved." is + // in (lib/formState.ts seedAfterSave, lib/useRefreshAfterSave.ts) — the h1 + // above the tabs and /sites's list follow with that refresh. + return { ok: true, siteId, values }; } export type DeleteResult = { ok: true } | { ok: false; error: string }; @@ -318,7 +319,8 @@ export async function deleteSiteAction( } catch (err) { return { ok: false, error: err instanceof Error ? err.message : String(err) }; } - revalidatePath("/sites"); + // No revalidatePath: the button refreshes the page itself (release 24 H5, + // lib/formState.ts seedAfterSave says why). return { ok: true }; } @@ -328,7 +330,7 @@ export async function migrateToSitesAction(): Promise<DeleteResult> { } catch (err) { return { ok: false, error: err instanceof Error ? err.message : String(err) }; } - revalidatePath("/sites"); - revalidatePath("/settings"); + // No revalidatePath: the button refreshes the page itself (release 24 H5). + // /settings is dynamic, rendered afresh on the next visit. return { ok: true }; } diff --git a/editor/app/sites/components/HomepageConfigForm.tsx b/editor/app/sites/components/HomepageConfigForm.tsx @@ -4,7 +4,8 @@ import { useActionState } from "react"; import type { HomepageConfig } from "yt-dlp-transcript-common/lib/homepage"; import { saveHomepageConfigAction, type SaveResult } from "../lib/homepageActions"; import { SeededInput } from "../../components/forms/Field"; -import { seedChecked } from "../../lib/formState"; +import { seedAfterSave, seedChecked } from "../../lib/formState"; +import { useRefreshAfterSave } from "../../lib/useRefreshAfterSave"; const input = "rounded-md border border-border bg-card px-3 py-1.5 text-sm"; @@ -15,13 +16,17 @@ export function HomepageConfigForm({ config }: { config: HomepageConfig }) { SaveResult | undefined, FormData >(saveHomepageConfigAction, undefined); + // The save does not revalidate /sites (lib/formState.ts seedAfterSave): the + // fields seed from what it saved, and the page refreshes once it has landed. + const seed = seedAfterSave(state); + useRefreshAfterSave(state); return ( <form action={formAction} className="flex flex-col gap-3 max-w-xl"> <label className={label}> Site title <SeededInput - state={state} + state={seed} className={input} name="siteTitle" initial={config.siteTitle} @@ -30,7 +35,7 @@ export function HomepageConfigForm({ config }: { config: HomepageConfig }) { <label className={label}> Header title <SeededInput - state={state} + state={seed} className={input} name="headerTitle" initial={config.headerTitle} @@ -39,7 +44,7 @@ export function HomepageConfigForm({ config }: { config: HomepageConfig }) { <label className={label}> Description <SeededInput - state={state} + state={seed} className={input} name="siteDescription" initial={config.siteDescription} @@ -48,7 +53,7 @@ export function HomepageConfigForm({ config }: { config: HomepageConfig }) { <label className={label}> Home tagline <SeededInput - state={state} + state={seed} className={input} name="homeTagline" initial={config.homeTagline} @@ -57,7 +62,7 @@ export function HomepageConfigForm({ config }: { config: HomepageConfig }) { <label className={label}> Public URL <SeededInput - state={state} + state={seed} className={input} name="siteUrl" placeholder="https://archilyzer-hub.pages.dev" @@ -67,7 +72,7 @@ export function HomepageConfigForm({ config }: { config: HomepageConfig }) { <label className={label}> Cloudflare Pages project <SeededInput - state={state} + state={seed} className={input} name="cloudflareProject" placeholder="archilyzer-hub" @@ -79,7 +84,7 @@ export function HomepageConfigForm({ config }: { config: HomepageConfig }) { type="checkbox" name="transcriptDownloads" defaultChecked={seedChecked( - state, + seed, "transcriptDownloads", config.transcriptDownloads !== false, )} diff --git a/editor/app/sites/components/SiteForm.tsx b/editor/app/sites/components/SiteForm.tsx @@ -22,7 +22,8 @@ import { ControlledCheck, ControlledSelect, } from "../../components/forms/Controlled"; -import { seedChecked } from "../../lib/formState"; +import { seedAfterSave, seedChecked } from "../../lib/formState"; +import { useRefreshAfterSave } from "../../lib/useRefreshAfterSave"; export type ChannelOption = { slug: string; name: string }; export type SiteOption = { siteId: string; siteTitle: string }; @@ -63,6 +64,10 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { saveSiteAction, undefined, ); + // The save does not revalidate (lib/formState.ts seedAfterSave): the fields + // seed from what it saved, and the page refreshes once it has landed. + const seed = seedAfterSave(state); + useRefreshAfterSave(state); const [groups, setGroups] = useState<GroupRow[]>(() => initial.groups.map(toGroupRow), ); @@ -235,7 +240,7 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { {isNew ? ( <Field label="Site ID" - state={state} + state={seed} name="siteId" defaultValue={initial.siteId} required @@ -252,34 +257,34 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { )} <Field label="Site title" - state={state} + state={seed} name="siteTitle" defaultValue={initial.siteTitle} required /> <Field label="Header title" - state={state} + state={seed} name="headerTitle" defaultValue={initial.headerTitle} required /> <Field label="Wordmark lead" - state={state} + state={seed} name="wordmarkLead" defaultValue={initial.wordmarkLead ?? ""} hint={'The heavy start of the wordmark — the subject\'s name, e.g. "Jer" for Jeralyzer; the rest is set light. It must be how the header text begins (same case) and shorter than it. Leave blank to set the whole name heavy.'} /> <Field label="Site description" - state={state} + state={seed} name="siteDescription" defaultValue={initial.siteDescription} /> <Field label="Home tagline" - state={state} + state={seed} name="homeTagline" defaultValue={initial.homeTagline} /> @@ -350,14 +355,14 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { </fieldset> <Field label="Cloudflare Pages project" - state={state} + state={seed} name="cloudflareProject" defaultValue={initial.cloudflareProject ?? ""} hint="Project name this site deploys to (wrangler --project-name). Leave blank to set later." /> <Field label="Public URL" - state={state} + state={seed} name="siteUrl" defaultValue={initial.siteUrl ?? ""} hint="Absolute URL this site is served at (e.g. https://jeralyzer.com). Used so other sites can link to it in their footer. Leave blank to omit this site from cross-site lists." @@ -365,7 +370,7 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { <label className="flex flex-col gap-1 text-sm"> <span className="font-medium">Audience</span> <SeededSelect - state={state} + state={seed} name="audience" aria-label="Audience" initial={initial.audience === "private" ? "private" : "public"} @@ -384,7 +389,7 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { <label className="flex flex-col gap-1 text-sm"> <span className="font-medium">Publish policy</span> <SeededSelect - state={state} + state={seed} name="publishAuto" aria-label="Publish policy" initial={initial.publish?.auto ?? "off"} @@ -405,7 +410,7 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { <input type="checkbox" name="search" - defaultChecked={seedChecked(state, "search", initial.search !== false)} + defaultChecked={seedChecked(seed, "search", initial.search !== false)} className="accent-brand" /> Search @@ -447,7 +452,7 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { type="checkbox" name="listed" defaultChecked={seedChecked( - state, + seed, "listed", initial.listed !== false, )} @@ -464,7 +469,7 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { </p> <Field label="Hub URL" - state={state} + state={seed} name="hubUrl" defaultValue={initial.hubUrl ?? ""} hint="The hub this site belongs under (e.g. https://archilyzer-hub.pages.dev), published in this site's /site.json and /corpus.json so the hub can tell it is a member; the header does not link to it. Leave blank to inherit the family default from Settings." @@ -473,7 +478,7 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { <input type="checkbox" name="pwa" - defaultChecked={seedChecked(state, "pwa", initial.pwa === true)} + defaultChecked={seedChecked(seed, "pwa", initial.pwa === true)} className="accent-brand" /> Ship as an installable PWA @@ -489,7 +494,7 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { type="checkbox" name="archives" defaultChecked={seedChecked( - state, + seed, "archives", initial.archives !== false, )} @@ -504,7 +509,7 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { </p> <Field label="Archive size cap (MB)" - state={state} + state={seed} name="archiveMaxMB" type="number" min="0" @@ -520,7 +525,7 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { type="checkbox" name="transcriptDownloads" defaultChecked={seedChecked( - state, + seed, "transcriptDownloads", initial.transcriptDownloads !== false, )} @@ -540,7 +545,7 @@ export function SiteForm({ initial, channels, allSites, isNew }: Props) { type="checkbox" name="duplicates" defaultChecked={seedChecked( - state, + seed, "duplicates", initial.duplicates !== false, )} diff --git a/editor/app/sites/components/SiteListActions.tsx b/editor/app/sites/components/SiteListActions.tsx @@ -1,9 +1,13 @@ "use client"; import { useState, useTransition } from "react"; +import { useRouter } from "next/navigation"; import { deleteSiteAction, migrateToSitesAction } from "../actions"; +// Both actions save without revalidating and refresh the page here (release 24 +// H5, lib/formState.ts seedAfterSave says why). export function DeleteSiteButton({ siteId }: { siteId: string }) { + const router = useRouter(); const [pending, start] = useTransition(); const [error, setError] = useState<string | null>(null); return ( @@ -16,6 +20,7 @@ export function DeleteSiteButton({ siteId }: { siteId: string }) { start(async () => { const res = await deleteSiteAction(siteId); if (!res.ok) setError(res.error); + else router.refresh(); }); }} className="px-2 py-1 rounded border border-destructive/30 text-xs text-destructive disabled:opacity-50" @@ -28,6 +33,7 @@ export function DeleteSiteButton({ siteId }: { siteId: string }) { } export function MigrateButton() { + const router = useRouter(); const [pending, start] = useTransition(); const [error, setError] = useState<string | null>(null); return ( @@ -39,6 +45,7 @@ export function MigrateButton() { start(async () => { const res = await migrateToSitesAction(); if (!res.ok) setError(res.error); + else router.refresh(); }) } className="px-3 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50" diff --git a/editor/app/sites/lib/homepageActions.ts b/editor/app/sites/lib/homepageActions.ts @@ -1,6 +1,5 @@ "use server"; -import { revalidatePath } from "next/cache"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getHomepageConfig, @@ -8,10 +7,12 @@ import { parseHomepageUrl, type HomepageConfig, } from "yt-dlp-transcript-common/lib/homepage"; -import { formValues, type FormState } from "../../lib/formState"; +import { formValues, type FormState, type FormValues } from "../../lib/formState"; -// A failure carries what was submitted (lib/formState.ts). -export type SaveResult = FormState; +// A failure carries what was submitted (lib/formState.ts), and so does a +// success: the save does not revalidate, and the form seeds from it +// (seedAfterSave) and refreshes the page itself (release 24 H5). +export type SaveResult = FormState<{ values: FormValues }>; // Branding/config for the hub landing site. The hub is a single cross-site // landing page (no authored Markdown pages), so this is the only homepage action. @@ -62,6 +63,5 @@ export async function saveHomepageConfigAction( values, }; } - revalidatePath("/sites"); - return { ok: true }; + return { ok: true, values }; } diff --git a/editor/e2e/sites-crud.spec.ts b/editor/e2e/sites-crud.spec.ts @@ -528,6 +528,47 @@ test("the hub form's per-video transcript downloads opt-out round-trips to homep await expect(downloads).toBeChecked(); }); +// Release 24 H5: the hub form's "Saved." never waits for a refresh of /sites. +// Its save used to revalidate the page, and now and then the router's refresh +// as the action landed did not settle until the next AutoRefresh tick, ~5 s +// later — the flake above. Every non-prefetch read of /sites is held here for +// 6 s: a save that waited on one would miss the default 5 s. After each save the +// fields show what was saved (React resets the form when the action lands). +test("the hub form's Saved. does not wait for /sites to refresh, and the fields keep what was saved", async ({ + page, +}) => { + await resetData("empty"); + await page.route(/\/sites\?_rsc=/, async (route) => { + if (!route.request().headers()["next-router-prefetch"]) { + await new Promise((r) => setTimeout(r, 6_000)); + } + await route.continue().catch(() => {}); + }); + const form = page + .locator("form") + .filter({ has: page.getByRole("button", { name: "Save config" }) }); + const downloads = form.getByRole("checkbox", { name: /per-video transcript downloads/i }); + const tagline = form.getByRole("textbox", { name: "Home tagline" }); + for (const [checked, text] of [ + [false, "First tagline"], + [true, "Second tagline"], + ] as const) { + await page.goto("/sites"); + await downloads.setChecked(checked); + await tagline.fill(text); + await form.getByRole("button", { name: "Save config" }).click(); + await expect(form.getByText("Saved.")).toBeVisible(); + if (checked) await expect(downloads).toBeChecked(); + else await expect(downloads).not.toBeChecked(); + await expect(tagline).toHaveValue(text); + } + const hub = await readJson<{ homeTagline?: string; transcriptDownloads?: boolean }>( + "test-transcripts/sites/_homepage/homepage.json", + ); + expect(hub.homeTagline).toBe("Second tagline"); + expect("transcriptDownloads" in hub).toBe(false); +}); + test("first-run migrate button appears only when no sites exist", async ({ page, }) => { diff --git a/plans/release-24.md b/plans/release-24.md @@ -111,6 +111,71 @@ was forced with an untracked copy of `mix.spec.ts` that sorts first (`a-mix-firs After the first run `testchan/vid1/clips/0.00-14.00.mp4`, clip-bench's editor-stub window, was back on disk: mix had set it aside and restored it. +### H5, as shipped — `sites-crud.spec.ts:491`, the hub form's "Saved." (added by the orchestrator) + +**The race.** In the production build, a server action that calls `revalidatePath` makes the router refresh the page +as the action lands. React commits the action's `useActionState` state together with that refresh. Now and then the +refresh did not settle until the next router update, which is AutoRefresh's tick about 5 s after the page loaded, so +"Saved." (and the button's "Saving…") waited with it. + +Measured with an untracked diagnostic spec. Across about 140 hub saves (start mode), the click was always hydrated +(not a pre-hydration native POST), the action's POST answered in about 15 ms with its body complete, and "Saved." took +about 110 ms. Five saves took 4.9–5.9 s, each ending just after a lone `/sites` RSC refresh. Without `revalidatePath`: +0 slow in 18. With it, the control run had 1 slow in 18. The status of the previous save was not the cause: each save +in the spec follows a fresh `goto`. + +A first suspicion was wrong: the sidebar prefetching `/sites` while on `/sites`. With that prefetch switched off, the +stall still happened. The same stall hit SiteForm's saves (`:53` and `:588`) and the delete button (`:126`) in this +file's own gate runs. + +**The fix** applies to the four `/sites` writers this spec drives. Each one saves without revalidating and refreshes +the page itself once its result has landed, so the confirmation never waits on a page render: + +- **The hub form** (`saveHomepageConfigAction`). +- **The site form** (`saveSiteAction`). +- **Delete and migrate** (`deleteSiteAction`, `migrateToSitesAction`). +- **What the forms do:** + - A success hands back what was submitted (`values`), and the form seeds from it (`seedAfterSave`, + `lib/formState.ts`). React's form reset after the action therefore shows what was saved. + - `useRefreshAfterSave` (`lib/useRefreshAfterSave.ts`) calls `router.refresh()` once the state is in, so the h1 + above a site's tabs, the `/sites` list and the Publish rows follow. +- **What delete and migrate do:** they call `router.refresh()` after their result. +- **New test:** sites-crud holds every non-prefetch `/sites` RSC read for 6 s. It still expects "Saved." within the + default 5 s, and the fields to show what was saved. `formState.test.ts` +1 covers `seedAfterSave`. + +**Found and left.** +- Every other editor action that calls `revalidatePath` keeps the same exposure: the publish actions, the reports + actions, release cuts, settings, and the channel and job actions. This release changes only the four writers above. +- AutoRefresh refreshes every page about 5 s after it loads. The pulse's first poll counts as a change (`revCounter` + 0 → 1). It is what ended each stall above, and it is a full server render per page load that its own comment says + should not happen. +- The underlying Next.js behaviour (16.2.3: the post-action navigation not settling) was not traced further than the + reducer: `server-action-reducer.js` resolves the action early, and React holds the state for the entangled + navigation. + +### H6, as shipped — `pnpm ops site-config` (added by the orchestrator) + +`POST /api/ops/site-config` (`editor/app/api/ops/site-config/route.ts`, behind the worker token through `ops()`, like +`channel-config`) and the ops action `site-config`. The body is `{"siteId", "citedChannels"?: [slug…], "publishAuto"?: +"off" | "build" | "preview" | "production"}` and needs at least one of the two. Only those keys for now. + +- **Written through `patchSite`** (`common/lib/site.ts`), so through `writeSite`, the validation the site form's save + gets: + - A slug the pool already holds is dropped from `citedChannels` (`siteToDisk` re-parses). + - `[]` clears the scope; the key is not written. + - A deploying policy on a site with no `cloudflareProject` is refused in `sitePublishProblem`'s words. + - A private site's policy is clamped to `build`. + - `"off"` removes the `publish` key. +- **Refused before anything is written**, each as a 400 naming the problem: + - an unknown key (the allow-list); + - an invalid or unknown site id; + - a slug that is not a valid channel slug, or not a channel (`channelExists`); + - a policy outside the four; + - a body with neither key. +- **Answer:** `{ok, siteId, citedChannels, publishAuto}`, as saved. +- **Docs:** the CLI's `usage()` paragraph and two header examples. COMMANDS.md is regenerated (`archilyzer docs cli`; + `--check` clean). OPERATING.md "Publish" gains the recipe line, and the editor changelog gains a bullet. + ### Commits | Commit | What | @@ -119,7 +184,11 @@ set it aside and restored it. | `60cea572` | `common, umtool:` H2 — `deps.freeBytes` in attachMedia/preparePlayable and their tests; `sources.test.mjs` through `tildify` | | `198d4a8f` | `common:` H3 — `keepProvenanceFields` / `keepProvenanceInFile` in the history wrap | | — | H4: no commit (release 19 B5 `10042c2d` fixed it; verified above) | -| this commit | `plans:` this record; `editor/CHANGELOG.md` (two bullets at the start of `[Unreleased]`) | +| `c2840cf1` | `plans:` this record; `editor/CHANGELOG.md` (two bullets at the start of `[Unreleased]`) | +| `0e887173` | `editor:` H5 — the four `/sites` writers save without revalidating (`seedAfterSave`, `useRefreshAfterSave`); the sites-crud test; a changelog bullet | +| `3cb4ad5f` | `plans:` the H5 record | +| `d81b8aff` | `editor, scripts:` H6 — `POST /api/ops/site-config` + test, the ops action, COMMANDS.md, OPERATING.md, the changelog | +| this commit | `plans:` the H6 record | ### Gates @@ -134,4 +203,10 @@ set it aside and restored it. | export unit | 118/118 | | umtool e2e `clip-bench.spec.ts mix.spec.ts` (`E2E_MODE=dev`) | 62 passed, 2.7 min (clip-bench first) | | umtool e2e, mix first (`a-mix-first.spec.ts` + `clip-bench.spec.ts`) | 62 passed, 2.4 min | +| H5: tsc; editor unit | clean; 247/247 (+1) | +| H5: `pnpm e2e sites-crud.spec.ts --repeat-each=3` (start mode) before the fix | 53 passed, 4 failed (a first, wrong fix); then 56 + 1 failed (`:588`); then 56 + 1 failed (`:126`): the same stall each time | +| H5: the same, after `0e887173` | 57/57 (58.6 s), and again 57/57 (55.3 s) | +| H5: the untracked diagnostic spec, 30 hub saves on the fixed build | 30 under 400 ms (before: 1 in 18 at ~5.9 s) | +| H6: `site-config/route.test.ts` | 3/3. Covered: setting the cited scope, dropping a pooled slug, deduping and clearing with `[]`; `publishAuto` round-tripping all four policies; a deploying policy with no Pages project refused, nothing written; a private site clamped to build; both keys in one call; ten refusals with nothing written; 401 without the token | +| H6: tsc; editor unit; `node --test scripts/archilyzer-ops.test.mjs`; `docs cli --check` | clean; 250/250; 63/63; clean | | counts-only privacy greps over `72c44159..` (home paths, the operator's names and email, session links and trailers) | 0 each | diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -51,6 +51,8 @@ // pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}' // pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}' // pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}' +// pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}' +// pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}' // pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}' // pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}' // pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}' @@ -233,6 +235,9 @@ export const JOB_VERBS = [ const ACTIONS = [ "channel-priority", "channel-config", + // A site's cited-only channels and its publish policy ({siteId, + // citedChannels?, publishAuto?}), through the site form's own writer. + "site-config", // The channel's lifecycle: the New channel form, and the channel page's // Danger → Rename and Danger → Delete. Synchronous; no job. "create-channel", @@ -866,6 +871,15 @@ export function usage() { ' recorded date: "patch": {"recordedDateTitlePattern": "<regex with named', ' groups year, month, day>"} (CHANNEL.md, recordedDate).', "", + 'site-config sets two keys of a site as its form does: {"siteId"} and any of', + ' "citedChannels" (the WHOLE cited scope, channel slugs: what the site\'s', + ' reports may cite without publishing the channel; [] clears it; a slug the', + ' pool holds is dropped) and "publishAuto" ("off" | "build" | "preview" |', + ' "production", the publish lane\'s policy; a deploying one needs a Pages', + ' project, a private site is clamped to "build"). Only those two keys; an', + ' unknown site or channel is refused before anything is written. Answers', + ' the saved values.', + "", 'create-channel is the New channel form: {"fields": {"name", "handling":', ' "youtube"|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?,', ' "socialHandle"?, …}} with channel-config\'s patch keys; "slug"? (else',