Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(export): enable Cancel during an MP4 export (#1014)

EtienneLescotf2012f9933a8
diff --git a/electron/ipc/gifExportJobs.test.ts b/electron/ipc/exportJobs.test.ts
similarity index 88%
rename from electron/ipc/gifExportJobs.test.ts
rename to electron/ipc/exportJobs.test.ts
index b54550da5..1ae944c28 100644
--- a/electron/ipc/gifExportJobs.test.ts
+++ b/electron/ipc/exportJobs.test.ts
@@ -1,7 +1,7 @@
import { EventEmitter } from "node:events";
import type { WebContents } from "electron";
import { describe, expect, it, vi } from "vitest";
-import { GifExportJobs, isGifExportId } from "./gifExportJobs";
+import { ExportJobs, isExportId } from "./exportJobs";
function owner(id = 1) {
return Object.assign(new EventEmitter(), {
@@ -20,9 +20,9 @@ function pending() {
return { result, resolve, reject, cancel: vi.fn(() => true) };
}
-describe("GIF export jobs", () => {
+describe("export jobs", () => {
it("binds cancel to the sender and ID, including before native compute starts", async () => {
- const jobs = new GifExportJobs();
+ const jobs = new ExportJobs();
const sender = owner();
const job = pending();
const run = jobs.run(sender, "job_1", () => job, vi.fn());
@@ -38,7 +38,7 @@ describe("GIF export jobs", () => {
});
it("rejects a duplicate job without starting it and allows a retry after failure", async () => {
- const jobs = new GifExportJobs();
+ const jobs = new ExportJobs();
const sender = owner();
const job = pending();
const run = jobs.run(sender, "first", () => job, vi.fn());
@@ -55,7 +55,7 @@ describe("GIF export jobs", () => {
});
it("cancels on sender destruction and suppresses late progress after a retry", async () => {
- const jobs = new GifExportJobs();
+ const jobs = new ExportJobs();
const sender = owner();
const job = pending();
const progress = vi.fn();
@@ -84,7 +84,7 @@ describe("GIF export jobs", () => {
});
it("does not reinterpret a completion that wins the cancellation race", async () => {
- const jobs = new GifExportJobs();
+ const jobs = new ExportJobs();
const sender = owner();
const job = pending();
job.cancel.mockReturnValue(false);
@@ -103,13 +103,13 @@ describe("GIF export jobs", () => {
"a/b",
"a".repeat(129),
])("rejects malformed IDs: %j", (id) => {
- expect(isGifExportId(id)).toBe(false);
+ expect(isExportId(id)).toBe(false);
});
it("rejects an invalid start before invoking native code", async () => {
const start = vi.fn(() => pending());
- await expect(new GifExportJobs().run(owner(), "../bad", start, vi.fn())).rejects.toThrow(
- "Invalid GIF export ID",
+ await expect(new ExportJobs().run(owner(), "../bad", start, vi.fn())).rejects.toThrow(
+ "Invalid export ID",
);
expect(start).not.toHaveBeenCalled();
});
diff --git a/electron/ipc/gifExportJobs.ts b/electron/ipc/exportJobs.ts
similarity index 72%
rename from electron/ipc/gifExportJobs.ts
rename to electron/ipc/exportJobs.ts
index fe318b35e..727fdff51 100644
--- a/electron/ipc/gifExportJobs.ts
+++ b/electron/ipc/exportJobs.ts
@@ -2,17 +2,17 @@ import type { WebContents } from "electron";
type ExportOwner = Pick<WebContents, "id" | "isDestroyed" | "once" | "removeListener">;
-export interface GifExportJob<T> {
+export interface ExportJob<T> {
result: Promise<T>;
cancel: () => boolean;
}
-export function isGifExportId(value: unknown): value is string {
+export function isExportId(value: unknown): value is string {
return typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
}
/** Controls never leave main. Unknown and foreign IDs have the same result. */
-export class GifExportJobs {
+export class ExportJobs {
private readonly jobs = new Map<number, { exportId: string; cancel: () => boolean }>();
cancel(owner: ExportOwner, exportId: string): boolean {
@@ -23,12 +23,12 @@ export class GifExportJobs {
async run<T>(
owner: ExportOwner,
exportId: string,
- start: (progress: (frames: number) => void) => GifExportJob<T>,
+ start: (progress: (frames: number) => void) => ExportJob<T>,
onProgress: (frames: number) => void,
): Promise<T> {
- if (!isGifExportId(exportId)) throw new Error("Invalid GIF export ID.");
- if (owner.isDestroyed()) throw new Error("GIF export window is closed.");
- if (this.jobs.has(owner.id)) throw new Error("A GIF export is already running in this window.");
+ if (!isExportId(exportId)) throw new Error("Invalid export ID.");
+ if (owner.isDestroyed()) throw new Error("Export window is closed.");
+ if (this.jobs.has(owner.id)) throw new Error("An export is already running in this window.");
let active = true;
const job = start((frames) => {
if (active && !owner.isDestroyed()) onProgress(frames);
diff --git a/electron/ipc/nativeBridge.export.test.ts b/electron/ipc/nativeBridge.export.test.ts
new file mode 100644
index 000000000..9fbd008eb
--- /dev/null
+++ b/electron/ipc/nativeBridge.export.test.ts
@@ -0,0 +1,88 @@
+// An MP4 export started with an ID runs as a job of its window, so a cancel naming that ID
+// reaches the native control, and the native cancellation comes back as CANCELLED.
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { NativeBridgeResponse } from "../../src/native/contracts";
+import { type NativeBridgeContext, registerNativeBridgeHandlers } from "./nativeBridge";
+
+const electron = vi.hoisted(() => ({ handle: vi.fn() }));
+vi.mock("electron", () => ({
+ app: { getAppPath: () => "", isPackaged: false },
+ ipcMain: { handle: electron.handle, removeHandler: vi.fn() },
+ shell: {},
+}));
+const compositor = vi.hoisted(() => ({ startExportMulti: vi.fn(), exportMulti: vi.fn() }));
+vi.mock("../native-bridge/services/compositorViewService", () => ({
+ CompositorViewService: class {
+ startExportMulti = compositor.startExportMulti;
+ exportMulti = compositor.exportMulti;
+ },
+}));
+vi.mock("../native-bridge/services/aiEditionService", () => ({
+ AiEditionService: class {},
+}));
+
+const sender = {
+ id: 1,
+ isDestroyed: () => false,
+ send: vi.fn(),
+ once: vi.fn(),
+ removeListener: vi.fn(),
+};
+let invoke: (action: string, payload: unknown) => Promise<NativeBridgeResponse>;
+
+beforeEach(() => {
+ electron.handle.mockClear();
+ sender.send.mockClear();
+ for (const fn of Object.values(compositor)) fn.mockReset();
+ registerNativeBridgeHandlers({
+ getPlatform: () => "linux",
+ getAiEditionDocuments: () => ({}),
+ getAiEditionLlmConfig: () => ({}),
+ } as unknown as NativeBridgeContext);
+ const handler = electron.handle.mock.calls[0]?.[1] as (
+ event: unknown,
+ request: unknown,
+ ) => Promise<NativeBridgeResponse>;
+ invoke = (action, payload) => handler({ sender }, { domain: "compositor", action, payload });
+});
+
+describe("native bridge MP4 export", () => {
+ it("cancels a running export by its ID and reports CANCELLED", async () => {
+ let fail!: (error: Error) => void;
+ const cancel = vi.fn(() => true);
+ compositor.startExportMulti.mockImplementation((...args: unknown[]) => {
+ (args[4] as (frames: number) => void)(3);
+ const result = new Promise((_, reject) => {
+ fail = reject;
+ });
+ return { result, cancel };
+ });
+ const running = invoke("exportMulti", { clips: [], outPath: "/tmp/a.mp4", exportId: "mp4-1" });
+ await vi.waitFor(() => expect(compositor.startExportMulti).toHaveBeenCalledOnce());
+ expect(sender.send).toHaveBeenCalledWith("export:native-progress", 3, "mp4-1");
+
+ expect(await invoke("cancelExport", { exportId: "other" })).toMatchObject({
+ ok: true,
+ data: { accepted: false },
+ });
+ expect(await invoke("cancelExport", { exportId: "mp4-1" })).toMatchObject({
+ ok: true,
+ data: { accepted: true },
+ });
+ expect(cancel).toHaveBeenCalledOnce();
+
+ fail(new Error("MP4_EXPORT_CANCELLED"));
+ expect(await running).toMatchObject({ ok: false, error: { code: "CANCELLED" } });
+ });
+
+ it("runs an export without an ID outside the job registry, as the CLI does", async () => {
+ const stats = { frames: 1, wallS: 1, fps: 1, videoDurationS: 1 };
+ compositor.exportMulti.mockResolvedValue(stats);
+ expect(await invoke("exportMulti", { clips: [], outPath: "/tmp/a.mp4" })).toMatchObject({
+ ok: true,
+ data: stats,
+ });
+ expect(compositor.startExportMulti).not.toHaveBeenCalled();
+ });
+});
diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.ts
index 61ed8ef86..954cc834f 100644
--- a/electron/ipc/nativeBridge.ts
+++ b/electron/ipc/nativeBridge.ts
@@ -24,7 +24,7 @@ import { CursorService } from "../native-bridge/services/cursorService";
import { ProjectService } from "../native-bridge/services/projectService";
import { SystemService } from "../native-bridge/services/systemService";
import { createNativeBridgeState } from "../native-bridge/store";
-import { GifExportJobs, isGifExportId } from "./gifExportJobs";
+import { ExportJobs, isExportId } from "./exportJobs";
export interface NativeBridgeContext {
getPlatform: () => NodeJS.Platform;
@@ -250,7 +250,7 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
deleteSession: context.deleteAiEditionChatSession,
});
- const gifExportJobs = new GifExportJobs();
+ const exportJobs = new ExportJobs();
ipcMain.handle(NATIVE_BRIDGE_CHANNEL, async (event, request: unknown) => {
if (!isBridgeRequest(request)) {
return createErrorResponse(undefined, "INVALID_REQUEST", "Invalid native bridge request.");
@@ -432,17 +432,34 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
return createSuccessResponse(requestId, { ok: true });
case "exportMulti": {
const sender = event.sender;
- const stats = await compositorViewService.exportMulti(
- request.payload.clips,
- request.payload.outPath,
- request.payload.sceneJson,
- request.payload.params,
- (frames) => {
- if (!sender.isDestroyed()) {
- sender.send("export:native-progress", frames);
- }
- },
- );
+ const exportId = request.payload?.exportId;
+ if (exportId !== undefined && !isExportId(exportId)) {
+ return createErrorResponse(requestId, "INVALID_REQUEST", "Invalid export ID.");
+ }
+ const onProgress = (frames: number) => {
+ if (!sender.isDestroyed()) sender.send("export:native-progress", frames, exportId);
+ };
+ const stats = exportId
+ ? await exportJobs.run(
+ sender,
+ exportId,
+ (progress) =>
+ compositorViewService.startExportMulti(
+ request.payload.clips,
+ request.payload.outPath,
+ request.payload.sceneJson,
+ request.payload.params,
+ progress,
+ ),
+ onProgress,
+ )
+ : await compositorViewService.exportMulti(
+ request.payload.clips,
+ request.payload.outPath,
+ request.payload.sceneJson,
+ request.payload.params,
+ onProgress,
+ );
if (!stats) {
return createErrorResponse(
requestId,
@@ -455,14 +472,14 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
case "exportGif": {
const sender = event.sender;
const exportId = request.payload?.exportId;
- if (exportId !== undefined && !isGifExportId(exportId)) {
- return createErrorResponse(requestId, "INVALID_REQUEST", "Invalid GIF export ID.");
+ if (exportId !== undefined && !isExportId(exportId)) {
+ return createErrorResponse(requestId, "INVALID_REQUEST", "Invalid export ID.");
}
const onProgress = (frames: number) => {
if (!sender.isDestroyed()) sender.send("export:native-progress", frames, exportId);
};
const stats = exportId
- ? await gifExportJobs.run(
+ ? await exportJobs.run(
sender,
exportId,
(progress) =>
@@ -491,13 +508,13 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
}
return createSuccessResponse(requestId, stats);
}
- case "cancelGifExport": {
+ case "cancelExport": {
const exportId = request.payload?.exportId;
- if (!isGifExportId(exportId)) {
- return createErrorResponse(requestId, "INVALID_REQUEST", "Invalid GIF export ID.");
+ if (!isExportId(exportId)) {
+ return createErrorResponse(requestId, "INVALID_REQUEST", "Invalid export ID.");
}
return createSuccessResponse(requestId, {
- accepted: gifExportJobs.cancel(event.sender, exportId),
+ accepted: exportJobs.cancel(event.sender, exportId),
});
}
default:
@@ -797,11 +814,11 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
} catch (error) {
if (
request.domain === "compositor" &&
- request.action === "exportGif" &&
error instanceof Error &&
- error.message === "GIF_EXPORT_CANCELLED"
+ ((request.action === "exportGif" && error.message === "GIF_EXPORT_CANCELLED") ||
+ (request.action === "exportMulti" && error.message === "MP4_EXPORT_CANCELLED"))
) {
- return createErrorResponse(requestId, "CANCELLED", "GIF export cancelled.");
+ return createErrorResponse(requestId, "CANCELLED", "Export cancelled.");
}
// Not retryable by default: most failures here are permanent (a missing
// file, a bad payload, an unavailable addon), and a blanket `true` tells
diff --git a/electron/native-bridge/services/compositorViewService.test.ts b/electron/native-bridge/services/compositorViewService.test.ts
index 4a099a7f9..9de1ac91b 100644
--- a/electron/native-bridge/services/compositorViewService.test.ts
+++ b/electron/native-bridge/services/compositorViewService.test.ts
@@ -59,6 +59,47 @@ describe("native GIF cancellation capability", () => {
});
});
+describe("native MP4 cancellation capability", () => {
+ const stats = { frames: 1, wallS: 1, fps: 1, videoDurationS: 1 };
+
+ it("passes one opaque control to the native export and cancels through it", async () => {
+ const control = {};
+ const exportMulti = vi.fn(async () => stats);
+ const cancelMp4Export = vi.fn(() => true);
+ const service = new CompositorViewService({
+ addon: {
+ createMp4ExportControl: () => control,
+ cancelMp4Export,
+ exportMulti,
+ } as unknown as CompositorViewAddon,
+ });
+ const progress = vi.fn();
+ const job = service.startExportMulti([], "/tmp/test.mp4", undefined, { fps: 30 }, progress);
+ expect(exportMulti).toHaveBeenCalledWith(
+ [],
+ "/tmp/test.mp4",
+ undefined,
+ { fps: 30 },
+ progress,
+ control,
+ );
+ expect(job.cancel()).toBe(true);
+ expect(cancelMp4Export).toHaveBeenCalledWith(control);
+ await expect(job.result).resolves.toEqual(stats);
+ });
+
+ it("still exports through an addon that cannot cancel an MP4, and refuses the cancel", async () => {
+ const exportMulti = vi.fn(async () => stats);
+ const service = new CompositorViewService({
+ addon: { exportMulti } as unknown as CompositorViewAddon,
+ });
+ const job = service.startExportMulti([], "/tmp/test.mp4");
+ expect(job.cancel()).toBe(false);
+ await expect(job.result).resolves.toEqual(stats);
+ expect(exportMulti).toHaveBeenCalledOnce();
+ });
+});
+
describe("CompositorViewService frames handed over as shared GPU textures", () => {
const target = { frameTreeNodeId: 1 } as unknown as WebFrameMain;
const sharedFrame = {
diff --git a/electron/native-bridge/services/compositorViewService.ts b/electron/native-bridge/services/compositorViewService.ts
index 6dbfb1461..6d16a2a09 100644
--- a/electron/native-bridge/services/compositorViewService.ts
+++ b/electron/native-bridge/services/compositorViewService.ts
@@ -12,7 +12,7 @@ import type {
CompositorSharedFrameMeta,
CompositorSharedFrameReceipt,
} from "../../../src/native/contracts";
-import type { GifExportJob } from "../../ipc/gifExportJobs";
+import type { ExportJob } from "../../ipc/exportJobs";
import type {
ClipInput,
CompositorBackend,
@@ -805,6 +805,7 @@ export class CompositorViewService {
sceneJson?: string,
params?: ExportParamsInput,
onProgress?: (frames: number) => void,
+ control?: object,
): Promise<ExportStats | null> {
const addon = this.ensureAddon();
if (!addon) {
@@ -817,9 +818,35 @@ export class CompositorViewService {
sceneJson ? resolveSceneAssetPaths(sceneJson) : undefined,
params,
onProgress,
+ control,
);
}
+ /** `startGifExport` for MP4, except that an addon built before MP4 cancellation still
+ * exports: the main export must not fail over a missing Cancel. That job runs to the end
+ * and refuses to cancel. */
+ startExportMulti(
+ clips: ClipInput[],
+ outPath?: string,
+ sceneJson?: string,
+ params?: ExportParamsInput,
+ onProgress?: (frames: number) => void,
+ ): ExportJob<ExportStats | null> {
+ const addon = this.ensureAddon();
+ if (!addon?.createMp4ExportControl || !addon.cancelMp4Export) {
+ return {
+ result: this.exportMulti(clips, outPath, sceneJson, params, onProgress),
+ cancel: () => false,
+ };
+ }
+ const control = addon.createMp4ExportControl();
+ const cancel = addon.cancelMp4Export.bind(addon);
+ return {
+ result: this.exportMulti(clips, outPath, sceneJson, params, onProgress, control),
+ cancel: () => cancel(control),
+ };
+ }
+
/** Native GIF export. Same inputs as `exportMulti` — one clip list, one scene —
* because it is the same render: both drive `walk_composited_timeline` in the
* compositor crate and differ only in the encoder. The scene carries background,
@@ -856,7 +883,7 @@ export class CompositorViewService {
sceneJson?: string,
params?: GifParamsInput,
onProgress?: (frames: number) => void,
- ): GifExportJob<GifExportStats | null> {
+ ): ExportJob<GifExportStats | null> {
const addon = this.ensureAddon();
if (!addon?.createGifExportControl || !addon.cancelGifExport) {
throw new Error(
diff --git a/electron/native/compositor-view/addon.d.ts b/electron/native/compositor-view/addon.d.ts
index e87b830b5..ade2769a7 100644
--- a/electron/native/compositor-view/addon.d.ts
+++ b/electron/native/compositor-view/addon.d.ts
@@ -216,14 +216,21 @@ export interface CompositorViewAddon {
* `sceneJson` — same `SceneDescription` as the live preview (background/layout/webcam/cursor/
* effects); omitted or invalid → nothing configured is applied (not a masking fallback).
* `params` — output size/fps/codec; omitted → 1920x1080/first clip's fps/h264.
- * `onProgress` (frames encoded so far) is optional, throttled to ~10/s. */
+ * `onProgress` (frames encoded so far) is optional, throttled to ~10/s.
+ * `control` (`createMp4ExportControl`) — cancelling it stops the render between two frames
+ * and rejects with `MP4_EXPORT_CANCELLED`, leaving no file. */
exportMulti(
clips: ClipInput[],
outPath: string,
sceneJson?: string,
params?: ExportParamsInput,
onProgress?: (frames: number) => void,
+ control?: object,
): Promise<ExportStats>;
+ /** Opaque napi External, like the GIF one. Absent from a `.node` whose `exportMulti` ignores
+ * a control: that addon's MP4 export cannot be cancelled. */
+ createMp4ExportControl?(): object;
+ cancelMp4Export?(control: object): boolean;
/** Native GIF export. Identical inputs to `exportMulti` — same clips, same
* scene — because it is the same render: both drive `walk_composited_timeline`
* in the compositor crate and differ only in the encoder. Cursor, background,
diff --git a/src/components/ai-edition/ExportDialog.cancel.test.tsx b/src/components/ai-edition/ExportDialog.cancel.test.tsx
index 8d2403b9c..308a76eee 100644
--- a/src/components/ai-edition/ExportDialog.cancel.test.tsx
+++ b/src/components/ai-edition/ExportDialog.cancel.test.tsx
@@ -7,7 +7,7 @@ vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
vi.mock("@/native", () => ({
exportMultiNative: vi.fn(),
exportGifNative: vi.fn(),
- cancelGifExportNative: vi.fn(async () => ({ accepted: true })),
+ cancelExportNative: vi.fn(async () => ({ accepted: true })),
useIsCpuCompositor: () => false,
}));
vi.mock("@/native/sceneDescription", () => ({
@@ -18,9 +18,9 @@ vi.mock("@/native/sceneDescription", () => ({
import { toast } from "sonner";
import { I18nProvider } from "@/contexts/I18nContext";
import { type AxcutDocument, axcutSchemaVersion } from "@/lib/ai-edition/schema";
-import { cancelGifExportNative, exportGifNative } from "@/native";
+import { cancelExportNative, exportGifNative, exportMultiNative } from "@/native";
import { NativeBridgeRequestError } from "@/native/client";
-import type { CompositorExportGifResult } from "@/native/contracts";
+import type { CompositorExportGifResult, CompositorExportResult } from "@/native/contracts";
import { ExportDialog } from "./ExportDialog";
const DOC: AxcutDocument = {
@@ -106,10 +106,34 @@ async function start() {
return { ...view, id };
}
-describe("GIF export cancellation", () => {
+function pendingMp4Export() {
+ let resolve!: (stats: CompositorExportResult) => void;
+ let reject!: (error: Error) => void;
+ const result = new Promise<CompositorExportResult>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ vi.mocked(exportMultiNative).mockReturnValueOnce(result);
+ return { resolve, reject };
+}
+
+async function startMp4() {
+ render(
+ <I18nProvider>
+ <ExportDialog open onClose={onClose} document={DOC} />
+ </I18nProvider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Export MP4" }));
+ await waitFor(() => expect(exportMultiNative).toHaveBeenCalledOnce());
+ const id = vi.mocked(exportMultiNative).mock.calls[0][4];
+ expect(id).toMatch(/^[A-Za-z0-9_-]+$/);
+ return id as string;
+}
+
+describe("export cancellation", () => {
beforeEach(() => {
vi.clearAllMocks();
- vi.mocked(cancelGifExportNative).mockResolvedValue({ accepted: true });
+ vi.mocked(cancelExportNative).mockResolvedValue({ accepted: true });
onClose = vi.fn();
unsubscribe = vi.fn();
window.electronAPI = {
@@ -128,10 +152,10 @@ describe("GIF export cancellation", () => {
const cancel = screen.getByRole("button", { name: "Cancel" });
expect(cancel).toBeEnabled();
fireEvent.click(cancel);
- await waitFor(() => expect(cancelGifExportNative).toHaveBeenCalledWith(id));
+ await waitFor(() => expect(cancelExportNative).toHaveBeenCalledWith(id));
expect(cancel).toBeDisabled();
fireEvent.click(cancel);
- expect(cancelGifExportNative).toHaveBeenCalledOnce();
+ expect(cancelExportNative).toHaveBeenCalledOnce();
expect(screen.queryByRole("button", { name: "Export GIF" })).not.toBeInTheDocument();
await act(async () =>
job.reject(
@@ -186,7 +210,7 @@ describe("GIF export cancellation", () => {
});
it("surfaces a rejected cancel request instead of keeping the progress view", async () => {
- vi.mocked(cancelGifExportNative).mockRejectedValueOnce(new Error("cancel ipc failed"));
+ vi.mocked(cancelExportNative).mockRejectedValueOnce(new Error("cancel ipc failed"));
pendingExport();
await start();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
@@ -196,8 +220,48 @@ describe("GIF export cancellation", () => {
expect(screen.queryByText(/Exporting your video/i)).not.toBeInTheDocument();
});
+ it("cancels an MP4 mid-render and returns to the same options", async () => {
+ const job = pendingMp4Export();
+ const id = await startMp4();
+ const cancel = screen.getByRole("button", { name: "Cancel" });
+ expect(cancel).toBeEnabled();
+ fireEvent.click(cancel);
+ await waitFor(() => expect(cancelExportNative).toHaveBeenCalledWith(id));
+ expect(cancel).toBeDisabled();
+ await act(async () =>
+ job.reject(
+ new NativeBridgeRequestError({
+ code: "CANCELLED",
+ message: "cancelled",
+ retryable: false,
+ }),
+ ),
+ );
+ expect(screen.getByRole("button", { name: "Export MP4" })).toBeEnabled();
+ expect(onClose).not.toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it("goes back to the progress when native refuses the cancel", async () => {
+ // An addon built before MP4 cancellation refuses every cancel; the export runs on.
+ vi.mocked(cancelExportNative).mockResolvedValue({ accepted: false });
+ const job = pendingMp4Export();
+ const id = await startMp4();
+ const cancel = screen.getByRole("button", { name: "Cancel" });
+ fireEvent.click(cancel);
+ await waitFor(() => expect(cancelExportNative).toHaveBeenCalledWith(id));
+ await waitFor(() => expect(cancel).toBeEnabled());
+ // 10 s at the default 60 fps: 60 frames is 10%.
+ act(() => progress(60, id));
+ expect(screen.getByText("10%")).toBeVisible();
+ await act(async () => job.resolve(STATS));
+ expect(screen.getByText("/tmp/result.gif")).toBeVisible();
+ expect(toast.success).toHaveBeenCalledOnce();
+ });
+
it("reports success when native publication wins the race", async () => {
- vi.mocked(cancelGifExportNative).mockResolvedValue({ accepted: false });
+ vi.mocked(cancelExportNative).mockResolvedValue({ accepted: false });
const job = pendingExport();
await start();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
@@ -221,7 +285,7 @@ describe("GIF export cancellation", () => {
const job = pendingExport();
const { id, unmount } = await start();
unmount();
- expect(cancelGifExportNative).toHaveBeenCalledWith(id);
+ expect(cancelExportNative).toHaveBeenCalledWith(id);
await act(async () => job.resolve(STATS));
expect(toast.success).not.toHaveBeenCalled();
expect(toast.error).not.toHaveBeenCalled();
diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsx
index 47b08b08a..195cb22bf 100644
--- a/src/components/ai-edition/ExportDialog.tsx
+++ b/src/components/ai-edition/ExportDialog.tsx
@@ -1,7 +1,7 @@
// Export dialog for the new editor. Wires together:
// 1. pickExportSavePath (native save dialog)
// 2. the native D3D exporter (exportMultiNative / exportGifNative)
-// 3. per-job GIF cancellation, with native cleanup before returning to options
+// 3. per-job cancellation (MP4 and GIF), with native cleanup before returning to options
//
// Format/quality/GIF options live in the dialog's local state. The
// dialog uses the new shell's modal style.
@@ -33,7 +33,7 @@ import {
import { calculateMp4ExportSettings, wouldUpscale } from "@/lib/exporter/mp4ExportSettings";
import { outputFrameCount } from "@/lib/exporter/outputFrameCount";
import {
- cancelGifExportNative,
+ cancelExportNative,
exportGifNative,
exportMultiNative,
useIsCpuCompositor,
@@ -48,7 +48,7 @@ import { Toggle } from "./RightPanes";
type Phase = "idle" | "configuring" | "rendering" | "writing" | "done" | "error";
interface ActiveExport {
- id?: string;
+ id: string;
cancelRequested: boolean;
unsubscribe?: () => void;
}
@@ -56,8 +56,8 @@ interface ActiveExport {
function disposeExport(exportJob: ActiveExport | null) {
exportJob?.unsubscribe?.();
if (exportJob?.id) {
- void cancelGifExportNative(exportJob.id).catch((error) => {
- console.warn("[export] failed to cancel detached GIF export", error);
+ void cancelExportNative(exportJob.id).catch((error) => {
+ console.warn("[export] failed to cancel detached export", error);
});
}
}
@@ -307,8 +307,14 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
job.cancelRequested = true;
setCancelPending(true);
try {
- await cancelGifExportNative(job.id);
- // Native settlement decides the winner and confirms file cleanup.
+ const { accepted } = await cancelExportNative(job.id);
+ // Native settlement decides the winner and confirms file cleanup. A refusal means the
+ // export finishes on its own (already publishing, or an addon too old to cancel an
+ // MP4), so the dialog goes back to showing its progress.
+ if (!accepted && activeExport.current === job) {
+ job.cancelRequested = false;
+ setCancelPending(false);
+ }
} catch (err) {
if (activeExport.current !== job) return;
job.cancelRequested = false;
@@ -367,10 +373,7 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
// as the live preview, so an export can no longer disagree with what the
// user previewed.
{
- const job: ActiveExport = {
- id: format === "gif" ? crypto.randomUUID() : undefined,
- cancelRequested: false,
- };
+ const job: ActiveExport = { id: crypto.randomUUID(), cancelRequested: false };
activeExport.current = job;
setPhase("rendering");
// Render the real timeline when there are clips; else fall back to the fixture.
@@ -428,16 +431,22 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
},
job.id,
)
- : await exportMultiNative(exportClips, pickedPath, sceneJson, {
- width: outDims?.width,
- height: outDims?.height,
- fps,
- // H.264 only. The native pipeline still encodes H.265, but nothing
- // offers it: it is software-only on Linux, slower than software on the
- // measured Macs, and the files half the players cannot open.
- codec: "h264",
- bitrate: outDims?.bitrate,
- });
+ : await exportMultiNative(
+ exportClips,
+ pickedPath,
+ sceneJson,
+ {
+ width: outDims?.width,
+ height: outDims?.height,
+ fps,
+ // H.264 only. The native pipeline still encodes H.265, but nothing
+ // offers it: it is software-only on Linux, slower than software on the
+ // measured Macs, and the files half the players cannot open.
+ codec: "h264",
+ bitrate: outDims?.bitrate,
+ },
+ job.id,
+ );
if (activeExport.current !== job) return;
setSavedPath(pickedPath);
setPhase("done");
@@ -698,7 +707,7 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
type="button"
className={`${styles.btn} ${styles.btnSecondary}`}
onClick={handleCancel}
- disabled={isBusy && !(format === "gif" && phase === "rendering" && !cancelPending)}
+ disabled={isBusy && !(phase === "rendering" && !cancelPending)}
aria-busy={cancelPending}
>
{cancelPending && <Loader2 size={14} className="animate-spin" />}
diff --git a/src/native/compositorViewClient.test.ts b/src/native/compositorViewClient.test.ts
index 15f3617f6..76cf5234b 100644
--- a/src/native/compositorViewClient.test.ts
+++ b/src/native/compositorViewClient.test.ts
@@ -1,11 +1,11 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { NativeBridgeRequestError } from "./client";
-import { cancelGifExportNative, exportGifNative } from "./compositorViewClient";
+import { cancelExportNative, exportGifNative, exportMultiNative } from "./compositorViewClient";
import type { NativeBridgeRequest } from "./contracts";
afterEach(() => vi.unstubAllGlobals());
-describe("GIF export bridge client", () => {
+describe("export bridge client", () => {
it("keeps the export ID independent from RPC IDs", async () => {
const invoke = vi.fn(async (_request: NativeBridgeRequest) => ({
ok: true,
@@ -13,7 +13,7 @@ describe("GIF export bridge client", () => {
}));
vi.stubGlobal("window", { electronAPI: { invokeNativeBridge: invoke } });
await exportGifNative([], "/tmp/test.gif", undefined, { fps: 15 }, "gif-1");
- await cancelGifExportNative("gif-1");
+ await cancelExportNative("gif-1");
expect(invoke.mock.calls).toHaveLength(2);
const first = invoke.mock.calls[0]?.[0];
expect(first?.requestId).not.toBe(invoke.mock.calls[1]?.[0].requestId);
@@ -24,7 +24,19 @@ describe("GIF export bridge client", () => {
}),
);
expect(invoke.mock.calls[1]?.[0]).toEqual(
- expect.objectContaining({ action: "cancelGifExport", payload: { exportId: "gif-1" } }),
+ expect.objectContaining({ action: "cancelExport", payload: { exportId: "gif-1" } }),
+ );
+ });
+
+ it("sends the MP4 export ID that a cancel names", async () => {
+ const invoke = vi.fn(async (_request: NativeBridgeRequest) => ({ ok: true, data: {} }));
+ vi.stubGlobal("window", { electronAPI: { invokeNativeBridge: invoke } });
+ await exportMultiNative([], "/tmp/test.mp4", undefined, { fps: 30 }, "mp4-1");
+ expect(invoke.mock.calls[0]?.[0]).toEqual(
+ expect.objectContaining({
+ action: "exportMulti",
+ payload: expect.objectContaining({ exportId: "mp4-1", params: { fps: 30 } }),
+ }),
);
});
@@ -33,14 +45,17 @@ describe("GIF export bridge client", () => {
electronAPI: {
invokeNativeBridge: vi.fn(async () => ({
ok: false,
- error: { code: "CANCELLED", message: "GIF export cancelled.", retryable: false },
+ error: { code: "CANCELLED", message: "Export cancelled.", retryable: false },
})),
},
});
- const error = await exportGifNative([], "/tmp/test.gif", undefined, undefined, "gif-2").catch(
- (e: unknown) => e,
- );
- expect(error).toBeInstanceOf(NativeBridgeRequestError);
- expect(error).toMatchObject({ code: "CANCELLED", message: "GIF export cancelled." });
+ for (const run of [
+ () => exportGifNative([], "/tmp/test.gif", undefined, undefined, "gif-2"),
+ () => exportMultiNative([], "/tmp/test.mp4", undefined, undefined, "mp4-2"),
+ ]) {
+ const error = await run().catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(NativeBridgeRequestError);
+ expect(error).toMatchObject({ code: "CANCELLED", message: "Export cancelled." });
+ }
});
});
diff --git a/src/native/compositorViewClient.ts b/src/native/compositorViewClient.ts
index 66f63ce56..131d8909c 100644
--- a/src/native/compositorViewClient.ts
+++ b/src/native/compositorViewClient.ts
@@ -196,11 +196,12 @@ export function exportMultiNative(
outPath?: string,
sceneJson?: string,
params?: CompositorExportParams,
+ exportId?: string,
): Promise<CompositorExportResult> {
return requireNativeBridgeData<CompositorExportResult>({
domain: "compositor",
action: "exportMulti",
- payload: { clips, outPath, sceneJson, params },
+ payload: { clips, outPath, sceneJson, params, exportId },
});
}
@@ -220,10 +221,12 @@ export function exportGifNative(
});
}
-export function cancelGifExportNative(exportId: string): Promise<{ accepted: boolean }> {
+/** Cancels the MP4 or GIF export started with `exportId`. `accepted: false` means it finishes on
+ * its own: it was already being published, or the addon cannot cancel it. */
+export function cancelExportNative(exportId: string): Promise<{ accepted: boolean }> {
return requireNativeBridgeData<{ accepted: boolean }>({
domain: "compositor",
- action: "cancelGifExport",
+ action: "cancelExport",
payload: { exportId },
});
}
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index 5421b994a..cc76bb59b 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -875,6 +875,7 @@ export type NativeBridgeRequest =
domain: "compositor";
action: "exportMulti";
payload: {
+ exportId?: string;
clips: CompositorClipInput[];
outPath?: string;
sceneJson?: string;
@@ -927,7 +928,8 @@ export type NativeBridgeRequest =
}
| {
domain: "compositor";
- action: "cancelGifExport";
+ /** Either format: the export ID names the job, MP4 or GIF. */
+ action: "cancelExport";
payload: { exportId: string };
requestId?: string;
}