commit 85743dfc39ffc9f6a0b949f6e9e3a2d54fd09e66 parent 15e109ea96cb7f0cdd092d9ee6ea6fd53782ba92 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Thu, 15 Oct 2026 10:41:26 -0400 Merge r29/gen-debts review fixes (G2, site picker) into r29/integration Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
27 files changed, 510 insertions(+), 114 deletions(-)
diff --git a/common/lib/report/draft/tasks/social.test.ts b/common/lib/report/draft/tasks/social.test.ts @@ -14,7 +14,7 @@ import path from "node:path"; import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; import { PROJECT_URL } from "../../../project"; import { createIteration, projectOf, updateIteration, writeIterationFile } from "../../iterations"; -import { blueskyLength, graphemes, SOCIAL_LIMITS, socialLinkOf, validateSocialPost, withLink, xLength } from "../../social.mjs"; +import { blueskyLength, graphemes, hasLink, SOCIAL_LIMITS, socialLinkOf, validateSocialPost, withLink, xLength } from "../../social.mjs"; import { groundingInputOf } from "../grounding"; import type { DraftFile } from "./media"; import { postBudget, postProblems, social, socialSystem } from "./social"; @@ -43,6 +43,14 @@ test("X weighs a URL as 23 whatever its length, an emoji as 2, a CJK character a assert.equal(xLength("๐"), 2); assert.equal(xLength("๐ฉโ๐ฉโ๐งโ๐ฆ"), 2, "a family is one emoji"); assert.equal(xLength("ๆฅๆฌ"), 4); + // A bare domain is a link to X too (review fix): "Kick.com" is 23, not 8. + assert.equal(xLength("Kai streamed on Kick.com"), 16 + 23); + assert.equal(xLength("jeralyzer.pages.dev/pages/a"), 23); + assert.ok(hasLink("on Kick.com") && hasLink("x.co") && !hasLink("e.g. this, i.e. that, No. 5, 3.5 million, a@b.com")); + // 270 characters and two bare domains are 318 as X counts them, not 280. + const two = `${"a".repeat(270)} x.co x.co`; + assert.equal(xLength(two), 318); + assert.deepEqual(validateSocialPost("x", { post: two }), ["publish.x.post is 318 characters as X counts them (at most 280)"]); // Three long links and the text between them: 205 + 3 ร (1 + 23) + 3 = 280, at the limit. const link = (i: number) => `https://archive.example/moment/${"x".repeat(60)}/${i}`; const text = `${"a".repeat(205)} ${link(1)} ${link(2)} ${link(3)} bb`; @@ -91,6 +99,7 @@ test("the checks: third person, grounded, quotes only verbatim, no link, hashtag assert.match(hard('The baker says "I will sell the bakery" now.'), /is not what a cited clip says, word for word/); assert.match(hard("Synth Kitchen's baker on the bakery: https://synth.example"), /no links, timestamps, hashtags or @mentions/); assert.match(hard("Synth Kitchen's baker on the bakery #bread"), /no links, timestamps, hashtags or @mentions/); + assert.match(hard("Synth Kitchen's baker streams on Kick.com"), /no links, timestamps, hashtags or @mentions/); assert.match(hard("Synth Kitchen's baker on the bakery @synthkitchen"), /no links, timestamps, hashtags or @mentions/); assert.match(hard("Synth Kitchen's baker on the bakery ๐"), /no emoji/); // 255 characters fit beside the link; 256 do not. @@ -188,6 +197,20 @@ test("the link appended by code: a public article's page on the homepage, else t assert.ok((await vid.manifestNow()).publish.x.post.endsWith("\n\nhttps://video.example/watch/1")); }); +test("a post wrapped whole in quotation marks loses them; a quote that opens or ends a post is kept verbatim", async () => { + const p = await project(); + ol.push( + jsonReply({ post: '"Synth Kitchen\'s baker says she paid for the new mixer herself."', thread: ['Synth Kitchen\'s baker says, "I paid for the new mixer myself"'] }), + jsonReply({ post: '"I would never sell the bakery to a chain," says the baker of Synth Kitchen.', thread: [] }), + ); + const res = await social(p.input, p.deps); + assert.equal(res.status, "done", res.summary); + const m = await p.manifestNow(); + assert.equal(m.publish.x.post, "Synth Kitchen's baker says she paid for the new mixer herself."); + assert.deepEqual(m.publish.x.thread, ['Synth Kitchen\'s baker says, "I paid for the new mixer myself"']); + assert.equal(m.publish.bluesky.post, '"I would never sell the bakery to a chain," says the baker of Synth Kitchen.'); +}); + test("a post over its count with its link is trimmed at a sentence; a failing thread post dropped; five thread posts refused, then cut to four", async () => { const p = await project({ publicArticle: true }); const long = "Synth Kitchen's baker says she would not sell the bakery to a chain.".padEnd(240, " ") + " She says she paid for the new mixer herself."; diff --git a/common/lib/report/draft/tasks/social.ts b/common/lib/report/draft/tasks/social.ts @@ -27,7 +27,7 @@ import { PROJECT_URL } from "../../../project"; import { readArticleState } from "../../registry"; import { ARTICLES_REPORTS_BASE } from "../../routes"; -import { SOCIAL_LIMITS, SOCIAL_NAMES, socialLength, socialLinkOf, withLink, type SocialPlatform, type SocialPost } from "../../social.mjs"; +import { SOCIAL_LIMITS, SOCIAL_NAMES, hasLink, socialLength, socialLinkOf, withLink, type SocialPlatform, type SocialPost } from "../../social.mjs"; import { reportPagePath } from "../../views"; import { sentencesOf, type GroundingInput } from "../grounding"; import { checkLine } from "./clipEvidence"; @@ -42,8 +42,10 @@ export type SocialValue = { post: string; thread: string[] }; type SocialUnit = MediaUnit & { platform: SocialPlatform; link: string | null; g: GroundingInput; evidence: string }; const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim(); -// What the model may not write: a link, a timestamp, a hashtag, an @mention. -const NOT_WRITTEN = /https?:\/\/|www\.|\b\d{1,2}:\d{2}\b|(^|\s)#\w|(^|\s)@\w/; +// What the model may not write: a link (a scheme, www. or a bare domain X +// would link: social.mjs hasLink), a timestamp, a hashtag, an @mention. +const NOT_WRITTEN = /\b\d{1,2}:\d{2}\b|(^|\s)#\w|(^|\s)@\w/; +const notWritten = (text: string) => hasLink(text) || NOT_WRITTEN.test(text); const EMOJI = /\p{Extended_Pictographic}/u; /** Room the link takes under the first post (its blank line included). */ @@ -63,7 +65,7 @@ export function postProblems(text: string, u: Pick<SocialUnit, "platform" | "lin const limit = SOCIAL_LIMITS[u.platform]; const n = socialLength(u.platform, first ? withLink(text, u.link) : text); if (n > limit) hard.push(`${where} is ${n} ${u.platform === "bluesky" ? "graphemes" : "characters as X counts them"}${first && u.link ? " with its link" : ""} (at most ${limit})`); - if (NOT_WRITTEN.test(text)) hard.push(`${where}: no links, timestamps, hashtags or @mentions โ the link is added after it`); + if (notWritten(text)) hard.push(`${where}: no links, timestamps, hashtags or @mentions โ the link is added after it`); if (EMOJI.test(text)) hard.push(`${where}: no emoji`); const r = text ? checkLine(text, u.g, { quotes: true }) : { hard: [], soft: [] }; return { hard: [...hard, ...r.hard.map((h) => `${where}: ${h}`)], soft: r.soft.map((s) => `${where}: ${s}`) }; @@ -145,7 +147,13 @@ export const SOCIAL_SPEC: MediaTaskSpec<SocialUnit, SocialValue, SocialInput> = user: (u) => `${u.evidence}\n\nWrite the ${SOCIAL_NAMES[u.platform]} post and its thread.`, parse(answer) { const a = answer as { post?: unknown; thread?: unknown } | null; - const clean = (s: unknown) => oneLine(s).replace(/^["โ]+|["โ]+$/g, ""); + // A post the model wrapped whole in quotation marks loses them; a quote + // inside the post (or one that opens or ends it) is the speaker's, kept. + const clean = (s: unknown) => { + const t = oneLine(s); + const m = /^["โ]([^"โโ]*)["โ]$/.exec(t); + return m ? m[1]!.trim() : t; + }; return { post: clean(a?.post), thread: (Array.isArray(a?.thread) ? a.thread : []).map(clean).filter(Boolean), diff --git a/common/lib/report/drafted.d.mts b/common/lib/report/drafted.d.mts @@ -48,3 +48,4 @@ export function pruneDrafted(manifest: unknown): string[]; export function clearEditedDrafts(before: unknown, after: unknown): { entry: string | null; field: string }[]; export function validateDrafted(manifest: unknown): string[]; export function validatePublish(manifest: unknown): string[]; +export function publishWarnings(manifest: unknown, o?: { only?: "x" | "bluesky" | "videoUrl" }): string[]; diff --git a/common/lib/report/drafted.mjs b/common/lib/report/drafted.mjs @@ -512,11 +512,12 @@ export function validateDrafted(manifest) { /** * `publish` (release 28; release 29 G2): what is published beside the video. - * `publish.youtube { title, description }`, two strings (M6 fills it); - * `publish.x` and `publish.bluesky` `{ post, thread? }` (the social task's: - * each post within its platform's count, ./social.mjs); `publish.videoUrl`, - * the video's public URL once it is up (the operator's: what a social post - * links, else the article's page). + * `publish.youtube { title, description }`, two strings (M6 fills it); its + * problems, and a key `publish` does not know, are ERRORS (the build refuses, + * as since release 28). `publish.x`, `publish.bluesky` `{ post, thread? }` and + * `publish.videoUrl` are not the video's: their problems are WARNINGS + * (`publishWarnings`), so a hand-edited post past its count never stops a + * build or an edit of the cut (review fix, release 29). * * @param {any} manifest * @returns {string[]} @@ -527,10 +528,6 @@ export function validatePublish(manifest) { if (!isObj(p)) return ["publish must be an object ({ youtube, x, bluesky, videoUrl })"]; const errors = []; for (const k of Object.keys(p)) if (!PUBLISH_KEYS.includes(k) && k !== "drafted") errors.push(`publish.${k} is not a publish key (${PUBLISH_KEYS.join(", ")})`); - if (p.videoUrl !== undefined && !(typeof p.videoUrl === "string" && /^https?:\/\/\S+$/i.test(p.videoUrl.trim()))) { - errors.push("publish.videoUrl must be the video's http(s) URL"); - } - for (const k of SOCIAL_PLATFORMS) if (p[k] !== undefined) errors.push(...validateSocialPost(k, p[k]).filter((e) => !e.endsWith(".drafted: the mark goes in the top-level drafted map"))); const y = p.youtube; if (y === undefined) return errors; if (!isObj(y)) return [...errors, "publish.youtube must be { title, description }"]; @@ -545,3 +542,27 @@ export function validatePublish(manifest) { if (typeof y.title === "string" && /[\r\n]/.test(y.title)) errors.push("publish.youtube.title must be one line"); return errors; } + +/** + * The social posts' and the video URL's problems (release 29 G2), as + * warnings: `publish.x` / `publish.bluesky` within their platform's count + * (./social.mjs), `publish.videoUrl` an http(s) URL. `only` limits them to one + * key (the field's own writer refuses on these). + * + * @param {any} manifest + * @param {{ only?: "x" | "bluesky" | "videoUrl" }} [o] + * @returns {string[]} + */ +export function publishWarnings(manifest, { only } = {}) { + const p = manifest?.publish; + if (!isObj(p)) return []; + const out = []; + if ((!only || only === "videoUrl") && p.videoUrl !== undefined && !(typeof p.videoUrl === "string" && /^https?:\/\/\S+$/i.test(p.videoUrl.trim()))) { + out.push("publish.videoUrl must be the video's http(s) URL"); + } + for (const k of SOCIAL_PLATFORMS) { + if (only && only !== k) continue; + if (p[k] !== undefined) out.push(...validateSocialPost(k, p[k]).filter((e) => !e.endsWith(".drafted: the mark goes in the top-level drafted map"))); + } + return out; +} diff --git a/common/lib/report/drafted.test.ts b/common/lib/report/drafted.test.ts @@ -18,6 +18,7 @@ import { pruneDrafted, reviewAddress, validateDrafted, + publishWarnings, validatePublish, } from "./drafted.mjs"; @@ -165,21 +166,28 @@ test("validatePublish: publish.youtube is two strings, YouTube's limits; nothing assert.deepEqual(validatePublish({ publish: [] }), ["publish must be an object ({ youtube, x, bluesky, videoUrl })"]); }); -test("validatePublish (release 29 G2): the social posts within their platform's count, a thread of at most 4, the video's URL", () => { +test("publishWarnings (release 29 G2): the social posts within their platform's count, a thread of at most 4, the video's URL โ warnings, never validatePublish's errors", () => { const link = "https://archilyzer.example/articles/synth-basic/"; - assert.deepEqual(validatePublish({ publish: { x: { post: `A post.\n\n${link}` }, bluesky: { post: "A post.", thread: ["Two.", "Three."] }, videoUrl: "https://video.example/v/1" } }), []); + const fine = { publish: { x: { post: `A post.\n\n${link}` }, bluesky: { post: "A post.", thread: ["Two.", "Three."] }, videoUrl: "https://video.example/v/1" } }; + assert.deepEqual(publishWarnings(fine), []); + assert.deepEqual(validatePublish(fine), []); // X: a URL weighs 23 whatever its length, so 255 characters and a long link is 280. - assert.deepEqual(validatePublish({ publish: { x: { post: `${"a".repeat(255)}\n\n${link}${"z".repeat(80)}` } } }), []); - assert.deepEqual(validatePublish({ publish: { x: { post: `${"a".repeat(256)}\n\n${link}` } } }), ["publish.x.post is 281 characters as X counts them (at most 280)"]); + assert.deepEqual(publishWarnings({ publish: { x: { post: `${"a".repeat(255)}\n\n${link}${"z".repeat(80)}` } } }), []); + const long = { publish: { x: { post: `${"a".repeat(256)}\n\n${link}` } } }; + assert.deepEqual(publishWarnings(long), ["publish.x.post is 281 characters as X counts them (at most 280)"]); + assert.deepEqual(validatePublish(long), [], "a post past its count does not refuse the build"); // Bluesky counts graphemes: 300 flags are 300, not 600 code points. - assert.deepEqual(validatePublish({ publish: { bluesky: { post: "๐ซ๐ท".repeat(300) } } }), []); - assert.deepEqual(validatePublish({ publish: { bluesky: { post: "๐ซ๐ท".repeat(301) } } }), ["publish.bluesky.post is 301 graphemes (at most 300)"]); - assert.deepEqual(validatePublish({ publish: { x: { post: "", thread: ["a", "b", "c", "d", "e"], tags: 1 }, videoUrl: "video" } }), [ + assert.deepEqual(publishWarnings({ publish: { bluesky: { post: "๐ซ๐ท".repeat(300) } } }), []); + assert.deepEqual(publishWarnings({ publish: { bluesky: { post: "๐ซ๐ท".repeat(301) } } }), ["publish.bluesky.post is 301 graphemes (at most 300)"]); + const bad = { publish: { x: { post: "", thread: ["a", "b", "c", "d", "e"], tags: 1 }, videoUrl: "video" } }; + assert.deepEqual(publishWarnings(bad), [ "publish.videoUrl must be the video's http(s) URL", "publish.x.tags is not a social post field (post, thread)", "publish.x.post must be a post (a string)", "publish.x.thread has 5 posts (at most 4)", ]); + assert.deepEqual(publishWarnings(bad, { only: "videoUrl" }), ["publish.videoUrl must be the video's http(s) URL"]); + assert.deepEqual(validatePublish(bad), []); }); test("review addresses and keys: one address per field, a key that moves with the value", () => { diff --git a/common/lib/report/social.d.mts b/common/lib/report/social.d.mts @@ -9,6 +9,8 @@ export const SOCIAL_PLATFORMS: readonly SocialPlatform[]; export const SOCIAL_LIMITS: Readonly<{ x: number; bluesky: number; thread: number; urlWeight: number }>; export const SOCIAL_NAMES: Readonly<Record<SocialPlatform, string>>; export const SOCIAL_URL_RE: RegExp; +export const SOCIAL_TLDS: readonly string[]; +export function hasLink(text: unknown): boolean; export function graphemes(text: unknown): string[]; export function xLength(text: unknown): number; diff --git a/common/lib/report/social.mjs b/common/lib/report/social.mjs @@ -26,8 +26,29 @@ export const SOCIAL_LIMITS = Object.freeze({ x: 280, bluesky: 300, thread: 4, ur /** What the page calls each platform. */ export const SOCIAL_NAMES = Object.freeze({ x: "X", bluesky: "Bluesky" }); -/** A URL as X sees one in a post (scheme, or a www. host). */ -export const SOCIAL_URL_RE = /\bhttps?:\/\/[^\s<>"]+|\bwww\.[^\s<>"]+\.[a-z]{2,}[^\s<>"]*/giu; +// The top-level domains a scheme-less `label.tld` is taken as a link for +// (X auto-links `Kick.com`, `x.com`, `jeralyzer.pages.dev` and weighs each as a +// URL). Conservative: the common generic TLDs and the country codes a link in +// a post is likely to carry โ counting a domain X would not link as 23 only +// makes a post shorter than it could be, never too long. +export const SOCIAL_TLDS = Object.freeze([ + "com", "net", "org", "edu", "gov", "info", "biz", "io", "co", "dev", "app", "ai", "gg", "tv", "fm", "me", "ly", "so", "to", + "xyz", "live", "news", "page", "site", "online", "blog", "link", "social", "video", "media", "art", "store", "shop", + "us", "uk", "ca", "au", "de", "fr", "es", "it", "nl", "be", "ch", "at", "se", "no", "dk", "fi", "ie", "pl", "pt", "ru", + "br", "mx", "ar", "in", "jp", "kr", "cn", "nz", "za", "eu", "is", "sh", "ws", "cc", "la", "im", "ms", "gl", "vc", "lol", +]); +const TLD = SOCIAL_TLDS.join("|"); +// A scheme-less domain: labels and a known TLD, not glued to a word, an @ (a +// handle or an address) or a dot before it, a path after it if any. +const BARE_DOMAIN = `(?<![\\w@.-])(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+(?:${TLD})(?![\\w-])(?:\\/[^\\s<>"]*)?`; + +/** A URL as X sees one in a post: a scheme, a `www.` host, or a bare `label.tld` (SOCIAL_TLDS). */ +export const SOCIAL_URL_RE = new RegExp(`\\bhttps?:\\/\\/[^\\s<>"]+|\\bwww\\.[^\\s<>"]+\\.[a-z]{2,}[^\\s<>"]*|${BARE_DOMAIN}`, "giu"); + +/** Whether a text holds anything X would turn into a link (a URL, a www. host, a bare domain). */ +export function hasLink(text) { + return new RegExp(SOCIAL_URL_RE.source, "iu").test(String(text ?? "")); +} const X_LIGHT = [ [0, 4351], diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -3,8 +3,8 @@ ## [Unreleased] - **A model can propose verdicts for a fact-check's unruled claims, for you to approve or reject.** `pnpm ops report-draft --json '{"task":"verdicts","article":"<id>"}'` asks each claim with no verdict, with the verdict bench's own prompt, and keeps each proposed verdict, its reason, the model and the prompt version in `verdicts.proposed.json` beside the article, never in `report.json`. It runs only on a model you ticked on the verdict bench (`settings.generation.verdicts.models`, empty until you do), and never sets a verdict itself. umtool's Inbox shows "N verdicts proposed" under Review; **Review verdicts** opens the article, where each proposal has **Approve** (the claim gets that verdict) and **Reject** (the claim stays unruled), with an optional note. A claim you have ruled, or whose proposal you have reviewed, is not asked again. `pnpm ops verdict-review` does the same from the command line. Needs a restart of the editor and umtool. - **Draft everything can add the on-screen deck first.** Tick **with the deck** beside **Draft everything** on a cut's Media tab (or `umtool chain <article> <n> --draft-all --deck`): before the flips, a step adds the on-screen deck with every setting at its default to a cut that has none, so the flips and threads are drafted on a cut the converter made. A copy of the cut as it was is kept in its revisions first. A cut that already has a deck is left as it is, and the step says "deck added" or "deck already there". Off by default: without the tick, Draft everything is as it was. Needs a restart of umtool. -- **Posts for X and Bluesky, drafted for you to copy โ never posted.** A new media draft, `social`, writes a post for X and one for Bluesky, each with up to four more posts under it, from the article's evidence: third person, every name and number from the report, quotation marks only around words a cited clip says, and no links, hashtags, @mentions or emoji of its own. The link under the first post is added by code: the video's URL when the cut's manifest has one (`publish.videoUrl`, yours to set once the video is up), else the article's page on the homepage when the article is public there. The lengths are counted as each platform counts them โ on X a link is 23 and an emoji 2, at most 280; on Bluesky 300 characters as a reader sees them โ and a post over it is cut at a sentence or refused, never sent long. The Media tab's **Social posts** shows each post with its counted length and **Copy**; every build that writes `out/youtube.txt` also writes `out/x.txt` and `out/bluesky.txt`, and Draft everything drafts them after the YouTube text. Draft it alone from the Media tab's **Social** row, `archilyzer gen run social --iteration <n>`, or `generate` in the MCP. It takes narration's route in every preset. Needs a restart of the editor and umtool. -- **The site picker no longer loses your place in the history, or lags under load.** Choosing another site on a site's own page could, now and then, replace the page you chose it on in the browser's history, so Back skipped it; and on a busy machine a new site could take seconds to show on Dashboard or Channels. The choice is now written first and the page then moves or re-renders, every time. Needs a restart of the editor. +- **Posts for X and Bluesky, drafted for you to copy โ never posted.** A new media draft, `social`, writes a post for X and one for Bluesky, each with up to four more posts under it, from the article's evidence: third person, every name and number from the report, quotation marks only around words a cited clip says, and no links, hashtags, @mentions or emoji of its own. The link under the first post is added by code: the video's URL when the cut's manifest has one (`publish.videoUrl`, yours to set once the video is up), else the article's page on the homepage when the article is public there. The lengths are counted as each platform counts them โ on X a link (also a bare `example.com`) is 23 and an emoji 2, at most 280; on Bluesky 300 characters as a reader sees them โ and a post over it is cut at a sentence or refused, never sent long. The Media tab's **Social posts** shows each post with its counted length and **Copy**, and when you set the video's URL after the posts were drafted it says so and offers **Re-draft the posts**; a post past its count is a build warning, never a refusal; every build that writes `out/youtube.txt` also writes `out/x.txt` and `out/bluesky.txt`, and Draft everything drafts them after the YouTube text. Draft it alone from the Media tab's **Social** row, `archilyzer gen run social --iteration <n>`, or `generate` in the MCP. It takes narration's route in every preset. Needs a restart of the editor and umtool. +- **The site picker no longer loses your place in the history.** Choosing another site on a site's own page (or on a page opened from a `?site=` link) could, now and then, replace the page you chose it on in the browser's history, so Back skipped it. The choice is now written first and the page then moves, and a page you had open a moment before under the old site shows the new one. Two quick picks keep the last. Needs a restart of the editor. - **The drive health timing on `/storage` says "Saved." at once** โ it could wait about five seconds (the next automatic refresh), as Settings' save did before. Needs a restart of the editor. - **A storage move's Reconcile and resume no longer calls a folder whose date alone differs "changed".** It says "N directories differ only in mtime" apart from what was added, missing or changed, and a reconcile with nothing else to settle says the copy's content already matches. - **`generate`'s answer for a media draft names the video project first**, above the iteration's own files. diff --git a/editor/app/api/active-site/route.ts b/editor/app/api/active-site/route.ts @@ -4,20 +4,19 @@ import { activeSiteCookieForRequest } from "../../lib/activeSiteServer"; export const dynamic = "force-dynamic"; -// THE ONE WRITER of the active-site cookie (see app/lib/activeSite.ts): POST -// `{ value }` from SiteScopeProvider โ the picker's choice, a site's own page -// recording itself, the localStorage migration โ answers `{ ok }`. +// THE COOKIE'S WRITER BEFORE A NAVIGATION (see app/lib/activeSite.ts): POST +// `{ value }` from SiteScopeProvider when the picker moves the URL after the +// choice (a site's own page, a `?site=` link's) answers `{ ok }`. A page that +// stays writes through setActiveSiteAction, whose answer re-renders it. // -// A ROUTE, NOT A SERVER ACTION (release 29 D1). A cookie set in a server action +// NOT A SERVER ACTION HERE (release 29 D1). A cookie set in a server action // makes Next re-render the page in the action's answer and apply it through -// the router โ answered BEFORE that applies, so a navigation the caller made -// next (the picker on a site's page pushes the other site's) discarded the -// pending action and replayed it as a refresh after the push, and when React -// committed the two together the push's history entry was written as a -// replace (Back skipped the page the choice was made on); and under load the -// re-render waited on in-flight prefetches, so a re-scope came seconds late -// (site-scope.spec). Here the write is only a write: the provider refreshes, -// or the picker navigates, itself. +// the router โ answered BEFORE that applies, so the navigation the picker +// made next discarded the pending action and replayed it as a refresh after +// the push, and when React committed the two together the push's history +// entry was written as a replace (Back skipped the page the choice was made +// on: site-scope.spec). The route only writes; the picker refreshes once the +// new URL has committed (the client cache is not cleared by a route). // // Same-origin only (a cross-site page could otherwise flip an operator's // scope): JSON, and an Origin, when sent, that is this host. The value is only @@ -25,7 +24,9 @@ export const dynamic = "force-dynamic"; // decided at every read, so a site deleted later resolves as no selection. export async function POST(request: Request): Promise<Response> { const origin = request.headers.get("origin"); - const host = request.headers.get("host"); + // The host the browser addressed: a proxy's X-Forwarded-Host first, as + // Next's own server-action origin check reads it. + const host = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || request.headers.get("host"); if (origin !== null && (() => { try { return new URL(origin).host !== host; diff --git a/editor/app/components/SiteScopeProvider.tsx b/editor/app/components/SiteScopeProvider.tsx @@ -18,7 +18,10 @@ import { siteIdFromPathname, } from "../lib/activeSite"; -// The cookie's one writer (app/api/active-site/route.ts): true when it is set. +import { setActiveSiteAction } from "../lib/activeSiteActions"; + +// The cookie's writer before a navigation (app/api/active-site/route.ts; see +// `write` below for the other): true when it is set. async function writeActiveSite(value: string): Promise<boolean> { try { const res = await fetch("/api/active-site", { @@ -60,8 +63,8 @@ async function writeActiveSite(value: string): Promise<boolean> { // cookie gets it copied into the cookie, then the key is removed. That is the // only localStorage read, and the one paint it may cost is on the first visit // after the update. -// Both only WRITE the cookie (`record`), then refresh: the value comes back -// through the server's re-render. They run as the page hydrates, and a state change there +// Both only WRITE the cookie (`record`, the server action): the value comes +// back through the server's re-render. They run as the page hydrates, and a state change there // would re-render the picker before React replays a choice made on the // server-rendered select before hydration: the re-render resets the select to // its old value, and the replayed change reads that instead of the choice. @@ -70,11 +73,11 @@ type SiteScope = { // The stored selection: a site id or "__all__". The picker resolves it // against the path and a `?site=` param; it is not the effective scope alone. stored: string; - // Store a choice: shown at once, written through /api/active-site. Resolves - // once the cookie is set to true โ the page then refreshes to re-render with - // it, unless `navigating` (the caller moves the URL itself, and the next page - // renders with the cookie) โ or to false with the previous selection put - // back when the write failed. + // Store a choice: shown at once, written (see `write`). Resolves once the + // cookie is set to true โ the page re-rendered with it, unless `navigating` + // (the caller moves the URL itself, and refreshes once it has: the route's + // write leaves the client cache alone) โ or to false with the previous + // selection put back when the write failed. choose: (value: string, o?: { navigating?: boolean }) => Promise<boolean>; }; @@ -113,12 +116,44 @@ export function SiteScopeProvider({ // The other tabs (see above): subscribe, and keep the one instance to post on. const router = useRouter(); + // TWO WRITERS OF ONE COOKIE, by what follows the write (release 29 D1): + // - a write the page stays on (a pick on Dashboard or Channels, a site + // page's visit, the migration) is the SERVER ACTION, whose answer carries + // the page re-rendered with the new cookie โ the re-scope, with nothing of + // our own (a route's write and a router.refresh after it was, now and + // then under load, never applied: site-scope.spec); + // - a write the caller navigates after (a pick on a site's page or a + // `?site=` link's) is the ROUTE, POST /api/active-site: a navigation made + // while a server action's re-render is still pending discards it and + // replays it as a refresh after the navigation, committing the push as a + // replace (Back skipped the page); the route's answer carries no render. + // THE WRITES GO ONE AT A TIME, in the order they were asked for (review fix, + // release 29): an earlier pick's write landing last would leave the cookie + // on it. Chained, the last pick is the last write. + const writes = useRef<Promise<unknown>>(Promise.resolve()); + const write = useCallback((value: string, navigating: boolean): Promise<boolean> => { + const next = writes.current.then(() => + navigating ? writeActiveSite(value) : setActiveSiteAction(value).catch(() => false), + ); + writes.current = next; + return next; + }, []); const channel = useRef<BroadcastChannel | null>(null); useEffect(() => { if (typeof BroadcastChannel === "undefined") return; const ch = new BroadcastChannel(ACTIVE_SITE_CHANNEL); channel.current = ch; - ch.onmessage = () => router.refresh(); + ch.onmessage = (e: MessageEvent) => { + // The value the other tab wrote is shown at once (review fix, release + // 29): the refresh brings the layout's own read of the cookie after it, + // and a refresh that lands late (a busy tab) no longer leaves the picker + // on the old site meanwhile. + if (isStorableActiveSite(e.data) && storedRef.current !== e.data) { + storedRef.current = e.data; + setStored(e.data); + } + router.refresh(); + }; return () => { ch.close(); if (channel.current === ch) channel.current = null; @@ -137,30 +172,23 @@ export function SiteScopeProvider({ storedRef.current = value; setStored(value); setWriting((n) => n + 1); - const ok = await writeActiveSite(value); + const ok = await write(value, o.navigating === true); setWriting((n) => n - 1); if (ok) { announce(value); - // The route only writes (no server action's implicit re-render): the - // page and the layout re-render with the cookie now โ unless the caller - // navigates, whose next page does. - if (!o.navigating) router.refresh(); } else { storedRef.current = previous; setStored(previous); } return ok; - }, [announce, router]); + }, [announce, write]); // Write a value the page did not choose โ no optimistic state (see above). const record = useCallback(async (value: string): Promise<boolean> => { - const ok = await writeActiveSite(value); - if (ok) { - announce(value); - router.refresh(); - } + const ok = await write(value, false); + if (ok) announce(value); return ok; - }, [announce, router]); + }, [announce, write]); // Visiting a site's own page records it: once per arrival at that site's // pages (a re-run of the effect โ StrictMode, Fast Refresh โ does not write diff --git a/editor/app/components/SiteScopeSelect.tsx b/editor/app/components/SiteScopeSelect.tsx @@ -1,6 +1,6 @@ "use client"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { ALL_SITES, @@ -42,6 +42,18 @@ export function SiteScopeSelect({ sites }: { sites: SiteScopeOption[] }) { null, ); if (pending !== null && pending.urlKey !== urlKey) setPending(null); + // A choice that navigates (a site's page, a `?site=` link's) refreshes once + // the new URL has COMMITTED (review fix, release 29): the cookie is written + // by a route, which โ unlike a server action โ leaves the client router's + // cache as it was, so a page visited within its stale time would otherwise + // show the scope it was rendered under. After the commit, so the push stays + // a push (the history fix the route was made for). + const refreshFrom = useRef<string | null>(null); + useEffect(() => { + if (refreshFrom.current === null || refreshFrom.current === urlKey) return; + refreshFrom.current = null; + router.refresh(); + }, [urlKey, router]); const held = pending?.urlKey === urlKey ? pending.value : null; const resolved = resolveActiveSiteFrom( [held, onSite?.siteId, param, stored], @@ -59,6 +71,7 @@ export function SiteScopeSelect({ sites }: { sites: SiteScopeOption[] }) { setPending(null); return; } + refreshFrom.current = urlKey; router.push( value === ALL_SITES ? "/sites" @@ -67,9 +80,9 @@ export function SiteScopeSelect({ sites }: { sites: SiteScopeOption[] }) { return; } if (param === null) { - // The common case: the stored value is what shows, and the provider - // refreshes this page (Dashboard, Channels) in the new scope once the - // cookie is written. + // The common case: the stored value is what shows, and the cookie write + // (the server action) re-renders this page (Dashboard, Channels) in the + // new scope. await choose(value); return; } @@ -80,6 +93,7 @@ export function SiteScopeSelect({ sites }: { sites: SiteScopeOption[] }) { setPending(null); return; } + refreshFrom.current = urlKey; router.replace(withoutSiteParam(pathname, search), { scroll: false }); } diff --git a/editor/app/lib/activeSite.ts b/editor/app/lib/activeSite.ts @@ -7,8 +7,9 @@ // `SiteScopeProvider`; Dashboard and Channels read it through the same helper. // So the server renders the picker, and the scoped pages, with the stored // selection on the first paint โ nothing is reconciled after it. It is written -// only by `POST /api/active-site` (app/api/active-site/route.ts; a server action -// until release 29), which SiteScopeProvider calls. +// by `setActiveSiteAction` (app/lib/activeSiteActions.ts) where the page stays, +// and by `POST /api/active-site` (app/api/active-site/route.ts) before a +// navigation (release 29) โ SiteScopeProvider chooses. // // A `?site=<id>` LINK still works: a valid param governs that one request (the // server pages read it from `searchParams`, the picker from the URL), and is not diff --git a/editor/app/lib/activeSiteActions.ts b/editor/app/lib/activeSiteActions.ts @@ -0,0 +1,34 @@ +"use server"; + +import { cookies } from "next/headers"; +import { + ACTIVE_SITE_COOKIE_MAX_AGE, + isStorableActiveSite, +} from "./activeSite"; +import { activeSiteCookieForRequest } from "./activeSiteServer"; + +// ONE OF THE TWO WRITERS of the active-site cookie (see ./activeSite.ts): the +// one a page that STAYS calls โ the picker on Dashboard or Channels, +// SiteScopeProvider when a site's own page is visited, and once its +// localStorage migration. Setting a cookie in a server action makes Next +// re-render the current page and its layouts with the new value in the +// action's answer, so the root layout hands the provider the new selection and +// Dashboard or Channels re-scope, with no refresh of our own. A write followed +// by a navigation goes through POST /api/active-site instead (release 29 D1: +// SiteScopeProvider's `write` says why). +// +// The value is only SHAPE-checked (a site id or "__all__"): whether it names a +// configured site is decided at every read, so a site deleted later resolves as +// no selection. Returns false, writing nothing, for anything else. +export async function setActiveSiteAction(value: string): Promise<boolean> { + if (!isStorableActiveSite(value)) return false; + const name = await activeSiteCookieForRequest(); + (await cookies()).set(name, value, { + path: "/", + sameSite: "lax", + maxAge: ACTIVE_SITE_COOKIE_MAX_AGE, + // Only the server reads it: the page gets it through the layout. + httpOnly: true, + }); + return true; +} diff --git a/editor/app/lib/activeSiteServer.ts b/editor/app/lib/activeSiteServer.ts @@ -13,7 +13,7 @@ import { // result to SiteScopeProvider; Dashboard and Channels call it with their // `searchParams.site`, which wins for that request when it names a site or // "__all__". Nothing is written here: a server component cannot set a cookie, -// and only POST /api/active-site does. +// and only setActiveSiteAction and POST /api/active-site do. export type ActiveSiteRead = ResolvedActiveSite & { // The cookie's raw value, or null when the request carried none โ which is // what tells the provider a visitor may still have the old localStorage key. diff --git a/editor/e2e/site-scope.spec.ts b/editor/e2e/site-scope.spec.ts @@ -6,6 +6,11 @@ import { readJson, resetData, writeSettings, writeSite, testPaths } from "./help type SiteFile = { channels: { slug: string }[] }; // Two sites over the shared two-channel pool: alpha exposes slow-a, beta slow-b. +// A pick re-scopes the page by a router refresh โ a server render of the +// whole page โ which on a loaded machine (other worktrees' builds and suites +// beside this one) can take longer than the default 5 s (release 29 D1). +const RESCOPED = { timeout: 15_000 }; + async function twoSites() { await resetData("two-slow-channels"); await writeSite("alpha", { @@ -22,8 +27,8 @@ test("defaults to all sites and shows the full pool", async ({ page }) => { await twoSites(); await page.goto("/channels"); await expect(page.getByLabel("Active site")).toHaveValue("__all__"); - await expect(page.getByRole("link", { name: "slow-a" })).toBeVisible(); - await expect(page.getByRole("link", { name: "slow-b" })).toBeVisible(); + await expect(page.getByRole("link", { name: "slow-a" })).toBeVisible(RESCOPED); + await expect(page.getByRole("link", { name: "slow-b" })).toBeVisible(RESCOPED); }); test("selecting a site scopes the channels list and persists", async ({ @@ -32,25 +37,26 @@ test("selecting a site scopes the channels list and persists", async ({ await twoSites(); await page.goto("/channels"); + await hydrated(page); // a pick before React attaches is lost (release 29 D1) await page.getByLabel("Active site").selectOption("alpha"); // The choice is a cookie (release 15 SS): the URL is left alone, where it // used to gain ?site=alpha. await expect(page).toHaveURL(/\/channels$/); - await expect(page.getByRole("link", { name: "slow-a" })).toBeVisible(); - await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0); + await expect(page.getByRole("link", { name: "slow-a" })).toBeVisible(RESCOPED); + await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0, RESCOPED); await expectNoSiteParam(page); // The cookie persists the choice: revisiting with no param re-applies it. await page.goto("/channels"); await expect(page.getByLabel("Active site")).toHaveValue("alpha"); await expect(page).toHaveURL(/\/channels$/); - await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0); + await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0, RESCOPED); await expectNoSiteParam(page); // Switching to beta flips the scope. await page.getByLabel("Active site").selectOption("beta"); - await expect(page.getByRole("link", { name: "slow-b" })).toBeVisible(); - await expect(page.getByRole("link", { name: "slow-a" })).toHaveCount(0); + await expect(page.getByRole("link", { name: "slow-b" })).toBeVisible(RESCOPED); + await expect(page.getByRole("link", { name: "slow-a" })).toHaveCount(0, RESCOPED); }); test("dashboard stats and table scope to the active site", async ({ page }) => { @@ -60,8 +66,8 @@ test("dashboard stats and table scope to the active site", async ({ page }) => { // (c63f5cb), which has no "channels" group; the scoped count is now observable // as the number of rows in its channels table. await expect(page.getByLabel(/^channel row /)).toHaveCount(1); - await expect(page.getByRole("link", { name: "slow-a" })).toBeVisible(); - await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0); + await expect(page.getByRole("link", { name: "slow-a" })).toBeVisible(RESCOPED); + await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0, RESCOPED); }); test("charts is a site's tab, and the picker follows the path", async ({ @@ -108,6 +114,7 @@ test("publish targets the site in the path, and says when it cannot deploy", asy ).toBeVisible(); await expect(page.getByText(/select a specific site/i)).toHaveCount(0); await expect(page.getByLabel("Active site")).toHaveValue("alpha"); + await hydrated(page); // a pick before React attaches is lost (release 29 D1) await page.getByLabel("Active site").selectOption("beta"); await expect(page).toHaveURL(/\/sites\/beta\/publish$/); }); @@ -256,8 +263,9 @@ test("a stored site is the picker's first paint on every page, never All sites", // Store alpha the way a person does, and wait for it to land: the re-render // that drops slow-b is the one the cookie write triggers. await page.goto("/channels"); + await hydrated(page); // a pick before React attaches is lost (release 29 D1) await picker.selectOption("alpha"); - await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0); + await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0, RESCOPED); expect(await storedCookie(page)).toBe("alpha"); // Full loads: the server renders the stored site, and nothing moves it. @@ -308,18 +316,19 @@ test("a ?site= link scopes its own page and is not stored; a choice there drops await twoSites(); const picker = page.getByLabel("Active site"); await page.goto("/channels"); + await hydrated(page); // a pick before React attaches is lost (release 29 D1) await picker.selectOption("alpha"); - await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0); + await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0, RESCOPED); // The link's scope, on the first paint, for this page only. expect(await firstPaint(page, "/channels?site=beta")).toBe("beta"); - await expect(page.getByRole("link", { name: "slow-b" })).toBeVisible(); - await expect(page.getByRole("link", { name: "slow-a" })).toHaveCount(0); + await expect(page.getByRole("link", { name: "slow-b" })).toBeVisible(RESCOPED); + await expect(page.getByRole("link", { name: "slow-a" })).toHaveCount(0, RESCOPED); expect(await storedCookie(page)).toBe("alpha"); // Not written: the next plain visit is the stored site's. expect(await firstPaint(page, "/channels")).toBe("alpha"); - await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0); + await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0, RESCOPED); // Choosing on a link's page replaces the link's scope: stored, and the param // goes, so the page and the picker agree. @@ -328,8 +337,8 @@ test("a ?site= link scopes its own page and is not stored; a choice there drops await picker.selectOption("__all__"); await expect(page).toHaveURL(/\/channels$/); await expect(picker).toHaveValue("__all__"); - await expect(page.getByRole("link", { name: "slow-a" })).toBeVisible(); - await expect(page.getByRole("link", { name: "slow-b" })).toBeVisible(); + await expect(page.getByRole("link", { name: "slow-a" })).toBeVisible(RESCOPED); + await expect(page.getByRole("link", { name: "slow-b" })).toBeVisible(RESCOPED); expect(await storedCookie(page)).toBe("__all__"); expect(await firstPaint(page, "/channels")).toBe("__all__"); }); @@ -349,7 +358,7 @@ test("a choice the old picker kept in localStorage moves to the cookie once", as // The one visit that may flash: the server had no cookie to render from. await page.goto("/channels"); await expect(picker).toHaveValue("beta"); - await expect(page.getByRole("link", { name: "slow-a" })).toHaveCount(0); + await expect(page.getByRole("link", { name: "slow-a" })).toHaveCount(0, RESCOPED); await expect.poll(() => storedCookie(page), { timeout: 15_000 }).toBe("beta"); await expect.poll(legacy, { timeout: 15_000 }).toBeNull(); @@ -379,6 +388,36 @@ test("Back to a site's page shows that site, not the choice made there", async ( await expect(picker).toHaveValue("alpha"); }); +// A choice that navigates refreshes the client cache once the new page is in +// (review fix, release 29): the cookie is written by a route, which leaves +// the router's cache alone, so Channels โ visited, and so cached, under alpha +// a moment before โ would otherwise come back scoped to alpha. +test("a choice made on a site's page reaches a page cached under the old site", async ({ + page, +}) => { + await twoSites(); + const picker = page.getByLabel("Active site"); + await page.goto("/channels"); + await hydrated(page); + await picker.selectOption("alpha"); + await expect(page.getByRole("link", { name: "slow-b" })).toHaveCount(0, RESCOPED); + await expect(page.getByRole("link", { name: "slow-a" })).toBeVisible(RESCOPED); + // A client-side visit to alpha's page, then the choice there. + await page.locator("aside nav").getByRole("link", { name: "Sites", exact: true }).click(); + await expect(page).toHaveURL(/\/sites$/); + await page.locator('main a[href="/sites/alpha"]').click(); + await expect(page).toHaveURL(/\/sites\/alpha$/); + await expect(picker).toHaveAttribute("data-hydrated", "true"); + await picker.selectOption("beta"); + await expect(page).toHaveURL(/\/sites\/beta$/); + // Back to Channels by the sidebar, well inside its stale time. + await page.locator("aside nav").getByRole("link", { name: "Channels", exact: true }).click(); + await expect(page).toHaveURL(/\/channels$/); + await expect(picker).toHaveValue("beta"); + await expect(page.getByRole("link", { name: "slow-b" })).toBeVisible(RESCOPED); + await expect(page.getByRole("link", { name: "slow-a" })).toHaveCount(0, RESCOPED); +}); + // A site picked in one tab reaches the others. The cookie is shared, but a // tab's picker reads its root layout, which a client-side navigation does not // re-render; without the broadcast, tab A kept showing alpha over beta's pages @@ -391,15 +430,17 @@ test("a site picked in another tab reaches this one", async ({ context }) => { const a = await context.newPage(); const pickerA = a.getByLabel("Active site"); await a.goto("/channels"); + await hydrated(a); // a pick before React attaches is lost (release 29 D1) await pickerA.selectOption("alpha"); - await expect(a.getByRole("link", { name: "slow-b" })).toHaveCount(0); + await expect(a.getByRole("link", { name: "slow-b" })).toHaveCount(0, RESCOPED); await a.goto("/settings"); await hydrated(a); const b = await context.newPage(); await b.goto("/channels"); + await hydrated(b); // a pick before React attaches is lost (release 29 D1) await b.getByLabel("Active site").selectOption("beta"); - await expect(b.getByRole("link", { name: "slow-a" })).toHaveCount(0); + await expect(b.getByRole("link", { name: "slow-a" })).toHaveCount(0, RESCOPED); expect(await storedCookie(b)).toBe("beta"); // Tab A follows without a reload, and its next page agrees with its picker. @@ -407,8 +448,8 @@ test("a site picked in another tab reaches this one", async ({ context }) => { await a.locator("aside nav").getByRole("link", { name: "Channels", exact: true }).click(); await expect(a).toHaveURL(/\/channels$/); await expect(pickerA).toHaveValue("beta"); - await expect(a.getByRole("link", { name: "slow-b" })).toBeVisible(); - await expect(a.getByRole("link", { name: "slow-a" })).toHaveCount(0); + await expect(a.getByRole("link", { name: "slow-b" })).toBeVisible(RESCOPED); + await expect(a.getByRole("link", { name: "slow-a" })).toHaveCount(0, RESCOPED); // And a client-side visit to alpha's page is recorded again: tab A no longer // believes alpha is stored. @@ -433,8 +474,9 @@ test("a new channel starts checked on the stored site, or on a ?site= link's", a await writeSettings({ autoRefreshIntervalSeconds: 0 }); const a = await context.newPage(); await a.goto("/channels"); + await hydrated(a); // a pick before React attaches is lost (release 29 D1) await a.getByLabel("Active site").selectOption("alpha"); - await expect(a.getByRole("link", { name: "slow-b" })).toHaveCount(0); + await expect(a.getByRole("link", { name: "slow-b" })).toHaveCount(0, RESCOPED); const alpha = a.getByLabel("Include on Alpha"); const beta = a.getByLabel("Include on Beta"); @@ -461,8 +503,9 @@ test("a new channel starts checked on the stored site, or on a ?site= link's", a await expect(a.getByLabel("Group for Alpha")).toHaveCount(0); const b = await context.newPage(); await b.goto("/channels"); + await hydrated(b); // a pick before React attaches is lost (release 29 D1) await b.getByLabel("Active site").selectOption("beta"); - await expect(b.getByRole("link", { name: "slow-a" })).toHaveCount(0); + await expect(b.getByRole("link", { name: "slow-a" })).toHaveCount(0, RESCOPED); await expect(a.getByLabel("Active site")).toHaveValue("beta"); await a.waitForTimeout(SETTLE_MS); expect(await alpha.isChecked()).toBe(false); diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -3257,7 +3257,7 @@ follow), `onChange` does `router.push("/sites/<other>/<segment>")` and "All site `app/lib/activeSite.ts`; base name `ACTIVE_SITE_COOKIE`, a host with no port uses it bare): `path=/`, `SameSite=Lax`, one year, `httpOnly`. The port is in the name because a cookie is shared by every port on a host and localStorage was per origin. -- **One writer:** `setActiveSiteAction` (`app/lib/activeSiteActions.ts`, `"use server"`), which +- **One writer** (release 29: two โ see "Release 29 lane C"): `setActiveSiteAction` (`app/lib/activeSiteActions.ts`, `"use server"`), which only shape-checks (`isStorableActiveSite`: a `SITE_ID_RE`-shaped id of โค 128 chars, or `__all__`). Setting the cookie makes Next re-render the current page and its layouts, which is how Dashboard and Channels re-scope; nothing calls `router.refresh()`. @@ -9579,13 +9579,16 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri `toField` appends it. `out/x.txt` / `out/bluesky.txt` are `report-to-video/social.mjs` `composeSocialText` (the first post, then `โ k/n โ` and each thread post), written by build-video at the top of `writeYoutubeText` (a platform with no post loses its file) and by Draft everything's `draft-social`. -- **The active-site cookie is written by `POST /api/active-site`** (`editor/app/api/active-site/route.ts`: JSON - `{value}`, an Origin that is not this host refused, `{ok}`), not a server action (`setActiveSiteAction` is gone). - `SiteScopeProvider.choose(value, {navigating?})` refreshes the router after a write unless the caller navigates; - `record` (a site page's visit, the migration) refreshes too. Why: a cookie set in a server action is answered before - the router applies the action's re-render; a `router.push` in that gap discards the action and its replayed refresh - can commit the push as a history REPLACE (Next 16 `HistoryUpdater`: a push whose URL is already the location is a - replace). +- **The active-site cookie has two writers, by what follows the write** (release 29 D1 and its review): where the page + STAYS (a pick on Dashboard or Channels, a site page's visit, the migration) `setActiveSiteAction` (its answer + re-renders the page; a route write followed by `router.refresh()` was, now and then under load, never applied); + before a NAVIGATION (the picker on a site's page or a `?site=` link's) `POST /api/active-site` + (`editor/app/api/active-site/route.ts`: JSON `{value}`, an Origin that is not `x-forwarded-host ?? host` refused, + `{ok}`), and the picker `router.refresh()`es once the new URL has committed (a route does not clear the client + cache). Why the route there: a server action's re-render is applied after its answer; a `router.push` in that gap + discards the action and its replayed refresh can commit the push as a history REPLACE (Next 16 `HistoryUpdater`). + `SiteScopeProvider` chains both writers through one promise (the last pick is the last write) and shows another + tab's broadcast value at once, then refreshes. - **A server action that revalidates delays its own answer** until the router applies the revalidated tree, which under in-flight prefetches can wait for the next AutoRefresh pulse (~5 s). Settings' save (R6.3) and the drive health timing's save (`saveHealthTimingsAction`, D1) no longer revalidate and refresh after an ok answer; the lane diff --git a/plans/release-29.md b/plans/release-29.md @@ -563,6 +563,45 @@ The social promotion text, text only. Built as the plan's Shape row, with these | `800a26fc` | editor e2e: `storage-locations.spec.ts`'s any-age eviction watched in the page | | (this commit) | these records, FACTS "Release 29 lane C", CHANGELOG | +### Lane C review fixes (2026-10-15, lane C, `r29/gen-debts`) + +The review of `cfdeb856..2f6a0ad1` (no blocker), fixed on the branch: +- **X weighs a bare domain** (`Kick.com`, `x.co`, `a.pages.dev/โฆ`) as 23: `SOCIAL_URL_RE` takes a scheme-less + `label.tld` whose TLD is in `SOCIAL_TLDS` (a conservative list), not glued to a word, an `@` or a dot (so `e.g.`, + `3.5`, `a@b.com` are not links); `hasLink` is the social task's link refusal. `Kai streamed on Kick.com` is 39; 270 + characters and ` x.co x.co` are 318. +- **The site picker after a navigating choice** refreshes once the new URL has committed (an effect on the URL after + the push or replace), so a page cached under the old site re-renders. And then โ found while re-running the spec โ + **the cookie has two writers again**: where the page stays, `setActiveSiteAction` (its answer re-renders the page); + before a navigation, the route. With the route for every write, a pick on Channels in a second tab now and then never + re-scoped (a `router.refresh` after the write that was not applied: 1โ3 of 70, and a retried refresh did not help); + the action never did. Both writers go through one promise chain (the last pick wins); the route's origin check reads + `x-forwarded-host` first; another tab's pick shows at once. site-scope.spec: every pick waits for hydration, a + re-scope's wait is 15 s (`RESCOPED`), and a new case โ a choice on a site's page reaches Channels cached under the + old site. +- **A social post's quotation marks** are stripped only when they wrap it whole. +- **Draft everything's social step** removes a platform's old `out/<platform>.txt` when it has no post. +- **`publish.x`, `publish.bluesky`, `publish.videoUrl` are warnings** (`publishWarnings`, `drafted.mjs`): the lint warns, + the build and the cut's structural edits go on; YouTube's rules and an unknown `publish` key stay errors; "Use this" + on a social post still refuses one past its count (the field's own writer). When `publish.videoUrl` is set and a post + drafted before it does not carry it, the Social posts section says so and offers **Re-draft the posts** (a forced + `social` draft on the cut's iteration; a post you wrote is named and never replaced). +- **A deck refused on a small frame** says "frame too small for the deck (WรH): โฆ" (`deckRefusedDetail`). + +| Commit | What | +| --- | --- | +| `ed4a429d` | common: bare domains in X's count and the task's refusal; the quote strip | +| `be921c5b` | common, umtool: `publishWarnings`; the re-draft notice and `RedraftSocial`; the social step's stale file; the deck's detail; tests | +| `f338e552` | editor: the refresh after a navigating choice, the write chain, `x-forwarded-host`, the broadcast value; site-scope.spec | +| `dcb704ba` | editor: the server action back for writes where the page stays | +| (this commit) | these records, FACTS, CHANGELOG | + +Gates: tsc clean at every commit. common 4236/4236 (+1: the quote case; the X cases are in existing tests); test:scripts +1022, 1019 + 3 skipped, 0 failed (+2: the small-frame deck, the lint warning); editor unit 308/308; mcp 371/371; umtool +unit 33/33 (final counts in the report). umtool e2e `media-draft.spec.ts` + `media-surfaces.spec.ts` 7/7 (1.7 min; the +social case now sets `publish.videoUrl` and re-drafts). Editor `site-scope.spec.ts`, 15 tests a run: with the route +alone 69/70, 69/70, 67/70, 69/70, 140/140, 68/70; with the action back 140/140 (`--repeat-each=10`), 70/70, 70/70. + ### Lane C gates (2026-10-15, `r29/gen-debts`) Counts at the branch's start (`3217bdfb`) โ before the merge โ after the merge of `r29/integration` (`d30248dc`): diff --git a/umtool/components/projects/RedraftSocial.tsx b/umtool/components/projects/RedraftSocial.tsx @@ -0,0 +1,45 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; + +// "Re-draft the posts" (release 29 review): the social draft again, forced, +// on the iteration the cut was made from โ what the Social posts section +// offers when `publish.videoUrl` changed after the posts were drafted (the +// link is code's, fixed when they are drafted). A post you wrote or edited is +// never replaced: the draft is kept as an alternative. +export default function RedraftSocial({ article, n }: { article: string; n: number }) { + const router = useRouter(); + const [state, setState] = useState<"idle" | "busy" | "queued" | "failed">("idle"); + const [error, setError] = useState(""); + async function go() { + setState("busy"); + setError(""); + const r = await fetch("/api/articles/generate", { + method: "POST", + body: JSON.stringify({ task: "social", article, iteration: n, force: true }), + }).catch(() => null); + const b = r ? await r.json().catch(() => ({})) : {}; + if (!r?.ok) { + setState("failed"); + setError(b.error ?? "the editor did not answer"); + return; + } + setState("queued"); + router.refresh(); + } + return ( + <span className="inline-flex items-center gap-2"> + <button type="button" data-social-redraft="" className={buttonVariants({ variant: "outline", size: "sm" })} disabled={state === "busy" || state === "queued"} onClick={() => void go()}> + Re-draft the posts + </button> + {state === "queued" && <span className="text-muted">queued โ the Social row follows it</span>} + {state === "failed" && ( + <span role="alert" className="text-reject-text"> + {error} + </span> + )} + </span> + ); +} diff --git a/umtool/components/projects/SocialPostSection.tsx b/umtool/components/projects/SocialPostSection.tsx @@ -5,6 +5,7 @@ import { Panel } from "@/components/ui/panel"; import { fmtAgo } from "@/lib/format"; import { SOCIAL_LIMITS, SOCIAL_NAMES, socialLength, type SocialPlatform } from "yt-dlp-transcript-common/lib/report/social.mjs"; import { SOCIAL_PLATFORMS, composeSocialText, socialPosts, socialTextName } from "umtool-report-to-video/social"; +import RedraftSocial from "./RedraftSocial"; // The promotion posts (release 29 G2): `publish.x` and `publish.bluesky`, the // first post (its link under it, added by code) and the thread under it, each @@ -12,11 +13,16 @@ import { SOCIAL_PLATFORMS, composeSocialText, socialPosts, socialTextName } from // graphemes). Copy takes what out/<platform>.txt holds -- the same text, // composed from the manifest. TEXT ONLY: nothing here posts. Nothing when // the cut has neither post. +// +// The link under a first post is fixed when it is drafted. When the cut's +// `publish.videoUrl` is set and a post does not carry it (it was drafted +// before, linking the article or nothing), the section says so and offers a +// re-draft on the iteration the cut was made from (review fix, release 29). -type Props = { dir: string; manifest: Record<string, unknown> }; +type Props = { dir: string; manifest: Record<string, unknown>; iteration?: { article: string; n: number } | null }; type Value = { post?: string; thread?: string[] }; -export default async function SocialPostSection({ dir, manifest }: Props) { +export default async function SocialPostSection({ dir, manifest, iteration = null }: Props) { const publish = (manifest.publish ?? {}) as Partial<Record<SocialPlatform, Value>>; const drafted = (manifest.drafted ?? {}) as Record<string, { model?: string } | undefined>; const platforms = (SOCIAL_PLATFORMS as readonly SocialPlatform[]).filter((p) => socialPosts(publish[p]).length > 0); @@ -24,8 +30,21 @@ export default async function SocialPostSection({ dir, manifest }: Props) { const written = Object.fromEntries( await Promise.all(platforms.map(async (p) => [p, await stat(path.join(dir, "out", socialTextName(p))).then((s) => s.mtimeMs, () => null)] as const)), ) as Record<SocialPlatform, number | null>; + const videoUrl = typeof (manifest.publish as { videoUrl?: unknown } | undefined)?.videoUrl === "string" ? String((manifest.publish as { videoUrl: string }).videoUrl).trim() : ""; + const stale = /^https?:\/\/\S+$/i.test(videoUrl) ? platforms.filter((p) => !String(publish[p]?.post ?? "").includes(videoUrl)) : []; + const yours = stale.filter((p) => !drafted[`publish.${p}`]); return ( <Panel title="social posts" aria-label="Social posts" aside={<span className="text-muted">text only โ copy it, nothing is posted</span>}> + {stale.length > 0 && ( + <p data-social-stale={stale.join(" ")} className="m-0 mb-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] text-text-2"> + <span> + The {stale.map((p) => SOCIAL_NAMES[p]).join(" and ")} post{stale.length > 1 ? "s link" : " links"} the old address, not the video + (<span className="font-mono">{videoUrl}</span>): the link is set when a post is drafted. + {yours.length > 0 ? ` ${yours.map((p) => SOCIAL_NAMES[p]).join(" and ")}: yours โ edit it, a re-draft never replaces it.` : ""} + </span> + {iteration && yours.length < stale.length && <RedraftSocial article={iteration.article} n={iteration.n} />} + </p> + )} <div className="grid gap-3 md:grid-cols-2"> {platforms.map((p) => { const posts = socialPosts(publish[p]); diff --git a/umtool/components/projects/report/MediaTab.tsx b/umtool/components/projects/report/MediaTab.tsx @@ -55,7 +55,11 @@ export default async function MediaTab({ project, detail }: ReportTabProps) { <YoutubeSection dir={project.dir} manifest={m as Record<string, unknown>} /> {/* --- the promotion posts (publish.x, publish.bluesky; text only) - */} - <SocialPostSection dir={project.dir} manifest={m as Record<string, unknown>} /> + <SocialPostSection + dir={project.dir} + manifest={m as Record<string, unknown>} + iteration={link.ok && link.status === "done" ? { article: link.article, n: link.n } : null} + /> </> ); } diff --git a/umtool/e2e/media-draft.spec.ts b/umtool/e2e/media-draft.spec.ts @@ -1,5 +1,5 @@ import { test, expect, type Page } from "@playwright/test"; -import { readFileSync } from "node:fs"; +import { readFileSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { WARM_TIMEOUT, warm } from "./warm"; @@ -109,4 +109,18 @@ test("social (release 29 G2): a post for X and one for Bluesky with their thread await expect(panel.getByRole("region", { name: "X post" }).getByRole("button", { name: "Copy" })).toBeVisible(); // Its draft row on the Media tab, in Draft everything's order (the last). await expect(page.locator("[data-media-chip='social']")).toBeVisible(); + + // The video is up: its URL set after the posts were drafted. The section + // says they link the old address and re-drafts them (review fix). + const file = path.join(FIXTURE, "gen-projects", ARTICLE, "i4", "video.manifest.json"); + const videoUrl = "https://video.example/watch/mdraft-4"; + writeFileSync(file, JSON.stringify({ ...manifestOf(4), publish: { ...manifestOf(4).publish, videoUrl } }, null, 2) + "\n"); + await page.reload(); + const stale = panel.locator("[data-social-stale]"); + await expect(stale).toHaveAttribute("data-social-stale", "x bluesky"); + await stale.getByRole("button", { name: "Re-draft the posts" }).click(); + await expect(stale).toContainText("queued"); + expect(lastAsked()).toMatchObject({ task: "social", article: ARTICLE, iteration: 4, force: true }); + await expect.poll(() => manifestOf(4).publish.x.post, { timeout: 60_000 }).toMatch(/\n\nhttps:\/\/video\.example\/watch\/mdraft-4$/); + expect(manifestOf(4).publish.bluesky.post.endsWith(`\n\n${videoUrl}`)).toBe(true); }); diff --git a/umtool/lib/report/chain-draft.mjs b/umtool/lib/report/chain-draft.mjs @@ -21,6 +21,21 @@ export function deckChrome() { export const deckStepDetail = (added) => added ? "deck added: render.chrome with every setting its default (a snapshot of the cut before it is in revisions/)" : "deck already there: the cut's render.chrome is kept as it is"; +/** + * A refused deck step's line: "frame too small for the deck" when the deck's + * defaults do not fit the cut's frame (validateChrome's "โฆ needs โฆpx but a + * โฆpx deck leaves โฆ"), else the refusal itself. + * + * @param {string[]} errors validateChrome's sentences + * @param {{ width?: number, height?: number } | undefined} render + */ +export function deckRefusedDetail(errors, render) { + const size = render?.width && render?.height ? ` (${render.width}ร${render.height})` : ""; + const small = (errors ?? []).find((e) => /needs \d+px but a \d+px deck leaves/.test(e)); + if (small) return `frame too small for the deck${size}: ${small} โ no deck added, so the flips and threads are skipped`; + return `the deck was refused: ${(errors ?? []).join("; ")}`; +} + /** The audit file each task writes beside the manifest (narrate's kept its old name). */ export const draftFileOf = (task) => (task === "narrate" ? "narration-draft.json" : `${task}-draft.json`); diff --git a/umtool/lib/report/chain-draft.test.mjs b/umtool/lib/report/chain-draft.test.mjs @@ -12,12 +12,12 @@ import assert from "node:assert/strict"; import test, { after, before } from "node:test"; import { spawn } from "node:child_process"; import http from "node:http"; -import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { CHAIN_RUN, REPO_ROOT } from "./chain.mjs"; -import { deckChrome, deckStepDetail, draftOutcome, draftPrecheck, draftFileOf } from "./chain-draft.mjs"; +import { deckChrome, deckRefusedDetail, deckStepDetail, draftOutcome, draftPrecheck, draftFileOf } from "./chain-draft.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const KIT = path.join(HERE, "..", "..", "..", "common", "testing", "draft"); @@ -216,6 +216,25 @@ test("the social draft (release 29 G2): done, and its posts written to out/x.txt assert.equal(recorded("draft-social").detail, "2 social posts drafted; out/x.txt and out/bluesky.txt written"); assert.equal(readFileSync(path.join(PROJECT, "out", "x.txt"), "utf8"), `The post.\n\n${link}\n\nโ 2/2 โ\nTwo.\n`); assert.equal(readFileSync(path.join(PROJECT, "out", "bluesky.txt"), "utf8"), `The post.\n\n${link}\n`); + // A re-draft that leaves Bluesky with no post removes its old file (review fix). + put(file, { ...baseManifest, publish: { x: { post: `The post.\n\n${link}` } } }); + const again = await (await step("draft-social")).done; + assert.equal(again.code, 0, again.out); + assert.equal(recorded("draft-social").detail, "2 social posts drafted; out/x.txt written"); + assert.equal(existsSync(path.join(PROJECT, "out", "bluesky.txt")), false); + put(file, baseManifest); +}); + +test("the deck step on a frame too small for the deck says so, adds nothing, and the chain goes on", async () => { + const file = path.join(PROJECT, "video.manifest.json"); + put(file, { ...baseManifest, render: { ...baseManifest.render, width: 640, height: 360 } }); + const before = readFileSync(file, "utf8"); + const r = await (await step("deck")).done; + assert.equal(r.code, 0, r.out); + assert.equal(recorded("deck").status, "failed"); + assert.match(recorded("deck").detail, /^frame too small for the deck \(640ร360\): .*needs \d+px but a \d+px deck leaves/); + assert.equal(readFileSync(file, "utf8"), before); + assert.match(deckRefusedDetail(["render.chrome.engine must be \"hyperframes\""], {}), /^the deck was refused: /); put(file, baseManifest); }); diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs @@ -27,7 +27,7 @@ // (manifest.mjs addDeckChrome: a snapshot first) when the cut has none. import { spawn } from "node:child_process"; -import { copyFile, mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; +import { copyFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; @@ -50,8 +50,8 @@ import { toManifestMain } from "yt-dlp-transcript-common/bin/reports-convert"; import { attachVideoMain } from "yt-dlp-transcript-common/bin/reports-attach-video"; import { checkMain } from "yt-dlp-transcript-common/bin/reports-check"; import { ALL_CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, chainStepDef, configuredProjectsRoot, chainTask, chainWindows, originFromSweep } from "./chain.mjs"; -import { deckChrome, deckStepDetail, draftFileOf, draftOutcome, draftPrecheck } from "./chain-draft.mjs"; -import { addDeckChrome } from "./manifest.mjs"; +import { deckChrome, deckRefusedDetail, deckStepDetail, draftFileOf, draftOutcome, draftPrecheck } from "./chain-draft.mjs"; +import { ChromeRefused, addDeckChrome } from "./manifest.mjs"; import { socialTexts } from "umtool-report-to-video/social"; import { PIPELINE_DIR } from "./driver.mjs"; import { dedupeMedia, seedFromParent } from "./iterations.mjs"; @@ -376,7 +376,16 @@ async function youtubeText(ctx) { STEPS.deck = async (ctx) => { const file = path.join(ctx.project, "video.manifest.json"); if (!(await exists(file))) throw new StepFailed(`no video manifest at ${file}: run the chain's manifest step first`); - const r = await addDeckChrome(ctx.project, deckChrome()); + let r; + try { + r = await addDeckChrome(ctx.project, deckChrome()); + } catch (err) { + // The deck's defaults need a frame tall enough for the footage beside it: + // a sub-HD cut refuses it, and the step says so (the flips and threads are + // then skipped for want of a deck). + if (err instanceof ChromeRefused) throw new StepFailed(deckRefusedDetail(err.errors, JSON.parse(await readFile(file, "utf8")).render)); + throw err; + } return deckStepDetail(r.added); }; @@ -397,7 +406,11 @@ async function writeSocialFiles(ctx) { await mkdir(out, { recursive: true }); const written = []; for (const { name, text } of socialTexts(manifest)) { - if (text === null) continue; + // A platform with no post loses its old file, as the build's writer does. + if (text === null) { + await rm(path.join(out, name), { force: true }); + continue; + } await writeFile(path.join(out, name), text, "utf8"); written.push(`out/${name}`); } diff --git a/umtool/lib/report/drafted-writer.test.mjs b/umtool/lib/report/drafted-writer.test.mjs @@ -16,6 +16,7 @@ import { fileURLToPath } from "node:url"; import { MANIFEST_NAME, StructureRefused, moveEntry, updateChrome, updateNarration, updateOnscreen, updateTeaser, writeDraftedField, } from "./manifest.mjs"; +import { lintManifest } from "umtool-report-to-video/lint"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const full = () => JSON.parse(readFileSync(path.join(HERE, "../../../common/testing/draft/manifests/full.video.manifest.json"), "utf8")); @@ -143,3 +144,18 @@ test("writeDraftedField: Use this on a social post (release 29 G2) writes it as (e) => e instanceof StructureRefused && /publish\.bluesky\.post is 301 graphemes \(at most 300\)/.test(e.message), ); }); + +test("a social post past its count is a lint warning, never a refusal of the cut's edits (release 29 review)", async (t) => { + const m = drafted(); + m.publish.x = { post: "x".repeat(300) }; + m.publish.videoUrl = "not a url"; + const p = await project(t, m); + // A structural edit of the cut goes through. + await moveEntry(p.dir, "c03", 3); + const after = await p.read(); + assert.equal(after.publish.x.post.length, 300); + const lint = lintManifest(after, { validators: true }); + assert.ok(lint.warnings.some((w) => /publish\.x\.post is 300 characters as X counts them/.test(w)), lint.warnings.join("\n")); + assert.ok(lint.warnings.some((w) => /publish\.videoUrl must be the video's http\(s\) URL/.test(w))); + assert.ok(!lint.errors.some((e) => /publish\./.test(e)), lint.errors.join("\n")); +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -39,7 +39,7 @@ import { parseMuteFrom } from "./playback.mjs"; import { DELIVERABLES_MODES } from "./storage.mjs"; import { createSnapshot, listSnapshots } from "./snapshots.mjs"; import { - DRAFTED_MANIFEST_FIELDS, clearEditedDrafts, isEntryField, pruneDrafted, validateDrafted, validatePublish, + DRAFTED_MANIFEST_FIELDS, clearEditedDrafts, isEntryField, publishWarnings, pruneDrafted, validateDrafted, validatePublish, } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; // Its own write queue, not lib/state.ts's. @@ -1144,8 +1144,8 @@ export async function updateNarration(dir, id, text, { token = null, at = null } * โ and the entries are checked as the build checks * them (validateThreadEntries) * publish.youtube `{ title, description }` (validatePublish) - * publish.x, .bluesky `{ post, thread? }` (validatePublish: each post - * within its platform's count) + * publish.x, .bluesky `{ post, thread? }` (publishWarnings, refused + * here: each post within its platform's count) * * The cut's order ("timeline") is not taken this way: an order replaces every * entry, and is the cut task's to apply. @@ -1181,7 +1181,8 @@ export async function writeDraftedField(dir, { entry = null, field, value }, { t if (field === "publish.youtube" || field === "publish.x" || field === "publish.bluesky") { const key = field.slice("publish.".length); m.publish = { ...(m.publish && typeof m.publish === "object" ? m.publish : {}), [key]: copy() }; - const errors = validatePublish(m); + // The field's own writer refuses what its count refuses (the build only warns). + const errors = [...validatePublish(m), ...(key === "youtube" ? [] : publishWarnings(m, { only: key }))]; if (errors.length) throw new StructureRefused(errors); return { entry: null, field, value: m.publish[key] }; } diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -86,7 +86,7 @@ import { qrUrlFor } from "./render-cards.mjs"; import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs"; import { validatePodcast } from "./build-podcast.mjs"; import { draftsReviewFromNarration, draftsReviewProblems, readDraftsReview } from "./drafts-review.mjs"; -import { orphanDrafts, validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; +import { orphanDrafts, publishWarnings, validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; export const TEASER_HOUSE_CHARS = 34; export const MIN_QR_PX_PER_MODULE_720P = 1.5; @@ -283,6 +283,9 @@ export function lintManifest(manifest, { const warnings = []; const render = manifest.render ?? {}; const height = Number(render.height) || 1080; + // The social posts and the video's URL are not the video's: a problem there + // is said, never a refusal (release 29 G2's review). + warnings.push(...publishWarnings(whole)); for (const { where, src } of imageSrcsOf(manifest, { only })) { if (path.isAbsolute(src) || src.startsWith("~")) {