Skip to content

Write HTML. Render video. Built for agents.

feat(studio): say which project this Studio is serving when a read 404s (#4228)

Vance Ingallsf476e78cc83d
diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx
index 477ec4129a..4f8cce91dc 100644
--- a/packages/studio/src/App.tsx
+++ b/packages/studio/src/App.tsx
@@ -7,6 +7,7 @@ import { usePlayerStore } from "./player";
import { StudioOverlays } from "./components/StudioOverlays";
import { SaveQueuePausedBanner } from "./components/SaveQueuePausedBanner";
import { ExternalFileConflictBanner } from "./components/ExternalFileConflictBanner";
+import { ProjectUnreachableBanner } from "./components/ProjectUnreachableBanner";
import { useCaptionStore } from "./captions/store";
import { useCaptionSync } from "./captions/hooks/useCaptionSync";
import { usePersistentEditHistory } from "./hooks/usePersistentEditHistory";
@@ -475,6 +476,9 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: St
/>
)}
<ExternalFileConflictBanner coordinator={externalFileChanges} />
+ {sdkHandle.unreachableProject && (
+ <ProjectUnreachableBanner projectId={sdkHandle.unreachableProject} />
+ )}
<EditorShell
readOnlyPreview={readOnlyPreview}
readOnlyPreviewReason={readOnlyPreviewReason}
diff --git a/packages/studio/src/components/ProjectUnreachableBanner.test.tsx b/packages/studio/src/components/ProjectUnreachableBanner.test.tsx
new file mode 100644
index 0000000000..a324b578ce
--- /dev/null
+++ b/packages/studio/src/components/ProjectUnreachableBanner.test.tsx
@@ -0,0 +1,113 @@
+// @vitest-environment happy-dom
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ProjectUnreachableBanner } from "./ProjectUnreachableBanner";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root | null = null;
+
+afterEach(() => {
+ if (root) act(() => root?.unmount());
+ root = null;
+ document.body.replaceChildren();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+function stubProjects(projects: unknown): void {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response(JSON.stringify({ projects }), { status: 200 })),
+ );
+}
+
+async function renderBanner(projectId: string): Promise<string> {
+ const host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+ await act(async () => {
+ root?.render(<ProjectUnreachableBanner projectId={projectId} />);
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ return host.textContent ?? "";
+}
+
+describe("ProjectUnreachableBanner", () => {
+ // The production case: the CLI host serves exactly one project, and it is not
+ // this tab's. Naming both sides is the whole point — the user needs to know
+ // their project still exists and which one this Studio actually opened.
+ it("names both projects when this Studio serves a different one", async () => {
+ stubProjects([{ id: "out-video1", title: "out-video1" }]);
+ const text = await renderBanner("out-fb1");
+
+ expect(text).toContain("out-video1");
+ expect(text).toContain("out-fb1");
+ expect(text).toContain("This Studio is serving");
+ expect(text).not.toContain("renamed");
+ });
+
+ // With several projects a 404 cannot be told apart from a rename or a
+ // deletion, so the banner must not claim a cause. "Could be gone" is the
+ // honest ceiling, and it is a weaker claim than "is gone".
+ it("does not claim a cause when several projects are served", async () => {
+ stubProjects([
+ { id: "a", title: "a" },
+ { id: "b", title: "b" },
+ ]);
+ const text = await renderBanner("out-fb1");
+
+ expect(text).toContain("renamed, moved, or deleted");
+ expect(text).not.toContain("This Studio is serving");
+ });
+
+ // A server that answers with this tab's own project while the read 404s is
+ // not the stale-tab case, so the single-project wording would be false.
+ it("falls back to the general wording when the served project is this one", async () => {
+ stubProjects([{ id: "out-fb1", title: "out-fb1" }]);
+ const text = await renderBanner("out-fb1");
+
+ expect(text).toContain("renamed, moved, or deleted");
+ expect(text).not.toContain("This Studio is serving");
+ });
+
+ it("says nothing it cannot back up when the project list cannot be read", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response("boom", { status: 500 })),
+ );
+ const text = await renderBanner("out-fb1");
+
+ expect(text).toContain("renamed, moved, or deleted");
+ expect(text).not.toContain("This Studio is serving");
+ });
+
+ it("renders nothing until the project list resolves", async () => {
+ let resolveList: ((value: Response) => void) | undefined;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ () =>
+ new Promise<Response>((resolve) => {
+ resolveList = resolve;
+ }),
+ ),
+ );
+ const host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+ await act(async () => {
+ root?.render(<ProjectUnreachableBanner projectId="out-fb1" />);
+ });
+ expect(host.textContent).toBe("");
+
+ await act(async () => {
+ resolveList?.(new Response(JSON.stringify({ projects: [{ id: "other" }] }), { status: 200 }));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ expect(host.textContent).toContain("This Studio is serving");
+ });
+});
diff --git a/packages/studio/src/components/ProjectUnreachableBanner.tsx b/packages/studio/src/components/ProjectUnreachableBanner.tsx
new file mode 100644
index 0000000000..b51be2e2e0
--- /dev/null
+++ b/packages/studio/src/components/ProjectUnreachableBanner.tsx
@@ -0,0 +1,89 @@
+import { useEffect, useState } from "react";
+
+interface ServedProject {
+ id: string;
+ title?: string;
+}
+
+interface ProjectUnreachableBannerProps {
+ /** The project this tab was opened for and the server cannot resolve. */
+ projectId: string;
+}
+
+/**
+ * Shown when the running Studio cannot resolve this tab's project id.
+ *
+ * Why this exists: a tab whose project the server does not serve fails every
+ * read with a 404, so every edit silently takes the server path and nothing
+ * lands. The user sees a normal-looking editor that does not save. In the
+ * CLI-embedded host — the only host that reports telemetry, since
+ * `telemetry/policy.ts` suppresses Vite dev — the cause is almost always that
+ * this Studio is serving a *different* project: `hyperframes preview` reuses
+ * port 3002, so starting it on another folder takes the port from under an
+ * open tab, and the project it was pointed at is untouched on disk.
+ *
+ * The wording is deliberately narrower than "this project is gone". We can see
+ * which project this server serves; we cannot see why it does not serve this
+ * one, and nothing here is lost. See
+ * `docs/hyperframes/plans/sdk/2026-09-20-stale-project-id-remaining-doors-plan.md` §C.
+ */
+export function ProjectUnreachableBanner({ projectId }: ProjectUnreachableBannerProps) {
+ const [served, setServed] = useState<ServedProject[] | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ // A list we could not read is not evidence of anything, so a failed fetch
+ // leaves `served` empty and the banner falls back to the vague wording
+ // rather than claiming this Studio serves nothing.
+ fetch("/api/projects")
+ .then((res) => (res.ok ? res.json() : { projects: [] }))
+ .then((data: { projects?: ServedProject[] }) => {
+ if (!cancelled) setServed(data.projects ?? []);
+ })
+ .catch(() => {
+ if (!cancelled) setServed([]);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId]);
+
+ // Withheld until the list arrives: which wording applies is a claim about
+ // what this server serves, and guessing it would flash the wrong one.
+ if (served === null) return null;
+
+ // Exactly one project served, and it is not this tab's. Under the CLI host
+ // that is the whole truth, and it names both sides. With several projects we
+ // cannot tell a rename from a deletion, so we do not pretend to.
+ const soleProject = served.length === 1 && served[0].id !== projectId ? served[0] : null;
+ const servedLabel = soleProject?.title ?? soleProject?.id;
+
+ return (
+ <div
+ role="alert"
+ className="hf-backdrop-in absolute left-1/2 top-14 z-92 flex max-w-[calc(100vw-32px)] -translate-x-1/2 items-center gap-3 rounded-md border border-amber-500/30 bg-amber-950/85 px-4 py-2 text-[12px] font-medium text-amber-100 shadow-lg shadow-black/30"
+ >
+ {soleProject ? (
+ <>
+ <span>
+ This Studio is serving <strong>{servedLabel}</strong>. This tab was opened for{" "}
+ <strong>{projectId}</strong>.
+ </span>
+ {/* Reloading re-runs the mount-time hash check, which rewrites the hash
+ to the project this server actually serves. That is the same
+ fallback a fresh load performs, so the button promises nothing
+ beyond what a reload already does. */}
+ <button
+ type="button"
+ onClick={() => window.location.reload()}
+ className="shrink-0 rounded-sm border border-amber-300/20 px-2 py-1 text-[11px] text-amber-100 transition-colors hover:bg-amber-400/10 active:scale-[0.98]"
+ >
+ Open {servedLabel}
+ </button>
+ </>
+ ) : (
+ <span>Couldn&apos;t open this project — it may have been renamed, moved, or deleted.</span>
+ )}
+ </div>
+ );
+}
diff --git a/packages/studio/src/hooks/useFileTree.test.tsx b/packages/studio/src/hooks/useFileTree.test.tsx
index 62910c9ec9..91491bac7f 100644
--- a/packages/studio/src/hooks/useFileTree.test.tsx
+++ b/packages/studio/src/hooks/useFileTree.test.tsx
@@ -5,6 +5,12 @@ import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useFileTree } from "./useFileTree";
+vi.mock("../components/feedback/projectProvenance", () => ({
+ captureProjectProvenance: vi.fn(),
+}));
+
+import { captureProjectProvenance } from "../components/feedback/projectProvenance";
+
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
let root: Root | null = null;
@@ -52,6 +58,56 @@ async function renderHarness(projectId: string): Promise<{ current: Handle | nul
return handleRef;
}
+describe("useFileTree unresolved project", () => {
+ const provenance = vi.mocked(captureProjectProvenance);
+
+ afterEach(() => {
+ provenance.mockClear();
+ });
+
+ /** Render the tree for `projectId` against one canned response. */
+ async function renderWithResponse(
+ projectId: string,
+ build: () => Response,
+ ): Promise<{ current: Handle | null }> {
+ const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async () => build());
+ const handleRef = await renderHarness(projectId);
+ fetchSpy.mockRestore();
+ return handleRef;
+ }
+
+ const notFound = () =>
+ new Response(JSON.stringify({ error: "not found" }), {
+ status: 404,
+ headers: { "content-type": "application/json" },
+ });
+ const emptyListing = () =>
+ new Response(JSON.stringify({ files: [], compositions: [] }), { status: 200 });
+
+ // An unresolvable project answers 404 with a JSON body. Without an `r.ok`
+ // check that parsed cleanly and took the SUCCESS branch, recording an empty
+ // tree and an empty provenance snapshot for a project that was never read —
+ // so a bug report filed from that tab described a project that does not
+ // exist. The tree itself stays empty either way; the provenance lie is the
+ // part that leaves the browser.
+ it("does not snapshot provenance for a project the server could not resolve", async () => {
+ const handleRef = await renderWithResponse("gone-project", notFound);
+
+ expect(handleRef.current?.compositions).toEqual([]);
+ expect(provenance).not.toHaveBeenCalled();
+ });
+
+ // The counterpart, and the reason the check above cannot be collapsed into
+ // "skip provenance whenever the tree is empty": a project with no
+ // compositions yet is a real, successful read and must still be snapshotted.
+ it("still snapshots provenance when a resolved project has no compositions", async () => {
+ const handleRef = await renderWithResponse("empty-project", emptyListing);
+
+ expect(handleRef.current?.compositions).toEqual([]);
+ expect(provenance).toHaveBeenCalledWith("empty-project", [], []);
+ });
+});
+
describe("useFileTree.refreshFileTree", () => {
it("updates compositions, not just the raw file list, on refresh", async () => {
let call = 0;
diff --git a/packages/studio/src/hooks/useFileTree.ts b/packages/studio/src/hooks/useFileTree.ts
index eaa788cd28..3cc8eb8720 100644
--- a/packages/studio/src/hooks/useFileTree.ts
+++ b/packages/studio/src/hooks/useFileTree.ts
@@ -39,7 +39,14 @@ export function useFileTree({ projectId, projectIdRef }: UseFileTreeOptions) {
let cancelled = false;
setFetched({ projectId, loaded: false, fileTree: [], compositionPaths: [], projectDir: null });
fetch(buildProjectApiPath(projectId))
- .then((r) => r.json())
+ // An unresolvable project answers 404 with a JSON body, so without this
+ // the error path parsed cleanly and the success branch below recorded an
+ // empty tree — and an empty provenance snapshot — for a project that was
+ // never read. Throwing hands it to the catch instead.
+ .then((r) => {
+ if (!r.ok) throw new Error(`tree fetch failed: ${r.status}`);
+ return r.json();
+ })
.then((data: { files?: string[]; dir?: string; compositions?: string[] }) => {
if (cancelled) return;
setFetched({
diff --git a/packages/studio/src/hooks/useSdkSession.lifecycle.test.tsx b/packages/studio/src/hooks/useSdkSession.lifecycle.test.tsx
index 34e2cc3e32..4583b71d54 100644
--- a/packages/studio/src/hooks/useSdkSession.lifecycle.test.tsx
+++ b/packages/studio/src/hooks/useSdkSession.lifecycle.test.tsx
@@ -147,6 +147,86 @@ describe("useSdkSession ownership", () => {
});
});
+describe("useSdkSession unreachable project", () => {
+ beforeEach(() => {
+ openComposition.mockReset();
+ trackMock.mockClear();
+ class FakeEventSource {
+ addEventListener(): void {}
+ close(): void {}
+ }
+ vi.stubGlobal("EventSource", FakeEventSource);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ function probeHandle(projectId: string) {
+ const captured: { handle: SdkSessionHandle | null } = { handle: null };
+ function HandleProbe() {
+ captured.handle = useSdkSession(projectId, "index.html");
+ return null;
+ }
+ return { captured, HandleProbe };
+ }
+
+ const failedRead = (status: number) => async () =>
+ ({ ok: false, status, json: async () => ({}) }) as Response;
+
+ /** Render the hook for `projectId` against a stubbed read and let it settle. */
+ async function readOutcome(
+ projectId: string,
+ read: () => Promise<Response>,
+ ): Promise<{ captured: { handle: SdkSessionHandle | null }; unmount: () => Promise<void> }> {
+ vi.stubGlobal("fetch", vi.fn(read));
+ const { captured, HandleProbe } = probeHandle(projectId);
+ const root = createRoot(document.createElement("div"));
+ await act(async () => root.render(<HandleProbe />));
+ await flushAsyncEffects();
+ return { captured, unmount: () => act(async () => root.unmount()) };
+ }
+
+ // A 404 on the composition read is the one failure that says something about
+ // the PROJECT rather than the request: under the CLI host it means this
+ // Studio serves a different one. Every edit then fails silently, so the UI
+ // needs the id to explain that.
+ it("names the project when the read is a 404", async () => {
+ const { captured, unmount } = await readOutcome("gone-project", failedRead(404));
+
+ expect(captured.handle?.unreachableProject).toBe("gone-project");
+ await unmount();
+ });
+
+ // A 500 says the request failed, not that the project is elsewhere. Claiming
+ // otherwise would tell a user their tab is pointed at the wrong project when
+ // the server is merely unwell.
+ it("stays quiet on a failure that says nothing about the project", async () => {
+ const { captured, unmount } = await readOutcome("project-a", failedRead(500));
+
+ expect(captured.handle?.unreachableProject).toBeNull();
+ await unmount();
+ });
+
+ it("clears the state once the project resolves", async () => {
+ const { captured, unmount } = await readOutcome("gone-project", failedRead(404));
+ expect(captured.handle?.unreachableProject).toBe("gone-project");
+
+ openComposition.mockResolvedValue(fakeSession());
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => response("PROJECT_A")),
+ );
+ await act(async () => {
+ captured.handle?.forceReload();
+ });
+ await flushAsyncEffects();
+
+ expect(captured.handle?.unreachableProject).toBeNull();
+ await unmount();
+ });
+});
+
describe("useSdkSession unavailable telemetry", () => {
beforeEach(() => {
openComposition.mockReset();
diff --git a/packages/studio/src/hooks/useSdkSession.ts b/packages/studio/src/hooks/useSdkSession.ts
index 86362b79f5..58f7bfc13b 100644
--- a/packages/studio/src/hooks/useSdkSession.ts
+++ b/packages/studio/src/hooks/useSdkSession.ts
@@ -25,6 +25,34 @@ type ProjectFileReadFailure =
type ProjectFileReadResult = { ok: true; content: string } | ProjectFileReadFailure;
+/**
+ * Record a read that produced no usable content, and answer which project — if
+ * any — the failure identifies as unreachable.
+ *
+ * No SDK session follows a failed read, so EVERY cutover chokepoint takes the
+ * server path and emits nothing — the shadow never runs either. A broken read
+ * would otherwise be a silent, total SDK bypass, which is why this is recorded
+ * at all.
+ *
+ * Only a 404 identifies the *project*: the server answered, and its answer was
+ * that it does not serve this id. A 5xx, a dropped request, an unexpected body
+ * and an empty file all say nothing about which project the server serves, so
+ * none of them claim it. See `unreachableProject` on the handle.
+ *
+ * A function rather than three more conditions inline: the read callback it is
+ * called from is a long pre-existing async body already near the complexity
+ * threshold, and this branch is one coherent unit.
+ */
+function reportReadFailure(read: ProjectFileReadFailure, projectId: string): string | null {
+ trackStudioEvent("sdk_session_unavailable", {
+ stage: "read",
+ reason: read.reason,
+ ...(read.reason === "http_error" ? { status: read.status } : {}),
+ });
+ if (read.reason !== "http_error") return null;
+ return read.status === 404 ? projectId : null;
+}
+
/**
* Read a project file's content (optional read — a missing file is not an
* error). Replaces the removed SDK http adapter's `read()` — the only thing
@@ -96,6 +124,19 @@ export interface SdkSessionHandle {
* side of that path is covered by usePersistentEditHistory.test.ts.
*/
forceReload: () => void;
+ /**
+ * Set when this server answered the composition read with a 404 for the
+ * project it was asked to open. In the CLI-embedded host — the only host
+ * that reports telemetry at all (`telemetry/policy.ts` suppresses Vite dev)
+ * — that does not mean the project is gone. It means this Studio is serving
+ * a *different* one; the project is untouched on disk. Either way every edit
+ * in this tab fails, and until now it failed silently.
+ *
+ * `null` for every other failure: a 500 or a dropped request says nothing
+ * about which project the server serves, and `absent_or_empty` /
+ * `missing_content` say nothing about the project at all.
+ */
+ unreachableProject: string | null;
}
interface SdkSessionOwner {
@@ -173,6 +214,7 @@ export function useSdkSession(
const [reloadToken, setReloadToken] = useState(0);
const reloadTokenRef = useRef(reloadToken);
reloadTokenRef.current = reloadToken;
+ const [unreachableProject, setUnreachableProject] = useState<string | null>(null);
useEffect(
() =>
@@ -195,6 +237,7 @@ export function useSdkSession(
if (previous) disposeSdkSession(previous.session);
if (!projectId || !activeCompPath) {
+ setUnreachableProject(null);
return () => {
cancelled = true;
};
@@ -211,17 +254,10 @@ export function useSdkSession(
.then(async (read) => {
if (cancelled) return;
if (!read.ok) {
- // No SDK session follows, so EVERY cutover chokepoint below takes the
- // server path and emits nothing — the shadow never runs either. This
- // is the only place a missing session can originate, so a broken read
- // would otherwise be a silent, total SDK bypass.
- trackStudioEvent("sdk_session_unavailable", {
- stage: "read",
- reason: read.reason,
- ...(read.reason === "http_error" ? { status: read.status } : {}),
- });
+ setUnreachableProject(reportReadFailure(read, projectId));
return;
}
+ setUnreachableProject(null);
const content = read.content;
// No persist queue: Studio's writeProjectFile (via sdkCutover's
// persistSdkSerialize) is the SINGLE writer. Wiring the SDK persist
@@ -316,5 +352,5 @@ export function useSdkSession(
ownedSession.reloadToken === reloadToken
? ownedSession.session
: null;
- return { session, publish, forceReload };
+ return { session, publish, forceReload, unreachableProject };
}