commit 4c45f197b1bcad5a225238e588a872887011c391
parent 24f0364c3810908e4e74dadcbe1716a09ba155e8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 16 Nov 2026 17:07:03 -0500
Merge lane/cookie-screen round 2: /cookies does everything the settings sections do -- X's full session controls open under its row (login source, Check login, cookie age limit, Connect X account, Refresh, Forget session, where X posts appear), the row's button Connect when no login is held; archive.today's session, host and pace; the browser-cookie source for Rumble, YouTube and Odysee in a small form of its own; each forum host's thread sessions; drawn by the same components as /settings with only their own slice of settings; X's browser spec drawn through the privacy rules; a stale /settings tab no longer writes back cookie keys changed elsewhere; a row's press keeps the other sections as they are, and one section that cannot be read says so in its place
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
33 files changed, 1232 insertions(+), 152 deletions(-)
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -264,7 +264,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| `E2E_UMTOOL_ORIGIN_FILE` | unset (UMTOOL_URL) | A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored. | common/lib/umtoolUrl.ts |
| `E2E_WAYBACK_ORIGIN_FILE` | unset (the real Wayback Machine) | A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/waybackClient.ts |
| `E2E_ARCHIVE_TODAY_ORIGIN_FILE` | unset (the real archive.today) | A file holding one loopback origin; while it exists, the editor's archive.today client sends every request for any archive.today name (archive.ph, archive.today, archive.is, …) there — the fake archive.today a spec starts (`common/testing/web/fakeArchiveToday.mjs`) — and never opens the archive session's browser. The editor's e2e server names a file in each slot's test data (`archive-today-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/archives/archiveTodayClient.ts, common/lib/archives/index.ts |
-| `E2E_FAKE_X_PROFILE_COOKIES_FILE` | unset (Refresh cookies opens the X profile in a real headless browser) | A JSON file of SYNTHETIC cookies (`{delayMs?, fail?, cookies}`); while it exists, Refresh cookies reads the X profile through a fake browser that hands them back and loads nothing — no browser starts, nothing is asked of X. Inert unless `E2E_TEST_ROUTES=1` and the file is inside the process's transcriptsDir. The editor's e2e server names a file in each slot's test data (`cookies-screen.spec`). | common/social/fakeXProfileBrowser.ts (editor/app/settings/xSessionActions.ts) |
+| `E2E_FAKE_X_PROFILE_COOKIES_FILE` | unset (Refresh cookies opens the X profile in a real headless browser) | A JSON file of SYNTHETIC cookies (`{delayMs?, fail?, cookies}`); while it exists, Refresh cookies and Connect X account open the X profile in a fake browser that hands them back and loads nothing (Connect's window closes by itself after `closeAfterMs`) — no browser starts, nothing is asked of X. Inert unless `E2E_TEST_ROUTES=1` and the file is inside the process's transcriptsDir. The editor's e2e server names a file in each slot's test data (`cookies-screen.spec`). | common/social/fakeXProfileBrowser.ts (editor/app/settings/xSessionActions.ts) |
| `E2E_BLUESKY_ORIGIN_FILE` | unset (the real Bluesky) | A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored. | common/social/blueskyEndpoints.ts |
| `E2E_AUDIO_CHECK_DEBUG_PAUSE_MS` | off | A debugging pause inside the audio check. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_FAKE_YTDLP_AUDIO_CHECK_MODE` | — | Fake yt-dlp: which audio-check scenario to act out. | editor/e2e/fixtures/bin/fake-ytdlp.mjs |
diff --git a/common/lib/cookieStatus.test.ts b/common/lib/cookieStatus.test.ts
@@ -176,3 +176,27 @@ test("forum hosts: from the profiles and from the state, sorted; Connect needs a
assert.deepEqual(forumThreadFor(state, "kiwifarms.st"), { url: "https://kiwifarms.st/threads/t.1/" });
assert.equal(forumThreadFor(state, "forum.example.org"), null);
});
+
+test("X with a profile that holds no login: the one press is Connect, not Refresh", () => {
+ const x = row(buildCookieStatus(input({ x: { source: "profile", profileDir: "/p", hasProfile: true, loggedIn: false } })), "x");
+ assert.deepEqual(x.button, { action: "connect", label: "Connect X account" });
+ assert.equal(x.headed, true);
+ const logged = row(buildCookieStatus(input({ x: { source: "profile", profileDir: "/p", hasProfile: true, loggedIn: true } })), "x");
+ assert.equal(logged.button?.action, "refresh");
+});
+
+test("forum thread channels add their hosts, name their channels, and give Connect a thread", () => {
+ const forumChannels = [
+ { host: "www.forum.example.org", slug: "b-thread", url: "https://forum.example.org/threads/b.2/" },
+ { host: "forum.example.org", slug: "a-thread", url: "https://forum.example.org/threads/a.1/" },
+ ];
+ const p = buildCookieStatus(input({ forumChannels }));
+ const f = row(p, "forum.example.org");
+ assert.deepEqual(f.channels, ["a-thread", "b-thread"]);
+ assert.equal(f.button?.disabled, undefined);
+ assert.equal(f.source, "No forum profile yet");
+ assert.deepEqual(forumThreadFor(emptyServiceCookieState(), "forum.example.org", forumChannels), {
+ url: "https://forum.example.org/threads/b.2/",
+ channel: "b-thread",
+ });
+});
diff --git a/common/lib/cookieStatus.ts b/common/lib/cookieStatus.ts
@@ -56,6 +56,9 @@ export type CookieRow = {
button: CookieRowButton | null;
last?: ServiceCookieAction;
running?: CookieRunning;
+ // A forum host's thread channels (each one's page carries its retry and
+ // import controls; each one's Connect opens at its own thread).
+ channels?: string[];
};
export type CookieRunning = { action: CookieRowButton["action"]; since: string; jobId?: string };
@@ -81,11 +84,15 @@ export type CookieStatusInput = {
browserSpec?: string;
profileDir: string;
hasProfile: boolean;
+ // The exported jar holds an X login (auth_token).
+ loggedIn?: boolean;
jar?: XJarStatusView;
};
ytdlp: Record<"rumble" | "youtube" | "odysee", YtdlpCookieInput>;
archive: { dir: string; hasProfile: boolean; connectedAt?: string; cleared?: boolean };
forums: { host: string; dir: string; hasProfile: boolean; connectedAt?: string; cleared?: boolean }[];
+ // The forum-thread channels, by host (each with its thread URL).
+ forumChannels?: { host: string; slug: string; url: string }[];
running: Record<string, CookieRunning>;
display: Displayers;
};
@@ -186,7 +193,9 @@ export function buildCookieStatus(input: CookieStatusInput): CookieStatusPayload
...(!at ? { ageUnknown: x.hasProfile ? "No cookie jar exported yet." : "No X profile connected yet." } : {}),
state: settle(!!at, a),
...(a.alert ? { alert: a.alert } : {}),
- ...(x.hasProfile
+ // Refresh re-exports a LOGGED-IN profile; with no login in it yet the
+ // one press is the login itself.
+ ...(x.hasProfile && x.loggedIn !== false
? { button: { action: "refresh", label: "Refresh cookies" } }
: { headed: true, todo: HEADED_NOTE, button: { action: "connect", label: "Connect X account" } }),
});
@@ -273,11 +282,18 @@ export function buildCookieStatus(input: CookieStatusInput): CookieStatusPayload
for (const key of [...Object.keys(input.state.services), ...Object.keys(input.state.lastGood)]) {
if (serviceFamily(key) === "forum" && !hosts.has(key)) hosts.set(key, null);
}
+ const byHost = new Map<string, { slug: string; url: string }[]>();
+ for (const c of input.forumChannels ?? []) {
+ const key = forumServiceKey(c.host);
+ if (!hosts.has(key)) hosts.set(key, null);
+ byHost.set(key, [...(byHost.get(key) ?? []), { slug: c.slug, url: c.url }]);
+ }
for (const [host, f] of [...hosts.entries()].sort(([a], [b]) => a.localeCompare(b))) {
const a = alertFields(host, input);
const at = f?.connectedAt ?? null;
const entry = input.state.services[host];
- const thread = input.state.lastGood[host]?.url ?? entry?.evidence.url;
+ const channels = (byHost.get(host) ?? []).map((c) => c.slug).sort();
+ const thread = input.state.lastGood[host]?.url ?? entry?.evidence.url ?? byHost.get(host)?.[0]?.url;
rows.push({
...common(host),
source: f ? `Forum profile (${display.path(f.dir)})` : "No forum profile yet",
@@ -293,6 +309,7 @@ export function buildCookieStatus(input: CookieStatusInput): CookieStatusPayload
label: "Connect forum session",
...(thread ? {} : { disabled: "No thread on this forum is recorded yet: connect from the thread's channel page." }),
},
+ ...(channels.length ? { channels } : {}),
});
}
@@ -300,11 +317,16 @@ export function buildCookieStatus(input: CookieStatusInput): CookieStatusPayload
}
// The thread a forum host's Connect opens at: the last clean page, else the
-// page that met the check.
-export function forumThreadFor(state: ServiceCookieState, host: string): { url: string; channel?: string } | null {
+// page that met the check, else the first thread channel on the host.
+export function forumThreadFor(
+ state: ServiceCookieState,
+ host: string,
+ channels: readonly { host: string; slug: string; url: string }[] = [],
+): { url: string; channel?: string } | null {
const good = state.lastGood[host];
if (good) return { url: good.url, ...(good.channel ? { channel: good.channel } : {}) };
const e = state.services[host];
if (e?.evidence.url) return { url: e.evidence.url, ...(e.evidence.channel ? { channel: e.evidence.channel } : {}) };
- return null;
+ const c = channels.find((x) => forumServiceKey(x.host) === host);
+ return c ? { url: c.url, channel: c.slug } : null;
}
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -261,7 +261,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." },
{ name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." },
{ name: "E2E_ARCHIVE_TODAY_ORIGIN_FILE", audience: "test", default: "unset (the real archive.today)", readBy: "common/lib/archives/archiveTodayClient.ts, common/lib/archives/index.ts", doc: "A file holding one loopback origin; while it exists, the editor's archive.today client sends every request for any archive.today name (archive.ph, archive.today, archive.is, …) there — the fake archive.today a spec starts (`common/testing/web/fakeArchiveToday.mjs`) — and never opens the archive session's browser. The editor's e2e server names a file in each slot's test data (`archive-today-pages.spec`); anything but a loopback origin in it is ignored." },
- { name: "E2E_FAKE_X_PROFILE_COOKIES_FILE", audience: "test", default: "unset (Refresh cookies opens the X profile in a real headless browser)", readBy: "common/social/fakeXProfileBrowser.ts (editor/app/settings/xSessionActions.ts)", doc: "A JSON file of SYNTHETIC cookies (`{delayMs?, fail?, cookies}`); while it exists, Refresh cookies reads the X profile through a fake browser that hands them back and loads nothing — no browser starts, nothing is asked of X. Inert unless `E2E_TEST_ROUTES=1` and the file is inside the process's transcriptsDir. The editor's e2e server names a file in each slot's test data (`cookies-screen.spec`)." },
+ { name: "E2E_FAKE_X_PROFILE_COOKIES_FILE", audience: "test", default: "unset (Refresh cookies opens the X profile in a real headless browser)", readBy: "common/social/fakeXProfileBrowser.ts (editor/app/settings/xSessionActions.ts)", doc: "A JSON file of SYNTHETIC cookies (`{delayMs?, fail?, cookies}`); while it exists, Refresh cookies and Connect X account open the X profile in a fake browser that hands them back and loads nothing (Connect's window closes by itself after `closeAfterMs`) — no browser starts, nothing is asked of X. Inert unless `E2E_TEST_ROUTES=1` and the file is inside the process's transcriptsDir. The editor's e2e server names a file in each slot's test data (`cookies-screen.spec`)." },
{ name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." },
{ name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." },
{ name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." },
diff --git a/common/social/fakeXProfileBrowser.test.ts b/common/social/fakeXProfileBrowser.test.ts
@@ -11,7 +11,7 @@ import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from "node:fs/promis
import os from "node:os";
import path from "node:path";
import { fakeXProfileChromium, fakeXProfileCookiesFile } from "./fakeXProfileBrowser";
-import { readXSessionStatus, refreshXCookies } from "./xSessionBroker";
+import { clearXSession, connectXAccount, readXSessionStatus, refreshXCookies } from "./xSessionBroker";
test("the gate: test server, inside transcriptsDir, the file exists", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "fake-x-"));
@@ -66,3 +66,27 @@ test("refreshXCookies on the fake writes the jar from the fixture's cookies", as
await rm(root, { recursive: true, force: true });
}
});
+
+test("connectXAccount on the fake: the window closes by itself, the login is exported; clearXSession forgets it", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "fake-x-"));
+ try {
+ const paths = { transcriptsDir: root } as Parameters<typeof connectXAccount>[0];
+ const file = path.join(root, ".fake-x-profile-cookies.json");
+ await writeFile(
+ file,
+ JSON.stringify({ closeAfterMs: 50, cookies: [{ name: "auth_token", value: "fixture-not-a-token", domain: ".x.com" }] }),
+ );
+ const chromium = fakeXProfileChromium(root, { E2E_TEST_ROUTES: "1", E2E_FAKE_X_PROFILE_COOKIES_FILE: file });
+ assert.ok(chromium);
+ // No system browser looked up: an empty PATH is the bundled build.
+ const status = await connectXAccount(paths, { chromium, env: { PATH: "" } });
+ assert.equal(status.looksAuthenticated, true);
+ assert.equal(status.hasProfile, true);
+ await clearXSession(paths);
+ const after = await readXSessionStatus(paths);
+ assert.equal(after.hasProfile, false);
+ assert.equal(after.hasCookies, false);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/common/social/fakeXProfileBrowser.ts b/common/social/fakeXProfileBrowser.ts
@@ -1,18 +1,22 @@
-// A FAKE BROWSER FOR "Refresh cookies", for the editor's e2e suite only
+// A FAKE BROWSER FOR "Refresh cookies" AND "Connect X account", for the
+// editor's e2e suite only
// (E2E_FAKE_X_PROFILE_COOKIES_FILE, set per slot by editor/e2e/servers.ts).
// refreshXCookies (xSessionBroker.ts) takes a `chromium`; under the test server
// it is handed this one, whose persistent context hands back the cookies a
// spec wrote into the file (after its `delayMs`, so a spec can watch the press
// run and be refused a second time) and whose page loads nothing — no browser
-// starts and nothing is asked of X. Everything after the browser (the jar
-// written, the login check, the status) is the real code.
+// starts and nothing is asked of X. Connect's "window" closes by itself after
+// `closeAfterMs` (the human closing it), and the cookies are exported as from
+// a login. Everything after the browser (the jar written, the login check, the
+// status) is the real code.
//
// INERT ON A REAL EDITOR, three ways: it answers null unless the process is the
// e2e test server (E2E_TEST_ROUTES=1, which editor/playwright.config.ts sets on
// its server and nothing else does), unless the variable names a file INSIDE
// this process's transcriptsDir (a slot's test data), and unless that file
// exists (a spec writes it). The file holds SYNTHETIC cookies only:
-// { "delayMs"?: number, "fail"?: string, "cookies": [{ name, value, domain, path?, expires? }] }
+// { "delayMs"?: number, "closeAfterMs"?: number, "fail"?: string,
+// "cookies": [{ name, value, domain, path?, expires? }] }
import { readFileSync, realpathSync } from "node:fs";
import path from "node:path";
@@ -20,6 +24,7 @@ import type { BrowserContextLike, ChromiumLike, PageLike } from "./playwrightRun
type FixtureFile = {
delayMs?: number;
+ closeAfterMs?: number;
fail?: string;
cookies?: Array<{ name: string; value: string; domain: string; path?: string; expires?: number }>;
};
@@ -84,7 +89,10 @@ export function fakeXProfileChromium(
})),
addCookies: async () => {},
close: async () => {},
- on: () => {},
+ // Connect waits for the window to close: the fake's closes by itself.
+ on: (event: string, cb: () => void) => {
+ if (event === "close") setTimeout(cb, Math.min(Math.max(readFixture(file).closeAfterMs ?? 0, 0), 30_000));
+ },
};
return {
launch: async () => {
diff --git a/common/social/xSessionBroker.ts b/common/social/xSessionBroker.ts
@@ -184,6 +184,9 @@ export async function connectXAccount(
onLog?: (line: string) => void;
timeoutMs?: number;
env?: Record<string, string | undefined>;
+ // Injectable so the flow is testable without a browser (the e2e suite's
+ // fake, social/fakeXProfileBrowser.ts).
+ chromium?: ChromiumLike;
} = {},
): Promise<XSessionStatus & { browser: string }> {
const log = opts.onLog ?? (() => {});
@@ -193,7 +196,7 @@ export async function connectXAccount(
const browser = findXBrowser({ env: opts.env });
const version = await browserVersion(browser);
const label = describeXBrowser(browser, version);
- const { chromium } = await importPlaywright();
+ const chromium = opts.chromium ?? (await importPlaywright()).chromium;
log(`Opening ${label}. Log in to X, then close the window.`);
let context: BrowserContextLike;
try {
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,18 @@
# Changelog
## [Unreleased]
+- **/cookies now has every cookie and session control /settings has, and logging in to X is one press away.** Each
+ row still starts with its status and its one button, and the whole session block now sits under it:
+ - X: login source, Check, the cookie-age limit, Connect X account, Refresh cookies, Forget session and where X posts
+ appear. This block is open by default.
+ - archive.today: the session's Connect, the host, the gap, the cooldown and reading past a check with the browser.
+ - Rumble, YouTube and Odysee: the browser yt-dlp reads cookies from, and the cookie mode, saved on their own.
+ - Each forum host: each thread channel's Connect forum session, with a link to the thread's page for its retry and
+ saved-page import.
+
+ These are the same components /settings and the forum page draw, given only their own slice of settings. With an X
+ profile that holds no login, the row's button is Connect X account instead of Refresh cookies. A forum thread
+ channel's host gets its row even before it has a profile. /settings keeps its sections as they were.
- **Cookies has its own screen: `/cookies`, in the Machine group of the nav.** It has one row for each service the
editor reads cookies for: X, Rumble, YouTube, Odysee, archive.today and each forum host. A row says where the cookies
come from, how old they are ("clearance issued 40 min ago · expires in 50 min", "jar written just now"), whether the
diff --git a/editor/app/channels/[slug]/components/ForumSessionConnect.tsx b/editor/app/channels/[slug]/components/ForumSessionConnect.tsx
@@ -0,0 +1,94 @@
+"use client";
+
+// A FORUM THREAD'S SESSION — its host's profile state and Connect, which opens
+// that profile in a window on the machine running the editor, at the thread
+// (connectForumSessionAction). Drawn by the channel page's forum panel
+// (SocialChannelPanel, with its retry and import controls below it) and by the
+// /cookies screen's forum row, one per thread channel on the host: one
+// component, so the two places cannot drift.
+
+import { useState, useTransition } from "react";
+import type { ForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession";
+import { connectForumSessionAction } from "../socialActions";
+
+export function forumSessionLine(s: ForumSessionStatus | undefined): string {
+ return s?.lastConnect
+ ? `${s.host}: connected ${new Date(s.lastConnect.connectedAt).toLocaleString()}` +
+ (s.lastConnect.cleared ? "" : " (the thread did not show)")
+ : s?.hasProfile
+ ? `${s.host}: profile in use, never connected by hand`
+ : `${s?.host ?? "this forum"}: no profile yet`;
+}
+
+export function ForumSessionConnect({
+ slug,
+ status,
+ onChange,
+}: {
+ slug: string;
+ status?: ForumSessionStatus;
+ // Told after a Connect ends (the /cookies screen re-reads its row).
+ onChange?: () => void;
+}) {
+ const [session, setSession] = useState(status);
+ const [note, setNote] = useState<string | null>(null);
+ const [err, setErr] = useState<string | null>(null);
+ const [pending, start] = useTransition();
+ const connect = () =>
+ start(async () => {
+ setNote(null);
+ setErr(null);
+ const res = await connectForumSessionAction(slug);
+ if (res.ok) {
+ if (session) setSession({ ...session, hasProfile: true, lastConnect: res.record });
+ setNote(
+ res.record.cleared
+ ? "Connected: the thread showed before the window closed. Fetch again."
+ : "The window closed before a thread page showed; the profile kept what it had.",
+ );
+ } else {
+ setErr(res.error);
+ }
+ onChange?.();
+ });
+ return (
+ <>
+ <div className="flex flex-wrap items-baseline gap-x-3">
+ <h2 className="text-sm font-medium">Forum session</h2>
+ <span aria-label="forum session state" className="text-xs text-muted-foreground">
+ {forumSessionLine(session)}
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ The fetcher reads the thread in a headless browser that keeps one
+ profile per forum host, so a browser check it clears once (Kiwi
+ Farms' KiwiFlare, say) stays cleared. When a check will not
+ clear by itself, or the thread needs a login, Connect opens that
+ profile in a window <strong>on the machine running the
+ editor</strong>, at the thread: clear it (or log in), wait for the
+ thread to show, then close the window.
+ </p>
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={connect}
+ disabled={pending}
+ aria-label="connect forum session"
+ className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50"
+ >
+ {pending ? "Working…" : "Connect forum session"}
+ </button>
+ </div>
+ {note && (
+ <p role="status" aria-label="forum session result" className="text-xs text-success">
+ {note}
+ </p>
+ )}
+ {err && (
+ <p role="alert" className="text-xs text-destructive">
+ {err}
+ </p>
+ )}
+ </>
+ );
+}
diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx
@@ -10,13 +10,13 @@ import Link from "next/link";
import { useState, useTransition } from "react";
import {
checkPostAvailabilityAction,
- connectForumSessionAction,
fetchPostsAction,
importForumPagesAction,
setForumRetryOnBlockAction,
setPostFetcherAction,
} from "../socialActions";
import type { ForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession";
+import { ForumSessionConnect } from "./ForumSessionConnect";
import {
describeRetryOnBlock,
roughDuration,
@@ -109,22 +109,6 @@ export function SocialChannelPanel({
const [forumErr, setForumErr] = useState<string | null>(null);
const [importPath, setImportPath] = useState("");
- const connect = () =>
- startTransition(async () => {
- setForumNote(null);
- setForumErr(null);
- const res = await connectForumSessionAction(slug);
- if (res.ok) {
- setForumNote(
- res.record.cleared
- ? "Connected: the thread showed before the window closed. Fetch again."
- : "The window closed before a thread page showed; the profile kept what it had.",
- );
- } else {
- setForumErr(res.error);
- }
- });
-
const importPages = () =>
startTransition(async () => {
setForumNote(null);
@@ -506,37 +490,8 @@ export function SocialChannelPanel({
data-forum-session=""
className="flex flex-col gap-3 rounded-lg border border-border bg-card p-4"
>
- <div className="flex flex-wrap items-baseline gap-x-3">
- <h2 className="text-sm font-medium">Forum session</h2>
- <span aria-label="forum session state" className="text-xs text-muted-foreground">
- {state.forumSession?.lastConnect
- ? `${state.forumSession.host}: connected ${new Date(state.forumSession.lastConnect.connectedAt).toLocaleString()}` +
- (state.forumSession.lastConnect.cleared ? "" : " (the thread did not show)")
- : state.forumSession?.hasProfile
- ? `${state.forumSession.host}: profile in use, never connected by hand`
- : `${state.forumSession?.host ?? "this forum"}: no profile yet`}
- </span>
- </div>
- <p className="text-xs text-muted-foreground">
- The fetcher reads the thread in a headless browser that keeps one
- profile per forum host, so a browser check it clears once (Kiwi
- Farms' KiwiFlare, say) stays cleared. When a check will not
- clear by itself, or the thread needs a login, Connect opens that
- profile in a window <strong>on the machine running the
- editor</strong>, at the thread: clear it (or log in), wait for the
- thread to show, then close the window.
- </p>
- <div className="flex flex-wrap gap-2">
- <button
- type="button"
- onClick={connect}
- disabled={pending}
- aria-label="connect forum session"
- className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50"
- >
- {pending ? "Working…" : "Connect forum session"}
- </button>
- </div>
+ {/* Shared with the /cookies screen's forum row. */}
+ <ForumSessionConnect slug={slug} {...(state.forumSession ? { status: state.forumSession } : {})} />
<div className="flex flex-col gap-1 border-t border-border pt-3 text-sm">
<span className="font-medium">Retry after a block</span>
diff --git a/editor/app/cookies/CookiesBoard.tsx b/editor/app/cookies/CookiesBoard.tsx
@@ -7,14 +7,20 @@
// refused in words: here at once, and by the server for another tab or the
// recheck timer (editor/app/lib/cookieRefreshGuard.ts).
-import { useEffect, useState } from "react";
+import Link from "next/link";
+import { useEffect, useState, type ReactNode } from "react";
import {
ageSentence,
type CookieRow,
type CookieStatusPayload,
} from "yt-dlp-transcript-common/lib/cookieStatus";
import { usePolledPayload } from "../lib/usePolledPayload";
-import { pressCookieButtonAction } from "./actions";
+import { cookieControlsAction, pressCookieButtonAction } from "./actions";
+import { sectionFailed, type CookieControls } from "../lib/cookieControlsTypes";
+import { XSessionSection } from "../settings/components/XSessionSection";
+import { ArchiveSourcesSection } from "../settings/components/ArchiveSessionSection";
+import { YtdlpCookieSourceForm } from "../settings/components/YtdlpCookieFields";
+import { ForumSessionConnect } from "../channels/[slug]/components/ForumSessionConnect";
const POLL_MS = 30_000;
@@ -43,7 +49,16 @@ function useNow(ms: number): number {
return now;
}
-function Row({ row, onStatus }: { row: CookieRow; onStatus: (s: CookieStatusPayload) => void }) {
+function Row({
+ row,
+ onStatus,
+ children,
+}: {
+ row: CookieRow;
+ onStatus: (s: CookieStatusPayload) => void;
+ // The service's full controls, under its status and its one button.
+ children?: ReactNode;
+}) {
const [pending, setPending] = useState<{ since: string } | null>(null);
const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);
const now = useNow(pending ? 1000 : 30_000);
@@ -155,12 +170,98 @@ function Row({ row, onStatus }: { row: CookieRow; onStatus: (s: CookieStatusPayl
<span className={row.last.ok ? "" : "text-destructive"}>{row.last.message}</span>
</p>
)}
+ {children}
</li>
);
}
-export function CookiesBoard({ initial }: { initial: CookieStatusPayload }) {
- const { data } = usePolledPayload<CookieStatusPayload>("/api/view/cookieStatus", true, POLL_MS, initial, {
+const DISCLOSURE = "border-t border-border pt-2";
+const SUMMARY = "cursor-pointer text-sm font-medium";
+
+// A section whose read failed says so in its place; the rest still draw.
+function SectionError({ what, error }: { what: string; error: string }) {
+ return (
+ <p role="alert" aria-label={`${what} controls error`} className="text-xs text-destructive break-words">
+ {error}
+ </p>
+ );
+}
+
+// Each service's whole session block, as /settings (and a forum channel's
+// page) draws it: X's open, so logging in is one press away; the others one
+// click away. `gen` re-keys the SECTION (never its disclosure) and only for
+// the row that was pressed, so a press elsewhere keeps what is being typed here.
+function Controls({
+ row,
+ controls,
+ gen,
+ refetch,
+}: {
+ row: CookieRow;
+ controls: CookieControls;
+ gen: number;
+ refetch: () => void;
+}): ReactNode {
+ if (row.service === "x") {
+ const x = controls.x;
+ return (
+ <details open className={DISCLOSURE} aria-label="X controls">
+ <summary className={SUMMARY}>X account session</summary>
+ <div className="mt-2">
+ {sectionFailed(x) ? (
+ <SectionError what="X" error={x.error} />
+ ) : (
+ <XSessionSection key={gen} {...x} onChange={refetch} cookiesLink={false} />
+ )}
+ </div>
+ </details>
+ );
+ }
+ if (row.service === "archive.today") {
+ const a = controls.archive;
+ return (
+ <details className={DISCLOSURE} aria-label="archive.today controls">
+ <summary className={SUMMARY}>Archive sources: session, host and pace</summary>
+ <div className="mt-2">
+ {sectionFailed(a) ? (
+ <SectionError what="archive.today" error={a.error} />
+ ) : (
+ <ArchiveSourcesSection key={gen} initial={a.initial} session={a.session} onChange={refetch} cookiesLink={false} />
+ )}
+ </div>
+ </details>
+ );
+ }
+ if (row.family === "forum") {
+ const forums = controls.forums;
+ if (sectionFailed(forums)) return <SectionError what={row.label} error={forums.error} />;
+ const f = forums[row.service];
+ if (!f || f.channels.length === 0) return null;
+ return (
+ <details className={DISCLOSURE} aria-label={`${row.label} controls`}>
+ <summary className={SUMMARY}>Forum session, per thread</summary>
+ <div className="mt-2 flex flex-col gap-3">
+ {f.channels.map((slug) => (
+ <section key={`${slug}:${gen}`} data-forum-session="" aria-label={`forum session ${slug}`} className="flex flex-col gap-2">
+ <ForumSessionConnect slug={slug} status={f.status} onChange={refetch} />
+ <p className="text-xs text-muted-foreground">
+ Thread{" "}
+ <Link href={`/channels/${slug}`} className="underline underline-offset-2">
+ {slug}
+ </Link>
+ : its retry after a block and its saved-page import are on its page.
+ </p>
+ </section>
+ ))}
+ </div>
+ </details>
+ );
+ }
+ return null;
+}
+
+export function CookiesBoard({ initial, controls }: { initial: CookieStatusPayload; controls?: CookieControls }) {
+ const { data, refetch } = usePolledPayload<CookieStatusPayload>("/api/view/cookieStatus", true, POLL_MS, initial, {
immediate: false,
});
const [status, setStatus] = useState<CookieStatusPayload>(initial);
@@ -170,11 +271,74 @@ export function CookiesBoard({ initial }: { initial: CookieStatusPayload }) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data]);
const take = (s: CookieStatusPayload) => setStatus((cur) => (s.readAt >= cur.readAt ? s : cur));
+ // A row's press can change what its own controls show (Connect made a
+ // profile): the slices are read again and THAT row's section is drawn
+ // afresh; every other section keeps its state (what is typed, what is open).
+ const [ctl, setCtl] = useState(controls);
+ const [gens, setGens] = useState<Record<string, number>>({});
+ const pressed = (service: string, s: CookieStatusPayload) => {
+ take(s);
+ if (!controls) return;
+ void cookieControlsAction()
+ .then((c) => {
+ setCtl(c);
+ setGens((g) => ({ ...g, [service]: (g[service] ?? 0) + 1 }));
+ })
+ .catch(() => undefined);
+ };
return (
<ul className="flex flex-col gap-3" aria-label="Services">
{status.rows.map((row) => (
- <Row key={row.service} row={row} onStatus={take} />
+ <ItemsFor
+ key={row.service}
+ row={row}
+ take={(s) => pressed(row.service, s)}
+ controls={ctl}
+ gen={gens[row.service] ?? 0}
+ refetch={() => void refetch()}
+ />
))}
</ul>
);
}
+
+// A row, its controls, and — after Odysee, the last of the three yt-dlp
+// services — the browser cookies all three are fetched with.
+function ItemsFor({
+ row,
+ take,
+ controls,
+ gen,
+ refetch,
+}: {
+ row: CookieRow;
+ take: (s: CookieStatusPayload) => void;
+ controls?: CookieControls;
+ gen: number;
+ refetch: () => void;
+}) {
+ return (
+ <>
+ <Row row={row} onStatus={take}>
+ {controls ? <Controls row={row} controls={controls} gen={gen} refetch={refetch} /> : null}
+ </Row>
+ {controls && row.service === "odysee" && (
+ <li
+ aria-label="yt-dlp cookie source"
+ className="flex flex-col gap-2 rounded-lg border border-border bg-card p-3 sm:p-4"
+ >
+ <h2 className="text-base font-medium">Browser cookies for Rumble, YouTube and Odysee</h2>
+ {sectionFailed(controls.ytdlp) ? (
+ <SectionError what="yt-dlp cookie" error={controls.ytdlp.error} />
+ ) : (
+ <YtdlpCookieSourceForm
+ cookiesFromBrowser={controls.ytdlp.cookiesFromBrowser}
+ cookieMode={controls.ytdlp.cookieMode}
+ onSaved={refetch}
+ />
+ )}
+ </li>
+ )}
+ </>
+ );
+}
diff --git a/editor/app/cookies/actions.ts b/editor/app/cookies/actions.ts
@@ -10,7 +10,8 @@
// x · connect connectXAccountAction (a headed window on the editor's machine)
// * · recheck recheckServiceCookiesAction (the dashboard's Recheck)
// archive.today connectArchiveSessionAction (headed)
-// a forum host connectForumAt, at the thread the app last met there (headed)
+// a forum host connectForumAt, at the thread the app last met there, else
+// the host's first thread channel (headed)
//
// Every one of them goes through lib/cookieRefreshGuard.ts: a second press
// while one runs is refused with a sentence, and the outcome is the row's
@@ -33,7 +34,9 @@ import { connectXAccountAction, refreshXCookiesAction } from "../settings/xSessi
import { connectArchiveSessionAction } from "../settings/archiveSessionActions";
import { recheckServiceCookiesAction } from "../operations/serviceCookiesActions";
import { connectForumAt } from "../lib/connectForum";
+import { listForumChannels } from "../lib/forumChannels";
import { loadCookieStatus } from "../lib/cookieStatus";
+import { loadCookieControls, type CookieControls } from "../lib/cookieControls";
export type CookiePressResult = {
ok: boolean;
@@ -77,7 +80,7 @@ async function press(service: string, action: string): Promise<Answer> {
return answerOf(r, r.ok ? (r.record.cleared ? "Connected: the check is passed." : "The window closed on a check page: not cleared.") : "");
}
if (family === "forum" && action === "connect") {
- const thread = forumThreadFor(await readServiceCookieState(paths), service);
+ const thread = forumThreadFor(await readServiceCookieState(paths), service, await listForumChannels(paths).catch(() => []));
if (!thread) return { ok: false, message: `No thread on ${service} is recorded yet: connect from the thread's channel page.` };
const r = await connectForumAt(thread.url, service, thread.channel);
return answerOf(r, r.ok ? (r.record.cleared ? "Connected: the thread showed." : "The window closed before the thread showed: not cleared.") : "");
@@ -85,6 +88,13 @@ async function press(service: string, action: string): Promise<Answer> {
return { ok: false, message: `${serviceLabel(service)} has no "${action}" here.` };
}
+// The full controls' own slices, read again after a row's press changed what
+// they show (a Connect made a profile, a Refresh a jar): the same reads the
+// page made, never the whole settings object.
+export async function cookieControlsAction(): Promise<CookieControls> {
+ return loadCookieControls(getPaths());
+}
+
export async function pressCookieButtonAction(service: string, action: string): Promise<CookiePressResult> {
let answer: Answer;
try {
diff --git a/editor/app/cookies/page.tsx b/editor/app/cookies/page.tsx
@@ -1,22 +1,26 @@
import type { Metadata } from "next";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { loadCookieStatus } from "../lib/cookieStatus";
+import { loadCookieControls } from "../lib/cookieControls";
import { CookiesBoard } from "./CookiesBoard";
// THE COOKIES SCREEN (plans/cookie-screen.md): one row per service the editor
// reads cookies for, each with its one refresh. It reads only what the rows
// show (lib/cookieStatus.ts) — never the whole settings object /settings ships
// to its form — so it loads fast from a phone, and polls its own rows after.
+// Under each row, that service's whole session block, as /settings draws it.
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Cookies" };
export default async function CookiesPage() {
- const initial = await loadCookieStatus(getPaths());
+ // The rows, and each service's full controls fed only its own slice of
+ // settings (lib/cookieControls.ts) — never the whole object.
+ const [initial, controls] = await Promise.all([loadCookieStatus(getPaths()), loadCookieControls(getPaths())]);
return (
<div className="flex flex-col gap-4">
<h1 className="text-2xl font-semibold">Cookies</h1>
- <CookiesBoard initial={initial} />
+ <CookiesBoard initial={initial} controls={controls} />
</div>
);
}
diff --git a/editor/app/lib/cookieControls.test.ts b/editor/app/lib/cookieControls.test.ts
@@ -0,0 +1,120 @@
+// The /cookies screen's full controls (cookieControls.ts), the forum-thread
+// channels behind its forum rows (forumChannels.ts) and yt-dlp's cookie keys
+// saved alone (settings/cookieSourceActions.ts), over a temp corpus.
+//
+// Run with: pnpm -C editor exec tsx --test app/lib/cookieControls.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { setupOpsCorpus } from "../api/ops/_testCorpus";
+
+const corpus = await setupOpsCorpus("one-youtube-channel-with-data");
+await corpus.writeSettings({ cookiesFromBrowser: "firefox", cookieMode: "always", minFreeDiskGB: 0 });
+test.after(() => corpus.cleanup());
+
+const { getPaths } = await import("yt-dlp-transcript-common/lib/paths");
+const { listForumChannels } = await import("./forumChannels");
+const { loadCookieControls } = await import("./cookieControls");
+const { sectionFailed } = await import("./cookieControlsTypes");
+function ok<T extends object>(v: T | { error: string }): T {
+ if (sectionFailed(v)) throw new Error(v.error);
+ return v as T;
+}
+const { saveYtdlpCookieSourceAction } = await import("../settings/cookieSourceActions");
+
+async function forumChannel(slug: string, url: string) {
+ const dir = path.join(corpus.transcripts, "channels", slug);
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ path.join(dir, "config.json"),
+ JSON.stringify({ handling: "youtube", name: slug, sourceKind: "social", platform: "xenforo", postFetcher: "xenforo-thread", url }),
+ );
+}
+
+test("the forum-thread channels: only xenforo threads, by host; remembered until channels/ changes or fresh", async () => {
+ const paths = getPaths();
+ await forumChannel("a-thread", "https://forum.example.test/threads/a-thread.1/");
+ const first = await listForumChannels(paths, { fresh: true });
+ assert.deepEqual(first, [{ host: "forum.example.test", slug: "a-thread", url: "https://forum.example.test/threads/a-thread.1/" }]);
+ // A new channel dir moves channels/'s mtime: read again at once.
+ await forumChannel("b-thread", "https://other.example.test/threads/b-thread.2/");
+ const second = await listForumChannels(paths);
+ assert.deepEqual(second.map((c) => c.slug), ["a-thread", "b-thread"]);
+ // An edit inside a channel does not move channels/'s mtime: remembered…
+ await writeFile(path.join(corpus.transcripts, "channels", "b-thread", "config.json"), JSON.stringify({ handling: "youtube", name: "b" }));
+ assert.equal((await listForumChannels(paths)).length, 2);
+ // …until fresh.
+ assert.deepEqual((await listForumChannels(paths, { fresh: true })).map((c) => c.slug), ["a-thread"]);
+});
+
+test("the controls carry only their slices: X's session, the archive block, yt-dlp's two keys, the forums", async () => {
+ const c = await loadCookieControls(getPaths());
+ assert.deepEqual(Object.keys(c).sort(), ["archive", "forums", "x", "ytdlp"]);
+ assert.deepEqual(c.ytdlp, { cookiesFromBrowser: "firefox", cookieMode: "always" });
+ const x = ok(c.x);
+ assert.equal(x.initial.hasProfile, false);
+ assert.equal(typeof x.initialMaxCookieAge, "number");
+ assert.ok("archiveTodayHost" in ok(c.archive).initial);
+ const forums = ok(c.forums);
+ assert.deepEqual(Object.keys(forums), ["forum.example.test"]);
+ assert.deepEqual(forums["forum.example.test"]?.channels, ["a-thread"]);
+ assert.equal(forums["forum.example.test"]?.status.hasProfile, false);
+ // No other settings block rode along.
+ assert.equal(JSON.stringify(c).includes("autoQueue"), false);
+});
+
+test("one section's read failing is that section's sentence; the others still read", async () => {
+ const c = await loadCookieControls(getPaths(), {
+ getSettings: () => {
+ throw new Error("settings.json is unreadable");
+ },
+ });
+ for (const k of ["x", "archive", "ytdlp"] as const) {
+ assert.equal(sectionFailed(c[k]), true, k);
+ assert.match((c[k] as { error: string }).error, /^Could not read .*settings\.json is unreadable/, k);
+ }
+ assert.equal(sectionFailed(c.forums), false);
+});
+
+test("X's browser spec reaches the client through the privacy rules (lib/xSourceDisplay.ts)", async () => {
+ const { xSourceForDisplay } = await import("./xSourceDisplay");
+ const { resetPrivacyMemo } = await import("yt-dlp-transcript-common/lib/privacy/privacy-server");
+ const home = (await import("node:os")).homedir();
+ await corpus.writeSettings({ cookiesFromBrowser: `firefox:${home}/zq-profile`, privacy: { displayPaths: "masked" } });
+ resetPrivacyMemo();
+ const v = xSourceForDisplay({
+ source: "browser",
+ chosen: false,
+ browserSpec: `firefox:${home}/zq-profile`,
+ label: `Browser login (firefox:${home}/zq-profile)`,
+ summary: `No store at ${home}/zq-profile.`,
+ });
+ assert.equal(v.source, "browser");
+ for (const s of [v.browserSpec, v.label, v.summary]) assert.equal(String(s).includes(home), false, String(s));
+ assert.match(String(v.browserSpec), /^firefox:.*zq-profile$/);
+ await corpus.writeSettings({ cookiesFromBrowser: "firefox", cookieMode: "always", minFreeDiskGB: 0 });
+ resetPrivacyMemo();
+});
+
+test("yt-dlp's cookie keys save alone: the two keys written, the rest of settings kept, a bad mode is the default", async () => {
+ const fd = new FormData();
+ fd.set("cookiesFromBrowser", " firefox:fixture-profile ");
+ fd.set("cookieMode", "defer");
+ const r = await saveYtdlpCookieSourceAction(undefined, fd);
+ assert.deepEqual(r, { ok: true, cookiesFromBrowser: "firefox:fixture-profile", cookieMode: "defer" });
+ const saved = JSON.parse(await readFile(getPaths().settingsFile, "utf8")) as Record<string, unknown>;
+ assert.equal(saved.cookiesFromBrowser, "firefox:fixture-profile");
+ assert.equal(saved.cookieMode, "defer");
+ assert.equal(saved.minFreeDiskGB, 0);
+ const bad = new FormData();
+ bad.set("cookiesFromBrowser", "");
+ bad.set("cookieMode", "sometimes");
+ const r2 = await saveYtdlpCookieSourceAction(undefined, bad);
+ assert.deepEqual(r2, { ok: true, cookiesFromBrowser: "", cookieMode: "when-required" });
+});
+
+test.after(async () => {
+ await rm(path.join(corpus.transcripts, "channels", "a-thread"), { recursive: true, force: true });
+});
diff --git a/editor/app/lib/cookieControls.ts b/editor/app/lib/cookieControls.ts
@@ -0,0 +1,90 @@
+// THE /cookies SCREEN'S FULL CONTROLS — each service's whole session block, as
+// /settings and a forum channel's page draw it (XSessionSection,
+// ArchiveSourcesSection, the yt-dlp cookie fields, ForumSessionConnect), fed
+// ONLY its own slice: the same reads /settings' page makes for those sections
+// (the X profile's status, the login source in use, social.x's visibility and
+// age limit; settings.archives and the archive session; cookiesFromBrowser and
+// cookieMode), and each forum host's session status. Never the whole settings
+// object, never a corpus walk. The rows themselves are lib/cookieStatus.ts.
+
+import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings, type SiteSettings } from "yt-dlp-transcript-common/lib/settings";
+import { displayText } from "yt-dlp-transcript-common/lib/privacy/privacy-server";
+import { readXSessionStatus, type XSessionStatus } from "yt-dlp-transcript-common/social/xSessionBroker";
+import { resolveXCookieSourceFor } from "yt-dlp-transcript-common/social/xBrowserLogin";
+import {
+ xCookieSourceView,
+ xMaxCookieAgeMinutes,
+ type XCookieSourceView,
+ type XPostsVisibility,
+} from "yt-dlp-transcript-common/social/xCookieSource";
+import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility";
+import { readArchiveSessionStatus, type ArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession";
+import type { ArchivesSettings } from "yt-dlp-transcript-common/lib/archives/settings";
+import { readForumSessionStatus, type ForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession";
+import { forumServiceKey } from "yt-dlp-transcript-common/lib/serviceCookies";
+import { DEFAULT_COOKIE_MODE } from "yt-dlp-transcript-common/lib/cookiePolicy";
+import { listForumChannels } from "./forumChannels";
+import { xSourceForDisplay } from "./xSourceDisplay";
+
+import { sectionFailed, type CookieControls, type ForumControls, type SectionRead } from "./cookieControlsTypes";
+export { sectionFailed, type CookieControls } from "./cookieControlsTypes";
+
+async function read<T>(what: string, fn: () => Promise<T>): Promise<SectionRead<T>> {
+ try {
+ return await fn();
+ } catch (e) {
+ return { error: displayText(`Could not read ${what}: ${(e as Error).message.split("\n")[0]}`) };
+ }
+}
+
+export async function loadCookieControls(
+ paths: Paths = getPaths(),
+ // Injectable for the tests: a settings read that throws.
+ deps: { getSettings?: () => SiteSettings } = {},
+): Promise<CookieControls> {
+ // One parse, shared; a settings read that throws fails the three sections
+ // that need it, each saying so.
+ const settings = await read("settings.json", async () => (deps.getSettings ?? getSettings)());
+ const need = <T,>(fn: (s: SiteSettings) => Promise<T>) => async (): Promise<T> => {
+ if (sectionFailed(settings)) throw new Error(settings.error);
+ return fn(settings);
+ };
+ const [x, archive, ytdlp, forums] = await Promise.all([
+ read(
+ "X's session",
+ need(async (st) => {
+ const [initial, resolved] = await Promise.all([readXSessionStatus(paths), resolveXCookieSourceFor(paths, st)]);
+ return {
+ initial,
+ // Drawn by the client: its spec and label through settings.privacy.
+ initialSource: xSourceForDisplay(xCookieSourceView(resolved)),
+ initialVisibility: xPostsVisibility(st),
+ initialMaxCookieAge: xMaxCookieAgeMinutes(st.social.x),
+ };
+ }),
+ ),
+ read(
+ "archive.today's session",
+ need(async (st) => ({ initial: st.archives, session: await readArchiveSessionStatus(paths) })),
+ ),
+ read(
+ "yt-dlp's cookie settings",
+ need(async (st) => ({
+ cookiesFromBrowser: st.cookiesFromBrowser ?? "",
+ cookieMode: st.cookieMode ?? DEFAULT_COOKIE_MODE,
+ })),
+ ),
+ read("the forum sessions", async () => {
+ const out: ForumControls = {};
+ for (const c of await listForumChannels(paths)) {
+ const key = forumServiceKey(c.host);
+ if (!out[key]) out[key] = { status: await readForumSessionStatus(paths, c.host), channels: [] };
+ out[key]!.channels.push(c.slug);
+ }
+ for (const f of Object.values(out)) f.channels.sort();
+ return out;
+ }),
+ ]);
+ return { x, archive, ytdlp, forums };
+}
diff --git a/editor/app/lib/cookieControlsTypes.ts b/editor/app/lib/cookieControlsTypes.ts
@@ -0,0 +1,35 @@
+// THE /cookies CONTROLS' SHAPES — client-safe (the board imports
+// `sectionFailed`); the server read is cookieControls.ts.
+
+import type { XSessionStatus } from "yt-dlp-transcript-common/social/xSessionBroker";
+import type { XCookieSourceView, XPostsVisibility } from "yt-dlp-transcript-common/social/xCookieSource";
+import type { ArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession";
+import type { ArchivesSettings } from "yt-dlp-transcript-common/lib/archives/settings";
+import type { ForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession";
+
+// A section whose read failed carries its error instead of its data: the
+// page draws that one section's sentence, never a failed page.
+export type SectionRead<T> = T | { error: string };
+
+export function sectionFailed<T extends object>(v: SectionRead<T>): v is { error: string } {
+ return "error" in v && typeof (v as { error?: unknown }).error === "string";
+}
+
+export type XControls = {
+ initial: XSessionStatus;
+ initialSource: XCookieSourceView;
+ initialVisibility: XPostsVisibility;
+ initialMaxCookieAge: number;
+};
+export type ArchiveControls = { initial: ArchivesSettings; session: ArchiveSessionStatus };
+export type YtdlpControls = { cookiesFromBrowser: string; cookieMode: string };
+// Per forum host (its service key): the session, and its thread channels.
+export type ForumControls = Record<string, { status: ForumSessionStatus; channels: string[] }>;
+
+export type CookieControls = {
+ x: SectionRead<XControls>;
+ archive: SectionRead<ArchiveControls>;
+ ytdlp: SectionRead<YtdlpControls>;
+ forums: SectionRead<ForumControls>;
+};
+
diff --git a/editor/app/lib/cookieStatus.ts b/editor/app/lib/cookieStatus.ts
@@ -12,7 +12,10 @@
// - one channel config per yt-dlp service (the channel of its last clean
// request: its own cookiesFromBrowser may be the one yt-dlp uses);
// - one name-only read of that browser's cookie store, cached 5 min
-// (lib/browserCookieAge.ts) — `fresh` reads it again.
+// (lib/browserCookieAge.ts) — `fresh` reads it again;
+// - the forum-thread channels (their host and thread): one config read per
+// channel, never their data/, remembered for a minute while channels/'s
+// own mtime holds (lib/forumChannels.ts).
//
// No channel listing, no index, no corpus walk. A read that fails leaves its
// row "unknown"; it never fails the page.
@@ -32,6 +35,7 @@ import { resolveXCookieSourceFor } from "yt-dlp-transcript-common/social/xBrowse
import { archiveSessionDir, readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession";
import { forumSessionDir, readForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession";
import { loadCookieAlerts } from "./cookieAlerts";
+import { listForumChannels } from "./forumChannels";
import { runningCookieActions } from "./cookieRefreshGuard";
async function safe<T>(fn: () => Promise<T>, fallback: T): Promise<T> {
@@ -66,6 +70,7 @@ export async function loadCookieStatus(
...(resolved?.browserSpec ? { browserSpec: resolved.browserSpec } : {}),
profileDir: xProfileDir(paths),
hasProfile: session.hasProfile,
+ loggedIn: session.looksAuthenticated,
...(alerts.x ? { jar: alerts.x } : {}),
};
@@ -116,6 +121,8 @@ export async function loadCookieStatus(
});
}
+ const forumChannels = await safe(() => listForumChannels(paths, { fresh: opts.fresh === true }), []);
+
return buildCookieStatus({
now,
alerts,
@@ -124,6 +131,7 @@ export async function loadCookieStatus(
ytdlp,
archive,
forums,
+ forumChannels,
running: runningCookieActions(),
display: { path: displayPath, text: displayText },
});
diff --git a/editor/app/lib/forumChannels.ts b/editor/app/lib/forumChannels.ts
@@ -0,0 +1,41 @@
+// THE FORUM-THREAD CHANNELS, BY HOST — for the /cookies screen's forum rows
+// (one per host, with each thread channel's own Connect) and for its Connect
+// when no thread of the host is in the cookie state yet. One config read per
+// channel (listChannelConfigs: ~40 ms over 231 channels), never a channel's
+// data/; remembered for a minute, and read again at once when channels/
+// itself changes (a channel created or removed moves its mtime) or `fresh`.
+
+import { stat } from "node:fs/promises";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
+import { parseXenforoThreadUrl } from "yt-dlp-transcript-common/social/xenforoParse";
+
+export type ForumChannel = { host: string; slug: string; url: string };
+
+export const FORUM_CHANNELS_TTL_MS = 60_000;
+
+type Memo = { key: string; at: number; rows: ForumChannel[] };
+const KEY = Symbol.for("archilyzer.cookies.forumChannels");
+function memo(): { last?: Memo } {
+ const g = globalThis as unknown as Record<symbol, { last?: Memo }>;
+ return (g[KEY] ??= {});
+}
+
+export async function listForumChannels(
+ paths: Paths,
+ opts: { fresh?: boolean; now?: number } = {},
+): Promise<ForumChannel[]> {
+ const now = opts.now ?? Date.now();
+ const mtime = await stat(paths.channelsDir).then((s) => s.mtimeMs, () => 0);
+ const key = `${paths.channelsDir}:${mtime}`;
+ const m = memo();
+ if (!opts.fresh && m.last && m.last.key === key && now - m.last.at < FORUM_CHANNELS_TTL_MS) return m.last.rows;
+ const rows: ForumChannel[] = [];
+ for (const { slug, config } of await listChannelConfigs(paths)) {
+ if (config.platform !== "xenforo") continue;
+ const thread = parseXenforoThreadUrl(config.url ?? "");
+ if (thread) rows.push({ host: thread.host, slug, url: thread.base });
+ }
+ m.last = { key, at: now, rows };
+ return rows;
+}
diff --git a/editor/app/lib/xSourceDisplay.ts b/editor/app/lib/xSourceDisplay.ts
@@ -0,0 +1,21 @@
+// X'S LOGIN SOURCE AS A PAGE MAY DRAW IT (round 2 review): the browser spec
+// can name a profile PATH ("firefox:/home/…/x.default"), and XSessionSection
+// draws it in the source select's option ("Browser login (…)"), the "In use"
+// line and the Check line. So every view of the source a client receives —
+// /settings', /cookies', and each X session action's answer — carries the spec,
+// its label and the Check summary through settings.privacy's displayText, on
+// the server. The client never ACTS on the spec: the select's value is the
+// source kind and whether it was chosen, the actions take only that choice,
+// and the spec's presence (all "Automatic" needs) survives the masking.
+
+import { displayText } from "yt-dlp-transcript-common/lib/privacy/privacy-server";
+import type { XCookieSourceView } from "yt-dlp-transcript-common/social/xCookieSource";
+
+export function xSourceForDisplay<T extends XCookieSourceView & { summary?: string }>(v: T): T {
+ return {
+ ...v,
+ label: displayText(v.label),
+ ...(v.browserSpec ? { browserSpec: displayText(v.browserSpec) } : {}),
+ ...(typeof v.summary === "string" ? { summary: displayText(v.summary) } : {}),
+ };
+}
diff --git a/editor/app/settings/actions.ts b/editor/app/settings/actions.ts
@@ -20,10 +20,7 @@ import {
} from "yt-dlp-transcript-common/lib/settings";
import { saveSettings } from "./saveSettings";
import { socialLinksForSave } from "yt-dlp-transcript-common/lib/socialLinks";
-import {
- DEFAULT_COOKIE_MODE,
- isCookieMode,
-} from "yt-dlp-transcript-common/lib/cookiePolicy";
+import { cookieKeysPatch } from "./cookieKeys";
import {
DEFAULT_SOURCE_VIDEO_QUALITY,
isDownloadFormatPreset,
@@ -78,13 +75,10 @@ export async function saveSettingsAction(
const maxBytesRaw = String(
formData.get("maxTranscriptPageBytes") ?? "",
).trim();
- const cookiesFromBrowser = String(
- formData.get("cookiesFromBrowser") ?? "",
- ).trim();
- const cookieModeRaw = String(formData.get("cookieMode") ?? "").trim();
- const cookieMode = isCookieMode(cookieModeRaw)
- ? cookieModeRaw
- : DEFAULT_COOKIE_MODE;
+ // yt-dlp's two cookie keys only when this form changed them: they are
+ // edited on /cookies too, and a tab left open here must not write its old
+ // values back (settings/cookieKeys.ts).
+ const cookieKeys = cookieKeysPatch(formData);
const sleepRaw = String(
formData.get("sleepBetweenDownloadsSeconds") ?? "",
).trim();
@@ -286,8 +280,7 @@ export async function saveSettingsAction(
const next: Partial<SiteSettings> = {
adminTitle,
maxTranscriptPageBytes: parsed,
- cookiesFromBrowser,
- cookieMode,
+ ...cookieKeys,
sleepBetweenDownloadsSeconds: sleepParsed,
// The whole pacing block as it is, with only the job gaps and the jitter
// this form edits.
diff --git a/editor/app/settings/components/ArchiveSessionSection.tsx b/editor/app/settings/components/ArchiveSessionSection.tsx
@@ -21,7 +21,16 @@ function sessionLine(status: ArchiveSessionStatus): string {
}
// The status line and Connect, alone (the channel panel's).
-export function ConnectArchiveSession({ initial, url }: { initial: ArchiveSessionStatus; url?: string }) {
+export function ConnectArchiveSession({
+ initial,
+ url,
+ onChange,
+}: {
+ initial: ArchiveSessionStatus;
+ url?: string;
+ // Told after a Connect ends (the /cookies screen re-reads its row).
+ onChange?: () => void;
+}) {
const [status, setStatus] = useState(initial);
const [error, setError] = useState<string | null>(null);
const [pending, start] = useTransition();
@@ -39,6 +48,7 @@ export function ConnectArchiveSession({ initial, url }: { initial: ArchiveSessio
const r = await connectArchiveSessionAction(url);
if (r.ok) setStatus({ ...status, hasProfile: true, lastConnect: r.record });
else setError(r.error);
+ onChange?.();
})
}
className="rounded-md border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50"
@@ -54,7 +64,18 @@ export function ConnectArchiveSession({ initial, url }: { initial: ArchiveSessio
);
}
-export function ArchiveSourcesSection({ initial, session }: { initial: ArchivesSettings; session: ArchiveSessionStatus }) {
+export function ArchiveSourcesSection({
+ initial,
+ session,
+ onChange,
+ cookiesLink = true,
+}: {
+ initial: ArchivesSettings;
+ session: ArchiveSessionStatus;
+ onChange?: () => void;
+ // The one-line link to /cookies (left out when drawn ON /cookies).
+ cookiesLink?: boolean;
+}) {
const [form, setForm] = useState(initial);
const [note, setNote] = useState<string | null>(null);
const [pending, start] = useTransition();
@@ -62,12 +83,14 @@ export function ArchiveSourcesSection({ initial, session }: { initial: ArchivesS
return (
<div aria-label="archive sources" className="flex flex-col gap-3">
<h2 className="text-lg font-semibold">Archive sources</h2>
- <p className="text-xs">
- <Link href="/cookies" className="underline underline-offset-2" aria-label="archive cookies screen link">
- Every service's cookies, and their refreshes, are on Cookies.
- </Link>
- </p>
- <ConnectArchiveSession initial={session} />
+ {cookiesLink && (
+ <p className="text-xs">
+ <Link href="/cookies" className="underline underline-offset-2" aria-label="archive cookies screen link">
+ Every service's cookies, and their refreshes, are on Cookies.
+ </Link>
+ </p>
+ )}
+ <ConnectArchiveSession initial={session} {...(onChange ? { onChange } : {})} />
<div className="flex flex-wrap items-end gap-3 text-sm">
<label className="flex flex-col gap-1">
<span>archive.today host</span>
diff --git a/editor/app/settings/components/SettingsForm.tsx b/editor/app/settings/components/SettingsForm.tsx
@@ -20,6 +20,7 @@ import {
SeededSelect,
} from "../../components/forms/Field";
import { seedChecked } from "../../lib/formState";
+import { YtdlpCookieFields } from "./YtdlpCookieFields";
import { jobGapSecondsFor } from "yt-dlp-transcript-common/lib/jobGap";
// The gaps this form edits (pacing.jobGapSeconds, plans/pacing-guard.md): the
@@ -84,43 +85,12 @@ export function SettingsForm({ initial }: Props) {
hint="Bytes per generated transcript page (256 KB – 20 MB). Affects pagination next build."
type="number"
/>
- <Field
- label="Cookies from browser"
- name="cookiesFromBrowser"
+ {/* Shared with the /cookies screen (YtdlpCookieFields.tsx). */}
+ <YtdlpCookieFields
state={state}
- defaultValue={initial.cookiesFromBrowser}
- hint="Browser spec passed to yt-dlp --cookies-from-browser (e.g. firefox, chrome:Default) for age-restricted, members-only, and private videos. When it is used is set by the cookie mode below. Leave blank for no cookies. Each channel can override both in its Advanced settings."
+ cookiesFromBrowser={initial.cookiesFromBrowser ?? ""}
+ cookieMode={initial.cookieMode ?? "when-required"}
/>
- <label className="flex flex-col gap-1 text-sm">
- <span className="font-medium">Cookie mode</span>
- <SeededSelect
- state={state}
- name="cookieMode"
- initial={initial.cookieMode}
- className="rounded border border-border bg-card px-2 py-1 text-sm"
- >
- <option value="when-required">
- When required — retry auth/age failures with cookies
- </option>
- <option value="always">
- Always — pass cookies on every yt-dlp invocation
- </option>
- <option value="defer">
- Defer — never in normal runs; collect into "Needs cookies"
- </option>
- </SeededSelect>
- <span className="text-xs text-muted-foreground">
- <strong>When required</strong> (default) runs cookie-free and retries
- only the attempts that fail with an auth/age error.{" "}
- <strong>Always</strong> sends cookies with every invocation
- (enumeration, metadata prefetch, availability probes, downloads) —
- for channels whose listing itself needs auth.{" "}
- <strong>Defer</strong> never uses cookies in normal runs: auth-gated
- videos are excluded from batches and gathered into each
- channel's “Needs cookies” bucket, downloaded on
- demand with its “Download with cookies” button.
- </span>
- </label>
<Field
label="Sleep between managed downloads (seconds)"
name="sleepBetweenDownloadsSeconds"
diff --git a/editor/app/settings/components/XSessionSection.tsx b/editor/app/settings/components/XSessionSection.tsx
@@ -37,13 +37,21 @@ export function XSessionSection({
initialSource,
initialVisibility,
initialMaxCookieAge,
+ onChange,
+ cookiesLink = true,
}: {
initial: XSessionStatus;
+ // The DISPLAY copy (lib/xSourceDisplay.ts): its spec and label already
+ // through settings.privacy. Drawn only — the select acts on the source kind.
initialSource: XCookieSourceView;
// `social.x.visibility`, resolved (absent = "public"); release 17 slice XP.
initialVisibility: XPostsVisibility;
// `social.x.maxCookieAgeMinutes`, resolved (absent = 60; 0 = off).
initialMaxCookieAge: number;
+ // Told after every action here ends (the /cookies screen re-reads its row).
+ onChange?: () => void;
+ // The one-line link to /cookies (left out when drawn ON /cookies).
+ cookiesLink?: boolean;
}) {
const [maxAge, setMaxAge] = useState(String(initialMaxCookieAge));
const [status, setStatus] = useState<XSessionStatus>(initial);
@@ -77,6 +85,7 @@ export function XSessionSection({
} else {
setError(res.error);
}
+ onChange?.();
});
const check = () =>
@@ -90,6 +99,7 @@ export function XSessionSection({
} else {
setError(res.error);
}
+ onChange?.();
});
const choose = (choice: string) =>
@@ -104,6 +114,7 @@ export function XSessionSection({
} else {
setError(res.error);
}
+ onChange?.();
});
// What "Automatic" resolves to right now, for its option's text.
@@ -136,11 +147,13 @@ export function XSessionSection({
</span>
</div>
- <p className="text-xs">
- <Link href="/cookies" className="underline underline-offset-2" aria-label="x cookies screen link">
- Refresh X's cookies (and every other service's) on Cookies.
- </Link>
- </p>
+ {cookiesLink && (
+ <p className="text-xs">
+ <Link href="/cookies" className="underline underline-offset-2" aria-label="x cookies screen link">
+ Refresh X's cookies (and every other service's) on Cookies.
+ </Link>
+ </p>
+ )}
<p className="text-xs text-muted-foreground">
X post archiving needs a logged-in session, from one of two sources.{" "}
@@ -162,7 +175,7 @@ export function XSessionSection({
value={source.chosen ? source.source : "auto"}
onChange={(e) => choose(e.target.value)}
disabled={pending || checking}
- className="rounded-md border border-border bg-background px-2 py-1 text-sm disabled:opacity-50"
+ className="min-w-0 max-w-full rounded-md border border-border bg-background px-2 py-1 text-sm disabled:opacity-50"
>
<option value="auto">Automatic — now: {automatic}</option>
<option value="browser">
@@ -237,6 +250,7 @@ export function XSessionSection({
const res = await setXMaxCookieAgeAction(Number(maxAge));
if (res.ok) setNote(res.minutes === 0 ? "Cookie age check off." : `X jobs now need cookies refreshed within ${res.minutes} min.`);
else setError(res.error);
+ onChange?.();
})
}
className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50"
diff --git a/editor/app/settings/components/YtdlpCookieFields.tsx b/editor/app/settings/components/YtdlpCookieFields.tsx
@@ -0,0 +1,121 @@
+"use client";
+
+// YT-DLP'S BROWSER COOKIES — `cookiesFromBrowser` (the browser spec yt-dlp's
+// --cookies-from-browser reads: Rumble's Cloudflare clearance, YouTube's
+// sign-in, Odysee's check) and `cookieMode` (when it is used). The two fields
+// are drawn by /settings' form (SettingsForm, inside its one Save) and by the
+// /cookies screen's own small form (YtdlpCookieSourceForm, saving these two
+// keys alone through saveYtdlpCookieSourceAction) — one component, so the two
+// places cannot drift.
+
+import { useActionState, useEffect } from "react";
+import { Field, SeededSelect } from "../../components/forms/Field";
+import type { SeedSource } from "../../lib/formState";
+import { saveYtdlpCookieSourceAction, type YtdlpCookieSourceResult } from "../cookieSourceActions";
+import { SEEDED_SUFFIX } from "../cookieKeys";
+
+export function YtdlpCookieFields({
+ state,
+ cookiesFromBrowser,
+ cookieMode,
+}: {
+ state?: SeedSource;
+ cookiesFromBrowser: string;
+ cookieMode: string;
+}) {
+ return (
+ <>
+ {/* What this form was drawn with: a save writes a key only when it
+ differs (settings/cookieKeys.ts), so a stale tab writes nothing back. */}
+ <input type="hidden" name={`cookiesFromBrowser${SEEDED_SUFFIX}`} value={cookiesFromBrowser} readOnly />
+ <input type="hidden" name={`cookieMode${SEEDED_SUFFIX}`} value={cookieMode} readOnly />
+ <Field
+ label="Cookies from browser"
+ name="cookiesFromBrowser"
+ state={state}
+ defaultValue={cookiesFromBrowser}
+ hint="Browser spec passed to yt-dlp --cookies-from-browser (e.g. firefox, chrome:Default) for age-restricted, members-only, and private videos. When it is used is set by the cookie mode below. Leave blank for no cookies. Each channel can override both in its Advanced settings."
+ />
+ <label className="flex flex-col gap-1 text-sm">
+ <span className="font-medium">Cookie mode</span>
+ <SeededSelect
+ state={state}
+ name="cookieMode"
+ initial={cookieMode}
+ className="rounded border border-border bg-card px-2 py-1 text-sm"
+ >
+ <option value="when-required">
+ When required — retry auth/age failures with cookies
+ </option>
+ <option value="always">
+ Always — pass cookies on every yt-dlp invocation
+ </option>
+ <option value="defer">
+ Defer — never in normal runs; collect into "Needs cookies"
+ </option>
+ </SeededSelect>
+ <span className="text-xs text-muted-foreground">
+ <strong>When required</strong> (default) runs cookie-free and retries
+ only the attempts that fail with an auth/age error.{" "}
+ <strong>Always</strong> sends cookies with every invocation
+ (enumeration, metadata prefetch, availability probes, downloads) —
+ for channels whose listing itself needs auth.{" "}
+ <strong>Defer</strong> never uses cookies in normal runs: auth-gated
+ videos are excluded from batches and gathered into each
+ channel's “Needs cookies” bucket, downloaded on
+ demand with its “Download with cookies” button.
+ </span>
+ </label>
+ </>
+ );
+}
+
+// The /cookies screen's form for the two keys: its own Save, its own answer.
+export function YtdlpCookieSourceForm({
+ cookiesFromBrowser,
+ cookieMode,
+ onSaved,
+}: {
+ cookiesFromBrowser: string;
+ cookieMode: string;
+ onSaved?: () => void;
+}) {
+ const [state, formAction, pending] = useActionState<YtdlpCookieSourceResult | undefined, FormData>(
+ saveYtdlpCookieSourceAction,
+ undefined,
+ );
+ useEffect(() => {
+ if (state?.ok) onSaved?.();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [state]);
+ const saved = state?.ok ? state : null;
+ return (
+ <form action={formAction} aria-label="yt-dlp cookies" className="flex flex-col gap-3">
+ <YtdlpCookieFields
+ state={state}
+ cookiesFromBrowser={saved ? saved.cookiesFromBrowser : cookiesFromBrowser}
+ cookieMode={saved ? saved.cookieMode : cookieMode}
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="submit"
+ disabled={pending}
+ aria-label="save yt-dlp cookies"
+ className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50"
+ >
+ {pending ? "Saving…" : "Save"}
+ </button>
+ {state?.ok && (
+ <span role="status" aria-label="yt-dlp cookies saved" className="text-xs text-success">
+ Saved.
+ </span>
+ )}
+ {state && !state.ok && (
+ <span role="alert" className="text-xs text-destructive">
+ {state.error}
+ </span>
+ )}
+ </div>
+ </form>
+ );
+}
diff --git a/editor/app/settings/cookieKeys.test.ts b/editor/app/settings/cookieKeys.test.ts
@@ -0,0 +1,44 @@
+// yt-dlp's two cookie keys written only when the form changed them
+// (cookieKeys.ts) — the stale-tab case: a /settings tab drawn before a change
+// on /cookies saves something else and must not write the old values back.
+//
+// Run with: pnpm -C editor exec tsx --test app/settings/cookieKeys.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import { cookieKeysPatch, submittedCookieKeys } from "./cookieKeys";
+
+const form = (o: Record<string, string>) => {
+ const f = new FormData();
+ for (const [k, v] of Object.entries(o)) f.set(k, v);
+ return f;
+};
+
+test("a form that did not touch the keys writes neither (the stale tab)", () => {
+ const stale = form({
+ cookiesFromBrowser: "firefox",
+ "cookiesFromBrowser.seeded": "firefox",
+ cookieMode: "when-required",
+ "cookieMode.seeded": "when-required",
+ });
+ assert.deepEqual(cookieKeysPatch(stale), {});
+});
+
+test("a changed key is written, and only it", () => {
+ assert.deepEqual(
+ cookieKeysPatch(form({ cookiesFromBrowser: " chrome ", "cookiesFromBrowser.seeded": "firefox", cookieMode: "always", "cookieMode.seeded": "always" })),
+ { cookiesFromBrowser: "chrome" },
+ );
+ assert.deepEqual(
+ cookieKeysPatch(form({ cookiesFromBrowser: "firefox", "cookiesFromBrowser.seeded": "firefox", cookieMode: "defer", "cookieMode.seeded": "always" })),
+ { cookieMode: "defer" },
+ );
+});
+
+test("a form without the seeded fields writes both, normalised as before", () => {
+ assert.deepEqual(cookieKeysPatch(form({ cookiesFromBrowser: " firefox ", cookieMode: "sometimes" })), {
+ cookiesFromBrowser: "firefox",
+ cookieMode: "when-required",
+ });
+ assert.deepEqual(submittedCookieKeys(form({})), { cookiesFromBrowser: "", cookieMode: "when-required" });
+});
diff --git a/editor/app/settings/cookieKeys.ts b/editor/app/settings/cookieKeys.ts
@@ -0,0 +1,39 @@
+// YT-DLP'S TWO COOKIE KEYS FROM A FORM, WRITTEN ONLY WHEN CHANGED (round 2
+// review). `cookiesFromBrowser` and `cookieMode` are edited in two places —
+// /settings' form and the /cookies screen's own — so a tab left open on one
+// must not write its old values back over a change made on the other. Each
+// form carries the value it was drawn with (`<key>.seeded`, hidden:
+// components/YtdlpCookieFields.tsx); a key is in the patch only when what was
+// submitted differs from that. A form without the seeded field (an older page)
+// writes both, as before.
+
+import { DEFAULT_COOKIE_MODE, isCookieMode, type CookieMode } from "yt-dlp-transcript-common/lib/cookiePolicy";
+
+export const SEEDED_SUFFIX = ".seeded";
+
+type Form = { get(name: string): FormDataEntryValue | null };
+
+function mode(v: unknown): CookieMode {
+ const s = String(v ?? "").trim();
+ return isCookieMode(s) ? s : DEFAULT_COOKIE_MODE;
+}
+
+// What was submitted, normalised as /settings' Save always has.
+export function submittedCookieKeys(form: Form): { cookiesFromBrowser: string; cookieMode: CookieMode } {
+ return {
+ cookiesFromBrowser: String(form.get("cookiesFromBrowser") ?? "").trim(),
+ cookieMode: mode(form.get("cookieMode")),
+ };
+}
+
+export function cookieKeysPatch(form: Form): Partial<{ cookiesFromBrowser: string; cookieMode: CookieMode }> {
+ const now = submittedCookieKeys(form);
+ const seededSpec = form.get(`cookiesFromBrowser${SEEDED_SUFFIX}`);
+ const seededMode = form.get(`cookieMode${SEEDED_SUFFIX}`);
+ return {
+ ...(seededSpec === null || String(seededSpec).trim() !== now.cookiesFromBrowser
+ ? { cookiesFromBrowser: now.cookiesFromBrowser }
+ : {}),
+ ...(seededMode === null || mode(seededMode) !== now.cookieMode ? { cookieMode: now.cookieMode } : {}),
+ };
+}
diff --git a/editor/app/settings/cookieSourceActions.ts b/editor/app/settings/cookieSourceActions.ts
@@ -0,0 +1,30 @@
+"use server";
+
+// yt-dlp's browser cookies, saved ALONE: `cookiesFromBrowser` and
+// `cookieMode`, read from the form exactly as /settings' Save reads them
+// (saveSettingsAction), written through the one settings writer and nothing
+// else. The /cookies screen's form (components/YtdlpCookieFields.tsx).
+
+import { saveSettings } from "./saveSettings";
+import type { CookieMode } from "yt-dlp-transcript-common/lib/cookiePolicy";
+import { formValues, type FormState } from "../lib/formState";
+import { cookieKeysPatch, submittedCookieKeys } from "./cookieKeys";
+
+export type YtdlpCookieSourceResult = FormState<{ cookiesFromBrowser: string; cookieMode: CookieMode }>;
+
+export async function saveYtdlpCookieSourceAction(
+ _prev: YtdlpCookieSourceResult | undefined,
+ formData: FormData,
+): Promise<YtdlpCookieSourceResult> {
+ const values = formValues(formData);
+ const { cookiesFromBrowser, cookieMode } = submittedCookieKeys(formData);
+ // Only a key this form changed: a tab left open must not write back over
+ // /settings' newer value (cookieKeys.ts).
+ const patch = cookieKeysPatch(formData);
+ try {
+ if (Object.keys(patch).length) await saveSettings(patch);
+ } catch (e) {
+ return { ok: false, error: (e as Error).message, values };
+ }
+ return { ok: true, cookiesFromBrowser, cookieMode };
+}
diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx
@@ -8,6 +8,7 @@ import { resolveXCookieSourceFor } from "yt-dlp-transcript-common/social/xBrowse
import { xCookieSourceView } from "yt-dlp-transcript-common/social/xCookieSource";
import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility";
import { SettingsForm } from "./components/SettingsForm";
+import { xSourceForDisplay } from "../lib/xSourceDisplay";
import { XSessionSection } from "./components/XSessionSection";
import { xMaxCookieAgeMinutes } from "yt-dlp-transcript-common/social/xCookieSource";
import { ArchiveSourcesSection } from "./components/ArchiveSessionSection";
@@ -40,8 +41,9 @@ export default async function SettingsPage() {
// xSessionActions.ts). The source is resolved here, not read: with no stored
// choice it depends on cookiesFromBrowser and the profile.
const xSession = await readXSessionStatus(paths);
- const xSource = xCookieSourceView(
- await resolveXCookieSourceFor(paths, settings),
+ // Drawn by the client: its spec and label through settings.privacy.
+ const xSource = xSourceForDisplay(
+ xCookieSourceView(await resolveXCookieSourceFor(paths, settings)),
);
return (
diff --git a/editor/app/settings/xSessionActions.ts b/editor/app/settings/xSessionActions.ts
@@ -42,6 +42,7 @@ import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility";
import { saveSettings } from "./saveSettings";
import { fakeXProfileChromium } from "yt-dlp-transcript-common/social/fakeXProfileBrowser";
import { withCookieAction } from "../lib/cookieRefreshGuard";
+import { xSourceForDisplay } from "../lib/xSourceDisplay";
// `social.x` is ONE value to saveSettings, whose merge is one level deep: a
// patch naming `social: { x }` replaces the whole X block. So each X choice is
@@ -59,8 +60,9 @@ export type XSessionActionResult =
| { ok: true; status: XSessionStatus; source: XCookieSourceView; browser?: string }
| { ok: false; error: string };
+// Drawn by the client, so through settings.privacy (lib/xSourceDisplay.ts).
async function sourceNow(): Promise<XCookieSourceView> {
- return xCookieSourceView(await resolveXCookieSourceFor(getPaths(), getSettings()));
+ return xSourceForDisplay(xCookieSourceView(await resolveXCookieSourceFor(getPaths(), getSettings())));
}
export async function xSessionStatusAction(): Promise<XSessionStatus> {
@@ -80,9 +82,13 @@ export async function connectXAccountAction(): Promise<XSessionActionResult> {
async function connectXAccountNow(): Promise<XSessionActionResult> {
try {
+ // Under the e2e test server only, the fake browser (fakeXProfileBrowser.ts
+ // says how it is gated); everywhere else null, and the real window opens.
+ const chromium = fakeXProfileChromium(getPaths().transcriptsDir);
const { browser, ...status } = await connectXAccount(getPaths(), {
// Which browser opened, and any fallback, in the editor's log.
onLog: (line) => console.log(`[x-session] ${line}`),
+ ...(chromium ? { chromium } : {}),
});
if (!status.looksAuthenticated) {
return {
@@ -145,7 +151,7 @@ export type XLoginCheckResult =
export async function checkXLoginAction(): Promise<XLoginCheckResult> {
try {
- return { ok: true, login: await readXLoginStatus(getPaths(), getSettings()) };
+ return { ok: true, login: xSourceForDisplay(await readXLoginStatus(getPaths(), getSettings())) };
} catch (e) {
return { ok: false, error: (e as Error).message };
}
diff --git a/editor/e2e/cookies-screen.spec.ts b/editor/e2e/cookies-screen.spec.ts
@@ -12,9 +12,9 @@
// The headed Connects (archive.today, a forum, X with no profile) open a
// window on the machine: they are looked at, never pressed.
-import { mkdir, writeFile } from "node:fs/promises";
+import { mkdir, readFile, utimes, writeFile } from "node:fs/promises";
import { test, expect, type Page } from "@playwright/test";
-import { resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+import { generateReport, resetData, resolvePath, testPaths, writeChannelConfig, writeSettings } from "./helpers";
import { baseUrl } from "./baseUrl";
// By relative path: a runtime import of the package specifier does not resolve
// under playwright's loader (digest.spec.ts says why).
@@ -24,7 +24,11 @@ const SLUG = "test-youtube";
const t = (p: string) => resolvePath(`${testPaths().transcriptsDir}/${p}`);
const MIN = 60_000;
-async function seed(opts: { xDelayMs?: number } = {}) {
+// A forum-thread channel on a fixture host (no request: nothing here fetches it).
+const FORUM_SLUG = "teapot-thread";
+const FORUM_HOST = "forum.example.test";
+
+async function seed(opts: { xDelayMs?: number; xProfile?: boolean; xCloseAfterMs?: number } = {}) {
await resetData("youtube-with-playlist");
const now = Date.now();
const profile = t("firefox-fixture/cs.default-release");
@@ -45,12 +49,30 @@ async function seed(opts: { xDelayMs?: number } = {}) {
cookiesFromBrowser: `firefox:${profile}`,
social: { x: { cookieSource: "profile" } },
});
- // A connected X profile with no jar exported yet, and the fake browser's cookies.
- await mkdir(t(".x-session/profile"), { recursive: true });
+ // A connected X profile whose jar (2 h old) holds a login, and the fake
+ // browser's cookies.
+ if (opts.xProfile !== false) {
+ await mkdir(t(".x-session/profile"), { recursive: true });
+ await writeFile(
+ t(".x-session/cookies.txt"),
+ "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfixture-not-a-real-token\n",
+ );
+ const old = new Date(now - 2 * 60 * MIN);
+ await utimes(t(".x-session/cookies.txt"), old, old);
+ }
+ await writeChannelConfig(FORUM_SLUG, {
+ name: "Teapot thread",
+ sourceKind: "social",
+ platform: "xenforo",
+ postFetcher: "xenforo-thread",
+ socialHandle: `${FORUM_SLUG}.4242`,
+ url: `https://${FORUM_HOST}/threads/${FORUM_SLUG}.4242/`,
+ });
await writeFile(
t(".fake-x-profile-cookies.json"),
JSON.stringify({
delayMs: opts.xDelayMs ?? 0,
+ closeAfterMs: opts.xCloseAfterMs ?? 0,
cookies: [
{ name: "auth_token", value: "fixture-not-a-real-token", domain: ".x.com" },
{ name: "ct0", value: "fixture-not-a-real-ct0", domain: ".x.com" },
@@ -93,7 +115,7 @@ test("one row per service: source, age, alert, and the one button", async ({ pag
await page.goto("/cookies");
await expect(page.getByRole("heading", { name: "Cookies", level: 1 })).toBeVisible();
const services = await page.locator("[data-service]").evaluateAll((els) => els.map((e) => e.getAttribute("data-service")));
- expect(services).toEqual(["x", "rumble", "youtube", "odysee", "archive.today"]);
+ expect(services).toEqual(["x", "rumble", "youtube", "odysee", "archive.today", FORUM_HOST]);
const rumble = row(page, "Rumble");
await expect(rumble).toHaveAttribute("data-state", "stale");
@@ -109,9 +131,11 @@ test("one row per service: source, age, alert, and the one button", async ({ pag
await expect(row(page, "Odysee")).toHaveAttribute("data-state", "unknown");
const x = row(page, "X");
- await expect(page.getByLabel("X cookie age")).toHaveText("No cookie jar exported yet.");
+ await expect(page.getByLabel("X cookie age", { exact: true })).toHaveText("jar written 2 h ago · no age limit");
await expect(page.getByRole("button", { name: "X Refresh cookies" })).toBeEnabled();
- await expect(x).not.toContainText("editor's machine");
+ // Logged in: the one press is Refresh; Connect is in the controls under it, open.
+ await expect(page.getByRole("button", { name: "X Connect X account" })).toHaveCount(0);
+ await expect(x.getByLabel("connect x account", { exact: true })).toBeVisible();
// The headed Connect says where its window opens. Never pressed here.
const archive = row(page, "archive.today");
@@ -161,7 +185,7 @@ test("X Refresh cookies: progress in the row, a second press refused, the result
// The first press ends: its result and the new jar's age, in the row.
await expect(page.getByRole("status", { name: "X press result" })).toHaveText("Cookies refreshed.", { timeout: 20_000 });
- await expect(page.getByLabel("X cookie age")).toHaveText(/^jar written just now · no age limit$/);
+ await expect(page.getByLabel("X cookie age", { exact: true })).toHaveText(/^jar written just now · no age limit$/);
await expect(refresh).toHaveText("Refresh cookies");
expect(await page.evaluate(() => (window as unknown as { __noReload?: number }).__noReload)).toBe(1);
@@ -194,11 +218,162 @@ test("at a phone's width the page does not scroll sideways", async ({ page }) =>
await page.setViewportSize({ width: 390, height: 844 });
await page.goto("/cookies");
await expect(row(page, "Rumble")).toBeVisible();
- const { scroll, client } = await page.evaluate(() => ({
+ const { scroll, client, wide } = await page.evaluate(() => ({
scroll: document.documentElement.scrollWidth,
client: document.documentElement.clientWidth,
+ // What sticks out, named, for a failure's message.
+ wide: [...document.querySelectorAll("main *")]
+ .filter((e) => e.getBoundingClientRect().right > document.documentElement.clientWidth + 1)
+ .slice(0, 5)
+ .map((e) => `${e.tagName.toLowerCase()}${e.getAttribute("aria-label") ? `[${e.getAttribute("aria-label")}]` : ""} ${Math.round(e.getBoundingClientRect().right)}`),
}));
- expect(scroll).toBeLessThanOrEqual(client);
+ expect(scroll, wide.join("; ")).toBeLessThanOrEqual(client);
const box = await page.getByRole("button", { name: "Rumble Check again" }).boundingBox();
expect(box && box.x + box.width).toBeLessThanOrEqual(390);
});
+
+// PARITY (operator, 16 Nov: "it and the others should be just as capable as
+// the old settings menu version"): every control of /settings' cookie sections
+// and of a forum channel's session block is on /cookies too.
+async function controlsIn(page: Page, selector: string) {
+ return page.locator(selector).evaluateAll((els) => {
+ const labels = new Set<string>();
+ const names = new Set<string>();
+ const buttons = new Set<string>();
+ for (const el of els) {
+ for (const e of el.querySelectorAll("[aria-label]")) labels.add(e.getAttribute("aria-label") ?? "");
+ // A server-action form's own hidden fields ($ACTION_…) are React's, not controls.
+ for (const e of el.querySelectorAll("input[name]:not([type=hidden]), select[name]")) {
+ const n = e.getAttribute("name") ?? "";
+ if (!n.startsWith("$")) names.add(n);
+ }
+ for (const e of el.querySelectorAll("button")) buttons.add((e.textContent ?? "").trim());
+ }
+ return { labels: [...labels].sort(), names: [...names].sort(), buttons: [...buttons].sort() };
+ });
+}
+
+test("every cookie control on /settings and on a forum channel's page is on /cookies", async ({ page }) => {
+ await seed();
+ // The links back to /cookies are the only thing /cookies leaves out of them.
+ const SELF_LINKS = ["x cookies screen link", "archive cookies screen link"];
+
+ await page.goto("/settings");
+ const xS = await controlsIn(page, "[data-x-session]");
+ const arS = await controlsIn(page, '[aria-label="archive sources"]');
+ expect(xS.labels).toEqual(expect.arrayContaining(["connect x account", "refresh x cookies", "clear x session", "check x login", "x cookie source", "save x max cookie age"]));
+ expect(arS.labels).toEqual(expect.arrayContaining(["archive.today host", "read a check through the browser"]));
+ // yt-dlp's two keys: on /settings' form.
+ await expect(page.locator('form input[name="cookiesFromBrowser"]')).toHaveValue(/^firefox:/);
+ await expect(page.locator('form select[name="cookieMode"]')).toHaveCount(1);
+
+ await generateReport(page, FORUM_SLUG);
+ await page.goto(`/channels/${FORUM_SLUG}`);
+ const forumS = await controlsIn(page, "[data-forum-session]");
+ // The per-thread fetch controls (retry after a block, saved-page import)
+ // belong to the thread and stay on its page, which /cookies links.
+ const THREAD_ONLY = ["retry after a block", "retry minutes", "retry tries", "save retry after a block", "turn off retry after a block", "saved pages path", "import saved pages"];
+ const forumSession = forumS.labels.filter((l) => !THREAD_ONLY.includes(l));
+ expect(forumSession).toEqual(["connect forum session", "forum session state"]);
+
+ await page.goto("/cookies");
+ const xC = await controlsIn(page, '[aria-label="X controls"]');
+ const arC = await controlsIn(page, '[aria-label="archive.today controls"]');
+ for (const l of xS.labels.filter((l) => !SELF_LINKS.includes(l))) expect(xC.labels, `X: ${l}`).toContain(l);
+ for (const b of xS.buttons) expect(xC.buttons, `X button: ${b}`).toContain(b);
+ for (const l of arS.labels.filter((l) => !SELF_LINKS.includes(l))) expect(arC.labels, `archive: ${l}`).toContain(l);
+ for (const b of arS.buttons) expect(arC.buttons, `archive button: ${b}`).toContain(b);
+ const yt = await controlsIn(page, '[aria-label="yt-dlp cookie source"]');
+ expect(yt.names).toEqual(["cookieMode", "cookiesFromBrowser"]);
+ await expect(page.getByLabel("yt-dlp cookie source").locator('input[name="cookiesFromBrowser"]')).toHaveValue(/^firefox:/);
+ const forumC = await controlsIn(page, `[aria-label="${FORUM_HOST} controls"]`);
+ for (const l of forumSession) expect(forumC.labels, `forum: ${l}`).toContain(l);
+ // Inside a closed disclosure: present, one click away.
+ await expect(page.getByLabel(`${FORUM_HOST} controls`).locator(`a[href="/channels/${FORUM_SLUG}"]`)).toHaveText(FORUM_SLUG);
+ // X's controls are open: logging in is one press away.
+ await expect(page.getByLabel("X controls").getByLabel("connect x account", { exact: true })).toBeVisible();
+
+ // The yt-dlp fields save from here, alone, and the row reads the new spec.
+ const form = page.getByLabel("yt-dlp cookie source");
+ await form.locator('select[name="cookieMode"]').selectOption("always");
+ await form.getByRole("button", { name: "save yt-dlp cookies" }).click();
+ await expect(page.getByRole("status", { name: "yt-dlp cookies saved" })).toHaveText("Saved.");
+ const settingsJson = JSON.parse(await readFile(testPaths().settingsFile, "utf8")) as { cookieMode?: string; cookiesFromBrowser?: string };
+ expect(settingsJson.cookieMode).toBe("always");
+ expect(settingsJson.cookiesFromBrowser).toMatch(/^firefox:/);
+});
+
+test("Connect X account and Forget session from /cookies, through the fake browser", async ({ page }) => {
+ await seed({ xProfile: false, xCloseAfterMs: 1500 });
+ await page.goto("/cookies");
+ const x = row(page, "X");
+ await expect(page.getByLabel("x session state")).toHaveText("not connected");
+ // No profile: the row's one press is Connect, and it says where the window opens.
+ const connect = page.getByRole("button", { name: "X Connect X account" });
+ await expect(x).toContainText("Opens a browser window on the editor's machine, not on this device.");
+ await connect.click();
+ await expect(connect).toHaveText(/^Waiting for the window… \d+ s$/);
+ await expect(page.getByRole("status", { name: "X press result" })).toHaveText(/^Connected.*\. Cookies exported\.$/, { timeout: 20_000 });
+ // The row now offers Refresh; the controls under it are drawn afresh.
+ await expect(page.getByRole("button", { name: "X Refresh cookies" })).toBeVisible();
+ await expect(page.getByLabel("x session state")).toHaveText("connected");
+ await expect(page.getByLabel("X cookie age", { exact: true })).toHaveText(/^jar written just now/);
+
+ // Forget session, from the controls: the profile goes, and the row says so.
+ await x.getByLabel("clear x session", { exact: true }).click();
+ await expect(x.getByRole("status").filter({ hasText: "Session cleared." })).toBeVisible();
+ await expect(page.getByLabel("x session state")).toHaveText("not connected");
+ await expect(page.getByRole("button", { name: "X Connect X account" })).toBeVisible({ timeout: 10_000 });
+
+ // Connect from the controls too (the button /settings has): connected again.
+ await x.getByLabel("connect x account", { exact: true }).click();
+ await expect(page.getByLabel("x session state")).toHaveText("connected", { timeout: 20_000 });
+ await expect(page.getByRole("button", { name: "X Refresh cookies" })).toBeVisible({ timeout: 10_000 });
+});
+
+// A /settings tab left open must not write its old cookie values back over a
+// change made on /cookies (round 2 review): its Save writes the two keys only
+// when IT changed them.
+test("a stale /settings tab's Save keeps the cookie mode /cookies set", async ({ page, browser }) => {
+ await seed();
+ const ctx = await browser.newContext();
+ try {
+ const stale = await ctx.newPage();
+ await stale.goto(`${baseUrl}/settings`);
+ await expect(stale.locator('form select[name="cookieMode"]')).toHaveValue("when-required");
+
+ await page.goto("/cookies");
+ const form = page.getByLabel("yt-dlp cookie source");
+ await form.locator('select[name="cookieMode"]').selectOption("defer");
+ await form.locator('input[name="cookiesFromBrowser"]').fill("firefox");
+ await form.getByRole("button", { name: "save yt-dlp cookies" }).click();
+ await expect(page.getByRole("status", { name: "yt-dlp cookies saved" })).toHaveText("Saved.");
+
+ // The old tab saves something else.
+ await stale.getByRole("button", { name: "Save settings" }).click();
+ await expect(stale.getByText("Saved.", { exact: true })).toBeVisible();
+ const saved = JSON.parse(await readFile(testPaths().settingsFile, "utf8")) as { cookieMode?: string; cookiesFromBrowser?: string };
+ expect(saved.cookieMode).toBe("defer");
+ expect(saved.cookiesFromBrowser).toBe("firefox");
+ } finally {
+ await ctx.close();
+ }
+});
+
+// A row's press redraws only that row's controls: what is open or typed in
+// another row's stays (round 2 review).
+test("a press in one row keeps another row's open disclosure and what is typed in it", async ({ page }) => {
+ await seed();
+ await page.goto("/cookies");
+ const archive = page.getByLabel("archive.today controls");
+ await archive.locator("summary").click();
+ const gap = archive.getByLabel("archive.today gap seconds");
+ await gap.fill("77");
+ await page.getByRole("button", { name: "X Refresh cookies" }).click();
+ await expect(page.getByRole("status", { name: "X press result" })).toHaveText("Cookies refreshed.", { timeout: 20_000 });
+ await expect(page.getByLabel("X cookie age", { exact: true })).toHaveText(/^jar written just now/);
+ // Give the controls' re-read (after the press) its moment, then look.
+ await page.waitForTimeout(1500);
+ await expect(archive).toHaveAttribute("open", "");
+ await expect(gap).toHaveValue("77");
+});
diff --git a/editor/e2e/privacy-audit.spec.ts b/editor/e2e/privacy-audit.spec.ts
@@ -87,6 +87,9 @@ const SLICE_2 = new Set<string>([
"/workers",
]);
+// Routes whose cookiesFromBrowser INPUT draws the saved spec as typed.
+const VALUE_ROUTES = new Set<string>(["/settings", "/cookies"]);
+
const lit = (text: string, from: string, ci = false): Literal => ({
bytes: ci ? foldAscii(Buffer.from(text, "utf8")) : Buffer.from(text, "utf8"),
ci,
@@ -105,6 +108,11 @@ function settings(privacy: Record<string, unknown> | null) {
const s = JSON.parse(readFileSync(paths.settingsFile, "utf8")) as Record<string, unknown>;
delete s.privacy;
if (privacy) s.privacy = privacy;
+ // A browser spec that names a profile PATH under the home dir (the path does
+ // not exist: nothing reads a browser store). X's login source draws it on
+ // /settings and /cookies — through the privacy rules, never raw — while the
+ // yt-dlp field that edits it shows the saved value as it is (VALUE_ROUTES).
+ s.cookiesFromBrowser = `firefox:${join(HOME, ".zq-audit-firefox", "zq.default")}`;
s.storage = {
locations: [{ id: "zq-drive", label: "Zq Drive", root: DRIVE_ROOT, autoRepoint: false }],
defaultLocationId: "",
@@ -261,7 +269,9 @@ test("masked, privacy on: no hit outside the slice-2 routes", async ({ browser }
await settle();
const result = await audit(browser);
const hits = failingHits(result);
- const outside = hits.filter((h) => !SLICE_2.has(h.route));
+ // The cookiesFromBrowser field's own value is a saved form value, raw by
+ // ruling (round 2 review): only that kind of hit, only on its two routes.
+ const outside = hits.filter((h) => !SLICE_2.has(h.route) && !(h.where === "value" && VALUE_ROUTES.has(h.route)));
const byRoute = new Map<string, { live: number; ssr: number }>();
for (const h of hits) {
const c = byRoute.get(h.route) ?? { live: 0, ssr: 0 };
diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts
@@ -59,7 +59,7 @@ import { currentSlot } from "./e2e/testPaths";
// (common/social/forumFixtureLoader.ts;
// forum-resume.spec)
// E2E_FAKE_X_PROFILE_COOKIES_FILE set per slot (e2e/servers.ts): the file
-// of SYNTHETIC cookies Refresh cookies' fake browser
+// of SYNTHETIC cookies the fake browser of Refresh cookies and Connect X account
// hands back while it exists — no browser starts,
// nothing asks X (common/social/fakeXProfileBrowser.ts;
// cookies-screen.spec); inert without E2E_TEST_ROUTES
diff --git a/plans/cookie-screen.md b/plans/cookie-screen.md
@@ -46,6 +46,24 @@ Every refresh, connect and recheck — /cookies, /settings, the dashboard, a for
while a `recheck-service-cookies` job is queued or running on its queue, is refused with a sentence; the
outcome is the service's last press (`actions` in `.service-cookies.json`).
+## Round 2 (2026-11-16): full parity with /settings
+
+Operator: "The cookies page doesn't let me log into X, it and the others should be just as capable as the old
+settings menu version." Under each row's status and its one button, the service's whole session block, drawn by
+the components /settings (and a forum channel's page) draw, fed only its own slice (`lib/cookieControls.ts`):
+
+| Settings / channel control | On /cookies |
+|---|---|
+| X: login source, Check, max cookie age + Save, Connect X account, Refresh cookies, Forget session, X posts visibility | X row → "X account session" (open) — XSessionSection |
+| archive.today: Connect archive session, host, gap, cooldown, read past a check, Save | archive.today row → "Archive sources" — ArchiveSourcesSection |
+| cookiesFromBrowser, cookieMode (SettingsForm) | "Browser cookies for Rumble, YouTube and Odysee" — YtdlpCookieFields, saved alone (saveYtdlpCookieSourceAction) |
+| A forum thread's session state + Connect forum session | forum host row → "Forum session, per thread" — ForumSessionConnect, one per thread channel |
+| A forum thread's retry after a block, saved-page import | the thread's page, linked from its forum row (per thread, not per host) |
+
+The forum rows come from the forum-thread channels too (`lib/forumChannels.ts`: one config read per channel,
+~40 ms over 231, never data/; remembered a minute while channels/'s mtime holds). With an X profile that holds no
+login, the row's one press is Connect, not Refresh. The e2e suite's fake browser covers Connect X account too.
+
## Ops
`pnpm ops get cookies [fresh]` — the rows, read-only. Check again is `recheck-service`; Refresh cookies and the