Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): validate the hash on hashchange, and stop pushing dead ids (#4225)
Vance Ingalls74af8b4279e0
diff --git a/packages/studio/src/hooks/useServerConnection.hashProject.test.tsx b/packages/studio/src/hooks/useServerConnection.hashProject.test.tsxindex e56b42c05b..55e1b358c7 100644--- a/packages/studio/src/hooks/useServerConnection.hashProject.test.tsx+++ b/packages/studio/src/hooks/useServerConnection.hashProject.test.tsx@@ -97,14 +97,248 @@ describe("useServerConnection hash project id", () => {});});+/** Per-project status, so one test can hold two projects in different states. */+function stubFetchByProject(statuses: Record<string, number | "reject">) {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string) => {+ if (url === "/api/projects") {+ return {+ ok: true,+ json: async () => ({ projects: [{ id: "real-project" }] }),+ } as Response;+ }+ const id = decodeURIComponent(url.replace("/api/projects/", ""));+ const status = statuses[id];+ if (status === "reject") throw new TypeError("Failed to fetch");+ if (status === undefined) return { ok: false, status: 404 } as Response;+ return { ok: status === 200, status } as Response;+ }),+ );+}++async function changeHash(hash: string) {+ await act(async () => {+ window.location.hash = hash;+ });+ await flush();+}++/**+ * Change the hash WITHOUT the test itself pushing or firing anything.+ *+ * `location.hash =` does both, which makes "did the CODE push?" unanswerable —+ * the test's own navigation moves history.length either way. replaceState does+ * neither, so the dispatch is explicit and any growth after it is the hook's.+ */+async function replaceHashAndDispatch(hash: string) {+ await act(async () => {+ window.history.replaceState(null, "", hash);+ window.dispatchEvent(new Event("hashchange"));+ });+ await flush();+}++/**+ * The hashchange path took any id the URL offered, with no validation — so the+ * mount fix from v0.8.52 could be walked straight around by changing projects.+ * These pin the second door shut.+ */+describe("useServerConnection hashchange validation", () => {+ beforeEach(() => {+ captured.projectId = null;+ window.location.hash = "";+ vi.mocked(trackStudioEvent).mockClear();+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("adopts a hash id the server can resolve", async () => {+ stubFetchByProject({ first: 200, second: 200 });+ const root = await renderWithHash("#project/first");+ expect(captured.projectId).toBe("first");++ await changeHash("#project/second");+ expect(captured.projectId).toBe("second");+ await act(async () => root.unmount());+ });++ it("falls back to the first project when the new hash id is gone", async () => {+ stubFetchByProject({ first: 200, deleted: 404 });+ const root = await renderWithHash("#project/first");+ expect(captured.projectId).toBe("first");++ await changeHash("#project/deleted");+ expect(captured.projectId).toBe("real-project");+ expect(window.location.hash).toContain("real-project");+ await act(async () => root.unmount());+ });++ it("keeps the new hash id when the check itself fails", async () => {+ // Same transient-tolerance as the mount path: a blip must not rewrite the+ // user's hash out from under a project that is actually fine.+ stubFetchByProject({ first: 200, flaky: "reject" });+ const root = await renderWithHash("#project/first");++ await changeHash("#project/flaky");+ expect(captured.projectId).toBe("flaky");+ await act(async () => root.unmount());+ });++ it("reports the hashchange verdict with its stage", async () => {+ stubFetchByProject({ first: 200, deleted: 404 });+ const root = await renderWithHash("#project/first");+ vi.mocked(trackStudioEvent).mockClear();++ await changeHash("#project/deleted");+ const verdicts = vi+ .mocked(trackStudioEvent)+ .mock.calls.filter(([name]) => name === "project_hash_validated");+ expect(verdicts).toEqual([+ ["project_hash_validated", { stage: "hashchange", outcome: "missing", status: 404 }],+ ]);+ await act(async () => root.unmount());+ });++ it("ignores a verdict that lands after the user moved on", async () => {+ // Two changes in quick succession. The first check resolves late; if it were+ // trusted, it would adopt a project the user already navigated away from.+ let releaseFirst: (() => void) | null = null;+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string) => {+ if (url === "/api/projects") {+ return {+ ok: true,+ json: async () => ({ projects: [{ id: "real-project" }] }),+ } as Response;+ }+ const id = decodeURIComponent(url.replace("/api/projects/", ""));+ if (id === "slow") {+ await new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ return { ok: true, status: 200 } as Response;+ }+ return { ok: true, status: 200 } as Response;+ }),+ );++ const root = await renderWithHash("#project/slow");+ await flush();+ // Move on before the slow validation answers.+ await act(async () => {+ window.location.hash = "#project/fast";+ });+ await flush();+ expect(captured.projectId).toBe("fast");++ // Now let the stale check resolve. It must not win.+ await act(async () => {+ releaseFirst?.();+ });+ await flush();+ expect(captured.projectId).toBe("fast");+ await act(async () => root.unmount());+ });++ it("falls back to the CURRENT project list, not the one from mount", async () => {+ // The mount fetch is a snapshot. A long-lived tab is exactly the case this+ // path exists for, so re-reading the list is the difference between landing+ // on a project that exists and landing on the one that was first an hour ago.+ let list = [{ id: "old-first" }];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string) => {+ if (url === "/api/projects") {+ return { ok: true, json: async () => ({ projects: list }) } as Response;+ }+ const id = decodeURIComponent(url.replace("/api/projects/", ""));+ return { ok: id !== "deleted", status: id === "deleted" ? 404 : 200 } as Response;+ }),+ );++ const root = await renderWithHash("#project/old-first");+ expect(captured.projectId).toBe("old-first");++ list = [{ id: "new-first" }];+ await changeHash("#project/deleted");+ expect(captured.projectId).toBe("new-first");+ await act(async () => root.unmount());+ });++ it("re-reads the list on a second dead hash rather than reusing the first answer", async () => {+ // The caching version is invisible with one dead hash — firstProjectId runs+ // once, so a memo and a fresh fetch look identical. Two dead hashes with the+ // list changing in between is what separates them.+ let list = [{ id: "first-a" }];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string) => {+ if (url === "/api/projects") {+ return { ok: true, json: async () => ({ projects: list }) } as Response;+ }+ const id = decodeURIComponent(url.replace("/api/projects/", ""));+ return { ok: id === "alive", status: id === "alive" ? 200 : 404 } as Response;+ }),+ );++ const root = await renderWithHash("#project/alive");+ await changeHash("#project/dead-one");+ expect(captured.projectId).toBe("first-a");++ list = [{ id: "first-b" }];+ await changeHash("#project/dead-two");+ expect(captured.projectId).toBe("first-b");+ await act(async () => root.unmount());+ });++ it("rewrites a dead hash without adding a history entry", async () => {+ // `location.hash =` pushes, which would leave the dead id one Back away —+ // and Back would then re-validate, fall back and push again, forever.+ stubFetchByProject({ first: 200, deleted: 404 });+ const root = await renderWithHash("#project/first");++ const before = window.history.length;+ await replaceHashAndDispatch("#project/deleted");+ expect(captured.projectId).toBe("real-project");+ expect(window.history.length).toBe(before);+ await act(async () => root.unmount());+ });++ it("rewrites the mount fallback without adding a history entry", async () => {+ // The mount path pushed until now — the same bug from the other end: Back+ // returned to the dead id, which re-validates and pushes again.+ stubFetchByProject({ deleted: 404 });+ window.history.replaceState(null, "", "#project/deleted");+ const before = window.history.length;++ const root = await renderWithHash("#project/deleted");+ expect(captured.projectId).toBe("real-project");+ expect(window.history.length).toBe(before);+ await act(async () => root.unmount());+ });+});+/*** The verdict event. Until it existed, a tab that kept its hash because the* check itself failed was indistinguishable in production from one that never* ran the check — different causes, different fixes, one silent bucket.*/describe("project_hash_validated", () => {+ // Mount only: assigning window.location.hash is what happy-dom turns into a+ // hashchange, so the listener reports too. This describe is about the mount+ // path; the hashchange verdicts have their own.const verdictCalls = () =>- vi.mocked(trackStudioEvent).mock.calls.filter(([name]) => name === "project_hash_validated");+ vi+ .mocked(trackStudioEvent)+ .mock.calls.filter(+ ([name, props]) =>+ name === "project_hash_validated" &&+ (props as { stage?: string } | undefined)?.stage === "mount",+ );beforeEach(() => {captured.projectId = null;diff --git a/packages/studio/src/hooks/useServerConnection.ts b/packages/studio/src/hooks/useServerConnection.tsindex 52d98621a4..a1928348ee 100644--- a/packages/studio/src/hooks/useServerConnection.ts+++ b/packages/studio/src/hooks/useServerConnection.ts@@ -51,6 +51,35 @@ async function resolveHashProject(id: string): Promise<ProjectHashVerdict> {* that never ran the check — the two have different fixes and, until this* event, no way to tell them apart in production.*/+/**+ * Rewrite the project hash WITHOUT pushing a history entry.+ *+ * `location.hash =` pushes. That leaves the dead id as the previous entry, so+ * Back returns to it — and now that hashchange validates, Back would re-run the+ * whole fallback and push again, leaving a trail of dead ids the user cannot+ * escape with the Back button.+ */+function replaceProjectHash(projectId: string): void {+ window.history.replaceState(null, "", buildProjectHash(projectId));+}++/**+ * The first project the server offers, for a hash that resolves to nothing.+ *+ * Fetched here rather than cached from mount: the mount fetch is a snapshot,+ * and the scenario this exists for is exactly the one where the project list+ * changed underneath a long-lived tab.+ */+async function firstProjectId(): Promise<string | null> {+ try {+ const res = await fetch("/api/projects");+ const data = (await res.json()) as { projects?: Array<{ id?: string }> };+ return data.projects?.[0]?.id ?? null;+ } catch {+ return null;+ }+}+function reportHashVerdict(stage: "mount" | "hashchange", verdict: ProjectHashVerdict): void {trackStudioEvent("project_hash_validated", {stage,@@ -105,7 +134,7 @@ export function useServerConnection(): ServerConnectionState {if (first) {setProjectId(first.id);setWaitingForServer(false);- window.location.hash = buildProjectHash(first.id);+ replaceProjectHash(first.id);} else {scheduleRetry();}@@ -129,7 +158,29 @@ export function useServerConnection(): ServerConnectionState {useEffect(() => {const onHashChange = () => {const next = parseProjectIdFromHash(window.location.hash);- if (next && next !== projectId) setProjectId(next);+ if (!next || next === projectId) return;+ // Validated, not adopted. The mount path has checked its hash since+ // v0.8.52; this path took any id the URL offered, so changing projects+ // re-armed the same dead-tab failure the mount check exists to prevent.+ void (async () => {+ const verdict = await resolveHashProject(next);+ // Ground truth, not a captured flag. This effect re-registers on every+ // projectId change, so a generation counter in this closure would reset+ // and an in-flight verdict from the previous registration would read as+ // current — adopting a project the user has already navigated away from.+ // The hash itself cannot go stale.+ if (parseProjectIdFromHash(window.location.hash) !== next) return;+ reportHashVerdict("hashchange", verdict);+ if (verdict.outcome !== "missing") {+ setProjectId(next);+ return;+ }+ const fallbackId = await firstProjectId();+ if (parseProjectIdFromHash(window.location.hash) !== next) return;+ if (!fallbackId) return;+ setProjectId(fallbackId);+ replaceProjectHash(fallbackId);+ })();};window.addEventListener("hashchange", onHashChange);return () => window.removeEventListener("hashchange", onHashChange);