# YouTube — play videos with no key, read a channel's numbers with no setup

> YouTube on a page: playing videos, playlists and a channel's uploads in YouTube's own player, which needs no key and no setup; and channel stats on the platform's key with no key for the owner to create: ctx.youtube.fetch in backend.js and its daily unit budget, resolving a channel from a handle or URL, reading videos through the uploads playlist, evening and morning samples compared into a 9 a.m. overnight recap pushed with ctx.notify, 28-day sample retention, and labeling the numbers an API key cannot see

Source: https://good.vibes.diy/docs/reference/youtube

Two different asks share the name. **Playing** a video, a playlist or a
channel's uploads inside the page needs no key, no backend and no setup: it is
YouTube's own player in a frame, and section 0 is all of it. **Counting** a
channel (subscribers, views, which videos picked up overnight) is the **YouTube
Data API v3**, read from `backend.js` with `ctx.youtube.fetch`. Vibes holds the
key, so the owner pastes a channel link and the numbers arrive; sections 1–9 are
the recipe that keeps the budget comfortable and the numbers honest. Build the
first for "show our videos", "my band's page", "a playlist of clips"; build the
second when the ask is about the numbers.

## 0. Play a video: no key at all

A pasted YouTube link becomes a player through the privacy-enhanced host,
`www.youtube-nocookie.com`, which sets no cookie until the person presses play.
Parse the link into an id and build the `src`; the frame itself is the shared
`EmbedFrame`.

```jsx
// A share link → an embed src, or null when the link is not one YouTube can play here.
function youtubeEmbedSrc(link) {
  let u;
  try { u = new URL(link.trim()); } catch { return null; }
  const host = u.hostname.replace(/^www\.|^m\./, "");
  const list = u.searchParams.get("list");
  const start = (u.searchParams.get("t") ?? u.searchParams.get("start") ?? "").match(/^(\d+)s?$/)?.[1];
  const tail = start ? `?start=${start}` : "";
  let id = null;
  if (host === "youtu.be") id = u.pathname.slice(1);
  else if (host === "youtube.com" || host === "music.youtube.com") {
    const channel = u.pathname.match(/^\/channel\/UC([\w-]{22})(?:\/|$)/);
    if (channel) return `https://www.youtube-nocookie.com/embed/videoseries?list=UU${channel[1]}`; // the channel's uploads
    if (u.pathname === "/playlist" && /^[\w-]+$/.test(list ?? "")) return `https://www.youtube-nocookie.com/embed/videoseries?list=${list}`;
    id = u.searchParams.get("v") ?? u.pathname.match(/^\/(?:shorts|embed|live)\/([\w-]{11})/)?.[1] ?? null;
  }
  if (!id || !/^[\w-]{11}$/.test(id)) return null;
  return `https://www.youtube-nocookie.com/embed/${id}${tail}`;
}

// The player, once the link has parsed:
// <EmbedFrame src={youtubeEmbedSrc(video.link)} title={video.title} />
```

- A **channel's uploads** play as one playlist: its id is the channel id with
  `UC` turned into `UU`. Only a `/channel/UC…` link carries that id; an
  `@handle` link is turned into the id by one backend call (section 3), so a
  page that only plays videos asks for a video or playlist link, or the
  channel's `/channel/` address.
- The title and thumbnail come from YouTube's keyless oEmbed endpoint,
  `https://www.youtube.com/oembed`, read once when the link is added.
- Under each player, "Watch on YouTube" links the original
  `https://www.youtube.com/watch?v=<id>` (the shared link-out rule).
- None of this touches the Data API, so a page that only plays videos needs
  nothing from the sections below.

## 1. `ctx.youtube.fetch`: the numbers with nothing to set up

Every YouTube Data API call is made in backend.js with ctx.youtube.fetch, which carries the platform's key, so the app asks its owner for no key and App.jsx never calls googleapis.com.

```js
const res = await ctx.youtube.fetch("/channels?part=snippet,statistics,contentDetails&forHandle=@name");
const body = await res.json(); // Google's own JSON, Google's own status
```

- The argument is a path rooted at the v3 resource (`/videos?part=statistics&id=a,b`)
  or a full `https://www.googleapis.com/youtube/v3/…` URL. Leave `key=` off: the
  platform adds its own.
- It reads `channels`, `videos`, `playlistItems`, `playlists` and
  `commentThreads`, with `GET`, 1 unit each. The first four answer every
  public-numbers question a channel app asks; `commentThreads` reads what
  viewers wrote (`/commentThreads?part=snippet&videoId=<id>&maxResults=100&order=relevance&textFormat=plainText`,
  each item's `snippet.topLevelComment.snippet.textDisplay`), for an app that
  shows what people are talking about.

What viewers say comes from commentThreads through ctx.youtube, read for the few videos on screen and kept as counted words, never as the comment text itself.

- It resolves a normal `Response`. A Google error (`quotaExceeded`, a bad
  `part`) arrives as a `Response` with Google's status and `error` body, so
  `res.ok` and `await res.json()` work as they do for any fetch.
- When the platform declines a call, the promise rejects with an Error whose
  `reason` names why: `over_budget` (this app's units for the day are spent),
  `unmodeled_endpoint` (a resource outside the five), `not_available` (this
  deployment has no YouTube key right now), `unsupported_method`,
  `invalid_path`, `body_too_large`, `upstream_error`.
- `await ctx.youtube.status()` answers `{ available, unitsLeftToday, dailyUnits }`
  and spends nothing.

A YouTube stats app has no Setup item: there is no key to create and no Secrets step, so no page of the app asks for YOUTUBE_API_KEY.

The owner's first step is the app's own first screen: paste the channel link,
press **Track**, and the first readings land within the minute.

## 2. A daily budget per app

Each app spends from its own budget of **2,000 units a day**, counted in UTC.
Every call to the five resources costs 1 unit. That is generous for one
channel: the overnight recap in section 5 spends about 110 units a day on a
500-video channel.

When ctx.youtube refuses over_budget, the app keeps its last readings on screen and says sampling resumes at midnight UTC.

Write the moment down (a `status` doc with `resumesAt`), finish the tick
without writing a sample, and let the page say *Today's readings are in; the
next ones arrive after midnight UTC* with the local time beside it. The first
sample that lands after the reset deletes the `status` doc, and the page reads
a `status` whose `resumesAt` has passed as no status at all. Google's own
`quotaExceeded` (a 403 that reaches the app) pauses the same way, until
Google's reset at midnight Pacific.

### The `/_api` routes are the second door

A handler that calls YouTube on every request lets a visitor's refresh button
spend the app's units.

Live YouTube calls are made only by the scheduled tick or for the vibe owner; every other visitor is served from the stored samples, so a stranger can never spend the app's daily budget.

The owner gate is one comparison at the top of the `fetch` handler
(`isOwner`). Everyone else is answered from the docs the tick already wrote,
with `source: "stored"` and the time they were taken, so the page can say *as
of 7:58 a.m.* instead of implying the numbers are live.

That visitor read happens on the `fetch` lane, which reads nothing for an
anonymous caller and cannot read an access-fn-bound database until the
backend opts in, so the recipe declares
`config.fetch.unfilteredReads = { dbs: ["youtube"], why: ... }` (see the
backend docs). The docs it serves hold only a channel's public numbers.

## 3. Resolve a channel from whatever the person pastes

People arrive with a handle, a URL, or a raw id. Normalize before you call:

| What they paste | What you call |
| --- | --- |
| `UC…` (24 chars, starts `UC`) | `/channels?id=UC…` |
| `@handle`, or `youtube.com/@handle` | `/channels?forHandle=@handle` |
| `youtube.com/channel/UC…` | `/channels?id=UC…` |
| `youtube.com/user/name` (legacy) | `/channels?forUsername=name` |

Ask for `part=snippet,statistics,contentDetails`. `snippet` carries the title,
the `@handle` (`customUrl`) and thumbnails; `statistics` carries
`subscriberCount`, `viewCount`, `videoCount` and `hiddenSubscriberCount`;
`contentDetails.relatedPlaylists.uploads` is the uploads playlist id the video
list comes from. An empty `items` array means no channel matched: keep the input
on screen with *No channel by that name — try the link from the channel page*.

## 4. Video performance through the uploads playlist

Read videos through the uploads playlist (playlistItems, then videos?part=statistics) and never through search, which costs 100 quota units per call.

`ctx.youtube` offers the two that cost 1 unit each:

```
/playlistItems?part=contentDetails&playlistId=<uploads>&maxResults=50&pageToken=<next>
/videos?part=snippet,statistics&id=<up to 50 comma-joined ids>
```

The uploads playlist lists newest first. A full catalog is pages of 50 until
`nextPageToken` runs out (stop at 500 videos), then `videos` in batches of 50;
the latest uploads are one `playlistItems` page with `maxResults=10` and one
`videos` call.

Counts arrive as strings. `Number(stats.viewCount ?? 0)` before you do arithmetic.

## 5. The overnight recap: sample, compare, push

"Which video picked up overnight" is a comparison between two readings, so the
recipe is a schedule of samples:

- **Full catalog** (up to 500 videos): once when the owner presses Track, every
  **evening** (9 p.m. in the owner's time zone) and every **morning** (7 a.m.).
  Each full reading also re-reads the channel (1 unit) and saves its
  subscribers, views and video count, so the totals on screen move with it.
- **Latest 10 uploads**: every hour, so a new video's first day is charted
  closely.
- **The recap**: at 9 a.m., compare the morning sample with last evening's and
  push the owner the winner.

```js
export const config = { scheduled: { interval: "1h" } };
```

One doc per sample, under a fixed `_id` per slot so a tick that runs twice
writes once:

```js
{
  _id: `sample-${channelId}-${day}-morning`, // or -evening, -setup, -hour-07
  type: "sample",
  kind: "full",                               // or "recent"
  channelId,
  takenAt: "2026-11-04T07:58:12.000Z",
  views: { [videoId]: 1234 },                 // one number per video
  titles: { [videoId]: "Title" },
}
```

Compare sample to sample, and name the window the two samples actually span.

A recap that says *between 9:02 p.m. and 7:58 a.m.* reads true; one that says
*overnight* about a sample the tick took at noon does not. Take both times from
`takenAt`.

A video first seen in the later sample is never ranked against zero.

It was published inside the window, so its whole count is new, not gained;
list it as *new since last night* beside the ranking instead.

The push is one `ctx.notify` to the owner, keyed by the day so a repeated tick
delivers once:

```js
await ctx.notify({
  toHandle: ctx.appInfo.ownerHandle,
  body: `"${title}" gained ${gained.toLocaleString()} views between 9:02 p.m. and 7:58 a.m.`,
  dedupeKey: `recap-${day}`,
  path: `#recap-${day}`,
});
```

Keep the recap as a doc (`type: "recap"`) as well, so the app's own screen
shows every morning's winner. Stamp it `deliveredAt` only after `ctx.notify`
succeeds: a tick that finds a recap without `deliveredAt` sends it again, and
the `dedupeKey` keeps a retry from reaching the owner twice.

Samples older than 28 days are deleted by the tick, because YouTube's developer policy keeps stored API data fresh for 28 days when the channel has not authorized the app.

The recap only ever needs last night's pair, and the chart reads well over four
weeks. Recap docs carry titles and view counts too, so the same sweep deletes a
recap once its `to` reading is older than 28 days, and the channel totals once
their `refreshedAt` is.

## 6. Label what an API key cannot see

An API key reads public data.

Watch time, revenue, impressions, traffic sources and demographics need YouTube Analytics with OAuth and are labeled "Not available with an API key", never shown as zero.

Give them their own section in the UI with that label, so the owner sees the
boundary instead of believing the channel earned nothing. YouTube Studio shows
them, and they settle 48–72 hours after the fact.

Three more honest labels:

- `statistics.hiddenSubscriberCount === true` means the channel hides the
  number. Show "hidden by the channel", not `0`.
- YouTube rounds public subscriber counts (three significant figures above
  1,000). Put "YouTube rounds public subscriber counts" in a caption under the
  subscriber tile.
- `likeCount` is absent when the channel hides likes, and `commentCount` is
  absent when comments are off. Render "hidden" for an absent field.

## 7. Errors keep their reason

Each answer has its own words:

- `over_budget` (a refusal) — *Today's readings are in; the next ones arrive
  after midnight UTC.*
- `quotaExceeded` (Google's 403) — YouTube's own daily quota for Vibes is
  spent; same words, same keep-the-last-readings behavior.
- `not_available` (a refusal) — *Channel numbers are taking a short break;
  your saved readings are all here.*
- anything else — show the API's own `error.message`.

## 8. When an app outgrows its daily units

Almost no app does: one channel's recap spends about a twentieth of the
budget. An app that tracks dozens of channels can read with the owner's own
Google Cloud key instead: the owner saves it in Settings → Secrets as
`YOUTUBE_API_KEY`, and backend.js calls `https://www.googleapis.com/youtube/v3/…`
with `ctx.fetch`, adding `key=` from `ctx.secrets`, exactly as the owner-key
services do. Build it that way only when the app's own numbers ask for it.

## 9. What commenters are talking about

One page of a video's top-level comments, the most relevant first, as plain
text:

```js
const res = await ctx.youtube.fetch(
  `/commentThreads?part=snippet&videoId=${videoId}&maxResults=100&order=relevance&textFormat=plainText`
);
```

Each item's words are `snippet.topLevelComment.snippet.textDisplay`, with
`likeCount` beside them; `nextPageToken` reads the next 100. A page is **1 unit**,
so one page each for a channel's 10 latest uploads is 10 units a day.

A video whose comments are turned off answers commentThreads with a 403 whose reason is commentsDisabled; the app labels that video "Comments are off" and moves on, never treating it as an error.

```js
if (res.status === 403 && (await res.clone().json()).error?.errors?.[0]?.reason === "commentsDisabled") {
  return { videoId, commentsOff: true };
}
```

Themes across a channel's recent videos come from the daily job, in one
`ctx.callAI` call (the backend docs' server-side AI call, 5 calls and about
64k characters per run):

1. Once a day in the scheduled tick (the morning full reading in section 5
   already has the latest uploads), read one comment page for each of the
   5–10 newest videos.
2. Keep a compact sample in memory for this run only: the 20 most-liked
   comments per video, each cut to 200 characters. Ten videos stay near 40k
   characters.
3. Ask `ctx.callAI` with a `schema` for 3–5 themes, each with exactly three
   fields: `label` (a few words), `summary` (one sentence) and `videoIds` (the
   ids of the videos whose comments carry it). Then `JSON.parse` the string it
   returns.
4. Store the themes (``_id: `themes-${channelId}-${day}` ``, `type: "themes"`)
   beside a `videos` list of `{ id, title, comments }` for the videos read
   (`comments` is the number of comments read for that video), and
   `commentsOff`, the list of ids of videos with comments turned off. A
   comment count belongs to a video in that list, never to a theme. The comment text itself stays in the
   run and is never written, and the 28-day sweep in section 5 deletes theme
   docs with the samples.

Every theme names the videos it came from: the ctx.callAI schema asks for videoIds on each theme, and the app shows those videos' titles under the theme.
That link is the whole point of a theme ("people love the new intro" is useful
when it says which uploads), and the schema is the only place it can be made:
a theme the model returned without ids cannot be matched to its videos later.

```js
const themes = JSON.parse(await ctx.callAI(
  `Viewer comments on a YouTube channel's latest videos, grouped by video id:\n${JSON.stringify(sample)}\n` +
  "Name the 3-5 things viewers talk about most. For each, list the ids of the videos whose comments carry it.",
  { schema: { properties: { themes: { type: "array", items: { type: "object", properties: {
    label: { type: "string" }, summary: { type: "string" }, videoIds: { type: "array", items: { type: "string" } },
  }, required: ["label", "summary", "videoIds"] } } }, required: ["themes"] } }
)).themes;
await ctx.db.put({ _id: `themes-${channelId}-${day}`, type: "themes", channelId, day, themes, videos, commentsOff });
```

In `App.jsx`, each theme card lists its videos by title, read from the same
doc, so a viewer sees at a glance which uploads the theme is about:

```jsx
const titleOf = Object.fromEntries((doc.videos ?? []).map((v) => [v.id, v.title]));
{(doc.themes ?? []).map((t) => {
  const from = (t.videoIds ?? []).map((id) => titleOf[id]).filter(Boolean);
  return (
    <section key={t.label}>
      <h3>{t.label}</h3>
      <p>{t.summary}</p>
      {from.length > 0 && <small>From: {from.join(", ")}</small>}
    </section>
  );
})}
```

A failed `ctx.callAI` throws: keep yesterday's themes on screen and try again
on the next morning's tick. Only the tick spends units and AI credits.

### The themes are the creator's; a visitor meets the app

The themes are the creator's brief, read by the creator and the friends they add: the fetch handler's visitor branch never reads a themes doc, and `access.js` routes each `themes` doc to the creator's own `user:<handle>` channel.

The scheduled tick writes as the app's owner, so the `themes` branch routes the
doc to `user:${user.userHandle}` and the access skill's `member` record shares it
with a friend. Keep `themes` out of the database that
`config.fetch.unfilteredReads` names: that one holds the channel's public numbers.

A visitor who is not the creator or a friend they added sees the app's own welcome: what it does and whose it is, in plain words, with a link to make their own; the channel form and the first-brief empty state are the creator's alone.

The visitor branch answers with who made the app, so the page can say it:

```js
if (!isOwner) {
  // The channel's public numbers may ride here; the themes stay in the creator's brief.
  return json({ ok: true, owner: false, ownerHandle: ctx.appInfo.ownerHandle, appSlug: ctx.appInfo.appSlug });
}
```

The page shows the themes it can read (the creator's, or a friend's view of
them), the channel form to the creator, and to everyone else a welcome built
from that answer. "Make your own" is the remix link: it opens a copy of this app
at a new address, with records of its own, ready for the visitor's channel. A
signed-out visitor also gets the sign-in ask, in case the app is theirs; a
`viewerLapsed` creator gets the sign-back-in nudge instead of the welcome.

```jsx
function VisitorWelcome({ ownerHandle, appSlug }) {
  const { viewer, viewerLapsed, requestLogin } = useViewer();
  return (
    <Stack>
      <Heading>Morning comment themes</Heading>
      <Text>
        Every morning this app sorts the comments on <ViewerTag userHandle={ownerHandle} />'s latest
        videos into a few themes, a brief for them and the friends they share it with.
      </Text>
      <a href={`https://vibes.diy/remix/${ownerHandle}/${appSlug}?skipChat=true`} target="_blank" rel="noopener">
        Make your own for your channel
      </a>
      {!viewer && (
        <Button type="button" variant="quiet" onClick={() => requestLogin()}>
          {viewerLapsed ? "Sign back in to read your brief" : "Is this yours? Sign in to read your brief"}
        </Button>
      )}
    </Stack>
  );
}
```

## Complete backend.js

### `backend.js`
```js app=youtube-recap
export const config = {
  scheduled: { interval: "1h" },
  // Visitors read the stored samples and recaps on the fetch lane, which reads nothing for a caller
  // with no session unless the db is named here. The docs hold only public channel numbers.
  fetch: { unfilteredReads: { dbs: ["youtube"], why: "serves the channel's public readings to visitors" } },
};

const DB = "youtube";
const FULL_CATALOG_LIMIT = 500;
const EVENING_HOUR = 21;
const MORNING_HOUR = 7;
const RECAP_HOUR = 9;
const KEEP_DAYS = 28;

/** One Data API read. Google's errors carry their reason; ctx.youtube's refusals already do. */
async function yt(ctx, path) {
  const res = await ctx.youtube.fetch(path);
  const body = await res.json().catch(() => null);
  if (res.ok && body) return body;
  const err = new Error(body?.error?.message ?? `YouTube answered ${res.status}`);
  err.reason = body?.error?.errors?.[0]?.reason ?? "unknown";
  throw err;
}

/** Run one step; a refusal comes back as `{ ok: false, reason }` instead of ending the tick. */
async function attempt(work) {
  try {
    return { ok: true, value: await work() };
  } catch (err) {
    return { ok: false, reason: err?.reason ?? "unknown", message: err?.message ?? String(err) };
  }
}

function channelQuery(raw) {
  const q = String(raw ?? "").trim();
  const typed = /^https?:\/\//i.test(q) ? new URL(q).pathname : q;
  let path = typed; // decoded, so youtube.com/@caf%C3%A9 reads as @café
  try { path = decodeURIComponent(typed); } catch { /* a stray % keeps the path as typed */ }
  const byId = /(?:^|\/)(UC[\w-]{22})(?:\/|$)/.exec(path);
  if (byId) return `id=${byId[1]}`;
  const byUser = /\/user\/([\w-]+)/.exec(path);
  if (byUser) return `forUsername=${encodeURIComponent(byUser[1])}`;
  const handle = /(?:^|\/)@([^/?#\s]+)/u.exec(path)?.[1] ?? q.replace(/^@/, ""); // any Unicode handle
  return `forHandle=${encodeURIComponent(`@${handle}`)}`;
}

async function loadChannel(ctx, raw) {
  const body = await yt(ctx, `/channels?part=snippet,statistics,contentDetails&${channelQuery(raw)}`);
  const item = body.items?.[0];
  if (!item) return null;
  const stats = item.statistics ?? {};
  return {
    channelId: item.id,
    title: item.snippet?.title ?? item.id,
    handle: item.snippet?.customUrl ?? null,
    thumbnail: item.snippet?.thumbnails?.default?.url ?? null,
    uploads: item.contentDetails?.relatedPlaylists?.uploads ?? null,
    subscribers: stats.hiddenSubscriberCount === true ? null : Number(stats.subscriberCount ?? 0),
    subscribersHidden: stats.hiddenSubscriberCount === true,
    views: Number(stats.viewCount ?? 0),
    videoCount: Number(stats.videoCount ?? 0),
  };
}

/** Newest-first video ids from the uploads playlist, 50 a page, up to `limit`. */
async function uploadIds(ctx, uploads, limit) {
  const ids = [];
  let pageToken = "";
  do {
    const size = Math.min(50, limit - ids.length);
    const page = await yt(
      ctx,
      `/playlistItems?part=contentDetails&playlistId=${uploads}&maxResults=${size}${pageToken ? `&pageToken=${pageToken}` : ""}`,
    );
    ids.push(...(page.items ?? []).map((i) => i.contentDetails?.videoId).filter(Boolean));
    pageToken = page.nextPageToken ?? "";
  } while (pageToken && ids.length < limit);
  return ids;
}

/** View counts and titles for `ids`, 50 per `videos` call. */
async function readViews(ctx, ids) {
  const views = {};
  const titles = {};
  for (let i = 0; i < ids.length; i += 50) {
    const body = await yt(ctx, `/videos?part=snippet,statistics&id=${ids.slice(i, i + 50).join(",")}`);
    for (const v of body.items ?? []) {
      views[v.id] = Number(v.statistics?.viewCount ?? 0);
      titles[v.id] = v.snippet?.title ?? v.id;
    }
  }
  return { views, titles };
}

/** The local calendar day and hour in the owner's time zone. */
function localTime(ms, timeZone) {
  const parts = Object.fromEntries(
    new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", hourCycle: "h23" })
      .formatToParts(new Date(ms))
      .map((p) => [p.type, p.value]),
  );
  return { day: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour) };
}

function clock(iso, timeZone) {
  return new Date(iso).toLocaleTimeString("en-US", { timeZone, hour: "numeric", minute: "2-digit" });
}

/** Take one sample under a fixed slot id; a slot already taken is left alone. */
async function takeSample(ctx, settings, { slot, kind, limit }) {
  const _id = `sample-${settings.channelId}-${slot}`;
  if (await ctx.db.get(_id, { db: DB })) return { ok: true, skipped: true };
  return attempt(async () => {
    const ids = await uploadIds(ctx, settings.uploads, limit);
    const { views, titles } = await readViews(ctx, ids);
    const doc = { _id, type: "sample", kind, channelId: settings.channelId, takenAt: new Date().toISOString(), views, titles };
    await ctx.db.put(doc, { db: DB });
    return doc;
  });
}

/** Rank last evening → this morning. A video missing from the earlier sample is new, never a gain from zero. */
function rankWindow(earlier, later) {
  const gains = [];
  const fresh = [];
  for (const [id, now] of Object.entries(later.views)) {
    if (earlier.views[id] === undefined) fresh.push({ id, title: later.titles[id], views: now });
    else gains.push({ id, title: later.titles[id], gained: now - earlier.views[id] });
  }
  gains.sort((a, b) => b.gained - a.gained);
  return { gains, fresh };
}

async function sendRecap(ctx, settings, day, yesterday) {
  const recapId = `recap-${day}`;
  const existing = await ctx.db.get(recapId, { db: DB });
  if (existing?.deliveredAt) return; // pushed already; an undelivered recap is sent again
  const earlier = await ctx.db.get(`sample-${settings.channelId}-${yesterday}-evening`, { db: DB });
  const later = await ctx.db.get(`sample-${settings.channelId}-${day}-morning`, { db: DB });
  if (!earlier || !later) return; // the pair is not complete yet; the next tick looks again
  const { gains, fresh } = rankWindow(earlier, later);
  const top = gains[0];
  const window = `between ${clock(earlier.takenAt, settings.timeZone)} and ${clock(later.takenAt, settings.timeZone)}`;
  const body = top
    ? `"${top.title}" gained ${top.gained.toLocaleString()} views ${window}.`
    : `Your readings ${window} are in.`;
  const recap = { _id: recapId, type: "recap", day, from: earlier.takenAt, to: later.takenAt, top: gains.slice(0, 5), fresh, body, deliveredAt: null };
  await ctx.db.put(recap, { db: DB }); // the screen shows it now, pushed or not
  await deliverRecap(ctx, recap);
}

/** Push a stored recap; it is stamped deliveredAt only once ctx.notify succeeds, and the dedupeKey makes a retry safe. */
async function deliverRecap(ctx, recap) {
  const sent = await attempt(() =>
    ctx.notify({ toHandle: ctx.appInfo.ownerHandle, body: recap.body, dedupeKey: recap._id, path: `#${recap._id}` }),
  );
  if (!sent.ok) return ctx.log("warn", "recap push failed; the next tick sends it again", { id: recap._id, reason: sent.reason });
  await ctx.db.put({ ...recap, deliveredAt: new Date().toISOString() }, { db: DB });
}

/**
 * Samples and recaps older than 28 days go, so stored readings stay inside YouTube's freshness
 * window. A sample is dated by `takenAt`, a recap by `to`, the channel totals by `refreshedAt`.
 */
async function pruneOldReadings(ctx, nowMs) {
  const cutoff = new Date(nowMs - KEEP_DAYS * 24 * 3600 * 1000).toISOString();
  const settings = await ctx.db.get("settings", { db: DB });
  if (settings?.channel && String(settings.channel.refreshedAt) < cutoff) await ctx.db.put({ ...settings, channel: null }, { db: DB });
  for (const [type, dateField] of [["sample", "takenAt"], ["recap", "to"]]) {
    let after;
    do {
      const page = await ctx.db.query({ db: DB, field: "type", key: type, limit: 100, after });
      after = page.next;
      for (const doc of page) if (String(doc[dateField]) < cutoff) await ctx.db.delete(doc._id, { db: DB });
    } while (after);
  }
}

// The UTC hour each budget resets: the app's own at midnight UTC (over_budget), Google's project
// quota at midnight Pacific (quotaExceeded, a 403 that ctx.youtube passes through).
const RESET_UTC_HOUR = { over_budget: 0, quotaExceeded: 8 };

async function notePause(ctx, nowMs, reason) {
  const resumesAt = new Date(nowMs);
  resumesAt.setUTCHours(RESET_UTC_HOUR[reason], 0, 0, 0);
  if (resumesAt.getTime() <= nowMs) resumesAt.setUTCDate(resumesAt.getUTCDate() + 1);
  await ctx.db.put({ _id: "status", type: "status", reason, resumesAt: resumesAt.toISOString() }, { db: DB });
}

/** A sample landed, so the budget is back: the "resumes at midnight" note comes down. */
async function clearStatus(ctx) {
  if (await ctx.db.get("status", { db: DB })) await ctx.db.delete("status", { db: DB });
}

/** The stored note, unless its resumesAt has passed. */
async function currentStatus(ctx) {
  const status = await ctx.db.get("status", { db: DB });
  return status && Date.parse(status.resumesAt) > Date.now() ? status : null;
}

/** Channel totals ride along with each full reading (1 unit), so subscribers and views keep moving. */
async function refreshChannel(ctx, settings) {
  const fresh = await attempt(() => loadChannel(ctx, settings.channelId));
  if (fresh.ok && fresh.value) {
    await ctx.db.put({ ...settings, channel: { ...fresh.value, refreshedAt: new Date().toISOString() } }, { db: DB });
  }
  return fresh;
}

export async function scheduled(event, ctx) {
  const settings = await ctx.db.get("settings", { db: DB });
  if (!settings?.uploads) return; // nothing tracked yet
  const nowMs = event.scheduledTime ? new Date(event.scheduledTime).getTime() : Date.now();
  const { day, hour } = localTime(nowMs, settings.timeZone);
  const yesterday = localTime(nowMs - 24 * 3600 * 1000, settings.timeZone).day;

  const steps = [{ slot: `${day}-hour-${String(hour).padStart(2, "0")}`, kind: "recent", limit: 10 }];
  if (hour >= MORNING_HOUR && hour < EVENING_HOUR) steps.push({ slot: `${day}-morning`, kind: "full", limit: FULL_CATALOG_LIMIT });
  if (hour >= EVENING_HOUR) steps.push({ slot: `${day}-evening`, kind: "full", limit: FULL_CATALOG_LIMIT });
  for (const step of steps) {
    const taken = await takeSample(ctx, settings, step);
    // A full reading that just landed re-reads the channel too; its refusal is handled like the sample's.
    const outcome = taken.ok && !taken.skipped && step.kind === "full" ? await refreshChannel(ctx, settings) : taken;
    if (!outcome.ok && Object.hasOwn(RESET_UTC_HOUR, outcome.reason)) {
      await notePause(ctx, nowMs, outcome.reason); // over_budget or quotaExceeded: keep the last readings, say when the next arrive
      break;
    }
    if (!outcome.ok) ctx.log("warn", "youtube read failed", { slot: step.slot, reason: outcome.reason });
    if (taken.ok && !taken.skipped) await clearStatus(ctx);
  }
  if (hour >= RECAP_HOUR) await sendRecap(ctx, settings, day, yesterday);
  const late = await ctx.db.get(`recap-${yesterday}`, { db: DB }); // yesterday's push, if it never went out
  if (late && !late.deliveredAt) await deliverRecap(ctx, late);
  await pruneOldReadings(ctx, nowMs);
}

function json(payload, status = 200) {
  return new Response(JSON.stringify(payload), { status, headers: { "content-type": "application/json" } });
}

/** Every stored recap, newest first: at most 28 days of them, since the sweep removes older ones. */
async function recapHistory(ctx) {
  const rows = [];
  let after;
  do {
    const page = await ctx.db.query({ db: DB, field: "type", key: "recap", limit: 100, after });
    after = page.next;
    rows.push(...page);
  } while (after);
  return rows.sort((a, b) => String(b.day).localeCompare(String(a.day)));
}

export async function fetch(request, ctx) {
  const url = new URL(request.url);
  const isOwner = ctx.userInfo?.userHandle != null && ctx.userInfo.userHandle === ctx.appInfo.ownerHandle;

  // Everyone but the owner reads what the tick already stored. Nothing here reaches YouTube, so a
  // visitor's refresh button never spends the app's daily units.
  if (!isOwner) {
    const settings = await ctx.db.get("settings", { db: DB });
    const status = await currentStatus(ctx);
    return json({ ok: true, owner: false, source: "stored", channel: settings?.channel ?? null, recaps: await recapHistory(ctx), status });
  }

  if (request.method === "POST" && url.pathname === "/track") {
    const { link, timeZone } = await request.json();
    const found = await attempt(() => loadChannel(ctx, link));
    if (!found.ok) return json({ ok: false, reason: found.reason, message: found.message });
    if (!found.value) return json({ ok: false, reason: "not-found", message: "No channel by that name — try the link from the channel page." });
    const channel = { ...found.value, refreshedAt: new Date().toISOString() };
    const settings = { _id: "settings", type: "settings", channelId: channel.channelId, uploads: channel.uploads, timeZone: timeZone || "UTC", channel };
    await ctx.db.put(settings, { db: DB });
    const first = await takeSample(ctx, settings, { slot: `setup-${Date.now()}`, kind: "full", limit: FULL_CATALOG_LIMIT });
    if (!first.ok && Object.hasOwn(RESET_UTC_HOUR, first.reason)) await notePause(ctx, Date.now(), first.reason);
    // Tracking is saved either way; firstSample tells the page whether the first readings are in yet.
    return json({ ok: true, owner: true, source: "live", channel, firstSample: first.ok ? "saved" : first.reason });
  }

  const settings = await ctx.db.get("settings", { db: DB });
  return json({
    ok: true,
    owner: true,
    source: "stored",
    channel: settings?.channel ?? null,
    recaps: await recapHistory(ctx),
    status: await currentStatus(ctx),
    budget: await ctx.youtube.status(), // spends nothing
  });
}
```

## App.jsx sketch

### `App.jsx`
```jsx app=youtube-recap
import React, { useEffect, useState } from "react";
import { apiFetch } from "use-vibes";
import { Button, Field, Heading, Input, Row, Stack, Text } from "@vibes.diy/ui";

export default function App() {
  // Owner and visitor alike read the backend's answer, which carries the recap history.
  const [view, setView] = useState(null); // { owner, channel, recaps, status, budget }
  const [link, setLink] = useState("");
  const [note, setNote] = useState(null);

  const load = () => apiFetch("/").then((r) => r.json()).then(setView).catch(() => setView({ owner: false }));
  useEffect(() => { load(); }, []);

  const track = async () => {
    const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    const res = await apiFetch("/track", { method: "POST", body: JSON.stringify({ link, timeZone }) });
    const data = await res.json();
    if (!data.ok) setNote(data.message);
    else if (data.firstSample === "saved") setNote("Tracking. Your first recap arrives tomorrow at 9 a.m.");
    else setNote("Tracking. The first readings arrive with the next scheduled reading.");
    load();
  };

  // The pause note holds only until its resumesAt; a timer drops it from an open page at the reset.
  const resumesAt = view?.status ? Date.parse(view.status.resumesAt) : NaN;
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    if (!(resumesAt > Date.now())) return undefined;
    const timer = setTimeout(() => setNow(Date.now()), resumesAt - Date.now() + 1000);
    return () => clearTimeout(timer);
  }, [resumesAt]);
  const resting = resumesAt > now;
  const history = view?.recaps ?? [];

  return (
    <Stack>
      <Heading>{view?.channel?.title ?? "Overnight recap"}</Heading>

      {view?.owner && !view.channel && (
        <Row gap={2} align="top">
          <Field label="Your channel">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={link} onChange={setLink} placeholder="@handle or channel link" />}</Field>
          <Button type="button" onClick={track}>Track</Button>
        </Row>
      )}
      {note && <Text role="status">{note}</Text>}

      {resting && (
        <Text muted>
          Today's readings are in; the next ones arrive after{" "}
          {view.status.reason === "over_budget" ? "midnight UTC" : "YouTube's midnight Pacific reset"} ({new Date(resumesAt).toLocaleTimeString()} your time).
        </Text>
      )}

      {view?.channel && (
        <section>
          <p>{view.channel.subscribersHidden ? "Subscribers hidden by the channel" : `${view.channel.subscribers.toLocaleString()} subscribers`}</p>
          <small>YouTube rounds public subscriber counts.</small>
        </section>
      )}

      <section>
        <h3>Every morning's winner</h3>
        {history.length === 0 ? (
          <p>The first recap lands at 9 a.m. after an evening and a morning reading.</p>
        ) : (
          history.map((r) => (
            <article key={r._id} id={r._id}>
              <h4>{r.day}</h4>
              <p>{r.body}</p>
              {r.fresh?.length > 0 && <small>New since last night: {r.fresh.map((v) => v.title).join(", ")}</small>}
            </article>
          ))
        )}
      </section>

      <section>
        <h3>Not available with an API key</h3>
        <p>Watch time, revenue, impressions, traffic sources and demographics live in YouTube Studio, which settles them 48–72 hours later.</p>
      </section>
    </Stack>
  );
}
```

Chart the samples with whichever chart surface the app already uses: `takenAt`
on the x axis and one series per video from `views`, so the owner sees the
evening-to-morning climb behind each recap.
