commit c26eb53dfe9007f1467078eeac710fc39560040f
parent c07da2e4fb6cc341cf5894b26826aaf4b847d6e4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 18 Nov 2026 04:43:09 -0500
Merge main (237f2fb0c, lane/page-speed) into lane/x-trending-2
One conflict, editor/CHANGELOG.md: both sides' bullets kept under [Unreleased].
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
31 files changed, 1862 insertions(+), 286 deletions(-)
diff --git a/common/controller/channels.ts b/common/controller/channels.ts
@@ -413,7 +413,9 @@ export type ChannelBrief = {
snapshot: ChannelSnapshot | null;
};
-async function listChannelSlugs(paths: Paths): Promise<string[]> {
+// Exported for a page that sizes a skeleton by the channel count before it
+// reads any channel (one readdir).
+export async function listChannelSlugs(paths: Paths): Promise<string[]> {
try {
const entries = await readdir(paths.channelsDir, { withFileTypes: true });
return entries.filter((e) => e.isDirectory()).map((e) => e.name);
diff --git a/common/jobs/listJobs.ts b/common/jobs/listJobs.ts
@@ -216,6 +216,15 @@ export async function listAllJobs(
return { entries, hasMore, total: candidates.size };
}
+// HOW MANY JOBS listAllJobs WOULD LIST, without reading one of them: the size
+// of the same candidate set (every log file ∪ every registry record) from one
+// readdir. For a page that sizes a placeholder before it reads the rows.
+export async function countAllJobs(paths: Paths): Promise<number> {
+ const ids = await readLogIds(paths);
+ for (const r of getRegistry().list()) ids.add(r.id);
+ return ids.size;
+}
+
// Resolve a single job by id for the detail page — avoids listing every job.
// Null when neither the registry nor an `<id>.log` file knows the id.
export async function getJobEntry(
diff --git a/common/lib/changelog.test.ts b/common/lib/changelog.test.ts
@@ -5,6 +5,7 @@ import {
bumpVersion,
changelogAnchor,
changelogAnchorPages,
+ changelogPreview,
changelogPageOf,
clampChangelogPage,
compareVersions,
@@ -352,3 +353,90 @@ test("withdrawing the latest release puts its bullets back under [Unreleased]",
"# Changelog\n\n## [Unreleased]\n- a\n",
);
});
+
+test("changelogPreview is the top of the newest entry, cut on a bullet", () => {
+ const bullet = (n: number) => `- **Change ${n}.** ${"words ".repeat(60)}\n - a nested line of change ${n}\n`;
+ const newest = `## [Unreleased]\n${[1, 2, 3, 4, 5, 6].map(bullet).join("")}`;
+ const source = `# Changelog\n\n${newest}\n## [1.0.0] - 2026-01-01\n- older\n`;
+
+ // An entry that fits is the whole entry, and never the older ones.
+ const whole = changelogPreview(source, 100_000);
+ assert.ok(whole.includes("Change 6."));
+ assert.ok(!whole.includes("older"));
+
+ // Cut: whole top-level bullets only, in order, within the budget.
+ const cut = changelogPreview(source, 1000);
+ assert.ok(cut.length <= 1000, String(cut.length));
+ assert.ok(cut.startsWith("# Changelog\n\n## [Unreleased]\n- **Change 1.**"));
+ assert.ok(cut.includes("a nested line of change 2"));
+ assert.ok(!cut.includes("Change 3."));
+ assert.ok(cut.endsWith("a nested line of change 2\n"));
+
+ // A first bullet longer than the budget is still shown whole.
+ const tiny = changelogPreview(source, 50);
+ assert.ok(tiny.includes("a nested line of change 1"));
+ assert.ok(!tiny.includes("Change 2."));
+
+ // One bullet, however long, is the entry.
+ const one = `# Changelog\n\n## [Unreleased]\n- ${"x".repeat(9000)}\n`;
+ assert.equal(changelogPreview(one, 6000), one);
+ assert.equal(changelogPreview("", 6000), "");
+});
+
+test("changelogPreview never cuts inside a fenced block", () => {
+ const filler = "words ".repeat(40);
+ const fenced = [
+ "## [Unreleased]",
+ `- **First.** ${filler}`,
+ " ```diff",
+ "- a removed line that starts like a bullet",
+ "+ an added line",
+ `- another removed line ${filler}`,
+ " ```",
+ `- **Second.** ${filler}`,
+ `- **Third.** ${filler}`,
+ "",
+ ].join("\n");
+ const source = `# Changelog\n\n${fenced}`;
+ // A budget that ends inside the fence: the only places to cut are before
+ // Second and before Third, so the whole first bullet, fence closed, is kept.
+ const insideFence = source.indexOf("another removed line");
+ const cut = changelogPreview(source, insideFence);
+ assert.ok(cut.includes("- another removed line"), "the fenced lines are kept whole");
+ assert.ok(cut.trimEnd().endsWith("```"), cut.slice(-40));
+ assert.ok(!cut.includes("Second."));
+ assert.equal(cut.split("```").length - 1, 2, "the fence is closed");
+ // The same with a tilde fence, and a fence char that differs inside it.
+ const tilde = source.replaceAll(" ```diff", "~~~").replace(" ```\n- **Second", "~~~\n- **Second");
+ const cutTilde = changelogPreview(tilde, tilde.indexOf("another removed line"));
+ assert.ok(cutTilde.trimEnd().endsWith("~~~"), cutTilde.slice(-40));
+});
+
+test("changelogPreview never ends on a heading with nothing under it", () => {
+ const filler = "words ".repeat(40);
+ const source = [
+ "# Changelog",
+ "",
+ "## [Unreleased]",
+ "### Added",
+ `- **One.** ${filler}`,
+ `- **Two.** ${filler}`,
+ "",
+ "### Fixed",
+ `- **Three.** ${filler}`,
+ `- **Four.** ${filler}`,
+ "",
+ ].join("\n");
+ // The budget ends just past the start of Three: the cut is before Three,
+ // which would leave "### Fixed" as the last line.
+ const cut = changelogPreview(source, source.indexOf("**Three.**") + 5);
+ assert.ok(cut.includes("**Two.**"));
+ assert.ok(!cut.includes("Fixed"), cut.slice(-60));
+ assert.ok(!cut.includes("Three"));
+ assert.ok(cut.endsWith(`- **Two.** ${filler}`.trimEnd() + "\n"), JSON.stringify(cut.slice(-30)));
+ // A sub-heading WITH a bullet under it stays.
+ assert.ok(cut.includes("### Added\n- **One.**"));
+ const more = changelogPreview(source, source.indexOf("**Four.**") + 5);
+ assert.ok(more.includes("### Fixed\n- **Three.**"));
+ assert.ok(!more.includes("Four"));
+});
diff --git a/common/lib/changelog.ts b/common/lib/changelog.ts
@@ -23,6 +23,56 @@ export function sliceTopEntries(source: string, limit: number): string {
return source.slice(0, indexes[limit]).trimEnd() + "\n";
}
+// THE TOP OF THE NEWEST ENTRY, for a box that shows only its first lines (the
+// dashboard's "Recent changes" card is 12rem tall and clipped). The newest
+// entry can run to a hundred kilobytes, and a caller that hands the whole of
+// it to a client component pays for it three times: in the document, in the
+// component payload and in a markdown parse on each side. This is the entry's
+// heading and as many of its top-level bullets as fit in `maxChars`, cut ON a
+// bullet boundary so no bullet is ever shown half-written — and always at
+// least the first bullet, however long. An entry that fits is returned whole.
+//
+// Two things a cut never does:
+// - land inside a fenced code block: a line starting `- ` between two fence
+// lines is code (a diff, a list in an example), not a bullet, and cutting
+// there would leave the fence open over everything after it;
+// - end on a heading with nothing under it: when the next bullet that does
+// not fit is the first under a `### …` sub-heading, the heading goes too.
+export function changelogPreview(source: string, maxChars = 6000): string {
+ const top = sliceTopEntries(source, 1);
+ if (top.length <= maxChars) return top;
+ // Where each top-level bullet starts (a nested bullet is indented), outside
+ // any fenced block.
+ const starts: number[] = [];
+ let fence: string | null = null;
+ let at = 0;
+ for (const line of top.split("\n")) {
+ const mark = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
+ if (mark) {
+ if (fence === null) fence = mark[0];
+ else if (mark[0] === fence) fence = null;
+ } else if (fence === null && /^[-*] /.test(line)) {
+ starts.push(at);
+ }
+ at += line.length + 1;
+ }
+ if (starts.length < 2) return top;
+ let cut = starts[1];
+ for (const start of starts.slice(1)) {
+ if (start > maxChars) break;
+ cut = start;
+ }
+ let kept = top.slice(0, cut).trimEnd();
+ // A sub-heading left with nothing under it. Never the entry's own `## `
+ // heading: the first bullet is always kept, so that one is never last.
+ for (;;) {
+ const lastLine = kept.slice(kept.lastIndexOf("\n") + 1);
+ if (!/^#{3,}\s/.test(lastLine)) break;
+ kept = kept.slice(0, kept.length - lastLine.length).trimEnd();
+ }
+ return kept + "\n";
+}
+
export function getLatestReleasedVersion(source: string): string | null {
const match = source.match(RELEASED_HEADING);
return match ? match[1] : null;
diff --git a/common/views/activeJobs.test.ts b/common/views/activeJobs.test.ts
@@ -4,6 +4,8 @@ import { defaultSiteSettings } from "../lib/settings";
import { createScheduler, type Scheduler } from "../jobs/scheduler";
import type { JobRecord } from "../jobs/registry";
import type { JobMeta } from "../jobs/jobMeta";
+import type { ChannelStat } from "../controller/channels";
+import { fromRecord, needsChannelStat } from "./jobRows";
import type { Paths } from "../lib/paths";
import type { DiskGateStatus } from "../lib/diskSpace";
import type { AutoRunnerStatus } from "../controller/autoRunner";
@@ -115,6 +117,7 @@ function harness(over: {
jobs?: JobRecord[];
slots?: string[];
meta?: (id: string) => JobMeta | null;
+ stat?: (slug: string) => ChannelStat | null;
disk?: DiskGateStatus;
runner?: (kind: AutoQueueKind) => AutoRunnerStatus;
} = {}): Harness {
@@ -151,7 +154,7 @@ function harness(over: {
now: () => NOW,
channelStat: async (slug) => {
statCalls.push(slug);
- return null;
+ return over.stat?.(slug) ?? null;
},
jobMeta: async (id) => {
metaCalls.push(id);
@@ -210,11 +213,13 @@ test("the log tail is read for stuck rows only", async () => {
});
test("a channel is stat-ed once however many of its jobs are running", async () => {
+ // Each with progress the disk has to count: the only rows that read a stat.
+ const progress = { metric: "transcripts", initial: 0, target: 5 } as const;
const h = harness({
jobs: [
- job({ id: "a1", channelSlug: "alpha" }),
- job({ id: "a2", channelSlug: "alpha", queueKey: "q2" }),
- job({ id: "b1", channelSlug: "beta", queueKey: "q3" }),
+ job({ id: "a1", channelSlug: "alpha", progress }),
+ job({ id: "a2", channelSlug: "alpha", queueKey: "q2", progress }),
+ job({ id: "b1", channelSlug: "beta", queueKey: "q3", progress }),
// No channel at all: a corpus-wide job contributes no slug.
job({ id: "c1", queueKey: "q4" }),
],
@@ -374,3 +379,69 @@ test("rowsFromJobsPage folds a listing page and nothing else", () => {
assert.equal(out.hasMore, true);
assert.deepEqual(out.rows.map((r) => r.id), ["j9"]);
});
+
+// THE CHANNEL STAT IS A WALK OF THE CHANNEL'S `data/`, asked for on every poll
+// of the job list. It is asked for only by a row that reads it — and every row
+// comes out exactly as it did when every channel was walked.
+const statOf = (slug: string): ChannelStat => ({
+ slug,
+ config: { handling: "youtube" } as ChannelStat["config"],
+ playlistCount: 50,
+ videoCount: 40,
+ transcriptCount: 17,
+ downloadCount: 23,
+ digestCount: 9,
+});
+
+const SHAPES: JobRecord[] = [
+ // Reads the stat: running, on a channel, progress the runner did not count.
+ job({ id: "walk-transcripts", channelSlug: "needs-t", progress: { metric: "transcripts", initial: 10, target: 30 } }),
+ job({ id: "walk-downloads", channelSlug: "needs-d", progress: { metric: "downloads", initial: 20, target: 30 } }),
+ job({ id: "walk-digests", channelSlug: "needs-g", progress: { metric: "digests", initial: 5, target: 12 } }),
+ // Never reads it.
+ job({ id: "runner-counted", channelSlug: "counted", progress: { metric: "digests", initial: 0, target: 8, current: 3 } }),
+ job({ id: "no-progress", channelSlug: "plain" }),
+ job({ id: "no-channel", progress: { metric: "clips", initial: 0, target: 4, current: 1 } }),
+ job({ id: "no-channel-no-progress" }),
+ job({ id: "queued", status: "queued", startedAt: undefined, channelSlug: "waiting", progress: { metric: "transcripts", initial: 0, target: 9 } }),
+ job({ id: "done", status: "done", endedAt: NOW - 5_000, channelSlug: "finished", progress: { metric: "transcripts", initial: 0, target: 9 } }),
+ job({ id: "failed", status: "failed", endedAt: NOW - 5_000, channelSlug: "broke" }),
+];
+
+test("the channel stat is read only for a row that uses it", async () => {
+ const h = harness({ jobs: SHAPES, stat: statOf });
+ await buildActiveJobsPayload(h.inputs);
+ assert.deepEqual([...h.statCalls].sort(), ["needs-d", "needs-g", "needs-t"]);
+ assert.deepEqual(
+ SHAPES.filter(needsChannelStat).map((j) => j.id),
+ ["walk-transcripts", "walk-downloads", "walk-digests"],
+ );
+});
+
+test("every row is the row a stat for every channel would have drawn", async () => {
+ const h = harness({ jobs: SHAPES, stat: statOf });
+ const payload = await buildActiveJobsPayload(h.inputs);
+ const rows = new Map([...payload.jobs, ...payload.recent].map((r) => [r.id, r]));
+ assert.equal(rows.size, SHAPES.length);
+ for (const j of SHAPES) {
+ const row = rows.get(j.id);
+ assert.ok(row, j.id);
+ // The row as it was built before: the channel's stat handed to every
+ // record that names a channel.
+ const before = fromRecord(j, {
+ now: NOW,
+ stat: j.channelSlug ? statOf(j.channelSlug) : undefined,
+ workerNames: new Map(),
+ position: -1,
+ queueMax: 0,
+ });
+ assert.deepEqual(row.progress, before.progress, `${j.id}: progress`);
+ assert.equal(row.status, before.status);
+ }
+ // And the three that read it did read it.
+ assert.equal(rows.get("walk-transcripts")?.progress?.current, 17);
+ assert.equal(rows.get("walk-downloads")?.progress?.current, 23);
+ assert.equal(rows.get("walk-digests")?.progress?.current, 9);
+ assert.equal(rows.get("runner-counted")?.progress?.current, 3);
+ assert.equal(rows.get("no-progress")?.progress, undefined);
+});
diff --git a/common/views/activeJobs.ts b/common/views/activeJobs.ts
@@ -2,6 +2,7 @@ import {
fromEntry,
fromRecord,
fromSlot,
+ needsChannelStat,
orderLiveRows,
reconcileSlots,
RECENT_MS,
@@ -133,9 +134,15 @@ async function rowsForRecords(
views: QueueView[],
now: number,
): Promise<JobRowView[]> {
+ // Only the channels a row will actually read the counts of (needsChannelStat,
+ // jobRows.ts): the stat is a walk of the channel's `data/`, and this runs on
+ // every poll of the job list.
const channelSlugs = Array.from(
new Set(
- records.map((j) => j.channelSlug).filter((s): s is string => Boolean(s)),
+ records
+ .filter(needsChannelStat)
+ .map((j) => j.channelSlug)
+ .filter((s): s is string => Boolean(s)),
),
);
diff --git a/common/views/channelRow.test.ts b/common/views/channelRow.test.ts
@@ -191,3 +191,27 @@ test("a remote-only channel's row says so, with its archive, and is not 'manual
assert.equal(remote.hasUrl, false);
assert.equal(buildChannelRowView(input()).remoteOnly, null);
});
+
+test("a row's bands carry the numbers, not what is true of the operation", () => {
+ // The label, the cost basis and `dispatched` are the same on every row of a
+ // column; the table states them on the column. On a row they were a third
+ // of what the channels page serialised.
+ const band = {
+ id: "digest",
+ label: "Digest",
+ costBasis: "about one model call per transcript chunk",
+ eligible: 10,
+ present: 4,
+ reachable: 3,
+ blocked: 2,
+ missingInput: 1,
+ deferred: 0,
+ dispatched: true,
+ };
+ const row = buildChannelRowView(input({ bands: [band] }));
+ assert.deepEqual(row.pipelines, [
+ { id: "digest", eligible: 10, present: 4, reachable: 3, blocked: 2, missingInput: 1, deferred: 0 },
+ ]);
+ // The input is not touched.
+ assert.equal(band.label, "Digest");
+});
diff --git a/common/views/channelRow.ts b/common/views/channelRow.ts
@@ -12,7 +12,7 @@ import {
locationOfDataDir,
type StorageLocation,
} from "../lib/storageLocations";
-import type { OperationBand } from "./pipeline/band";
+import type { BandCounts, OperationBand } from "./pipeline/band";
import {
digestReachableCountOf,
undownloadedCountOf,
@@ -104,7 +104,7 @@ export type ChannelRowView = {
};
// The pipeline bands, in column order, projected from the same snapshot the
// counts come from. `[]` for a table that draws no pipeline column.
- pipelines: OperationBand[];
+ pipelines: ChannelRowBand[];
priority: ChannelRowPriority;
// How old this channel's report is. Every count and every band on this row is
// projected from that report, so its age is the caveat on all of them.
@@ -201,6 +201,22 @@ export function channelVolumeOf(
: { id: "", label: "Elsewhere" };
}
+// ONE BAND ON A ROW: the band's numbers, by operation id. A band also carries
+// what is true of the OPERATION and so is the same on every row — its label,
+// its cost basis in words, whether this system dispatches it. A table states
+// those once, on the column (channels/page.tsx `pipelineColumns`); repeated on
+// every row of every channel they were a third of the rows the channels page
+// serialises, and no cell read them.
+export type ChannelRowBand = BandCounts;
+
+function rowBandOf(band: OperationBand): ChannelRowBand {
+ const { label: _label, costBasis: _costBasis, dispatched: _dispatched, ...numbers } = band;
+ void _label;
+ void _costBasis;
+ void _dispatched;
+ return numbers;
+}
+
export function buildChannelRowView(i: ChannelRowInput): ChannelRowView {
const snap = i.snapshot;
return {
@@ -221,7 +237,7 @@ export function buildChannelRowView(i: ChannelRowInput): ChannelRowView {
untranscribed: untranscribedCountOf(snap),
digestReachable: digestReachableCountOf(snap),
},
- pipelines: i.bands,
+ pipelines: i.bands.map(rowBandOf),
priority: i.priority,
report: {
generatedAt: snap?.generatedAt ?? null,
diff --git a/common/views/jobRows.ts b/common/views/jobRows.ts
@@ -161,6 +161,23 @@ function computeEtaSeconds(
return (waves * avgProcMs) / 1000;
}
+// WHETHER A ROW'S PROGRESS NEEDS THE CHANNEL'S ON-DISK COUNTS. The counts are
+// a walk of the channel's whole `data/` (readChannelStat: a second on a
+// channel of ten thousand videos), and the job list is polled every second —
+// so the walk is asked for only by a row that will read it: a RUNNING job on a
+// channel whose progress the runner did not count itself. Every other record
+// (queued, finished, no progress snapshot, a runner-reported `current`) draws
+// the same row with or without the counts; `fromRecord` and
+// `computeJobProgressView` below are the two conditions this restates.
+export function needsChannelStat(job: JobRecord): boolean {
+ return (
+ job.status === "running" &&
+ Boolean(job.channelSlug) &&
+ job.progress !== undefined &&
+ job.progress.current === undefined
+ );
+}
+
function computeJobProgressView(
job: JobRecord,
stat: ChannelStat | undefined,
diff --git a/common/views/pipeline/band.ts b/common/views/pipeline/band.ts
@@ -61,6 +61,13 @@ export type OperationBand = {
dispatched: boolean;
};
+// A BAND'S NUMBERS, without what is true of the operation rather than of the
+// channel (its label, its cost basis, whether it is dispatched). Everything
+// that draws or words a band reads only these, which is what lets a table of
+// channels carry them per row and state the rest once per column
+// (views/channelRow.ts `ChannelRowBand`).
+export type BandCounts = Omit<OperationBand, "label" | "costBasis" | "dispatched">;
+
// Sum that returns null if ANY term is null. Same rule digestEligibleKnown uses
// in the widget payload: a partial sum is a denominator smaller than its own
// numerator, which is a worse lie than admitting the number is not knowable.
@@ -78,7 +85,7 @@ export function sumOrNull(
// The fraction of a band that is `present`, or null when either half is unknown.
// Null renders as an unfilled outline — never as 0, which on a fully-digested
// channel would read as "nothing digested".
-export function bandCoverage(band: OperationBand): number | null {
+export function bandCoverage(band: BandCounts): number | null {
if (band.present == null || band.eligible == null || band.eligible <= 0) {
return null;
}
@@ -141,7 +148,7 @@ export const SEGMENTS = [
export type SegmentKey = (typeof SEGMENTS)[number]["key"];
-export function segmentValue(band: OperationBand, key: SegmentKey): number {
+export function segmentValue(band: BandCounts, key: SegmentKey): number {
if (key === "present") return band.present ?? 0;
return band[key];
}
@@ -153,7 +160,7 @@ export function segmentValue(band: OperationBand, key: SegmentKey): number {
// silently redraw the band as "100% accounted for", so instead the band renders
// as an un-filled outline and says `coverage unknown`. Unknown is not zero, and
// it is not full either.
-export function bandDenominator(band: OperationBand): number | null {
+export function bandDenominator(band: BandCounts): number | null {
if (band.eligible != null && band.eligible > 0) return band.eligible;
return null;
}
@@ -165,7 +172,7 @@ export function bandDenominator(band: OperationBand): number | null {
// measured corpus `reachable` and `missingInput` are four orders of magnitude
// apart on diarization; one "remaining" number would say the same thing about a
// lane that is finished and a lane that cannot start.
-export function bandSentence(band: OperationBand): string {
+export function bandSentence(band: BandCounts): string {
const parts: string[] = [`${band.reachable.toLocaleString()} can run now`];
if (band.blocked > 0) {
parts.push(`${band.blocked.toLocaleString()} blocked upstream`);
@@ -192,7 +199,7 @@ export function bandSentence(band: OperationBand): string {
// true sentence about a pipeline. "11,333 no media" and "11,329 to do" are the
// same size of number and mean opposite things; a single "remaining" figure
// would render them identically.
-export function bandHeadline(band: OperationBand): string {
+export function bandHeadline(band: BandCounts): string {
const candidates: Array<[number, string]> = [
[band.reachable, "to do"],
[band.blocked, "blocked"],
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -27,6 +27,38 @@
post's thread, judgement, capture and gone mark.
- Everything this adds stays private: `trending/.gitignore` keeps the media out of the corpus's git repo, and no
site, build, report or video project is given a judgement, a capture or a watch.
+- **The dashboard, Jobs, Settings, Storage and Channels show their heading and controls at once, and the slow parts
+ fill in.** Each page used to wait for every read before sending anything. Now the sidebar, the heading and the
+ buttons arrive first, and each slow section arrives when its read is done, in the place a grey placeholder of the
+ same size was holding for it:
+ - the dashboard's pipeline band with "Needs work", and its channels table;
+ - the job list on /jobs;
+ - the X session and archive.today sections on /settings (the form above them no longer waits);
+ - the locations, the saved-video store and the clip windows on /storage;
+ - the freshness line and the rack on /channels.
+ A sidebar click lands on the new page's heading straight away as well. A refresh never brings a placeholder back: what
+ is on screen stays until the new figures are ready. With JavaScript turned off a placeholder stays a placeholder: the
+ section is in the page but nothing moves it into place.
+- **A slow part that fails says so in its own place.** If one of those sections cannot be loaded, its place carries a
+ sentence saying so, with the error, and the rest of the page stays: on /settings the form still shows and saves.
+ Nothing retries on its own; the next refresh or visit shows what it finds. On an archive with no channel yet, the
+ dashboard's first-steps list arrives with the heading.
+- **The job list no longer counts a channel's files for a job that cannot use the count.** Every second, for every
+ listed job that named a channel, the list walked that channel's whole `data/` to count its files (about a second on
+ a channel of ten thousand videos), on /jobs, on the dashboard and in the widget. Only a running job whose progress
+ bar is counted from the disk reads that count; a queued job, a finished one, a job with no progress bar and a job
+ that reports its own count never did. Those no longer cause a walk. Every row reads as before.
+- **The dashboard's "Recent changes" card is the top of the newest entry.** The card is 12rem tall and clipped, but the
+ whole changelog was sent to the browser for it, twice, and the newest entry was parsed there again. The card now
+ carries the first changes of the newest entry, whole bullets only; **View all** beside its heading opens the full
+ changelog, as before.
+- **/settings and /channels send less.** The settings form is no longer sent the four lanes' queue trees, which it
+ never showed; a save from it leaves them exactly as they are. A channel's row no longer repeats each pipeline's name
+ and cost sentence, which the column header already states. Nothing on either page reads differently.
+- **umtool: the home page shows its frame at once and the Inbox fills in.** The rail, the header, Quick clip, what is
+ running and the recent cuts no longer wait for the Inbox to be read; the count and the cards arrive when it is, where
+ a placeholder was holding their place, with the Muted and Show hidden toggles. With JavaScript turned off the
+ placeholder stays.
- **X trending pages can be read into a private library.** A new kind of channel, **X trending library** in the New
channel form's Platform (`"platform": "x-trending"`), holds the posts X's trending pages (`x.com/i/trending/…`)
show, grouped into your topics. Read one page with **Read a trending page** on the library's channel page, or
diff --git a/editor/app/channels/components/ChannelsTable.tsx b/editor/app/channels/components/ChannelsTable.tsx
@@ -4,7 +4,7 @@ import { useMemo, useState, type ReactNode, type Ref } from "react";
import type { ChannelRowView } from "yt-dlp-transcript-common/views/channelRow";
import {
bandSentence,
- type OperationBand,
+ type BandCounts,
} from "yt-dlp-transcript-common/views/pipeline/band";
import type { ChannelGroupSectionView } from "yt-dlp-transcript-common/views/channelGroupSections";
import { tierOrder } from "yt-dlp-transcript-common/lib/channelPriority";
@@ -63,7 +63,7 @@ export function defaultDirFor(key: ChannelSortKey): SortDir {
return DEFAULT_DIR[key] ?? "desc";
}
-function bandOf(row: ChannelRowView, id: string): OperationBand | undefined {
+function bandOf(row: ChannelRowView, id: string): BandCounts | undefined {
return row.pipelines.find((b) => b.id === id);
}
@@ -446,7 +446,7 @@ function PipelineCell({
}: {
slug: string;
column: PipelineColumn;
- band: OperationBand | undefined;
+ band: BandCounts | undefined;
// The bare number for a column that already had one. THE SUITE ASSERTS ON
// THIS: channels-counts.spec.ts does getByLabel("transcripts count for X")
// .toHaveText("3"), so the labelled cell keeps a text node holding the raw
diff --git a/editor/app/channels/page.tsx b/editor/app/channels/page.tsx
@@ -1,9 +1,11 @@
import { displayPath, hidePrivateSites } from "yt-dlp-transcript-common/lib/privacy/privacy-server";
import { isPrivateSite } from "yt-dlp-transcript-common/lib/siteSchema";
import type { Metadata } from "next";
+import { cache, Suspense } from "react";
import Link from "next/link";
import {
listChannelBriefs,
+ listChannelSlugs,
listChannelStatsFromSnapshots,
type ChannelBrief,
} from "yt-dlp-transcript-common/controller/channels";
@@ -61,6 +63,9 @@ import {
import { SyncAllChannelsButton } from "./components/SyncAllChannelsButton";
import { RefreshAllReportsButton } from "./components/RefreshAllReportsButton";
import { readActiveSite } from "../lib/activeSiteServer";
+import { SkeletonPanel, SkeletonRows, StreamFilled } from "../components/StreamSkeleton";
+import { e2eStreamDelay } from "../lib/streamDelay";
+import { StreamErrorBoundary } from "../components/StreamErrorBoundary";
export const dynamic = "force-dynamic";
@@ -166,14 +171,20 @@ function focusLabelOf(
: `${focusSlugs.length} channels`;
}
-export default async function ChannelsPage({
- searchParams,
-}: {
- searchParams: Promise<{ site?: string; location?: string; sort?: string }>;
-}) {
+// EVERYTHING BELOW THE HEADING, read once per request for the two sections
+// that draw it (the freshness line under the heading, and the rack). The page
+// starts this and does not await it: the heading and the corpus-wide buttons
+// are sent at once and both sections stream in behind them. What it returns is
+// the two sections already rendered, so the page function above stays a shell.
+const loadChannelsView = cache(
+ async (
+ site: string | undefined,
+ locationParam: string | undefined,
+ sortParam: string | undefined,
+ ): Promise<{ freshnessLine: React.ReactNode; body: React.ReactNode }> => {
+ await e2eStreamDelay("channels-rack");
const paths = getPaths();
const settings = getSettings();
- const { site, location: locationParam, sort: sortParam } = await searchParams;
// The active site: a `?site=` link's for this request, else the cookie's.
const active = await readActiveSite(site, listSiteIds(paths));
// Counts come from each channel's last snapshot, not a corpus walk. One read
@@ -361,29 +372,14 @@ export default async function ChannelsPage({
const freshness = summariseFreshness(
briefs.filter((b) => shownSlugs.has(b.slug)),
);
- return (
- // ON md+ THE DOCUMENT STOPS SCROLLING. The page is a flex column exactly
- // the height of the viewport (main carries py-6, hence -3rem) so that the
- // header, the focus line, the instrument bar and the selection deck are
- // fixed chrome and the rack between them is the only thing that moves.
- // Below md there is no height and the document scrolls as it always has.
- <div className="flex flex-col gap-3 md:h-[calc(100vh-3rem)] md:min-h-0">
- {/* THE HEADER WRAPS; IT NEVER SQUEEZES. The title block has a 16rem
- basis, so when the corpus-wide cluster cannot sit beside it at full
- width the cluster drops onto its own line. It used to be nowrap with
- the cluster shrink-0, and at a narrow md+ column (sidebar open) the
- title block was left ~60px and its text ran one word per line. */}
- <header className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2 shrink-0">
- <div className="min-w-0 flex-[1_1_16rem]">
- <h1 className="text-2xl font-semibold">Channels</h1>
- {/* A STATUS LINE, NOT A LEAD PARAGRAPH. Every pipeline on the page is
- read from each channel's last report, so the line says how old the
- oldest one is and how many have none (the rack's Report column names
- them). */}
- {channels.length > 0 && (
+ return {
+ freshnessLine:
+ channels.length > 0 ? (
+
<p
className="text-xs text-muted-foreground"
data-testid="channels-freshness"
+ data-stream-filled="channels-freshness"
>
<span className="tabular-nums">{channels.length}</span>{" "}
{channels.length === 1 ? "channel" : "channels"} ·{" "}
@@ -409,30 +405,11 @@ export default async function ChannelsPage({
</>
)}
</p>
- )}
- </div>
- {/* FOUR DARK PILLS OF EQUAL WEIGHT was four things shouting. Three of
- these sweep the WHOLE pool and are used rarely; one creates a
- channel and is the page's actual call to action. So the three are
- outlines under an eyebrow that says what they act on, and only
- "New channel" is filled. */}
- <div className="flex w-full flex-col items-start gap-1 md:w-auto md:shrink-0 md:items-end md:self-start">
- <span className="font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground">
- Every channel
- </span>
- <div className="flex flex-wrap items-center gap-2 md:justify-end">
- <SyncAllChannelsButton />
- <RefreshAllReportsButton />
- <Link
- href="/channels/new"
- className="inline-flex h-8 items-center rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:opacity-90"
- >
- New channel
- </Link>
- </div>
- </div>
- </header>
- {channels.length === 0 ? (
+ ) : null,
+ body:
+ channels.length === 0 ? (
+ <StreamFilled name="channels-rack">
+
<p className="text-sm text-muted-foreground border border-dashed border-border rounded p-4">
{active.siteId && !active.isAll
? `No channels assigned to ${
@@ -442,7 +419,12 @@ export default async function ChannelsPage({
} yet — add some on the Sites page, or create a channel to add it here.`
: "No channels yet."}
</p>
+ </StreamFilled>
) : (
+ // The rack is a pane of the page's viewport-height column (see
+ // ChannelsRack): this wrapper has to be one too.
+ <StreamFilled name="channels-rack" className="flex min-h-0 flex-1 flex-col">
+
<ChannelsRack
channels={channels}
columns={columns}
@@ -473,7 +455,114 @@ export default async function ChannelsPage({
}))}
focusLabel={focusLabel}
/>
- )}
+ </StreamFilled>
+ ),
+ };
+ },
+);
+
+async function Freshness({ view }: { view: ReturnType<typeof loadChannelsView> }) {
+ return (await view).freshnessLine;
+}
+
+async function Rack({ view }: { view: ReturnType<typeof loadChannelsView> }) {
+ return (await view).body;
+}
+
+// The rack's skeleton, in px, where the page has no height of its own (below
+// md): the chrome above the rows (focus line, volume bar, header) and one row.
+// On md+ the skeleton is a pane of the viewport-height column, like the rack.
+const RACK_CHROME_PX = 150;
+const RACK_ROW_PX = 37;
+const RACK_EMPTY_PX = 54;
+
+export default async function ChannelsPage({
+ searchParams,
+}: {
+ searchParams: Promise<{ site?: string; location?: string; sort?: string }>;
+}) {
+ const { site, location: locationParam, sort: sortParam } = await searchParams;
+ // What the skeleton is sized by: how many channels there are (one readdir).
+ const pending = (await listChannelSlugs(getPaths())).length;
+ const view = loadChannelsView(site, locationParam, sortParam);
+ return (
+ // ON md+ THE DOCUMENT STOPS SCROLLING. The page is a flex column exactly
+ // the height of the viewport (main carries py-6, hence -3rem) so that the
+ // header, the focus line, the instrument bar and the selection deck are
+ // fixed chrome and the rack between them is the only thing that moves.
+ // Below md there is no height and the document scrolls as it always has.
+ <div className="flex flex-col gap-3 md:h-[calc(100vh-3rem)] md:min-h-0">
+ {/* THE HEADER WRAPS; IT NEVER SQUEEZES. The title block has a 16rem
+ basis, so when the corpus-wide cluster cannot sit beside it at full
+ width the cluster drops onto its own line. It used to be nowrap with
+ the cluster shrink-0, and at a narrow md+ column (sidebar open) the
+ title block was left ~60px and its text ran one word per line. */}
+ <header className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2 shrink-0">
+ <div className="min-w-0 flex-[1_1_16rem]">
+ <h1 className="text-2xl font-semibold">Channels</h1>
+ {/* A STATUS LINE, NOT A LEAD PARAGRAPH. Every pipeline on the page is
+ read from each channel's last report, so the line says how old the
+ oldest one is and how many have none (the rack's Report column names
+ them). */}
+ {/* Quiet: the rack below reports the same read's failure. */}
+ <StreamErrorBoundary name="channels-freshness" what="The report freshness" quiet>
+ <Suspense
+ fallback={
+ pending > 0 ? (
+ <p
+ className="text-xs text-muted-foreground"
+ data-stream-skeleton="channels-freshness"
+ aria-hidden="true"
+ >
+
+ </p>
+ ) : null
+ }
+ >
+ <Freshness view={view} />
+ </Suspense>
+ </StreamErrorBoundary>
+ </div>
+ {/* FOUR DARK PILLS OF EQUAL WEIGHT was four things shouting. Three of
+ these sweep the WHOLE pool and are used rarely; one creates a
+ channel and is the page's actual call to action. So the three are
+ outlines under an eyebrow that says what they act on, and only
+ "New channel" is filled. */}
+ <div className="flex w-full flex-col items-start gap-1 md:w-auto md:shrink-0 md:items-end md:self-start">
+ <span className="font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground">
+ Every channel
+ </span>
+ <div className="flex flex-wrap items-center gap-2 md:justify-end">
+ <SyncAllChannelsButton />
+ <RefreshAllReportsButton />
+ <Link
+ href="/channels/new"
+ className="inline-flex h-8 items-center rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:opacity-90"
+ >
+ New channel
+ </Link>
+ </div>
+ </div>
+ </header>
+ <StreamErrorBoundary name="channels-rack" what="The channels">
+ <Suspense
+ fallback={
+ pending === 0 ? (
+ <SkeletonPanel name="channels-rack" height={RACK_EMPTY_PX} />
+ ) : (
+ <SkeletonRows
+ name="channels-rack"
+ rows={pending}
+ rowHeight={RACK_ROW_PX}
+ head={RACK_CHROME_PX}
+ className="min-h-0 flex-1 rounded-md border border-border"
+ />
+ )
+ }
+ >
+ <Rack view={view} />
+ </Suspense>
+ </StreamErrorBoundary>
</div>
);
}
diff --git a/editor/app/components/StreamErrorBoundary.tsx b/editor/app/components/StreamErrorBoundary.tsx
@@ -0,0 +1,68 @@
+"use client";
+
+import { Component, type ReactNode } from "react";
+
+// WHAT A STREAMED SECTION SHOWS WHEN ITS READ THROWS.
+//
+// A page that streams sends its shell first and each slow section when its
+// read is done (StreamSkeleton.tsx). A section's read can fail on its own — a
+// session file that cannot be parsed, a probe that throws — and without a
+// boundary of its own the failure climbs to the route's error page and takes
+// the shell with it: on /settings, the form. With one, the rest of the page
+// stays and the section's place says, in a sentence, that it could not be
+// loaded, and why.
+//
+// NO RETRY. Nothing here asks for the section again. The next render of the
+// page (a refresh, a navigation) hands this boundary new children, and it
+// shows whatever that render produced — the section, or the error again.
+//
+// The message is the error's own. In a production build React replaces a
+// server component's message with a generic one and a digest; the digest is
+// shown, because that is what the server's log names the real error by.
+
+type Props = {
+ // data-stream-error="<name>": the section's name, as its skeleton has it.
+ name: string;
+ // The sentence's subject: "The job list".
+ what: string;
+ // A section whose failure another boundary on the page already reports
+ // (two sections of one read): hold nothing, say nothing.
+ quiet?: boolean;
+ children: ReactNode;
+};
+
+type State = { error: (Error & { digest?: string }) | null };
+
+export class StreamErrorBoundary extends Component<Props, State> {
+ state: State = { error: null };
+
+ static getDerivedStateFromError(error: Error): State {
+ return { error };
+ }
+
+ componentDidUpdate(prev: Props) {
+ // A new render of the page: show what it produced.
+ if (this.state.error && prev.children !== this.props.children) {
+ this.setState({ error: null });
+ }
+ }
+
+ render() {
+ const { error } = this.state;
+ if (!error) return this.props.children;
+ if (this.props.quiet) return null;
+ return (
+ <p
+ role="alert"
+ data-stream-error={this.props.name}
+ className="rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm"
+ >
+ {this.props.what} could not be loaded.{" "}
+ <span className="text-muted-foreground">
+ {error.message}
+ {error.digest ? ` (${error.digest})` : ""}
+ </span>
+ </p>
+ );
+ }
+}
diff --git a/editor/app/components/StreamSkeleton.tsx b/editor/app/components/StreamSkeleton.tsx
@@ -0,0 +1,101 @@
+import type { CSSProperties, ReactNode } from "react";
+
+// WHAT A STREAMED SECTION SHOWS UNTIL ITS READ IS DONE.
+//
+// A page that streams sends its heading and controls at once and each slow
+// section when it is ready. Until then the section's place is held by one of
+// these: a box the size of what is coming, so nothing below it moves when the
+// content arrives. The size comes from what is known without the slow read —
+// a fixed height for a panel, a row count for a table.
+//
+// Every skeleton carries `data-stream-skeleton="<name>"` and the section that
+// replaces it `data-stream-filled="<name>"` (StreamFilled below), which is how
+// e2e/streaming.spec.ts compares the two boxes. Hidden from assistive
+// technology: `aria-busy` on a live region would announce on every refresh,
+// and there is nothing here to read.
+//
+// No "use client": plain markup, usable from a server page and from a client
+// component's Suspense fallback alike.
+
+const PULSE = "animate-pulse rounded bg-muted";
+
+// One panel-shaped block of a fixed height (in px).
+export function SkeletonPanel({
+ name,
+ height,
+ className = "",
+}: {
+ name: string;
+ height: number;
+ className?: string;
+}) {
+ return (
+ <div
+ data-stream-skeleton={name}
+ aria-hidden="true"
+ style={{ height }}
+ className={`rounded-md border border-border bg-card ${className}`}
+ >
+ <div className="flex h-full flex-col gap-3 px-4 py-4">
+ <div className={`${PULSE} h-3 w-32`} />
+ <div className={`${PULSE} min-h-0 flex-1`} />
+ </div>
+ </div>
+ );
+}
+
+// A table-shaped block: a header band and `rows` rows of `rowHeight` px each.
+// `head` is the header's height in px.
+export function SkeletonRows({
+ name,
+ rows,
+ rowHeight,
+ head = 0,
+ className = "",
+ style,
+}: {
+ name: string;
+ rows: number;
+ rowHeight: number;
+ head?: number;
+ className?: string;
+ style?: CSSProperties;
+}) {
+ return (
+ <div
+ data-stream-skeleton={name}
+ aria-hidden="true"
+ style={{ height: head + rows * rowHeight, ...style }}
+ className={`overflow-hidden ${className}`}
+ >
+ {head > 0 && <div style={{ height: head }} className="bg-muted" />}
+ {Array.from({ length: Math.min(rows, 40) }, (_, n) => (
+ <div
+ key={n}
+ style={{ height: rowHeight }}
+ className="flex items-center border-t border-border px-2"
+ >
+ <div className={`${PULSE} h-3 w-full`} />
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// The wrapper of a section that streamed in: the box a skeleton of the same
+// name is compared against.
+export function StreamFilled({
+ name,
+ className,
+ children,
+}: {
+ name: string;
+ className?: string;
+ children: ReactNode;
+}) {
+ return (
+ <div data-stream-filled={name} className={className}>
+ {children}
+ </div>
+ );
+}
diff --git a/editor/app/components/dashboard/DashboardCockpit.tsx b/editor/app/components/dashboard/DashboardCockpit.tsx
@@ -1,10 +1,13 @@
"use client";
+import { Suspense, use, type ReactNode } from "react";
import type { ActiveJobsPayload } from "yt-dlp-transcript-common/views/activeJobs";
import type { WorkersPayload } from "yt-dlp-transcript-common/views/workers";
import type { WidgetActionablePayload } from "yt-dlp-transcript-common/views/widgetActionable";
import type { WidgetSyncPayload } from "yt-dlp-transcript-common/views/widgetSync";
import { usePolledPayload, useNow } from "../../lib/usePolledPayload";
+import { SkeletonPanel, SkeletonRows, StreamFilled } from "../StreamSkeleton";
+import { StreamErrorBoundary } from "../StreamErrorBoundary";
import { PipelineBand } from "./PipelineBand";
import { NeedsWorkPanel } from "./NeedsWorkPanel";
import { QuickAddPanel } from "./QuickAddPanel";
@@ -29,103 +32,207 @@ import { PrioritizeButton } from "../actions/PrioritizeButton";
const FAST_MS = 1000;
const SLOW_MS = 15000;
-export type DashboardCockpitInitial = {
- jobs: ActiveJobsPayload;
- workers: WorkersPayload;
+// WHAT THE CORPUS READ ANSWERS (app/page.tsx `loadCorpus`): the seeds that come
+// off every channel's config and report. One promise, read by the two sections
+// that draw it.
+export type DashboardCorpus = {
actionable: WidgetActionablePayload;
sync: WidgetSyncPayload;
// Built server-side in app/page.tsx and passed straight through — never into
// client state — so a global AutoRefresh re-seeds them live.
channels: ChannelRowView[];
- changelogSource: string | null;
// Set while the corpus has no channel (app/page.tsx): the first-run checklist.
- firstRun?: FirstRunState | null;
+ firstRun: FirstRunState | null;
// The cookie refresh alerts (lib/cookieAlerts.ts), polled SLOW after this.
- cookieAlerts?: ServiceCookieAlertsPayload;
+ cookieAlerts: ServiceCookieAlertsPayload;
// The drive banner (storage/lib/driveHealth.ts), polled SLOW after this.
- driveHealth?: DriveHealthPayload;
+ driveHealth: DriveHealthPayload;
+};
+
+type CockpitProps = {
+ workers: WorkersPayload;
+ // The "Recent changes" card's content, rendered by the server page.
+ changelog: ReactNode;
+ // The two slow reads, STARTED by the page and not awaited there. Each
+ // section below reads the one it needs with `use()` inside its own Suspense
+ // boundary, so the page's shell is sent before either is done.
+ jobs: Promise<ActiveJobsPayload>;
+ corpus: Promise<DashboardCorpus>;
+ // The first-run checklist, when the shell already knows there is no channel
+ // (app/page.tsx): drawn with the heading, not with the live half.
+ firstRun: FirstRunState | null;
+ // What the skeletons are sized by: counts known without the slow reads.
+ pending: { channels: number; jobs: number };
};
const EMPTY_COOKIE_ALERTS: ServiceCookieAlertsPayload = { alerts: [], pending: [] };
const NO_DRIVE_TROUBLE: DriveHealthPayload = { drives: [] };
-// The mission-control cockpit. A server component (app/page.tsx) SSRs the
-// initial payloads for a flicker-free first paint; this client shell then polls
-// the same /api endpoints the widget uses so the whole surface updates in place.
-export function DashboardCockpit({
- initial,
-}: {
- initial: DashboardCockpitInitial;
-}) {
+// The mission-control cockpit. A server component (app/page.tsx) starts the
+// reads; the shell (the heading, "Add a channel", recent changes) is sent at
+// once and two sections stream in behind it — the live half (pipeline band and
+// "Needs work") and the channels table — each seeded for a flicker-free first
+// paint. The live half then polls the same /api endpoints the widget uses, so
+// the whole surface updates in place.
+//
+// A REFRESH NEVER BRINGS A SKELETON BACK. router.refresh() (the global
+// AutoRefresh, any action) is a transition: the new promises suspend, and
+// React keeps the section that is already on screen until they resolve.
+export function DashboardCockpit(props: CockpitProps) {
+ return (
+ <div className="flex flex-col gap-6">
+ <h1 className="sr-only">Dashboard</h1>
+ {props.firstRun && <FirstRunPanel state={props.firstRun} />}
+ <StreamErrorBoundary name="dashboard-pipeline" what="The pipeline and Needs work">
+ <Suspense
+ fallback={
+ <>
+ <SkeletonPanel
+ name="dashboard-pipeline"
+ height={
+ PIPELINE_IDLE_PX +
+ (props.pending.jobs > 0
+ ? PIPELINE_JOBS_CHROME_PX + props.pending.jobs * PIPELINE_JOB_ROW_PX
+ : 0)
+ }
+ />
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">
+ <SkeletonPanel name="dashboard-needs-work" height={NEEDS_WORK_EMPTY_PX} />
+ <QuickAddPanel changelog={props.changelog} />
+ </div>
+ </>
+ }
+ >
+ <CockpitLive {...props} />
+ </Suspense>
+ </StreamErrorBoundary>
+ <StreamErrorBoundary name="dashboard-channels" what="The channels table">
+ <Suspense
+ fallback={
+ props.pending.channels > 0 ? (
+ <section className="flex flex-col gap-3">
+ <h2 className="font-mono text-xs uppercase tracking-[0.14em] text-muted-foreground">
+ Channels
+ </h2>
+ <SkeletonRows
+ name="dashboard-channels"
+ rows={props.pending.channels}
+ rowHeight={CHANNEL_ROW_PX}
+ head={CHANNEL_HEAD_PX}
+ />
+ </section>
+ ) : null
+ }
+ >
+ <CockpitChannels corpus={props.corpus} />
+ </Suspense>
+ </StreamErrorBoundary>
+ </div>
+ );
+}
+
+// THE SKELETONS' SIZES, in px, measured at the desktop width: the idle pipeline
+// band; what a live job list adds to it (its strip and header) and one job's
+// row; the "Needs work" card with nothing in it; the channels table's header
+// and row. e2e/streaming.spec.ts holds each skeleton's box to the box of what
+// replaces it — idle, and with one live job seeded — so a restyle that moves
+// one of these fails there. What is known before the reads is a COUNT, so a
+// section whose height depends on more than that is held to its usual size,
+// not its exact one: a job row with a channel and tasks is a few px taller
+// than this one, a job that just finished is listed for half a minute though
+// it is no longer counted, and "Needs work" is sized for its empty state.
+// The alerts above the band (a drive, a cookie refresh) are not held at all:
+// whether one exists is the answer of the slow read itself.
+const PIPELINE_IDLE_PX = 333;
+const PIPELINE_JOBS_CHROME_PX = 182;
+const PIPELINE_JOB_ROW_PX = 59;
+const NEEDS_WORK_EMPTY_PX = 74;
+const CHANNEL_HEAD_PX = 38;
+const CHANNEL_ROW_PX = 43;
+
+// The live half: the alerts, the pipeline band and "Needs work".
+function CockpitLive({ workers: workersSeed, changelog, jobs: jobsPromise, corpus, firstRun }: CockpitProps) {
+ const seed = use(corpus);
+ const jobsSeed = use(jobsPromise);
const now = useNow();
const { data: jobs } = usePolledPayload<ActiveJobsPayload>(
"/api/view/activeJobs",
true,
FAST_MS,
- initial.jobs,
+ jobsSeed,
);
const { data: workers, refetch: refetchWorkers } =
usePolledPayload<WorkersPayload>(
"/api/view/workers",
true,
FAST_MS,
- initial.workers,
+ workersSeed,
);
const { data: actionable } = usePolledPayload<WidgetActionablePayload>(
"/api/view/widgetActionable",
true,
SLOW_MS,
- initial.actionable,
+ seed.actionable,
);
const { data: sync, refetch: refetchSync } = usePolledPayload<WidgetSyncPayload>(
"/api/view/widgetSync",
true,
SLOW_MS,
- initial.sync,
+ seed.sync,
);
const { data: cookieAlerts, refetch: refetchCookieAlerts } =
usePolledPayload<ServiceCookieAlertsPayload>(
"/api/view/cookieAlerts",
true,
SLOW_MS,
- initial.cookieAlerts ?? EMPTY_COOKIE_ALERTS,
+ seed.cookieAlerts ?? EMPTY_COOKIE_ALERTS,
);
const { data: driveHealth } = usePolledPayload<DriveHealthPayload>(
"/api/view/driveHealth",
true,
SLOW_MS,
- initial.driveHealth ?? NO_DRIVE_TROUBLE,
+ seed.driveHealth ?? NO_DRIVE_TROUBLE,
);
return (
- <div className="flex flex-col gap-6">
- <h1 className="sr-only">Dashboard</h1>
+ <>
<DriveHealthBanner data={driveHealth ?? NO_DRIVE_TROUBLE} />
<CookieAlertsPanel
data={cookieAlerts ?? EMPTY_COOKIE_ALERTS}
onChange={() => void refetchCookieAlerts()}
/>
- {initial.firstRun && <FirstRunPanel state={initial.firstRun} />}
- <PipelineBand
- jobs={jobs}
- workers={workers}
- sync={sync}
- actionable={actionable}
- now={now}
- onWorkersChange={refetchWorkers}
- onSynced={refetchSync}
- />
+ {/* Only when the shell did not already draw it: channel directories
+ exist, but none of them holds a channel. */}
+ {!firstRun && seed.firstRun && <FirstRunPanel state={seed.firstRun} />}
+ <StreamFilled name="dashboard-pipeline">
+ <PipelineBand
+ jobs={jobs}
+ workers={workers}
+ sync={sync}
+ actionable={actionable}
+ now={now}
+ onWorkersChange={refetchWorkers}
+ onSynced={refetchSync}
+ />
+ </StreamFilled>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">
- <NeedsWorkPanel data={actionable} />
- <QuickAddPanel changelogSource={initial.changelogSource} />
+ <StreamFilled name="dashboard-needs-work">
+ <NeedsWorkPanel data={actionable} />
+ </StreamFilled>
+ <QuickAddPanel changelog={changelog} />
</div>
- <DashboardChannels channels={initial.channels} now={now} />
- </div>
+ </>
);
}
+function CockpitChannels({ corpus }: { corpus: Promise<DashboardCorpus> }) {
+ const { channels } = use(corpus);
+ const now = useNow();
+ return <DashboardChannels channels={channels} now={now} />;
+}
+
// The dashboard's channels table: the shared channel table with six columns,
// a relative "last sync" that ticks live, and per-row inline actions (Sync,
// Download missing, and a one-click "Top of queue" that prioritizes the channel
@@ -165,15 +272,17 @@ function DashboardChannels({
<h2 className="font-mono text-xs uppercase tracking-[0.14em] text-muted-foreground">
Channels
</h2>
- <ChannelsTable
- rows={channels}
- columns={DASHBOARD_COLUMNS}
- rowLabelPrefix="channel"
- rowExtras={rowExtras}
- sort={false}
- selection={false}
- now={now}
- />
+ <StreamFilled name="dashboard-channels">
+ <ChannelsTable
+ rows={channels}
+ columns={DASHBOARD_COLUMNS}
+ rowLabelPrefix="channel"
+ rowExtras={rowExtras}
+ sort={false}
+ selection={false}
+ now={now}
+ />
+ </StreamFilled>
</section>
);
}
diff --git a/editor/app/components/dashboard/QuickAddPanel.tsx b/editor/app/components/dashboard/QuickAddPanel.tsx
@@ -1,15 +1,16 @@
"use client";
+import type { ReactNode } from "react";
import Link from "next/link";
-import { Changelog } from "yt-dlp-transcript-common/components/Changelog";
// The quiet right-hand column: a prominent entry into the URL-first onboarding
// flow, and the recent-changes card beneath it (reusing the shared Changelog).
-export function QuickAddPanel({
- changelogSource,
-}: {
- changelogSource: string | null;
-}) {
+//
+// `changelog` is the card's content, already rendered by the server page (the
+// top of the newest entry, app/page.tsx): this component ships no markdown and
+// parses none. The card is clipped at 12rem and has no expand control — the
+// whole changelog is "View all", one link away.
+export function QuickAddPanel({ changelog }: { changelog: ReactNode }) {
return (
<section
aria-label="Quick add and changes"
@@ -29,7 +30,7 @@ export function QuickAddPanel({
</p>
</Link>
- {changelogSource && (
+ {changelog && (
// A plain <div>, not a Link: the Changelog renders its own anchors and
// CopyLink buttons, and wrapping interactive content in an outer <a> is
// invalid nesting that the browser reparents — an SSR hydration
@@ -49,7 +50,7 @@ export function QuickAddPanel({
</Link>
</div>
<div className="relative max-h-48 overflow-hidden">
- <Changelog source={changelogSource} limit={1} />
+ {changelog}
<div
aria-hidden="true"
className="pointer-events-none absolute inset-x-0 bottom-0 h-16 bg-gradient-to-t from-card to-transparent"
diff --git a/editor/app/components/pipelines/StateBand.tsx b/editor/app/components/pipelines/StateBand.tsx
@@ -4,7 +4,7 @@ import {
bandDenominator,
SEGMENTS,
segmentValue,
- type OperationBand,
+ type BandCounts,
} from "yt-dlp-transcript-common/views/pipeline/band";
// THE INSTRUMENT. One component, three scales, one vocabulary.
@@ -49,7 +49,7 @@ export function StateBand({
size,
className = "",
}: {
- band: OperationBand;
+ band: BandCounts;
size: BandSize;
className?: string;
}) {
diff --git a/editor/app/jobs/page.tsx b/editor/app/jobs/page.tsx
@@ -1,6 +1,10 @@
import type { Metadata } from "next";
+import { Suspense } from "react";
import Link from "next/link";
-import { DEFAULT_JOBS_LIMIT } from "yt-dlp-transcript-common/jobs/listJobs";
+import {
+ countAllJobs,
+ DEFAULT_JOBS_LIMIT,
+} from "yt-dlp-transcript-common/jobs/listJobs";
import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
import { getWorkerPool } from "yt-dlp-transcript-common/jobs/workerPool";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
@@ -14,6 +18,9 @@ import { JobsTable } from "./components/JobsTable";
import { RenderModeBanner } from "./components/RenderModeBanner";
import { RetryAllFailedButton } from "./components/RetryAllFailedButton";
import { PauseLaneButton } from "../components/lanes/pauseControl";
+import { SkeletonPanel, StreamFilled } from "../components/StreamSkeleton";
+import { e2eStreamDelay } from "../lib/streamDelay";
+import { StreamErrorBoundary } from "../components/StreamErrorBoundary";
export const dynamic = "force-dynamic";
@@ -35,22 +42,32 @@ function parseLimit(raw: string | string[] | undefined): number {
return Math.min(Math.floor(n), MAX_JOBS_LIMIT);
}
+// What the skeleton is sized by, in px: the list with no job in it, the chrome
+// above a table (the lane strip, the health line, the kind filters, the header
+// row), and one row. e2e/streaming.spec.ts holds the skeleton to the box of
+// what replaces it with no job and with one live and one finished job seeded;
+// a row with a channel and tasks is a few px taller than this one.
+const JOBS_EMPTY_PX = 326;
+const JOBS_CHROME_PX = 412;
+const JOBS_ROW_PX = 59;
+
export default async function JobsPage({
searchParams,
}: {
searchParams: Promise<{ limit?: string | string[] }>;
}) {
const limit = parseLimit((await searchParams).limit);
- const [{ rows, hasMore, total }, initial] = await Promise.all([
- listJobRows(getPaths(), { limit }),
- buildActiveJobsPayload(),
- ]);
+ // THE SHELL: the heading and the controls, from memory (the registry, the
+ // pool) and one readdir. The list itself — a page of sidecar reads and the
+ // live payload, which counts a running job's progress off the disk — streams
+ // in below, behind a skeleton sized by how many rows are coming.
// Base the Retry-all affordance on the registry (what retryAllFailedAction
// actually acts on), not just the loaded page.
const hasRetryableFailed = getRegistry()
.list()
.some((j) => j.status === "failed" && Boolean(j.spec));
const paused = getWorkerPool().isPaused();
+ const pending = Math.min(await countAllJobs(getPaths()), limit);
return (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
@@ -65,6 +82,33 @@ export default async function JobsPage({
</div>
</div>
<RenderModeBanner />
+ <StreamErrorBoundary name="jobs-list" what="The job list">
+ <Suspense
+ fallback={
+ <SkeletonPanel
+ name="jobs-list"
+ height={
+ pending === 0 ? JOBS_EMPTY_PX : JOBS_CHROME_PX + pending * JOBS_ROW_PX
+ }
+ />
+ }
+ >
+ <JobsList limit={limit} />
+ </Suspense>
+ </StreamErrorBoundary>
+ </div>
+ );
+}
+
+// The list: the live head and one page of the history tail.
+async function JobsList({ limit }: { limit: number }) {
+ await e2eStreamDelay("jobs-list");
+ const [{ rows, hasMore, total }, initial] = await Promise.all([
+ listJobRows(getPaths(), { limit }),
+ buildActiveJobsPayload(),
+ ]);
+ return (
+ <StreamFilled name="jobs-list" className="flex flex-col gap-4">
<JobsTable initial={initial} history={rows} total={total} />
{hasMore && (
<div className="flex items-center justify-center gap-3 text-sm">
@@ -80,6 +124,6 @@ export default async function JobsPage({
</Link>
</div>
)}
- </div>
+ </StreamFilled>
);
}
diff --git a/editor/app/lib/streamDelay.ts b/editor/app/lib/streamDelay.ts
@@ -0,0 +1,32 @@
+import { cookies } from "next/headers";
+
+// A TEST SERVER'S WAY TO HOLD A STREAMED SECTION BACK.
+//
+// The pages that stream (the dashboard, /jobs, /settings, /storage, /channels)
+// send their shell first and each slow section when its read is done. Against
+// the e2e fixture every read is over in milliseconds, so a spec could never
+// see a skeleton, measure its box against the box of what replaces it, or
+// prove that a refresh does not bring it back. A spec sets this cookie to a
+// number of milliseconds and every streamed section waits that long before it
+// reads.
+//
+// INERT OUTSIDE A TEST SERVER: without E2E_TEST_ROUTES=1 (the test server's
+// identity, api/test/_guard.ts) the cookie is not even read.
+//
+// A SECOND COOKIE MAKES ONE SECTION FAIL: `e2e-stream-fail=<name>` throws in
+// the section of that name, so a spec can see that a section's failure stays
+// in its own place (StreamErrorBoundary) and the rest of the page stands.
+export const STREAM_DELAY_COOKIE = "e2e-stream-delay";
+export const STREAM_FAIL_COOKIE = "e2e-stream-fail";
+const MAX_DELAY_MS = 5_000;
+
+// `name` is the section's (its skeleton's `data-stream-skeleton`).
+export async function e2eStreamDelay(name?: string): Promise<void> {
+ if (process.env.E2E_TEST_ROUTES !== "1") return;
+ const jar = await cookies();
+ const ms = Math.min(Number(jar.get(STREAM_DELAY_COOKIE)?.value) || 0, MAX_DELAY_MS);
+ if (ms > 0) await new Promise((resolve) => setTimeout(resolve, ms));
+ if (name && jar.get(STREAM_FAIL_COOKIE)?.value === name) {
+ throw new Error(`e2e: the ${name} section was told to fail`);
+ }
+}
diff --git a/editor/app/page.tsx b/editor/app/page.tsx
@@ -1,5 +1,6 @@
import { displayPath } from "yt-dlp-transcript-common/lib/privacy/privacy-server";
import { existsSync, readFileSync } from "node:fs";
+import { cache } from "react";
import type { Metadata } from "next";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { inspectChannelMedia } from "yt-dlp-transcript-common/lib/channelMedia";
@@ -19,7 +20,15 @@ import { buildActiveJobsPayload } from "./jobs/active/buildActiveJobs";
import { buildWorkersPayload } from "./workers/buildWorkers";
import { buildWidgetSyncPayload } from "yt-dlp-transcript-common/views/widgetSync";
import { widgetSyncInputs } from "./widget/lib/syncInputs";
-import { DashboardCockpit } from "./components/dashboard/DashboardCockpit";
+import {
+ DashboardCockpit,
+ type DashboardCorpus,
+} from "./components/dashboard/DashboardCockpit";
+import { Changelog } from "yt-dlp-transcript-common/components/Changelog";
+import { changelogPreview } from "yt-dlp-transcript-common/lib/changelog";
+import { listChannelSlugs } from "yt-dlp-transcript-common/controller/channels";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { e2eStreamDelay } from "./lib/streamDelay";
import { loadCookieAlerts } from "./lib/cookieAlerts";
import { buildDriveHealthPayload } from "./storage/lib/driveHealth";
import {
@@ -59,107 +68,152 @@ function firstRunState(paths: Paths): FirstRunState {
return { workers, siteCount: listSiteIds(paths).length };
}
-function loadChangelog(): string | null {
+// THE "RECENT CHANGES" CARD, RENDERED HERE. The card is 12rem tall and clipped
+// (QuickAddPanel), and "View all" beside it opens /changelog. The whole file
+// used to be handed to the client component as a string — 900 KB, doubled in
+// the document — and the newest entry (160 KB) parsed as markdown on the server
+// and again in the browser, to show its first few lines. What is rendered now
+// is the top of the newest entry, cut on a bullet (changelogPreview), and it
+// is rendered once, on the server: the client gets the elements, not markdown.
+function loadChangelogCard(): React.ReactNode {
try {
- return readFileSync(getPaths().editorChangelogFile, "utf8");
+ const source = readFileSync(getPaths().editorChangelogFile, "utf8");
+ return <Changelog source={changelogPreview(source)} limit={1} />;
} catch {
return null;
}
}
+// EVERYTHING THE DASHBOARD READS OFF THE CORPUS — every channel's config and
+// report, where each one's media is, the sync state, the cookie alerts and the
+// drives. One read for the two sections that draw it (the cockpit's live half
+// and the channels table), started by the page and NOT awaited there: the
+// page's shell is sent first and each section streams in behind its own
+// boundary (DashboardCockpit).
+const loadCorpus = cache(
+ async (paths: Paths, siteParam: string | undefined): Promise<DashboardCorpus> => {
+ await e2eStreamDelay("dashboard-channels");
+ // The active site: a `?site=` link's for this request, else the cookie's.
+ const active = await readActiveSite(siteParam, listSiteIds(paths));
+ const summary = await getActionableSummary(paths);
+
+ // Scope the channel-derived data to the active site's membership. Under
+ // "all sites" the full pool is shown. Job/worker state stays global (pool
+ // state).
+ const inScope = (() => {
+ if (active.isAll || !active.siteId) return () => true;
+ const slugs = siteChannelSlugs(getSite(active.siteId, paths));
+ return (r: ActionableRow) => slugs.has(r.channel.slug);
+ })();
+ const rows = summary.rows.filter(inScope);
+
+ // WHERE EACH CHANNEL'S MEDIA IS — two stats and a small JSON read per row,
+ // with the config already in hand. Not a corpus walk. A row whose drive is
+ // not mounted reports every other number as zero, which is exactly why the
+ // dashboard has to be able to say so rather than drawing a confident zero.
+ const mediaBySlug = new Map(
+ await Promise.all(
+ rows.map(
+ async (r) =>
+ [
+ r.channel.slug,
+ await inspectChannelMedia(paths, r.channel.slug, r.channel.config),
+ ] as const,
+ ),
+ ),
+ );
+ // Read once for the whole table, not once per row.
+ const locations = getSettings().storage.locations;
+ // The shared channel row (common/views/channelRow.ts), drawn by the shared
+ // table with the dashboard's six columns. No pipeline bands and a neutral
+ // priority: this table draws neither.
+ const channels: ChannelRowView[] = rows.map((r) => {
+ const media = mediaBySlug.get(r.channel.slug) ?? null;
+ return buildChannelRowView({
+ slug: r.channel.slug,
+ config: r.channel.config,
+ // From the snapshot rather than a corpus walk, so the Videos figure
+ // lags a sync by the snapshot scheduler's debounce.
+ snapshot: r.snapshot,
+ playlistCount: null,
+ bands: [],
+ priority: neutralChannelPriority(),
+ media,
+ volume: channelVolumeOf(r.channel.config, locations),
+ // The named location, matched against the configured roots from the
+ // media TARGET, as this table always has. A pure prefix match, never a
+ // probe.
+ mediaLocationLabel: media
+ ? locationLabelOfDataDir(media.target, locations)
+ : undefined,
+ // settings.privacy: the badge's "relocated to <path>" as displayed.
+ show: displayPath,
+ });
+ });
+
+ // "Needs work" payload, same shape (and the same two functions) the
+ // /api/view/widgetActionable handler the cockpit polls serves, scoped to
+ // the active site for the SSR seed.
+ const actionable = buildWidgetActionablePayload(widgetActionableRows(rows));
+
+ const [sync, cookieAlerts, driveHealth] = await Promise.all([
+ widgetSyncInputs().then(buildWidgetSyncPayload),
+ loadCookieAlerts(paths),
+ buildDriveHealthPayload(),
+ ]);
+ return {
+ actionable,
+ sync,
+ channels,
+ firstRun: summary.rows.length === 0 ? firstRunState(paths) : null,
+ cookieAlerts,
+ driveHealth,
+ };
+ },
+);
+
+// The live job list: its own read, so a job whose progress has to be counted
+// off the disk (a walk of that channel's data/) holds back only the cockpit's
+// live half, never the page.
+async function loadJobs() {
+ await e2eStreamDelay("dashboard-pipeline");
+ return buildActiveJobsPayload();
+}
+
export default async function Dashboard({
searchParams,
}: {
searchParams: Promise<{ site?: string }>;
}) {
const paths = getPaths();
- // The active site: a `?site=` link's for this request, else the cookie's.
const { site } = await searchParams;
+ // WHAT THE SKELETONS ARE SIZED BY, known without either slow read: how many
+ // channels the table will list (one readdir, narrowed to the active site's
+ // members — a cookie and that site's own file) and how many jobs are live
+ // (memory).
+ const slugs = await listChannelSlugs(paths);
const active = await readActiveSite(site, listSiteIds(paths));
- const summary = await getActionableSummary(paths);
-
- // Scope the channel-derived data to the active site's membership. Under "all
- // sites" the full pool is shown. Job/worker state stays global (pool state).
- const inScope = (() => {
- if (active.isAll || !active.siteId) return () => true;
- const slugs = siteChannelSlugs(getSite(active.siteId, paths));
- return (r: ActionableRow) => slugs.has(r.channel.slug);
- })();
- const rows = summary.rows.filter(inScope);
-
- // Enriched channels table rows (pass-through, not client state, so a global
- // AutoRefresh re-seeds them live).
- // WHERE EACH CHANNEL'S MEDIA IS — two stats and a small JSON read per row,
- // with the config already in hand. Not a corpus walk. A row whose drive is
- // not mounted reports every other number as zero, which is exactly why the
- // dashboard has to be able to say so rather than drawing a confident zero.
- const mediaBySlug = new Map(
- await Promise.all(
- rows.map(
- async (r) =>
- [
- r.channel.slug,
- await inspectChannelMedia(paths, r.channel.slug, r.channel.config),
- ] as const,
- ),
- ),
- );
- // Read once for the whole table, not once per row.
- const locations = getSettings().storage.locations;
- // The shared channel row (common/views/channelRow.ts), drawn by the shared
- // table with the dashboard's six columns. No pipeline bands and a neutral
- // priority: this table draws neither.
- const channels: ChannelRowView[] = rows.map((r) => {
- const media = mediaBySlug.get(r.channel.slug) ?? null;
- return buildChannelRowView({
- slug: r.channel.slug,
- config: r.channel.config,
- // From the snapshot rather than a corpus walk, so the Videos figure lags
- // a sync by the snapshot scheduler's debounce.
- snapshot: r.snapshot,
- playlistCount: null,
- bands: [],
- priority: neutralChannelPriority(),
- media,
- volume: channelVolumeOf(r.channel.config, locations),
- // The named location, matched against the configured roots from the
- // media TARGET, as this table always has. A pure prefix match, never a
- // probe.
- mediaLocationLabel: media
- ? locationLabelOfDataDir(media.target, locations)
- : undefined,
- // settings.privacy: the badge's "relocated to <path>" as displayed.
- show: displayPath,
- });
- });
-
- // "Needs work" payload, same shape (and the same two functions) the
- // /api/view/widgetActionable handler the cockpit polls serves, scoped to the
- // active site for the SSR seed.
- const actionable = buildWidgetActionablePayload(widgetActionableRows(rows));
-
- const [jobs, sync, cookieAlerts, driveHealth] = await Promise.all([
- buildActiveJobsPayload(),
- widgetSyncInputs().then(buildWidgetSyncPayload),
- loadCookieAlerts(paths),
- buildDriveHealthPayload(),
- ]);
- const workers = buildWorkersPayload();
- const changelogSource = loadChangelog();
+ const scope =
+ active.isAll || !active.siteId
+ ? null
+ : siteChannelSlugs(getSite(active.siteId, paths));
+ const channelCount = scope ? slugs.filter((s) => scope.has(s)).length : slugs.length;
+ const liveJobs = getRegistry()
+ .list()
+ .filter((j) => j.status === "running" || j.status === "queued").length;
return (
<DashboardCockpit
- initial={{
- jobs,
- workers,
- actionable,
- sync,
- channels,
- changelogSource,
- firstRun: summary.rows.length === 0 ? firstRunState(paths) : null,
- cookieAlerts,
- driveHealth,
- }}
+ workers={buildWorkersPayload()}
+ changelog={loadChangelogCard()}
+ jobs={loadJobs()}
+ corpus={loadCorpus(paths, site)}
+ // THE FIRST-RUN CHECKLIST IS THE SHELL'S: an archive with no channel
+ // directory is known from the readdir above, and the checklist's facts
+ // are a few stats. Sent with the heading, it does not push the page
+ // down when the live half arrives.
+ firstRun={slugs.length === 0 ? firstRunState(paths) : null}
+ pending={{ channels: channelCount, jobs: liveJobs }}
/>
);
}
diff --git a/editor/app/settings/components/SettingsForm.tsx b/editor/app/settings/components/SettingsForm.tsx
@@ -39,7 +39,9 @@ import {
} from "../../components/SocialLinksField";
type Props = {
- initial: SiteSettings;
+ // The settings WITHOUT `autoQueue` (the lanes' policy trees): this form
+ // reads none of it, and the page does not send it (settings/page.tsx).
+ initial: Omit<SiteSettings, "autoQueue">;
};
export function SettingsForm({ initial }: Props) {
diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx
@@ -1,13 +1,17 @@
import type { Metadata } from "next";
+import { Suspense } from "react";
import Link from "next/link";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { displayPath } from "yt-dlp-transcript-common/lib/privacy/privacy-server";
-import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { getSettings, type SiteSettings } from "yt-dlp-transcript-common/lib/settings";
import { readXSessionStatus } from "yt-dlp-transcript-common/social/xSessionBroker";
import { resolveXCookieSourceFor } from "yt-dlp-transcript-common/social/xBrowserLogin";
import { xCookieSourceView } from "yt-dlp-transcript-common/social/xCookieSource";
import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility";
import { SettingsForm } from "./components/SettingsForm";
+import { SkeletonPanel, StreamFilled } from "../components/StreamSkeleton";
+import { StreamErrorBoundary } from "../components/StreamErrorBoundary";
+import { e2eStreamDelay } from "../lib/streamDelay";
import { xSourceForDisplay } from "../lib/xSourceDisplay";
import { XSessionSection } from "./components/XSessionSection";
import { xMaxCookieAgeMinutes } from "yt-dlp-transcript-common/social/xCookieSource";
@@ -37,14 +41,15 @@ export default async function SettingsPage() {
["galleryDlBin", paths.galleryDlBin],
];
- // The X session broker's current state and the X login source in use (see
- // xSessionActions.ts). The source is resolved here, not read: with no stored
- // choice it depends on cookiesFromBrowser and the profile.
- const xSession = await readXSessionStatus(paths);
- // Drawn by the client: its spec and label through settings.privacy.
- const xSource = xSourceForDisplay(
- xCookieSourceView(await resolveXCookieSourceFor(paths, settings)),
- );
+ // THE FORM GETS WHAT IT EDITS, NOT THE WHOLE FILE. `autoQueue` — the four
+ // lanes' policy trees, most of settings.json on a large corpus — is edited
+ // on the operation pages and /channels and read by nothing in this form, and
+ // it was serialised into the document twice (the HTML and the component
+ // payload). Leaving it out cannot lose it: the save builds its patch from
+ // the submitted fields alone and merges it over the stored file
+ // (settings/actions.ts; pinned in saveSettingsAction.test.ts).
+ const { autoQueue: _autoQueue, ...formSettings } = settings;
+ void _autoQueue;
return (
<div className="flex flex-col gap-8">
@@ -96,21 +101,29 @@ export default async function SettingsPage() {
, beside the workers it describes.
</p>
</div>
- <SettingsForm initial={settings} />
+ <SettingsForm initial={formSettings} />
</section>
+ {/* THE TWO SESSION SECTIONS STREAM. Each reads a session's state off
+ the disk (X's profile and cookie source; archive.today's), and the
+ form above must not wait for either. */}
<section className="flex flex-col gap-3 border-t border-border pt-6">
- <XSessionSection
- initial={xSession}
- initialSource={xSource}
- initialVisibility={xPostsVisibility(settings)}
- initialMaxCookieAge={xMaxCookieAgeMinutes(settings.social.x)}
- />
+ <StreamErrorBoundary name="settings-x" what="The X session section">
+ <Suspense fallback={<SkeletonPanel name="settings-x" height={X_SECTION_PX} />}>
+ <XSection settings={settings} />
+ </Suspense>
+ </StreamErrorBoundary>
</section>
{/* Release 37 lane F: archive.today's host, pace and session. */}
<section className="flex flex-col gap-3 border-t border-border pt-6">
- <ArchiveSourcesSection initial={settings.archives} session={await readArchiveSessionStatus(paths)} />
+ <StreamErrorBoundary name="settings-archives" what="The archive.today section">
+ <Suspense
+ fallback={<SkeletonPanel name="settings-archives" height={ARCHIVE_SECTION_PX} />}
+ >
+ <ArchivesSection settings={settings} />
+ </Suspense>
+ </StreamErrorBoundary>
</section>
<section className="flex flex-col gap-3 border-t border-border pt-6">
@@ -146,3 +159,43 @@ export default async function SettingsPage() {
</div>
);
}
+
+// The skeletons' heights in px: each section as it stands with no session
+// connected (e2e/streaming.spec.ts holds them to the boxes that replace them).
+const X_SECTION_PX = 507;
+const ARCHIVE_SECTION_PX = 198;
+
+// `settings` is the page's one read of the file: the form and both sections
+// draw the same settings, not three reads at three instants.
+async function XSection({ settings }: { settings: SiteSettings }) {
+ await e2eStreamDelay("settings-x");
+ const paths = getPaths();
+ // The X session broker's current state and the X login source in use (see
+ // xSessionActions.ts). The source is resolved here, not read: with no stored
+ // choice it depends on cookiesFromBrowser and the profile.
+ const xSession = await readXSessionStatus(paths);
+ // Drawn by the client: its spec and label through settings.privacy.
+ const xSource = xSourceForDisplay(
+ xCookieSourceView(await resolveXCookieSourceFor(paths, settings)),
+ );
+ return (
+ <StreamFilled name="settings-x" className="flex flex-col gap-3">
+ <XSessionSection
+ initial={xSession}
+ initialSource={xSource}
+ initialVisibility={xPostsVisibility(settings)}
+ initialMaxCookieAge={xMaxCookieAgeMinutes(settings.social.x)}
+ />
+ </StreamFilled>
+ );
+}
+
+async function ArchivesSection({ settings }: { settings: SiteSettings }) {
+ await e2eStreamDelay("settings-archives");
+ const session = await readArchiveSessionStatus(getPaths());
+ return (
+ <StreamFilled name="settings-archives" className="flex flex-col gap-3">
+ <ArchiveSourcesSection initial={settings.archives} session={session} />
+ </StreamFilled>
+ );
+}
diff --git a/editor/app/settings/saveSettingsAction.test.ts b/editor/app/settings/saveSettingsAction.test.ts
@@ -0,0 +1,105 @@
+import { mkdtempSync, readFileSync } from "node:fs";
+import { rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+
+// Run with: pnpm -C editor exec tsx --test "app/**/*.test.ts"
+//
+// THE SETTINGS FORM IS NOT SENT `autoQueue` (settings/page.tsx): the four
+// lanes' policy trees are most of settings.json on a large corpus, the form
+// reads none of them, and they were serialised into /settings twice. That is
+// only safe while a save from the form cannot write settings back without
+// them — which holds because the action builds its patch from the SUBMITTED
+// FIELDS alone and saveSettings merges it over the stored file. This pins it:
+// a save through the real action, from a form that never saw `autoQueue`,
+// leaves every lane's tree, and every other block the form does not edit,
+// exactly as stored.
+//
+// SETTINGS SEAM as in saveSettings.test.ts: getPaths() memoizes, so
+// SETTINGS_FILE is set before the module under test is imported.
+
+const ROOT = mkdtempSync(path.join(os.tmpdir(), "save-settings-action-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+
+const { saveSettingsAction } = await import("./actions");
+const { defaultSiteSettings, getSettings, writeSettings } = await import(
+ "yt-dlp-transcript-common/lib/settings"
+);
+
+after(() => rm(ROOT, { recursive: true, force: true }));
+
+// What the form posts: its own fields, and nothing of any other block.
+function formOf(over: Record<string, string> = {}): FormData {
+ const s = getSettings();
+ const fields: Record<string, string> = {
+ adminTitle: s.adminTitle,
+ homepageUrl: s.homepageUrl ?? "",
+ maxTranscriptPageBytes: String(s.maxTranscriptPageBytes),
+ sleepBetweenDownloadsSeconds: String(s.sleepBetweenDownloadsSeconds),
+ autoRefreshIntervalSeconds: String(s.autoRefreshIntervalSeconds),
+ minFreeDiskGB: String(s.minFreeDiskGB),
+ resumeMarginGB: String(s.resumeMarginGB),
+ pacingJitterPercent: String(Math.round(s.pacing.jitter * 100)),
+ downloadFormat: s.downloadFormat,
+ sourceVideoQuality: s.sourceVideoQuality,
+ reportDebouncePreset: s.reportDebouncePreset,
+ archiveStorageBucket: "",
+ archiveStoragePublicBaseUrl: "",
+ maxParallelBuilds: String(s.buildPipeline.maxParallelBuilds),
+ dockerImage: s.buildPipeline.dockerImage,
+ dockerfile: s.buildPipeline.dockerfile,
+ socialLinksJson: "[]",
+ ...over,
+ };
+ const form = new FormData();
+ for (const [k, v] of Object.entries(fields)) form.set(k, v);
+ return form;
+}
+
+test("a save from the settings form keeps autoQueue, which the form is never sent", async () => {
+ // A stored file whose lanes are NOT the defaults: a held lane, a changed
+ // order, and a policy tree with a channel in it.
+ const stored = defaultSiteSettings();
+ const lanes = Object.keys(stored.autoQueue) as Array<keyof typeof stored.autoQueue>;
+ assert.ok(lanes.length >= 4, "the four lanes");
+ for (const lane of lanes) {
+ const l = stored.autoQueue[lane] as unknown as Record<string, unknown>;
+ l.held = true;
+ l.enabled = true;
+ }
+ stored.channelPriority.channels = { "some-channel": { tier: "low" } };
+ stored.workers = [];
+ await writeSettings(stored);
+ const before = getSettings();
+ assert.equal((before.autoQueue[lanes[0]] as unknown as { held: boolean }).held, true);
+
+ // No field of the form names autoQueue: it has nothing to post it with.
+ const form = formOf({ adminTitle: "Renamed by the form" });
+ assert.deepEqual(
+ [...form.keys()].filter((k) => /autoQueue|channelPriority|workers/i.test(k)),
+ [],
+ );
+
+ const result = await saveSettingsAction(undefined, form);
+ assert.deepEqual(result, { ok: true });
+
+ const after_ = getSettings();
+ assert.equal(after_.adminTitle, "Renamed by the form");
+ assert.deepEqual(after_.autoQueue, before.autoQueue);
+ assert.deepEqual(after_.channelPriority, before.channelPriority);
+ assert.deepEqual(after_.workers, before.workers);
+ // And on disk, not only through the reader's defaults.
+ const raw = JSON.parse(readFileSync(process.env.SETTINGS_FILE!, "utf8"));
+ assert.deepEqual(raw.autoQueue, JSON.parse(JSON.stringify(before.autoQueue)));
+});
+
+test("a refused save writes nothing", async () => {
+ const before = readFileSync(process.env.SETTINGS_FILE!, "utf8");
+ const result = await saveSettingsAction(undefined, formOf({ adminTitle: "" }));
+ assert.equal(result.ok, false);
+ assert.equal(readFileSync(process.env.SETTINGS_FILE!, "utf8"), before);
+});
+
diff --git a/editor/app/storage/page.tsx b/editor/app/storage/page.tsx
@@ -1,9 +1,13 @@
import type { Metadata } from "next";
+import { Suspense } from "react";
import Link from "next/link";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { buildStorage } from "./buildStorage";
import { StorageLocationsTable } from "./components/StorageLocationsTable";
import { HealthTimingForm } from "./components/HealthTimingForm";
+import { SkeletonPanel, StreamFilled } from "../components/StreamSkeleton";
+import { e2eStreamDelay } from "../lib/streamDelay";
+import { StreamErrorBoundary } from "../components/StreamErrorBoundary";
// FORCE-DYNAMIC, and not as a formality. Every number on this page comes from a
// probe of the machine taken when the page was asked for — whether a disk is
@@ -14,9 +18,30 @@ export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Storage" };
-export default async function StoragePage() {
+// The skeleton's size in px (e2e/streaming.spec.ts holds it to the box of what
+// replaces it, with no location and with one seeded): the section with no
+// location in it — the two cards (the saved
+// video store, the clip windows) and the add form's button — and one
+// location's card.
+const STORAGE_BASE_PX = 1034;
+const STORAGE_LOCATION_PX = 284;
+
+// The locations, the store and the clip windows: every figure here is a probe
+// of the machine (is each drive mounted, how much room is on it, how big is
+// the store), so it streams in behind the heading rather than holding it.
+async function StorageBody() {
+ await e2eStreamDelay("storage-locations");
const payload = await buildStorage();
return (
+ <StreamFilled name="storage-locations">
+ <StorageLocationsTable payload={payload} />
+ </StreamFilled>
+ );
+}
+
+export default function StoragePage() {
+ const settings = getSettings();
+ return (
<div className="flex flex-col gap-6">
<div className="flex items-center justify-between flex-wrap gap-2">
<h1 className="text-2xl font-semibold">Storage</h1>
@@ -27,11 +52,25 @@ export default async function StoragePage() {
<Link href="/channels" className="underline">Storage panel</Link>.
</p>
- <StorageLocationsTable payload={payload} />
+ <StreamErrorBoundary name="storage-locations" what="The storage locations">
+ <Suspense
+ fallback={
+ <SkeletonPanel
+ name="storage-locations"
+ height={
+ STORAGE_BASE_PX +
+ settings.storage.locations.length * STORAGE_LOCATION_PX
+ }
+ />
+ }
+ >
+ <StorageBody />
+ </Suspense>
+ </StreamErrorBoundary>
{/* THE TIMINGS EVERY LOCATION IS JUDGED BY (settings.storage.health),
collapsed and last: a page-wide setting, not a fact about a row. */}
- <HealthTimingForm stored={getSettings().storage.health ?? {}} />
+ <HealthTimingForm stored={settings.storage.health ?? {}} />
</div>
);
}
diff --git a/editor/e2e/streaming.spec.ts b/editor/e2e/streaming.spec.ts
@@ -0,0 +1,333 @@
+import { test, expect, type Page } from "@playwright/test";
+import { mkdir } from "node:fs/promises";
+import { join } from "node:path";
+import { resetData, writeSettings } from "./helpers";
+import { testPaths } from "./testPaths";
+
+// THE PAGES THAT STREAM. The dashboard, /jobs, /settings, /storage and
+// /channels send their shell — the sidebar, the heading, the controls — at
+// once, and each slow section when its read is done, behind a <Suspense>
+// boundary whose fallback is a skeleton the size of what is coming.
+//
+// Against this fixture every read is over in milliseconds, so the test server
+// honours a cookie (app/lib/streamDelay.ts, inert outside a test server) that
+// holds every streamed section back. With it a spec can see the three things
+// worth pinning:
+//
+// 1. THE SHELL COMES FIRST: the heading and every skeleton are in the
+// document before any section is. This is an assertion about ORDER in
+// the response, not about a clock.
+// 2. NOTHING MOVES WHEN A SECTION ARRIVES: each skeleton's box is the box of
+// the section that replaces it, to a few px.
+// 3. A REFRESH NEVER BRINGS A SKELETON BACK: router.refresh() (the global
+// AutoRefresh) is a transition, so a section already on screen stays
+// until its new render is ready.
+//
+// 4. A SECTION THAT FAILS FAILS ALONE: its place says so and the rest of
+// the page stands (StreamErrorBoundary) — on /settings, the form.
+//
+// The skeletons are sized by counts (live jobs, jobs listed, storage
+// locations), so the box test also runs with one of each SEEDED, through the
+// test routes and the settings file: the per-row constants are held to a
+// filled box, not only the empty ones.
+//
+// And the one thing streaming must not cost: a page that calls notFound()
+// still answers 404. Only these static routes carry a boundary; none of them
+// can be "not found". (navigation.spec.ts explains what a loading.tsx did to
+// that, and why there is none.)
+
+const DELAY_MS = 1500;
+const TOLERANCE_PX = 4;
+// The first-run checklist, as the document carries it (FirstRunPanel).
+const FIRST_RUN_MARK = 'aria-label="First steps"';
+
+type Streamed = {
+ path: string;
+ heading: string;
+ // data-stream-skeleton / data-stream-filled names, in document order.
+ sections: string[];
+};
+
+const PAGES: Streamed[] = [
+ {
+ path: "/",
+ heading: "Dashboard",
+ sections: ["dashboard-pipeline", "dashboard-needs-work", "dashboard-channels"],
+ },
+ { path: "/jobs", heading: "Jobs", sections: ["jobs-list"] },
+ { path: "/settings", heading: "Settings", sections: ["settings-x", "settings-archives"] },
+ { path: "/storage", heading: "Storage", sections: ["storage-locations"] },
+ { path: "/channels", heading: "Channels", sections: ["channels-freshness", "channels-rack"] },
+];
+
+async function holdSections(page: Page, baseURL: string) {
+ await page.context().addCookies([
+ { name: "e2e-stream-delay", value: String(DELAY_MS), url: baseURL },
+ ]);
+}
+
+// What a browser console must not say on a streamed page: a hydration
+// mismatch, a suspended-outside-a-boundary error, an uncaught exception.
+function watchConsole(page: Page): string[] {
+ const problems: string[] = [];
+ page.on("console", (m) => {
+ if (m.type() === "error") problems.push(m.text());
+ });
+ page.on("pageerror", (e) => problems.push(String(e)));
+ return problems;
+}
+
+// Open `path` with every section held back, measure each skeleton, let the
+// sections arrive, and hold each one's box to its skeleton's.
+async function expectSkeletonsHoldTheirBoxes(
+ page: Page,
+ baseURL: string,
+ { path, heading, sections }: Streamed,
+) {
+ const problems = watchConsole(page);
+ await holdSections(page, baseURL);
+ await page.goto(path, { waitUntil: "commit" });
+ await expect(
+ page.getByRole("heading", { name: heading, level: 1 }),
+ ).toBeAttached();
+ const before: Record<string, { x: number; y: number; width: number; height: number }> = {};
+ for (const name of sections) {
+ const skeleton = page.locator(`[data-stream-skeleton="${name}"]`);
+ await expect(skeleton, name).toBeVisible();
+ before[name] = (await skeleton.boundingBox())!;
+ }
+ for (const name of sections) {
+ const filled = page.locator(`[data-stream-filled="${name}"]`);
+ await expect(filled, name).toBeVisible({ timeout: 15_000 });
+ }
+ await expect(page.locator("[data-stream-skeleton]")).toHaveCount(0);
+ for (const name of sections) {
+ const after = (await page.locator(`[data-stream-filled="${name}"]`).boundingBox())!;
+ const b = before[name];
+ const say = `${name}: skeleton ${JSON.stringify(b)} filled ${JSON.stringify(after)}`;
+ expect.soft(Math.abs(after.y - b.y), say).toBeLessThanOrEqual(TOLERANCE_PX);
+ expect.soft(Math.abs(after.height - b.height), say).toBeLessThanOrEqual(TOLERANCE_PX);
+ expect.soft(Math.abs(after.x - b.x), say).toBeLessThanOrEqual(TOLERANCE_PX);
+ expect.soft(Math.abs(after.width - b.width), say).toBeLessThanOrEqual(TOLERANCE_PX);
+ }
+ expect(problems, problems.join("\n")).toEqual([]);
+}
+
+test.describe("streamed pages", () => {
+ test.beforeEach(async () => {
+ await resetData("channel-with-counts");
+ });
+
+ for (const p of PAGES) {
+ test(`${p.path}: the shell is sent before its sections`, async ({ baseURL }) => {
+ const res = await fetch(baseURL + p.path, {
+ headers: {
+ "Accept-Encoding": "identity",
+ Cookie: `e2e-stream-delay=${DELAY_MS}`,
+ },
+ });
+ expect(res.status).toBe(200);
+ const html = await res.text();
+ // THE SHELL is everything the server sent before the first section: the
+ // document is written in the order it was produced, so what precedes
+ // the first filled block was on its way before any section was ready.
+ // (Its first mention in ANY form: its markup, or the component payload
+ // that describes it, whichever the server wrote first.)
+ const firstFilled = html.indexOf("data-stream-filled");
+ expect(firstFilled, "no section ever streamed in").toBeGreaterThan(0);
+ const shell = html.slice(0, firstFilled);
+ expect(shell, "the heading is not in the shell").toContain("</h1>");
+ for (const name of p.sections) {
+ // Every skeleton is in the shell…
+ expect(shell, name).toContain(`data-stream-skeleton="${name}"`);
+ // …and each section streamed in after it.
+ expect(html.slice(firstFilled), name).toContain(`data-stream-filled="${name}"`);
+ }
+ });
+
+ test(`${p.path}: each skeleton holds the box of the section that replaces it`, async ({
+ page,
+ baseURL,
+ }) => {
+ await expectSkeletonsHoldTheirBoxes(page, baseURL!, p);
+ });
+
+ test(`${p.path}: a refresh never brings a skeleton back`, async ({ page, baseURL }) => {
+ await writeSettings({ autoRefreshIntervalSeconds: 1, adminTitle: "Before Title" });
+ const problems = watchConsole(page);
+ await holdSections(page, baseURL!);
+ await page.goto(p.path);
+ for (const name of p.sections) {
+ await expect(page.locator(`[data-stream-filled="${name}"]`), name).toBeVisible({
+ timeout: 15_000,
+ });
+ }
+ await expect(page.locator("[data-stream-skeleton]")).toHaveCount(0);
+ // Count every skeleton that enters the document from here on.
+ await page.evaluate(() => {
+ const w = window as unknown as { __skeletons: number };
+ w.__skeletons = 0;
+ new MutationObserver(() => {
+ w.__skeletons += document.querySelectorAll("[data-stream-skeleton]").length;
+ }).observe(document.body, { childList: true, subtree: true });
+ });
+ // A change the passive refresher brings in: the sidebar's title is the
+ // root layout's, so seeing the new one means a whole refresh landed —
+ // with every section held back DELAY_MS on the way.
+ await writeSettings({ autoRefreshIntervalSeconds: 1, adminTitle: "After Title" });
+ await expect(page.locator("aside").getByText("After Title")).toBeVisible({
+ timeout: 20_000,
+ });
+ for (const name of p.sections) {
+ await expect(page.locator(`[data-stream-filled="${name}"]`), name).toBeVisible();
+ }
+ expect(
+ await page.evaluate(() => (window as unknown as { __skeletons: number }).__skeletons),
+ ).toBe(0);
+ expect(problems, problems.join("\n")).toEqual([]);
+ });
+ }
+
+ // THE ROW CONSTANTS, HELD TO A FILLED BOX. A fake job from the stuck-job
+ // test route (a running job that has gone quiet: the row the list draws for
+ // it carries its last log line) and, for /jobs, one more that is finished.
+ const fakeJob = async (baseURL: string, queue: string): Promise<string> =>
+ ((await (await fetch(`${baseURL}/api/test/stuck-job?queue=${queue}`)).json()) as { id: string }).id;
+ const release = (baseURL: string, id: string) =>
+ fetch(`${baseURL}/api/test/stuck-job?release=${id}`);
+
+ test("/: the pipeline band's skeleton holds its box with a live job in it", async ({
+ page,
+ baseURL,
+ }) => {
+ const id = await fakeJob(baseURL!, "streaming-live");
+ try {
+ await expectSkeletonsHoldTheirBoxes(page, baseURL!, {
+ path: "/",
+ heading: "Dashboard",
+ sections: ["dashboard-pipeline", "dashboard-needs-work", "dashboard-channels"],
+ });
+ await expect(
+ page.locator('[data-stream-filled="dashboard-pipeline"] tbody tr'),
+ ).toHaveCount(1);
+ } finally {
+ await release(baseURL!, id);
+ }
+ });
+
+ test("/jobs: the list's skeleton holds its box with a live and a finished job in it", async ({
+ page,
+ baseURL,
+ request,
+ }) => {
+ const live = await fakeJob(baseURL!, "streaming-live");
+ const done = await fakeJob(baseURL!, "streaming-done");
+ try {
+ await release(baseURL!, done);
+ // The finished one has to BE finished before the page is asked for.
+ await expect
+ .poll(async () => {
+ const payload = (await (await request.get("/api/jobs/active")).json()) as {
+ jobs: { id: string }[];
+ };
+ return payload.jobs.map((j) => j.id);
+ })
+ .toEqual([live]);
+ await expectSkeletonsHoldTheirBoxes(page, baseURL!, {
+ path: "/jobs",
+ heading: "Jobs",
+ sections: ["jobs-list"],
+ });
+ await expect(page.locator('[data-stream-filled="jobs-list"] tbody tr')).toHaveCount(2);
+ } finally {
+ await release(baseURL!, live);
+ }
+ });
+
+ test("/storage: the skeleton holds its box with a location configured", async ({
+ page,
+ baseURL,
+ }) => {
+ const root = join(testPaths().transcriptsDir, ".streaming-location");
+ await mkdir(root, { recursive: true });
+ await writeSettings({
+ storage: {
+ locations: [{ id: "cold", label: "Cold", root, autoRepoint: false }],
+ defaultLocationId: "cold",
+ },
+ });
+ await expectSkeletonsHoldTheirBoxes(page, baseURL!, {
+ path: "/storage",
+ heading: "Storage",
+ sections: ["storage-locations"],
+ });
+ await expect(page.getByLabel("storage location: cold")).toBeVisible();
+ });
+
+ // A SECTION THAT FAILS FAILS ALONE. The test server makes one section throw
+ // (the `e2e-stream-fail` cookie, app/lib/streamDelay.ts).
+ test("/settings: a session section that throws leaves the form and the other section standing", async ({
+ page,
+ baseURL,
+ }) => {
+ await page.context().addCookies([
+ { name: "e2e-stream-fail", value: "settings-x", url: baseURL! },
+ ]);
+ await page.goto("/settings");
+ const failed = page.locator('[data-stream-error="settings-x"]');
+ await expect(failed).toBeVisible();
+ await expect(failed).toContainText("The X session section could not be loaded.");
+ // The form is there and saves.
+ await expect(page.getByRole("heading", { name: "Settings", level: 1 })).toBeVisible();
+ await page.getByLabel(/auto-refresh interval/i).fill("0");
+ await page.getByRole("button", { name: /save settings/i }).click();
+ await expect(page.getByRole("status").filter({ hasText: "Saved" })).toBeVisible();
+ // The other streamed section arrived; nothing is left waiting.
+ await expect(page.locator('[data-stream-filled="settings-archives"]')).toBeVisible();
+ await expect(page.locator("[data-stream-skeleton]")).toHaveCount(0);
+ await expect(page.locator('[data-stream-error="settings-archives"]')).toHaveCount(0);
+ });
+
+ test("the other pages: a section that throws says so in its place, under the heading", async ({
+ page,
+ baseURL,
+ }) => {
+ const cases = [
+ { path: "/", heading: "Dashboard", name: "dashboard-pipeline", text: "The pipeline and Needs work could not be loaded." },
+ { path: "/jobs", heading: "Jobs", name: "jobs-list", text: "The job list could not be loaded." },
+ { path: "/storage", heading: "Storage", name: "storage-locations", text: "The storage locations could not be loaded." },
+ { path: "/channels", heading: "Channels", name: "channels-rack", text: "The channels could not be loaded." },
+ ];
+ for (const c of cases) {
+ await page.context().clearCookies();
+ await page.context().addCookies([{ name: "e2e-stream-fail", value: c.name, url: baseURL! }]);
+ await page.goto(c.path);
+ await expect(page.getByRole("heading", { name: c.heading, level: 1 }), c.path).toBeAttached();
+ await expect(page.locator(`[data-stream-error="${c.name}"]`), c.path).toContainText(c.text);
+ // The sidebar still works: the page is not the route's error page.
+ await expect(page.locator("aside").getByRole("link", { name: "Jobs", exact: true }).first()).toBeVisible();
+ }
+ });
+
+ // THE FIRST-RUN CHECKLIST IS PART OF THE SHELL: with no channel at all it is
+ // sent with the heading, so it cannot push the page down when the live half
+ // arrives.
+ test("/: with no channel, the first-run checklist is in the shell", async ({ baseURL }) => {
+ await resetData("empty");
+ const res = await fetch(baseURL + "/", {
+ headers: { "Accept-Encoding": "identity", Cookie: `e2e-stream-delay=${DELAY_MS}` },
+ });
+ const html = await res.text();
+ const shell = html.slice(0, html.indexOf("data-stream-filled"));
+ expect(shell).toContain(FIRST_RUN_MARK);
+ // Once, not again with the live half.
+ expect(html.split(FIRST_RUN_MARK).length - 1).toBe(1);
+ });
+
+ // The regression guard beside navigation.spec.ts's: a boundary on the static
+ // routes must not turn another route's notFound() into a 200.
+ test("a channel that does not exist still answers 404", async ({ request }) => {
+ const res = await request.get("/channels/this-channel-does-not-exist");
+ expect(res.status()).toBe(404);
+ });
+});
diff --git a/umtool/app/page.tsx b/umtool/app/page.tsx
@@ -1,3 +1,4 @@
+import { cache, Suspense } from "react";
import Link from "next/link";
import InboxList, { type InboxCard, type InboxGroup } from "@/components/inbox/InboxList";
import { UndoBar } from "@/components/piece/Lifecycle";
@@ -19,6 +20,7 @@ import RunningList from "@/components/shell/RunningList";
import RecentCuts from "@/components/shell/RecentCuts";
import { initialRunning } from "@/lib/activity";
import { projectRefs } from "@/lib/projects";
+import { e2eStreamDelay } from "@/lib/streamDelay";
export const dynamic = "force-dynamic";
@@ -96,12 +98,15 @@ function hiddenCards(items: Decision[], keep: (d: Decision) => boolean, lifeOf:
);
}
-export default async function Inbox({
- searchParams,
-}: {
- searchParams: Promise<{ hidden?: string; muted?: string }>;
-}) {
- const { hidden: showHidden, muted: showMuted } = await searchParams;
+// EVERYTHING THE INBOX READS — every project's open decisions, the piece
+// graph, the lifecycle, the mutes, the machine's calls, each card's play link.
+// It is the slow part of this page (seconds on a few hundred projects, more on
+// a busy machine), so the page starts it and does not await it: the shell —
+// the rail, the header, Quick clip, what is running, the recent cuts — is sent
+// at once and the Inbox streams in behind a placeholder. One read per request,
+// shared by the three places that draw it.
+const loadInbox = cache(async (showHidden: boolean, showMuted: boolean) => {
+ await e2eStreamDelay();
// settings.privacy.hidePrivateSites: the private sites' cards are left out.
const inbox = await readInbox({ hide: await privateFilter() });
const lifeOf = new Map<string, LifecycleState>();
@@ -143,6 +148,113 @@ export default async function Inbox({
const refs = await projectRefs();
await Promise.all(all.flatMap((g) => g.cards.map(async (c) => (c.play = await playHrefOfPiece(c.piece, c.action.href, refs)))));
+ return { inbox, all, head, parkedN };
+});
+
+type InboxView = ReturnType<typeof loadInbox>;
+
+// The header's two toggles: how many decisions are muted, how many hidden.
+async function InboxToggles({ view, showHidden, showMuted }: { view: InboxView; showHidden: boolean; showMuted: boolean }) {
+ const { inbox, parkedN } = await view;
+ return (
+ <>
+ {inbox.muted > 0 && (
+ <Link
+ href={homeHref({ muted: !showMuted, hidden: showHidden })}
+ prefetch={false}
+ data-show-muted={showMuted ? "1" : "0"}
+ aria-pressed={showMuted}
+ className={buttonVariants({ variant: "quiet", size: "md" })}
+ >
+ {showMuted ? "Hide muted" : `Muted ${inbox.muted}`}
+ </Link>
+ )}
+ {parkedN > 0 && (
+ <Link
+ href={homeHref({ hidden: !showHidden, muted: showMuted })}
+ prefetch={false}
+ data-show-hidden={showHidden ? "1" : "0"}
+ aria-pressed={showHidden}
+ className={buttonVariants({ variant: "quiet", size: "md" })}
+ >
+ {showHidden ? "Hide hidden" : `Show hidden ${parkedN}`}
+ </Link>
+ )}
+ </>
+ );
+}
+
+async function InboxErrors({ view }: { view: InboxView }) {
+ const { inbox } = await view;
+ return (
+ <>
+ {inbox.lifecycleError && (
+ <p role="alert" className="mb-3 text-[12.5px] text-reject-text">
+ {inbox.lifecycleError} — every piece reads as active until it is fixed.
+ </p>
+ )}
+ {inbox.mutesError && (
+ <p role="alert" className="mb-3 text-[12.5px] text-reject-text">
+ {inbox.mutesError} — nothing reads as muted until it is fixed.
+ </p>
+ )}
+ </>
+ );
+}
+
+// The count and the cards.
+async function InboxBody({ view }: { view: InboxView }) {
+ const { all, head } = await view;
+ return (
+ <div data-stream-filled="inbox">
+ <div className="mb-1 mt-1 flex items-end gap-3.5" data-inbox-count={head.calls}>
+ <span className="display text-[72px] font-[850] leading-[0.8]">{head.calls}</span>
+ <span className="pb-0.5 text-[13px] text-text-2">
+ {head.calls === 1 ? "call waiting on you" : "calls waiting on you"}
+ <small className="block text-[12px] text-muted" data-inbox-note="">
+ {headlineNote(head)}
+ </small>
+ </span>
+ </div>
+
+ <InboxList groups={all} />
+ </div>
+ );
+}
+
+// What holds the Inbox's place: the count's line at its real size, and a few
+// card-shaped rows. Nothing sits below the Inbox in its column, so its height
+// is open: only where it starts and how wide it is must not move.
+function InboxPlaceholder() {
+ return (
+ <div data-stream-skeleton="inbox" aria-hidden="true">
+ {/* The count's line, at its real size, with nothing to read in it. */}
+ <div className="mb-1 mt-1 flex items-end gap-3.5">
+ <span className="display animate-pulse rounded-md bg-panel text-[72px] font-[850] leading-[0.8] text-transparent">0</span>
+ <span className="pb-0.5 text-[13px] text-transparent">
+ calls waiting on you
+ <small className="block text-[12px]"> </small>
+ </span>
+ </div>
+ <div className="mt-4 space-y-2">
+ {[0, 1, 2, 3].map((n) => (
+ <div key={n} className="h-[58px] animate-pulse rounded-md border border-seam bg-panel" />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+export default async function Inbox({
+ searchParams,
+}: {
+ searchParams: Promise<{ hidden?: string; muted?: string }>;
+}) {
+ const sp = await searchParams;
+ const showHidden = !!sp.hidden;
+ const showMuted = !!sp.muted;
+ const view = loadInbox(showHidden, showMuted);
+
return (
<div className="flex h-full flex-col">
<AppShell
@@ -151,57 +263,23 @@ export default async function Inbox({
actions={
<>
<ResumeChip />
- {inbox.muted > 0 && (
- <Link
- href={homeHref({ muted: !showMuted, hidden: !!showHidden })}
- prefetch={false}
- data-show-muted={showMuted ? "1" : "0"}
- aria-pressed={!!showMuted}
- className={buttonVariants({ variant: "quiet", size: "md" })}
- >
- {showMuted ? "Hide muted" : `Muted ${inbox.muted}`}
- </Link>
- )}
- {parkedN > 0 && (
- <Link
- href={homeHref({ hidden: !showHidden, muted: !!showMuted })}
- prefetch={false}
- data-show-hidden={showHidden ? "1" : "0"}
- aria-pressed={!!showHidden}
- className={buttonVariants({ variant: "quiet", size: "md" })}
- >
- {showHidden ? "Hide hidden" : `Show hidden ${parkedN}`}
- </Link>
- )}
+ <Suspense fallback={null}>
+ <InboxToggles view={view} showHidden={showHidden} showMuted={showMuted} />
+ </Suspense>
</>
}
/>
<main className="deck-main flex-1 px-4 pb-6 pt-4">
- {inbox.lifecycleError && (
- <p role="alert" className="mb-3 text-[12.5px] text-reject-text">
- {inbox.lifecycleError} — every piece reads as active until it is fixed.
- </p>
- )}
- {inbox.mutesError && (
- <p role="alert" className="mb-3 text-[12.5px] text-reject-text">
- {inbox.mutesError} — nothing reads as muted until it is fixed.
- </p>
- )}
+ <Suspense fallback={null}>
+ <InboxErrors view={view} />
+ </Suspense>
<div className="grid gap-x-6 gap-y-5 min-[1280px]:grid-cols-[minmax(0,1fr)_300px]">
<div className="min-w-0">
- <div className="mb-1 mt-1 flex items-end gap-3.5" data-inbox-count={head.calls}>
- <span className="display text-[72px] font-[850] leading-[0.8]">{head.calls}</span>
- <span className="pb-0.5 text-[13px] text-text-2">
- {head.calls === 1 ? "call waiting on you" : "calls waiting on you"}
- <small className="block text-[12px] text-muted" data-inbox-note="">
- {headlineNote(head)}
- </small>
- </span>
- </div>
-
- <InboxList groups={all} />
+ <Suspense fallback={<InboxPlaceholder />}>
+ <InboxBody view={view} />
+ </Suspense>
</div>
<aside data-home-aside="" className="min-w-0 space-y-4 min-[1280px]:sticky min-[1280px]:top-4 min-[1280px]:self-start">
<QuickClip />
diff --git a/umtool/e2e/streaming.spec.ts b/umtool/e2e/streaming.spec.ts
@@ -0,0 +1,113 @@
+import { test, expect, type Page } from "@playwright/test";
+import * as urls from "./urls";
+import { warm, WARM_TIMEOUT } from "./warm";
+
+// ---------------------------------------------------------------------------
+// THE HOME PAGE STREAMS. Its shell — the rail, the header, Quick clip, what is
+// running, the recent cuts — is sent at once, and the Inbox (every project's
+// open decisions: the slow read) when it is done, behind a placeholder.
+//
+// Against the fixture that read is over in milliseconds, so the app server
+// honours a cookie (lib/streamDelay.ts; E2E_UMTOOL_STREAM_DELAY, set by
+// playwright.config.ts) that holds the Inbox back. With it:
+// 1. the shell is in the document before the Inbox is (its ORDER in the
+// response, not a clock);
+// 2. the Inbox starts where its placeholder started, at its width (nothing
+// sits below it in its column, so its height is open);
+// 3. a refresh never brings the placeholder back.
+// WRITES the fixture's REPORTS_ROOT/.umtool/lifecycle.json (zeta parked, then
+// active again), as inbox.spec does.
+// ---------------------------------------------------------------------------
+
+// A piece with open calls in the fixture (inbox.spec parks the same one).
+const ZETA = "a:articles/zeta";
+const DELAY_MS = 1500;
+const TOLERANCE_PX = 4;
+
+async function holdInbox(page: Page, baseURL: string) {
+ await page.context().addCookies([{ name: "e2e-stream-delay", value: String(DELAY_MS), url: baseURL }]);
+}
+
+function watchConsole(page: Page): string[] {
+ const problems: string[] = [];
+ page.on("console", (m) => {
+ if (m.type() === "error") problems.push(m.text());
+ });
+ page.on("pageerror", (e) => problems.push(String(e)));
+ return problems;
+}
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ await warm(playwright, ["/"]);
+});
+
+test("the shell is sent before the Inbox", async ({ baseURL }) => {
+ const res = await fetch(baseURL + urls.homeHref(), {
+ headers: { "Accept-Encoding": "identity", Cookie: `e2e-stream-delay=${DELAY_MS}` },
+ });
+ expect(res.status).toBe(200);
+ const html = await res.text();
+ // THE SHELL is everything the server sent before the Inbox: the document is
+ // written in the order it was produced. An assertion about order, not about
+ // a clock.
+ // (The first mention of the filled block in ANY form: its markup, or the
+ // component payload that describes it, whichever the server wrote first.)
+ const filledAt = html.indexOf("data-stream-filled");
+ expect(filledAt, "the Inbox never streamed in").toBeGreaterThan(0);
+ const shell = html.slice(0, filledAt);
+ // The rail, the aside and the placeholder are in it; the count is not.
+ expect(shell).toContain("data-app-rail");
+ expect(shell).toContain("data-home-aside");
+ expect(shell).toContain('data-stream-skeleton="inbox"');
+ expect(shell).not.toContain("data-inbox-count");
+ expect(html.slice(filledAt)).toContain("data-inbox-count");
+ expect(html.slice(filledAt)).toContain('data-stream-filled="inbox"');
+});
+
+test("the Inbox starts where its placeholder did, and a refresh never brings the placeholder back", async ({ page, request, baseURL }) => {
+ const problems = watchConsole(page);
+ await holdInbox(page, baseURL!);
+ await page.goto(urls.homeHref(), { waitUntil: "commit" });
+ const placeholder = page.locator('[data-stream-skeleton="inbox"]');
+ await expect(placeholder).toBeVisible();
+ // The shell is usable while the Inbox is still being read.
+ await expect(page.locator("[data-app-rail] [data-place=inbox]")).toBeVisible();
+ await expect(page.locator("[data-home-aside]")).toBeVisible();
+ const before = (await placeholder.boundingBox())!;
+
+ const filled = page.locator('[data-stream-filled="inbox"]');
+ await expect(filled).toBeVisible({ timeout: 20_000 });
+ await expect(page.locator("[data-stream-skeleton]")).toHaveCount(0);
+ await expect(page.locator("[data-inbox-count]")).toBeVisible();
+ const after = (await filled.boundingBox())!;
+ const say = `placeholder ${JSON.stringify(before)} filled ${JSON.stringify(after)}`;
+ expect(Math.abs(after.x - before.x), say).toBeLessThanOrEqual(TOLERANCE_PX);
+ expect(Math.abs(after.y - before.y), say).toBeLessThanOrEqual(TOLERANCE_PX);
+ expect(Math.abs(after.width - before.width), say).toBeLessThanOrEqual(TOLERANCE_PX);
+ // The count's line is the placeholder's first line, to the pixel row.
+ const line = (await page.locator("[data-inbox-count]").boundingBox())!;
+ expect(Math.abs(line.y - before.y), say).toBeLessThanOrEqual(TOLERANCE_PX);
+
+ // A refresh, with the Inbox held back again: the list on screen stays until
+ // the new one is ready. A piece is parked out of band so the refresh has
+ // something to bring in — the count moving is the proof that it landed.
+ const count = page.locator("[data-inbox-count]");
+ const was = await count.getAttribute("data-inbox-count");
+ await page.evaluate(() => {
+ const w = window as unknown as { __skeletons: number };
+ w.__skeletons = 0;
+ new MutationObserver(() => {
+ w.__skeletons += document.querySelectorAll("[data-stream-skeleton]").length;
+ }).observe(document.body, { childList: true, subtree: true });
+ });
+ try {
+ expect((await request.post("/api/pieces/lifecycle", { data: { piece: ZETA, state: "parked" } })).status()).toBe(200);
+ await page.evaluate(() => (window as unknown as { next: { router: { refresh(): void } } }).next.router.refresh());
+ await expect(count).not.toHaveAttribute("data-inbox-count", was!, { timeout: 20_000 });
+ expect(await page.evaluate(() => (window as unknown as { __skeletons: number }).__skeletons)).toBe(0);
+ } finally {
+ await request.post("/api/pieces/lifecycle", { data: { piece: ZETA, state: "active" } });
+ }
+ expect(problems, problems.join("\n")).toEqual([]);
+});
diff --git a/umtool/e2e/visual-audit.spec.ts b/umtool/e2e/visual-audit.spec.ts
@@ -206,7 +206,10 @@ test("keyboard only: Inbox → a piece → its bench → the piece → the Inbox
await page.setViewportSize({ width: 1366, height: 768 });
await page.goto(urls.homeHref());
await expect(page.locator("dialog[data-jump][data-ready]")).toBeAttached();
- // The Inbox's lit list: j/k move the light and the focus with it.
+ // The Inbox's lit list: j/k move the light and the focus with it. The list
+ // streams in after the shell (app/page.tsx), so the keys wait for it to be
+ // there and listening.
+ await expect(page.locator("[data-lit-list][data-hydrated]").first()).toBeAttached();
await page.keyboard.press("j");
await page.keyboard.press("k");
expect(await page.evaluate(() => !!document.activeElement?.closest("[data-lit-line]"))).toBe(true);
diff --git a/umtool/lib/streamDelay.ts b/umtool/lib/streamDelay.ts
@@ -0,0 +1,21 @@
+import { cookies } from "next/headers";
+
+// A TEST SERVER'S WAY TO HOLD A STREAMED SECTION BACK (the Inbox, app/page.tsx).
+//
+// The home page sends its shell first and the Inbox when its read is done.
+// Against the e2e fixture that read is over in milliseconds, so a spec could
+// never see the placeholder, or prove a refresh does not bring it back. A spec
+// sets this cookie to a number of milliseconds and the Inbox waits that long
+// before it reads.
+//
+// INERT OUTSIDE THE E2E SERVER: without E2E_UMTOOL_STREAM_DELAY=1 (set by
+// playwright.config.ts on the app server only) the cookie is not even read.
+export const STREAM_DELAY_COOKIE = "e2e-stream-delay";
+const MAX_DELAY_MS = 5_000;
+
+export async function e2eStreamDelay(): Promise<void> {
+ if (process.env.E2E_UMTOOL_STREAM_DELAY !== "1") return;
+ const raw = (await cookies()).get(STREAM_DELAY_COOKIE)?.value;
+ const ms = Math.min(Number(raw) || 0, MAX_DELAY_MS);
+ if (ms > 0) await new Promise((resolve) => setTimeout(resolve, ms));
+}
diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts
@@ -52,6 +52,11 @@ import { dataRootRefusal } from "./lib/e2eEnvGuard.mjs";
// E2E_UMTOOL_OPEN_FOLDER_LOG set below on the app server: where the clip
// export's Open folder records what it was asked to
// show, in place of a file manager (lib/report/openFolder.mjs)
+// E2E_UMTOOL_STREAM_DELAY set below on the app server: the home page's
+// streamed Inbox honours a spec's `e2e-stream-delay`
+// cookie (milliseconds to wait before it reads), so
+// streaming.spec can see the placeholder
+// (lib/streamDelay.ts); unset, the cookie is not read
// E2E_CASE_STAGES_SHOTS a directory, set by whoever runs the suite: the
// research case stages' screenshots go there
// (case-stages.spec.ts, release 38 lane C)
@@ -267,6 +272,9 @@ export default defineConfig({
// Open folder (a clip's export) records the ask instead of opening a file manager.
`E2E_UMTOOL_OPEN_FOLDER_LOG=${FIXTURE}/open-folder.jsonl ` +
`E2E_DIGEST_CONTEXT_PLAN=${FIXTURE}/digest-context-review.md ` +
+ // The home page's Inbox waits as long as a spec's `e2e-stream-delay`
+ // cookie says before it reads (lib/streamDelay.ts; streaming.spec).
+ `E2E_UMTOOL_STREAM_DELAY=1 ` +
// No background refresh check (R4, lib/inbox/refresh.ts): an Inbox read
// would otherwise enumerate every fixture article's corpus and add cards
// other specs count. refresh.spec runs the check itself, through its route.