Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(media): stop media pause/resume from blocking the main process (#2073) (#2094)

Chad Piha71bf4f6e3885
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 088d2639a..520880b38 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Managed enterprise providers no longer require SSO. Require SSO stays an independent workspace control.
- Managed Azure text processing accepts AI Foundry and AI Services endpoints.
+### Fixed
+
+- Windows and Linux media pause/resume no longer block the main process. A slow or stuck PowerShell, nircmd, playerctl or dbus-send helper previously froze hotkeys, IPC and the dictation window until it exited, so a dictation could no longer be stopped and its recording was lost. Pause, resume and toggle now also run one at a time, so a quick tap can no longer strand media paused — previously possible on macOS. (#2073)
+
## [1.9.2] - 2026-08-29
A repair release for two 1.9.1 regressions. Windows desktop sign-in works again — every provider button had gone dead — and the three transcription paths that only failed in packaged builds are back on all platforms. Meetings get three fixes of their own: recordings that captured only your voice on Windows, prompts that stopped appearing after the first call, and swipe-to-dismiss on the prompt cards.
diff --git a/src/helpers/mediaPlayer.js b/src/helpers/mediaPlayer.js
index 950d7db7a..cee74d853 100644
--- a/src/helpers/mediaPlayer.js
+++ b/src/helpers/mediaPlayer.js
@@ -1,24 +1,44 @@
-const { spawn, spawnSync } = require("child_process");
+const { spawn } = require("child_process");
const path = require("path");
const fs = require("fs");
const debugLogger = require("./debugLogger");
-
-// Runs `cmd args` asynchronously and resolves with { status, stdout, stderr }.
-// Times out after `timeout` ms; on timeout, kills the child and resolves with
-// status: null. Never rejects — callers branch on status === 0.
+const { killProcess } = require("../utils/process");
+
+// spawnSync capped a child's output at 1 MB and killed anything past it. Keep
+// that bound: these helpers emit a few KB, and an unbounded buffer would let a
+// runaway one grow main-process memory until its deadline.
+const MAX_OUTPUT_BYTES = 1024 * 1024;
+
+// Runs `cmd args` asynchronously and resolves with
+// { status, stdout, stderr, timedOut }. Times out after `timeout` ms; on
+// timeout it kills the child and resolves with the exit code the child already
+// reported, or status: null and timedOut: true when it never exited. A spawn
+// failure also resolves with status: null but timedOut: false. Output is
+// capped at MAX_OUTPUT_BYTES. Never rejects — callers branch on status === 0.
+//
+// Every media helper goes through here rather than spawnSync: a synchronous
+// spawn parks the Electron main thread in a nested libuv loop until the
+// child's stdio pipes close, which froze hotkeys, IPC and the dictation
+// window mid-recording (#2073).
function spawnAsync(cmd, args, { timeout = 3000 } = {}) {
return new Promise((resolve) => {
let child;
try {
child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
} catch (err) {
- resolve({ status: null, stdout: "", stderr: String(err?.message || err) });
+ resolve({ status: null, stdout: "", stderr: String(err?.message || err), timedOut: false });
return;
}
const chunks = { stdout: [], stderr: [] };
+ let bufferedBytes = 0;
+ const collect = (stream, chunk) => {
+ if (bufferedBytes >= MAX_OUTPUT_BYTES) return;
+ bufferedBytes += chunk.length;
+ chunks[stream].push(chunk);
+ };
let settled = false;
- const settle = (status) => {
+ const settle = (status, timedOut = false) => {
if (settled) return;
settled = true;
clearTimeout(timer);
@@ -26,21 +46,40 @@ function spawnAsync(cmd, args, { timeout = 3000 } = {}) {
status,
stdout: Buffer.concat(chunks.stdout).toString("utf8"),
stderr: Buffer.concat(chunks.stderr).toString("utf8"),
+ timedOut,
});
};
const timer = setTimeout(() => {
+ // A helper can finish its work and exit while a descendant it spawned
+ // keeps the inherited pipes open, so the deadline can arrive with the
+ // outcome already known. Honour that exit code: discarding it sends the
+ // Windows pause into the media-key fallback, which toggles playback back
+ // on mid-dictation and then leaves it paused afterwards (#2073).
+ const exitCode = child.exitCode;
try {
- child.kill("SIGKILL");
+ // A no-op once the child has exited; dropping our own pipe ends is
+ // what lets the deadline resolve while a descendant lingers.
+ killProcess(child, "SIGKILL");
+ child.stdout.destroy();
+ child.stderr.destroy();
+ debugLogger.warn(
+ "Media helper timed out",
+ { cmd: path.basename(cmd), timeout, exitCode },
+ "media"
+ );
} catch {
- // ignored
+ // Teardown and logging are best effort; the deadline must still settle
+ // below, or the serialized queue stalls for the rest of the session.
}
- settle(null);
+ settle(exitCode, exitCode === null);
}, timeout);
- child.stdout.on("data", (d) => chunks.stdout.push(d));
- child.stderr.on("data", (d) => chunks.stderr.push(d));
+ child.stdout.on("data", (d) => collect("stdout", d));
+ child.stderr.on("data", (d) => collect("stderr", d));
child.on("error", (err) => {
+ // Pushed past the cap on purpose: this is the only diagnostic a failed
+ // spawn produces, and it must not be the thing the cap drops.
chunks.stderr.push(Buffer.from(String(err?.message || err)));
settle(null);
});
@@ -62,6 +101,20 @@ class MediaPlayer {
this._adapterChecked = false;
this._adapterPaths = null; // { perl, script, framework } once resolved
this._pausedViaAdapter = false; // macOS: whether we paused via the adapter
+ // Pause/resume/toggle run one at a time. macOS was already async and had
+ // the race this prevents: a quick tap could run the resume before the
+ // pause had recorded what it paused, stranding media until the next
+ // dictation ended. Windows and Linux inherited the risk by becoming async
+ // too (#2073).
+ this._queue = Promise.resolve();
+ }
+
+ // The queue holds a caught copy so a failed operation can't stall the ones
+ // behind it, while the caller still gets the raw run.
+ _serialize(operation) {
+ const run = this._queue.then(operation);
+ this._queue = run.catch(() => {});
+ return run;
}
_resolveLinuxFastPaste() {
@@ -184,62 +237,65 @@ class MediaPlayer {
return this._adapterPaths;
}
- async pauseMedia() {
- try {
- if (process.platform === "linux") {
- return this._pauseLinux();
- } else if (process.platform === "darwin") {
- return await this._pauseMacOS();
- } else if (process.platform === "win32") {
- return this._pauseWindows();
+ pauseMedia() {
+ return this._serialize(async () => {
+ try {
+ if (process.platform === "linux") {
+ return await this._pauseLinux();
+ } else if (process.platform === "darwin") {
+ return await this._pauseMacOS();
+ } else if (process.platform === "win32") {
+ return await this._pauseWindows();
+ }
+ } catch (err) {
+ debugLogger.warn("Media pause failed", { error: err.message }, "media");
}
- } catch (err) {
- debugLogger.warn("Media pause failed", { error: err.message }, "media");
- }
- return false;
+ return false;
+ });
}
- async resumeMedia() {
- try {
- if (process.platform === "linux") {
- return this._resumeLinux();
- } else if (process.platform === "darwin") {
- return await this._resumeMacOS();
- } else if (process.platform === "win32") {
- return this._resumeWindows();
+ resumeMedia() {
+ return this._serialize(async () => {
+ try {
+ if (process.platform === "linux") {
+ return await this._resumeLinux();
+ } else if (process.platform === "darwin") {
+ return await this._resumeMacOS();
+ } else if (process.platform === "win32") {
+ return await this._resumeWindows();
+ }
+ } catch (err) {
+ debugLogger.warn("Media resume failed", { error: err.message }, "media");
}
- } catch (err) {
- debugLogger.warn("Media resume failed", { error: err.message }, "media");
- }
- return false;
+ return false;
+ });
}
- async toggleMedia() {
- try {
- if (process.platform === "linux") {
- return this._toggleLinux();
- } else if (process.platform === "darwin") {
- return await this._toggleMacOS();
- } else if (process.platform === "win32") {
- return this._toggleWindows();
+ toggleMedia() {
+ return this._serialize(async () => {
+ try {
+ if (process.platform === "linux") {
+ return await this._toggleLinux();
+ } else if (process.platform === "darwin") {
+ return await this._toggleMacOS();
+ } else if (process.platform === "win32") {
+ return await this._toggleWindows();
+ }
+ } catch (err) {
+ debugLogger.warn("Media toggle failed", { error: err.message }, "media");
}
- } catch (err) {
- debugLogger.warn("Media toggle failed", { error: err.message }, "media");
- }
- return false;
+ return false;
+ });
}
// --- Linux: MPRIS-aware pause/resume ---
- _pauseLinux() {
+ async _pauseLinux() {
this._pausedPlayers = [];
- if (this._pauseMpris()) return true;
+ if (await this._pauseMpris()) return true;
// Fallback: playerctl pause (not play-pause)
- const result = spawnSync("playerctl", ["pause"], {
- stdio: "pipe",
- timeout: 3000,
- });
+ const result = await spawnAsync("playerctl", ["pause"], { timeout: 3000 });
if (result.status === 0) {
debugLogger.debug("Media paused via playerctl", {}, "media");
this._pausedPlayers = ["playerctl"];
@@ -249,16 +305,13 @@ class MediaPlayer {
return false;
}
- _resumeLinux() {
+ async _resumeLinux() {
if (this._pausedPlayers.length === 0) return false;
// If we used playerctl fallback
if (this._pausedPlayers.length === 1 && this._pausedPlayers[0] === "playerctl") {
this._pausedPlayers = [];
- const result = spawnSync("playerctl", ["play"], {
- stdio: "pipe",
- timeout: 3000,
- });
+ const result = await spawnAsync("playerctl", ["play"], { timeout: 3000 });
if (result.status === 0) {
debugLogger.debug("Media resumed via playerctl", {}, "media");
return true;
@@ -266,20 +319,20 @@ class MediaPlayer {
return false;
}
- const resumed = this._resumeMpris();
+ const resumed = await this._resumeMpris();
this._pausedPlayers = [];
return resumed;
}
- _pauseMpris() {
- const players = this._listMprisPlayers();
+ async _pauseMpris() {
+ const players = await this._listMprisPlayers();
if (!players || players.length === 0) return false;
for (const dest of players) {
- const status = this._getMprisPlaybackStatus(dest);
+ const status = await this._getMprisPlaybackStatus(dest);
if (status !== "Playing") continue;
- const result = spawnSync(
+ const result = await spawnAsync(
"dbus-send",
[
"--session",
@@ -288,7 +341,7 @@ class MediaPlayer {
"/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player.Pause",
],
- { stdio: "pipe", timeout: 2000 }
+ { timeout: 2000 }
);
if (result.status === 0) {
@@ -299,11 +352,11 @@ class MediaPlayer {
return this._pausedPlayers.length > 0;
}
- _resumeMpris() {
+ async _resumeMpris() {
let resumed = false;
for (const dest of this._pausedPlayers) {
if (dest === "playerctl") continue;
- const result = spawnSync(
+ const result = await spawnAsync(
"dbus-send",
[
"--session",
@@ -312,7 +365,7 @@ class MediaPlayer {
"/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player.Play",
],
- { stdio: "pipe", timeout: 2000 }
+ { timeout: 2000 }
);
if (result.status === 0) {
@@ -323,8 +376,8 @@ class MediaPlayer {
return resumed;
}
- _getMprisPlaybackStatus(dest) {
- const result = spawnSync(
+ async _getMprisPlaybackStatus(dest) {
+ const result = await spawnAsync(
"dbus-send",
[
"--session",
@@ -335,18 +388,17 @@ class MediaPlayer {
"string:org.mpris.MediaPlayer2.Player",
"string:PlaybackStatus",
],
- { stdio: "pipe", timeout: 2000 }
+ { timeout: 2000 }
);
if (result.status !== 0) return null;
- const output = result.stdout?.toString() || "";
- const match = output.match(/string "([A-Za-z]+)"/);
+ const match = result.stdout.match(/string "([A-Za-z]+)"/);
return match ? match[1] : null;
}
- _listMprisPlayers() {
- const listResult = spawnSync(
+ async _listMprisPlayers() {
+ const listResult = await spawnAsync(
"dbus-send",
[
"--session",
@@ -356,13 +408,12 @@ class MediaPlayer {
"/org/freedesktop/DBus",
"org.freedesktop.DBus.ListNames",
],
- { stdio: "pipe", timeout: 2000 }
+ { timeout: 2000 }
);
if (listResult.status !== 0) return [];
- const output = listResult.stdout?.toString() || "";
- const matches = output.match(/string "org\.mpris\.MediaPlayer2\.[A-Za-z0-9_.\-]+"/g);
+ const matches = listResult.stdout.match(/string "org\.mpris\.MediaPlayer2\.[A-Za-z0-9_.\-]+"/g);
if (!matches || matches.length === 0) return [];
return matches.map((m) => m.replace(/^string "/, "").replace(/"$/, ""));
@@ -370,25 +421,19 @@ class MediaPlayer {
// --- Linux toggle (legacy, used by toggleMedia) ---
- _toggleLinux() {
- if (this._toggleMpris()) return true;
+ async _toggleLinux() {
+ if (await this._toggleMpris()) return true;
const binary = this._resolveLinuxFastPaste();
if (binary) {
- const result = spawnSync(binary, ["--media-play-pause"], {
- stdio: "pipe",
- timeout: 3000,
- });
+ const result = await spawnAsync(binary, ["--media-play-pause"], { timeout: 3000 });
if (result.status === 0) {
debugLogger.debug("Media toggled via linux-fast-paste", {}, "media");
return true;
}
}
- const result = spawnSync("playerctl", ["play-pause"], {
- stdio: "pipe",
- timeout: 3000,
- });
+ const result = await spawnAsync("playerctl", ["play-pause"], { timeout: 3000 });
if (result.status === 0) {
debugLogger.debug("Media toggled via playerctl", {}, "media");
return true;
@@ -398,13 +443,13 @@ class MediaPlayer {
return false;
}
- _toggleMpris() {
- const players = this._listMprisPlayers();
+ async _toggleMpris() {
+ const players = await this._listMprisPlayers();
if (!players || players.length === 0) return false;
let toggled = false;
for (const dest of players) {
- const result = spawnSync(
+ const result = await spawnAsync(
"dbus-send",
[
"--session",
@@ -413,7 +458,7 @@ class MediaPlayer {
"/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2.Player.PlayPause",
],
- { stdio: "pipe", timeout: 2000 }
+ { timeout: 2000 }
);
if (result.status === 0) {
@@ -424,7 +469,7 @@ class MediaPlayer {
return toggled;
}
- // --- macOS: MediaRemote-aware pause/resume (async) ---
+ // --- macOS: MediaRemote-aware pause/resume ---
async _runAdapter(args, timeout = 3000) {
const paths = this._resolveMediaRemoteAdapter();
@@ -617,18 +662,14 @@ try {
}`.trim();
}
- _sendWindowsMediaKey() {
+ async _sendWindowsMediaKey() {
const nircmd = this._resolveNircmd();
if (nircmd) {
- const result = spawnSync(nircmd, ["sendkeypress", "0xB3"], {
- stdio: "pipe",
- timeout: 3000,
- windowsHide: true,
- });
+ const result = await spawnAsync(nircmd, ["sendkeypress", "0xB3"], { timeout: 3000 });
if (result.status === 0) return true;
}
- const result = spawnSync(
+ const result = await spawnAsync(
"powershell.exe",
[
"-NoProfile",
@@ -636,28 +677,24 @@ try {
"-Command",
"Add-Type -TypeDefinition 'using System.Runtime.InteropServices; public class KB { [DllImport(\"user32.dll\")] public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo); }'; [KB]::keybd_event(0xB3, 0, 1, 0); [KB]::keybd_event(0xB3, 0, 3, 0)",
],
- {
- stdio: "pipe",
- timeout: 5000,
- windowsHide: true,
- }
+ { timeout: 5000 }
);
return result.status === 0;
}
- _pauseWindows() {
+ async _pauseWindows() {
this._pausedWinApps = [];
this._didPause = false;
- // Use GSMTC (Windows 10 1809+) — state-aware, targets specific apps
- const result = spawnSync(
+ // GSMTC (Windows 10 1809+) — state-aware, targets specific apps
+ const result = await spawnAsync(
"powershell.exe",
["-NoProfile", "-NonInteractive", "-Command", this._gsmtcPauseScript()],
- { stdio: "pipe", timeout: 5000, windowsHide: true }
+ { timeout: 5000 }
);
if (result.status === 0) {
- const output = (result.stdout?.toString() || "").trim();
+ const output = result.stdout.trim();
if (output === "GSMTC_FAIL") {
debugLogger.debug("GSMTC unavailable, falling back to media key", {}, "media");
return this._pauseWindowsFallback();
@@ -671,12 +708,12 @@ try {
return false;
}
- const stderr = (result.stderr?.toString() || "").trim();
+ const stderr = result.stderr.trim();
debugLogger.debug(
"GSMTC PowerShell failed, falling back to media key",
{
status: result.status,
- signal: result.signal,
+ timedOut: result.timedOut,
stderr: stderr ? stderr.slice(0, 200) : undefined,
},
"media"
@@ -684,8 +721,8 @@ try {
return this._pauseWindowsFallback();
}
- _pauseWindowsFallback() {
- if (this._sendWindowsMediaKey()) {
+ async _pauseWindowsFallback() {
+ if (await this._sendWindowsMediaKey()) {
this._didPause = true;
debugLogger.debug("Media paused via media key fallback", {}, "media");
return true;
@@ -693,16 +730,16 @@ try {
return false;
}
- _resumeWindows() {
+ async _resumeWindows() {
// Resume via GSMTC if we paused that way
if (this._pausedWinApps && this._pausedWinApps.length > 0) {
const apps = this._pausedWinApps;
this._pausedWinApps = [];
- const result = spawnSync(
+ const result = await spawnAsync(
"powershell.exe",
["-NoProfile", "-NonInteractive", "-Command", this._gsmtcResumeScript(apps)],
- { stdio: "pipe", timeout: 5000, windowsHide: true }
+ { timeout: 5000 }
);
if (result.status === 0) {
@@ -718,7 +755,7 @@ try {
// Resume via media key toggle if we paused with the fallback
if (this._didPause) {
this._didPause = false;
- if (this._sendWindowsMediaKey()) {
+ if (await this._sendWindowsMediaKey()) {
debugLogger.debug("Media resumed via media key fallback", {}, "media");
return true;
}
@@ -727,8 +764,8 @@ try {
return false;
}
- _toggleWindows() {
- if (this._sendWindowsMediaKey()) {
+ async _toggleWindows() {
+ if (await this._sendWindowsMediaKey()) {
debugLogger.debug("Media toggled via Windows media key", {}, "media");
return true;
}
diff --git a/test/helpers/mediaPlayer.test.js b/test/helpers/mediaPlayer.test.js
new file mode 100644
index 000000000..69aa8c62f
--- /dev/null
+++ b/test/helpers/mediaPlayer.test.js
@@ -0,0 +1,527 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+const { EventEmitter } = require("node:events");
+const path = require("node:path");
+const childProcess = require("node:child_process");
+const fs = require("node:fs");
+
+const modulePath = require.resolve("../../src/helpers/mediaPlayer");
+// mediaPlayer kills timed-out helpers through this shared utility, which
+// spawns taskkill on Windows — so it has to re-bind to each test's stub too.
+const processUtilPath = require.resolve("../../src/utils/process");
+const originalLoad = Module._load;
+const originalPlatform = process.platform;
+
+function setPlatform(platform) {
+ Object.defineProperty(process, "platform", { value: platform, configurable: true });
+}
+test.afterEach(() => {
+ setPlatform(originalPlatform);
+ Module._load = originalLoad;
+});
+
+// A child whose pipes only close when the test says so, so a helper that never
+// finishes can be observed the way the reporter's stuck PowerShell behaved.
+// Records what the timeout branch does to it (kill / destroy).
+function createFakeChild() {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.stdoutDestroyed = false;
+ child.stderrDestroyed = false;
+ child.stdout.destroy = () => {
+ child.stdoutDestroyed = true;
+ };
+ child.stderr.destroy = () => {
+ child.stderrDestroyed = true;
+ };
+ // killProcess skips a child that has already exited, and needs a pid to
+ // hand to taskkill.
+ child.exitCode = null;
+ child.pid = 4242;
+ child.killSignals = [];
+ child.kill = (signal) => {
+ child.killSignals.push(signal);
+ return true;
+ };
+ // child_process delivers "error" and then "close" when the executable is
+ // missing; spawnAsync must treat that like a failure rather than hang.
+ child.fail = (err) => {
+ child.emit("error", err);
+ child.emit("close", -2);
+ };
+ child.finish = (status, stdout = "", stderr = "") => {
+ if (stdout) child.stdout.emit("data", Buffer.from(stdout));
+ if (stderr) child.stderr.emit("data", Buffer.from(stderr));
+ child.emit("close", status);
+ };
+ // A helper that printed its result and exited, but whose pipes a descendant
+ // still holds open. Node sets exitCode at "exit"; "close" is what's stuck,
+ // so the deadline fires with the outcome already known.
+ child.exitLeavingPipesOpen = (status, stdout = "") => {
+ if (stdout) child.stdout.emit("data", Buffer.from(stdout));
+ child.exitCode = status;
+ child.emit("exit", status, null);
+ };
+ return child;
+}
+
+// Loads a fresh MediaPlayer singleton for `platform`. Every synchronous
+// child_process entry point throws, so a regression back to a blocking call
+// fails every test in this file (#2073). The stub stays installed for the whole
+// test rather than just the initial require, so a call added inside a function
+// is caught too, and it only answers requires made by the two modules under
+// test, so node:test's own requires are untouched.
+function loadMediaPlayer(platform, { existingPaths = () => false, warnThrows = false } = {}) {
+ delete require.cache[modulePath];
+ delete require.cache[processUtilPath];
+ setPlatform(platform);
+ const calls = [];
+ const logs = [];
+ const spawn = (cmd, args, options) => {
+ const child = createFakeChild();
+ calls.push({ cmd: path.basename(cmd), args, options, child });
+ return child;
+ };
+ const syncSpawn = () => {
+ throw new Error(
+ "no synchronous child-process call may run on the media pause/resume path (#2073)"
+ );
+ };
+ const mockedRequesters = new Set([modulePath, processUtilPath]);
+ Module._load = function loadWithMocks(request, parent, isMain) {
+ if (!mockedRequesters.has(parent?.filename)) {
+ return originalLoad.call(this, request, parent, isMain);
+ }
+ // A "node:"-prefixed require reaches the same builtin, so it must not be
+ // the way a blocking call slips past the stub.
+ const builtin = request.startsWith("node:") ? request.slice(5) : request;
+ if (request === "./debugLogger") {
+ // The real logger requires electron at load time.
+ return {
+ debug: (message, meta) => logs.push({ level: "debug", message, meta }),
+ info() {},
+ warn: (message, meta) => {
+ logs.push({ level: "warn", message, meta });
+ // debugLogger.write ends in an unguarded logStream.write, so a
+ // broken sink throws straight back into the caller.
+ if (warnThrows) throw new Error("log stream is broken");
+ },
+ error() {},
+ };
+ }
+ if (builtin === "child_process") {
+ return {
+ ...childProcess,
+ spawn,
+ spawnSync: syncSpawn,
+ execSync: syncSpawn,
+ execFileSync: syncSpawn,
+ };
+ }
+ if (builtin === "fs") {
+ // Binary resolution hits the real filesystem; pin it so the host's
+ // downloaded binaries can't change which fallback runs. Only existsSync
+ // is stubbed, which covers nircmd and the macOS mediaremote adapter;
+ // resolvers that also call accessSync (linux-fast-paste,
+ // macos-media-remote) still see the real filesystem and resolve null.
+ return { ...fs, existsSync: (p) => existingPaths(String(p)) };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+ };
+ return { mediaPlayer: require(modulePath), calls, logs };
+}
+
+// Lets any pending continuation run, for assertions that something did *not*
+// happen and so have no call to wait for.
+async function drain() {
+ for (let i = 0; i < 10; i += 1) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+}
+
+// Awaits until the module has spawned call #index. The chain between one
+// child's close and the next spawn is microtask-only, so a single immediate
+// suffices; the bound is just a guard against a hang.
+async function waitForCall(calls, index) {
+ for (let i = 0; i < 50 && calls.length <= index; i += 1) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ assert.ok(calls.length > index, `expected spawn call #${index + 1}, saw ${calls.length}`);
+ return calls[index];
+}
+
+const WIN_STDIO = ["ignore", "pipe", "pipe"];
+
+test("win32: GSMTC pause runs through async spawn and records the apps it paused", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("win32");
+
+ const pausing = mediaPlayer.pauseMedia();
+ const gsmtc = await waitForCall(calls, 0);
+
+ assert.equal(gsmtc.cmd, "powershell.exe");
+ assert.deepEqual(gsmtc.args.slice(0, 3), ["-NoProfile", "-NonInteractive", "-Command"]);
+ assert.match(gsmtc.args[3], /TryPauseAsync/);
+ assert.deepEqual(gsmtc.options.stdio, WIN_STDIO);
+ assert.equal(gsmtc.options.windowsHide, true);
+
+ gsmtc.child.finish(0, "Spotify.exe|Chrome.exe\n");
+ assert.equal(await pausing, true);
+ assert.equal(calls.length, 1);
+ assert.deepEqual(mediaPlayer._pausedWinApps, ["Spotify.exe", "Chrome.exe"]);
+});
+
+test("win32: GSMTC_FAIL falls back to the PowerShell media key when nircmd is absent", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("win32");
+
+ const pausing = mediaPlayer.pauseMedia();
+ (await waitForCall(calls, 0)).child.finish(0, "GSMTC_FAIL\n");
+
+ const fallback = await waitForCall(calls, 1);
+ assert.equal(fallback.cmd, "powershell.exe");
+ assert.match(fallback.args[3], /keybd_event/);
+ assert.deepEqual(fallback.options.stdio, WIN_STDIO);
+ fallback.child.finish(0);
+
+ assert.equal(await pausing, true);
+ assert.equal(mediaPlayer._didPause, true);
+ assert.deepEqual(mediaPlayer._pausedWinApps, []);
+});
+
+test("win32: bundled nircmd is tried before the PowerShell media key", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("win32", {
+ existingPaths: (p) => /nircmd\.exe$/.test(p),
+ });
+
+ const pausing = mediaPlayer.pauseMedia();
+ (await waitForCall(calls, 0)).child.finish(1, "", "boom");
+
+ const nircmd = await waitForCall(calls, 1);
+ assert.equal(nircmd.cmd, "nircmd.exe");
+ assert.deepEqual(nircmd.args, ["sendkeypress", "0xB3"]);
+ nircmd.child.finish(0);
+
+ assert.equal(await pausing, true);
+ assert.equal(calls.length, 2);
+});
+
+test("win32: a PowerShell that cannot be spawned at all falls through to the media key", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("win32");
+
+ const pausing = mediaPlayer.pauseMedia();
+ const enoent = new Error("spawn powershell.exe ENOENT");
+ enoent.code = "ENOENT";
+ (await waitForCall(calls, 0)).child.fail(enoent);
+
+ // The media-key fallback comes from the same missing PATH, so it fails too
+ // and pauseMedia reports honestly instead of throwing.
+ (await waitForCall(calls, 1)).child.fail(enoent);
+
+ assert.equal(await pausing, false);
+ assert.equal(mediaPlayer._didPause, false);
+});
+
+test("win32: a PowerShell that never closes its pipes is killed at the deadline and the pause falls through to the media key", async (t) => {
+ // Only setTimeout is mocked: waitForCall drives progress with setImmediate,
+ // which a bare enable() would also mock, stalling every helper below.
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const { mediaPlayer, calls, logs } = loadMediaPlayer("win32");
+
+ const pausing = mediaPlayer.pauseMedia();
+ await waitForCall(calls, 0);
+
+ t.mock.timers.tick(4999);
+ assert.equal(calls.length, 1, "nothing is killed before the deadline");
+ t.mock.timers.tick(1);
+
+ // taskkill /t, not child.kill: on Windows that takes down descendants the
+ // helper spawned, which a bare kill would orphan. It only fires while the
+ // child is still live — killProcess skips one that has already exited.
+ const taskkill = await waitForCall(calls, 1);
+ assert.equal(taskkill.cmd, "taskkill");
+ assert.deepEqual(taskkill.args, ["/pid", "4242", "/f", "/t"]);
+ assert.ok(
+ logs.some((entry) => entry.level === "warn" && entry.message.includes("timed out")),
+ "a timed-out helper is reported above debug level"
+ );
+
+ const fallback = await waitForCall(calls, 2);
+ assert.match(fallback.args[3], /keybd_event/);
+ fallback.child.finish(0);
+ assert.equal(await pausing, true);
+
+ // The GSMTC failure is logged as a timeout rather than a plain non-zero exit.
+ const failure = logs.find((entry) => entry.message.includes("GSMTC PowerShell failed"));
+ assert.equal(failure.meta.timedOut, true);
+});
+
+test("win32: resume without a prior pause spawns nothing", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("win32");
+ assert.equal(await mediaPlayer.resumeMedia(), false);
+ assert.equal(calls.length, 0);
+});
+
+test("win32: resume after a media-key pause toggles the media key again", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("win32");
+
+ const pausing = mediaPlayer.pauseMedia();
+ (await waitForCall(calls, 0)).child.finish(0, "GSMTC_FAIL\n");
+ (await waitForCall(calls, 1)).child.finish(0); // keybd_event pause
+ assert.equal(await pausing, true);
+
+ const resuming = mediaPlayer.resumeMedia();
+ const key = await waitForCall(calls, 2);
+ assert.match(key.args[3], /keybd_event/);
+ key.child.finish(0);
+ assert.equal(await resuming, true);
+ assert.equal(mediaPlayer._didPause, false);
+});
+
+// Dropping our own read ends is what actually lets the deadline resolve: a
+// descendant holding the helper's inherited pipes keeps "close" from firing, so
+// without the destroy we leak a stuck pair per timed-out dictation. Only the
+// media-key path spawns such a descendant, through Add-Type -TypeDefinition and
+// its csc.exe; the GSMTC scripts use Add-Type -AssemblyName and spawn nothing.
+test("win32: a timed-out helper has its stdio destroyed so stuck pipes don't accumulate", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const { mediaPlayer, calls } = loadMediaPlayer("win32");
+
+ const pausing = mediaPlayer.pauseMedia();
+ const gsmtc = await waitForCall(calls, 0);
+ t.mock.timers.tick(5000);
+
+ assert.equal(gsmtc.child.stdoutDestroyed, true);
+ assert.equal(gsmtc.child.stderrDestroyed, true);
+
+ // A late close after the deadline must not double-settle or re-run anything.
+ // calls: [gsmtc, taskkill, media-key fallback]
+ const fallback = await waitForCall(calls, 2);
+ gsmtc.child.finish(0, "Spotify.exe\n");
+ fallback.child.finish(0);
+
+ assert.equal(await pausing, true);
+ assert.equal(calls.length, 3);
+ assert.deepEqual(mediaPlayer._pausedWinApps, []);
+});
+
+// The deadline can arrive after the helper has already done its job and
+// exited, with only its pipes held open by a descendant — the shape behind
+// #2073. Its exit code and the output we buffered are the real result;
+// discarding them sends the pause into the media-key fallback, which toggles
+// playback back ON mid-dictation and then leaves it paused afterwards.
+test("win32: a GSMTC run that exited before the deadline is honoured, not reported as a timeout", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const { mediaPlayer, calls } = loadMediaPlayer("win32");
+
+ const pausing = mediaPlayer.pauseMedia();
+ const gsmtc = await waitForCall(calls, 0);
+ gsmtc.child.exitLeavingPipesOpen(0, "Spotify.exe\n");
+
+ t.mock.timers.tick(5000);
+ await drain();
+
+ // Asserted before awaiting the pause: a fallback spawn means the pause is
+ // waiting on a media key this test never finishes, which would hang here.
+ assert.equal(calls.length, 1, "no media-key toggle: GSMTC had already paused it");
+ assert.equal(await pausing, true);
+ assert.deepEqual(mediaPlayer._pausedWinApps, ["Spotify.exe"]);
+});
+
+// spawnSync capped output at 1 MB and killed anything past it. Without a
+// replacement cap a runaway helper buffers in the main process until its
+// deadline, and a large enough payload makes the settle path throw after it
+// has marked itself settled — stalling the serialized queue for good.
+test("win32: a helper that floods stdout has its output capped", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("win32");
+
+ const pausing = mediaPlayer.pauseMedia();
+ const gsmtc = await waitForCall(calls, 0);
+ const chunk = "A".repeat(512 * 1024);
+ for (let i = 0; i < 4; i += 1) gsmtc.child.stdout.emit("data", Buffer.from(chunk));
+ gsmtc.child.finish(0);
+
+ assert.equal(await pausing, true);
+ const buffered = mediaPlayer._pausedWinApps.join("").length;
+ assert.ok(buffered > 0, "output up to the cap is still delivered");
+ assert.ok(
+ buffered <= 1024 * 1024 + chunk.length,
+ `stdout should be capped, buffered ${buffered} bytes of the 2 MB emitted`
+ );
+});
+
+// Teardown and logging at the deadline are best effort, but the deadline must
+// still settle: an unsettled promise sits at the head of the serial queue and
+// kills every later pause and resume for the rest of the session.
+test("win32: a logger that throws at the deadline still settles and leaves the queue usable", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const { mediaPlayer, calls } = loadMediaPlayer("win32", { warnThrows: true });
+
+ const pausing = mediaPlayer.pauseMedia();
+ await waitForCall(calls, 0);
+ t.mock.timers.tick(5000);
+
+ // calls: [gsmtc, taskkill, media-key fallback]
+ (await waitForCall(calls, 2)).child.finish(0);
+ assert.equal(await pausing, true);
+
+ const resuming = mediaPlayer.resumeMedia();
+ (await waitForCall(calls, 3)).child.finish(0);
+ assert.equal(await resuming, true);
+});
+
+// A quick tap stops the recording before the pause has decided which apps it
+// paused. With synchronous spawns that ordering was free; with async ones the
+// resume must queue behind the pause or media is left paused (#2073).
+test("win32: resume waits for an in-flight pause and resumes exactly the apps it paused", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("win32");
+
+ const pausing = mediaPlayer.pauseMedia();
+ const resuming = mediaPlayer.resumeMedia();
+
+ const gsmtcPause = await waitForCall(calls, 0);
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(calls.length, 1, "resume must not spawn until the pause has settled");
+
+ gsmtcPause.child.finish(0, "Spotify.exe\n");
+ assert.equal(await pausing, true);
+
+ const gsmtcResume = await waitForCall(calls, 1);
+ assert.equal(gsmtcResume.cmd, "powershell.exe");
+ assert.match(gsmtcResume.args[3], /TryPlayAsync/);
+ assert.match(gsmtcResume.args[3], /'Spotify\.exe'/);
+ assert.deepEqual(gsmtcResume.options.stdio, WIN_STDIO);
+ gsmtcResume.child.finish(0, "OK\n");
+
+ assert.equal(await resuming, true);
+ assert.deepEqual(mediaPlayer._pausedWinApps, []);
+});
+
+test("win32: toggle sends the media key asynchronously", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("win32");
+ const toggling = mediaPlayer.toggleMedia();
+ const key = await waitForCall(calls, 0);
+ assert.match(key.args[3], /keybd_event/);
+ key.child.finish(0);
+ assert.equal(await toggling, true);
+});
+
+// macOS never blocked the main thread, but it was already async and therefore
+// already raced: _pauseMacOS only sets _didPause after two perl spawns, so a
+// resume arriving in that window saw _didPause false, returned early, and left
+// media paused until the next dictation ended.
+const MAC_ADAPTER_PATHS = (p) =>
+ p === "/usr/bin/perl" ||
+ p.endsWith("mediaremote-adapter.pl") ||
+ p.endsWith("MediaRemoteAdapter.framework");
+
+test("darwin: resume waits for an in-flight pause instead of no-oping on _didPause", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("darwin", { existingPaths: MAC_ADAPTER_PATHS });
+
+ const pausing = mediaPlayer.pauseMedia();
+ const resuming = mediaPlayer.resumeMedia();
+
+ const probe = await waitForCall(calls, 0);
+ assert.equal(probe.cmd, "perl");
+ assert.deepEqual(probe.args.slice(-2), ["get", "--no-artwork"]);
+ probe.child.finish(0, '{"playing":true}');
+
+ const pause = await waitForCall(calls, 1);
+ assert.deepEqual(pause.args.slice(-2), ["send", "1"]); // kMRAPause
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(calls.length, 2, "resume must not spawn until the pause has settled");
+ pause.child.finish(0);
+
+ assert.equal(await pausing, true);
+
+ const play = await waitForCall(calls, 2);
+ assert.deepEqual(play.args.slice(-2), ["send", "0"]); // kMRAPlay
+ play.child.finish(0);
+
+ assert.equal(await resuming, true);
+ assert.equal(mediaPlayer._didPause, false);
+});
+
+// Linux has the same hazard: dbus-send and playerctl ran through spawnSync on
+// the same main thread (#2073).
+test("linux: pauses only Playing MPRIS players and resumes exactly those", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("linux");
+
+ const pausing = mediaPlayer.pauseMedia();
+
+ const list = await waitForCall(calls, 0);
+ assert.equal(list.cmd, "dbus-send");
+ assert.ok(list.args.includes("org.freedesktop.DBus.ListNames"));
+ list.child.finish(
+ 0,
+ 'string "org.mpris.MediaPlayer2.spotify"\nstring "org.mpris.MediaPlayer2.vlc"\n'
+ );
+
+ const spotifyStatus = await waitForCall(calls, 1);
+ assert.ok(spotifyStatus.args.includes("--dest=org.mpris.MediaPlayer2.spotify"));
+ assert.ok(spotifyStatus.args.includes("string:PlaybackStatus"));
+ spotifyStatus.child.finish(0, 'variant string "Playing"\n');
+
+ const spotifyPause = await waitForCall(calls, 2);
+ assert.ok(spotifyPause.args.includes("org.mpris.MediaPlayer2.Player.Pause"));
+ spotifyPause.child.finish(0);
+
+ const vlcStatus = await waitForCall(calls, 3);
+ assert.ok(vlcStatus.args.includes("--dest=org.mpris.MediaPlayer2.vlc"));
+ vlcStatus.child.finish(0, 'variant string "Paused"\n');
+
+ assert.equal(await pausing, true);
+ assert.equal(calls.length, 4);
+ assert.deepEqual(mediaPlayer._pausedPlayers, ["org.mpris.MediaPlayer2.spotify"]);
+
+ const resuming = mediaPlayer.resumeMedia();
+ const play = await waitForCall(calls, 4);
+ assert.ok(play.args.includes("--dest=org.mpris.MediaPlayer2.spotify"));
+ assert.ok(play.args.includes("org.mpris.MediaPlayer2.Player.Play"));
+ play.child.finish(0);
+
+ assert.equal(await resuming, true);
+ assert.equal(calls.length, 5);
+ assert.deepEqual(mediaPlayer._pausedPlayers, []);
+});
+
+test("linux: falls back to playerctl when no MPRIS player is available", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("linux");
+
+ const pausing = mediaPlayer.pauseMedia();
+ (await waitForCall(calls, 0)).child.finish(1); // ListNames failed → no players
+
+ const playerctl = await waitForCall(calls, 1);
+ assert.equal(playerctl.cmd, "playerctl");
+ assert.deepEqual(playerctl.args, ["pause"]);
+ playerctl.child.finish(0);
+
+ assert.equal(await pausing, true);
+ assert.deepEqual(mediaPlayer._pausedPlayers, ["playerctl"]);
+
+ const resuming = mediaPlayer.resumeMedia();
+ const play = await waitForCall(calls, 2);
+ assert.equal(play.cmd, "playerctl");
+ assert.deepEqual(play.args, ["play"]);
+ play.child.finish(0);
+ assert.equal(await resuming, true);
+});
+
+test("linux: toggle uses MPRIS PlayPause for every player, else playerctl play-pause", async () => {
+ const { mediaPlayer, calls } = loadMediaPlayer("linux");
+
+ const toggling = mediaPlayer.toggleMedia();
+ (await waitForCall(calls, 0)).child.finish(0, 'string "org.mpris.MediaPlayer2.vlc"\n');
+ const playPause = await waitForCall(calls, 1);
+ assert.ok(playPause.args.includes("org.mpris.MediaPlayer2.Player.PlayPause"));
+ playPause.child.finish(0);
+ assert.equal(await toggling, true);
+
+ const togglingAgain = mediaPlayer.toggleMedia();
+ (await waitForCall(calls, 2)).child.finish(1); // no MPRIS players this time
+ const playerctl = await waitForCall(calls, 3);
+ assert.equal(playerctl.cmd, "playerctl");
+ assert.deepEqual(playerctl.args, ["play-pause"]);
+ playerctl.child.finish(0);
+ assert.equal(await togglingAgain, true);
+});