Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(speech): ship an AVX2 build of whisper.cpp on Linux x64 and use more threads
Enes Kirca8f01dc937616
diff --git a/CLAUDE.md b/CLAUDE.mdindex f6f9029da..3e8e3bdaa 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -9872,6 +9872,27 @@ Voice-to-text input captured via microphone, turned into terminal text via on-dethe default is still `auto`. **Mobile** keeps its own list, tracked separately as issue #591.- **Browser constraints** — `getUserMedia` requires HTTPS or `localhost`; mic permission prompt is the browser's own (not handled by nodeterm). Model downloads land on the **server's data dir** (accessible across sessions).- **Electron + native dep** — smart-whisper is externalized + `asarUnpack`'d (not bundled); `postinstall` rebuilds it against Electron's ABI. Device verification of the ABI rebuild is not yet exercised on a dev machine — test paths exist but have not been run in CI.+- **Linux x64 ships TWO whisper binaries, picked per CPU (issue #1267).** smart-whisper's+ binding.gyp passes no `-m` flags, so on x86-64 ggml compiles at the SSE2 baseline and every+ AVX/AVX2/FMA/F16C kernel drops out (`objdump -d smart-whisper.node | grep -c ymm` = **0** on the+ shipped build). Measured, base model, 3 s of audio, 12-thread AVX2 box: **18.8 s** as shipped vs+ **1.9 s** with `-mavx -mavx2 -mfma -mf16c`, and the same 11.2 s → 1.5 s under Electron's ABI; the+ report was large-v3-turbo taking ~7 min for one sentence. `scripts/patch-smart-whisper.mjs` (run+ before `electron-rebuild` in `postinstall`/`rebuild`, beside the node-pty patch) adds a+ `smart-whisper-avx2` target behind a gyp `OS=="linux" and target_arch=="x64"` condition — mac and+ Windows builds are unchanged — and makes smart-whisper's loader read+ `globalThis.__NODETERM_WHISPER_BINARY__`. `pickWhisperBinary` sets it from `/proc/cpuinfo`.+ **Never ship a single `-mavx2` build**: on a CPU without AVX2 that is a SIGILL that takes the+ whole app down on the first dictation, which is why the baseline stays and why every failure+ (flags unreadable, variant file absent, variant fails to load) falls back to it rather than to+ "unavailable". `WHISPER_SIMD_FLAGS` and the script's `SIMD_FLAGS` must name the same set (pinned+ by `smart-whisper-patch.test.ts`, which also fails on an unpatched install). Threads:+ `whisperThreads` replaces whisper.cpp's `min(4, cpus)` with about half the logical CPUs plus two,+ capped at 8 — **not** every CPU: ggml's workers spin-wait, and 12 threads on 12 busy logical CPUs+ measured 12.8 s against 8 threads' 1.4 s. Not covered yet: macOS x64 (Accelerate, same missing+ SIMD flags in ggml), a GPU backend (this smart-whisper has no Vulkan build option), cancelling a+ running transcription, and the Server Edition (installed with `--ignore-scripts`, so it keeps the+ baseline; the startup log line `[speech] whisper binary: …` says which binary loaded).## Packaging & auto-updatediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 3a8beda69..9c1ffcee8 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -30,6 +30,9 @@ Run `npm run rebuild`. node-pty 1.1.0 leaks a pty device per spawn on macOSconhost alive per killed session (its exit thread deletes the ConPTY baton without closing theHPCON); we patch both sources before `electron-rebuild` compiles them, and that test guards thepatches surviving upgrades.+The same goes for `src/core/speech/smart-whisper-patch.test.ts`: `scripts/patch-smart-whisper.mjs`+adds an AVX2 build of whisper.cpp beside the baseline on Linux x64 (issue #1267, ~10× faster+dictation), and `npm run rebuild` applies it.After the rebuild, `scripts/stage-conpty-dll.mjs` copies node-pty's bundled `conpty.dll` +`OpenConsole.exe` back beside `build/Release/conpty.node` on Windows (the rebuild deletes them);without them Windows terminals fall back to the inbox ConPTY, where a fullscreen TUI cannot scroll.diff --git a/package.json b/package.jsonindex b82fcecde..d8d0fead1 100644--- a/package.json+++ b/package.json@@ -22,7 +22,7 @@"test": "vitest run","test:unit": "vitest run test/remote","diagnose:agents": "node scripts/agent-session-scan.mjs",- "rebuild": "node scripts/patch-node-pty.mjs && electron-rebuild -f -w node-pty,smart-whisper && node scripts/stage-conpty-dll.mjs",+ "rebuild": "node scripts/patch-node-pty.mjs && node scripts/patch-smart-whisper.mjs && electron-rebuild -f -w node-pty,smart-whisper && node scripts/stage-conpty-dll.mjs","server:build": "esbuild src/server/main.ts --bundle --platform=node --format=cjs --outfile=out/server/main.cjs --external:node-pty --external:ws --external:smart-whisper --external:ssh2 --tsconfig=tsconfig.node.json","host:build": "esbuild src/session-host/host.ts --bundle --platform=node --format=cjs --outfile=out/session-host/host.cjs --external:node-pty --tsconfig=tsconfig.node.json","server:start": "node out/server/main.cjs",@@ -34,7 +34,7 @@"dist:win": "npm run make-icon && npm run build && electron-builder --win --x64 --publish never -c.extraMetadata.nodeTermUpdates=disabled","dist:win:release": "npm run make-icon && npm run build && electron-builder --win --x64 --publish never -c.extraMetadata.nodeTermUpdates=manual","release": "npm run make-icon && npm run build && sh -c 'electron-builder --mac --arm64 --x64 --publish never; s=$?; npm run rebuild; exit $s'",- "postinstall": "node scripts/patch-node-pty.mjs && electron-rebuild -f -w node-pty,smart-whisper && node scripts/stage-conpty-dll.mjs"+ "postinstall": "node scripts/patch-node-pty.mjs && node scripts/patch-smart-whisper.mjs && electron-rebuild -f -w node-pty,smart-whisper && node scripts/stage-conpty-dll.mjs"},"build": {"appId": "com.nodeterm.app",diff --git a/scripts/patch-smart-whisper.d.mts b/scripts/patch-smart-whisper.d.mtsnew file mode 100644index 000000000..25b15f9b2--- /dev/null+++ b/scripts/patch-smart-whisper.d.mts@@ -0,0 +1,6 @@+// Type surface of patch-smart-whisper.mjs for the vitest suite (smart-whisper-patch.test.ts); the+// script itself stays plain .mjs because postinstall runs it before anything is built.+export declare const PATCH_MARKER: string+export declare const VARIANT_TARGET: string+export declare const SIMD_FLAGS: readonly string[]+export declare function patchSmartWhisper(dir: string): 'patched' | 'already-patched'diff --git a/scripts/patch-smart-whisper.mjs b/scripts/patch-smart-whisper.mjsnew file mode 100644index 000000000..dbf65eaca--- /dev/null+++ b/scripts/patch-smart-whisper.mjs@@ -0,0 +1,138 @@+#!/usr/bin/env node+/**+ * patch-smart-whisper.mjs — gives Linux x64 a SIMD build of whisper.cpp (issue #1267).+ *+ * WHAT IT FIXES+ * smart-whisper's binding.gyp compiles whisper.cpp/ggml with no -m flags, so on x86-64 the+ * compiler targets the SSE2 baseline and every AVX/AVX2/FMA/F16C kernel in ggml is compiled out+ * (`objdump -d smart-whisper.node | grep -c ymm` = 0 on the shipped Linux build). macOS arm64 is+ * unaffected (NEON is baseline and Metal does the heavy lifting). Measured on a 12-thread AVX2+ * machine, base model, 3 s of audio: 18.8 s as shipped vs 1.9 s with -mavx2 -mfma -mf16c — the+ * report was large-v3-turbo taking ~7 minutes for one sentence.+ *+ * A single -mavx2 build would SIGILL on CPUs without AVX2 (pre-Haswell, many Atom/Pentium+ * parts), killing the whole app on the first dictation. So we build BOTH:+ * - `smart-whisper.node` — untouched baseline, loads everywhere+ * - `smart-whisper-avx2.node` — linux x64 only, -mavx -mavx2 -mfma -mf16c+ * and choose at load time from the CPU's own flags (`pickWhisperBinary` in+ * src/core/speech/speech-service.ts). The choice reaches smart-whisper's loader through+ * `globalThis.__NODETERM_WHISPER_BINARY__`; the patched loader falls back to the baseline when+ * the variant file is absent or fails to load, so a missing/broken variant degrades to the old+ * speed, never to "dictation unavailable".+ *+ * PROPERTIES+ * - Idempotent (PATCH_MARKER), and every anchor must match exactly once or the script exits+ * non-zero — a smart-whisper upgrade that reshapes these files fails the install loudly.+ * - Cross-platform safe: the extra target sits behind a gyp `OS=="linux" and target_arch=="x64"`+ * condition, so mac/Windows builds are byte-for-byte what they were. The loader change is a+ * no-op when nothing sets the global.+ * - Runs before electron-rebuild in `postinstall` / `rebuild`, so the native build sees it.+ *+ * GUARD: src/core/speech/smart-whisper-patch.test.ts asserts the marker is present in the+ * installed sources. If it is red, your node_modules is unpatched — run `npm run rebuild`.+ */++import fs from 'node:fs'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++export const PATCH_MARKER = 'NODETERM-PATCH(smart-whisper-simd)'+export const VARIANT_TARGET = 'smart-whisper-avx2'+export const SIMD_FLAGS = ['-mavx', '-mavx2', '-mfma', '-mf16c']++const LOADER_FIND =+ 'var module2 = require(import_node_path.default.join(__dirname, "../build/Release/smart-whisper"));'++const LOADER_REPLACE = `// ${PATCH_MARKER}: load the binary nodeterm picked for this CPU, falling back to the baseline.+var module2 = (() => {+ const base = import_node_path.default.join(__dirname, "../build/Release/smart-whisper");+ const want = globalThis.__NODETERM_WHISPER_BINARY__;+ if (typeof want === "string" && /^smart-whisper-[a-z0-9]+$/.test(want)) {+ const file = import_node_path.default.join(__dirname, "../build/Release", want);+ if (require("fs").existsSync(file + ".node")) {+ try {+ const m = require(file);+ globalThis.__NODETERM_WHISPER_LOADED__ = want;+ return m;+ } catch (err) {+ console.warn("[speech] " + want + " failed to load, using the baseline build:", err);+ }+ }+ }+ globalThis.__NODETERM_WHISPER_LOADED__ = "smart-whisper";+ return require(base);+})();`++const GYP_FIND = ' }\n ],\n}'++/** Patches the smart-whisper package in `dir`. Returns 'patched' | 'already-patched'. */+export function patchSmartWhisper(dir) {+ const gypPath = path.join(dir, 'binding.gyp')+ const jsPath = path.join(dir, 'dist', 'index.js')+ const gyp = fs.readFileSync(gypPath, 'utf8')+ const js = fs.readFileSync(jsPath, 'utf8')+ const gypDone = gyp.includes(PATCH_MARKER)+ const jsDone = js.includes(PATCH_MARKER)+ if (gypDone && jsDone) return 'already-patched'++ if (!jsDone) {+ expectOnce(js, LOADER_FIND, 'dist/index.js binary require')+ fs.writeFileSync(jsPath, js.replace(LOADER_FIND, LOADER_REPLACE))+ }++ if (!gypDone) {+ const start = gyp.indexOf(' {\n "target_name": "smart-whisper",')+ expectOnce(gyp, '"target_name": "smart-whisper",', 'binding.gyp target_name')+ expectOnce(gyp, GYP_FIND, 'binding.gyp end of targets')+ expectOnce(gyp, " 'cflags_cc!': [ '-fno-exceptions' ],\n", 'binding.gyp cflags_cc!')+ if (start < 0) fail('binding.gyp target block', 'not found')+ const end = gyp.indexOf(GYP_FIND)+ // The baseline target, copied verbatim so both binaries compile the same sources and defines.+ const target = gyp.slice(start, end + ' }'.length)+ const variant = target+ .replace('"target_name": "smart-whisper",', `"target_name": "${VARIANT_TARGET}",`)+ .replace(+ " 'cflags_cc!': [ '-fno-exceptions' ],\n",+ " 'cflags_cc!': [ '-fno-exceptions' ],\n" ++ ` 'cflags': [ ${SIMD_FLAGS.map((f) => `'${f}'`).join(', ')} ],\n`+ )+ .replace(/^/gm, ' ')+ const conditions =+ ` # ${PATCH_MARKER}: an AVX2 build beside the baseline; the loader picks per CPU.\n` ++ ` 'conditions': [\n` ++ ` ['OS=="linux" and target_arch=="x64"', {\n` ++ ` 'targets': [\n${variant}\n ],\n` ++ ` }],\n` ++ ` ],\n`+ fs.writeFileSync(gypPath, gyp.replace(GYP_FIND, ` }\n ],\n${conditions}}`))+ }+ return 'patched'+}++function expectOnce(text, needle, name) {+ const n = text.split(needle).length - 1+ if (n !== 1) fail(name, `expected exactly 1 match, found ${n}`)+}++function fail(name, why) {+ throw new Error(+ `[patch-smart-whisper] anchor "${name}": ${why}. smart-whisper was probably upgraded — ` ++ 're-derive the anchors in scripts/patch-smart-whisper.mjs (issue #1267).'+ )+}++const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)+if (isMain) {+ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')+ const dir = path.join(repoRoot, 'node_modules', 'smart-whisper')+ if (!fs.existsSync(dir)) {+ console.log('[patch-smart-whisper] smart-whisper not installed; nothing to patch.')+ } else {+ try {+ console.log(`[patch-smart-whisper] ${patchSmartWhisper(dir)}`)+ } catch (err) {+ console.error(String(err instanceof Error ? err.message : err))+ process.exit(1)+ }+ }+}diff --git a/src/core/speech/__fixtures__/smart-whisper-0.8.1/binding.gyp b/src/core/speech/__fixtures__/smart-whisper-0.8.1/binding.gypnew file mode 100644index 000000000..bfc86db8a--- /dev/null+++ b/src/core/speech/__fixtures__/smart-whisper-0.8.1/binding.gyp@@ -0,0 +1,37 @@+{+ 'variables' : {+ 'openssl_fips': '',+ },+ "targets": [+ {+ "target_name": "smart-whisper",+ "sources": [+ "src/binding/binding.cc",+ "src/binding/common.cc",+ "src/binding/model.cc",+ "src/binding/transcribe.cc",+ "<!@(node -p \"require('./dist/build.js').sources\")"+ ],+ "libraries": [ "<!@(node -p \"require('./dist/build.js').libraries\")" ],+ 'defines': [ "<!@(node -p \"require('./dist/build.js').defines\")" ],+ 'include_dirs': ["<!@(node -p \"require('node-addon-api').include\")", "whisper.cpp/include", "whisper.cpp/ggml/include", "whisper.cpp/examples"],+ 'dependencies': ["<!(node -p \"require('node-addon-api').gyp\")"],+ 'cflags!': [ '-fno-exceptions' ],+ 'cflags_cc!': [ '-fno-exceptions' ],+ 'xcode_settings': {+ 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',+ 'CLANG_CXX_LIBRARY': 'libc++',+ },+ 'msvs_settings': {+ 'VCCLCompilerTool': { 'ExceptionHandling': 1 },+ },+ 'conditions': [+ ['OS=="mac"', {+ 'xcode_settings': {+ 'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES', # -fvisibility=hidden+ }+ }]+ ]+ }+ ],+}diff --git a/src/core/speech/smart-whisper-patch.test.ts b/src/core/speech/smart-whisper-patch.test.tsnew file mode 100644index 000000000..bfd65a95f--- /dev/null+++ b/src/core/speech/smart-whisper-patch.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from 'vitest'+import fs from 'node:fs'+import path from 'node:path'+import { createRequire } from 'node:module'+import { PATCH_MARKER, SIMD_FLAGS, VARIANT_TARGET, patchSmartWhisper } from '../../../scripts/patch-smart-whisper.mjs'+import { WHISPER_SIMD_FLAGS } from './speech-service'+import { testTmpDir } from '../test-tmp'++/**+ * scripts/patch-smart-whisper.mjs builds an AVX2 variant of whisper.cpp beside the baseline on+ * linux x64 and lets the loader pick per CPU (issue #1267). These tests run the patch over a pristine+ * fixture of the package and the patched loader against fake binaries; the first test asserts the+ * installed sources carry the patch, so an install that skipped it fails loudly.+ */+const PKG = path.resolve(__dirname, '../../../node_modules/smart-whisper')+const installed = fs.existsSync(path.join(PKG, 'binding.gyp'))+/** Pristine smart-whisper 0.8.1 binding.gyp + the loader lines of its dist/index.js. */+const FIXTURE = path.resolve(__dirname, '__fixtures__/smart-whisper-0.8.1')++function copyPackage(): string {+ const dir = testTmpDir('sw-patch-')+ fs.mkdirSync(path.join(dir, 'dist'), { recursive: true })+ fs.copyFileSync(path.join(FIXTURE, 'binding.gyp'), path.join(dir, 'binding.gyp'))+ fs.copyFileSync(path.join(FIXTURE, 'dist', 'index.js'), path.join(dir, 'dist', 'index.js'))+ return dir+}++describe('patch-smart-whisper', () => {+ it.skipIf(!installed)('is applied to the installed smart-whisper', () => {+ const howto = 'node_modules is unpatched — run `npm run rebuild`.'+ expect(fs.readFileSync(path.join(PKG, 'binding.gyp'), 'utf8'), howto).toContain(PATCH_MARKER)+ expect(fs.readFileSync(path.join(PKG, 'dist', 'index.js'), 'utf8'), howto).toContain(PATCH_MARKER)+ })++ it('builds for exactly the CPU flags the runtime checks', () => {+ // A flag compiled in but not checked at load time is a SIGILL on the CPU that lacks it.+ expect(SIMD_FLAGS.map((f: string) => f.replace(/^-m/, '')).sort()).toEqual([...WHISPER_SIMD_FLAGS].sort())+ })++ it('adds a linux-x64-only variant target and is idempotent', () => {+ const dir = copyPackage()+ const pristine = fs.readFileSync(path.join(dir, 'binding.gyp'), 'utf8')+ expect(patchSmartWhisper(dir)).toBe('patched')+ const gyp = fs.readFileSync(path.join(dir, 'binding.gyp'), 'utf8')+ expect(gyp.startsWith(pristine.slice(0, pristine.lastIndexOf(' ],\n}')))).toBe(true)+ expect(gyp).toContain(`['OS=="linux" and target_arch=="x64"', {`)+ expect(gyp).toContain(`"target_name": "${VARIANT_TARGET}",`)+ expect(gyp).toContain("'cflags': [ '-mavx', '-mavx2', '-mfma', '-mf16c' ],")+ expect(patchSmartWhisper(dir)).toBe('already-patched')+ expect(fs.readFileSync(path.join(dir, 'binding.gyp'), 'utf8')).toBe(gyp)+ })++ it('refuses an anchor it cannot find instead of writing a half-patched package', () => {+ const dir = testTmpDir('sw-patch-bad-')+ fs.mkdirSync(path.join(dir, 'dist'))+ fs.writeFileSync(path.join(dir, 'binding.gyp'), '{}')+ fs.writeFileSync(path.join(dir, 'dist', 'index.js'), 'module.exports = {}')+ expect(() => patchSmartWhisper(dir)).toThrow(/anchor/)+ })++ describe('patched loader', () => {+ type G = { __NODETERM_WHISPER_BINARY__?: string; __NODETERM_WHISPER_LOADED__?: string }+ const g = globalThis as G++ /** A patched package whose "binaries" are JS stubs (require resolves .js before .node). */+ function fakePackage(variant: 'ok' | 'broken' | 'absent'): string {+ const dir = copyPackage()+ patchSmartWhisper(dir)+ const rel = path.join(dir, 'build', 'Release')+ fs.mkdirSync(rel, { recursive: true })+ fs.writeFileSync(path.join(rel, 'smart-whisper.js'), 'module.exports = { WhisperModel: class { which = "base" } }')+ if (variant !== 'absent') fs.writeFileSync(path.join(rel, `${VARIANT_TARGET}.node`), 'not a binary')+ if (variant === 'ok')+ fs.writeFileSync(path.join(rel, `${VARIANT_TARGET}.js`), 'module.exports = { WhisperModel: class { which = "avx2" } }')+ return dir+ }++ function load(dir: string, want: string | undefined): string | undefined {+ delete g.__NODETERM_WHISPER_LOADED__+ g.__NODETERM_WHISPER_BINARY__ = want+ try {+ const mod = createRequire(path.join(dir, 'dist', 'index.js'))('./index.js')+ return new mod.binding.WhisperModel().which+ } finally {+ delete g.__NODETERM_WHISPER_BINARY__+ }+ }++ it('loads the requested variant', () => {+ expect(load(fakePackage('ok'), VARIANT_TARGET)).toBe('avx2')+ expect(g.__NODETERM_WHISPER_LOADED__).toBe(VARIANT_TARGET)+ })++ it('falls back to the baseline when the variant is absent or fails to load', () => {+ expect(load(fakePackage('absent'), VARIANT_TARGET)).toBe('base')+ expect(load(fakePackage('broken'), VARIANT_TARGET)).toBe('base')+ expect(g.__NODETERM_WHISPER_LOADED__).toBe('smart-whisper')+ })++ it('ignores a missing or malformed request', () => {+ expect(load(fakePackage('ok'), undefined)).toBe('base')+ expect(load(fakePackage('ok'), '../../evil')).toBe('base')+ })+ })+})diff --git a/src/core/speech/speech-service.test.ts b/src/core/speech/speech-service.test.tsindex cbb065049..ebcccef93 100644--- a/src/core/speech/speech-service.test.ts+++ b/src/core/speech/speech-service.test.ts@@ -1,6 +1,14 @@import { beforeEach, describe, expect, it, vi } from 'vitest'import { writeFileSync } from 'node:fs'-import { describeWhisperLoadError, isGgmlModelHeader, SpeechService, type WhisperEngineHandle } from './speech-service'+import {+ describeWhisperLoadError,+ isGgmlModelHeader,+ parseCpuFlags,+ pickWhisperBinary,+ SpeechService,+ whisperThreads,+ type WhisperEngineHandle,+} from './speech-service'import { WhisperModelStore } from './whisper-models'import { testTmpDir } from '../test-tmp'@@ -235,3 +243,38 @@ describe('isGgmlModelHeader', () => {expect(isGgmlModelHeader(Uint8Array.from([0x67, 0x67, 0x6d, 0x6c]))).toBe(false)})})++describe('whisper binary + threads (issue #1267)', () => {+ const avx2 = new Set(['sse2', 'avx', 'avx2', 'fma', 'f16c'])++ it('parses the flags line of /proc/cpuinfo', () => {+ const info = 'processor\t: 0\nmodel name\t: X\nflags\t\t: fpu sse2 avx avx2 fma f16c\nbugs\t\t: spectre\n'+ expect(parseCpuFlags(info)).toEqual(new Set(['fpu', 'sse2', 'avx', 'avx2', 'fma', 'f16c']))+ expect(parseCpuFlags('processor : 0\n').size).toBe(0)+ })++ it('picks the SIMD build only on linux x64 with every flag present', () => {+ expect(pickWhisperBinary({ platform: 'linux', arch: 'x64', cpuFlags: avx2 })).toBe('smart-whisper-avx2')+ for (const missing of ['avx', 'avx2', 'fma', 'f16c']) {+ const flags = new Set([...avx2].filter((f) => f !== missing))+ expect(pickWhisperBinary({ platform: 'linux', arch: 'x64', cpuFlags: flags })).toBe('smart-whisper')+ }+ })++ it('falls back to the baseline when the flags are unknown or the platform has no variant', () => {+ expect(pickWhisperBinary({ platform: 'linux', arch: 'x64', cpuFlags: null })).toBe('smart-whisper')+ expect(pickWhisperBinary({ platform: 'linux', arch: 'arm64', cpuFlags: avx2 })).toBe('smart-whisper')+ expect(pickWhisperBinary({ platform: 'darwin', arch: 'x64', cpuFlags: avx2 })).toBe('smart-whisper')+ expect(pickWhisperBinary({ platform: 'win32', arch: 'x64', cpuFlags: avx2 })).toBe('smart-whisper')+ })++ it('uses more threads than whisper.cpp\'s default 4, but never every CPU', () => {+ expect([1, 2, 4].map(whisperThreads)).toEqual([1, 2, 4])+ expect(whisperThreads(8)).toBe(6)+ expect(whisperThreads(12)).toBe(8)+ expect(whisperThreads(16)).toBe(8)+ expect(whisperThreads(64)).toBe(8)+ expect(whisperThreads(0)).toBe(1)+ expect(whisperThreads(Number.NaN)).toBe(1)+ })+})diff --git a/src/core/speech/speech-service.ts b/src/core/speech/speech-service.tsindex 498fdcda1..e1fcaf2c6 100644--- a/src/core/speech/speech-service.ts+++ b/src/core/speech/speech-service.ts@@ -1,4 +1,5 @@-import { open } from 'node:fs/promises'+import { open, readFile } from 'node:fs/promises'+import os from 'node:os'import { whisperModel } from '../../shared/speech'import type { WhisperModelStore } from './whisper-models'@@ -27,6 +28,40 @@ export function isGgmlModelHeader(header: Uint8Array): boolean {)}+/** CPU features the SIMD build of whisper.cpp is compiled for (`-mavx -mavx2 -mfma -mf16c`, see+ * scripts/patch-smart-whisper.mjs). Every one must be present, or that binary SIGILLs the app. */+export const WHISPER_SIMD_FLAGS = ['avx', 'avx2', 'fma', 'f16c'] as const++/** The `flags` line of /proc/cpuinfo as a set. Pure — tested. */+export function parseCpuFlags(cpuinfo: string): Set<string> {+ const line = cpuinfo.split('\n').find((l) => /^flags\s*:/.test(l))+ return new Set(line ? line.slice(line.indexOf(':') + 1).trim().split(/\s+/) : [])+}++/** Which smart-whisper binary to load (issue #1267). The SIMD build exists only on linux x64; on a+ * CPU without its flags — or when the flags could not be read — the baseline is the only safe+ * answer, since a wrong guess is a SIGILL, not an error. Pure — tested. */+export function pickWhisperBinary(input: {+ platform: string+ arch: string+ cpuFlags: ReadonlySet<string> | null+}): 'smart-whisper' | 'smart-whisper-avx2' {+ if (input.platform !== 'linux' || input.arch !== 'x64' || !input.cpuFlags) return 'smart-whisper'+ return WHISPER_SIMD_FLAGS.every((f) => input.cpuFlags!.has(f)) ? 'smart-whisper-avx2' : 'smart-whisper'+}++/** whisper.cpp threads for a machine with `available` logical CPUs. whisper.cpp's own default is+ * min(4, cpus), which leaves most of a modern laptop idle. Using EVERY logical CPU is worse than+ * the default, though: ggml's workers spin-wait, so one oversubscribed or hyperthread-paired worker+ * stalls the whole graph (measured, 12 logical CPUs under load, base model: 4 threads 1.9 s,+ * 8 threads 1.4 s, 12 threads 12.8 s). So: about half plus two, never below whisper's own 4 when+ * the machine has them, capped at 8 where the gain flattens. Pure — tested. */+export function whisperThreads(available: number): number {+ const n = Math.max(1, Math.floor(available) || 1)+ if (n <= 4) return n+ return Math.min(8, Math.max(4, Math.ceil(n / 2) + 2))+}+/** Local dictation via whisper.cpp (smart-whisper). One loaded model at a* time (they are hundreds of MB of RAM); same-model loads dedupe onto one* in-flight promise; transcriptions run FIFO on a promise chain. The Pro@@ -117,11 +152,38 @@ export class SpeechService {}}+let loggedBinary = false++/** Linux only — the one platform with a SIMD variant. null = unknown, which picks the baseline. */+async function readCpuFlags(): Promise<Set<string> | null> {+ if (process.platform !== 'linux') return null+ try {+ return parseCpuFlags(await readFile('/proc/cpuinfo', 'utf8'))+ } catch {+ return null+ }+}+async function defaultEngineFactory(modelPath: string): Promise<WhisperEngineHandle> {let mod: anytry {+ // Read by the patched smart-whisper loader (scripts/patch-smart-whisper.mjs) at its first+ // import; later imports are cached, so setting it again is harmless.+ const g = globalThis as { __NODETERM_WHISPER_BINARY__?: string; __NODETERM_WHISPER_LOADED__?: string }+ g.__NODETERM_WHISPER_BINARY__ ??= pickWhisperBinary({+ platform: process.platform,+ arch: process.arch,+ cpuFlags: await readCpuFlags(),+ })// @ts-ignore -- optional native dep: absent until installed, and @ts-ignore stays valid either way (an expect-error would break the build the moment it resolves)mod = await import('smart-whisper')+ if (!loggedBinary) {+ loggedBinary = true+ console.info(+ `[speech] whisper binary: ${g.__NODETERM_WHISPER_LOADED__ ?? 'smart-whisper (unpatched)'}` ++ ` (wanted ${g.__NODETERM_WHISPER_BINARY__})`,+ )+ }} catch (err) {console.error('[speech] smart-whisper failed to load:', err)throw new Error(@@ -147,9 +209,13 @@ async function defaultEngineFactory(modelPath: string): Promise<WhisperEngineHan)}const whisper = new mod.Whisper(modelPath, { gpu: true })+ const nThreads = whisperThreads(os.availableParallelism?.() ?? os.cpus().length)return {async transcribe(pcm, language) {- const task = await whisper.transcribe(pcm, { language: language === 'auto' ? 'auto' : language })+ const task = await whisper.transcribe(pcm, {+ language: language === 'auto' ? 'auto' : language,+ n_threads: nThreads,+ })const result = await task.resultreturn (Array.isArray(result) ? result.map((r: any) => r.text).join(' ') : String(result ?? '')).trim()},