Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,6 @@ aside-react/extracted/
# Local screenshot-generation harnesses; keep private paths out of source PRs.
tests/ui/hero-frame.capture.spec.ts
tests/ui/hero-capture.config.ts

# Personal Claude Code settings
.claude/settings.local.json
366 changes: 366 additions & 0 deletions electron/autoVideo/autoVideoController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,366 @@
import { execFile } from "node:child_process";
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { type BrowserWindow, dialog, globalShortcut, ipcMain, shell } from "electron";
import { type AutoVideoScript, parseAutoVideoScript } from "../../src/lib/autoVideo/script";
import { getSessionCaptureSource } from "../ipc/captureSelection";
import { captureRecordingZoomMarker } from "../ipc/cursor/telemetry";
import { isTrustedRenderer } from "../trustedRenderer";
import { getHudOverlayWindow } from "../windows";
import {
AutoVideoExportQueue,
type AutoVideoExportResult,
resolveAutoVideoOutputPath,
} from "./exportQueue";
import { startAutoVideoInputDriver } from "./inputDriver";
import { AutoVideoRun, type AutoVideoRunResult, DEFAULT_AUTO_VIDEO_TIMINGS } from "./runner";

const execFileAsync = promisify(execFile);

/** Global shortcut that stops a running script. */
export const AUTO_VIDEO_ABORT_ACCELERATOR = "CommandOrControl+Shift+Escape";
const ABORT_SHORTCUT_LABEL = "⌘⇧Esc";

/** Bundle identifiers such as com.apple.Safari. */
const BUNDLE_ID_PATTERN = /^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+){2,}$/;

const exportQueue = new AutoVideoExportQueue({
stat: async (filePath) => {
try {
const stat = await fs.stat(filePath);
return stat.isFile()
? { birthtimeMs: stat.birthtimeMs, mtimeMs: stat.mtimeMs, size: stat.size }
: null;
} catch {
return null;
}
},
});

function toFilePath(value: unknown): string | null {
if (typeof value !== "string" || value === "") return null;
if (value.startsWith("file:")) {
try {
return fileURLToPath(value);
} catch {
return null;
}
}
return path.isAbsolute(value) ? value : null;
}

/** IPC the editor uses to pick up and report an auto-video export. */
export function registerAutoVideoIpcHandlers() {
ipcMain.handle("auto-video-claim-export", async (event, videoPath: unknown) => {
if (!isTrustedRenderer(event)) return null;
if (!exportQueue.hasPending) return null;
const request = await exportQueue.claim(toFilePath(videoPath));
if (request) {
// Closing the editor window skips the editor's own cleanup, so watch it here.
// A report after the export already finished is ignored.
event.sender.once("destroyed", () => {
void exportQueue.report(
request.requestId,
"The editor closed before the export finished",
);
});
}
return request;
});
ipcMain.handle(
"auto-video-report-export",
async (event, requestId: unknown, error: unknown) => {
if (!isTrustedRenderer(event)) return;
await exportQueue.report(requestId, error);
},
);
}

let activeRun: AutoVideoRun | null = null;
let running = false;
let recordingActive = false;

/** Forward every recording state change here (from main's recording-state callback). */
export function notifyAutoVideoRecordingState(recording: boolean) {
recordingActive = recording;
activeRun?.setRecordingState(recording);
}

export function isAutoVideoRunning() {
return running;
}

export async function openAppForAutoVideo(app: string) {
const args = path.isAbsolute(app)
? [app]
: BUNDLE_ID_PATTERN.test(app) && !app.endsWith(".app")
? ["-b", app]
: ["-a", app];
try {
await execFileAsync("open", args, { timeout: 30_000 });
} catch (error) {
const stderr = (error as { stderr?: string }).stderr?.trim();
throw new Error(stderr || `Could not open ${app}`);
}
}

function requestStartRecording() {
const hud = getHudOverlayWindow();
if (!hud || hud.isDestroyed() || hud.webContents.isDestroyed()) {
throw new Error("Open Recordly's recording controls before running a script");
}
hud.webContents.send("start-recording-from-main");
}

function requestStopRecording() {
const hud = getHudOverlayWindow();
if (hud && !hud.isDestroyed() && !hud.webContents.isDestroyed()) {
hud.webContents.send("stop-recording-from-tray");
}
}

export interface AutoVideoScriptRun {
result: AutoVideoRunResult;
/** Set when the steps finished and the video is being exported. */
exported: Promise<AutoVideoExportResult> | null;
}

/**
* Runs a validated script. Only one script runs at a time. When the script
* asks for it, the finished recording is exported to `outputPath` once it has
* loaded in the editor.
*/
export async function runAutoVideoScript(
script: AutoVideoScript,
options: { outputPath?: string } = {},
): Promise<AutoVideoScriptRun> {
const fail = (error: string): AutoVideoScriptRun => ({
result: { status: "failed", error, recorded: false, stepIndex: null },
exported: null,
});
if (process.platform !== "darwin") {
return fail("Automatic video generation is only available on macOS");
}
if (running) {
return fail("A script is already running");
}
// Reserve before any await, so a second script can't start in the meantime.
running = true;
let run: AutoVideoRun | null = null;
let shortcutRegistered = false;
try {
const outputPath = script.export ? options.outputPath : undefined;
if (outputPath) {
try {
await fs.mkdir(path.dirname(outputPath), { recursive: true });
} catch (error) {
return fail(`Could not create the folder for ${outputPath}: ${String(error)}`);
}
}

const runStartedAt = Date.now();
let exported: Promise<AutoVideoExportResult> | null = null;

const thisRun = new AutoVideoRun(
{
startDriver: () => startAutoVideoInputDriver({ promptForPermission: true }),
hasCaptureSource: () => getSessionCaptureSource() !== null,
requestStartRecording,
requestStopRecording,
openUrl: (url) => shell.openExternal(url, { activate: true }),
openApp: openAppForAutoVideo,
addZoomMarker: () => captureRecordingZoomMarker(Date.now()),
onStepsFinished: () => {
// Queue before the recording stops, so the editor can claim it as soon as it opens.
if (outputPath) {
exported = exportQueue.request({
outputPath,
quality: script.exportQuality,
notBeforeMs: runStartedAt,
});
}
},
},
{ recording: recordingActive },
);
run = thisRun;
activeRun = thisRun;

try {
shortcutRegistered = globalShortcut.register(AUTO_VIDEO_ABORT_ACCELERATOR, () =>
thisRun.abort(`Stopped with ${ABORT_SHORTCUT_LABEL}`),
);
} catch (error) {
console.warn("[auto-video] Could not register the stop shortcut:", error);
}
if (!shortcutRegistered) {
console.warn(
`[auto-video] ${ABORT_SHORTCUT_LABEL} is unavailable; stop from the recorder.`,
);
}

const result = await thisRun.run(script);
if (result.status !== "completed" && exported) {
exportQueue.cancel();
exported = null;
} else if (exported) {
// The recording has stopped; now give the editor its time to open it.
exportQueue.startClaimTimeout();
}
return { result, exported };
} finally {
running = false;
if (shortcutRegistered) globalShortcut.unregister(AUTO_VIDEO_ABORT_ACCELERATOR);
// Keep the run briefly so a recording that starts late can still be stopped,
// then stop forwarding recording changes to it.
const finishedRun = run;
if (finishedRun) {
setTimeout(() => {
if (activeRun === finishedRun) activeRun = null;
}, DEFAULT_AUTO_VIDEO_TIMINGS.lateStartGraceMs + 1_000);
}
}
}

/** True if this app can use the stop shortcut (no other app has claimed it). */
function isAbortShortcutAvailable() {
try {
if (globalShortcut.isRegistered(AUTO_VIDEO_ABORT_ACCELERATOR)) return true;
const registered = globalShortcut.register(AUTO_VIDEO_ABORT_ACCELERATOR, () => undefined);
if (registered) globalShortcut.unregister(AUTO_VIDEO_ABORT_ACCELERATOR);
return registered;
} catch {
return false;
}
}

async function fileExists(filePath: string) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}

async function showError(parent: BrowserWindow | undefined, message: string, detail: string) {
const options = { type: "error" as const, message, detail, buttons: ["OK"] };
if (parent && !parent.isDestroyed()) await dialog.showMessageBox(parent, options);
else await dialog.showMessageBox(options);
}

/**
* Lets the user pick a script file, confirms, runs it, and reports problems.
* Used by the "Run Auto-Video Script…" menu item.
*/
export async function promptAndRunAutoVideoScript(parent?: BrowserWindow) {
if (running) {
await showError(
parent,
"A script is already running",
`Press ${ABORT_SHORTCUT_LABEL} to stop it.`,
);
return;
}

const openOptions: Electron.OpenDialogOptions = {
title: "Run Auto-Video Script",
properties: ["openFile"],
filters: [{ name: "Auto-Video Script", extensions: ["json"] }],
};
const picked =
parent && !parent.isDestroyed()
? await dialog.showOpenDialog(parent, openOptions)
: await dialog.showOpenDialog(openOptions);
const filePath = picked.filePaths[0];
if (picked.canceled || !filePath) return;

let text: string;
try {
text = await fs.readFile(filePath, "utf8");
} catch (error) {
await showError(parent, "Could not read the script", String(error));
return;
}

const parsed = parseAutoVideoScript(text);
if (!parsed.ok) {
const shown = parsed.errors.slice(0, 10);
const more = parsed.errors.length - shown.length;
await showError(
parent,
`${path.basename(filePath)} has problems`,
shown.join("\n") + (more > 0 ? `\n…and ${more} more` : ""),
);
return;
}

const script = parsed.script;
const outputPath = script.export
? resolveAutoVideoOutputPath(filePath, script.output)
: undefined;
const stopHint = isAbortShortcutAvailable()
? `Press ${ABORT_SHORTCUT_LABEL} to stop at any time.`
: `${ABORT_SHORTCUT_LABEL} is in use by another app, so it can't stop this script. ` +
"To stop, use Stop in Recordly's recording controls.";
const outputNote = !outputPath
? ""
: (await fileExists(outputPath))
? `\n\nThe finished video will replace the existing file:\n${outputPath}`
: `\n\nThe finished video will be saved to:\n${outputPath}`;
const confirmOptions: Electron.MessageBoxOptions = {
type: "warning",
message: `Run “${script.name ?? path.basename(filePath)}”?`,
detail:
`Recordly will start recording and control your mouse and keyboard for ${script.steps.length} ` +
`step${script.steps.length === 1 ? "" : "s"}. Don't touch the mouse or keyboard until it finishes.\n\n` +
stopHint +
outputNote,
buttons: ["Run Script", "Cancel"],
defaultId: 0,
cancelId: 1,
};
const confirmed =
parent && !parent.isDestroyed()
? await dialog.showMessageBox(parent, confirmOptions)
: await dialog.showMessageBox(confirmOptions);
if (confirmed.response !== 0) return;

const { result, exported } = await runAutoVideoScript(script, { outputPath });
if (result.status === "failed") {
await showError(
parent,
"The script could not finish",
result.error +
(result.recorded ? "\n\nThe recording up to that point opens in the editor." : ""),
);
return;
}
if (!exported) return;

const exportResult = await exported;
if (!exportResult.success) {
await showError(
parent,
"The video could not be exported",
`${exportResult.error}\n\nThe recording is still open in the editor, so you can export it from there.`,
);
return;
}

const doneOptions: Electron.MessageBoxOptions = {
type: "info",
message: "Video exported",
detail: exportResult.path,
buttons: ["Show in Finder", "OK"],
defaultId: 0,
cancelId: 1,
};
const done =
parent && !parent.isDestroyed()
? await dialog.showMessageBox(parent, doneOptions)
: await dialog.showMessageBox(doneOptions);
if (done.response === 0) shell.showItemInFolder(exportResult.path);
}
Loading