commit bb58d02f8d503a8726d89a2618a92bb309022000
parent c302699c4f68ac7744f9bb3deb1c181970094d95
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 15 Oct 2026 08:01:59 -0400
editor: the active-site cookie is written by POST /api/active-site (same-origin JSON), no longer a server action — a cookie set in an action re-rendered through the router after its answer, so the picker's push on a site's page could discard it and have its replayed refresh commit the push as a replace (Back skipped the page: site-scope.spec ~1/13), and under load a re-scope waited seconds on prefetches; the provider refreshes after a write unless the caller navigates. The drive health timing's save no longer revalidates /storage (its "Saved." waited on the router: storage-locations.spec:723) and the form refreshes after the answer, as Settings does. e2e: site-scope's `hydrated` waits on the picker's data-hydrated (every first-commit effect has run, the provider's BroadcastChannel subscription with them); publish-lane waits on the lane's held state (publishStatus), then reads the page fresh
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 133 insertions(+), 71 deletions(-)
diff --git a/editor/app/api/active-site/route.ts b/editor/app/api/active-site/route.ts
@@ -0,0 +1,55 @@
+import { cookies } from "next/headers";
+import { ACTIVE_SITE_COOKIE_MAX_AGE, isStorableActiveSite } from "../../lib/activeSite";
+import { activeSiteCookieForRequest } from "../../lib/activeSiteServer";
+
+export const dynamic = "force-dynamic";
+
+// THE ONE WRITER of the active-site cookie (see app/lib/activeSite.ts): POST
+// `{ value }` from SiteScopeProvider — the picker's choice, a site's own page
+// recording itself, the localStorage migration — answers `{ ok }`.
+//
+// A ROUTE, NOT A SERVER ACTION (release 29 D1). A cookie set in a server action
+// makes Next re-render the page in the action's answer and apply it through
+// the router — answered BEFORE that applies, so a navigation the caller made
+// next (the picker on a site's page pushes the other site's) discarded the
+// pending action and replayed it as a refresh after the push, and when React
+// committed the two together the push's history entry was written as a
+// replace (Back skipped the page the choice was made on); and under load the
+// re-render waited on in-flight prefetches, so a re-scope came seconds late
+// (site-scope.spec). Here the write is only a write: the provider refreshes,
+// or the picker navigates, itself.
+//
+// Same-origin only (a cross-site page could otherwise flip an operator's
+// scope): JSON, and an Origin, when sent, that is this host. The value is only
+// SHAPE-checked (a site id or "__all__"): whether it names a configured site is
+// decided at every read, so a site deleted later resolves as no selection.
+export async function POST(request: Request): Promise<Response> {
+ const origin = request.headers.get("origin");
+ const host = request.headers.get("host");
+ if (origin !== null && (() => {
+ try {
+ return new URL(origin).host !== host;
+ } catch {
+ return true;
+ }
+ })()) {
+ return Response.json({ ok: false, error: "cross-origin" }, { status: 403 });
+ }
+ if (!(request.headers.get("content-type") ?? "").startsWith("application/json")) {
+ return Response.json({ ok: false, error: "expected JSON" }, { status: 415 });
+ }
+ const body = (await request.json().catch(() => null)) as { value?: unknown } | null;
+ const value = body?.value;
+ if (typeof value !== "string" || !isStorableActiveSite(value)) {
+ return Response.json({ ok: false, error: "not a site id or __all__" }, { status: 400 });
+ }
+ const name = await activeSiteCookieForRequest();
+ (await cookies()).set(name, value, {
+ path: "/",
+ sameSite: "lax",
+ maxAge: ACTIVE_SITE_COOKIE_MAX_AGE,
+ // Only the server reads it: the page gets it through the layout.
+ httpOnly: true,
+ });
+ return Response.json({ ok: true }, { headers: { "cache-control": "no-store" } });
+}
diff --git a/editor/app/components/SiteScopeProvider.tsx b/editor/app/components/SiteScopeProvider.tsx
@@ -17,7 +17,21 @@ import {
isStorableActiveSite,
siteIdFromPathname,
} from "../lib/activeSite";
-import { setActiveSiteAction } from "../lib/activeSiteActions";
+
+// The cookie's one writer (app/api/active-site/route.ts): true when it is set.
+async function writeActiveSite(value: string): Promise<boolean> {
+ try {
+ const res = await fetch("/api/active-site", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ value }),
+ cache: "no-store",
+ });
+ return res.ok && ((await res.json()) as { ok?: boolean }).ok === true;
+ } catch {
+ return false;
+ }
+}
// THE SITE SCOPE, supplied once by the root layout (see app/lib/activeSite.ts).
//
@@ -46,8 +60,8 @@ import { setActiveSiteAction } from "../lib/activeSiteActions";
// cookie gets it copied into the cookie, then the key is removed. That is the
// only localStorage read, and the one paint it may cost is on the first visit
// after the update.
-// Both only WRITE the cookie (`record`); the value comes back through the
-// server's re-render. They run as the page hydrates, and a state change there
+// Both only WRITE the cookie (`record`), then refresh: the value comes back
+// through the server's re-render. They run as the page hydrates, and a state change there
// would re-render the picker before React replays a choice made on the
// server-rendered select before hydration: the re-render resets the select to
// its old value, and the replayed change reads that instead of the choice.
@@ -56,10 +70,12 @@ type SiteScope = {
// The stored selection: a site id or "__all__". The picker resolves it
// against the path and a `?site=` param; it is not the effective scope alone.
stored: string;
- // Store a choice: shown at once, written through setActiveSiteAction. Resolves
- // once the cookie is set (and the server has re-rendered with it) to true, or
- // to false with the previous selection put back when the write failed.
- choose: (value: string) => Promise<boolean>;
+ // Store a choice: shown at once, written through /api/active-site. Resolves
+ // once the cookie is set to true — the page then refreshes to re-render with
+ // it, unless `navigating` (the caller moves the URL itself, and the next page
+ // renders with the cookie) — or to false with the previous selection put
+ // back when the write failed.
+ choose: (value: string, o?: { navigating?: boolean }) => Promise<boolean>;
};
const SiteScopeContext = createContext<SiteScope | null>(null);
@@ -116,38 +132,35 @@ export function SiteScopeProvider({
}
}, []);
- const choose = useCallback(async (value: string): Promise<boolean> => {
+ const choose = useCallback(async (value: string, o: { navigating?: boolean } = {}): Promise<boolean> => {
const previous = storedRef.current;
storedRef.current = value;
setStored(value);
setWriting((n) => n + 1);
- let ok = false;
- try {
- ok = await setActiveSiteAction(value);
- } catch {
- ok = false;
- }
+ const ok = await writeActiveSite(value);
setWriting((n) => n - 1);
if (ok) {
announce(value);
+ // The route only writes (no server action's implicit re-render): the
+ // page and the layout re-render with the cookie now — unless the caller
+ // navigates, whose next page does.
+ if (!o.navigating) router.refresh();
} else {
storedRef.current = previous;
setStored(previous);
}
return ok;
- }, [announce]);
+ }, [announce, router]);
// Write a value the page did not choose — no optimistic state (see above).
const record = useCallback(async (value: string): Promise<boolean> => {
- let ok = false;
- try {
- ok = await setActiveSiteAction(value);
- } catch {
- ok = false;
+ const ok = await writeActiveSite(value);
+ if (ok) {
+ announce(value);
+ router.refresh();
}
- if (ok) announce(value);
return ok;
- }, [announce]);
+ }, [announce, router]);
// Visiting a site's own page records it: once per arrival at that site's
// pages (a re-run of the effect — StrictMode, Fast Refresh — does not write
diff --git a/editor/app/components/SiteScopeSelect.tsx b/editor/app/components/SiteScopeSelect.tsx
@@ -55,7 +55,7 @@ export function SiteScopeSelect({ sites }: { sites: SiteScopeOption[] }) {
// of the other site, or the family page for "All sites". The cookie is
// written FIRST, so a page opened right after the URL moves reads it.
setPending({ urlKey, value });
- if (!(await choose(value))) {
+ if (!(await choose(value, { navigating: true }))) {
setPending(null);
return;
}
@@ -67,15 +67,16 @@ export function SiteScopeSelect({ sites }: { sites: SiteScopeOption[] }) {
return;
}
if (param === null) {
- // The common case: the stored value is what shows, and the cookie write
- // re-renders this page (Dashboard, Channels) in the new scope.
+ // The common case: the stored value is what shows, and the provider
+ // refreshes this page (Dashboard, Channels) in the new scope once the
+ // cookie is written.
await choose(value);
return;
}
// A `?site=` link's page: the choice replaces the link's scope, so the
// param goes — after the cookie is written, so the new URL renders with it.
setPending({ urlKey, value });
- if (!(await choose(value))) {
+ if (!(await choose(value, { navigating: true }))) {
setPending(null);
return;
}
diff --git a/editor/app/lib/activeSite.ts b/editor/app/lib/activeSite.ts
@@ -7,7 +7,8 @@
// `SiteScopeProvider`; Dashboard and Channels read it through the same helper.
// So the server renders the picker, and the scoped pages, with the stored
// selection on the first paint — nothing is reconciled after it. It is written
-// only by `setActiveSiteAction` (app/lib/activeSiteActions.ts).
+// only by `POST /api/active-site` (app/api/active-site/route.ts; a server action
+// until release 29), which SiteScopeProvider calls.
//
// A `?site=<id>` LINK still works: a valid param governs that one request (the
// server pages read it from `searchParams`, the picker from the URL), and is not
diff --git a/editor/app/lib/activeSiteActions.ts b/editor/app/lib/activeSiteActions.ts
@@ -1,31 +0,0 @@
-"use server";
-
-import { cookies } from "next/headers";
-import {
- ACTIVE_SITE_COOKIE_MAX_AGE,
- isStorableActiveSite,
-} from "./activeSite";
-import { activeSiteCookieForRequest } from "./activeSiteServer";
-
-// THE ONE WRITER of the active-site cookie (see ./activeSite.ts). Called by the
-// picker's onChange, by SiteScopeProvider when a site's own page is visited, and
-// once by its localStorage migration. Setting a cookie in a server action makes
-// Next re-render the current page and its layouts with the new value, so the
-// root layout hands the provider the new selection and Dashboard or Channels
-// re-scope, with no refresh of our own.
-//
-// The value is only SHAPE-checked (a site id or "__all__"): whether it names a
-// configured site is decided at every read, so a site deleted later resolves as
-// no selection. Returns false, writing nothing, for anything else.
-export async function setActiveSiteAction(value: string): Promise<boolean> {
- if (!isStorableActiveSite(value)) return false;
- const name = await activeSiteCookieForRequest();
- (await cookies()).set(name, value, {
- path: "/",
- sameSite: "lax",
- maxAge: ACTIVE_SITE_COOKIE_MAX_AGE,
- // Only the server reads it: the page gets it through the layout.
- httpOnly: true,
- });
- return true;
-}
diff --git a/editor/app/lib/activeSiteServer.ts b/editor/app/lib/activeSiteServer.ts
@@ -13,7 +13,7 @@ import {
// result to SiteScopeProvider; Dashboard and Channels call it with their
// `searchParams.site`, which wins for that request when it names a site or
// "__all__". Nothing is written here: a server component cannot set a cookie,
-// and only setActiveSiteAction does.
+// and only POST /api/active-site does.
export type ActiveSiteRead = ResolvedActiveSite & {
// The cookie's raw value, or null when the request carried none — which is
// what tells the provider a visitor may still have the old localStorage key.
diff --git a/editor/app/storage/actions.ts b/editor/app/storage/actions.ts
@@ -521,7 +521,12 @@ export async function saveHealthTimingsAction(
return { ok: false, error: (e as Error).message, values };
}
const t = applyHealthTimings(getSettings().storage.health);
- revalidatePath("/storage");
+ // NO revalidatePath here (release 29 D1, as saveSettingsAction since
+ // aaba3723): with it, the form's "Saved." waited on the client router
+ // applying the revalidated /storage tree, which a save made while the page's
+ // prefetches were in flight did only at the next AutoRefresh pulse
+ // (storage-locations.spec:723's late "timing saved"). The form refreshes the
+ // tree itself once the answer is in (HealthTimingForm).
return {
ok: true,
note:
diff --git a/editor/app/storage/components/HealthTimingForm.tsx b/editor/app/storage/components/HealthTimingForm.tsx
@@ -1,6 +1,7 @@
"use client";
-import { useActionState } from "react";
+import { useActionState, useEffect } from "react";
+import { useRouter } from "next/navigation";
import {
HEALTH_TIMING_BOUNDS,
HEALTH_TIMING_DEFAULTS,
@@ -40,6 +41,13 @@ export function HealthTimingForm({ stored }: { stored: StorageHealthSettings })
HealthTimingsResult | undefined,
FormData
>(saveHealthTimingsAction, undefined);
+ // A save answers first ("Saved. …"), THEN the page re-renders what reads the
+ // timings (the summary's count): the action does not revalidate, so its
+ // answer never waits on the router (saveHealthTimingsAction).
+ const router = useRouter();
+ useEffect(() => {
+ if (state?.ok) router.refresh();
+ }, [state, router]);
const tuned = HEALTH_TIMING_FIELDS.filter((f) => stored[f.key] !== undefined).length;
return (
diff --git a/editor/e2e/publish-lane.spec.ts b/editor/e2e/publish-lane.spec.ts
@@ -101,10 +101,14 @@ test("enabled and started, the lane updates the index; a hold mid-stage stops th
const [index] = await metasOf("publish-update-index");
expect(index.spec?.params?.runId).toMatch(/^lane-/);
- // Hold the lane while that stage is in flight.
+ // Hold the lane while that stage is in flight. The hold is the lane's state
+ // (publishStatus): wait on THAT, then read the page fresh — the button's own
+ // re-render waits on the router applying the action's revalidated tree,
+ // which under load can come seconds late (release 29 D1).
await page.getByRole("button", { name: "pause publishing" }).click();
+ await expect.poll(async () => (await publishStatus(request)).lane.held, { timeout: 30_000 }).toBe(true);
+ await page.reload();
await expect(page.getByRole("button", { name: "resume publishing" })).toBeVisible();
- expect((await publishStatus(request)).lane.held).toBe(true);
const settings = await readJson<{ publish?: { held?: boolean } }>(testPaths().settingsFile);
expect(settings.publish?.held).toBe(true);
// The stage is still queued behind the holder; let the holder go.
@@ -126,10 +130,12 @@ test("enabled and started, the lane updates the index; a hold mid-stage stops th
.toContain("no next stage dispatched");
expect(await metasOf("publish-build-site")).toEqual([]);
- // Resume, then Drain: the runner finishes what it is doing and stops.
+ // Resume (waited on the lane's state, then the page read fresh), then Drain:
+ // the runner finishes what it is doing and stops.
await page.getByRole("button", { name: "resume publishing" }).click();
+ await expect.poll(async () => (await publishStatus(request)).lane.held, { timeout: 30_000 }).toBe(false);
+ await page.reload();
await expect(page.getByRole("button", { name: "pause publishing" })).toBeVisible();
- expect((await publishStatus(request)).lane.held).toBe(false);
await page.getByRole("button", { name: "Drain publish lane" }).click();
await expect(async () => {
await page.reload();
diff --git a/editor/e2e/site-scope.spec.ts b/editor/e2e/site-scope.spec.ts
@@ -198,13 +198,17 @@ function pickerValues(page: Page): Promise<string[]> {
);
}
-// Hydrated = React has attached its props to the select. It is the one React
-// internal this spec peeks at; there is no public signal. Effects follow it.
+// Hydrated = the picker's `data-hydrated`, which its own effect stamps by a
+// re-render: so every effect of the first commit has run by then — the site
+// provider's above it too (its BroadcastChannel subscription, its visit
+// record). React's props on the select (what this waited for before release
+// 29 D1) come BEFORE those effects, and a tab that was "hydrated" that way
+// could miss another tab's broadcast posted in the gap.
async function hydrated(page: Page) {
- await page.waitForFunction((selector) => {
- const el = document.querySelector(selector);
- return !!el && Object.keys(el).some((k) => k.startsWith("__reactProps"));
- }, PICKER);
+ await page.waitForFunction(
+ (selector) => document.querySelector(selector)?.getAttribute("data-hydrated") === "true",
+ PICKER,
+ );
}
// A hydration mismatch is logged by React in development; fail on any.