Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(cli): add auto-zoom, sources, pack and captions commands
PeterTakahashid53af7d82dc4
diff --git a/docs/cli.md b/docs/cli.mdindex f546442d4..046e5696d 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -74,6 +74,17 @@ Platform notes:which may show a system picker dialog and requires a desktop session(headless/SSH sessions without a portal cannot record).+### `openscreen sources`++Lists capturable displays, windows, and microphones — the same enumeration the+GUI picker uses — so scripts and agents can choose `--display`, `--window`, and+`--mic-device` values without guesswork.++```bash+openscreen sources # human-readable+openscreen sources --json # {"event":"done","sources":{displays,windows,microphones,...}}+```+### `openscreen export`Renders a project to MP4 or GIF using the app's real export pipeline (WebCodecs +@@ -95,6 +106,7 @@ openscreen export demo.openscreen --json | while read line; do ...; done| `--quality <medium\|good\|source>` | MP4 quality || `--gif-fps <15\|20\|25\|30>`, `--gif-size <medium\|large\|original>` | GIF settings || `--preview-size <WxH>` | Reference preview box (default `1280x720`), see below |+| `--auto-zoom` | Add automatic zooms from cursor telemetry before rendering — the same dwell-detection engine as the editor's magic wand. Existing zoom regions are kept; suggestions never overlap them || `--audio <file>` | Mix a voiceover file into the MP4 (mp3/wav/m4a — anything Chromium can decode; AIFF is not supported) || `--audio-mode <mix\|replace>` | Layer the voiceover over the recording's audio (default `mix`) or replace it || `--audio-offset <seconds>` | Delay before the voiceover starts (default 0) |@@ -117,6 +129,36 @@ deterministic reference box instead (the composition fitted into 1280×720).Authoring tip for scripts: treat annotation `fontSize` as "pixels in a1280-wide preview".+### `openscreen pack`++Copies a project and everything it references (screen/webcam video, cursor+telemetry sidecar) into one portable folder and rewrites the project's media+paths:++```bash+openscreen pack demo.openscreen --out bundle/+```++The folder survives being moved or shipped as a CI artifact: when the stored+absolute paths go stale, the loader falls back to files with the same basename+next to the project file.++### `openscreen captions`++Transcribes the project's audio with the app's on-device Whisper model (no+upload; language auto-detected) and writes the resulting caption annotations+into the project. Re-running replaces earlier auto-captions; manual annotations+are preserved.++```bash+openscreen captions demo.openscreen --min-words 2 --max-words 7+openscreen export demo.openscreen -o demo.mp4 # subtitles are burned in+```++Requires an audio track in the project's video (e.g. `record --mic`, or a+voiceover mixed in with a re-recorded source). Accuracy reflects the bundled+whisper-tiny model: strong for English, rough for other languages.+### `openscreen info`Prints a project summary (referenced media and whether it exists, format,@@ -163,8 +205,8 @@ node -e '# 3. Narrate with any TTS (macOS `say` shown; any engine producing mp3/wav/m4a works)say -o voice.m4a --file-format=m4af "Welcome to my product. Here's a quick tour."-# 4. Render with the voiceover mixed in-openscreen export demo.openscreen -o demo.mp4 --audio voice.m4a --audio-mode replace --json+# 4. Render with auto-zooms and the voiceover mixed in+openscreen export demo.openscreen -o demo.mp4 --auto-zoom --audio voice.m4a --audio-mode replace --json```## Architecturediff --git a/electron/cli/args.test.ts b/electron/cli/args.test.tsindex f8886bf7e..575e0f7c5 100644--- a/electron/cli/args.test.ts+++ b/electron/cli/args.test.ts@@ -143,6 +143,46 @@ describe("parseCliArgs", () => {expect(parse(["record", "--project", "demo.json"])).toMatchObject({ kind: "error" });});+ it("parses --auto-zoom", () => {+ expect(parse(["export", "a.openscreen", "--auto-zoom"])).toMatchObject({+ kind: "export",+ autoZoom: true,+ });+ expect(parse(["export", "a.openscreen"])).toMatchObject({ autoZoom: false });+ });++ it("parses sources", () => {+ expect(parse(["sources", "--json"])).toMatchObject({ kind: "sources", json: true });+ expect(parse(["sources", "--bogus"])).toMatchObject({ kind: "error" });+ });++ it("parses pack", () => {+ expect(parse(["pack", "demo.openscreen", "--out", "bundle"])).toMatchObject({+ kind: "pack",+ projectPath: inCwd("demo.openscreen"),+ outDir: inCwd("bundle"),+ });+ expect(parse(["pack", "demo.openscreen"])).toMatchObject({ kind: "error" });+ });++ it("parses captions", () => {+ expect(+ parse(["captions", "demo.openscreen", "--min-words", "1", "--max-words", "5"]),+ ).toMatchObject({+ kind: "captions",+ projectPath: inCwd("demo.openscreen"),+ minWordsPerCaption: 1,+ maxWordsPerCaption: 5,+ });+ expect(parse(["captions", "demo.openscreen"])).toMatchObject({+ minWordsPerCaption: 2,+ maxWordsPerCaption: 7,+ });+ expect(+ parse(["captions", "a.openscreen", "--min-words", "9", "--max-words", "3"]),+ ).toMatchObject({ kind: "error" });+ });+it("parses info and help", () => {expect(parse(["info", "demo.openscreen", "--json"])).toMatchObject({kind: "info",diff --git a/electron/cli/args.ts b/electron/cli/args.tsindex 69578198b..a14d74b06 100644--- a/electron/cli/args.ts+++ b/electron/cli/args.ts@@ -18,18 +18,38 @@ export interface CliErrorCommand {message: string;}-export type CliCommand = (CliRequest | CliInfoCommand | CliHelpCommand | CliErrorCommand) & {+export type CliCommand = (+ | CliRequest+ | CliInfoCommand+ | CliPackCommand+ | CliHelpCommand+ | CliErrorCommand+) & {/** Machine-readable NDJSON output on stdout instead of human progress. */json?: boolean;};-const SUBCOMMANDS = new Set(["export", "record", "info", "help", "--help", "-h"]);+const SUBCOMMANDS = new Set([+ "export",+ "record",+ "sources",+ "pack",+ "captions",+ "info",+ "help",+ "--help",+ "-h",+]);export const CLI_USAGE = `OpenScreen CLIUsage:openscreen export <project.openscreen> [options] Render a project to MP4/GIFopenscreen record [options] Record the screen headlessly+ openscreen sources [--json] List displays, windows and microphones+ openscreen pack <project.openscreen> --out <dir> Copy project + media into one portable folder+ openscreen captions <project.openscreen> Add auto-captions (on-device Whisper) to a project+ [--min-words <n>] [--max-words <n>]openscreen info <project.openscreen> [--json] Inspect a project fileopenscreen help Show this help@@ -42,6 +62,7 @@ Export options:--gif-size <medium|large|original>GIF size preset (default: from project)--preview-size <WxH> Reference preview box for annotation scaling (default 1280x720)+ --auto-zoom Add automatic zooms from cursor telemetry (editor's magic wand)--audio <file> Mix a voiceover audio file into the MP4 (mp3/wav/m4a)--audio-mode <mix|replace>Layer over the recording's audio (default) or replace it@@ -111,6 +132,9 @@ export function parseCliArgs(try {if (sub === "export") return parseExport(args.slice(1), cwd);if (sub === "record") return parseRecord(args.slice(1), cwd);+ if (sub === "sources") return parseSources(args.slice(1));+ if (sub === "pack") return parsePack(args.slice(1), cwd);+ if (sub === "captions") return parseCaptions(args.slice(1), cwd);return parseInfo(args.slice(1), cwd);} catch (error) {return { kind: "error", message: error instanceof Error ? error.message : String(error) };@@ -128,6 +152,7 @@ function parseExport(args: string[], cwd: string): CliCommand {gifSizePreset: null,previewWidth: null,previewHeight: null,+ autoZoom: false,audioPath: null,audioMode: "mix",audioOffsetSec: 0,@@ -194,6 +219,9 @@ function parseExport(args: string[], cwd: string): CliCommand {i = next;break;}+ case "--auto-zoom":+ request.autoZoom = true;+ break;case "--audio": {const [value, next] = takeValue(args, i, arg);request.audioPath = resolvePath(value, cwd);@@ -332,6 +360,82 @@ function parseRecord(args: string[], cwd: string): CliCommand {return request;}+function parseSources(args: string[]): CliCommand {+ let json = false;+ for (const arg of args) {+ if (arg === "--json") {+ json = true;+ } else {+ throw new Error(`Unknown sources option: ${arg}`);+ }+ }+ return { kind: "sources", json };+}++export interface CliPackCommand {+ kind: "pack";+ projectPath: string;+ outDir: string;+}++function parsePack(args: string[], cwd: string): CliCommand {+ let projectPath = "";+ let outDir = "";+ let json = false;+ for (let i = 0; i < args.length; i++) {+ const arg = args[i];+ if (arg === "-o" || arg === "--out") {+ const [value, next] = takeValue(args, i, arg);+ outDir = resolvePath(value, cwd);+ i = next;+ } else if (arg === "--json") {+ json = true;+ } else if (arg.startsWith("-")) {+ throw new Error(`Unknown pack option: ${arg}`);+ } else if (projectPath) {+ throw new Error(`Unexpected extra argument: ${arg}`);+ } else {+ projectPath = resolvePath(arg, cwd);+ }+ }+ if (!projectPath) throw new Error("pack requires a <project.openscreen> path");+ if (!outDir) throw new Error("pack requires --out <directory>");+ return { kind: "pack", projectPath, outDir, json };+}++function parseCaptions(args: string[], cwd: string): CliCommand {+ let projectPath = "";+ let minWordsPerCaption = 2;+ let maxWordsPerCaption = 7;+ let json = false;+ for (let i = 0; i < args.length; i++) {+ const arg = args[i];+ if (arg === "--min-words" || arg === "--max-words") {+ const [value, next] = takeValue(args, i, arg);+ const count = Number(value);+ if (!Number.isInteger(count) || count < 1) {+ throw new Error(`${arg} must be a positive integer, got "${value}"`);+ }+ if (arg === "--min-words") minWordsPerCaption = count;+ else maxWordsPerCaption = count;+ i = next;+ } else if (arg === "--json") {+ json = true;+ } else if (arg.startsWith("-")) {+ throw new Error(`Unknown captions option: ${arg}`);+ } else if (projectPath) {+ throw new Error(`Unexpected extra argument: ${arg}`);+ } else {+ projectPath = resolvePath(arg, cwd);+ }+ }+ if (!projectPath) throw new Error("captions requires a <project.openscreen> path");+ if (minWordsPerCaption > maxWordsPerCaption) {+ throw new Error("--min-words cannot exceed --max-words");+ }+ return { kind: "captions", projectPath, minWordsPerCaption, maxWordsPerCaption, json };+}+function parseInfo(args: string[], cwd: string): CliCommand {let projectPath = "";let json = false;diff --git a/electron/cli/cliMain.ts b/electron/cli/cliMain.tsindex 02fe23585..dbf8035ab 100644--- a/electron/cli/cliMain.ts+++ b/electron/cli/cliMain.ts@@ -7,7 +7,12 @@ import path from "node:path";import readline from "node:readline";import { fileURLToPath } from "node:url";import { app, BrowserWindow, ipcMain, session, systemPreferences } from "electron";-import type { CliDoneResult, CliProgressEvent, CliRequest } from "../../src/lib/cliContracts";+import type {+ CliDoneResult,+ CliProgressEvent,+ CliRequest,+ CliSourcesResult,+} from "../../src/lib/cliContracts";import { getSelectedDesktopSource, registerIpcHandlers } from "../ipc/handlers";import { ASSET_BASE_URL_ARG } from "../windows";import { CLI_USAGE, type CliCommand } from "./args";@@ -145,6 +150,35 @@ function registerAppHandlersForCli(cliWindowRef: () => BrowserWindow | null) {);}+function printSources(output: CliOutput, sources: CliSourcesResult): void {+ if (output.json) {+ // The "done" event already carries the payload; nothing extra to print.+ return;+ }+ const lines: string[] = [];+ lines.push("Displays:");+ for (const display of sources.displays) {+ lines.push(` ${display.index} ${display.name} (${display.id})`);+ }+ lines.push("Windows:");+ if (sources.windows.length === 0) {+ lines.push(" (none)");+ }+ for (const win of sources.windows) {+ lines.push(` - ${win.name}`);+ }+ lines.push("Microphones:");+ if (sources.microphoneLabelsUnavailable) {+ lines.push(" (labels unavailable — grant microphone permission to see device names)");+ } else if (sources.microphones.length === 0) {+ lines.push(" (none)");+ }+ for (const mic of sources.microphones) {+ lines.push(` - ${mic.label}`);+ }+ output.info(lines.join("\n"));+}+async function writeProjectFile(projectOut: string, projectData: unknown): Promise<void> {await fs.mkdir(path.dirname(projectOut), { recursive: true });await fs.writeFile(projectOut, JSON.stringify(projectData, null, 2), "utf8");@@ -174,6 +208,111 @@ function setupRecordStopSignals(stop: (reason: string) => void): void {}}+interface PackedProjectData {+ version?: number;+ media?: { screenVideoPath?: string; webcamVideoPath?: string; cursorCaptureMode?: string };+ videoPath?: string;+ editor?: Record<string, unknown>;+}++/** Copies a project and everything it references into one portable folder. */+async function runPackCommand(projectPath: string, outDir: string, json: boolean): Promise<number> {+ const emit = (message: string) => {+ if (!json) safeWrite(process.stdout, `${message}\n`);+ };++ const raw = await fs.readFile(projectPath, "utf8");+ const data = JSON.parse(raw) as PackedProjectData;+ const media = data.media ?? (data.videoPath ? { screenVideoPath: data.videoPath } : undefined);+ const screenVideoPath = media?.screenVideoPath;+ if (!screenVideoPath) {+ throw new Error("Project file does not reference a screen video");+ }++ const projectDir = path.dirname(path.resolve(projectPath));+ const resolveSource = async (mediaPath: string): Promise<string> => {+ const exists = await fs+ .stat(mediaPath)+ .then((stats) => stats.isFile())+ .catch(() => false);+ if (exists) return mediaPath;+ const sibling = path.join(projectDir, path.basename(mediaPath));+ const siblingExists = await fs+ .stat(sibling)+ .then((stats) => stats.isFile())+ .catch(() => false);+ if (siblingExists) return sibling;+ throw new Error(`Referenced media not found: ${mediaPath}`);+ };++ await fs.mkdir(outDir, { recursive: true });++ const copied: string[] = [];+ const copyIn = async (sourcePath: string): Promise<string> => {+ const destination = path.join(outDir, path.basename(sourcePath));+ if (path.resolve(sourcePath) !== path.resolve(destination)) {+ await fs.copyFile(sourcePath, destination);+ }+ copied.push(destination);+ return destination;+ };++ const screenSource = await resolveSource(screenVideoPath);+ const newScreenPath = await copyIn(screenSource);++ let newWebcamPath: string | undefined;+ if (media.webcamVideoPath) {+ newWebcamPath = await copyIn(await resolveSource(media.webcamVideoPath));+ }++ // Cursor telemetry sidecar sits at "<video path>.cursor.json".+ const cursorSidecar = `${screenSource}.cursor.json`;+ const hasCursorData = await fs+ .stat(cursorSidecar)+ .then((stats) => stats.isFile())+ .catch(() => false);+ if (hasCursorData) {+ await copyIn(cursorSidecar);+ }++ const packedProject: PackedProjectData = {+ ...data,+ media: {+ ...media,+ screenVideoPath: newScreenPath,+ ...(newWebcamPath ? { webcamVideoPath: newWebcamPath } : {}),+ },+ };+ delete packedProject.videoPath;+ const packedProjectPath = path.join(outDir, path.basename(projectPath));+ await fs.writeFile(packedProjectPath, JSON.stringify(packedProject, null, 2), "utf8");++ if (json) {+ safeWrite(+ process.stdout,+ `${JSON.stringify({+ event: "done",+ success: true,+ projectPath: packedProjectPath,+ files: [packedProjectPath, ...copied],+ cursorData: hasCursorData,+ })}\n`,+ );+ } else {+ emit(`Packed project → ${packedProjectPath}`);+ for (const file of copied) {+ emit(` + ${path.basename(file)}`);+ }+ if (!hasCursorData) {+ emit(" (no cursor telemetry sidecar found)");+ }+ emit(+ "The folder is self-contained: if the stored paths go stale after moving it, the loader falls back to files next to the project.",+ );+ }+ return 0;+}+async function runInfoCommand(projectPath: string, json: boolean): Promise<number> {const raw = await fs.readFile(projectPath, "utf8");const data = JSON.parse(raw) as {@@ -245,6 +384,7 @@ export function runCli(command: CliCommand): void {// own console chatter (e.g. "[native-sck] starting…") to stderr.const stringifyArg = (value: unknown): string => {if (typeof value === "string") return value;+ if (value instanceof Error) return value.stack ?? value.message;try {return JSON.stringify(value) ?? String(value);} catch {@@ -307,6 +447,16 @@ export function runCli(command: CliCommand): void {return;}+ if (command.kind === "pack") {+ const code = await runPackCommand(+ command.projectPath,+ command.outDir,+ command.json === true,+ );+ app.exit(code);+ return;+ }+await fs.mkdir(path.join(app.getPath("userData"), "recordings"), { recursive: true });// Media/screen permissions for the renderer (mic metering, future browser@@ -388,9 +538,12 @@ export function runCli(command: CliCommand): void {result.projectPath = command.projectOut;}}+ if (result.success && command.kind === "captions" && result.projectData !== undefined) {+ await writeProjectFile(command.projectPath, result.projectData);+ }} catch (error) {result.success = false;- result.error = `Recording succeeded but writing the project file failed: ${String(error)}`;+ result.error = `Run succeeded but writing the project file failed: ${String(error)}`;}if (result.success) {@@ -398,7 +551,13 @@ export function runCli(command: CliCommand): void {output.info(`Warning: ${warning}`);output.event("warning", { message: warning });}- if (command.kind === "export") {+ if (command.kind === "sources" && result.sources) {+ printSources(output, result.sources);+ } else if (command.kind === "captions") {+ output.info(+ `Added ${result.captionCount ?? 0} caption annotation(s) → ${result.projectPath}`,+ );+ } else if (command.kind === "export") {output.info(`Exported ${result.format ?? ""} → ${result.outputPath}`);} else {output.info(`Recording saved → ${result.screenVideoPath}`);@@ -424,7 +583,12 @@ export function runCli(command: CliCommand): void {setupRecordStopSignals(stop);}- const windowType = command.kind === "export" ? "cli-export" : "cli-record";+ const windowType = {+ export: "cli-export",+ record: "cli-record",+ sources: "cli-sources",+ captions: "cli-captions",+ }[command.kind];cliWindow = loadRunnerWindow(windowType);// Surface renderer console errors/warnings on stderr — the hidden windowdiff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex 5e0c3af82..4baa9ee8f 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -378,13 +378,40 @@ async function getApprovedProjectSession(trustedDirs.push(path.dirname(path.resolve(projectFilePath)));}- const screenVideoPath = await approveReadableVideoPath(media.screenVideoPath, trustedDirs);+ // Packed/portable projects: when the stored absolute path no longer exists+ // (project moved to another machine or directory), fall back to a file with+ // the same basename next to the project file (see `openscreen pack`).+ const resolveWithSiblingFallback = async (mediaPath: string): Promise<string> => {+ if (!projectFilePath) return mediaPath;+ const exists = await fs+ .stat(mediaPath)+ .then((stats) => stats.isFile())+ .catch(() => false);+ if (exists) return mediaPath;+ const sibling = path.join(+ path.dirname(path.resolve(projectFilePath)),+ path.basename(mediaPath),+ );+ const siblingExists = await fs+ .stat(sibling)+ .then((stats) => stats.isFile())+ .catch(() => false);+ return siblingExists ? sibling : mediaPath;+ };++ const screenVideoPath = await approveReadableVideoPath(+ await resolveWithSiblingFallback(media.screenVideoPath),+ trustedDirs,+ );if (!screenVideoPath) {throw new Error("Project references an invalid or unsupported screen video path");}const webcamVideoPath = media.webcamVideoPath- ? await approveReadableVideoPath(media.webcamVideoPath, trustedDirs)+ ? await approveReadableVideoPath(+ await resolveWithSiblingFallback(media.webcamVideoPath),+ trustedDirs,+ ): undefined;if (media.webcamVideoPath && !webcamVideoPath) {throw new Error("Project references an invalid or unsupported webcam video path");diff --git a/src/App.tsx b/src/App.tsxindex 8bbed307e..53d52c742 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -22,6 +22,8 @@ const VideoEditorEntry = lazy(() =>);const CliExportRunner = lazy(() => import("./cli/CliExportRunner"));const CliRecordRunner = lazy(() => import("./cli/CliRecordRunner"));+const CliSourcesRunner = lazy(() => import("./cli/CliSourcesRunner"));+const CliCaptionsRunner = lazy(() => import("./cli/CliCaptionsRunner"));const ShortcutsConfigDialog = lazy(() =>import("./components/video-editor/ShortcutsConfigDialog").then((module) => ({default: module.ShortcutsConfigDialog,@@ -90,6 +92,18 @@ export default function App() {<CliRecordRunner /></Suspense>);+ case "cli-sources":+ return (+ <Suspense fallback={null}>+ <CliSourcesRunner />+ </Suspense>+ );+ case "cli-captions":+ return (+ <Suspense fallback={null}>+ <CliCaptionsRunner />+ </Suspense>+ );case "editor":return (<ShortcutsProvider>diff --git a/src/cli/CliCaptionsRunner.tsx b/src/cli/CliCaptionsRunner.tsxnew file mode 100644index 000000000..32d01ca11--- /dev/null+++ b/src/cli/CliCaptionsRunner.tsx@@ -0,0 +1,168 @@+// Hidden-window runner for `openscreen captions`: transcribes the project's+// audio with the on-device Whisper worker and writes the resulting caption+// annotations back into the project. Mirrors VideoEditor.generateAutoCaptions.++import { useEffect, useRef, useState } from "react";+import {+ normalizeProjectEditor,+ resolveProjectMedia,+ toFileUrl,+ validateProjectData,+} from "@/components/video-editor/projectPersistence";+import type { AnnotationRegion, TrimRegion } from "@/components/video-editor/types";+import { captionSegmentsToAnnotationRegions } from "@/lib/captioning/annotationsFromCaptions";+import { extractMono16kFromVideoUrl } from "@/lib/captioning/extractMono16k";+import {+ shiftTrimRegionsMsForCaptionBuffer,+ trimLeadingSilenceMono16k,+} from "@/lib/captioning/leadingSilence";+import { transcribeMono16kToSegments } from "@/lib/captioning/transcribe";+import type { CliCaptionsRequest, CliDoneResult } from "@/lib/cliContracts";+import { nativeBridgeClient } from "@/native";++/** Highest trailing number across existing region ids, so new ids never collide. */+function nextNumericIdFrom(regions: { id: string }[]): number {+ let max = 0;+ for (const region of regions) {+ const match = /(\d+)$/.exec(region.id);+ if (match) max = Math.max(max, Number(match[1]));+ }+ return max + 1;+}++async function runCaptions(request: CliCaptionsRequest): Promise<CliDoneResult> {+ const loaded = await nativeBridgeClient.project.loadProjectFileFromPath(request.projectPath);+ if (!loaded.success || loaded.project === undefined) {+ throw new Error(loaded.error ?? loaded.message ?? "Failed to load project file");+ }+ if (!validateProjectData(loaded.project)) {+ throw new Error("Project file is not a valid .openscreen project");+ }+ const project = loaded.project;+ const media = resolveProjectMedia(project);+ if (!media) {+ throw new Error("Project file does not reference any recorded media");+ }+ const editor = normalizeProjectEditor(project.editor ?? {});+ const trimRegions: TrimRegion[] = editor.trimRegions;++ window.electronAPI.cliLog("info", "Extracting audio…");+ const videoUrl = toFileUrl(media.screenVideoPath);+ const { samples, durationSec } = await extractMono16kFromVideoUrl(videoUrl);+ if (!Number.isFinite(durationSec) || durationSec <= 0 || samples.length < 800) {+ throw new Error("The project's video has no usable audio track to transcribe");+ }++ const { samples: speechSamples, trimSec } = trimLeadingSilenceMono16k(samples);+ if (speechSamples.length < 800) {+ throw new Error("No speech detected in the project's audio");+ }++ const trimMs = Math.round(trimSec * 1000);+ const trimRegionsForTranscribe = shiftTrimRegionsMsForCaptionBuffer(trimRegions, trimMs);++ const transcribeOptions = {+ onStatus: (phase: "model" | "transcribe") => {+ window.electronAPI.cliLog(+ "info",+ phase === "model" ? "Loading caption model…" : "Transcribing…",+ );+ },+ };++ let { segments: segmentsRaw, granularity } = await transcribeMono16kToSegments(speechSamples, {+ trimRegions: trimRegionsForTranscribe,+ ...transcribeOptions,+ });+ let transcribedFromTrimmedBuffer = true;++ // Leading-silence trimming can return empty even when the full source has+ // speech. Retry once against the untrimmed buffer before giving up.+ if (segmentsRaw.length === 0 && trimSec > 0) {+ ({ segments: segmentsRaw, granularity } = await transcribeMono16kToSegments(samples, {+ trimRegions,+ ...transcribeOptions,+ }));+ transcribedFromTrimmedBuffer = false;+ }++ const segments =+ transcribedFromTrimmedBuffer && trimSec > 0+ ? segmentsRaw.map((segment) => ({+ ...segment,+ startSec: segment.startSec + trimSec,+ endSec: segment.endSec + trimSec,+ }))+ : segmentsRaw;++ // Re-running the command replaces earlier auto-captions instead of stacking+ // duplicates; manually added annotations are preserved.+ const manualAnnotations: AnnotationRegion[] = editor.annotationRegions.filter(+ (annotation) => annotation.annotationSource !== "auto-caption",+ );+ const startNumericId = nextNumericIdFrom([...editor.annotationRegions, ...editor.zoomRegions]);+ const startZIndex = manualAnnotations.reduce((max, a) => Math.max(max, a.zIndex + 1), 1);++ let { regions } = captionSegmentsToAnnotationRegions(segments, startNumericId, startZIndex, {+ minWordsPerCaption: request.minWordsPerCaption,+ maxWordsPerCaption: request.maxWordsPerCaption,+ timestampGranularity: granularity,+ });+ if (regions.length === 0 && segments.length > 0) {+ ({ regions } = captionSegmentsToAnnotationRegions(segments, startNumericId, startZIndex, {+ minWordsPerCaption: 1,+ maxWordsPerCaption: Number.MAX_SAFE_INTEGER,+ timestampGranularity: granularity,+ }));+ }+ if (regions.length === 0) {+ throw new Error("Transcription produced no caption segments");+ }++ const updatedProject = {+ ...project,+ editor: {+ ...editor,+ annotationRegions: [...manualAnnotations, ...regions],+ },+ };++ return {+ success: true,+ projectPath: request.projectPath,+ projectData: updatedProject,+ captionCount: regions.length,+ };+}++export function CliCaptionsRunner() {+ const startedRef = useRef(false);+ const [status] = useState("Generating captions…");++ useEffect(() => {+ if (startedRef.current) return;+ startedRef.current = true;++ void (async () => {+ try {+ const request = await window.electronAPI.cliGetRequest();+ if (request.kind !== "captions") {+ throw new Error(`cli-captions window received a ${request.kind} request`);+ }+ const result = await runCaptions(request);+ await window.electronAPI.cliDone(result);+ } catch (error) {+ const message = error instanceof Error ? (error.stack ?? error.message) : String(error);+ await window.electronAPI.cliDone({ success: false, error: message });+ }+ })();+ }, []);++ return (+ <div className="flex h-screen items-center justify-center bg-[#09090b] text-white/60 text-sm">+ {status}+ </div>+ );+}++export default CliCaptionsRunner;diff --git a/src/cli/CliExportRunner.tsx b/src/cli/CliExportRunner.tsxindex 56f60581e..08e600b34 100644--- a/src/cli/CliExportRunner.tsx+++ b/src/cli/CliExportRunner.tsx@@ -13,7 +13,13 @@ import {toFileUrl,validateProjectData,} from "@/components/video-editor/projectPersistence";-import type { CursorTelemetryPoint } from "@/components/video-editor/types";+import { buildAutoZoomSuggestions } from "@/components/video-editor/timeline/zoomSuggestionUtils";+import type { CursorTelemetryPoint, ZoomRegion } from "@/components/video-editor/types";+import {+ clampFocusToDepth,+ DEFAULT_ZOOM_DEPTH,+ ZOOM_DEPTH_SCALES,+} from "@/components/video-editor/types";import type { CliDoneResult, CliExportRequest } from "@/lib/cliContracts";import { hasNativeCursorRecordingData } from "@/lib/cursor/nativeCursor";import { calculateOutputDimensions, GifExporter } from "@/lib/exporter/gifExporter";@@ -39,7 +45,9 @@ function isClickInteractionType(interactionType: string | null | undefined) {);}-function probeVideoDimensions(url: string): Promise<{ width: number; height: number }> {+function probeVideoDimensions(+ url: string,+): Promise<{ width: number; height: number; durationMs: number }> {return new Promise((resolve, reject) => {const video = document.createElement("video");video.preload = "metadata";@@ -57,8 +65,9 @@ function probeVideoDimensions(url: string): Promise<{ width: number; height: numvideo.onloadedmetadata = () => {const width = video.videoWidth;const height = video.videoHeight;+ const durationMs = Number.isFinite(video.duration) ? Math.round(video.duration * 1000) : 0;cleanup();- resolve({ width, height });+ resolve({ width, height, durationMs });};video.onerror = () => {cleanup();@@ -80,6 +89,32 @@ function fitPreviewBox(aspectRatioValue: number, boxWidth: number, boxHeight: nureturn { width: Math.round(width), height: Math.round(height) };}+/** Mirrors the editor's buildAutoZoomRegions: cursor-dwell suggestions that+ * follow the cursor (focusMode "auto") and never overlap existing regions. */+function buildAutoZoomRegions(+ cursorTelemetry: CursorTelemetryPoint[],+ totalMs: number,+ existingRegions: ZoomRegion[],+): ZoomRegion[] {+ const suggestions = buildAutoZoomSuggestions({+ cursorTelemetry,+ totalMs,+ existingRegions,+ defaultDurationMs: Math.max(1000, Math.round(totalMs * 0.05)),+ });+ let nextId = 1;+ return suggestions.map((suggestion) => ({+ id: `cli-auto-zoom-${nextId++}`,+ startMs: Math.round(suggestion.span.start),+ endMs: Math.round(suggestion.span.end),+ depth: DEFAULT_ZOOM_DEPTH,+ customScale: ZOOM_DEPTH_SCALES[DEFAULT_ZOOM_DEPTH],+ focus: clampFocusToDepth(suggestion.focus, DEFAULT_ZOOM_DEPTH),+ focusMode: "auto" as const,+ source: "auto" as const,+ }));+}+function replaceExtension(filePath: string, newExtension: string): string {return filePath.replace(/\.(openscreen|json)$/i, "") + newExtension;}@@ -97,6 +132,20 @@ async function runExport(request: CliExportRequest): Promise<CliDoneResult> {if (!media) {throw new Error("Project file does not reference any recorded media");}+ // Prefer the main process's approved session paths: they carry the+ // packed-project sibling fallback when the stored absolute paths are stale.+ try {+ const sessionResult = await window.electronAPI.getCurrentRecordingSession();+ const session = sessionResult?.session;+ if (session?.screenVideoPath) {+ media.screenVideoPath = session.screenVideoPath;+ if (media.webcamVideoPath && session.webcamVideoPath) {+ media.webcamVideoPath = session.webcamVideoPath;+ }+ }+ } catch {+ // Fall back to the paths stored in the project file.+ }const editor = normalizeProjectEditor(project.editor ?? {});const format = request.format ?? editor.exportFormat;@@ -154,6 +203,21 @@ async function runExport(request: CliExportRequest): Promise<CliDoneResult> {const probed = await probeVideoDimensions(videoUrl);const sourceWidth = probed.width || DEFAULT_SOURCE_DIMENSIONS.width;const sourceHeight = probed.height || DEFAULT_SOURCE_DIMENSIONS.height;++ if (request.autoZoom) {+ const autoRegions = buildAutoZoomRegions(+ cursorTelemetry,+ probed.durationMs,+ editor.zoomRegions,+ );+ if (autoRegions.length > 0) {+ editor.zoomRegions = [...editor.zoomRegions, ...autoRegions];+ }+ window.electronAPI.cliLog(+ "info",+ `Auto-zoom: added ${autoRegions.length} region(s) from cursor telemetry`,+ );+ }const effectiveSourceDimensions = calculateEffectiveSourceDimensions(sourceWidth,sourceHeight,diff --git a/src/cli/CliSourcesRunner.tsx b/src/cli/CliSourcesRunner.tsxnew file mode 100644index 000000000..a1e464e23--- /dev/null+++ b/src/cli/CliSourcesRunner.tsx@@ -0,0 +1,87 @@+// Hidden-window runner for `openscreen sources`: enumerates capturable+// displays/windows (via the same get-sources IPC the GUI picker uses) and+// microphone inputs, then hands the payload to the CLI controller to print.++import { useEffect, useRef, useState } from "react";+import type { CliSourcesResult } from "@/lib/cliContracts";++async function enumerateMicrophones(): Promise<{+ microphones: { label: string }[];+ microphoneLabelsUnavailable: boolean;+}> {+ const listInputs = async () =>+ (await navigator.mediaDevices.enumerateDevices()).filter(+ (device) => device.kind === "audioinput",+ );++ let inputs = await listInputs();++ // Labels are blank until a getUserMedia grant exists; a short-lived probe+ // stream unlocks them without leaving anything recording.+ if (inputs.length > 0 && inputs.every((device) => !device.label)) {+ let probeStream: MediaStream | null = null;+ try {+ probeStream = await navigator.mediaDevices.getUserMedia({ audio: true });+ inputs = await listInputs();+ } catch {+ // Permission denied — report devices without labels.+ } finally {+ probeStream?.getTracks().forEach((track) => track.stop());+ }+ }++ const labeled = inputs.filter((device) => device.label);+ return {+ microphones: labeled.map((device) => ({ label: device.label })),+ microphoneLabelsUnavailable: inputs.length > 0 && labeled.length === 0,+ };+}++async function enumerateSources(): Promise<CliSourcesResult> {+ const sources = await window.electronAPI.getSources({+ types: ["screen", "window"],+ thumbnailSize: { width: 32, height: 18 },+ });++ const displays = sources+ .filter((source) => source.id.startsWith("screen:"))+ .map((source, index) => ({ index, id: source.id, name: source.name }));+ const windows = sources+ .filter((source) => source.id.startsWith("window:"))+ .map((source) => ({ id: source.id, name: source.name }));++ const { microphones, microphoneLabelsUnavailable } = await enumerateMicrophones();+ return { displays, windows, microphones, microphoneLabelsUnavailable };+}++export function CliSourcesRunner() {+ const startedRef = useRef(false);+ const [status] = useState("Enumerating sources…");++ useEffect(() => {+ if (startedRef.current) return;+ startedRef.current = true;++ void (async () => {+ try {+ const request = await window.electronAPI.cliGetRequest();+ if (request.kind !== "sources") {+ throw new Error(`cli-sources window received a ${request.kind} request`);+ }+ const sources = await enumerateSources();+ await window.electronAPI.cliDone({ success: true, sources });+ } catch (error) {+ const message = error instanceof Error ? (error.stack ?? error.message) : String(error);+ await window.electronAPI.cliDone({ success: false, error: message });+ }+ })();+ }, []);++ return (+ <div className="flex h-screen items-center justify-center bg-[#09090b] text-white/60 text-sm">+ {status}+ </div>+ );+}++export default CliSourcesRunner;diff --git a/src/lib/cliContracts.ts b/src/lib/cliContracts.tsindex cdd7a4506..111f2ed2a 100644--- a/src/lib/cliContracts.ts+++ b/src/lib/cliContracts.ts@@ -25,6 +25,12 @@ export interface CliExportRequest {*/previewWidth: number | null;previewHeight: number | null;+ /**+ * Add automatic zoom regions derived from cursor-dwell telemetry (same+ * suggestion engine as the editor's magic wand) before rendering. Existing+ * zoom regions are preserved; suggestions never overlap them.+ */+ autoZoom: boolean;/** Absolute path to a voiceover audio file to mix into the export (MP4 only). */audioPath: string | null;/** "mix" layers the voiceover over the recording's audio; "replace" drops the original. */@@ -50,7 +56,31 @@ export interface CliRecordRequest {projectOut: string | null;}-export type CliRequest = CliExportRequest | CliRecordRequest;+export interface CliSourcesRequest {+ kind: "sources";+}++export interface CliCaptionsRequest {+ kind: "captions";+ /** Absolute path to the .openscreen project file (updated in place). */+ projectPath: string;+ minWordsPerCaption: number;+ maxWordsPerCaption: number;+}++export type CliRequest =+ | CliExportRequest+ | CliRecordRequest+ | CliSourcesRequest+ | CliCaptionsRequest;++export interface CliSourcesResult {+ displays: { index: number; id: string; name: string }[];+ windows: { id: string; name: string }[];+ microphones: { label: string }[];+ /** True when microphone labels required a permission the user hasn't granted. */+ microphoneLabelsUnavailable: boolean;+}export interface CliProgressEvent {percentage: number;@@ -80,4 +110,8 @@ export interface CliDoneResult {* The main process writes it to the --project path (renderer has no fs).*/projectData?: unknown;+ /** Sources: enumeration payload printed by the main process. */+ sources?: CliSourcesResult;+ /** Captions: number of caption annotations generated. */+ captionCount?: number;}