Skip to content

Write HTML. Render video. Built for agents.

feat(studio): report why a fallback happened, and when a session is missing

Vance Ingalls9f3a778fd11b
diff --git a/packages/studio/src/hooks/useSdkSession.lifecycle.test.tsx b/packages/studio/src/hooks/useSdkSession.lifecycle.test.tsx
index 7719b6d883..dd52400913 100644
--- a/packages/studio/src/hooks/useSdkSession.lifecycle.test.tsx
+++ b/packages/studio/src/hooks/useSdkSession.lifecycle.test.tsx
@@ -12,6 +12,17 @@ vi.mock("@hyperframes/sdk", () => ({
import type { Composition } from "@hyperframes/sdk";
import { useSdkSession, type SdkSessionHandle } from "./useSdkSession";
+vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() }));
+
+import { trackStudioEvent } from "../utils/studioTelemetry";
+
+const trackMock = vi.mocked(trackStudioEvent);
+
+function Probe({ projectId }: { projectId: string }) {
+ useSdkSession(projectId, "index.html");
+ return null;
+}
+
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
function fakeSession(): Composition {
@@ -135,3 +146,68 @@ describe("useSdkSession ownership", () => {
expect(published.dispose).toHaveBeenCalledOnce();
});
});
+
+describe("useSdkSession unavailable telemetry", () => {
+ beforeEach(() => {
+ openComposition.mockReset();
+ trackMock.mockClear();
+ class FakeEventSource {
+ addEventListener(): void {}
+ close(): void {}
+ }
+ vi.stubGlobal("EventSource", FakeEventSource);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ // Every cutover chokepoint silently takes the server path when there is no
+ // session, and the shadow never runs either — so a missing session is a total,
+ // otherwise-invisible SDK bypass. These three exits are its only origin.
+ it("reports an unreadable composition", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => ({ ok: false, json: async () => ({}) }) as Response),
+ );
+ const root = createRoot(document.createElement("div"));
+ await act(async () => root.render(<Probe projectId="project-a" />));
+ await flushAsyncEffects();
+
+ expect(trackMock).toHaveBeenCalledWith("sdk_session_unavailable", { stage: "read" });
+ await act(async () => root.unmount());
+ });
+
+ it("reports a parse failure with its message", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => response("PROJECT_A")),
+ );
+ openComposition.mockRejectedValue(new Error("unparseable composition"));
+
+ const root = createRoot(document.createElement("div"));
+ await act(async () => root.render(<Probe projectId="project-a" />));
+ await flushAsyncEffects();
+
+ expect(trackMock).toHaveBeenCalledWith("sdk_session_unavailable", {
+ stage: "open",
+ error: "unparseable composition",
+ });
+ await act(async () => root.unmount());
+ });
+
+ it("stays silent on the happy path", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => response("PROJECT_A")),
+ );
+ openComposition.mockResolvedValue(fakeSession());
+
+ const root = createRoot(document.createElement("div"));
+ await act(async () => root.render(<Probe projectId="project-a" />));
+ await flushAsyncEffects();
+
+ expect(trackMock).not.toHaveBeenCalledWith("sdk_session_unavailable", expect.anything());
+ await act(async () => root.unmount());
+ });
+});
diff --git a/packages/studio/src/hooks/useSdkSession.ts b/packages/studio/src/hooks/useSdkSession.ts
index 278598376a..837b4d3b46 100644
--- a/packages/studio/src/hooks/useSdkSession.ts
+++ b/packages/studio/src/hooks/useSdkSession.ts
@@ -181,7 +181,15 @@ export function useSdkSession(
readProjectFileOptional(projectId, activeCompPath)
.then(async (content) => {
- if (cancelled || typeof content !== "string") return;
+ if (cancelled) return;
+ if (typeof content !== "string") {
+ // 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" });
+ return;
+ }
// No persist queue: Studio's writeProjectFile (via sdkCutover's
// persistSdkSerialize) is the SINGLE writer. Wiring the SDK persist
// queue too would double-write the file (queue auto-writes on every
@@ -206,6 +214,7 @@ export function useSdkSession(
)
) {
disposeSdkSession(comp);
+ trackStudioEvent("sdk_session_unavailable", { stage: "ownership" });
return;
}
const displaced = ownedSessionRef.current;
@@ -215,8 +224,17 @@ export function useSdkSession(
setOwnedSession(installed);
if (displaced && displaced.session !== comp) disposeSdkSession(displaced.session);
})
- .catch(() => {
- if (!cancelled && generationRef.current === generation) setOwnedSession(null);
+ .catch((error: unknown) => {
+ if (!cancelled && generationRef.current === generation) {
+ setOwnedSession(null);
+ // openComposition threw (unparseable composition, OOM) — same total
+ // bypass as the read failure above, but this one is a real defect
+ // rather than a missing file. Carry the message; it is the only clue.
+ trackStudioEvent("sdk_session_unavailable", {
+ stage: "open",
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
});
return () => {
diff --git a/packages/studio/src/utils/sdkCutover.test.ts b/packages/studio/src/utils/sdkCutover.test.ts
index 4815ac4bc4..d5644bc0e3 100644
--- a/packages/studio/src/utils/sdkCutover.test.ts
+++ b/packages/studio/src/utils/sdkCutover.test.ts
@@ -23,6 +23,8 @@ vi.mock("./studioTelemetry", () => ({
trackStudioEvent: vi.fn(),
}));
+import { trackStudioEvent } from "./studioTelemetry";
+
const styleOp = (property: string, value: string): PatchOperation => ({
type: "inline-style",
property,
@@ -202,6 +204,46 @@ describe("sdkCutoverPersist", () => {
expect(result.status).toBe("declined");
});
+ it("tags target_not_found with resolverDisagreement when dispatch could have resolved it", async () => {
+ // getElement is canonical-only for a bare id; resolveSnapshot mirrors what
+ // dispatch resolves (bare ids anywhere). An element present under a scoped
+ // id is dispatchable, so getElement refusing it is a resolver disagreement
+ // — and one the shadow event stays silent about.
+ const deps = makeDeps();
+ const session = makeSession(false);
+ (session as unknown as { getElements: () => unknown[] }).getElements = () => [
+ { id: "hf-abc", scopedId: "host/hf-abc" },
+ ];
+ const sel = { hfId: "hf-abc" } as never;
+
+ await sdkCutoverPersist(sel, [styleOp("color", "red")], "before", "/path.html", session, deps);
+
+ expect(trackStudioEvent).toHaveBeenCalledWith(
+ "sdk_cutover_declined",
+ expect.objectContaining({ reason: "target_not_found", resolverDisagreement: true }),
+ );
+ });
+
+ it("does not tag resolverDisagreement when the element is genuinely absent", async () => {
+ const deps = makeDeps();
+ const session = makeSession(false);
+ (session as unknown as { getElements: () => unknown[] }).getElements = () => [
+ { id: "hf-other", scopedId: "hf-other" },
+ ];
+ const sel = { hfId: "hf-abc" } as never;
+ vi.mocked(trackStudioEvent).mockClear();
+
+ await sdkCutoverPersist(sel, [styleOp("color", "red")], "before", "/path.html", session, deps);
+
+ expect(trackStudioEvent).toHaveBeenLastCalledWith(
+ "sdk_cutover_declined",
+ expect.objectContaining({ reason: "target_not_found" }),
+ );
+ expect(vi.mocked(trackStudioEvent).mock.lastCall?.[1]).not.toHaveProperty(
+ "resolverDisagreement",
+ );
+ });
+
it("dispatches setStyle for inline-style ops", async () => {
const deps = makeDeps();
const session = makeSession(true);
diff --git a/packages/studio/src/utils/sdkCutover.ts b/packages/studio/src/utils/sdkCutover.ts
index 37e170112d..faf33b4b1f 100644
--- a/packages/studio/src/utils/sdkCutover.ts
+++ b/packages/studio/src/utils/sdkCutover.ts
@@ -5,7 +5,11 @@ import * as studioAvailability from "../components/editor/manualEditingAvailabil
import { trackStudioEvent } from "./studioTelemetry";
import { patchOpsToSdkEditOps } from "./sdkOpMapping";
import { recordResolverParity, recordAnimationResolverParity } from "./sdkResolverShadow";
-import { shouldDeclineTextCutoverForTarget, shouldUseSdkCutover } from "./sdkCutoverEligibility";
+import {
+ isResolverDisagreement,
+ shouldDeclineTextCutoverForTarget,
+ shouldUseSdkCutover,
+} from "./sdkCutoverEligibility";
import {
asCutoverError,
declinedCutover,
@@ -83,7 +87,8 @@ export async function sdkCutoverPersist(
const hfId = selection.hfId;
if (!hfId) return declinedCutover("target_unaddressable", "dom");
const target = sdkSession.getElement(hfId);
- if (!target) return declinedCutover("target_not_found", "dom");
+ if (!target)
+ return declinedCutover("target_not_found", "dom", isResolverDisagreement(sdkSession, hfId));
if (shouldDeclineTextCutoverForTarget(target, ops))
return declinedCutover("unsupported_text_target", "dom");
if (wrongCompositionFile(deps, targetPath))
@@ -125,7 +130,8 @@ export async function sdkTimingPersist(
// NOT disable it. Gate here so flag-off routes back to the legacy server path.
if (!sdkFamilyEnabled("timing")) return declinedCutover("feature_disabled", "timing");
if (!sdkSession) return declinedCutover("session_unavailable", "timing");
- if (!sdkSession.getElement(hfId)) return declinedCutover("target_not_found", "timing");
+ if (!sdkSession.getElement(hfId))
+ return declinedCutover("target_not_found", "timing", isResolverDisagreement(sdkSession, hfId));
if (wrongCompositionFile(deps, targetPath))
return declinedCutover("wrong_composition_file", "timing");
try {
@@ -172,8 +178,13 @@ export async function sdkTimingBatchPersist(
if (!sdkSession) return declinedCutover("session_unavailable", "timing");
if (wrongCompositionFile(deps, targetPath))
return declinedCutover("wrong_composition_file", "timing");
- if (changes.some((change) => !sdkSession.getElement(change.hfId)))
- return declinedCutover("target_not_found", "timing");
+ const unresolved = changes.find((change) => !sdkSession.getElement(change.hfId));
+ if (unresolved)
+ return declinedCutover(
+ "target_not_found",
+ "timing",
+ isResolverDisagreement(sdkSession, unresolved.hfId),
+ );
try {
const serializedBefore = sdkSession.serialize();
const result = await persistSdkCandidateMutation(
@@ -565,7 +576,12 @@ export async function sdkDeletePersist(
// Dark-launch gate: flag OFF → legacy server delete path.
if (!sdkFamilyEnabled("lifecycle")) return declinedCutover("feature_disabled", "lifecycle");
if (!sdkSession) return declinedCutover("session_unavailable", "lifecycle");
- if (!sdkSession.getElement(hfId)) return declinedCutover("target_not_found", "lifecycle");
+ if (!sdkSession.getElement(hfId))
+ return declinedCutover(
+ "target_not_found",
+ "lifecycle",
+ isResolverDisagreement(sdkSession, hfId),
+ );
if (wrongCompositionFile(deps, targetPath))
return declinedCutover("wrong_composition_file", "lifecycle");
const result = await persistSdkCandidateMutation(
diff --git a/packages/studio/src/utils/sdkCutoverEligibility.ts b/packages/studio/src/utils/sdkCutoverEligibility.ts
index 4e779807bb..2dbc0aee63 100644
--- a/packages/studio/src/utils/sdkCutoverEligibility.ts
+++ b/packages/studio/src/utils/sdkCutoverEligibility.ts
@@ -4,8 +4,10 @@
* sdkCutover.ts (which hit the packages/studio 600-line filesize cap) — this
* block has no dependency on the persist/dispatch functions there.
*/
+import type { Composition } from "@hyperframes/sdk";
import type { PatchOperation } from "./sourcePatcher";
import { isAllowedHtmlAttribute, isSafeAttributeValue } from "./htmlAttrSafety";
+import { resolveSnapshot } from "./sdkResolverShadow";
const CUTOVER_OP_TYPES = new Set<PatchOperation["type"]>([
"inline-style",
@@ -102,6 +104,25 @@ export function shouldDeclineTextCutoverForTarget(target: unknown, ops: PatchOpe
return tag !== null && NON_HTML_CHILD_TAGS.has(tag);
}
+/**
+ * On a `target_not_found`, decide whether the miss is the known benign class
+ * (node genuinely absent from the session — nothing dispatch could have done)
+ * or a resolver disagreement: the shadow's broader resolver finds it, so
+ * dispatch could have made the edit and `getElement` refused it. The shadow
+ * event stays silent in that case, so this flag is the only signal for it.
+ *
+ * Diagnostic context only — it must never turn a clean decline into a throw, so
+ * a session shape without `getElements` reports "no disagreement" and the edit
+ * falls back exactly as it otherwise would have.
+ */
+export function isResolverDisagreement(session: Composition, hfId: string): boolean {
+ try {
+ return resolveSnapshot(session, hfId) !== null;
+ } catch {
+ return false;
+ }
+}
+
export function shouldUseSdkCutover(
flagEnabled: boolean,
hasSession: boolean,
diff --git a/packages/studio/src/utils/sdkEditTransaction.decline.test.ts b/packages/studio/src/utils/sdkEditTransaction.decline.test.ts
index a038b68fee..2de21a7916 100644
--- a/packages/studio/src/utils/sdkEditTransaction.decline.test.ts
+++ b/packages/studio/src/utils/sdkEditTransaction.decline.test.ts
@@ -22,4 +22,25 @@ describe("declinedCutover telemetry", () => {
family: null,
});
});
+
+ it("omits resolverDisagreement when it is not set, and carries it when it is", () => {
+ declinedCutover("target_not_found", "timing");
+ expect(trackStudioEvent).toHaveBeenLastCalledWith("sdk_cutover_declined", {
+ reason: "target_not_found",
+ family: "timing",
+ });
+
+ declinedCutover("target_not_found", "timing", true);
+ expect(trackStudioEvent).toHaveBeenLastCalledWith("sdk_cutover_declined", {
+ reason: "target_not_found",
+ family: "timing",
+ resolverDisagreement: true,
+ });
+
+ declinedCutover("target_not_found", "timing", false);
+ expect(trackStudioEvent).toHaveBeenLastCalledWith("sdk_cutover_declined", {
+ reason: "target_not_found",
+ family: "timing",
+ });
+ });
});
diff --git a/packages/studio/src/utils/sdkEditTransaction.ts b/packages/studio/src/utils/sdkEditTransaction.ts
index a8acb2a1fd..4e8f371d05 100644
--- a/packages/studio/src/utils/sdkEditTransaction.ts
+++ b/packages/studio/src/utils/sdkEditTransaction.ts
@@ -71,9 +71,23 @@ interface CandidateEdit {
* Explicit fall-back to the legacy server path. Emits `sdk_cutover_declined` so
* post-flip we can distinguish "SDK took the edit" from "SDK bowed out"; payload
* is reason + family only (no hfId / path / content).
+ *
+ * `resolverDisagreement` is the one extra field with diagnostic value beyond the
+ * reason itself: on a `target_not_found`, the shadow's `resolveSnapshot` (what
+ * dispatch resolves) found the element that `getElement` could not. The shadow
+ * event stays silent in that case, so without this flag the case is invisible —
+ * and it is an adoption loss (a dispatchable edit refused), not a missing node.
*/
-export function declinedCutover(reason: string, family?: StudioSdkOperationFamily): CutoverResult {
- trackStudioEvent("sdk_cutover_declined", { reason, family: family ?? null });
+export function declinedCutover(
+ reason: string,
+ family?: StudioSdkOperationFamily,
+ resolverDisagreement?: boolean,
+): CutoverResult {
+ trackStudioEvent("sdk_cutover_declined", {
+ reason,
+ family: family ?? null,
+ ...(resolverDisagreement ? { resolverDisagreement: true } : {}),
+ });
return { status: "declined", reason };
}
diff --git a/packages/studio/src/utils/sdkResolverShadow.ts b/packages/studio/src/utils/sdkResolverShadow.ts
index 6508e683f8..e06167480c 100644
--- a/packages/studio/src/utils/sdkResolverShadow.ts
+++ b/packages/studio/src/utils/sdkResolverShadow.ts
@@ -96,7 +96,16 @@ function countHfIdInSource(source: string, id: string): number {
);
}
-function resolveSnapshot(session: Composition, id: string): FlatEl | null {
+/**
+ * Resolvability the SDK DISPATCH path actually has (mirrors `resolveScoped`):
+ * exact scoped-path match, then canonical bare match, then first bare match.
+ *
+ * Exported so the cutover path can distinguish its two `target_not_found` cases:
+ * `Composition.getElement` is narrower (canonical-only for a bare id) than what
+ * `dispatch` resolves, so an element can be genuinely dispatchable yet still
+ * fail `getElement` — a resolver disagreement worth fixing, not a missing node.
+ */
+export function resolveSnapshot(session: Composition, id: string): FlatEl | null {
const els = session.getElements();
const exact = els.find((el) => el.scopedId === id);
if (exact) return exact;