Skip to content

Commit 18e87ac

Browse files
committed
feat(studio,studio-server,cli): render cancel end-to-end + renders/nle/storyboard UX
1 parent 13bc5d2 commit 18e87ac

19 files changed

Lines changed: 866 additions & 201 deletions

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

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

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

351351
startRender(opts): RenderJobState {
352+
const abortController = new AbortController();
352353
const state: RenderJobState = {
353354
id: opts.jobId,
354355
status: "rendering",
355356
progress: 0,
356357
outputPath: opts.outputPath,
358+
cancel: () => abortController.abort(),
357359
};
358360

359361
// Run render asynchronously, mutating the state object
360362
const startTime = Date.now();
361363
(async () => {
362364
let renderJob: RenderJob | undefined;
365+
const removeCancelledOutput = () => {
366+
// User-initiated cancel: not a failure. Remove any output so the
367+
// cancelled job doesn't resurrect in the render history.
368+
state.status = "cancelled";
369+
for (const suffix of ["", ".meta.json"]) {
370+
const fp = suffix
371+
? opts.outputPath.replace(/\.(mp4|webm|mov)$/, suffix)
372+
: opts.outputPath;
373+
try {
374+
if (existsSync(fp)) unlinkSync(fp);
375+
} catch {
376+
/* ignore */
377+
}
378+
}
379+
};
363380
try {
364381
const { createRenderJob, executeRenderJob } = await import("@hyperframes/producer");
365382
const { ensureBrowser } = await import("../browser/manager.js");
@@ -390,7 +407,19 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
390407
state.progress = j.progress;
391408
if (j.currentStage) state.stage = j.currentStage;
392409
};
393-
await executeRenderJob(job, opts.project.dir, opts.outputPath, onProgress);
410+
await executeRenderJob(
411+
job,
412+
opts.project.dir,
413+
opts.outputPath,
414+
onProgress,
415+
abortController.signal,
416+
);
417+
if (abortController.signal.aborted) {
418+
// Cancel landed just as the render finished: honor the cancel the
419+
// route already reported instead of resurrecting a completed job.
420+
removeCancelledOutput();
421+
return;
422+
}
394423
state.status = "complete";
395424
state.progress = 100;
396425
const metaPath = opts.outputPath.replace(/\.(mp4|webm|mov)$/, ".meta.json");
@@ -400,6 +429,10 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
400429
);
401430
emitStudioRenderComplete(opts, Date.now() - startTime, job.perfSummary);
402431
} catch (err) {
432+
if (abortController.signal.aborted) {
433+
removeCancelledOutput();
434+
return;
435+
}
403436
state.status = "failed";
404437
state.error = err instanceof Error ? err.message : String(err);
405438
// fallow-ignore-next-line code-duplication

‎packages/studio-server/src/routes/render.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,81 @@ describe("GET /projects/:id/renders/file/* — path safety", () => {
429429
});
430430
});
431431

432+
describe("POST /render/:jobId/cancel", () => {
433+
async function startJob(app: Hono): Promise<string> {
434+
const res = await app.request("http://localhost/projects/demo/render", {
435+
method: "POST",
436+
headers: { "content-type": "application/json" },
437+
body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4" }),
438+
});
439+
expect(res.status).toBe(200);
440+
return ((await res.json()) as { jobId: string }).jobId;
441+
}
442+
443+
it("marks a rendering job cancelled and invokes the adapter abort hook", async () => {
444+
const spy = vi.fn();
445+
let aborted = false;
446+
const { adapter, rendersDir } = createAdapter(spy);
447+
const baseStartRender = adapter.startRender.bind(adapter);
448+
adapter.startRender = (opts) => {
449+
const state = baseStartRender(opts);
450+
state.cancel = () => {
451+
aborted = true;
452+
};
453+
return state;
454+
};
455+
const app = new Hono();
456+
registerRenderRoutes(app, adapter);
457+
try {
458+
const jobId = await startJob(app);
459+
const res = await app.request(`http://localhost/render/${jobId}/cancel`, { method: "POST" });
460+
expect(res.status).toBe(200);
461+
expect(((await res.json()) as { status: string }).status).toBe("cancelled");
462+
expect(aborted).toBe(true);
463+
// SSE progress for a cancelled job must terminate (status is terminal).
464+
const progress = await app.request(`http://localhost/render/${jobId}/progress`);
465+
expect(progress.status).toBe(200);
466+
} finally {
467+
rmSync(rendersDir, { recursive: true, force: true });
468+
}
469+
});
470+
471+
it("does not cancel a job that already completed", async () => {
472+
const spy = vi.fn();
473+
const states: Array<{ status: string }> = [];
474+
const { adapter, rendersDir } = createAdapter(spy);
475+
const baseStartRender = adapter.startRender.bind(adapter);
476+
adapter.startRender = (opts) => {
477+
const state = baseStartRender(opts);
478+
states.push(state);
479+
return state;
480+
};
481+
const app = new Hono();
482+
registerRenderRoutes(app, adapter);
483+
try {
484+
const jobId = await startJob(app);
485+
const [state] = states;
486+
if (state) state.status = "complete";
487+
const res = await app.request(`http://localhost/render/${jobId}/cancel`, { method: "POST" });
488+
expect(res.status).toBe(200);
489+
expect(((await res.json()) as { status: string }).status).toBe("complete");
490+
} finally {
491+
rmSync(rendersDir, { recursive: true, force: true });
492+
}
493+
});
494+
495+
it("404s for unknown jobs", async () => {
496+
const spy = vi.fn();
497+
const { app, cleanup } = buildApp(spy);
498+
try {
499+
const res = await app.request("http://localhost/render/nope/cancel", { method: "POST" });
500+
expect(res.status).toBe(404);
501+
} finally {
502+
cleanup();
503+
}
504+
});
505+
});
506+
432507
describe("POST /projects/:id/render — telemetryDistinctId forwarding", () => {
433508
it("forwards the browser telemetryDistinctId to the adapter as distinctId", async () => {
434509
const spy = vi.fn();

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

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ export function registerRenderRoutes(api: Hono, adapter: StudioApiAdapter): void
2626
const cleanupFinishedJobs = () => {
2727
const now = Date.now();
2828
for (const [key, job] of renderJobs) {
29-
if ((job.status === "complete" || job.status === "failed") && now - job.createdAt > TTL_MS) {
29+
if (job.status !== "rendering" && now - job.createdAt > TTL_MS) {
3030
renderJobs.delete(key);
3131
}
3232
}
@@ -142,12 +142,25 @@ export function registerRenderRoutes(api: Hono, adapter: StudioApiAdapter): void
142142
error: current.error,
143143
}),
144144
});
145-
if (current.status === "complete" || current.status === "failed") break;
145+
if (current.status !== "rendering") break;
146146
await stream.sleep(500);
147147
}
148148
});
149149
});
150150

151+
// Cancel an in-flight render. Marks the job cancelled immediately (so the
152+
// SSE stream terminates) and invokes the adapter's abort hook when present.
153+
api.post("/render/:jobId/cancel", (c) => {
154+
const { jobId } = c.req.param();
155+
const job = renderJobs.get(jobId);
156+
if (!job) return c.json({ error: "not found" }, 404);
157+
if (job.status === "rendering") {
158+
job.status = "cancelled";
159+
job.cancel?.();
160+
}
161+
return c.json({ status: job.status });
162+
});
163+
151164
const RENDER_MIME: Record<string, string> = {
152165
".mp4": "video/mp4",
153166
".webm": "video/webm",

‎packages/studio-server/src/types.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,17 @@ export interface ResolvedProject {
1212
/** Observable render job state, polled by the SSE progress handler. */
1313
export interface RenderJobState {
1414
id: string;
15-
status: "rendering" | "complete" | "failed";
15+
status: "rendering" | "complete" | "failed" | "cancelled";
1616
progress: number;
1717
stage?: string;
1818
outputPath: string;
1919
error?: string;
20+
/**
21+
* Optional abort hook set by the adapter. The cancel route calls this to
22+
* stop an in-flight render; adapters that can't abort may omit it (the
23+
* route still marks the job cancelled so the SSE stream terminates).
24+
*/
25+
cancel?: () => void;
2026
}
2127

2228
/** Lint result from the core linter. */

‎packages/studio/src/components/nle/CompositionBreadcrumb.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,9 @@ export function CompositionBreadcrumb({ stack, onNavigate }: CompositionBreadcru
3333
});
3434
onNavigate(stack.length - 2);
3535
}}
36-
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"
37-
title="Back (Esc)"
36+
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"
37+
title="Back (Esc, or double-click empty timeline)"
38+
aria-label="Back to parent composition"
3839
>
3940
<ArrowLeft size={12} weight="bold" />
4041
</button>

0 commit comments

Comments
 (0)