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
cleanup
Siddharthc539e9ba266f
diff --git a/electron/globalShortcut.ts b/electron/globalShortcut.tsindex f1b046a34..2765bad22 100644--- a/electron/globalShortcut.ts+++ b/electron/globalShortcut.ts@@ -41,16 +41,14 @@ let currentAccelerator: string | null = null;export function registerOpenAppShortcut(binding: ShortcutBinding, onTrigger: () => void): boolean {const accelerator = bindingToAccelerator(binding);- // Same shortcut already registered, nothing to doif (accelerator === currentAccelerator) {return true;}- // Try to register new shortcut first (before unregistering old one)+ // Register the new shortcut before unregistering the old, so a failure leaves the old binding intactconst success = globalShortcut.register(accelerator, onTrigger);if (success) {- // Only unregister old shortcut after new one succeedsif (currentAccelerator) {globalShortcut.unregister(currentAccelerator);}diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex a7f41016c..1eb569efe 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -62,10 +62,7 @@ const ALLOWED_IMPORT_VIDEO_EXTENSIONS = new Set([const PREVIEW_AUDIO_DIR = path.join(app.getPath("userData"), "preview-audio");const nativeMacCaptureEvents = new EventEmitter();-/**- * Paths explicitly approved by the user via file picker dialogs or project loads.- * These are added at runtime when the user selects files from outside the default directories.- */+// Paths the user approved via file picker or project load (i.e. outside the default dirs).const approvedPaths = new Set<string>();function approveFilePath(filePath: string): void {@@ -101,10 +98,7 @@ function resolveApprovedVideoPath(videoPath?: string | null): string | null {return normalizedPath;}-/**- * Helper function to build dialog options with a parent window only when it's valid.- * This prevents passing stale or destroyed BrowserWindow references to dialog calls.- */+// Attach the parent window only when valid, to avoid passing a destroyed BrowserWindow to dialogs.function buildDialogOptions<T extends Electron.OpenDialogOptions | Electron.SaveDialogOptions>(baseOptions: T,parentWindow: BrowserWindow | null,@@ -233,9 +227,8 @@ async function approveReadableVideoPath(return null;}- // When called with trustedDirs (e.g. from project load), only auto-approve- // paths within those directories. This prevents malicious project files from- // approving reads to arbitrary filesystem locations.+ // With trustedDirs (e.g. project load), only auto-approve paths inside them so a+ // malicious project file can't approve reads to arbitrary locations.if (trustedDirs) {const resolved = path.resolve(normalizedPath);const withinTrusted = trustedDirs.some((dir) => isPathWithinDir(resolved, dir));@@ -282,11 +275,9 @@ function isValidDurationMs(value: number | undefined): value is number {}/**- * Finalize a single recording file: if it was streamed to disk, flush and close- * the stream; otherwise (a short recording, or the stream failed to open and the- * renderer fell back to in-memory buffering) write the buffered bytes. Returns- * whether the file was streamed, which the caller uses to decide whether the- * WebM duration needs patching on disk.+ * Finalize one recording file: flush/close the stream if it was streamed, else write+ * the buffered bytes (short recording or stream failed to open). Returns whether it was+ * streamed, so the caller knows if the WebM duration needs patching on disk.*/async function finalizeRecordingFile(registry: RecordingStreamRegistry,@@ -322,8 +313,8 @@ async function getApprovedProjectSession(return null;}- // Only auto-approve media paths within the project's directory or RECORDINGS_DIR.- // This prevents crafted project files from approving reads to arbitrary locations.+ // Only auto-approve media within the project's dir or RECORDINGS_DIR, so a crafted+ // project file can't approve reads to arbitrary locations.const trustedDirs = [RECORDINGS_DIR];if (projectFilePath) {trustedDirs.push(path.dirname(path.resolve(projectFilePath)));@@ -366,10 +357,7 @@ let lastEnumeratedSources = new Map<string, DesktopCapturerSource>();let currentProjectPath: string | null = null;let currentRecordingSession: RecordingSession | null = null;-/**- * Returns the cached DesktopCapturerSource set when the user picked a source.- * Used by setDisplayMediaRequestHandler in main.ts for cursor-free capture.- */+// Cached source from the user's pick. Used by setDisplayMediaRequestHandler in main.ts for cursor-free capture.export function getSelectedDesktopSource(): DesktopCapturerSource | null {return selectedDesktopSource;}@@ -1290,7 +1278,7 @@ export function registerIpcHandlers(return { success: true, granted: true, status };}- // Screen recording has no askForMediaAccess equivalent. Trigger the+ // Screen recording has no askForMediaAccess equivalent, so trigger the// TCC prompt without opening OpenScreen's source selector above it.if (status === "not-determined") {const mainWin = getMainWindow();@@ -1398,9 +1386,8 @@ export function registerIpcHandlers(ipcMain.handle("request-native-mac-cursor-access", async () => {const access = await requestMacCursorAccessibilityAccess();- // When the editable cursor can't get Accessibility trust, don't leave the- // user guessing where to enable it — pop a native dialog that deep-links- // straight to the Accessibility pane (mirrors the Screen Recording flow).+ // When the editable cursor can't get Accessibility trust, pop a native dialog+ // that deep-links to the Accessibility pane (mirrors the Screen Recording flow).if (process.platform === "darwin" && !access.granted) {const mainWin = getMainWindow();const detail =@@ -1470,10 +1457,9 @@ export function registerIpcHandlers(});ipcMain.handle("switch-to-editor", () => {- // createEditorWindow is createEditorWindowWrapper — it already closes- // the current mainWindow (the HUD) before opening the editor. Closing- // it here too causes a double-close which leaves ghost transparent- // windows and makes the HUD shadow compound on each cycle.+ // createEditorWindow already closes the current mainWindow (the HUD) before+ // opening the editor. Closing it here too double-closes, leaving ghost+ // transparent windows and compounding the HUD shadow each cycle.createEditorWindow();});@@ -1493,9 +1479,8 @@ export function registerIpcHandlers(return;}- // Wait for the first frame to be painted before showing the window.- // Showing before ready-to-show produces a black rectangle flash because- // Chromium hasn't rendered any pixels yet.+ // Wait for the first frame before showing, else Chromium flashes a black+ // rectangle because it hasn't rendered any pixels yet.if (overlayWindow.webContents.isLoading()) {await new Promise<void>((resolve) => {overlayWindow.once("ready-to-show", resolve);@@ -2211,8 +2196,7 @@ export function registerIpcHandlers();// On-disk write streams for in-progress recordings, keyed by output file name.- // Chunks are appended as they arrive from ondataavailable so the renderer- // never buffers the full video in memory (the #616 fix).+ // Chunks append as they arrive so the renderer never buffers the full video (#616).const recordingStreams = new RecordingStreamRegistry();registerRecordingStreamHandlers(ipcMain, recordingStreams, resolveRecordingOutputPath);@@ -2255,9 +2239,9 @@ export function registerIpcHandlers();}- // Streamed files lack the WebM Duration header (the renderer no longer holds- // the blob to patch). Patch on disk so the editor's seek bar and timeline- // work. Best-effort and independent per file, so the patches run together.+ // Streamed files lack the WebM Duration header (renderer no longer holds the+ // blob), so patch on disk for the editor's seek bar and timeline. Best-effort,+ // independent per file, so they run together.if (isValidDurationMs(payload.durationMs)) {const patches: Promise<unknown>[] = [];if (screenStreamed) {@@ -2388,9 +2372,8 @@ export function registerIpcHandlers(? [{ name: mainT("dialogs", "fileDialogs.gifImage"), extensions: ["gif"] }]: [{ name: mainT("dialogs", "fileDialogs.mp4Video"), extensions: ["mp4"] }];- // Prefer the user's last export folder if it still exists, otherwise fall- // back to ~/Downloads. Validation must happen here because the renderer- // can't stat the filesystem.+ // Prefer the user's last export folder if it still exists, else ~/Downloads.+ // Validate here because the renderer can't stat the filesystem.let defaultDir = app.getPath("downloads");if (exportFolder) {try {@@ -2435,8 +2418,8 @@ export function registerIpcHandlers(ipcMain.handle("write-export-to-path", async (_, videoData: ArrayBuffer, filePath: string) => {try {- // Sanity-check the path. The renderer is trusted (contextIsolation is on),- // but a stale state bug shouldn't be able to clobber arbitrary files.+ // Sanity-check the path: the renderer is trusted (contextIsolation on), but a+ // stale-state bug shouldn't be able to clobber arbitrary files.if (typeof filePath !== "string" || !path.isAbsolute(filePath)) {return { success: false, message: "Invalid path" };}@@ -2512,14 +2495,13 @@ export function registerIpcHandlers(ipcMain.handle("reveal-in-folder", async (_, filePath: string) => {try {- // shell.showItemInFolder doesn't return a value, it throws on error+ // showItemInFolder returns nothing, it throws on errorshell.showItemInFolder(filePath);return { success: true };} catch (error) {console.error(`Error revealing item in folder: ${filePath}`, error);- // Fallback to open the directory if revealing the item fails- // This might happen if the file was moved or deleted after export,- // or if the path is somehow invalid for showItemInFolder+ // Fall back to opening the directory if revealing fails (file moved/deleted+ // after export, or a path showItemInFolder rejects).try {const openPathResult = await shell.openPath(path.dirname(filePath));if (openPathResult) {@@ -2658,9 +2640,8 @@ export function registerIpcHandlers(async function loadProjectFile(projectFolder?: string): Promise<ProjectFileResult> {try {- // Prefer the user's last opened-project folder if it still exists,- // otherwise fall back to RECORDINGS_DIR. Validation must happen here- // because the renderer can't stat the filesystem.+ // Prefer the user's last opened-project folder if it still exists, else+ // RECORDINGS_DIR. Validate here because the renderer can't stat the filesystem.let defaultDir = RECORDINGS_DIR;if (projectFolder) {try {@@ -2669,9 +2650,8 @@ export function registerIpcHandlers(defaultDir = projectFolder;}} catch (err) {- // Stat can fail because the folder was moved/deleted (expected) or- // because of a permission error (worth surfacing). Either way we- // fall back to RECORDINGS_DIR, but log so debugging isn't blind.+ // Stat can fail if the folder was moved/deleted (expected) or on a+ // permission error (worth surfacing). We fall back either way, but log it.console.warn(`Could not access remembered project folder "${projectFolder}", falling back to RECORDINGS_DIR:`,err,@@ -2742,9 +2722,8 @@ export function registerIpcHandlers(const project = JSON.parse(content);currentProjectPath = filePath;- // Approve session paths; tolerate failures (e.g. video moved outside- // trusted dirs) so the project still loads and the renderer can surface- // a "video not found" error rather than a generic load failure.+ // Approve session paths but tolerate failures (e.g. video moved outside trusted+ // dirs) so the project still loads and the renderer can show "video not found".let session: import("../../src/lib/recordingSession").RecordingSession | null = null;try {session = await getApprovedProjectSession(project, filePath);diff --git a/electron/ipc/recordingStream.ts b/electron/ipc/recordingStream.tsindex 3dce5b955..665ea4194 100644--- a/electron/ipc/recordingStream.ts+++ b/electron/ipc/recordingStream.ts@@ -3,23 +3,18 @@ import { unlink } from "node:fs/promises";import type { IpcMain } from "electron";/**- * Owns the lifecycle of on-disk write streams for in-progress recordings, keyed- * by the recording's output file name. Browser MediaRecorder chunks are appended- * here as they arrive so a long recording never buffers the whole video in the- * renderer (the #616 fix).- *- * The file name is the key because it is the one value the renderer and main- * process already exchange and it is globally unique per recording, so there is- * no derived/offset key to keep in sync across the IPC boundary.+ * Owns write streams for in-progress recordings, keyed by output file name.+ * MediaRecorder chunks are appended as they arrive so a long recording never+ * buffers the whole video in the renderer (#616 fix). File name is the key+ * because it's already exchanged across IPC and is unique per recording.*/export class RecordingStreamRegistry {private readonly streams = new Map<string, WriteStream>();/**- * Open a write stream and resolve only once the OS confirms it is writable.- * Resolving on the `open` event (rather than on `createWriteStream` returning)- * means a bad path or permission error rejects here instead of surfacing as a- * silent chunk drop later, so the renderer's fallback can take over.+ * Open a write stream, resolving only on the `open` event so a bad path or+ * permission error rejects here instead of becoming a silent chunk drop later,+ * letting the renderer's fallback take over.*/async open(fileName: string, filePath: string): Promise<void> {await this.endStream(fileName);@@ -33,9 +28,8 @@ export class RecordingStreamRegistry {resolve();});});- // Keep a listener for the stream's lifetime so a late error logs rather- // than crashing the main process with an unhandled 'error' event. Per-write- // failures still surface through the `append` callback below.+ // Keep a lifetime listener so a late error logs instead of crashing the main+ // process with an unhandled 'error'. Per-write failures still surface in `append`.ws.on("error", (error) => {console.error(`[recording-stream] ${fileName}:`, error);});@@ -59,9 +53,8 @@ export class RecordingStreamRegistry {}/**- * Flush and close the stream, keeping the file. Returns whether a stream was- * open — i.e. whether the recording was streamed to disk (true) or needs its- * in-memory buffer written by the caller (false).+ * Flush and close the stream, keeping the file. Returns true if a stream was+ * open (streamed to disk) or false if the caller still needs to write its buffer.*/async finalize(fileName: string): Promise<boolean> {const ws = this.streams.get(fileName);@@ -76,9 +69,8 @@ export class RecordingStreamRegistry {}/**- * Close the stream (if any) and delete the partial file. Used when a streamed- * recording is discarded or fails before a successful save, so cancelled runs- * don't leak file descriptors or orphan partial recordings on disk.+ * Close the stream (if any) and delete the partial file, so a discarded or+ * failed recording doesn't leak descriptors or orphan partial files on disk.*/async discard(fileName: string, filePath: string): Promise<void> {await this.endStream(fileName);diff --git a/electron/main.ts b/electron/main.tsindex 14255d5b3..bfb949ed7 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -28,15 +28,14 @@ import {const __dirname = path.dirname(fileURLToPath(import.meta.url));-// Use Screen & System Audio Recording permissions instead of CoreAudio Tap API on macOS.-// CoreAudio Tap requires NSAudioCaptureUsageDescription in the parent app's Info.plist,-// which doesn't work when running from a terminal/IDE during development, makes my life easier+// Use Screen & System Audio Recording permissions instead of the CoreAudio Tap API on macOS.+// Tap needs NSAudioCaptureUsageDescription in the parent app's Info.plist, which breaks when+// running from a terminal/IDE during dev.if (process.platform === "darwin") {app.commandLine.appendSwitch("disable-features", "MacCatapLoopbackAudioForScreenShare");}-// Enable Wayland support for proper screen capture and window management-// on Wayland compositors (Hyprland, GNOME, KDE, etc.)+// Wayland support for screen capture and window management on Wayland compositors.if (process.platform === "linux") {const isWayland =process.env.XDG_SESSION_TYPE === "wayland" || process.env.WAYLAND_DISPLAY !== undefined;@@ -384,7 +383,7 @@ function createEditorWindowWrapper() {const windowToClose = mainWindow;if (!windowToClose || windowToClose.isDestroyed()) return;- // Ask renderer to show the custom in-app dialog+ // Ask renderer to show the in-app close dialog.windowToClose.webContents.send("request-close-confirm");ipcMain.once("close-confirm-response", (event, choice: "save" | "discard" | "cancel") => {@@ -393,7 +392,7 @@ function createEditorWindowWrapper() {if (!windowToClose || windowToClose.isDestroyed()) return;if (choice === "save") {- // Tell renderer to save the project, then close when done+ // Save first, then close when the renderer reports done.windowToClose.webContents.send("request-save-before-close");ipcMain.once("save-before-close-done", (event, shouldClose: boolean) => {if (event.sender.id !== windowToClose?.webContents.id) return;@@ -428,16 +427,14 @@ function createCountdownOverlayWindowWrapper() {return countdownOverlayWindow;}-// Closing every window quits the app entirely (tray icon goes too).-// The in-app "Return to Recorder" button covers the editor → HUD round-trip,-// so closing the last window is an explicit "I'm done" signal.+// Closing every window quits the app (tray goes too). The in-app "Return to Recorder"+// button covers the editor-to-HUD round-trip, so closing the last window means "I'm done".app.on("window-all-closed", () => {app.quit();});app.on("activate", () => {- // On OS X it's common to re-create a window in the app when the- // dock icon is clicked and there are no other windows open.+ // On macOS, re-open a window when the dock icon is clicked and none are open.const hasVisibleWindow = BrowserWindow.getAllWindows().some((window) => {if (window.isDestroyed() || !window.isVisible()) {return false;@@ -456,16 +453,14 @@ app.on("will-quit", () => {unregisterAllGlobalShortcuts();});-// Register all IPC handlers when app is readyapp.whenReady().then(async () => {- // Force the app into "regular" activation policy so the Dock icon appears.- // The HUD overlay (transparent + frameless + skipTaskbar) is the first- // window we open, and AppKit otherwise classifies us as an accessory app.+ // Force "regular" activation policy so the Dock icon appears. The HUD overlay+ // (transparent, frameless, skipTaskbar) is the first window, and AppKit would+ // otherwise classify us as an accessory app.if (process.platform === "darwin") {app.dock?.show();}- // Allow microphone/media/screen permission checkssession.defaultSession.setPermissionCheckHandler((_webContents, permission) => {const allowed = ["media",@@ -508,9 +503,8 @@ app.whenReady().then(async () => {{ useSystemPicker: false },);- // Request microphone permission from macOS. Screen Recording is requested- // lazily from the source-picker action so the system prompt is not hidden- // behind OpenScreen's source selector window.+ // Request mic permission now. Screen Recording is requested lazily from the+ // source-picker action so its prompt isn't hidden behind the selector window.if (process.platform === "darwin") {const micStatus = systemPreferences.getMediaAccessStatus("microphone");if (micStatus !== "granted") {@@ -518,7 +512,6 @@ app.whenReady().then(async () => {}}- // Listen for HUD overlay quit event (macOS only)ipcMain.on("hud-overlay-close", () => {app.quit();});@@ -536,7 +529,6 @@ app.whenReady().then(async () => {createTray();updateTrayMenu();setupApplicationMenu();- // Ensure recordings directory existsawait ensureRecordingsDir();function switchToHudWrapper() {diff --git a/electron/native-bridge/cursor/recording/factory.ts b/electron/native-bridge/cursor/recording/factory.tsindex 0ba307788..9a82ffd55 100644--- a/electron/native-bridge/cursor/recording/factory.ts+++ b/electron/native-bridge/cursor/recording/factory.ts@@ -36,7 +36,7 @@ export function createCursorRecordingSession(}// Linux: capture cursor positions via Electron's `screen` API on an interval.- // No cursor sprites/assets and no clicks — just position telemetry.+ // No cursor sprites/assets and no clicks, just position telemetry.return new TelemetryRecordingSession({getDisplayBounds: options.getDisplayBounds,maxSamples: options.maxSamples,diff --git a/electron/native-bridge/cursor/recording/macNativeCursorRecordingSession.ts b/electron/native-bridge/cursor/recording/macNativeCursorRecordingSession.tsindex 5e09e9298..27a8a870c 100644--- a/electron/native-bridge/cursor/recording/macNativeCursorRecordingSession.ts+++ b/electron/native-bridge/cursor/recording/macNativeCursorRecordingSession.ts@@ -193,7 +193,7 @@ export class MacNativeCursorRecordingSession implements CursorRecordingSession {private readyTimer: NodeJS.Timeout | null = null;private previousLeftButtonDown = false;private consecutiveOutsideSamples = 0;- // Only hide after this many consecutive out-of-bounds samples (≈100ms at 33ms interval).+ // Hide only after this many consecutive out-of-bounds samples (~100ms at 33ms interval).// Fast swipes that briefly exit the display are clipped by clip-path instead of disappearing.private static readonly OUTSIDE_HIDE_THRESHOLD = 3;@@ -211,7 +211,7 @@ export class MacNativeCursorRecordingSession implements CursorRecordingSession {systemPreferences.isTrustedAccessibilityClient(true);} catch {// Without Accessibility, text/pointer affordance detection is unavailable;- // cursor bitmaps are still captured natively via NSCursor.+ // bitmaps are still captured natively via NSCursor.}const helperPath = findMacCursorHelperPath();@@ -370,10 +370,9 @@ export class MacNativeCursorRecordingSession implements CursorRecordingSession {const normalizedY = (cursor.y - bounds.y) / height;const isOutsideDisplay =normalizedX < 0 || normalizedX > 1 || normalizedY < 0 || normalizedY > 1;- // Fast swipes that briefly exit the display (<THRESHOLD samples) are handled by- // clip-path — the cursor clips to the canvas edge instead of snapping invisible.- // Sustained exits (≥THRESHOLD samples, ≈100ms) mark visible=false to prevent- // ghost cursors and motion trails from multi-display movement.+ // Brief exits (under THRESHOLD samples) clip to the canvas edge via clip-path instead+ // of snapping invisible. Sustained exits (>=THRESHOLD, ~100ms) mark visible=false to+ // avoid ghost cursors and motion trails from multi-display movement.if (isOutsideDisplay) {this.consecutiveOutsideSamples++;} else {diff --git a/electron/recording/webm-duration.ts b/electron/recording/webm-duration.tsindex 5b2c197c9..a93451f0a 100644--- a/electron/recording/webm-duration.ts+++ b/electron/recording/webm-duration.ts@@ -9,23 +9,16 @@ export type DurationPatchResult =/*** Patch the WebM Duration header on a finalized recording file.*- * Browser MediaRecorder writes WebM with no Duration EBML element. With the- * streaming-to-disk path the renderer never holds the blob, so the historical- * `fixWebmDuration(blob, durationMs)` call can't run. Patching on disk after- * `WriteStream.end()` produces an equivalent result: the editor's seek bar and- * timeline read a real duration instead of `N/A`.+ * MediaRecorder writes WebM with no Duration EBML element, and the streaming-to-disk+ * path never holds the blob so the old `fixWebmDuration(blob, durationMs)` can't run.+ * Patching on disk after `WriteStream.end()` gives the editor a real duration instead of `N/A`.*- * Atomic by design: writes the patched bytes to `<filePath>.duration-patch.tmp`- * and renames in place. If the process crashes mid-rewrite, the original file- * survives intact, so the user never loses their recording to a partial write.+ * Atomic: writes to `<filePath>.duration-patch.tmp` and renames in place, so a mid-rewrite+ * crash leaves the original intact. Best-effort: any read/parse/write failure logs and returns+ * a non-`patched` result rather than throwing; the file still plays without the patch (decoders+ * walk frames sequentially), only the seek bar and timeline break.*- * Best-effort by intent: any failure (read, parse, write) logs and returns a- * non-`patched` result rather than throwing. The file is still playable without- * the patch (decoders walk frames sequentially); the only cost is that the- * editor's seek bar and timeline break until it is patched.- *- * Memory: reads the whole file into a main-process Buffer, the same footprint- * as the pre-streaming renderer path, just on the side without V8's heap cap.+ * Reads the whole file into a main-process Buffer, off the renderer so it dodges V8's heap cap.*/export async function patchWebmDurationOnDisk(filePath: string,@@ -37,9 +30,8 @@ export async function patchWebmDurationOnDisk(const patched = fixParsedWebmDuration(webm, durationMs, { logger: false });if (!patched) {- // fixParsedWebmDuration returns false for: missing Segment, missing- // Info, or a Duration that is already valid. The first two mean a- // malformed (most likely truncated) file; the third is a no-op.+ // false means missing Segment, missing Info, or an already-valid Duration.+ // The first two mean a malformed (likely truncated) file; the third is a no-op.const reason = inferUnpatchedReason(webm);if (reason === "no-section") {console.warn(@@ -66,8 +58,7 @@ export async function patchWebmDurationOnDisk(return { patched: true };} catch (writeError) {console.error(`[webm-duration] failed to write patched ${filePath}:`, writeError);- // Best-effort cleanup of the temp file; if unlink also fails, leave it.- // The original recording is untouched because the rename never ran.+ // Clean up the temp file; the original is untouched since the rename never ran.await fs.unlink(tmpPath).catch(() => undefined);return { patched: false, reason: "io-error" };}@@ -78,14 +69,12 @@ export async function patchWebmDurationOnDisk(}/**- * Distinguish "no Segment/Info section" (malformed/truncated file) from "Info- * present but Duration already valid" (patch unnecessary).+ * Distinguish "no Segment/Info section" (malformed/truncated file) from "Info present+ * but Duration already valid" (patch unnecessary).*- * The IDs are the length-descriptor-stripped form that @fix-webm-duration/parser- * uses as its lookup keys (Segment `0x8538067`, Info `0x549a966`), verified- * against the parser's `src/lib/sections.js` — not the canonical 4-byte EBML- * IDs (`0x18538067` / `0x1549A966`), which this parser's `getSectionById` would- * never match.+ * The IDs are the length-descriptor-stripped form @fix-webm-duration/parser uses as lookup+ * keys (Segment `0x8538067`, Info `0x549a966`), per the parser's `src/lib/sections.js`, not+ * the canonical 4-byte EBML IDs (`0x18538067` / `0x1549A966`) that `getSectionById` never matches.*/function inferUnpatchedReason(webm: WebmFile): "no-section" | "already-valid" {const segment = webm.getSectionById?.(0x8538067);diff --git a/electron/windows.ts b/electron/windows.tsindex 7c7b0b030..c3830157f 100644--- a/electron/windows.ts+++ b/electron/windows.ts@@ -10,7 +10,7 @@ const RENDERER_DIST = path.join(APP_ROOT, "dist");const HEADLESS = process.env["HEADLESS"] === "true";// Asset base URL for renderer (wallpapers, etc.). Packaged: extraResources copies-// public/wallpapers -> resources/wallpapers. Unpackaged: <appRoot>/public/.+// public/wallpapers to resources/wallpapers. Unpackaged: <appRoot>/public/.const ASSET_BASE_DIR = process.defaultApp? path.join(__dirname, "..", "public"): process.resourcesPath;@@ -44,11 +44,9 @@ ipcMain.on("hud-overlay-move-by", (_event, deltaX: number, deltaY: number) => {hudOverlayWindow.setPosition(Math.round(x + deltaX), Math.round(y + deltaY), false);});-// Resize the HUD to fit its rendered content (the renderer measures the bar and-// its popups). The window is anchored by its bottom-centre so it stays put — and-// respects wherever the user dragged it — while only growing/shrinking. This is-// what lets the vertical tray layout become tall instead of scrolling inside a-// fixed-height window.+// Resize the HUD to fit its rendered content. Anchored by its bottom-centre so it+// stays where the user dragged it while only growing/shrinking, which lets the+// vertical tray layout grow tall instead of scrolling inside a fixed window.ipcMain.on("hud-overlay-set-size", (_event, width: number, height: number) => {if (!hudOverlayWindow ||@@ -61,9 +59,8 @@ ipcMain.on("hud-overlay-set-size", (_event, width: number, height: number) => {const bounds = hudOverlayWindow.getBounds();- // Clamp to the work area of the display the HUD currently sits on. The renderer- // reports the bar's natural size; on a short screen the vertical layout can be- // taller than the display, in which case the bar's own overflow scroll takes over.+ // Clamp to the work area of the display the HUD sits on; on a short screen the+ // vertical layout can exceed the display, where the bar's own overflow scroll takes over.const { workArea } = screen.getDisplayMatching(bounds);const nextWidth = Math.min(workArea.width, Math.max(1, Math.round(width)));const nextHeight = Math.min(workArea.height, Math.max(1, Math.round(height)));@@ -84,9 +81,8 @@ ipcMain.on("hud-overlay-set-size", (_event, width: number, height: number) => {});/**- * Creates the always-on-top HUD overlay window centred at the bottom of the- * primary display. The window is frameless, transparent, and follows the user- * across macOS Spaces so it is never lost when switching virtual desktops.+ * Frameless transparent HUD overlay, always-on-top, centred at the bottom of the+ * primary display. Follows the user across macOS Spaces so it isn't lost on switch.*/export function createHudOverlayWindow(): BrowserWindow {const primaryDisplay = screen.getPrimaryDisplay();@@ -101,21 +97,19 @@ export function createHudOverlayWindow(): BrowserWindow {const win = new BrowserWindow({width: windowWidth,height: windowHeight,- // Min/max are intentionally loose: the renderer resizes the window to fit- // its content via the "hud-overlay-set-size" channel (see above), which is- // required for the vertical tray layout to grow taller than the default.+ // Min/max are intentionally loose: the renderer resizes to fit content via+ // "hud-overlay-set-size" (above), needed for the vertical tray to grow taller.minWidth: 120,minHeight: 80,x: x,y: y,frame: false,transparent: true,- // Fully-transparent ARGB backing. Without this, macOS falls back to an- // opaque/translucent window material and draws it as a rounded glass panel- // with a border around the HUD content.+ // Fully-transparent ARGB backing. Without this macOS draws the window as a+ // rounded glass panel with a border around the HUD content.backgroundColor: "#00000000",- // Don't let macOS mask the (transparent) window into a rounded rect — the- // HUD bar provides its own rounding; the window itself must be invisible.+ // Don't let macOS mask the window into a rounded rect; the HUD bar provides+ // its own rounding and the window itself must be invisible.roundedCorners: false,resizable: false,alwaysOnTop: true,@@ -132,14 +126,14 @@ export function createHudOverlayWindow(): BrowserWindow {});win.setIgnoreMouseEvents(true, { forward: true });- // Follow the user across macOS Spaces (virtual desktops).- // Without this the HUD stays pinned to the Space it was first opened on.+ // Follow the user across macOS Spaces, else the HUD stays pinned to the Space+ // it was first opened on.if (process.platform === "darwin") {win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });}- // Show only once content is painted — prevents the black rectangle flash- // that appears when a transparent window is shown before its first paint.+ // Show only once painted to avoid the black rectangle flash when a transparent+ // window is shown before its first paint.win.once("ready-to-show", () => {if (!HEADLESS) win.show();});@@ -168,8 +162,8 @@ export function createHudOverlayWindow(): BrowserWindow {}/**- * Creates the main editor window. Starts maximised with a hidden title bar on- * macOS. This window is not always-on-top and appears in the taskbar/dock.+ * Main editor window. Starts maximised with a hidden title bar on macOS; not+ * always-on-top and appears in the taskbar/dock.*/export function createEditorWindow(): BrowserWindow {const isMac = process.platform === "darwin";@@ -200,16 +194,15 @@ export function createEditorWindow(): BrowserWindow {},});- // Maximize the window by defaultwin.maximize();- // Show only once content is painted — prevents white flash on cold Vite start.+ // Show only once painted to avoid a white flash on cold Vite start.win.once("ready-to-show", () => {if (!HEADLESS) win.show();});- // Inject dark background before any React paint so the sub-titlebar area- // never flashes white even on the very first cold Vite load.+ // Inject dark background before any React paint so the sub-titlebar area never+ // flashes white on a cold Vite load.win.webContents.on("dom-ready", () => {win.webContents.insertCSS("html, body, #root { background: #09090b !important; }").catch(() => {// Best-effort cosmetic; ignore if the page is mid-teardown.@@ -232,8 +225,8 @@ export function createEditorWindow(): BrowserWindow {}/**- * Creates the floating source-selector window used to pick a screen or window- * to record. Frameless, transparent, and follows the user across macOS Spaces.+ * Floating source-selector window for picking a screen or window to record.+ * Frameless, transparent, and follows the user across macOS Spaces.*/export function createSourceSelectorWindow(): BrowserWindow {const { width, height } = screen.getPrimaryDisplay().workAreaSize;@@ -258,8 +251,8 @@ export function createSourceSelectorWindow(): BrowserWindow {},});- // Follow the user across macOS Spaces so the selector appears on the- // active desktop regardless of where the HUD was originally opened.+ // Follow the user across macOS Spaces so the selector appears on the active+ // desktop regardless of where the HUD was opened.if (process.platform === "darwin") {win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });}@@ -276,8 +269,8 @@ export function createSourceSelectorWindow(): BrowserWindow {}/**- * Creates a centered transparent countdown overlay window that sits above the- * HUD while recording pre-roll is running.+ * Centered transparent countdown overlay that sits above the HUD during+ * recording pre-roll.*/export function createCountdownOverlayWindow(): BrowserWindow {const { workArea } = screen.getPrimaryDisplay();diff --git a/scripts/before-pack.cjs b/scripts/before-pack.cjsindex 0242e39cf..934756a4d 100644--- a/scripts/before-pack.cjs+++ b/scripts/before-pack.cjs@@ -1,7 +1,7 @@// electron-builder beforePack hook: ensure the auto-caption assets (Whisper model + ORT wasm) exist-// before packaging, so the `caption-assets` extraResources entry has something to copy. Runs for-// every package invocation — local `npm run build:*` and CI's bare `electron-builder` alike. The-// fetch script is idempotent, so this is a no-op once the assets are present.+// before packaging, so the `caption-assets` extraResources entry has something to copy. Runs on+// every package invocation (local `npm run build:*` and CI's bare `electron-builder`). The fetch+// script is idempotent, so it's a no-op once the assets are present.const { execFileSync } = require("node:child_process");const path = require("node:path");diff --git a/scripts/fetch-caption-model.mjs b/scripts/fetch-caption-model.mjsindex bf72e1145..87af07f34 100644--- a/scripts/fetch-caption-model.mjs+++ b/scripts/fetch-caption-model.mjs@@ -1,12 +1,11 @@-// Populates `caption-assets/` with everything the auto-caption worker needs at runtime so the-// packaged app can transcribe fully offline (under file://), instead of fetching the Whisper model-// from HuggingFace and the onnxruntime wasm from a CDN.+// Populates `caption-assets/` so the packaged app can transcribe offline (under file://)+// instead of fetching the Whisper model from HuggingFace and the onnxruntime wasm from a CDN.//// caption-assets/// models/Xenova/whisper-tiny/... ← downloaded from HuggingFace (config + quantized ONNX)// ort/ort-wasm*.wasm ← copied from @xenova/transformers/dist//-// Idempotent: existing, non-empty files are left alone, so re-runs (and CI cache hits) are no-ops.+// Idempotent: existing non-empty files are left alone, so re-runs and CI cache hits are no-ops.// `caption-assets/` is gitignored and shipped via electron-builder `extraResources`.import { createWriteStream } from "node:fs";@@ -21,9 +20,9 @@ const OUT = path.join(ROOT, "caption-assets");const MODEL_ID = "Xenova/whisper-tiny";const HF_BASE = `https://huggingface.co/${MODEL_ID}/resolve/main`;-// Config/tokenizer/preprocessor files (all small) plus the quantized ONNX the ASR pipeline loads by-// default (encoder + merged decoder). We grab all the small metadata files so transformers never-// requests one we forgot to bundle.+// Small config/tokenizer/preprocessor files plus the quantized ONNX the ASR pipeline loads by+// default (encoder + merged decoder). Grab every metadata file so transformers never requests+// one we forgot to bundle.const MODEL_FILES = ["config.json","generation_config.json",@@ -69,8 +68,8 @@ async function download(url, dest) {async function copyOrtWasm() {const distDir = path.join(ROOT, "node_modules", "@xenova", "transformers", "dist");- // Non-threaded variants only — the worker runs ORT with numThreads=1 (SharedArrayBuffer isn't- // available under file://), so the threaded wasm is never loaded. Saves ~20MB.+ // Non-threaded variants only: the worker runs ORT with numThreads=1 (no SharedArrayBuffer+ // under file://), so the threaded wasm is never loaded. Saves ~20MB.const wasm = ["ort-wasm.wasm", "ort-wasm-simd.wasm"];const ortOut = path.join(OUT, "ort");await mkdir(ortOut, { recursive: true });diff --git a/src/components/launch/LaunchWindow.tsx b/src/components/launch/LaunchWindow.tsxindex def30ff75..a93514c5a 100644--- a/src/components/launch/LaunchWindow.tsx+++ b/src/components/launch/LaunchWindow.tsx@@ -37,11 +37,9 @@ import { openSourceSelectorWithPermissionRetry } from "./openSourceSelectorFlow"const ICON_SIZE = 20;-// Gap (px) between the top of the bar and the device-selector popups in the-// vertical tray layout: the bar's `bottom-5` offset (20px) plus an 8px gap.+// Vertical tray gap (px): bar's `bottom-5` (20px) plus an 8px gap.const HUD_DEVICE_POPUP_GAP = 28;-// Distance (px) of the device-selector popups from the window bottom in the-// horizontal layout. Mirrors the `bottom-[68px]` utility class on that element.+// Horizontal layout: mirrors the `bottom-[68px]` class on the popup element.const HUD_DEVICE_POPUP_HORIZONTAL_BOTTOM = 68;const ICON_CONFIG = {@@ -149,8 +147,7 @@ export function LaunchWindow() {const languageMenuPanelRef = useRef<HTMLDivElement | null>(null);const hudBarRef = useRef<HTMLDivElement | null>(null);const deviceSelectorRef = useRef<HTMLDivElement | null>(null);- // Measured height of the HUD bar, used to anchor the device-selector popups- // directly above the (potentially tall) vertical tray instead of overlapping it.+ // Measured bar height, anchors the popups above the tall vertical tray so they don't overlap it.const [hudBarHeight, setHudBarHeight] = useState(0);const [languageMenuStyle, setLanguageMenuStyle] = useState<{right: number;@@ -303,45 +300,35 @@ export function LaunchWindow() {return () => cancelAnimationFrame(id);}, [isLanguageMenuOpen]);- // Resize the HUD overlay window to fit its rendered content. Without this the- // window stays at its fixed default size, so the vertical tray layout (which is- // much taller than the horizontal one) gets clipped and forces scrolling. We- // measure relative to the window's bottom-centre — the anchor the main process- // preserves — so the elements' fixed bottom/centre offsets keep this stable and- // it never oscillates.+ // Resize the overlay window to fit content, else the taller vertical tray gets clipped+ // and scrolls. Measure from the window's bottom-centre (the anchor the main process+ // preserves) so fixed bottom/centre offsets keep this stable and it doesn't oscillate.const lastHudSizeRef = useRef({ width: 0, height: 0 });const measureHudSize = useCallback(() => {const barEl = hudBarRef.current;if (!barEl || !window.electronAPI?.setHudOverlaySize) return;- // Breathing room so the bar's drop shadow isn't clipped and content isn't- // flush against the edge. TOP_MARGIN must also exceed the slack in the bar's- // `max-h: calc(100vh - 2.5rem)` cap (40px reserved − 20px bottom gap = 20px)- // so the window is always tall enough for that cap not to engage and trigger- // an unwanted scrollbar.+ // Breathing room so the drop shadow isn't clipped. TOP_MARGIN must also exceed the+ // slack in the bar's `max-h: calc(100vh - 2.5rem)` cap (40px reserved - 20px bottom+ // gap = 20px) so the window stays tall enough that the cap never engages and adds a scrollbar.const SIDE_MARGIN = 24;const TOP_MARGIN = 24;- // Keep the window wide enough that the language menu (11rem) never clips,- // even when the bar itself is narrow (vertical layout, no popups open).+ // Wide enough that the language menu (11rem) never clips, even when the bar is narrow.const MIN_WIDTH = 220;const viewportHeight = window.innerHeight;const centerX = window.innerWidth / 2;- // The bar is measured by its *natural* (scroll) size, not its clipped box: in- // vertical mode it carries a `max-h` + overflow cap as a small-screen- // fallback, and reading the clipped height would pin the window to that cap- // and never let it grow. scrollHeight reports the full content height (the cap- // then only engages when the main process clamps the window to the screen).+ // Use natural (scroll) size, not the clipped box: vertical mode's max-h cap is a+ // small-screen fallback, and reading clipped height would pin the window to it.+ // scrollHeight gives full content height; the cap only engages when the main process clamps to screen.let topFromBottom = viewportHeight - barEl.getBoundingClientRect().bottom + barEl.scrollHeight;let halfWidth = barEl.scrollWidth / 2;- // Device-selector popups also drive both dimensions. Their vertical anchor- // depends on the bar height (they sit above the tall vertical tray), which is- // fed back through React state and lags the bar by a frame. So we derive- // their top edge analytically from the bar's natural height instead of from- // their (stale) rendered position — that keeps a single measurement pass- // authoritative and avoids a feedback re-measure.+ // Popups drive both dimensions too. Their vertical anchor depends on bar height,+ // which is fed back through React state and lags by a frame, so derive their top+ // edge from the bar's natural height instead of the stale rendered position. Keeps+ // one measurement pass authoritative and avoids a feedback re-measure.if (deviceSelectorRef.current) {const rect = deviceSelectorRef.current.getBoundingClientRect();if (rect.width !== 0 || rect.height !== 0) {@@ -354,9 +341,8 @@ export function LaunchWindow() {}}- // The language menu scrolls within the available height, so it only needs to- // influence width (not grow the window to the full height). Its presence in- // the DOM means it is open.+ // The language menu scrolls within available height, so it only influences width.+ // Its presence in the DOM means it's open.if (languageMenuPanelRef.current) {const rect = languageMenuPanelRef.current.getBoundingClientRect();halfWidth = Math.max(halfWidth, centerX - rect.left, rect.right - centerX);@@ -376,9 +362,8 @@ export function LaunchWindow() {window.electronAPI.setHudOverlaySize(width, height);}, [trayLayout]);- // A single persistent observer; elements wire themselves up via callback refs as- // they mount/unmount (device popups, language menu) so the measurement re-runs- // without recreating the observer or threading mount state through effect deps.+ // One persistent observer; elements wire themselves up via callback refs as they+ // mount/unmount so measurement re-runs without recreating it or threading mount state through deps.const hudResizeObserverRef = useRef<ResizeObserver | null>(null);useEffect(() => {const observer = new ResizeObserver(() => measureHudSize());@@ -515,10 +500,8 @@ export function LaunchWindow() {};return (- // Root fills the HUD window only. Avoid w-screen/h-screen (100vw/100vh):- // 100vw can exceed the inner layout width when scrollbars affect the- // viewport (notably on Windows), causing a horizontal scrollbar once the- // recording toolbar widened (issue #305).+ // Avoid w-screen/h-screen: 100vw can exceed the inner layout width when scrollbars+ // affect the viewport (Windows), causing a horizontal scrollbar (issue #305).<divclassName={`h-full w-full min-w-0 max-w-full overflow-x-hidden overflow-y-hidden bg-transparent ${styles.electronDrag}`}onPointerMove={(event) => {@@ -570,7 +553,7 @@ export function LaunchWindow() {</div>)}- {/* Device selectors — fixed above HUD bar, viewport-relative, never clipped */}+ {/* Device selectors, fixed above HUD bar, viewport-relative, never clipped */}{(showMicControls || showWebcamControls) && (<divref={setDeviceSelectorEl}@@ -578,8 +561,8 @@ export function LaunchWindow() {className={`fixed left-1/2 -translate-x-1/2 flex items-center gap-2 animate-mic-panel-in ${trayLayout === "vertical" ? "" : "bottom-[68px]"} ${styles.electronNoDrag}`}style={trayLayout === "vertical"- ? // Sit above the top of the (tall) vertical tray, anchored to the- // measured bar height. Matches the analytic offset in measureHudSize.+ ? // Sit above the tall vertical tray, anchored to the measured bar+ // height. Matches the offset in measureHudSize.{ bottom: hudBarHeight + HUD_DEVICE_POPUP_GAP }: undefined}@@ -713,7 +696,7 @@ export function LaunchWindow() {</div>)}- {/* HUD bar — fixed at bottom center, viewport-relative, never moves */}+ {/* HUD bar, fixed at bottom center, viewport-relative, never moves */}<divref={setHudBarEl}data-hud-interactive="true"diff --git a/src/components/ui/color-picker.tsx b/src/components/ui/color-picker.tsxindex d8ec2b33c..72f0135e2 100644--- a/src/components/ui/color-picker.tsx+++ b/src/components/ui/color-picker.tsx@@ -46,8 +46,7 @@ export default function ColorPicker(props: ColorPickerProps) {return "#ffffff";};- // Normalize the hex input.- // Adds a # at the beginning of the input if it's not there.+ // Prefix a # when the user typed a bare hex value.const normalizeHexDraft = (raw: string) => {const trimmed = raw.trim();if (trimmed === "") return "";@@ -58,8 +57,7 @@ export default function ColorPicker(props: ColorPickerProps) {const handleColorInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {const normalized = normalizeHexDraft(e.target.value);setHexInput(normalized);- // Check if the normalized hex is a valid hex color.- // It should follow the format #RRGGBB or #RGB.+ // Only push when it's a complete #RGB or #RRGGBB value.const isValidHexColor =/^#[0-9A-Fa-f]{3}$/.test(normalized) || /^#[0-9A-Fa-f]{6}$/.test(normalized);if (isValidHexColor) {diff --git a/src/components/video-editor/AddCustomFontDialog.tsx b/src/components/video-editor/AddCustomFontDialog.tsxindex 9ab9ce3da..872559d28 100644--- a/src/components/video-editor/AddCustomFontDialog.tsx+++ b/src/components/video-editor/AddCustomFontDialog.tsx@@ -36,7 +36,6 @@ export function AddCustomFontDialog({ onFontAdded }: AddCustomFontDialogProps) {const handleImportUrlChange = (url: string) => {setImportUrl(url);- // Auto-extract font name if valid Google Fonts URLif (isValidGoogleFontsUrl(url)) {const extracted = parseFontFamilyFromImport(url);if (extracted && !fontName) {@@ -46,7 +45,6 @@ export function AddCustomFontDialog({ onFontAdded }: AddCustomFontDialogProps) {};const handleAdd = async () => {- // Validate inputsif (!importUrl.trim()) {toast.error(t("customFont.errorEmptyUrl"));return;@@ -65,7 +63,6 @@ export function AddCustomFontDialog({ onFontAdded }: AddCustomFontDialogProps) {setLoading(true);try {- // Extract font family from URLconst fontFamily = parseFontFamilyFromImport(importUrl);if (!fontFamily) {toast.error(t("customFont.errorExtractFailed"));@@ -73,7 +70,6 @@ export function AddCustomFontDialog({ onFontAdded }: AddCustomFontDialogProps) {return;}- // Create custom font objectconst newFont: CustomFont = {id: generateFontId(fontName),name: fontName.trim(),@@ -81,17 +77,15 @@ export function AddCustomFontDialog({ onFontAdded }: AddCustomFontDialogProps) {importUrl: importUrl.trim(),};- // Add font (this will load and verify it) - throws if it fails+ // Loads and verifies the font; throws on failureawait addCustomFont(newFont);- // Notify parentif (onFontAdded) {onFontAdded(newFont);}toast.success(t("customFont.successMessage", { fontName }));- // Reset and closesetImportUrl("");setFontName("");setOpen(false);diff --git a/src/components/video-editor/AnnotationOverlay.tsx b/src/components/video-editor/AnnotationOverlay.tsxindex 13d245b8a..09669d4e7 100644--- a/src/components/video-editor/AnnotationOverlay.tsx+++ b/src/components/video-editor/AnnotationOverlay.tsx@@ -48,7 +48,7 @@ interface AnnotationOverlayProps {onBlurDataCommit?: () => void;onClick: (id: string) => void;zIndex: number;- isSelectedBoost: boolean; // Boost z-index when selected for easy editing+ isSelectedBoost: boolean; // raise z-index when selected, for easier editingpreviewSourceCanvas?: PreviewCanvasSource | null;previewFrameVersion?: number;currentTimeMs: number;@@ -537,7 +537,7 @@ export function AnnotationOverlay({const yPercent = (d.y / containerHeight) * 100;onPositionChange(annotation.id, { x: xPercent, y: yPercent });- // Reset dragging flag after a short delay to prevent click event+ // Delay clearing so the trailing click doesn't fire onClicksetTimeout(() => {isDraggingRef.current = false;}, 100);@@ -576,7 +576,7 @@ export function AnnotationOverlay({"ring-2 ring-[#34B27B] ring-offset-2 ring-offset-transparent",)}style={{- zIndex: isSelectedBoost ? zIndex + 1000 : zIndex, // Boost selected annotation to ensure it's on top+ zIndex: isSelectedBoost ? zIndex + 1000 : zIndex, // keep the selected annotation on toppointerEvents: isSelected ? "auto" : "none",border:isSelected && annotation.type !== "blur" ? "2px solid rgba(52, 178, 123, 0.8)" : "none",diff --git a/src/components/video-editor/AnnotationSettingsPanel.tsx b/src/components/video-editor/AnnotationSettingsPanel.tsxindex 4fe3f505e..f98c4cc11 100644--- a/src/components/video-editor/AnnotationSettingsPanel.tsx+++ b/src/components/video-editor/AnnotationSettingsPanel.tsx@@ -108,7 +108,6 @@ export function AnnotationSettingsPanel({const getFontLabel = (font: (typeof FONT_FAMILIES)[number]) =>font.labelKey ? fontStyleLabels[font.labelKey] : font.name;- // Load custom fonts on mountuseEffect(() => {setCustomFonts(getCustomFonts());}, []);@@ -138,7 +137,6 @@ export function AnnotationSettingsPanel({const file = files[0];- // Validate file typeconst validTypes = ["image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp"];if (!validTypes.includes(file.type)) {toast.error(t("annotation.invalidImageType"), {diff --git a/src/components/video-editor/ArrowSvgs.tsx b/src/components/video-editor/ArrowSvgs.tsxindex 99c542ff7..5078b844e 100644--- a/src/components/video-editor/ArrowSvgs.tsx+++ b/src/components/video-editor/ArrowSvgs.tsx@@ -7,9 +7,7 @@ interface ArrowSvgProps {}/**- * Inline SVG arrow components for 8 directions.- * These match the visual style of the previous icon-based arrows but use- * pure SVG paths for easy replication in export.+ * Inline SVG arrows for 8 directions. Pure paths (not icon fonts) so export can replicate them.*/export function ArrowUp({ color, strokeWidth, className }: ArrowSvgProps) {diff --git a/src/components/video-editor/EditorEmptyState.tsx b/src/components/video-editor/EditorEmptyState.tsxindex f8e4632d6..2a5c49547 100644--- a/src/components/video-editor/EditorEmptyState.tsx+++ b/src/components/video-editor/EditorEmptyState.tsx@@ -7,7 +7,7 @@ import { nativeBridgeClient } from "@/native";interface EditorEmptyStateProps {onVideoImported: (videoPath: string) => void;- /** Called with the loaded project data — handles both button click and drag-drop */+ /** Called with the loaded project data; handles both button click and drag-drop */onProjectOpened: (project: unknown, path: string | null) => void;}@@ -18,8 +18,8 @@ export function EditorEmptyState({ onVideoImported, onProjectOpened }: EditorEmpconst tc = useScopedT("common");const [isDraggingOver, setIsDraggingOver] = useState(false);const [dropError, setDropError] = useState<DropError>(null);- // Freeze the last non-null error type so dialog content doesn't snap to the- // else-branch during the closing animation (same pattern as UnsavedChangesDialog).+ // Freeze the last non-null error type so dialog content doesn't snap to the else-branch+ // during the closing animation (same pattern as UnsavedChangesDialog).const lastDropErrorRef = useRef<Exclude<DropError, null>>("unsupported-format");if (dropError !== null) {lastDropErrorRef.current = dropError;@@ -74,7 +74,7 @@ export function EditorEmptyState({ onVideoImported, onProjectOpened }: EditorEmpreturn;}- // Use Electron's webUtils.getPathForFile — File.path was removed in Electron 32++ // Use Electron's webUtils.getPathForFile; File.path was removed in Electron 32+let filePath: string;try {filePath = window.electronAPI.getPathForFile(projectFile);diff --git a/src/components/video-editor/ExportDialog.tsx b/src/components/video-editor/ExportDialog.tsxindex 203228909..44eae5d2e 100644--- a/src/components/video-editor/ExportDialog.tsx+++ b/src/components/video-editor/ExportDialog.tsx@@ -30,14 +30,13 @@ export function ExportDialog({const t = useScopedT("dialogs");const [showSuccess, setShowSuccess] = useState(false);- // Reset showSuccess when a new export starts or dialog reopensuseEffect(() => {if (isExporting) {setShowSuccess(false);}}, [isExporting]);- // Reset showSuccess when dialog opens fresh+ // Reset when the dialog opens fresh (not mid-export).useEffect(() => {if (isOpen && !isExporting && !progress) {setShowSuccess(false);@@ -59,13 +58,12 @@ export function ExportDialog({const formatLabel = exportFormat === "gif" ? "GIF" : "Video";- // Determine if we're in the compiling phase (frames done but still exporting)+ // Compiling phase: frames are done but the export is still finishing.const isCompiling =isExporting && progress && progress.percentage >= 100 && exportFormat === "gif";const isFinalizing = progress?.phase === "finalizing";const renderProgress = progress?.renderProgress;- // Get status message based on phaseconst getStatusMessage = () => {if (error) return t("export.tryAgain");if (isCompiling || isFinalizing) {@@ -80,7 +78,6 @@ export function ExportDialog({return t("export.takeMoment");};- // Get title based on phaseconst getTitle = () => {if (error) return t("export.failed");if (isFinalizing && exportFormat === "mp4") return t("export.finalizingVideoTitle");@@ -194,7 +191,7 @@ export function ExportDialog({</div><div className="h-2 bg-white/5 rounded-full overflow-hidden border border-white/5">{isCompiling || isFinalizing ? (- // Show render progress if available, otherwise animated indeterminate bar+ // Real progress if we have it, otherwise an indeterminate bar.renderProgress !== undefined && renderProgress > 0 ? (<divclassName="h-full bg-[#34B27B] shadow-[0_0_10px_rgba(52,178,123,0.3)] transition-all duration-300 ease-out"diff --git a/src/components/video-editor/SettingsPanel.tsx b/src/components/video-editor/SettingsPanel.tsxindex 09ceb49f6..b9cc7628c 100644--- a/src/components/video-editor/SettingsPanel.tsx+++ b/src/components/video-editor/SettingsPanel.tsx@@ -174,10 +174,8 @@ function ZoomFocusCoordInput({disabled?: boolean;ariaLabel: string;}) {- // While the input is focused (user is editing), show their draft text- // so partial entries like "5" or "" don't get overwritten by re-renders.- // When not focused, mirror the live prop value so external changes- // (dragging the overlay on the preview) update the displayed number in real time.+ // While focused, show the draft so partial entries like "5" or "" survive re-renders.+ // While not focused, mirror the live prop so overlay drags update the number live.const [draft, setDraft] = useState<string | null>(null);const display = percent.toFixed(1);@@ -490,12 +488,11 @@ export function SettingsPanel({const t = useScopedT("settings");const [activePanelMode, setActivePanelMode] = useState<SettingsPanelMode>("background");const sourceDimensions = formatSourceDimensions(videoElement, cropRegion);- // Resolved URLs are for DOM rendering only (backgroundImage). The canonical- // `/wallpapers/wallpaperN.jpg` form in WALLPAPER_PATHS is what gets persisted- // on click — never the machine-specific file:// URL.+ // Resolved URLs are for DOM rendering only. We persist the canonical+ // `/wallpapers/wallpaperN.jpg` form from WALLPAPER_PATHS, never the file:// URL.const wallpaperPreviewUrls = useMemo(() => WALLPAPER_PATHS.map(resolveImageWallpaperUrl), []);- // "Default" (built-in art) plus each bundled cursor theme. Preview thumbnails use- // the theme's arrow asset; the persisted/selected value is the theme id.+ // Built-in "Default" plus each bundled theme. Thumbnails use the theme's arrow asset;+ // the persisted value is the theme id.const cursorThemeOptions = useMemo(() => [{@@ -731,13 +728,12 @@ export function SettingsPanel({const handleRemoveCustomImage = (imageUrl: string, event: React.MouseEvent) => {event.stopPropagation();setCustomImages((prev) => prev.filter((img) => img !== imageUrl));- // If the removed image was selected, clear selection+ // If the removed image was selected, reset to the first wallpaper.if (selected === imageUrl) {onWallpaperChange(WALLPAPER_PATHS[0]);}};- // Find selected annotationconst selectedAnnotation = selectedAnnotationId? annotationRegions.find((a) => a.id === selectedAnnotationId): null;@@ -781,7 +777,7 @@ export function SettingsPanel({</div>);- // If an annotation is selected, show annotation settings instead+ // Annotation selected: show its settings panel instead.if (selectedAnnotation &&onAnnotationContentChange &&diff --git a/src/components/video-editor/VideoEditor.tsx b/src/components/video-editor/VideoEditor.tsxindex 91a9fa5bb..445a09060 100644--- a/src/components/video-editor/VideoEditor.tsx+++ b/src/components/video-editor/VideoEditor.tsx@@ -115,7 +115,7 @@ import {import { UnsavedChangesDialog } from "./UnsavedChangesDialog";import VideoPlayback, { VideoPlaybackRef } from "./VideoPlayback";-/** Single Sonner slot for auto-caption progress so phases update in place instead of stacking. */+/** Single Sonner slot so auto-caption phases update in place instead of stacking. */const AUTO_CAPTION_PROGRESS_TOAST_ID = "auto-caption-progress";function isClickInteractionType(interactionType: string | null | undefined) {@@ -211,7 +211,7 @@ export default function VideoEditor() {webcamPosition,} = editorState;- // ── Non-undoable state+ // Non-undoable stateconst [videoPath, setVideoPath] = useState<string | null>(null);const [videoSourcePath, setVideoSourcePath] = useState<string | null>(null);const [webcamVideoPath, setWebcamVideoPath] = useState<string | null>(null);@@ -255,8 +255,8 @@ export default function VideoEditor() {} | null>(null);const [isFullscreen, setIsFullscreen] = useState(false);const [showCloseConfirmDialog, setShowCloseConfirmDialog] = useState(false);- // Unsaved-changes confirmation for New Project / Load Project actions.- // (The window-close flow uses showCloseConfirmDialog above.)+ // Unsaved-changes confirmation for New Project / Load Project.+ // The window-close flow uses showCloseConfirmDialog above.const [confirmDialogVariant, setConfirmDialogVariant] = useState<"newProject" | "loadProject" | null>(null);@@ -301,9 +301,9 @@ export default function VideoEditor() {const nextSpeedIdRef = useRef(1);const { shortcuts, isMac } = useShortcuts();- // Native Windows recordings include captured cursor assets. Native macOS- // recordings hide the system cursor in ScreenCaptureKit and use telemetry- // samples with OpenScreen's default arrow asset for the editable overlay.+ // Windows recordings include captured cursor assets. macOS hides the system+ // cursor in ScreenCaptureKit and renders telemetry samples with OpenScreen's+ // default arrow asset for the editable overlay.const hasEditableCursorRecording =recordingCursorCaptureMode === "editable-overlay" &&(nativePlatform === "win32" || nativePlatform === "darwin") &&@@ -394,7 +394,7 @@ export default function VideoEditor() {setRecordingCursorCaptureMode(projectCursorCaptureMode);setCurrentProjectPath(path ?? null);- // A loaded project keeps its zooms exactly as saved — never auto-suggest+ // A loaded project keeps its zooms exactly as saved, so never auto-suggest// over it (even if it has zero zooms because the user deleted them all).autoProcessedSourceRef.current = sourcePath;@@ -589,8 +589,8 @@ export default function VideoEditor() {createProjectSnapshot({ screenVideoPath: result.path }, INITIAL_EDITOR_STATE),);}- // No video/project/session — leave videoPath null so the- // EditorEmptyState dashboard renders instead of an error screen.+ // No video/project/session, so leave videoPath null and let the+ // EditorEmptyState dashboard render instead of an error screen.} catch (err) {setError("Error loading video: " + String(err));} finally {@@ -601,8 +601,7 @@ export default function VideoEditor() {loadInitialData();}, [applyLoadedProject]);- // Track whether user preferences have been loaded to avoid- // overwriting saved prefs with defaults on the first render+ // Avoid overwriting saved prefs with defaults before they've loaded.const [prefsHydrated, setPrefsHydrated] = useState(false);// Load persisted user preferences on mount (intentionally runs once)@@ -671,8 +670,8 @@ export default function VideoEditor() {.split(/[\\/]/).pop()?.replace(/\.[^.]+$/, "") || `project-${Date.now()}`;- // Match the normalization path used by `currentProjectSnapshot` so the- // post-save baseline compares equal and `hasUnsavedChanges` clears.+ // Normalize the same way as currentProjectSnapshot so the post-save+ // baseline compares equal and hasUnsavedChanges clears.const projectSnapshot = createProjectSnapshot(currentProjectMedia, editorState);const result = await nativeBridgeClient.project.saveProjectFile(projectData,@@ -1021,7 +1020,7 @@ export default function VideoEditor() {depth: DEFAULT_ZOOM_DEPTH,customScale: ZOOM_DEPTH_SCALES[DEFAULT_ZOOM_DEPTH],focus: { cx: 0.5, cy: 0.5 },- // Auto-Focus toggle on → new zooms follow the cursor too.+ // Auto-Focus on means new zooms follow the cursor too.focusMode: autoFocusAll ? "auto" : undefined,source: "manual",};@@ -1035,9 +1034,8 @@ export default function VideoEditor() {[pushState, autoFocusAll],);- // Builds fresh "auto" zoom regions from cursor telemetry, avoiding overlap with- // the regions already present. Used by both the on-load auto-suggest pass and- // the magic-wand toggle.+ // Builds fresh "auto" zoom regions from cursor telemetry without overlapping+ // existing ones. Used by both the on-load auto-suggest pass and the wand toggle.const buildAutoZoomRegions = useCallback((existingRegions: ZoomRegion[]): ZoomRegion[] => {const totalMs = Math.round(duration * 1000);@@ -1063,8 +1061,7 @@ export default function VideoEditor() {// Auto-suggest zooms once per fresh recording (no existing zooms, telemetry// available, wand enabled). Loaded projects are marked processed elsewhere so- // they're never touched. The ref guard makes this run exactly once per source- // and survive undo.+ // they're never touched. The ref guard runs this once per source and survives undo.const autoProcessedSourceRef = useRef<string | null>(null);useEffect(() => {if (!autoZoomEnabled || !cursorTelemetrySourcePath) return;@@ -1089,8 +1086,8 @@ export default function VideoEditor() {pushState,]);- // Magic-wand toggle: ON regenerates suggestions around existing zooms; OFF- // removes only untouched auto zooms (manual + edited-to-manual survive).+ // Wand toggle: ON regenerates suggestions around existing zooms; OFF removes+ // only untouched auto zooms (manual and edited-to-manual survive).const handleToggleAutoZoom = useCallback((enabled: boolean) => {if (enabled) {@@ -1109,8 +1106,7 @@ export default function VideoEditor() {[pushState, buildAutoZoomRegions, cursorTelemetrySourcePath],);- // Global Auto-Focus toggle: flip every zoom between auto (cursor-follow) and- // manual at once.+ // Flip every zoom between auto (cursor-follow) and manual at once.const handleToggleAutoFocusAll = useCallback((on: boolean) => {pushState((prev) => ({@@ -1177,7 +1173,7 @@ export default function VideoEditor() {[pushState],);- // Focus drag: updateState for live preview, commitState on pointer-up+ // Focus drag: updateState for live preview, commitState on pointer-up.const handleZoomFocusChange = useCallback((id: string, focus: ZoomFocus) => {updateState((prev) => ({@@ -1704,7 +1700,7 @@ export default function VideoEditor() {}if (matchesShortcut(e, shortcuts.playPause, isMac)) {- // Allow space only in inputs/textareas+ // Let space pass through inside inputs/textareas.if (isInput) {return;}@@ -1840,9 +1836,8 @@ export default function VideoEditor() {return;}- // Ask the user where to save BEFORE starting the export. This avoids the- // post-export save dialog getting hidden behind other windows after a- // long-running export.+ // Pick the save path before exporting, otherwise the save dialog can end up+ // hidden behind other windows after a long-running export.const isGifFormat = settings.format === "gif";const targetFileName = `export-${Date.now()}.${isGifFormat ? "gif" : "mp4"}`;const pickResult = await window.electronAPI.pickExportSavePath(@@ -1878,7 +1873,7 @@ export default function VideoEditor() {? getNativeAspectRatioValue(sourceWidth, sourceHeight, cropRegion): getAspectRatioValue(aspectRatio);- // Get preview CONTAINER dimensions for scaling+ // Preview container dimensions, used for scaling.const playbackRef = videoPlaybackRef.current;const containerElement = playbackRef?.containerRef?.current;const previewWidth = containerElement?.clientWidth || DEFAULT_SOURCE_DIMENSIONS.width;@@ -2087,8 +2082,8 @@ export default function VideoEditor() {} finally {setIsExporting(false);exporterRef.current = null;- // Reset dialog state to ensure it can be opened again on next export- // This fixes the bug where second export doesn't show save dialog+ // Reset so the next export can reopen the dialog (second export+ // otherwise wouldn't show the save dialog).setShowExportDialog(false);setExportProgress(null);}@@ -2266,9 +2261,8 @@ export default function VideoEditor() {);let transcribedFromTrimmedBuffer = true;- // Some recordings come back empty after leading-silence trimming even though the full- // source has recognizable speech. Retry once against the untouched audio buffer before- // giving up so we do not show "no speech detected" for a spoken clip.+ // 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,@@ -2540,7 +2534,7 @@ export default function VideoEditor() {</div></div>- {/* Empty state — shown when no video is loaded */}+ {/* Empty state shown when no video is loaded */}{!videoPath && (<div className="flex-1 min-h-0 relative"><EditorEmptyStatediff --git a/src/components/video-editor/VideoPlayback.tsx b/src/components/video-editor/VideoPlayback.tsxindex d47dfc7d6..1b4ad5263 100644--- a/src/components/video-editor/VideoPlayback.tsx+++ b/src/components/video-editor/VideoPlayback.tsx@@ -145,8 +145,8 @@ interface VideoPlaybackProps {cursorClickBounce?: number;cursorClipToBounds?: boolean;cursorTheme?: string;- // When true, render the selected zoom at the playhead even while paused —- // lets the editor preview the zoom effect without leaving the focus-edit view.+ // Render the selected zoom at the playhead even while paused, so the editor can+ // preview the effect without leaving the focus-edit view.isPreviewingZoom?: boolean;}@@ -482,17 +482,8 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>([onDurationChange, syncResolvedDuration],);- // IMPORTANT: must use clampFocusToScale(focus, getZoomScale(region)) here,- // NOT clampFocusToStage(focus, region.depth).- //- // region.depth is the preset slot (1×/2×/4×) and ignores customScale entirely.- // getZoomScale(region) returns customScale when set, falling back to the preset- // depth scale — so drag-to-reposition respects the actual zoom level the user- // configured, not the preset bucket it sits in.- //- // This was previously broken (invisible drag boundaries near canvas edges) and- // has been fixed twice. If you're refactoring this drag handler, keep this call- // as clampFocusForRegion(focus, region) — do not switch it back to region.depth.+ // Clamp against getZoomScale(region), not region.depth: depth is just the preset+ // slot (1x/2x/4x) and ignores customScale, which gives wrong drag bounds near the edges.const clampFocusForRegion = useCallback((focus: ZoomFocus, region: ZoomRegion) => {return clampFocusToScale(focus, getZoomScale(region));}, []);@@ -506,7 +497,6 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(return;}- // Update stage size from overlay dimensionsconst stageWidth = overlayEl.clientWidth;const stageHeight = overlayEl.clientHeight;if (stageWidth && stageHeight) {@@ -861,8 +851,8 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(webcamReactiveZoomRef.current = webcamReactiveZoom;webcamLayoutPresetRef.current = webcamLayoutPreset;webcamPositionRef.current = webcamPosition;- // Clear any reactive transform the moment the effect is turned off or layout changes,- // so a stale shrink doesn't linger when the ticker isn't actively updating it.+ // Clear any reactive transform when the effect is turned off or layout changes,+ // so a stale shrink doesn't linger while the ticker isn't updating it.if (webcamWrapperRef.current &&(!webcamReactiveZoom || webcamLayoutPreset !== "picture-in-picture")@@ -934,10 +924,9 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(};}, [pixiReady, videoReady, layoutVideoContent]);- // Drop the PIXI canvas resolution to 1.0 while scrubbing (the user is- // navigating, not previewing) and restore native DPR on play/idle so the- // preview stays faithful. Mutating renderer.resolution per-frame would- // thrash texture uploads; we only do it on scrub-state transitions.+ // Drop canvas resolution to 1.0 while scrubbing and restore native DPR on play/idle.+ // Only on scrub-state transitions; mutating renderer.resolution per-frame thrashes+ // texture uploads.useEffect(() => {if (!pixiReady) return;const app = appRef.current;@@ -1323,8 +1312,8 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(motionBlurAmount: motionBlurAmountRef.current,transformOverride: transform,motionBlurState: motionBlurStateRef.current,- // Content time (not wall-clock) so camera motion-blur velocity matches export and is- // correct under speed regions; export passes the same content `timeMs` (frameRenderer).+ // Content time, not wall-clock, so motion-blur velocity matches export and stays+ // correct under speed regions (frameRenderer passes the same content timeMs).frameTimeMs: currentTimeRef.current,});@@ -1332,9 +1321,8 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(state.y = appliedTransform.y;state.appliedScale = appliedTransform.scale;- // Reactive camera sizing: scale the PiP webcam inversely with the (already eased) zoom.- // Anchor the shrink to the corner the camera is docked in (bottom-right by default)- // so it stays flush against the edges instead of drifting toward center.+ // Scale the PiP webcam inversely with the (eased) zoom, anchored to the docked+ // corner (bottom-right by default) so it stays flush instead of drifting to center.const webcamWrapper = webcamWrapperRef.current;if (webcamWrapper) {const reactive =@@ -1370,16 +1358,16 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(let targetFocus = defaultFocus;let targetProgress = 0;- // If a zoom is selected but video is not playing, show default unzoomed view+ // If a zoom is selected but not playing, show the default unzoomed view.const selectedId = selectedZoomIdRef.current;const hasSelectedZoom = selectedId !== null;const shouldShowUnzoomedView =hasSelectedZoom && !isPlayingRef.current && !isPreviewingZoomRef.current;if (region && strength > 0 && !shouldShowUnzoomedView) {- // Use getZoomScale (customScale-aware) to match export (frameRenderer) and the- // magnification findDominantRegion already resolves the focus at — preview must not- // fall back to the raw depth preset or it zooms/pans to a different level than export.+ // Use getZoomScale (customScale-aware) to match export and the magnification+ // findDominantRegion resolved focus at. Falling back to the depth preset would+ // zoom/pan to a different level than export.const zoomScale = blendedScale ?? getZoomScale(region);const regionFocus = region.focus;@@ -1387,14 +1375,14 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(targetFocus = regionFocus;targetProgress = strength;- // Apply adaptive smoothing for auto-follow mode+ // Adaptive smoothing for auto-follow mode.if (region.focusMode === "auto" && !transition) {const raw = targetFocus;const isZoomingIn =targetProgress < 0.999 && targetProgress >= prevTargetProgressRef.current;- // Follow the cursor in CONTENT time (frame-rate independent) so the camera pans+ // Follow the cursor in content time (frame-rate independent) so the camera pans// at the same speed in preview and export. Snap to target when not actively- // playing (paused/seek/scrub) — matches the zoom spring's snap.+ // playing (paused/seek/scrub), matching the zoom spring's snap.const focusAnimating =isPlayingRef.current && !isSeekingRef.current && !isScrubbingRef.current;const focusDtMs =@@ -1402,7 +1390,7 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(? 0: currentTimeRef.current - prevZoomTimeMsRef.current;if (targetProgress >= 0.999) {- // Full zoom: adaptive smoothing — moves faster when far, decelerates when close+ // Full zoom: adaptive smoothing, faster when far, decelerating when close.const prev = smoothedAutoFocusRef.current ?? raw;const smoothed = focusAnimating? advanceFollowFocus(prev, raw, focusDtMs, AUTO_FOLLOW_PARAMS)@@ -1410,11 +1398,11 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(smoothedAutoFocusRef.current = smoothed;targetFocus = smoothed;} else if (isZoomingIn) {- // Zoom-in: track cursor directly so zoom always aims at current cursor- // position; keep ref in sync to avoid snap when full-zoom begins+ // Zoom-in: track cursor directly so zoom always aims at the current position;+ // keep ref in sync to avoid a snap when full-zoom begins.smoothedAutoFocusRef.current = raw;} else {- // Zoom-out: keep smoothing for continuity — avoids snap at zoom-out start+ // Zoom-out: keep smoothing for continuity to avoid a snap at zoom-out start.const prev = smoothedAutoFocusRef.current ?? raw;const smoothed = focusAnimating? advanceFollowFocus(prev, raw, focusDtMs, AUTO_FOLLOW_PARAMS)@@ -1427,7 +1415,7 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(}prevTargetProgressRef.current = targetProgress;- // Handle connected zoom transitions (pan between adjacent zoom regions)+ // Connected zoom transitions: pan between adjacent regions.if (transition) {const startTransform = computeZoomTransform({stageSize: stageSizeRef.current,@@ -1487,8 +1475,7 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(// Chase the eased target with a spring so the camera glides (no jerk at the steep// start of the ease, no snap at close-region seams). Step by content time while- // playing; snap to the deterministic target when paused/seeking/scrubbing so those- // frames are crisp and exact.+ // playing; snap to the exact target when paused/seeking/scrubbing for crisp frames.const nowMs = currentTimeRef.current;const prevMs = prevZoomTimeMsRef.current;const animating = isPlayingRef.current && !isSeekingRef.current && !isScrubbingRef.current;@@ -1545,7 +1532,6 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(}}- // Update cursor overlayconst cursorOverlay = cursorOverlayRef.current;if (cursorOverlay) {const timeMs = currentTimeRef.current; // already in ms@@ -1613,7 +1599,7 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(}): null;if (projectedLocalPoint && projectedStagePoint) {- // Pass deviceScaleFactor=1 — asset.scaleFactor already encodes DPR.+ // Pass deviceScaleFactor=1 since asset.scaleFactor already encodes DPR.// Size is normalized below so preview matches export proportionally.const renderAsset = resolveNativeCursorRenderAsset(frame.asset,@@ -1649,9 +1635,8 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(nativeCursorImageIdRef.current = renderAsset.id;}nativeCursorImage.style.display = "block";- // Update clip-path on nativeCursorClipRef to the camera-aware video boundary.- // clip-path works correctly here because nativeCursorClipRef is outside preserve-3d.- // When cursorClipToBounds is off, allow the cursor to overflow the canvas.+ // Clip to the camera-aware video boundary. Works here because nativeCursorClipRef+ // sits outside preserve-3d. When cursorClipToBounds is off, let the cursor overflow.if (nativeCursorClipRef.current) {if (!cursorClipToBoundsRef.current) {nativeCursorClipRef.current.style.clipPath = "none";@@ -1674,7 +1659,7 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(nativeCursorImage.style.filter =blurPx > 0 ? `blur(${blurPx.toFixed(2)}px)` : "none";// translate3d is relative to nativeCursorClipRef (absolute inset-0 = stage origin).- // projectedStagePoint.x is the stage-space cursor position — no offset needed.+ // projectedStagePoint.x is the stage-space cursor position, so no offset is needed.nativeCursorImage.style.transform = `translate3d(${projectedStagePoint.x - renderAsset.hotspotX * transformedScale}px, ${projectedStagePoint.y - renderAsset.hotspotY * transformedScale}px, 0)`;@@ -1916,7 +1901,7 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(),}}>- {/* Background layer - always render as DOM element with blur */}+ {/* Background always renders as a DOM element so it can be blurred. */}<divclassName="absolute inset-0 bg-cover bg-center"style={{@@ -1985,7 +1970,7 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(</div>);})()}- {/* Only render overlay after PIXI and video are fully initialized */}+ {/* Render the overlay only once PIXI and video are ready. */}{pixiReady && videoReady && (<divref={setOverlayRefs}@@ -2051,18 +2036,15 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(})(): null;- // Handle click-through cycling: when clicking same annotation, cycle to next+ // Re-clicking a selected annotation cycles through any overlapping ones.const handleAnnotationClick = (clickedId: string) => {if (!onSelectAnnotation) return;- // If clicking on already selected annotation and there are multiple overlappingif (clickedId === selectedAnnotationId && filteredAnnotations.length > 1) {- // Find current index and cycle to nextconst currentIndex = filteredAnnotations.findIndex((a) => a.id === clickedId);const nextIndex = (currentIndex + 1) % filteredAnnotations.length;onSelectAnnotation(filteredAnnotations[nextIndex].id);} else {- // First click or clicking different annotationonSelectAnnotation(clickedId);}};@@ -2126,10 +2108,8 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(</div>)}</div>- {/* Clip the native cursor overlay to the exact video canvas boundary.- Placed OUTSIDE composite3DRef (preserve-3d) so clip-path works- correctly even during 3D zoom rotation regions.- clip-path is set dynamically to the camera-aware video bounds. */}+ {/* Native cursor clip. Lives outside composite3DRef (preserve-3d) so clip-path+ keeps working during 3D zoom rotations; bounds are set dynamically. */}<divref={nativeCursorClipRef}className="absolute inset-0"diff --git a/src/components/video-editor/projectPersistence.ts b/src/components/video-editor/projectPersistence.tsindex 22899be51..258efdf6a 100644--- a/src/components/video-editor/projectPersistence.ts+++ b/src/components/video-editor/projectPersistence.ts@@ -47,11 +47,10 @@ import {const VALID_BLUR_SHAPES = new Set(["rectangle", "oval", "freehand"] as const);-// Pre-fix projects could persist resolved file:// URLs (machine-specific) for-// bundled wallpapers. Rewrite only paths that match a known install layout-// (resources/[assets/]wallpapers for packaged, public/wallpapers for dev) so-// a legitimate user file that happens to live in a folder named "wallpapers"-// elsewhere is never silently replaced.+// Old projects persisted machine-specific file:// URLs for bundled wallpapers.+// Match only the known install layouts (packaged resources/[assets/]wallpapers,+// dev public/wallpapers) so a user's own file under some "wallpapers" folder isn't+// silently replaced.const LEGACY_FILE_WALLPAPER_RE =/^file:\/\/.*?\/(?:resources\/(?:assets\/)?|public\/)wallpapers\/(wallpaper\d+\.jpg)$/i;const CANONICAL_WALLPAPERS = new Set(WALLPAPER_PATHS);@@ -485,8 +484,8 @@ export function normalizeProjectEditor(editor: Partial<ProjectEditorState>): Proheight: cropHeight,},zoomRegions: normalizedZoomRegions,- // Default on for legacy projects so re-opens behave like the new default;- // the on-load auto-suggest pass is gated separately so it won't add zooms.+ // Default on for legacy projects so re-opens match the new default. The+ // on-load auto-suggest pass is gated separately, so this won't add zooms.autoZoomEnabled: typeof editor.autoZoomEnabled === "boolean" ? editor.autoZoomEnabled : true,autoFocusAll: typeof editor.autoFocusAll === "boolean" ? editor.autoFocusAll : false,trimRegions: normalizedTrimRegions,diff --git a/src/components/video-editor/timeline/BackgroundWaveform.tsx b/src/components/video-editor/timeline/BackgroundWaveform.tsxindex c572fdf66..d89a14c40 100644--- a/src/components/video-editor/timeline/BackgroundWaveform.tsx+++ b/src/components/video-editor/timeline/BackgroundWaveform.tsx@@ -1,42 +1,28 @@import { useTimelineContext } from "dnd-timeline";import { useEffect, useMemo, useRef, useState } from "react";-/**- * Perceptual curve applied to normalized amplitude (exponent < 1 lifts quiet- * passages so they stay visible without a single loud spike flattening the rest).- */+// Perceptual curve on normalized amplitude; exponent < 1 lifts quiet passages so+// one loud spike doesn't flatten the rest.const WAVEFORM_GAMMA = 0.6;export interface BackgroundWaveformProps {- /** Pre-computed peaks array: pairs of [min, max] per block (length = 2 * N). */+ /** Pre-computed peaks: pairs of [min, max] per block (length = 2 * N). */peaks: Float32Array | null;videoDurationMs: number;- /**- * Pixels to inset the drawn waveform from the top of the canvas row,- * so it aligns with the item content top edge. Defaults to 0.- */+ /** Inset from canvas top so the waveform aligns with item content top. Defaults to 0. */topInset?: number;- /**- * Pixels to inset the drawn waveform from the bottom of the canvas row,- * so it aligns with the item content bottom edge. Defaults to 0.- */+ /** Inset from canvas bottom so the waveform aligns with item content bottom. Defaults to 0. */bottomInset?: number;}/**- * Renders a rectified (half-wave) audio waveform on a `<canvas>` that fills- * its containing block. Designed to be passed as the `background` prop of- * `<Row>`, which already provides `relative overflow-hidden` — no wrapper- * element needed.- *- * The canvas always uses `inset-0` (full row height). Vertical alignment with- * the item content is achieved via `topInset`/`bottomInset` in the draw calls- * rather than CSS positioning, so the result is immune to sub-pixel CSS layout- * differences.+ * Renders a rectified (half-wave) audio waveform on a canvas filling its block.+ * Pass as the `background` prop of `<Row>`, which already provides+ * `relative overflow-hidden`.*- * - Accepts pre-computed `peaks` from the caller (see `useAudioPeaks`).- * - Redraws whenever the timeline zoom/pan range changes.- * - `pointer-events: none` — never blocks drag-to-create interactions.+ * Canvas is always `inset-0` (full row height); vertical alignment comes from+ * `topInset`/`bottomInset` in the draw calls, not CSS, so it's immune to+ * sub-pixel layout rounding. `pointer-events: none` keeps drag-to-create working.*/export default function BackgroundWaveform({peaks,@@ -48,9 +34,9 @@ export default function BackgroundWaveform({const canvasRef = useRef<HTMLCanvasElement>(null);const [canvasSize, setCanvasSize] = useState({ w: 0, h: 0 });- // Normalize against the track's own loudest peak so quiet recordings (mic /- // system audio rarely approach full scale) still fill the row. Computed once- // per peaks change, not per zoom/pan, so the height stays stable as you scroll.+ // Normalize against the track's own loudest peak so quiet recordings (mic/system+ // audio rarely hit full scale) still fill the row. Recomputed only on peaks change,+ // not zoom/pan, so height stays stable while scrolling.const normFactor = useMemo(() => {if (!peaks || peaks.length === 0) return 0;let globalMax = 0;@@ -61,8 +47,8 @@ export default function BackgroundWaveform({return globalMax > 0 ? 1 / globalMax : 0;}, [peaks]);- // Observe the canvas itself — Row's `relative overflow-hidden` parent- // makes it fill the row exactly, so no wrapper div is needed.+ // Observe the canvas directly; Row's `relative overflow-hidden` parent makes+ // it fill the row exactly, so no wrapper div is needed.useEffect(() => {const canvas = canvasRef.current;if (!canvas) return;@@ -74,7 +60,6 @@ export default function BackgroundWaveform({return () => ro.disconnect();}, []);- // Redraw whenever peaks, range, or canvas size changes.useEffect(() => {const canvas = canvasRef.current;if (!canvas || canvasSize.w <= 0 || canvasSize.h <= 0) return;@@ -97,7 +82,7 @@ export default function BackgroundWaveform({if (rangeMs <= 0 || videoDurationMs <= 0) return;// Draw within [topY, bottomY] so the waveform aligns with item bounds- // regardless of CSS sub-pixel rounding on the canvas element itself.+ // regardless of sub-pixel rounding on the canvas element.const topY = topInset;const bottomY = H - bottomInset;const drawHeight = bottomY - topY;@@ -106,8 +91,8 @@ export default function BackgroundWaveform({const N = peaks.length / 2;const amp = drawHeight * 0.9;- // Rectified (half-wave): amplitude = max(|min|, |max|), normalized to the- // track's loudest peak and perceptually curved, drawn upward from bottomY.+ // Rectified: amplitude = max(|min|, |max|), normalized to the loudest peak+ // and gamma-curved, drawn upward from bottomY.const colY = new Float32Array(W);for (let x = 0; x < W; x++) {const startMs = range.start + (x / W) * rangeMs;@@ -127,7 +112,7 @@ export default function BackgroundWaveform({colY[x] = bottomY - display * amp;}- // Filled polygon: bottom-left → top silhouette → bottom-right.+ // Filled polygon: bottom-left, up over the silhouette, down to bottom-right.ctx.beginPath();ctx.moveTo(0, bottomY);for (let x = 0; x < W; x++) {@@ -138,7 +123,7 @@ export default function BackgroundWaveform({ctx.fillStyle = "rgba(74, 222, 128, 0.55)";ctx.fill();- // Crisp top-edge stroke for the sharp silhouette.+ // Crisp top-edge stroke.ctx.beginPath();ctx.moveTo(0, colY[0]);for (let x = 1; x < W; x++) {diff --git a/src/components/video-editor/timeline/Item.tsx b/src/components/video-editor/timeline/Item.tsxindex 7251af6de..254c4f94b 100644--- a/src/components/video-editor/timeline/Item.tsx+++ b/src/components/video-editor/timeline/Item.tsx@@ -79,9 +79,8 @@ export default function Item({[span.start, span.end],);- // Minimum clickable width on the outer wrapper.- // Kept small (6px) so items visually distinguish their real positions;- // users should zoom in to interact with sub-second items precisely.+ // Minimum clickable width on the outer wrapper. Kept small so items keep their real+ // positions; zoom in to interact with sub-second items precisely.const MIN_ITEM_PX = 6;const safeItemStyle = { ...itemStyle, minWidth: MIN_ITEM_PX };diff --git a/src/components/video-editor/timeline/Row.tsx b/src/components/video-editor/timeline/Row.tsxindex 17a59e83c..a0b00c9a5 100644--- a/src/components/video-editor/timeline/Row.tsx+++ b/src/components/video-editor/timeline/Row.tsx@@ -9,9 +9,8 @@ interface RowProps extends RowDefinition {}/**- * A single horizontal lane in the timeline. Wraps the dnd-timeline `useRow`- * hook and adds an optional `background` layer (e.g. `BackgroundWaveform`),- * an empty-state hint label, and a minimum height.+ * A horizontal timeline lane. Wraps dnd-timeline's `useRow` and adds an optional+ * `background` layer, an empty-state hint label, and a minimum height.*/export default function Row({ id, children, hint, isEmpty, background }: RowProps) {const { setNodeRef, rowWrapperStyle, rowStyle } = useRow({ id });diff --git a/src/components/video-editor/timeline/TimelineEditor.tsx b/src/components/video-editor/timeline/TimelineEditor.tsxindex 6f6d8f545..17894ad1c 100644--- a/src/components/video-editor/timeline/TimelineEditor.tsx+++ b/src/components/video-editor/timeline/TimelineEditor.tsx@@ -136,9 +136,8 @@ const SCALE_CANDIDATES = [];/**- * Picks the best axis interval for the currently visible time range.- * Called dynamically — re-runs on every zoom change so the axis always- * shows a meaningful density of markers regardless of video length.+ * Picks the best axis interval for the currently visible time range, so marker+ * density stays meaningful regardless of video length.*/function calculateAxisScale(visibleRangeMs: number): { intervalMs: number; gridMs: number } {const visibleSeconds = visibleRangeMs / 1000;@@ -156,19 +155,17 @@ function calculateAxisScale(visibleRangeMs: number): { intervalMs: number; gridMfunction calculateTimelineScale(durationSeconds: number): TimelineScaleConfig {const totalMs = Math.max(0, Math.round(durationSeconds * 1000));- // Minimum item duration: fixed at 100ms (0.1s).- // Allows precise cuts while remaining interactive.+ // 100ms, precise enough to cut but still grabbable.const minItemDurationMs = 100;- // Default placement size: 5% of video duration, clamped between 1s and 30s.+ // 5% of duration, clamped to 1-30s.const defaultItemDurationMs =totalMs > 0? Math.max(minItemDurationMs, Math.min(Math.round(totalMs * 0.05), 30000)): Math.max(minItemDurationMs, 1000);- // Minimum visible range: 300ms — allows comfortably viewing 0.1s items.- // Axis markers adapt dynamically via calculateAxisScale, so there is no- // upper constraint on how far the user can zoom in.+ // 300ms, enough to view 0.1s items comfortably. Axis markers adapt via+ // calculateAxisScale, so there's no cap on zoom-in.const minVisibleRangeMs = 300;return {@@ -299,11 +296,11 @@ function PlaybackCursor({const clickX = e.clientX - rect.left - sidebarWidth;const contentWidth = Math.max(rect.width - sidebarWidth, 1);- // Allow dragging outside to 0 or max, but clamp the value+ // Allow dragging past the edges, but clamp the valueconst relativeMs = pixelsToValue(clickX);let absoluteMs = Math.max(0, Math.min(range.start + relativeMs, videoDurationMs));- // Snap to nearby keyframe if within threshold (150ms)+ // Snap to a keyframe within 150msconst snapThresholdMs = 150;const nearbyKeyframe = keyframes.find((kf) =>@@ -406,7 +403,7 @@ function PlaybackCursor({className="absolute top-0 bottom-0 z-50 group/cursor"style={{[sideProperty === "right" ? "marginRight" : "marginLeft"]: `${sidebarWidth - 1}px`,- pointerEvents: "none", // Allow clicks to pass through to timeline, but we'll enable pointer events on the handle+ pointerEvents: "none", // pass clicks through to the timeline; the handle re-enables them}}><div@@ -446,7 +443,6 @@ function TimelineAxis({const { sidebarWidth, direction, range, valueToPixels } = useTimelineContext();const sideProperty = direction === "rtl" ? "right" : "left";- // Recompute axis scale dynamically on every zoom change.const { intervalMs } = useMemo(() => calculateAxisScale(range.end - range.start),[range.end, range.start],@@ -482,13 +478,12 @@ function TimelineAxis({.filter((time) => time <= maxTime).sort((a, b) => a - b);- // Generate minor ticks (4 ticks between major intervals)+ // 4 minor ticks between major intervalsconst minorTicks = [];const minorInterval = intervalMs / 5;for (let time = firstMarker; time <= maxTime; time += minorInterval) {if (time >= visibleStart && time <= visibleEnd) {- // Skip if it's close to a major markerconst isMajor = Math.abs(time % intervalMs) < 1;if (!isMajor) {minorTicks.push(time);@@ -639,8 +634,7 @@ function Timeline({const handleTimelineClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => {- // Only clear selection if clicking on empty space (not on items)- // This is handled by event propagation - items stop propagation+ // Items stop propagation, so this only fires on empty spaceclearTimelineSelection();seekTimelineAtClientX(e.currentTarget, e.clientX);},@@ -963,7 +957,6 @@ export default function TimelineEditor({});}, []);- // Add keyframe at current playhead positionconst addKeyframe = useCallback(() => {if (totalMs === 0) return;const time = Math.max(0, Math.min(currentTimeMs, totalMs));@@ -971,14 +964,12 @@ export default function TimelineEditor({setKeyframes((prev) => [...prev, { id: uuidv4(), time }]);}, [currentTimeMs, totalMs, keyframes]);- // Delete selected keyframeconst deleteSelectedKeyframe = useCallback(() => {if (!selectedKeyframeId) return;setKeyframes((prev) => prev.filter((kf) => kf.id !== selectedKeyframeId));setSelectedKeyframeId(null);}, [selectedKeyframeId]);- // Move keyframe to new time positionconst handleKeyframeMove = useCallback((id: string, newTime: number) => {setKeyframes((prev) =>@@ -990,14 +981,12 @@ export default function TimelineEditor({[totalMs],);- // Delete selected zoom itemconst deleteSelectedZoom = useCallback(() => {if (!selectedZoomId) return;onZoomDelete(selectedZoomId);onSelectZoom(null);}, [selectedZoomId, onZoomDelete, onSelectZoom]);- // Delete selected trim itemconst deleteSelectedTrim = useCallback(() => {if (!selectedTrimId || !onTrimDelete || !onSelectTrim) return;onTrimDelete(selectedTrimId);@@ -1026,9 +1015,8 @@ export default function TimelineEditor({setRange(createInitialRange(totalMs));}, [totalMs]);- // Normalize regions only when timeline bounds change (not on every region edit).- // Using refs to read current regions avoids a dependency-loop that re-fires- // this effect on every drag/resize and races with dnd-timeline's internal state.+ // Normalize regions only when timeline bounds change. Reading via refs avoids a+ // dependency loop that would re-fire on every drag and race dnd-timeline's state.const zoomRegionsRef = useRef(zoomRegions);const trimRegionsRef = useRef(trimRegions);const speedRegionsRef = useRef(speedRegions);@@ -1076,12 +1064,10 @@ export default function TimelineEditor({onSpeedSpanChange?.(region.id, { start: normalizedStart, end: normalizedEnd });}});- // Only re-run when the timeline scale changes, not on every region edit}, [totalMs, safeMinDurationMs, onZoomSpanChange, onTrimSpanChange, onSpeedSpanChange]);const hasOverlap = useCallback((newSpan: Span, excludeId?: string): boolean => {- // Determine which row the item belongs toconst isZoomItem = zoomRegions.some((r) => r.id === excludeId);const isTrimItem = trimRegions.some((r) => r.id === excludeId);const isAnnotationItem = annotationRegions.some((r) => r.id === excludeId);@@ -1092,11 +1078,10 @@ export default function TimelineEditor({return false;}- // Helper to check overlap against a specific set of regionsconst checkOverlap = (regions: (ZoomRegion | TrimRegion | SpeedRegion)[]) => {return regions.some((region) => {if (region.id === excludeId) return false;- // True overlap: regions actually intersect (not just adjacent)+ // True intersection, adjacency is allowedreturn newSpan.end > region.startMs && newSpan.start < region.endMs;});};@@ -1118,8 +1103,7 @@ export default function TimelineEditor({[zoomRegions, trimRegions, annotationRegions, blurRegions, speedRegions],);- // At least 5% of the timeline or 1000ms, whichever is larger, so the region- // is always wide enough to grab and resize comfortably.+ // 5% of the timeline or 1000ms, whichever is larger, so it's wide enough to grab.const defaultRegionDurationMs = useMemo(() => Math.max(1000, Math.round(totalMs * 0.05)),[totalMs],@@ -1135,14 +1119,11 @@ export default function TimelineEditor({return;}- // Always place zoom at playheadconst startPos = Math.max(0, Math.min(currentTimeMs, totalMs));- // Find the next zoom region after the playheadconst sorted = [...zoomRegions].sort((a, b) => a.startMs - b.startMs);const nextRegion = sorted.find((region) => region.startMs > startPos);const gapToNext = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;- // Check if playhead is inside any zoom regionconst isOverlapping = sorted.some((region) => startPos >= region.startMs && startPos < region.endMs,);@@ -1167,14 +1148,11 @@ export default function TimelineEditor({return;}- // Always place trim at playheadconst startPos = Math.max(0, Math.min(currentTimeMs, totalMs));- // Find the next trim region after the playheadconst sorted = [...trimRegions].sort((a, b) => a.startMs - b.startMs);const nextRegion = sorted.find((region) => region.startMs > startPos);const gapToNext = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;- // Check if playhead is inside any trim regionconst isOverlapping = sorted.some((region) => startPos >= region.startMs && startPos < region.endMs,);@@ -1199,14 +1177,11 @@ export default function TimelineEditor({return;}- // Always place speed region at playheadconst startPos = Math.max(0, Math.min(currentTimeMs, totalMs));- // Find the next speed region after the playheadconst sorted = [...speedRegions].sort((a, b) => a.startMs - b.startMs);const nextRegion = sorted.find((region) => region.startMs > startPos);const gapToNext = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;- // Check if playhead is inside any speed regionconst isOverlapping = sorted.some((region) => startPos >= region.startMs && startPos < region.endMs,);@@ -1286,12 +1261,12 @@ export default function TimelineEditor({handleAddSpeed();}- // Tab: Cycle through overlapping annotations at current time+ // Tab cycles through overlapping annotations at the current timeif (e.key === "Tab" && annotationRegions.length > 0) {const currentTimeMs = Math.round(currentTime * 1000);const overlapping = annotationRegions.filter((a) => currentTimeMs >= a.startMs && currentTimeMs <= a.endMs)- .sort((a, b) => a.zIndex - b.zIndex); // Sort by z-index+ .sort((a, b) => a.zIndex - b.zIndex);if (overlapping.length > 0) {e.preventDefault();@@ -1299,11 +1274,10 @@ export default function TimelineEditor({if (!selectedAnnotationId || !overlapping.some((a) => a.id === selectedAnnotationId)) {onSelectAnnotation?.(overlapping[0].id);} else {- // Cycle to next annotationconst currentIndex = overlapping.findIndex((a) => a.id === selectedAnnotationId);const nextIndex = e.shiftKey- ? (currentIndex - 1 + overlapping.length) % overlapping.length // Shift+Tab = backward- : (currentIndex + 1) % overlapping.length; // Tab = forward+ ? (currentIndex - 1 + overlapping.length) % overlapping.length // Shift+Tab steps backward+ : (currentIndex + 1) % overlapping.length;onSelectAnnotation?.(overlapping[nextIndex].id);}}@@ -1392,7 +1366,6 @@ export default function TimelineEditor({let label: string;if (region.type === "text") {- // Show text previewconst preview = region.content.trim() || t("labels.emptyText");label = preview.length > 20 ? `${preview.substring(0, 20)}...` : preview;} else if (region.type === "image") {@@ -1430,10 +1403,8 @@ export default function TimelineEditor({return [...zooms, ...trims, ...annotations, ...blurs, ...speeds];}, [zoomRegions, trimRegions, annotationRegions, blurRegions, speedRegions, t]);- // Spans that participate in overlap resolution (clampToNeighbours).- // Excludes annotation/blur deliberately — those are allowed to overlap and- // must NOT act as hard constraints when a zoom/trim/speed drag is being- // resolved.+ // Spans that participate in overlap resolution (clampToNeighbours). Annotation+ // and blur are excluded since they may overlap and shouldn't constrain a drag.const allRegionSpans = useMemo(() => {const zooms = zoomRegions.map((r) => ({ id: r.id, start: r.startMs, end: r.endMs }));const trims = trimRegions.map((r) => ({ id: r.id, start: r.startMs, end: r.endMs }));@@ -1441,8 +1412,7 @@ export default function TimelineEditor({return [...zooms, ...trims, ...speeds];}, [zoomRegions, trimRegions, speedRegions]);- // Additional snap targets that are NOT clamping constraints. Their edges- // pull during snap, but they don't push anyone away.+ // Snap targets whose edges pull during a snap but don't push anyone away.const softSnapSpans = useMemo(() => {const annotations = annotationRegions.map((r) => ({id: r.id,@@ -1457,7 +1427,6 @@ export default function TimelineEditor({const handleItemSpanChange = useCallback((id: string, span: Span) => {- // Check if it's a zoom, trim, speed, or annotation itemif (zoomRegions.some((r) => r.id === id)) {onZoomSpanChange(id, span);} else if (trimRegions.some((r) => r.id === id)) {diff --git a/src/components/video-editor/timeline/TimelineWrapper.tsx b/src/components/video-editor/timeline/TimelineWrapper.tsxindex 2a44262af..9cd71cb05 100644--- a/src/components/video-editor/timeline/TimelineWrapper.tsx+++ b/src/components/video-editor/timeline/TimelineWrapper.tsx@@ -21,11 +21,9 @@ interface TimelineWrapperProps {minVisibleRangeMs: number;gridSizeMs?: number;onItemSpanChange: (id: string, span: Span) => void;- // Spans that act as hard overlap constraints (zoom/trim/speed). Used by- // clampToNeighbours AND as snap targets.+ // Hard overlap constraints (zoom/trim/speed), used by clampToNeighbours and as snap targets.allRegionSpans?: { id: string; start: number; end: number }[];- // Spans that act ONLY as snap targets (annotation/blur). They never push- // other items away during overlap resolution.+ // Snap targets only (annotation/blur); never push other items during overlap resolution.softSnapSpans?: { id: string; start: number; end: number }[];currentTimeMs?: number;keyframeTimesMs?: number[];@@ -36,9 +34,8 @@ interface SnapGuideHandle {hide: () => void;}-// Lives inside TimelineContext so it can read valueToPixels. Updates DOM-// directly via an imperative handle — same pattern as the drag tooltip — to-// avoid re-rendering the timeline on every pointer move.+// Lives inside TimelineContext to read valueToPixels. Updates the DOM directly via+// an imperative handle (like the drag tooltip) to avoid re-rendering on every pointer move.const SnapGuide = forwardRef<SnapGuideHandle>((_, ref) => {const { sidebarWidth, direction, range, valueToPixels } = useTimelineContext();const elRef = useRef<HTMLDivElement>(null);@@ -198,10 +195,9 @@ export default function TimelineWrapper({const snapGuideRef = useRef<SnapGuideHandle>(null);- // Pull the active span's edges to nearby region boundaries, timeline bounds,- // the playhead, and keyframes. Threshold scales with zoom (~1% of visible- // range, min 50ms) so snap feels right at any zoom level.- // Returns the snapped span plus the actual snap target used (for guide rendering).+ // Pull the active span's edges to nearby region boundaries, timeline bounds, playhead,+ // and keyframes. Threshold scales with zoom (~1% of visible range, min 50ms). Returns+ // the snapped span plus the snap target used (for guide rendering).const snapSpanToTargets = useCallback((span: Span,@@ -296,12 +292,10 @@ export default function TimelineWrapper({],);- // dnd-timeline's resize event doesn't expose direction. Compare the live- // span to the committed one (committed spans only update on commit, so- // during a single resize they still reflect the pre-resize state).- // Returns null when the deltas are equal — including the common clamped- // case where both are 0 — because we can't tell which handle the user- // grabbed, and guessing wrong would snap the other edge.+ // dnd-timeline's resize event doesn't expose direction, so compare the live span to+ // the committed one (committed only updates on commit, so it's the pre-resize state).+ // Returns null when deltas are equal (including the common clamped both-0 case): we+ // can't tell which handle was grabbed, and guessing wrong snaps the other edge.const inferResizeMode = useCallback((activeItemId: string, span: Span): "resize-left" | "resize-right" | null => {const old =diff --git a/src/components/video-editor/timeline/zoomSuggestionUtils.ts b/src/components/video-editor/timeline/zoomSuggestionUtils.tsindex 6068557b3..f083a7f7c 100644--- a/src/components/video-editor/timeline/zoomSuggestionUtils.ts+++ b/src/components/video-editor/timeline/zoomSuggestionUtils.ts@@ -88,10 +88,9 @@ export interface AutoZoomSuggestion {}/**- * Builds non-overlapping zoom suggestions from cursor telemetry: detects dwell- * moments, ranks them by dwell duration, spaces them out by SUGGESTION_SPACING_MS,- * and drops any that overlap an existing region. Pure — shared by the magic-wand- * toggle and the on-load auto-suggest pass.+ * Build non-overlapping zoom suggestions from cursor telemetry: detect dwell moments,+ * rank by duration, space by SUGGESTION_SPACING_MS, drop any overlapping an existing+ * region. Pure, shared by the magic-wand toggle and the on-load auto-suggest pass.*/export function buildAutoZoomSuggestions(options: {cursorTelemetry: CursorTelemetryPoint[];diff --git a/src/components/video-editor/types.ts b/src/components/video-editor/types.tsindex e2d3d46ae..93ae00237 100644--- a/src/components/video-editor/types.ts+++ b/src/components/video-editor/types.ts@@ -3,7 +3,7 @@ import type { WebcamLayoutPreset } from "@/lib/compositeLayout";export type ZoomDepth = 1 | 2 | 3 | 4 | 5 | 6;export type ZoomFocusMode = "manual" | "auto";export type { WebcamLayoutPreset };-/** Webcam size as a percentage of the canvas reference dimension (10–50). */+/** Webcam size as a percentage of the canvas reference dimension (10-50). */export type WebcamSizePreset = number;export const DEFAULT_WEBCAM_SIZE_PRESET: WebcamSizePreset = 25;@@ -53,9 +53,8 @@ export const ROTATION_3D_PRESETS: Record<Rotation3DPreset, Rotation3D> = {export const ROTATION_3D_PRESET_ORDER: Rotation3DPreset[] = ["iso", "left", "right"];-/** Perspective distance in CSS px is computed at render-time as this factor times- * min(viewport width, viewport height). Same factor used in preview and export so- * the visual look is identical regardless of canvas resolution. */+/** Perspective distance in CSS px is this factor times min(viewport w, h). Same+ * factor in preview and export so the look matches at any canvas resolution. */export const ROTATION_3D_PERSPECTIVE_FACTOR = 2.6;export function rotation3DPerspective(width: number, height: number): number {@@ -63,9 +62,9 @@ export function rotation3DPerspective(width: number, height: number): number {}/**- * Origin of a zoom region. "auto" marks zooms added by the magic-wand auto-suggest- * pass; toggling the wand off removes only these. Editing an auto zoom promotes it- * to "manual" so it survives. Undefined is treated as "manual" for back-compat.+ * Origin of a zoom region. "auto" marks zooms from the magic-wand suggest pass;+ * toggling the wand off removes only these. Editing an auto zoom promotes it to+ * "manual" so it survives. Undefined is treated as "manual" for back-compat.*/export type ZoomRegionSource = "auto" | "manual";@@ -77,7 +76,7 @@ export interface ZoomRegion {focus: ZoomFocus;focusMode?: ZoomFocusMode;rotationPreset?: Rotation3DPreset;- /** Custom scale overriding the preset depth (1.0–5.0, two decimal precision). */+ /** Custom scale overriding the preset depth (1.0-5.0, two decimal precision). */customScale?: number;source?: ZoomRegionSource;}@@ -100,13 +99,10 @@ export function lerpRotation3D(a: Rotation3D, b: Rotation3D, t: number): Rotatio}/**- * Compute the maximum uniform scale that, when applied alongside `rot` and a perspective- * of `perspective` CSS px, keeps the projected bounding box of a `width × height` element- * inside its original `width × height` rectangle. Returns 1 when no scaling is needed.- *- * Math: project each rotated corner onto the screen via x' = x·P/(P−z); take the worst-case- * |x'|/|y'| against the half-extents and return the limiting ratio. This makes the rotated- * recording sit *inside* the zoom window instead of bleeding past it.+ * Max uniform scale that, with `rot` and a perspective of `perspective` CSS px, keeps+ * the projected bounding box of a width x height element inside its original rectangle.+ * Returns 1 when no scaling is needed. Projects each rotated corner (x' = x*P/(P-z)) and+ * returns the limiting half-extent ratio so the rotated recording stays inside the zoom window.*/export function computeRotation3DContainScale(rot: Rotation3D,@@ -136,7 +132,7 @@ export function computeRotation3DContainScale(let maxAbsY = 0;for (const [x0, y0] of corners) {- // CSS "rotateX(α) rotateY(β) rotateZ(γ)" reads right-to-left: Z first, then Y, then X.+ // CSS "rotateX rotateY rotateZ" applies right-to-left: Z first, then Y, then X.let px = x0;let py = y0;let pz = 0;@@ -159,11 +155,11 @@ export function computeRotation3DContainScale(py = xy;pz = xz;- // Perspective projection: viewer at (0, 0, P), looking toward −z. A point at z=pz- // is scaled by P / (P − pz). When perspective ≤ 0 we treat as orthographic.+ // Viewer at (0, 0, P) looking toward -z; a point at z=pz scales by P/(P-pz).+ // perspective <= 0 means orthographic.if (perspective > 0) {const denom = perspective - pz;- if (denom <= 0) return 1; // pathological — skip scaling rather than crash+ if (denom <= 0) return 1; // pathological, skip scaling rather than crashconst f = perspective / denom;px *= f;py *= f;@@ -208,8 +204,7 @@ export const DEFAULT_CURSOR_SIZE = 3.0;export const DEFAULT_CURSOR_SMOOTHING = 0.67;export const DEFAULT_CURSOR_MOTION_BLUR = 0.35;export const DEFAULT_CURSOR_CLICK_BOUNCE = 2.5;-// false = allow the cursor to overflow into the background by default.-// true = clip the native cursor to the video canvas bounds.+// false lets the cursor overflow into the background; true clips it to the canvas bounds.export const DEFAULT_CURSOR_CLIP_TO_BOUNDS = false;export const DEFAULT_ZOOM_MOTION_BLUR = 0.35;@@ -373,8 +368,7 @@ export const DEFAULT_CROP_REGION: CropRegion = {export type PlaybackSpeed = number;export const MIN_PLAYBACK_SPEED = 0.1;-// Anything above 16x causes the playhead to stall during preview-// due to the video decoder not being able to keep up.+// Above 16x the decoder can't keep up and the playhead stalls during preview.export const MAX_PLAYBACK_SPEED = 16;export function clampPlaybackSpeed(speed: number): PlaybackSpeed {diff --git a/src/components/video-editor/videoPlayback/constants.ts b/src/components/video-editor/videoPlayback/constants.tsindex 64471657d..0cfa17c6b 100644--- a/src/components/video-editor/videoPlayback/constants.ts+++ b/src/components/video-editor/videoPlayback/constants.ts@@ -11,11 +11,11 @@ export const ZOOM_SCALE_DEADZONE = 0.002;export const AUTO_FOLLOW_SMOOTHING_FACTOR = 0.1;export const AUTO_FOLLOW_SMOOTHING_FACTOR_MAX = 0.25;export const AUTO_FOLLOW_RAMP_DISTANCE = 0.15;-// Reference frame interval for the (content-time, frame-rate-independent) auto-focus follow. Both-// preview and export reframe their per-frame smoothing against this so they converge identically-// regardless of render fps. Lower fps here = floatier follow (tuned to the live-preview feel).+// Reference frame interval so preview and export normalize their per-frame+// smoothing identically regardless of render fps. Lower fps = floatier follow+// (tuned to the live-preview feel).export const AUTO_FOLLOW_REFERENCE_MS = 1000 / 40;-// Bundled auto-follow params, shared by preview and export so the camera follows the cursor identically.+// Shared by preview and export so the camera follows the cursor identically.export const AUTO_FOLLOW_PARAMS = {minFactor: AUTO_FOLLOW_SMOOTHING_FACTOR,maxFactor: AUTO_FOLLOW_SMOOTHING_FACTOR_MAX,diff --git a/src/components/video-editor/videoPlayback/cursorFollowUtils.ts b/src/components/video-editor/videoPlayback/cursorFollowUtils.tsindex 646cf8762..12113970c 100644--- a/src/components/video-editor/videoPlayback/cursorFollowUtils.ts+++ b/src/components/video-editor/videoPlayback/cursorFollowUtils.ts@@ -1,9 +1,6 @@import type { CursorTelemetryPoint, ZoomFocus } from "../types";-/**- * Binary-search the sorted telemetry array and linearly interpolate- * the cursor position at the given playback time.- */+/** Binary-search the sorted telemetry and lerp the cursor position at the given playback time. */export function interpolateCursorAt(telemetry: CursorTelemetryPoint[],timeMs: number,@@ -44,7 +41,7 @@ export function interpolateCursorAt(/*** Exponential smoothing to reduce jitter from high-frequency cursor data.- * Lower factor = smoother / more lag, higher = more responsive.+ * Lower factor = smoother/more lag, higher = more responsive.*/export function smoothCursorFocus(raw: ZoomFocus, prev: ZoomFocus, factor: number): ZoomFocus {return {@@ -61,10 +58,9 @@ export interface FollowParams {}/**- * Advance the auto-follow focus from `prev` toward the cursor target `raw` over `dtMs` of content- * time. The distance-adaptive factor is reframed against `referenceMs` so the per-frame convergence- * is (first-order) content-time based and matches between preview and export. Returns `prev` unchanged- * when no content time elapsed (paused) so the camera holds still.+ * Advance the auto-follow focus from `prev` toward target `raw` over `dtMs` of content time. The+ * distance-adaptive factor is reframed against `referenceMs` so convergence is content-time based and+ * matches between preview and export. Returns `prev` unchanged when paused so the camera holds still.*/export function advanceFollowFocus(prev: ZoomFocus,@@ -85,11 +81,10 @@ export function advanceFollowFocus(}/**- * Make a per-frame smoothing `baseFactor` frame-rate independent by reframing it in CONTENT time.- * The camera converges as `(1 - baseFactor)^(dtMs / referenceMs)` regardless of how that content time- * is chunked into frames, so preview (variable editor fps) and export (fixed fps) follow the cursor- * at the *same* speed. A larger `referenceMs` (lower reference fps) = floatier. Returns 0 when no- * content time elapsed (paused) so the camera holds still.+ * Make a per-frame smoothing `baseFactor` frame-rate independent by reframing it in content time.+ * The camera converges as `(1 - baseFactor)^(dtMs / referenceMs)` regardless of frame chunking, so+ * preview (variable fps) and export (fixed fps) follow at the same speed. Larger `referenceMs` =+ * floatier. Returns 0 when paused so the camera holds still.*/export function timeCorrectedFollowFactor(baseFactor: number,@@ -101,9 +96,8 @@ export function timeCorrectedFollowFactor(}/**- * Compute an adaptive smoothing factor that scales with distance:- * far from target → faster (maxFactor), close → slower (minFactor).- * This replaces the hard deadzone with a natural deceleration curve.+ * Adaptive smoothing factor that scales with distance: far from target = faster (maxFactor), close =+ * slower (minFactor). Replaces a hard deadzone with a natural deceleration curve.*/export function adaptiveSmoothFactor(raw: ZoomFocus,diff --git a/src/components/video-editor/videoPlayback/cursorRenderer.ts b/src/components/video-editor/videoPlayback/cursorRenderer.tsindex dd3087bd2..2edcca97d 100644--- a/src/components/video-editor/videoPlayback/cursorRenderer.ts+++ b/src/components/video-editor/videoPlayback/cursorRenderer.ts@@ -43,11 +43,11 @@ export interface CursorRenderConfig {dotRadius: number;/** Cursor fill color (hex number for PixiJS) */dotColor: number;- /** Cursor opacity (0–1) */+ /** Cursor opacity (0-1) */dotAlpha: number;/** Unused, kept for interface compatibility */trailLength: number;- /** Smoothing factor for cursor interpolation (0–1, lower = smoother/slower) */+ /** Smoothing factor for cursor interpolation (0-1, lower = smoother/slower) */smoothingFactor: number;/** Directional cursor motion blur amount. */motionBlur: number;@@ -122,10 +122,9 @@ function getNormalizedAnchor(}/**- * Loads an SVG at `sampleSize × sampleSize`, crops the trim region out of it,- * and returns a PNG data-URL of the cropped result. This is required because- * SVG files have their own natural pixel size (e.g. 32×32) which does not- * match the 1024-sample coordinate space used by the trim measurements.+ * Loads an SVG at `sampleSize × sampleSize`, crops the trim region, and returns+ * a PNG data-URL. Needed because an SVG's natural size (e.g. 32×32) doesn't match+ * the 1024-sample coordinate space the trim measurements use.*/async function rasterizeAndCropSvg(url: string,@@ -137,14 +136,12 @@ async function rasterizeAndCropSvg(): Promise<{ dataUrl: string; width: number; height: number }> {const img = await loadImage(url);- // Draw at full sample sizeconst srcCanvas = document.createElement("canvas");srcCanvas.width = sampleSize;srcCanvas.height = sampleSize;const srcCtx = srcCanvas.getContext("2d")!;srcCtx.drawImage(img, 0, 0, sampleSize, sampleSize);- // Crop to trim boundsconst dstCanvas = document.createElement("canvas");dstCanvas.width = trimWidth;dstCanvas.height = trimHeight;@@ -349,7 +346,7 @@ function findLatestInteractionSample(samples: CursorTelemetryPoint[], timeMs: nu}function findLatestStableCursorType(samples: CursorTelemetryPoint[], timeMs: number) {- // Binary search to find position at timeMs, then scan backwards+ // Binary search to position at timeMs, then scan backwardslet lo = 0;let hi = samples.length - 1;while (lo < hi) {@@ -361,8 +358,8 @@ function findLatestStableCursorType(samples: CursorTelemetryPoint[], timeMs: num}}- // Scan backwards from the position to find a sample with cursorType- // Skip click events only (not mouseup) to avoid transient re-type during clicks+ // Scan back for a sample with cursorType. Skip click events (not mouseup) to+ // avoid a transient re-type during clicks.for (let index = lo; index >= 0; index -= 1) {const sample = samples[index];if (sample.timeMs > timeMs) {diff --git a/src/components/video-editor/videoPlayback/layoutUtils.ts b/src/components/video-editor/videoPlayback/layoutUtils.tsindex 6bf094634..bdedf6a2f 100644--- a/src/components/video-editor/videoPlayback/layoutUtils.ts+++ b/src/components/video-editor/videoPlayback/layoutUtils.ts@@ -73,10 +73,8 @@ export function layoutVideoContent(params: LayoutParams): LayoutResult | null {app.canvas.style.width = "100%";app.canvas.style.height = "100%";- // Apply crop regionconst crop = cropRegion || { x: 0, y: 0, width: 1, height: 1 };- // Calculate the cropped dimensionsconst croppedVideoWidth = videoWidth * crop.width;const croppedVideoHeight = videoHeight * crop.height;@@ -85,9 +83,8 @@ export function layoutVideoContent(params: LayoutParams): LayoutResult | null {const cropEndX = cropStartX + croppedVideoWidth;const cropEndY = cropStartY + croppedVideoHeight;- // Calculate scale to fit the cropped area in the viewport- // Padding is a percentage (0-100), where 50 matches the original VIEWPORT_SCALE of 0.8- // Vertical stack ignores padding — it's full-bleed+ // Padding is a percent (0-100); 50 matches the original VIEWPORT_SCALE of 0.8.+ // Vertical stack is full-bleed, so it ignores padding.const effectivePadding = webcamLayoutPreset === "vertical-stack" ? 0 : padding;const paddingScale = 1.0 - (effectivePadding / 100) * 0.4;const maxDisplayWidth = width * paddingScale;@@ -120,11 +117,10 @@ export function layoutVideoContent(params: LayoutParams): LayoutResult | null {videoSprite.scale.set(scale);- // Calculate display size of the full video at this scaleconst fullVideoDisplayWidth = videoWidth * scale;const fullVideoDisplayHeight = videoHeight * scale;- // Position the video so the cropped region is centered within the screenRect+ // Position the video so the cropped region is centered within screenRect.const croppedDisplayWidth = croppedVideoWidth * scale;const croppedDisplayHeight = croppedVideoHeight * scale;const offsetX = screenRect.x + (screenRect.width - croppedDisplayWidth) / 2;@@ -134,7 +130,7 @@ export function layoutVideoContent(params: LayoutParams): LayoutResult | null {videoSprite.position.set(spriteX, spriteY);- // Apply border radius — mask clips the video to the screenRect+ // Mask clips the video to screenRect, with border radius.maskGraphics.clear();maskGraphics.roundRect(screenRect.x,diff --git a/src/components/video-editor/videoPlayback/mathUtils.ts b/src/components/video-editor/videoPlayback/mathUtils.tsindex 78c9414f3..6553c622c 100644--- a/src/components/video-editor/videoPlayback/mathUtils.ts+++ b/src/components/video-editor/videoPlayback/mathUtils.ts@@ -68,8 +68,7 @@ export function smoothStep(t: number) {}/**- * Gentle ease-in-out cubic — slow start, smooth middle, gentle landing.- * Used for zoom-in transitions.+ * Ease-in-out cubic. Used for zoom-in transitions.*/export function easeInOutCubic(t: number) {const x = clamp01(t);@@ -77,8 +76,7 @@ export function easeInOutCubic(t: number) {}/**- * Ease-out cubic — starts at speed, then decelerates to a gentle stop.- * Used for zoom-out transitions so strength eases smoothly to zero.+ * Ease-out cubic. Used for zoom-out transitions so strength eases to zero.*/export function easeOutCubic(t: number) {const x = clamp01(t);diff --git a/src/components/video-editor/videoPlayback/videoEventHandlers.ts b/src/components/video-editor/videoPlayback/videoEventHandlers.tsindex a26107daa..3b26aa812 100644--- a/src/components/video-editor/videoPlayback/videoEventHandlers.ts+++ b/src/components/video-editor/videoPlayback/videoEventHandlers.ts@@ -1,9 +1,8 @@import type React from "react";import type { SpeedRegion, TrimRegion } from "../types";-// Keep "scrub mode" on for a brief tail after `seeked` — rapid drag-scrubbing-// fires `seeking`/`seeked` dozens of times per second, and toggling effects-// each time would flicker.+// Keep "scrub mode" on for a brief tail after `seeked`: rapid drag-scrubbing fires+// `seeking`/`seeked` dozens of times a second and toggling effects each time would flicker.const SCRUB_END_DEBOUNCE_MS = 150;interface VideoEventHandlersParams {@@ -51,7 +50,6 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {onTimeUpdate(timeValue);};- // Helper function to check if current time is within a trim regionconst findActiveTrimRegion = (currentTimeMs: number): TrimRegion | null => {const trimRegions = trimRegionsRef.current;return (@@ -61,7 +59,6 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {);};- // Helper function to find the active speed region at the current timeconst findActiveSpeedRegion = (currentTimeMs: number): SpeedRegion | null => {return (speedRegionsRef.current.find(@@ -76,11 +73,11 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {const currentTimeMs = video.currentTime * 1000;const activeTrimRegion = findActiveTrimRegion(currentTimeMs);- // If we're in a trim region during playback, skip to the end of it+ // In a trim region during playback: skip to its endif (activeTrimRegion && !video.paused && !video.ended) {const skipToTime = activeTrimRegion.endMs / 1000;- // If the skip would take us past the video duration, pause instead+ // Pause if the skip would run past the endif (skipToTime >= video.duration) {video.pause();} else {@@ -88,7 +85,6 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {emitTime(skipToTime);}} else {- // Apply playback speed from active speed regionconst activeSpeedRegion = findActiveSpeedRegion(currentTimeMs);video.playbackRate = activeSpeedRegion ? activeSpeedRegion.speed : 1;emitTime(video.currentTime);@@ -143,7 +139,7 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {const currentTimeMs = video.currentTime * 1000;const activeTrimRegion = findActiveTrimRegion(currentTimeMs);- // If we seeked into a trim region while playing, skip to the end+ // Seeked into a trim region while playing: skip to the endif (activeTrimRegion && isPlayingRef.current && !video.paused) {const skipToTime = activeTrimRegion.endMs / 1000;diff --git a/src/components/video-editor/videoPlayback/zoomRegionUtils.ts b/src/components/video-editor/videoPlayback/zoomRegionUtils.tsindex 1bfa4655b..34fceffe7 100644--- a/src/components/video-editor/videoPlayback/zoomRegionUtils.ts+++ b/src/components/video-editor/videoPlayback/zoomRegionUtils.ts@@ -271,8 +271,8 @@ type DominantRegionResult = {};// Single-slot cache: the ticker calls findDominantRegion at 60fps with mostly-// unchanged inputs (especially while paused). Reusing the previous result when-// inputs match avoids the per-frame O(N) region scan + allocations.+// unchanged inputs (especially while paused), so reusing the last result skips+// the per-frame O(N) scan and allocations.let dominantRegionCache: {regions: ZoomRegion[];timeMsKey: number;diff --git a/src/components/video-editor/videoPlayback/zoomSpring.ts b/src/components/video-editor/videoPlayback/zoomSpring.tsindex 6a49a5140..94e19250e 100644--- a/src/components/video-editor/videoPlayback/zoomSpring.ts+++ b/src/components/video-editor/videoPlayback/zoomSpring.ts@@ -8,11 +8,11 @@ import {/*** Spring-chase for the camera zoom transform.*- * The zoom envelope (`computeZoomTransform`) is a deterministic, time-driven *target* shaped by an- * ease curve. Applying it straight to the camera reproduces every velocity discontinuity in that- * curve — the steep launch of the ease-in, the seams between close regions — which reads as a jerk.- * Instead we chase the target with a spring per axis: the target supplies the authored timing, the- * spring guarantees the rendered motion is velocity-continuous, so it physically can't jerk.+ * computeZoomTransform is a time-driven target shaped by an ease curve. Applying it+ * straight to the camera reproduces every velocity discontinuity (the ease-in launch,+ * seams between close regions), which reads as a jerk. Instead we chase the target with+ * a per-axis spring: the target keeps the authored timing, the spring keeps the rendered+ * motion velocity-continuous.*/export interface ZoomTransform {@@ -49,9 +49,9 @@ export function resetZoomSpring(state: ZoomSpringState, target: ZoomTransform):}/**- * Step one axis toward `target`, with a moving-target overshoot clamp: because the target moves every- * frame, a fast (near-critical) spring can carry velocity past it on a reversal and wobble. If the- * step crosses the target, we snap to it and zero the velocity — keeping the spring quick without jelly.+ * Step one axis toward target with a moving-target overshoot clamp. The target moves+ * every frame, so a fast spring can carry velocity past it on a reversal and wobble. If+ * the step crosses the target, snap to it and zero the velocity to stay quick without jelly.*/function stepAxis(axis: SpringState,@@ -70,10 +70,7 @@ function stepAxis(return after;}-/**- * Advance the spring toward `target` by `deltaMs` (content time). Returns the smoothed transform to- * apply to the camera.- */+/** Advance the spring toward target by deltaMs (content time); returns the smoothed transform. */export function stepZoomSpring(state: ZoomSpringState,target: ZoomTransform,diff --git a/src/components/video-editor/videoPlayback/zoomTransform.ts b/src/components/video-editor/videoPlayback/zoomTransform.tsindex 800949f08..ea96077e2 100644--- a/src/components/video-editor/videoPlayback/zoomTransform.ts+++ b/src/components/video-editor/videoPlayback/zoomTransform.ts@@ -8,7 +8,7 @@ const MAX_AMOUNT_BOOST = 2.2;function getMotionBlurAmountResponse(motionBlurAmount: number) {const clampedAmount = Math.min(1, Math.max(0, motionBlurAmount));- // Keep the low end usable while giving the top of the slider substantially more headroom.+ // Keep the low end usable while giving the top of the slider more headroom.return clampedAmount * (1 + (MAX_AMOUNT_BOOST - 1) * clampedAmount);}@@ -90,8 +90,7 @@ export function computeZoomTransform({}const progress = Math.min(1, Math.max(0, zoomProgress));- // Focus coordinates are stage-normalized (0-1 of full canvas),- // so map directly to stage pixels, not through baseMask.+ // Focus coords are stage-normalized (0-1 of full canvas), so map directly to stage pixels, not via baseMask.const focusStagePxX = focusX * stageSize.width;const focusStagePxY = focusY * stageSize.height;const stageCenterX = stageSize.width / 2;@@ -173,7 +172,6 @@ export function applyZoomTransform({focusY,});- // Apply position & scale to camera containercameraContainer.scale.set(transform.scale);cameraContainer.position.set(transform.x, transform.y);diff --git a/src/contexts/I18nContext.tsx b/src/contexts/I18nContext.tsxindex 5d7534b34..894ba56d5 100644--- a/src/contexts/I18nContext.tsx+++ b/src/contexts/I18nContext.tsx@@ -106,7 +106,6 @@ export function I18nProvider({ children }: { children: ReactNode }) {// localStorage may be unavailable}document.documentElement.lang = newLocale;- // Notify Electron main processwindow.electronAPI?.setLocale?.(newLocale);}, []);diff --git a/src/hooks/audioPeaksWorker.ts b/src/hooks/audioPeaksWorker.tsindex 27812fd96..8a487193d 100644--- a/src/hooks/audioPeaksWorker.ts+++ b/src/hooks/audioPeaksWorker.ts@@ -1,11 +1,8 @@/*** Web Worker: computes min/max peak pairs from raw audio channel data.- *- * Input message: { channels: Float32Array[]; duration: number }- * Output message: Float32Array of length 2*N — [min0, max0, min1, max1, …]- *- * Channel buffers are transferred (zero-copy) from the caller.- * The peaks buffer is transferred back.+ * In: { channels: Float32Array[]; duration: number }.+ * Out: Float32Array of length 2*N, [min0, max0, min1, max1, ...].+ * Channel buffers and the peaks buffer are transferred (zero-copy).*/self.onmessage = (event: MessageEvent<{ channels: Float32Array[]; duration: number }>) => {const { channels, duration } = event.data;@@ -18,7 +15,7 @@ self.onmessage = (event: MessageEvent<{ channels: Float32Array[]; duration: numbconst totalSamples = channels[0].length;const N = Math.min(24000, Math.ceil(duration * 200));const blockSize = totalSamples / N;- const peaks = new Float32Array(N * 2); // [min0, max0, min1, max1, …]+ const peaks = new Float32Array(N * 2); // [min0, max0, min1, max1, ...]for (let i = 0; i < N; i++) {const start = Math.floor(i * blockSize);diff --git a/src/hooks/recorderHandle.ts b/src/hooks/recorderHandle.tsindex e98000e6e..6264b9be5 100644--- a/src/hooks/recorderHandle.ts+++ b/src/hooks/recorderHandle.ts@@ -3,23 +3,19 @@ const RECORDER_TIMESLICE_MS = 1000;export type RecorderHandle = {recorder: MediaRecorder;/**- * Resolves once the recording has fully drained. For a streamed recording the- * blob is empty (the bytes are already on disk); for an in-memory recording it- * holds the full WebM. Rejects if a chunk failed to write to disk mid-stream,- * so a truncated recording surfaces as an error instead of a silent partial save.+ * Resolves once the recording drains. Empty blob when streamed (bytes already on+ * disk), full WebM when in-memory. Rejects on a mid-stream write failure so a+ * truncated recording surfaces as an error instead of a silent partial save.*/recordedBlobPromise: Promise<Blob>;/**- * Whether the recording's bytes went to disk via the streaming path. Computed- * at finalize time rather than construction, so a stream that fails to open is- * correctly reported as not-streamed and its in-memory fallback is used.+ * Whether bytes went to disk via streaming. Computed at finalize, not construction,+ * so a stream that fails to open reports as not-streamed and uses its memory fallback.*/isStreaming: () => boolean;/**- * Close the disk stream (if one opened) and delete its partial file. Called- * when a recording is discarded or fails before a successful save, so cancelled- * runs don't leak the stream or orphan a partial file. No-op for in-memory- * recorders.+ * Close the disk stream (if any) and delete its partial file. Called when a recording+ * is discarded or fails before save, so cancelled runs don't leak. No-op in-memory.*/discard: () => Promise<void>;};@@ -27,13 +23,10 @@ export type RecorderHandle = {/*** Wrap a MediaRecorder, optionally streaming its chunks to disk.*- * When `fileName` is given, chunks are written to disk in arrival order through- * the main process as they arrive, so a long recording never buffers the whole- * video in the renderer (the #616 fix). Until the disk stream confirms it is- * open, chunks are held in memory; if the open fails, that buffer becomes a- * complete in-memory fallback so nothing is lost. Native-capture webcam sidecars- * omit `fileName` and always buffer in memory, since their finalize path reads- * the blob directly to attach the webcam track.+ * With `fileName`, chunks stream to disk through the main process so a long recording+ * never buffers the whole video in the renderer (#616). Chunks held in memory until the+ * stream confirms open; if the open fails, that buffer is the complete fallback. Webcam+ * sidecars omit `fileName` and buffer in memory, since finalize reads the blob directly.*/export function createRecorderHandle(stream: MediaStream,@@ -44,26 +37,23 @@ export function createRecorderHandle(const mimeType = options.mimeType || "video/webm";const api = window.electronAPI;- // Chunks held in memory: everything before the stream opens, plus everything- // when not streaming at all. On a successful open these flush to disk and are- // dropped; on open failure they remain as the complete fallback recording.+ // Chunks held in memory before the stream opens, or for the whole recording when not+ // streaming. On open they flush to disk and drop; on open failure they're the fallback.const memoryChunks: Blob[] = [];let mode: "pending" | "streaming" | "buffering" = fileName ? "pending" : "buffering";let streamOpened = false;let appendError: Error | null = null;- // Serialize chunk writes so they land on disk in arrival order, and so stop- // can await every in-flight write before the main process closes the stream- // (otherwise a late chunk arrives after close and truncates the recording).+ // Serialize writes so chunks land in arrival order and stop can await every in-flight+ // write before the stream closes (a late chunk after close truncates the recording).let writeChain: Promise<void> = Promise.resolve();const enqueueWrite = (chunk: Blob) => {writeChain = writeChain.then(async () => {if (appendError || !fileName || !api?.appendRecordingChunk) {return;}- // Capture both outcomes — a `{ success: false }` result and an outright- // rejection (channel/handler error) — into appendError, so writeChain- // never rejects and isStreaming() stays consistent after a failure.+ // Capture both a `{ success: false }` result and an outright rejection into+ // appendError, so writeChain never rejects and isStreaming() stays consistent.try {const buffer = await chunk.arrayBuffer();const result = await api.appendRecordingChunk(fileName, buffer);@@ -76,10 +66,9 @@ export function createRecorderHandle(});};- // Require BOTH stream IPC methods before attempting to stream. If only- // openRecordingStream exists (renderer/main version skew), streaming would- // open but every append would silently no-op, saving an empty file — so in- // that case fall through to in-memory buffering instead.+ // Require both stream IPC methods before streaming. With only openRecordingStream+ // (renderer/main version skew) the open succeeds but appends no-op, saving an empty+ // file, so fall through to in-memory buffering instead.const openPromise: Promise<{ success: boolean; error?: string }> =fileName !== undefined &&typeof api?.openRecordingStream === "function" &&@@ -101,8 +90,7 @@ export function createRecorderHandle(}},() => {- // The IPC call itself rejected (channel or handler error). Treat it the- // same as a failed open: keep buffering in memory so nothing is lost.+ // IPC call rejected. Treat like a failed open: keep buffering in memory.mode = "buffering";},);@@ -115,7 +103,7 @@ export function createRecorderHandle(if (mode === "streaming") {enqueueWrite(event.data);} else {- // "pending" (stream not open yet) or "buffering" (not streaming).+ // pending (stream not open yet) or buffering (not streaming).memoryChunks.push(event.data);}};@@ -130,9 +118,9 @@ export function createRecorderHandle(});async function finalizeBlob(): Promise<Blob> {- // Wait for the open attempt to settle so its flush (or fallback switch) has- // been applied, then for every queued write to land, so we never resolve- // while chunks are still in flight to the about-to-close disk stream.+ // Wait for the open to settle (flush or fallback applied) then for every queued+ // write to land, so we don't resolve while chunks are still in flight to the+ // about-to-close stream.await openPromise.catch(() => undefined);await writeChain;if (appendError) {diff --git a/src/hooks/useAudioPeaks.ts b/src/hooks/useAudioPeaks.tsindex 085504d96..337f50344 100644--- a/src/hooks/useAudioPeaks.ts+++ b/src/hooks/useAudioPeaks.ts@@ -10,8 +10,7 @@ function getAudioCtx(): AudioContext {/*** Offloads peak computation to a Web Worker (zero-copy via Transferable).- * Accepts an optional AbortSignal — if aborted, the worker is terminated- * immediately and the promise rejects with an AbortError.+ * On abort, the worker is terminated and the promise rejects with AbortError.*/function computePeaksInWorker(audioBuffer: AudioBuffer,@@ -60,15 +59,10 @@ function computePeaksInWorker(}/**- * Decodes audio from `videoUrl` and returns a Float32Array of paired- * [min, max] peak values (length = 2 * N blocks). Returns `null` while- * decoding is in progress, and stays `null` when the file has no audio- * track or decoding fails (silent degradation).- *- * - File loading uses the Electron IPC bridge for local paths (same as the exporter).- * - Peak computation runs in a Web Worker to avoid blocking the main thread.- * - Results are cached in a ref scoped to the hook instance (survives re-renders- * and waveform toggle off/on, but not component unmount).+ * Decodes audio from `videoUrl` into paired [min, max] peaks (length = 2 * N+ * blocks). Returns `null` while decoding, and stays `null` on no audio track or+ * decode failure (silent degradation). Results are cached in a ref scoped to the+ * hook instance, so they survive re-renders and waveform toggles but not unmount.*/export function useAudioPeaks(videoUrl?: string): Float32Array | null {const cacheRef = useRef<Map<string, Float32Array>>(new Map());@@ -103,10 +97,10 @@ export function useAudioPeaks(videoUrl?: string): Float32Array | null {cacheRef.current.set(videoUrl, p);setPeaks(p);} catch (err) {- // AbortError means the effect cleaned up — no state update needed.+ // AbortError means the effect cleaned up, so no state update needed.if (err instanceof DOMException && err.name === "AbortError") return;- // No audio track or unsupported format — degrade gracefully (no- // waveform), but log so an unexpectedly-missing waveform is diagnosable.+ // No audio track or unsupported format: degrade to no waveform, but log+ // so an unexpectedly-missing waveform is diagnosable.console.warn("useAudioPeaks: could not decode audio for waveform:", err);if (!cancelled) setPeaks(null);}diff --git a/src/hooks/useCameraDevices.test.ts b/src/hooks/useCameraDevices.test.tsindex 5ca21bc85..e6ec8a9ed 100644--- a/src/hooks/useCameraDevices.test.ts+++ b/src/hooks/useCameraDevices.test.ts@@ -91,7 +91,7 @@ describe("useCameraDevices", () => {expect(result.current.selectedDeviceId).toBe("cam1");});- // Simulate cam1 being unplugged — only cam2 remains+ // Simulate cam1 being unplugged, only cam2 remainsconst cam2Only = [{ kind: "videoinput", deviceId: "cam2", label: "Camera 2", groupId: "group1" },];diff --git a/src/hooks/useCameraDevices.ts b/src/hooks/useCameraDevices.tsindex a02e65aa2..bf402c7f0 100644--- a/src/hooks/useCameraDevices.ts+++ b/src/hooks/useCameraDevices.ts@@ -23,8 +23,8 @@ export function useCameraDevices(enabled: boolean = false) {setIsLoading(true);setError(null);- // Enumerate without requesting a second stream — the recorder handles- // the real acquisition; unlabeled devices fall back to their device ID.+ // Enumerate without requesting a second stream; the recorder handles+ // the real acquisition. Unlabeled devices fall back to their device ID.const allDevices = await navigator.mediaDevices.enumerateDevices();const videoInputs = allDevices.filter((device) => device.kind === "videoinput")diff --git a/src/hooks/useEditorHistory.ts b/src/hooks/useEditorHistory.tsindex 0b27ee067..9ca00440b 100644--- a/src/hooks/useEditorHistory.ts+++ b/src/hooks/useEditorHistory.ts@@ -22,8 +22,8 @@ import {} from "@/components/video-editor/types";import type { AspectRatio } from "@/utils/aspectRatioUtils";-// Undoable state — selection IDs are intentionally excluded (undoing a-// selection change would feel surprising to the user).+// Undoable state. Selection IDs are excluded, since undoing a selection change+// would feel surprising.export interface EditorState {zoomRegions: ZoomRegion[];/** Magic-wand auto-zoom toggle. When on, fresh recordings get suggested zooms. */@@ -101,8 +101,8 @@ function withCheckpoint(history: History, newPresent: EditorState): History {export function useEditorHistory(initial: EditorState = INITIAL_EDITOR_STATE) {const [history, setHistory] = useState<History>({ past: [], present: initial, future: [] });- // Tracks whether a live-update series (e.g. slider drag) is in progress.- // The first updateState call saves the pre-interaction state as a checkpoint.+ // True while a live-update series (e.g. slider drag) is in progress. The first+ // updateState call checkpoints the pre-interaction state.const dirtyRef = useRef(false);const pushState = useCallback((update: StateUpdate) => {diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.tsindex e0db20ed9..ce0e0b77f 100644--- a/src/hooks/useScreenRecorder.ts+++ b/src/hooks/useScreenRecorder.ts@@ -135,10 +135,9 @@ export function useScreenRecorder(): UseScreenRecorderReturn {}, []);const selectMimeType = () => {- // H.264 first: hardware-accelerated on all modern devices, gives sharp- // real-time output. AV1/VP9 are great for distribution but too- // CPU-intensive for live 60 fps capture — they produce blurry frames- // when the software encoder can't keep up.+ // H.264 first: hardware-accelerated, so sharp real-time output. AV1/VP9 are+ // better for distribution but too CPU-heavy for live 60 fps capture (software+ // encoder falls behind and produces blurry frames).const preferred = ["video/webm;codecs=h264","video/webm;codecs=vp8",@@ -339,7 +338,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {window.electronAPI?.discardCursorTelemetry(activeRecordingId);return;}- // When streaming succeeded the blob is empty — the data is already on disk.+ // When streaming succeeded the blob is empty; the data is already on disk.if (!activeScreenRecorder.isStreaming() && screenBlob.size === 0) {return;}@@ -398,10 +397,9 @@ export function useScreenRecorder(): UseScreenRecorderReturn {} catch (error) {console.error("Error saving recording:", error);} finally {- // Discard any recorder whose data was not part of a successful save- // — a discarded run, a failed save, or a webcam whose disk write- // failed (so it was omitted while the screen still saved) — so no- // stream or partial file is left open or orphaned.+ // Discard any recorder whose data wasn't part of a successful save (discarded+ // run, failed save, or a webcam whose disk write failed while the screen still+ // saved) so no stream or partial file is left open or orphaned.if (!storeSucceeded) {await activeScreenRecorder.discard().catch(() => undefined);}diff --git a/src/lib/captioning/annotationsFromCaptions.ts b/src/lib/captioning/annotationsFromCaptions.tsindex 0f6dc2af4..c3e22b21d 100644--- a/src/lib/captioning/annotationsFromCaptions.ts+++ b/src/lib/captioning/annotationsFromCaptions.ts@@ -2,7 +2,7 @@ import type { AnnotationRegion, AnnotationTextStyle } from "@/components/video-eimport type { CaptionSegment } from "./transcribe";-/** Wide lower-third bar; `position.x` is top-left as % of container, so center with (100 − width) / 2. */+/** Wide lower-third bar; `position.x` is top-left as % of container, so center with (100 - width) / 2. */const CAPTION_WIDTH = 92;const CAPTION_HEIGHT = 12;const CAPTION_BOTTOM_MARGIN = 2;@@ -25,16 +25,10 @@ const CAPTION_STYLE: AnnotationTextStyle = {textAlign: "center",};-/**- * Nudge caption **starts** earlier (seconds). Whisper onsets are often slightly late vs. what you- * hear; do **not** apply the same offset to ends — that pulls lines off-screen too early.- */+/** Nudge caption starts earlier (seconds); Whisper onsets run slightly late. Do not offset ends too, that pulls lines off-screen early. */const AUTO_CAPTION_START_BIAS_SEC = 0;-/**- * Extra time held after Whisper’s segment **end** (seconds). Model end times are often early vs.- * trailing vowels / room tone; this is separate from `AUTO_CAPTION_START_BIAS_SEC`.- */+/** Extra hold after Whisper's segment end (seconds); model end times run early vs trailing vowels. Separate from the start bias. */const AUTO_CAPTION_END_HOLD_SEC = 0;/** Inside one Whisper phrase, sub-lines can be shorter (do not steal time from neighbors). */@@ -46,13 +40,10 @@ const CAPTION_LINE_END_TAIL_SEC = 0;/** A real silence between word-level timestamps should start a new caption run. */const WORD_RUN_BREAK_GAP_SEC = 0.24;-/**- * Minimum time between consecutive caption regions on the timeline (seconds). Keeps a visible gap- * so blocks do not read as one clip; kept small so we do not erase natural short pauses between phrases.- */+/** Min time between consecutive caption regions (seconds); keeps a visible gap so blocks don't read as one clip. Small so short pauses survive. */const MIN_CAPTION_TIMELINE_GAP_SEC = 0;-/** Same text again with almost no gap or overlap — common Whisper / chunk artifact. */+/** Same text again with almost no gap or overlap; common Whisper/chunk artifact. */const DEDUPE_SAME_TEXT_MAX_GAP_SEC = 0.55;export const SAME_CONTENT_ECHO_MAX_GAP_SEC = 1.15;@@ -96,10 +87,6 @@ export function collapseSameContentEchoes(segments: CaptionSegment[]): CaptionSereturn out;}-/**- * Only merge segments that are almost back-to-back (Whisper often splits mid-phrase with a tiny gap).- * Wider gaps are usually silence or missed audio — merging those stretches word timing across dead air.- *//*** Collapse adjacent duplicate lines (overlapping or tiny gap). Does not merge the same phrase* repeated later in the video when separated by real silence.@@ -155,9 +142,8 @@ function finalizeCaptionSegmentsForPlayback(segments: CaptionSegment[]): Captionexport const DEFAULT_AUTO_CAPTION_MIN_GAP_MS = Math.round(MIN_CAPTION_TIMELINE_GAP_SEC * 1000);/**- * Enforces a minimum gap between consecutive `auto-caption` regions (by start time). Shortens the- * previous region's end when possible; otherwise shifts the following region later so edits on- * the timeline cannot squeeze caption blocks completely flush.+ * Enforce a min gap between consecutive `auto-caption` regions (by start time). Shortens the previous+ * region's end when possible, else shifts the following region later so blocks can't sit completely flush.*/export function reconcileAutoCaptionTimelineGaps(regions: AnnotationRegion[],@@ -392,7 +378,7 @@ export function groupTimedCaptionWordsIntoLines(/*** Splits each merged transcription span into shorter captions with about- * `minWords`–`maxWords` words. Times are interpolated by character weight inside the span.+ * `minWords`-`maxWords` words. Times are interpolated by character weight inside the span.*/export function splitMergedCaptionsByWordBounds(merged: CaptionSegment[],@@ -561,7 +547,7 @@ export function captionSegmentsToAnnotationRegions(startZIndex: number,layout?: CaptionSegmentLayoutOptions,): { regions: AnnotationRegion[]; nextNumericId: number; nextZIndex: number } {- // Do not echo-collapse raw word tokens before grouping: repeated words ("I … I") share a+ // Don't echo-collapse raw word tokens before grouping: repeated words ("I … I") share a// normalized key and would merge spans while keeping only the first token's text.const minW = layout?.minWordsPerCaption ?? 2;const maxW = layout?.maxWordsPerCaption ?? 7;diff --git a/src/lib/captioning/extractMono16k.ts b/src/lib/captioning/extractMono16k.tsindex 53258567c..bce9a9fd8 100644--- a/src/lib/captioning/extractMono16k.ts+++ b/src/lib/captioning/extractMono16k.ts@@ -22,9 +22,9 @@ async function fetchWithTimeout(url: string, signal?: AbortSignal): Promise<Resp}/**- * Load the editor video the same way as `StreamingVideoDecoder`:- * Electron `readBinaryFile` for local paths (fetch(file://) is unreliable in the renderer),- * otherwise HTTP / blob / data URLs via fetch.+ * Load the editor video like `StreamingVideoDecoder`: Electron `readBinaryFile`+ * for local paths (fetch(file://) is unreliable in the renderer), otherwise+ * HTTP/blob/data URLs via fetch.*/async function loadSourceVideoFile(videoUrl: string, signal?: AbortSignal): Promise<File> {const isRemoteUrl = /^(https?:|blob:|data:)/i.test(videoUrl);@@ -104,7 +104,7 @@ async function truncateAndResampleTo16k(/*** Decode the video's audio track to mono 16 kHz float samples (Whisper input).- * Prefers `decodeAudioData` when the container is supported; otherwise uses the same+ * Prefers `decodeAudioData` when the container is supported, else the same* web-demuxer + AudioDecoder path as export.*/export async function extractMono16kFromVideoUrl(@@ -137,7 +137,7 @@ export async function extractMono16kFromVideoUrl(const fromRate = audioBuffer.sampleRate;const out = await truncateAndResampleTo16k(mono, fromRate, durationSec, options?.signal);// decodeAudioData can resolve for some WebM/Matroska inputs yet yield almost no usable- // PCM; captions only run the demuxer path on throw today, so we never recover.+ // PCM, and captions only fall back to the demuxer path on throw, so return null to recover.if (out.samples.length < 800) {return null;}diff --git a/src/lib/captioning/extractMono16kWebDemuxer.ts b/src/lib/captioning/extractMono16kWebDemuxer.tsindex fd85f5703..f86b6dc57 100644--- a/src/lib/captioning/extractMono16kWebDemuxer.ts+++ b/src/lib/captioning/extractMono16kWebDemuxer.ts@@ -89,8 +89,8 @@ function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promi}/**- * Demux + WebCodecs audio decode (same stack as export). Use when- * `decodeAudioData` cannot handle the container (e.g. WebM with video).+ * Demux + WebCodecs audio decode (same stack as export). Use when `decodeAudioData`+ * can't handle the container (e.g. WebM with video).*/export async function extractMonoPcmViaWebDemuxer(file: File,@@ -128,9 +128,9 @@ export async function extractMonoPcmViaWebDemuxer(const sampleRate = audioConfig.sampleRate || 48_000;- // Many WebM/Matroska files report a too-short duration; capping read at reported time stops- // demux early and mergeAndConsumeDecodedAudioToMonoLinear clips everything past that. Read up to the- // same ceiling as caption decode (demuxer stops when the track ends).+ // Many WebM/Matroska files report a too-short duration, so capping read at reported time stops+ // demux early and clips everything past that. Read to the caption-decode ceiling instead; the+ // demuxer stops when the track ends.const readEndSec = MAX_CAPTION_AUDIO_SEC + READ_END_PADDING_SEC;const decodedFrames: AudioData[] = [];@@ -178,8 +178,8 @@ export async function extractMonoPcmViaWebDemuxer(if (end > maxEndUs) maxEndUs = end;}const inferredDurationSec = maxEndUs / 1e6;- // Prefer extent implied by decoded frames (fixes bad container duration). If frames lack- // duration, fall back to reported metadata.+ // Prefer extent implied by decoded frames (fixes bad container duration); fall back to reported+ // metadata when frames lack duration.const durationSec = inferredDurationSec > 0.02 ? inferredDurationSec : reportedDurationSec;const mono = mergeAndConsumeDecodedAudioToMonoLinear(decodedFrames, sampleRate, durationSec);diff --git a/src/lib/captioning/transcribe.ts b/src/lib/captioning/transcribe.tsindex 1a24320d3..a72a89673 100644--- a/src/lib/captioning/transcribe.ts+++ b/src/lib/captioning/transcribe.ts@@ -19,9 +19,9 @@ export interface TranscribeWorkerRequest {samples: Float32Array;trimRegions: TrimRegion[];/**- * When true, the worker loads the Whisper model + ORT wasm from the app's bundled `caption-assets`- * instead of remote CDNs — required in the packaged app, which runs from `file://` where remote- * fetches fail. The worker can't read `window.electronAPI`, so the renderer resolves these here.+ * Load the Whisper model + ORT wasm from bundled `caption-assets` instead of remote CDNs.+ * Required in the packaged app (runs from `file://` where remote fetches fail). The worker+ * can't read `window.electronAPI`, so the renderer resolves this here.*/useLocalModels: boolean;/** Base URL of bundled resources (packaged: resourcesPath file:// URL); used when `useLocalModels`. */@@ -37,10 +37,9 @@ export type TranscribeWorkerResponse =/*** Transcribes mono 16 kHz audio into timed caption segments using in-browser Whisper.*- * The model load and inference run inside a dedicated Web Worker so the editor's- * main thread stays responsive (WASM inference does not yield). The first run- * downloads model weights. Aborting (via `options.signal`) terminates the worker- * immediately, since model load / inference cannot be cooperatively cancelled.+ * Runs in a Web Worker so the editor's main thread stays responsive (WASM inference+ * doesn't yield). First run downloads model weights. Aborting via `options.signal`+ * terminates the worker, since load/inference can't be cooperatively cancelled.*/export function transcribeMono16kToSegments(samples: Float32Array,@@ -88,14 +87,14 @@ export function transcribeMono16kToSegments(finish(() => reject(new Error(e.message || "Caption transcription worker failed")));};- // Packaged app runs from file:// (remote model/wasm fetches fail there) → load bundled assets.- // Dev runs from http://localhost where the remote path works, so keep using it.+ // Packaged app runs from file:// (remote fetches fail), so load bundled assets.+ // Dev runs from http://localhost where the remote path works.const useLocalModels = typeof window !== "undefined" && window.location?.protocol === "file:";const assetBaseUrl =typeof window !== "undefined" ? window.electronAPI?.assetBaseUrl : undefined;- // Structured-clone copy (not a transfer): the caller may reuse `samples`- // for the full-buffer retry pass, so the buffer must stay valid here.+ // Structured-clone copy, not a transfer: the caller may reuse `samples` for the+ // full-buffer retry pass, so the buffer must stay valid here.const request: TranscribeWorkerRequest = {samples,trimRegions: options?.trimRegions ?? [],diff --git a/src/lib/captioning/transcribe.worker.ts b/src/lib/captioning/transcribe.worker.tsindex 86d42010d..ab65b2eea 100644--- a/src/lib/captioning/transcribe.worker.ts+++ b/src/lib/captioning/transcribe.worker.ts@@ -1,15 +1,11 @@/**- * Web Worker: runs in-browser Whisper transcription off the renderer's main- * thread so the editor UI never blocks while the model loads or audio is- * transcribed.+ * Web Worker running in-browser Whisper transcription off the renderer's main+ * thread so the editor UI never blocks during model load or transcription.*- * Input message: { samples: Float32Array; trimRegions: TrimRegion[] }- * Output messages (see `TranscribeWorkerResponse`):- * { type: "status", phase: "model" | "transcribe" } progress updates- * { type: "result", segments, granularity } final captions- * { type: "error", message } failure detail+ * Input: { samples: Float32Array; trimRegions: TrimRegion[] }+ * Output (see `TranscribeWorkerResponse`): status / result / error messages.*- * The caller terminates this worker to abort (model load / inference cannot be+ * The caller terminates this worker to abort (model load and inference can't be* cooperatively cancelled), so there is no in-worker abort handling.*/@@ -22,8 +18,8 @@ function post(message: TranscribeWorkerResponse): void {/*** ONNX Runtime's wasm bundle treats `process.versions.node` (which can leak into- * an Electron worker) as Node and tries `require("fs")`, which Vite does not- * support. Mask it only while Transformers / ORT run. No-op when `process` is+ * an Electron worker) as Node and tries `require("fs")`, which Vite doesn't+ * support. Mask it only while Transformers/ORT run. No-op when `process` is* undefined (the usual case in a Web Worker).*/function withoutNodeVersion<T>(fn: () => Promise<T>): Promise<T> {@@ -54,8 +50,8 @@ async function loadTranscriber(opts: {return withoutNodeVersion(async () => {const { pipeline, env } = await import("@xenova/transformers");if (opts.useLocalModels && opts.assetBaseUrl) {- // Packaged app: load the bundled model + ORT wasm from disk so transcription needs no- // network and resolves under file:// (remote HuggingFace/CDN fetches fail there).+ // Packaged app: load the bundled model and ORT wasm from disk so transcription+ // needs no network and works under file:// (remote HuggingFace/CDN fetches fail there).const base = new URL("caption-assets/", opts.assetBaseUrl).href;env.allowLocalModels = true;env.allowRemoteModels = false;@@ -67,8 +63,8 @@ async function loadTranscriber(opts: {// Dev (http://localhost): fetch from the remote CDN, which works there.env.allowLocalModels = false;}- // Default tiny weights only: the `output_attentions` revision has regressed inference for- // some environments (empty chunks / thrown errors) while phrase mode works on this model.+ // Default tiny weights only: the `output_attentions` revision regresses inference in+ // some environments (empty chunks, thrown errors) while phrase mode works on this model.const transcriber = (await pipeline("automatic-speech-recognition","Xenova/whisper-tiny",diff --git a/src/lib/captioning/transcribeCore.ts b/src/lib/captioning/transcribeCore.tsindex 111995246..9834e3654 100644--- a/src/lib/captioning/transcribeCore.ts+++ b/src/lib/captioning/transcribeCore.ts@@ -2,10 +2,9 @@ import type { TrimRegion } from "@/components/video-editor/types";import type { CaptionSegment, TranscribeMono16kResult } from "./transcribe";/**- * Pure transcription algorithm shared by the captioning Web Worker. It takes an- * already-constructed Whisper `transcriber` and turns mono 16 kHz audio into- * timed caption segments. Kept free of DOM / Transformers.js imports so it can- * run inside a worker and be unit-tested in isolation.+ * Pure transcription algorithm for the captioning Web Worker: takes a built Whisper+ * `transcriber` and turns mono 16 kHz audio into timed caption segments. No DOM or+ * Transformers.js imports so it runs in a worker and unit-tests in isolation.*//** A Transformers.js automatic-speech-recognition pipeline call. */@@ -178,8 +177,8 @@ function extractChunksFromAsrResult(result: unknown): Array<{/*** Drives Whisper over (possibly sliced) mono 16 kHz audio and returns timed segments.- * Long audio is split so one forward pass does not exhaust WASM memory; timestamps are- * shifted back onto the full timeline. Tries word- then phrase-level timestamps, with a+ * Long audio is split so one pass doesn't exhaust WASM memory; timestamps are shifted+ * back onto the full timeline. Tries word- then phrase-level timestamps, with a* trim-ignoring retry, before giving up.*/export async function runTranscription(diff --git a/src/lib/compositeLayout.test.ts b/src/lib/compositeLayout.test.tsindex 65cdfd573..51c3fd0b7 100644--- a/src/lib/compositeLayout.test.ts+++ b/src/lib/compositeLayout.test.ts@@ -69,7 +69,7 @@ describe("computeCompositeLayout", () => {expect(landscape).not.toBeNull();expect(portrait).not.toBeNull();- // Same total pixel count — webcam area should be comparable+ // Same total pixel count, so webcam area should be comparable.const landscapeArea = landscape!.webcamRect!.width * landscape!.webcamRect!.height;const portraitArea = portrait!.webcamRect!.width * portrait!.webcamRect!.height;expect(landscapeArea).toBe(portraitArea);@@ -135,10 +135,8 @@ describe("computeCompositeLayout", () => {webcamSizePreset: 100,});- // Values below 10 should clamp to 10expect(belowMin!.webcamRect!.width).toBe(atMin!.webcamRect!.width);expect(belowMin!.webcamRect!.height).toBe(atMin!.webcamRect!.height);- // Values above 50 should clamp to 50expect(aboveMax!.webcamRect!.width).toBe(atMax!.webcamRect!.width);expect(aboveMax!.webcamRect!.height).toBe(atMax!.webcamRect!.height);});diff --git a/src/lib/compositeLayout.ts b/src/lib/compositeLayout.tsindex a0ee58d89..5eedb266d 100644--- a/src/lib/compositeLayout.ts+++ b/src/lib/compositeLayout.ts@@ -9,11 +9,10 @@ export interface RenderRect {export const WEBCAM_REACTIVE_ZOOM_MIN_SCALE = 0.35;/**- * Maps the live (spring-animated) zoom scale to a webcam size multiplier. The camera scales- * inversely to the zoom — at 2× zoom it's half size, at 3× a third — so it stays out of the way- * as you zoom into content, then returns to full size as the zoom eases back. Clamped to a floor- * so it never disappears. Because `appliedScale` is already eased every frame, the camera animates- * in sync with the zoom for free.+ * Maps the live zoom scale to a webcam size multiplier, inversely (2x zoom, half size; 3x, a+ * third) so the camera stays out of the way while zoomed and returns to full size as zoom eases+ * back. Clamped to a floor so it never disappears. appliedScale is already eased per frame, so+ * the camera animates in sync for free.*/export function reactiveWebcamScale(zoomScale: number): number {const safe = Number.isFinite(zoomScale) && zoomScale > 0 ? zoomScale : 1;@@ -207,7 +206,7 @@ export function computeCompositeLayout(params: {const { width: canvasWidth, height: canvasHeight } = canvasSize;const { width: screenWidth, height: screenHeight } = screenSize;- // "no-webcam" preset: hide the webcam entirely, screen fills the canvas normally+ // no-webcam: hide the webcam, screen fills the canvas normally.if (layoutPreset === "no-webcam") {const screenRect = centerRect({canvasSize,@@ -229,7 +228,7 @@ export function computeCompositeLayout(params: {if (preset.transform.type === "stack") {if (!webcamWidth || !webcamHeight || webcamWidth <= 0 || webcamHeight <= 0) {- // No webcam — screen fills the entire canvas (cover mode)+ // No webcam, so screen fills the whole canvas (cover mode).return {screenRect: { x: 0, y: 0, width: canvasWidth, height: canvasHeight },webcamRect: null,@@ -237,12 +236,12 @@ export function computeCompositeLayout(params: {};}- // Webcam: full width at the bottom, maintaining its aspect ratio+ // Webcam: full width at the bottom, keeping aspect ratio.const webcamAspect = webcamWidth / webcamHeight;const resolvedWebcamWidth = canvasWidth;const resolvedWebcamHeight = Math.round(canvasWidth / webcamAspect);- // Screen: fills remaining space at the top (cover mode — may crop sides)+ // Screen: fills remaining space at the top (cover mode, may crop sides).const screenRectHeight = canvasHeight - resolvedWebcamHeight;return {@@ -341,8 +340,7 @@ export function computeCompositeLayout(params: {transform.minMargin,Math.round(Math.min(canvasWidth, canvasHeight) * transform.marginFraction),);- // Use geometric mean so the webcam occupies a consistent visual proportion- // regardless of whether the canvas is portrait or landscape.+ // Geometric mean so the webcam keeps a consistent visual proportion in portrait or landscape.const referenceDim = Math.sqrt(canvasWidth * canvasHeight);const maxWidth = Math.max(transform.minSize, referenceDim * MAX_STAGE_FRACTION);const maxHeight = Math.max(transform.minSize, referenceDim * MAX_STAGE_FRACTION);@@ -361,10 +359,10 @@ export function computeCompositeLayout(params: {let webcamY: number;if (webcamPosition) {- // Custom position: cx/cy represent the center of the webcam as a fraction of the canvas+ // cx/cy are the webcam center as a fraction of the canvas.webcamX = Math.round(webcamPosition.cx * canvasWidth - width / 2);webcamY = Math.round(webcamPosition.cy * canvasHeight - height / 2);- // Clamp to stay within canvas bounds+ // Clamp inside canvas bounds.webcamX = Math.max(0, Math.min(canvasWidth - width, webcamX));webcamY = Math.max(0, Math.min(canvasHeight - height, webcamY));} else {diff --git a/src/lib/cursor/cursorPathSmoothing.test.ts b/src/lib/cursor/cursorPathSmoothing.test.tsindex deea614ea..e9bdd5e38 100644--- a/src/lib/cursor/cursorPathSmoothing.test.ts+++ b/src/lib/cursor/cursorPathSmoothing.test.ts@@ -6,7 +6,7 @@ function makeRecording(samples: CursorRecordingSample[]): CursorRecordingData {return { version: 2, provider: "native", assets: [], samples };}-/** Sum of squared second differences of x sampled on a uniform grid — a roughness proxy. */+/** Roughness proxy: sum of squared second differences of x on a uniform grid. */function roughness(sampleAt: (t: number) => { cx: number; cy: number } | null,t0: number,diff --git a/src/lib/cursor/cursorPathSmoothing.ts b/src/lib/cursor/cursorPathSmoothing.tsindex 1bdd51b30..e89b9575d 100644--- a/src/lib/cursor/cursorPathSmoothing.ts+++ b/src/lib/cursor/cursorPathSmoothing.ts@@ -4,12 +4,9 @@ import type { CursorRecordingData, CursorRecordingSample } from "@/native/contra/*** Offline cursor-path smoothing for native recordings.*- * Live preview/export used to run a per-frame exponential filter over the cursor — causal,- * framerate-dependent, and momentum-free. Because post-processing has the entire path up front, we- * instead precompute a smoothed path once: resample to a fixed high rate, lightly denoise away- * capture tremor, then drive a spring-damper (mass/stiffness/damping) over the result. The spring- * gives the motion natural inertia — it trails the real cursor like a weight on a string — which- * reads as a professional glide. The result is deterministic, so preview and export match exactly.+ * We have the whole path up front, so instead of a per-frame causal filter we precompute once:+ * resample to a fixed high rate, then run a spring-damper over it. The spring gives the motion+ * inertia (it trails the real cursor) and is deterministic, so preview and export match exactly.*/export interface SmoothedCursorPosition {@@ -22,7 +19,7 @@ export interface SmoothedCursorPath {sampleAt(timeMs: number): SmoothedCursorPosition | null;}-/** Integration grid: 240 steps/sec keeps the spring stable and the output crisp at any playback fps. */+/** 240 steps/sec keeps the spring stable and crisp at any playback fps. */const STEP_MS = 1000 / 240;const STEP_S = STEP_MS / 1000;@@ -77,8 +74,8 @@ function interpolateRun(samples: CursorRecordingSample[], timeMs: number): Smoot}/**- * Drive a critically-tunable spring across `targets`, returning the smoothed series. Semi-implicit- * (symplectic) Euler in seconds — stable for these stiffness values at the 240Hz grid.+ * Drive a spring across `targets`, returning the smoothed series. Semi-implicit+ * (symplectic) Euler, stable for these stiffness values at the 240Hz grid.*/function springSmooth(targets: Float32Array,@@ -100,7 +97,7 @@ function springSmooth(return out;}-/** Maximal sequences of visible samples — we never smooth across a hidden gap. */+/** Maximal runs of visible samples, so we never smooth across a hidden gap. */function splitVisibleRuns(samples: CursorRecordingSample[]): CursorRecordingSample[][] {const runs: CursorRecordingSample[][] = [];let current: CursorRecordingSample[] = [];@@ -137,8 +134,8 @@ function buildSmoothedRun(rawY[i] = p.cy;}// The spring is itself a strong low-pass (~3Hz cutoff), so it removes capture tremor without a- // separate denoise pass — and chasing the *raw* target keeps the cursor accurate (no acausal- // pull toward neighbouring samples near sharp stops, which would offset clicks/dwells).+ // separate denoise pass. Chasing the raw target keeps the cursor accurate near sharp stops (no+ // acausal pull toward neighbouring samples that would offset clicks/dwells).return {start,end,@@ -188,8 +185,8 @@ function buildSmoothedPath(return buildRawPath(runs);}- // Use the slider value directly, matching the live cursor overlay's spring strength so the two- // cursor systems lag identically (an extra multiplier here over-smoothed → visible offset).+ // Use the slider value directly to match the live overlay's spring strength so both cursor+ // systems lag identically (an extra multiplier here over-smoothed, causing a visible offset).const config = getCursorSpringConfig(clamp(smoothing01, 0, 1));const smoothedRuns = runs.map((run) =>diff --git a/src/lib/cursor/cursorThemes.ts b/src/lib/cursor/cursorThemes.tsindex 8dbd2081a..dd6fa7cc0 100644--- a/src/lib/cursor/cursorThemes.ts+++ b/src/lib/cursor/cursorThemes.ts@@ -3,11 +3,10 @@ import type { NativeCursorType } from "@/native/contracts";/*** A single themed cursor image override for one {@link NativeCursorType}.*- * `width`/`height`/`hotspot*` are expressed in the same ~32-logical-pixel reference- * used by the built-in `PRETTY_NATIVE_CURSOR_ASSETS` in `nativeCursor.ts`, so a theme- * asset renders at the same on-screen size as the default cursor regardless of the- * source PNG resolution. The PNG itself can be higher-res (e.g. 128×128) and is- * downscaled at draw time for crisper retina output.+ * width/height/hotspot are in the same ~32-logical-pixel reference as the built-in+ * PRETTY_NATIVE_CURSOR_ASSETS, so a theme asset matches the default cursor's on-screen+ * size regardless of source PNG resolution. The PNG can be higher-res (e.g. 128x128)+ * and is downscaled at draw time for crisper retina output.*/export interface CursorThemeAsset {/** Path relative to the public asset root, e.g. "cursors/hello-kitty-watermelon/arrow.png". */@@ -20,13 +19,13 @@ export interface CursorThemeAsset {export interface CursorTheme {id: string;- /** Display label. Theme names are proper nouns, so they are not run through i18n. */+ /** Display label. Proper nouns, so not run through i18n. */name: string;/** Attribution / origin for the artwork. */source?: string;/**- * Per-cursor-type overrides. Any type not present here falls back to the built-in- * default cursor art. Sweezy packs only ship "arrow" and "pointer" art.+ * Per-cursor-type overrides. Missing types fall back to the built-in default art.+ * Sweezy packs only ship "arrow" and "pointer".*/assets: Partial<Record<NativeCursorType, CursorThemeAsset>>;}@@ -35,8 +34,8 @@ export interface CursorTheme {export const DEFAULT_CURSOR_THEME_ID = "default";/**- * Bundled cursor themes. To add a pack: drop `arrow.png`/`pointer.png` into- * `public/cursors/<id>/` and add an entry here with hotspots normalized to the+ * Bundled cursor themes. To add a pack: drop arrow.png/pointer.png into+ * public/cursors/<id>/ and add an entry here with hotspots normalized to the* 32-logical reference (divide a 128px-pack hotspot by 4). No renderer changes needed.*/export const CURSOR_THEMES: readonly CursorTheme[] = [diff --git a/src/lib/cursor/nativeCursor.ts b/src/lib/cursor/nativeCursor.tsindex 11dabe3af..dcf55eea5 100644--- a/src/lib/cursor/nativeCursor.ts+++ b/src/lib/cursor/nativeCursor.ts@@ -529,11 +529,10 @@ export function resolvePrettyNativeCursorAsset(}/**- * Infers "arrow" vs "pointer" from a captured cursor bitmap's hotspot, for platforms- * (notably macOS) that don't tag samples with a `cursorType`. The arrow's hotspot sits- * in the top-left tip; the pointing hand's fingertip hotspot sits in the upper-center- * band. Anything else (text I-beam, crosshair, resize) is left unclassified so it keeps- * its real captured cursor instead of being forced into a themed arrow/pointer.+ * Infers "arrow" vs "pointer" from a captured bitmap's hotspot, for platforms (macOS)+ * that don't tag samples with a `cursorType`. Arrow's hotspot is in the top-left tip;+ * the pointing hand's fingertip is in the upper-center band. Anything else stays+ * unclassified so it keeps its real captured cursor instead of a themed arrow/pointer.*/function classifyCapturedCursorType(asset: NativeCursorAsset): NativeCursorType | null {if (asset.width <= 0 || asset.height <= 0) {@@ -551,10 +550,9 @@ function classifyCapturedCursorType(asset: NativeCursorAsset): NativeCursorType}/**- * Resolves the cursor-theme override for a given type, or null when the default- * theme is active or the theme has no art for that type. The bundled asset URL is- * resolved lazily (only when a theme is active) so this is safe to call from tests- * and non-renderer contexts. A resolution failure degrades to the default art.+ * Resolves the theme override for a cursor type, or null when the default theme is active+ * or has no art for that type. The asset URL resolves lazily (only when a theme is active)+ * so this is safe from tests and non-renderer contexts; a failure degrades to default art.*/function resolveThemedCursorAsset(themeId: string | null | undefined,@@ -588,9 +586,9 @@ export function resolveNativeCursorRenderAsset() {const cursorType = sample?.cursorType ?? asset.cursorType ?? null;if (themeId && themeId !== DEFAULT_CURSOR_THEME_ID) {- // A known type uses its override when the theme provides one. Untyped samples —- // common on macOS, where the cursor type isn't tagged — are classified from the- // captured bitmap's hotspot so arrow→themed-arrow and hand→themed-pointer.+ // A known type uses its override when the theme provides one. Untyped samples+ // (common on macOS, where the type isn't tagged) are classified from the captured+ // bitmap's hotspot so arrow becomes themed-arrow and hand becomes themed-pointer.const themedType = cursorType ?? classifyCapturedCursorType(asset);const themedAsset = themedType ? resolveThemedCursorAsset(themeId, themedType) : null;if (themedAsset && themedType) {diff --git a/src/lib/cursorTelemetryBuffer.test.ts b/src/lib/cursorTelemetryBuffer.test.tsindex 17174accc..dffb5eec1 100644--- a/src/lib/cursorTelemetryBuffer.test.ts+++ b/src/lib/cursorTelemetryBuffer.test.ts@@ -2,8 +2,7 @@ import { describe, expect, it, vi } from "vitest";import { type CursorTelemetryPoint, createCursorTelemetryBuffer } from "./cursorTelemetryBuffer";function sample(tag: number): CursorTelemetryPoint {- // Decouple the timestamp tag from the coordinate fixture so cursor- // points stay inside the normalized [0, 1] range that real samples use.+ // Decouple the tag from coordinates so points stay in the normalized [0, 1] range.const normalized = (tag % 100) / 100;return { timeMs: tag, cx: normalized, cy: normalized };}@@ -121,11 +120,9 @@ describe("createCursorTelemetryBuffer", () => {});it("discardBatch(id) targets the correct batch even when a later recording sits in front of it", () => {- // Regression test for the rapid Stop → Record → Discard sequence:- // recording A's finalize callback does async work (fixWebmDuration),- // recording B finishes in the meantime, then A's callback resolves- // with discard intent. The discard must drop A — not B, which- // happens to be the *latest* pending batch by the time discard runs.+ // Regression for the rapid Stop/Record/Discard sequence: A's finalize callback does+ // async work (fixWebmDuration), B finishes meanwhile, then A resolves with discard+ // intent. The discard must drop A, not B, which is the latest pending batch by then.const buf = createCursorTelemetryBuffer({ maxActiveSamples: 10 });buf.startSession(1);@@ -216,8 +213,8 @@ describe("createCursorTelemetryBuffer", () => {expect(buf.pendingCount).toBe(2);expect(warn).not.toHaveBeenCalled();- // Simulate a misuse where a retry prepends without first draining:- // queue would grow to 3, so the oldest-trailing entry must be evicted.+ // Misuse: a retry prepends without draining first, so the queue would grow to 3+ // and the oldest-trailing entry must be evicted.buf.prependBatch({ recordingId: 99, samples: [sample(99)] });expect(buf.pendingCount).toBe(2);expect(warn).toHaveBeenCalledTimes(1);@@ -232,8 +229,7 @@ describe("createCursorTelemetryBuffer", () => {});it("sanitizes non-finite or non-positive option values to safe defaults", () => {- // Infinity / NaN / negative would otherwise turn the trim loops- // into infinite loops. The buffer must fall back to defaults.+ // Infinity/NaN/negative would turn the trim loops infinite; the buffer must fall back to defaults.const buf = createCursorTelemetryBuffer({maxActiveSamples: Number.POSITIVE_INFINITY,maxPendingBatches: Number.NaN,diff --git a/src/lib/cursorTelemetryBuffer.ts b/src/lib/cursorTelemetryBuffer.tsindex 0c7e0e10e..02d6147bb 100644--- a/src/lib/cursorTelemetryBuffer.ts+++ b/src/lib/cursorTelemetryBuffer.ts@@ -1,10 +1,7 @@/**- * A single cursor telemetry sample captured during a recording session.- *- * Coordinates (`cx`, `cy`) are clamped ratios in the `[0, 1]` range,- * normalised against the captured surface's width and height by the- * main-process `sampleCursorPoint()` before being pushed. `timeMs` is the- * offset (in milliseconds) from the recording's start.+ * A single cursor telemetry sample. cx/cy are clamped [0,1] ratios of the+ * captured surface (normalised in the main process by sampleCursorPoint).+ * timeMs is the offset from recording start.*/export interface CursorTelemetryPoint {timeMs: number;@@ -13,9 +10,9 @@ export interface CursorTelemetryPoint {}/**- * A completed batch of cursor samples, tagged with the recording id that- * produced them. The id is supplied at `startSession()` time and travels- * with the batch through the pending queue, retries, and discards.+ * A completed batch of cursor samples, tagged with its recording id. The id+ * (from startSession) travels with the batch through the queue, retries, and+ * discards.*/export interface CursorTelemetryBatch {recordingId: number;@@ -25,87 +22,64 @@ export interface CursorTelemetryBatch {/*** Per-session cursor telemetry buffer with bounded memory.*- * Flow: `startSession(recordingId)` → `push(point)` N times → `endSession()`- * enqueues the collected samples as a completed batch tagged with that- * `recordingId`. The main process later drains batches in FIFO order via- * `takeNextBatch()` to persist them to disk, and can `prependBatch()` on- * write failure to retry without losing order. A discard request keys on- * the recording id so an asynchronous "discard recording A" decision that- * arrives after recording B has already enqueued its batch still drops- * the right one.+ * Flow: startSession(recordingId), push(point) N times, endSession() enqueues+ * the samples as a batch tagged with that id. The main process drains batches+ * FIFO via takeNextBatch() to persist, and prependBatch() on write failure to+ * retry without losing order. Discard keys on the recording id so an async+ * "discard recording A" that arrives after recording B has enqueued still+ * drops the right batch.*- * Memory is bounded by `maxActiveSamples` (ring buffer on the in-progress- * batch) and `maxPendingBatches` (FIFO cap across completed batches).+ * Memory bounded by maxActiveSamples (ring buffer on the in-progress batch)+ * and maxPendingBatches (FIFO cap across completed batches).*/export interface CursorTelemetryBuffer {/**- * Begin a new recording session under the given `recordingId`. Clears- * any in-progress active samples (without touching already-completed- * pending batches). Safe to call repeatedly — e.g. a rapid Stop →- * Record sequence — and the most recent id wins.+ * Begin a new recording session. Clears in-progress active samples but+ * leaves completed pending batches. Safe to call repeatedly (e.g. a rapid+ * Stop then Record); the most recent id wins.*/startSession(recordingId: number): void;/**- * Append a telemetry sample to the current active session. When the- * active buffer exceeds `maxActiveSamples`, the oldest sample is- * dropped (ring behaviour).+ * Append a sample to the active session. Over maxActiveSamples, the oldest+ * sample is dropped (ring behaviour).*/push(point: CursorTelemetryPoint): void;/**- * Finalize the active session, moving its samples into the pending- * queue as a single batch tagged with the current recording id. Empty- * sessions are dropped (no empty batch is enqueued).- *- * If the pending queue would exceed `maxPendingBatches`, the oldest- * batches are evicted to bound memory. A `console.warn` is emitted- * whenever at least one batch is dropped so that pathological rapid-- * restart scenarios are observable.+ * Finalize the active session into a single pending batch tagged with the+ * current recording id. Empty sessions enqueue nothing. Over+ * maxPendingBatches, oldest batches are evicted and a warn is logged so+ * pathological rapid-restart cases are observable.*- * @returns the number of pending batches dropped by this call (0 under- * normal operation).+ * @returns the number of pending batches dropped (0 normally).*/endSession(): number;- /**- * Remove and return the oldest pending batch, or `null` if the queue- * is empty.- */+ /** Remove and return the oldest pending batch, or null if empty. */takeNextBatch(): CursorTelemetryBatch | null;/**- * Re-insert a batch at the front of the queue, preserving FIFO order- * on retry paths (e.g. when persisting the batch failed and the- * caller wants the next `takeNextBatch()` to yield it again).- *- * Empty batches are ignored. The pending cap is enforced defensively- * — if prepending would push the queue past `maxPendingBatches`, the- * oldest entries are evicted and a `console.warn` is emitted. In- * normal retry usage this trim is a no-op because the caller has just- * removed the batch via `takeNextBatch()`.+ * Re-insert a batch at the front, preserving FIFO order on retry (e.g.+ * persisting failed and the next takeNextBatch() should yield it again).+ * Empty batches are ignored. The pending cap is enforced defensively; in+ * normal retry usage the trim is a no-op since the caller just took it.*/prependBatch(batch: CursorTelemetryBatch): void;/**- * Drop the pending batch produced by the given `recordingId`. Used- * when a recording is discarded after its `endSession()` has run but- * before it has been persisted. Returns `true` if a batch was- * removed, `false` otherwise (no matching id, or the batch was- * already drained).+ * Drop the pending batch for the given recordingId, when a recording is+ * discarded after endSession() but before persistence. Returns true if a+ * batch was removed.*- * Keying on the recording id (rather than "the latest pending batch")- * avoids a real bug: when finalizing a recording does asynchronous- * work like `fixWebmDuration`, a quick Stop → Record → Discard- * sequence can interleave such that the latest pending batch belongs- * to a *later* recording than the one being discarded.+ * Keys on the recording id rather than "the latest pending batch" to avoid+ * a bug: async finalize work (fixWebmDuration) means a quick Stop, Record,+ * Discard can leave the latest pending batch belonging to a later recording+ * than the one being discarded.*/discardBatch(recordingId: number): boolean;- /**- * Clear both the active and pending state. Intended for tests and- * full teardown paths.- */+ /** Clear active and pending state. For tests and full teardown. */reset(): void;readonly activeCount: number;@@ -128,11 +102,8 @@ function sanitizeLimit(value: number | undefined, fallback: number): number {}/**- * Create a cursor telemetry buffer.- *- * Numeric options are sanitized: non-finite, negative, or zero values fall- * back to safe defaults so a bad caller cannot disable the memory bounds- * (which would turn the trim loops into infinite loops).+ * Create a cursor telemetry buffer. Options are sanitized so a bad caller+ * cannot disable the memory bounds (which would make the trim loops infinite).** @see CursorTelemetryBuffer for the full lifecycle contract.*/diff --git a/src/lib/customFonts.ts b/src/lib/customFonts.tsindex af332c139..4cf00c6a3 100644--- a/src/lib/customFonts.ts+++ b/src/lib/customFonts.ts@@ -1,16 +1,15 @@-// Google Fonts loading and management utility+// Google Fonts loading and managementexport interface CustomFont {id: string;- name: string; // Display name- fontFamily: string; // CSS font-family value+ name: string;+ fontFamily: string;importUrl: string; // Google Fonts @import URL}const STORAGE_KEY = "openscreen_custom_fonts";const loadedFonts = new Set<string>();-// Load custom fonts from localStorageexport function getCustomFonts(): CustomFont[] {try {const stored = localStorage.getItem(STORAGE_KEY);@@ -21,7 +20,6 @@ export function getCustomFonts(): CustomFont[] {}}-// Save custom fonts to localStorageexport function saveCustomFonts(fonts: CustomFont[]): void {try {localStorage.setItem(STORAGE_KEY, JSON.stringify(fonts));@@ -30,7 +28,7 @@ export function saveCustomFonts(fonts: CustomFont[]): void {}}-// Add a new custom font (throws error if font fails to load)+// Throws if the font fails to loadexport async function addCustomFont(font: CustomFont): Promise<CustomFont[]> {const fonts = getCustomFonts();const exists = fonts.some((f) => f.id === font.id || f.fontFamily === font.fontFamily);@@ -39,23 +37,20 @@ export async function addCustomFont(font: CustomFont): Promise<CustomFont[]> {return fonts;}- // Try to load the font first - this will throw if it fails+ // Load first so a failure throws before we persist itawait loadFont(font);- // Only add to storage if font loaded successfullyfonts.push(font);saveCustomFonts(fonts);return fonts;}-// Remove a custom fontexport function removeCustomFont(fontId: string): CustomFont[] {const fonts = getCustomFonts();const filtered = fonts.filter((f) => f.id !== fontId);saveCustomFonts(filtered);- // Remove the style elementconst styleEl = document.getElementById(`custom-font-${fontId}`);if (styleEl) {styleEl.remove();@@ -68,7 +63,6 @@ export function removeCustomFont(fontId: string): CustomFont[] {// Load a Google Font into the documentexport function loadFont(font: CustomFont): Promise<void> {return new Promise((resolve, reject) => {- // Skip if already loadedif (loadedFonts.has(font.id)) {resolve();return;@@ -77,19 +71,16 @@ export function loadFont(font: CustomFont): Promise<void> {try {const styleId = `custom-font-${font.id}`;- // Remove existing style if presentconst existing = document.getElementById(styleId);if (existing) {existing.remove();}- // Create style element with @importconst style = document.createElement("style");style.id = styleId;style.textContent = `@import url('${font.importUrl}');`;document.head.appendChild(style);- // Wait for font to loadwaitForFont(font.fontFamily).then(() => {loadedFonts.add(font.id);@@ -103,17 +94,15 @@ export function loadFont(font: CustomFont): Promise<void> {});}-// Wait for a font to be available and verify it loaded+// Wait for a font to load and verify it's actually availablefunction waitForFont(fontFamily: string, timeout = 5000): Promise<void> {return new Promise((resolve, reject) => {- // Use CSS Font Loading API if availableif ("fonts" in document) {Promise.race([document.fonts.load(`16px "${fontFamily}"`),new Promise((_, rej) => setTimeout(() => rej(new Error("Font load timeout")), timeout)),]).then(() => {- // Verify the font actually loaded by checking if it's availableconst isAvailable = document.fonts.check(`16px "${fontFamily}"`);if (isAvailable) {resolve();@@ -125,14 +114,13 @@ function waitForFont(fontFamily: string, timeout = 5000): Promise<void> {reject(error);});} else {- // Fallback for browsers without Font Loading API- // Wait a bit and hope for the best+ // No Font Loading API: wait a bit and hope for the bestsetTimeout(() => resolve(), 1000);}});}-// Load all stored custom fonts on app initialization+// Load all stored custom fonts on app initexport function loadAllCustomFonts(): Promise<void[]> {const fonts = getCustomFonts();return Promise.all(@@ -144,22 +132,21 @@ export function loadAllCustomFonts(): Promise<void[]> {);}-// Generate a unique ID for a fontexport function generateFontId(name: string): string {return `${name.toLowerCase().replace(/\s+/g, "-")}-${Date.now()}`;}-// Parse Google Fonts @import URL to extract font family name+// Extract the font family from a Google Fonts @import URLexport function parseFontFamilyFromImport(importUrl: string): string | null {try {- // Extract from URL like: https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap+ // e.g. https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swapconst url = new URL(importUrl);const familyParam = url.searchParams.get("family");if (familyParam) {- // Remove weight/style info: "Roboto:wght@400;700" -> "Roboto"+ // "Roboto:wght@400;700" -> "Roboto"const fontName = familyParam.split(":")[0];- // Replace + with spaces: "Open+Sans" -> "Open Sans"+ // "Open+Sans" -> "Open Sans"return fontName.replace(/\+/g, " ");}@@ -170,7 +157,7 @@ export function parseFontFamilyFromImport(importUrl: string): string | null {}}-// Validate if a string looks like a Google Fonts import URL+// Does this look like a Google Fonts import URL?export function isValidGoogleFontsUrl(url: string): boolean {try {const urlObj = new URL(url);diff --git a/src/lib/exporter/annotationRenderer.ts b/src/lib/exporter/annotationRenderer.tsindex a2ac08a19..1ef55d672 100644--- a/src/lib/exporter/annotationRenderer.ts+++ b/src/lib/exporter/annotationRenderer.ts@@ -11,11 +11,9 @@ import {let blurScratchCanvas: HTMLCanvasElement | null = null;let blurScratchCtx: CanvasRenderingContext2D | null = null;-// Matches a single code point whose script is Han (including non-BMP-// Extension A-F), Hiragana, Katakana (including halfwidth forms), or-// Hangul. Used to split CJK text at character boundaries during wrap,-// since CJK scripts have no word-separating whitespace. Unicode script-// property escapes require ES2018+; tsconfig target is ES2020.+// Han/Hiragana/Katakana/Hangul code points, to split CJK text at character+// boundaries during wrap (CJK has no word-separating whitespace). Script+// escapes need ES2018+; tsconfig targets ES2020.const CJK_CHAR = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;type GraphemeSegmenter = {@@ -39,10 +37,9 @@ function splitGraphemes(value: string): string[] {}function tokenizeForWrap(line: string): string[] {- // Split Latin text on whitespace (preserving the whitespace as its own token,- // matching the original behavior), and split CJK runs into individual- // characters so each one becomes a breakable unit. This mirrors the editor's- // CSS `word-break: break-word` handling for CJK content.+ // Split Latin on whitespace (kept as its own token) and split CJK runs into+ // individual chars so each is breakable, mirroring the editor's CSS+ // word-break: break-word for CJK.const tokens: string[] = [];let buffer = "";const chars = Array.from(line);@@ -126,10 +123,8 @@ function renderArrow(const offsetX = padding + (availableWidth - 100 * scale) / 2;const offsetY = padding + (availableHeight - 100 * scale) / 2;- // Apply centering offsetctx.translate(offsetX, offsetY);- // Apply shadow filterctx.shadowColor = "rgba(0, 0, 0, 0.3)";ctx.shadowBlur = 8 * scale;ctx.shadowOffsetX = 0;@@ -140,7 +135,7 @@ function renderArrow(ctx.lineCap = "round";ctx.lineJoin = "round";- // Draw all paths as a single shape to avoid overlapping shadows/strokes+ // One shape so shadows/strokes don't overlapctx.beginPath();for (const pathString of paths) {@@ -278,7 +273,7 @@ function renderText(ctx.translate(-transformOriginX, -transformOriginY);ctx.globalAlpha *= animationState.opacity;- // Clip text to annotation box bounds (matches editor's overflow: hidden)+ // Clip to box bounds, matching editor's overflow: hiddenctx.beginPath();ctx.rect(x, y, width, height);ctx.clip();@@ -414,7 +409,7 @@ async function renderImage(return new Promise((resolve) => {const img = new Image();img.onload = () => {- // Preserve aspect ratio - contain the image within the bounds+ // Contain within bounds, preserving aspect ratioconst imgAspect = img.width / img.height;const boxAspect = width / height;@@ -450,12 +445,11 @@ export async function renderAnnotations(currentTimeMs: number,scaleFactor: number = 1.0,): Promise<void> {- // Filter active annotations at current timeconst activeAnnotations = annotations.filter((ann) => currentTimeMs >= ann.startMs && currentTimeMs < ann.endMs,);- // Sort by z-index (lower first, so higher z-index draws on top)+ // Lower z-index first so higher draws on topconst sortedAnnotations = [...activeAnnotations].sort((a, b) => a.zIndex - b.zIndex);for (const annotation of sortedAnnotations) {diff --git a/src/lib/exporter/audioEncoder.ts b/src/lib/exporter/audioEncoder.tsindex 95227844d..7514907e2 100644--- a/src/lib/exporter/audioEncoder.ts+++ b/src/lib/exporter/audioEncoder.ts@@ -210,9 +210,8 @@ export class AudioProcessor {}/**- * Audio export has two modes:- * 1) no speed regions -> fast WebCodecs trim-only pipeline- * 2) speed regions present -> pitch-preserving rendered timeline pipeline+ * Two modes: no speed regions uses the fast WebCodecs trim-only pipeline; speed+ * regions use the pitch-preserving rendered timeline pipeline.*/async process(demuxer: WebDemuxer,@@ -230,7 +229,7 @@ export class AudioProcessor {.sort((a, b) => a.startMs - b.startMs): [];- // Speed edits must use timeline playback to preserve pitch+ // Speed edits need timeline playback to preserve pitch.if (sortedSpeedRegions.length > 0) {const renderedAudioBlob = await this.renderPitchPreservedTimelineAudio(videoUrl,@@ -245,14 +244,14 @@ export class AudioProcessor {return;}- // No speed edits: keep the original demux/decode/encode path with trim timestamp remap.- // The +0.5s buffer mirrors streamingDecoder.decodeAll's read window so the trim-only- // and speed-aware paths agree on how far to read past the validated duration boundary.+ // No speed edits: demux/decode/encode with trim timestamp remap. The +0.5s mirrors+ // streamingDecoder.decodeAll's read window so both paths read the same distance past+ // the validated duration boundary.const readEndSec = validatedDurationSec + 0.5;await this.processTrimOnlyAudio(demuxer, muxer, sortedTrims, readEndSec, exportCodec);}- // Legacy trim-only path. This is still used for projects without speed regions.+ // Trim-only path, used for projects without speed regions.private async processTrimOnlyAudio(demuxer: WebDemuxer,muxer: VideoMuxer,@@ -274,7 +273,7 @@ export class AudioProcessor {return;}- // Phase 1: Decode audio from source, skipping trimmed regions+ // Phase 1: decode, skipping trimmed regions.const decodedFrames: AudioData[] = [];const decoder = new AudioDecoder({@@ -325,7 +324,7 @@ export class AudioProcessor {return;}- // Phase 2: Re-encode with timestamps adjusted for trim gaps+ // Phase 2: re-encode with timestamps adjusted for trim gaps.const encodedChunks: { chunk: EncodedAudioChunk; meta?: EncodedAudioChunkMetadata }[] = [];const encoder = new AudioEncoder({@@ -391,7 +390,7 @@ export class AudioProcessor {encoder.close();}- // Phase 3: Flush encoded chunks to muxer+ // Phase 3: flush encoded chunks to muxer.for (const { chunk, meta } of encodedChunks) {if (this.cancelled) break;await muxer.addAudioChunk(chunk, meta);@@ -402,8 +401,8 @@ export class AudioProcessor {);}- // Speed-aware path that mirrors preview semantics (trim skipping + playbackRate regions)- // preserve pitch through browser media playback behavior to avoid chipmunk effect.+ // Speed-aware path mirroring preview semantics (trim skipping + playbackRate). Relies on+ // browser media playback to preserve pitch and avoid the chipmunk effect.private async renderPitchPreservedTimelineAudio(videoUrl: string,trimRegions: TrimRegion[],@@ -442,9 +441,8 @@ export class AudioProcessor {await audioContext.resume();}- // Skip past any initial trim region(s) before recording starts to avoid- // capturing trimmed audio during the first rAF frames of playback.- // Loops to handle back-to-back or overlapping trims at t=0.+ // Skip initial trim region(s) before recording so the first rAF frames don't+ // capture trimmed audio. Loops to handle back-to-back/overlapping trims at t=0.const effectiveEnd = validatedDurationSec;let startPosition = 0;for (let i = 0; i <= trimRegions.length; i++) {@@ -455,19 +453,19 @@ export class AudioProcessor {}if (startPosition >= effectiveEnd) {- // All content is trimmed — return silent blob+ // Everything is trimmed; return a silent blob.return new Blob([], { type: "audio/webm" });}await this.seekTo(media, startPosition);- // Set initial playback rate for the starting position+ // Set initial playback rate for the starting position.const initialSpeedRegion = this.findActiveSpeedRegion(startPosition * 1000, speedRegions);if (initialSpeedRegion) {media.playbackRate = initialSpeedRegion.speed;}- // Start recording only AFTER seeking past trims+ // Start recording only after seeking past trims.const recording = this.startAudioRecording(destinationNode.stream);recorder = recording.recorder;recordedBlobPromise = recording.recordedBlobPromise;@@ -500,8 +498,8 @@ export class AudioProcessor {return;}- // Stop playback at validated duration — browser's media.duration- // may be inflated from bad container metadata.+ // Stop at validated duration; media.duration can be inflated by bad+ // container metadata.if (media.currentTime >= validatedDurationSec) {media.pause();cleanup();@@ -520,8 +518,7 @@ export class AudioProcessor {resolve();return;}- // Pause recording during trim seek to prevent capturing- // silence/noise as the audio element seeks.+ // Pause recording during the seek so we don't capture silence/noise.media.pause();if (recorder?.state === "recording") recorder.pause();const onSeeked = () => {@@ -591,9 +588,8 @@ export class AudioProcessor {}if (!recordedBlobPromise) {- // Invariant: either an early return above fires, or startAudioRecording ran and- // populated recordedBlobPromise before the playback Promise resolved. Reaching- // here means that contract was broken — fail loud instead of returning silence.+ // Either an early return fired or startAudioRecording set this before playback+ // resolved. Reaching here means that broke; fail loud rather than return silence.throw new Error("Audio recorder finished without assigning recordedBlobPromise");}const recordedBlob = await recordedBlobPromise;@@ -603,7 +599,7 @@ export class AudioProcessor {return recordedBlob;}- // Demuxes the rendered speed-adjusted blob and feeds encoded chunks into the MP4 muxer.+ // Demux the rendered speed-adjusted blob and feed its chunks into the MP4 muxer.private async muxRenderedAudioBlob(blob: Blob,muxer: VideoMuxer,diff --git a/src/lib/exporter/frameRenderer.ts b/src/lib/exporter/frameRenderer.tsindex 49351d7e8..d8f3c4312 100644--- a/src/lib/exporter/frameRenderer.ts+++ b/src/lib/exporter/frameRenderer.ts@@ -180,22 +180,19 @@ export class FrameRenderer {}async initialize(): Promise<void> {- // Create canvas for renderingconst canvas = document.createElement("canvas");canvas.width = this.config.width;canvas.height = this.config.height;- // Try to set colorSpace if supported (may not be available on all platforms)+ // colorSpace isn't available on all platformstry {if (canvas && "colorSpace" in canvas) {canvas.colorSpace = "srgb";}} catch (error) {- // Silently ignore colorSpace errors on platforms that don't support itconsole.warn("[FrameRenderer] colorSpace not supported on this platform:", error);}- // Initialize PixiJS with optimized settings for export performancethis.app = new Application();await this.app.init({canvas,@@ -207,16 +204,14 @@ export class FrameRenderer {autoDensity: true,});- // Setup containersthis.cameraContainer = new Container();this.videoContainer = new Container();this.app.stage.addChild(this.cameraContainer);this.cameraContainer.addChild(this.videoContainer);- // Setup background (render separately, not in PixiJS)+ // Background renders separately, not in PixiJSawait this.setupBackground();- // Setup blur filter for video containerthis.blurFilter = new BlurFilter();this.blurFilter.quality = 5;this.blurFilter.resolution = this.app.renderer.resolution;@@ -224,12 +219,12 @@ export class FrameRenderer {this.motionBlurFilter = new MotionBlurFilter([0, 0], 5, 0);this.videoContainer.filters = [this.blurFilter, this.motionBlurFilter];- // Setup composite canvas for final output with shadows+ // Composite canvas: final output with shadowsthis.compositeCanvas = document.createElement("canvas");this.compositeCanvas.width = this.config.width;this.compositeCanvas.height = this.config.height;- // On Linux, getImageData() is called frequently causing frequent CPU readback+ // On Linux getImageData() runs frequently, so hint frequent CPU readbackthis.compositeCtx = this.compositeCanvas.getContext("2d", {willReadFrequently: this.isLinux,});@@ -246,9 +241,8 @@ export class FrameRenderer {throw new Error("Failed to get 2D context for raster canvas");}- // Foreground canvas: holds recording + shadow + webcam + cursor + annotations,- // transparent background. The 3D rotation pass operates only on this layer so- // the wallpaper stays flat behind the rotated content (matching preview).+ // Foreground (transparent): recording + shadow + webcam + cursor + annotations.+ // The 3D pass operates only on this layer so the wallpaper stays flat behind it.this.foregroundCanvas = document.createElement("canvas");this.foregroundCanvas.width = this.config.width;this.foregroundCanvas.height = this.config.height;@@ -259,7 +253,6 @@ export class FrameRenderer {throw new Error("Failed to get 2D context for foreground canvas");}- // Setup shadow canvas if neededif (this.config.showShadow) {this.shadowCanvas = document.createElement("canvas");this.shadowCanvas.width = this.config.width;@@ -273,7 +266,6 @@ export class FrameRenderer {}}- // Setup maskthis.maskGraphics = new Graphics();this.videoContainer.addChild(this.maskGraphics);this.videoContainer.mask = this.maskGraphics;@@ -390,20 +382,18 @@ export class FrameRenderer {this.currentVideoTime = timestamp / 1000000;- // Create or update video sprite from VideoFrameif (!this.videoSprite) {const texture = Texture.from(videoFrame as unknown as TextureSourceLike);this.videoSprite = new Sprite(texture);this.videoContainer.addChild(this.videoSprite);} else {- // Destroy old texture to avoid memory leaks, then create new one+ // Destroy old texture before swapping to avoid a leakconst oldTexture = this.videoSprite.texture;const newTexture = Texture.from(videoFrame as unknown as TextureSourceLike);this.videoSprite.texture = newTexture;oldTexture.destroy(true);}- // Apply layoutthis.updateLayout(webcamFrame);const timeMs = this.currentVideoTime * 1000;@@ -420,15 +410,11 @@ export class FrameRenderer {throw new Error("Layout cache not initialized");}- // Apply transform once with maximum motion intensity from all ticks.- // CRITICAL: feed the spring-smoothed transform (appliedScale/x/y from updateAnimationState)- // via transformOverride — exactly as the preview does. Without it, applyZoomTransform would- // recompute the camera from the raw eased *target* (state.scale/progress/focus) and the spring- // would be discarded for the camera container, so the export camera would snap to the target- // every frame while the preview glides. That asymmetry is invisible for a static (manual-focus)- // zoom but very visible for auto-focus, whose target pans with the cursor — it read as the- // export being "snappier". Using the sprung transform also keeps the camera, mask and cursor- // (which already read appliedScale/x/y) mutually consistent.+ // Feed the spring-smoothed transform (appliedScale/x/y) via transformOverride, like the+ // preview. Without it applyZoomTransform recomputes the camera from the raw eased target and+ // the spring is discarded, so the export snaps to the target every frame while the preview+ // glides (very visible for auto-focus, whose target pans with the cursor). It also keeps the+ // camera, mask, and cursor (which already read appliedScale/x/y) consistent.applyZoomTransform({cameraContainer: this.cameraContainer,blurFilter: this.blurFilter,@@ -451,17 +437,17 @@ export class FrameRenderer {},});- // Render the PixiJS stage to its canvas (video only, transparent background)+ // Render the PixiJS stage (video only, transparent background)this.app.renderer.render(this.app.stage);- // Skip baking the shadow when the WebGL rotation pass will run — it'd alias to- // a hard edge through bilinear sampling. We re-apply shadow fresh after rotation.+ // Skip baking the shadow when the rotation pass will run; bilinear sampling would+ // alias it to a hard edge. Re-applied fresh after rotation.const willRotate = !isRotation3DIdentity(this.currentRotation3D);this.compositeWithShadows(webcamFrame, !willRotate);await this.drawNativeCursor(timeMs);- // Render annotations on top of foreground (so they rotate with recording).+ // Annotations go on top of foreground so they rotate with the recordingif (this.config.annotationRegions &&this.config.annotationRegions.length > 0 &&@@ -483,14 +469,14 @@ export class FrameRenderer {);}- // Apply 3D rotation to foreground only. Wallpaper (on compositeCanvas) is untouched.+ // Rotate foreground only; wallpaper (on compositeCanvas) stays untouchedif (willRotate && this.threeDPass && this.foregroundCanvas && this.foregroundCtx) {const passCanvas = this.threeDPass.apply(this.foregroundCanvas, this.currentRotation3D);const w = this.foregroundCanvas.width;const h = this.foregroundCanvas.height;this.foregroundCtx.clearRect(0, 0, w, h);if (this.isLinux) {- // drawImage(webglCanvas) is unreliable on Linux/Wayland — use readPixels.+ // drawImage(webglCanvas) is unreliable on Linux/Wayland, so use readPixelsconst pixels = this.threeDPass.readPixels();const imageData = this.foregroundCtx.createImageData(w, h);imageData.data.set(pixels);@@ -500,9 +486,9 @@ export class FrameRenderer {}}- // Apply shadow fresh on the rotated silhouette (flat path already baked it- // in compositeWithShadows, so guard on willRotate to avoid doubling).- // Same 3-layer filter chain as `main` — keeps the soft Gaussian intact.+ // Apply shadow fresh on the rotated silhouette. Flat path already baked it in+ // compositeWithShadows, so guard on willRotate to avoid doubling. Same 3-layer+ // filter chain as the flat path to keep the soft Gaussian intact.if (willRotate &&this.config.showShadow &&@@ -531,24 +517,23 @@ export class FrameRenderer {this.compositeCtx.drawImage(this.shadowCanvas, 0, 0);}} else if (this.compositeCtx && this.foregroundCanvas) {- // Flat path or 3D-without-shadow: stamp foreground directly.+ // Flat path or 3D-without-shadow: stamp foreground directlythis.compositeCtx.drawImage(this.foregroundCanvas, 0, 0);}}- // The video's actual on-screen boundary, accounting for the zoom camera- // transform. The PIXI mask lives inside cameraContainer, so during zoom the- // visible video extends beyond the static maskRect — a static clip would crop- // it. Mirrors the preview, which clips via the same camera-scaled bounds.+ // Video's on-screen boundary including the zoom camera transform. The PIXI mask+ // lives inside cameraContainer, so during zoom the visible video extends beyond+ // the static maskRect and a static clip would crop it. Mirrors the preview.private cameraAwareMaskRect() {if (!this.layoutCache) return null;const { x: maskX, y: maskY, width: maskW, height: maskH } = this.layoutCache.maskRect;const camS = this.animationState.appliedScale;const camX = this.animationState.x;const camY = this.animationState.y;- // No stage clamping: canvas naturally clips to its bounds, matching CSS inset() behavior.- // Clamping x/y would shift rounded corners to the stage edge rather than the true mask- // boundary, causing preview/export mismatch when zoom/pan pushes the mask off-stage.+ // No stage clamping: the canvas clips to its own bounds, matching CSS inset().+ // Clamping x/y would pin rounded corners to the stage edge instead of the true+ // mask boundary, mismatching preview/export when zoom/pan pushes the mask off-stage.return {x: camX + camS * maskX,y: camY + camS * maskY,@@ -576,7 +561,7 @@ export class FrameRenderer {resetNativeCursorMotionBlurState(this.nativeCursorMotionBlurState);return;}- // Position comes from the precomputed offline-smoothed path (deterministic, matches preview);+ // Position comes from the precomputed smoothed path (deterministic, matches preview);// the frame still supplies the cursor image, type, and click timing.const smoothedPos = getSmoothedCursorPath(this.config.cursorRecordingData,@@ -616,8 +601,8 @@ export class FrameRenderer {getNativeCursorClickBounceProgress(this.config.cursorRecordingData, timeMs),);const appliedScale = this.animationState.appliedScale;- // Normalize cursor size so it appears at the same fraction of the video width- // as in the preview — both paths now use maskRect.width / croppedVideoWidth.+ // Normalize cursor size to the same fraction of video width as the preview;+ // both paths use maskRect.width / croppedVideoWidth.const sizeNorm =this.layoutCache.videoSize.width > 0? this.layoutCache.maskRect.width / this.layoutCache.videoSize.width@@ -630,7 +615,7 @@ export class FrameRenderer {state: this.nativeCursorMotionBlurState,timeMs,});- // Clip only when explicitly enabled; by default the cursor may overflow the canvas.+ // Clip only when explicitly enabled; by default the cursor may overflow the canvasconst cursorClip = this.config.cursorClipToBounds === true ? this.cameraAwareMaskRect() : null;this.foregroundCtx.save();this.foregroundCtx.beginPath();@@ -692,7 +677,6 @@ export class FrameRenderer {const videoWidth = this.config.videoWidth;const videoHeight = this.config.videoHeight;- // Calculate cropped video dimensionsconst cropStartX = cropRegion.x;const cropStartY = cropRegion.y;const cropEndX = cropRegion.x + cropRegion.width;@@ -701,9 +685,8 @@ export class FrameRenderer {const croppedVideoWidth = videoWidth * (cropEndX - cropStartX);const croppedVideoHeight = videoHeight * (cropEndY - cropStartY);- // Calculate scale to fit in viewport- // Padding is a percentage (0-100), where 50% ~ 0.8 scale- // Vertical stack ignores padding — it's full-bleed+ // Padding is a percentage (0-100), where 50% ~ 0.8 scale.+ // Vertical stack is full-bleed, so it ignores padding.const effectivePadding = this.config.webcamLayoutPreset === "vertical-stack" ? 0 : padding;const paddingScale = 1.0 - (effectivePadding / 100) * 0.4;const viewportWidth = width * paddingScale;@@ -722,7 +705,7 @@ export class FrameRenderer {const screenRect = compositeLayout.screenRect;- // Cover mode: scale to fill the rect (may crop), otherwise fit-to-width+ // Cover mode scales to fill the rect (may crop), otherwise fit-to-widthlet scale: number;if (compositeLayout.screenCover) {scale = Math.max(@@ -733,7 +716,6 @@ export class FrameRenderer {scale = screenRect.width / croppedVideoWidth;}- // Position video spritethis.videoSprite.width = videoWidth * scale;this.videoSprite.height = videoHeight * scale;@@ -748,11 +730,10 @@ export class FrameRenderer {this.videoSprite.x = -cropPixelX + coverOffsetX;this.videoSprite.y = -cropPixelY + coverOffsetY;- // Position video containerthis.videoContainer.x = screenRect.x;this.videoContainer.y = screenRect.y;- // scale border radius by export/preview canvas ratio+ // Scale border radius by the export/preview canvas ratioconst previewWidth = this.config.previewWidth ?? this.config.width;const previewHeight = this.config.previewHeight ?? this.config.height;const canvasScaleFactor = Math.min(width / previewWidth, height / previewHeight);@@ -767,10 +748,9 @@ export class FrameRenderer {this.maskGraphics.roundRect(0, 0, screenRect.width, screenRect.height, scaledBorderRadius);this.maskGraphics.fill({ color: 0xffffff });- // Cache layout info. baseOffset is the stage position of the FULL- // (uncropped) video sprite's top-left — matches preview semantics so- // downstream consumers (e.g. cursor highlight) can map normalized- // recording-space coordinates to stage coordinates uniformly:+ // baseOffset is the stage position of the full (uncropped) sprite's top-left, matching+ // preview semantics, so consumers (e.g. cursor highlight) can map normalized+ // recording-space coords to stage coords uniformly:// stagePos = baseOffset + (cx, cy) * (videoWidth, videoHeight) * baseScalethis.layoutCache = {stageSize: { width, height },@@ -813,23 +793,23 @@ export class FrameRenderer {targetFocus = regionFocus;targetProgress = strength;- // Apply adaptive smoothing for auto-follow mode+ // Adaptive smoothing for auto-follow modeif (region.focusMode === "auto" && !transition) {const raw = targetFocus;const dtMs = this.prevAnimationTimeMs != null ? timeMs - this.prevAnimationTimeMs : 0;const isZoomingIn = targetProgress < 0.999 && targetProgress >= this.prevTargetProgress;if (targetProgress >= 0.999) {- // Full zoom: adaptive smoothing — moves faster when far, decelerates when close+ // Full zoom: move faster when far, decelerate when closeconst prev = this.smoothedAutoFocus ?? raw;const smoothed = advanceFollowFocus(prev, raw, dtMs, AUTO_FOLLOW_PARAMS);this.smoothedAutoFocus = smoothed;targetFocus = smoothed;} else if (isZoomingIn) {- // Zoom-in: track cursor directly so zoom always aims at current cursor- // position; keep ref in sync to avoid snap when full-zoom begins+ // Track cursor directly while zooming in; keep ref in sync to avoid a snap+ // when full-zoom beginsthis.smoothedAutoFocus = raw;} else {- // Zoom-out: keep smoothing for continuity — avoids snap at zoom-out start+ // Zoom-out: keep smoothing to avoid a snap at the startconst prev = this.smoothedAutoFocus ?? raw;const smoothed = advanceFollowFocus(prev, raw, dtMs, AUTO_FOLLOW_PARAMS);this.smoothedAutoFocus = smoothed;@@ -898,9 +878,9 @@ export class FrameRenderer {focusY: state.focusY,});- // Spring-chase the eased target (same as preview) so exported motion glides without the- // jerk at the steep start of the ease. Stepped by content time; snapped on the first frame- // or any large time jump.+ // Spring-chase the eased target (same as preview) so exported motion glides past the jerk+ // at the steep start of the ease. Stepped by content time; snapped on the first frame or+ // any large time jump.const dtMs = this.prevAnimationTimeMs != null ? timeMs - this.prevAnimationTimeMs : 0;let appliedScale: number;let appliedX: number;@@ -930,10 +910,9 @@ export class FrameRenderer {);}- // On Linux/Wayland the implicit GPU→2D texture-sharing path- // used by drawImage(webglCanvas) can fail silently (EGL/Ozone),- // producing green/empty frames. Explicit gl.readPixels always- // copies from GPU to CPU memory, bypassing that path.+ // On Linux/Wayland the implicit GPU-to-2D texture-sharing path behind+ // drawImage(webglCanvas) can fail silently (EGL/Ozone), giving green/empty+ // frames. gl.readPixels copies GPU to CPU directly, bypassing that path.private readbackVideoCanvas(): HTMLCanvasElement {const glCanvas = this.app!.canvas as HTMLCanvasElement;const gl =@@ -966,8 +945,8 @@ export class FrameRenderer {return this.rasterCanvas;}- // `applyShadowToRecording` is false when the 3D pass will rotate this canvas- // next — the shadow gets re-applied after rotation to avoid aliasing.+ // applyShadowToRecording is false when the 3D pass will rotate this canvas next;+ // the shadow is re-applied after rotation to avoid aliasing.private compositeWithShadows(webcamFrame: VideoFrame | null | undefined,applyShadowToRecording: boolean,@@ -990,8 +969,8 @@ export class FrameRenderer {const w = this.compositeCanvas.width;const h = this.compositeCanvas.height;- // Background layer (compositeCanvas): wallpaper only. Stays flat — never- // touched by the 3D rotation pass, matching preview behavior.+ // Background (compositeCanvas): wallpaper only. Stays flat, never touched by the+ // 3D rotation pass, matching the preview.bgCtx.clearRect(0, 0, w, h);if (this.backgroundSprite) {const bgCanvas = this.backgroundSprite;@@ -1007,8 +986,8 @@ export class FrameRenderer {console.warn("[FrameRenderer] No background sprite found during compositing!");}- // Foreground (transparent): recording + webcam. Shadow only baked here on- // the flat path; the 3D path applies it after rotation (see renderFrame).+ // Foreground (transparent): recording + webcam. Shadow baked here only on the+ // flat path; the 3D path applies it after rotation (see renderFrame).fgCtx.clearRect(0, 0, w, h);if (applyShadowToRecording &&@@ -1042,9 +1021,9 @@ export class FrameRenderer {if (webcamFrame && webcamRect) {const preset = getWebcamLayoutPresetDefinition(this.config.webcamLayoutPreset);const shape = webcamRect.maskShape ?? this.config.webcamMaskShape ?? "rectangle";- // Reactive camera sizing: scale the PiP webcam inversely with the eased zoom. Anchor the- // shrink to the corner the camera is docked in (bottom-right by default), matching the- // preview, so it stays flush against the edges instead of drifting toward center.+ // Scale the PiP webcam inversely with the eased zoom, anchoring the shrink to the+ // docked corner (bottom-right by default) like the preview, so it stays flush to the+ // edges instead of drifting toward center.const reactiveFactor =this.config.webcamReactiveZoom && this.config.webcamLayoutPreset === "picture-in-picture"? reactiveWebcamScale(this.animationState.appliedScale)diff --git a/src/lib/exporter/gifExporter.ts b/src/lib/exporter/gifExporter.tsindex 43a7e4688..9b06fcd30 100644--- a/src/lib/exporter/gifExporter.ts+++ b/src/lib/exporter/gifExporter.ts@@ -138,7 +138,6 @@ export class GifExporter {this.cleanup();this.cancelled = false;- // Initialize streaming decoder and load video metadatathis.streamingDecoder = new StreamingVideoDecoder();const videoInfo = await this.streamingDecoder.loadMetadata(this.config.videoUrl);let webcamInfo: Awaited<ReturnType<StreamingVideoDecoder["loadMetadata"]>> | null = null;@@ -147,7 +146,6 @@ export class GifExporter {webcamInfo = await this.webcamDecoder.loadMetadata(this.config.webcamVideoUrl);}- // Initialize frame rendererthis.renderer = new FrameRenderer({width: this.config.width,height: this.config.height,@@ -186,8 +184,7 @@ export class GifExporter {});await this.renderer.initialize();- // Initialize GIF encoder- // Loop: 0 = infinite loop, 1 = play once (no loop)+ // gif.js repeat: 0 = infinite loop, 1 = play onceconst repeat = this.config.loop ? 0 : 1;const cores = navigator.hardwareConcurrency || 4;const WORKER_COUNT = Math.max(1, Math.min(8, cores - 1));@@ -203,14 +200,14 @@ export class GifExporter {dither: "FloydSteinberg",});- // Calculate effective duration and frame count (excluding trim regions)+ // Effective duration and frame count, excluding trim regionsconst { effectiveDuration, totalFrames } = this.streamingDecoder.getExportMetrics(this.config.frameRate,this.config.trimRegions,this.config.speedRegions,);- // Calculate frame delay in milliseconds (gif.js uses ms)+ // gif.js wants frame delay in msconst frameDelay = Math.round(1000 / this.config.frameRate);console.log("[GifExporter] Original duration:", videoInfo.duration, "s");@@ -260,7 +257,7 @@ export class GifExporter {})(): null;- // Stream decode and process frames — no seeking!+ // Stream decode and process frames, no seekingawait this.streamingDecoder.decodeAll(this.config.frameRate,this.config.trimRegions,@@ -280,19 +277,15 @@ export class GifExporter {return;}- // Render the frame with all effects using source timestamp- const sourceTimestampUs = sourceTimestampMs * 1000; // Convert to microseconds+ const sourceTimestampUs = sourceTimestampMs * 1000; // usawait renderer.renderFrame(videoFrame, sourceTimestampUs, webcamFrame);- // Get the rendered canvas and add to GIFconst canvas = renderer.getCanvas();- // Add frame to GIF encoder with delaythis.gif!.addFrame(canvas, { delay: frameDelay, copy: true });frameIndex++;- // Update progressif (this.config.onProgress) {this.config.onProgress({currentFrame: frameIndex,@@ -318,7 +311,7 @@ export class GifExporter {this.webcamDecoder?.cancel();await webcamDecodePromise;- // Update progress to show we're now in the finalizing phase+ // Now in the finalizing phaseif (this.config.onProgress) {this.config.onProgress({currentFrame: totalFrames,@@ -329,13 +322,11 @@ export class GifExporter {});}- // Render the GIFconst blob = await new Promise<Blob>((resolve, _reject) => {this.gif!.on("finished", (blob: Blob) => {resolve(blob);});- // Track rendering progressthis.gif!.on("progress", (progress: number) => {if (this.config.onProgress) {this.config.onProgress({@@ -349,7 +340,7 @@ export class GifExporter {}});- // gif.js doesn't have a typed 'error' event, but we can catch errors in the try/catch+ // gif.js has no typed 'error' event; the outer try/catch handles failuresthis.gif!.render();});diff --git a/src/lib/exporter/muxer.ts b/src/lib/exporter/muxer.tsindex 95d41ad2e..d2a2a93b9 100644--- a/src/lib/exporter/muxer.ts+++ b/src/lib/exporter/muxer.ts@@ -26,7 +26,6 @@ export class VideoMuxer {}async initialize(): Promise<void> {- // Create the buffer targetthis.target = new BufferTarget();this.output = new Output({@@ -36,19 +35,17 @@ export class VideoMuxer {target: this.target,});- // Create video source - codec will be deduced from metadata+ // Codec is deduced from the chunk metadata.this.videoSource = new EncodedVideoPacketSource("avc");this.output.addVideoTrack(this.videoSource, {frameRate: this.config.frameRate,});- // Create audio source if neededif (this.hasAudio) {this.audioSource = new EncodedAudioPacketSource(this.audioCodec);this.output.addAudioTrack(this.audioSource);}- // Start the output to begin accepting media dataawait this.output.start();}@@ -57,10 +54,8 @@ export class VideoMuxer {throw new Error("Muxer not initialized");}- // Convert WebCodecs chunk to Mediabunny packetconst packet = EncodedPacket.fromEncodedChunk(chunk);- // Add metadata with the first chunkawait this.videoSource.add(packet, meta);}@@ -69,10 +64,8 @@ export class VideoMuxer {throw new Error("Audio not configured for this muxer");}- // Convert WebCodecs chunk to Mediabunny packetconst packet = EncodedPacket.fromEncodedChunk(chunk);- // Add metadata with the first chunkawait this.audioSource.add(packet, meta);}diff --git a/src/lib/exporter/streamingDecoder.ts b/src/lib/exporter/streamingDecoder.tsindex 752d5cd4c..472da8195 100644--- a/src/lib/exporter/streamingDecoder.ts+++ b/src/lib/exporter/streamingDecoder.ts@@ -5,9 +5,8 @@ const SOURCE_LOAD_TIMEOUT_MS = 60_000;const EPSILON_SEC = 0.001;/*** Build a full WebCodecs-compatible AV1 codec string from the AV1CodecConfigurationRecord.- * web-demuxer may return a bare "av01" when the WASM-side parser fails to read- * the extradata (e.g. raw OBU sequence header from WebM instead of ISOBMFF av1C box).- * This function parses the record if present, otherwise returns a safe default.+ * web-demuxer can return a bare "av01" when the WASM parser fails to read the extradata.+ * Parses the record if present, otherwise returns a safe default.** @see https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-section*/@@ -25,9 +24,8 @@ function buildAV1CodecString(description?: BufferSource): string {// Byte 0: marker (1) | version (7)// Byte 1: seq_profile (3) | seq_level_idx_0 (5)// Byte 2: seq_tier_0 (1) | high_bitdepth (1) | twelve_bit (1) | ...- // The spec says version should be 1, but Chrome/Electron's MediaRecorder- // may write version 127 (0xFF first byte). We accept any version as long- // as the marker bit is set and the record is long enough.+ // Spec says version 1, but Chrome/Electron MediaRecorder may write 127 (0xFF),+ // so accept any version as long as the marker bit is set and the record is long enough.if (bytes.length < 4) return fallback;if (!(bytes[0] & 0x80)) return fallback; // marker bit must be 1@@ -71,26 +69,22 @@ const EARLY_DECODE_END_THRESHOLD_SEC = 1;const METADATA_TAIL_TOLERANCE_SEC = 2;const STREAM_DURATION_MATCH_TOLERANCE_SEC = 0.25;const DURATION_DIVERGENCE_THRESHOLD_SEC = 1.5;-// Fallback upper bound for the packet scan when no reliable duration hint is-// available. Explicit end is required (some containers are truncated without-// one), but the hint-derived bound would cap the scan prematurely when-// container/stream duration are missing or corrupt.+// Fallback upper bound for the packet scan when no reliable duration hint exists.+// An explicit end is required (some containers are truncated without one), but a+// hint-derived bound would cap the scan early when duration is missing or corrupt.const SCAN_UNBOUNDED_FALLBACK_SEC = 24 * 60 * 60;/**- * Validate container duration against actual packet timestamps.- *- * Chrome/Electron's MediaRecorder writes WebM containers with unreliable- * Duration fields (often Infinity, 0, or inflated) — especially on Linux.- * This function picks the most trustworthy duration value.+ * Pick the most trustworthy duration. Chrome/Electron MediaRecorder writes WebM+ * with unreliable Duration fields (often Infinity, 0, or inflated), especially on Linux.** @param containerDuration Duration from the container-level metadata* @param scannedDuration Duration derived from actual packet timestamps (ground truth)*/export function validateDuration(containerDuration: number, scannedDuration: number): number {if (scannedDuration <= 0) {- // Zero scanned duration means corrupted/empty file — fall back to container- // (downstream shouldFailDecodeEndedEarly will catch truly empty files)+ // Corrupted/empty file, fall back to container.+ // (downstream shouldFailDecodeEndedEarly catches truly empty files)return Number.isFinite(containerDuration) ? Math.max(containerDuration, 0) : 0;}if (!Number.isFinite(containerDuration) || containerDuration <= 0) {@@ -138,11 +132,8 @@ export function shouldFailDecodeEndedEarly({}/**- * Loads a video file as an ArrayBuffer, delegating to- * `StreamingVideoDecoder.loadLocalSourceFile` for local paths (Electron IPC)- * and `StreamingVideoDecoder.loadRemoteSourceFile` for remote / blob / data URLs.- * Also returns the `contentType` derived from the blob (empty string for local- * IPC reads where no Content-Type is available).+ * Loads a video file as an ArrayBuffer via the local (Electron IPC) or remote loader.+ * contentType is empty for local IPC reads, which carry no Content-Type.*/export async function loadFileAsArrayBuffer(videoUrl: string,@@ -229,7 +220,7 @@ export class StreamingVideoDecoder {async loadMetadata(videoUrl: string): Promise<DecodedVideoInfo> {const { file } = await this.loadSourceFile(videoUrl);- // Relative URL so it resolves correctly in both dev (http) and packaged (file://) builds+ // Relative URL so it resolves in both dev (http) and packaged (file://) buildsconst wasmUrl = new URL("./wasm/web-demuxer.wasm", window.location.href).href;this.demuxer = new WebDemuxer({ wasmFilePath: wasmUrl });await this.withTimeout(@@ -257,12 +248,11 @@ export class StreamingVideoDecoder {const audioStream = mediaInfo.streams.find((s) => s.codec_type_string === "audio");- // Scan video packets to find the true content boundary.- // MediaRecorder (especially on Linux) writes unreliable container durations.- // Packet timestamps are ground truth — no decode needed, just timestamp reads.- // Pass explicit range because some containers are truncated without one.- // Sanitize because mediaInfo.duration can be NaN/Infinity (Chromium Linux bug),- // which would propagate into demuxer.read() as an invalid endpoint.+ // Scan video packets for the true content boundary; MediaRecorder (especially on+ // Linux) writes unreliable container durations and packet timestamps are ground truth.+ // Pass an explicit range because some containers are truncated without one.+ // Sanitize because mediaInfo.duration can be NaN/Infinity (Chromium Linux bug), which+ // would reach demuxer.read() as an invalid endpoint.const containerDurationSec = Number.isFinite(mediaInfo.duration) ? mediaInfo.duration : 0;const streamDurationSec =typeof videoStream?.duration === "number" && Number.isFinite(videoStream.duration)@@ -307,12 +297,10 @@ export class StreamingVideoDecoder {return this.metadata;}/**- * Decodes all video frames from the loaded source and invokes a callback for each.- * Handles trimming and speed adjustments, and resamples to the target frame rate.- * On Windows, early decode termination is tolerated to work around driver quirks.+ * Decodes all video frames, applying trim/speed and resampling to the target frame rate.* @param targetFrameRate - Desired output frame rate.- * @param trimRegions - Array of time regions to keep (others discarded).- * @param speedRegions - Array of speed adjustments for specific time ranges.+ * @param trimRegions - Time regions to keep (others discarded).+ * @param speedRegions - Speed adjustments for specific time ranges.* @param onFrame - Async callback receiving each decoded VideoFrame.*/async decodeAll(@@ -331,9 +319,8 @@ export class StreamingVideoDecoder {console.log("[StreamingVideoDecoder] decoderConfig.codec:", decoderConfig.codec);console.log("[StreamingVideoDecoder] decoderConfig.description:", decoderConfig.description);- // web-demuxer may return bare four-character code strings ("av01", "vp08",- // "vp09", "avc1") that WebCodecs rejects. Normalize them to the short or- // full parametrized forms that VideoDecoder accepts.+ // web-demuxer can return bare fourcc strings ("av01", "vp08", "vp09", "avc1")+ // that WebCodecs rejects; normalize to forms VideoDecoder accepts.if (/^av01$/i.test(decoderConfig.codec)) {decoderConfig.codec = buildAV1CodecString(decoderConfig.description as BufferSource | undefined,@@ -373,7 +360,7 @@ export class StreamingVideoDecoder {);const frameDurationUs = 1_000_000 / targetFrameRate;- // Async frame queue — decoder pushes, consumer pulls+ // Async frame queue: decoder pushes, consumer pulls.const pendingFrames: VideoFrame[] = [];let frameResolve: ((frame: VideoFrame | null) => void) | null = null;let decodeError: Error | null = null;@@ -443,12 +430,12 @@ export class StreamingVideoDecoder {});};- // One forward stream through the whole file.- // Pass explicit range because some containers are truncated when no end is provided.+ // One forward stream through the whole file. Pass an explicit range because+ // some containers are truncated when no end is provided.const readEndSec = this.metadata.duration + 0.5;const reader = this.demuxer.read("video", 0, readEndSec).getReader();- // Feed chunks to decoder in background with backpressure+ // Feed chunks to the decoder in the background with backpressure.const feedPromise = (async () => {try {while (!this.cancelled) {@@ -482,7 +469,7 @@ export class StreamingVideoDecoder {}})();- // Route decoded frames into segments by timestamp, then deliver with VFR→CFR resampling+ // Route decoded frames into segments by timestamp, then deliver with VFR to CFR resampling.let segmentIdx = 0;let segmentFrameIndex = 0;let exportFrameIndex = 0;@@ -681,9 +668,8 @@ export class StreamingVideoDecoder {}/**- * Calculates the effective output duration (in seconds) and total frame count- * for a given combination of trim and speed regions at the target frame rate.- * Requires `loadMetadata()` to have been called first.+ * Effective output duration (seconds) and total frame count for the given trim/speed+ * regions at the target frame rate. Requires loadMetadata() first.*/getExportMetrics(targetFrameRate: number,diff --git a/src/lib/exporter/threeDPass.ts b/src/lib/exporter/threeDPass.tsindex 5733bd05f..657c5ff2a 100644--- a/src/lib/exporter/threeDPass.ts+++ b/src/lib/exporter/threeDPass.ts@@ -5,10 +5,9 @@ import {rotation3DPerspective,} from "@/components/video-editor/types";-// CSS uses +y down, WebGL clip space uses +y up. We do all rotation math in CSS-// convention (top-left origin, +y down) to match the preview, then flip-// gl_Position.y at the end so WebGL's clip space lands the input's top edge at-// the top of the output viewport.+// Rotation math is done in CSS convention (+y down) to match the preview, then+// gl_Position.y is flipped so WebGL clip space (+y up) lands the input's top edge+// at the top of the viewport.const VERTEX_SHADER = `#version 300 esin vec2 aPos;in vec2 aUV;@@ -151,10 +150,7 @@ function createProgram(gl: WebGL2RenderingContext): WebGLProgram {export interface ThreeDPass {apply(srcCanvas: HTMLCanvasElement | OffscreenCanvas, rot: Rotation3D): HTMLCanvasElement;- /**- * Reads back the most recent apply() result into a Uint8ClampedArray suitable- * for ImageData. Use this on platforms where drawImage(webglCanvas) is unreliable.- */+ /** Read the last apply() result as ImageData-ready pixels, for platforms where drawImage(webglCanvas) is unreliable. */readPixels(): Uint8ClampedArray;resize(width: number, height: number): void;destroy(): void;@@ -180,10 +176,9 @@ export function createThreeDPass(width: number, height: number): ThreeDPass {const vao = gl.createVertexArray();gl.bindVertexArray(vao);- // Quad: two triangles sharing UVs consistently per corner.- // pos.y ranges 0 (top of input) → 1 (bottom of input) following CSS convention.- // UV.y is inverted (1 - pos.y) so that with UNPACK_FLIP_Y_WEBGL the texture- // sample at the top of the input lands at the top of the rendered quad.+ // Quad as two triangles. pos.y is 0 (top) to 1 (bottom) per CSS convention; UV.y+ // is inverted so that with UNPACK_FLIP_Y_WEBGL the top of the input lands at the+ // top of the rendered quad.// TL: pos(0,0) uv(0,1) TR: pos(1,0) uv(1,1)// BL: pos(0,1) uv(0,0) BR: pos(1,1) uv(1,0)const verts = new Float32Array([@@ -207,7 +202,7 @@ export function createThreeDPass(width: number, height: number): ThreeDPass {1,0,1,- 1, // TR (was 1,0,1,0 — broken)+ 1, // TR (was 1,0,1,0, broken)1,1,1,@@ -224,20 +219,17 @@ export function createThreeDPass(width: number, height: number): ThreeDPass {const texture = gl.createTexture();gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D, texture);- // Plain bilinear, NO mipmaps. Mipmaps pre-blur the texture for downsampling, but- // at our moderate rotation angles (≤22°) the receding edge would still pick a- // smaller mipmap level, which softens fine details — specifically the few-pixel- // rounded-corner anti-alias ramp and the shadow's Gaussian falloff. The result- // is "rounding looks like a hard corner / shadow looks grimy". Sampling level 0- // directly preserves the source crispness.+ // Plain bilinear, no mipmaps. Even at our moderate angles (<=22deg) the receding+ // edge picks a smaller mip level, softening the rounded-corner AA ramp and shadow+ // falloff (corners look hard, shadows grimy). Sampling level 0 keeps source crispness.gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);- // Anisotropic filtering still helps without mipmaps: at oblique viewing angles- // it samples multiple texels along the gradient direction at level 0, recovering- // detail that plain bilinear would lose. Cap to the device max (16× typical).+ // Anisotropic filtering still helps without mipmaps: at oblique angles it samples+ // multiple texels along the gradient at level 0, recovering detail bilinear loses.+ // Cap to the device max (16x typical).const anisoExt =gl.getExtension("EXT_texture_filter_anisotropic") ||gl.getExtension("MOZ_EXT_texture_filter_anisotropic") ||@@ -263,15 +255,10 @@ export function createThreeDPass(width: number, height: number): ThreeDPass {gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D, texture);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);- // CRITICAL: premultiply on upload. The source 2D canvas stores non-premultiplied- // RGBA (alpha=0 areas have RGB=0). Bilinear filtering between an inside-the-shape- // texel (alpha=1, RGB=color) and an outside texel (alpha=0, RGB=0) in- // non-premultiplied space yields (color/2, alpha=0.5), which the- // premultipliedAlpha:true canvas then interprets as half-strength color — visible- // as a dark halo around rounded corners and softened/grimy shadows. Premultiplying- // at upload time makes the bilinear math operate in linear-light premultiplied- // space, which is exactly the math used for compositing. Edges and shadows then- // reproduce the source crisply.+ // Premultiply on upload. The source 2D canvas is non-premultiplied (alpha=0 areas+ // have RGB=0), so bilinear filtering across a shape edge in that space gives+ // half-strength color, showing as a dark halo on rounded corners and grimy shadows.+ // Premultiplying makes the filter math match compositing, so edges stay crisp.gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);gl.texImage2D(gl.TEXTURE_2D,@@ -308,11 +295,9 @@ export function createThreeDPass(width: number, height: number): ThreeDPass {const h = currentSize.height;const buf = new Uint8Array(w * h * 4);gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, buf);- // gl.readPixels is bottom-up; flip to top-down for ImageData. We also need- // to un-premultiply the alpha here: the framebuffer holds premultiplied RGBA- // (we set UNPACK_PREMULTIPLY_ALPHA_WEBGL=true on upload), but ImageData /- // putImageData expect non-premultiplied. Without this divide, semi-transparent- // pixels get interpreted as darker than they should be.+ // readPixels is bottom-up, so flip to top-down. Also un-premultiply: the+ // framebuffer is premultiplied (UNPACK_PREMULTIPLY_ALPHA_WEBGL on upload) but+ // ImageData expects non-premultiplied, else semi-transparent pixels read too dark.const rowSize = w * 4;const out = new Uint8ClampedArray(buf.length);for (let row = 0; row < h; row += 1) {diff --git a/src/lib/exporter/types.ts b/src/lib/exporter/types.tsindex 387334177..138d97ecb 100644--- a/src/lib/exporter/types.ts+++ b/src/lib/exporter/types.ts@@ -10,9 +10,9 @@ export interface ExportProgress {currentFrame: number;totalFrames: number;percentage: number;- estimatedTimeRemaining: number; // in seconds- phase?: "extracting" | "finalizing"; // Phase of export- renderProgress?: number; // 0-100, progress of GIF rendering phase+ estimatedTimeRemaining: number; // seconds+ phase?: "extracting" | "finalizing";+ renderProgress?: number; // 0-100, GIF render phase}export interface ExportResult {diff --git a/src/lib/exporter/videoDecoder.ts b/src/lib/exporter/videoDecoder.tsindex 4ed1157ac..505e94f2e 100644--- a/src/lib/exporter/videoDecoder.ts+++ b/src/lib/exporter/videoDecoder.ts@@ -36,9 +36,7 @@ export class VideoFileDecoder {});}- /**- * Get video element for seeking- */+ /** The underlying video element, used for seeking. */getVideoElement(): HTMLVideoElement | null {return this.videoElement;}diff --git a/src/lib/frameStep.ts b/src/lib/frameStep.tsindex dc42d78cb..29d8f49fa 100644--- a/src/lib/frameStep.ts+++ b/src/lib/frameStep.ts@@ -1,10 +1,7 @@-/** Duration of a single frame in seconds at 60 FPS (~16.67ms). */+/** One frame in seconds at 60 FPS (~16.67ms). */export const FRAME_DURATION_SEC = 1 / 60;-/**- * Compute the new playhead time after stepping one frame forward or backward.- * The result is clamped to the range [0, duration].- */+/** New playhead time after stepping one frame, clamped to [0, duration]. */export function computeFrameStepTime(currentTime: number,duration: number,diff --git a/src/lib/recordingSession.ts b/src/lib/recordingSession.tsindex 12a6afd22..f7d69cbf7 100644--- a/src/lib/recordingSession.ts+++ b/src/lib/recordingSession.ts@@ -21,11 +21,10 @@ export interface StoreRecordedSessionInput {createdAt?: number;cursorCaptureMode?: CursorCaptureMode;/**- * Recording wall-clock duration in milliseconds. Used by the main process- * to patch the WebM Duration header on streamed recordings, since the- * renderer no longer holds the bytes. Browser MediaRecorder writes WebM- * with no/zero duration; without this patch, the editor's seek bar and- * timeline break for any recording that took the streaming path.+ * Recording wall-clock duration (ms). The main process patches the WebM Duration+ * header on streamed recordings (the renderer no longer holds the bytes). Browser+ * MediaRecorder writes no/zero duration, which breaks the editor seek bar and+ * timeline for anything that took the streaming path.*/durationMs?: number;}diff --git a/src/lib/userPreferences.ts b/src/lib/userPreferences.tsindex 730236016..66c5a66a4 100644--- a/src/lib/userPreferences.ts+++ b/src/lib/userPreferences.ts@@ -55,10 +55,7 @@ function safeJsonParse(text: string | null): Record<string, unknown> | null {}}-/**- * Load persisted user preferences from localStorage.- * Returns defaults for any missing or invalid fields.- */+/** Load preferences from localStorage, falling back to defaults for missing or invalid fields. */export function loadUserPreferences(): UserPreferences {let raw: Record<string, unknown> | null = null;try {@@ -106,15 +103,10 @@ export function loadUserPreferences(): UserPreferences {}/**- * Extracts the parent directory from a saved file path. Handles both POSIX- * and Windows separators since the path comes from the OS save dialog.- *- * Root directories are preserved with their trailing separator so that the- * value is still a valid directory path:- * "/video.mp4" -> "/"- * "C:\\video.mp4" -> "C:\\"- *- * Returns null if no separator is found.+ * Parent directory of a saved file path. Handles both POSIX and Windows+ * separators since the path comes from the OS save dialog. Root dirs keep their+ * trailing separator so the result stays a valid directory ("/video.mp4" -> "/",+ * "C:\\video.mp4" -> "C:\\"). Returns null if no separator is found.*/export function parentDirectoryOf(filePath: string): string | null {const lastSep = Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\"));@@ -131,33 +123,23 @@ export function parentDirectoryOf(filePath: string): string | null {return filePath.slice(0, lastSep);}-/**- * Returns the remembered export folder as `string | undefined`, suitable for- * passing directly to IPC handlers that treat absence as "use the default".- */+/** Remembered export folder as `string | undefined`, for IPC handlers that treat absence as "use the default". */export function getExportFolder(): string | undefined {return loadUserPreferences().exportFolder ?? undefined;}-/**- * Returns the remembered open-project folder as `string | undefined`,- * suitable for passing directly to IPC handlers that treat absence as- * "use the default".- */+/** Remembered open-project folder as `string | undefined`, for IPC handlers that treat absence as "use the default". */export function getProjectFolder(): string | undefined {return loadUserPreferences().projectFolder ?? undefined;}-/**- * Persist user preferences to localStorage.- * Only the explicitly provided fields are updated.- */+/** Persist preferences to localStorage; only the provided fields are updated. */export function saveUserPreferences(partial: Partial<UserPreferences>): void {const current = loadUserPreferences();const merged = { ...current, ...partial };try {localStorage.setItem(PREFS_KEY, JSON.stringify(merged));} catch {- // localStorage may be unavailable (e.g. private browsing quota exceeded)+ // localStorage may be unavailable (e.g. private browsing, quota exceeded)}}diff --git a/src/lib/vite-stubs/empty-node-module.ts b/src/lib/vite-stubs/empty-node-module.tsindex 16ee52688..00d8207f7 100644--- a/src/lib/vite-stubs/empty-node-module.ts+++ b/src/lib/vite-stubs/empty-node-module.ts@@ -1,7 +1,7 @@/**- * Default export with no enumerable keys. Used as a Vite alias target for Node- * builtins that `@xenova/transformers` imports; `env.js` treats an empty object- * as “no filesystem” so it stays on browser / remote paths.+ * Empty default export, used as the Vite alias target for Node builtins that+ * @xenova/transformers imports. Its env.js reads an empty object as "no filesystem"+ * and stays on the browser/remote paths.*/const empty = Object.create(null) as Record<string, never>;export default empty;diff --git a/src/lib/vite-stubs/onnxruntime-node-stub.ts b/src/lib/vite-stubs/onnxruntime-node-stub.tsindex a70b3dd60..f13969c22 100644--- a/src/lib/vite-stubs/onnxruntime-node-stub.ts+++ b/src/lib/vite-stubs/onnxruntime-node-stub.ts@@ -1,8 +1,8 @@/**- * Transformers always imports `onnxruntime-node`, then picks web vs node from `process.release.name`.- * In Electron's renderer that name is often `"node"` while we still must use the WASM build — the real- * `onnxruntime-node` package is aliased away (it pulls `fs`). Re-export `onnxruntime-web` here so the- * "node" branch still receives a working ORT with `registerBackend` etc.+ * Transformers imports `onnxruntime-node`, then picks web vs node from+ * `process.release.name`, which is often `"node"` in Electron's renderer even+ * though we need the WASM build. The real `onnxruntime-node` is aliased away (it+ * pulls `fs`), so re-export `onnxruntime-web` to give the node branch a working ORT.*/import * as ortWeb from "onnxruntime-web";diff --git a/src/lib/webcamMaskShapes.ts b/src/lib/webcamMaskShapes.tsindex f90e727d2..44d2ca6be 100644--- a/src/lib/webcamMaskShapes.ts+++ b/src/lib/webcamMaskShapes.ts@@ -16,8 +16,8 @@ export function getCssClipPath(shape: WebcamMaskShape): string | null {}/**- * Draws a Canvas 2D clip path for the given webcam mask shape.- * Call ctx.beginPath() is handled internally; caller should call ctx.clip() after.+ * Draws a Canvas 2D clip path for the given webcam mask shape. beginPath is+ * handled internally; caller should call ctx.clip() after.*/export function drawCanvasClipPath(ctx: CanvasRenderingContext2D,diff --git a/src/native/contracts.ts b/src/native/contracts.tsindex 123447f14..60075d397 100644--- a/src/native/contracts.ts+++ b/src/native/contracts.ts@@ -166,7 +166,7 @@ export type NativeBridgeRequest =domain: "project";action: "loadProjectFile";payload?: {- /** Folder to pre-fill the open dialog with — typically the user's+ /** Folder to pre-fill the open dialog with, usually the user's* last-opened project folder from userPreferences. */projectFolder?: string;};diff --git a/src/utils/aspectRatioUtils.ts b/src/utils/aspectRatioUtils.tsindex 5e174ab3c..3fbdcd07c 100644--- a/src/utils/aspectRatioUtils.ts+++ b/src/utils/aspectRatioUtils.ts@@ -14,9 +14,8 @@ export type AspectRatio = (typeof ASPECT_RATIOS)[number];const NATIVE_ASPECT_RATIO_FALLBACK = 16 / 9;/**- * Returns the numeric value of an aspect ratio.- * For "native", returns a fallback ratio of 16/9.- * Callers with source/crop context should use getNativeAspectRatioValue().+ * Numeric value of an aspect ratio. "native" returns the 16/9 fallback;+ * callers with source/crop context should use getNativeAspectRatioValue().*/export function getAspectRatioValue(aspectRatio: AspectRatio): number {switch (aspectRatio) {diff --git a/src/utils/platformUtils.ts b/src/utils/platformUtils.tsindex 2fb57e1b9..e41145ee4 100644--- a/src/utils/platformUtils.ts+++ b/src/utils/platformUtils.ts@@ -12,7 +12,7 @@ export const getPlatform = async (): Promise<string> => {return platform;} catch (error) {console.warn("Failed to get platform from Electron, falling back to navigator:", error);- // Fallback for development/testing+ // Fallback for dev/testinglet fallbackPlatform = "win32";if (typeof navigator !== "undefined") {if (/Mac|iPhone|iPad|iPod/.test(navigator.platform)) {