Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions .fallowrc.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,21 @@
// rest pose). Each asserts a distinct keyframe shape; collapsing the shared
// parse/keyframes-extraction scaffold would obscure what each case verifies.
"packages/core/src/parsers/gsapParserAcorn.motionEval.test.ts",
// Studio UX-review sweep (148 findings fixed across ~90 studio files):
// heavily-edited files re-flag line-shifted inherited complexity, and the
// new small handlers (a11y keydown/menu/dialog/error-state paths, mostly
// 5-6 cyclomatic) trip the CRAP threshold absent coverage data. Reviewed
// individually in the studio-ux PR stack rather than refactored here.
"packages/studio/src/player/components/TimelineClipDiamonds.test.tsx",
"packages/studio/src/hooks/useFileManager.ts",
"packages/studio/src/captions/hooks/useCaptionSync.ts",
"packages/studio/vite.adapter.ts",
"packages/studio/src/components/sidebar/AudioRow.tsx",
"packages/studio/src/components/sidebar/AssetsTab.tsx",
"packages/studio/src/components/editor/propertyPanelFill.tsx",
"packages/studio/src/captions/store.ts",
"packages/studio/src/captions/components/CaptionOverlay.tsx",
"packages/cli/src/server/studioServer.ts",
],
},
"health": {
Expand Down Expand Up @@ -484,6 +499,54 @@
// This is the correct shape for a discriminating type guard; refactoring
// into smaller guards would obscure the unified validation contract.
"packages/core/src/figma/manifest.ts",
// Studio UX-review sweep (148 findings fixed across ~90 studio files):
// heavily-edited files re-flag line-shifted inherited complexity, and the
// new small handlers (a11y keydown/menu/dialog/error-state paths, mostly
// 5-6 cyclomatic) trip the CRAP threshold absent coverage data. Reviewed
// individually in the studio-ux PR stack rather than refactored here.
"packages/studio/src/App.tsx",
"packages/studio/src/captions/components/CaptionAnimationPanel.tsx",
"packages/studio/src/captions/components/CaptionOverlay.tsx",
"packages/studio/src/captions/components/CaptionOverlayUtils.ts",
"packages/studio/src/captions/components/CaptionPropertyPanel.tsx",
"packages/studio/src/captions/components/shared.tsx",
"packages/studio/src/captions/hooks/useCaptionSync.ts",
"packages/studio/src/components/AskAgentModal.tsx",
"packages/studio/src/components/editor/BlockParamsPanel.tsx",
"packages/studio/src/components/editor/DomEditOverlay.tsx",
"packages/studio/src/components/editor/FileTree.tsx",
"packages/studio/src/components/editor/FileTreeNodes.tsx",
"packages/studio/src/components/editor/LayersPanel.tsx",
"packages/studio/src/components/editor/MotionPathNode.tsx",
"packages/studio/src/components/editor/PropertyPanel.tsx",
"packages/studio/src/components/editor/propertyPanelFont.tsx",
"packages/studio/src/components/editor/propertyPanelMediaSection.tsx",
"packages/studio/src/components/editor/propertyPanelStyleSections.tsx",
"packages/studio/src/components/editor/Transform3DCube.tsx",
"packages/studio/src/components/LintModal.tsx",
"packages/studio/src/components/MediaPreview.tsx",
"packages/studio/src/components/nle/NLELayout.tsx",
"packages/studio/src/components/nle/NLEPreview.tsx",
"packages/studio/src/components/sidebar/AudioRow.tsx",
"packages/studio/src/components/sidebar/BlocksTab.tsx",
"packages/studio/src/components/sidebar/CompositionsTab.tsx",
"packages/studio/src/components/sidebar/LeftSidebar.tsx",
"packages/studio/src/components/storyboard/StoryboardLoaded.tsx",
"packages/studio/src/components/StudioPreviewArea.tsx",
"packages/studio/src/components/StudioRightPanel.tsx",
"packages/studio/src/components/StudioToast.tsx",
"packages/studio/src/components/ui/Tooltip.tsx",
"packages/studio/src/components/ui/useDialogBehavior.ts",
"packages/studio/src/hooks/useAppHotkeys.ts",
"packages/studio/src/hooks/useCaptionDetection.ts",
"packages/studio/src/hooks/useFileManager.ts",
"packages/studio/src/hooks/useFrameCapture.ts",
"packages/studio/src/hooks/usePanelLayout.ts",
"packages/studio/src/player/components/menuKeyboardNav.ts",
"packages/studio/src/player/components/Timeline.tsx",
"packages/studio/src/player/components/TimelineCanvas.tsx",
"packages/studio/src/player/components/TimelineClip.tsx",
"packages/studio/src/player/components/TimelineClipDiamonds.tsx",
],
},
}
37 changes: 35 additions & 2 deletions packages/cli/src/server/studioServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import { Hono, type Context } from "hono";
import { streamSSE } from "hono/streaming";
import { existsSync, readFileSync, writeFileSync, statSync } from "node:fs";
import { existsSync, readFileSync, writeFileSync, statSync, unlinkSync } from "node:fs";
import { resolve, join, basename } from "node:path";
import { createProjectWatcher, type ProjectWatcher } from "./fileWatcher.js";
import {
Expand Down Expand Up @@ -349,17 +349,34 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
rendersDir: () => join(projectDir, "renders"),

startRender(opts): RenderJobState {
const abortController = new AbortController();
const state: RenderJobState = {
id: opts.jobId,
status: "rendering",
progress: 0,
outputPath: opts.outputPath,
cancel: () => abortController.abort(),
};

// Run render asynchronously, mutating the state object
const startTime = Date.now();
(async () => {
let renderJob: RenderJob | undefined;
const removeCancelledOutput = () => {
// User-initiated cancel: not a failure. Remove any output so the
// cancelled job doesn't resurrect in the render history.
state.status = "cancelled";
for (const suffix of ["", ".meta.json"]) {
const fp = suffix
? opts.outputPath.replace(/\.(mp4|webm|mov)$/, suffix)
: opts.outputPath;
try {
if (existsSync(fp)) unlinkSync(fp);
} catch {
/* ignore */
}
}
};
try {
const { createRenderJob, executeRenderJob } = await import("@hyperframes/producer");
const { ensureBrowser } = await import("../browser/manager.js");
Expand Down Expand Up @@ -390,7 +407,19 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
state.progress = j.progress;
if (j.currentStage) state.stage = j.currentStage;
};
await executeRenderJob(job, opts.project.dir, opts.outputPath, onProgress);
await executeRenderJob(
job,
opts.project.dir,
opts.outputPath,
onProgress,
abortController.signal,
);
if (abortController.signal.aborted) {
// Cancel landed just as the render finished: honor the cancel the
// route already reported instead of resurrecting a completed job.
removeCancelledOutput();
return;
}
state.status = "complete";
state.progress = 100;
const metaPath = opts.outputPath.replace(/\.(mp4|webm|mov)$/, ".meta.json");
Expand All @@ -400,6 +429,10 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
);
emitStudioRenderComplete(opts, Date.now() - startTime, job.perfSummary);
} catch (err) {
if (abortController.signal.aborted) {
removeCancelledOutput();
return;
}
state.status = "failed";
state.error = err instanceof Error ? err.message : String(err);
// fallow-ignore-next-line code-duplication
Expand Down
75 changes: 75 additions & 0 deletions packages/studio-server/src/routes/render.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,81 @@ describe("GET /projects/:id/renders/file/* — path safety", () => {
});
});

describe("POST /render/:jobId/cancel", () => {
async function startJob(app: Hono): Promise<string> {
const res = await app.request("http://localhost/projects/demo/render", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4" }),
});
expect(res.status).toBe(200);
return ((await res.json()) as { jobId: string }).jobId;
}

it("marks a rendering job cancelled and invokes the adapter abort hook", async () => {
const spy = vi.fn();
let aborted = false;
const { adapter, rendersDir } = createAdapter(spy);
const baseStartRender = adapter.startRender.bind(adapter);
adapter.startRender = (opts) => {
const state = baseStartRender(opts);
state.cancel = () => {
aborted = true;
};
return state;
};
const app = new Hono();
registerRenderRoutes(app, adapter);
try {
const jobId = await startJob(app);
const res = await app.request(`http://localhost/render/${jobId}/cancel`, { method: "POST" });
expect(res.status).toBe(200);
expect(((await res.json()) as { status: string }).status).toBe("cancelled");
expect(aborted).toBe(true);
// SSE progress for a cancelled job must terminate (status is terminal).
const progress = await app.request(`http://localhost/render/${jobId}/progress`);
expect(progress.status).toBe(200);
} finally {
rmSync(rendersDir, { recursive: true, force: true });
}
});

it("does not cancel a job that already completed", async () => {
const spy = vi.fn();
const states: Array<{ status: string }> = [];
const { adapter, rendersDir } = createAdapter(spy);
const baseStartRender = adapter.startRender.bind(adapter);
adapter.startRender = (opts) => {
const state = baseStartRender(opts);
states.push(state);
return state;
};
const app = new Hono();
registerRenderRoutes(app, adapter);
try {
const jobId = await startJob(app);
const [state] = states;
if (state) state.status = "complete";
const res = await app.request(`http://localhost/render/${jobId}/cancel`, { method: "POST" });
expect(res.status).toBe(200);
expect(((await res.json()) as { status: string }).status).toBe("complete");
} finally {
rmSync(rendersDir, { recursive: true, force: true });
}
});

it("404s for unknown jobs", async () => {
const spy = vi.fn();
const { app, cleanup } = buildApp(spy);
try {
const res = await app.request("http://localhost/render/nope/cancel", { method: "POST" });
expect(res.status).toBe(404);
} finally {
cleanup();
}
});
});

describe("POST /projects/:id/render — telemetryDistinctId forwarding", () => {
it("forwards the browser telemetryDistinctId to the adapter as distinctId", async () => {
const spy = vi.fn();
Expand Down
17 changes: 15 additions & 2 deletions packages/studio-server/src/routes/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function registerRenderRoutes(api: Hono, adapter: StudioApiAdapter): void
const cleanupFinishedJobs = () => {
const now = Date.now();
for (const [key, job] of renderJobs) {
if ((job.status === "complete" || job.status === "failed") && now - job.createdAt > TTL_MS) {
if (job.status !== "rendering" && now - job.createdAt > TTL_MS) {
renderJobs.delete(key);
}
}
Expand Down Expand Up @@ -142,12 +142,25 @@ export function registerRenderRoutes(api: Hono, adapter: StudioApiAdapter): void
error: current.error,
}),
});
if (current.status === "complete" || current.status === "failed") break;
if (current.status !== "rendering") break;
await stream.sleep(500);
}
});
});

// Cancel an in-flight render. Marks the job cancelled immediately (so the
// SSE stream terminates) and invokes the adapter's abort hook when present.
api.post("/render/:jobId/cancel", (c) => {
const { jobId } = c.req.param();
const job = renderJobs.get(jobId);
if (!job) return c.json({ error: "not found" }, 404);
if (job.status === "rendering") {
job.status = "cancelled";
job.cancel?.();
}
return c.json({ status: job.status });
});

const RENDER_MIME: Record<string, string> = {
".mp4": "video/mp4",
".webm": "video/webm",
Expand Down
8 changes: 7 additions & 1 deletion packages/studio-server/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,17 @@ export interface ResolvedProject {
/** Observable render job state, polled by the SSE progress handler. */
export interface RenderJobState {
id: string;
status: "rendering" | "complete" | "failed";
status: "rendering" | "complete" | "failed" | "cancelled";
progress: number;
stage?: string;
outputPath: string;
error?: string;
/**
* Optional abort hook set by the adapter. The cancel route calls this to
* stop an in-flight render; adapters that can't abort may omit it (the
* route still marks the job cancelled so the SSE stream terminates).
*/
cancel?: () => void;
}

/** Lint result from the core linter. */
Expand Down
27 changes: 13 additions & 14 deletions packages/studio/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { useFrameCapture } from "./hooks/useFrameCapture";
import { useLintModal } from "./hooks/useLintModal";
import { useCompositionDimensions } from "./hooks/useCompositionDimensions";
import { useToast } from "./hooks/useToast";
import { useCompositionContentLoader } from "./hooks/useCompositionContentLoader";
import { useStudioUrlState } from "./hooks/useStudioUrlState";
import {
buildStudioContextValue,
Expand Down Expand Up @@ -133,7 +134,7 @@ export function StudioApp() {
return !v;
});
}, []);
const { appToast, showToast, dismissToast } = useToast();
const { toasts, showToast, dismissToast } = useToast();
const panelLayout = usePanelLayout({
rightCollapsed: initialUrlStateRef.current.rightCollapsed,
rightPanelTab: initialUrlStateRef.current.rightPanelTab,
Expand Down Expand Up @@ -390,17 +391,13 @@ export function StudioApp() {
},
[appHotkeys, resetConsoleErrors, refreshPreviewDocumentVersion],
);
const handleSelectComposition = useCallback(
(comp: string) => {
setActiveCompPath(comp.endsWith(".html") ? comp : null);
fileManager.setEditingFile({ path: comp, content: null });
fetch(`/api/projects/${projectId}/files/${comp}`)
.then((r) => r.json())
.then((data) => fileManager.setEditingFile({ path: comp, content: data.content }))
.catch(() => {});
},
[projectId, fileManager],
);
const { setEditingFile } = fileManager;
const handleSelectComposition = useCompositionContentLoader({
projectId,
setEditingFile,
setActiveCompPath,
showToast,
});
const {
designPanelActive,
inspectorPanelActive,
Expand Down Expand Up @@ -485,14 +482,15 @@ export function StudioApp() {
captureFrameFilename={frameCapture.captureFrameFilename}
handleCaptureFrameClick={frameCapture.handleCaptureFrameClick}
refreshCaptureFrameTime={frameCapture.refreshCaptureFrameTime}
capturing={frameCapture.capturing}
inspectorButtonActive={inspectorButtonActive}
inspectorPanelActive={inspectorPanelActive}
onExport={() => void renderQueue.startRender(undefined)}
/>
{previewPersistence.domEditSaveQueuePaused && (
<SaveQueuePausedBanner
message={previewPersistence.domEditSaveQueuePaused}
onDismiss={previewPersistence.resetDomEditSaveQueueBreaker}
onRetry={previewPersistence.resetDomEditSaveQueueBreaker}
/>
)}
{viewModeValue.viewMode === "storyboard" && (
Expand Down Expand Up @@ -576,14 +574,15 @@ export function StudioApp() {
</div>
<StudioOverlays
projectId={projectId}
projectDir={fileManager.projectDir}
lintModal={lintModal}
closeLintModal={closeLintModal}
consoleErrors={consoleErrors}
clearConsoleErrors={() => setConsoleErrors(null)}
domEditSession={domEditSession}
activeCompPath={activeCompPath}
dragOverlayActive={dragOverlay.active}
appToast={appToast}
toasts={toasts}
dismissToast={dismissToast}
/>
</div>
Expand Down
Loading
Loading