Archilyzer · Source

archilyzer

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

commit 39369093937c08fd1c58b10a2f6e9087f45d4d54
parent 5bd83a4ceb2bf7b30eb3db5d65cdce84b425d11c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 16 Nov 2026 10:31:13 -0500

/cookies: a fast screen for cookie refreshes, one row per service, one button each

The operator, 16 Nov: "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."

- editor/app/cookies: one row per service the editor reads cookies for (X,
  Rumble, YouTube, Odysee, archive.today, each forum host): the source
  (through settings.privacy), the age (ticking), the alert stale/fine/unknown
  with its sentence, the last press, and ONE button -- Refresh cookies (X,
  then X's alert rechecked from disk), Check again (the existing recheck) with
  the site to open in one line, or a Connect that says its window opens on the
  editor's machine. A press shows progress and its answer in place and swaps
  in the rows it carries; a second press is refused in words.
- Fast: editor/app/lib/cookieStatus.ts reads only what the rows show -- not
  the whole settings object /settings ships to its form (153 KB of RSC);
  AutoRefresh leaves the page alone, it polls its own `cookieStatus` view.
- Nav: Machine -> Cookies (the third recorded exception, nav.ts says why).
  The dashboard's cookie banners and /settings' X and archive sections link it.
- `pnpm ops get cookies [fresh]` (GET /api/ops/cookies): the rows, read-only.
  COMMANDS.md, ENVIRONMENT.md and SETTINGS.md regenerated.
- e2e/cookies-screen.spec.ts over fixtures: a fixture Firefox store, Refresh
  cookies through the test server's fake browser, Check again through the fake
  yt-dlp, a phone's width. plans/cookie-screen.md, OPERATING.md, CHANGELOG.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 16++++++++++++++--
MENVIRONMENT.md | 1+
MOPERATING.md | 20++++++++++++++++++--
MSETTINGS.md | 2+-
Mcommon/jobs/pacingGuard.test.ts | 2+-
Mcommon/views/names.ts | 5+++++
Meditor/CHANGELOG.md | 19+++++++++++++++++++
Meditor/app/api/ops/_read.test.ts | 20+++++++++++++++++++-
Aeditor/app/api/ops/cookies/route.ts | 28++++++++++++++++++++++++++++
Meditor/app/api/ops/sync/route.test.ts | 2+-
Meditor/app/api/view/[name]/route.test.ts | 2+-
Meditor/app/api/view/views.ts | 6++++++
Meditor/app/components/AutoRefresh.tsx | 4+++-
Meditor/app/components/dashboard/CookieAlertsPanel.tsx | 19++++++++++---------
Aeditor/app/cookies/CookiesBoard.tsx | 180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/cookies/actions.ts | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/cookies/page.tsx | 22++++++++++++++++++++++
Aeditor/app/lib/cookieStatus.ts | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/lib/nav.test.ts | 10++++++----
Meditor/app/lib/nav.ts | 10++++++++++
Meditor/app/settings/components/ArchiveSessionSection.tsx | 6++++++
Meditor/app/settings/components/XSessionSection.tsx | 7+++++++
Aeditor/e2e/cookies-screen.spec.ts | 204+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aplans/cookie-screen.md | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 25+++++++++++++++++++++++--
Mscripts/archilyzer-ops.test.mjs | 11+++++++++++
26 files changed, 888 insertions(+), 25 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" — "&lt;tts engine&gt;:&lt;stock voice&gt;" (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": {"&lt;top-level key&gt;": 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"} -&gt; {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}}}'`). 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"} -&gt; {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 &lt;platform&gt;" (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/&lt;id&gt;/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": "&lt;run id&gt;"} 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": "&lt;run id&gt;"} 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/&lt;id&gt;/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/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. 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/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/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/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> </> ) : ( <> @@ -73,14 +78,10 @@ function AlertCard({ </Link> </> )} - {(alert.family === "archive" || alert.family === "x") && ( - <> - {" · "} - <Link href="/settings" className="underline underline-offset-2 hover:text-foreground"> - Settings - </Link> - </> - )} + {" · "} + <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,101 @@ +"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; +}; + +export async function cookieStatusAction(fresh = false): Promise<CookieStatusPayload> { + return loadCookieStatus(getPaths(), { fresh: fresh === true }); +} + +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/cookieStatus.ts b/editor/app/lib/cookieStatus.ts @@ -0,0 +1,129 @@ +// 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 { 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; + const config = 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/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&apos;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&apos;s cookies (and every other service&apos;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/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/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,7 +1433,7 @@ 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;', @@ -1828,7 +1849,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"]);