Skip to content

fix(recording): publish Windows mic sidecar atomically - #785

Open
AbhishekBarali wants to merge 1 commit into
webadderallorg:mainfrom
AbhishekBarali:fix/windows-mic-sidecar-truncation
Open

fix(recording): publish Windows mic sidecar atomically#785
AbhishekBarali wants to merge 1 commit into
webadderallorg:mainfrom
AbhishekBarali:fix/windows-mic-sidecar-truncation

Conversation

@AbhishekBarali

@AbhishekBarali AbhishekBarali commented Aug 1, 2026

Copy link
Copy Markdown

Description

On Windows the microphone track is cut short — it typically stops 15-20 seconds in, even though the capture itself is complete.

Motivation

The mic is captured in the renderer and converted to a .mic.wav sidecar by FFmpeg after capture stops. That took 3.2s for a 67s clip, but the editor opens immediately, and FFmpeg wrote directly to the final path.

An unfinalized WAV declares a data size of 0xFFFFFFFF ("read to EOF"), so a mid-write read parses as a complete but shorter recording. Discovery accepted any file above zero bytes, so the editor loaded it.

Sampling the output during a real encode (bundled FFmpeg, same filter chain):

  • 315 ms elapsed: 5.5 s of audio visible
  • 630 ms: 13.7 s
  • 930 ms: 21.8 s

Editor startup lands inside that window, matching the reported 15-20 s. From an affected recording: capture stopped 09:21:12.922, sidecar finalized 09:21:16.138, finished file holds 67.26 s.

Type of Change

  • Bug Fix

What changed

  • Encode to a staging path, publish with one atomic rename; timing metadata written first.
  • Skip WAV sidecars still holding the streaming sentinel. Zero-byte files are still accepted, so recovery of interrupted recordings is unaffected.
  • Make the cross-volume fallback in the file move atomic too.
  • Report an in-flight conversion so the editor re-checks, instead of relying only on the session-changed broadcast that a mux failure could suppress.

Testing Guide

npm test (997 pass, including 2 new regression tests), npx tsc --noEmit, npm run lint.

A harness driving the real FFmpeg binary: the old path returned a truncated file on 20 of 20 samples (2.73-65.54 s apparent); the new path returned none, with the published file complete.

Verified at the file level on Windows 11, not yet through a long GUI session. macOS and Linux are untouched, as the new check applies only to WAV.

Summary by CodeRabbit

  • Bug Fixes
    • Improved audio fallback handling so partially written microphone recordings are not used prematurely.
    • Added automatic retrying while companion audio conversion is still in progress.
    • Improved cross-volume file transfers to prevent incomplete files from being published.
    • Windows recording sessions now continue broadcasting and finalizing if muxing encounters an error.
    • Incomplete audio staging files are cleaned up automatically.

FFmpeg wrote the mic sidecar straight to its final path while the editor was
already open. An unfinalized WAV advertises data size 0xFFFFFFFF, so the editor
loaded a valid-looking but truncated track.
@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The recording pipeline now stages microphone sidecars with atomic publication, reports pending conversion state, validates WAV finalization, retries fallback discovery, cleans incomplete files, and continues background finalization after Windows mux errors.

Changes

Sidecar finalization and fallback handling

Layer / File(s) Summary
Atomic sidecar publication
electron/ipc/constants.ts, electron/ipc/utils.ts, electron/ipc/recording/prune.ts
Adds the .incomplete suffix. Cross-volume moves publish through a destination-side staging file. Cleanup removes incomplete system and microphone sidecars.
Pending microphone conversion
electron/electron-env.d.ts, electron/ipc/register/recording.ts
Tracks microphone sidecar conversion, exposes pending, encodes to a staging path, writes metadata, atomically publishes the final WAV, and clears pending state during cleanup.
WAV finalization diagnostics
electron/ipc/recording/diagnostics.ts, electron/ipc/recording/diagnostics.test.ts
Rejects WAV files with unknown RIFF or data chunk sizes. Tests cover streaming, finalized, non-RIFF, and missing files.
Fallback polling and recording continuation
src/components/video-editor/audio/useSourceAudioFallback.ts, src/hooks/useScreenRecorder.ts
Polls pending fallback conversion with bounded retries and logs Windows mux failures without stopping later finalization work.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Recorder
  participant RecordingIPC
  participant FFmpeg
  participant Editor
  Recorder->>RecordingIPC: start microphone sidecar conversion
  RecordingIPC->>FFmpeg: write incomplete staging WAV
  Editor->>RecordingIPC: request fallback paths
  RecordingIPC-->>Editor: pending conversion state
  FFmpeg-->>RecordingIPC: conversion completes
  RecordingIPC->>RecordingIPC: write metadata and publish final sidecar
  Editor->>RecordingIPC: retry fallback paths
  RecordingIPC-->>Editor: finalized sidecar path
Loading

Possibly related PRs

Suggested reviewers: webadderall, meiiie, extrabinoss

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: atomic publication of the Windows microphone sidecar.
Description check ✅ Passed The description covers the problem, motivation, bug-fix type, implementation, and testing results with sufficient technical detail.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@electron/ipc/recording/diagnostics.ts`:
- Around line 467-473: Update isUsableCompanionAudioFile so zero-byte companion
files remain eligible for recovery instead of being rejected by the stat.size
check; preserve the existing finalized-WAV validation for .wav files and the
unconditional eligibility of non-WAV files. Add a regression test covering a
zero-byte .wav companion returned by the fallback lookup.

In `@electron/ipc/register/recording.ts`:
- Around line 1791-1795: Update the conversion cleanup Promise.all near
moveFileWithOverwrite to also remove the metadata sidecar created from
sidecarPath. Delete the ${sidecarPath}.json artifact with forced, non-failing
cleanup alongside tempWebmPath, stagingSidecarPath, and sidecarPath, preserving
cleanup behavior on retries.

In `@src/hooks/useScreenRecorder.ts`:
- Around line 1159-1169: Update the native Windows mux handling in the recording
flow around muxNativeWindowsRecording to inspect its resolved result and log an
error when success is false, in addition to retaining the existing catch for
rejected IPC calls. Ensure resolved mux failures include the returned error
details in the console.error output before proceeding.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 36a1517e-c377-49fb-a085-2d9b413a928b

📥 Commits

Reviewing files that changed from the base of the PR and between 54ae801 and 06810e2.

📒 Files selected for processing (9)
  • electron/electron-env.d.ts
  • electron/ipc/constants.ts
  • electron/ipc/recording/diagnostics.test.ts
  • electron/ipc/recording/diagnostics.ts
  • electron/ipc/recording/prune.ts
  • electron/ipc/register/recording.ts
  • electron/ipc/utils.ts
  • src/components/video-editor/audio/useSourceAudioFallback.ts
  • src/hooks/useScreenRecorder.ts

Comment on lines +467 to +473
async function isUsableCompanionAudioFile(companionPath: string): Promise<boolean> {
const stat = await fs.stat(companionPath);
if (stat.size <= 0) {
return false;
}

return companionPath.toLowerCase().endsWith(".wav") ? isFinalizedWavFile(companionPath) : true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Keep zero-byte sidecars eligible for recovery.

Line 469 rejects zero-byte files before WAV finalization inspection. The fallback lookup therefore cannot return a zero-byte sidecar. This conflicts with the recovery contract in the PR objective.

Proposed fix
 const stat = await fs.stat(companionPath);
- if (stat.size <= 0) {
+ if (stat.size < 0) {
   return false;
 }

Add a regression test for a zero-byte .wav companion.

🧰 Tools
🪛 ast-grep (0.45.0)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFile } from "node:child_process";
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@electron/ipc/recording/diagnostics.ts` around lines 467 - 473, Update
isUsableCompanionAudioFile so zero-byte companion files remain eligible for
recovery instead of being rejected by the stat.size check; preserve the existing
finalized-WAV validation for .wav files and the unconditional eligibility of
non-WAV files. Add a regression test covering a zero-byte .wav companion
returned by the fallback lookup.

Comment on lines 1791 to 1795
await Promise.all([
fs.rm(tempWebmPath, { force: true }).catch(() => undefined),
fs.rm(stagingSidecarPath, { force: true }).catch(() => undefined),
fs.rm(sidecarPath, { force: true }).catch(() => undefined),
]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Remove the metadata sidecar during conversion cleanup.

Line 1763 can create ${sidecarPath}.json before moveFileWithOverwrite fails. This cleanup leaves that metadata behind. A later retry without metadata can then use stale timing data for the new sidecar.

Proposed fix
 await Promise.all([
   fs.rm(tempWebmPath, { force: true }).catch(() => undefined),
   fs.rm(stagingSidecarPath, { force: true }).catch(() => undefined),
   fs.rm(sidecarPath, { force: true }).catch(() => undefined),
+  fs.rm(`${sidecarPath}.json`, { force: true }).catch(() => undefined),
 ]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await Promise.all([
fs.rm(tempWebmPath, { force: true }).catch(() => undefined),
fs.rm(stagingSidecarPath, { force: true }).catch(() => undefined),
fs.rm(sidecarPath, { force: true }).catch(() => undefined),
]);
await Promise.all([
fs.rm(tempWebmPath, { force: true }).catch(() => undefined),
fs.rm(stagingSidecarPath, { force: true }).catch(() => undefined),
fs.rm(sidecarPath, { force: true }).catch(() => undefined),
fs.rm(`${sidecarPath}.json`, { force: true }).catch(() => undefined),
]);
🧰 Tools
🪛 ast-grep (0.45.0)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import type { ChildProcessWithoutNullStreams } from "node:child_process";
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@electron/ipc/register/recording.ts` around lines 1791 - 1795, Update the
conversion cleanup Promise.all near moveFileWithOverwrite to also remove the
metadata sidecar created from sidecarPath. Delete the ${sidecarPath}.json
artifact with forced, non-failing cleanup alongside tempWebmPath,
stagingSidecarPath, and sidecarPath, preserving cleanup behavior on retries.

Comment on lines 1159 to +1169
if (isNativeWindows) {
await window.electronAPI.muxNativeWindowsRecording(expectedDurationMs);
try {
await window.electronAPI.muxNativeWindowsRecording(
expectedDurationMs,
);
} catch (muxError) {
console.error(
"Failed to mux native Windows recording audio:",
muxError,
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Log resolved mux failures.

muxNativeWindowsRecording returns success: false for mux errors. This catch only handles rejected IPC calls. A resolved failure proceeds without the required error log.

 if (isNativeWindows) {
   try {
-    await window.electronAPI.muxNativeWindowsRecording(expectedDurationMs);
+    const muxResult =
+      await window.electronAPI.muxNativeWindowsRecording(expectedDurationMs);
+    if (!muxResult.success) {
+      console.error(
+        "Failed to mux native Windows recording audio:",
+        muxResult.error ?? muxResult.message,
+      );
+    }
   } catch (muxError) {
     console.error(
       "Failed to mux native Windows recording audio:",
       muxError,
     );
   }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (isNativeWindows) {
await window.electronAPI.muxNativeWindowsRecording(expectedDurationMs);
try {
await window.electronAPI.muxNativeWindowsRecording(
expectedDurationMs,
);
} catch (muxError) {
console.error(
"Failed to mux native Windows recording audio:",
muxError,
);
}
if (isNativeWindows) {
try {
const muxResult =
await window.electronAPI.muxNativeWindowsRecording(
expectedDurationMs,
);
if (!muxResult.success) {
console.error(
"Failed to mux native Windows recording audio:",
muxResult.error ?? muxResult.message,
);
}
} catch (muxError) {
console.error(
"Failed to mux native Windows recording audio:",
muxError,
);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/hooks/useScreenRecorder.ts` around lines 1159 - 1169, Update the native
Windows mux handling in the recording flow around muxNativeWindowsRecording to
inspect its resolved result and log an error when success is false, in addition
to retaining the existing catch for rejected IPC calls. Ensure resolved mux
failures include the returned error details in the console.error output before
proceeding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant