Skip to content

Commit 24c3e19

Browse files
vanceingallsclaude
andauthored
fix(studio): cutover gate classification, SSE cross-project bleed, benign races (#4269)
Implements the fixes from the 2026-09-21 cutover dashboard read (plans/sdk/2026-09-21-cutover-dashboard-fixes-plan.md): - sdk_cutover_failed now carries `family` and `error_kind` (network/conflict/http/sdk). The one production gate event was a raw `TypeError: Failed to fetch` from an unwrapped fetch (readProjectFile / writeProjectFile's preflight), which an instanceof-only classifier would still file as "sdk" and trip the rollback gate — added a message-based fallback for the browser's fetch-rejection strings. - studio:sdk_session_unavailable's `network` reason now carries `elapsed_ms` and `hidden` (document.visibilityState at rejection), separating a near-instant policy block (CSP/PNA/extension) from a dropped connection the tab or server going away mid-flight. - The ownership-race branch in useSdkSession's open effect now emits sdk_session_superseded instead of sdk_session_unavailable{stage:ownership} — it's a benign race (identity moved on mid-open), not a broken precondition, and was being counted as one on the dashboard. - Root-caused and fixed the read-404 "storm": /api/events (CLI host) and the vite-dev hot-reload channel are one connection per SERVER, not per project. A stale tab left open after `hyperframes preview` restarts on a different folder (same port) received every save the CURRENT project made, reloading its preview (which then 404s) and re-reading its own composition on each one. Both transports now carry `projectId`; the client-side coordinator drops a delivery whose projectId doesn't match the tab's (absent field still passes, for one release of skew). - studio-server's file routes report `why` on 403/404: `project_dir_missing` (new — the CLI host's static resolveProject kept answering for a project whose folder was renamed/deleted under a running server, which used to fail closed as an indistinguishable path-traversal 403) vs `nul` vs `outside_project`. - absent_or_empty reads now carry `path_in_tree` (against the caller's loaded file tree). Instrumentation only, per the graveyard page (clearing-activecomppath-on-tree-absence) that refuted the "clear activeCompPath" fix this was the proposed next step for. Tests: unit coverage added for every change (sdkCutover.test.ts, useSdkSession.lifecycle.test.tsx, useExternalFileChangeCoordinator.test.tsx, studioServer.test.ts, files.pathSafety.test.ts). oxlint/oxfmt clean, tsc --noEmit clean on studio/studio-server/cli. Co-authored-by: Claude Sonnet 5 <[email protected]>
1 parent 01734fa commit 24c3e19

14 files changed

Lines changed: 601 additions & 43 deletions

‎packages/cli/src/server/studioServer.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,4 +269,23 @@ describe("Studio file-change SSE", () => {
269269
expect(payload).toContain(encodedVersion("<html>agent</html>"));
270270
}
271271
});
272+
273+
// `/api/events` is one connection per SERVER, not per project: a tab left
274+
// open from a `preview` run whose port was later reused by a DIFFERENT
275+
// project shares this exact stream. Without `projectId` on the wire, that
276+
// stale tab cannot tell "my project changed" from "the other project this
277+
// server now serves changed" — see useExternalFileChangeCoordinator's
278+
// cross-project filter, which reads this field.
279+
it("labels every file-change with this server's project id", async () => {
280+
const projectDir = tmpProject();
281+
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
282+
server = createStudioServer({ projectDir, projectName: "demo-project" });
283+
const streams = await subscribe(1);
284+
285+
writeFileSync(join(projectDir, "index.html"), "<html>agent</html>");
286+
mockWatcher.emit("change", "change", "index.html");
287+
288+
const [payload] = await Promise.all(streams.map(nextEvent));
289+
expect(payload).toContain('"projectId":"demo-project"');
290+
});
272291
});

‎packages/cli/src/server/studioServer.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -788,8 +788,20 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
788788
// identity for an unlabelled change, and without it every duplicate
789789
// delivery of one watcher event drains and reloads again.
790790
const receipt = version ? identifyFileWrite(absPath, version) : null;
791+
// `projectId` so a stale tab — one still pointed at a project this
792+
// server no longer serves, because `hyperframes preview` reused this
793+
// port for a different folder (see ProjectUnreachableBanner's doc
794+
// comment) — can tell "my project changed" from "some OTHER project,
795+
// now served on this same connection, changed". Every subscriber on
796+
// this port shares one `/api/events` stream regardless of which
797+
// project their tab was opened for; without this field a stale tab
798+
// reloads its preview and re-reads its composition on every save the
799+
// CURRENT project makes, 404ing each time.
791800
stream
792-
.writeSSE({ event: "file-change", data: JSON.stringify({ path, version, ...receipt }) })
801+
.writeSSE({
802+
event: "file-change",
803+
data: JSON.stringify({ path, version, projectId: project.id, ...receipt }),
804+
})
793805
.catch(() => {});
794806
};
795807
// Re-applied here because the watcher now also emits the signature

‎packages/studio-server/src/routes/files.pathSafety.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,40 @@ describe("file route containment", () => {
203203
});
204204
});
205205

206+
describe("resolveProjectPath why", () => {
207+
// The CLI host's `resolveProject` is static — it answers with this project
208+
// for as long as the server runs, even after its folder is renamed or
209+
// deleted. Before this fix that produced a 403 "forbidden" (isSafePath
210+
// fails closed when its base doesn't exist), indistinguishable from a real
211+
// path-traversal attempt. This must be a 404 with its own `why`, checked
212+
// BEFORE the NUL/traversal checks so it wins when both are true.
213+
it("reports a missing project directory as 404, not 403", async () => {
214+
const { app, project } = fixture();
215+
rmSync(project, { recursive: true, force: true });
216+
217+
const response = await app.request(fileUrl("inside.txt"));
218+
219+
expect(response.status).toBe(404);
220+
expect(await response.json()).toMatchObject({ why: "project_dir_missing" });
221+
});
222+
223+
it("still reports a NUL byte as 403 with its own why when the project exists", async () => {
224+
const response = await fixture().app.request(fileUrl("inside.txt\0"));
225+
226+
expect(response.status).toBe(403);
227+
expect(await response.json()).toMatchObject({ why: "nul" });
228+
});
229+
230+
it("still reports an escaping path as 403 with its own why when the project exists", async () => {
231+
const { app, project, outside } = fixture();
232+
233+
const response = await app.request(fileUrl(relative(project, join(outside, "secret.txt"))));
234+
235+
expect(response.status).toBe(403);
236+
expect(await response.json()).toMatchObject({ why: "outside_project" });
237+
});
238+
});
239+
206240
describe("upload collision races", () => {
207241
function raceDuringRead(filename: string, collide: () => void) {
208242
const file = new File(["new upload"], filename);

‎packages/studio-server/src/routes/files.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,14 +138,28 @@ async function resolveProjectPath(
138138
return { error: c.json({ error: "not found" }, 404) } as const;
139139
}
140140

141+
// The CLI host's `resolveProject` is static (`id === projectId ? project : null`),
142+
// so it keeps answering with this project even after its folder is renamed
143+
// or deleted out from under a running `preview` — mount-time validation
144+
// (`/api/projects/:id`) still passes, so nothing upstream catches this.
145+
// Every subsequent read then failed closed inside `isSafePath` (its
146+
// `realpathSync(base)` throws when the base itself is gone) and reported as
147+
// `403 forbidden` — indistinguishable from a real path-traversal attempt.
148+
// Checked here, once, so every route built on this shares the fix.
149+
if (!existsSync(project.dir)) {
150+
return {
151+
error: c.json({ error: "not found", why: "project_dir_missing" }, 404),
152+
} as const;
153+
}
154+
141155
const filePath = decodeURIComponent(c.req.path.replace(pathPrefix(project.id), ""));
142156
if (filePath.includes("\0")) {
143-
return { error: c.json({ error: "forbidden" }, 403) } as const;
157+
return { error: c.json({ error: "forbidden", why: "nul" }, 403) } as const;
144158
}
145159

146160
const absPath = resolveWithinProject(project.dir, filePath);
147161
if (!absPath) {
148-
return { error: c.json({ error: "forbidden" }, 403) } as const;
162+
return { error: c.json({ error: "forbidden", why: "outside_project" }, 403) } as const;
149163
}
150164

151165
if (opts?.mustExist && !existsSync(absPath)) {

‎packages/studio/src/App.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,8 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: St
130130
projectId,
131131
activeCompPath,
132132
masterCompPath,
133+
fileManager.fileTree,
134+
fileManager.fileTreeLoaded,
133135
);
134136
const activeCompPathRef = useRef(activeCompPath);
135137
activeCompPathRef.current = activeCompPath;

‎packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// fallow-ignore-file code-duplication
12
// @vitest-environment happy-dom
23
import { act } from "react";
34
import { createRoot } from "react-dom/client";
@@ -376,4 +377,59 @@ describe("external file change coordinator", () => {
376377
expect(reloadPreview).not.toHaveBeenCalled();
377378
});
378379
});
380+
381+
// `/api/events` is one connection per SERVER (CLI host), not per project — a
382+
// tab left open from a `preview` run whose port was later reused by a
383+
// different project's `preview` shares this stream with it. Both projects
384+
// commonly use the same default composition path, so without the filter a
385+
// stale tab reloads its preview and re-reads its own composition on every
386+
// save the OTHER project makes.
387+
describe("cross-project deliveries on a shared connection", () => {
388+
it("ignores a delivery whose projectId does not match this tab's", async () => {
389+
const drainPendingChanges = vi.fn(async () => ({ status: "clean" as const }));
390+
const reloadPreview = vi.fn();
391+
const reloadSdkSession = vi.fn();
392+
await mountCoordinator({ drainPendingChanges, reloadPreview, reloadSdkSession });
393+
394+
await act(async () =>
395+
handler?.({
396+
path: "index.html",
397+
content: "other project",
398+
version: "v9",
399+
projectId: "project-b",
400+
}),
401+
);
402+
403+
expect(drainPendingChanges).not.toHaveBeenCalled();
404+
expect(reloadPreview).not.toHaveBeenCalled();
405+
expect(reloadSdkSession).not.toHaveBeenCalled();
406+
});
407+
408+
it("still reloads for a delivery whose projectId matches this tab's", async () => {
409+
const reloadPreview = vi.fn();
410+
await mountCoordinator({ reloadPreview });
411+
412+
await act(async () =>
413+
handler?.({
414+
path: "index.html",
415+
content: "same project",
416+
version: "v9",
417+
projectId: "project-a",
418+
}),
419+
);
420+
421+
expect(reloadPreview).toHaveBeenCalledOnce();
422+
});
423+
424+
it("still reloads when projectId is absent (older server, one release of skew)", async () => {
425+
const reloadPreview = vi.fn();
426+
await mountCoordinator({ reloadPreview });
427+
428+
await act(async () =>
429+
handler?.({ path: "index.html", content: "no project id", version: "v9" }),
430+
);
431+
432+
expect(reloadPreview).toHaveBeenCalledOnce();
433+
});
434+
});
379435
});

‎packages/studio/src/hooks/useExternalFileChangeCoordinator.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,19 @@ export function useExternalFileChangeCoordinator({
349349
logReload("file-change", { path: null, why: path ? "no project" : "no path in payload" });
350350
return;
351351
}
352+
// `/api/events` is one connection per SERVER, not per project: under the
353+
// CLI host, a tab left open from a `preview` run that has since exited
354+
// shares this stream with whatever project now runs on that port. Both
355+
// commonly use the same default composition path, so without this check
356+
// a stale tab reloads its preview (which then 404s — the CLI host is
357+
// single-project, so it can't resolve the OTHER project it's serving)
358+
// and re-reads its own composition on every save the CURRENT project
359+
// makes. Absent field (older server, one release of skew) still passes.
360+
const deliveredProjectId = readFileChangeField(payload, "projectId");
361+
if (deliveredProjectId && deliveredProjectId !== projectId) {
362+
logReload("suppressed", { path, why: "other project" });
363+
return;
364+
}
352365
pendingTimelineEditPathRef.current.delete(path);
353366

354367
const content = readFileChangeContent(payload);

0 commit comments

Comments
 (0)