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(cli): address CodeRabbit review on #176

PeterTakahashi06dcd6ef24b8
diff --git a/docs/cli.md b/docs/cli.md
index 8ebb31080..f546442d4 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -4,7 +4,7 @@ Headless command-line interface for recording the screen and exporting `.openscr
projects — no visible windows, machine-readable output. Designed so scripts, CI
pipelines, and AI coding agents can produce polished product demos automatically:
-```
+```text
record → edit the project JSON programmatically → export → MP4/GIF
```
@@ -102,6 +102,8 @@ openscreen export demo.openscreen --json | while read line; do ...; done
`--audio` re-muxes after the render: video packets are copied untouched, and the
audio is mixed offline (OfflineAudioContext) and re-encoded to AAC. MP4 only.
+In `mix` mode the original audio is ducked to 40% under the voiceover so the
+sum cannot clip; use `replace` to drop the original entirely.
**Media path rule**: for safety, a project's referenced media is only auto-approved
when it lives in the app's recordings directory or **next to the project file**.
diff --git a/electron/cli/args.test.ts b/electron/cli/args.test.ts
index bf3bab8a7..f8886bf7e 100644
--- a/electron/cli/args.test.ts
+++ b/electron/cli/args.test.ts
@@ -1,7 +1,9 @@
+import path from "node:path";
import { describe, expect, it } from "vitest";
import { parseCliArgs } from "./args";
-const CWD = "/work";
+const CWD = path.resolve("/work");
+const inCwd = (name: string) => path.resolve(CWD, name);
function parse(args: string[]) {
return parseCliArgs(["electron", "app-path", ...args], 2, CWD);
@@ -16,7 +18,7 @@ describe("parseCliArgs", () => {
it("skips leading Chromium switches before the subcommand (AppImage --no-sandbox)", () => {
expect(parse(["--no-sandbox", "export", "demo.openscreen"])).toMatchObject({
kind: "export",
- projectPath: "/work/demo.openscreen",
+ projectPath: inCwd("demo.openscreen"),
});
expect(parse(["--no-sandbox", "--enable-unsafe-swiftshader", "record"])).toMatchObject({
kind: "record",
@@ -29,7 +31,7 @@ describe("parseCliArgs", () => {
const cmd = parse(["export", "demo.openscreen"]);
expect(cmd).toMatchObject({
kind: "export",
- projectPath: "/work/demo.openscreen",
+ projectPath: inCwd("demo.openscreen"),
outPath: null,
format: null,
});
@@ -49,7 +51,7 @@ describe("parseCliArgs", () => {
]);
expect(cmd).toMatchObject({
kind: "export",
- outPath: "/work/out.gif",
+ outPath: inCwd("out.gif"),
format: "gif",
gifFrameRate: 20,
previewWidth: 1600,
@@ -80,7 +82,7 @@ describe("parseCliArgs", () => {
]);
expect(cmd).toMatchObject({
kind: "export",
- audioPath: "/work/voice.mp3",
+ audioPath: inCwd("voice.mp3"),
audioMode: "replace",
audioOffsetSec: 1.5,
});
@@ -131,7 +133,7 @@ describe("parseCliArgs", () => {
micDevice: "MacBook",
systemAudio: true,
durationMs: 12500,
- projectOut: "/work/demo.openscreen",
+ projectOut: inCwd("demo.openscreen"),
});
});
@@ -144,7 +146,7 @@ describe("parseCliArgs", () => {
it("parses info and help", () => {
expect(parse(["info", "demo.openscreen", "--json"])).toMatchObject({
kind: "info",
- projectPath: "/work/demo.openscreen",
+ projectPath: inCwd("demo.openscreen"),
json: true,
});
expect(parse(["help"])).toMatchObject({ kind: "help" });
diff --git a/electron/cli/args.ts b/electron/cli/args.ts
index 0ed95c858..69578198b 100644
--- a/electron/cli/args.ts
+++ b/electron/cli/args.ts
@@ -184,8 +184,13 @@ function parseExport(args: string[], cwd: string): CliCommand {
const [value, next] = takeValue(args, i, arg);
const match = /^(\d+)x(\d+)$/.exec(value);
if (!match) throw new Error(`--preview-size must look like 1280x720, got "${value}"`);
- request.previewWidth = Number(match[1]);
- request.previewHeight = Number(match[2]);
+ const previewWidth = Number(match[1]);
+ const previewHeight = Number(match[2]);
+ if (previewWidth <= 0 || previewHeight <= 0) {
+ throw new Error(`--preview-size dimensions must be positive, got "${value}"`);
+ }
+ request.previewWidth = previewWidth;
+ request.previewHeight = previewHeight;
i = next;
break;
}
diff --git a/electron/cli/cliMain.ts b/electron/cli/cliMain.ts
index ed3d487fb..02fe23585 100644
--- a/electron/cli/cliMain.ts
+++ b/electron/cli/cliMain.ts
@@ -210,9 +210,10 @@ async function runInfoCommand(projectPath: string, json: boolean): Promise<numbe
};
if (json) {
- process.stdout.write(`${JSON.stringify(summary)}\n`);
+ safeWrite(process.stdout, `${JSON.stringify(summary)}\n`);
} else {
- process.stdout.write(
+ safeWrite(
+ process.stdout,
[
`Project: ${summary.projectPath} (version ${summary.version ?? "?"})`,
`Video: ${summary.screenVideoPath ?? "(none)"}${mediaExists ? "" : " [MISSING]"}`,
@@ -242,12 +243,17 @@ export function runCli(command: CliCommand): void {
// stdout belongs to the CLI protocol (NDJSON / progress); reroute the app's
// own console chatter (e.g. "[native-sck] starting…") to stderr.
+ const stringifyArg = (value: unknown): string => {
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value) ?? String(value);
+ } catch {
+ return String(value);
+ }
+ };
for (const level of ["log", "info", "warn", "error", "debug"] as const) {
console[level] = (...args: unknown[]) => {
- safeWrite(
- process.stderr,
- `${args.map((a) => (typeof a === "string" ? a : JSON.stringify(a))).join(" ")}\n`,
- );
+ safeWrite(process.stderr, `${args.map(stringifyArg).join(" ")}\n`);
};
}
@@ -271,6 +277,10 @@ export function runCli(command: CliCommand): void {
app.exit(1);
});
+ // Set once cli-done has been received; suppresses the window-all-closed
+ // failure path during the normal teardown race after a successful run.
+ let finished = false;
+
// GPU may be unavailable in CI/servers; let Chromium fall back to SwiftShader
// so the WebGL-based export renderer still works.
app.commandLine.appendSwitch("enable-unsafe-swiftshader");
@@ -281,7 +291,9 @@ export function runCli(command: CliCommand): void {
}
app.on("window-all-closed", () => {
- // Completion is signalled via cli-done; a vanished window is a failure.
+ // Completion is signalled via cli-done; a vanished window is a failure
+ // only while the run is still in flight.
+ if (finished) return;
output.error("Renderer window closed unexpectedly");
app.exit(1);
});
@@ -365,7 +377,6 @@ export function runCli(command: CliCommand): void {
output.progress(progress);
});
- let finished = false;
ipcMain.handle("cli-done", async (_event, result: CliDoneResult) => {
if (finished) return;
finished = true;
diff --git a/electron/preload.ts b/electron/preload.ts
index bc1ac803e..6aa0a886c 100644
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@ -430,16 +430,16 @@ contextBridge.exposeInMainWorld("electronAPI", {
},
},
// --- CLI mode (hidden runner windows; see electron/cli/) ---
- cliGetRequest: () => {
+ cliGetRequest: (): Promise<import("../src/lib/cliContracts").CliRequest> => {
return ipcRenderer.invoke("cli-get-request");
},
- cliProgress: (progress: unknown) => {
+ cliProgress: (progress: import("../src/lib/cliContracts").CliProgressEvent) => {
ipcRenderer.send("cli-progress", progress);
},
cliLog: (level: "info" | "error", message: string) => {
ipcRenderer.send("cli-log", level, message);
},
- cliDone: (result: unknown) => {
+ cliDone: (result: import("../src/lib/cliContracts").CliDoneResult) => {
return ipcRenderer.invoke("cli-done", result);
},
onCliStopRecording: (callback: () => void) => {
diff --git a/src/cli/CliExportRunner.tsx b/src/cli/CliExportRunner.tsx
index b8b0ea51c..56f60581e 100644
--- a/src/cli/CliExportRunner.tsx
+++ b/src/cli/CliExportRunner.tsx
@@ -44,14 +44,26 @@ function probeVideoDimensions(url: string): Promise<{ width: number; height: num
const video = document.createElement("video");
video.preload = "metadata";
video.muted = true;
+ const cleanup = () => {
+ clearTimeout(timer);
+ video.removeAttribute("src");
+ video.load();
+ };
+ // A stalled load fires neither event; without a deadline the CLI hangs.
+ const timer = setTimeout(() => {
+ cleanup();
+ reject(new Error(`Timed out reading video metadata: ${url}`));
+ }, 30_000);
video.onloadedmetadata = () => {
const width = video.videoWidth;
const height = video.videoHeight;
- video.removeAttribute("src");
- video.load();
+ cleanup();
resolve({ width, height });
};
- video.onerror = () => reject(new Error(`Failed to load video metadata: ${url}`));
+ video.onerror = () => {
+ cleanup();
+ reject(new Error(`Failed to load video metadata: ${url}`));
+ };
video.src = url;
});
}
diff --git a/src/cli/CliRecordRunner.tsx b/src/cli/CliRecordRunner.tsx
index 7bf6c7afd..e19c451f9 100644
--- a/src/cli/CliRecordRunner.tsx
+++ b/src/cli/CliRecordRunner.tsx
@@ -105,6 +105,9 @@ export function CliRecordRunner() {
const [requestReady, setRequestReady] = useState<CliRecordRequest | null>(null);
const phaseRef = useRef<Phase>("init");
const recordingStartedAtRef = useRef<number | null>(null);
+ // A stop (SIGINT/stdin) can land while the capture helper is still starting;
+ // remember it and apply as soon as recording flips on.
+ const stopRequestedRef = useRef(false);
const [status, setStatus] = useState("Preparing recording…");
const {
@@ -121,9 +124,11 @@ export function CliRecordRunner() {
// Keep latest values in refs for the stop/finish effects.
const toggleRecordingRef = useRef(toggleRecording);
- toggleRecordingRef.current = toggleRecording;
const recordingRef = useRef(recording);
- recordingRef.current = recording;
+ useEffect(() => {
+ toggleRecordingRef.current = toggleRecording;
+ recordingRef.current = recording;
+ });
const fail = async (error: unknown) => {
phaseRef.current = "done";
@@ -190,6 +195,18 @@ export function CliRecordRunner() {
void (async () => {
try {
await startRecordingImmediately();
+ // The hook reports start failures via toast/console, not by
+ // rejecting — without a deadline a failed start would hang the
+ // CLI forever.
+ setTimeout(() => {
+ if (recordingStartedAtRef.current === null && phaseRef.current === "recording") {
+ void fail(
+ new Error(
+ "Recording did not start within 30s — see stderr for the underlying capture error",
+ ),
+ );
+ }
+ }, 30_000);
} catch (error) {
await fail(error);
}
@@ -209,6 +226,13 @@ export function CliRecordRunner() {
setStatus("Recording…");
window.electronAPI.cliLog("info", "Recording started");
+ if (stopRequestedRef.current) {
+ phaseRef.current = "stopping";
+ setStatus("Stopping…");
+ toggleRecordingRef.current();
+ return;
+ }
+
if (request?.durationMs) {
const timer = setTimeout(() => {
if (recordingRef.current && phaseRef.current === "recording") {
@@ -229,6 +253,9 @@ export function CliRecordRunner() {
phaseRef.current = "stopping";
setStatus("Stopping…");
toggleRecordingRef.current();
+ } else {
+ // Capture is still starting; stop as soon as it comes up.
+ stopRequestedRef.current = true;
}
});
}, []);
diff --git a/src/lib/exporter/voiceoverMix.ts b/src/lib/exporter/voiceoverMix.ts
index 269410537..0c6305627 100644
--- a/src/lib/exporter/voiceoverMix.ts
+++ b/src/lib/exporter/voiceoverMix.ts
@@ -20,7 +20,7 @@ import {
export type VoiceoverMixMode = "mix" | "replace";
export interface VoiceoverMixOptions {
- /** Encoded audio file bytes (mp3/wav/m4a/aiff — anything decodeAudioData accepts). */
+ /** Encoded audio file bytes (mp3/wav/m4a — anything decodeAudioData accepts). */
voiceoverData: ArrayBuffer;
mode: VoiceoverMixMode;
/** Delay before the voiceover starts, in seconds. */
@@ -29,6 +29,10 @@ export interface VoiceoverMixOptions {
originalGain?: number;
}
+// Duck the original bed under the voiceover by default so the unity-gain sum
+// of two loud sources doesn't hard-clip.
+const DEFAULT_ORIGINAL_GAIN = 0.4;
+
const OUTPUT_SAMPLE_RATE = 48_000;
const OUTPUT_CHANNELS = 2;
const VOICEOVER_AUDIO_BITRATE = 192_000;
@@ -43,7 +47,7 @@ async function decodeToBuffer(
/** Renders the final audio track: original bed (optional) + offset voiceover. */
async function renderMixedAudio(
- videoData: ArrayBuffer,
+ videoData: ArrayBuffer | null,
durationSec: number,
options: VoiceoverMixOptions,
): Promise<AudioBuffer> {
@@ -56,13 +60,13 @@ async function renderMixedAudio(
voiceoverNode.connect(context.destination);
voiceoverNode.start(Math.max(0, options.offsetSec));
- if (options.mode === "mix") {
+ if (options.mode === "mix" && videoData) {
try {
const original = await decodeToBuffer(context, videoData);
const originalNode = context.createBufferSource();
originalNode.buffer = original;
const gainNode = context.createGain();
- gainNode.gain.value = options.originalGain ?? 1;
+ gainNode.gain.value = options.originalGain ?? DEFAULT_ORIGINAL_GAIN;
originalNode.connect(gainNode);
gainNode.connect(context.destination);
originalNode.start(0);
@@ -99,7 +103,9 @@ export async function mixVoiceoverIntoVideo(
}
const durationSec = await input.computeDuration();
- const videoData = await videoBlob.arrayBuffer();
+ // The full-file bytes are only needed to decode the original bed in
+ // "mix" mode; "replace" skips the copy entirely.
+ const videoData = options.mode === "mix" ? await videoBlob.arrayBuffer() : null;
const mixedAudio = await renderMixedAudio(videoData, durationSec, options);
const target = new BufferTarget();
@@ -107,24 +113,29 @@ export async function mixVoiceoverIntoVideo(
format: new Mp4OutputFormat({ fastStart: "in-memory" }),
target,
});
- const videoSource = new EncodedVideoPacketSource(codec);
- output.addVideoTrack(videoSource);
- const audioSource = new AudioBufferSource({
- codec: "aac",
- bitrate: VOICEOVER_AUDIO_BITRATE,
- });
- output.addAudioTrack(audioSource);
- await output.start();
+ try {
+ const videoSource = new EncodedVideoPacketSource(codec);
+ output.addVideoTrack(videoSource);
+ const audioSource = new AudioBufferSource({
+ codec: "aac",
+ bitrate: VOICEOVER_AUDIO_BITRATE,
+ });
+ output.addAudioTrack(audioSource);
+ await output.start();
- const sink = new EncodedPacketSink(videoTrack);
- let isFirstPacket = true;
- for await (const packet of sink.packets()) {
- await videoSource.add(packet, isFirstPacket ? { decoderConfig } : undefined);
- isFirstPacket = false;
- }
- await audioSource.add(mixedAudio);
+ const sink = new EncodedPacketSink(videoTrack);
+ let isFirstPacket = true;
+ for await (const packet of sink.packets()) {
+ await videoSource.add(packet, isFirstPacket ? { decoderConfig } : undefined);
+ isFirstPacket = false;
+ }
+ await audioSource.add(mixedAudio);
- await output.finalize();
+ await output.finalize();
+ } catch (error) {
+ await output.cancel().catch(() => undefined);
+ throw error;
+ }
const buffer = target.buffer;
if (!buffer) {
throw new Error("Voiceover remux produced no output");