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
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
5 changes: 3 additions & 2 deletions packages/studio/src/components/nle/CompositionBreadcrumb.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ export function CompositionBreadcrumb({ stack, onNavigate }: CompositionBreadcru
});
onNavigate(stack.length - 2);
}}
className="flex items-center gap-1 px-1.5 py-0.5 rounded text-xs text-neutral-400 hover:text-white hover:bg-neutral-800 transition-colors"
title="Back (Esc)"
className="flex items-center gap-1 px-1.5 py-0.5 rounded text-xs text-neutral-400 hover:text-white hover:bg-neutral-800 active:scale-[0.98] transition-colors"
title="Back (Esc, or double-click empty timeline)"
aria-label="Back to parent composition"
>
<ArrowLeft size={12} weight="bold" />
</button>
Expand Down
Loading
Loading