Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(stt): make the macOS whisper helper actually shippable, and report its real device

Etienne Lescotcc781806accf
diff --git a/electron/native/whisper-stt/src/main.cpp b/electron/native/whisper-stt/src/main.cpp
index 1cc067697..339f759b1 100644
--- a/electron/native/whisper-stt/src/main.cpp
+++ b/electron/native/whisper-stt/src/main.cpp
@@ -175,14 +175,30 @@ std::string detect_active_backend() {
for (size_t i = 0; i < n; ++i) {
ggml_backend_dev_t dev = ggml_backend_dev_get(i);
if (!dev) continue;
+ // Only compute devices are candidates. This drops ggml-cpu (type CPU)
+ // and ggml-blas (type ACCEL — Accelerate on macOS), neither of which is
+ // the GPU offload this field is meant to report. IGPU is accepted
+ // because that is how an integrated adapter enumerates.
+ // `auto`: ggml_backend_dev_type names both a C enum and the accessor
+ // function, so spelling the type out needs the `enum` tag to disambiguate.
+ const auto type = ggml_backend_dev_type(dev);
+ if (type != GGML_BACKEND_DEVICE_TYPE_GPU && type != GGML_BACKEND_DEVICE_TYPE_IGPU) {
+ continue;
+ }
const char* name = ggml_backend_dev_name(dev);
if (!name) continue;
std::string s = name;
- // ggml-cpu shows up as "CPU" — skip it on the first pass, only return
- // it as a last resort.
- if (s == "CPU" || s == "cpu") continue;
+ // These are ggml *device* names, which carry a device index:
+ // "Vulkan0", "CUDA0", "MTL0". Matching the bare backend title is why
+ // Metal never matched — ggml-metal's device name is built from
+ // GGML_METAL_NAME ("MTL"), and the string "Metal" appears nowhere in
+ // it, so every Apple Silicon run reported `whispercpp-cpu` while the
+ // Metal backend was in fact bound. `backend` is documented as the
+ // source of truth for which device ran, so this was the one number a
+ // consumer could not get right on macOS.
if (s.find("Vulkan") != std::string::npos) return "whispercpp-vulkan";
if (s.find("CUDA") != std::string::npos) return "whispercpp-cuda";
+ if (s.find("MTL") != std::string::npos) return "whispercpp-metal";
if (s.find("Metal") != std::string::npos) return "whispercpp-metal";
}
// Last resort: the CPU device, or a hard "cpu" if ggml has nothing
@@ -464,9 +480,26 @@ int main(int argc, char** argv) {
}
// ---- Emit verbose_json (CT2-compatible shape + backend + timing) ----
+ //
+ // Report the language whisper actually decoded with, not the one the
+ // request asked for. `language` is the raw request parameter, and the
+ // renderer sends "auto" on every call (there is no language selector in
+ // the UI yet), so echoing it back meant `detected_language` never
+ // carried a language at all: the media stage's "detected language" line
+ // rendered the literal string "auto", and AxcutTranscript.language was
+ // set to it via transcribe.ts. whisper_full_lang_id() returns the id
+ // whisper resolved — the detected one under "auto", and the forced one
+ // otherwise, which is correct for both paths.
+ std::string resolved_language = language;
+ const int lang_id = whisper_full_lang_id(ctx);
+ if (lang_id >= 0) {
+ if (const char* lang_str = whisper_lang_str(lang_id)) {
+ resolved_language = lang_str;
+ }
+ }
nlohmann::json reply;
- reply["language"] = language;
- reply["detected_language"] = language;
+ reply["language"] = resolved_language;
+ reply["detected_language"] = resolved_language;
reply["backend"] = active_backend;
reply["timing"] = {
{"elapsed_s", elapsed_s},
diff --git a/package.json b/package.json
index 4bb0f3d65..4646e9184 100644
--- a/package.json
+++ b/package.json
@@ -36,6 +36,7 @@
"build:win:store": "npm run build:native:win && npm run fetch:ffmpeg && npm run build:native:compositor && tsc && vite build && electron-builder --win appx --config.npmRebuild=false",
"build:linux": "tsc && vite build && electron-builder --linux AppImage deb pacman --config.npmRebuild=false",
"build:whisper-binaries": "bash scripts/build-whisper-stt.sh",
+ "test:whisper-stt": "node scripts/test-whisper-stt.mjs",
"test": "vitest --run",
"test:watch": "vitest",
"test:cursor-native:win": "node scripts/test-windows-native-cursor.mjs",
diff --git a/scripts/build-whisper-stt.sh b/scripts/build-whisper-stt.sh
index 2e8ec5ffe..16d6a4f7e 100644
--- a/scripts/build-whisper-stt.sh
+++ b/scripts/build-whisper-stt.sh
@@ -87,6 +87,59 @@ backend_flag_for_host() {
esac
}
+# ---------------------------------------------------------------------------
+# macOS: make the staged tree relocatable.
+#
+# CMake links the helper and every ggml/whisper dylib against `@rpath/...` and
+# then bakes a single absolute LC_RPATH pointing at its own build tree
+# (`.cache/whisper-stt-build/build-<tag>-<variant>/bin`). That resolves on the
+# machine that ran the build and nowhere else: delete the build cache, or
+# download the CI artifact onto a different runner, and dyld cannot find
+# libwhisper at all — the process aborts (SIGABRT, exit 134) before main().
+#
+# This is the macOS twin of the Windows 0xC0000135 incident that shipped in
+# 1.8.0-rc.1..rc.3 (see the OpenSSL note in the CMakeLists). Swapping the
+# absolute rpath for `@loader_path` makes each binary look for its siblings
+# next to itself, which is exactly how the staged directory and the packaged
+# `resources/electron/native/bin/<tag>/` are laid out.
+#
+# Editing a Mach-O header invalidates its code signature, and arm64 refuses to
+# execute an unsigned-but-modified image ("killed: 9"), so each patched file is
+# re-signed ad-hoc afterwards.
+# ---------------------------------------------------------------------------
+relocate_macos_rpaths() {
+ local out_dir="$1"
+
+ local f rp
+ for f in "${out_dir}"/*; do
+ # Symlinks share the payload of their target; patching the target is
+ # enough, and codesign would follow the link and sign it twice.
+ [[ -L "${f}" ]] && continue
+ [[ -f "${f}" ]] || continue
+ # Mach-O only: skips *.metal shader sidecars and anything else non-binary.
+ file -b "${f}" | grep -q "Mach-O" || continue
+
+ # Drop every *absolute* LC_RPATH. An absolute rpath in a shipped artifact
+ # is always a build-machine path; relative ones (@loader_path,
+ # @executable_path) are already correct and must survive.
+ while read -r rp; do
+ [[ "${rp}" == /* ]] || continue
+ install_name_tool -delete_rpath "${rp}" "${f}" 2>/dev/null || true
+ done < <(otool -l "${f}" | awk '/cmd LC_RPATH/{n=1;next} n&&/^ *path /{print $2;n=0}')
+
+ # Idempotent: a second run would otherwise stack duplicate rpaths.
+ if ! otool -l "${f}" | awk '/cmd LC_RPATH/{n=1;next} n&&/^ *path /{print $2;n=0}' |
+ grep -qx "@loader_path"; then
+ install_name_tool -add_rpath "@loader_path" "${f}"
+ fi
+
+ codesign --force --sign - --timestamp=none "${f}" 2>/dev/null ||
+ echo "[whisper-stt] WARN: could not re-sign ${f##*/}" >&2
+ done
+
+ echo "[whisper-stt] rewrote macOS rpaths to @loader_path in ${out_dir}"
+}
+
build_variant() {
local variant_name="$1"
shift
@@ -109,7 +162,10 @@ build_variant() {
${extra_cmake_flags[@]+"${extra_cmake_flags[@]}"}
echo "[whisper-stt] building ${variant_name}"
- cmake --build "${build_dir}" --config Release -j "$(nproc 2>/dev/null || echo 4)"
+ # ponytail: macOS has no `nproc` (it is GNU coreutils), so this silently built
+ # with -j4 on an 8-core Mac. `sysctl -n hw.ncpu` is the BSD equivalent.
+ cmake --build "${build_dir}" --config Release \
+ -j "$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)"
local bin_name="whisper-stt-server"
if [[ "${OS_ARCH}" == win32-* ]]; then
@@ -152,14 +208,36 @@ build_variant() {
# Stage any shared libraries / backend sidecars that CMake produced.
# Copy everything that looks like a ggml/whisper shared library, plus any
# .metal shader files (only produced when Metal is not embedded).
+ #
+ # ponytail: the pattern list used to be `ggml*.*|whisper.*|libwhisper.*`,
+ # which only ever matched on Windows. CMake names shared libraries
+ # `ggml-base.dll` on Windows but `libggml-base.dylib` / `libggml-base.so.0`
+ # everywhere else, so on macOS and Linux every ggml sidecar was skipped and
+ # only libwhisper was staged — leaving a helper that cannot resolve
+ # @rpath/libggml.0.dylib and dies in dyld before main(). The `lib` prefix and
+ # the `.so.<N>` version suffixes are what the globs below add.
+ #
+ # -a preserves the symlink farm (libggml.dylib -> libggml.0.dylib ->
+ # libggml.0.15.1.dylib); plain `cp` dereferences each one into a full copy of
+ # the same payload, which tripled the staged size for no benefit.
local found_libs=0
for lib_dir in "${search_dirs[@]}"; do
if [[ -d "${lib_dir}" ]]; then
for f in "${lib_dir}"/*; do
- if [[ -f "${f}" ]]; then
+ # -f follows symlinks (true for both link and target); -L catches the
+ # links themselves so the farm is staged intact.
+ if [[ -f "${f}" || -L "${f}" ]]; then
+ # Patterns, in order: Windows DLLs; macOS dylibs; Linux .so plus its
+ # versioned forms (libggml-base.so.0, libggml-base.so.0.15.1); Metal
+ # shader sidecars. A comment cannot be placed inside a `case` pattern
+ # list — a `| \` continuation would swallow it as part of the pattern.
case "${f##*/}" in
- ggml*.*|whisper.*|whisper.dylib|whisper.dll|libwhisper.*|*.metal)
- cp "${f}" "${OUT_DIR}/"
+ ggml*.dll|whisper.dll|parakeet.dll|\
+libggml*.dylib|libwhisper*.dylib|libparakeet*.dylib|\
+libggml*.so|libggml*.so.*|libwhisper*.so|libwhisper*.so.*|\
+libparakeet*.so|libparakeet*.so.*|\
+*.metal)
+ cp -a "${f}" "${OUT_DIR}/"
found_libs=1
;;
esac
@@ -168,6 +246,21 @@ build_variant() {
fi
done
+ # Fail here rather than in the installer. `found_libs` was computed and then
+ # never read, so a staging glob that matched nothing — which is precisely what
+ # happened on macOS and Linux — still exited 0 and produced a green build.
+ if [[ "${found_libs}" -eq 0 ]]; then
+ echo "FATAL: staged no shared libraries alongside ${out_bin_name}." >&2
+ echo " Searched: ${search_dirs[*]}" >&2
+ echo " The helper links ggml/whisper as shared libraries; without them" >&2
+ echo " it cannot start. Check the sidecar glob in this script." >&2
+ exit 1
+ fi
+
+ if [[ "${OS_ARCH}" == darwin-* ]]; then
+ relocate_macos_rpaths "${OUT_DIR}"
+ fi
+
echo "[whisper-stt] built ${variant_name} -> ${OUT_DIR}/${out_bin_name}"
ls -la "${OUT_DIR}"
}
diff --git a/scripts/stage-whisper-stt.sh b/scripts/stage-whisper-stt.sh
index ffe9b45a7..37883d34e 100755
--- a/scripts/stage-whisper-stt.sh
+++ b/scripts/stage-whisper-stt.sh
@@ -86,9 +86,19 @@ if [ "${TAG#win32}" != "${TAG}" ]; then
else
MINIMAL_PATH="/usr/bin:/bin"
fi
+# `timeout` is GNU coreutils: absent from a stock macOS runner. Unqualified, it
+# made the whole check evaporate there — `env: timeout: No such file or
+# directory` is itself output, so the "did it print anything" test below passed
+# without ever starting the binary. Use it only when it exists.
+if command -v timeout >/dev/null 2>&1; then
+ TIMEOUT_CMD="timeout 60"
+else
+ TIMEOUT_CMD=""
+fi
# A bad --model makes it fail fast; we only care that it got far enough to speak.
set +e
-LOAD_OUT="$(cd "${DEST}" && timeout 60 env PATH="${MINIMAL_PATH}" \
+# shellcheck disable=SC2086 # TIMEOUT_CMD is deliberately word-split (or empty).
+LOAD_OUT="$(cd "${DEST}" && ${TIMEOUT_CMD} env PATH="${MINIMAL_PATH}" \
"./$(basename "${BIN}")" --model "__staging_load_check__" 2>&1)"
LOAD_CODE=$?
set -e
@@ -98,6 +108,26 @@ if [ -z "${LOAD_OUT}" ]; then
echo " Windows exit 3221225781 = 0xC0000135 STATUS_DLL_NOT_FOUND." >&2
exit 1
fi
+
+# "It printed something" is a Windows-shaped test: the loader there dies mute.
+# dyld and ld.so are chatty, so on macOS/Linux a helper that never reached
+# main() still satisfies the check above — which is exactly how a macOS build
+# missing every libggml*.dylib passed staging. Demand the marker that main()
+# itself prints (electron/native/whisper-stt/src/main.cpp), so the gate proves
+# execution rather than mere noise.
+case "${LOAD_OUT}" in
+ *"[whisper-stt] boot:"*) ;;
+ *)
+ echo "FATAL: $(basename "${BIN}") never reached main() (exit ${LOAD_CODE})." >&2
+ echo " Expected its '[whisper-stt] boot:' line; got:" >&2
+ printf '%s\n' "${LOAD_OUT}" | sed 's/^/ /' | head -n 12 >&2
+ echo " A dynamic-loader error here means a sidecar is missing from the" >&2
+ echo " artifact, or the binary carries an absolute rpath/RUNPATH into" >&2
+ echo " the build machine's tree. Both are bugs in" >&2
+ echo " scripts/build-whisper-stt.sh's staging step." >&2
+ exit 1
+ ;;
+esac
echo "Load check OK (exit ${LOAD_CODE}): $(printf '%s' "${LOAD_OUT}" | head -n 1)"
echo "Staged $(basename "${BIN}") + $(( $(ls -1 "${DEST}" | wc -l) - 1 )) sidecar(s) -> ${DEST}"
diff --git a/scripts/test-whisper-stt.mjs b/scripts/test-whisper-stt.mjs
new file mode 100644
index 000000000..b1f9b4504
--- /dev/null
+++ b/scripts/test-whisper-stt.mjs
@@ -0,0 +1,326 @@
+// Round-trips a real WAV through a real `whisper-stt-server` and checks the
+// response against the invariants in
+// technical-documentation/architecture/transcription-and-captions.md.
+//
+// WHY THIS EXISTS. The helper's unit tests mock `fetch`, so every assertion
+// about the wire format was made against a hand-written fixture rather than the
+// binary. Three defects lived in that blind spot at once on macOS: no ggml
+// dylib was staged next to the executable, the executable carried an absolute
+// rpath into the build tree, and `backend`/`detected_language` reported values
+// the helper had never actually resolved. All three are things only a real
+// request can see.
+//
+// Usage:
+// node scripts/test-whisper-stt.mjs # macOS: synthesizes speech with `say`
+// node scripts/test-whisper-stt.mjs --wav a.wav # any platform: bring your own clip
+// node scripts/test-whisper-stt.mjs --wav a.wav --ref "expected words"
+// node scripts/test-whisper-stt.mjs --language fr # force a language instead of auto
+//
+// Env overrides:
+// OPENSCREEN_WHISPER_SERVER_EXE helper binary (default: the staged one for this host)
+// OPENSCREEN_WHISPER_MODEL GGML model (default: the userData cache location)
+
+import { spawn, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.join(__dirname, "..");
+
+const argOf = (flag) => {
+ const i = process.argv.indexOf(flag);
+ return i >= 0 && i + 1 < process.argv.length ? process.argv[i + 1] : null;
+};
+
+const TAG = `${process.platform}-${process.arch}`;
+const BIN =
+ process.env.OPENSCREEN_WHISPER_SERVER_EXE ??
+ path.join(
+ ROOT,
+ "electron",
+ "native",
+ "bin",
+ TAG,
+ process.platform === "win32" ? "whisper-stt-server.exe" : "whisper-stt-server",
+ );
+
+// Mirrors modelManager.ts's cache location. Electron's userData dir is
+// "Electron" in dev and the productName once packaged.
+const MODEL = process.env.OPENSCREEN_WHISPER_MODEL ?? defaultModelPath();
+const LANGUAGE = argOf("--language") ?? "auto";
+const WAV_ARG = argOf("--wav");
+const REF_ARG = argOf("--ref");
+
+function defaultModelPath() {
+ const file = path.join("stt-models", "whisper-ggml", "ggml-small-q8_0.bin");
+ if (process.platform === "darwin") {
+ return path.join(os.homedir(), "Library", "Application Support", "Electron", file);
+ }
+ if (process.platform === "win32") {
+ return path.join(process.env.APPDATA ?? "", "Electron", file);
+ }
+ return path.join(os.homedir(), ".config", "Electron", file);
+}
+
+const failures = [];
+const check = (ok, label, detail = "") => {
+ console.log(` ${ok ? "PASS" : "FAIL"} ${label}${detail ? ` — ${detail}` : ""}`);
+ if (!ok) failures.push(label);
+};
+
+/** Minimal RIFF/WAVE parse: enough to assert the clip is what the helper expects. */
+function readWavMeta(file) {
+ const buf = fs.readFileSync(file);
+ if (buf.toString("ascii", 0, 4) !== "RIFF" || buf.toString("ascii", 8, 12) !== "WAVE") {
+ throw new Error(`${file} is not a RIFF/WAVE file`);
+ }
+ let offset = 12;
+ let fmt = null;
+ let dataBytes = null;
+ while (offset + 8 <= buf.length) {
+ const id = buf.toString("ascii", offset, offset + 4);
+ const size = buf.readUInt32LE(offset + 4);
+ if (id === "fmt ") {
+ fmt = {
+ channels: buf.readUInt16LE(offset + 10),
+ sampleRate: buf.readUInt32LE(offset + 12),
+ bitsPerSample: buf.readUInt16LE(offset + 22),
+ };
+ } else if (id === "data") {
+ dataBytes = size;
+ }
+ offset += 8 + size + (size % 2);
+ }
+ if (!fmt || dataBytes == null) throw new Error(`${file} has no fmt/data chunk`);
+ const bytesPerFrame = (fmt.bitsPerSample / 8) * fmt.channels;
+ return { ...fmt, durationSec: dataBytes / bytesPerFrame / fmt.sampleRate };
+}
+
+/** macOS-only: synthesize a clip with a known transcript so WER is meaningful. */
+function synthesizeWav() {
+ const text =
+ "And so my fellow Americans, ask not what your country can do for you, " +
+ "ask what you can do for your country.";
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "whisper-stt-test-"));
+ const aiff = path.join(dir, "speech.aiff");
+ const wav = path.join(dir, "speech.wav");
+ for (const [cmd, args] of [
+ ["say", ["-o", aiff, text]],
+ ["afconvert", ["-f", "WAVE", "-d", "LEI16@16000", "-c", "1", aiff, wav]],
+ ]) {
+ const r = spawnSync(cmd, args, { stdio: "inherit" });
+ if (r.status !== 0) throw new Error(`${cmd} failed (status ${r.status})`);
+ }
+ return { wav, ref: text, cleanup: () => fs.rmSync(dir, { recursive: true, force: true }) };
+}
+
+const normalize = (s) =>
+ s
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N}\s']/gu, " ")
+ .split(/\s+/)
+ .filter(Boolean);
+
+/** Word error rate: Levenshtein over word arrays, (S+D+I)/N. */
+function wer(refText, hypText) {
+ const ref = normalize(refText);
+ const hyp = normalize(hypText);
+ if (ref.length === 0) return hyp.length === 0 ? 0 : 1;
+ let prev = Array.from({ length: hyp.length + 1 }, (_, j) => j);
+ for (let i = 1; i <= ref.length; i++) {
+ const cur = [i];
+ for (let j = 1; j <= hyp.length; j++) {
+ cur[j] = Math.min(
+ prev[j] + 1,
+ cur[j - 1] + 1,
+ prev[j - 1] + (ref[i - 1] === hyp[j - 1] ? 0 : 1),
+ );
+ }
+ prev = cur;
+ }
+ return prev[hyp.length] / ref.length;
+}
+
+async function waitForReady(baseUrl, timeoutMs = 120_000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ try {
+ const res = await fetch(baseUrl, { method: "GET" });
+ if (res.ok) return;
+ } catch {
+ // not up yet
+ }
+ await new Promise((r) => setTimeout(r, 250));
+ }
+ throw new Error(`helper did not become ready within ${timeoutMs}ms`);
+}
+
+async function main() {
+ for (const [label, p] of [
+ ["helper binary", BIN],
+ ["GGML model", MODEL],
+ ]) {
+ if (!fs.existsSync(p)) {
+ console.error(`FATAL: ${label} not found at ${p}`);
+ if (label === "helper binary") {
+ console.error(" Build it: bash scripts/build-whisper-stt.sh");
+ } else {
+ console.error(
+ " Run a transcription in the app once, or set OPENSCREEN_WHISPER_MODEL.",
+ );
+ }
+ process.exit(1);
+ }
+ }
+
+ let wavPath = WAV_ARG;
+ let refText = REF_ARG;
+ // No-op unless we synthesize a clip into a temp dir that needs removing.
+ let cleanup = () => undefined;
+ if (!wavPath) {
+ if (process.platform !== "darwin") {
+ console.error("FATAL: --wav <file> is required off macOS (no `say` to synthesize with).");
+ process.exit(2);
+ }
+ const made = synthesizeWav();
+ wavPath = made.wav;
+ refText = refText ?? made.ref;
+ cleanup = made.cleanup;
+ }
+
+ const meta = readWavMeta(wavPath);
+ console.log(`\nclip : ${wavPath}`);
+ console.log(
+ `format : ${meta.channels}ch ${meta.sampleRate}Hz ${meta.bitsPerSample}-bit, ` +
+ `${meta.durationSec.toFixed(2)}s`,
+ );
+ console.log(`helper : ${BIN}`);
+ console.log(`model : ${MODEL}\n`);
+
+ const port = 20100 + Math.floor(process.pid % 400);
+ const child = spawn(
+ BIN,
+ [
+ "--model",
+ MODEL,
+ "--port",
+ String(port),
+ "--host",
+ "127.0.0.1",
+ "--threads",
+ String(Math.max(1, os.cpus().length)),
+ ],
+ { stdio: ["ignore", "pipe", "pipe"] },
+ );
+ let stderr = "";
+ child.stderr.on("data", (d) => {
+ stderr += String(d);
+ });
+ child.on("exit", (code, signal) => {
+ if (code !== 0 && code !== null) {
+ console.error(`\nhelper exited early (code ${code}, signal ${signal}):`);
+ console.error(stderr.split("\n").slice(-15).join("\n"));
+ }
+ });
+
+ let json;
+ try {
+ await waitForReady(`http://127.0.0.1:${port}/`);
+ const form = new FormData();
+ form.append("file", new Blob([fs.readFileSync(wavPath)]), path.basename(wavPath));
+ form.append("language", LANGUAGE);
+ form.append("response_format", "verbose_json");
+ const res = await fetch(`http://127.0.0.1:${port}/inference`, {
+ method: "POST",
+ body: form,
+ });
+ if (!res.ok) throw new Error(`/inference returned ${res.status}: ${await res.text()}`);
+ json = await res.json();
+ } finally {
+ child.kill();
+ cleanup();
+ }
+
+ const segments = json.segments ?? [];
+ const words = segments.flatMap((s) => s.words ?? []);
+ const text = segments
+ .map((s) => s.text ?? "")
+ .join("")
+ .trim();
+
+ console.log(`text : ${text}\n`);
+ console.log("assertions:");
+
+ check(segments.length > 0, "response carries phrase segments", `${segments.length}`);
+ check(words.length > 0, "response carries per-word timings", `${words.length} words`);
+
+ // The DTW guardrail lives in the helper; its stderr line is the only place
+ // the result is reported, and a FAIL there is a 500 rather than a bad body.
+ check(/§4\.1 guardrail: PASS/.test(stderr), "DTW guardrail passed in the helper");
+
+ // `backend` is documented as the source of truth for the device that ran.
+ // Metal reported as CPU is the exact bug this catches: ggml's Metal *device*
+ // is named "MTL0", so a matcher looking for "Metal" never fires.
+ const gpuExpected =
+ (process.platform === "darwin" && process.arch === "arm64") || process.platform === "win32";
+ check(
+ typeof json.backend === "string" && json.backend.startsWith("whispercpp-"),
+ "backend is a contract value",
+ String(json.backend),
+ );
+ if (gpuExpected) {
+ check(
+ json.backend !== "whispercpp-cpu",
+ "backend reports GPU offload on a GPU-capable host",
+ String(json.backend),
+ );
+ }
+
+ // "auto" is a request value, never a response value: the helper must report
+ // the language whisper resolved.
+ check(
+ typeof json.detected_language === "string" &&
+ json.detected_language !== "auto" &&
+ json.detected_language.length > 0,
+ "detected_language is a resolved language, not the request echo",
+ String(json.detected_language),
+ );
+
+ // Contract invariant: absolute seconds in the source recording, [0, duration).
+ const tolerance = 0.5; // whisper rounds segment ends up to the chunk edge
+ const inRange = words.every(
+ (w) => w.start >= 0 && w.end >= w.start && w.end <= meta.durationSec + tolerance,
+ );
+ check(inRange, "word times lie within the clip", `clip is ${meta.durationSec.toFixed(2)}s`);
+
+ let monotonic = true;
+ for (let i = 1; i < words.length; i++) {
+ if (words[i].start < words[i - 1].start) monotonic = false;
+ }
+ check(monotonic, "word starts are monotonic non-decreasing");
+
+ if (refText) {
+ const rate = wer(refText, text);
+ check(rate <= 0.15, "WER within tolerance", `${rate.toFixed(4)}`);
+ }
+
+ if (json.timing) {
+ console.log(
+ `\ntiming : ${json.timing.elapsed_s?.toFixed?.(2)}s for ` +
+ `${json.timing.audio_s?.toFixed?.(2)}s audio (rtf ${json.timing.rtf?.toFixed?.(3)})`,
+ );
+ }
+
+ if (failures.length > 0) {
+ console.error(`\n${failures.length} check(s) failed: ${failures.join("; ")}`);
+ process.exit(1);
+ }
+ console.log("\nAll checks passed.");
+}
+
+main().catch((err) => {
+ console.error(`\nFATAL: ${err.message}`);
+ process.exit(1);
+});
diff --git a/technical-documentation/architecture/transcription-and-captions.md b/technical-documentation/architecture/transcription-and-captions.md
index 1ae45bc0e..c9694ec79 100644
--- a/technical-documentation/architecture/transcription-and-captions.md
+++ b/technical-documentation/architecture/transcription-and-captions.md
@@ -55,17 +55,32 @@ factors — lives in
### Per-platform backend
-| Platform | Helper binary | Runtime device candidates |
+The binary is named `whisper-stt-server` (`.exe` on Windows) on **every**
+platform — the backend is a build-time flag, not a file name, and
+`binaryNameForBackend`
+([`electron/stt/gpuDetector.ts:60`](../../electron/stt/gpuDetector.ts:60))
+returns that single name. What varies is which backend was compiled in:
+
+| Platform | Backend compiled in | Runtime device candidates |
|---|---|---|
-| macOS arm64 | `whisper-stt-server-metal` | Metal, CPU |
-| macOS x64 | `whisper-stt-server-cpu` | CPU |
-| Windows x64 | `whisper-stt-server-vulkan` | Vulkan, CPU |
-| Linux x64 | `whisper-stt-server-vulkan` | Vulkan, CPU |
+| macOS arm64 | Metal (`-DOSC_ENABLE_METAL=ON`) | Metal, CPU |
+| macOS x64 | CPU only | CPU |
+| Windows x64 | Vulkan (`-DOSC_ENABLE_VULKAN=ON`) | Vulkan, CPU |
+| Linux x64 | Vulkan (`-DOSC_ENABLE_VULKAN=ON`) | Vulkan, CPU |
whisper.cpp chooses the device in `whisper_backend_init`; the helper reports
what actually bound (via `ggml_backend_dev_name()`) and `SttManager` returns
it verbatim in the response.
+> `ggml_backend_dev_name()` returns a *device* name carrying an index —
+> `Vulkan0`, `CUDA0`, `MTL0` — not the backend's title. Metal is the trap:
+> ggml-metal builds its device name from `GGML_METAL_NAME` (`"MTL"`), so the
+> string `"Metal"` appears nowhere in it. `detect_active_backend()` matched
+> `"Metal"` and therefore reported `whispercpp-cpu` on every Apple Silicon run
+> while the Metal backend was in fact bound. It now matches `MTL` and filters on
+> `ggml_backend_dev_type()` being GPU/IGPU, which also drops ggml-blas
+> (Accelerate on macOS, device type ACCEL) from consideration.
+
### Word-level alignment (DTW token timestamps)
1. **Decode** — `whisper_full()` runs with the default sampling parameters
@@ -170,6 +185,61 @@ curl -X POST -F "[email protected]" -F "language=auto" -F "response_format=verbose_
The helper's stderr logs the actual backend it bound
(`whispercpp-vulkan` / `-metal` / `-cpu`).
+`npm run test:whisper-stt` round-trips a real clip through a real helper and
+checks the response against the invariants below — segments and per-word
+timings present, the DTW guardrail passed, `backend` reporting GPU offload on a
+GPU-capable host, `detected_language` resolved rather than echoed, word times
+monotonic and inside the clip, and WER against a reference. On macOS it
+synthesizes its own clip with `say`, so it needs no fixture; elsewhere pass
+`--wav <file>` (and optionally `--ref "<expected text>"`). This is the check
+that the unit tests structurally cannot make: they mock `fetch`, so they assert
+against a hand-written fixture rather than the binary.
+
+#### What the staged directory has to contain
+
+`electron/native/bin/<os>-<arch>/` is not just the executable. whisper.cpp is
+built as **shared** libraries, so the helper is dynamically linked against
+`whisper` plus the ggml backends, and every one of them has to sit next to the
+binary:
+
+- **Windows** — `whisper.dll`, `ggml.dll`, `ggml-base.dll`, `ggml-cpu.dll`,
+ `ggml-vulkan.dll`.
+- **macOS** — `libwhisper.*.dylib`, `libggml{,-base,-cpu,-blas,-metal}.*.dylib`,
+ plus the version symlink farm (`libggml.dylib` → `libggml.0.dylib` →
+ `libggml.0.15.1.dylib`).
+- **Linux** — the `.so` equivalents, including the `.so.<major>` and
+ `.so.<full>` links.
+
+Two macOS/Linux-specific hazards, both of which shipped silently:
+
+1. **The sidecar glob.** CMake emits `ggml-base.dll` on Windows but
+ `libggml-base.dylib` / `libggml-base.so.0` elsewhere. A glob written as
+ `ggml*.*` matches only the Windows spelling, so the staging step copied
+ nothing but `libwhisper` on macOS and Linux and the helper died in dyld
+ before `main()`. `build_variant()` now globs the `lib`-prefixed and
+ `.so.<N>`-suffixed forms too, uses `cp -a` to keep the symlink farm intact
+ instead of dereferencing each link into a full copy, and **fails the build**
+ when it stages zero libraries.
+2. **Absolute rpaths.** CMake bakes an `LC_RPATH` pointing at its own build
+ tree, which resolves on the machine that built it and nowhere else — delete
+ `.cache/`, or download the CI artifact onto a different runner, and the
+ helper aborts (SIGABRT, exit 134) in the loader.
+ `relocate_macos_rpaths()` strips every absolute `LC_RPATH` from the
+ executable and each dylib, adds `@loader_path`, and re-signs ad-hoc
+ (editing a Mach-O header invalidates its signature, and arm64 refuses to
+ execute a modified unsigned image).
+
+`scripts/stage-whisper-stt.sh` gates the installer on actually loading the
+binary with a scrubbed `PATH`. That gate was written for Windows, where the
+loader dies mute, so it asserted only that the process *printed something* —
+and dyld and `ld.so` are chatty, so a macOS helper missing every ggml dylib
+printed a four-line loader error and passed. It now requires the
+`[whisper-stt] boot:` line that `main()` itself emits, which proves execution
+rather than noise, and it no longer depends on `timeout` (GNU coreutils, absent
+from a stock macOS runner — unqualified, `env: timeout: No such file or
+directory` was itself enough "output" to satisfy the old check without ever
+starting the binary).
+
## The transcription contract
The wire types in `electron/stt/transcriptionContract.ts` are shared across
@@ -390,16 +460,31 @@ it deletes data
first window and slightly improve WER. Needs a UI control wired
through `setTranscript` and a mapping from the UI string to a
whisper.cpp language token.
+
+ Note that `"auto"` is a *request* value only. The helper used to echo the
+ request straight back into `detected_language`, so with no selector the field
+ was permanently the literal string `"auto"`: the media stage's "detected
+ language" line ([`src/components/ai-edition/Modals.tsx:1763`](../../src/components/ai-edition/Modals.tsx:1763))
+ displayed it verbatim, and `transcribe.ts` wrote it onto
+ `AxcutTranscript.language`. It now reports `whisper_full_lang_id()` — the
+ detected language under `"auto"`, the forced one otherwise.
- **No CUDA build.** Vulkan already accelerates NVIDIA on Windows and
Linux, but a dedicated CUDA build can be added later via
`OSC_ENABLE_CUDA=ON`; the build script and CMake already accept the
flag, the default matrix doesn't build it yet.
- **No CoreML/ANE encoder.** Metal already covers Apple GPU; CoreML is
a future perf refinement.
-- **HTTP integration test not on CI.** No automated `POST /inference`
- round-trip against a known WAV on the macOS-ARM/Metal,
- Ubuntu-x64/Vulkan, Windows-x64/Vulkan matrix. The native build
- matrix is the right place to land it.
+- **HTTP integration test not on CI.** `npm run test:whisper-stt` does the
+ `POST /inference` round-trip and asserts the contract, but nothing runs it on
+ the macOS-ARM/Metal, Ubuntu-x64/Vulkan, Windows-x64/Vulkan matrix. The native
+ build matrix (`build-whisper-stt.yml`) is the right place to land it — each
+ job already has the freshly built helper on disk, so it only needs a clip and
+ the model. Off macOS the harness needs `--wav`, so a committed fixture (or a
+ runner-side TTS) is the missing piece. Until then the three GPU paths are
+ verified only by whoever runs it locally: **macOS arm64/Metal was verified
+ this way on 2026-07-30 (WER 0.0000 on an English and a French clip, rtf
+ 0.18–0.25 on an M1); Vulkan on Windows and Linux has not been re-checked
+ since the backend-detection fix.**
- **No C++ unit tests.** The WAV reader and the DTW-inactive guardrail
in `electron/native/whisper-stt/src/main.cpp` are exercised only at
runtime.