commit 24f0364c3810908e4e74dadcbe1716a09ba155e8
parent d0a5dbdaebde2f32a52e7a5ecab9225ee7846a2c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 16 Nov 2026 11:27:22 -0500
Merge lane/cookie-screen: a Cookies screen for the one operation done over and over -- /cookies in the editor's nav, one row per service the editor reads cookies for (X, Rumble, YouTube, Odysee, archive.today, each forum host) with its source drawn through the privacy rules, how old its cookies are, its alert and its last press, and one button that runs the action the settings page and the dashboard already run (Refresh cookies, Check again, Connect), the result in place without a reload and a second press refused while one runs; it reads only what it shows (Firefox's cookie names and times from a private copy, never a value; no settings sent to the page, no corpus walk); pnpm ops get cookies says the same; a busy recheck answers 409; alerts and the settings sections link to it
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
60 files changed, 2470 insertions(+), 84 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -196,7 +196,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "<tts engine>:<stock voice>" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). "pitch" is where the result's pitch comes from (settings.voice.convert.pitch): "target" — the stock voice's own, the read's intonation flattened to it; "source" — the pitch the take was read at (raise your voice and it rises); "contour" — the read's rises and falls, moved as a whole to the stock voice's register. "semitones" (-12 to 12) then moves a followed pitch; left out, a followed pitch takes settings.voice.convert.semitones (0 unless set). source and contour are seed-vc's, on its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them. The target's reference is synthesized once through the tts op and kept. The result adds target, voice, pitch (semitones and f0 — the medians heard and the move applied — when followed), synthetic: true and the disclosure line. | |
| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
| `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | |
-| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /settings) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` |
+| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /cookies) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). Asked while a recheck or another press for the service runs (a click, the dashboard's, the timer's): refused, 409 {busy: true}, never queued. dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` |
| `dismiss-service` | — | |
| `rerun-service-jobs` | — | |
| `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` |
@@ -233,7 +233,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for <platform>" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait` |
| `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/<id>/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` |
| `fetch-chat-backlog` | fetch-chat-backlog fetches a channel's stream chats after its downloads: {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose metadata says it was a stream (live\_status was\_live / post\_live) and whose chat is not here, newest first, one at a time through fetch-chat's pass with the batch downloads' gap between two, as one fetch-chat-backlog job on the platform's download queue; a raw replay already here is only normalized. It stops on a rate limit, a held platform, three failures in a row, a drain or "limit" chats; a re-run skips the chats here and the streams known to have none (chat-backlog.json), and a restart resumes it. The download lane queues it by itself (25 a run) for a channel whose "chat" is "later" once it has nothing left to download. "dryRun": true counts from the disk and starts nothing: chats, normalizeOnly, have, settled, notStreams, ids (the first 50). | `pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}'` |
-| `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it is past social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and the rest are DEFERRED until the next refresh. It never refreshes the jar: Refresh cookies on /settings, then {"resume": "<run id>"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` |
+| `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it is past social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and the rest are DEFERRED until the next refresh. It never refreshes the jar: Refresh cookies on /cookies, then {"resume": "<run id>"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` |
| `lookout-run` | lookout-run runs a saved lookout (settings.lookouts), or lists what it would read. {"id", "dryRun": true, "days"?, "maxVideos"?, "until"?: "YYYY-MM-DD"} is the list: every video of its channels whose AIR date (release\_timestamp, else timestamp, in the lookout's timeZone — not the UTC upload\_date) falls in the window; a duplicate upload of one recording, and a stream's cut-down, folded into it (each named, with why and its score); the longest maxVideos recordings read and the rest listed as skipped for the cap; under minSeconds and no transcript yet listed too. A local media library channel or a slug this archive does not hold is named in "refused". Answers {plan: {window, counts, read, skipped, refused, estimate}}: readCalls is one per transcript chunk, priced once a run has been measured. Synchronous, reads text only, writes nothing. Without "dryRun" it is the RUN, a lookout-run job on draft:local: {"id", "days"?, "maxVideos"?, "until"?, "model"?, "maxCalls"?}. The same list, made at the job's turn, read by the local model one chunk a call (every call through the GPU arbiter, after render mode, in the job's model log) into each video's private reading-notes.json; the notes grouped into ideas of at least two located, dated moments; the run written to transcripts/.lookouts/<id>/runs/. A video whose notes are fresh is not read again, so a cancelled run's next start continues where it stopped. maxCalls caps the reading calls (default 400; past it the run ends partial). Refused with lookouts off (settings.lookouts.enabled), the lookout route not local (model names a local one), a run of it already queued or running, a damaged verdicts.json, or under 3 GB of free memory at its turn. --wait prints the log's @@lookout-run line. {"id", "cancel": true} cancels its queued or running run (answers the job ids; the notes read so far are kept). | `pnpm ops lookout-run --json '{"id":"example-week","dryRun":true}'`<br>`pnpm ops lookout-run --json '{"id":"example-week","dryRun":true,"days":3,"until":"2026-11-10"}'`<br>`pnpm ops lookout-run --json '{"id":"example-week"}' --wait`<br>`pnpm ops lookout-run --json '{"id":"example-week","cancel":true}'` |
### Usage, flags and environment
@@ -259,6 +259,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops get kept-originals [<slug>]
pnpm ops get services
pnpm ops get x-session [<slug>]
+ pnpm ops get cookies [fresh]
pnpm ops get x-run [<run id>]
pnpm ops get cleanup <slug>
pnpm ops get speakers
@@ -356,6 +357,17 @@ get x-session [<slug>] is the X login an X job would use and whether one
channel whose own cookiesFromBrowser may decide the source. Nothing is
asked of X: a refresh is Refresh cookies / Connect X account on
/settings. Ask it before queueing fetch-posts or capture-posts on X.
+get cookies [fresh] is the /cookies screen's rows, one per service the
+ editor reads cookies for (x, rumble, youtube, odysee, archive.today, each
+ forum host): source (drawn through settings.privacy), age (ageVerb, ageAt,
+ ageMinutes; ageUnknown when it cannot be read), state (stale | fine |
+ unknown) with the alert's sentence, todo (what to do by hand), button
+ (the row's one press: refresh | connect | recheck; headed: a window on
+ the editor's machine), last (the last press and how it ended) and
+ running. Nothing is asked of any service; "fresh" re-reads the
+ browser's cookie store (names and times only, never a value) instead of
+ the 5-minute cache. Check again is recheck-service; Refresh cookies and
+ the Connects are clicks on /cookies.
get x-run [<run id>] is the X run as /review's X run console shows it:
the latest run (or the one named) — each channel's status (queued,
running, done with its new posts, deferred, failed), "summary" ("N
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -264,6 +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_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/OPERATING.md b/OPERATING.md
@@ -166,6 +166,22 @@ pnpm ops fetch-chat-backlog --json '{"slug":"example"}' --wait
- The caption languages are a Configure field too (`subLangs`, yt-dlp's `--sub-langs`; blank = `en.*,live_chat`),
and a `channel-config` patch key.
+### Cookies: the /cookies screen
+
+```sh
+pnpm ops get cookies # every service's cookie source, age, alert and last press
+pnpm ops get cookies fresh # the same, the browser's cookie store read again (names and times only)
+```
+
+- **/cookies** (Machine → Cookies) has one row per service with its one button. X with a connected profile:
+ **Refresh cookies**. Rumble, YouTube and Odysee: open the site in the browser the row names, then **Check
+ again** (one request, as `recheck-service`). archive.today and each forum host: **Connect**, which opens a window
+ on the editor's machine, not on the phone you pressed it from.
+- A second press while one runs is refused with a sentence, from any tab and from the dashboard's or
+ /settings' buttons too. The row's "last result" is the last press's answer (`actions` in
+ `transcripts/.service-cookies.json`).
+- Refresh cookies stays a click: it loads x.com. There is no ops write for it.
+
### Cookies gone stale: the dashboard's banner
```sh
@@ -183,12 +199,12 @@ pnpm ops dismiss-service --json '{"service":"rumble"}'
names. YouTube's bot check → open youtube.com there, signed in. Odysee's Cloudflare page (a 403 with
Cloudflare's challenge words; no real sample yet) → open odysee.com. A forum's browser check, captcha or
login wall, by host → Connect forum session on the thread's channel page. archive.today's check page →
- Connect archive session (Settings). A Connect that ends on a cleared page clears the banner too.
+ Connect archive session (/cookies). A Connect that ends on a cleared page clears the banner too.
- **X** (`"service":"x"`): a Cloudflare challenge, a 401/403 or a login wall in gallery-dl's output — even
on a run that exits 0 — fails the fetch (posts read so far kept) and raises it; one is enough. **While it
is up, no X job starts**: every fetch, older walk, X search, capture or import on X is refused with its
sentence, and the refused jobs are listed for **Re-run stopped jobs**. Pass X's check by hand (Connect X
- account on /settings and clear it in the window; with the browser login, open x.com in that browser),
+ account on /cookies and clear it in the window; with the browser login, open x.com in that browser),
press **Refresh cookies**, then **Recheck** — which sends X *no* request: it clears when the login on disk
was renewed after the alert was raised. A gallery-dl "AuthRequired: authenticated cookies needed" (a
logged-out timeline), "Could not authenticate you" or a 401 is a **login failure**; a 429 or a rate-limit
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -193,7 +193,7 @@ Per-platform settings of the social posts: X's three, all chosen in the X accoun
|---|---|---|
| `cookieSource` | absent | Where the X fetchers' login comes from. `"browser"`: the operator's everyday browser, named by `cookiesFromBrowser` — gallery-dl is handed `--cookies-from-browser <spec>` and reads it on every run, and the Playwright fallback reads the same store (Firefox only; common/social/xBrowserLogin.ts), so the login lasts as long as the browser's. `"profile"`: the session broker's persistent profile ("Connect X account" on /settings) and the cookie jar it exports. ABSENT (the default) is resolved at read time, never stored: `"browser"` when `cookiesFromBrowser` is set and no profile is connected (no exported jar carrying an auth_token), else `"profile"`. The source, not `cookieMode`, governs the X fetchers. |
| `visibility` | absent | Where X posts may appear. `"public"` (the default; absent): an X channel's posts are built into every site that has the channel. `"private"`: every X channel's posts (a channel with `sourceKind: "social"` and `platform: "twitter"`) are left out of every PUBLIC site build — the channel with them, since posts are all an X channel holds — and built only into PRIVATE sites (`site.json` `audience`). Nothing on disk changes and fetching does not; a site already published changes on its next build and deploy, and flipping back is a rebuild. Chosen in the X account session section of /settings; the rule is common/lib/postsVisibility.ts. |
-| `maxCookieAgeMinutes` | absent | THE FRESH-JAR RULE: with the `"profile"` login source, a job that sends requests to X (Fetch posts, the older walk, an X search, Capture posts, Import one post, Check deleted posts — and the scheduler's fetches) is refused when it STARTS unless the profile's exported cookie jar was written within this many minutes and carries a login (an auth_token). The refusal says what to do: press Refresh cookies (or Connect X account) on /settings, then fetch again. A refresh is a human click — it loads x.com/home, itself a request to X — so the editor never refreshes the jar to satisfy this. With the `"browser"` source the age cannot be read: the job logs that and proceeds. ABSENT: 60. 0 turns the rule off; at most 10080 (a week). Set in the X account session section of /settings. common/jobs/networkGuard.ts. |
+| `maxCookieAgeMinutes` | absent | THE FRESH-JAR RULE: with the `"profile"` login source, a job that sends requests to X (Fetch posts, the older walk, an X search, Capture posts, Import one post, Check deleted posts — and the scheduler's fetches) is refused when it STARTS unless the profile's exported cookie jar was written within this many minutes and carries a login (an auth_token). The refusal says what to do: press Refresh cookies (or Connect X account) on /cookies, then fetch again. A refresh is a human click — it loads x.com/home, itself a request to X — so the editor never refreshes the jar to satisfy this. With the `"browser"` source the age cannot be read: the job logs that and proceeds. ABSENT: 60. 0 turns the rule off; at most 10080 (a week). Set in the X account session section of /settings. common/jobs/networkGuard.ts. |
#### `social.xenforo`
diff --git a/common/controller/recheckServiceCookies.test.ts b/common/controller/recheckServiceCookies.test.ts
@@ -189,7 +189,7 @@ test("Recheck (X, jar-age): the jar's age on disk, no request — stale while ol
loggedIn: true,
fresh,
readAt: new Date().toISOString(),
- summary: fresh ? "The X cookie jar was written 1 min ago (limit 60 min)." : "The X cookie jar was written 3 h ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings.",
+ summary: fresh ? "The X cookie jar was written 1 min ago (limit 60 min)." : "The X cookie jar was written 3 h ago (limit 60 min): press Refresh cookies (or Connect X account) on /cookies.",
}),
};
const stale = await recheckServiceCookies({ paths, service: "x", deps });
diff --git a/common/controller/recheckServiceCookies.ts b/common/controller/recheckServiceCookies.ts
@@ -19,7 +19,7 @@
// that gets an account locked. Clean when the
// login was renewed AFTER the alert was raised —
// the profile's jar re-exported (Refresh cookies
-// on /settings) with a login in it, or, with the
+// on /cookies) with a login in it, or, with the
// browser source, the browser's x.com auth_token
// last sent since — read from disk only.
// A "jar-age" alert (the fresh-jar rule's
@@ -269,7 +269,7 @@ export async function recheckServiceCookies(opts: {
"stale",
login.source === "profile"
? `${label}'s cookie jar has not been re-exported with a login since the challenge${at}: pass X's check by hand ` +
- "(Connect X account on /settings), press Refresh cookies there, then Recheck. Recheck sends X no request."
+ "(Connect X account on /cookies), press Refresh cookies there, then Recheck. Recheck sends X no request."
: `The browser's X login has not been used since the challenge${at}: open x.com in ` +
`${login.browser ?? "the browser cookiesFromBrowser names"}, pass its check, then Recheck. Recheck sends X no request.`,
);
diff --git a/common/controller/serviceCookieTimer.test.ts b/common/controller/serviceCookieTimer.test.ts
@@ -38,7 +38,7 @@ function jar(fresh: boolean): XJarStatusView {
loggedIn: true,
fresh,
readAt: new Date(NOW).toISOString(),
- summary: fresh ? "The X cookie jar was written 5 min ago (limit 60 min)." : "The X cookie jar was written 5 h ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings.",
+ summary: fresh ? "The X cookie jar was written 5 min ago (limit 60 min)." : "The X cookie jar was written 5 h ago (limit 60 min): press Refresh cookies (or Connect X account) on /cookies.",
};
}
diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts
@@ -16,7 +16,7 @@
// - BEFORE EACH CHANNEL the network guard is asked again (the fresh-jar rule
// and the X alert, jobs/networkGuard.ts). When it refuses, the run STOPS
// there and every channel not yet fetched is DEFERRED. Nothing here ever
-// refreshes the jar: a refresh is the operator's click on /settings
+// refreshes the jar: a refresh is the operator's click on /cookies
// (refreshXCookies loads x.com/home — itself a request to X);
// - a deferred run is resumed by its id (the console's Resume, `pnpm ops
// x-run {"resume": id}`, a Retry of the job): it starts with the deferred
diff --git a/common/jobs/networkGuard.test.ts b/common/jobs/networkGuard.test.ts
@@ -30,7 +30,7 @@ test("the fresh-jar rule (profile source)", () => {
assert.deepEqual(v(16 * 24 * 3600_000), {
ok: false,
message:
- "X cookies were last refreshed 16 days ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings, then fetch again.",
+ "X cookies were last refreshed 16 days ago (limit 60 min): press Refresh cookies (or Connect X account) on /cookies, then fetch again.",
});
assert.match((v(61 * 60_000) as { message: string }).message, /61 min ago/);
assert.match((v(60_000, false) as { message: string }).message, /holds no login/);
diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts
@@ -10,7 +10,7 @@
// 3. X ONLY ON A FRESH JAR. With the "profile" login source, a job aimed at X
// starts only when the exported cookie jar was written within
// `social.x.maxCookieAgeMinutes` (default 60; 0 = off) and carries a login.
-// A refresh is a human click on /settings — refreshXCookies loads
+// A refresh is a human click on /cookies — refreshXCookies loads
// x.com/home, itself a request to X — so nothing here refreshes it. With
// the "browser" source the age cannot be read: the job logs that and
// proceeds.
@@ -120,14 +120,14 @@ export function xJarVerdict(input: {
if (!status.hasCookies || !status.cookiesUpdatedAt) {
return {
ok: false,
- message: "No X cookie jar has been exported: press Connect X account on /settings, then fetch again.",
+ message: "No X cookie jar has been exported: press Connect X account on /cookies, then fetch again.",
};
}
if (!status.looksAuthenticated) {
return {
ok: false,
message:
- "The X cookie jar holds no login (no auth_token): press Connect X account on /settings, then fetch again.",
+ "The X cookie jar holds no login (no auth_token): press Connect X account on /cookies, then fetch again.",
};
}
const age = input.now - Date.parse(status.cookiesUpdatedAt);
@@ -136,7 +136,7 @@ export function xJarVerdict(input: {
ok: false,
message:
`X cookies were last refreshed ${ageText(age)} ago (limit ${input.maxAgeMinutes} min): ` +
- `press Refresh cookies (or Connect X account) on /settings, then fetch again.`,
+ `press Refresh cookies (or Connect X account) on /cookies, then fetch again.`,
};
}
return { ok: true };
diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts
@@ -205,7 +205,7 @@ test("a stale jar is refused at enqueue, and at the start of a job queued while
assert.equal(res.ok, false);
assert.match(
res.ok ? "" : res.error,
- /^X cookies were last refreshed 16 days ago \(limit 60 min\): press Refresh cookies \(or Connect X account\) on \/settings, then fetch again\.$/,
+ /^X cookies were last refreshed 16 days ago \(limit 60 min\): press Refresh cookies \(or Connect X account\) on \/cookies, then fetch again\.$/,
);
// Fresh at enqueue; stale by the time the queue reaches it.
@@ -283,7 +283,7 @@ test("the fresh-jar rule raises X's jar-age banner (the job refused at its start
xJar: { source: "profile", ageMinutes: 120, maxAgeMinutes: 60 },
});
assert.equal(view.alerts[0]?.headline, "X cookies are 2 h old (limit 60 min)");
- assert.equal(view.alerts[0]?.fix, "Refresh cookies (or Connect X account) on /settings — then Recheck.");
+ assert.equal(view.alerts[0]?.fix, "Refresh cookies (or Connect X account) on /cookies — then Recheck.");
assert.equal(view.alerts[0]?.detail, `Refused fetch-posts ${bDone.jobId} (${SLUGS[1]}).`);
assert.equal(view.alerts[0]?.compact, true);
const browserView = buildServiceCookieAlerts(st, {
diff --git a/common/lib/browserCookieAge.test.ts b/common/lib/browserCookieAge.test.ts
@@ -0,0 +1,162 @@
+// The yt-dlp services' browser-cookie ages (browserCookieAge.ts), read BY NAME
+// from a Firefox cookies.sqlite. Every store is a fixture written through
+// node:sqlite under a temp dir (social/__fixtures__/firefoxCookieStore.ts) — no
+// test reads a real browser profile, and nothing asks any service.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/browserCookieAge.test.ts
+
+import { test, after, beforeEach } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { mkdir, readdir, rm, utimes, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {
+ BROWSER_COOKIE_TIMES_SQL,
+ readBrowserCookieAges,
+ readFirefoxServiceCookieTimes,
+ resetBrowserCookieAgeCache,
+ STALE_COPY_MS,
+} from "./browserCookieAge";
+import { writeFirefoxCookieStore } from "../social/__fixtures__/firefoxCookieStore";
+
+const TMP = mkdtempSync(path.join(os.tmpdir(), "cookieage-"));
+after(() => rm(TMP, { recursive: true, force: true }));
+beforeEach(() => resetBrowserCookieAgeCache());
+
+const us = (iso: string) => Date.parse(iso) * 1000;
+
+test("the query never selects a cookie's value", () => {
+ // The column list is everything between SELECT and FROM.
+ const cols = /^SELECT (.*) FROM /.exec(BROWSER_COOKIE_TIMES_SQL)?.[1] ?? "";
+ assert.ok(cols.length > 0);
+ assert.doesNotMatch(cols, /\bvalue\b/i);
+ assert.doesNotMatch(cols, /\*/);
+ assert.deepEqual(
+ cols.split(",").map((c) => c.trim()),
+ ["host", "name", "creationTime", "lastAccessed", "expiry", "originAttributes"],
+ );
+});
+
+test("rumble's clearance: issued and expiry; youtube's sign-in: last used; odysee with none", async () => {
+ const dir = path.join(TMP, "p1");
+ await writeFirefoxCookieStore(dir, [
+ {
+ host: ".rumble.com",
+ name: "cf_clearance",
+ value: "fixture-not-a-real-clearance",
+ creationTime: us("2026-11-16T09:00:00Z"),
+ lastAccessed: us("2026-11-16T09:10:00Z"),
+ expiry: Date.parse("2026-11-16T10:00:00Z") / 1000,
+ },
+ // An older clearance on a subdomain: the newest wins.
+ { host: "a.rumble.com", name: "cf_clearance", value: "x", creationTime: us("2026-11-15T09:00:00Z") },
+ // Not the site's (a lookalike host).
+ { host: ".notrumble.com", name: "cf_clearance", value: "x", creationTime: us("2026-11-16T09:30:00Z") },
+ { host: ".youtube.com", name: "SID", value: "x", lastAccessed: us("2026-11-16T08:00:00Z"), creationTime: us("2026-01-01T00:00:00Z") },
+ { host: ".youtube.com", name: "__Secure-3PSID", value: "x", lastAccessed: us("2026-11-16T08:30:00Z") },
+ { host: ".youtube.com", name: "PREF", value: "x", lastAccessed: us("2026-11-16T09:59:00Z") },
+ ]);
+ const out = await readFirefoxServiceCookieTimes(path.join(dir, "cookies.sqlite"), { tmpRoot: TMP });
+ assert.deepEqual(out.rumble, {
+ service: "rumble",
+ basis: "clearance",
+ found: true,
+ at: "2026-11-16T09:00:00.000Z",
+ expiresAt: "2026-11-16T10:00:00.000Z",
+ });
+ assert.equal(out.youtube.basis, "login-used");
+ assert.equal(out.youtube.at, "2026-11-16T08:30:00.000Z");
+ assert.equal(out.youtube.expiresAt, undefined);
+ assert.deepEqual(out.odysee, { service: "odysee", basis: "clearance", found: false, at: null });
+ // Nothing returned carries a value.
+ assert.doesNotMatch(JSON.stringify(out), /fixture-not-a-real/);
+});
+
+test("a cookie only in the write-ahead log counts; a container the spec does not read does not", async () => {
+ const dir = path.join(TMP, "p2");
+ const { db } = await writeFirefoxCookieStore(
+ dir,
+ [
+ { host: ".rumble.com", name: "cf_clearance", value: "x", creationTime: us("2026-11-16T07:00:00Z") },
+ {
+ host: ".rumble.com",
+ name: "cf_clearance",
+ value: "x",
+ creationTime: us("2026-11-16T09:45:00Z"),
+ originAttributes: "^userContextId=2",
+ },
+ ],
+ { keepOpen: true },
+ );
+ try {
+ const out = await readFirefoxServiceCookieTimes(path.join(dir, "cookies.sqlite"), { tmpRoot: TMP });
+ assert.equal(out.rumble.at, "2026-11-16T07:00:00.000Z");
+ const all = await readFirefoxServiceCookieTimes(path.join(dir, "cookies.sqlite"), { tmpRoot: TMP, container: "all" });
+ assert.equal(all.rumble.at, "2026-11-16T09:45:00.000Z");
+ } finally {
+ db?.close();
+ }
+});
+
+test("readBrowserCookieAges: a profile path spec, the cache, and fresh", async () => {
+ const dir = path.join(TMP, "p3");
+ await writeFirefoxCookieStore(dir, [
+ { host: ".rumble.com", name: "cf_clearance", value: "x", creationTime: us("2026-11-16T09:00:00Z") },
+ ]);
+ const spec = `firefox:${dir}`;
+ const a = await readBrowserCookieAges(spec, { home: TMP, tmpRoot: TMP, now: 1000 });
+ assert.equal(a.services.rumble.at, "2026-11-16T09:00:00.000Z");
+ // A rewrite of the store is not seen inside the cache window...
+ await rm(path.join(dir, "cookies.sqlite"));
+ await writeFirefoxCookieStore(dir, [
+ { host: ".rumble.com", name: "cf_clearance", value: "x", creationTime: us("2026-11-16T09:50:00Z") },
+ ]);
+ const b = await readBrowserCookieAges(spec, { home: TMP, tmpRoot: TMP, now: 2000 });
+ assert.equal(b.services.rumble.at, "2026-11-16T09:00:00.000Z");
+ // ...and is with fresh.
+ const c = await readBrowserCookieAges(spec, { home: TMP, tmpRoot: TMP, now: 3000, fresh: true });
+ assert.equal(c.services.rumble.at, "2026-11-16T09:50:00.000Z");
+});
+
+test("unreadable sources are answers, never throws", async () => {
+ const none = await readBrowserCookieAges(undefined, { home: TMP });
+ assert.equal(none.services.rumble.found, null);
+ assert.match(none.services.rumble.unknown ?? "", /No cookiesFromBrowser/);
+ const chrome = await readBrowserCookieAges("chrome", { home: TMP });
+ assert.match(chrome.services.youtube.unknown ?? "", /encrypted/);
+ const missing = await readBrowserCookieAges(`firefox:${path.join(TMP, "no-such-profile")}`, { home: TMP });
+ assert.equal(missing.services.odysee.at, null);
+ assert.ok(missing.services.odysee.unknown);
+ const corrupt = path.join(TMP, "p4");
+ await writeFirefoxCookieStore(corrupt, []);
+ await writeFile(path.join(corrupt, "cookies.sqlite"), "not a database");
+ const bad = await readBrowserCookieAges(`firefox:${corrupt}`, { home: TMP, tmpRoot: TMP });
+ assert.match(bad.services.rumble.unknown ?? "", /Could not read Firefox's cookie store/);
+});
+
+test("a file: spec is aged by the file's mtime", async () => {
+ const file = path.join(TMP, "cookies.txt");
+ await writeFile(file, "# Netscape HTTP Cookie File\n");
+ const t = new Date("2026-11-16T06:00:00Z");
+ await utimes(file, t, t);
+ const out = await readBrowserCookieAges(`file:${file}`);
+ assert.deepEqual(out.services.youtube, { service: "youtube", basis: "file", found: true, at: t.toISOString() });
+});
+
+test("a read sweeps this module's stale copies (they hold values), and leaves fresh ones and others alone", async () => {
+ const root = path.join(TMP, "sweep");
+ await mkdir(root);
+ const old = path.join(root, "archilyzer-cookieage-old1");
+ const fresh = path.join(root, "archilyzer-cookieage-new1");
+ const other = path.join(root, "someone-elses-old");
+ for (const d of [old, fresh, other]) await mkdir(d);
+ const past = new Date(Date.now() - STALE_COPY_MS - 60_000);
+ await utimes(old, past, past);
+ await utimes(other, past, past);
+ const dir = path.join(TMP, "p5");
+ await writeFirefoxCookieStore(dir, []);
+ await readFirefoxServiceCookieTimes(path.join(dir, "cookies.sqlite"), { tmpRoot: root });
+ // The read's own copy is gone too, once it is done.
+ assert.deepEqual((await readdir(root)).sort(), ["archilyzer-cookieage-new1", "someone-elses-old"]);
+});
diff --git a/common/lib/browserCookieAge.ts b/common/lib/browserCookieAge.ts
@@ -0,0 +1,229 @@
+// HOW FRESH A yt-dlp SERVICE'S BROWSER COOKIES ARE — read from disk, never from
+// the service (the /cookies screen, plans/cookie-screen.md). Rumble, YouTube
+// and Odysee are fetched by yt-dlp with `--cookies-from-browser <spec>`: their
+// "jar" IS the browser's cookie store, and a refresh is the operator opening
+// the site in that browser. So the age shown is what the store says:
+//
+// rumble, odysee Cloudflare's `cf_clearance` for the site — when it was
+// issued (creationTime: the check passed) and when it
+// expires.
+// youtube the sign-in cookies — when Firefox last SENT one
+// (lastAccessed: youtube.com was open, signed in).
+//
+// THE SAME DISCIPLINE AS X's (social/xJarAge.ts readFirefoxXAuthTimes): a
+// private copy of the store and its write-ahead log in a 0700 temp dir removed
+// after; the query selects host, name and the three times ONLY — never the
+// value (BROWSER_COOKIE_TIMES_SQL; a test fails if it ever does); nothing here
+// logs a cookie's name. Firefox only (Chromium stores are encrypted). A
+// `file:` spec (an exported cookies.txt) is aged by the file's mtime.
+//
+// Cached for a few minutes per spec (the page polls); `fresh: true` reads again
+// (Check again). A read that fails is an answer — `unknown` with the reason —
+// never a throw.
+
+import { copyFile, mkdir, mkdtemp, readdir, rm, stat } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { loadSqlite } from "../social/nodeSqlite";
+import { findFirefoxCookieDb, firefoxContainerScope, inContainerScope } from "../social/xBrowserLogin";
+import { parseBrowserSpec, SELF_READ_BROWSERS } from "../social/xCookieSource";
+import { cookieFileOf } from "./cookiePolicy";
+
+export const BROWSER_COOKIE_AGE_CACHE_MS = 5 * 60_000;
+
+export type BrowserCookieService = "rumble" | "youtube" | "odysee";
+export const BROWSER_COOKIE_SERVICES: readonly BrowserCookieService[] = ["rumble", "youtube", "odysee"];
+
+type Want = { domain: string; names: readonly string[]; basis: "clearance" | "login-used" };
+
+// What each service's freshness is read from.
+export const BROWSER_COOKIE_WANTS: Record<BrowserCookieService, Want> = {
+ rumble: { domain: "rumble.com", names: ["cf_clearance"], basis: "clearance" },
+ odysee: { domain: "odysee.com", names: ["cf_clearance"], basis: "clearance" },
+ youtube: { domain: "youtube.com", names: ["SID", "__Secure-3PSID", "LOGIN_INFO"], basis: "login-used" },
+};
+
+// THE NAME-ONLY QUERY. Never add `value` here.
+export const BROWSER_COOKIE_TIMES_SQL =
+ "SELECT host, name, creationTime, lastAccessed, expiry, originAttributes FROM moz_cookies WHERE name IN (";
+
+export type BrowserCookieAge = {
+ service: BrowserCookieService;
+ // "clearance": `at` is when the clearance was issued; "login-used": when the
+ // browser last sent the sign-in; "file": the exported cookies file's mtime.
+ basis: "clearance" | "login-used" | "file";
+ // A cookie for the service is in the store (null: the store could not be read).
+ found: boolean | null;
+ at: string | null;
+ expiresAt?: string;
+ // Why nothing could be read, when nothing could.
+ unknown?: string;
+};
+
+export type BrowserCookieAges = {
+ spec: string;
+ readAt: string;
+ services: Record<BrowserCookieService, BrowserCookieAge>;
+};
+
+// PRTime (µs) → ms; a value already in ms is kept.
+function prtimeMs(v: unknown): number | undefined {
+ const n = typeof v === "bigint" ? Number(v) : typeof v === "number" ? v : NaN;
+ if (!Number.isFinite(n) || n <= 0) return undefined;
+ return Math.floor(n > 1e14 ? n / 1000 : n);
+}
+
+function secondsMs(v: unknown): number | undefined {
+ const n = typeof v === "bigint" ? Number(v) : typeof v === "number" ? v : NaN;
+ if (!Number.isFinite(n) || n <= 0) return undefined;
+ return Math.floor(n > 1e11 ? n : n * 1000);
+}
+
+function onDomain(host: string, domain: string): boolean {
+ const h = host.replace(/^\./, "").toLowerCase();
+ return h === domain || h.endsWith(`.${domain}`);
+}
+
+function allUnknown(why: string, basis?: BrowserCookieAge["basis"]): Record<BrowserCookieService, BrowserCookieAge> {
+ const out = {} as Record<BrowserCookieService, BrowserCookieAge>;
+ for (const s of BROWSER_COOKIE_SERVICES) {
+ out[s] = { service: s, basis: basis ?? BROWSER_COOKIE_WANTS[s].basis, found: null, at: null, unknown: why };
+ }
+ return out;
+}
+
+const TMP_PREFIX = "archilyzer-cookieage-";
+// A private copy older than this was left by a read that never finished (the
+// process died mid-read): it holds cookie values, so it goes.
+export const STALE_COPY_MS = 10 * 60_000;
+
+// Remove this module's own leftover copies under `tmpRoot`. Never throws.
+export async function sweepStaleCookieCopies(tmpRoot: string, now: number = Date.now()): Promise<number> {
+ let removed = 0;
+ const names = await readdir(tmpRoot).catch(() => [] as string[]);
+ for (const name of names) {
+ if (!name.startsWith(TMP_PREFIX)) continue;
+ const dir = path.join(tmpRoot, name);
+ const st = await stat(dir).catch(() => null);
+ if (!st?.isDirectory() || now - st.mtimeMs < STALE_COPY_MS) continue;
+ await rm(dir, { recursive: true, force: true }).then(
+ () => removed++,
+ () => undefined,
+ );
+ }
+ return removed;
+}
+
+// One read of a Firefox cookies.sqlite for every service (`container` as in a
+// cookiesFromBrowser spec).
+export async function readFirefoxServiceCookieTimes(
+ dbFile: string,
+ opts: { container?: string; tmpRoot?: string } = {},
+): Promise<Record<BrowserCookieService, BrowserCookieAge>> {
+ const { DatabaseSync } = await loadSqlite();
+ const scope = await firefoxContainerScope(dbFile, opts.container);
+ const names = [...new Set(BROWSER_COOKIE_SERVICES.flatMap((s) => BROWSER_COOKIE_WANTS[s].names))];
+ const tmpRoot = opts.tmpRoot ?? os.tmpdir();
+ await sweepStaleCookieCopies(tmpRoot);
+ const tmp = await mkdtemp(path.join(tmpRoot, TMP_PREFIX));
+ try {
+ const copy = path.join(tmp, "store", "cookies.sqlite");
+ await mkdir(path.dirname(copy), { mode: 0o700 });
+ await copyFile(dbFile, copy);
+ await copyFile(`${dbFile}-wal`, `${copy}-wal`).catch((err: NodeJS.ErrnoException) => {
+ if (err.code !== "ENOENT") throw err;
+ });
+ const db = new DatabaseSync(copy);
+ let rows: Array<Record<string, unknown>>;
+ try {
+ rows = db
+ .prepare(`${BROWSER_COOKIE_TIMES_SQL}${names.map(() => "?").join(", ")})`)
+ .all(...names) as Array<Record<string, unknown>>;
+ } finally {
+ db.close();
+ }
+ const out = {} as Record<BrowserCookieService, BrowserCookieAge>;
+ for (const s of BROWSER_COOKIE_SERVICES) {
+ const want = BROWSER_COOKIE_WANTS[s];
+ let best: { at?: number; exp?: number } | null = null;
+ for (const r of rows) {
+ if (typeof r.host !== "string" || typeof r.name !== "string") continue;
+ if (!want.names.includes(r.name) || !onDomain(r.host, want.domain)) continue;
+ const attrs = typeof r.originAttributes === "string" ? r.originAttributes : "";
+ if (!inContainerScope(attrs, scope)) continue;
+ const at = want.basis === "clearance" ? prtimeMs(r.creationTime) ?? prtimeMs(r.lastAccessed) : prtimeMs(r.lastAccessed);
+ if (!best || (at ?? 0) > (best.at ?? 0)) best = { at, exp: secondsMs(r.expiry) };
+ }
+ out[s] = {
+ service: s,
+ basis: want.basis,
+ found: best !== null,
+ at: best?.at ? new Date(best.at).toISOString() : null,
+ ...(best?.exp && want.basis === "clearance" ? { expiresAt: new Date(best.exp).toISOString() } : {}),
+ };
+ }
+ return out;
+ } finally {
+ await rm(tmp, { recursive: true, force: true });
+ }
+}
+
+type Cache = { key: string; at: number; value: BrowserCookieAges };
+const CACHE_KEY = Symbol.for("archilyzer.browserCookieAge.cache");
+function cache(): Map<string, Cache> {
+ const g = globalThis as unknown as Record<symbol, Map<string, Cache>>;
+ return (g[CACHE_KEY] ??= new Map());
+}
+
+// The ages for one cookie spec (a channel's or settings' cookiesFromBrowser).
+export async function readBrowserCookieAges(
+ spec: string | undefined,
+ opts: { now?: number; fresh?: boolean; home?: string; tmpRoot?: string } = {},
+): Promise<BrowserCookieAges> {
+ const now = opts.now ?? Date.now();
+ const key = (spec ?? "").trim();
+ const readAt = new Date(now).toISOString();
+ const c = cache();
+ const hit = c.get(key);
+ if (!opts.fresh && hit && now - hit.at < BROWSER_COOKIE_AGE_CACHE_MS) return hit.value;
+ const done = (services: Record<BrowserCookieService, BrowserCookieAge>): BrowserCookieAges => {
+ const value = { spec: key, readAt, services };
+ c.set(key, { key, at: now, value });
+ return value;
+ };
+ if (!key) return done(allUnknown("No cookiesFromBrowser is set, so yt-dlp sends no browser cookies."));
+ const file = cookieFileOf(key);
+ if (file) {
+ try {
+ const st = await stat(file);
+ const at = new Date(st.mtimeMs).toISOString();
+ const out = {} as Record<BrowserCookieService, BrowserCookieAge>;
+ for (const s of BROWSER_COOKIE_SERVICES) out[s] = { service: s, basis: "file", found: true, at };
+ return done(out);
+ } catch {
+ return done(allUnknown("The cookies file cookiesFromBrowser names could not be read.", "file"));
+ }
+ }
+ const parsed = parseBrowserSpec(key);
+ if (!parsed) return done(allUnknown("cookiesFromBrowser names no browser this screen can read."));
+ if (!SELF_READ_BROWSERS.includes(parsed.browser)) {
+ return done(allUnknown(`${parsed.browser}'s cookie store is encrypted; only Firefox's can be read here.`));
+ }
+ try {
+ const found = await findFirefoxCookieDb(parsed, opts.home ?? os.homedir());
+ if (!found.file) return done(allUnknown("No Firefox cookie store found."));
+ return done(
+ await readFirefoxServiceCookieTimes(found.file, {
+ ...(parsed.container ? { container: parsed.container } : {}),
+ ...(opts.tmpRoot ? { tmpRoot: opts.tmpRoot } : {}),
+ }),
+ );
+ } catch (err) {
+ return done(allUnknown(`Could not read Firefox's cookie store: ${(err as Error).message.split("\n")[0]}`));
+ }
+}
+
+// Forget every cached read (tests).
+export function resetBrowserCookieAgeCache(): void {
+ cache().clear();
+}
diff --git a/common/lib/cookieStatus.test.ts b/common/lib/cookieStatus.test.ts
@@ -0,0 +1,178 @@
+// The /cookies screen's rows (cookieStatus.ts): pure, from what the editor read.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/cookieStatus.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import { ageSentence, buildCookieStatus, durationText, forumThreadFor, HEADED_NOTE, type CookieStatusInput } from "./cookieStatus";
+import { emptyServiceCookieState, type ServiceCookieAlertView } from "./serviceCookies";
+import type { BrowserCookieAge } from "./browserCookieAge";
+
+const NOW = Date.parse("2026-11-16T10:00:00Z");
+const age = (service: "rumble" | "youtube" | "odysee", over: Partial<BrowserCookieAge> = {}): BrowserCookieAge => ({
+ service,
+ basis: service === "youtube" ? "login-used" : "clearance",
+ found: false,
+ at: null,
+ ...over,
+});
+
+// The privacy displayers, as settings.privacy would draw them.
+const display = {
+ path: (p: string) => p.replace("/home/someone", "/home/user"),
+ text: (s: string) => s.replace("/home/someone", "/home/user"),
+};
+
+function input(over: Partial<CookieStatusInput> = {}): CookieStatusInput {
+ return {
+ now: NOW,
+ alerts: { alerts: [], pending: [] },
+ state: emptyServiceCookieState(),
+ x: { source: "profile", profileDir: "/home/someone/t/.x-session/profile", hasProfile: true },
+ ytdlp: {
+ rumble: { spec: "firefox", specFrom: "settings", age: age("rumble") },
+ youtube: { spec: "firefox", specFrom: "settings", age: age("youtube") },
+ odysee: { spec: "firefox", specFrom: "settings", age: age("odysee") },
+ },
+ archive: { dir: "/home/someone/t/.archive-session", hasProfile: false },
+ forums: [],
+ running: {},
+ display,
+ ...over,
+ };
+}
+
+const row = (p: ReturnType<typeof buildCookieStatus>, s: string) => {
+ const r = p.rows.find((x) => x.service === s);
+ assert.ok(r, `no row for ${s}`);
+ return r;
+};
+
+test("durations and age sentences", () => {
+ assert.equal(durationText(12), "12 min");
+ assert.equal(durationText(180), "3 h");
+ assert.equal(durationText(60 * 24 * 3), "3 days");
+ assert.equal(ageSentence("jar written", "2026-11-16T09:48:00Z", NOW), "jar written 12 min ago");
+ assert.equal(ageSentence("jar written", "2026-11-16T09:59:40Z", NOW), "jar written just now");
+ assert.equal(ageSentence("jar written", null, NOW), null);
+});
+
+test("the fixed rows, in order, with paths drawn through the displayers", () => {
+ const p = buildCookieStatus(input());
+ assert.deepEqual(p.rows.map((r) => r.service), ["x", "rumble", "youtube", "odysee", "archive.today"]);
+ assert.equal(row(p, "x").source, "Connected profile (/home/user/t/.x-session/profile)");
+ assert.equal(row(p, "archive.today").source, "Archive profile (/home/user/t/.archive-session)");
+ assert.doesNotMatch(JSON.stringify(p), /someone/);
+});
+
+test("X with a connected profile: Refresh cookies, the jar's age and its limit", () => {
+ const p = buildCookieStatus(
+ input({
+ x: {
+ source: "profile",
+ profileDir: "/p",
+ hasProfile: true,
+ jar: { source: "profile", at: "2026-11-16T09:48:00Z", ageMinutes: 12, maxAgeMinutes: 60, loggedIn: true, fresh: true, readAt: "", summary: "" },
+ },
+ }),
+ );
+ const x = row(p, "x");
+ assert.deepEqual(x.button, { action: "refresh", label: "Refresh cookies" });
+ assert.equal(x.age, "jar written 12 min ago");
+ assert.equal(x.ageNote, "limit 60 min");
+ assert.equal(x.state, "fine");
+ assert.equal(x.headed, undefined);
+});
+
+test("X with no profile: Connect, said to open on the editor's machine", () => {
+ const x = row(buildCookieStatus(input({ x: { source: "profile", profileDir: "/p", hasProfile: false } })), "x");
+ assert.deepEqual(x.button, { action: "connect", label: "Connect X account" });
+ assert.equal(x.headed, true);
+ assert.equal(x.todo, HEADED_NOTE);
+ assert.equal(x.state, "unknown");
+ assert.equal(x.ageUnknown, "No X profile connected yet.");
+});
+
+test("X with the browser login: open x.com, then Check again", () => {
+ const x = row(
+ buildCookieStatus(input({ x: { source: "browser", browserSpec: "firefox:/home/someone/ff", profileDir: "/p", hasProfile: false } })),
+ "x",
+ );
+ assert.deepEqual(x.button, { action: "recheck", label: "Check again" });
+ assert.equal(x.todo, "Open x.com in firefox, then Check again (no request is sent to X).");
+ assert.equal(x.source, "Browser login (firefox:/home/user/ff)");
+});
+
+test("Rumble: a stale alert's headline, the clearance's age and expiry, Check again", () => {
+ const state = emptyServiceCookieState();
+ state.lastGood.rumble = { url: "https://rumble.com/v1", channel: "c", at: "2026-11-16T08:00:00Z" };
+ state.actions = { rumble: { at: "2026-11-16T09:30:00Z", action: "recheck", ok: true, result: "stale", message: "still refused" } };
+ const alert = { service: "rumble", state: "stale", headline: "Rumble needs fresh cookies: open rumble.com in firefox" } as ServiceCookieAlertView;
+ const p = buildCookieStatus(
+ input({
+ state,
+ alerts: { alerts: [alert], pending: [] },
+ ytdlp: {
+ ...input().ytdlp,
+ rumble: {
+ spec: "firefox",
+ specFrom: "channel",
+ channel: "c",
+ age: age("rumble", { found: true, at: "2026-11-16T09:20:00Z", expiresAt: "2026-11-16T10:30:00Z" }),
+ },
+ },
+ running: { rumble: { action: "recheck", since: "2026-11-16T09:59:00Z" } },
+ }),
+ );
+ const r = row(p, "rumble");
+ assert.equal(r.state, "stale");
+ assert.equal(r.alert, alert.headline);
+ assert.equal(r.age, "clearance issued 40 min ago");
+ assert.equal(r.ageNote, "expires in 30 min");
+ assert.equal(r.source, "firefox (channel c)");
+ assert.equal(r.todo, "Open rumble.com in firefox, then Check again.");
+ assert.deepEqual(r.button, { action: "recheck", label: "Check again" });
+ assert.equal(r.last?.result, "stale");
+ assert.deepEqual(r.running, { action: "recheck", since: "2026-11-16T09:59:00Z" });
+});
+
+test("a yt-dlp service with nothing recorded: unknown, and Check again says why it cannot ask", () => {
+ const p = buildCookieStatus(input());
+ const o = row(p, "odysee");
+ assert.equal(o.state, "unknown");
+ assert.equal(o.ageUnknown, "No clearance cookie for odysee.com in firefox.");
+ assert.equal(o.button?.disabled, "No Odysee request is recorded yet to ask again.");
+ const y = row(p, "youtube");
+ assert.equal(y.todo, "Open youtube.com in firefox signed in, then Check again.");
+});
+
+test("a pending first signal is said, not raised", () => {
+ const p = buildCookieStatus(
+ input({ alerts: { alerts: [], pending: [{ service: "rumble", label: "Rumble", kind: "embed-403", videos: ["a"], lastSeen: "2026-11-16T09:12:00Z" }] } }),
+ );
+ assert.equal(row(p, "rumble").alert, "One embed 403 at 09:12 UTC; a second video raises the alert.");
+});
+
+test("forum hosts: from the profiles and from the state, sorted; Connect needs a thread", () => {
+ const state = emptyServiceCookieState();
+ state.lastGood["kiwifarms.st"] = { url: "https://kiwifarms.st/threads/t.1/", at: "2026-11-16T08:00:00Z" };
+ const p = buildCookieStatus(
+ input({
+ state,
+ forums: [
+ { host: "kiwifarms.st", dir: "/home/someone/t/.forum-session/kiwifarms.st", hasProfile: true, connectedAt: "2026-11-15T10:00:00Z", cleared: true },
+ { host: "forum.example.org", dir: "/d", hasProfile: true },
+ ],
+ }),
+ );
+ assert.deepEqual(p.rows.slice(5).map((r) => r.service), ["forum.example.org", "kiwifarms.st"]);
+ const kf = row(p, "kiwifarms.st");
+ assert.equal(kf.label, "Kiwi Farms (kiwifarms.st)");
+ assert.equal(kf.age, "connected 24 h ago");
+ assert.equal(kf.ageNote, "check passed");
+ assert.equal(kf.headed, true);
+ assert.equal(kf.button?.disabled, undefined);
+ assert.match(row(p, "forum.example.org").button?.disabled ?? "", /No thread on this forum/);
+ assert.deepEqual(forumThreadFor(state, "kiwifarms.st"), { url: "https://kiwifarms.st/threads/t.1/" });
+ assert.equal(forumThreadFor(state, "forum.example.org"), null);
+});
diff --git a/common/lib/cookieStatus.ts b/common/lib/cookieStatus.ts
@@ -0,0 +1,310 @@
+// THE COOKIES SCREEN'S ROWS (editor /cookies, plans/cookie-screen.md): one row
+// per service the editor reads cookies for — X, Rumble, YouTube, Odysee,
+// archive.today and each forum host — saying where its cookies come from, how
+// old they are, whether its cookie alert is up, how the last press ended, and
+// the ONE thing to press.
+//
+// Client-safe and pure: the reads are editor/app/lib/cookieStatus.ts, which
+// hands this builder what it read and the privacy displayers (every path and
+// spec drawn goes through them — settings.privacy decides what a home path or
+// a user name looks like).
+//
+// THE ONE BUTTON PER ROW, and what it runs (each the existing action):
+// x, connected profile Refresh cookies refreshXCookies (headless; loads x.com/home)
+// x, no profile yet Connect X account (a HEADED window on the editor's machine)
+// x, browser login Check again recheck "x" — no request; the line says open x.com
+// rumble / youtube / odysee Check again recheck — one request; the line says open the site
+// archive.today Connect archive session (headed)
+// a forum host Connect forum session (headed), at a thread the app has met
+
+import type { ServiceCookieAction, ServiceCookieAlertsPayload, ServiceCookieState, XJarStatusView } from "./serviceCookies";
+import { forumServiceKey, serviceFamily, serviceLabel, type ServiceFamily } from "./serviceCookies";
+import type { BrowserCookieAge } from "./browserCookieAge";
+
+export type CookieRowState = "stale" | "fine" | "unknown";
+
+export type CookieRowButton = {
+ action: "refresh" | "connect" | "recheck";
+ label: string;
+ // Why it cannot be pressed, when it cannot.
+ disabled?: string;
+};
+
+export type CookieRow = {
+ service: string;
+ label: string;
+ family: ServiceFamily;
+ // Where the cookies come from, already through the privacy displayers.
+ source: string;
+ // How old they are: `ageAt` is the time, `ageVerb` what happened then
+ // ("jar written"); `age` the sentence at readAt ("jar written 12 min ago").
+ ageVerb: string | null;
+ ageAt: string | null;
+ ageMinutes: number | null;
+ age: string | null;
+ // The age limit or expiry, as a clause ("limit 60 min", "expires 10:40 UTC").
+ ageNote?: string;
+ // Why the age is not known, when it is not.
+ ageUnknown?: string;
+ state: CookieRowState;
+ // The alert's sentence (or the pending first signal's), when there is one.
+ alert?: string;
+ // What to do by hand, in one line, where no button does it.
+ todo?: string;
+ // The button opens a window on the machine running the editor.
+ headed?: boolean;
+ button: CookieRowButton | null;
+ last?: ServiceCookieAction;
+ running?: CookieRunning;
+};
+
+export type CookieRunning = { action: CookieRowButton["action"]; since: string; jobId?: string };
+
+export type CookieStatusPayload = { readAt: string; rows: CookieRow[] };
+
+export type Displayers = { path: (p: string) => string; text: (s: string) => string };
+
+export type YtdlpCookieInput = {
+ // The cookiesFromBrowser yt-dlp uses for this service, and where it is set.
+ spec?: string;
+ specFrom: "channel" | "settings";
+ channel?: string;
+ age: BrowserCookieAge;
+};
+
+export type CookieStatusInput = {
+ now: number;
+ alerts: ServiceCookieAlertsPayload;
+ state: ServiceCookieState;
+ x: {
+ source: "profile" | "browser";
+ browserSpec?: string;
+ profileDir: string;
+ hasProfile: 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 }[];
+ running: Record<string, CookieRunning>;
+ display: Displayers;
+};
+
+export const HEADED_NOTE = "Opens a browser window on the editor's machine, not on this device.";
+
+// "12 min", "3 h", "16 days".
+export function durationText(min: number): string {
+ if (min < 1) return "less than a minute";
+ if (min < 120) return `${min} min`;
+ const h = Math.floor(min / 60);
+ return h < 48 ? `${h} h` : `${Math.floor(h / 24)} days`;
+}
+
+export function minutesSince(at: string | null | undefined, now: number): number | null {
+ if (!at) return null;
+ const t = Date.parse(at);
+ return Number.isFinite(t) ? Math.max(0, Math.floor((now - t) / 60_000)) : null;
+}
+
+// "jar written 12 min ago" — the client re-derives it every tick.
+export function ageSentence(verb: string | null, at: string | null, now: number): string | null {
+ const m = minutesSince(at, now);
+ if (!verb || m === null) return null;
+ return m < 1 ? `${verb} just now` : `${verb} ${durationText(m)} ago`;
+}
+
+function hhmm(at: string): string {
+ return `${at.slice(11, 16)} UTC`;
+}
+
+function browserWord(spec: string | undefined): string {
+ const s = spec?.trim() ?? "";
+ if (!s) return "the browser";
+ if (s.startsWith("file:")) return "a browser";
+ return s.split(/[:+]/)[0] || s;
+}
+
+const SITE: Record<"rumble" | "youtube" | "odysee", string> = {
+ rumble: "rumble.com",
+ youtube: "youtube.com",
+ odysee: "odysee.com",
+};
+
+function alertFields(
+ service: string,
+ input: CookieStatusInput,
+): { state: CookieRowState | null; alert?: string } {
+ const a = input.alerts.alerts.find((x) => x.service === service);
+ // A fix sentence may name a cookies file: drawn through the displayers too.
+ if (a?.state === "stale") return { state: "stale", alert: input.display.text(a.headline) };
+ if (a?.state === "ok-again") return { state: "fine", alert: input.display.text(a.headline) };
+ const p = input.alerts.pending.find((x) => x.service === service);
+ if (p) {
+ return {
+ state: null,
+ alert: `One ${p.kind === "embed-403" ? "embed 403" : p.kind} at ${hhmm(p.lastSeen)}; a second video raises the alert.`,
+ };
+ }
+ return { state: null };
+}
+
+export function buildCookieStatus(input: CookieStatusInput): CookieStatusPayload {
+ const { now, display } = input;
+ const rows: CookieRow[] = [];
+ const last = (service: string) => {
+ const a = input.state.actions?.[service];
+ return a ? { last: { ...a, message: display.text(a.message) } } : {};
+ };
+ const common = (service: string) => ({
+ service,
+ label: serviceLabel(service),
+ family: serviceFamily(service),
+ ...last(service),
+ ...(input.running[service] ? { running: input.running[service] } : {}),
+ });
+ const aged = (verb: string | null, at: string | null) => ({
+ ageVerb: at ? verb : null,
+ ageAt: at,
+ ageMinutes: minutesSince(at, now),
+ age: ageSentence(verb, at, now),
+ });
+ const settle = (known: boolean, a: ReturnType<typeof alertFields>): CookieRowState =>
+ a.state ?? (known ? "fine" : "unknown");
+
+ // ── X ──
+ {
+ const x = input.x;
+ const a = alertFields("x", input);
+ const jar = x.jar;
+ if (x.source === "profile") {
+ const at = jar?.at ?? null;
+ rows.push({
+ ...common("x"),
+ source: `Connected profile (${display.path(x.profileDir)})`,
+ ...aged("jar written", at),
+ ...(jar ? { ageNote: jar.maxAgeMinutes > 0 ? `limit ${jar.maxAgeMinutes} min` : "no age limit" } : {}),
+ ...(!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
+ ? { button: { action: "refresh", label: "Refresh cookies" } }
+ : { headed: true, todo: HEADED_NOTE, button: { action: "connect", label: "Connect X account" } }),
+ });
+ } else {
+ const at = jar?.at ?? null;
+ const b = browserWord(x.browserSpec);
+ rows.push({
+ ...common("x"),
+ source: `Browser login (${display.text(x.browserSpec ?? "no cookiesFromBrowser set")})`,
+ ...aged("login last used", at),
+ ...(jar && jar.maxAgeMinutes > 0 ? { ageNote: `limit ${jar.maxAgeMinutes} min` } : {}),
+ ...(!at ? { ageUnknown: jar?.summary ? display.text(jar.summary) : "Not read." } : {}),
+ state: settle(!!at, a),
+ ...(a.alert ? { alert: a.alert } : {}),
+ todo: `Open x.com in ${b}, then Check again (no request is sent to X).`,
+ button: { action: "recheck", label: "Check again" },
+ });
+ }
+ }
+
+ // ── the yt-dlp services ──
+ for (const svc of ["rumble", "youtube", "odysee"] as const) {
+ const y = input.ytdlp[svc];
+ const a = alertFields(svc, input);
+ const verb =
+ y.age.basis === "file" ? "cookies file written" : y.age.basis === "clearance" ? "clearance issued" : "sign-in last used";
+ const at = y.age.at;
+ const exp = y.age.expiresAt;
+ const expMin = exp ? Math.floor((Date.parse(exp) - now) / 60_000) : null;
+ const entry = input.state.services[svc];
+ const canAsk = !!input.state.lastGood[svc] || !!entry?.evidence.url;
+ const lastGood = input.state.lastGood[svc];
+ const ageUnknown =
+ y.age.unknown
+ ? display.text(y.age.unknown)
+ : y.age.found === false
+ ? `No ${svc === "youtube" ? "sign-in" : "clearance"} cookie for ${SITE[svc]} in ${browserWord(y.spec)}.`
+ : undefined;
+ rows.push({
+ ...common(svc),
+ source: y.spec
+ ? `${display.text(y.spec)} (${y.specFrom === "channel" && y.channel ? `channel ${y.channel}` : "cookiesFromBrowser"})`
+ : "No browser cookies (cookiesFromBrowser is not set)",
+ ...aged(verb, at),
+ ...(expMin !== null ? { ageNote: expMin > 0 ? `expires in ${durationText(expMin)}` : `expired ${durationText(-expMin)} ago` } : {}),
+ ...(ageUnknown && !at ? { ageUnknown } : {}),
+ state: settle(!!at || !!lastGood, a),
+ ...(a.alert
+ ? { alert: a.alert }
+ : lastGood
+ ? { alert: `Last clean request ${durationText(minutesSince(lastGood.at, now) ?? 0)} ago.` }
+ : {}),
+ todo: `Open ${SITE[svc]} in ${browserWord(y.spec)}${svc === "youtube" ? " signed in" : ""}, then Check again.`,
+ button: {
+ action: "recheck",
+ label: "Check again",
+ ...(canAsk ? {} : { disabled: `No ${serviceLabel(svc)} request is recorded yet to ask again.` }),
+ },
+ });
+ }
+
+ // ── archive.today ──
+ {
+ const ar = input.archive;
+ const a = alertFields("archive.today", input);
+ const at = ar.connectedAt ?? null;
+ rows.push({
+ ...common("archive.today"),
+ source: `Archive profile (${display.path(ar.dir)})`,
+ ...aged("connected", at),
+ ...(at ? { ageNote: ar.cleared ? "check passed" : "check not passed" } : {}),
+ ...(!at ? { ageUnknown: ar.hasProfile ? "Profile present, never connected here." : "Never connected." } : {}),
+ state: settle(!!at, a),
+ ...(a.alert ? { alert: a.alert } : {}),
+ headed: true,
+ todo: HEADED_NOTE,
+ button: { action: "connect", label: "Connect archive session" },
+ });
+ }
+
+ // ── each forum host ──
+ const hosts = new Map<string, CookieStatusInput["forums"][number] | null>();
+ for (const f of input.forums) hosts.set(forumServiceKey(f.host), f);
+ 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);
+ }
+ 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;
+ rows.push({
+ ...common(host),
+ source: f ? `Forum profile (${display.path(f.dir)})` : "No forum profile yet",
+ ...aged("connected", at),
+ ...(at ? { ageNote: f?.cleared ? "check passed" : "check not passed" } : {}),
+ ...(!at ? { ageUnknown: f?.hasProfile ? "Profile present, never connected here." : "Never connected." } : {}),
+ state: settle(!!at, a),
+ ...(a.alert ? { alert: a.alert } : {}),
+ headed: true,
+ todo: HEADED_NOTE,
+ button: {
+ action: "connect",
+ label: "Connect forum session",
+ ...(thread ? {} : { disabled: "No thread on this forum is recorded yet: connect from the thread's channel page." }),
+ },
+ });
+ }
+
+ return { readAt: new Date(now).toISOString(), rows };
+}
+
+// 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 {
+ 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;
+}
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -261,6 +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_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/lib/serviceCookies-server.test.ts b/common/lib/serviceCookies-server.test.ts
@@ -18,6 +18,7 @@ import {
markServiceCookieRerun,
noteArchiveTodayOutcome,
noteForumServiceOutcome,
+ noteServiceCookieAction,
noteServiceCookieClean,
noteServiceCookieSignal,
observeYtdlpServiceOutcome,
@@ -227,3 +228,31 @@ test("a Rumble listing 403 on a channel with no cookie config names the missing
await rm(paths.transcriptsDir, { recursive: true, force: true });
}
});
+
+test("the last press per service is recorded, replaced by the next, and coerced back", async () => {
+ const paths = await tmpPaths();
+ try {
+ await noteServiceCookieAction(paths, "x", { action: "refresh", ok: true, message: "Cookies refreshed." }, Date.parse("2026-11-16T09:00:00Z"));
+ await noteServiceCookieAction(
+ paths,
+ "rumble",
+ { action: "recheck", ok: false, result: "stale", message: "Rumble still refused.", jobId: "job-1" },
+ Date.parse("2026-11-16T09:01:00Z"),
+ );
+ await noteServiceCookieAction(paths, "x", { action: "refresh", ok: false, message: "No X session profile yet." }, Date.parse("2026-11-16T09:02:00Z"));
+ const state = await readServiceCookieState(paths);
+ assert.deepEqual(state.actions, {
+ x: { at: "2026-11-16T09:02:00.000Z", action: "refresh", ok: false, message: "No X session profile yet." },
+ rumble: { at: "2026-11-16T09:01:00.000Z", action: "recheck", ok: false, result: "stale", message: "Rumble still refused.", jobId: "job-1" },
+ });
+ // A torn record is dropped, never thrown on.
+ const raw = JSON.parse(await readFile(serviceCookiesFile(paths), "utf8"));
+ raw.actions.youtube = { at: "not a time", action: "refresh" };
+ raw.actions["not a service!"] = { at: "2026-11-16T09:00:00Z", action: "refresh" };
+ raw.actions.odysee = { at: "2026-11-16T09:00:00Z", action: "explode" };
+ await writeFile(serviceCookiesFile(paths), JSON.stringify(raw));
+ assert.deepEqual(Object.keys((await readServiceCookieState(paths)).actions ?? {}).sort(), ["rumble", "x"]);
+ } finally {
+ await rm(paths.transcriptsDir, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/serviceCookies-server.ts b/common/lib/serviceCookies-server.ts
@@ -33,6 +33,7 @@ import {
serviceCookieSignalFromStderr,
serviceLabel,
serviceStoppedLine,
+ type ServiceCookieAction,
type ServiceCookieEntry,
type ServiceCookieSignal,
type ServiceCookieState,
@@ -331,6 +332,25 @@ export async function markServiceCookieRerun(
);
}
+// The last press on a service's own button and how it ended (the /cookies
+// screen's "last result"). Never throws: a press is not failed by its
+// bookkeeping.
+export async function noteServiceCookieAction(
+ paths: Pick<Paths, "transcriptsDir">,
+ service: string,
+ action: Omit<ServiceCookieAction, "at">,
+ now: number = Date.now(),
+): Promise<void> {
+ await mutate(
+ paths,
+ (state, at) => {
+ (state.actions ??= {})[service] = { at: new Date(at).toISOString(), ...action, message: action.message.slice(0, 600) };
+ return { changed: true, out: undefined };
+ },
+ now,
+ ).catch(() => undefined);
+}
+
// ── X (plans/pacing-guard.md) ─────────────────────────────────────────────
// One gallery-dl run against X: a challenge or login-wall line raises the X
diff --git a/common/lib/serviceCookies.ts b/common/lib/serviceCookies.ts
@@ -105,7 +105,7 @@ export function serviceFixText(service: string, browser?: string, kind?: Service
const b = browserName(browser);
if (service === X_SERVICE && kind === "jar-age") {
return (
- "press Refresh cookies (or Connect X account) on /settings for a fresh X cookie jar — with the browser " +
+ "press Refresh cookies (or Connect X account) on /cookies for a fresh X cookie jar — with the browser " +
`login, open x.com in ${b} — then Recheck; nothing is asked of X until then`
);
}
@@ -117,10 +117,10 @@ export function serviceFixText(service: string, browser?: string, kind?: Service
case "odysee":
return `open odysee.com in ${b} and let its check pass`;
case ARCHIVE_TODAY_SERVICE:
- return "Connect archive session (Settings → Archive sources) and pass the check once in the window";
+ return "Connect archive session on /cookies and pass the check once in the window (it opens on the editor's machine)";
case X_SERVICE:
return (
- "pass X's check by hand — Connect X account on /settings and clear it in the window (with the " +
+ "pass X's check by hand — Connect X account on /cookies and clear it in the window (with the " +
"browser login: open x.com in that browser) — then press Refresh cookies there; no X job starts until then"
);
default:
@@ -258,10 +258,29 @@ export type ServiceCookieLastGood = {
prev?: { url: string; channel?: string; at: string };
};
+// The last press on a service's own button (the /cookies screen's Refresh,
+// Connect or Check again; the dashboard's Recheck; settings' Refresh cookies):
+// what was pressed, when, and how it ended. Written by the one guard every
+// such press goes through (editor/app/lib/cookieRefreshGuard.ts).
+export type ServiceCookieActionKind = "refresh" | "connect" | "recheck";
+export const SERVICE_COOKIE_ACTION_KINDS: readonly ServiceCookieActionKind[] = ["refresh", "connect", "recheck"];
+
+export type ServiceCookieAction = {
+ at: string;
+ action: ServiceCookieActionKind;
+ ok: boolean;
+ // A recheck's answer.
+ result?: "clean" | "stale" | "failed";
+ message: string;
+ jobId?: string;
+};
+
export type ServiceCookieState = {
version: 1;
services: Record<string, ServiceCookieEntry>;
lastGood: Record<string, ServiceCookieLastGood>;
+ // Absent until a press is recorded (an older file has none).
+ actions?: Record<string, ServiceCookieAction>;
};
export const PENDING_SIGNAL_TTL_MS = 60 * 60_000;
@@ -364,6 +383,28 @@ export function coerceServiceCookieState(raw: unknown): ServiceCookieState {
: {}),
};
}
+ const actions = r.actions && typeof r.actions === "object" ? (r.actions as Record<string, unknown>) : null;
+ if (actions) {
+ for (const [key, v] of Object.entries(actions)) {
+ if (!isServiceKey(key) || !v || typeof v !== "object") continue;
+ const a = v as Record<string, unknown>;
+ const at = iso(a.at);
+ const action = SERVICE_COOKIE_ACTION_KINDS.includes(a.action as ServiceCookieActionKind)
+ ? (a.action as ServiceCookieActionKind)
+ : null;
+ if (!at || !action) continue;
+ const result = a.result === "clean" || a.result === "stale" || a.result === "failed" ? a.result : undefined;
+ const jobId = str(a.jobId, 200);
+ (out.actions ??= {})[key] = {
+ at,
+ action,
+ ok: a.ok === true,
+ message: str(a.message, 600) ?? "",
+ ...(result ? { result } : {}),
+ ...(jobId ? { jobId } : {}),
+ };
+ }
+ }
return out;
}
@@ -665,7 +706,7 @@ export function buildServiceCookieAlerts(
const action =
jar?.source === "browser"
? `Open x.com in ${browserName(opts.browser).replace(/^[a-z]/, (c) => c.toUpperCase())} — then Recheck.`
- : "Refresh cookies (or Connect X account) on /settings — then Recheck.";
+ : "Refresh cookies (or Connect X account) on /cookies — then Recheck.";
const queued = /^(\d+ X jobs? (?:is|are) queued)/.exec(e.evidence.line)?.[1];
const refused = job
? `Refused ${job.kind ? `${job.kind} ` : ""}${job.id}${e.evidence.channel ? ` (${e.evidence.channel})` : ""}.`
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -197,7 +197,7 @@ export const X_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XSocialSettings> = {
"(Fetch posts, the older walk, an X search, Capture posts, Import one post, Check deleted " +
"posts — and the scheduler's fetches) is refused when it STARTS unless the profile's exported " +
"cookie jar was written within this many minutes and carries a login (an auth_token). The " +
- "refusal says what to do: press Refresh cookies (or Connect X account) on /settings, then " +
+ "refusal says what to do: press Refresh cookies (or Connect X account) on /cookies, then " +
"fetch again. A refresh is a human click — it loads x.com/home, itself a request to X — so " +
"the editor never refreshes the jar to satisfy this. With the `\"browser\"` source the age " +
"cannot be read: the job logs that and proceeds. ABSENT: 60. 0 turns the rule off; at most " +
diff --git a/common/social/fakeXProfileBrowser.test.ts b/common/social/fakeXProfileBrowser.test.ts
@@ -0,0 +1,68 @@
+// The e2e suite's fake "Refresh cookies" browser (fakeXProfileBrowser.ts) is
+// inert unless the process is the test server AND the file is inside its
+// transcriptsDir AND exists; when live, refreshXCookies runs on it end to end
+// with no browser and no request.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/fakeXProfileBrowser.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { fakeXProfileChromium, fakeXProfileCookiesFile } from "./fakeXProfileBrowser";
+import { 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-"));
+ try {
+ const t = path.join(root, "transcripts");
+ await mkdir(t);
+ const inside = path.join(t, ".fake-x-profile-cookies.json");
+ const outside = path.join(root, "elsewhere.json");
+ await writeFile(outside, "{}");
+ const env = { E2E_TEST_ROUTES: "1", E2E_FAKE_X_PROFILE_COOKIES_FILE: inside };
+ // Not written yet.
+ assert.equal(fakeXProfileCookiesFile(t, env), null);
+ await writeFile(inside, "{}");
+ assert.equal(fakeXProfileCookiesFile(t, env), inside);
+ // Not the test server: inert, even with the file there.
+ assert.equal(fakeXProfileCookiesFile(t, { E2E_FAKE_X_PROFILE_COOKIES_FILE: inside }), null);
+ assert.equal(fakeXProfileCookiesFile(t, { ...env, E2E_TEST_ROUTES: "0" }), null);
+ assert.equal(fakeXProfileChromium(t, { E2E_FAKE_X_PROFILE_COOKIES_FILE: inside }), null);
+ // A file outside the test data: inert.
+ assert.equal(fakeXProfileCookiesFile(t, { ...env, E2E_FAKE_X_PROFILE_COOKIES_FILE: outside }), null);
+ assert.equal(fakeXProfileCookiesFile(t, { ...env, E2E_FAKE_X_PROFILE_COOKIES_FILE: path.join(t, "..", "elsewhere.json") }), null);
+ assert.equal(fakeXProfileCookiesFile(t, { E2E_TEST_ROUTES: "1" }), null);
+ // A symlink inside the test data pointing out of it: inert.
+ const link = path.join(t, "link.json");
+ await symlink(outside, link);
+ assert.equal(fakeXProfileCookiesFile(t, { ...env, E2E_FAKE_X_PROFILE_COOKIES_FILE: link }), null);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("refreshXCookies on the fake writes the jar from the fixture's cookies", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "fake-x-"));
+ try {
+ const paths = { transcriptsDir: root } as Parameters<typeof refreshXCookies>[0];
+ await mkdir(path.join(root, ".x-session", "profile"), { recursive: true });
+ const file = path.join(root, ".fake-x-profile-cookies.json");
+ await writeFile(
+ file,
+ JSON.stringify({ 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);
+ const status = await refreshXCookies(paths, { chromium });
+ assert.equal(status.looksAuthenticated, true);
+ assert.equal((await readXSessionStatus(paths)).hasCookies, true);
+ assert.match(await readFile(path.join(root, ".x-session", "cookies.txt"), "utf8"), /\.x\.com\tTRUE\t\/\tTRUE\t0\tauth_token/);
+ // `fail` makes the launch throw, as a profile the browser cannot open.
+ await writeFile(file, JSON.stringify({ fail: "profile locked" }));
+ await assert.rejects(refreshXCookies(paths, { chromium }), /profile locked/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/common/social/fakeXProfileBrowser.ts b/common/social/fakeXProfileBrowser.ts
@@ -0,0 +1,99 @@
+// A FAKE BROWSER FOR "Refresh cookies", 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.
+//
+// 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? }] }
+
+import { readFileSync, realpathSync } from "node:fs";
+import path from "node:path";
+import type { BrowserContextLike, ChromiumLike, PageLike } from "./playwrightRuntime";
+
+type FixtureFile = {
+ delayMs?: number;
+ fail?: string;
+ cookies?: Array<{ name: string; value: string; domain: string; path?: string; expires?: number }>;
+};
+
+export function fakeXProfileCookiesFile(
+ transcriptsDir: string,
+ env: Readonly<Record<string, string | undefined>> = process.env,
+): string | null {
+ if (env.E2E_TEST_ROUTES !== "1") return null;
+ const file = env.E2E_FAKE_X_PROFILE_COOKIES_FILE?.trim();
+ if (!file) return null;
+ // Real paths, so a symlink inside the test data cannot point the fake out
+ // of it; a file that does not exist answers null here too.
+ let real: string;
+ let root: string;
+ try {
+ real = realpathSync(file);
+ root = realpathSync(transcriptsDir);
+ } catch {
+ return null;
+ }
+ const rel = path.relative(root, real);
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null;
+ return real;
+}
+
+function readFixture(file: string): FixtureFile {
+ return JSON.parse(readFileSync(file, "utf8")) as FixtureFile;
+}
+
+// The fake, or null when the gate above says no.
+export function fakeXProfileChromium(
+ transcriptsDir: string,
+ env: Readonly<Record<string, string | undefined>> = process.env,
+): ChromiumLike | null {
+ const file = fakeXProfileCookiesFile(transcriptsDir, env);
+ if (!file) return null;
+ const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
+ const page = {
+ goto: async () => {
+ const f = readFixture(file);
+ if (f.delayMs && f.delayMs > 0) await wait(Math.min(f.delayMs, 30_000));
+ return null;
+ },
+ waitForSelector: async () => null,
+ waitForTimeout: wait,
+ evaluate: async () => null,
+ on: () => {},
+ } as unknown as PageLike;
+ const context: BrowserContextLike = {
+ newPage: async () => page,
+ pages: () => [page],
+ cookies: async () =>
+ (readFixture(file).cookies ?? []).map((c) => ({
+ name: c.name,
+ value: c.value,
+ domain: c.domain,
+ path: c.path ?? "/",
+ expires: c.expires ?? -1,
+ httpOnly: true,
+ secure: true,
+ })),
+ addCookies: async () => {},
+ close: async () => {},
+ on: () => {},
+ };
+ return {
+ launch: async () => {
+ throw new Error("the fake X profile browser launches no browser");
+ },
+ launchPersistentContext: async () => {
+ const f = readFixture(file);
+ if (f.fail) throw new Error(f.fail);
+ return context;
+ },
+ };
+}
diff --git a/common/social/xCookieSource.ts b/common/social/xCookieSource.ts
@@ -59,7 +59,7 @@ export type XSocialSettings = {
};
// Absent `social.x.maxCookieAgeMinutes`: an hour. A refresh is a human click
-// on /settings (refreshXCookies loads x.com/home — itself a request to X), so
+// on /cookies (refreshXCookies loads x.com/home — itself a request to X), so
// the editor never refreshes the jar on its own to satisfy this.
export const X_DEFAULT_MAX_COOKIE_AGE_MINUTES = 60;
// A week: past that, "fresh" means nothing.
diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts
@@ -93,7 +93,7 @@ export function xBlockedError(line: string): string {
return (
`X answered with a challenge or a login wall (${line.trim().slice(0, 200)}): stopped here, posts read so far ` +
"kept. The X cookie alert is up — no X job starts until it is cleared (pass X's check by hand, Refresh " +
- "cookies on /settings, then Recheck on the dashboard)."
+ "cookies on /cookies, then Recheck on the dashboard)."
);
}
@@ -399,7 +399,7 @@ export async function captureXPostsByIds(
const status = await readXSessionStatus(paths);
if (!status.hasProfile) {
const why =
- "No X session profile to shoot posts or open articles with: connect an X account on /settings, then run it again.";
+ "No X session profile to shoot posts or open articles with: connect an X account on /cookies, then run it again.";
input.onLog?.(`[auth] ${why}`);
return { outcomes: [], needsCookies: true, stoppedEarly: why };
}
@@ -928,7 +928,7 @@ function readLines(
}
const SEARCH_NEEDS_LOGIN =
- "X search needs a logged-in session: connect an X account on /settings, or " +
+ "X search needs a logged-in session: connect an X account on /cookies, or " +
"set cookiesFromBrowser for this channel (or globally), then run it again.";
// The older-posts backfill: search windows walked backwards from `position`
diff --git a/common/social/xJarAge.ts b/common/social/xJarAge.ts
@@ -131,11 +131,11 @@ export function xJarStatusFrom(input: {
if (input.unreadable) summary = input.unreadable;
else if (input.source === "profile") {
summary = !input.at
- ? "No X cookie jar has been exported: press Connect X account on /settings."
+ ? "No X cookie jar has been exported: press Connect X account on /cookies."
: input.loggedIn !== true
- ? "The X cookie jar holds no login (no auth_token): press Connect X account on /settings."
+ ? "The X cookie jar holds no login (no auth_token): press Connect X account on /cookies."
: `The X cookie jar was written ${ageText(ageMinutes!)} ago${limit}` +
- (fresh ? "." : ": press Refresh cookies (or Connect X account) on /settings.");
+ (fresh ? "." : ": press Refresh cookies (or Connect X account) on /cookies.");
} else {
summary = input.loggedIn !== true
? "No X login in the browser cookiesFromBrowser names (no x.com auth_token): log in to x.com there."
diff --git a/common/views/names.ts b/common/views/names.ts
@@ -34,6 +34,10 @@ export const VIEW_NAMES = [
// every storage location whose drive is slow, not answering or not mounted.
// The health record is memory; the mount half is /storage's 10 s probe memo.
"driveHealth",
+ // The /cookies screen's rows (editor/app/lib/cookieStatus.ts): each
+ // service's cookie source, age, alert and last press. Disk reads only, the
+ // browser store's name-only read cached 5 min.
+ "cookieStatus",
] as const;
export type ViewName = (typeof VIEW_NAMES)[number];
@@ -63,4 +67,5 @@ export const VIEW_CONTRACT: Record<ViewName, "observe" | "construct"> = {
cookieAlerts: "construct",
xRun: "construct",
driveHealth: "construct",
+ cookieStatus: "construct",
};
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,25 @@
# Changelog
## [Unreleased]
+- **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
+ service's cookie alert is up, and how the last press ended. Each row has one button.
+ - X with a connected profile has **Refresh cookies**, the same action as on /settings. When X's alert is up, X is
+ rechecked from disk right after, so the alert clears at once.
+ - Rumble, YouTube and Odysee say which site to open in the browser, then offer **Check again** (the dashboard's
+ Recheck).
+ - archive.today and the forums have their **Connect**. The row says the window opens on the editor's machine, not
+ on the phone.
+ - A press shows its progress and its answer in the row, without a reload. A second press while one runs is refused
+ with a sentence, from any tab. That includes /settings, the dashboard, a forum channel's Connect, and the timer's
+ recheck.
+ - The page reads only what the rows show, so it loads fast on a phone. /settings ships its whole settings object
+ to the browser. Rumble's, Odysee's and YouTube's ages come from the browser's cookie store, read by name and time
+ only (never a value), cached for 5 minutes.
+ - `pnpm ops get cookies [fresh]` gives the same rows as JSON.
+ - The dashboard's cookie banners, /settings' X and archive sections and /review's X run console link to it. The
+ alert sentences and job log lines now say "on /cookies" where they said "on /settings".
- **An Orpheus line can be read again differently: the tts op takes a `tuning` and a `reading`.** `pnpm ops tts`
(`POST /api/ops/tts`) takes `tuning` (any of temperature 0.1–1.5, top_p 0.05–1, top_k 0–200, min_p 0–0.5,
repeat_penalty 1–2, takes 1–6) and `reading` (0–99,999; reading r reads with seed base 1234 + 9973 × r). A value out
diff --git a/editor/app/api/ops/_read.test.ts b/editor/app/api/ops/_read.test.ts
@@ -47,7 +47,7 @@ const route = async (name: string) => (await import(`./${name}/route`)).GET as G
test.after(() => corpus.cleanup());
test("every read route is behind the token", async () => {
- for (const name of ["settings", "storage", "sites", "workers", "auto-queue", "scheduler", "saved-alternates", "x-session"]) {
+ for (const name of ["settings", "storage", "sites", "workers", "auto-queue", "scheduler", "saved-alternates", "x-session", "cookies"]) {
const res = await callGet(await route(name), undefined, {}, {});
assert.equal(res.status, 401, name);
}
@@ -166,6 +166,24 @@ test("get x-session answers the X login and the guard's verdict: no jar here, so
assert.equal(stray.status, 400);
});
+test("get cookies answers the /cookies rows: the fixed services, nothing read from a browser here", async () => {
+ const get = await route("cookies");
+ const res = await callGet(get);
+ assert.equal(res.status, 200, JSON.stringify(res.body));
+ const rows = res.body.rows as { service: string; state: string; button: { action: string } | null; ageUnknown?: string }[];
+ assert.deepEqual(rows.map((r) => r.service), ["x", "rumble", "youtube", "odysee", "archive.today"]);
+ // No profile connected: X's one button is Connect; no cookiesFromBrowser: Rumble's age is unknown, said why.
+ assert.equal(rows[0]!.button?.action, "connect");
+ assert.match(rows[1]!.ageUnknown ?? "", /No cookiesFromBrowser is set/);
+ assert.ok(rows.every((r) => ["stale", "fine", "unknown"].includes(r.state)));
+ const fresh = await callGet(get, "http://localhost/api/ops/cookies?fresh=1");
+ assert.equal(fresh.status, 200);
+ const bad = await callGet(get, "http://localhost/api/ops/cookies?fresh=yes");
+ assert.equal(bad.status, 400);
+ const stray = await callGet(get, "http://localhost/api/ops/cookies?service=x");
+ assert.equal(stray.status, 400);
+});
+
test("/api/auto-queue/control is behind the ops token now", async () => {
const { POST } = await import("../auto-queue/control/route");
const anon = await callPost(POST, { kind: "download", action: "stop" }, {});
diff --git a/editor/app/api/ops/_writes.test.ts b/editor/app/api/ops/_writes.test.ts
@@ -138,6 +138,27 @@ test("the cookie alert's three writes refuse a name that is not a service; rerun
assert.match(String(rerun.body.error), /^Rumble has no cookie alert\./);
});
+test("recheck-service while a press for the service runs: 409, busy, nothing queued", async () => {
+ const { withCookieAction } = await import("../../lib/cookieRefreshGuard");
+ let release!: () => void;
+ const held = withCookieAction(
+ "odysee",
+ "recheck",
+ () => new Promise<{ ok: true }>((r) => (release = () => r({ ok: true }))),
+ () => ({ ok: true, message: "" }),
+ { jobs: () => [] },
+ );
+ try {
+ const res = await callPost(await route("recheck-service"), { service: "odysee" });
+ assert.equal(res.status, 409, JSON.stringify(res.body));
+ assert.equal(res.body.busy, true);
+ assert.match(String(res.body.error), /^Odysee's recheck is already running \(since \d\d:\d\d:\d\d UTC\)/);
+ } finally {
+ release();
+ await held;
+ }
+});
+
test("workers: the op and the ids are checked at the door", async () => {
const workers = await route("workers");
const op = await callPost(workers, { op: "restart", ids: ["a"] });
diff --git a/editor/app/api/ops/cookies/route.ts b/editor/app/api/ops/cookies/route.ts
@@ -0,0 +1,28 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { loadCookieStatus } from "../../../lib/cookieStatus";
+import { readRoute } from "../_read";
+import { opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// GET /api/ops/cookies[?fresh=1]
+// -> { ok, readAt, rows: [{ service, label, family, source, ageVerb, ageAt,
+// ageMinutes, age, ageNote?, ageUnknown?, state, alert?, todo?,
+// headed?, button, last?, running? }] }
+//
+// The /cookies screen's rows (editor/app/lib/cookieStatus.ts): one per service
+// the editor reads cookies for — X, Rumble, YouTube, Odysee, archive.today and
+// each forum host — with where its cookies come from (drawn through
+// settings.privacy), how old they are, its cookie alert (stale / fine /
+// unknown), the last press on its button and how it ended, and what is
+// running. Read-only: nothing is asked of any service. `fresh=1` re-reads the
+// browser's cookie store (names and times only) instead of the 5-minute cache.
+// The presses themselves: recheck-service (Check again); X's Refresh cookies
+// and the headed Connects stay human clicks on /cookies.
+export async function GET(request: Request) {
+ return readRoute(request, ["fresh"], async (q) => {
+ const fresh = q.get("fresh");
+ if (fresh !== null && fresh !== "1" && fresh !== "0") return opsFail(`fresh must be 1 or 0, not "${fresh}"`);
+ return { ...(await loadCookieStatus(getPaths(), { fresh: fresh === "1" })) };
+ });
+}
diff --git a/editor/app/api/ops/recheck-service/route.ts b/editor/app/api/ops/recheck-service/route.ts
@@ -12,10 +12,13 @@ export const dynamic = "force-dynamic";
// at all — the login on disk, renewed since the alert), as a one-step
// job (kind `recheck-service-cookies`) the answer waits for:
// { ok, jobId, result: "clean" | "stale" | "failed", message }. "clean"
-// clears the alert.
+// clears the alert. A second ask while one runs for the service (a press, the
+// dashboard's, the timer's) is refused: 409 { ok: false, busy: true, error }.
export async function POST(request: Request) {
return ops(request, ["service"], async (body) => {
const res = await recheckServiceCookiesAction(reqString(body, "service"));
+ // A recheck (or another press) for the service already running: 409, busy.
+ if (!res.ok && res.busy) return opsFail(res.error, 409, { busy: true });
if (!res.ok) return opsFail(res.error, 400, res.jobId ? { jobId: res.jobId } : {});
return NextResponse.json({ ok: true, jobId: res.jobId, result: res.result, message: res.message });
});
diff --git a/editor/app/api/ops/sync/route.test.ts b/editor/app/api/ops/sync/route.test.ts
@@ -59,7 +59,7 @@ const jobs = () => readdir(path.join(ROOT, ".jobs")).catch(() => []);
test("an X channel's sync is fetch-posts: refused on no cookie jar, in the post fetch's own words, before any job", async () => {
const res = await post({ slug: "demo-x" });
assert.notEqual(res.status, 200);
- assert.match(res.error, /^No X cookie jar has been exported: press Connect X account on \/settings, then fetch again\.$/);
+ assert.match(res.error, /^No X cookie jar has been exported: press Connect X account on \/cookies, then fetch again\.$/);
assert.deepEqual(await jobs(), []);
});
diff --git a/editor/app/api/view/[name]/route.test.ts b/editor/app/api/view/[name]/route.test.ts
@@ -55,7 +55,7 @@ const PAIRS: Array<[string, string]> = [
// Views born after the consolidation: there is no old path to rewrite, so
// they are served only at /api/view/<name>.
-const NEW_VIEWS = ["cookieAlerts", "xRun", "driveHealth"];
+const NEW_VIEWS = ["cookieAlerts", "xRun", "driveHealth", "cookieStatus"];
async function view(name: string): Promise<number> {
const res = await GET(new Request(`http://localhost/api/view/${name}`), {
diff --git a/editor/app/api/view/views.ts b/editor/app/api/view/views.ts
@@ -12,6 +12,7 @@ import { buildSchedulerStatusPayload } from "../../scheduler/status";
import { widgetSyncInputs } from "../../widget/lib/syncInputs";
import { cleanableChannels } from "../../cleanup/lib/loadCleanup";
import { loadCookieAlerts } from "../../lib/cookieAlerts";
+import { loadCookieStatus } from "../../lib/cookieStatus";
import { buildDriveHealthPayload } from "../../storage/lib/driveHealth";
import { xRunConsole } from "yt-dlp-transcript-common/controller/xRun";
import {
@@ -93,4 +94,9 @@ export const VIEWS: Record<ViewName, (req: Request) => Promise<Response>> = {
// summary), the X posts channels in the default order and the jar's age
// against social.x.maxCookieAgeMinutes. Disk reads only; nothing asks X.
xRun: async () => NextResponse.json(await xRunConsole(getPaths())),
+
+ // The /cookies screen's rows: per service its cookie source, age, alert,
+ // last press and what is running. Disk reads only; the browser store's
+ // name-only read is cached 5 min (a press reads it again).
+ cookieStatus: async () => NextResponse.json(await loadCookieStatus(getPaths())),
};
diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts
@@ -74,14 +74,12 @@ import {
} from "yt-dlp-transcript-common/jobs/streamCommand";
import { importForumPages } from "yt-dlp-transcript-common/controller/importForumPages";
import {
- connectForumSession,
readForumSessionStatus,
type ForumSessionRecord,
type ForumSessionStatus,
} from "yt-dlp-transcript-common/social/forumSession";
import { parseXenforoThreadUrl } from "yt-dlp-transcript-common/social/xenforoParse";
-import { noteServiceCookieClean } from "yt-dlp-transcript-common/lib/serviceCookies-server";
-import { forumServiceKey } from "yt-dlp-transcript-common/lib/serviceCookies";
+import { connectForumAt } from "../../lib/connectForum";
// Switch which SocialFetcher drives this channel. The fetchers differ in what
// they can actually reach — for X, gallery-dl needs credentials for depth,
@@ -466,20 +464,11 @@ export async function connectForumSessionAction(
): Promise<{ ok: true; record: ForumSessionRecord } | { ok: false; error: string }> {
const ch = await forumChannel(slug);
if (!ch.ok) return ch;
- try {
- const record = await connectForumSession(getPaths(), ch.url, {
- onLog: (line) => console.log(`[forum-session] ${line}`),
- });
- // A window that closed on the thread clears the forum's cookie refresh
- // alert (the dashboard's banner).
- if (record.cleared) {
- await noteServiceCookieClean(getPaths(), forumServiceKey(ch.host), { url: ch.url, channel: slug }, { by: "connect" });
- }
- revalidatePath(`/channels/${slug}`);
- return { ok: true, record };
- } catch (e) {
- return { ok: false, error: (e as Error).message };
- }
+ // A window that closed on the thread clears the forum's cookie refresh alert
+ // (lib/connectForum.ts, shared with the /cookies row).
+ const res = await connectForumAt(ch.url, ch.host, slug);
+ if (res.ok) revalidatePath(`/channels/${slug}`);
+ return res;
}
// IMPORT: thread pages saved from a browser ("Save page as", .html), read from
diff --git a/editor/app/components/AutoRefresh.tsx b/editor/app/components/AutoRefresh.tsx
@@ -25,7 +25,9 @@ type Props = {
// A predicate rather than an allow-list of every route, so a NEW page defaults
// to refreshing (the safe direction) instead of silently going stale.
function selfPolling(pathname: string): boolean {
- return pathname.startsWith("/widget");
+ // /cookies polls its own rows (the cookieStatus view) and answers every
+ // press in place; a tree refresh would only redraw what it already has.
+ return pathname.startsWith("/widget") || pathname === "/cookies";
}
// Don't START a tree refresh within this long of a navigation. A refresh
diff --git a/editor/app/components/dashboard/CookieAlertsPanel.tsx b/editor/app/components/dashboard/CookieAlertsPanel.tsx
@@ -59,7 +59,12 @@ function AlertCard({
<p className="text-xs" aria-label={`${alert.label} cookies action`}>
{alert.fix}
</p>
- {alert.detail && <p className="text-xs text-muted-foreground break-words">{alert.detail}</p>}
+ <p className="text-xs text-muted-foreground break-words">
+ {alert.detail ? <>{alert.detail} · </> : null}
+ <Link href="/cookies" className="underline underline-offset-2 hover:text-foreground">
+ Cookies
+ </Link>
+ </p>
</>
) : (
<>
@@ -67,20 +72,17 @@ function AlertCard({
{alert.detail}
{alert.family === "forum" && channel && (
<>
- {" · "}
+ {alert.detail ? " · " : null}
<Link href={`/channels/${channel}`} className="underline underline-offset-2 hover:text-foreground">
channel page
</Link>
</>
)}
- {(alert.family === "archive" || alert.family === "x") && (
- <>
- {" · "}
- <Link href="/settings" className="underline underline-offset-2 hover:text-foreground">
- Settings
- </Link>
- </>
- )}
+ {/* A separator only after something: no leading " · ". */}
+ {alert.detail || (alert.family === "forum" && channel) ? " · " : null}
+ <Link href="/cookies" className="underline underline-offset-2 hover:text-foreground">
+ Cookies
+ </Link>
</p>
{alert.family === "x" && xJar && (
<p
diff --git a/editor/app/cookies/CookiesBoard.tsx b/editor/app/cookies/CookiesBoard.tsx
@@ -0,0 +1,180 @@
+"use client";
+
+// The /cookies rows (common/lib/cookieStatus.ts builds them): per service its
+// source, the cookies' age (ticking), the alert, the last press, and ONE
+// button. A press shows its progress and its answer in the row and swaps in
+// the rows the answer carries — no reload. A second press while one runs is
+// 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 {
+ ageSentence,
+ type CookieRow,
+ type CookieStatusPayload,
+} from "yt-dlp-transcript-common/lib/cookieStatus";
+import { usePolledPayload } from "../lib/usePolledPayload";
+import { pressCookieButtonAction } from "./actions";
+
+const POLL_MS = 30_000;
+
+const PROGRESS: Record<NonNullable<CookieRow["button"]>["action"], string> = {
+ refresh: "Refreshing…",
+ connect: "Waiting for the window…",
+ recheck: "Checking…",
+};
+
+const STATE_CLASS: Record<CookieRow["state"], string> = {
+ stale: "border-destructive/60 text-destructive",
+ fine: "border-success/50 text-success",
+ unknown: "border-border text-muted-foreground",
+};
+
+function hms(iso: string): string {
+ return `${iso.slice(11, 19)} UTC`;
+}
+
+function useNow(ms: number): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const t = setInterval(() => setNow(Date.now()), ms);
+ return () => clearInterval(t);
+ }, [ms]);
+ return now;
+}
+
+function Row({ row, onStatus }: { row: CookieRow; onStatus: (s: CookieStatusPayload) => void }) {
+ 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);
+ const button = row.button;
+ const age = ageSentence(row.ageVerb, row.ageAt, now);
+ const elapsed = pending ? Math.max(0, Math.floor((now - Date.parse(pending.since)) / 1000)) : 0;
+
+ const press = async () => {
+ if (!button || button.disabled) return;
+ if (pending) {
+ setNote({
+ text: `${row.label}'s ${button.action} is already running (since ${hms(pending.since)}) — wait for it to finish.`,
+ ok: false,
+ });
+ return;
+ }
+ const since = new Date().toISOString();
+ setPending({ since });
+ setNote(null);
+ try {
+ const r = await pressCookieButtonAction(row.service, button.action);
+ onStatus(r.status);
+ setNote({ text: r.message, ok: r.ok });
+ } catch (e) {
+ setNote({ text: (e as Error).message || "The press failed.", ok: false });
+ } finally {
+ setPending(null);
+ }
+ };
+
+ const runningElsewhere = !pending && row.running;
+ return (
+ <li
+ data-service={row.service}
+ data-state={row.state}
+ aria-label={`${row.label} cookies`}
+ className="flex flex-col gap-2 rounded-lg border border-border bg-card p-3 sm:p-4"
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <h2 className="text-base font-medium">{row.label}</h2>
+ <span
+ aria-label={`${row.label} cookie state`}
+ className={`rounded-full border px-2 py-0.5 text-xs ${STATE_CLASS[row.state]}`}
+ >
+ {row.state}
+ </span>
+ </div>
+
+ <p className="text-xs text-muted-foreground break-words" aria-label={`${row.label} cookie source`}>
+ {row.source}
+ </p>
+
+ <p className="text-sm" aria-label={`${row.label} cookie age`}>
+ {age ? (
+ <>
+ {age}
+ {row.ageNote ? <span className="text-muted-foreground"> · {row.ageNote}</span> : null}
+ </>
+ ) : (
+ <span className="text-muted-foreground">{row.ageUnknown ?? "Age unknown."}</span>
+ )}
+ </p>
+
+ {row.alert && (
+ <p
+ aria-label={`${row.label} cookie alert`}
+ className={`text-xs break-words ${row.state === "stale" ? "text-destructive" : "text-muted-foreground"}`}
+ >
+ {row.alert}
+ </p>
+ )}
+
+ {row.todo && <p className="text-xs text-muted-foreground">{row.todo}</p>}
+
+ <div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center">
+ {button && (
+ <button
+ type="button"
+ onClick={press}
+ disabled={!!button.disabled}
+ aria-label={`${row.label} ${button.label}`}
+ aria-busy={pending ? true : undefined}
+ title={button.disabled}
+ className="w-full rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50 sm:w-auto sm:py-1.5"
+ >
+ {pending ? `${PROGRESS[button.action]} ${elapsed} s` : button.label}
+ </button>
+ )}
+ {button?.disabled && <span className="text-xs text-muted-foreground">{button.disabled}</span>}
+ {runningElsewhere && row.running && (
+ <span className="text-xs text-muted-foreground" aria-label={`${row.label} running`}>
+ A {row.running.action} is running (since {hms(row.running.since)}).
+ </span>
+ )}
+ </div>
+
+ {note && (
+ <p
+ role="status"
+ aria-label={`${row.label} press result`}
+ className={`text-xs break-words ${note.ok ? "text-success" : "text-destructive"}`}
+ >
+ {note.text}
+ </p>
+ )}
+ {!note && row.last && (
+ <p className="text-xs text-muted-foreground break-words" aria-label={`${row.label} last result`}>
+ {ageSentence(`Last ${row.last.action}`, row.last.at, now) ?? `Last ${row.last.action}`}:{" "}
+ <span className={row.last.ok ? "" : "text-destructive"}>{row.last.message}</span>
+ </p>
+ )}
+ </li>
+ );
+}
+
+export function CookiesBoard({ initial }: { initial: CookieStatusPayload }) {
+ const { data } = usePolledPayload<CookieStatusPayload>("/api/view/cookieStatus", true, POLL_MS, initial, {
+ immediate: false,
+ });
+ const [status, setStatus] = useState<CookieStatusPayload>(initial);
+ // A poll newer than what the rows show replaces it; a press's answer does too.
+ useEffect(() => {
+ if (data && data.readAt > status.readAt) setStatus(data);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [data]);
+ const take = (s: CookieStatusPayload) => setStatus((cur) => (s.readAt >= cur.readAt ? s : cur));
+ return (
+ <ul className="flex flex-col gap-3" aria-label="Services">
+ {status.rows.map((row) => (
+ <Row key={row.service} row={row} onStatus={take} />
+ ))}
+ </ul>
+ );
+}
diff --git a/editor/app/cookies/actions.ts b/editor/app/cookies/actions.ts
@@ -0,0 +1,97 @@
+"use server";
+
+// THE /cookies SCREEN'S BUTTONS (plans/cookie-screen.md). Each row has ONE,
+// and it runs the action that already exists for that service — nothing here
+// refreshes anything itself:
+//
+// x · refresh refreshXCookiesAction (/settings' Refresh cookies); when
+// X's alert is up, the recheck after it (X's sends no
+// request — the login on disk), so the alert clears at once
+// 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)
+//
+// 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
+// "last result". Each answer carries the screen's rows read again, so the
+// row's age and state change in place, without a reload.
+
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { displayText } from "yt-dlp-transcript-common/lib/privacy/privacy-server";
+import {
+ ARCHIVE_TODAY_SERVICE,
+ X_SERVICE,
+ isServiceKey,
+ serviceFamily,
+ serviceLabel,
+} from "yt-dlp-transcript-common/lib/serviceCookies";
+import { readServiceCookieState, raisedServiceAlert } from "yt-dlp-transcript-common/lib/serviceCookies-server";
+import { forumThreadFor, type CookieStatusPayload } from "yt-dlp-transcript-common/lib/cookieStatus";
+import { recheckServiceCookies } from "yt-dlp-transcript-common/controller/recheckServiceCookies";
+import { connectXAccountAction, refreshXCookiesAction } from "../settings/xSessionActions";
+import { connectArchiveSessionAction } from "../settings/archiveSessionActions";
+import { recheckServiceCookiesAction } from "../operations/serviceCookiesActions";
+import { connectForumAt } from "../lib/connectForum";
+import { loadCookieStatus } from "../lib/cookieStatus";
+
+export type CookiePressResult = {
+ ok: boolean;
+ message: string;
+ // Refused because a press for the service is already running.
+ busy?: boolean;
+ status: CookieStatusPayload;
+};
+
+type Answer = { ok: boolean; message: string; busy?: boolean };
+
+function answerOf(r: { ok: true } | { ok: false; error: string; busy?: true }, okMessage: string): Answer {
+ return r.ok ? { ok: true, message: okMessage } : { ok: false, message: r.error, ...("busy" in r && r.busy ? { busy: true } : {}) };
+}
+
+async function press(service: string, action: string): Promise<Answer> {
+ if (!isServiceKey(service)) return { ok: false, message: `Not a service: ${service}` };
+ const family = serviceFamily(service);
+ const paths = getPaths();
+ if (action === "recheck" && (family === "ytdlp" || family === "x")) {
+ const r = await recheckServiceCookiesAction(service);
+ return r.ok ? { ok: r.result === "clean", message: r.message } : answerOf(r, "");
+ }
+ if (service === X_SERVICE && action === "refresh") {
+ const r = await refreshXCookiesAction();
+ if (!r.ok) return answerOf(r, "");
+ // The jar is new; an X alert up since before it is rechecked from disk
+ // (no request to X) so it clears now, not at the next X job.
+ if (await raisedServiceAlert(paths, X_SERVICE)) {
+ const o = await recheckServiceCookies({ paths, service: X_SERVICE }).catch(() => null);
+ if (o) return { ok: true, message: `Cookies refreshed. ${o.message}` };
+ }
+ return { ok: true, message: "Cookies refreshed." };
+ }
+ if (service === X_SERVICE && action === "connect") {
+ const r = await connectXAccountAction();
+ return answerOf(r, r.ok ? `Connected${r.browser ? ` with ${r.browser}` : ""}. Cookies exported.` : "");
+ }
+ if (service === ARCHIVE_TODAY_SERVICE && action === "connect") {
+ const r = await connectArchiveSessionAction();
+ 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);
+ 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.") : "");
+ }
+ return { ok: false, message: `${serviceLabel(service)} has no "${action}" here.` };
+}
+
+export async function pressCookieButtonAction(service: string, action: string): Promise<CookiePressResult> {
+ let answer: Answer;
+ try {
+ answer = await press(String(service ?? ""), String(action ?? ""));
+ } catch (e) {
+ answer = { ok: false, message: (e as Error).message };
+ }
+ // An error may carry a path: drawn as the page draws one.
+ return { ...answer, message: displayText(answer.message), status: await loadCookieStatus(getPaths(), { fresh: action === "recheck" }) };
+}
diff --git a/editor/app/cookies/page.tsx b/editor/app/cookies/page.tsx
@@ -0,0 +1,22 @@
+import type { Metadata } from "next";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { loadCookieStatus } from "../lib/cookieStatus";
+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.
+export const dynamic = "force-dynamic";
+
+export const metadata: Metadata = { title: "Cookies" };
+
+export default async function CookiesPage() {
+ const initial = await loadCookieStatus(getPaths());
+ return (
+ <div className="flex flex-col gap-4">
+ <h1 className="text-2xl font-semibold">Cookies</h1>
+ <CookiesBoard initial={initial} />
+ </div>
+ );
+}
diff --git a/editor/app/lib/connectForum.ts b/editor/app/lib/connectForum.ts
@@ -0,0 +1,45 @@
+// CONNECT A FORUM SESSION — the one body behind the forum channel page's
+// "Connect forum session" (channels/[slug]/socialActions.ts) and the /cookies
+// row of a forum host (cookies/actions.ts): a HEADED browser window on the
+// host's profile (common/social/forumSession.ts), opened at a thread on the
+// machine running the editor, for the operator to clear a check and close. A
+// window that closed on the thread clears the host's cookie refresh alert.
+// Through the one-press-per-service guard (lib/cookieRefreshGuard.ts).
+
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { connectForumSession, type ForumSessionRecord } from "yt-dlp-transcript-common/social/forumSession";
+import { noteServiceCookieClean } from "yt-dlp-transcript-common/lib/serviceCookies-server";
+import { forumServiceKey } from "yt-dlp-transcript-common/lib/serviceCookies";
+import { withCookieAction } from "./cookieRefreshGuard";
+
+export type ConnectForumResult = { ok: true; record: ForumSessionRecord } | { ok: false; error: string };
+
+export async function connectForumAt(url: string, host: string, channel?: string): Promise<ConnectForumResult> {
+ const service = forumServiceKey(host);
+ return withCookieAction(
+ service,
+ "connect",
+ async (): Promise<ConnectForumResult> => {
+ try {
+ const record = await connectForumSession(getPaths(), url, {
+ onLog: (line) => console.log(`[forum-session] ${line}`),
+ });
+ if (record.cleared) {
+ await noteServiceCookieClean(getPaths(), service, { url, ...(channel ? { channel } : {}) }, { by: "connect" });
+ }
+ return { ok: true, record };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+ },
+ (r) =>
+ r.ok
+ ? {
+ ok: true,
+ message: r.record.cleared
+ ? `Connected: the window closed on the thread (${r.record.cookies} cookies).`
+ : "The window closed before the thread showed: not cleared.",
+ }
+ : { ok: false, message: r.error },
+ );
+}
diff --git a/editor/app/lib/cookieRefreshGuard.test.ts b/editor/app/lib/cookieRefreshGuard.test.ts
@@ -0,0 +1,140 @@
+// One press at a time per service, and its result recorded
+// (cookieRefreshGuard.ts). Over a temp transcripts dir; the jobs are handed in.
+//
+// Run with: pnpm -C editor exec tsx --test app/lib/cookieRefreshGuard.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+import { readServiceCookieState } from "yt-dlp-transcript-common/lib/serviceCookies-server";
+import { recheckOutcome, runningCookieActions, withCookieAction } from "./cookieRefreshGuard";
+
+const root = await mkdtemp(path.join(os.tmpdir(), "cookie-guard-"));
+const paths = { transcriptsDir: root } as Paths;
+test.after(() => rm(root, { recursive: true, force: true }));
+const noJobs = () => [];
+
+test("a second press while the first runs is refused with a sentence, then allowed once it ends", async () => {
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ let runs = 0;
+ const first = withCookieAction(
+ "x",
+ "refresh",
+ async () => {
+ runs++;
+ await gate;
+ return { ok: true as const };
+ },
+ () => ({ ok: true, message: "Cookies refreshed." }),
+ { paths, jobs: noJobs },
+ );
+ // While it runs: shown as running, and a second press is refused, not queued.
+ assert.equal(runningCookieActions([]).x?.action, "refresh");
+ const second = await withCookieAction("x", "refresh", async () => ({ ok: true as const }), () => ({ ok: true, message: "" }), {
+ paths,
+ jobs: noJobs,
+ });
+ assert.equal(second.ok, false);
+ assert.match((second as { error: string }).error, /^X's refresh is already running \(since \d\d:\d\d:\d\d UTC\) — wait for it to finish\.$/);
+ assert.equal(runs, 1);
+ // Another service is not held by X's press.
+ const other = await withCookieAction("rumble", "recheck", async () => ({ ok: true as const }), () => ({ ok: true, message: "clean", result: "clean" }), {
+ paths,
+ jobs: noJobs,
+ });
+ assert.equal(other.ok, true);
+ release();
+ assert.deepEqual(await first, { ok: true });
+ assert.equal(runningCookieActions([]).x, undefined);
+ const state = await readServiceCookieState(paths);
+ assert.equal(state.actions?.x?.message, "Cookies refreshed.");
+ assert.equal(state.actions?.x?.ok, true);
+ assert.equal(state.actions?.rumble?.result, "clean");
+});
+
+test("a recheck job queued or running on the service's queue counts as in flight", async () => {
+ const jobs = () => [
+ { id: "j1", kind: "recheck-service-cookies", queueKey: "service-cookies:rumble", status: "running", queuedAt: 0, startedAt: Date.parse("2026-11-16T09:31:00Z") },
+ { id: "j2", kind: "recheck-service-cookies", queueKey: "service-cookies:youtube", status: "done", queuedAt: 0 },
+ { id: "j3", kind: "download", queueKey: "service-cookies:odysee", status: "running", queuedAt: 0 },
+ ];
+ assert.deepEqual(runningCookieActions(jobs()), {
+ rumble: { action: "recheck", since: "2026-11-16T09:31:00.000Z", jobId: "j1" },
+ });
+ let ran = false;
+ const r = await withCookieAction("rumble", "recheck", async () => {
+ ran = true;
+ return { ok: true as const };
+ }, () => ({ ok: true, message: "" }), { paths, jobs });
+ assert.equal(ran, false);
+ assert.match((r as { error: string }).error, /Rumble's recheck is already running \(since 09:31:00 UTC\)/);
+});
+
+test("a press that throws is recorded as failed and the mark is released", async () => {
+ await assert.rejects(
+ withCookieAction("archive.today", "connect", async () => {
+ throw new Error("no display");
+ }, () => ({ ok: true, message: "" }), { paths, jobs: noJobs }),
+ /no display/,
+ );
+ assert.equal(runningCookieActions([])["archive.today"], undefined);
+ const a = (await readServiceCookieState(paths)).actions?.["archive.today"];
+ assert.equal(a?.ok, false);
+ assert.equal(a?.message, "no display");
+ assert.equal(a?.action, "connect");
+});
+
+test("a recheck that answers stale or failed is remembered as not ok; clean is ok", async () => {
+ assert.deepEqual(recheckOutcome({ ok: true, jobId: "j", result: "stale", message: "Rumble still refused." }), {
+ ok: false,
+ result: "stale",
+ message: "Rumble still refused.",
+ jobId: "j",
+ });
+ assert.equal(recheckOutcome({ ok: true, jobId: "j", result: "failed", message: "m" }).ok, false);
+ assert.equal(recheckOutcome({ ok: true, jobId: "j", result: "clean", message: "m" }).ok, true);
+ assert.deepEqual(recheckOutcome({ ok: false, error: "ended failed", jobId: "k" }), { ok: false, message: "ended failed", jobId: "k" });
+ // Through the guard, as the action records it.
+ await withCookieAction(
+ "youtube",
+ "recheck",
+ async () => ({ ok: true as const, jobId: "j9", result: "stale" as const, message: "YouTube still refused." }),
+ recheckOutcome,
+ { paths, jobs: noJobs },
+ );
+ const a = (await readServiceCookieState(paths)).actions?.youtube;
+ assert.equal(a?.ok, false);
+ assert.equal(a?.result, "stale");
+});
+
+test("a describe that throws keeps the press's answer and releases the mark", async () => {
+ const r = await withCookieAction(
+ "odysee",
+ "recheck",
+ async () => ({ ok: true as const, n: 1 }),
+ () => {
+ throw new Error("describe broke");
+ },
+ { paths, jobs: noJobs },
+ );
+ assert.deepEqual(r, { ok: true, n: 1 });
+ assert.equal(runningCookieActions([]).odysee, undefined);
+});
+
+test("a throw before the press (finding the paths) never leaves the service marked busy", async () => {
+ const opts = {
+ jobs: noJobs,
+ get paths(): Paths {
+ throw new Error("no paths");
+ },
+ };
+ await assert.rejects(
+ withCookieAction("rumble", "recheck", async () => ({ ok: true }), () => ({ ok: true, message: "" }), opts),
+ /no paths/,
+ );
+ assert.equal(runningCookieActions([]).rumble, undefined);
+});
diff --git a/editor/app/lib/cookieRefreshGuard.ts b/editor/app/lib/cookieRefreshGuard.ts
@@ -0,0 +1,123 @@
+// ONE PRESS AT A TIME PER SERVICE, AND ITS RESULT REMEMBERED (the /cookies
+// screen, plans/cookie-screen.md). Every button that refreshes, connects or
+// rechecks a service's cookies — /cookies, the dashboard banner's Recheck,
+// /settings' Refresh cookies and Connect, a forum channel's Connect, `pnpm ops
+// recheck-service` — runs through `withCookieAction`:
+//
+// - a second press while one is in flight for that service is REFUSED with a
+// sentence saying so (never queued behind it): an in-process mark per
+// service, and a `recheck-service-cookies` job already queued or running
+// on the service's queue (the proactive timer's) counts as in flight too;
+// - the outcome is recorded as the service's last press
+// (noteServiceCookieAction, `.service-cookies.json` `actions`), which the
+// screen shows as "last result".
+//
+// The mark lives on globalThis (one per server process, like the registry).
+
+import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { noteServiceCookieAction } from "yt-dlp-transcript-common/lib/serviceCookies-server";
+import { serviceLabel, type ServiceCookieActionKind } from "yt-dlp-transcript-common/lib/serviceCookies";
+import type { CookieRunning } from "yt-dlp-transcript-common/lib/cookieStatus";
+import { RECHECK_JOB_KIND } from "yt-dlp-transcript-common/controller/serviceCookieTimer";
+
+const QUEUE_PREFIX = "service-cookies:";
+const KEY = Symbol.for("archilyzer.cookieRefresh.inflight");
+
+function inflight(): Map<string, CookieRunning> {
+ const g = globalThis as unknown as Record<symbol, Map<string, CookieRunning>>;
+ return (g[KEY] ??= new Map());
+}
+
+type JobLike = { id: string; kind: string; queueKey: string; status: string; queuedAt?: number; startedAt?: number };
+
+// What is running per service now: the presses in flight here, and any
+// recheck job queued or running on a service's queue.
+export function runningCookieActions(
+ jobs: readonly JobLike[] = getRegistry().list(),
+): Record<string, CookieRunning> {
+ const out: Record<string, CookieRunning> = {};
+ for (const j of jobs) {
+ if (j.kind !== RECHECK_JOB_KIND || !j.queueKey.startsWith(QUEUE_PREFIX)) continue;
+ if (j.status !== "queued" && j.status !== "running") continue;
+ const since = j.startedAt ?? j.queuedAt;
+ out[j.queueKey.slice(QUEUE_PREFIX.length)] = {
+ action: "recheck",
+ since: new Date(since ?? Date.now()).toISOString(),
+ jobId: j.id,
+ };
+ }
+ for (const [service, r] of inflight()) out[service] = r;
+ return out;
+}
+
+export function busySentence(service: string, r: CookieRunning): string {
+ return `${serviceLabel(service)}'s ${r.action} is already running (since ${r.since.slice(11, 19)} UTC) — wait for it to finish.`;
+}
+
+export type CookieActionOutcome = {
+ ok: boolean;
+ message: string;
+ result?: "clean" | "stale" | "failed";
+ jobId?: string;
+};
+
+// The recorded outcome of a recheck (operations/serviceCookiesActions.ts): ok
+// only when the service answered cleanly — a "stale" or "failed" answer is
+// remembered as not ok, as the press's own note in the row says it.
+export function recheckOutcome(
+ r:
+ | { ok: true; jobId: string; result: "clean" | "stale" | "failed"; message: string }
+ | { ok: false; error: string; jobId?: string },
+): CookieActionOutcome {
+ return r.ok
+ ? { ok: r.result === "clean", result: r.result, message: r.message, jobId: r.jobId }
+ : { ok: false, message: r.error, ...(r.jobId ? { jobId: r.jobId } : {}) };
+}
+
+// Run `fn` as the one press for `service`, or refuse. `describe` turns its
+// answer into the recorded outcome.
+export async function withCookieAction<T>(
+ service: string,
+ action: ServiceCookieActionKind,
+ fn: () => Promise<T>,
+ describe: (r: T) => CookieActionOutcome,
+ opts: { paths?: Paths; jobs?: () => readonly JobLike[] } = {},
+): Promise<T | { ok: false; error: string; busy: true }> {
+ const running = runningCookieActions(opts.jobs ? opts.jobs() : undefined)[service];
+ if (running) return { ok: false, error: busySentence(service, running), busy: true };
+ const map = inflight();
+ map.set(service, { action, since: new Date().toISOString() });
+ // Everything after the mark is inside the try: whatever throws, the finally
+ // releases it, so a service is never left marked busy.
+ try {
+ const paths = opts.paths ?? getPaths();
+ let r: T;
+ try {
+ r = await fn();
+ } catch (e) {
+ await noteServiceCookieAction(paths, service, { action, ok: false, message: (e as Error).message });
+ throw e;
+ }
+ // A describe that throws only costs the record: the press itself succeeded
+ // and its answer is returned as it came.
+ let o: CookieActionOutcome | null = null;
+ try {
+ o = describe(r);
+ } catch {
+ o = null;
+ }
+ if (o) {
+ await noteServiceCookieAction(paths, service, {
+ action,
+ ok: o.ok,
+ message: o.message,
+ ...(o.result ? { result: o.result } : {}),
+ ...(o.jobId ? { jobId: o.jobId } : {}),
+ });
+ }
+ return r;
+ } finally {
+ map.delete(service);
+ }
+}
diff --git a/editor/app/lib/cookieStatus.ts b/editor/app/lib/cookieStatus.ts
@@ -0,0 +1,130 @@
+// THE /cookies SCREEN'S READS (plans/cookie-screen.md) — only what the rows
+// show, so the page loads fast where /settings does not (/settings ships the
+// whole parsed settings.json, ~120 KB of it the lanes' state, into one big
+// client form):
+//
+// - `.service-cookies.json` and each alert job's status (loadCookieAlerts —
+// the dashboard's own payload, which carries X's jar age);
+// - settings.json parsed once here for cookiesFromBrowser and social.x —
+// nothing of it is sent to the browser but the rows;
+// - a stat and a read of X's exported jar, archive.today's session.json, a
+// readdir of `.forum-session/` and each host's session.json;
+// - 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.
+//
+// No channel listing, no index, no corpus walk. A read that fails leaves its
+// row "unknown"; it never fails the page.
+
+import { readdir } from "node:fs/promises";
+import path from "node:path";
+import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings, type SiteSettings } from "yt-dlp-transcript-common/lib/settings";
+import { displayPath, displayText } from "yt-dlp-transcript-common/lib/privacy/privacy-server";
+import { readServiceCookieState } from "yt-dlp-transcript-common/lib/serviceCookies-server";
+import { buildCookieStatus, type CookieStatusInput, type CookieStatusPayload, type YtdlpCookieInput } from "yt-dlp-transcript-common/lib/cookieStatus";
+import { BROWSER_COOKIE_SERVICES, readBrowserCookieAges } from "yt-dlp-transcript-common/lib/browserCookieAge";
+import { resolveCookiePolicy } from "yt-dlp-transcript-common/lib/cookiePolicy";
+import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { readXSessionStatus, xProfileDir } from "yt-dlp-transcript-common/social/xSessionBroker";
+import { resolveXCookieSourceFor } from "yt-dlp-transcript-common/social/xBrowserLogin";
+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 { runningCookieActions } from "./cookieRefreshGuard";
+
+async function safe<T>(fn: () => Promise<T>, fallback: T): Promise<T> {
+ try {
+ return await fn();
+ } catch {
+ return fallback;
+ }
+}
+
+export async function loadCookieStatus(
+ paths: Paths = getPaths(),
+ opts: { now?: number; fresh?: boolean } = {},
+): Promise<CookieStatusPayload> {
+ const now = opts.now ?? Date.now();
+ let settings: SiteSettings | null = null;
+ try {
+ settings = getSettings();
+ } catch {
+ settings = null;
+ }
+ const [alerts, state] = await Promise.all([
+ safe(() => loadCookieAlerts(paths, now), { alerts: [], pending: [] }),
+ readServiceCookieState(paths),
+ ]);
+
+ // X: the source in use and the profile.
+ const session = await safe(() => readXSessionStatus(paths), { hasProfile: false, hasCookies: false, looksAuthenticated: false });
+ const resolved = settings ? await safe(() => resolveXCookieSourceFor(paths, settings!), null) : null;
+ const x: CookieStatusInput["x"] = {
+ source: resolved?.source ?? "profile",
+ ...(resolved?.browserSpec ? { browserSpec: resolved.browserSpec } : {}),
+ profileDir: xProfileDir(paths),
+ hasProfile: session.hasProfile,
+ ...(alerts.x ? { jar: alerts.x } : {}),
+ };
+
+ // The yt-dlp services: the spec yt-dlp uses (the last clean request's
+ // channel's own, else settings'), and its store's ages — one read per spec.
+ const ytdlp = {} as CookieStatusInput["ytdlp"];
+ for (const svc of BROWSER_COOKIE_SERVICES) {
+ const channel = state.lastGood[svc]?.channel ?? state.services[svc]?.evidence.channel;
+ // A slug from the state file, checked before it names a path.
+ const config = channel && isValidChannelSlug(channel) ? await safe(() => readChannelConfig(paths, channel), null) : null;
+ const own = config?.cookiesFromBrowser?.trim();
+ const spec = settings ? resolveCookiePolicy(settings, config ?? undefined).cookies : own || undefined;
+ const age = await readBrowserCookieAges(spec, { now, ...(opts.fresh ? { fresh: true } : {}) });
+ const entry: YtdlpCookieInput = {
+ ...(spec ? { spec } : {}),
+ specFrom: own ? "channel" : "settings",
+ ...(own && channel ? { channel } : {}),
+ age: age.services[svc],
+ };
+ ytdlp[svc] = entry;
+ }
+
+ const archiveStatus = await safe(() => readArchiveSessionStatus(paths), null);
+ const archive: CookieStatusInput["archive"] = {
+ dir: archiveSessionDir(paths),
+ hasProfile: archiveStatus?.hasProfile ?? false,
+ ...(archiveStatus?.lastConnect
+ ? { connectedAt: archiveStatus.lastConnect.connectedAt, cleared: archiveStatus.lastConnect.cleared }
+ : {}),
+ };
+
+ const hosts = await safe(
+ async () =>
+ (await readdir(path.join(paths.transcriptsDir, ".forum-session"), { withFileTypes: true }))
+ .filter((d) => d.isDirectory())
+ .map((d) => d.name),
+ [] as string[],
+ );
+ const forums: CookieStatusInput["forums"] = [];
+ for (const host of hosts) {
+ const st = await safe(() => readForumSessionStatus(paths, host), null);
+ if (!st) continue;
+ forums.push({
+ host,
+ dir: forumSessionDir(paths, host),
+ hasProfile: st.hasProfile,
+ ...(st.lastConnect ? { connectedAt: st.lastConnect.connectedAt, cleared: st.lastConnect.cleared } : {}),
+ });
+ }
+
+ return buildCookieStatus({
+ now,
+ alerts,
+ state,
+ x,
+ ytdlp,
+ archive,
+ forums,
+ running: runningCookieActions(),
+ display: { path: displayPath, text: displayText },
+ });
+}
diff --git a/editor/app/lib/nav.test.ts b/editor/app/lib/nav.test.ts
@@ -16,7 +16,7 @@ test("four groups, one noun each", () => {
);
});
-// THIRTEEN, and the twelfth and thirteenth are recorded exceptions rather than
+// THIRTEEN WAS, and the twelfth and thirteenth are recorded exceptions rather than
// slips. The IA rule is "fold, do not add" and this test is where it is either
// true or not — so the number moves only when a plan says why. /storage is a
// Machine NOUN (a place the machine keeps bytes), not a fold of Cleanup (an
@@ -24,9 +24,11 @@ test("four groups, one noun each", () => {
// vocabulary over every channel and every site), which is precisely what it
// stops being if it is folded under one site or one channel. See nav.ts's
// header, plans/editor-operations-ia.md and plans/curated-tags.md.
-test("thirteen entries, every href distinct", () => {
- assert.equal(NAV_LINKS.length, 13);
- assert.equal(new Set(NAV_LINKS.map((l) => l.href)).size, 13);
+// FOURTEEN since /cookies (2026-11-16): the operator's one operation pressed
+// over and over, recorded in nav.ts's header and plans/cookie-screen.md.
+test("fourteen entries, every href distinct", () => {
+ assert.equal(NAV_LINKS.length, 14);
+ assert.equal(new Set(NAV_LINKS.map((l) => l.href)).size, 14);
});
test("the Sites group is one entry", () => {
diff --git a/editor/app/lib/nav.ts b/editor/app/lib/nav.ts
@@ -1,6 +1,7 @@
import type { LucideIcon } from "lucide-react";
import {
ClipboardCheck,
+ Cookie,
Cpu,
Globe,
HardDrive,
@@ -52,6 +53,14 @@ import {
// Agreed with the operator 2026-09-17; plans/editor-operations-ia.md carries
// the same sentence.
+// A THIRD RECORDED EXCEPTION, at fourteen: /cookies. The operator, 2026-11-16:
+// "make a dedicated screen for cookie refreshes like Rumble and X, because
+// sometimes the settings screen takes too long to load when most of the time
+// I'm going for this one operation over and over." One operation pressed over
+// and over, from a phone, is what a nav entry is for; folding it back under
+// /settings is the thing being undone. plans/cookie-screen.md carries the same
+// sentence.
+
export type NavBadgeKey = "jobs" | "changelog" | "cleanable";
export type NavLink = {
@@ -113,6 +122,7 @@ export const NAV_GROUPS: NavGroup[] = [
{ href: "/cleanup", label: "Cleanup", icon: Trash2, badgeKey: "cleanable", keywords: "clean reclaim disk space prune audio" },
{ href: "/storage", label: "Storage", icon: HardDrive, keywords: "drive disk platter mount volume media location relocate cold" },
{ href: "/saved-videos", label: "Saved videos", icon: Bookmark, keywords: "backup" },
+ { href: "/cookies", label: "Cookies", icon: Cookie, keywords: "cookie refresh rumble x twitter youtube odysee archive.today forum kiwi farms cf_clearance session login jar stale recheck connect" },
{ href: "/settings", label: "Settings", icon: Settings, keywords: "config preferences" },
{ href: "/changelog", label: "Changelog", icon: ScrollText, badgeKey: "changelog", keywords: "release notes" },
],
diff --git a/editor/app/operations/serviceCookiesActions.ts b/editor/app/operations/serviceCookiesActions.ts
@@ -27,19 +27,26 @@ import {
} from "yt-dlp-transcript-common/controller/recheckServiceCookies";
import { retryJobAction } from "../jobs/actions";
import { loadCookieAlerts } from "../lib/cookieAlerts";
+import { recheckOutcome, withCookieAction } from "../lib/cookieRefreshGuard";
function refuse(service: string): string | null {
return isServiceKey(service) ? null : `Not a service: ${service}`;
}
-export async function recheckServiceCookiesAction(
- service: string,
-): Promise<
+export type RecheckActionResult =
| { ok: true; jobId: string; result: RecheckOutcome["result"]; message: string }
- | { ok: false; error: string; jobId?: string }
-> {
+ // busy: refused because a recheck (or another press) for the service is running.
+ | { ok: false; error: string; jobId?: string; busy?: true };
+
+// Through the one-press-per-service guard (lib/cookieRefreshGuard.ts): a
+// second Recheck while one runs (or the timer's) is refused, not queued.
+export async function recheckServiceCookiesAction(service: string): Promise<RecheckActionResult> {
const bad = refuse(service);
if (bad) return { ok: false, error: bad };
+ return withCookieAction(service, "recheck", () => recheckNow(service), recheckOutcome);
+}
+
+async function recheckNow(service: string): Promise<RecheckActionResult> {
const paths = getPaths();
let outcome: RecheckOutcome | null = null;
const res = await runManagedFunction({
diff --git a/editor/app/review/components/XRunConsole.tsx b/editor/app/review/components/XRunConsole.tsx
@@ -65,9 +65,9 @@ const TIER_TONE: Record<string, string> = {
};
// THE JAR, COUNTED DOWN. Ticks every second from the jar's mtime and the
-// limit; the poll refreshes both (a refresh on /settings rewrites the jar).
+// limit; the poll refreshes both (a refresh on /cookies rewrites the jar).
function JarCountdown({ jar, now }: { jar: XRunConsolePayload["jar"]; now: number | null }) {
- const href = "/settings";
+ const href = "/cookies";
if (jar.alert) {
return (
<p role="status" aria-label="x cookie jar" data-jar="alert" className="text-sm text-destructive">
@@ -87,7 +87,7 @@ function JarCountdown({ jar, now }: { jar: XRunConsolePayload["jar"]; now: numbe
if (!jar.cookiesUpdatedAt || !jar.staleAt) {
return (
<p role="status" aria-label="x cookie jar" data-jar="none" className="text-sm text-destructive">
- No X cookie jar: <Link href={href} className="underline">Connect X account on /settings</Link>.
+ No X cookie jar: <Link href={href} className="underline">Connect X account on /cookies</Link>.
</p>
);
}
@@ -98,7 +98,7 @@ function JarCountdown({ jar, now }: { jar: XRunConsolePayload["jar"]; now: numbe
return (
<p role="status" aria-label="x cookie jar" data-jar="stale" className="text-sm text-warning">
Cookie jar {age(old)} old, past the {jar.maxAgeMinutes} min limit —{" "}
- <Link href={href} className="underline">Refresh cookies on /settings</Link>, then Resume.
+ <Link href={href} className="underline">Refresh cookies on /cookies</Link>, then Resume.
</p>
);
}
diff --git a/editor/app/settings/archiveSessionActions.ts b/editor/app/settings/archiveSessionActions.ts
@@ -20,6 +20,7 @@ import {
import { isArchiveTodayUrl } from "yt-dlp-transcript-common/lib/archives/mementos";
import { sanitizeArchives, type ArchivesSettings } from "yt-dlp-transcript-common/lib/archives/settings";
import { saveSettings } from "./saveSettings";
+import { withCookieAction } from "../lib/cookieRefreshGuard";
import { noteServiceCookieClean } from "yt-dlp-transcript-common/lib/serviceCookies-server";
import { ARCHIVE_TODAY_SERVICE } from "yt-dlp-transcript-common/lib/serviceCookies";
@@ -29,9 +30,23 @@ export async function archiveSessionStatusAction(): Promise<ArchiveSessionStatus
// Open the window at `url` (an archive.today copy the check stood in front
// of), else at archive.today's front page on the canonical host.
-export async function connectArchiveSessionAction(
- url?: string,
-): Promise<{ ok: true; record: ArchiveSessionRecord } | { ok: false; error: string }> {
+export type ConnectArchiveResult = { ok: true; record: ArchiveSessionRecord } | { ok: false; error: string };
+
+// Through the one-press-per-service guard (lib/cookieRefreshGuard.ts).
+export async function connectArchiveSessionAction(url?: string): Promise<ConnectArchiveResult> {
+ return withCookieAction(ARCHIVE_TODAY_SERVICE, "connect", () => connectArchiveNow(url), (r) =>
+ r.ok
+ ? {
+ ok: true,
+ message: r.record.cleared
+ ? `Connected: the window closed past the check (${r.record.cookies} cookies).`
+ : "The window closed on a check page: not cleared.",
+ }
+ : { ok: false, message: r.error },
+ );
+}
+
+async function connectArchiveNow(url?: string): Promise<ConnectArchiveResult> {
const host = getSettings().archives.archiveTodayHost;
const at = url?.trim() && isArchiveTodayUrl(url.trim()) ? url.trim() : `https://${host}/`;
try {
diff --git a/editor/app/settings/components/ArchiveSessionSection.tsx b/editor/app/settings/components/ArchiveSessionSection.tsx
@@ -6,6 +6,7 @@
// pass archive.today's check once; the headless reads reuse it. The same
// Connect control sits on an Archived pages channel's panel.
+import Link from "next/link";
import { useState, useTransition } from "react";
import { ARCHIVE_TODAY_HOSTS } from "yt-dlp-transcript-common/lib/archives/mementos";
import type { ArchivesSettings } from "yt-dlp-transcript-common/lib/archives/settings";
@@ -61,6 +62,11 @@ 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} />
<div className="flex flex-wrap items-end gap-3 text-sm">
<label className="flex flex-col gap-1">
diff --git a/editor/app/settings/components/XSessionSection.tsx b/editor/app/settings/components/XSessionSection.tsx
@@ -11,6 +11,7 @@
// the fetcher re-exports fresh cookies from, because X cookies otherwise
// expire within days.
+import Link from "next/link";
import { useEffect, useState, useTransition } from "react";
import {
checkXLoginAction,
@@ -135,6 +136,12 @@ 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>
+
<p className="text-xs text-muted-foreground">
X post archiving needs a logged-in session, from one of two sources.{" "}
<strong>Browser login</strong>: your everyday browser, named by{" "}
diff --git a/editor/app/settings/xSessionActions.ts b/editor/app/settings/xSessionActions.ts
@@ -40,6 +40,8 @@ import {
} from "yt-dlp-transcript-common/social/xCookieSource";
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";
// `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
@@ -65,7 +67,18 @@ export async function xSessionStatusAction(): Promise<XSessionStatus> {
return readXSessionStatus(getPaths());
}
+// Connect and Refresh go through the one-press-per-service guard
+// (lib/cookieRefreshGuard.ts): a second press while one runs is refused, and
+// each outcome is the X row's "last result" on /cookies.
export async function connectXAccountAction(): Promise<XSessionActionResult> {
+ return withCookieAction("x", "connect", connectXAccountNow, (r) =>
+ r.ok
+ ? { ok: true, message: `Connected${r.browser ? ` with ${r.browser}` : ""}. Cookies exported.` }
+ : { ok: false, message: r.error },
+ );
+}
+
+async function connectXAccountNow(): Promise<XSessionActionResult> {
try {
const { browser, ...status } = await connectXAccount(getPaths(), {
// Which browser opened, and any fallback, in the editor's log.
@@ -88,9 +101,21 @@ export async function connectXAccountAction(): Promise<XSessionActionResult> {
}
export async function refreshXCookiesAction(): Promise<XSessionActionResult> {
+ return withCookieAction("x", "refresh", refreshXCookiesNow, (r) =>
+ r.ok ? { ok: true, message: "Cookies refreshed." } : { ok: false, message: r.error },
+ );
+}
+
+async function refreshXCookiesNow(): Promise<XSessionActionResult> {
try {
- const status = await refreshXCookies(getPaths(), {
+ const paths = getPaths();
+ // Under the e2e test server only, a fake browser (no browser starts,
+ // nothing asks X): common/social/fakeXProfileBrowser.ts says how it is
+ // gated. On any other process this is null and the real browser runs.
+ const chromium = fakeXProfileChromium(paths.transcriptsDir);
+ const status = await refreshXCookies(paths, {
onLog: (line) => console.log(`[x-session] ${line}`),
+ ...(chromium ? { chromium } : {}),
});
return { ok: true, status, source: await sourceNow() };
} catch (e) {
diff --git a/editor/e2e/cookie-alerts.spec.ts b/editor/e2e/cookie-alerts.spec.ts
@@ -192,7 +192,7 @@ test("X: a stale jar refuses Fetch posts; \"\" is refused; a challenge fails the
const stale = await fetchPosts(request, "x-other");
expect(stale.status).toBe(400);
expect(stale.body.error).toBe(
- "X cookies were last refreshed 16 days ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings, then fetch again.",
+ "X cookies were last refreshed 16 days ago (limit 60 min): press Refresh cookies (or Connect X account) on /cookies, then fetch again.",
);
// A fresh jar; an unqueued fetch is still refused.
@@ -227,7 +227,7 @@ test("X: a stale jar refuses Fetch posts; \"\" is refused; a challenge fails the
});
await expect(banner).toHaveAttribute("data-state", "stale");
- // The operator refreshes the jar (Refresh cookies on /settings); Recheck clears it.
+ // The operator refreshes the jar (Refresh cookies on /cookies); Recheck clears it.
await xJar(0);
await banner.getByRole("button", { name: "Recheck" }).click();
await expect(banner).toHaveAttribute("data-state", "ok-again", { timeout: 30_000 });
@@ -284,7 +284,7 @@ test("X: a fetch refused for an old jar raises the X banner with the jar's age;
// Three short lines, no lead paragraph: the age, the one action, the job it refused.
await expect(banner.locator("p").first()).toHaveText("X cookies are 3 h old (limit 60 min)");
await expect(banner.getByLabel("X cookies action")).toHaveText(
- "Refresh cookies (or Connect X account) on /settings — then Recheck.",
+ "Refresh cookies (or Connect X account) on /cookies — then Recheck.",
);
await expect(banner).toContainText("Refused an X job on x-other.");
await expect(banner.locator("code")).toHaveCount(0);
diff --git a/editor/e2e/cookies-screen.spec.ts b/editor/e2e/cookies-screen.spec.ts
@@ -0,0 +1,204 @@
+// THE COOKIES SCREEN (/cookies, plans/cookie-screen.md), end to end — over
+// FIXTURES only:
+// - a fixture Firefox store written under the slot's test data
+// (common/social/__fixtures__/firefoxCookieStore.ts), named by
+// cookiesFromBrowser as a profile PATH: no real browser profile is read;
+// - X's Refresh cookies through the test server's fake browser
+// (E2E_FAKE_X_PROFILE_COOKIES_FILE, common/social/fakeXProfileBrowser.ts):
+// synthetic cookies, no browser starts, nothing is asked of X;
+// - Rumble's Check again through the fake yt-dlp, which answers an embed403
+// URL with Rumble's 403 until the spec drops `fake-ytdlp.fresh-cookies`
+// in the channel dir (cookie-alerts.spec's fake).
+// 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 { test, expect, type Page } from "@playwright/test";
+import { resetData, resolvePath, testPaths, 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).
+import { writeFirefoxCookieStore } from "../../common/social/__fixtures__/firefoxCookieStore";
+
+const SLUG = "test-youtube";
+const t = (p: string) => resolvePath(`${testPaths().transcriptsDir}/${p}`);
+const MIN = 60_000;
+
+async function seed(opts: { xDelayMs?: number } = {}) {
+ await resetData("youtube-with-playlist");
+ const now = Date.now();
+ const profile = t("firefox-fixture/cs.default-release");
+ await writeFirefoxCookieStore(profile, [
+ {
+ host: ".rumble.com",
+ name: "cf_clearance",
+ value: "fixture-not-a-real-clearance",
+ creationTime: (now - 40 * MIN) * 1000,
+ lastAccessed: (now - 5 * MIN) * 1000,
+ expiry: Math.floor((now + 50 * MIN) / 1000),
+ },
+ { host: ".youtube.com", name: "SID", value: "fixture-not-a-real-sid", lastAccessed: (now - 3 * 60 * MIN) * 1000 },
+ { host: ".example.com", name: "session", value: "not-a-service" },
+ ]);
+ await writeSettings({
+ minFreeDiskGB: 0,
+ 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 });
+ await writeFile(
+ t(".fake-x-profile-cookies.json"),
+ JSON.stringify({
+ delayMs: opts.xDelayMs ?? 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" },
+ ],
+ }),
+ );
+ // Rumble's alert, raised: two embeds refused on different videos.
+ const since = new Date(now - 30 * MIN).toISOString();
+ await writeFile(
+ t(".service-cookies.json"),
+ JSON.stringify({
+ version: 1,
+ services: {
+ rumble: {
+ service: "rumble",
+ kind: "embed-403",
+ since,
+ lastSeen: since,
+ raisedAt: since,
+ count: 2,
+ videos: ["embed403a", "embed403b"],
+ jobs: [],
+ evidence: {
+ channel: SLUG,
+ videoId: "embed403b",
+ url: "https://rumble.com/vembed403b-second.html",
+ line: "ERROR: [RumbleEmbed] embed403b: Unable to download JSON metadata: HTTP Error 403: Forbidden",
+ },
+ },
+ },
+ lastGood: {},
+ }),
+ );
+}
+
+const row = (page: Page, label: string) => page.getByRole("listitem", { name: `${label} cookies` });
+
+test("one row per service: source, age, alert, and the one button", async ({ page }) => {
+ await seed();
+ 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"]);
+
+ const rumble = row(page, "Rumble");
+ await expect(rumble).toHaveAttribute("data-state", "stale");
+ await expect(page.getByLabel("Rumble cookie alert")).toContainText("Rumble needs fresh cookies: open rumble.com in firefox");
+ await expect(page.getByLabel("Rumble cookie age")).toHaveText(/^clearance issued 40 min ago · expires in (49|50) min$/);
+ await expect(page.getByLabel("Rumble cookie source")).toContainText("(cookiesFromBrowser)");
+ await expect(rumble).toContainText("Open rumble.com in firefox, then Check again.");
+ await expect(page.getByRole("button", { name: "Rumble Check again" })).toBeEnabled();
+
+ await expect(page.getByLabel("YouTube cookie age")).toHaveText("sign-in last used 3 h ago");
+ await expect(page.getByLabel("Odysee cookie age")).toHaveText("No clearance cookie for odysee.com in firefox.");
+ await expect(page.getByRole("button", { name: "Odysee Check again" })).toBeDisabled();
+ 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.getByRole("button", { name: "X Refresh cookies" })).toBeEnabled();
+ await expect(x).not.toContainText("editor's machine");
+
+ // The headed Connect says where its window opens. Never pressed here.
+ const archive = row(page, "archive.today");
+ await expect(page.getByRole("button", { name: "archive.today Connect archive session" })).toBeVisible();
+ await expect(archive).toContainText("Opens a browser window on the editor's machine, not on this device.");
+
+ // Nothing drawn carries a cookie's value.
+ await expect(page.locator("body")).not.toContainText("fixture-not-a-real");
+
+ // /settings' two sections and the dashboard banner point here.
+ await page.goto("/settings");
+ await expect(page.getByLabel("x cookies screen link")).toHaveAttribute("href", "/cookies");
+ await expect(page.getByLabel("archive cookies screen link")).toHaveAttribute("href", "/cookies");
+ await page.goto("/");
+ const banner = page.getByRole("alert", { name: "Rumble cookies" });
+ await expect(banner.getByRole("link", { name: "Cookies" })).toHaveAttribute("href", "/cookies");
+});
+
+test("X Refresh cookies: progress in the row, a second press refused, the result and the jar's age in place", async ({ page, browser }) => {
+ await seed({ xDelayMs: 4000 });
+ await page.goto("/cookies");
+ // A marker that a reload would wipe: the answer must land without one.
+ await page.evaluate(() => ((window as unknown as { __noReload?: number }).__noReload = 1));
+ const refresh = page.getByRole("button", { name: "X Refresh cookies" });
+ await refresh.click();
+ await expect(refresh).toHaveText(/^Refreshing… \d+ s$/);
+
+ // Pressed again here: refused in words, not sent twice.
+ await refresh.click();
+ await expect(page.getByRole("status", { name: "X press result" })).toHaveText(
+ /^X's refresh is already running \(since \d\d:\d\d:\d\d UTC\) — wait for it to finish\.$/,
+ );
+
+ // Pressed from another tab: the server refuses it (the guard is per service, not per tab).
+ const ctx = await browser.newContext();
+ try {
+ const other = await ctx.newPage();
+ await other.goto(`${baseUrl}/cookies`);
+ await expect(other.getByLabel("X running")).toHaveText(/^A refresh is running \(since \d\d:\d\d:\d\d UTC\)\.$/);
+ await other.getByRole("button", { name: "X Refresh cookies" }).click();
+ await expect(other.getByRole("status", { name: "X press result" })).toHaveText(
+ /^X's refresh is already running \(since \d\d:\d\d:\d\d UTC\) — wait for it to finish\.$/,
+ );
+ } finally {
+ await ctx.close();
+ }
+
+ // 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(refresh).toHaveText("Refresh cookies");
+ expect(await page.evaluate(() => (window as unknown as { __noReload?: number }).__noReload)).toBe(1);
+
+ // Remembered: the row's last result after a reload.
+ await page.reload();
+ await expect(page.getByLabel("X last result")).toHaveText("Last refresh just now: Cookies refreshed.");
+});
+
+test("Rumble Check again: still refused with stale cookies; clears once the browser has fresh ones", async ({ page }) => {
+ test.setTimeout(120_000);
+ await seed();
+ await page.goto("/cookies");
+ const check = page.getByRole("button", { name: "Rumble Check again" });
+ await check.click();
+ await expect(page.getByRole("status", { name: "Rumble press result" })).toContainText("Rumble still refused", {
+ timeout: 45_000,
+ });
+ await expect(row(page, "Rumble")).toHaveAttribute("data-state", "stale");
+
+ // The operator opens rumble.com in the browser (the fake's marker).
+ await writeFile(t(`channels/${SLUG}/fake-ytdlp.fresh-cookies`), "fresh");
+ await check.click();
+ await expect(row(page, "Rumble")).toHaveAttribute("data-state", "fine", { timeout: 45_000 });
+ await expect(page.getByRole("status", { name: "Rumble press result" })).toContainText("Rumble answered cleanly");
+ await expect(page.getByLabel("Rumble cookie alert")).toContainText("Rumble cookies OK again");
+});
+
+test("at a phone's width the page does not scroll sideways", async ({ page }) => {
+ await seed();
+ await page.setViewportSize({ width: 390, height: 844 });
+ await page.goto("/cookies");
+ await expect(row(page, "Rumble")).toBeVisible();
+ const { scroll, client } = await page.evaluate(() => ({
+ scroll: document.documentElement.scrollWidth,
+ client: document.documentElement.clientWidth,
+ }));
+ expect(scroll).toBeLessThanOrEqual(client);
+ const box = await page.getByRole("button", { name: "Rumble Check again" }).boundingBox();
+ expect(box && box.x + box.width).toBeLessThanOrEqual(390);
+});
diff --git a/editor/e2e/privacy-audit.spec.ts b/editor/e2e/privacy-audit.spec.ts
@@ -173,9 +173,12 @@ test.afterAll(async () => {
test("byte identity: absent and explicit defaults render the same HTML, and the same /storage text", async ({ browser }) => {
const statics = appRoutes(APP_DIR).filter((r) => !r.dynamic).map((r) => r.pattern);
+ // An ISO timestamp is the clock, not the privacy setting: a page that says
+ // when it read (/cookies' readAt) is compared with its times blanked.
+ const ISO = /\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z/g;
const fetchHtml = async (r: string) => {
const res = await fetch(`${baseUrl}${r}`, { redirect: "manual" });
- return `${res.status}\n${await res.text()}`;
+ return `${res.status}\n${(await res.text()).replace(ISO, "<time>")}`;
};
const storageText = async () => {
const ctx = await browser.newContext();
@@ -232,6 +235,8 @@ test("byte identity: absent and explicit defaults render the same HTML, and the
await settle();
test.info().annotations.push({ type: "byte-identity", description: `${compared} of ${statics.length} static routes compared; volatile, skipped: ${volatile.join(" ") || "none"}` });
expect(compared).toBeGreaterThan(statics.length / 2);
+ // /cookies stamps its rows with the time read; blanked, it compares.
+ expect(volatile).not.toContain("/cookies");
expect(bText).toBe(aText);
});
diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts
@@ -73,6 +73,11 @@ export function archiveTodayOriginFile(transcriptsDir: string): string {
return join(transcriptsDir, ".fake-archive-today-origin");
}
+/** The synthetic cookies a slot's fake "Refresh cookies" browser hands back (common/social/fakeXProfileBrowser.ts; cookies-screen.spec). */
+export function xProfileCookiesFixtureFile(transcriptsDir: string): string {
+ return join(transcriptsDir, ".fake-x-profile-cookies.json");
+}
+
/** The saved thread pages a slot's forum fetcher reads (forumFixtureLoader.ts; forum-resume.spec). */
export function forumFixtureDir(transcriptsDir: string): string {
return join(transcriptsDir, ".forum-fixture");
@@ -245,6 +250,9 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env)
// The forum fetcher's saved pages (forum-resume.spec): the slot's own
// directory (common/social/forumFixtureLoader.ts).
editorEnv.E2E_FORUM_FIXTURE_DIR = forumFixtureDir(paths.transcriptsDir);
+ // The fake browser Refresh cookies reads the X profile through while the
+ // file exists (common/social/fakeXProfileBrowser.ts; cookies-screen.spec).
+ editorEnv.E2E_FAKE_X_PROFILE_COOKIES_FILE = xProfileCookiesFixtureFile(paths.transcriptsDir);
// The same for the stub umtool find-clips.spec starts (lib/umtoolUrl.ts).
editorEnv.E2E_UMTOOL_ORIGIN_FILE = umtoolOriginFile(paths.transcriptsDir);
// settings.privacy's opt-in rule files (demo epic D4, useSourceRules): the
diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts
@@ -58,6 +58,11 @@ import { currentSlot } from "./e2e/testPaths";
// reads in place of a browser, with no pause
// (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
+// hands back while it exists — no browser starts,
+// nothing asks X (common/social/fakeXProfileBrowser.ts;
+// cookies-screen.spec); inert without E2E_TEST_ROUTES
// E2E_UMTOOL_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec
// writes its stub umtool's loopback origin into,
// which Find clips then posts to
diff --git a/plans/cookie-screen.md b/plans/cookie-screen.md
@@ -0,0 +1,62 @@
+# The Cookies screen — `/cookies`, one row per service, one button each
+
+Operator, 2026-11-16: "Make a dedicated screen for cookie refreshes like Rumble and X, because sometimes the
+settings screen takes too long to load when most of the time I'm going for this one operation over and over."
+
+The nav's third recorded exception (editor/app/lib/nav.ts): one operation pressed over and over, from a phone.
+
+## Why /settings is slow, and what /cookies reads instead
+
+Measured on the live editor (read-only GETs, load average 19): /settings rendered on the server in 0.2–0.6 s,
+the dashboard in 4.7 s and /jobs in 5.5 s. The server work is not the cost. The cost is what /settings ships and
+redraws:
+
+- the whole parsed settings object (122 KB, 110 KB of it `autoQueue`) as SettingsForm's `initial`: 153 KB of
+ RSC and 238 KB of HTML, for a 480-line form to hydrate on a phone;
+- `getSettings()` three times per render (layout metadata, layout, page), each a synchronous parse;
+- a tree re-render whenever the pulse moves (any job change).
+
+/cookies (`editor/app/lib/cookieStatus.ts`) reads only what its rows show: `.service-cookies.json` (through
+`loadCookieAlerts`, which carries X's jar age), settings parsed once for `cookiesFromBrowser` and `social.x`
+(nothing of it sent to the browser), a stat of X's jar, archive.today's and each forum host's `session.json`,
+one channel config per yt-dlp service (its last clean request's channel), and one name-only read of the
+browser's cookie store, cached 5 min. It is exempt from AutoRefresh and polls its own `cookieStatus` view.
+
+## The rows (`common/lib/cookieStatus.ts`)
+
+| Service | Age from | The one button |
+|---|---|---|
+| X, connected profile | the exported jar's mtime | Refresh cookies (`refreshXCookiesAction`); X's alert is rechecked from disk after it |
+| X, no profile | — | Connect X account (headed) |
+| X, browser login | Firefox's x.com `auth_token` last sent | Check again (recheck "x": no request) |
+| Rumble, Odysee | Firefox's `cf_clearance` issued / expiry | Check again (`recheckServiceCookiesAction`) |
+| YouTube | Firefox's sign-in cookies last sent | Check again |
+| archive.today | the last Connect | Connect archive session (headed) |
+| each forum host | the last Connect | Connect forum session at the last thread met (headed) |
+
+The browser read (`common/lib/browserCookieAge.ts`) follows X's precedent: a private copy of the store and its
+WAL, `SELECT host, name, creationTime, lastAccessed, expiry, originAttributes` and never the value (a test fails
+if it does), no cookie name logged, cached 5 min, a failure shown as "unknown". A headed Connect's row says the
+window opens on the editor's machine.
+
+## One press at a time (`editor/app/lib/cookieRefreshGuard.ts`)
+
+Every refresh, connect and recheck — /cookies, /settings, the dashboard, a forum channel's Connect, ops
+`recheck-service` — goes through `withCookieAction`: a second press for the service while one is in flight, or
+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`).
+
+## Ops
+
+`pnpm ops get cookies [fresh]` — the rows, read-only. Check again is `recheck-service`; Refresh cookies and the
+Connects stay clicks (a refresh loads x.com; a Connect opens a window).
+
+## Tests
+
+Unit: `common/lib/browserCookieAge.test.ts`, `common/lib/cookieStatus.test.ts`,
+`common/social/fakeXProfileBrowser.test.ts`, `common/lib/serviceCookies-server.test.ts` (the last press),
+`editor/app/lib/cookieRefreshGuard.test.ts`, `editor/app/api/ops/_read.test.ts`, the view route test, nav.test,
+`scripts/archilyzer-ops.test.mjs`. e2e: `editor/e2e/cookies-screen.spec.ts` — a fixture Firefox store, Refresh
+cookies through the test server's fake browser (`E2E_FAKE_X_PROFILE_COOKIES_FILE`, inert unless
+`E2E_TEST_ROUTES=1` and the file is inside the slot's transcriptsDir), Check again through the fake yt-dlp, a
+phone's width.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -143,6 +143,7 @@
// pnpm ops get tags eva-collab
// pnpm ops get services
// pnpm ops get x-session
+// pnpm ops get cookies [fresh]
// pnpm ops recheck-service --json '{"service":"rumble"}'
// pnpm ops recheck-service --json '{"service":"x"}'
// pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'
@@ -320,6 +321,10 @@ const GETTERS = {
// Render mode (AGENTS.md "Render mode"): whether a render holds the machine,
// for what, since when, and which lanes it held. No token.
"render-mode": () => "/api/ops/render-mode",
+ // The /cookies screen's rows: per service its cookie source, age, alert
+ // state and last press. `fresh` re-reads the browser's cookie store (names
+ // and times only) instead of the 5-minute cache.
+ cookies: (arg) => (arg === "fresh" ? "/api/ops/cookies?fresh=1" : "/api/ops/cookies"),
// The X login an X job would use and whether one would start now: the
// source, the exported jar's age, social.x.maxCookieAgeMinutes and the
// network guard's verdict (common/jobs/networkGuard.ts xSessionReport).
@@ -396,6 +401,7 @@ const GET_ARG_OPTIONAL = new Set([
"scheduler",
"services",
"x-session",
+ "cookies",
"x-run",
"generation-usage",
"render-mode",
@@ -971,6 +977,9 @@ export function parseArgs(argv) {
error: `get ${noun} does not take ${stray.map((f) => `--${f}`).join(", ")}`,
};
}
+ if (noun === "cookies" && positional[2] && positional[2] !== "fresh") {
+ return { error: `get cookies takes "fresh" or nothing, not "${positional[2]}"` };
+ }
if (noun === "channel" && used.has("limit") && !leads) {
return { error: "get channel: --limit goes with --leads" };
}
@@ -1147,6 +1156,7 @@ export function usage() {
" pnpm ops get kept-originals [<slug>]",
" pnpm ops get services",
" pnpm ops get x-session [<slug>]",
+ " pnpm ops get cookies [fresh]",
" pnpm ops get x-run [<run id>]",
" pnpm ops get cleanup <slug>",
" pnpm ops get speakers",
@@ -1246,6 +1256,17 @@ export function usage() {
" channel whose own cookiesFromBrowser may decide the source. Nothing is",
" asked of X: a refresh is Refresh cookies / Connect X account on",
" /settings. Ask it before queueing fetch-posts or capture-posts on X.",
+ "get cookies [fresh] is the /cookies screen's rows, one per service the",
+ " editor reads cookies for (x, rumble, youtube, odysee, archive.today, each",
+ " forum host): source (drawn through settings.privacy), age (ageVerb, ageAt,",
+ " ageMinutes; ageUnknown when it cannot be read), state (stale | fine |",
+ " unknown) with the alert's sentence, todo (what to do by hand), button",
+ " (the row's one press: refresh | connect | recheck; headed: a window on",
+ " the editor's machine), last (the last press and how it ended) and",
+ " running. Nothing is asked of any service; \"fresh\" re-reads the",
+ " browser's cookie store (names and times only, never a value) instead of",
+ " the 5-minute cache. Check again is recheck-service; Refresh cookies and",
+ " the Connects are clicks on /cookies.",
"get x-run [<run id>] is the X run as /review's X run console shows it:",
" the latest run (or the one named) — each channel's status (queued,",
" running, done with its new posts, deferred, failed), \"summary\" (\"N",
@@ -1412,12 +1433,14 @@ export function usage() {
' Waits for it: {jobId, result: "clean" | "stale" | "failed", message};',
" \"clean\" clears the alert (and a yt-dlp service's backoff, as any clean",
' request). For "x" it sends X NO request: clean when the login on disk',
- ' was renewed after the alert (Refresh cookies on /settings) — for a',
+ ' was renewed after the alert (Refresh cookies on /cookies) — for a',
' jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The',
' editor also rechecks by itself on a timer',
' (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off;',
' `pnpm ops settings',
' --json \'{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}\'`).',
+ ' Asked while a recheck or another press for the service runs (a click,',
+ ' the dashboard\'s, the timer\'s): refused, 409 {busy: true}, never queued.',
'dismiss-service clears a service\'s cookie alert by hand: {"service"}.',
'rerun-service-jobs retries every job a service\'s cookie alert stopped, once',
' it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them.',
@@ -1828,7 +1851,7 @@ export function usage() {
" channel the jar is checked again: once it is past",
" social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and",
" the rest are DEFERRED until the next refresh. It never refreshes the",
- ' jar: Refresh cookies on /settings, then {"resume": "<run id>"} runs the',
+ ' jar: Refresh cookies on /cookies, then {"resume": "<run id>"} runs the',
" deferred channels (the console's Resume; a Retry of the job is the",
" same). One run at a time; refused before a job on a stale jar (a new",
" run's channels are kept, deferred). An interrupted run is not resumed",
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -959,6 +959,17 @@ test("get services is a GET on its route; recheck/dismiss/rerun are POSTs named
}
});
+// THE COOKIES SCREEN'S ROWS: read-only, with an optional fresh re-read.
+test("get cookies is a GET on its route; fresh re-reads; anything else is refused", () => {
+ const g = parseArgs(["get", "cookies"]);
+ assert.equal(g.method, "GET");
+ assert.equal(g.path, "/api/ops/cookies");
+ assert.equal(parseArgs(["get", "cookies", "fresh"]).path, "/api/ops/cookies?fresh=1");
+ assert.match(parseArgs(["get", "cookies", "stale"]).error ?? "", /get cookies takes "fresh" or nothing/);
+ assert.match(usage(), /pnpm ops get cookies \[fresh\]/);
+ assert.match(usage(), /never a value/);
+});
+
// X SESSION FRESHNESS: what an agent asks before it queues an X fetch.
test("get x-session is a GET on its route, with an optional channel", () => {
const g = parseArgs(["get", "x-session"]);